diff --git "a/assets/ArtifactWorkspace-RZHQ0Df5.js" "b/assets/ArtifactWorkspace-RZHQ0Df5.js" new file mode 100644--- /dev/null +++ "b/assets/ArtifactWorkspace-RZHQ0Df5.js" @@ -0,0 +1,163 @@ +var PL=Object.defineProperty;var vA=n=>{throw TypeError(n)};var RL=(n,e,t)=>e in n?PL(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t;var oe=(n,e,t)=>RL(n,typeof e!="symbol"?e+"":e,t),lv=(n,e,t)=>e.has(n)||vA("Cannot "+t);var f=(n,e,t)=>(lv(n,e,"read from private field"),t?t.call(n):e.get(n)),M=(n,e,t)=>e.has(n)?vA("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(n):e.set(n,t),T=(n,e,t,s)=>(lv(n,e,"write to private field"),s?s.call(n,t):e.set(n,t),t),P=(n,e,t)=>(lv(n,e,"access private method"),t);var ds=(n,e,t,s)=>({set _(i){T(n,e,i,t)},get _(){return f(n,e,s)}});import{h as Ro,r as U,j as S,F as ee,Y as tS,K as on,_ as ym,Z as c0,L as Ld,$ as ML,X as h0,a0 as IL,e as XC,m as OL}from"./index-DBceUpOG.js";import{u as YC,a as JC,b as QC,M as NL,d as nS,A as LL,t as DL,W as jL,X as FL,Y as zL,Z as e$,_ as HL}from"./chatLaunch-BBgwpPz7.js";/* empty css */import{H as Lp,a as Dp,b as jp}from"./hover-card--gtvf4fX.js";import{u as bo}from"./useQuery-CTayxP22.js";import{f as BL,i as t$,p as UL,C as qL,a as VL,T as WL}from"./CatalogEntityPreviewLink-Bj_5cBOb.js";import{G as u0}from"./github-B_L8HPJq.js";import{F as n$}from"./file-text-DD-Khly2.js";import{r as GL,a as KL,P as d0,c as ZL}from"./PaperPreviewLink-BC09InuS.js";import{M as XL,d as YL}from"./index-CKHiHVd5.js";import{r as JL}from"./index-B5H-uAx7.js";import{c as bA}from"./chat-rMFgp859.js";import{C as QL}from"./copy-Cfv8dW0j.js";import{T as eD}from"./thumbs-up-CQJAD5NR.js";import{u as vm}from"./useMutation-BQ-qd6gh.js";import{A as tD}from"./arrow-left-DkQOvoxh.js";import{E as s$}from"./external-link-D7EUNjfC.js";import{P as nD}from"./plus-DNvZMnTT.js";import{S as sD}from"./search-CaAV69FQ.js";import{C as i$,a as r$}from"./chevron-up-Dd0sIWtC.js";import{A as iD}from"./AuthorAvatar-Bcx_ri0M.js";import{p as rD}from"./papers-iaygykZ6.js";/** + * @license lucide-react v0.462.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const oD=Ro("ChevronLeft",[["path",{d:"m15 18-6-6 6-6",key:"1wnfg3"}]]);/** + * @license lucide-react v0.462.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const wA=Ro("Download",[["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}],["polyline",{points:"7 10 12 15 17 10",key:"2ggqvy"}],["line",{x1:"12",x2:"12",y1:"15",y2:"3",key:"1vk2je"}]]);/** + * @license lucide-react v0.462.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const sS=Ro("FileCode2",[["path",{d:"M4 22h14a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v4",key:"1pf5j1"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"m5 12-3 3 3 3",key:"oke12k"}],["path",{d:"m9 18 3-3-3-3",key:"112psh"}]]);/** + * @license lucide-react v0.462.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const aD=Ro("FilePlus2",[["path",{d:"M4 22h14a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v4",key:"1pf5j1"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M3 15h6",key:"4e2qda"}],["path",{d:"M6 12v6",key:"1u72j0"}]]);/** + * @license lucide-react v0.462.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const lD=Ro("Image",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2",key:"1m3agn"}],["circle",{cx:"9",cy:"9",r:"2",key:"af1f0g"}],["path",{d:"m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21",key:"1xmnt7"}]]);/** + * @license lucide-react v0.462.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const cD=Ro("Minus",[["path",{d:"M5 12h14",key:"1ays0h"}]]);/** + * @license lucide-react v0.462.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const o$=Ro("Pencil",[["path",{d:"M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z",key:"1a8usu"}],["path",{d:"m15 5 4 4",key:"1mk7zo"}]]);/** + * @license lucide-react v0.462.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const hD=Ro("Save",[["path",{d:"M15.2 3a2 2 0 0 1 1.4.6l3.8 3.8a2 2 0 0 1 .6 1.4V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2z",key:"1c8476"}],["path",{d:"M17 21v-7a1 1 0 0 0-1-1H8a1 1 0 0 0-1 1v7",key:"1ydtos"}],["path",{d:"M7 3v4a1 1 0 0 0 1 1h7",key:"t51u73"}]]);/** + * @license lucide-react v0.462.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const uD=Ro("ThumbsDown",[["path",{d:"M17 14V2",key:"8ymqnk"}],["path",{d:"M9 18.12 10 14H4.17a2 2 0 0 1-1.92-2.56l2.33-8A2 2 0 0 1 6.5 2H20a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2h-2.76a2 2 0 0 0-1.79 1.11L12 22a3.13 3.13 0 0 1-3-3.88Z",key:"m61m77"}]]);function f0({selection:n,editable:e=!1,onRemove:t}){const s=U.useId(),i=U.useRef(null),[r,o]=U.useState(!1),[a,l]=U.useState(!1),c=`Selection · Page ${n.page}`;return U.useEffect(()=>{const h=i.current;!h||r||l(h.scrollHeight>h.clientHeight+1)},[r,n.text]),S.jsxs("div",{className:`chat-paper-selection${e?" is-editable":""}`,children:[S.jsxs("div",{className:"chat-paper-selection-header",children:[S.jsx("span",{className:"chat-paper-selection-label",children:c}),S.jsxs("div",{className:"chat-paper-selection-actions",children:[(a||r)&&S.jsx("button",{type:"button",className:"chat-paper-selection-toggle","aria-expanded":r,"aria-controls":s,onClick:()=>o(h=>!h),children:r?"Collapse":"Expand"}),e&&t&&S.jsx("button",{type:"button",className:"chat-paper-selection-remove","aria-label":"Remove selected paper passage",onClick:t,children:"Remove"})]})]}),S.jsx("blockquote",{id:s,ref:i,className:`chat-paper-selection-quote${r?" is-expanded":""}`,children:n.text})]})}const dD=DL(),ese=({onSend:n,busy:e,placeholder:t,autoFocus:s,draft:i,onDraftChange:r,onStop:o,models:a=[],selectedModel:l,onModelChange:c,disabled:h=!1,describedBy:u,paperMentionsEnabled:d=!1,paperSelectionEnabled:p=!0,paperArtifactsEnabled:m=!1})=>{const[y,v]=U.useState(dD),g=i??y,b=U.useRef(null),[_,x]=U.useState(0),A=L=>{i||v(L),r==null||r(L)},C=YC({draft:g,onChange:A,enabled:d,textareaRef:b});U.useEffect(()=>{const L=b.current;L&&(L.style.height="auto",L.style.height=`${Math.min(L.scrollHeight,200)}px`)},[g.text]),U.useEffect(()=>{var L;s&&((L=b.current)==null||L.focus())},[s]);const $=()=>{const L=g.text.length-g.text.trimStart().length,B=g.text.trim(),H=!!g.paperSelection&&!p;if(!B||e||h||H)return;const D=L+B.length,X={text:B,paperMentions:g.paperMentions.filter(te=>te.start>=L&&te.end<=D).map(te=>({...te,start:te.start-L,end:te.end-L})),...g.paperSelection?{paperSelection:g.paperSelection}:{}};n(X)},I=!!g.paperSelection&&!p,j=!!g.text.trim()&&!I,q=m&&g.text==="/";return S.jsxs("div",{className:"chat-composer ph-no-capture","data-ph-no-autocapture":"true","data-ph-no-capture":"true",children:[g.paperSelection&&S.jsx(f0,{selection:g.paperSelection,editable:!0,onRemove:()=>{var L;A({text:g.text,paperMentions:g.paperMentions}),(L=b.current)==null||L.focus()}}),I&&S.jsx("div",{className:"chat-paper-selection-disabled",role:"status",children:"Paper selection is currently disabled. Remove the selected passage or wait for the feature to recover."}),S.jsxs("div",{className:"chat-composer-textarea-wrap",children:[S.jsx(JC,{text:g.text,mentions:g.paperMentions,scrollTop:_}),S.jsx("textarea",{className:"ph-no-capture","data-ph-no-autocapture":"true","data-ph-no-capture":"true",ref:b,rows:1,value:g.text,placeholder:t||(g.paperSelection?"Ask about this selection…":"Ask anything about research…"),onChange:L=>C.updateText(L.target.value,L.target.selectionStart),onSelect:L=>C.refresh(L.currentTarget.selectionStart),onClick:L=>C.refresh(L.currentTarget.selectionStart),onScroll:L=>x(L.currentTarget.scrollTop),onBlur:L=>{var B,H;(H=(B=L.relatedTarget)==null?void 0:B.closest)!=null&&H.call(B,".chat-paper-picker, .chat-slash-command")||window.setTimeout(C.close,0)},onKeyDown:L=>{C.keyDown(L)||L.key==="Enter"&&!L.shiftKey&&!L.nativeEvent.isComposing&&(L.preventDefault(),$())},role:"combobox","aria-expanded":C.open||q,"aria-controls":C.open?C.pickerId:q?"chat-write-paper-command":void 0,"aria-activedescendant":C.open&&C.results.length?`${C.optionIdPrefix}-${C.activeIndex}`:q?"chat-write-paper-command":void 0,"aria-autocomplete":"list","aria-describedby":[u,C.message?"chat-paper-mention-message":null].filter(Boolean).join(" ")||void 0}),S.jsx(QC,{open:C.open,query:C.query,results:C.results,activeIndex:C.activeIndex,loading:C.loading,error:C.error,onSelect:C.select,id:C.pickerId,optionIdPrefix:C.optionIdPrefix}),q&&S.jsxs("button",{type:"button",id:"chat-write-paper-command",className:"chat-slash-command",role:"option",onMouseDown:L=>{var B;L.preventDefault(),A({...g,text:"/write-paper "}),(B=b.current)==null||B.focus()},children:[S.jsx("code",{children:"/write-paper"}),S.jsx("span",{children:"Draft a paper from this research chat"})]})]}),C.message&&S.jsx("div",{id:"chat-paper-mention-message",className:"chat-paper-mention-message",role:"alert",children:C.message}),S.jsxs("div",{className:"chat-composer-row",children:[S.jsxs("div",{className:"chat-composer-tools",children:[a.length>0&&l&&c&&S.jsx(NL,{models:a,selectedModel:l,onModelChange:c,disabled:e}),S.jsx("span",{className:"chat-composer-hint",children:"Enter to send · Shift+Enter for newline"})]}),S.jsx("button",{type:"button",className:`chat-send${e||j?" chat-send-on":""}`,onClick:e?o:$,disabled:h||(e?!o:!j),"aria-label":e?"Stop generating":"Send message",children:e?o?S.jsx("span",{"aria-hidden":"true",children:"■"}):S.jsx(nS,{light:!0}):S.jsx(LL,{})})]})]})};function fD(){const[n,e]=U.useState(!1);return U.useEffect(()=>{const t=window.setTimeout(()=>e(!0),15e3);return()=>window.clearTimeout(t)},[]),S.jsxs("div",{className:"chat-waiting chat-compaction-status",role:"status","aria-live":"polite",children:[S.jsx("span",{className:"chat-thinking",children:"Summarizing earlier context…"}),n&&S.jsx("span",{className:"chat-compaction-explanation",children:"This conversation is long. Preserving its details may take up to a minute."})]})}const cv=new Map,a$=n=>{if(!n)return Promise.resolve();const e=cv.get(n);if(e)return e;const t=new Promise(s=>{const i=new Image;i.onload=()=>{s()},i.onerror=()=>{cv.delete(n),s()},i.src=n});return cv.set(n,t),t},pD=new Set(["huggingface.co","www.huggingface.co"]),mD=new Set(["api","blog","chat","collections","docs","enterprise","join","login","models","new","organizations","papers","posts","pricing","search","settings","spaces","tasks"]);function gD(n){let e;try{e=new URL(n)}catch{return null}if(e.protocol!=="https:"||!pD.has(e.hostname))return null;const t=e.pathname.split("/").filter(Boolean),s=t[0]==="datasets"?"dataset":"model",i=s==="dataset"?t.slice(1):t;if(i.length!==2||s==="model"&&mD.has(i[0])||i.some(c=>!c||c==="."||c===".."))return null;const r=i.join("/"),o=i.map(encodeURIComponent).join("/"),a=s==="dataset"?`datasets/${o}`:o,l=s==="dataset"?"datasets":"models";return{type:s,repoId:r,url:`https://huggingface.co/${a}`,thumbnailUrl:`https://cdn-thumbnails.huggingface.co/social-thumbnails/${l}/${o}.png`}}const yD=()=>typeof window.matchMedia=="function"&&window.matchMedia("(hover: none), (pointer: coarse)").matches,vD=({repo:n})=>{const[e,t]=ee.useState(!1);return S.jsxs("div",{className:"hf-preview-card",children:[e?S.jsx("div",{className:"hf-preview-fallback","aria-hidden":"true",children:"🤗"}):S.jsx("img",{className:"hf-preview-image","data-testid":"hf-preview-image",src:n.thumbnailUrl,alt:"",loading:"eager",decoding:"async",onError:()=>t(!0)}),S.jsxs("div",{className:"hf-preview-meta",children:[S.jsxs("span",{className:"hf-preview-kind",children:["Hugging Face ",n.type]}),S.jsx("strong",{children:n.repoId}),S.jsx("span",{children:"huggingface.co"})]})]})},bD=({repo:n,children:e})=>{const[t,s]=ee.useState(!1),i=ee.useRef(null),r=ee.useCallback(()=>{a$(n.thumbnailUrl)},[n.thumbnailUrl]);return ee.useEffect(()=>{const o=i.current;if(!o||typeof IntersectionObserver>"u")return;const a=new IntersectionObserver(([l])=>{l.isIntersecting&&(r(),a.disconnect())},{rootMargin:"200px"});return a.observe(o),()=>a.disconnect()},[r]),S.jsxs(Lp,{open:t,onOpenChange:o=>{(!o||!yD())&&s(o)},openDelay:150,closeDelay:100,children:[S.jsx(Dp,{asChild:!0,children:S.jsx("a",{ref:i,className:"chat-paper-link chat-hf-link",href:n.url,target:"_blank",rel:"noopener noreferrer",onPointerEnter:r,onFocus:r,children:e})}),S.jsx(jp,{className:"hf-preview-pop",side:"bottom",align:"start",collisionPadding:12,children:S.jsx(vD,{repo:n})})]})},wD=()=>typeof window.matchMedia=="function"&&window.matchMedia("(hover: none), (pointer: coarse)").matches,_D=({repo:n,preview:e,unavailable:t})=>{const[s,i]=ee.useState(!1),r=!!(e!=null&&e.avatarUrl)&&!s;return S.jsxs("div",{className:"github-preview-card",children:[r?S.jsx("img",{className:"github-preview-image","data-testid":"github-preview-image",src:e==null?void 0:e.avatarUrl,alt:"",loading:"eager",decoding:"async",onError:()=>i(!0)}):S.jsx("div",{className:"github-preview-fallback","aria-hidden":"true",children:S.jsx(u0,{})}),S.jsxs("div",{className:"github-preview-meta",children:[S.jsx("span",{className:"github-preview-kind",children:"GitHub repository"}),S.jsx("strong",{children:n.repoId}),(e==null?void 0:e.description)&&S.jsx("span",{className:"github-preview-description",children:e.description}),e?S.jsxs("span",{className:"github-preview-stats",children:[e.language&&S.jsxs(S.Fragment,{children:[e.language," · "]}),"★ ",e.stars.toLocaleString()," · ⑂ ",e.forks.toLocaleString(),e.archived&&S.jsx(S.Fragment,{children:" · Archived"})]}):S.jsx("span",{children:t?"Preview unavailable":"Loading preview…"})]})]})},SD=({repo:n,children:e})=>{var c;const[t,s]=ee.useState(!1),[i,r]=ee.useState(!1),o=ee.useRef(null),a=ee.useCallback(()=>r(!0),[]),l=bo({queryKey:["github-repository-preview",n.repoId.toLowerCase()],queryFn:({signal:h})=>BL(n,h),enabled:t||i,staleTime:30*60*1e3,gcTime:60*60*1e3,retry:!1});return ee.useEffect(()=>{const h=o.current;if(!h||typeof IntersectionObserver>"u")return;const u=new IntersectionObserver(([d])=>{d.isIntersecting&&(a(),u.disconnect())},{rootMargin:"200px"});return u.observe(h),()=>u.disconnect()},[a]),ee.useEffect(()=>{var h;(h=l.data)!=null&&h.avatarUrl&&a$(l.data.avatarUrl)},[(c=l.data)==null?void 0:c.avatarUrl]),S.jsxs(Lp,{open:t,onOpenChange:h=>{(!h||!wD())&&s(h)},openDelay:150,closeDelay:100,children:[S.jsx(Dp,{asChild:!0,children:S.jsxs("a",{ref:o,className:"chat-github-link",href:n.url,target:"_blank",rel:"noopener noreferrer",onPointerEnter:a,onFocus:a,children:[S.jsx(u0,{"aria-hidden":"true"}),e]})}),S.jsx(jp,{className:"github-preview-pop",side:"bottom",align:"start",collisionPadding:12,children:S.jsx(_D,{repo:n,preview:l.data,unavailable:l.isError})})]})},xD=/^p\d+b\d+$/;function tse(n,e){const t=n.blocks[e];return t?t.label!=="Section-Header"?[{page:t.page,bbox:t.bbox}]:Object.entries(n.blocks).filter(([s,i])=>s===e||i.section===e).map(([,s])=>({page:s.page,bbox:s.bbox})):[]}function AD(n){const e=[...n.matchAll(/\]\(pdf:(p\d+b\d+)\)/g)].map(t=>t[1]);return[...new Set(e)]}const kD=320,_A=12,ED=170;function CD(n,e){const t=Math.min(kD,e*.7),s=e-_A-t-n.left,i=_A-n.left;return{left:Math.max(i,Math.min(0,s)),below:n.topU.useContext(TD);function c$(n){return n.length>220?`${n.slice(0,220).trimEnd()}…`:n}function PD({anchor:n,children:e}){var l;const t=l$(),[s,i]=U.useState({left:0,below:!1}),r=(l=t==null?void 0:t.layout)==null?void 0:l.blocks[n];if(!t||!r)return S.jsx("span",{className:"chat-invalid-citation",children:e});const o=r.label==="Section-Header",a=c=>i(CD(c.getBoundingClientRect(),window.innerWidth));return S.jsxs("button",{type:"button",className:"chat-pdf-citation",onClick:()=>t.open(n),onMouseEnter:c=>a(c.currentTarget),onFocus:c=>a(c.currentTarget),"aria-label":`${o?"Jump to section":"Jump to passage"} on page ${r.page}`,children:[S.jsx(n$,{"aria-hidden":"true"}),S.jsx("span",{children:U.Children.map(e,(c,h)=>h===0&&typeof c=="string"?$D(c):c)}),S.jsxs("span",{className:`chat-pdf-citation-preview${s.below?" is-below":""}`,role:"tooltip",style:{left:s.left},children:[S.jsxs("strong",{children:["Page ",r.page,o?" · section":""]}),r.text&&S.jsx("span",{children:c$(r.text)})]})]})}function RD({text:n}){const e=l$(),t=e==null?void 0:e.layout;if(!e||!t)return null;const s=AD(n).filter(i=>t.blocks[i]);return s.length?S.jsxs("details",{className:"chat-pdf-sources",children:[S.jsxs("summary",{children:["Sources (",s.length,")"]}),S.jsx("ol",{children:s.map(i=>{const r=t.blocks[i];return S.jsx("li",{children:S.jsxs("button",{type:"button",onClick:()=>e.open(i),children:[S.jsxs("span",{className:"chat-pdf-sources-page",children:["p. ",r.page]}),S.jsx("span",{children:c$(r.text)||r.label})]})},i)})})]}):null}const MD=()=>typeof window.matchMedia=="function"&&window.matchMedia("(hover: none), (pointer: coarse)").matches;function ID(n){try{return new URL(n).hostname.replace(/^www\./,"")}catch{return"Web source"}}const OD=({citation:n})=>{const[e,t]=ee.useState(!1),[s,i]=ee.useState(!1),r=n.thumbnail_url,o=n.favicon_url;return S.jsxs("div",{className:"web-preview-card",children:[r&&!e&&S.jsx("img",{className:"web-preview-image","data-testid":"web-preview-image",src:r,alt:"",loading:"eager",decoding:"async",referrerPolicy:"no-referrer",onError:()=>t(!0)}),S.jsxs("div",{className:"web-preview-meta",children:[S.jsxs("div",{className:"web-preview-source",children:[o&&!s&&S.jsx("img",{src:o,alt:"",loading:"eager",decoding:"async",referrerPolicy:"no-referrer",onError:()=>i(!0)}),S.jsx("span",{children:ID(n.url??"")}),n.published&&S.jsxs(S.Fragment,{children:[S.jsx("span",{"aria-hidden":"true",children:"·"}),S.jsx("time",{children:n.published.slice(0,10)})]})]}),S.jsx("strong",{children:n.title}),n.excerpt&&S.jsx("p",{children:n.excerpt.replace(/\s+/g," ").trim()})]})]})},ND=({citation:n,children:e})=>{const[t,s]=ee.useState(!1),i=n.url??"";return S.jsxs(Lp,{open:t,onOpenChange:r=>{(!r||!MD())&&s(r)},openDelay:150,closeDelay:100,children:[S.jsx(Dp,{asChild:!0,children:S.jsx("a",{href:i,className:"chat-web-citation",target:"_blank",rel:"noopener noreferrer",children:e})}),S.jsx(jp,{className:"web-preview-pop",side:"bottom",align:"start",collisionPadding:12,children:S.jsx(OD,{citation:n})})]})},LD=()=>typeof window.matchMedia=="function"&&window.matchMedia("(hover: none), (pointer: coarse)").matches,DD=n=>n==="semantic_scholar"?"Semantic Scholar":"External paper",jD=({citation:n})=>{var e,t;return S.jsxs("div",{className:"external-paper-preview-card",children:[S.jsxs("div",{className:"external-paper-preview-source",children:[S.jsx("span",{children:DD(n.provider)}),n.published&&S.jsxs(S.Fragment,{children:[S.jsx("span",{"aria-hidden":"true",children:"·"}),S.jsx("time",{children:n.published.slice(0,10)})]})]}),S.jsx("strong",{children:n.title}),(((e=n.authors)==null?void 0:e.length)??0)>0&&S.jsx("p",{className:"external-paper-preview-authors",children:(t=n.authors)==null?void 0:t.join(", ")}),n.excerpt&&S.jsx("p",{children:n.excerpt.replace(/\s+/g," ").trim()}),n.citation_count!==null&&n.citation_count!==void 0&&S.jsxs("span",{className:"external-paper-preview-citations",children:[n.citation_count.toLocaleString()," citations"]})]})},FD=({citation:n,children:e})=>{const[t,s]=ee.useState(!1);return S.jsxs(Lp,{open:t,onOpenChange:i=>{(!i||!LD())&&s(i)},openDelay:150,closeDelay:100,children:[S.jsx(Dp,{asChild:!0,children:S.jsx("a",{href:n.url??"",className:"chat-external-paper-citation",target:"_blank",rel:"noopener noreferrer",children:e})}),S.jsx(jp,{className:"external-paper-preview-pop",side:"bottom",align:"start",collisionPadding:12,children:S.jsx(jD,{citation:n})})]})};function zD(n){const e=[];let t=0,s=null;for(const i of n.match(/.*(?:\n|$)/g)??[]){if(!i)continue;const r=i.endsWith(` +`)?i.slice(0,-1):i;if(s){const l=r.match(/^ {0,3}(`+|~+)[ \t]*$/);l&&l[1][0]===s.marker&&l[1].length>=s.length&&(e.push({start:s.start,end:t+i.length}),s=null),t+=i.length;continue}const o=r.match(/^ {0,3}(`{3,}|~{3,})/);if(o){s={marker:o[1][0],length:o[1].length,start:t},t+=i.length;continue}let a=0;for(;ae>=t.start&&e=0&&n[s]==="\\";s-=1)t+=1;return t%2===0}function AA(n,e,t,s){const i=[];let r=0;for(;rs.name),published:e.metadata.published,conference:e.metadata.conference,citationCount:e.metadata.citation_count,tasks:e.metadata.tasks};if(t)return{routeId:n,title:t.title,arxivId:t.arxiv_id??null,source:t.arxiv_id?"arxiv":"external",sourceUrl:t.source_url,thumbnailUrl:t.thumbnail_url??null,authors:t.authors??[],published:t.published??null,conference:t.conference??null,citationCount:t.citation_count??null,tasks:[]}}const h$=({routeId:n,paper:e,citation:t,className:s="chat-paper-link",children:i})=>S.jsx(d0,{routeId:n,initialData:BD(n,e,t),className:s,target:"_blank",children:i});function UD(n){const e=n.lastIndexOf("[");if(e===-1)return n;const t=n.slice(e);return/^\[[^\]]*(\]\(?[^)\s]*)?$/.test(t)?n.slice(0,e):n}const qD=n=>n.startsWith("paper:")||n.startsWith("pdf:")||t$(n)?n:YL(n);function VD(n){try{const e=new URL(n);return e.protocol==="https:"&&(e.hostname==="github.com"||e.hostname==="www.github.com")}catch{return!1}}const ib=({text:n,streaming:e,papers:t,citations:s,webCitations:i})=>{const r=HD(e?UD(n):n);return S.jsxs(S.Fragment,{children:[S.jsx(XL,{remarkPlugins:[JL,KL],rehypePlugins:[GL],urlTransform:qD,components:{a:({href:o,children:a})=>{if(o!=null&&o.startsWith("paper:")){const h=o.slice(6);return!t[h]&&!(s!=null&&s[h])?S.jsx("span",{className:"chat-invalid-citation",children:a}):S.jsx(h$,{routeId:h,paper:t[h],citation:s==null?void 0:s[h],children:a})}if(o!=null&&o.startsWith("pdf:")){const h=o.slice(4);return xD.test(h)?S.jsx(PD,{anchor:h,children:a}):S.jsx("span",{className:"chat-invalid-citation",children:a})}if(o&&t$(o)){const h=UL(o);return h?S.jsx(qL,{entity:h,children:a}):S.jsx("span",{className:"chat-invalid-citation",children:a})}const l=o?gD(o):null;if(l)return S.jsx(bD,{repo:l,children:a});const c=o?VL(o):null;return c?S.jsx(SD,{repo:c,children:a}):o&&VD(o)?S.jsxs("a",{href:o,className:"chat-github-link",target:"_blank",rel:"noopener noreferrer",children:[S.jsx(u0,{"aria-hidden":"true"}),a]}):o!=null&&o.startsWith("https://")&&(i!=null&&i[o])?i[o].source_type==="paper"?S.jsx(FD,{citation:i[o],children:a}):S.jsx(ND,{citation:i[o],children:a}):o!=null&&o.startsWith("https://")?S.jsx("a",{href:o,className:"chat-external-link",target:"_blank",rel:"noopener noreferrer",children:a}):S.jsx("span",{children:a})}},children:r}),!e&&S.jsx(RD,{text:r})]})},WD=Object.freeze({status:"aborted"});function Q(n,e,t){function s(a,l){var c;Object.defineProperty(a,"_zod",{value:a._zod??{},enumerable:!1}),(c=a._zod).traits??(c.traits=new Set),a._zod.traits.add(n),e(a,l);for(const h in o.prototype)h in a||Object.defineProperty(a,h,{value:o.prototype[h].bind(a)});a._zod.constr=o,a._zod.def=l}const i=(t==null?void 0:t.Parent)??Object;class r extends i{}Object.defineProperty(r,"name",{value:n});function o(a){var l;const c=t!=null&&t.Parent?new r:this;s(c,a),(l=c._zod).deferred??(l.deferred=[]);for(const h of c._zod.deferred)h();return c}return Object.defineProperty(o,"init",{value:s}),Object.defineProperty(o,Symbol.hasInstance,{value:a=>{var l,c;return t!=null&&t.Parent&&a instanceof t.Parent?!0:(c=(l=a==null?void 0:a._zod)==null?void 0:l.traits)==null?void 0:c.has(n)}}),Object.defineProperty(o,"name",{value:n}),o}class sf extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}const u$={};function Ca(n){return u$}function GD(n){const e=Object.values(n).filter(s=>typeof s=="number");return Object.entries(n).filter(([s,i])=>e.indexOf(+s)===-1).map(([s,i])=>i)}function KD(n,e){return typeof e=="bigint"?e.toString():e}function iS(n){return{get value(){{const e=n();return Object.defineProperty(this,"value",{value:e}),e}}}}function rS(n){return n==null}function oS(n){const e=n.startsWith("^")?1:0,t=n.endsWith("$")?n.length-1:n.length;return n.slice(e,t)}function ZD(n,e){const t=(n.toString().split(".")[1]||"").length,s=(e.toString().split(".")[1]||"").length,i=t>s?t:s,r=Number.parseInt(n.toFixed(i).replace(".","")),o=Number.parseInt(e.toFixed(i).replace(".",""));return r%o/10**i}function Pt(n,e,t){Object.defineProperty(n,e,{get(){{const s=t();return n[e]=s,s}},set(s){Object.defineProperty(n,e,{value:s})},configurable:!0})}function p0(n,e,t){Object.defineProperty(n,e,{value:t,writable:!0,enumerable:!0,configurable:!0})}function Ju(n){return JSON.stringify(n)}const d$=Error.captureStackTrace?Error.captureStackTrace:(...n)=>{};function ey(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}const XD=iS(()=>{var n;if(typeof navigator<"u"&&((n=navigator==null?void 0:navigator.userAgent)!=null&&n.includes("Cloudflare")))return!1;try{const e=Function;return new e(""),!0}catch{return!1}});function ty(n){if(ey(n)===!1)return!1;const e=n.constructor;if(e===void 0)return!0;const t=e.prototype;return!(ey(t)===!1||Object.prototype.hasOwnProperty.call(t,"isPrototypeOf")===!1)}const YD=new Set(["string","number","symbol"]);function Fp(n){return n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Ec(n,e,t){const s=new n._zod.constr(e??n._zod.def);return(!e||t!=null&&t.parent)&&(s._zod.parent=n),s}function ve(n){const e=n;if(!e)return{};if(typeof e=="string")return{error:()=>e};if((e==null?void 0:e.message)!==void 0){if((e==null?void 0:e.error)!==void 0)throw new Error("Cannot specify both `message` and `error` params");e.error=e.message}return delete e.message,typeof e.error=="string"?{...e,error:()=>e.error}:e}function JD(n){return Object.keys(n).filter(e=>n[e]._zod.optin==="optional"&&n[e]._zod.optout==="optional")}const QD={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function e2(n,e){const t={},s=n._zod.def;for(const i in e){if(!(i in s.shape))throw new Error(`Unrecognized key: "${i}"`);e[i]&&(t[i]=s.shape[i])}return Ec(n,{...n._zod.def,shape:t,checks:[]})}function t2(n,e){const t={...n._zod.def.shape},s=n._zod.def;for(const i in e){if(!(i in s.shape))throw new Error(`Unrecognized key: "${i}"`);e[i]&&delete t[i]}return Ec(n,{...n._zod.def,shape:t,checks:[]})}function n2(n,e){if(!ty(e))throw new Error("Invalid input to extend: expected a plain object");const t={...n._zod.def,get shape(){const s={...n._zod.def.shape,...e};return p0(this,"shape",s),s},checks:[]};return Ec(n,t)}function s2(n,e){return Ec(n,{...n._zod.def,get shape(){const t={...n._zod.def.shape,...e._zod.def.shape};return p0(this,"shape",t),t},catchall:e._zod.def.catchall,checks:[]})}function i2(n,e,t){const s=e._zod.def.shape,i={...s};if(t)for(const r in t){if(!(r in s))throw new Error(`Unrecognized key: "${r}"`);t[r]&&(i[r]=n?new n({type:"optional",innerType:s[r]}):s[r])}else for(const r in s)i[r]=n?new n({type:"optional",innerType:s[r]}):s[r];return Ec(e,{...e._zod.def,shape:i,checks:[]})}function r2(n,e,t){const s=e._zod.def.shape,i={...s};if(t)for(const r in t){if(!(r in i))throw new Error(`Unrecognized key: "${r}"`);t[r]&&(i[r]=new n({type:"nonoptional",innerType:s[r]}))}else for(const r in s)i[r]=new n({type:"nonoptional",innerType:s[r]});return Ec(e,{...e._zod.def,shape:i,checks:[]})}function Dd(n,e=0){var t;for(let s=e;s{var s;return(s=t).path??(s.path=[]),t.path.unshift(n),t})}function bm(n){return typeof n=="string"?n:n==null?void 0:n.message}function $a(n,e,t){var i,r,o,a,l,c;const s={...n,path:n.path??[]};if(!n.message){const h=bm((o=(r=(i=n.inst)==null?void 0:i._zod.def)==null?void 0:r.error)==null?void 0:o.call(r,n))??bm((a=e==null?void 0:e.error)==null?void 0:a.call(e,n))??bm((l=t.customError)==null?void 0:l.call(t,n))??bm((c=t.localeError)==null?void 0:c.call(t,n))??"Invalid input";s.message=h}return delete s.inst,delete s.continue,e!=null&&e.reportInput||delete s.input,s}function aS(n){return Array.isArray(n)?"array":typeof n=="string"?"string":"unknown"}function rf(...n){const[e,t,s]=n;return typeof e=="string"?{message:e,code:"custom",input:t,inst:s}:{...e}}const f$=(n,e)=>{n.name="$ZodError",Object.defineProperty(n,"_zod",{value:n._zod,enumerable:!1}),Object.defineProperty(n,"issues",{value:e,enumerable:!1}),Object.defineProperty(n,"message",{get(){return JSON.stringify(e,KD,2)},enumerable:!0}),Object.defineProperty(n,"toString",{value:()=>n.message,enumerable:!1})},p$=Q("$ZodError",f$),m$=Q("$ZodError",f$,{Parent:Error});function o2(n,e=t=>t.message){const t={},s=[];for(const i of n.issues)i.path.length>0?(t[i.path[0]]=t[i.path[0]]||[],t[i.path[0]].push(e(i))):s.push(e(i));return{formErrors:s,fieldErrors:t}}function a2(n,e){const t=e||function(r){return r.message},s={_errors:[]},i=r=>{for(const o of r.issues)if(o.code==="invalid_union"&&o.errors.length)o.errors.map(a=>i({issues:a}));else if(o.code==="invalid_key")i({issues:o.issues});else if(o.code==="invalid_element")i({issues:o.issues});else if(o.path.length===0)s._errors.push(t(o));else{let a=s,l=0;for(;l(e,t,s,i)=>{const r=s?Object.assign(s,{async:!1}):{async:!1},o=e._zod.run({value:t,issues:[]},r);if(o instanceof Promise)throw new sf;if(o.issues.length){const a=new((i==null?void 0:i.Err)??n)(o.issues.map(l=>$a(l,r,Ca())));throw d$(a,i==null?void 0:i.callee),a}return o.value},c2=n=>async(e,t,s,i)=>{const r=s?Object.assign(s,{async:!0}):{async:!0};let o=e._zod.run({value:t,issues:[]},r);if(o instanceof Promise&&(o=await o),o.issues.length){const a=new((i==null?void 0:i.Err)??n)(o.issues.map(l=>$a(l,r,Ca())));throw d$(a,i==null?void 0:i.callee),a}return o.value},g$=n=>(e,t,s)=>{const i=s?{...s,async:!1}:{async:!1},r=e._zod.run({value:t,issues:[]},i);if(r instanceof Promise)throw new sf;return r.issues.length?{success:!1,error:new(n??p$)(r.issues.map(o=>$a(o,i,Ca())))}:{success:!0,data:r.value}},y$=g$(m$),v$=n=>async(e,t,s)=>{const i=s?Object.assign(s,{async:!0}):{async:!0};let r=e._zod.run({value:t,issues:[]},i);return r instanceof Promise&&(r=await r),r.issues.length?{success:!1,error:new n(r.issues.map(o=>$a(o,i,Ca())))}:{success:!0,data:r.value}},h2=v$(m$),u2=/^[cC][^\s-]{8,}$/,d2=/^[0-9a-z]+$/,f2=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,p2=/^[0-9a-vA-V]{20}$/,m2=/^[A-Za-z0-9]{27}$/,g2=/^[a-zA-Z0-9_-]{21}$/,y2=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,v2=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,kA=n=>n?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${n}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000)$/,b2=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,w2="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function _2(){return new RegExp(w2,"u")}const S2=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,x2=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})$/,A2=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,k2=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,E2=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,b$=/^[A-Za-z0-9_-]*$/,C2=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/,$2=/^\+(?:[0-9]){6,14}[0-9]$/,w$="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",T2=new RegExp(`^${w$}$`);function _$(n){const e="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof n.precision=="number"?n.precision===-1?`${e}`:n.precision===0?`${e}:[0-5]\\d`:`${e}:[0-5]\\d\\.\\d{${n.precision}}`:`${e}(?::[0-5]\\d(?:\\.\\d+)?)?`}function P2(n){return new RegExp(`^${_$(n)}$`)}function R2(n){const e=_$({precision:n.precision}),t=["Z"];n.local&&t.push(""),n.offset&&t.push("([+-]\\d{2}:\\d{2})");const s=`${e}(?:${t.join("|")})`;return new RegExp(`^${w$}T(?:${s})$`)}const M2=n=>{const e=n?`[\\s\\S]{${(n==null?void 0:n.minimum)??0},${(n==null?void 0:n.maximum)??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)},I2=/^\d+$/,O2=/^-?\d+(?:\.\d+)?/i,N2=/true|false/i,L2=/null/i,D2=/undefined/i,j2=/^[^A-Z]*$/,F2=/^[^a-z]*$/,Hs=Q("$ZodCheck",(n,e)=>{var t;n._zod??(n._zod={}),n._zod.def=e,(t=n._zod).onattach??(t.onattach=[])}),S$={number:"number",bigint:"bigint",object:"date"},x$=Q("$ZodCheckLessThan",(n,e)=>{Hs.init(n,e);const t=S$[typeof e.value];n._zod.onattach.push(s=>{const i=s._zod.bag,r=(e.inclusive?i.maximum:i.exclusiveMaximum)??Number.POSITIVE_INFINITY;e.value{(e.inclusive?s.value<=e.value:s.value{Hs.init(n,e);const t=S$[typeof e.value];n._zod.onattach.push(s=>{const i=s._zod.bag,r=(e.inclusive?i.minimum:i.exclusiveMinimum)??Number.NEGATIVE_INFINITY;e.value>r&&(e.inclusive?i.minimum=e.value:i.exclusiveMinimum=e.value)}),n._zod.check=s=>{(e.inclusive?s.value>=e.value:s.value>e.value)||s.issues.push({origin:t,code:"too_small",minimum:e.value,input:s.value,inclusive:e.inclusive,inst:n,continue:!e.abort})}}),z2=Q("$ZodCheckMultipleOf",(n,e)=>{Hs.init(n,e),n._zod.onattach.push(t=>{var s;(s=t._zod.bag).multipleOf??(s.multipleOf=e.value)}),n._zod.check=t=>{if(typeof t.value!=typeof e.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof t.value=="bigint"?t.value%e.value===BigInt(0):ZD(t.value,e.value)===0)||t.issues.push({origin:typeof t.value,code:"not_multiple_of",divisor:e.value,input:t.value,inst:n,continue:!e.abort})}}),H2=Q("$ZodCheckNumberFormat",(n,e)=>{var o;Hs.init(n,e),e.format=e.format||"float64";const t=(o=e.format)==null?void 0:o.includes("int"),s=t?"int":"number",[i,r]=QD[e.format];n._zod.onattach.push(a=>{const l=a._zod.bag;l.format=e.format,l.minimum=i,l.maximum=r,t&&(l.pattern=I2)}),n._zod.check=a=>{const l=a.value;if(t){if(!Number.isInteger(l)){a.issues.push({expected:s,format:e.format,code:"invalid_type",input:l,inst:n});return}if(!Number.isSafeInteger(l)){l>0?a.issues.push({input:l,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:n,origin:s,continue:!e.abort}):a.issues.push({input:l,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:n,origin:s,continue:!e.abort});return}}lr&&a.issues.push({origin:"number",input:l,code:"too_big",maximum:r,inst:n})}}),B2=Q("$ZodCheckMaxLength",(n,e)=>{var t;Hs.init(n,e),(t=n._zod.def).when??(t.when=s=>{const i=s.value;return!rS(i)&&i.length!==void 0}),n._zod.onattach.push(s=>{const i=s._zod.bag.maximum??Number.POSITIVE_INFINITY;e.maximum{const i=s.value;if(i.length<=e.maximum)return;const o=aS(i);s.issues.push({origin:o,code:"too_big",maximum:e.maximum,inclusive:!0,input:i,inst:n,continue:!e.abort})}}),U2=Q("$ZodCheckMinLength",(n,e)=>{var t;Hs.init(n,e),(t=n._zod.def).when??(t.when=s=>{const i=s.value;return!rS(i)&&i.length!==void 0}),n._zod.onattach.push(s=>{const i=s._zod.bag.minimum??Number.NEGATIVE_INFINITY;e.minimum>i&&(s._zod.bag.minimum=e.minimum)}),n._zod.check=s=>{const i=s.value;if(i.length>=e.minimum)return;const o=aS(i);s.issues.push({origin:o,code:"too_small",minimum:e.minimum,inclusive:!0,input:i,inst:n,continue:!e.abort})}}),q2=Q("$ZodCheckLengthEquals",(n,e)=>{var t;Hs.init(n,e),(t=n._zod.def).when??(t.when=s=>{const i=s.value;return!rS(i)&&i.length!==void 0}),n._zod.onattach.push(s=>{const i=s._zod.bag;i.minimum=e.length,i.maximum=e.length,i.length=e.length}),n._zod.check=s=>{const i=s.value,r=i.length;if(r===e.length)return;const o=aS(i),a=r>e.length;s.issues.push({origin:o,...a?{code:"too_big",maximum:e.length}:{code:"too_small",minimum:e.length},inclusive:!0,exact:!0,input:s.value,inst:n,continue:!e.abort})}}),m0=Q("$ZodCheckStringFormat",(n,e)=>{var t,s;Hs.init(n,e),n._zod.onattach.push(i=>{const r=i._zod.bag;r.format=e.format,e.pattern&&(r.patterns??(r.patterns=new Set),r.patterns.add(e.pattern))}),e.pattern?(t=n._zod).check??(t.check=i=>{e.pattern.lastIndex=0,!e.pattern.test(i.value)&&i.issues.push({origin:"string",code:"invalid_format",format:e.format,input:i.value,...e.pattern?{pattern:e.pattern.toString()}:{},inst:n,continue:!e.abort})}):(s=n._zod).check??(s.check=()=>{})}),V2=Q("$ZodCheckRegex",(n,e)=>{m0.init(n,e),n._zod.check=t=>{e.pattern.lastIndex=0,!e.pattern.test(t.value)&&t.issues.push({origin:"string",code:"invalid_format",format:"regex",input:t.value,pattern:e.pattern.toString(),inst:n,continue:!e.abort})}}),W2=Q("$ZodCheckLowerCase",(n,e)=>{e.pattern??(e.pattern=j2),m0.init(n,e)}),G2=Q("$ZodCheckUpperCase",(n,e)=>{e.pattern??(e.pattern=F2),m0.init(n,e)}),K2=Q("$ZodCheckIncludes",(n,e)=>{Hs.init(n,e);const t=Fp(e.includes),s=new RegExp(typeof e.position=="number"?`^.{${e.position}}${t}`:t);e.pattern=s,n._zod.onattach.push(i=>{const r=i._zod.bag;r.patterns??(r.patterns=new Set),r.patterns.add(s)}),n._zod.check=i=>{i.value.includes(e.includes,e.position)||i.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:e.includes,input:i.value,inst:n,continue:!e.abort})}}),Z2=Q("$ZodCheckStartsWith",(n,e)=>{Hs.init(n,e);const t=new RegExp(`^${Fp(e.prefix)}.*`);e.pattern??(e.pattern=t),n._zod.onattach.push(s=>{const i=s._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(t)}),n._zod.check=s=>{s.value.startsWith(e.prefix)||s.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:e.prefix,input:s.value,inst:n,continue:!e.abort})}}),X2=Q("$ZodCheckEndsWith",(n,e)=>{Hs.init(n,e);const t=new RegExp(`.*${Fp(e.suffix)}$`);e.pattern??(e.pattern=t),n._zod.onattach.push(s=>{const i=s._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(t)}),n._zod.check=s=>{s.value.endsWith(e.suffix)||s.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:e.suffix,input:s.value,inst:n,continue:!e.abort})}}),Y2=Q("$ZodCheckOverwrite",(n,e)=>{Hs.init(n,e),n._zod.check=t=>{t.value=e.tx(t.value)}});class J2{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if(typeof e=="function"){e(this,{execution:"sync"}),e(this,{execution:"async"});return}const s=e.split(` +`).filter(o=>o),i=Math.min(...s.map(o=>o.length-o.trimStart().length)),r=s.map(o=>o.slice(i)).map(o=>" ".repeat(this.indent*2)+o);for(const o of r)this.content.push(o)}compile(){const e=Function,t=this==null?void 0:this.args,i=[...((this==null?void 0:this.content)??[""]).map(r=>` ${r}`)];return new e(...t,i.join(` +`))}}const Q2={major:4,minor:0,patch:0},xt=Q("$ZodType",(n,e)=>{var i;var t;n??(n={}),n._zod.def=e,n._zod.bag=n._zod.bag||{},n._zod.version=Q2;const s=[...n._zod.def.checks??[]];n._zod.traits.has("$ZodCheck")&&s.unshift(n);for(const r of s)for(const o of r._zod.onattach)o(n);if(s.length===0)(t=n._zod).deferred??(t.deferred=[]),(i=n._zod.deferred)==null||i.push(()=>{n._zod.run=n._zod.parse});else{const r=(o,a,l)=>{let c=Dd(o),h;for(const u of a){if(u._zod.def.when){if(!u._zod.def.when(o))continue}else if(c)continue;const d=o.issues.length,p=u._zod.check(o);if(p instanceof Promise&&(l==null?void 0:l.async)===!1)throw new sf;if(h||p instanceof Promise)h=(h??Promise.resolve()).then(async()=>{await p,o.issues.length!==d&&(c||(c=Dd(o,d)))});else{if(o.issues.length===d)continue;c||(c=Dd(o,d))}}return h?h.then(()=>o):o};n._zod.run=(o,a)=>{const l=n._zod.parse(o,a);if(l instanceof Promise){if(a.async===!1)throw new sf;return l.then(c=>r(c,s,a))}return r(l,s,a)}}n["~standard"]={validate:r=>{var o;try{const a=y$(n,r);return a.success?{value:a.data}:{issues:(o=a.error)==null?void 0:o.issues}}catch{return h2(n,r).then(l=>{var c;return l.success?{value:l.data}:{issues:(c=l.error)==null?void 0:c.issues}})}},vendor:"zod",version:1}}),lS=Q("$ZodString",(n,e)=>{var t;xt.init(n,e),n._zod.pattern=[...((t=n==null?void 0:n._zod.bag)==null?void 0:t.patterns)??[]].pop()??M2(n._zod.bag),n._zod.parse=(s,i)=>{if(e.coerce)try{s.value=String(s.value)}catch{}return typeof s.value=="string"||s.issues.push({expected:"string",code:"invalid_type",input:s.value,inst:n}),s}}),Nt=Q("$ZodStringFormat",(n,e)=>{m0.init(n,e),lS.init(n,e)}),ej=Q("$ZodGUID",(n,e)=>{e.pattern??(e.pattern=v2),Nt.init(n,e)}),tj=Q("$ZodUUID",(n,e)=>{if(e.version){const s={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[e.version];if(s===void 0)throw new Error(`Invalid UUID version: "${e.version}"`);e.pattern??(e.pattern=kA(s))}else e.pattern??(e.pattern=kA());Nt.init(n,e)}),nj=Q("$ZodEmail",(n,e)=>{e.pattern??(e.pattern=b2),Nt.init(n,e)}),sj=Q("$ZodURL",(n,e)=>{Nt.init(n,e),n._zod.check=t=>{try{const s=t.value,i=new URL(s),r=i.href;e.hostname&&(e.hostname.lastIndex=0,e.hostname.test(i.hostname)||t.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:C2.source,input:t.value,inst:n,continue:!e.abort})),e.protocol&&(e.protocol.lastIndex=0,e.protocol.test(i.protocol.endsWith(":")?i.protocol.slice(0,-1):i.protocol)||t.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:e.protocol.source,input:t.value,inst:n,continue:!e.abort})),!s.endsWith("/")&&r.endsWith("/")?t.value=r.slice(0,-1):t.value=r;return}catch{t.issues.push({code:"invalid_format",format:"url",input:t.value,inst:n,continue:!e.abort})}}}),ij=Q("$ZodEmoji",(n,e)=>{e.pattern??(e.pattern=_2()),Nt.init(n,e)}),rj=Q("$ZodNanoID",(n,e)=>{e.pattern??(e.pattern=g2),Nt.init(n,e)}),oj=Q("$ZodCUID",(n,e)=>{e.pattern??(e.pattern=u2),Nt.init(n,e)}),aj=Q("$ZodCUID2",(n,e)=>{e.pattern??(e.pattern=d2),Nt.init(n,e)}),lj=Q("$ZodULID",(n,e)=>{e.pattern??(e.pattern=f2),Nt.init(n,e)}),cj=Q("$ZodXID",(n,e)=>{e.pattern??(e.pattern=p2),Nt.init(n,e)}),hj=Q("$ZodKSUID",(n,e)=>{e.pattern??(e.pattern=m2),Nt.init(n,e)}),uj=Q("$ZodISODateTime",(n,e)=>{e.pattern??(e.pattern=R2(e)),Nt.init(n,e)}),dj=Q("$ZodISODate",(n,e)=>{e.pattern??(e.pattern=T2),Nt.init(n,e)}),fj=Q("$ZodISOTime",(n,e)=>{e.pattern??(e.pattern=P2(e)),Nt.init(n,e)}),pj=Q("$ZodISODuration",(n,e)=>{e.pattern??(e.pattern=y2),Nt.init(n,e)}),mj=Q("$ZodIPv4",(n,e)=>{e.pattern??(e.pattern=S2),Nt.init(n,e),n._zod.onattach.push(t=>{const s=t._zod.bag;s.format="ipv4"})}),gj=Q("$ZodIPv6",(n,e)=>{e.pattern??(e.pattern=x2),Nt.init(n,e),n._zod.onattach.push(t=>{const s=t._zod.bag;s.format="ipv6"}),n._zod.check=t=>{try{new URL(`http://[${t.value}]`)}catch{t.issues.push({code:"invalid_format",format:"ipv6",input:t.value,inst:n,continue:!e.abort})}}}),yj=Q("$ZodCIDRv4",(n,e)=>{e.pattern??(e.pattern=A2),Nt.init(n,e)}),vj=Q("$ZodCIDRv6",(n,e)=>{e.pattern??(e.pattern=k2),Nt.init(n,e),n._zod.check=t=>{const[s,i]=t.value.split("/");try{if(!i)throw new Error;const r=Number(i);if(`${r}`!==i)throw new Error;if(r<0||r>128)throw new Error;new URL(`http://[${s}]`)}catch{t.issues.push({code:"invalid_format",format:"cidrv6",input:t.value,inst:n,continue:!e.abort})}}});function k$(n){if(n==="")return!0;if(n.length%4!==0)return!1;try{return atob(n),!0}catch{return!1}}const bj=Q("$ZodBase64",(n,e)=>{e.pattern??(e.pattern=E2),Nt.init(n,e),n._zod.onattach.push(t=>{t._zod.bag.contentEncoding="base64"}),n._zod.check=t=>{k$(t.value)||t.issues.push({code:"invalid_format",format:"base64",input:t.value,inst:n,continue:!e.abort})}});function wj(n){if(!b$.test(n))return!1;const e=n.replace(/[-_]/g,s=>s==="-"?"+":"/"),t=e.padEnd(Math.ceil(e.length/4)*4,"=");return k$(t)}const _j=Q("$ZodBase64URL",(n,e)=>{e.pattern??(e.pattern=b$),Nt.init(n,e),n._zod.onattach.push(t=>{t._zod.bag.contentEncoding="base64url"}),n._zod.check=t=>{wj(t.value)||t.issues.push({code:"invalid_format",format:"base64url",input:t.value,inst:n,continue:!e.abort})}}),Sj=Q("$ZodE164",(n,e)=>{e.pattern??(e.pattern=$2),Nt.init(n,e)});function xj(n,e=null){try{const t=n.split(".");if(t.length!==3)return!1;const[s]=t;if(!s)return!1;const i=JSON.parse(atob(s));return!("typ"in i&&(i==null?void 0:i.typ)!=="JWT"||!i.alg||e&&(!("alg"in i)||i.alg!==e))}catch{return!1}}const Aj=Q("$ZodJWT",(n,e)=>{Nt.init(n,e),n._zod.check=t=>{xj(t.value,e.alg)||t.issues.push({code:"invalid_format",format:"jwt",input:t.value,inst:n,continue:!e.abort})}}),E$=Q("$ZodNumber",(n,e)=>{xt.init(n,e),n._zod.pattern=n._zod.bag.pattern??O2,n._zod.parse=(t,s)=>{if(e.coerce)try{t.value=Number(t.value)}catch{}const i=t.value;if(typeof i=="number"&&!Number.isNaN(i)&&Number.isFinite(i))return t;const r=typeof i=="number"?Number.isNaN(i)?"NaN":Number.isFinite(i)?void 0:"Infinity":void 0;return t.issues.push({expected:"number",code:"invalid_type",input:i,inst:n,...r?{received:r}:{}}),t}}),kj=Q("$ZodNumber",(n,e)=>{H2.init(n,e),E$.init(n,e)}),Ej=Q("$ZodBoolean",(n,e)=>{xt.init(n,e),n._zod.pattern=N2,n._zod.parse=(t,s)=>{if(e.coerce)try{t.value=!!t.value}catch{}const i=t.value;return typeof i=="boolean"||t.issues.push({expected:"boolean",code:"invalid_type",input:i,inst:n}),t}}),Cj=Q("$ZodUndefined",(n,e)=>{xt.init(n,e),n._zod.pattern=D2,n._zod.values=new Set([void 0]),n._zod.optin="optional",n._zod.optout="optional",n._zod.parse=(t,s)=>{const i=t.value;return typeof i>"u"||t.issues.push({expected:"undefined",code:"invalid_type",input:i,inst:n}),t}}),$j=Q("$ZodNull",(n,e)=>{xt.init(n,e),n._zod.pattern=L2,n._zod.values=new Set([null]),n._zod.parse=(t,s)=>{const i=t.value;return i===null||t.issues.push({expected:"null",code:"invalid_type",input:i,inst:n}),t}}),Tj=Q("$ZodAny",(n,e)=>{xt.init(n,e),n._zod.parse=t=>t}),Pj=Q("$ZodUnknown",(n,e)=>{xt.init(n,e),n._zod.parse=t=>t}),Rj=Q("$ZodNever",(n,e)=>{xt.init(n,e),n._zod.parse=(t,s)=>(t.issues.push({expected:"never",code:"invalid_type",input:t.value,inst:n}),t)});function EA(n,e,t){n.issues.length&&e.issues.push(...ll(t,n.issues)),e.value[t]=n.value}const Mj=Q("$ZodArray",(n,e)=>{xt.init(n,e),n._zod.parse=(t,s)=>{const i=t.value;if(!Array.isArray(i))return t.issues.push({expected:"array",code:"invalid_type",input:i,inst:n}),t;t.value=Array(i.length);const r=[];for(let o=0;oEA(c,t,o))):EA(l,t,o)}return r.length?Promise.all(r).then(()=>t):t}});function wm(n,e,t){n.issues.length&&e.issues.push(...ll(t,n.issues)),e.value[t]=n.value}function CA(n,e,t,s){n.issues.length?s[t]===void 0?t in s?e.value[t]=void 0:e.value[t]=n.value:e.issues.push(...ll(t,n.issues)):n.value===void 0?t in s&&(e.value[t]=void 0):e.value[t]=n.value}const Ij=Q("$ZodObject",(n,e)=>{xt.init(n,e);const t=iS(()=>{const u=Object.keys(e.shape);for(const p of u)if(!(e.shape[p]instanceof xt))throw new Error(`Invalid element at key "${p}": expected a Zod schema`);const d=JD(e.shape);return{shape:e.shape,keys:u,keySet:new Set(u),numKeys:u.length,optionalKeys:new Set(d)}});Pt(n._zod,"propValues",()=>{const u=e.shape,d={};for(const p in u){const m=u[p]._zod;if(m.values){d[p]??(d[p]=new Set);for(const y of m.values)d[p].add(y)}}return d});const s=u=>{const d=new J2(["shape","payload","ctx"]),p=t.value,m=b=>{const _=Ju(b);return`shape[${_}]._zod.run({ value: input[${_}], issues: [] }, ctx)`};d.write("const input = payload.value;");const y=Object.create(null);let v=0;for(const b of p.keys)y[b]=`key_${v++}`;d.write("const newResult = {}");for(const b of p.keys)if(p.optionalKeys.has(b)){const _=y[b];d.write(`const ${_} = ${m(b)};`);const x=Ju(b);d.write(` + if (${_}.issues.length) { + if (input[${x}] === undefined) { + if (${x} in input) { + newResult[${x}] = undefined; + } + } else { + payload.issues = payload.issues.concat( + ${_}.issues.map((iss) => ({ + ...iss, + path: iss.path ? [${x}, ...iss.path] : [${x}], + })) + ); + } + } else if (${_}.value === undefined) { + if (${x} in input) newResult[${x}] = undefined; + } else { + newResult[${x}] = ${_}.value; + } + `)}else{const _=y[b];d.write(`const ${_} = ${m(b)};`),d.write(` + if (${_}.issues.length) payload.issues = payload.issues.concat(${_}.issues.map(iss => ({ + ...iss, + path: iss.path ? [${Ju(b)}, ...iss.path] : [${Ju(b)}] + })));`),d.write(`newResult[${Ju(b)}] = ${_}.value`)}d.write("payload.value = newResult;"),d.write("return payload;");const g=d.compile();return(b,_)=>g(u,b,_)};let i;const r=ey,o=!u$.jitless,l=o&&XD.value,c=e.catchall;let h;n._zod.parse=(u,d)=>{h??(h=t.value);const p=u.value;if(!r(p))return u.issues.push({expected:"object",code:"invalid_type",input:p,inst:n}),u;const m=[];if(o&&l&&(d==null?void 0:d.async)===!1&&d.jitless!==!0)i||(i=s(e.shape)),u=i(u,d);else{u.value={};const _=h.shape;for(const x of h.keys){const A=_[x],C=A._zod.run({value:p[x],issues:[]},d),$=A._zod.optin==="optional"&&A._zod.optout==="optional";C instanceof Promise?m.push(C.then(I=>$?CA(I,u,x,p):wm(I,u,x))):$?CA(C,u,x,p):wm(C,u,x)}}if(!c)return m.length?Promise.all(m).then(()=>u):u;const y=[],v=h.keySet,g=c._zod,b=g.def.type;for(const _ of Object.keys(p)){if(v.has(_))continue;if(b==="never"){y.push(_);continue}const x=g.run({value:p[_],issues:[]},d);x instanceof Promise?m.push(x.then(A=>wm(A,u,_))):wm(x,u,_)}return y.length&&u.issues.push({code:"unrecognized_keys",keys:y,input:p,inst:n}),m.length?Promise.all(m).then(()=>u):u}});function $A(n,e,t,s){for(const i of n)if(i.issues.length===0)return e.value=i.value,e;return e.issues.push({code:"invalid_union",input:e.value,inst:t,errors:n.map(i=>i.issues.map(r=>$a(r,s,Ca())))}),e}const C$=Q("$ZodUnion",(n,e)=>{xt.init(n,e),Pt(n._zod,"optin",()=>e.options.some(t=>t._zod.optin==="optional")?"optional":void 0),Pt(n._zod,"optout",()=>e.options.some(t=>t._zod.optout==="optional")?"optional":void 0),Pt(n._zod,"values",()=>{if(e.options.every(t=>t._zod.values))return new Set(e.options.flatMap(t=>Array.from(t._zod.values)))}),Pt(n._zod,"pattern",()=>{if(e.options.every(t=>t._zod.pattern)){const t=e.options.map(s=>s._zod.pattern);return new RegExp(`^(${t.map(s=>oS(s.source)).join("|")})$`)}}),n._zod.parse=(t,s)=>{let i=!1;const r=[];for(const o of e.options){const a=o._zod.run({value:t.value,issues:[]},s);if(a instanceof Promise)r.push(a),i=!0;else{if(a.issues.length===0)return a;r.push(a)}}return i?Promise.all(r).then(o=>$A(o,t,n,s)):$A(r,t,n,s)}}),Oj=Q("$ZodDiscriminatedUnion",(n,e)=>{C$.init(n,e);const t=n._zod.parse;Pt(n._zod,"propValues",()=>{const i={};for(const r of e.options){const o=r._zod.propValues;if(!o||Object.keys(o).length===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(r)}"`);for(const[a,l]of Object.entries(o)){i[a]||(i[a]=new Set);for(const c of l)i[a].add(c)}}return i});const s=iS(()=>{const i=e.options,r=new Map;for(const o of i){const a=o._zod.propValues[e.discriminator];if(!a||a.size===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(o)}"`);for(const l of a){if(r.has(l))throw new Error(`Duplicate discriminator value "${String(l)}"`);r.set(l,o)}}return r});n._zod.parse=(i,r)=>{const o=i.value;if(!ey(o))return i.issues.push({code:"invalid_type",expected:"object",input:o,inst:n}),i;const a=s.value.get(o==null?void 0:o[e.discriminator]);return a?a._zod.run(i,r):e.unionFallback?t(i,r):(i.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",input:o,path:[e.discriminator],inst:n}),i)}}),Nj=Q("$ZodIntersection",(n,e)=>{xt.init(n,e),n._zod.parse=(t,s)=>{const i=t.value,r=e.left._zod.run({value:i,issues:[]},s),o=e.right._zod.run({value:i,issues:[]},s);return r instanceof Promise||o instanceof Promise?Promise.all([r,o]).then(([l,c])=>TA(t,l,c)):TA(t,r,o)}});function rb(n,e){if(n===e)return{valid:!0,data:n};if(n instanceof Date&&e instanceof Date&&+n==+e)return{valid:!0,data:n};if(ty(n)&&ty(e)){const t=Object.keys(e),s=Object.keys(n).filter(r=>t.indexOf(r)!==-1),i={...n,...e};for(const r of s){const o=rb(n[r],e[r]);if(!o.valid)return{valid:!1,mergeErrorPath:[r,...o.mergeErrorPath]};i[r]=o.data}return{valid:!0,data:i}}if(Array.isArray(n)&&Array.isArray(e)){if(n.length!==e.length)return{valid:!1,mergeErrorPath:[]};const t=[];for(let s=0;s{xt.init(n,e),n._zod.parse=(t,s)=>{const i=t.value;if(!ty(i))return t.issues.push({expected:"record",code:"invalid_type",input:i,inst:n}),t;const r=[];if(e.keyType._zod.values){const o=e.keyType._zod.values;t.value={};for(const l of o)if(typeof l=="string"||typeof l=="number"||typeof l=="symbol"){const c=e.valueType._zod.run({value:i[l],issues:[]},s);c instanceof Promise?r.push(c.then(h=>{h.issues.length&&t.issues.push(...ll(l,h.issues)),t.value[l]=h.value})):(c.issues.length&&t.issues.push(...ll(l,c.issues)),t.value[l]=c.value)}let a;for(const l in i)o.has(l)||(a=a??[],a.push(l));a&&a.length>0&&t.issues.push({code:"unrecognized_keys",input:i,inst:n,keys:a})}else{t.value={};for(const o of Reflect.ownKeys(i)){if(o==="__proto__")continue;const a=e.keyType._zod.run({value:o,issues:[]},s);if(a instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(a.issues.length){t.issues.push({origin:"record",code:"invalid_key",issues:a.issues.map(c=>$a(c,s,Ca())),input:o,path:[o],inst:n}),t.value[a.value]=a.value;continue}const l=e.valueType._zod.run({value:i[o],issues:[]},s);l instanceof Promise?r.push(l.then(c=>{c.issues.length&&t.issues.push(...ll(o,c.issues)),t.value[a.value]=c.value})):(l.issues.length&&t.issues.push(...ll(o,l.issues)),t.value[a.value]=l.value)}}return r.length?Promise.all(r).then(()=>t):t}}),Dj=Q("$ZodEnum",(n,e)=>{xt.init(n,e);const t=GD(e.entries);n._zod.values=new Set(t),n._zod.pattern=new RegExp(`^(${t.filter(s=>YD.has(typeof s)).map(s=>typeof s=="string"?Fp(s):s.toString()).join("|")})$`),n._zod.parse=(s,i)=>{const r=s.value;return n._zod.values.has(r)||s.issues.push({code:"invalid_value",values:t,input:r,inst:n}),s}}),jj=Q("$ZodLiteral",(n,e)=>{xt.init(n,e),n._zod.values=new Set(e.values),n._zod.pattern=new RegExp(`^(${e.values.map(t=>typeof t=="string"?Fp(t):t?t.toString():String(t)).join("|")})$`),n._zod.parse=(t,s)=>{const i=t.value;return n._zod.values.has(i)||t.issues.push({code:"invalid_value",values:e.values,input:i,inst:n}),t}}),Fj=Q("$ZodTransform",(n,e)=>{xt.init(n,e),n._zod.parse=(t,s)=>{const i=e.transform(t.value,t);if(s.async)return(i instanceof Promise?i:Promise.resolve(i)).then(o=>(t.value=o,t));if(i instanceof Promise)throw new sf;return t.value=i,t}}),zj=Q("$ZodOptional",(n,e)=>{xt.init(n,e),n._zod.optin="optional",n._zod.optout="optional",Pt(n._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,void 0]):void 0),Pt(n._zod,"pattern",()=>{const t=e.innerType._zod.pattern;return t?new RegExp(`^(${oS(t.source)})?$`):void 0}),n._zod.parse=(t,s)=>e.innerType._zod.optin==="optional"?e.innerType._zod.run(t,s):t.value===void 0?t:e.innerType._zod.run(t,s)}),Hj=Q("$ZodNullable",(n,e)=>{xt.init(n,e),Pt(n._zod,"optin",()=>e.innerType._zod.optin),Pt(n._zod,"optout",()=>e.innerType._zod.optout),Pt(n._zod,"pattern",()=>{const t=e.innerType._zod.pattern;return t?new RegExp(`^(${oS(t.source)}|null)$`):void 0}),Pt(n._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,null]):void 0),n._zod.parse=(t,s)=>t.value===null?t:e.innerType._zod.run(t,s)}),Bj=Q("$ZodDefault",(n,e)=>{xt.init(n,e),n._zod.optin="optional",Pt(n._zod,"values",()=>e.innerType._zod.values),n._zod.parse=(t,s)=>{if(t.value===void 0)return t.value=e.defaultValue,t;const i=e.innerType._zod.run(t,s);return i instanceof Promise?i.then(r=>PA(r,e)):PA(i,e)}});function PA(n,e){return n.value===void 0&&(n.value=e.defaultValue),n}const Uj=Q("$ZodPrefault",(n,e)=>{xt.init(n,e),n._zod.optin="optional",Pt(n._zod,"values",()=>e.innerType._zod.values),n._zod.parse=(t,s)=>(t.value===void 0&&(t.value=e.defaultValue),e.innerType._zod.run(t,s))}),qj=Q("$ZodNonOptional",(n,e)=>{xt.init(n,e),Pt(n._zod,"values",()=>{const t=e.innerType._zod.values;return t?new Set([...t].filter(s=>s!==void 0)):void 0}),n._zod.parse=(t,s)=>{const i=e.innerType._zod.run(t,s);return i instanceof Promise?i.then(r=>RA(r,n)):RA(i,n)}});function RA(n,e){return!n.issues.length&&n.value===void 0&&n.issues.push({code:"invalid_type",expected:"nonoptional",input:n.value,inst:e}),n}const Vj=Q("$ZodCatch",(n,e)=>{xt.init(n,e),n._zod.optin="optional",Pt(n._zod,"optout",()=>e.innerType._zod.optout),Pt(n._zod,"values",()=>e.innerType._zod.values),n._zod.parse=(t,s)=>{const i=e.innerType._zod.run(t,s);return i instanceof Promise?i.then(r=>(t.value=r.value,r.issues.length&&(t.value=e.catchValue({...t,error:{issues:r.issues.map(o=>$a(o,s,Ca()))},input:t.value}),t.issues=[]),t)):(t.value=i.value,i.issues.length&&(t.value=e.catchValue({...t,error:{issues:i.issues.map(r=>$a(r,s,Ca()))},input:t.value}),t.issues=[]),t)}}),Wj=Q("$ZodPipe",(n,e)=>{xt.init(n,e),Pt(n._zod,"values",()=>e.in._zod.values),Pt(n._zod,"optin",()=>e.in._zod.optin),Pt(n._zod,"optout",()=>e.out._zod.optout),n._zod.parse=(t,s)=>{const i=e.in._zod.run(t,s);return i instanceof Promise?i.then(r=>MA(r,e,s)):MA(i,e,s)}});function MA(n,e,t){return Dd(n)?n:e.out._zod.run({value:n.value,issues:n.issues},t)}const Gj=Q("$ZodReadonly",(n,e)=>{xt.init(n,e),Pt(n._zod,"propValues",()=>e.innerType._zod.propValues),Pt(n._zod,"values",()=>e.innerType._zod.values),Pt(n._zod,"optin",()=>e.innerType._zod.optin),Pt(n._zod,"optout",()=>e.innerType._zod.optout),n._zod.parse=(t,s)=>{const i=e.innerType._zod.run(t,s);return i instanceof Promise?i.then(IA):IA(i)}});function IA(n){return n.value=Object.freeze(n.value),n}const Kj=Q("$ZodCustom",(n,e)=>{Hs.init(n,e),xt.init(n,e),n._zod.parse=(t,s)=>t,n._zod.check=t=>{const s=t.value,i=e.fn(s);if(i instanceof Promise)return i.then(r=>OA(r,t,s,n));OA(i,t,s,n)}});function OA(n,e,t,s){if(!n){const i={code:"custom",input:t,inst:s,path:[...s._zod.def.path??[]],continue:!s._zod.def.abort};s._zod.def.params&&(i.params=s._zod.def.params),e.issues.push(rf(i))}}class Zj{constructor(){this._map=new Map,this._idmap=new Map}add(e,...t){const s=t[0];if(this._map.set(e,s),s&&typeof s=="object"&&"id"in s){if(this._idmap.has(s.id))throw new Error(`ID ${s.id} already exists in the registry`);this._idmap.set(s.id,e)}return this}clear(){return this._map=new Map,this._idmap=new Map,this}remove(e){const t=this._map.get(e);return t&&typeof t=="object"&&"id"in t&&this._idmap.delete(t.id),this._map.delete(e),this}get(e){const t=e._zod.parent;if(t){const s={...this.get(t)??{}};return delete s.id,{...s,...this._map.get(e)}}return this._map.get(e)}has(e){return this._map.has(e)}}function Xj(){return new Zj}const _m=Xj();function Yj(n,e){return new n({type:"string",...ve(e)})}function Jj(n,e){return new n({type:"string",format:"email",check:"string_format",abort:!1,...ve(e)})}function NA(n,e){return new n({type:"string",format:"guid",check:"string_format",abort:!1,...ve(e)})}function Qj(n,e){return new n({type:"string",format:"uuid",check:"string_format",abort:!1,...ve(e)})}function eF(n,e){return new n({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...ve(e)})}function tF(n,e){return new n({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...ve(e)})}function nF(n,e){return new n({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...ve(e)})}function $$(n,e){return new n({type:"string",format:"url",check:"string_format",abort:!1,...ve(e)})}function sF(n,e){return new n({type:"string",format:"emoji",check:"string_format",abort:!1,...ve(e)})}function iF(n,e){return new n({type:"string",format:"nanoid",check:"string_format",abort:!1,...ve(e)})}function rF(n,e){return new n({type:"string",format:"cuid",check:"string_format",abort:!1,...ve(e)})}function oF(n,e){return new n({type:"string",format:"cuid2",check:"string_format",abort:!1,...ve(e)})}function aF(n,e){return new n({type:"string",format:"ulid",check:"string_format",abort:!1,...ve(e)})}function lF(n,e){return new n({type:"string",format:"xid",check:"string_format",abort:!1,...ve(e)})}function cF(n,e){return new n({type:"string",format:"ksuid",check:"string_format",abort:!1,...ve(e)})}function hF(n,e){return new n({type:"string",format:"ipv4",check:"string_format",abort:!1,...ve(e)})}function uF(n,e){return new n({type:"string",format:"ipv6",check:"string_format",abort:!1,...ve(e)})}function dF(n,e){return new n({type:"string",format:"cidrv4",check:"string_format",abort:!1,...ve(e)})}function fF(n,e){return new n({type:"string",format:"cidrv6",check:"string_format",abort:!1,...ve(e)})}function pF(n,e){return new n({type:"string",format:"base64",check:"string_format",abort:!1,...ve(e)})}function mF(n,e){return new n({type:"string",format:"base64url",check:"string_format",abort:!1,...ve(e)})}function gF(n,e){return new n({type:"string",format:"e164",check:"string_format",abort:!1,...ve(e)})}function yF(n,e){return new n({type:"string",format:"jwt",check:"string_format",abort:!1,...ve(e)})}function vF(n,e){return new n({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...ve(e)})}function bF(n,e){return new n({type:"string",format:"date",check:"string_format",...ve(e)})}function wF(n,e){return new n({type:"string",format:"time",check:"string_format",precision:null,...ve(e)})}function _F(n,e){return new n({type:"string",format:"duration",check:"string_format",...ve(e)})}function SF(n,e){return new n({type:"number",checks:[],...ve(e)})}function xF(n,e){return new n({type:"number",coerce:!0,checks:[],...ve(e)})}function AF(n,e){return new n({type:"number",check:"number_format",abort:!1,format:"safeint",...ve(e)})}function kF(n,e){return new n({type:"boolean",...ve(e)})}function EF(n,e){return new n({type:"undefined",...ve(e)})}function CF(n,e){return new n({type:"null",...ve(e)})}function $F(n){return new n({type:"any"})}function TF(n){return new n({type:"unknown"})}function PF(n,e){return new n({type:"never",...ve(e)})}function LA(n,e){return new x$({check:"less_than",...ve(e),value:n,inclusive:!1})}function hv(n,e){return new x$({check:"less_than",...ve(e),value:n,inclusive:!0})}function DA(n,e){return new A$({check:"greater_than",...ve(e),value:n,inclusive:!1})}function uv(n,e){return new A$({check:"greater_than",...ve(e),value:n,inclusive:!0})}function jA(n,e){return new z2({check:"multiple_of",...ve(e),value:n})}function T$(n,e){return new B2({check:"max_length",...ve(e),maximum:n})}function ny(n,e){return new U2({check:"min_length",...ve(e),minimum:n})}function P$(n,e){return new q2({check:"length_equals",...ve(e),length:n})}function RF(n,e){return new V2({check:"string_format",format:"regex",...ve(e),pattern:n})}function MF(n){return new W2({check:"string_format",format:"lowercase",...ve(n)})}function IF(n){return new G2({check:"string_format",format:"uppercase",...ve(n)})}function OF(n,e){return new K2({check:"string_format",format:"includes",...ve(e),includes:n})}function NF(n,e){return new Z2({check:"string_format",format:"starts_with",...ve(e),prefix:n})}function LF(n,e){return new X2({check:"string_format",format:"ends_with",...ve(e),suffix:n})}function zp(n){return new Y2({check:"overwrite",tx:n})}function DF(n){return zp(e=>e.normalize(n))}function jF(){return zp(n=>n.trim())}function FF(){return zp(n=>n.toLowerCase())}function zF(){return zp(n=>n.toUpperCase())}function HF(n,e,t){return new n({type:"array",element:e,...ve(t)})}function BF(n,e,t){const s=ve(t);return s.abort??(s.abort=!0),new n({type:"custom",check:"custom",fn:e,...s})}function UF(n,e,t){return new n({type:"custom",check:"custom",fn:e,...ve(t)})}const qF=Q("ZodISODateTime",(n,e)=>{uj.init(n,e),qt.init(n,e)});function R$(n){return vF(qF,n)}const VF=Q("ZodISODate",(n,e)=>{dj.init(n,e),qt.init(n,e)});function WF(n){return bF(VF,n)}const GF=Q("ZodISOTime",(n,e)=>{fj.init(n,e),qt.init(n,e)});function KF(n){return wF(GF,n)}const ZF=Q("ZodISODuration",(n,e)=>{pj.init(n,e),qt.init(n,e)});function XF(n){return _F(ZF,n)}const YF=(n,e)=>{p$.init(n,e),n.name="ZodError",Object.defineProperties(n,{format:{value:t=>a2(n,t)},flatten:{value:t=>o2(n,t)},addIssue:{value:t=>n.issues.push(t)},addIssues:{value:t=>n.issues.push(...t)},isEmpty:{get(){return n.issues.length===0}}})},g0=Q("ZodError",YF,{Parent:Error}),JF=l2(g0),QF=c2(g0),ez=g$(g0),tz=v$(g0),Rt=Q("ZodType",(n,e)=>(xt.init(n,e),n.def=e,Object.defineProperty(n,"_def",{value:e}),n.check=(...t)=>n.clone({...e,checks:[...e.checks??[],...t.map(s=>typeof s=="function"?{_zod:{check:s,def:{check:"custom"},onattach:[]}}:s)]}),n.clone=(t,s)=>Ec(n,t,s),n.brand=()=>n,n.register=(t,s)=>(t.add(n,s),n),n.parse=(t,s)=>JF(n,t,s,{callee:n.parse}),n.safeParse=(t,s)=>ez(n,t,s),n.parseAsync=async(t,s)=>QF(n,t,s,{callee:n.parseAsync}),n.safeParseAsync=async(t,s)=>tz(n,t,s),n.spa=n.safeParseAsync,n.refine=(t,s)=>n.check(Gz(t,s)),n.superRefine=t=>n.check(Kz(t)),n.overwrite=t=>n.check(zp(t)),n.optional=()=>Ut(n),n.nullable=()=>HA(n),n.nullish=()=>Ut(HA(n)),n.nonoptional=t=>Fz(n,t),n.array=()=>re(n),n.or=t=>Ye([n,t]),n.and=t=>uS(n,t),n.transform=t=>cb(n,D$(t)),n.default=t=>Lz(n,t),n.prefault=t=>jz(n,t),n.catch=t=>Hz(n,t),n.pipe=t=>cb(n,t),n.readonly=()=>qz(n),n.describe=t=>{const s=n.clone();return _m.add(s,{description:t}),s},Object.defineProperty(n,"description",{get(){var t;return(t=_m.get(n))==null?void 0:t.description},configurable:!0}),n.meta=(...t)=>{if(t.length===0)return _m.get(n);const s=n.clone();return _m.add(s,t[0]),s},n.isOptional=()=>n.safeParse(void 0).success,n.isNullable=()=>n.safeParse(null).success,n)),M$=Q("_ZodString",(n,e)=>{lS.init(n,e),Rt.init(n,e);const t=n._zod.bag;n.format=t.format??null,n.minLength=t.minimum??null,n.maxLength=t.maximum??null,n.regex=(...s)=>n.check(RF(...s)),n.includes=(...s)=>n.check(OF(...s)),n.startsWith=(...s)=>n.check(NF(...s)),n.endsWith=(...s)=>n.check(LF(...s)),n.min=(...s)=>n.check(ny(...s)),n.max=(...s)=>n.check(T$(...s)),n.length=(...s)=>n.check(P$(...s)),n.nonempty=(...s)=>n.check(ny(1,...s)),n.lowercase=s=>n.check(MF(s)),n.uppercase=s=>n.check(IF(s)),n.trim=()=>n.check(jF()),n.normalize=(...s)=>n.check(DF(...s)),n.toLowerCase=()=>n.check(FF()),n.toUpperCase=()=>n.check(zF())}),nz=Q("ZodString",(n,e)=>{lS.init(n,e),M$.init(n,e),n.email=t=>n.check(Jj(sz,t)),n.url=t=>n.check($$(I$,t)),n.jwt=t=>n.check(yF(bz,t)),n.emoji=t=>n.check(sF(rz,t)),n.guid=t=>n.check(NA(FA,t)),n.uuid=t=>n.check(Qj(Sm,t)),n.uuidv4=t=>n.check(eF(Sm,t)),n.uuidv6=t=>n.check(tF(Sm,t)),n.uuidv7=t=>n.check(nF(Sm,t)),n.nanoid=t=>n.check(iF(oz,t)),n.guid=t=>n.check(NA(FA,t)),n.cuid=t=>n.check(rF(az,t)),n.cuid2=t=>n.check(oF(lz,t)),n.ulid=t=>n.check(aF(cz,t)),n.base64=t=>n.check(pF(gz,t)),n.base64url=t=>n.check(mF(yz,t)),n.xid=t=>n.check(lF(hz,t)),n.ksuid=t=>n.check(cF(uz,t)),n.ipv4=t=>n.check(hF(dz,t)),n.ipv6=t=>n.check(uF(fz,t)),n.cidrv4=t=>n.check(dF(pz,t)),n.cidrv6=t=>n.check(fF(mz,t)),n.e164=t=>n.check(gF(vz,t)),n.datetime=t=>n.check(R$(t)),n.date=t=>n.check(WF(t)),n.time=t=>n.check(KF(t)),n.duration=t=>n.check(XF(t))});function F(n){return Yj(nz,n)}const qt=Q("ZodStringFormat",(n,e)=>{Nt.init(n,e),M$.init(n,e)}),sz=Q("ZodEmail",(n,e)=>{nj.init(n,e),qt.init(n,e)}),FA=Q("ZodGUID",(n,e)=>{ej.init(n,e),qt.init(n,e)}),Sm=Q("ZodUUID",(n,e)=>{tj.init(n,e),qt.init(n,e)}),I$=Q("ZodURL",(n,e)=>{sj.init(n,e),qt.init(n,e)});function iz(n){return $$(I$,n)}const rz=Q("ZodEmoji",(n,e)=>{ij.init(n,e),qt.init(n,e)}),oz=Q("ZodNanoID",(n,e)=>{rj.init(n,e),qt.init(n,e)}),az=Q("ZodCUID",(n,e)=>{oj.init(n,e),qt.init(n,e)}),lz=Q("ZodCUID2",(n,e)=>{aj.init(n,e),qt.init(n,e)}),cz=Q("ZodULID",(n,e)=>{lj.init(n,e),qt.init(n,e)}),hz=Q("ZodXID",(n,e)=>{cj.init(n,e),qt.init(n,e)}),uz=Q("ZodKSUID",(n,e)=>{hj.init(n,e),qt.init(n,e)}),dz=Q("ZodIPv4",(n,e)=>{mj.init(n,e),qt.init(n,e)}),fz=Q("ZodIPv6",(n,e)=>{gj.init(n,e),qt.init(n,e)}),pz=Q("ZodCIDRv4",(n,e)=>{yj.init(n,e),qt.init(n,e)}),mz=Q("ZodCIDRv6",(n,e)=>{vj.init(n,e),qt.init(n,e)}),gz=Q("ZodBase64",(n,e)=>{bj.init(n,e),qt.init(n,e)}),yz=Q("ZodBase64URL",(n,e)=>{_j.init(n,e),qt.init(n,e)}),vz=Q("ZodE164",(n,e)=>{Sj.init(n,e),qt.init(n,e)}),bz=Q("ZodJWT",(n,e)=>{Aj.init(n,e),qt.init(n,e)}),cS=Q("ZodNumber",(n,e)=>{E$.init(n,e),Rt.init(n,e),n.gt=(s,i)=>n.check(DA(s,i)),n.gte=(s,i)=>n.check(uv(s,i)),n.min=(s,i)=>n.check(uv(s,i)),n.lt=(s,i)=>n.check(LA(s,i)),n.lte=(s,i)=>n.check(hv(s,i)),n.max=(s,i)=>n.check(hv(s,i)),n.int=s=>n.check(zA(s)),n.safe=s=>n.check(zA(s)),n.positive=s=>n.check(DA(0,s)),n.nonnegative=s=>n.check(uv(0,s)),n.negative=s=>n.check(LA(0,s)),n.nonpositive=s=>n.check(hv(0,s)),n.multipleOf=(s,i)=>n.check(jA(s,i)),n.step=(s,i)=>n.check(jA(s,i)),n.finite=()=>n;const t=n._zod.bag;n.minValue=Math.max(t.minimum??Number.NEGATIVE_INFINITY,t.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,n.maxValue=Math.min(t.maximum??Number.POSITIVE_INFINITY,t.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,n.isInt=(t.format??"").includes("int")||Number.isSafeInteger(t.multipleOf??.5),n.isFinite=!0,n.format=t.format??null});function je(n){return SF(cS,n)}const wz=Q("ZodNumberFormat",(n,e)=>{kj.init(n,e),cS.init(n,e)});function zA(n){return AF(wz,n)}const _z=Q("ZodBoolean",(n,e)=>{Ej.init(n,e),Rt.init(n,e)});function et(n){return kF(_z,n)}const Sz=Q("ZodUndefined",(n,e)=>{Cj.init(n,e),Rt.init(n,e)});function ob(n){return EF(Sz,n)}const xz=Q("ZodNull",(n,e)=>{$j.init(n,e),Rt.init(n,e)});function Az(n){return CF(xz,n)}const kz=Q("ZodAny",(n,e)=>{Tj.init(n,e),Rt.init(n,e)});function hS(){return $F(kz)}const Ez=Q("ZodUnknown",(n,e)=>{Pj.init(n,e),Rt.init(n,e)});function St(){return TF(Ez)}const Cz=Q("ZodNever",(n,e)=>{Rj.init(n,e),Rt.init(n,e)});function ab(n){return PF(Cz,n)}const $z=Q("ZodArray",(n,e)=>{Mj.init(n,e),Rt.init(n,e),n.element=e.element,n.min=(t,s)=>n.check(ny(t,s)),n.nonempty=t=>n.check(ny(1,t)),n.max=(t,s)=>n.check(T$(t,s)),n.length=(t,s)=>n.check(P$(t,s)),n.unwrap=()=>n.element});function re(n,e){return HF($z,n,e)}const O$=Q("ZodObject",(n,e)=>{Ij.init(n,e),Rt.init(n,e),Pt(n,"shape",()=>e.shape),n.keyof=()=>ri(Object.keys(n._zod.def.shape)),n.catchall=t=>n.clone({...n._zod.def,catchall:t}),n.passthrough=()=>n.clone({...n._zod.def,catchall:St()}),n.loose=()=>n.clone({...n._zod.def,catchall:St()}),n.strict=()=>n.clone({...n._zod.def,catchall:ab()}),n.strip=()=>n.clone({...n._zod.def,catchall:void 0}),n.extend=t=>n2(n,t),n.merge=t=>s2(n,t),n.pick=t=>e2(n,t),n.omit=t=>t2(n,t),n.partial=(...t)=>i2(j$,n,t[0]),n.required=(...t)=>r2(F$,n,t[0])});function K(n,e){const t={type:"object",get shape(){return p0(this,"shape",{...n}),this.shape},...ve(e)};return new O$(t)}function Vn(n,e){return new O$({type:"object",get shape(){return p0(this,"shape",{...n}),this.shape},catchall:St(),...ve(e)})}const N$=Q("ZodUnion",(n,e)=>{C$.init(n,e),Rt.init(n,e),n.options=e.options});function Ye(n,e){return new N$({type:"union",options:n,...ve(e)})}const Tz=Q("ZodDiscriminatedUnion",(n,e)=>{N$.init(n,e),Oj.init(n,e)});function L$(n,e,t){return new Tz({type:"union",options:e,discriminator:n,...ve(t)})}const Pz=Q("ZodIntersection",(n,e)=>{Nj.init(n,e),Rt.init(n,e)});function uS(n,e){return new Pz({type:"intersection",left:n,right:e})}const Rz=Q("ZodRecord",(n,e)=>{Lj.init(n,e),Rt.init(n,e),n.keyType=e.keyType,n.valueType=e.valueType});function tt(n,e,t){return new Rz({type:"record",keyType:n,valueType:e,...ve(t)})}const lb=Q("ZodEnum",(n,e)=>{Dj.init(n,e),Rt.init(n,e),n.enum=e.entries,n.options=Object.values(e.entries);const t=new Set(Object.keys(e.entries));n.extract=(s,i)=>{const r={};for(const o of s)if(t.has(o))r[o]=e.entries[o];else throw new Error(`Key ${o} not found in enum`);return new lb({...e,checks:[],...ve(i),entries:r})},n.exclude=(s,i)=>{const r={...e.entries};for(const o of s)if(t.has(o))delete r[o];else throw new Error(`Key ${o} not found in enum`);return new lb({...e,checks:[],...ve(i),entries:r})}});function ri(n,e){const t=Array.isArray(n)?Object.fromEntries(n.map(s=>[s,s])):n;return new lb({type:"enum",entries:t,...ve(e)})}const Mz=Q("ZodLiteral",(n,e)=>{jj.init(n,e),Rt.init(n,e),n.values=new Set(e.values),Object.defineProperty(n,"value",{get(){if(e.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return e.values[0]}})});function W(n,e){return new Mz({type:"literal",values:Array.isArray(n)?n:[n],...ve(e)})}const Iz=Q("ZodTransform",(n,e)=>{Fj.init(n,e),Rt.init(n,e),n._zod.parse=(t,s)=>{t.addIssue=r=>{if(typeof r=="string")t.issues.push(rf(r,t.value,e));else{const o=r;o.fatal&&(o.continue=!1),o.code??(o.code="custom"),o.input??(o.input=t.value),o.inst??(o.inst=n),o.continue??(o.continue=!0),t.issues.push(rf(o))}};const i=e.transform(t.value,t);return i instanceof Promise?i.then(r=>(t.value=r,t)):(t.value=i,t)}});function D$(n){return new Iz({type:"transform",transform:n})}const j$=Q("ZodOptional",(n,e)=>{zj.init(n,e),Rt.init(n,e),n.unwrap=()=>n._zod.def.innerType});function Ut(n){return new j$({type:"optional",innerType:n})}const Oz=Q("ZodNullable",(n,e)=>{Hj.init(n,e),Rt.init(n,e),n.unwrap=()=>n._zod.def.innerType});function HA(n){return new Oz({type:"nullable",innerType:n})}const Nz=Q("ZodDefault",(n,e)=>{Bj.init(n,e),Rt.init(n,e),n.unwrap=()=>n._zod.def.innerType,n.removeDefault=n.unwrap});function Lz(n,e){return new Nz({type:"default",innerType:n,get defaultValue(){return typeof e=="function"?e():e}})}const Dz=Q("ZodPrefault",(n,e)=>{Uj.init(n,e),Rt.init(n,e),n.unwrap=()=>n._zod.def.innerType});function jz(n,e){return new Dz({type:"prefault",innerType:n,get defaultValue(){return typeof e=="function"?e():e}})}const F$=Q("ZodNonOptional",(n,e)=>{qj.init(n,e),Rt.init(n,e),n.unwrap=()=>n._zod.def.innerType});function Fz(n,e){return new F$({type:"nonoptional",innerType:n,...ve(e)})}const zz=Q("ZodCatch",(n,e)=>{Vj.init(n,e),Rt.init(n,e),n.unwrap=()=>n._zod.def.innerType,n.removeCatch=n.unwrap});function Hz(n,e){return new zz({type:"catch",innerType:n,catchValue:typeof e=="function"?e:()=>e})}const Bz=Q("ZodPipe",(n,e)=>{Wj.init(n,e),Rt.init(n,e),n.in=e.in,n.out=e.out});function cb(n,e){return new Bz({type:"pipe",in:n,out:e})}const Uz=Q("ZodReadonly",(n,e)=>{Gj.init(n,e),Rt.init(n,e)});function qz(n){return new Uz({type:"readonly",innerType:n})}const z$=Q("ZodCustom",(n,e)=>{Kj.init(n,e),Rt.init(n,e)});function Vz(n){const e=new Hs({check:"custom"});return e._zod.check=n,e}function Wz(n,e){return BF(z$,n??(()=>!0),e)}function Gz(n,e={}){return UF(z$,n,e)}function Kz(n){const e=Vz(t=>(t.addIssue=s=>{if(typeof s=="string")t.issues.push(rf(s,t.value,e._zod.def));else{const i=s;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),i.input??(i.input=t.value),i.inst??(i.inst=e),i.continue??(i.continue=!e._zod.def.abort),t.issues.push(rf(i))}},n(t.value,t)));return e}function H$(n,e){return cb(D$(n),e)}const Zz={custom:"custom"};function Xz(n){return xF(cS,n)}const y0="2025-11-25",Yz=[y0,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],Ga="io.modelcontextprotocol/related-task",v0="2.0",vn=Wz(n=>n!==null&&(typeof n=="object"||typeof n=="function")),B$=Ye([F(),je().int()]),U$=F();Vn({ttl:je().optional(),pollInterval:je().optional()});const Jz=K({ttl:je().optional()}),Qz=K({taskId:F()}),dS=Vn({progressToken:B$.optional(),[Ga]:Qz.optional()}),oi=K({_meta:dS.optional()}),Hp=oi.extend({task:Jz.optional()}),eH=n=>Hp.safeParse(n).success,Kn=K({method:F(),params:oi.loose().optional()}),xi=K({_meta:dS.optional()}),Ai=K({method:F(),params:xi.loose().optional()}),Zn=Vn({_meta:dS.optional()}),Bp=Ye([F(),je().int()]),q$=K({jsonrpc:W(v0),id:Bp,...Kn.shape}).strict(),hb=n=>q$.safeParse(n).success,V$=K({jsonrpc:W(v0),...Ai.shape}).strict(),tH=n=>V$.safeParse(n).success,fS=K({jsonrpc:W(v0),id:Bp,result:Zn}).strict(),dd=n=>fS.safeParse(n).success;var Re;(function(n){n[n.ConnectionClosed=-32e3]="ConnectionClosed",n[n.RequestTimeout=-32001]="RequestTimeout",n[n.ParseError=-32700]="ParseError",n[n.InvalidRequest=-32600]="InvalidRequest",n[n.MethodNotFound=-32601]="MethodNotFound",n[n.InvalidParams=-32602]="InvalidParams",n[n.InternalError=-32603]="InternalError",n[n.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(Re||(Re={}));const pS=K({jsonrpc:W(v0),id:Bp.optional(),error:K({code:je().int(),message:F(),data:St().optional()})}).strict(),nH=n=>pS.safeParse(n).success,og=Ye([q$,V$,fS,pS]);Ye([fS,pS]);const th=Zn.strict(),sH=xi.extend({requestId:Bp.optional(),reason:F().optional()}),mS=Ai.extend({method:W("notifications/cancelled"),params:sH}),iH=K({src:F(),mimeType:F().optional(),sizes:re(F()).optional(),theme:ri(["light","dark"]).optional()}),Up=K({icons:re(iH).optional()}),vu=K({name:F(),title:F().optional()}),b0=vu.extend({...vu.shape,...Up.shape,version:F(),websiteUrl:F().optional(),description:F().optional()}),rH=uS(K({applyDefaults:et().optional()}),tt(F(),St())),oH=H$(n=>n&&typeof n=="object"&&!Array.isArray(n)&&Object.keys(n).length===0?{form:{}}:n,uS(K({form:rH.optional(),url:vn.optional()}),tt(F(),St()).optional())),aH=Vn({list:vn.optional(),cancel:vn.optional(),requests:Vn({sampling:Vn({createMessage:vn.optional()}).optional(),elicitation:Vn({create:vn.optional()}).optional()}).optional()}),lH=Vn({list:vn.optional(),cancel:vn.optional(),requests:Vn({tools:Vn({call:vn.optional()}).optional()}).optional()}),cH=K({experimental:tt(F(),vn).optional(),sampling:K({context:vn.optional(),tools:vn.optional()}).optional(),elicitation:oH.optional(),roots:K({listChanged:et().optional()}).optional(),tasks:aH.optional(),extensions:tt(F(),vn).optional()}),hH=oi.extend({protocolVersion:F(),capabilities:cH,clientInfo:b0}),uH=Kn.extend({method:W("initialize"),params:hH}),dH=K({experimental:tt(F(),vn).optional(),logging:vn.optional(),completions:vn.optional(),prompts:K({listChanged:et().optional()}).optional(),resources:K({subscribe:et().optional(),listChanged:et().optional()}).optional(),tools:K({listChanged:et().optional()}).optional(),tasks:lH.optional(),extensions:tt(F(),vn).optional()}),W$=Zn.extend({protocolVersion:F(),capabilities:dH,serverInfo:b0,instructions:F().optional()}),G$=Ai.extend({method:W("notifications/initialized"),params:xi.optional()}),fH=n=>G$.safeParse(n).success,w0=Kn.extend({method:W("ping"),params:oi.optional()}),pH=K({progress:je(),total:Ut(je()),message:Ut(F())}),mH=K({...xi.shape,...pH.shape,progressToken:B$}),gS=Ai.extend({method:W("notifications/progress"),params:mH}),gH=oi.extend({cursor:U$.optional()}),qp=Kn.extend({params:gH.optional()}),Vp=Zn.extend({nextCursor:U$.optional()}),yH=ri(["working","input_required","completed","failed","cancelled"]),Wp=K({taskId:F(),status:yH,ttl:Ye([je(),Az()]),createdAt:F(),lastUpdatedAt:F(),pollInterval:Ut(je()),statusMessage:Ut(F())}),of=Zn.extend({task:Wp}),vH=xi.merge(Wp),sy=Ai.extend({method:W("notifications/tasks/status"),params:vH}),yS=Kn.extend({method:W("tasks/get"),params:oi.extend({taskId:F()})}),vS=Zn.merge(Wp),bS=Kn.extend({method:W("tasks/result"),params:oi.extend({taskId:F()})});Zn.loose();const wS=qp.extend({method:W("tasks/list")}),_S=Vp.extend({tasks:re(Wp)}),SS=Kn.extend({method:W("tasks/cancel"),params:oi.extend({taskId:F()})}),bH=Zn.merge(Wp),K$=K({uri:F(),mimeType:Ut(F()),_meta:tt(F(),St()).optional()}),Z$=K$.extend({text:F()}),xS=F().refine(n=>{try{return atob(n),!0}catch{return!1}},{message:"Invalid Base64 string"}),X$=K$.extend({blob:xS}),Gp=ri(["user","assistant"]),Nu=K({audience:re(Gp).optional(),priority:je().min(0).max(1).optional(),lastModified:R$({offset:!0}).optional()}),Y$=K({...vu.shape,...Up.shape,uri:F(),description:Ut(F()),mimeType:Ut(F()),size:Ut(je()),annotations:Nu.optional(),_meta:Ut(Vn({}))}),wH=K({...vu.shape,...Up.shape,uriTemplate:F(),description:Ut(F()),mimeType:Ut(F()),annotations:Nu.optional(),_meta:Ut(Vn({}))}),J$=qp.extend({method:W("resources/list")}),AS=Vp.extend({resources:re(Y$)}),Q$=qp.extend({method:W("resources/templates/list")}),kS=Vp.extend({resourceTemplates:re(wH)}),ES=oi.extend({uri:F()}),_H=ES,eT=Kn.extend({method:W("resources/read"),params:_H}),CS=Zn.extend({contents:re(Ye([Z$,X$]))}),$S=Ai.extend({method:W("notifications/resources/list_changed"),params:xi.optional()}),SH=ES,xH=Kn.extend({method:W("resources/subscribe"),params:SH}),AH=ES,kH=Kn.extend({method:W("resources/unsubscribe"),params:AH}),EH=xi.extend({uri:F()}),CH=Ai.extend({method:W("notifications/resources/updated"),params:EH}),$H=K({name:F(),description:Ut(F()),required:Ut(et())}),TH=K({...vu.shape,...Up.shape,description:Ut(F()),arguments:Ut(re($H)),_meta:Ut(Vn({}))}),tT=qp.extend({method:W("prompts/list")}),TS=Vp.extend({prompts:re(TH)}),PH=oi.extend({name:F(),arguments:tt(F(),F()).optional()}),RH=Kn.extend({method:W("prompts/get"),params:PH}),PS=K({type:W("text"),text:F(),annotations:Nu.optional(),_meta:tt(F(),St()).optional()}),RS=K({type:W("image"),data:xS,mimeType:F(),annotations:Nu.optional(),_meta:tt(F(),St()).optional()}),MS=K({type:W("audio"),data:xS,mimeType:F(),annotations:Nu.optional(),_meta:tt(F(),St()).optional()}),MH=K({type:W("tool_use"),name:F(),id:F(),input:tt(F(),St()),_meta:tt(F(),St()).optional()}),nT=K({type:W("resource"),resource:Ye([Z$,X$]),annotations:Nu.optional(),_meta:tt(F(),St()).optional()}),sT=Y$.extend({type:W("resource_link")}),Kp=Ye([PS,RS,MS,sT,nT]),IH=K({role:Gp,content:Kp}),iT=Zn.extend({description:F().optional(),messages:re(IH)}),IS=Ai.extend({method:W("notifications/prompts/list_changed"),params:xi.optional()}),OH=K({title:F().optional(),readOnlyHint:et().optional(),destructiveHint:et().optional(),idempotentHint:et().optional(),openWorldHint:et().optional()}),NH=K({taskSupport:ri(["required","optional","forbidden"]).optional()}),OS=K({...vu.shape,...Up.shape,description:F().optional(),inputSchema:K({type:W("object"),properties:tt(F(),vn).optional(),required:re(F()).optional()}).catchall(St()),outputSchema:K({type:W("object"),properties:tt(F(),vn).optional(),required:re(F()).optional()}).catchall(St()).optional(),annotations:OH.optional(),execution:NH.optional(),_meta:tt(F(),St()).optional()}),LH=qp.extend({method:W("tools/list")}),NS=Vp.extend({tools:re(OS)}),lc=Zn.extend({content:re(Kp).default([]),structuredContent:tt(F(),St()).optional(),isError:et().optional()});lc.or(Zn.extend({toolResult:St()}));const DH=Hp.extend({name:F(),arguments:tt(F(),St()).optional()}),rT=Kn.extend({method:W("tools/call"),params:DH}),LS=Ai.extend({method:W("notifications/tools/list_changed"),params:xi.optional()}),jH=K({autoRefresh:et().default(!0),debounceMs:je().int().nonnegative().default(300)}),oT=ri(["debug","info","notice","warning","error","critical","alert","emergency"]),FH=oi.extend({level:oT}),zH=Kn.extend({method:W("logging/setLevel"),params:FH}),HH=xi.extend({level:oT,logger:F().optional(),data:St()}),aT=Ai.extend({method:W("notifications/message"),params:HH}),BH=K({name:F().optional()}),UH=K({hints:re(BH).optional(),costPriority:je().min(0).max(1).optional(),speedPriority:je().min(0).max(1).optional(),intelligencePriority:je().min(0).max(1).optional()}),qH=K({mode:ri(["auto","required","none"]).optional()}),VH=K({type:W("tool_result"),toolUseId:F().describe("The unique identifier for the corresponding tool call."),content:re(Kp).default([]),structuredContent:K({}).loose().optional(),isError:et().optional(),_meta:tt(F(),St()).optional()}),WH=L$("type",[PS,RS,MS]),iy=L$("type",[PS,RS,MS,MH,VH]),GH=K({role:Gp,content:Ye([iy,re(iy)]),_meta:tt(F(),St()).optional()}),KH=Hp.extend({messages:re(GH),modelPreferences:UH.optional(),systemPrompt:F().optional(),includeContext:ri(["none","thisServer","allServers"]).optional(),temperature:je().optional(),maxTokens:je().int(),stopSequences:re(F()).optional(),metadata:vn.optional(),tools:re(OS).optional(),toolChoice:qH.optional()}),DS=Kn.extend({method:W("sampling/createMessage"),params:KH}),lT=Zn.extend({model:F(),stopReason:Ut(ri(["endTurn","stopSequence","maxTokens"]).or(F())),role:Gp,content:WH}),cT=Zn.extend({model:F(),stopReason:Ut(ri(["endTurn","stopSequence","maxTokens","toolUse"]).or(F())),role:Gp,content:Ye([iy,re(iy)])}),ZH=K({type:W("boolean"),title:F().optional(),description:F().optional(),default:et().optional()}),XH=K({type:W("string"),title:F().optional(),description:F().optional(),minLength:je().optional(),maxLength:je().optional(),format:ri(["email","uri","date","date-time"]).optional(),default:F().optional()}),YH=K({type:ri(["number","integer"]),title:F().optional(),description:F().optional(),minimum:je().optional(),maximum:je().optional(),default:je().optional()}),JH=K({type:W("string"),title:F().optional(),description:F().optional(),enum:re(F()),default:F().optional()}),QH=K({type:W("string"),title:F().optional(),description:F().optional(),oneOf:re(K({const:F(),title:F()})),default:F().optional()}),eB=K({type:W("string"),title:F().optional(),description:F().optional(),enum:re(F()),enumNames:re(F()).optional(),default:F().optional()}),tB=Ye([JH,QH]),nB=K({type:W("array"),title:F().optional(),description:F().optional(),minItems:je().optional(),maxItems:je().optional(),items:K({type:W("string"),enum:re(F())}),default:re(F()).optional()}),sB=K({type:W("array"),title:F().optional(),description:F().optional(),minItems:je().optional(),maxItems:je().optional(),items:K({anyOf:re(K({const:F(),title:F()}))}),default:re(F()).optional()}),iB=Ye([nB,sB]),rB=Ye([eB,tB,iB]),oB=Ye([rB,ZH,XH,YH]),aB=Hp.extend({mode:W("form").optional(),message:F(),requestedSchema:K({type:W("object"),properties:tt(F(),oB),required:re(F()).optional()})}),lB=Hp.extend({mode:W("url"),message:F(),elicitationId:F(),url:F().url()}),cB=Ye([aB,lB]),hT=Kn.extend({method:W("elicitation/create"),params:cB}),hB=xi.extend({elicitationId:F()}),uB=Ai.extend({method:W("notifications/elicitation/complete"),params:hB}),uT=Zn.extend({action:ri(["accept","decline","cancel"]),content:H$(n=>n===null?void 0:n,tt(F(),Ye([F(),je(),et(),re(F())])).optional())}),dB=K({type:W("ref/resource"),uri:F()}),fB=K({type:W("ref/prompt"),name:F()}),pB=oi.extend({ref:Ye([fB,dB]),argument:K({name:F(),value:F()}),context:K({arguments:tt(F(),F()).optional()}).optional()}),mB=Kn.extend({method:W("completion/complete"),params:pB}),dT=Zn.extend({completion:Vn({values:re(F()).max(100),total:Ut(je().int()),hasMore:Ut(et())})}),gB=K({uri:F().startsWith("file://"),name:F().optional(),_meta:tt(F(),St()).optional()}),yB=Kn.extend({method:W("roots/list"),params:oi.optional()}),vB=Zn.extend({roots:re(gB)}),bB=Ai.extend({method:W("notifications/roots/list_changed"),params:xi.optional()});Ye([w0,uH,mB,zH,RH,tT,J$,Q$,eT,xH,kH,rT,LH,yS,bS,wS,SS]);Ye([mS,gS,G$,bB,sy]);Ye([th,lT,cT,uT,vB,vS,_S,of]);Ye([w0,DS,hT,yB,yS,bS,wS,SS]);Ye([mS,gS,aT,CH,$S,LS,IS,sy,uB]);Ye([th,W$,dT,iT,TS,AS,kS,CS,lc,NS,vS,_S,of]);class Ee extends Error{constructor(e,t,s){super(`MCP error ${e}: ${t}`),this.code=e,this.data=s,this.name="McpError"}static fromError(e,t,s){if(e===Re.UrlElicitationRequired&&s){const i=s;if(i.elicitations)return new wB(i.elicitations,t)}return new Ee(e,t,s)}}class wB extends Ee{constructor(e,t=`URL elicitation${e.length>1?"s":""} required`){super(Re.UrlElicitationRequired,t,{elicitations:e})}get elicitations(){var e;return((e=this.data)==null?void 0:e.elicitations)??[]}}function jS(n){return!!n._zod}function Fo(n,e){return jS(n)?y$(n,e):n.safeParse(e)}function fT(n){var t,s;if(!n)return;let e;if(jS(n)?e=(s=(t=n._zod)==null?void 0:t.def)==null?void 0:s.shape:e=n.shape,!!e){if(typeof e=="function")try{return e()}catch{return}return e}}function pT(n){var i;if(jS(n)){const o=(i=n._zod)==null?void 0:i.def;if(o){if(o.value!==void 0)return o.value;if(Array.isArray(o.values)&&o.values.length>0)return o.values[0]}}const t=n._def;if(t){if(t.value!==void 0)return t.value;if(Array.isArray(t.values)&&t.values.length>0)return t.values[0]}const s=n.value;if(s!==void 0)return s}function za(n){return n==="completed"||n==="failed"||n==="cancelled"}new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function BA(n){const e=fT(n),t=e==null?void 0:e.method;if(!t)throw new Error("Schema is missing a method literal");const s=pT(t);if(typeof s!="string")throw new Error("Schema method literal must be a string");return s}function UA(n,e){const t=Fo(n,e);if(!t.success)throw t.error;return t.data}const _B=6e4;class mT{constructor(e){this._options=e,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(mS,t=>{this._oncancel(t)}),this.setNotificationHandler(gS,t=>{this._onprogress(t)}),this.setRequestHandler(w0,t=>({})),this._taskStore=e==null?void 0:e.taskStore,this._taskMessageQueue=e==null?void 0:e.taskMessageQueue,this._taskStore&&(this.setRequestHandler(yS,async(t,s)=>{const i=await this._taskStore.getTask(t.params.taskId,s.sessionId);if(!i)throw new Ee(Re.InvalidParams,"Failed to retrieve task: Task not found");return{...i}}),this.setRequestHandler(bS,async(t,s)=>{const i=async()=>{var a;const r=t.params.taskId;if(this._taskMessageQueue){let l;for(;l=await this._taskMessageQueue.dequeue(r,s.sessionId);){if(l.type==="response"||l.type==="error"){const c=l.message,h=c.id,u=this._requestResolvers.get(h);if(u)if(this._requestResolvers.delete(h),l.type==="response")u(c);else{const d=c,p=new Ee(d.error.code,d.error.message,d.error.data);u(p)}else{const d=l.type==="response"?"Response":"Error";this._onerror(new Error(`${d} handler missing for request ${h}`))}continue}await((a=this._transport)==null?void 0:a.send(l.message,{relatedRequestId:s.requestId}))}}const o=await this._taskStore.getTask(r,s.sessionId);if(!o)throw new Ee(Re.InvalidParams,`Task not found: ${r}`);if(!za(o.status))return await this._waitForTaskUpdate(r,s.signal),await i();if(za(o.status)){const l=await this._taskStore.getTaskResult(r,s.sessionId);return this._clearTaskQueue(r),{...l,_meta:{...l._meta,[Ga]:{taskId:r}}}}return await i()};return await i()}),this.setRequestHandler(wS,async(t,s)=>{var i;try{const{tasks:r,nextCursor:o}=await this._taskStore.listTasks((i=t.params)==null?void 0:i.cursor,s.sessionId);return{tasks:r,nextCursor:o,_meta:{}}}catch(r){throw new Ee(Re.InvalidParams,`Failed to list tasks: ${r instanceof Error?r.message:String(r)}`)}}),this.setRequestHandler(SS,async(t,s)=>{try{const i=await this._taskStore.getTask(t.params.taskId,s.sessionId);if(!i)throw new Ee(Re.InvalidParams,`Task not found: ${t.params.taskId}`);if(za(i.status))throw new Ee(Re.InvalidParams,`Cannot cancel task in terminal status: ${i.status}`);await this._taskStore.updateTaskStatus(t.params.taskId,"cancelled","Client cancelled task execution.",s.sessionId),this._clearTaskQueue(t.params.taskId);const r=await this._taskStore.getTask(t.params.taskId,s.sessionId);if(!r)throw new Ee(Re.InvalidParams,`Task not found after cancellation: ${t.params.taskId}`);return{_meta:{},...r}}catch(i){throw i instanceof Ee?i:new Ee(Re.InvalidRequest,`Failed to cancel task: ${i instanceof Error?i.message:String(i)}`)}}))}async _oncancel(e){if(!e.params.requestId)return;const t=this._requestHandlerAbortControllers.get(e.params.requestId);t==null||t.abort(e.params.reason)}_setupTimeout(e,t,s,i,r=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(i,t),startTime:Date.now(),timeout:t,maxTotalTimeout:s,resetTimeoutOnProgress:r,onTimeout:i})}_resetTimeout(e){const t=this._timeoutInfo.get(e);if(!t)return!1;const s=Date.now()-t.startTime;if(t.maxTotalTimeout&&s>=t.maxTotalTimeout)throw this._timeoutInfo.delete(e),Ee.fromError(Re.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:t.maxTotalTimeout,totalElapsed:s});return clearTimeout(t.timeoutId),t.timeoutId=setTimeout(t.onTimeout,t.timeout),!0}_cleanupTimeout(e){const t=this._timeoutInfo.get(e);t&&(clearTimeout(t.timeoutId),this._timeoutInfo.delete(e))}async connect(e){var r,o,a;if(this._transport)throw new Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.");this._transport=e;const t=(r=this.transport)==null?void 0:r.onclose;this._transport.onclose=()=>{t==null||t(),this._onclose()};const s=(o=this.transport)==null?void 0:o.onerror;this._transport.onerror=l=>{s==null||s(l),this._onerror(l)};const i=(a=this._transport)==null?void 0:a.onmessage;this._transport.onmessage=(l,c)=>{i==null||i(l,c),dd(l)||nH(l)?this._onresponse(l):hb(l)?this._onrequest(l,c):tH(l)?this._onnotification(l):this._onerror(new Error(`Unknown message type: ${JSON.stringify(l)}`))},await this._transport.start()}_onclose(){var s;const e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(const i of this._timeoutInfo.values())clearTimeout(i.timeoutId);this._timeoutInfo.clear();for(const i of this._requestHandlerAbortControllers.values())i.abort();this._requestHandlerAbortControllers.clear();const t=Ee.fromError(Re.ConnectionClosed,"Connection closed");this._transport=void 0,(s=this.onclose)==null||s.call(this);for(const i of e.values())i(t)}_onerror(e){var t;(t=this.onerror)==null||t.call(this,e)}_onnotification(e){const t=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;t!==void 0&&Promise.resolve().then(()=>t(e)).catch(s=>this._onerror(new Error(`Uncaught error in notification handler: ${s}`)))}_onrequest(e,t){var h,u,d,p;const s=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,i=this._transport,r=(d=(u=(h=e.params)==null?void 0:h._meta)==null?void 0:u[Ga])==null?void 0:d.taskId;if(s===void 0){const m={jsonrpc:"2.0",id:e.id,error:{code:Re.MethodNotFound,message:"Method not found"}};r&&this._taskMessageQueue?this._enqueueTaskMessage(r,{type:"error",message:m,timestamp:Date.now()},i==null?void 0:i.sessionId).catch(y=>this._onerror(new Error(`Failed to enqueue error response: ${y}`))):i==null||i.send(m).catch(y=>this._onerror(new Error(`Failed to send an error response: ${y}`)));return}const o=new AbortController;this._requestHandlerAbortControllers.set(e.id,o);const a=eH(e.params)?e.params.task:void 0,l=this._taskStore?this.requestTaskStore(e,i==null?void 0:i.sessionId):void 0,c={signal:o.signal,sessionId:i==null?void 0:i.sessionId,_meta:(p=e.params)==null?void 0:p._meta,sendNotification:async m=>{if(o.signal.aborted)return;const y={relatedRequestId:e.id};r&&(y.relatedTask={taskId:r}),await this.notification(m,y)},sendRequest:async(m,y,v)=>{var _;if(o.signal.aborted)throw new Ee(Re.ConnectionClosed,"Request was cancelled");const g={...v,relatedRequestId:e.id};r&&!g.relatedTask&&(g.relatedTask={taskId:r});const b=((_=g.relatedTask)==null?void 0:_.taskId)??r;return b&&l&&await l.updateTaskStatus(b,"input_required"),await this.request(m,y,g)},authInfo:t==null?void 0:t.authInfo,requestId:e.id,requestInfo:t==null?void 0:t.requestInfo,taskId:r,taskStore:l,taskRequestedTtl:a==null?void 0:a.ttl,closeSSEStream:t==null?void 0:t.closeSSEStream,closeStandaloneSSEStream:t==null?void 0:t.closeStandaloneSSEStream};Promise.resolve().then(()=>{a&&this.assertTaskHandlerCapability(e.method)}).then(()=>s(e,c)).then(async m=>{if(o.signal.aborted)return;const y={result:m,jsonrpc:"2.0",id:e.id};r&&this._taskMessageQueue?await this._enqueueTaskMessage(r,{type:"response",message:y,timestamp:Date.now()},i==null?void 0:i.sessionId):await(i==null?void 0:i.send(y))},async m=>{if(o.signal.aborted)return;const y={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(m.code)?m.code:Re.InternalError,message:m.message??"Internal error",...m.data!==void 0&&{data:m.data}}};r&&this._taskMessageQueue?await this._enqueueTaskMessage(r,{type:"error",message:y,timestamp:Date.now()},i==null?void 0:i.sessionId):await(i==null?void 0:i.send(y))}).catch(m=>this._onerror(new Error(`Failed to send response: ${m}`))).finally(()=>{this._requestHandlerAbortControllers.get(e.id)===o&&this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){const{progressToken:t,...s}=e.params,i=Number(t),r=this._progressHandlers.get(i);if(!r){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}const o=this._responseHandlers.get(i),a=this._timeoutInfo.get(i);if(a&&o&&a.resetTimeoutOnProgress)try{this._resetTimeout(i)}catch(l){this._responseHandlers.delete(i),this._progressHandlers.delete(i),this._cleanupTimeout(i),o(l);return}r(s)}_onresponse(e){const t=Number(e.id),s=this._requestResolvers.get(t);if(s){if(this._requestResolvers.delete(t),dd(e))s(e);else{const o=new Ee(e.error.code,e.error.message,e.error.data);s(o)}return}const i=this._responseHandlers.get(t);if(i===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(t),this._cleanupTimeout(t);let r=!1;if(dd(e)&&e.result&&typeof e.result=="object"){const o=e.result;if(o.task&&typeof o.task=="object"){const a=o.task;typeof a.taskId=="string"&&(r=!0,this._taskProgressTokens.set(a.taskId,t))}}if(r||this._progressHandlers.delete(t),dd(e))i(e);else{const o=Ee.fromError(e.error.code,e.error.message,e.error.data);i(o)}}get transport(){return this._transport}async close(){var e;await((e=this._transport)==null?void 0:e.close())}async*requestStream(e,t,s){var o,a;const{task:i}=s??{};if(!i){try{yield{type:"result",result:await this.request(e,t,s)}}catch(l){yield{type:"error",error:l instanceof Ee?l:new Ee(Re.InternalError,String(l))}}return}let r;try{const l=await this.request(e,of,s);if(l.task)r=l.task.taskId,yield{type:"taskCreated",task:l.task};else throw new Ee(Re.InternalError,"Task creation did not return a task");for(;;){const c=await this.getTask({taskId:r},s);if(yield{type:"taskStatus",task:c},za(c.status)){c.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:r},t,s)}:c.status==="failed"?yield{type:"error",error:new Ee(Re.InternalError,`Task ${r} failed`)}:c.status==="cancelled"&&(yield{type:"error",error:new Ee(Re.InternalError,`Task ${r} was cancelled`)});return}if(c.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:r},t,s)};return}const h=c.pollInterval??((o=this._options)==null?void 0:o.defaultTaskPollInterval)??1e3;await new Promise(u=>setTimeout(u,h)),(a=s==null?void 0:s.signal)==null||a.throwIfAborted()}}catch(l){yield{type:"error",error:l instanceof Ee?l:new Ee(Re.InternalError,String(l))}}}request(e,t,s){const{relatedRequestId:i,resumptionToken:r,onresumptiontoken:o,task:a,relatedTask:l}=s??{};return new Promise((c,h)=>{var b,_,x,A,C;const u=$=>{h($)};if(!this._transport){u(new Error("Not connected"));return}if(((b=this._options)==null?void 0:b.enforceStrictCapabilities)===!0)try{this.assertCapabilityForMethod(e.method),a&&this.assertTaskCapability(e.method)}catch($){u($);return}(_=s==null?void 0:s.signal)==null||_.throwIfAborted();const d=this._requestMessageId++,p={...e,jsonrpc:"2.0",id:d};s!=null&&s.onprogress&&(this._progressHandlers.set(d,s.onprogress),p.params={...e.params,_meta:{...((x=e.params)==null?void 0:x._meta)||{},progressToken:d}}),a&&(p.params={...p.params,task:a}),l&&(p.params={...p.params,_meta:{...((A=p.params)==null?void 0:A._meta)||{},[Ga]:l}});const m=$=>{var j;this._responseHandlers.delete(d),this._progressHandlers.delete(d),this._cleanupTimeout(d),(j=this._transport)==null||j.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:d,reason:String($)}},{relatedRequestId:i,resumptionToken:r,onresumptiontoken:o}).catch(q=>this._onerror(new Error(`Failed to send cancellation: ${q}`)));const I=$ instanceof Ee?$:new Ee(Re.RequestTimeout,String($));h(I)};this._responseHandlers.set(d,$=>{var I;if(!((I=s==null?void 0:s.signal)!=null&&I.aborted)){if($ instanceof Error)return h($);try{const j=Fo(t,$.result);j.success?c(j.data):h(j.error)}catch(j){h(j)}}}),(C=s==null?void 0:s.signal)==null||C.addEventListener("abort",()=>{var $;m(($=s==null?void 0:s.signal)==null?void 0:$.reason)});const y=(s==null?void 0:s.timeout)??_B,v=()=>m(Ee.fromError(Re.RequestTimeout,"Request timed out",{timeout:y}));this._setupTimeout(d,y,s==null?void 0:s.maxTotalTimeout,v,(s==null?void 0:s.resetTimeoutOnProgress)??!1);const g=l==null?void 0:l.taskId;if(g){const $=I=>{const j=this._responseHandlers.get(d);j?j(I):this._onerror(new Error(`Response handler missing for side-channeled request ${d}`))};this._requestResolvers.set(d,$),this._enqueueTaskMessage(g,{type:"request",message:p,timestamp:Date.now()}).catch(I=>{this._cleanupTimeout(d),h(I)})}else this._transport.send(p,{relatedRequestId:i,resumptionToken:r,onresumptiontoken:o}).catch($=>{this._cleanupTimeout(d),h($)})})}async getTask(e,t){return this.request({method:"tasks/get",params:e},vS,t)}async getTaskResult(e,t,s){return this.request({method:"tasks/result",params:e},t,s)}async listTasks(e,t){return this.request({method:"tasks/list",params:e},_S,t)}async cancelTask(e,t){return this.request({method:"tasks/cancel",params:e},bH,t)}async notification(e,t){var a,l,c,h;if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(e.method);const s=(a=t==null?void 0:t.relatedTask)==null?void 0:a.taskId;if(s){const u={...e,jsonrpc:"2.0",params:{...e.params,_meta:{...((l=e.params)==null?void 0:l._meta)||{},[Ga]:t.relatedTask}}};await this._enqueueTaskMessage(s,{type:"notification",message:u,timestamp:Date.now()});return}if((((c=this._options)==null?void 0:c.debouncedNotificationMethods)??[]).includes(e.method)&&!e.params&&!(t!=null&&t.relatedRequestId)&&!(t!=null&&t.relatedTask)){if(this._pendingDebouncedNotifications.has(e.method))return;this._pendingDebouncedNotifications.add(e.method),Promise.resolve().then(()=>{var d,p;if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;let u={...e,jsonrpc:"2.0"};t!=null&&t.relatedTask&&(u={...u,params:{...u.params,_meta:{...((d=u.params)==null?void 0:d._meta)||{},[Ga]:t.relatedTask}}}),(p=this._transport)==null||p.send(u,t).catch(m=>this._onerror(m))});return}let o={...e,jsonrpc:"2.0"};t!=null&&t.relatedTask&&(o={...o,params:{...o.params,_meta:{...((h=o.params)==null?void 0:h._meta)||{},[Ga]:t.relatedTask}}}),await this._transport.send(o,t)}setRequestHandler(e,t){const s=BA(e);this.assertRequestHandlerCapability(s),this._requestHandlers.set(s,(i,r)=>{const o=UA(e,i);return Promise.resolve(t(o,r))})}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw new Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,t){const s=BA(e);this._notificationHandlers.set(s,i=>{const r=UA(e,i);return Promise.resolve(t(r))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){const t=this._taskProgressTokens.get(e);t!==void 0&&(this._progressHandlers.delete(t),this._taskProgressTokens.delete(e))}async _enqueueTaskMessage(e,t,s){var r;if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");const i=(r=this._options)==null?void 0:r.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,t,s,i)}async _clearTaskQueue(e,t){if(this._taskMessageQueue){const s=await this._taskMessageQueue.dequeueAll(e,t);for(const i of s)if(i.type==="request"&&hb(i.message)){const r=i.message.id,o=this._requestResolvers.get(r);o?(o(new Ee(Re.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(r)):this._onerror(new Error(`Resolver missing for request ${r} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,t){var i,r;let s=((i=this._options)==null?void 0:i.defaultTaskPollInterval)??1e3;try{const o=await((r=this._taskStore)==null?void 0:r.getTask(e));o!=null&&o.pollInterval&&(s=o.pollInterval)}catch{}return new Promise((o,a)=>{if(t.aborted){a(new Ee(Re.InvalidRequest,"Request cancelled"));return}const l=setTimeout(o,s);t.addEventListener("abort",()=>{clearTimeout(l),a(new Ee(Re.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(e,t){const s=this._taskStore;if(!s)throw new Error("No task store configured");return{createTask:async i=>{if(!e)throw new Error("No request provided");return await s.createTask(i,e.id,{method:e.method,params:e.params},t)},getTask:async i=>{const r=await s.getTask(i,t);if(!r)throw new Ee(Re.InvalidParams,"Failed to retrieve task: Task not found");return r},storeTaskResult:async(i,r,o)=>{await s.storeTaskResult(i,r,o,t);const a=await s.getTask(i,t);if(a){const l=sy.parse({method:"notifications/tasks/status",params:a});await this.notification(l),za(a.status)&&this._cleanupTaskProgressHandler(i)}},getTaskResult:i=>s.getTaskResult(i,t),updateTaskStatus:async(i,r,o)=>{const a=await s.getTask(i,t);if(!a)throw new Ee(Re.InvalidParams,`Task "${i}" not found - it may have been cleaned up`);if(za(a.status))throw new Ee(Re.InvalidParams,`Cannot update task "${i}" from terminal status "${a.status}" to "${r}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await s.updateTaskStatus(i,r,o,t);const l=await s.getTask(i,t);if(l){const c=sy.parse({method:"notifications/tasks/status",params:l});await this.notification(c),za(l.status)&&this._cleanupTaskProgressHandler(i)}},listTasks:i=>s.listTasks(i,t)}}}function qA(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)}function SB(n,e){const t={...n};for(const s in e){const i=s,r=e[i];if(r===void 0)continue;const o=t[i];qA(o)&&qA(r)?t[i]={...o,...r}:t[i]=r}return t}(n=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(n,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):n)(function(n){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+n+'" is not supported')});class xB extends mT{constructor(){super(...arguments);oe(this,"_registeredMethods",new Set);oe(this,"_eventSlots",new Map);oe(this,"setRequestHandler",(t,s)=>{this._assertMethodNotRegistered(t,"setRequestHandler"),super.setRequestHandler(t,s)});oe(this,"setNotificationHandler",(t,s)=>{this._assertMethodNotRegistered(t,"setNotificationHandler"),super.setNotificationHandler(t,s)});oe(this,"replaceRequestHandler",(t,s)=>{let i=t.shape.method.value;this._registeredMethods.add(i),super.setRequestHandler(t,s)})}onEventDispatch(t,s){}_ensureEventSlot(t){let s=this._eventSlots.get(t);if(!s){let i=this.eventSchemas[t];if(!i)throw Error(`Unknown event: ${String(t)}`);s={listeners:[]},this._eventSlots.set(t,s);let r=i.shape.method.value;this._registeredMethods.add(r);let o=s;super.setNotificationHandler(i,a=>{var c;let l=a.params;this.onEventDispatch(t,l),(c=o.onHandler)==null||c.call(o,l);for(let h of[...o.listeners])h(l)})}return s}setEventHandler(t,s){let i=this._ensureEventSlot(t);i.onHandler&&s&&console.warn(`[MCP Apps] on${String(t)} handler replaced. Use addEventListener("${String(t)}", …) to add multiple listeners without replacing.`),i.onHandler=s}getEventHandler(t){var s;return(s=this._eventSlots.get(t))==null?void 0:s.onHandler}addEventListener(t,s){this._ensureEventSlot(t).listeners.push(s)}removeEventListener(t,s){let i=this._eventSlots.get(t);if(!i)return;let r=i.listeners.indexOf(s);r!==-1&&i.listeners.splice(r,1)}warnIfRequestHandlerReplaced(t,s,i){s&&i&&console.warn(`[MCP Apps] ${t} handler replaced. Previous handler will no longer be called.`)}_assertMethodNotRegistered(t,s){let i=t.shape.method.value;if(this._registeredMethods.has(i))throw Error(`Handler for "${i}" already registered (via ${s}). Use addEventListener() to attach multiple listeners, or the on* setter for replace semantics.`);this._registeredMethods.add(i)}}var gT="2026-01-26",AB="ui/notifications/tool-input-partial",kB=Ye([W("light"),W("dark")]).describe("Color theme preference for the host environment."),af=Ye([W("inline"),W("fullscreen"),W("pip")]).describe("Display mode for UI presentation."),EB=Ye([W("--color-background-primary"),W("--color-background-secondary"),W("--color-background-tertiary"),W("--color-background-inverse"),W("--color-background-ghost"),W("--color-background-info"),W("--color-background-danger"),W("--color-background-success"),W("--color-background-warning"),W("--color-background-disabled"),W("--color-text-primary"),W("--color-text-secondary"),W("--color-text-tertiary"),W("--color-text-inverse"),W("--color-text-ghost"),W("--color-text-info"),W("--color-text-danger"),W("--color-text-success"),W("--color-text-warning"),W("--color-text-disabled"),W("--color-border-primary"),W("--color-border-secondary"),W("--color-border-tertiary"),W("--color-border-inverse"),W("--color-border-ghost"),W("--color-border-info"),W("--color-border-danger"),W("--color-border-success"),W("--color-border-warning"),W("--color-border-disabled"),W("--color-ring-primary"),W("--color-ring-secondary"),W("--color-ring-inverse"),W("--color-ring-info"),W("--color-ring-danger"),W("--color-ring-success"),W("--color-ring-warning"),W("--font-sans"),W("--font-mono"),W("--font-weight-normal"),W("--font-weight-medium"),W("--font-weight-semibold"),W("--font-weight-bold"),W("--font-text-xs-size"),W("--font-text-sm-size"),W("--font-text-md-size"),W("--font-text-lg-size"),W("--font-heading-xs-size"),W("--font-heading-sm-size"),W("--font-heading-md-size"),W("--font-heading-lg-size"),W("--font-heading-xl-size"),W("--font-heading-2xl-size"),W("--font-heading-3xl-size"),W("--font-text-xs-line-height"),W("--font-text-sm-line-height"),W("--font-text-md-line-height"),W("--font-text-lg-line-height"),W("--font-heading-xs-line-height"),W("--font-heading-sm-line-height"),W("--font-heading-md-line-height"),W("--font-heading-lg-line-height"),W("--font-heading-xl-line-height"),W("--font-heading-2xl-line-height"),W("--font-heading-3xl-line-height"),W("--border-radius-xs"),W("--border-radius-sm"),W("--border-radius-md"),W("--border-radius-lg"),W("--border-radius-xl"),W("--border-radius-full"),W("--border-width-regular"),W("--shadow-hairline"),W("--shadow-sm"),W("--shadow-md"),W("--shadow-lg")]).describe("CSS variable keys available to MCP apps for theming."),CB=tt(EB.describe(`Style variables for theming MCP apps. + +Individual style keys are optional - hosts may provide any subset of these values. +Values are strings containing CSS values (colors, sizes, font stacks, etc.). + +Note: This type uses \`Record\` rather than \`Partial>\` +for compatibility with Zod schema generation. Both are functionally equivalent for validation.`),Ye([F(),ob()]).describe(`Style variables for theming MCP apps. + +Individual style keys are optional - hosts may provide any subset of these values. +Values are strings containing CSS values (colors, sizes, font stacks, etc.). + +Note: This type uses \`Record\` rather than \`Partial>\` +for compatibility with Zod schema generation. Both are functionally equivalent for validation.`)).describe(`Style variables for theming MCP apps. + +Individual style keys are optional - hosts may provide any subset of these values. +Values are strings containing CSS values (colors, sizes, font stacks, etc.). + +Note: This type uses \`Record\` rather than \`Partial>\` +for compatibility with Zod schema generation. Both are functionally equivalent for validation.`),$B=K({method:W("ui/open-link"),params:K({url:F().describe("URL to open in the host's browser")})});K({isError:et().optional().describe("True if the host failed to open the URL (e.g., due to security policy).")}).passthrough();K({isError:et().optional().describe("True if the download failed (e.g., user cancelled or host denied).")}).passthrough();K({isError:et().optional().describe("True if the host rejected or failed to deliver the message.")}).passthrough();var TB=K({method:W("ui/notifications/sandbox-proxy-ready"),params:K({})}),FS=K({connectDomains:re(F()).optional().describe(`Origins for network requests (fetch/XHR/WebSocket). + +- Maps to CSP \`connect-src\` directive +- Empty or omitted → no network connections (secure default)`),resourceDomains:re(F()).optional().describe("Origins for static resources (images, scripts, stylesheets, fonts, media).\n\n- Maps to CSP `img-src`, `script-src`, `style-src`, `font-src`, `media-src` directives\n- Wildcard subdomains supported: `https://*.example.com`\n- Empty or omitted → no network resources (secure default)"),frameDomains:re(F()).optional().describe("Origins for nested iframes.\n\n- Maps to CSP `frame-src` directive\n- Empty or omitted → no nested iframes allowed (`frame-src 'none'`)"),baseUriDomains:re(F()).optional().describe("Allowed base URIs for the document.\n\n- Maps to CSP `base-uri` directive\n- Empty or omitted → only same origin allowed (`base-uri 'self'`)")}),zS=K({camera:K({}).optional().describe("Request camera access.\n\nMaps to Permission Policy `camera` feature."),microphone:K({}).optional().describe("Request microphone access.\n\nMaps to Permission Policy `microphone` feature."),geolocation:K({}).optional().describe("Request geolocation access.\n\nMaps to Permission Policy `geolocation` feature."),clipboardWrite:K({}).optional().describe("Request clipboard write access.\n\nMaps to Permission Policy `clipboard-write` feature.")}),PB=K({method:W("ui/notifications/size-changed"),params:K({width:je().optional().describe("New width in pixels."),height:je().optional().describe("New height in pixels.")})});K({method:W("ui/notifications/tool-input"),params:K({arguments:tt(F(),St().describe("Complete tool call arguments as key-value pairs.")).optional().describe("Complete tool call arguments as key-value pairs.")})});K({method:W("ui/notifications/tool-input-partial"),params:K({arguments:tt(F(),St().describe("Partial tool call arguments (incomplete, may change).")).optional().describe("Partial tool call arguments (incomplete, may change).")})});K({method:W("ui/notifications/tool-cancelled"),params:K({reason:F().optional().describe('Optional reason for the cancellation (e.g., "user action", "timeout").')})});var RB=K({fonts:F().optional()}),MB=K({variables:CB.optional().describe("CSS variables for theming the app."),css:RB.optional().describe("CSS blocks that apps can inject.")});K({method:W("ui/resource-teardown"),params:K({})});var IB=tt(F(),St()),VA=K({text:K({}).optional().describe("Host supports text content blocks."),image:K({}).optional().describe("Host supports image content blocks."),audio:K({}).optional().describe("Host supports audio content blocks."),resource:K({}).optional().describe("Host supports resource content blocks."),resourceLink:K({}).optional().describe("Host supports resource link content blocks."),structuredContent:K({}).optional().describe("Host supports structured content.")}),OB=K({method:W("ui/notifications/request-teardown"),params:K({}).optional()}),NB=K({experimental:tt(F(),tt(F(),hS()).describe("Experimental features keyed by identifier.")).optional().describe("Experimental features keyed by identifier."),openLinks:K({}).optional().describe("Host supports opening external URLs."),downloadFile:K({}).optional().describe("Host supports file downloads via ui/download-file."),serverTools:K({listChanged:et().optional().describe("Host supports tools/list_changed notifications.")}).optional().describe("Host can proxy tool calls to the MCP server."),serverResources:K({listChanged:et().optional().describe("Host supports resources/list_changed notifications.")}).optional().describe("Host can proxy resource reads to the MCP server."),logging:K({}).optional().describe("Host accepts log messages."),sandbox:K({permissions:zS.optional().describe("Permissions granted by the host (camera, microphone, geolocation)."),csp:FS.optional().describe("CSP domains approved by the host.")}).optional().describe("Sandbox configuration applied by the host."),updateModelContext:VA.optional().describe("Host accepts context updates (ui/update-model-context) to be included in the model's context for future turns."),message:VA.optional().describe("Host supports receiving content messages (ui/message) from the view."),sampling:K({tools:K({}).optional().describe("Host supports tool use via `tools` and `toolChoice` parameters.")}).optional().describe("Host supports LLM sampling (sampling/createMessage) from the view.\nMirrors the MCP `ClientCapabilities.sampling` shape so hosts can pass it through.")}),LB=K({experimental:tt(F(),tt(F(),hS()).describe("Experimental features keyed by identifier.")).optional().describe("Experimental features keyed by identifier."),tools:K({listChanged:et().optional().describe("App supports tools/list_changed notifications.")}).optional().describe("App exposes MCP-style tools that the host can call."),availableDisplayModes:re(af).optional().describe("Display modes the app supports.")}),DB=K({method:W("ui/notifications/initialized"),params:K({}).optional()});K({csp:FS.optional().describe("Content Security Policy configuration for UI resources."),permissions:zS.optional().describe("Sandbox permissions requested by the UI resource."),domain:F().optional().describe(`Dedicated origin for view sandbox. + +Useful when views need stable, dedicated origins for OAuth callbacks, CORS policies, or API key allowlists. + +**Host-dependent:** The format and validation rules for this field are determined by each host. Servers MUST consult host-specific documentation for the expected domain format. Common patterns include: +- Hash-based subdomains (e.g., \`{hash}.claudemcpcontent.com\`) +- URL-derived subdomains (e.g., \`www-example-com.oaiusercontent.com\`) + +If omitted, host uses default sandbox origin (typically per-conversation).`),prefersBorder:et().optional().describe(`Visual boundary preference - true if view prefers a visible border. + +Boolean requesting whether a visible border and background is provided by the host. Specifying an explicit value for this is recommended because hosts' defaults may vary. + +- \`true\`: request visible border + background +- \`false\`: request no visible border + background +- omitted: host decides border`)});var WA=K({method:W("ui/request-display-mode"),params:K({mode:af.describe("The display mode being requested.")})});K({mode:af.describe("The display mode that was actually set. May differ from requested if not supported.")}).passthrough();var jB=Ye([W("model"),W("app")]).describe("Tool visibility scope - who can access the tool.");K({resourceUri:F().optional(),visibility:re(jB).optional().describe(`Who can access this tool. Default: ["model", "app"] +- "model": Tool visible to and callable by the agent +- "app": Tool callable by the app from this server only`),csp:ab().optional(),permissions:ab().optional()});K({mimeTypes:re(F()).optional().describe('Array of supported MIME types for UI resources.\nMust include `"text/html;profile=mcp-app"` for MCP Apps support.')});var FB=K({method:W("ui/download-file"),params:K({contents:re(Ye([nT,sT])).describe("Resource contents to download — embedded (inline data) or linked (host fetches). Uses standard MCP resource types.")})}),zB=K({method:W("ui/message"),params:K({role:W("user").describe('Message role, currently only "user" is supported.'),content:re(Kp).describe("Message content blocks (text, image, etc.).")})});K({method:W("ui/notifications/sandbox-resource-ready"),params:K({html:F().describe("HTML content to load into the inner iframe."),sandbox:F().optional().describe("Optional override for the inner iframe's sandbox attribute."),csp:FS.optional().describe("CSP configuration from resource metadata."),permissions:zS.optional().describe("Sandbox permissions from resource metadata.")})});K({method:W("ui/notifications/tool-result"),params:lc.describe("Standard MCP tool execution result.")});var yT=K({toolInfo:K({id:Bp.optional().describe("JSON-RPC id of the tools/call request."),tool:OS.describe("Tool definition including name, inputSchema, etc.")}).optional().describe("Metadata of the tool call that instantiated this App."),theme:kB.optional().describe("Current color theme preference."),styles:MB.optional().describe("Style configuration for theming the app."),displayMode:af.optional().describe("How the UI is currently displayed."),availableDisplayModes:re(af).optional().describe("Display modes the host supports."),containerDimensions:Ye([K({height:je().describe("Fixed container height in pixels.")}),K({maxHeight:Ye([je(),ob()]).optional().describe("Maximum container height in pixels.")})]).and(Ye([K({width:je().describe("Fixed container width in pixels.")}),K({maxWidth:Ye([je(),ob()]).optional().describe("Maximum container width in pixels.")})])).optional().describe(`Container dimensions. Represents the dimensions of the iframe or other +container holding the app. Specify either width or maxWidth, and either height or maxHeight.`),locale:F().optional().describe("User's language and region preference in BCP 47 format."),timeZone:F().optional().describe("User's timezone in IANA format."),userAgent:F().optional().describe("Host application identifier."),platform:Ye([W("web"),W("desktop"),W("mobile")]).optional().describe("Platform type for responsive design decisions."),deviceCapabilities:K({touch:et().optional().describe("Whether the device supports touch input."),hover:et().optional().describe("Whether the device supports hover interactions.")}).optional().describe("Device input capabilities."),safeAreaInsets:K({top:je().describe("Top safe area inset in pixels."),right:je().describe("Right safe area inset in pixels."),bottom:je().describe("Bottom safe area inset in pixels."),left:je().describe("Left safe area inset in pixels.")}).optional().describe("Mobile safe area boundaries in pixels.")}).passthrough();K({method:W("ui/notifications/host-context-changed"),params:yT.describe("Partial context update containing only changed fields.")});var HB=K({method:W("ui/update-model-context"),params:K({content:re(Kp).optional().describe("Context content blocks (text, image, etc.)."),structuredContent:tt(F(),St().describe("Structured content for machine-readable context data.")).optional().describe("Structured content for machine-readable context data.")})}),BB=K({method:W("ui/initialize"),params:K({appInfo:b0.describe("App identification (name and version)."),appCapabilities:LB.describe("Features and capabilities this app provides."),protocolVersion:F().describe("Protocol version this app supports.")})});K({protocolVersion:F().describe('Negotiated protocol version string (e.g., "2025-11-21").'),hostInfo:b0.describe("Host application identification and version."),hostCapabilities:NB.describe("Features and capabilities provided by the host."),hostContext:yT.describe("Rich context about the host environment.")}).passthrough();class UB{constructor(e=window.parent,t){oe(this,"eventTarget");oe(this,"eventSource");oe(this,"messageListener");oe(this,"onclose");oe(this,"onerror");oe(this,"onmessage");oe(this,"sessionId");oe(this,"setProtocolVersion");this.eventTarget=e,this.eventSource=t,this.messageListener=s=>{var r,o,a;if(t&&s.source!==this.eventSource){console.debug("Ignoring message from unknown source",s);return}let i=og.safeParse(s.data);i.success?(console.debug("Parsed message",i.data),(r=this.onmessage)==null||r.call(this,i.data)):((o=s.data)==null?void 0:o.jsonrpc)!=="2.0"?console.debug("Ignoring non-JSON-RPC message",i.error.message,s):(console.error("Failed to parse message",i.error.message,s),(a=this.onerror)==null||a.call(this,Error("Invalid JSON-RPC message received: "+i.error.message)))}}async start(){window.addEventListener("message",this.messageListener)}async send(e,t){e.method!==AB&&console.debug("Sending message",e),this.eventTarget.postMessage(e,"*")}async close(){var e;window.removeEventListener("message",this.messageListener),(e=this.onclose)==null||e.call(this)}}var qB=[gT];class VB extends xB{constructor(t,s,i,r){super(r);oe(this,"_client");oe(this,"_hostInfo");oe(this,"_capabilities");oe(this,"_appCapabilities");oe(this,"_hostContext",{});oe(this,"_appInfo");oe(this,"_initializedReceived",!1);oe(this,"_baseReplaceRequestHandler",this.replaceRequestHandler);oe(this,"replaceRequestHandler",(t,s)=>{this._baseReplaceRequestHandler(t,(i,r)=>(this._initializedReceived||console.warn(`[ext-apps] AppBridge received '${i.method}' before ui/notifications/initialized. The View is calling host methods before completing the handshake; it should await app.connect() first.`),s(i,r)))});oe(this,"eventSchemas",{sizechange:PB,sandboxready:TB,initialized:DB,requestteardown:OB,loggingmessage:aT});oe(this,"onping");oe(this,"_onmessage");oe(this,"_onopenlink");oe(this,"_ondownloadfile");oe(this,"_onrequestdisplaymode");oe(this,"_onupdatemodelcontext");oe(this,"_oncalltool");oe(this,"_onlistresources");oe(this,"_onlistresourcetemplates");oe(this,"_onreadresource");oe(this,"_onlistprompts");oe(this,"sendResourceTeardown",this.teardownResource);this._client=t,this._hostInfo=s,this._capabilities=i,this.addEventListener("initialized",()=>{this._initializedReceived=!0}),this._hostContext=(r==null?void 0:r.hostContext)||{},this.setRequestHandler(BB,o=>this._oninitialize(o)),this.setRequestHandler(w0,(o,a)=>{var l;return(l=this.onping)==null||l.call(this,o.params,a),{}}),this.replaceRequestHandler(WA,o=>({mode:this._hostContext.displayMode??"inline"}))}getAppCapabilities(){return this._appCapabilities}getAppVersion(){return this._appInfo}get onsizechange(){return this.getEventHandler("sizechange")}set onsizechange(t){this.setEventHandler("sizechange",t)}get onsandboxready(){return this.getEventHandler("sandboxready")}set onsandboxready(t){this.setEventHandler("sandboxready",t)}get oninitialized(){return this.getEventHandler("initialized")}set oninitialized(t){this.setEventHandler("initialized",t)}get onmessage(){return this._onmessage}set onmessage(t){this.warnIfRequestHandlerReplaced("onmessage",this._onmessage,t),this._onmessage=t,this.replaceRequestHandler(zB,async(s,i)=>{if(!this._onmessage)throw Error("No onmessage handler set");return this._onmessage(s.params,i)})}get onopenlink(){return this._onopenlink}set onopenlink(t){this.warnIfRequestHandlerReplaced("onopenlink",this._onopenlink,t),this._onopenlink=t,this.replaceRequestHandler($B,async(s,i)=>{if(!this._onopenlink)throw Error("No onopenlink handler set");return this._onopenlink(s.params,i)})}get ondownloadfile(){return this._ondownloadfile}set ondownloadfile(t){this.warnIfRequestHandlerReplaced("ondownloadfile",this._ondownloadfile,t),this._ondownloadfile=t,this.replaceRequestHandler(FB,async(s,i)=>{if(!this._ondownloadfile)throw Error("No ondownloadfile handler set");return this._ondownloadfile(s.params,i)})}get onrequestteardown(){return this.getEventHandler("requestteardown")}set onrequestteardown(t){this.setEventHandler("requestteardown",t)}get onrequestdisplaymode(){return this._onrequestdisplaymode}set onrequestdisplaymode(t){this.warnIfRequestHandlerReplaced("onrequestdisplaymode",this._onrequestdisplaymode,t),this._onrequestdisplaymode=t,this.replaceRequestHandler(WA,async(s,i)=>{if(!this._onrequestdisplaymode)throw Error("No onrequestdisplaymode handler set");return this._onrequestdisplaymode(s.params,i)})}get onloggingmessage(){return this.getEventHandler("loggingmessage")}set onloggingmessage(t){this.setEventHandler("loggingmessage",t)}get onupdatemodelcontext(){return this._onupdatemodelcontext}set onupdatemodelcontext(t){this.warnIfRequestHandlerReplaced("onupdatemodelcontext",this._onupdatemodelcontext,t),this._onupdatemodelcontext=t,this.replaceRequestHandler(HB,async(s,i)=>{if(!this._onupdatemodelcontext)throw Error("No onupdatemodelcontext handler set");return this._onupdatemodelcontext(s.params,i)})}get oncalltool(){return this._oncalltool}set oncalltool(t){this.warnIfRequestHandlerReplaced("oncalltool",this._oncalltool,t),this._oncalltool=t,this.replaceRequestHandler(rT,async(s,i)=>{if(!this._oncalltool)throw Error("No oncalltool handler set");return this._oncalltool(s.params,i)})}set oncreatesamplingmessage(t){this.setRequestHandler(DS,async(s,i)=>t(s.params,i))}sendToolListChanged(t={}){return this.notification({method:"notifications/tools/list_changed",params:t})}get onlistresources(){return this._onlistresources}set onlistresources(t){this.warnIfRequestHandlerReplaced("onlistresources",this._onlistresources,t),this._onlistresources=t,this.replaceRequestHandler(J$,async(s,i)=>{if(!this._onlistresources)throw Error("No onlistresources handler set");return this._onlistresources(s.params,i)})}get onlistresourcetemplates(){return this._onlistresourcetemplates}set onlistresourcetemplates(t){this.warnIfRequestHandlerReplaced("onlistresourcetemplates",this._onlistresourcetemplates,t),this._onlistresourcetemplates=t,this.replaceRequestHandler(Q$,async(s,i)=>{if(!this._onlistresourcetemplates)throw Error("No onlistresourcetemplates handler set");return this._onlistresourcetemplates(s.params,i)})}get onreadresource(){return this._onreadresource}set onreadresource(t){this.warnIfRequestHandlerReplaced("onreadresource",this._onreadresource,t),this._onreadresource=t,this.replaceRequestHandler(eT,async(s,i)=>{if(!this._onreadresource)throw Error("No onreadresource handler set");return this._onreadresource(s.params,i)})}sendResourceListChanged(t={}){return this.notification({method:"notifications/resources/list_changed",params:t})}get onlistprompts(){return this._onlistprompts}set onlistprompts(t){this.warnIfRequestHandlerReplaced("onlistprompts",this._onlistprompts,t),this._onlistprompts=t,this.replaceRequestHandler(tT,async(s,i)=>{if(!this._onlistprompts)throw Error("No onlistprompts handler set");return this._onlistprompts(s.params,i)})}sendPromptListChanged(t={}){return this.notification({method:"notifications/prompts/list_changed",params:t})}assertCapabilityForMethod(t){}assertRequestHandlerCapability(t){}assertNotificationCapability(t){}assertTaskCapability(t){throw Error("Tasks are not supported in MCP Apps")}assertTaskHandlerCapability(t){throw Error("Task handlers are not supported in MCP Apps")}getCapabilities(){return this._capabilities}async _oninitialize(t){let s=t.params.protocolVersion;return this._appInfo!==void 0&&console.warn("[ext-apps] AppBridge received a second ui/initialize. The View may be double-mounting (e.g. React StrictMode in dev) without closing the previous App instance. Responding normally; the latest appInfo/appCapabilities replace the previous values."),this._appCapabilities=t.params.appCapabilities,this._appInfo=t.params.appInfo,{protocolVersion:qB.includes(s)?s:gT,hostCapabilities:this.getCapabilities(),hostInfo:this._hostInfo,hostContext:this._hostContext}}setHostContext(t){let s={},i=!1;for(let r of Object.keys(t)){let o=this._hostContext[r],a=t[r];WB(o,a)||(s[r]=a,i=!0)}i&&(this._hostContext=t,this.sendHostContextChange(s))}sendHostContextChange(t){return this.notification({method:"ui/notifications/host-context-changed",params:t})}sendToolInput(t){return this.notification({method:"ui/notifications/tool-input",params:t})}sendToolInputPartial(t){return this.notification({method:"ui/notifications/tool-input-partial",params:t})}sendToolResult(t){return this.notification({method:"ui/notifications/tool-result",params:t})}sendToolCancelled(t){return this.notification({method:"ui/notifications/tool-cancelled",params:t})}sendSandboxResourceReady(t){return this.notification({method:"ui/notifications/sandbox-resource-ready",params:t})}teardownResource(t,s){return this.request({method:"ui/resource-teardown",params:t},IB,s)}callTool(t,s){return this.request({method:"tools/call",params:t},lc,s)}listTools(t,s){return this.request({method:"tools/list",params:t},NS,s)}async connect(t){if(this.transport)throw Error("AppBridge is already connected. Call close() before connecting again.");if(this._initializedReceived=!1,this._client){let s=this._client.getServerCapabilities();if(!s)throw Error("Client server capabilities not available");s.tools&&(this.oncalltool=async(i,r)=>this._client.request({method:"tools/call",params:i},lc,{signal:r.signal}),s.tools.listChanged&&this._client.setNotificationHandler(LS,i=>this.sendToolListChanged(i.params))),s.resources&&(this.onlistresources=async(i,r)=>this._client.request({method:"resources/list",params:i},AS,{signal:r.signal}),this.onlistresourcetemplates=async(i,r)=>this._client.request({method:"resources/templates/list",params:i},kS,{signal:r.signal}),this.onreadresource=async(i,r)=>this._client.request({method:"resources/read",params:i},CS,{signal:r.signal}),s.resources.listChanged&&this._client.setNotificationHandler($S,i=>this.sendResourceListChanged(i.params))),s.prompts&&(this.onlistprompts=async(i,r)=>this._client.request({method:"prompts/list",params:i},TS,{signal:r.signal}),s.prompts.listChanged&&this._client.setNotificationHandler(IS,i=>this.sendPromptListChanged(i.params)))}return super.connect(t)}}function WB(n,e){return JSON.stringify(n)===JSON.stringify(e)}const GB={x:0,y:0,width:1024,height:768},ub=28,KB=12,ZB=.9;function va(n){return typeof n=="number"&&Number.isFinite(n)?n:void 0}function vT(n){if(!(!n||typeof n!="object"||Array.isArray(n)))return n}function db(n){if(Array.isArray(n))return n.map(db);const e=vT(n);return e?Object.fromEntries(Object.entries(e).map(([t,s])=>[t,(t==="text"||t==="originalText")&&typeof s=="string"?s.replace(/\\r\\n|\\n|\\r/gu,` +`):db(s)])):n}function XB(n){return n.type==="text"&&typeof(n.text??n.originalText)=="string"}function bT(n){const e=String(n.text??n.originalText??""),t=va(n.fontSize)??20,s=e.length*t*ZB,i=va(n.width);return Math.max(i&&i>0?i:0,s)}function YB(n){for(const e of n){if(e.type!=="cameraUpdate")continue;const t=va(e.width),s=va(e.height);if(!(!t||t<=0||!s||s<=0))return{x:va(e.x)??0,y:va(e.y)??0,width:t,height:s}}return GB}function JB(n,e){const t=va(n.x);if(t===void 0)return!1;const s=bT(n),i=e.x+ub,r=e.x+e.width-ub;return tr+1}function QB(n,e){const t={...n},s=va(t.fontSize)??20;let i=bT(t);const r=Math.max(1,e.width-ub*2);if(i>r){const o=r/i;t.fontSize=Math.max(KB,s*o),typeof t.height=="number"&&(t.height*=Number(t.fontSize)/s),i=Math.min(r,i*(Number(t.fontSize)/s))}return t.width=i,t.autoResize=!1,t.textAlign="left",t.x=e.x+(e.width-i)/2,t}function eU(n){const t=db(n).map(vT);if(t.some(r=>r===void 0))return n;const s=t,i=YB(s);return s.map(r=>!XB(r)||!JB(r,i)?r:QB(r,i))}var fb={exports:{}},wT={},Yi={},bu={},Zp={},Ke={},lf={};(function(n){Object.defineProperty(n,"__esModule",{value:!0}),n.regexpCode=n.getEsmExportName=n.getProperty=n.safeStringify=n.stringify=n.strConcat=n.addCodeArg=n.str=n._=n.nil=n._Code=n.Name=n.IDENTIFIER=n._CodeOrName=void 0;class e{}n._CodeOrName=e,n.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;class t extends e{constructor(b){if(super(),!n.IDENTIFIER.test(b))throw new Error("CodeGen: name must be a valid identifier");this.str=b}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}}n.Name=t;class s extends e{constructor(b){super(),this._items=typeof b=="string"?[b]:b}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;const b=this._items[0];return b===""||b==='""'}get str(){var b;return(b=this._str)!==null&&b!==void 0?b:this._str=this._items.reduce((_,x)=>`${_}${x}`,"")}get names(){var b;return(b=this._names)!==null&&b!==void 0?b:this._names=this._items.reduce((_,x)=>(x instanceof t&&(_[x.str]=(_[x.str]||0)+1),_),{})}}n._Code=s,n.nil=new s("");function i(g,...b){const _=[g[0]];let x=0;for(;x{if(u.scopePath===void 0)throw new Error(`CodeGen: name "${u}" has no value`);return(0,e._)`${c}${u.scopePath}`})}scopeCode(c=this._values,h,u){return this._reduceValues(c,d=>{if(d.value===void 0)throw new Error(`CodeGen: name "${d}" has no value`);return d.value.code},h,u)}_reduceValues(c,h,u={},d){let p=e.nil;for(const m in c){const y=c[m];if(!y)continue;const v=u[m]=u[m]||new Map;y.forEach(g=>{if(v.has(g))return;v.set(g,s.Started);let b=h(g);if(b){const _=this.opts.es5?n.varKinds.var:n.varKinds.const;p=(0,e._)`${p}${_} ${g} = ${b};${this.opts._n}`}else if(b=d==null?void 0:d(g))p=(0,e._)`${p}${b}${this.opts._n}`;else throw new t(g);v.set(g,s.Completed)})}return p}}n.ValueScope=a})(pb);(function(n){Object.defineProperty(n,"__esModule",{value:!0}),n.or=n.and=n.not=n.CodeGen=n.operators=n.varKinds=n.ValueScopeName=n.ValueScope=n.Scope=n.Name=n.regexpCode=n.stringify=n.getProperty=n.nil=n.strConcat=n.str=n._=void 0;const e=lf,t=pb;var s=lf;Object.defineProperty(n,"_",{enumerable:!0,get:function(){return s._}}),Object.defineProperty(n,"str",{enumerable:!0,get:function(){return s.str}}),Object.defineProperty(n,"strConcat",{enumerable:!0,get:function(){return s.strConcat}}),Object.defineProperty(n,"nil",{enumerable:!0,get:function(){return s.nil}}),Object.defineProperty(n,"getProperty",{enumerable:!0,get:function(){return s.getProperty}}),Object.defineProperty(n,"stringify",{enumerable:!0,get:function(){return s.stringify}}),Object.defineProperty(n,"regexpCode",{enumerable:!0,get:function(){return s.regexpCode}}),Object.defineProperty(n,"Name",{enumerable:!0,get:function(){return s.Name}});var i=pb;Object.defineProperty(n,"Scope",{enumerable:!0,get:function(){return i.Scope}}),Object.defineProperty(n,"ValueScope",{enumerable:!0,get:function(){return i.ValueScope}}),Object.defineProperty(n,"ValueScopeName",{enumerable:!0,get:function(){return i.ValueScopeName}}),Object.defineProperty(n,"varKinds",{enumerable:!0,get:function(){return i.varKinds}}),n.operators={GT:new e._Code(">"),GTE:new e._Code(">="),LT:new e._Code("<"),LTE:new e._Code("<="),EQ:new e._Code("==="),NEQ:new e._Code("!=="),NOT:new e._Code("!"),OR:new e._Code("||"),AND:new e._Code("&&"),ADD:new e._Code("+")};class r{optimizeNodes(){return this}optimizeNames(w,k){return this}}class o extends r{constructor(w,k,N){super(),this.varKind=w,this.name=k,this.rhs=N}render({es5:w,_n:k}){const N=w?t.varKinds.var:this.varKind,G=this.rhs===void 0?"":` = ${this.rhs}`;return`${N} ${this.name}${G};`+k}optimizeNames(w,k){if(w[this.name.str])return this.rhs&&(this.rhs=D(this.rhs,w,k)),this}get names(){return this.rhs instanceof e._CodeOrName?this.rhs.names:{}}}class a extends r{constructor(w,k,N){super(),this.lhs=w,this.rhs=k,this.sideEffects=N}render({_n:w}){return`${this.lhs} = ${this.rhs};`+w}optimizeNames(w,k){if(!(this.lhs instanceof e.Name&&!w[this.lhs.str]&&!this.sideEffects))return this.rhs=D(this.rhs,w,k),this}get names(){const w=this.lhs instanceof e.Name?{}:{...this.lhs.names};return H(w,this.rhs)}}class l extends a{constructor(w,k,N,G){super(w,N,G),this.op=k}render({_n:w}){return`${this.lhs} ${this.op}= ${this.rhs};`+w}}class c extends r{constructor(w){super(),this.label=w,this.names={}}render({_n:w}){return`${this.label}:`+w}}class h extends r{constructor(w){super(),this.label=w,this.names={}}render({_n:w}){return`break${this.label?` ${this.label}`:""};`+w}}class u extends r{constructor(w){super(),this.error=w}render({_n:w}){return`throw ${this.error};`+w}get names(){return this.error.names}}class d extends r{constructor(w){super(),this.code=w}render({_n:w}){return`${this.code};`+w}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(w,k){return this.code=D(this.code,w,k),this}get names(){return this.code instanceof e._CodeOrName?this.code.names:{}}}class p extends r{constructor(w=[]){super(),this.nodes=w}render(w){return this.nodes.reduce((k,N)=>k+N.render(w),"")}optimizeNodes(){const{nodes:w}=this;let k=w.length;for(;k--;){const N=w[k].optimizeNodes();Array.isArray(N)?w.splice(k,1,...N):N?w[k]=N:w.splice(k,1)}return w.length>0?this:void 0}optimizeNames(w,k){const{nodes:N}=this;let G=N.length;for(;G--;){const Z=N[G];Z.optimizeNames(w,k)||(X(w,Z.names),N.splice(G,1))}return N.length>0?this:void 0}get names(){return this.nodes.reduce((w,k)=>B(w,k.names),{})}}class m extends p{render(w){return"{"+w._n+super.render(w)+"}"+w._n}}class y extends p{}class v extends m{}v.kind="else";class g extends m{constructor(w,k){super(k),this.condition=w}render(w){let k=`if(${this.condition})`+super.render(w);return this.else&&(k+="else "+this.else.render(w)),k}optimizeNodes(){super.optimizeNodes();const w=this.condition;if(w===!0)return this.nodes;let k=this.else;if(k){const N=k.optimizeNodes();k=this.else=Array.isArray(N)?new v(N):N}if(k)return w===!1?k instanceof g?k:k.nodes:this.nodes.length?this:new g(te(w),k instanceof g?[k]:k.nodes);if(!(w===!1||!this.nodes.length))return this}optimizeNames(w,k){var N;if(this.else=(N=this.else)===null||N===void 0?void 0:N.optimizeNames(w,k),!!(super.optimizeNames(w,k)||this.else))return this.condition=D(this.condition,w,k),this}get names(){const w=super.names;return H(w,this.condition),this.else&&B(w,this.else.names),w}}g.kind="if";class b extends m{}b.kind="for";class _ extends b{constructor(w){super(),this.iteration=w}render(w){return`for(${this.iteration})`+super.render(w)}optimizeNames(w,k){if(super.optimizeNames(w,k))return this.iteration=D(this.iteration,w,k),this}get names(){return B(super.names,this.iteration.names)}}class x extends b{constructor(w,k,N,G){super(),this.varKind=w,this.name=k,this.from=N,this.to=G}render(w){const k=w.es5?t.varKinds.var:this.varKind,{name:N,from:G,to:Z}=this;return`for(${k} ${N}=${G}; ${N}<${Z}; ${N}++)`+super.render(w)}get names(){const w=H(super.names,this.from);return H(w,this.to)}}class A extends b{constructor(w,k,N,G){super(),this.loop=w,this.varKind=k,this.name=N,this.iterable=G}render(w){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(w)}optimizeNames(w,k){if(super.optimizeNames(w,k))return this.iterable=D(this.iterable,w,k),this}get names(){return B(super.names,this.iterable.names)}}class C extends m{constructor(w,k,N){super(),this.name=w,this.args=k,this.async=N}render(w){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(w)}}C.kind="func";class $ extends p{render(w){return"return "+super.render(w)}}$.kind="return";class I extends m{render(w){let k="try"+super.render(w);return this.catch&&(k+=this.catch.render(w)),this.finally&&(k+=this.finally.render(w)),k}optimizeNodes(){var w,k;return super.optimizeNodes(),(w=this.catch)===null||w===void 0||w.optimizeNodes(),(k=this.finally)===null||k===void 0||k.optimizeNodes(),this}optimizeNames(w,k){var N,G;return super.optimizeNames(w,k),(N=this.catch)===null||N===void 0||N.optimizeNames(w,k),(G=this.finally)===null||G===void 0||G.optimizeNames(w,k),this}get names(){const w=super.names;return this.catch&&B(w,this.catch.names),this.finally&&B(w,this.finally.names),w}}class j extends m{constructor(w){super(),this.error=w}render(w){return`catch(${this.error})`+super.render(w)}}j.kind="catch";class q extends m{render(w){return"finally"+super.render(w)}}q.kind="finally";class L{constructor(w,k={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...k,_n:k.lines?` +`:""},this._extScope=w,this._scope=new t.Scope({parent:w}),this._nodes=[new y]}toString(){return this._root.render(this.opts)}name(w){return this._scope.name(w)}scopeName(w){return this._extScope.name(w)}scopeValue(w,k){const N=this._extScope.value(w,k);return(this._values[N.prefix]||(this._values[N.prefix]=new Set)).add(N),N}getScopeValue(w,k){return this._extScope.getValue(w,k)}scopeRefs(w){return this._extScope.scopeRefs(w,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(w,k,N,G){const Z=this._scope.toName(k);return N!==void 0&&G&&(this._constants[Z.str]=N),this._leafNode(new o(w,Z,N)),Z}const(w,k,N){return this._def(t.varKinds.const,w,k,N)}let(w,k,N){return this._def(t.varKinds.let,w,k,N)}var(w,k,N){return this._def(t.varKinds.var,w,k,N)}assign(w,k,N){return this._leafNode(new a(w,k,N))}add(w,k){return this._leafNode(new l(w,n.operators.ADD,k))}code(w){return typeof w=="function"?w():w!==e.nil&&this._leafNode(new d(w)),this}object(...w){const k=["{"];for(const[N,G]of w)k.length>1&&k.push(","),k.push(N),(N!==G||this.opts.es5)&&(k.push(":"),(0,e.addCodeArg)(k,G));return k.push("}"),new e._Code(k)}if(w,k,N){if(this._blockNode(new g(w)),k&&N)this.code(k).else().code(N).endIf();else if(k)this.code(k).endIf();else if(N)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(w){return this._elseNode(new g(w))}else(){return this._elseNode(new v)}endIf(){return this._endBlockNode(g,v)}_for(w,k){return this._blockNode(w),k&&this.code(k).endFor(),this}for(w,k){return this._for(new _(w),k)}forRange(w,k,N,G,Z=this.opts.es5?t.varKinds.var:t.varKinds.let){const ae=this._scope.toName(w);return this._for(new x(Z,ae,k,N),()=>G(ae))}forOf(w,k,N,G=t.varKinds.const){const Z=this._scope.toName(w);if(this.opts.es5){const ae=k instanceof e.Name?k:this.var("_arr",k);return this.forRange("_i",0,(0,e._)`${ae}.length`,ie=>{this.var(Z,(0,e._)`${ae}[${ie}]`),N(Z)})}return this._for(new A("of",G,Z,k),()=>N(Z))}forIn(w,k,N,G=this.opts.es5?t.varKinds.var:t.varKinds.const){if(this.opts.ownProperties)return this.forOf(w,(0,e._)`Object.keys(${k})`,N);const Z=this._scope.toName(w);return this._for(new A("in",G,Z,k),()=>N(Z))}endFor(){return this._endBlockNode(b)}label(w){return this._leafNode(new c(w))}break(w){return this._leafNode(new h(w))}return(w){const k=new $;if(this._blockNode(k),this.code(w),k.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode($)}try(w,k,N){if(!k&&!N)throw new Error('CodeGen: "try" without "catch" and "finally"');const G=new I;if(this._blockNode(G),this.code(w),k){const Z=this.name("e");this._currNode=G.catch=new j(Z),k(Z)}return N&&(this._currNode=G.finally=new q,this.code(N)),this._endBlockNode(j,q)}throw(w){return this._leafNode(new u(w))}block(w,k){return this._blockStarts.push(this._nodes.length),w&&this.code(w).endBlock(k),this}endBlock(w){const k=this._blockStarts.pop();if(k===void 0)throw new Error("CodeGen: not in self-balancing block");const N=this._nodes.length-k;if(N<0||w!==void 0&&N!==w)throw new Error(`CodeGen: wrong number of nodes: ${N} vs ${w} expected`);return this._nodes.length=k,this}func(w,k=e.nil,N,G){return this._blockNode(new C(w,k,N)),G&&this.code(G).endFunc(),this}endFunc(){return this._endBlockNode(C)}optimize(w=1){for(;w-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(w){return this._currNode.nodes.push(w),this}_blockNode(w){this._currNode.nodes.push(w),this._nodes.push(w)}_endBlockNode(w,k){const N=this._currNode;if(N instanceof w||k&&N instanceof k)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${k?`${w.kind}/${k.kind}`:w.kind}"`)}_elseNode(w){const k=this._currNode;if(!(k instanceof g))throw new Error('CodeGen: "else" without "if"');return this._currNode=k.else=w,this}get _root(){return this._nodes[0]}get _currNode(){const w=this._nodes;return w[w.length-1]}set _currNode(w){const k=this._nodes;k[k.length-1]=w}}n.CodeGen=L;function B(R,w){for(const k in w)R[k]=(R[k]||0)+(w[k]||0);return R}function H(R,w){return w instanceof e._CodeOrName?B(R,w.names):R}function D(R,w,k){if(R instanceof e.Name)return N(R);if(!G(R))return R;return new e._Code(R._items.reduce((Z,ae)=>(ae instanceof e.Name&&(ae=N(ae)),ae instanceof e._Code?Z.push(...ae._items):Z.push(ae),Z),[]));function N(Z){const ae=k[Z.str];return ae===void 0||w[Z.str]!==1?Z:(delete w[Z.str],ae)}function G(Z){return Z instanceof e._Code&&Z._items.some(ae=>ae instanceof e.Name&&w[ae.str]===1&&k[ae.str]!==void 0)}}function X(R,w){for(const k in w)R[k]=(R[k]||0)-(w[k]||0)}function te(R){return typeof R=="boolean"||typeof R=="number"||R===null?!R:(0,e._)`!${O(R)}`}n.not=te;const J=E(n.operators.AND);function Y(...R){return R.reduce(J)}n.and=Y;const ye=E(n.operators.OR);function z(...R){return R.reduce(ye)}n.or=z;function E(R){return(w,k)=>w===e.nil?k:k===e.nil?w:(0,e._)`${O(w)} ${R} ${O(k)}`}function O(R){return R instanceof e.Name?R:(0,e._)`(${R})`}})(Ke);var fe={};Object.defineProperty(fe,"__esModule",{value:!0});fe.checkStrictMode=fe.getErrorPath=fe.Type=fe.useFunc=fe.setEvaluated=fe.evaluatedPropsToName=fe.mergeEvaluated=fe.eachItem=fe.unescapeJsonPointer=fe.escapeJsonPointer=fe.escapeFragment=fe.unescapeFragment=fe.schemaRefOrVal=fe.schemaHasRulesButRef=fe.schemaHasRules=fe.checkUnknownRules=fe.alwaysValidSchema=fe.toHash=void 0;const vt=Ke,tU=lf;function nU(n){const e={};for(const t of n)e[t]=!0;return e}fe.toHash=nU;function sU(n,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(_T(n,e),!ST(e,n.self.RULES.all))}fe.alwaysValidSchema=sU;function _T(n,e=n.schema){const{opts:t,self:s}=n;if(!t.strictSchema||typeof e=="boolean")return;const i=s.RULES.keywords;for(const r in e)i[r]||kT(n,`unknown keyword: "${r}"`)}fe.checkUnknownRules=_T;function ST(n,e){if(typeof n=="boolean")return!n;for(const t in n)if(e[t])return!0;return!1}fe.schemaHasRules=ST;function iU(n,e){if(typeof n=="boolean")return!n;for(const t in n)if(t!=="$ref"&&e.all[t])return!0;return!1}fe.schemaHasRulesButRef=iU;function rU({topSchemaRef:n,schemaPath:e},t,s,i){if(!i){if(typeof t=="number"||typeof t=="boolean")return t;if(typeof t=="string")return(0,vt._)`${t}`}return(0,vt._)`${n}${e}${(0,vt.getProperty)(s)}`}fe.schemaRefOrVal=rU;function oU(n){return xT(decodeURIComponent(n))}fe.unescapeFragment=oU;function aU(n){return encodeURIComponent(HS(n))}fe.escapeFragment=aU;function HS(n){return typeof n=="number"?`${n}`:n.replace(/~/g,"~0").replace(/\//g,"~1")}fe.escapeJsonPointer=HS;function xT(n){return n.replace(/~1/g,"/").replace(/~0/g,"~")}fe.unescapeJsonPointer=xT;function lU(n,e){if(Array.isArray(n))for(const t of n)e(t);else e(n)}fe.eachItem=lU;function GA({mergeNames:n,mergeToName:e,mergeValues:t,resultToName:s}){return(i,r,o,a)=>{const l=o===void 0?r:o instanceof vt.Name?(r instanceof vt.Name?n(i,r,o):e(i,r,o),o):r instanceof vt.Name?(e(i,o,r),r):t(r,o);return a===vt.Name&&!(l instanceof vt.Name)?s(i,l):l}}fe.mergeEvaluated={props:GA({mergeNames:(n,e,t)=>n.if((0,vt._)`${t} !== true && ${e} !== undefined`,()=>{n.if((0,vt._)`${e} === true`,()=>n.assign(t,!0),()=>n.assign(t,(0,vt._)`${t} || {}`).code((0,vt._)`Object.assign(${t}, ${e})`))}),mergeToName:(n,e,t)=>n.if((0,vt._)`${t} !== true`,()=>{e===!0?n.assign(t,!0):(n.assign(t,(0,vt._)`${t} || {}`),BS(n,t,e))}),mergeValues:(n,e)=>n===!0?!0:{...n,...e},resultToName:AT}),items:GA({mergeNames:(n,e,t)=>n.if((0,vt._)`${t} !== true && ${e} !== undefined`,()=>n.assign(t,(0,vt._)`${e} === true ? true : ${t} > ${e} ? ${t} : ${e}`)),mergeToName:(n,e,t)=>n.if((0,vt._)`${t} !== true`,()=>n.assign(t,e===!0?!0:(0,vt._)`${t} > ${e} ? ${t} : ${e}`)),mergeValues:(n,e)=>n===!0?!0:Math.max(n,e),resultToName:(n,e)=>n.var("items",e)})};function AT(n,e){if(e===!0)return n.var("props",!0);const t=n.var("props",(0,vt._)`{}`);return e!==void 0&&BS(n,t,e),t}fe.evaluatedPropsToName=AT;function BS(n,e,t){Object.keys(t).forEach(s=>n.assign((0,vt._)`${e}${(0,vt.getProperty)(s)}`,!0))}fe.setEvaluated=BS;const KA={};function cU(n,e){return n.scopeValue("func",{ref:e,code:KA[e.code]||(KA[e.code]=new tU._Code(e.code))})}fe.useFunc=cU;var mb;(function(n){n[n.Num=0]="Num",n[n.Str=1]="Str"})(mb||(fe.Type=mb={}));function hU(n,e,t){if(n instanceof vt.Name){const s=e===mb.Num;return t?s?(0,vt._)`"[" + ${n} + "]"`:(0,vt._)`"['" + ${n} + "']"`:s?(0,vt._)`"/" + ${n}`:(0,vt._)`"/" + ${n}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return t?(0,vt.getProperty)(n).toString():"/"+HS(n)}fe.getErrorPath=hU;function kT(n,e,t=n.opts.strictSchema){if(t){if(e=`strict mode: ${e}`,t===!0)throw new Error(e);n.self.logger.warn(e)}}fe.checkStrictMode=kT;var Dr={};Object.defineProperty(Dr,"__esModule",{value:!0});const Jn=Ke,uU={data:new Jn.Name("data"),valCxt:new Jn.Name("valCxt"),instancePath:new Jn.Name("instancePath"),parentData:new Jn.Name("parentData"),parentDataProperty:new Jn.Name("parentDataProperty"),rootData:new Jn.Name("rootData"),dynamicAnchors:new Jn.Name("dynamicAnchors"),vErrors:new Jn.Name("vErrors"),errors:new Jn.Name("errors"),this:new Jn.Name("this"),self:new Jn.Name("self"),scope:new Jn.Name("scope"),json:new Jn.Name("json"),jsonPos:new Jn.Name("jsonPos"),jsonLen:new Jn.Name("jsonLen"),jsonPart:new Jn.Name("jsonPart")};Dr.default=uU;(function(n){Object.defineProperty(n,"__esModule",{value:!0}),n.extendErrors=n.resetErrorsCount=n.reportExtraError=n.reportError=n.keyword$DataError=n.keywordError=void 0;const e=Ke,t=fe,s=Dr;n.keywordError={message:({keyword:v})=>(0,e.str)`must pass "${v}" keyword validation`},n.keyword$DataError={message:({keyword:v,schemaType:g})=>g?(0,e.str)`"${v}" keyword must be ${g} ($data)`:(0,e.str)`"${v}" keyword is invalid ($data)`};function i(v,g=n.keywordError,b,_){const{it:x}=v,{gen:A,compositeRule:C,allErrors:$}=x,I=u(v,g,b);_??(C||$)?l(A,I):c(x,(0,e._)`[${I}]`)}n.reportError=i;function r(v,g=n.keywordError,b){const{it:_}=v,{gen:x,compositeRule:A,allErrors:C}=_,$=u(v,g,b);l(x,$),A||C||c(_,s.default.vErrors)}n.reportExtraError=r;function o(v,g){v.assign(s.default.errors,g),v.if((0,e._)`${s.default.vErrors} !== null`,()=>v.if(g,()=>v.assign((0,e._)`${s.default.vErrors}.length`,g),()=>v.assign(s.default.vErrors,null)))}n.resetErrorsCount=o;function a({gen:v,keyword:g,schemaValue:b,data:_,errsCount:x,it:A}){if(x===void 0)throw new Error("ajv implementation error");const C=v.name("err");v.forRange("i",x,s.default.errors,$=>{v.const(C,(0,e._)`${s.default.vErrors}[${$}]`),v.if((0,e._)`${C}.instancePath === undefined`,()=>v.assign((0,e._)`${C}.instancePath`,(0,e.strConcat)(s.default.instancePath,A.errorPath))),v.assign((0,e._)`${C}.schemaPath`,(0,e.str)`${A.errSchemaPath}/${g}`),A.opts.verbose&&(v.assign((0,e._)`${C}.schema`,b),v.assign((0,e._)`${C}.data`,_))})}n.extendErrors=a;function l(v,g){const b=v.const("err",g);v.if((0,e._)`${s.default.vErrors} === null`,()=>v.assign(s.default.vErrors,(0,e._)`[${b}]`),(0,e._)`${s.default.vErrors}.push(${b})`),v.code((0,e._)`${s.default.errors}++`)}function c(v,g){const{gen:b,validateName:_,schemaEnv:x}=v;x.$async?b.throw((0,e._)`new ${v.ValidationError}(${g})`):(b.assign((0,e._)`${_}.errors`,g),b.return(!1))}const h={keyword:new e.Name("keyword"),schemaPath:new e.Name("schemaPath"),params:new e.Name("params"),propertyName:new e.Name("propertyName"),message:new e.Name("message"),schema:new e.Name("schema"),parentSchema:new e.Name("parentSchema")};function u(v,g,b){const{createErrors:_}=v.it;return _===!1?(0,e._)`{}`:d(v,g,b)}function d(v,g,b={}){const{gen:_,it:x}=v,A=[p(x,b),m(v,b)];return y(v,g,A),_.object(...A)}function p({errorPath:v},{instancePath:g}){const b=g?(0,e.str)`${v}${(0,t.getErrorPath)(g,t.Type.Str)}`:v;return[s.default.instancePath,(0,e.strConcat)(s.default.instancePath,b)]}function m({keyword:v,it:{errSchemaPath:g}},{schemaPath:b,parentSchema:_}){let x=_?g:(0,e.str)`${g}/${v}`;return b&&(x=(0,e.str)`${x}${(0,t.getErrorPath)(b,t.Type.Str)}`),[h.schemaPath,x]}function y(v,{params:g,message:b},_){const{keyword:x,data:A,schemaValue:C,it:$}=v,{opts:I,propertyName:j,topSchemaRef:q,schemaPath:L}=$;_.push([h.keyword,x],[h.params,typeof g=="function"?g(v):g||(0,e._)`{}`]),I.messages&&_.push([h.message,typeof b=="function"?b(v):b]),I.verbose&&_.push([h.schema,C],[h.parentSchema,(0,e._)`${q}${L}`],[s.default.data,A]),j&&_.push([h.propertyName,j])}})(Zp);Object.defineProperty(bu,"__esModule",{value:!0});bu.boolOrEmptySchema=bu.topBoolOrEmptySchema=void 0;const dU=Zp,fU=Ke,pU=Dr,mU={message:"boolean schema is false"};function gU(n){const{gen:e,schema:t,validateName:s}=n;t===!1?ET(n,!1):typeof t=="object"&&t.$async===!0?e.return(pU.default.data):(e.assign((0,fU._)`${s}.errors`,null),e.return(!0))}bu.topBoolOrEmptySchema=gU;function yU(n,e){const{gen:t,schema:s}=n;s===!1?(t.var(e,!1),ET(n)):t.var(e,!0)}bu.boolOrEmptySchema=yU;function ET(n,e){const{gen:t,data:s}=n,i={gen:t,keyword:"false schema",data:s,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:n};(0,dU.reportError)(i,mU,void 0,e)}var pn={},cc={};Object.defineProperty(cc,"__esModule",{value:!0});cc.getRules=cc.isJSONType=void 0;const vU=["string","number","integer","boolean","null","object","array"],bU=new Set(vU);function wU(n){return typeof n=="string"&&bU.has(n)}cc.isJSONType=wU;function _U(){const n={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...n,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},n.number,n.string,n.array,n.object],post:{rules:[]},all:{},keywords:{}}}cc.getRules=_U;var wo={};Object.defineProperty(wo,"__esModule",{value:!0});wo.shouldUseRule=wo.shouldUseGroup=wo.schemaHasRulesForType=void 0;function SU({schema:n,self:e},t){const s=e.RULES.types[t];return s&&s!==!0&&CT(n,s)}wo.schemaHasRulesForType=SU;function CT(n,e){return e.rules.some(t=>$T(n,t))}wo.shouldUseGroup=CT;function $T(n,e){var t;return n[e.keyword]!==void 0||((t=e.definition.implements)===null||t===void 0?void 0:t.some(s=>n[s]!==void 0))}wo.shouldUseRule=$T;Object.defineProperty(pn,"__esModule",{value:!0});pn.reportTypeError=pn.checkDataTypes=pn.checkDataType=pn.coerceAndCheckDataType=pn.getJSONTypes=pn.getSchemaTypes=pn.DataType=void 0;const xU=cc,AU=wo,kU=Zp,Ne=Ke,TT=fe;var ah;(function(n){n[n.Correct=0]="Correct",n[n.Wrong=1]="Wrong"})(ah||(pn.DataType=ah={}));function EU(n){const e=PT(n.type);if(e.includes("null")){if(n.nullable===!1)throw new Error("type: null contradicts nullable: false")}else{if(!e.length&&n.nullable!==void 0)throw new Error('"nullable" cannot be used without "type"');n.nullable===!0&&e.push("null")}return e}pn.getSchemaTypes=EU;function PT(n){const e=Array.isArray(n)?n:n?[n]:[];if(e.every(xU.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}pn.getJSONTypes=PT;function CU(n,e){const{gen:t,data:s,opts:i}=n,r=$U(e,i.coerceTypes),o=e.length>0&&!(r.length===0&&e.length===1&&(0,AU.schemaHasRulesForType)(n,e[0]));if(o){const a=US(e,s,i.strictNumbers,ah.Wrong);t.if(a,()=>{r.length?TU(n,e,r):qS(n)})}return o}pn.coerceAndCheckDataType=CU;const RT=new Set(["string","number","integer","boolean","null"]);function $U(n,e){return e?n.filter(t=>RT.has(t)||e==="array"&&t==="array"):[]}function TU(n,e,t){const{gen:s,data:i,opts:r}=n,o=s.let("dataType",(0,Ne._)`typeof ${i}`),a=s.let("coerced",(0,Ne._)`undefined`);r.coerceTypes==="array"&&s.if((0,Ne._)`${o} == 'object' && Array.isArray(${i}) && ${i}.length == 1`,()=>s.assign(i,(0,Ne._)`${i}[0]`).assign(o,(0,Ne._)`typeof ${i}`).if(US(e,i,r.strictNumbers),()=>s.assign(a,i))),s.if((0,Ne._)`${a} !== undefined`);for(const c of t)(RT.has(c)||c==="array"&&r.coerceTypes==="array")&&l(c);s.else(),qS(n),s.endIf(),s.if((0,Ne._)`${a} !== undefined`,()=>{s.assign(i,a),PU(n,a)});function l(c){switch(c){case"string":s.elseIf((0,Ne._)`${o} == "number" || ${o} == "boolean"`).assign(a,(0,Ne._)`"" + ${i}`).elseIf((0,Ne._)`${i} === null`).assign(a,(0,Ne._)`""`);return;case"number":s.elseIf((0,Ne._)`${o} == "boolean" || ${i} === null + || (${o} == "string" && ${i} && ${i} == +${i})`).assign(a,(0,Ne._)`+${i}`);return;case"integer":s.elseIf((0,Ne._)`${o} === "boolean" || ${i} === null + || (${o} === "string" && ${i} && ${i} == +${i} && !(${i} % 1))`).assign(a,(0,Ne._)`+${i}`);return;case"boolean":s.elseIf((0,Ne._)`${i} === "false" || ${i} === 0 || ${i} === null`).assign(a,!1).elseIf((0,Ne._)`${i} === "true" || ${i} === 1`).assign(a,!0);return;case"null":s.elseIf((0,Ne._)`${i} === "" || ${i} === 0 || ${i} === false`),s.assign(a,null);return;case"array":s.elseIf((0,Ne._)`${o} === "string" || ${o} === "number" + || ${o} === "boolean" || ${i} === null`).assign(a,(0,Ne._)`[${i}]`)}}}function PU({gen:n,parentData:e,parentDataProperty:t},s){n.if((0,Ne._)`${e} !== undefined`,()=>n.assign((0,Ne._)`${e}[${t}]`,s))}function gb(n,e,t,s=ah.Correct){const i=s===ah.Correct?Ne.operators.EQ:Ne.operators.NEQ;let r;switch(n){case"null":return(0,Ne._)`${e} ${i} null`;case"array":r=(0,Ne._)`Array.isArray(${e})`;break;case"object":r=(0,Ne._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case"integer":r=o((0,Ne._)`!(${e} % 1) && !isNaN(${e})`);break;case"number":r=o();break;default:return(0,Ne._)`typeof ${e} ${i} ${n}`}return s===ah.Correct?r:(0,Ne.not)(r);function o(a=Ne.nil){return(0,Ne.and)((0,Ne._)`typeof ${e} == "number"`,a,t?(0,Ne._)`isFinite(${e})`:Ne.nil)}}pn.checkDataType=gb;function US(n,e,t,s){if(n.length===1)return gb(n[0],e,t,s);let i;const r=(0,TT.toHash)(n);if(r.array&&r.object){const o=(0,Ne._)`typeof ${e} != "object"`;i=r.null?o:(0,Ne._)`!${e} || ${o}`,delete r.null,delete r.array,delete r.object}else i=Ne.nil;r.number&&delete r.integer;for(const o in r)i=(0,Ne.and)(i,gb(o,e,t,s));return i}pn.checkDataTypes=US;const RU={message:({schema:n})=>`must be ${n}`,params:({schema:n,schemaValue:e})=>typeof n=="string"?(0,Ne._)`{type: ${n}}`:(0,Ne._)`{type: ${e}}`};function qS(n){const e=MU(n);(0,kU.reportError)(e,RU)}pn.reportTypeError=qS;function MU(n){const{gen:e,data:t,schema:s}=n,i=(0,TT.schemaRefOrVal)(n,s,"type");return{gen:e,keyword:"type",data:t,schema:s.type,schemaCode:i,schemaValue:i,parentSchema:s,params:{},it:n}}var _0={};Object.defineProperty(_0,"__esModule",{value:!0});_0.assignDefaults=void 0;const Nc=Ke,IU=fe;function OU(n,e){const{properties:t,items:s}=n.schema;if(e==="object"&&t)for(const i in t)ZA(n,i,t[i].default);else e==="array"&&Array.isArray(s)&&s.forEach((i,r)=>ZA(n,r,i.default))}_0.assignDefaults=OU;function ZA(n,e,t){const{gen:s,compositeRule:i,data:r,opts:o}=n;if(t===void 0)return;const a=(0,Nc._)`${r}${(0,Nc.getProperty)(e)}`;if(i){(0,IU.checkStrictMode)(n,`default is ignored for: ${a}`);return}let l=(0,Nc._)`${a} === undefined`;o.useDefaults==="empty"&&(l=(0,Nc._)`${l} || ${a} === null || ${a} === ""`),s.if(l,(0,Nc._)`${a} = ${(0,Nc.stringify)(t)}`)}var Tr={},We={};Object.defineProperty(We,"__esModule",{value:!0});We.validateUnion=We.validateArray=We.usePattern=We.callValidateCode=We.schemaProperties=We.allSchemaProperties=We.noPropertyInData=We.propertyInData=We.isOwnProperty=We.hasPropFunc=We.reportMissingProp=We.checkMissingProp=We.checkReportMissingProp=void 0;const Ct=Ke,VS=fe,Io=Dr,NU=fe;function LU(n,e){const{gen:t,data:s,it:i}=n;t.if(GS(t,s,e,i.opts.ownProperties),()=>{n.setParams({missingProperty:(0,Ct._)`${e}`},!0),n.error()})}We.checkReportMissingProp=LU;function DU({gen:n,data:e,it:{opts:t}},s,i){return(0,Ct.or)(...s.map(r=>(0,Ct.and)(GS(n,e,r,t.ownProperties),(0,Ct._)`${i} = ${r}`)))}We.checkMissingProp=DU;function jU(n,e){n.setParams({missingProperty:e},!0),n.error()}We.reportMissingProp=jU;function MT(n){return n.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,Ct._)`Object.prototype.hasOwnProperty`})}We.hasPropFunc=MT;function WS(n,e,t){return(0,Ct._)`${MT(n)}.call(${e}, ${t})`}We.isOwnProperty=WS;function FU(n,e,t,s){const i=(0,Ct._)`${e}${(0,Ct.getProperty)(t)} !== undefined`;return s?(0,Ct._)`${i} && ${WS(n,e,t)}`:i}We.propertyInData=FU;function GS(n,e,t,s){const i=(0,Ct._)`${e}${(0,Ct.getProperty)(t)} === undefined`;return s?(0,Ct.or)(i,(0,Ct.not)(WS(n,e,t))):i}We.noPropertyInData=GS;function IT(n){return n?Object.keys(n).filter(e=>e!=="__proto__"):[]}We.allSchemaProperties=IT;function zU(n,e){return IT(e).filter(t=>!(0,VS.alwaysValidSchema)(n,e[t]))}We.schemaProperties=zU;function HU({schemaCode:n,data:e,it:{gen:t,topSchemaRef:s,schemaPath:i,errorPath:r},it:o},a,l,c){const h=c?(0,Ct._)`${n}, ${e}, ${s}${i}`:e,u=[[Io.default.instancePath,(0,Ct.strConcat)(Io.default.instancePath,r)],[Io.default.parentData,o.parentData],[Io.default.parentDataProperty,o.parentDataProperty],[Io.default.rootData,Io.default.rootData]];o.opts.dynamicRef&&u.push([Io.default.dynamicAnchors,Io.default.dynamicAnchors]);const d=(0,Ct._)`${h}, ${t.object(...u)}`;return l!==Ct.nil?(0,Ct._)`${a}.call(${l}, ${d})`:(0,Ct._)`${a}(${d})`}We.callValidateCode=HU;const BU=(0,Ct._)`new RegExp`;function UU({gen:n,it:{opts:e}},t){const s=e.unicodeRegExp?"u":"",{regExp:i}=e.code,r=i(t,s);return n.scopeValue("pattern",{key:r.toString(),ref:r,code:(0,Ct._)`${i.code==="new RegExp"?BU:(0,NU.useFunc)(n,i)}(${t}, ${s})`})}We.usePattern=UU;function qU(n){const{gen:e,data:t,keyword:s,it:i}=n,r=e.name("valid");if(i.allErrors){const a=e.let("valid",!0);return o(()=>e.assign(a,!1)),a}return e.var(r,!0),o(()=>e.break()),r;function o(a){const l=e.const("len",(0,Ct._)`${t}.length`);e.forRange("i",0,l,c=>{n.subschema({keyword:s,dataProp:c,dataPropType:VS.Type.Num},r),e.if((0,Ct.not)(r),a)})}}We.validateArray=qU;function VU(n){const{gen:e,schema:t,keyword:s,it:i}=n;if(!Array.isArray(t))throw new Error("ajv implementation error");if(t.some(l=>(0,VS.alwaysValidSchema)(i,l))&&!i.opts.unevaluated)return;const o=e.let("valid",!1),a=e.name("_valid");e.block(()=>t.forEach((l,c)=>{const h=n.subschema({keyword:s,schemaProp:c,compositeRule:!0},a);e.assign(o,(0,Ct._)`${o} || ${a}`),n.mergeValidEvaluated(h,a)||e.if((0,Ct.not)(o))})),n.result(o,()=>n.reset(),()=>n.error(!0))}We.validateUnion=VU;Object.defineProperty(Tr,"__esModule",{value:!0});Tr.validateKeywordUsage=Tr.validSchemaType=Tr.funcKeywordCode=Tr.macroKeywordCode=void 0;const ms=Ke,Qa=Dr,WU=We,GU=Zp;function KU(n,e){const{gen:t,keyword:s,schema:i,parentSchema:r,it:o}=n,a=e.macro.call(o.self,i,r,o),l=OT(t,s,a);o.opts.validateSchema!==!1&&o.self.validateSchema(a,!0);const c=t.name("valid");n.subschema({schema:a,schemaPath:ms.nil,errSchemaPath:`${o.errSchemaPath}/${s}`,topSchemaRef:l,compositeRule:!0},c),n.pass(c,()=>n.error(!0))}Tr.macroKeywordCode=KU;function ZU(n,e){var t;const{gen:s,keyword:i,schema:r,parentSchema:o,$data:a,it:l}=n;YU(l,e);const c=!a&&e.compile?e.compile.call(l.self,r,o,l):e.validate,h=OT(s,i,c),u=s.let("valid");n.block$data(u,d),n.ok((t=e.valid)!==null&&t!==void 0?t:u);function d(){if(e.errors===!1)y(),e.modifying&&XA(n),v(()=>n.error());else{const g=e.async?p():m();e.modifying&&XA(n),v(()=>XU(n,g))}}function p(){const g=s.let("ruleErrs",null);return s.try(()=>y((0,ms._)`await `),b=>s.assign(u,!1).if((0,ms._)`${b} instanceof ${l.ValidationError}`,()=>s.assign(g,(0,ms._)`${b}.errors`),()=>s.throw(b))),g}function m(){const g=(0,ms._)`${h}.errors`;return s.assign(g,null),y(ms.nil),g}function y(g=e.async?(0,ms._)`await `:ms.nil){const b=l.opts.passContext?Qa.default.this:Qa.default.self,_=!("compile"in e&&!a||e.schema===!1);s.assign(u,(0,ms._)`${g}${(0,WU.callValidateCode)(n,h,b,_)}`,e.modifying)}function v(g){var b;s.if((0,ms.not)((b=e.valid)!==null&&b!==void 0?b:u),g)}}Tr.funcKeywordCode=ZU;function XA(n){const{gen:e,data:t,it:s}=n;e.if(s.parentData,()=>e.assign(t,(0,ms._)`${s.parentData}[${s.parentDataProperty}]`))}function XU(n,e){const{gen:t}=n;t.if((0,ms._)`Array.isArray(${e})`,()=>{t.assign(Qa.default.vErrors,(0,ms._)`${Qa.default.vErrors} === null ? ${e} : ${Qa.default.vErrors}.concat(${e})`).assign(Qa.default.errors,(0,ms._)`${Qa.default.vErrors}.length`),(0,GU.extendErrors)(n)},()=>n.error())}function YU({schemaEnv:n},e){if(e.async&&!n.$async)throw new Error("async keyword in sync schema")}function OT(n,e,t){if(t===void 0)throw new Error(`keyword "${e}" failed to compile`);return n.scopeValue("keyword",typeof t=="function"?{ref:t}:{ref:t,code:(0,ms.stringify)(t)})}function JU(n,e,t=!1){return!e.length||e.some(s=>s==="array"?Array.isArray(n):s==="object"?n&&typeof n=="object"&&!Array.isArray(n):typeof n==s||t&&typeof n>"u")}Tr.validSchemaType=JU;function QU({schema:n,opts:e,self:t,errSchemaPath:s},i,r){if(Array.isArray(i.keyword)?!i.keyword.includes(r):i.keyword!==r)throw new Error("ajv implementation error");const o=i.dependencies;if(o!=null&&o.some(a=>!Object.prototype.hasOwnProperty.call(n,a)))throw new Error(`parent schema must have dependencies of ${r}: ${o.join(",")}`);if(i.validateSchema&&!i.validateSchema(n[r])){const l=`keyword "${r}" value is invalid at path "${s}": `+t.errorsText(i.validateSchema.errors);if(e.validateSchema==="log")t.logger.error(l);else throw new Error(l)}}Tr.validateKeywordUsage=QU;var Aa={};Object.defineProperty(Aa,"__esModule",{value:!0});Aa.extendSubschemaMode=Aa.extendSubschemaData=Aa.getSubschema=void 0;const kr=Ke,NT=fe;function eq(n,{keyword:e,schemaProp:t,schema:s,schemaPath:i,errSchemaPath:r,topSchemaRef:o}){if(e!==void 0&&s!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(e!==void 0){const a=n.schema[e];return t===void 0?{schema:a,schemaPath:(0,kr._)`${n.schemaPath}${(0,kr.getProperty)(e)}`,errSchemaPath:`${n.errSchemaPath}/${e}`}:{schema:a[t],schemaPath:(0,kr._)`${n.schemaPath}${(0,kr.getProperty)(e)}${(0,kr.getProperty)(t)}`,errSchemaPath:`${n.errSchemaPath}/${e}/${(0,NT.escapeFragment)(t)}`}}if(s!==void 0){if(i===void 0||r===void 0||o===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:s,schemaPath:i,topSchemaRef:o,errSchemaPath:r}}throw new Error('either "keyword" or "schema" must be passed')}Aa.getSubschema=eq;function tq(n,e,{dataProp:t,dataPropType:s,data:i,dataTypes:r,propertyName:o}){if(i!==void 0&&t!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');const{gen:a}=e;if(t!==void 0){const{errorPath:c,dataPathArr:h,opts:u}=e,d=a.let("data",(0,kr._)`${e.data}${(0,kr.getProperty)(t)}`,!0);l(d),n.errorPath=(0,kr.str)`${c}${(0,NT.getErrorPath)(t,s,u.jsPropertySyntax)}`,n.parentDataProperty=(0,kr._)`${t}`,n.dataPathArr=[...h,n.parentDataProperty]}if(i!==void 0){const c=i instanceof kr.Name?i:a.let("data",i,!0);l(c),o!==void 0&&(n.propertyName=o)}r&&(n.dataTypes=r);function l(c){n.data=c,n.dataLevel=e.dataLevel+1,n.dataTypes=[],e.definedProperties=new Set,n.parentData=e.data,n.dataNames=[...e.dataNames,c]}}Aa.extendSubschemaData=tq;function nq(n,{jtdDiscriminator:e,jtdMetadata:t,compositeRule:s,createErrors:i,allErrors:r}){s!==void 0&&(n.compositeRule=s),i!==void 0&&(n.createErrors=i),r!==void 0&&(n.allErrors=r),n.jtdDiscriminator=e,n.jtdMetadata=t}Aa.extendSubschemaMode=nq;var Bn={},S0=function n(e,t){if(e===t)return!0;if(e&&t&&typeof e=="object"&&typeof t=="object"){if(e.constructor!==t.constructor)return!1;var s,i,r;if(Array.isArray(e)){if(s=e.length,s!=t.length)return!1;for(i=s;i--!==0;)if(!n(e[i],t[i]))return!1;return!0}if(e.constructor===RegExp)return e.source===t.source&&e.flags===t.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===t.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===t.toString();if(r=Object.keys(e),s=r.length,s!==Object.keys(t).length)return!1;for(i=s;i--!==0;)if(!Object.prototype.hasOwnProperty.call(t,r[i]))return!1;for(i=s;i--!==0;){var o=r[i];if(!n(e[o],t[o]))return!1}return!0}return e!==e&&t!==t},LT={exports:{}},ba=LT.exports=function(n,e,t){typeof e=="function"&&(t=e,e={}),t=e.cb||t;var s=typeof t=="function"?t:t.pre||function(){},i=t.post||function(){};ag(e,s,i,n,"",n)};ba.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};ba.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};ba.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};ba.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0};function ag(n,e,t,s,i,r,o,a,l,c){if(s&&typeof s=="object"&&!Array.isArray(s)){e(s,i,r,o,a,l,c);for(var h in s){var u=s[h];if(Array.isArray(u)){if(h in ba.arrayKeywords)for(var d=0;de+=DT(s)),e===1/0))return 1/0}return e}function jT(n,e="",t){t!==!1&&(e=lh(e));const s=n.parse(e);return FT(n,s)}Bn.getFullPath=jT;function FT(n,e){return n.serialize(e).split("#")[0]+"#"}Bn._getFullPath=FT;const uq=/#\/?$/;function lh(n){return n?n.replace(uq,""):""}Bn.normalizeId=lh;function dq(n,e,t){return t=lh(t),n.resolve(e,t)}Bn.resolveUrl=dq;const fq=/^[a-z_][-a-z0-9._]*$/i;function pq(n,e){if(typeof n=="boolean")return{};const{schemaId:t,uriResolver:s}=this.opts,i=lh(n[t]||e),r={"":i},o=jT(s,i,!1),a={},l=new Set;return aq(n,{allKeys:!0},(u,d,p,m)=>{if(m===void 0)return;const y=o+d;let v=r[m];typeof u[t]=="string"&&(v=g.call(this,u[t])),b.call(this,u.$anchor),b.call(this,u.$dynamicAnchor),r[d]=v;function g(_){const x=this.opts.uriResolver.resolve;if(_=lh(v?x(v,_):_),l.has(_))throw h(_);l.add(_);let A=this.refs[_];return typeof A=="string"&&(A=this.refs[A]),typeof A=="object"?c(u,A.schema,_):_!==lh(y)&&(_[0]==="#"?(c(u,a[_],_),a[_]=u):this.refs[_]=y),_}function b(_){if(typeof _=="string"){if(!fq.test(_))throw new Error(`invalid anchor "${_}"`);g.call(this,`#${_}`)}}}),a;function c(u,d,p){if(d!==void 0&&!oq(u,d))throw h(p)}function h(u){return new Error(`reference "${u}" resolves to more than one schema`)}}Bn.getSchemaRefs=pq;Object.defineProperty(Yi,"__esModule",{value:!0});Yi.getData=Yi.KeywordCxt=Yi.validateFunctionCode=void 0;const zT=bu,YA=pn,KS=wo,ry=pn,mq=_0,jd=Tr,dv=Aa,we=Ke,Ce=Dr,gq=Bn,_o=fe,Qu=Zp;function yq(n){if(UT(n)&&(qT(n),BT(n))){wq(n);return}HT(n,()=>(0,zT.topBoolOrEmptySchema)(n))}Yi.validateFunctionCode=yq;function HT({gen:n,validateName:e,schema:t,schemaEnv:s,opts:i},r){i.code.es5?n.func(e,(0,we._)`${Ce.default.data}, ${Ce.default.valCxt}`,s.$async,()=>{n.code((0,we._)`"use strict"; ${JA(t,i)}`),bq(n,i),n.code(r)}):n.func(e,(0,we._)`${Ce.default.data}, ${vq(i)}`,s.$async,()=>n.code(JA(t,i)).code(r))}function vq(n){return(0,we._)`{${Ce.default.instancePath}="", ${Ce.default.parentData}, ${Ce.default.parentDataProperty}, ${Ce.default.rootData}=${Ce.default.data}${n.dynamicRef?(0,we._)`, ${Ce.default.dynamicAnchors}={}`:we.nil}}={}`}function bq(n,e){n.if(Ce.default.valCxt,()=>{n.var(Ce.default.instancePath,(0,we._)`${Ce.default.valCxt}.${Ce.default.instancePath}`),n.var(Ce.default.parentData,(0,we._)`${Ce.default.valCxt}.${Ce.default.parentData}`),n.var(Ce.default.parentDataProperty,(0,we._)`${Ce.default.valCxt}.${Ce.default.parentDataProperty}`),n.var(Ce.default.rootData,(0,we._)`${Ce.default.valCxt}.${Ce.default.rootData}`),e.dynamicRef&&n.var(Ce.default.dynamicAnchors,(0,we._)`${Ce.default.valCxt}.${Ce.default.dynamicAnchors}`)},()=>{n.var(Ce.default.instancePath,(0,we._)`""`),n.var(Ce.default.parentData,(0,we._)`undefined`),n.var(Ce.default.parentDataProperty,(0,we._)`undefined`),n.var(Ce.default.rootData,Ce.default.data),e.dynamicRef&&n.var(Ce.default.dynamicAnchors,(0,we._)`{}`)})}function wq(n){const{schema:e,opts:t,gen:s}=n;HT(n,()=>{t.$comment&&e.$comment&&WT(n),kq(n),s.let(Ce.default.vErrors,null),s.let(Ce.default.errors,0),t.unevaluated&&_q(n),VT(n),$q(n)})}function _q(n){const{gen:e,validateName:t}=n;n.evaluated=e.const("evaluated",(0,we._)`${t}.evaluated`),e.if((0,we._)`${n.evaluated}.dynamicProps`,()=>e.assign((0,we._)`${n.evaluated}.props`,(0,we._)`undefined`)),e.if((0,we._)`${n.evaluated}.dynamicItems`,()=>e.assign((0,we._)`${n.evaluated}.items`,(0,we._)`undefined`))}function JA(n,e){const t=typeof n=="object"&&n[e.schemaId];return t&&(e.code.source||e.code.process)?(0,we._)`/*# sourceURL=${t} */`:we.nil}function Sq(n,e){if(UT(n)&&(qT(n),BT(n))){xq(n,e);return}(0,zT.boolOrEmptySchema)(n,e)}function BT({schema:n,self:e}){if(typeof n=="boolean")return!n;for(const t in n)if(e.RULES.all[t])return!0;return!1}function UT(n){return typeof n.schema!="boolean"}function xq(n,e){const{schema:t,gen:s,opts:i}=n;i.$comment&&t.$comment&&WT(n),Eq(n),Cq(n);const r=s.const("_errs",Ce.default.errors);VT(n,r),s.var(e,(0,we._)`${r} === ${Ce.default.errors}`)}function qT(n){(0,_o.checkUnknownRules)(n),Aq(n)}function VT(n,e){if(n.opts.jtd)return QA(n,[],!1,e);const t=(0,YA.getSchemaTypes)(n.schema),s=(0,YA.coerceAndCheckDataType)(n,t);QA(n,t,!s,e)}function Aq(n){const{schema:e,errSchemaPath:t,opts:s,self:i}=n;e.$ref&&s.ignoreKeywordsWithRef&&(0,_o.schemaHasRulesButRef)(e,i.RULES)&&i.logger.warn(`$ref: keywords ignored in schema at path "${t}"`)}function kq(n){const{schema:e,opts:t}=n;e.default!==void 0&&t.useDefaults&&t.strictSchema&&(0,_o.checkStrictMode)(n,"default is ignored in the schema root")}function Eq(n){const e=n.schema[n.opts.schemaId];e&&(n.baseId=(0,gq.resolveUrl)(n.opts.uriResolver,n.baseId,e))}function Cq(n){if(n.schema.$async&&!n.schemaEnv.$async)throw new Error("async schema in sync schema")}function WT({gen:n,schemaEnv:e,schema:t,errSchemaPath:s,opts:i}){const r=t.$comment;if(i.$comment===!0)n.code((0,we._)`${Ce.default.self}.logger.log(${r})`);else if(typeof i.$comment=="function"){const o=(0,we.str)`${s}/$comment`,a=n.scopeValue("root",{ref:e.root});n.code((0,we._)`${Ce.default.self}.opts.$comment(${r}, ${o}, ${a}.schema)`)}}function $q(n){const{gen:e,schemaEnv:t,validateName:s,ValidationError:i,opts:r}=n;t.$async?e.if((0,we._)`${Ce.default.errors} === 0`,()=>e.return(Ce.default.data),()=>e.throw((0,we._)`new ${i}(${Ce.default.vErrors})`)):(e.assign((0,we._)`${s}.errors`,Ce.default.vErrors),r.unevaluated&&Tq(n),e.return((0,we._)`${Ce.default.errors} === 0`))}function Tq({gen:n,evaluated:e,props:t,items:s}){t instanceof we.Name&&n.assign((0,we._)`${e}.props`,t),s instanceof we.Name&&n.assign((0,we._)`${e}.items`,s)}function QA(n,e,t,s){const{gen:i,schema:r,data:o,allErrors:a,opts:l,self:c}=n,{RULES:h}=c;if(r.$ref&&(l.ignoreKeywordsWithRef||!(0,_o.schemaHasRulesButRef)(r,h))){i.block(()=>ZT(n,"$ref",h.all.$ref.definition));return}l.jtd||Pq(n,e),i.block(()=>{for(const d of h.rules)u(d);u(h.post)});function u(d){(0,KS.shouldUseGroup)(r,d)&&(d.type?(i.if((0,ry.checkDataType)(d.type,o,l.strictNumbers)),ek(n,d),e.length===1&&e[0]===d.type&&t&&(i.else(),(0,ry.reportTypeError)(n)),i.endIf()):ek(n,d),a||i.if((0,we._)`${Ce.default.errors} === ${s||0}`))}}function ek(n,e){const{gen:t,schema:s,opts:{useDefaults:i}}=n;i&&(0,mq.assignDefaults)(n,e.type),t.block(()=>{for(const r of e.rules)(0,KS.shouldUseRule)(s,r)&&ZT(n,r.keyword,r.definition,e.type)})}function Pq(n,e){n.schemaEnv.meta||!n.opts.strictTypes||(Rq(n,e),n.opts.allowUnionTypes||Mq(n,e),Iq(n,n.dataTypes))}function Rq(n,e){if(e.length){if(!n.dataTypes.length){n.dataTypes=e;return}e.forEach(t=>{GT(n.dataTypes,t)||ZS(n,`type "${t}" not allowed by context "${n.dataTypes.join(",")}"`)}),Nq(n,e)}}function Mq(n,e){e.length>1&&!(e.length===2&&e.includes("null"))&&ZS(n,"use allowUnionTypes to allow union type keyword")}function Iq(n,e){const t=n.self.RULES.all;for(const s in t){const i=t[s];if(typeof i=="object"&&(0,KS.shouldUseRule)(n.schema,i)){const{type:r}=i.definition;r.length&&!r.some(o=>Oq(e,o))&&ZS(n,`missing type "${r.join(",")}" for keyword "${s}"`)}}}function Oq(n,e){return n.includes(e)||e==="number"&&n.includes("integer")}function GT(n,e){return n.includes(e)||e==="integer"&&n.includes("number")}function Nq(n,e){const t=[];for(const s of n.dataTypes)GT(e,s)?t.push(s):e.includes("integer")&&s==="number"&&t.push("integer");n.dataTypes=t}function ZS(n,e){const t=n.schemaEnv.baseId+n.errSchemaPath;e+=` at "${t}" (strictTypes)`,(0,_o.checkStrictMode)(n,e,n.opts.strictTypes)}let KT=class{constructor(e,t,s){if((0,jd.validateKeywordUsage)(e,t,s),this.gen=e.gen,this.allErrors=e.allErrors,this.keyword=s,this.data=e.data,this.schema=e.schema[s],this.$data=t.$data&&e.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,_o.schemaRefOrVal)(e,this.schema,s,this.$data),this.schemaType=t.schemaType,this.parentSchema=e.schema,this.params={},this.it=e,this.def=t,this.$data)this.schemaCode=e.gen.const("vSchema",XT(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,jd.validSchemaType)(this.schema,t.schemaType,t.allowUndefined))throw new Error(`${s} value must be ${JSON.stringify(t.schemaType)}`);("code"in t?t.trackErrors:t.errors!==!1)&&(this.errsCount=e.gen.const("_errs",Ce.default.errors))}result(e,t,s){this.failResult((0,we.not)(e),t,s)}failResult(e,t,s){this.gen.if(e),s?s():this.error(),t?(this.gen.else(),t(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(e,t){this.failResult((0,we.not)(e),void 0,t)}fail(e){if(e===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(e),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(e){if(!this.$data)return this.fail(e);const{schemaCode:t}=this;this.fail((0,we._)`${t} !== undefined && (${(0,we.or)(this.invalid$data(),e)})`)}error(e,t,s){if(t){this.setParams(t),this._error(e,s),this.setParams({});return}this._error(e,s)}_error(e,t){(e?Qu.reportExtraError:Qu.reportError)(this,this.def.error,t)}$dataError(){(0,Qu.reportError)(this,this.def.$dataError||Qu.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,Qu.resetErrorsCount)(this.gen,this.errsCount)}ok(e){this.allErrors||this.gen.if(e)}setParams(e,t){t?Object.assign(this.params,e):this.params=e}block$data(e,t,s=we.nil){this.gen.block(()=>{this.check$data(e,s),t()})}check$data(e=we.nil,t=we.nil){if(!this.$data)return;const{gen:s,schemaCode:i,schemaType:r,def:o}=this;s.if((0,we.or)((0,we._)`${i} === undefined`,t)),e!==we.nil&&s.assign(e,!0),(r.length||o.validateSchema)&&(s.elseIf(this.invalid$data()),this.$dataError(),e!==we.nil&&s.assign(e,!1)),s.else()}invalid$data(){const{gen:e,schemaCode:t,schemaType:s,def:i,it:r}=this;return(0,we.or)(o(),a());function o(){if(s.length){if(!(t instanceof we.Name))throw new Error("ajv implementation error");const l=Array.isArray(s)?s:[s];return(0,we._)`${(0,ry.checkDataTypes)(l,t,r.opts.strictNumbers,ry.DataType.Wrong)}`}return we.nil}function a(){if(i.validateSchema){const l=e.scopeValue("validate$data",{ref:i.validateSchema});return(0,we._)`!${l}(${t})`}return we.nil}}subschema(e,t){const s=(0,dv.getSubschema)(this.it,e);(0,dv.extendSubschemaData)(s,this.it,e),(0,dv.extendSubschemaMode)(s,e);const i={...this.it,...s,items:void 0,props:void 0};return Sq(i,t),i}mergeEvaluated(e,t){const{it:s,gen:i}=this;s.opts.unevaluated&&(s.props!==!0&&e.props!==void 0&&(s.props=_o.mergeEvaluated.props(i,e.props,s.props,t)),s.items!==!0&&e.items!==void 0&&(s.items=_o.mergeEvaluated.items(i,e.items,s.items,t)))}mergeValidEvaluated(e,t){const{it:s,gen:i}=this;if(s.opts.unevaluated&&(s.props!==!0||s.items!==!0))return i.if(t,()=>this.mergeEvaluated(e,we.Name)),!0}};Yi.KeywordCxt=KT;function ZT(n,e,t,s){const i=new KT(n,t,e);"code"in t?t.code(i,s):i.$data&&t.validate?(0,jd.funcKeywordCode)(i,t):"macro"in t?(0,jd.macroKeywordCode)(i,t):(t.compile||t.validate)&&(0,jd.funcKeywordCode)(i,t)}const Lq=/^\/(?:[^~]|~0|~1)*$/,Dq=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function XT(n,{dataLevel:e,dataNames:t,dataPathArr:s}){let i,r;if(n==="")return Ce.default.rootData;if(n[0]==="/"){if(!Lq.test(n))throw new Error(`Invalid JSON-pointer: ${n}`);i=n,r=Ce.default.rootData}else{const c=Dq.exec(n);if(!c)throw new Error(`Invalid JSON-pointer: ${n}`);const h=+c[1];if(i=c[2],i==="#"){if(h>=e)throw new Error(l("property/index",h));return s[e-h]}if(h>e)throw new Error(l("data",h));if(r=t[e-h],!i)return r}let o=r;const a=i.split("/");for(const c of a)c&&(r=(0,we._)`${r}${(0,we.getProperty)((0,_o.unescapeJsonPointer)(c))}`,o=(0,we._)`${o} && ${r}`);return o;function l(c,h){return`Cannot access ${c} ${h} levels up, current level is ${e}`}}Yi.getData=XT;var Xp={};Object.defineProperty(Xp,"__esModule",{value:!0});let jq=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};Xp.default=jq;var Lu={};Object.defineProperty(Lu,"__esModule",{value:!0});const fv=Bn;let Fq=class extends Error{constructor(e,t,s,i){super(i||`can't resolve reference ${s} from id ${t}`),this.missingRef=(0,fv.resolveUrl)(e,t,s),this.missingSchema=(0,fv.normalizeId)((0,fv.getFullPath)(e,this.missingRef))}};Lu.default=Fq;var Ns={};Object.defineProperty(Ns,"__esModule",{value:!0});Ns.resolveSchema=Ns.getCompilingSchema=Ns.resolveRef=Ns.compileSchema=Ns.SchemaEnv=void 0;const Ci=Ke,zq=Xp,Ha=Dr,Wi=Bn,tk=fe,Hq=Yi;let x0=class{constructor(e){var t;this.refs={},this.dynamicAnchors={};let s;typeof e.schema=="object"&&(s=e.schema),this.schema=e.schema,this.schemaId=e.schemaId,this.root=e.root||this,this.baseId=(t=e.baseId)!==null&&t!==void 0?t:(0,Wi.normalizeId)(s==null?void 0:s[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=s==null?void 0:s.$async,this.refs={}}};Ns.SchemaEnv=x0;function XS(n){const e=YT.call(this,n);if(e)return e;const t=(0,Wi.getFullPath)(this.opts.uriResolver,n.root.baseId),{es5:s,lines:i}=this.opts.code,{ownProperties:r}=this.opts,o=new Ci.CodeGen(this.scope,{es5:s,lines:i,ownProperties:r});let a;n.$async&&(a=o.scopeValue("Error",{ref:zq.default,code:(0,Ci._)`require("ajv/dist/runtime/validation_error").default`}));const l=o.scopeName("validate");n.validateName=l;const c={gen:o,allErrors:this.opts.allErrors,data:Ha.default.data,parentData:Ha.default.parentData,parentDataProperty:Ha.default.parentDataProperty,dataNames:[Ha.default.data],dataPathArr:[Ci.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:o.scopeValue("schema",this.opts.code.source===!0?{ref:n.schema,code:(0,Ci.stringify)(n.schema)}:{ref:n.schema}),validateName:l,ValidationError:a,schema:n.schema,schemaEnv:n,rootId:t,baseId:n.baseId||t,schemaPath:Ci.nil,errSchemaPath:n.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,Ci._)`""`,opts:this.opts,self:this};let h;try{this._compilations.add(n),(0,Hq.validateFunctionCode)(c),o.optimize(this.opts.code.optimize);const u=o.toString();h=`${o.scopeRefs(Ha.default.scope)}return ${u}`,this.opts.code.process&&(h=this.opts.code.process(h,n));const p=new Function(`${Ha.default.self}`,`${Ha.default.scope}`,h)(this,this.scope.get());if(this.scope.value(l,{ref:p}),p.errors=null,p.schema=n.schema,p.schemaEnv=n,n.$async&&(p.$async=!0),this.opts.code.source===!0&&(p.source={validateName:l,validateCode:u,scopeValues:o._values}),this.opts.unevaluated){const{props:m,items:y}=c;p.evaluated={props:m instanceof Ci.Name?void 0:m,items:y instanceof Ci.Name?void 0:y,dynamicProps:m instanceof Ci.Name,dynamicItems:y instanceof Ci.Name},p.source&&(p.source.evaluated=(0,Ci.stringify)(p.evaluated))}return n.validate=p,n}catch(u){throw delete n.validate,delete n.validateName,h&&this.logger.error("Error compiling schema, function code:",h),u}finally{this._compilations.delete(n)}}Ns.compileSchema=XS;function Bq(n,e,t){var s;t=(0,Wi.resolveUrl)(this.opts.uriResolver,e,t);const i=n.refs[t];if(i)return i;let r=Vq.call(this,n,t);if(r===void 0){const o=(s=n.localRefs)===null||s===void 0?void 0:s[t],{schemaId:a}=this.opts;o&&(r=new x0({schema:o,schemaId:a,root:n,baseId:e}))}if(r!==void 0)return n.refs[t]=Uq.call(this,r)}Ns.resolveRef=Bq;function Uq(n){return(0,Wi.inlineRef)(n.schema,this.opts.inlineRefs)?n.schema:n.validate?n:XS.call(this,n)}function YT(n){for(const e of this._compilations)if(qq(e,n))return e}Ns.getCompilingSchema=YT;function qq(n,e){return n.schema===e.schema&&n.root===e.root&&n.baseId===e.baseId}function Vq(n,e){let t;for(;typeof(t=this.refs[e])=="string";)e=t;return t||this.schemas[e]||A0.call(this,n,e)}function A0(n,e){const t=this.opts.uriResolver.parse(e),s=(0,Wi._getFullPath)(this.opts.uriResolver,t);let i=(0,Wi.getFullPath)(this.opts.uriResolver,n.baseId,void 0);if(Object.keys(n.schema).length>0&&s===i)return pv.call(this,t,n);const r=(0,Wi.normalizeId)(s),o=this.refs[r]||this.schemas[r];if(typeof o=="string"){const a=A0.call(this,n,o);return typeof(a==null?void 0:a.schema)!="object"?void 0:pv.call(this,t,a)}if(typeof(o==null?void 0:o.schema)=="object"){if(o.validate||XS.call(this,o),r===(0,Wi.normalizeId)(e)){const{schema:a}=o,{schemaId:l}=this.opts,c=a[l];return c&&(i=(0,Wi.resolveUrl)(this.opts.uriResolver,i,c)),new x0({schema:a,schemaId:l,root:n,baseId:i})}return pv.call(this,t,o)}}Ns.resolveSchema=A0;const Wq=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function pv(n,{baseId:e,schema:t,root:s}){var i;if(((i=n.fragment)===null||i===void 0?void 0:i[0])!=="/")return;for(const a of n.fragment.slice(1).split("/")){if(typeof t=="boolean")return;const l=t[(0,tk.unescapeFragment)(a)];if(l===void 0)return;t=l;const c=typeof t=="object"&&t[this.opts.schemaId];!Wq.has(a)&&c&&(e=(0,Wi.resolveUrl)(this.opts.uriResolver,e,c))}let r;if(typeof t!="boolean"&&t.$ref&&!(0,tk.schemaHasRulesButRef)(t,this.RULES)){const a=(0,Wi.resolveUrl)(this.opts.uriResolver,e,t.$ref);r=A0.call(this,s,a)}const{schemaId:o}=this.opts;if(r=r||new x0({schema:t,schemaId:o,root:s,baseId:e}),r.schema!==r.root.schema)return r}const Gq="https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",Kq="Meta-schema for $data reference (JSON AnySchema extension proposal)",Zq="object",Xq=["$data"],Yq={$data:{type:"string",anyOf:[{format:"relative-json-pointer"},{format:"json-pointer"}]}},Jq=!1,Qq={$id:Gq,description:Kq,type:Zq,required:Xq,properties:Yq,additionalProperties:Jq};var YS={},k0={exports:{}};const eV=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),JT=RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u),JS=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),QT=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),tV=RegExp.prototype.test.bind(/^[\da-z\-._~!$&'()*+,;=:@/]$/iu);function eP(n){let e="",t=0,s=0;for(s=0;s=48&&t<=57||t>=65&&t<=70||t>=97&&t<=102))return"";e+=n[s];break}for(s+=1;s=48&&t<=57||t>=65&&t<=70||t>=97&&t<=102))return"";e+=n[s]}return e}const nV=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function nk(n){return n.length=0,!0}function sV(n,e,t){if(n.length){const s=eP(n);if(s!=="")e.push(s);else return t.error=!0,!1;n.length=0}return!0}function iV(n){let e=0;const t={error:!1,address:"",zone:""},s=[],i=[];let r=!1,o=!1,a=sV;for(let l=0;l7){t.error=!0;break}l>0&&n[l-1]===":"&&(r=!0),s.push(":");continue}else if(c==="%"){if(!a(i,s,t))break;a=nk}else{i.push(c);continue}}return i.length&&(a===nk?t.zone=i.join(""):o?s.push(i.join("")):s.push(eP(i))),t.address=s.join(""),t}function tP(n){if(rV(n,":")<2)return{host:n,isIPV6:!1};const e=iV(n);if(e.error)return{host:n,isIPV6:!1};{let t=e.address,s=e.address;return e.zone&&(t+="%"+e.zone,s+="%25"+e.zone),{host:t,isIPV6:!0,escapedHost:s}}}function rV(n,e){let t=0;for(let s=0;saV[s])}function hV(n,e=!1){if(n.indexOf("%")===-1)return n;let t="";for(let s=0;s65535))return"URI port is malformed."}function ay(n,e){const t=Object.assign({},e),s={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0};let i=!1,r=!1;t.reference==="suffix"&&(t.scheme?n=t.scheme+":"+n:n="//"+n);const o=n.match(zV);o!==null&&o[1].indexOf("\\")!==-1&&(s.error="URI authority must not contain a literal backslash.",i=!0);const a=n.match(HV);if(a!==null){const c=a[1],h=c.replace(/[\t\n\r]/g,"");h.length>=2&&(h.slice(0,2)!=="//"?(s.error=s.error||"URI authority must not contain a literal backslash.",i=!0):c.length!==h.length&&(s.error=s.error||"URI authority introducer must not contain whitespace.",i=!0))}const l=n.match(FV);if(l){s.scheme=l[1],s.userinfo=l[3],s.host=l[4],s.port=parseInt(l[5],10),s.path=l[6]||"",s.query=l[7],s.fragment=l[8],isNaN(s.port)&&(s.port=l[5]);const c=BV(s,l);if(c!==void 0&&(s.error=s.error||c,i=!0),s.host)if(IV(s.host)===!1){const d=CV(s.host);s.host=d.host.toLowerCase(),r=d.isIPV6}else r=!0;s.scheme===void 0&&s.userinfo===void 0&&s.host===void 0&&s.port===void 0&&s.query===void 0&&!s.path?s.reference="same-document":s.scheme===void 0?s.reference="relative":s.fragment===void 0?s.reference="absolute":s.reference="uri",t.reference&&t.reference!=="suffix"&&t.reference!==s.reference&&(s.error=s.error||"URI is not a "+t.reference+" reference.");const h=lP(t.scheme||s.scheme);if(!t.unicodeSupport&&(!h||!h.unicodeSupport)&&s.host&&(t.domainHost||h&&h.domainHost)&&r===!1&&OV(s.host))try{s.host=new URL("http://"+s.host).hostname}catch(u){s.error=s.error||"Host's domain name can not be converted to ASCII: "+u}if((!h||h&&!h.skipNormalize)&&(n.indexOf("%")!==-1&&(s.scheme!==void 0&&(s.scheme=unescape(s.scheme)),s.host!==void 0&&(s.host=MV(unescape(s.host),r))),s.path&&(s.path=PV(s.path)),s.fragment))try{s.fragment=encodeURI(decodeURIComponent(s.fragment))}catch{s.error=s.error||"URI malformed"}h&&h.parse&&h.parse(s,t)}else s.error=s.error||"URI can not be parsed.";return{parsed:s,malformedAuthorityOrPort:i}}function ly(n,e){return ay(n,e).parsed}function UV(n,e){return hP(n,e).normalized}function hP(n,e){const{parsed:t,malformedAuthorityOrPort:s}=ay(n,e);return{normalized:s?n:hc(t,e),malformedAuthorityOrPort:s}}function sk(n,e){if(typeof n=="string"){const{normalized:t,malformedAuthorityOrPort:s}=hP(n,e);return s?void 0:t}if(typeof n=="object")return hc(n,e)}const e1={SCHEMES:NV,normalize:LV,resolve:DV,resolveComponent:cP,equal:jV,serialize:hc,parse:ly};k0.exports=e1;k0.exports.default=e1;k0.exports.fastUri=e1;var uP=k0.exports;Object.defineProperty(YS,"__esModule",{value:!0});const dP=uP;dP.code='require("ajv/dist/runtime/uri").default';YS.default=dP;(function(n){Object.defineProperty(n,"__esModule",{value:!0}),n.CodeGen=n.Name=n.nil=n.stringify=n.str=n._=n.KeywordCxt=void 0;var e=Yi;Object.defineProperty(n,"KeywordCxt",{enumerable:!0,get:function(){return e.KeywordCxt}});var t=Ke;Object.defineProperty(n,"_",{enumerable:!0,get:function(){return t._}}),Object.defineProperty(n,"str",{enumerable:!0,get:function(){return t.str}}),Object.defineProperty(n,"stringify",{enumerable:!0,get:function(){return t.stringify}}),Object.defineProperty(n,"nil",{enumerable:!0,get:function(){return t.nil}}),Object.defineProperty(n,"Name",{enumerable:!0,get:function(){return t.Name}}),Object.defineProperty(n,"CodeGen",{enumerable:!0,get:function(){return t.CodeGen}});const s=Xp,i=Lu,r=cc,o=Ns,a=Ke,l=Bn,c=pn,h=fe,u=Qq,d=YS,p=(z,E)=>new RegExp(z,E);p.code="new RegExp";const m=["removeAdditional","useDefaults","coerceTypes"],y=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),v={errorDataPath:"",format:"`validateFormats: false` can be used instead.",nullable:'"nullable" keyword is supported by default.',jsonPointers:"Deprecated jsPropertySyntax can be used instead.",extendRefs:"Deprecated ignoreKeywordsWithRef can be used instead.",missingRefs:"Pass empty schema with $id that should be ignored to ajv.addSchema.",processCode:"Use option `code: {process: (code, schemaEnv: object) => string}`",sourceCode:"Use option `code: {source: true}`",strictDefaults:"It is default now, see option `strict`.",strictKeywords:"It is default now, see option `strict`.",uniqueItems:'"uniqueItems" keyword is always validated.',unknownFormats:"Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",cache:"Map is used as cache, schema object as key.",serialize:"Map is used as cache, schema object as key.",ajvErrors:"It is default now."},g={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},b=200;function _(z){var E,O,R,w,k,N,G,Z,ae,ie,Ae,ct,Ie,Fe,Je,st,tn,Pn,Et,As,Rn,ks,hs,us,Es;const ln=z.strict,cn=(E=z.code)===null||E===void 0?void 0:E.optimize,Mn=cn===!0||cn===void 0?1:cn||0,Xn=(R=(O=z.code)===null||O===void 0?void 0:O.regExp)!==null&&R!==void 0?R:p,Yn=(w=z.uriResolver)!==null&&w!==void 0?w:d.default;return{strictSchema:(N=(k=z.strictSchema)!==null&&k!==void 0?k:ln)!==null&&N!==void 0?N:!0,strictNumbers:(Z=(G=z.strictNumbers)!==null&&G!==void 0?G:ln)!==null&&Z!==void 0?Z:!0,strictTypes:(ie=(ae=z.strictTypes)!==null&&ae!==void 0?ae:ln)!==null&&ie!==void 0?ie:"log",strictTuples:(ct=(Ae=z.strictTuples)!==null&&Ae!==void 0?Ae:ln)!==null&&ct!==void 0?ct:"log",strictRequired:(Fe=(Ie=z.strictRequired)!==null&&Ie!==void 0?Ie:ln)!==null&&Fe!==void 0?Fe:!1,code:z.code?{...z.code,optimize:Mn,regExp:Xn}:{optimize:Mn,regExp:Xn},loopRequired:(Je=z.loopRequired)!==null&&Je!==void 0?Je:b,loopEnum:(st=z.loopEnum)!==null&&st!==void 0?st:b,meta:(tn=z.meta)!==null&&tn!==void 0?tn:!0,messages:(Pn=z.messages)!==null&&Pn!==void 0?Pn:!0,inlineRefs:(Et=z.inlineRefs)!==null&&Et!==void 0?Et:!0,schemaId:(As=z.schemaId)!==null&&As!==void 0?As:"$id",addUsedSchema:(Rn=z.addUsedSchema)!==null&&Rn!==void 0?Rn:!0,validateSchema:(ks=z.validateSchema)!==null&&ks!==void 0?ks:!0,validateFormats:(hs=z.validateFormats)!==null&&hs!==void 0?hs:!0,unicodeRegExp:(us=z.unicodeRegExp)!==null&&us!==void 0?us:!0,int32range:(Es=z.int32range)!==null&&Es!==void 0?Es:!0,uriResolver:Yn}}class x{constructor(E={}){this.schemas={},this.refs={},this.formats=Object.create(null),this._compilations=new Set,this._loading={},this._cache=new Map,E=this.opts={...E,..._(E)};const{es5:O,lines:R}=this.opts.code;this.scope=new a.ValueScope({scope:{},prefixes:y,es5:O,lines:R}),this.logger=B(E.logger);const w=E.validateFormats;E.validateFormats=!1,this.RULES=(0,r.getRules)(),A.call(this,v,E,"NOT SUPPORTED"),A.call(this,g,E,"DEPRECATED","warn"),this._metaOpts=q.call(this),E.formats&&I.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),E.keywords&&j.call(this,E.keywords),typeof E.meta=="object"&&this.addMetaSchema(E.meta),$.call(this),E.validateFormats=w}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){const{$data:E,meta:O,schemaId:R}=this.opts;let w=u;R==="id"&&(w={...u},w.id=w.$id,delete w.$id),O&&E&&this.addMetaSchema(w,w[R],!1)}defaultMeta(){const{meta:E,schemaId:O}=this.opts;return this.opts.defaultMeta=typeof E=="object"?E[O]||E:void 0}validate(E,O){let R;if(typeof E=="string"){if(R=this.getSchema(E),!R)throw new Error(`no schema with key or ref "${E}"`)}else R=this.compile(E);const w=R(O);return"$async"in R||(this.errors=R.errors),w}compile(E,O){const R=this._addSchema(E,O);return R.validate||this._compileSchemaEnv(R)}compileAsync(E,O){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");const{loadSchema:R}=this.opts;return w.call(this,E,O);async function w(ie,Ae){await k.call(this,ie.$schema);const ct=this._addSchema(ie,Ae);return ct.validate||N.call(this,ct)}async function k(ie){ie&&!this.getSchema(ie)&&await w.call(this,{$ref:ie},!0)}async function N(ie){try{return this._compileSchemaEnv(ie)}catch(Ae){if(!(Ae instanceof i.default))throw Ae;return G.call(this,Ae),await Z.call(this,Ae.missingSchema),N.call(this,ie)}}function G({missingSchema:ie,missingRef:Ae}){if(this.refs[ie])throw new Error(`AnySchema ${ie} is loaded but ${Ae} cannot be resolved`)}async function Z(ie){const Ae=await ae.call(this,ie);this.refs[ie]||await k.call(this,Ae.$schema),this.refs[ie]||this.addSchema(Ae,ie,O)}async function ae(ie){const Ae=this._loading[ie];if(Ae)return Ae;try{return await(this._loading[ie]=R(ie))}finally{delete this._loading[ie]}}}addSchema(E,O,R,w=this.opts.validateSchema){if(Array.isArray(E)){for(const N of E)this.addSchema(N,void 0,R,w);return this}let k;if(typeof E=="object"){const{schemaId:N}=this.opts;if(k=E[N],k!==void 0&&typeof k!="string")throw new Error(`schema ${N} must be string`)}return O=(0,l.normalizeId)(O||k),this._checkUnique(O),this.schemas[O]=this._addSchema(E,R,O,w,!0),this}addMetaSchema(E,O,R=this.opts.validateSchema){return this.addSchema(E,O,!0,R),this}validateSchema(E,O){if(typeof E=="boolean")return!0;let R;if(R=E.$schema,R!==void 0&&typeof R!="string")throw new Error("$schema must be a string");if(R=R||this.opts.defaultMeta||this.defaultMeta(),!R)return this.logger.warn("meta-schema not available"),this.errors=null,!0;const w=this.validate(R,E);if(!w&&O){const k="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(k);else throw new Error(k)}return w}getSchema(E){let O;for(;typeof(O=C.call(this,E))=="string";)E=O;if(O===void 0){const{schemaId:R}=this.opts,w=new o.SchemaEnv({schema:{},schemaId:R});if(O=o.resolveSchema.call(this,w,E),!O)return;this.refs[E]=O}return O.validate||this._compileSchemaEnv(O)}removeSchema(E){if(E instanceof RegExp)return this._removeAllSchemas(this.schemas,E),this._removeAllSchemas(this.refs,E),this;switch(typeof E){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{const O=C.call(this,E);return typeof O=="object"&&this._cache.delete(O.schema),delete this.schemas[E],delete this.refs[E],this}case"object":{const O=E;this._cache.delete(O);let R=E[this.opts.schemaId];return R&&(R=(0,l.normalizeId)(R),delete this.schemas[R],delete this.refs[R]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(E){for(const O of E)this.addKeyword(O);return this}addKeyword(E,O){let R;if(typeof E=="string")R=E,typeof O=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),O.keyword=R);else if(typeof E=="object"&&O===void 0){if(O=E,R=O.keyword,Array.isArray(R)&&!R.length)throw new Error("addKeywords: keyword must be string or non-empty array")}else throw new Error("invalid addKeywords parameters");if(D.call(this,R,O),!O)return(0,h.eachItem)(R,k=>X.call(this,k)),this;J.call(this,O);const w={...O,type:(0,c.getJSONTypes)(O.type),schemaType:(0,c.getJSONTypes)(O.schemaType)};return(0,h.eachItem)(R,w.type.length===0?k=>X.call(this,k,w):k=>w.type.forEach(N=>X.call(this,k,w,N))),this}getKeyword(E){const O=this.RULES.all[E];return typeof O=="object"?O.definition:!!O}removeKeyword(E){const{RULES:O}=this;delete O.keywords[E],delete O.all[E];for(const R of O.rules){const w=R.rules.findIndex(k=>k.keyword===E);w>=0&&R.rules.splice(w,1)}return this}addFormat(E,O){return typeof O=="string"&&(O=new RegExp(O)),this.formats[E]=O,this}errorsText(E=this.errors,{separator:O=", ",dataVar:R="data"}={}){return!E||E.length===0?"No errors":E.map(w=>`${R}${w.instancePath} ${w.message}`).reduce((w,k)=>w+O+k)}$dataMetaSchema(E,O){const R=this.RULES.all;E=JSON.parse(JSON.stringify(E));for(const w of O){const k=w.split("/").slice(1);let N=E;for(const G of k)N=N[G];for(const G in R){const Z=R[G];if(typeof Z!="object")continue;const{$data:ae}=Z.definition,ie=N[G];ae&&ie&&(N[G]=ye(ie))}}return E}_removeAllSchemas(E,O){for(const R in E){const w=E[R];(!O||O.test(R))&&(typeof w=="string"?delete E[R]:w&&!w.meta&&(this._cache.delete(w.schema),delete E[R]))}}_addSchema(E,O,R,w=this.opts.validateSchema,k=this.opts.addUsedSchema){let N;const{schemaId:G}=this.opts;if(typeof E=="object")N=E[G];else{if(this.opts.jtd)throw new Error("schema must be object");if(typeof E!="boolean")throw new Error("schema must be object or boolean")}let Z=this._cache.get(E);if(Z!==void 0)return Z;R=(0,l.normalizeId)(N||R);const ae=l.getSchemaRefs.call(this,E,R);return Z=new o.SchemaEnv({schema:E,schemaId:G,meta:O,baseId:R,localRefs:ae}),this._cache.set(Z.schema,Z),k&&!R.startsWith("#")&&(R&&this._checkUnique(R),this.refs[R]=Z),w&&this.validateSchema(E,!0),Z}_checkUnique(E){if(this.schemas[E]||this.refs[E])throw new Error(`schema with key or id "${E}" already exists`)}_compileSchemaEnv(E){if(E.meta?this._compileMetaSchema(E):o.compileSchema.call(this,E),!E.validate)throw new Error("ajv implementation error");return E.validate}_compileMetaSchema(E){const O=this.opts;this.opts=this._metaOpts;try{o.compileSchema.call(this,E)}finally{this.opts=O}}}x.ValidationError=s.default,x.MissingRefError=i.default,n.default=x;function A(z,E,O,R="error"){for(const w in z){const k=w;k in E&&this.logger[R](`${O}: option ${w}. ${z[k]}`)}}function C(z){return z=(0,l.normalizeId)(z),this.schemas[z]||this.refs[z]}function $(){const z=this.opts.schemas;if(z)if(Array.isArray(z))this.addSchema(z);else for(const E in z)this.addSchema(z[E],E)}function I(){for(const z in this.opts.formats){const E=this.opts.formats[z];E&&this.addFormat(z,E)}}function j(z){if(Array.isArray(z)){this.addVocabulary(z);return}this.logger.warn("keywords option as map is deprecated, pass array");for(const E in z){const O=z[E];O.keyword||(O.keyword=E),this.addKeyword(O)}}function q(){const z={...this.opts};for(const E of m)delete z[E];return z}const L={log(){},warn(){},error(){}};function B(z){if(z===!1)return L;if(z===void 0)return console;if(z.log&&z.warn&&z.error)return z;throw new Error("logger must implement log, warn and error methods")}const H=/^[a-z_$][a-z0-9_$:-]*$/i;function D(z,E){const{RULES:O}=this;if((0,h.eachItem)(z,R=>{if(O.keywords[R])throw new Error(`Keyword ${R} is already defined`);if(!H.test(R))throw new Error(`Keyword ${R} has invalid name`)}),!!E&&E.$data&&!("code"in E||"validate"in E))throw new Error('$data keyword must have "code" or "validate" function')}function X(z,E,O){var R;const w=E==null?void 0:E.post;if(O&&w)throw new Error('keyword with "post" flag cannot have "type"');const{RULES:k}=this;let N=w?k.post:k.rules.find(({type:Z})=>Z===O);if(N||(N={type:O,rules:[]},k.rules.push(N)),k.keywords[z]=!0,!E)return;const G={keyword:z,definition:{...E,type:(0,c.getJSONTypes)(E.type),schemaType:(0,c.getJSONTypes)(E.schemaType)}};E.before?te.call(this,N,G,E.before):N.rules.push(G),k.all[z]=G,(R=E.implements)===null||R===void 0||R.forEach(Z=>this.addKeyword(Z))}function te(z,E,O){const R=z.rules.findIndex(w=>w.keyword===O);R>=0?z.rules.splice(R,0,E):(z.rules.push(E),this.logger.warn(`rule ${O} is not defined`))}function J(z){let{metaSchema:E}=z;E!==void 0&&(z.$data&&this.opts.$data&&(E=ye(E)),z.validateSchema=this.compile(E,!0))}const Y={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function ye(z){return{anyOf:[z,Y]}}})(wT);var t1={},n1={},s1={};Object.defineProperty(s1,"__esModule",{value:!0});const qV={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};s1.default=qV;var uc={};Object.defineProperty(uc,"__esModule",{value:!0});uc.callRef=uc.getValidate=void 0;const VV=Lu,ik=We,Ms=Ke,Lc=Dr,rk=Ns,xm=fe,WV={keyword:"$ref",schemaType:"string",code(n){const{gen:e,schema:t,it:s}=n,{baseId:i,schemaEnv:r,validateName:o,opts:a,self:l}=s,{root:c}=r;if((t==="#"||t==="#/")&&i===c.baseId)return u();const h=rk.resolveRef.call(l,c,i,t);if(h===void 0)throw new VV.default(s.opts.uriResolver,i,t);if(h instanceof rk.SchemaEnv)return d(h);return p(h);function u(){if(r===c)return cg(n,o,r,r.$async);const m=e.scopeValue("root",{ref:c});return cg(n,(0,Ms._)`${m}.validate`,c,c.$async)}function d(m){const y=fP(n,m);cg(n,y,m,m.$async)}function p(m){const y=e.scopeValue("schema",a.code.source===!0?{ref:m,code:(0,Ms.stringify)(m)}:{ref:m}),v=e.name("valid"),g=n.subschema({schema:m,dataTypes:[],schemaPath:Ms.nil,topSchemaRef:y,errSchemaPath:t},v);n.mergeEvaluated(g),n.ok(v)}}};function fP(n,e){const{gen:t}=n;return e.validate?t.scopeValue("validate",{ref:e.validate}):(0,Ms._)`${t.scopeValue("wrapper",{ref:e})}.validate`}uc.getValidate=fP;function cg(n,e,t,s){const{gen:i,it:r}=n,{allErrors:o,schemaEnv:a,opts:l}=r,c=l.passContext?Lc.default.this:Ms.nil;s?h():u();function h(){if(!a.$async)throw new Error("async schema referenced by sync schema");const m=i.let("valid");i.try(()=>{i.code((0,Ms._)`await ${(0,ik.callValidateCode)(n,e,c)}`),p(e),o||i.assign(m,!0)},y=>{i.if((0,Ms._)`!(${y} instanceof ${r.ValidationError})`,()=>i.throw(y)),d(y),o||i.assign(m,!1)}),n.ok(m)}function u(){n.result((0,ik.callValidateCode)(n,e,c),()=>p(e),()=>d(e))}function d(m){const y=(0,Ms._)`${m}.errors`;i.assign(Lc.default.vErrors,(0,Ms._)`${Lc.default.vErrors} === null ? ${y} : ${Lc.default.vErrors}.concat(${y})`),i.assign(Lc.default.errors,(0,Ms._)`${Lc.default.vErrors}.length`)}function p(m){var y;if(!r.opts.unevaluated)return;const v=(y=t==null?void 0:t.validate)===null||y===void 0?void 0:y.evaluated;if(r.props!==!0)if(v&&!v.dynamicProps)v.props!==void 0&&(r.props=xm.mergeEvaluated.props(i,v.props,r.props));else{const g=i.var("props",(0,Ms._)`${m}.evaluated.props`);r.props=xm.mergeEvaluated.props(i,g,r.props,Ms.Name)}if(r.items!==!0)if(v&&!v.dynamicItems)v.items!==void 0&&(r.items=xm.mergeEvaluated.items(i,v.items,r.items));else{const g=i.var("items",(0,Ms._)`${m}.evaluated.items`);r.items=xm.mergeEvaluated.items(i,g,r.items,Ms.Name)}}}uc.callRef=cg;uc.default=WV;Object.defineProperty(n1,"__esModule",{value:!0});const GV=s1,KV=uc,ZV=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",GV.default,KV.default];n1.default=ZV;var i1={},r1={};Object.defineProperty(r1,"__esModule",{value:!0});const cy=Ke,Oo=cy.operators,hy={maximum:{okStr:"<=",ok:Oo.LTE,fail:Oo.GT},minimum:{okStr:">=",ok:Oo.GTE,fail:Oo.LT},exclusiveMaximum:{okStr:"<",ok:Oo.LT,fail:Oo.GTE},exclusiveMinimum:{okStr:">",ok:Oo.GT,fail:Oo.LTE}},XV={message:({keyword:n,schemaCode:e})=>(0,cy.str)`must be ${hy[n].okStr} ${e}`,params:({keyword:n,schemaCode:e})=>(0,cy._)`{comparison: ${hy[n].okStr}, limit: ${e}}`},YV={keyword:Object.keys(hy),type:"number",schemaType:"number",$data:!0,error:XV,code(n){const{keyword:e,data:t,schemaCode:s}=n;n.fail$data((0,cy._)`${t} ${hy[e].fail} ${s} || isNaN(${t})`)}};r1.default=YV;var o1={};Object.defineProperty(o1,"__esModule",{value:!0});const Fd=Ke,JV={message:({schemaCode:n})=>(0,Fd.str)`must be multiple of ${n}`,params:({schemaCode:n})=>(0,Fd._)`{multipleOf: ${n}}`},QV={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:JV,code(n){const{gen:e,data:t,schemaCode:s,it:i}=n,r=i.opts.multipleOfPrecision,o=e.let("res"),a=r?(0,Fd._)`Math.abs(Math.round(${o}) - ${o}) > 1e-${r}`:(0,Fd._)`${o} !== parseInt(${o})`;n.fail$data((0,Fd._)`(${s} === 0 || (${o} = ${t}/${s}, ${a}))`)}};o1.default=QV;var a1={},l1={};Object.defineProperty(l1,"__esModule",{value:!0});function pP(n){const e=n.length;let t=0,s=0,i;for(;s=55296&&i<=56319&&s(0,el._)`{limit: ${n}}`},s3={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:n3,code(n){const{keyword:e,data:t,schemaCode:s,it:i}=n,r=e==="maxLength"?el.operators.GT:el.operators.LT,o=i.opts.unicode===!1?(0,el._)`${t}.length`:(0,el._)`${(0,e3.useFunc)(n.gen,t3.default)}(${t})`;n.fail$data((0,el._)`${o} ${r} ${s}`)}};a1.default=s3;var c1={};Object.defineProperty(c1,"__esModule",{value:!0});const i3=We,r3=fe,nh=Ke,o3={message:({schemaCode:n})=>(0,nh.str)`must match pattern "${n}"`,params:({schemaCode:n})=>(0,nh._)`{pattern: ${n}}`},a3={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:o3,code(n){const{gen:e,data:t,$data:s,schema:i,schemaCode:r,it:o}=n,a=o.opts.unicodeRegExp?"u":"";if(s){const{regExp:l}=o.opts.code,c=l.code==="new RegExp"?(0,nh._)`new RegExp`:(0,r3.useFunc)(e,l),h=e.let("valid");e.try(()=>e.assign(h,(0,nh._)`${c}(${r}, ${a}).test(${t})`),()=>e.assign(h,!1)),n.fail$data((0,nh._)`!${h}`)}else{const l=(0,i3.usePattern)(n,i);n.fail$data((0,nh._)`!${l}.test(${t})`)}}};c1.default=a3;var h1={};Object.defineProperty(h1,"__esModule",{value:!0});const zd=Ke,l3={message({keyword:n,schemaCode:e}){const t=n==="maxProperties"?"more":"fewer";return(0,zd.str)`must NOT have ${t} than ${e} properties`},params:({schemaCode:n})=>(0,zd._)`{limit: ${n}}`},c3={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:l3,code(n){const{keyword:e,data:t,schemaCode:s}=n,i=e==="maxProperties"?zd.operators.GT:zd.operators.LT;n.fail$data((0,zd._)`Object.keys(${t}).length ${i} ${s}`)}};h1.default=c3;var u1={};Object.defineProperty(u1,"__esModule",{value:!0});const ed=We,Hd=Ke,h3=fe,u3={message:({params:{missingProperty:n}})=>(0,Hd.str)`must have required property '${n}'`,params:({params:{missingProperty:n}})=>(0,Hd._)`{missingProperty: ${n}}`},d3={keyword:"required",type:"object",schemaType:"array",$data:!0,error:u3,code(n){const{gen:e,schema:t,schemaCode:s,data:i,$data:r,it:o}=n,{opts:a}=o;if(!r&&t.length===0)return;const l=t.length>=a.loopRequired;if(o.allErrors?c():h(),a.strictRequired){const p=n.parentSchema.properties,{definedProperties:m}=n.it;for(const y of t)if((p==null?void 0:p[y])===void 0&&!m.has(y)){const v=o.schemaEnv.baseId+o.errSchemaPath,g=`required property "${y}" is not defined at "${v}" (strictRequired)`;(0,h3.checkStrictMode)(o,g,o.opts.strictRequired)}}function c(){if(l||r)n.block$data(Hd.nil,u);else for(const p of t)(0,ed.checkReportMissingProp)(n,p)}function h(){const p=e.let("missing");if(l||r){const m=e.let("valid",!0);n.block$data(m,()=>d(p,m)),n.ok(m)}else e.if((0,ed.checkMissingProp)(n,t,p)),(0,ed.reportMissingProp)(n,p),e.else()}function u(){e.forOf("prop",s,p=>{n.setParams({missingProperty:p}),e.if((0,ed.noPropertyInData)(e,i,p,a.ownProperties),()=>n.error())})}function d(p,m){n.setParams({missingProperty:p}),e.forOf(p,s,()=>{e.assign(m,(0,ed.propertyInData)(e,i,p,a.ownProperties)),e.if((0,Hd.not)(m),()=>{n.error(),e.break()})},Hd.nil)}}};u1.default=d3;var d1={};Object.defineProperty(d1,"__esModule",{value:!0});const Bd=Ke,f3={message({keyword:n,schemaCode:e}){const t=n==="maxItems"?"more":"fewer";return(0,Bd.str)`must NOT have ${t} than ${e} items`},params:({schemaCode:n})=>(0,Bd._)`{limit: ${n}}`},p3={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:f3,code(n){const{keyword:e,data:t,schemaCode:s}=n,i=e==="maxItems"?Bd.operators.GT:Bd.operators.LT;n.fail$data((0,Bd._)`${t}.length ${i} ${s}`)}};d1.default=p3;var f1={},Yp={};Object.defineProperty(Yp,"__esModule",{value:!0});const mP=S0;mP.code='require("ajv/dist/runtime/equal").default';Yp.default=mP;Object.defineProperty(f1,"__esModule",{value:!0});const mv=pn,On=Ke,m3=fe,g3=Yp,y3={message:({params:{i:n,j:e}})=>(0,On.str)`must NOT have duplicate items (items ## ${e} and ${n} are identical)`,params:({params:{i:n,j:e}})=>(0,On._)`{i: ${n}, j: ${e}}`},v3={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:y3,code(n){const{gen:e,data:t,$data:s,schema:i,parentSchema:r,schemaCode:o,it:a}=n;if(!s&&!i)return;const l=e.let("valid"),c=r.items?(0,mv.getSchemaTypes)(r.items):[];n.block$data(l,h,(0,On._)`${o} === false`),n.ok(l);function h(){const m=e.let("i",(0,On._)`${t}.length`),y=e.let("j");n.setParams({i:m,j:y}),e.assign(l,!0),e.if((0,On._)`${m} > 1`,()=>(u()?d:p)(m,y))}function u(){return c.length>0&&!c.some(m=>m==="object"||m==="array")}function d(m,y){const v=e.name("item"),g=(0,mv.checkDataTypes)(c,v,a.opts.strictNumbers,mv.DataType.Wrong),b=e.const("indices",(0,On._)`{}`);e.for((0,On._)`;${m}--;`,()=>{e.let(v,(0,On._)`${t}[${m}]`),e.if(g,(0,On._)`continue`),c.length>1&&e.if((0,On._)`typeof ${v} == "string"`,(0,On._)`${v} += "_"`),e.if((0,On._)`typeof ${b}[${v}] == "number"`,()=>{e.assign(y,(0,On._)`${b}[${v}]`),n.error(),e.assign(l,!1).break()}).code((0,On._)`${b}[${v}] = ${m}`)})}function p(m,y){const v=(0,m3.useFunc)(e,g3.default),g=e.name("outer");e.label(g).for((0,On._)`;${m}--;`,()=>e.for((0,On._)`${y} = ${m}; ${y}--;`,()=>e.if((0,On._)`${v}(${t}[${m}], ${t}[${y}])`,()=>{n.error(),e.assign(l,!1).break(g)})))}}};f1.default=v3;var p1={};Object.defineProperty(p1,"__esModule",{value:!0});const vb=Ke,b3=fe,w3=Yp,_3={message:"must be equal to constant",params:({schemaCode:n})=>(0,vb._)`{allowedValue: ${n}}`},S3={keyword:"const",$data:!0,error:_3,code(n){const{gen:e,data:t,$data:s,schemaCode:i,schema:r}=n;s||r&&typeof r=="object"?n.fail$data((0,vb._)`!${(0,b3.useFunc)(e,w3.default)}(${t}, ${i})`):n.fail((0,vb._)`${r} !== ${t}`)}};p1.default=S3;var m1={};Object.defineProperty(m1,"__esModule",{value:!0});const pd=Ke,x3=fe,A3=Yp,k3={message:"must be equal to one of the allowed values",params:({schemaCode:n})=>(0,pd._)`{allowedValues: ${n}}`},E3={keyword:"enum",schemaType:"array",$data:!0,error:k3,code(n){const{gen:e,data:t,$data:s,schema:i,schemaCode:r,it:o}=n;if(!s&&i.length===0)throw new Error("enum must have non-empty array");const a=i.length>=o.opts.loopEnum;let l;const c=()=>l??(l=(0,x3.useFunc)(e,A3.default));let h;if(a||s)h=e.let("valid"),n.block$data(h,u);else{if(!Array.isArray(i))throw new Error("ajv implementation error");const p=e.const("vSchema",r);h=(0,pd.or)(...i.map((m,y)=>d(p,y)))}n.pass(h);function u(){e.assign(h,!1),e.forOf("v",r,p=>e.if((0,pd._)`${c()}(${t}, ${p})`,()=>e.assign(h,!0).break()))}function d(p,m){const y=i[m];return typeof y=="object"&&y!==null?(0,pd._)`${c()}(${t}, ${p}[${m}])`:(0,pd._)`${t} === ${y}`}}};m1.default=E3;Object.defineProperty(i1,"__esModule",{value:!0});const C3=r1,$3=o1,T3=a1,P3=c1,R3=h1,M3=u1,I3=d1,O3=f1,N3=p1,L3=m1,D3=[C3.default,$3.default,T3.default,P3.default,R3.default,M3.default,I3.default,O3.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},N3.default,L3.default];i1.default=D3;var g1={},Du={};Object.defineProperty(Du,"__esModule",{value:!0});Du.validateAdditionalItems=void 0;const tl=Ke,bb=fe,j3={message:({params:{len:n}})=>(0,tl.str)`must NOT have more than ${n} items`,params:({params:{len:n}})=>(0,tl._)`{limit: ${n}}`},F3={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:j3,code(n){const{parentSchema:e,it:t}=n,{items:s}=e;if(!Array.isArray(s)){(0,bb.checkStrictMode)(t,'"additionalItems" is ignored when "items" is not an array of schemas');return}gP(n,s)}};function gP(n,e){const{gen:t,schema:s,data:i,keyword:r,it:o}=n;o.items=!0;const a=t.const("len",(0,tl._)`${i}.length`);if(s===!1)n.setParams({len:e.length}),n.pass((0,tl._)`${a} <= ${e.length}`);else if(typeof s=="object"&&!(0,bb.alwaysValidSchema)(o,s)){const c=t.var("valid",(0,tl._)`${a} <= ${e.length}`);t.if((0,tl.not)(c),()=>l(c)),n.ok(c)}function l(c){t.forRange("i",e.length,a,h=>{n.subschema({keyword:r,dataProp:h,dataPropType:bb.Type.Num},c),o.allErrors||t.if((0,tl.not)(c),()=>t.break())})}}Du.validateAdditionalItems=gP;Du.default=F3;var y1={},ju={};Object.defineProperty(ju,"__esModule",{value:!0});ju.validateTuple=void 0;const ok=Ke,hg=fe,z3=We,H3={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(n){const{schema:e,it:t}=n;if(Array.isArray(e))return yP(n,"additionalItems",e);t.items=!0,!(0,hg.alwaysValidSchema)(t,e)&&n.ok((0,z3.validateArray)(n))}};function yP(n,e,t=n.schema){const{gen:s,parentSchema:i,data:r,keyword:o,it:a}=n;h(i),a.opts.unevaluated&&t.length&&a.items!==!0&&(a.items=hg.mergeEvaluated.items(s,t.length,a.items));const l=s.name("valid"),c=s.const("len",(0,ok._)`${r}.length`);t.forEach((u,d)=>{(0,hg.alwaysValidSchema)(a,u)||(s.if((0,ok._)`${c} > ${d}`,()=>n.subschema({keyword:o,schemaProp:d,dataProp:d},l)),n.ok(l))});function h(u){const{opts:d,errSchemaPath:p}=a,m=t.length,y=m===u.minItems&&(m===u.maxItems||u[e]===!1);if(d.strictTuples&&!y){const v=`"${o}" is ${m}-tuple, but minItems or maxItems/${e} are not specified or different at path "${p}"`;(0,hg.checkStrictMode)(a,v,d.strictTuples)}}}ju.validateTuple=yP;ju.default=H3;Object.defineProperty(y1,"__esModule",{value:!0});const B3=ju,U3={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:n=>(0,B3.validateTuple)(n,"items")};y1.default=U3;var v1={};Object.defineProperty(v1,"__esModule",{value:!0});const ak=Ke,q3=fe,V3=We,W3=Du,G3={message:({params:{len:n}})=>(0,ak.str)`must NOT have more than ${n} items`,params:({params:{len:n}})=>(0,ak._)`{limit: ${n}}`},K3={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:G3,code(n){const{schema:e,parentSchema:t,it:s}=n,{prefixItems:i}=t;s.items=!0,!(0,q3.alwaysValidSchema)(s,e)&&(i?(0,W3.validateAdditionalItems)(n,i):n.ok((0,V3.validateArray)(n)))}};v1.default=K3;var b1={};Object.defineProperty(b1,"__esModule",{value:!0});const fi=Ke,Am=fe,Z3={message:({params:{min:n,max:e}})=>e===void 0?(0,fi.str)`must contain at least ${n} valid item(s)`:(0,fi.str)`must contain at least ${n} and no more than ${e} valid item(s)`,params:({params:{min:n,max:e}})=>e===void 0?(0,fi._)`{minContains: ${n}}`:(0,fi._)`{minContains: ${n}, maxContains: ${e}}`},X3={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:Z3,code(n){const{gen:e,schema:t,parentSchema:s,data:i,it:r}=n;let o,a;const{minContains:l,maxContains:c}=s;r.opts.next?(o=l===void 0?1:l,a=c):o=1;const h=e.const("len",(0,fi._)`${i}.length`);if(n.setParams({min:o,max:a}),a===void 0&&o===0){(0,Am.checkStrictMode)(r,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&o>a){(0,Am.checkStrictMode)(r,'"minContains" > "maxContains" is always invalid'),n.fail();return}if((0,Am.alwaysValidSchema)(r,t)){let y=(0,fi._)`${h} >= ${o}`;a!==void 0&&(y=(0,fi._)`${y} && ${h} <= ${a}`),n.pass(y);return}r.items=!0;const u=e.name("valid");a===void 0&&o===1?p(u,()=>e.if(u,()=>e.break())):o===0?(e.let(u,!0),a!==void 0&&e.if((0,fi._)`${i}.length > 0`,d)):(e.let(u,!1),d()),n.result(u,()=>n.reset());function d(){const y=e.name("_valid"),v=e.let("count",0);p(y,()=>e.if(y,()=>m(v)))}function p(y,v){e.forRange("i",0,h,g=>{n.subschema({keyword:"contains",dataProp:g,dataPropType:Am.Type.Num,compositeRule:!0},y),v()})}function m(y){e.code((0,fi._)`${y}++`),a===void 0?e.if((0,fi._)`${y} >= ${o}`,()=>e.assign(u,!0).break()):(e.if((0,fi._)`${y} > ${a}`,()=>e.assign(u,!1).break()),o===1?e.assign(u,!0):e.if((0,fi._)`${y} >= ${o}`,()=>e.assign(u,!0)))}}};b1.default=X3;var vP={};(function(n){Object.defineProperty(n,"__esModule",{value:!0}),n.validateSchemaDeps=n.validatePropertyDeps=n.error=void 0;const e=Ke,t=fe,s=We;n.error={message:({params:{property:l,depsCount:c,deps:h}})=>{const u=c===1?"property":"properties";return(0,e.str)`must have ${u} ${h} when property ${l} is present`},params:({params:{property:l,depsCount:c,deps:h,missingProperty:u}})=>(0,e._)`{property: ${l}, + missingProperty: ${u}, + depsCount: ${c}, + deps: ${h}}`};const i={keyword:"dependencies",type:"object",schemaType:"object",error:n.error,code(l){const[c,h]=r(l);o(l,c),a(l,h)}};function r({schema:l}){const c={},h={};for(const u in l){if(u==="__proto__")continue;const d=Array.isArray(l[u])?c:h;d[u]=l[u]}return[c,h]}function o(l,c=l.schema){const{gen:h,data:u,it:d}=l;if(Object.keys(c).length===0)return;const p=h.let("missing");for(const m in c){const y=c[m];if(y.length===0)continue;const v=(0,s.propertyInData)(h,u,m,d.opts.ownProperties);l.setParams({property:m,depsCount:y.length,deps:y.join(", ")}),d.allErrors?h.if(v,()=>{for(const g of y)(0,s.checkReportMissingProp)(l,g)}):(h.if((0,e._)`${v} && (${(0,s.checkMissingProp)(l,y,p)})`),(0,s.reportMissingProp)(l,p),h.else())}}n.validatePropertyDeps=o;function a(l,c=l.schema){const{gen:h,data:u,keyword:d,it:p}=l,m=h.name("valid");for(const y in c)(0,t.alwaysValidSchema)(p,c[y])||(h.if((0,s.propertyInData)(h,u,y,p.opts.ownProperties),()=>{const v=l.subschema({keyword:d,schemaProp:y},m);l.mergeValidEvaluated(v,m)},()=>h.var(m,!0)),l.ok(m))}n.validateSchemaDeps=a,n.default=i})(vP);var w1={};Object.defineProperty(w1,"__esModule",{value:!0});const bP=Ke,Y3=fe,J3={message:"property name must be valid",params:({params:n})=>(0,bP._)`{propertyName: ${n.propertyName}}`},Q3={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:J3,code(n){const{gen:e,schema:t,data:s,it:i}=n;if((0,Y3.alwaysValidSchema)(i,t))return;const r=e.name("valid");e.forIn("key",s,o=>{n.setParams({propertyName:o}),n.subschema({keyword:"propertyNames",data:o,dataTypes:["string"],propertyName:o,compositeRule:!0},r),e.if((0,bP.not)(r),()=>{n.error(!0),i.allErrors||e.break()})}),n.ok(r)}};w1.default=Q3;var E0={};Object.defineProperty(E0,"__esModule",{value:!0});const km=We,Ti=Ke,eW=Dr,Em=fe,tW={message:"must NOT have additional properties",params:({params:n})=>(0,Ti._)`{additionalProperty: ${n.additionalProperty}}`},nW={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:tW,code(n){const{gen:e,schema:t,parentSchema:s,data:i,errsCount:r,it:o}=n;if(!r)throw new Error("ajv implementation error");const{allErrors:a,opts:l}=o;if(o.props=!0,l.removeAdditional!=="all"&&(0,Em.alwaysValidSchema)(o,t))return;const c=(0,km.allSchemaProperties)(s.properties),h=(0,km.allSchemaProperties)(s.patternProperties);u(),n.ok((0,Ti._)`${r} === ${eW.default.errors}`);function u(){e.forIn("key",i,v=>{!c.length&&!h.length?m(v):e.if(d(v),()=>m(v))})}function d(v){let g;if(c.length>8){const b=(0,Em.schemaRefOrVal)(o,s.properties,"properties");g=(0,km.isOwnProperty)(e,b,v)}else c.length?g=(0,Ti.or)(...c.map(b=>(0,Ti._)`${v} === ${b}`)):g=Ti.nil;return h.length&&(g=(0,Ti.or)(g,...h.map(b=>(0,Ti._)`${(0,km.usePattern)(n,b)}.test(${v})`))),(0,Ti.not)(g)}function p(v){e.code((0,Ti._)`delete ${i}[${v}]`)}function m(v){if(l.removeAdditional==="all"||l.removeAdditional&&t===!1){p(v);return}if(t===!1){n.setParams({additionalProperty:v}),n.error(),a||e.break();return}if(typeof t=="object"&&!(0,Em.alwaysValidSchema)(o,t)){const g=e.name("valid");l.removeAdditional==="failing"?(y(v,g,!1),e.if((0,Ti.not)(g),()=>{n.reset(),p(v)})):(y(v,g),a||e.if((0,Ti.not)(g),()=>e.break()))}}function y(v,g,b){const _={keyword:"additionalProperties",dataProp:v,dataPropType:Em.Type.Str};b===!1&&Object.assign(_,{compositeRule:!0,createErrors:!1,allErrors:!1}),n.subschema(_,g)}}};E0.default=nW;var _1={};Object.defineProperty(_1,"__esModule",{value:!0});const sW=Yi,lk=We,gv=fe,ck=E0,iW={keyword:"properties",type:"object",schemaType:"object",code(n){const{gen:e,schema:t,parentSchema:s,data:i,it:r}=n;r.opts.removeAdditional==="all"&&s.additionalProperties===void 0&&ck.default.code(new sW.KeywordCxt(r,ck.default,"additionalProperties"));const o=(0,lk.allSchemaProperties)(t);for(const u of o)r.definedProperties.add(u);r.opts.unevaluated&&o.length&&r.props!==!0&&(r.props=gv.mergeEvaluated.props(e,(0,gv.toHash)(o),r.props));const a=o.filter(u=>!(0,gv.alwaysValidSchema)(r,t[u]));if(a.length===0)return;const l=e.name("valid");for(const u of a)c(u)?h(u):(e.if((0,lk.propertyInData)(e,i,u,r.opts.ownProperties)),h(u),r.allErrors||e.else().var(l,!0),e.endIf()),n.it.definedProperties.add(u),n.ok(l);function c(u){return r.opts.useDefaults&&!r.compositeRule&&t[u].default!==void 0}function h(u){n.subschema({keyword:"properties",schemaProp:u,dataProp:u},l)}}};_1.default=iW;var S1={};Object.defineProperty(S1,"__esModule",{value:!0});const hk=We,Cm=Ke,uk=fe,dk=fe,rW={keyword:"patternProperties",type:"object",schemaType:"object",code(n){const{gen:e,schema:t,data:s,parentSchema:i,it:r}=n,{opts:o}=r,a=(0,hk.allSchemaProperties)(t),l=a.filter(y=>(0,uk.alwaysValidSchema)(r,t[y]));if(a.length===0||l.length===a.length&&(!r.opts.unevaluated||r.props===!0))return;const c=o.strictSchema&&!o.allowMatchingProperties&&i.properties,h=e.name("valid");r.props!==!0&&!(r.props instanceof Cm.Name)&&(r.props=(0,dk.evaluatedPropsToName)(e,r.props));const{props:u}=r;d();function d(){for(const y of a)c&&p(y),r.allErrors?m(y):(e.var(h,!0),m(y),e.if(h))}function p(y){for(const v in c)new RegExp(y).test(v)&&(0,uk.checkStrictMode)(r,`property ${v} matches pattern ${y} (use allowMatchingProperties)`)}function m(y){e.forIn("key",s,v=>{e.if((0,Cm._)`${(0,hk.usePattern)(n,y)}.test(${v})`,()=>{const g=l.includes(y);g||n.subschema({keyword:"patternProperties",schemaProp:y,dataProp:v,dataPropType:dk.Type.Str},h),r.opts.unevaluated&&u!==!0?e.assign((0,Cm._)`${u}[${v}]`,!0):!g&&!r.allErrors&&e.if((0,Cm.not)(h),()=>e.break())})})}}};S1.default=rW;var x1={};Object.defineProperty(x1,"__esModule",{value:!0});const oW=fe,aW={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(n){const{gen:e,schema:t,it:s}=n;if((0,oW.alwaysValidSchema)(s,t)){n.fail();return}const i=e.name("valid");n.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},i),n.failResult(i,()=>n.reset(),()=>n.error())},error:{message:"must NOT be valid"}};x1.default=aW;var A1={};Object.defineProperty(A1,"__esModule",{value:!0});const lW=We,cW={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:lW.validateUnion,error:{message:"must match a schema in anyOf"}};A1.default=cW;var k1={};Object.defineProperty(k1,"__esModule",{value:!0});const ug=Ke,hW=fe,uW={message:"must match exactly one schema in oneOf",params:({params:n})=>(0,ug._)`{passingSchemas: ${n.passing}}`},dW={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:uW,code(n){const{gen:e,schema:t,parentSchema:s,it:i}=n;if(!Array.isArray(t))throw new Error("ajv implementation error");if(i.opts.discriminator&&s.discriminator)return;const r=t,o=e.let("valid",!1),a=e.let("passing",null),l=e.name("_valid");n.setParams({passing:a}),e.block(c),n.result(o,()=>n.reset(),()=>n.error(!0));function c(){r.forEach((h,u)=>{let d;(0,hW.alwaysValidSchema)(i,h)?e.var(l,!0):d=n.subschema({keyword:"oneOf",schemaProp:u,compositeRule:!0},l),u>0&&e.if((0,ug._)`${l} && ${o}`).assign(o,!1).assign(a,(0,ug._)`[${a}, ${u}]`).else(),e.if(l,()=>{e.assign(o,!0),e.assign(a,u),d&&n.mergeEvaluated(d,ug.Name)})})}}};k1.default=dW;var E1={};Object.defineProperty(E1,"__esModule",{value:!0});const fW=fe,pW={keyword:"allOf",schemaType:"array",code(n){const{gen:e,schema:t,it:s}=n;if(!Array.isArray(t))throw new Error("ajv implementation error");const i=e.name("valid");t.forEach((r,o)=>{if((0,fW.alwaysValidSchema)(s,r))return;const a=n.subschema({keyword:"allOf",schemaProp:o},i);n.ok(i),n.mergeEvaluated(a)})}};E1.default=pW;var C1={};Object.defineProperty(C1,"__esModule",{value:!0});const uy=Ke,wP=fe,mW={message:({params:n})=>(0,uy.str)`must match "${n.ifClause}" schema`,params:({params:n})=>(0,uy._)`{failingKeyword: ${n.ifClause}}`},gW={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:mW,code(n){const{gen:e,parentSchema:t,it:s}=n;t.then===void 0&&t.else===void 0&&(0,wP.checkStrictMode)(s,'"if" without "then" and "else" is ignored');const i=fk(s,"then"),r=fk(s,"else");if(!i&&!r)return;const o=e.let("valid",!0),a=e.name("_valid");if(l(),n.reset(),i&&r){const h=e.let("ifClause");n.setParams({ifClause:h}),e.if(a,c("then",h),c("else",h))}else i?e.if(a,c("then")):e.if((0,uy.not)(a),c("else"));n.pass(o,()=>n.error(!0));function l(){const h=n.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},a);n.mergeEvaluated(h)}function c(h,u){return()=>{const d=n.subschema({keyword:h},a);e.assign(o,a),n.mergeValidEvaluated(d,o),u?e.assign(u,(0,uy._)`${h}`):n.setParams({ifClause:h})}}}};function fk(n,e){const t=n.schema[e];return t!==void 0&&!(0,wP.alwaysValidSchema)(n,t)}C1.default=gW;var $1={};Object.defineProperty($1,"__esModule",{value:!0});const yW=fe,vW={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:n,parentSchema:e,it:t}){e.if===void 0&&(0,yW.checkStrictMode)(t,`"${n}" without "if" is ignored`)}};$1.default=vW;Object.defineProperty(g1,"__esModule",{value:!0});const bW=Du,wW=y1,_W=ju,SW=v1,xW=b1,AW=vP,kW=w1,EW=E0,CW=_1,$W=S1,TW=x1,PW=A1,RW=k1,MW=E1,IW=C1,OW=$1;function NW(n=!1){const e=[TW.default,PW.default,RW.default,MW.default,IW.default,OW.default,kW.default,EW.default,AW.default,CW.default,$W.default];return n?e.push(wW.default,SW.default):e.push(bW.default,_W.default),e.push(xW.default),e}g1.default=NW;var T1={},P1={};Object.defineProperty(P1,"__esModule",{value:!0});const Kt=Ke,LW={message:({schemaCode:n})=>(0,Kt.str)`must match format "${n}"`,params:({schemaCode:n})=>(0,Kt._)`{format: ${n}}`},DW={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:LW,code(n,e){const{gen:t,data:s,$data:i,schema:r,schemaCode:o,it:a}=n,{opts:l,errSchemaPath:c,schemaEnv:h,self:u}=a;if(!l.validateFormats)return;i?d():p();function d(){const m=t.scopeValue("formats",{ref:u.formats,code:l.code.formats}),y=t.const("fDef",(0,Kt._)`${m}[${o}]`),v=t.let("fType"),g=t.let("format");t.if((0,Kt._)`typeof ${y} == "object" && !(${y} instanceof RegExp)`,()=>t.assign(v,(0,Kt._)`${y}.type || "string"`).assign(g,(0,Kt._)`${y}.validate`),()=>t.assign(v,(0,Kt._)`"string"`).assign(g,y)),n.fail$data((0,Kt.or)(b(),_()));function b(){return l.strictSchema===!1?Kt.nil:(0,Kt._)`${o} && !${g}`}function _(){const x=h.$async?(0,Kt._)`(${y}.async ? await ${g}(${s}) : ${g}(${s}))`:(0,Kt._)`${g}(${s})`,A=(0,Kt._)`(typeof ${g} == "function" ? ${x} : ${g}.test(${s}))`;return(0,Kt._)`${g} && ${g} !== true && ${v} === ${e} && !${A}`}}function p(){const m=u.formats[r];if(!m){b();return}if(m===!0)return;const[y,v,g]=_(m);y===e&&n.pass(x());function b(){if(l.strictSchema===!1){u.logger.warn(A());return}throw new Error(A());function A(){return`unknown format "${r}" ignored in schema at path "${c}"`}}function _(A){const C=A instanceof RegExp?(0,Kt.regexpCode)(A):l.code.formats?(0,Kt._)`${l.code.formats}${(0,Kt.getProperty)(r)}`:void 0,$=t.scopeValue("formats",{key:r,ref:A,code:C});return typeof A=="object"&&!(A instanceof RegExp)?[A.type||"string",A.validate,(0,Kt._)`${$}.validate`]:["string",A,$]}function x(){if(typeof m=="object"&&!(m instanceof RegExp)&&m.async){if(!h.$async)throw new Error("async format in sync schema");return(0,Kt._)`await ${g}(${s})`}return typeof v=="function"?(0,Kt._)`${g}(${s})`:(0,Kt._)`${g}.test(${s})`}}}};P1.default=DW;Object.defineProperty(T1,"__esModule",{value:!0});const jW=P1,FW=[jW.default];T1.default=FW;var wu={};Object.defineProperty(wu,"__esModule",{value:!0});wu.contentVocabulary=wu.metadataVocabulary=void 0;wu.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];wu.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"];Object.defineProperty(t1,"__esModule",{value:!0});const zW=n1,HW=i1,BW=g1,UW=T1,pk=wu,qW=[zW.default,HW.default,(0,BW.default)(),UW.default,pk.metadataVocabulary,pk.contentVocabulary];t1.default=qW;var R1={},C0={};Object.defineProperty(C0,"__esModule",{value:!0});C0.DiscrError=void 0;var mk;(function(n){n.Tag="tag",n.Mapping="mapping"})(mk||(C0.DiscrError=mk={}));Object.defineProperty(R1,"__esModule",{value:!0});const Hc=Ke,wb=C0,gk=Ns,VW=Lu,WW=fe,GW={message:({params:{discrError:n,tagName:e}})=>n===wb.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:n,tag:e,tagName:t}})=>(0,Hc._)`{error: ${n}, tag: ${t}, tagValue: ${e}}`},KW={keyword:"discriminator",type:"object",schemaType:"object",error:GW,code(n){const{gen:e,data:t,schema:s,parentSchema:i,it:r}=n,{oneOf:o}=i;if(!r.opts.discriminator)throw new Error("discriminator: requires discriminator option");const a=s.propertyName;if(typeof a!="string")throw new Error("discriminator: requires propertyName");if(s.mapping)throw new Error("discriminator: mapping is not supported");if(!o)throw new Error("discriminator: requires oneOf keyword");const l=e.let("valid",!1),c=e.const("tag",(0,Hc._)`${t}${(0,Hc.getProperty)(a)}`);e.if((0,Hc._)`typeof ${c} == "string"`,()=>h(),()=>n.error(!1,{discrError:wb.DiscrError.Tag,tag:c,tagName:a})),n.ok(l);function h(){const p=d();e.if(!1);for(const m in p)e.elseIf((0,Hc._)`${c} === ${m}`),e.assign(l,u(p[m]));e.else(),n.error(!1,{discrError:wb.DiscrError.Mapping,tag:c,tagName:a}),e.endIf()}function u(p){const m=e.name("valid"),y=n.subschema({keyword:"oneOf",schemaProp:p},m);return n.mergeEvaluated(y,Hc.Name),m}function d(){var p;const m={},y=g(i);let v=!0;for(let x=0;xthis.addVocabulary(m)),this.opts.discriminator&&this.addKeyword(i.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;const m=this.opts.$data?this.$dataMetaSchema(r,o):r;this.addMetaSchema(m,a,!1),this.refs["http://json-schema.org/schema"]=a}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(a)?a:void 0)}}e.Ajv=l,n.exports=e=l,n.exports.Ajv=l,Object.defineProperty(e,"__esModule",{value:!0}),e.default=l;var c=Yi;Object.defineProperty(e,"KeywordCxt",{enumerable:!0,get:function(){return c.KeywordCxt}});var h=Ke;Object.defineProperty(e,"_",{enumerable:!0,get:function(){return h._}}),Object.defineProperty(e,"str",{enumerable:!0,get:function(){return h.str}}),Object.defineProperty(e,"stringify",{enumerable:!0,get:function(){return h.stringify}}),Object.defineProperty(e,"nil",{enumerable:!0,get:function(){return h.nil}}),Object.defineProperty(e,"Name",{enumerable:!0,get:function(){return h.Name}}),Object.defineProperty(e,"CodeGen",{enumerable:!0,get:function(){return h.CodeGen}});var u=Xp;Object.defineProperty(e,"ValidationError",{enumerable:!0,get:function(){return u.default}});var d=Lu;Object.defineProperty(e,"MissingRefError",{enumerable:!0,get:function(){return d.default}})})(fb,fb.exports);var n4=fb.exports;const s4=tS(n4);var _b={exports:{}},_P={};(function(n){Object.defineProperty(n,"__esModule",{value:!0}),n.formatNames=n.fastFormats=n.fullFormats=void 0;function e(L,B){return{validate:L,compare:B}}n.fullFormats={date:e(r,o),time:e(l(!0),c),"date-time":e(d(!0),p),"iso-time":e(l(),h),"iso-date-time":e(d(),m),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:g,"uri-reference":/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,"uri-template":/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,url:/^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,email:/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,hostname:/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/,ipv6:/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,regex:q,uuid:/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,"json-pointer":/^(?:\/(?:[^~/]|~0|~1)*)*$/,"json-pointer-uri-fragment":/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,"relative-json-pointer":/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,byte:_,int32:{type:"number",validate:C},int64:{type:"number",validate:$},float:{type:"number",validate:I},double:{type:"number",validate:I},password:!0,binary:!0},n.fastFormats={...n.fullFormats,date:e(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,o),time:e(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,c),"date-time":e(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,p),"iso-time":e(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,h),"iso-date-time":e(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,m),uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i},n.formatNames=Object.keys(n.fullFormats);function t(L){return L%4===0&&(L%100!==0||L%400===0)}const s=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,i=[0,31,28,31,30,31,30,31,31,30,31,30,31];function r(L){const B=s.exec(L);if(!B)return!1;const H=+B[1],D=+B[2],X=+B[3];return D>=1&&D<=12&&X>=1&&X<=(D===2&&t(H)?29:i[D])}function o(L,B){if(L&&B)return L>B?1:L23||E>59||L&&!Y)return!1;if(X<=23&&te<=59&&J<60)return!0;const O=te-E*ye,R=X-z*ye-(O<0?1:0);return(R===23||R===-1)&&(O===59||O===-1)&&J<61}}function c(L,B){if(!(L&&B))return;const H=new Date("2020-01-01T"+L).valueOf(),D=new Date("2020-01-01T"+B).valueOf();if(H&&D)return H-D}function h(L,B){if(!(L&&B))return;const H=a.exec(L),D=a.exec(B);if(H&&D)return L=H[1]+H[2]+H[3],B=D[1]+D[2]+D[3],L>B?1:L=x}function $(L){return Number.isInteger(L)}function I(){return!0}const j=/[^\\]\\Z/;function q(L){if(j.test(L))return!1;try{return new RegExp(L),!0}catch{return!1}}})(_P);var SP={},Sb={exports:{}},xP={},Ji={},_u={},Jp={},Be={},cf={};(function(n){Object.defineProperty(n,"__esModule",{value:!0}),n.regexpCode=n.getEsmExportName=n.getProperty=n.safeStringify=n.stringify=n.strConcat=n.addCodeArg=n.str=n._=n.nil=n._Code=n.Name=n.IDENTIFIER=n._CodeOrName=void 0;class e{}n._CodeOrName=e,n.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;class t extends e{constructor(b){if(super(),!n.IDENTIFIER.test(b))throw new Error("CodeGen: name must be a valid identifier");this.str=b}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}}n.Name=t;class s extends e{constructor(b){super(),this._items=typeof b=="string"?[b]:b}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;const b=this._items[0];return b===""||b==='""'}get str(){var b;return(b=this._str)!==null&&b!==void 0?b:this._str=this._items.reduce((_,x)=>`${_}${x}`,"")}get names(){var b;return(b=this._names)!==null&&b!==void 0?b:this._names=this._items.reduce((_,x)=>(x instanceof t&&(_[x.str]=(_[x.str]||0)+1),_),{})}}n._Code=s,n.nil=new s("");function i(g,...b){const _=[g[0]];let x=0;for(;x{if(u.scopePath===void 0)throw new Error(`CodeGen: name "${u}" has no value`);return(0,e._)`${c}${u.scopePath}`})}scopeCode(c=this._values,h,u){return this._reduceValues(c,d=>{if(d.value===void 0)throw new Error(`CodeGen: name "${d}" has no value`);return d.value.code},h,u)}_reduceValues(c,h,u={},d){let p=e.nil;for(const m in c){const y=c[m];if(!y)continue;const v=u[m]=u[m]||new Map;y.forEach(g=>{if(v.has(g))return;v.set(g,s.Started);let b=h(g);if(b){const _=this.opts.es5?n.varKinds.var:n.varKinds.const;p=(0,e._)`${p}${_} ${g} = ${b};${this.opts._n}`}else if(b=d==null?void 0:d(g))p=(0,e._)`${p}${b}${this.opts._n}`;else throw new t(g);v.set(g,s.Completed)})}return p}}n.ValueScope=a})(xb);(function(n){Object.defineProperty(n,"__esModule",{value:!0}),n.or=n.and=n.not=n.CodeGen=n.operators=n.varKinds=n.ValueScopeName=n.ValueScope=n.Scope=n.Name=n.regexpCode=n.stringify=n.getProperty=n.nil=n.strConcat=n.str=n._=void 0;const e=cf,t=xb;var s=cf;Object.defineProperty(n,"_",{enumerable:!0,get:function(){return s._}}),Object.defineProperty(n,"str",{enumerable:!0,get:function(){return s.str}}),Object.defineProperty(n,"strConcat",{enumerable:!0,get:function(){return s.strConcat}}),Object.defineProperty(n,"nil",{enumerable:!0,get:function(){return s.nil}}),Object.defineProperty(n,"getProperty",{enumerable:!0,get:function(){return s.getProperty}}),Object.defineProperty(n,"stringify",{enumerable:!0,get:function(){return s.stringify}}),Object.defineProperty(n,"regexpCode",{enumerable:!0,get:function(){return s.regexpCode}}),Object.defineProperty(n,"Name",{enumerable:!0,get:function(){return s.Name}});var i=xb;Object.defineProperty(n,"Scope",{enumerable:!0,get:function(){return i.Scope}}),Object.defineProperty(n,"ValueScope",{enumerable:!0,get:function(){return i.ValueScope}}),Object.defineProperty(n,"ValueScopeName",{enumerable:!0,get:function(){return i.ValueScopeName}}),Object.defineProperty(n,"varKinds",{enumerable:!0,get:function(){return i.varKinds}}),n.operators={GT:new e._Code(">"),GTE:new e._Code(">="),LT:new e._Code("<"),LTE:new e._Code("<="),EQ:new e._Code("==="),NEQ:new e._Code("!=="),NOT:new e._Code("!"),OR:new e._Code("||"),AND:new e._Code("&&"),ADD:new e._Code("+")};class r{optimizeNodes(){return this}optimizeNames(w,k){return this}}class o extends r{constructor(w,k,N){super(),this.varKind=w,this.name=k,this.rhs=N}render({es5:w,_n:k}){const N=w?t.varKinds.var:this.varKind,G=this.rhs===void 0?"":` = ${this.rhs}`;return`${N} ${this.name}${G};`+k}optimizeNames(w,k){if(w[this.name.str])return this.rhs&&(this.rhs=D(this.rhs,w,k)),this}get names(){return this.rhs instanceof e._CodeOrName?this.rhs.names:{}}}class a extends r{constructor(w,k,N){super(),this.lhs=w,this.rhs=k,this.sideEffects=N}render({_n:w}){return`${this.lhs} = ${this.rhs};`+w}optimizeNames(w,k){if(!(this.lhs instanceof e.Name&&!w[this.lhs.str]&&!this.sideEffects))return this.rhs=D(this.rhs,w,k),this}get names(){const w=this.lhs instanceof e.Name?{}:{...this.lhs.names};return H(w,this.rhs)}}class l extends a{constructor(w,k,N,G){super(w,N,G),this.op=k}render({_n:w}){return`${this.lhs} ${this.op}= ${this.rhs};`+w}}class c extends r{constructor(w){super(),this.label=w,this.names={}}render({_n:w}){return`${this.label}:`+w}}class h extends r{constructor(w){super(),this.label=w,this.names={}}render({_n:w}){return`break${this.label?` ${this.label}`:""};`+w}}class u extends r{constructor(w){super(),this.error=w}render({_n:w}){return`throw ${this.error};`+w}get names(){return this.error.names}}class d extends r{constructor(w){super(),this.code=w}render({_n:w}){return`${this.code};`+w}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(w,k){return this.code=D(this.code,w,k),this}get names(){return this.code instanceof e._CodeOrName?this.code.names:{}}}class p extends r{constructor(w=[]){super(),this.nodes=w}render(w){return this.nodes.reduce((k,N)=>k+N.render(w),"")}optimizeNodes(){const{nodes:w}=this;let k=w.length;for(;k--;){const N=w[k].optimizeNodes();Array.isArray(N)?w.splice(k,1,...N):N?w[k]=N:w.splice(k,1)}return w.length>0?this:void 0}optimizeNames(w,k){const{nodes:N}=this;let G=N.length;for(;G--;){const Z=N[G];Z.optimizeNames(w,k)||(X(w,Z.names),N.splice(G,1))}return N.length>0?this:void 0}get names(){return this.nodes.reduce((w,k)=>B(w,k.names),{})}}class m extends p{render(w){return"{"+w._n+super.render(w)+"}"+w._n}}class y extends p{}class v extends m{}v.kind="else";class g extends m{constructor(w,k){super(k),this.condition=w}render(w){let k=`if(${this.condition})`+super.render(w);return this.else&&(k+="else "+this.else.render(w)),k}optimizeNodes(){super.optimizeNodes();const w=this.condition;if(w===!0)return this.nodes;let k=this.else;if(k){const N=k.optimizeNodes();k=this.else=Array.isArray(N)?new v(N):N}if(k)return w===!1?k instanceof g?k:k.nodes:this.nodes.length?this:new g(te(w),k instanceof g?[k]:k.nodes);if(!(w===!1||!this.nodes.length))return this}optimizeNames(w,k){var N;if(this.else=(N=this.else)===null||N===void 0?void 0:N.optimizeNames(w,k),!!(super.optimizeNames(w,k)||this.else))return this.condition=D(this.condition,w,k),this}get names(){const w=super.names;return H(w,this.condition),this.else&&B(w,this.else.names),w}}g.kind="if";class b extends m{}b.kind="for";class _ extends b{constructor(w){super(),this.iteration=w}render(w){return`for(${this.iteration})`+super.render(w)}optimizeNames(w,k){if(super.optimizeNames(w,k))return this.iteration=D(this.iteration,w,k),this}get names(){return B(super.names,this.iteration.names)}}class x extends b{constructor(w,k,N,G){super(),this.varKind=w,this.name=k,this.from=N,this.to=G}render(w){const k=w.es5?t.varKinds.var:this.varKind,{name:N,from:G,to:Z}=this;return`for(${k} ${N}=${G}; ${N}<${Z}; ${N}++)`+super.render(w)}get names(){const w=H(super.names,this.from);return H(w,this.to)}}class A extends b{constructor(w,k,N,G){super(),this.loop=w,this.varKind=k,this.name=N,this.iterable=G}render(w){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(w)}optimizeNames(w,k){if(super.optimizeNames(w,k))return this.iterable=D(this.iterable,w,k),this}get names(){return B(super.names,this.iterable.names)}}class C extends m{constructor(w,k,N){super(),this.name=w,this.args=k,this.async=N}render(w){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(w)}}C.kind="func";class $ extends p{render(w){return"return "+super.render(w)}}$.kind="return";class I extends m{render(w){let k="try"+super.render(w);return this.catch&&(k+=this.catch.render(w)),this.finally&&(k+=this.finally.render(w)),k}optimizeNodes(){var w,k;return super.optimizeNodes(),(w=this.catch)===null||w===void 0||w.optimizeNodes(),(k=this.finally)===null||k===void 0||k.optimizeNodes(),this}optimizeNames(w,k){var N,G;return super.optimizeNames(w,k),(N=this.catch)===null||N===void 0||N.optimizeNames(w,k),(G=this.finally)===null||G===void 0||G.optimizeNames(w,k),this}get names(){const w=super.names;return this.catch&&B(w,this.catch.names),this.finally&&B(w,this.finally.names),w}}class j extends m{constructor(w){super(),this.error=w}render(w){return`catch(${this.error})`+super.render(w)}}j.kind="catch";class q extends m{render(w){return"finally"+super.render(w)}}q.kind="finally";class L{constructor(w,k={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...k,_n:k.lines?` +`:""},this._extScope=w,this._scope=new t.Scope({parent:w}),this._nodes=[new y]}toString(){return this._root.render(this.opts)}name(w){return this._scope.name(w)}scopeName(w){return this._extScope.name(w)}scopeValue(w,k){const N=this._extScope.value(w,k);return(this._values[N.prefix]||(this._values[N.prefix]=new Set)).add(N),N}getScopeValue(w,k){return this._extScope.getValue(w,k)}scopeRefs(w){return this._extScope.scopeRefs(w,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(w,k,N,G){const Z=this._scope.toName(k);return N!==void 0&&G&&(this._constants[Z.str]=N),this._leafNode(new o(w,Z,N)),Z}const(w,k,N){return this._def(t.varKinds.const,w,k,N)}let(w,k,N){return this._def(t.varKinds.let,w,k,N)}var(w,k,N){return this._def(t.varKinds.var,w,k,N)}assign(w,k,N){return this._leafNode(new a(w,k,N))}add(w,k){return this._leafNode(new l(w,n.operators.ADD,k))}code(w){return typeof w=="function"?w():w!==e.nil&&this._leafNode(new d(w)),this}object(...w){const k=["{"];for(const[N,G]of w)k.length>1&&k.push(","),k.push(N),(N!==G||this.opts.es5)&&(k.push(":"),(0,e.addCodeArg)(k,G));return k.push("}"),new e._Code(k)}if(w,k,N){if(this._blockNode(new g(w)),k&&N)this.code(k).else().code(N).endIf();else if(k)this.code(k).endIf();else if(N)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(w){return this._elseNode(new g(w))}else(){return this._elseNode(new v)}endIf(){return this._endBlockNode(g,v)}_for(w,k){return this._blockNode(w),k&&this.code(k).endFor(),this}for(w,k){return this._for(new _(w),k)}forRange(w,k,N,G,Z=this.opts.es5?t.varKinds.var:t.varKinds.let){const ae=this._scope.toName(w);return this._for(new x(Z,ae,k,N),()=>G(ae))}forOf(w,k,N,G=t.varKinds.const){const Z=this._scope.toName(w);if(this.opts.es5){const ae=k instanceof e.Name?k:this.var("_arr",k);return this.forRange("_i",0,(0,e._)`${ae}.length`,ie=>{this.var(Z,(0,e._)`${ae}[${ie}]`),N(Z)})}return this._for(new A("of",G,Z,k),()=>N(Z))}forIn(w,k,N,G=this.opts.es5?t.varKinds.var:t.varKinds.const){if(this.opts.ownProperties)return this.forOf(w,(0,e._)`Object.keys(${k})`,N);const Z=this._scope.toName(w);return this._for(new A("in",G,Z,k),()=>N(Z))}endFor(){return this._endBlockNode(b)}label(w){return this._leafNode(new c(w))}break(w){return this._leafNode(new h(w))}return(w){const k=new $;if(this._blockNode(k),this.code(w),k.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode($)}try(w,k,N){if(!k&&!N)throw new Error('CodeGen: "try" without "catch" and "finally"');const G=new I;if(this._blockNode(G),this.code(w),k){const Z=this.name("e");this._currNode=G.catch=new j(Z),k(Z)}return N&&(this._currNode=G.finally=new q,this.code(N)),this._endBlockNode(j,q)}throw(w){return this._leafNode(new u(w))}block(w,k){return this._blockStarts.push(this._nodes.length),w&&this.code(w).endBlock(k),this}endBlock(w){const k=this._blockStarts.pop();if(k===void 0)throw new Error("CodeGen: not in self-balancing block");const N=this._nodes.length-k;if(N<0||w!==void 0&&N!==w)throw new Error(`CodeGen: wrong number of nodes: ${N} vs ${w} expected`);return this._nodes.length=k,this}func(w,k=e.nil,N,G){return this._blockNode(new C(w,k,N)),G&&this.code(G).endFunc(),this}endFunc(){return this._endBlockNode(C)}optimize(w=1){for(;w-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(w){return this._currNode.nodes.push(w),this}_blockNode(w){this._currNode.nodes.push(w),this._nodes.push(w)}_endBlockNode(w,k){const N=this._currNode;if(N instanceof w||k&&N instanceof k)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${k?`${w.kind}/${k.kind}`:w.kind}"`)}_elseNode(w){const k=this._currNode;if(!(k instanceof g))throw new Error('CodeGen: "else" without "if"');return this._currNode=k.else=w,this}get _root(){return this._nodes[0]}get _currNode(){const w=this._nodes;return w[w.length-1]}set _currNode(w){const k=this._nodes;k[k.length-1]=w}}n.CodeGen=L;function B(R,w){for(const k in w)R[k]=(R[k]||0)+(w[k]||0);return R}function H(R,w){return w instanceof e._CodeOrName?B(R,w.names):R}function D(R,w,k){if(R instanceof e.Name)return N(R);if(!G(R))return R;return new e._Code(R._items.reduce((Z,ae)=>(ae instanceof e.Name&&(ae=N(ae)),ae instanceof e._Code?Z.push(...ae._items):Z.push(ae),Z),[]));function N(Z){const ae=k[Z.str];return ae===void 0||w[Z.str]!==1?Z:(delete w[Z.str],ae)}function G(Z){return Z instanceof e._Code&&Z._items.some(ae=>ae instanceof e.Name&&w[ae.str]===1&&k[ae.str]!==void 0)}}function X(R,w){for(const k in w)R[k]=(R[k]||0)-(w[k]||0)}function te(R){return typeof R=="boolean"||typeof R=="number"||R===null?!R:(0,e._)`!${O(R)}`}n.not=te;const J=E(n.operators.AND);function Y(...R){return R.reduce(J)}n.and=Y;const ye=E(n.operators.OR);function z(...R){return R.reduce(ye)}n.or=z;function E(R){return(w,k)=>w===e.nil?k:k===e.nil?w:(0,e._)`${O(w)} ${R} ${O(k)}`}function O(R){return R instanceof e.Name?R:(0,e._)`(${R})`}})(Be);var pe={};Object.defineProperty(pe,"__esModule",{value:!0});pe.checkStrictMode=pe.getErrorPath=pe.Type=pe.useFunc=pe.setEvaluated=pe.evaluatedPropsToName=pe.mergeEvaluated=pe.eachItem=pe.unescapeJsonPointer=pe.escapeJsonPointer=pe.escapeFragment=pe.unescapeFragment=pe.schemaRefOrVal=pe.schemaHasRulesButRef=pe.schemaHasRules=pe.checkUnknownRules=pe.alwaysValidSchema=pe.toHash=void 0;const bt=Be,i4=cf;function r4(n){const e={};for(const t of n)e[t]=!0;return e}pe.toHash=r4;function o4(n,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(AP(n,e),!kP(e,n.self.RULES.all))}pe.alwaysValidSchema=o4;function AP(n,e=n.schema){const{opts:t,self:s}=n;if(!t.strictSchema||typeof e=="boolean")return;const i=s.RULES.keywords;for(const r in e)i[r]||$P(n,`unknown keyword: "${r}"`)}pe.checkUnknownRules=AP;function kP(n,e){if(typeof n=="boolean")return!n;for(const t in n)if(e[t])return!0;return!1}pe.schemaHasRules=kP;function a4(n,e){if(typeof n=="boolean")return!n;for(const t in n)if(t!=="$ref"&&e.all[t])return!0;return!1}pe.schemaHasRulesButRef=a4;function l4({topSchemaRef:n,schemaPath:e},t,s,i){if(!i){if(typeof t=="number"||typeof t=="boolean")return t;if(typeof t=="string")return(0,bt._)`${t}`}return(0,bt._)`${n}${e}${(0,bt.getProperty)(s)}`}pe.schemaRefOrVal=l4;function c4(n){return EP(decodeURIComponent(n))}pe.unescapeFragment=c4;function h4(n){return encodeURIComponent(M1(n))}pe.escapeFragment=h4;function M1(n){return typeof n=="number"?`${n}`:n.replace(/~/g,"~0").replace(/\//g,"~1")}pe.escapeJsonPointer=M1;function EP(n){return n.replace(/~1/g,"/").replace(/~0/g,"~")}pe.unescapeJsonPointer=EP;function u4(n,e){if(Array.isArray(n))for(const t of n)e(t);else e(n)}pe.eachItem=u4;function yk({mergeNames:n,mergeToName:e,mergeValues:t,resultToName:s}){return(i,r,o,a)=>{const l=o===void 0?r:o instanceof bt.Name?(r instanceof bt.Name?n(i,r,o):e(i,r,o),o):r instanceof bt.Name?(e(i,o,r),r):t(r,o);return a===bt.Name&&!(l instanceof bt.Name)?s(i,l):l}}pe.mergeEvaluated={props:yk({mergeNames:(n,e,t)=>n.if((0,bt._)`${t} !== true && ${e} !== undefined`,()=>{n.if((0,bt._)`${e} === true`,()=>n.assign(t,!0),()=>n.assign(t,(0,bt._)`${t} || {}`).code((0,bt._)`Object.assign(${t}, ${e})`))}),mergeToName:(n,e,t)=>n.if((0,bt._)`${t} !== true`,()=>{e===!0?n.assign(t,!0):(n.assign(t,(0,bt._)`${t} || {}`),I1(n,t,e))}),mergeValues:(n,e)=>n===!0?!0:{...n,...e},resultToName:CP}),items:yk({mergeNames:(n,e,t)=>n.if((0,bt._)`${t} !== true && ${e} !== undefined`,()=>n.assign(t,(0,bt._)`${e} === true ? true : ${t} > ${e} ? ${t} : ${e}`)),mergeToName:(n,e,t)=>n.if((0,bt._)`${t} !== true`,()=>n.assign(t,e===!0?!0:(0,bt._)`${t} > ${e} ? ${t} : ${e}`)),mergeValues:(n,e)=>n===!0?!0:Math.max(n,e),resultToName:(n,e)=>n.var("items",e)})};function CP(n,e){if(e===!0)return n.var("props",!0);const t=n.var("props",(0,bt._)`{}`);return e!==void 0&&I1(n,t,e),t}pe.evaluatedPropsToName=CP;function I1(n,e,t){Object.keys(t).forEach(s=>n.assign((0,bt._)`${e}${(0,bt.getProperty)(s)}`,!0))}pe.setEvaluated=I1;const vk={};function d4(n,e){return n.scopeValue("func",{ref:e,code:vk[e.code]||(vk[e.code]=new i4._Code(e.code))})}pe.useFunc=d4;var Ab;(function(n){n[n.Num=0]="Num",n[n.Str=1]="Str"})(Ab||(pe.Type=Ab={}));function f4(n,e,t){if(n instanceof bt.Name){const s=e===Ab.Num;return t?s?(0,bt._)`"[" + ${n} + "]"`:(0,bt._)`"['" + ${n} + "']"`:s?(0,bt._)`"/" + ${n}`:(0,bt._)`"/" + ${n}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return t?(0,bt.getProperty)(n).toString():"/"+M1(n)}pe.getErrorPath=f4;function $P(n,e,t=n.opts.strictSchema){if(t){if(e=`strict mode: ${e}`,t===!0)throw new Error(e);n.self.logger.warn(e)}}pe.checkStrictMode=$P;var jr={};Object.defineProperty(jr,"__esModule",{value:!0});const Qn=Be,p4={data:new Qn.Name("data"),valCxt:new Qn.Name("valCxt"),instancePath:new Qn.Name("instancePath"),parentData:new Qn.Name("parentData"),parentDataProperty:new Qn.Name("parentDataProperty"),rootData:new Qn.Name("rootData"),dynamicAnchors:new Qn.Name("dynamicAnchors"),vErrors:new Qn.Name("vErrors"),errors:new Qn.Name("errors"),this:new Qn.Name("this"),self:new Qn.Name("self"),scope:new Qn.Name("scope"),json:new Qn.Name("json"),jsonPos:new Qn.Name("jsonPos"),jsonLen:new Qn.Name("jsonLen"),jsonPart:new Qn.Name("jsonPart")};jr.default=p4;(function(n){Object.defineProperty(n,"__esModule",{value:!0}),n.extendErrors=n.resetErrorsCount=n.reportExtraError=n.reportError=n.keyword$DataError=n.keywordError=void 0;const e=Be,t=pe,s=jr;n.keywordError={message:({keyword:v})=>(0,e.str)`must pass "${v}" keyword validation`},n.keyword$DataError={message:({keyword:v,schemaType:g})=>g?(0,e.str)`"${v}" keyword must be ${g} ($data)`:(0,e.str)`"${v}" keyword is invalid ($data)`};function i(v,g=n.keywordError,b,_){const{it:x}=v,{gen:A,compositeRule:C,allErrors:$}=x,I=u(v,g,b);_??(C||$)?l(A,I):c(x,(0,e._)`[${I}]`)}n.reportError=i;function r(v,g=n.keywordError,b){const{it:_}=v,{gen:x,compositeRule:A,allErrors:C}=_,$=u(v,g,b);l(x,$),A||C||c(_,s.default.vErrors)}n.reportExtraError=r;function o(v,g){v.assign(s.default.errors,g),v.if((0,e._)`${s.default.vErrors} !== null`,()=>v.if(g,()=>v.assign((0,e._)`${s.default.vErrors}.length`,g),()=>v.assign(s.default.vErrors,null)))}n.resetErrorsCount=o;function a({gen:v,keyword:g,schemaValue:b,data:_,errsCount:x,it:A}){if(x===void 0)throw new Error("ajv implementation error");const C=v.name("err");v.forRange("i",x,s.default.errors,$=>{v.const(C,(0,e._)`${s.default.vErrors}[${$}]`),v.if((0,e._)`${C}.instancePath === undefined`,()=>v.assign((0,e._)`${C}.instancePath`,(0,e.strConcat)(s.default.instancePath,A.errorPath))),v.assign((0,e._)`${C}.schemaPath`,(0,e.str)`${A.errSchemaPath}/${g}`),A.opts.verbose&&(v.assign((0,e._)`${C}.schema`,b),v.assign((0,e._)`${C}.data`,_))})}n.extendErrors=a;function l(v,g){const b=v.const("err",g);v.if((0,e._)`${s.default.vErrors} === null`,()=>v.assign(s.default.vErrors,(0,e._)`[${b}]`),(0,e._)`${s.default.vErrors}.push(${b})`),v.code((0,e._)`${s.default.errors}++`)}function c(v,g){const{gen:b,validateName:_,schemaEnv:x}=v;x.$async?b.throw((0,e._)`new ${v.ValidationError}(${g})`):(b.assign((0,e._)`${_}.errors`,g),b.return(!1))}const h={keyword:new e.Name("keyword"),schemaPath:new e.Name("schemaPath"),params:new e.Name("params"),propertyName:new e.Name("propertyName"),message:new e.Name("message"),schema:new e.Name("schema"),parentSchema:new e.Name("parentSchema")};function u(v,g,b){const{createErrors:_}=v.it;return _===!1?(0,e._)`{}`:d(v,g,b)}function d(v,g,b={}){const{gen:_,it:x}=v,A=[p(x,b),m(v,b)];return y(v,g,A),_.object(...A)}function p({errorPath:v},{instancePath:g}){const b=g?(0,e.str)`${v}${(0,t.getErrorPath)(g,t.Type.Str)}`:v;return[s.default.instancePath,(0,e.strConcat)(s.default.instancePath,b)]}function m({keyword:v,it:{errSchemaPath:g}},{schemaPath:b,parentSchema:_}){let x=_?g:(0,e.str)`${g}/${v}`;return b&&(x=(0,e.str)`${x}${(0,t.getErrorPath)(b,t.Type.Str)}`),[h.schemaPath,x]}function y(v,{params:g,message:b},_){const{keyword:x,data:A,schemaValue:C,it:$}=v,{opts:I,propertyName:j,topSchemaRef:q,schemaPath:L}=$;_.push([h.keyword,x],[h.params,typeof g=="function"?g(v):g||(0,e._)`{}`]),I.messages&&_.push([h.message,typeof b=="function"?b(v):b]),I.verbose&&_.push([h.schema,C],[h.parentSchema,(0,e._)`${q}${L}`],[s.default.data,A]),j&&_.push([h.propertyName,j])}})(Jp);Object.defineProperty(_u,"__esModule",{value:!0});_u.boolOrEmptySchema=_u.topBoolOrEmptySchema=void 0;const m4=Jp,g4=Be,y4=jr,v4={message:"boolean schema is false"};function b4(n){const{gen:e,schema:t,validateName:s}=n;t===!1?TP(n,!1):typeof t=="object"&&t.$async===!0?e.return(y4.default.data):(e.assign((0,g4._)`${s}.errors`,null),e.return(!0))}_u.topBoolOrEmptySchema=b4;function w4(n,e){const{gen:t,schema:s}=n;s===!1?(t.var(e,!1),TP(n)):t.var(e,!0)}_u.boolOrEmptySchema=w4;function TP(n,e){const{gen:t,data:s}=n,i={gen:t,keyword:"false schema",data:s,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:n};(0,m4.reportError)(i,v4,void 0,e)}var mn={},dc={};Object.defineProperty(dc,"__esModule",{value:!0});dc.getRules=dc.isJSONType=void 0;const _4=["string","number","integer","boolean","null","object","array"],S4=new Set(_4);function x4(n){return typeof n=="string"&&S4.has(n)}dc.isJSONType=x4;function A4(){const n={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...n,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},n.number,n.string,n.array,n.object],post:{rules:[]},all:{},keywords:{}}}dc.getRules=A4;var So={};Object.defineProperty(So,"__esModule",{value:!0});So.shouldUseRule=So.shouldUseGroup=So.schemaHasRulesForType=void 0;function k4({schema:n,self:e},t){const s=e.RULES.types[t];return s&&s!==!0&&PP(n,s)}So.schemaHasRulesForType=k4;function PP(n,e){return e.rules.some(t=>RP(n,t))}So.shouldUseGroup=PP;function RP(n,e){var t;return n[e.keyword]!==void 0||((t=e.definition.implements)===null||t===void 0?void 0:t.some(s=>n[s]!==void 0))}So.shouldUseRule=RP;Object.defineProperty(mn,"__esModule",{value:!0});mn.reportTypeError=mn.checkDataTypes=mn.checkDataType=mn.coerceAndCheckDataType=mn.getJSONTypes=mn.getSchemaTypes=mn.DataType=void 0;const E4=dc,C4=So,$4=Jp,Le=Be,MP=pe;var ch;(function(n){n[n.Correct=0]="Correct",n[n.Wrong=1]="Wrong"})(ch||(mn.DataType=ch={}));function T4(n){const e=IP(n.type);if(e.includes("null")){if(n.nullable===!1)throw new Error("type: null contradicts nullable: false")}else{if(!e.length&&n.nullable!==void 0)throw new Error('"nullable" cannot be used without "type"');n.nullable===!0&&e.push("null")}return e}mn.getSchemaTypes=T4;function IP(n){const e=Array.isArray(n)?n:n?[n]:[];if(e.every(E4.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}mn.getJSONTypes=IP;function P4(n,e){const{gen:t,data:s,opts:i}=n,r=R4(e,i.coerceTypes),o=e.length>0&&!(r.length===0&&e.length===1&&(0,C4.schemaHasRulesForType)(n,e[0]));if(o){const a=O1(e,s,i.strictNumbers,ch.Wrong);t.if(a,()=>{r.length?M4(n,e,r):N1(n)})}return o}mn.coerceAndCheckDataType=P4;const OP=new Set(["string","number","integer","boolean","null"]);function R4(n,e){return e?n.filter(t=>OP.has(t)||e==="array"&&t==="array"):[]}function M4(n,e,t){const{gen:s,data:i,opts:r}=n,o=s.let("dataType",(0,Le._)`typeof ${i}`),a=s.let("coerced",(0,Le._)`undefined`);r.coerceTypes==="array"&&s.if((0,Le._)`${o} == 'object' && Array.isArray(${i}) && ${i}.length == 1`,()=>s.assign(i,(0,Le._)`${i}[0]`).assign(o,(0,Le._)`typeof ${i}`).if(O1(e,i,r.strictNumbers),()=>s.assign(a,i))),s.if((0,Le._)`${a} !== undefined`);for(const c of t)(OP.has(c)||c==="array"&&r.coerceTypes==="array")&&l(c);s.else(),N1(n),s.endIf(),s.if((0,Le._)`${a} !== undefined`,()=>{s.assign(i,a),I4(n,a)});function l(c){switch(c){case"string":s.elseIf((0,Le._)`${o} == "number" || ${o} == "boolean"`).assign(a,(0,Le._)`"" + ${i}`).elseIf((0,Le._)`${i} === null`).assign(a,(0,Le._)`""`);return;case"number":s.elseIf((0,Le._)`${o} == "boolean" || ${i} === null + || (${o} == "string" && ${i} && ${i} == +${i})`).assign(a,(0,Le._)`+${i}`);return;case"integer":s.elseIf((0,Le._)`${o} === "boolean" || ${i} === null + || (${o} === "string" && ${i} && ${i} == +${i} && !(${i} % 1))`).assign(a,(0,Le._)`+${i}`);return;case"boolean":s.elseIf((0,Le._)`${i} === "false" || ${i} === 0 || ${i} === null`).assign(a,!1).elseIf((0,Le._)`${i} === "true" || ${i} === 1`).assign(a,!0);return;case"null":s.elseIf((0,Le._)`${i} === "" || ${i} === 0 || ${i} === false`),s.assign(a,null);return;case"array":s.elseIf((0,Le._)`${o} === "string" || ${o} === "number" + || ${o} === "boolean" || ${i} === null`).assign(a,(0,Le._)`[${i}]`)}}}function I4({gen:n,parentData:e,parentDataProperty:t},s){n.if((0,Le._)`${e} !== undefined`,()=>n.assign((0,Le._)`${e}[${t}]`,s))}function kb(n,e,t,s=ch.Correct){const i=s===ch.Correct?Le.operators.EQ:Le.operators.NEQ;let r;switch(n){case"null":return(0,Le._)`${e} ${i} null`;case"array":r=(0,Le._)`Array.isArray(${e})`;break;case"object":r=(0,Le._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case"integer":r=o((0,Le._)`!(${e} % 1) && !isNaN(${e})`);break;case"number":r=o();break;default:return(0,Le._)`typeof ${e} ${i} ${n}`}return s===ch.Correct?r:(0,Le.not)(r);function o(a=Le.nil){return(0,Le.and)((0,Le._)`typeof ${e} == "number"`,a,t?(0,Le._)`isFinite(${e})`:Le.nil)}}mn.checkDataType=kb;function O1(n,e,t,s){if(n.length===1)return kb(n[0],e,t,s);let i;const r=(0,MP.toHash)(n);if(r.array&&r.object){const o=(0,Le._)`typeof ${e} != "object"`;i=r.null?o:(0,Le._)`!${e} || ${o}`,delete r.null,delete r.array,delete r.object}else i=Le.nil;r.number&&delete r.integer;for(const o in r)i=(0,Le.and)(i,kb(o,e,t,s));return i}mn.checkDataTypes=O1;const O4={message:({schema:n})=>`must be ${n}`,params:({schema:n,schemaValue:e})=>typeof n=="string"?(0,Le._)`{type: ${n}}`:(0,Le._)`{type: ${e}}`};function N1(n){const e=N4(n);(0,$4.reportError)(e,O4)}mn.reportTypeError=N1;function N4(n){const{gen:e,data:t,schema:s}=n,i=(0,MP.schemaRefOrVal)(n,s,"type");return{gen:e,keyword:"type",data:t,schema:s.type,schemaCode:i,schemaValue:i,parentSchema:s,params:{},it:n}}var $0={};Object.defineProperty($0,"__esModule",{value:!0});$0.assignDefaults=void 0;const Dc=Be,L4=pe;function D4(n,e){const{properties:t,items:s}=n.schema;if(e==="object"&&t)for(const i in t)bk(n,i,t[i].default);else e==="array"&&Array.isArray(s)&&s.forEach((i,r)=>bk(n,r,i.default))}$0.assignDefaults=D4;function bk(n,e,t){const{gen:s,compositeRule:i,data:r,opts:o}=n;if(t===void 0)return;const a=(0,Dc._)`${r}${(0,Dc.getProperty)(e)}`;if(i){(0,L4.checkStrictMode)(n,`default is ignored for: ${a}`);return}let l=(0,Dc._)`${a} === undefined`;o.useDefaults==="empty"&&(l=(0,Dc._)`${l} || ${a} === null || ${a} === ""`),s.if(l,(0,Dc._)`${a} = ${(0,Dc.stringify)(t)}`)}var Pr={},Ge={};Object.defineProperty(Ge,"__esModule",{value:!0});Ge.validateUnion=Ge.validateArray=Ge.usePattern=Ge.callValidateCode=Ge.schemaProperties=Ge.allSchemaProperties=Ge.noPropertyInData=Ge.propertyInData=Ge.isOwnProperty=Ge.hasPropFunc=Ge.reportMissingProp=Ge.checkMissingProp=Ge.checkReportMissingProp=void 0;const $t=Be,L1=pe,No=jr,j4=pe;function F4(n,e){const{gen:t,data:s,it:i}=n;t.if(j1(t,s,e,i.opts.ownProperties),()=>{n.setParams({missingProperty:(0,$t._)`${e}`},!0),n.error()})}Ge.checkReportMissingProp=F4;function z4({gen:n,data:e,it:{opts:t}},s,i){return(0,$t.or)(...s.map(r=>(0,$t.and)(j1(n,e,r,t.ownProperties),(0,$t._)`${i} = ${r}`)))}Ge.checkMissingProp=z4;function H4(n,e){n.setParams({missingProperty:e},!0),n.error()}Ge.reportMissingProp=H4;function NP(n){return n.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,$t._)`Object.prototype.hasOwnProperty`})}Ge.hasPropFunc=NP;function D1(n,e,t){return(0,$t._)`${NP(n)}.call(${e}, ${t})`}Ge.isOwnProperty=D1;function B4(n,e,t,s){const i=(0,$t._)`${e}${(0,$t.getProperty)(t)} !== undefined`;return s?(0,$t._)`${i} && ${D1(n,e,t)}`:i}Ge.propertyInData=B4;function j1(n,e,t,s){const i=(0,$t._)`${e}${(0,$t.getProperty)(t)} === undefined`;return s?(0,$t.or)(i,(0,$t.not)(D1(n,e,t))):i}Ge.noPropertyInData=j1;function LP(n){return n?Object.keys(n).filter(e=>e!=="__proto__"):[]}Ge.allSchemaProperties=LP;function U4(n,e){return LP(e).filter(t=>!(0,L1.alwaysValidSchema)(n,e[t]))}Ge.schemaProperties=U4;function q4({schemaCode:n,data:e,it:{gen:t,topSchemaRef:s,schemaPath:i,errorPath:r},it:o},a,l,c){const h=c?(0,$t._)`${n}, ${e}, ${s}${i}`:e,u=[[No.default.instancePath,(0,$t.strConcat)(No.default.instancePath,r)],[No.default.parentData,o.parentData],[No.default.parentDataProperty,o.parentDataProperty],[No.default.rootData,No.default.rootData]];o.opts.dynamicRef&&u.push([No.default.dynamicAnchors,No.default.dynamicAnchors]);const d=(0,$t._)`${h}, ${t.object(...u)}`;return l!==$t.nil?(0,$t._)`${a}.call(${l}, ${d})`:(0,$t._)`${a}(${d})`}Ge.callValidateCode=q4;const V4=(0,$t._)`new RegExp`;function W4({gen:n,it:{opts:e}},t){const s=e.unicodeRegExp?"u":"",{regExp:i}=e.code,r=i(t,s);return n.scopeValue("pattern",{key:r.toString(),ref:r,code:(0,$t._)`${i.code==="new RegExp"?V4:(0,j4.useFunc)(n,i)}(${t}, ${s})`})}Ge.usePattern=W4;function G4(n){const{gen:e,data:t,keyword:s,it:i}=n,r=e.name("valid");if(i.allErrors){const a=e.let("valid",!0);return o(()=>e.assign(a,!1)),a}return e.var(r,!0),o(()=>e.break()),r;function o(a){const l=e.const("len",(0,$t._)`${t}.length`);e.forRange("i",0,l,c=>{n.subschema({keyword:s,dataProp:c,dataPropType:L1.Type.Num},r),e.if((0,$t.not)(r),a)})}}Ge.validateArray=G4;function K4(n){const{gen:e,schema:t,keyword:s,it:i}=n;if(!Array.isArray(t))throw new Error("ajv implementation error");if(t.some(l=>(0,L1.alwaysValidSchema)(i,l))&&!i.opts.unevaluated)return;const o=e.let("valid",!1),a=e.name("_valid");e.block(()=>t.forEach((l,c)=>{const h=n.subschema({keyword:s,schemaProp:c,compositeRule:!0},a);e.assign(o,(0,$t._)`${o} || ${a}`),n.mergeValidEvaluated(h,a)||e.if((0,$t.not)(o))})),n.result(o,()=>n.reset(),()=>n.error(!0))}Ge.validateUnion=K4;Object.defineProperty(Pr,"__esModule",{value:!0});Pr.validateKeywordUsage=Pr.validSchemaType=Pr.funcKeywordCode=Pr.macroKeywordCode=void 0;const gs=Be,nl=jr,Z4=Ge,X4=Jp;function Y4(n,e){const{gen:t,keyword:s,schema:i,parentSchema:r,it:o}=n,a=e.macro.call(o.self,i,r,o),l=DP(t,s,a);o.opts.validateSchema!==!1&&o.self.validateSchema(a,!0);const c=t.name("valid");n.subschema({schema:a,schemaPath:gs.nil,errSchemaPath:`${o.errSchemaPath}/${s}`,topSchemaRef:l,compositeRule:!0},c),n.pass(c,()=>n.error(!0))}Pr.macroKeywordCode=Y4;function J4(n,e){var t;const{gen:s,keyword:i,schema:r,parentSchema:o,$data:a,it:l}=n;e5(l,e);const c=!a&&e.compile?e.compile.call(l.self,r,o,l):e.validate,h=DP(s,i,c),u=s.let("valid");n.block$data(u,d),n.ok((t=e.valid)!==null&&t!==void 0?t:u);function d(){if(e.errors===!1)y(),e.modifying&&wk(n),v(()=>n.error());else{const g=e.async?p():m();e.modifying&&wk(n),v(()=>Q4(n,g))}}function p(){const g=s.let("ruleErrs",null);return s.try(()=>y((0,gs._)`await `),b=>s.assign(u,!1).if((0,gs._)`${b} instanceof ${l.ValidationError}`,()=>s.assign(g,(0,gs._)`${b}.errors`),()=>s.throw(b))),g}function m(){const g=(0,gs._)`${h}.errors`;return s.assign(g,null),y(gs.nil),g}function y(g=e.async?(0,gs._)`await `:gs.nil){const b=l.opts.passContext?nl.default.this:nl.default.self,_=!("compile"in e&&!a||e.schema===!1);s.assign(u,(0,gs._)`${g}${(0,Z4.callValidateCode)(n,h,b,_)}`,e.modifying)}function v(g){var b;s.if((0,gs.not)((b=e.valid)!==null&&b!==void 0?b:u),g)}}Pr.funcKeywordCode=J4;function wk(n){const{gen:e,data:t,it:s}=n;e.if(s.parentData,()=>e.assign(t,(0,gs._)`${s.parentData}[${s.parentDataProperty}]`))}function Q4(n,e){const{gen:t}=n;t.if((0,gs._)`Array.isArray(${e})`,()=>{t.assign(nl.default.vErrors,(0,gs._)`${nl.default.vErrors} === null ? ${e} : ${nl.default.vErrors}.concat(${e})`).assign(nl.default.errors,(0,gs._)`${nl.default.vErrors}.length`),(0,X4.extendErrors)(n)},()=>n.error())}function e5({schemaEnv:n},e){if(e.async&&!n.$async)throw new Error("async keyword in sync schema")}function DP(n,e,t){if(t===void 0)throw new Error(`keyword "${e}" failed to compile`);return n.scopeValue("keyword",typeof t=="function"?{ref:t}:{ref:t,code:(0,gs.stringify)(t)})}function t5(n,e,t=!1){return!e.length||e.some(s=>s==="array"?Array.isArray(n):s==="object"?n&&typeof n=="object"&&!Array.isArray(n):typeof n==s||t&&typeof n>"u")}Pr.validSchemaType=t5;function n5({schema:n,opts:e,self:t,errSchemaPath:s},i,r){if(Array.isArray(i.keyword)?!i.keyword.includes(r):i.keyword!==r)throw new Error("ajv implementation error");const o=i.dependencies;if(o!=null&&o.some(a=>!Object.prototype.hasOwnProperty.call(n,a)))throw new Error(`parent schema must have dependencies of ${r}: ${o.join(",")}`);if(i.validateSchema&&!i.validateSchema(n[r])){const l=`keyword "${r}" value is invalid at path "${s}": `+t.errorsText(i.validateSchema.errors);if(e.validateSchema==="log")t.logger.error(l);else throw new Error(l)}}Pr.validateKeywordUsage=n5;var ka={};Object.defineProperty(ka,"__esModule",{value:!0});ka.extendSubschemaMode=ka.extendSubschemaData=ka.getSubschema=void 0;const Er=Be,jP=pe;function s5(n,{keyword:e,schemaProp:t,schema:s,schemaPath:i,errSchemaPath:r,topSchemaRef:o}){if(e!==void 0&&s!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(e!==void 0){const a=n.schema[e];return t===void 0?{schema:a,schemaPath:(0,Er._)`${n.schemaPath}${(0,Er.getProperty)(e)}`,errSchemaPath:`${n.errSchemaPath}/${e}`}:{schema:a[t],schemaPath:(0,Er._)`${n.schemaPath}${(0,Er.getProperty)(e)}${(0,Er.getProperty)(t)}`,errSchemaPath:`${n.errSchemaPath}/${e}/${(0,jP.escapeFragment)(t)}`}}if(s!==void 0){if(i===void 0||r===void 0||o===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:s,schemaPath:i,topSchemaRef:o,errSchemaPath:r}}throw new Error('either "keyword" or "schema" must be passed')}ka.getSubschema=s5;function i5(n,e,{dataProp:t,dataPropType:s,data:i,dataTypes:r,propertyName:o}){if(i!==void 0&&t!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');const{gen:a}=e;if(t!==void 0){const{errorPath:c,dataPathArr:h,opts:u}=e,d=a.let("data",(0,Er._)`${e.data}${(0,Er.getProperty)(t)}`,!0);l(d),n.errorPath=(0,Er.str)`${c}${(0,jP.getErrorPath)(t,s,u.jsPropertySyntax)}`,n.parentDataProperty=(0,Er._)`${t}`,n.dataPathArr=[...h,n.parentDataProperty]}if(i!==void 0){const c=i instanceof Er.Name?i:a.let("data",i,!0);l(c),o!==void 0&&(n.propertyName=o)}r&&(n.dataTypes=r);function l(c){n.data=c,n.dataLevel=e.dataLevel+1,n.dataTypes=[],e.definedProperties=new Set,n.parentData=e.data,n.dataNames=[...e.dataNames,c]}}ka.extendSubschemaData=i5;function r5(n,{jtdDiscriminator:e,jtdMetadata:t,compositeRule:s,createErrors:i,allErrors:r}){s!==void 0&&(n.compositeRule=s),i!==void 0&&(n.createErrors=i),r!==void 0&&(n.allErrors=r),n.jtdDiscriminator=e,n.jtdMetadata=t}ka.extendSubschemaMode=r5;var Un={},FP={exports:{}},wa=FP.exports=function(n,e,t){typeof e=="function"&&(t=e,e={}),t=e.cb||t;var s=typeof t=="function"?t:t.pre||function(){},i=t.post||function(){};dg(e,s,i,n,"",n)};wa.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};wa.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};wa.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};wa.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0};function dg(n,e,t,s,i,r,o,a,l,c){if(s&&typeof s=="object"&&!Array.isArray(s)){e(s,i,r,o,a,l,c);for(var h in s){var u=s[h];if(Array.isArray(u)){if(h in wa.arrayKeywords)for(var d=0;de+=zP(s)),e===1/0))return 1/0}return e}function HP(n,e="",t){t!==!1&&(e=hh(e));const s=n.parse(e);return BP(n,s)}Un.getFullPath=HP;function BP(n,e){return n.serialize(e).split("#")[0]+"#"}Un._getFullPath=BP;const p5=/#\/?$/;function hh(n){return n?n.replace(p5,""):""}Un.normalizeId=hh;function m5(n,e,t){return t=hh(t),n.resolve(e,t)}Un.resolveUrl=m5;const g5=/^[a-z_][-a-z0-9._]*$/i;function y5(n,e){if(typeof n=="boolean")return{};const{schemaId:t,uriResolver:s}=this.opts,i=hh(n[t]||e),r={"":i},o=HP(s,i,!1),a={},l=new Set;return h5(n,{allKeys:!0},(u,d,p,m)=>{if(m===void 0)return;const y=o+d;let v=r[m];typeof u[t]=="string"&&(v=g.call(this,u[t])),b.call(this,u.$anchor),b.call(this,u.$dynamicAnchor),r[d]=v;function g(_){const x=this.opts.uriResolver.resolve;if(_=hh(v?x(v,_):_),l.has(_))throw h(_);l.add(_);let A=this.refs[_];return typeof A=="string"&&(A=this.refs[A]),typeof A=="object"?c(u,A.schema,_):_!==hh(y)&&(_[0]==="#"?(c(u,a[_],_),a[_]=u):this.refs[_]=y),_}function b(_){if(typeof _=="string"){if(!g5.test(_))throw new Error(`invalid anchor "${_}"`);g.call(this,`#${_}`)}}}),a;function c(u,d,p){if(d!==void 0&&!c5(u,d))throw h(p)}function h(u){return new Error(`reference "${u}" resolves to more than one schema`)}}Un.getSchemaRefs=y5;Object.defineProperty(Ji,"__esModule",{value:!0});Ji.getData=Ji.KeywordCxt=Ji.validateFunctionCode=void 0;const UP=_u,_k=mn,F1=So,dy=mn,v5=$0,Ud=Pr,yv=ka,_e=Be,$e=jr,b5=Un,xo=pe,td=Jp;function w5(n){if(WP(n)&&(GP(n),VP(n))){x5(n);return}qP(n,()=>(0,UP.topBoolOrEmptySchema)(n))}Ji.validateFunctionCode=w5;function qP({gen:n,validateName:e,schema:t,schemaEnv:s,opts:i},r){i.code.es5?n.func(e,(0,_e._)`${$e.default.data}, ${$e.default.valCxt}`,s.$async,()=>{n.code((0,_e._)`"use strict"; ${Sk(t,i)}`),S5(n,i),n.code(r)}):n.func(e,(0,_e._)`${$e.default.data}, ${_5(i)}`,s.$async,()=>n.code(Sk(t,i)).code(r))}function _5(n){return(0,_e._)`{${$e.default.instancePath}="", ${$e.default.parentData}, ${$e.default.parentDataProperty}, ${$e.default.rootData}=${$e.default.data}${n.dynamicRef?(0,_e._)`, ${$e.default.dynamicAnchors}={}`:_e.nil}}={}`}function S5(n,e){n.if($e.default.valCxt,()=>{n.var($e.default.instancePath,(0,_e._)`${$e.default.valCxt}.${$e.default.instancePath}`),n.var($e.default.parentData,(0,_e._)`${$e.default.valCxt}.${$e.default.parentData}`),n.var($e.default.parentDataProperty,(0,_e._)`${$e.default.valCxt}.${$e.default.parentDataProperty}`),n.var($e.default.rootData,(0,_e._)`${$e.default.valCxt}.${$e.default.rootData}`),e.dynamicRef&&n.var($e.default.dynamicAnchors,(0,_e._)`${$e.default.valCxt}.${$e.default.dynamicAnchors}`)},()=>{n.var($e.default.instancePath,(0,_e._)`""`),n.var($e.default.parentData,(0,_e._)`undefined`),n.var($e.default.parentDataProperty,(0,_e._)`undefined`),n.var($e.default.rootData,$e.default.data),e.dynamicRef&&n.var($e.default.dynamicAnchors,(0,_e._)`{}`)})}function x5(n){const{schema:e,opts:t,gen:s}=n;qP(n,()=>{t.$comment&&e.$comment&&ZP(n),$5(n),s.let($e.default.vErrors,null),s.let($e.default.errors,0),t.unevaluated&&A5(n),KP(n),R5(n)})}function A5(n){const{gen:e,validateName:t}=n;n.evaluated=e.const("evaluated",(0,_e._)`${t}.evaluated`),e.if((0,_e._)`${n.evaluated}.dynamicProps`,()=>e.assign((0,_e._)`${n.evaluated}.props`,(0,_e._)`undefined`)),e.if((0,_e._)`${n.evaluated}.dynamicItems`,()=>e.assign((0,_e._)`${n.evaluated}.items`,(0,_e._)`undefined`))}function Sk(n,e){const t=typeof n=="object"&&n[e.schemaId];return t&&(e.code.source||e.code.process)?(0,_e._)`/*# sourceURL=${t} */`:_e.nil}function k5(n,e){if(WP(n)&&(GP(n),VP(n))){E5(n,e);return}(0,UP.boolOrEmptySchema)(n,e)}function VP({schema:n,self:e}){if(typeof n=="boolean")return!n;for(const t in n)if(e.RULES.all[t])return!0;return!1}function WP(n){return typeof n.schema!="boolean"}function E5(n,e){const{schema:t,gen:s,opts:i}=n;i.$comment&&t.$comment&&ZP(n),T5(n),P5(n);const r=s.const("_errs",$e.default.errors);KP(n,r),s.var(e,(0,_e._)`${r} === ${$e.default.errors}`)}function GP(n){(0,xo.checkUnknownRules)(n),C5(n)}function KP(n,e){if(n.opts.jtd)return xk(n,[],!1,e);const t=(0,_k.getSchemaTypes)(n.schema),s=(0,_k.coerceAndCheckDataType)(n,t);xk(n,t,!s,e)}function C5(n){const{schema:e,errSchemaPath:t,opts:s,self:i}=n;e.$ref&&s.ignoreKeywordsWithRef&&(0,xo.schemaHasRulesButRef)(e,i.RULES)&&i.logger.warn(`$ref: keywords ignored in schema at path "${t}"`)}function $5(n){const{schema:e,opts:t}=n;e.default!==void 0&&t.useDefaults&&t.strictSchema&&(0,xo.checkStrictMode)(n,"default is ignored in the schema root")}function T5(n){const e=n.schema[n.opts.schemaId];e&&(n.baseId=(0,b5.resolveUrl)(n.opts.uriResolver,n.baseId,e))}function P5(n){if(n.schema.$async&&!n.schemaEnv.$async)throw new Error("async schema in sync schema")}function ZP({gen:n,schemaEnv:e,schema:t,errSchemaPath:s,opts:i}){const r=t.$comment;if(i.$comment===!0)n.code((0,_e._)`${$e.default.self}.logger.log(${r})`);else if(typeof i.$comment=="function"){const o=(0,_e.str)`${s}/$comment`,a=n.scopeValue("root",{ref:e.root});n.code((0,_e._)`${$e.default.self}.opts.$comment(${r}, ${o}, ${a}.schema)`)}}function R5(n){const{gen:e,schemaEnv:t,validateName:s,ValidationError:i,opts:r}=n;t.$async?e.if((0,_e._)`${$e.default.errors} === 0`,()=>e.return($e.default.data),()=>e.throw((0,_e._)`new ${i}(${$e.default.vErrors})`)):(e.assign((0,_e._)`${s}.errors`,$e.default.vErrors),r.unevaluated&&M5(n),e.return((0,_e._)`${$e.default.errors} === 0`))}function M5({gen:n,evaluated:e,props:t,items:s}){t instanceof _e.Name&&n.assign((0,_e._)`${e}.props`,t),s instanceof _e.Name&&n.assign((0,_e._)`${e}.items`,s)}function xk(n,e,t,s){const{gen:i,schema:r,data:o,allErrors:a,opts:l,self:c}=n,{RULES:h}=c;if(r.$ref&&(l.ignoreKeywordsWithRef||!(0,xo.schemaHasRulesButRef)(r,h))){i.block(()=>JP(n,"$ref",h.all.$ref.definition));return}l.jtd||I5(n,e),i.block(()=>{for(const d of h.rules)u(d);u(h.post)});function u(d){(0,F1.shouldUseGroup)(r,d)&&(d.type?(i.if((0,dy.checkDataType)(d.type,o,l.strictNumbers)),Ak(n,d),e.length===1&&e[0]===d.type&&t&&(i.else(),(0,dy.reportTypeError)(n)),i.endIf()):Ak(n,d),a||i.if((0,_e._)`${$e.default.errors} === ${s||0}`))}}function Ak(n,e){const{gen:t,schema:s,opts:{useDefaults:i}}=n;i&&(0,v5.assignDefaults)(n,e.type),t.block(()=>{for(const r of e.rules)(0,F1.shouldUseRule)(s,r)&&JP(n,r.keyword,r.definition,e.type)})}function I5(n,e){n.schemaEnv.meta||!n.opts.strictTypes||(O5(n,e),n.opts.allowUnionTypes||N5(n,e),L5(n,n.dataTypes))}function O5(n,e){if(e.length){if(!n.dataTypes.length){n.dataTypes=e;return}e.forEach(t=>{XP(n.dataTypes,t)||z1(n,`type "${t}" not allowed by context "${n.dataTypes.join(",")}"`)}),j5(n,e)}}function N5(n,e){e.length>1&&!(e.length===2&&e.includes("null"))&&z1(n,"use allowUnionTypes to allow union type keyword")}function L5(n,e){const t=n.self.RULES.all;for(const s in t){const i=t[s];if(typeof i=="object"&&(0,F1.shouldUseRule)(n.schema,i)){const{type:r}=i.definition;r.length&&!r.some(o=>D5(e,o))&&z1(n,`missing type "${r.join(",")}" for keyword "${s}"`)}}}function D5(n,e){return n.includes(e)||e==="number"&&n.includes("integer")}function XP(n,e){return n.includes(e)||e==="integer"&&n.includes("number")}function j5(n,e){const t=[];for(const s of n.dataTypes)XP(e,s)?t.push(s):e.includes("integer")&&s==="number"&&t.push("integer");n.dataTypes=t}function z1(n,e){const t=n.schemaEnv.baseId+n.errSchemaPath;e+=` at "${t}" (strictTypes)`,(0,xo.checkStrictMode)(n,e,n.opts.strictTypes)}class YP{constructor(e,t,s){if((0,Ud.validateKeywordUsage)(e,t,s),this.gen=e.gen,this.allErrors=e.allErrors,this.keyword=s,this.data=e.data,this.schema=e.schema[s],this.$data=t.$data&&e.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,xo.schemaRefOrVal)(e,this.schema,s,this.$data),this.schemaType=t.schemaType,this.parentSchema=e.schema,this.params={},this.it=e,this.def=t,this.$data)this.schemaCode=e.gen.const("vSchema",QP(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,Ud.validSchemaType)(this.schema,t.schemaType,t.allowUndefined))throw new Error(`${s} value must be ${JSON.stringify(t.schemaType)}`);("code"in t?t.trackErrors:t.errors!==!1)&&(this.errsCount=e.gen.const("_errs",$e.default.errors))}result(e,t,s){this.failResult((0,_e.not)(e),t,s)}failResult(e,t,s){this.gen.if(e),s?s():this.error(),t?(this.gen.else(),t(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(e,t){this.failResult((0,_e.not)(e),void 0,t)}fail(e){if(e===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(e),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(e){if(!this.$data)return this.fail(e);const{schemaCode:t}=this;this.fail((0,_e._)`${t} !== undefined && (${(0,_e.or)(this.invalid$data(),e)})`)}error(e,t,s){if(t){this.setParams(t),this._error(e,s),this.setParams({});return}this._error(e,s)}_error(e,t){(e?td.reportExtraError:td.reportError)(this,this.def.error,t)}$dataError(){(0,td.reportError)(this,this.def.$dataError||td.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,td.resetErrorsCount)(this.gen,this.errsCount)}ok(e){this.allErrors||this.gen.if(e)}setParams(e,t){t?Object.assign(this.params,e):this.params=e}block$data(e,t,s=_e.nil){this.gen.block(()=>{this.check$data(e,s),t()})}check$data(e=_e.nil,t=_e.nil){if(!this.$data)return;const{gen:s,schemaCode:i,schemaType:r,def:o}=this;s.if((0,_e.or)((0,_e._)`${i} === undefined`,t)),e!==_e.nil&&s.assign(e,!0),(r.length||o.validateSchema)&&(s.elseIf(this.invalid$data()),this.$dataError(),e!==_e.nil&&s.assign(e,!1)),s.else()}invalid$data(){const{gen:e,schemaCode:t,schemaType:s,def:i,it:r}=this;return(0,_e.or)(o(),a());function o(){if(s.length){if(!(t instanceof _e.Name))throw new Error("ajv implementation error");const l=Array.isArray(s)?s:[s];return(0,_e._)`${(0,dy.checkDataTypes)(l,t,r.opts.strictNumbers,dy.DataType.Wrong)}`}return _e.nil}function a(){if(i.validateSchema){const l=e.scopeValue("validate$data",{ref:i.validateSchema});return(0,_e._)`!${l}(${t})`}return _e.nil}}subschema(e,t){const s=(0,yv.getSubschema)(this.it,e);(0,yv.extendSubschemaData)(s,this.it,e),(0,yv.extendSubschemaMode)(s,e);const i={...this.it,...s,items:void 0,props:void 0};return k5(i,t),i}mergeEvaluated(e,t){const{it:s,gen:i}=this;s.opts.unevaluated&&(s.props!==!0&&e.props!==void 0&&(s.props=xo.mergeEvaluated.props(i,e.props,s.props,t)),s.items!==!0&&e.items!==void 0&&(s.items=xo.mergeEvaluated.items(i,e.items,s.items,t)))}mergeValidEvaluated(e,t){const{it:s,gen:i}=this;if(s.opts.unevaluated&&(s.props!==!0||s.items!==!0))return i.if(t,()=>this.mergeEvaluated(e,_e.Name)),!0}}Ji.KeywordCxt=YP;function JP(n,e,t,s){const i=new YP(n,t,e);"code"in t?t.code(i,s):i.$data&&t.validate?(0,Ud.funcKeywordCode)(i,t):"macro"in t?(0,Ud.macroKeywordCode)(i,t):(t.compile||t.validate)&&(0,Ud.funcKeywordCode)(i,t)}const F5=/^\/(?:[^~]|~0|~1)*$/,z5=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function QP(n,{dataLevel:e,dataNames:t,dataPathArr:s}){let i,r;if(n==="")return $e.default.rootData;if(n[0]==="/"){if(!F5.test(n))throw new Error(`Invalid JSON-pointer: ${n}`);i=n,r=$e.default.rootData}else{const c=z5.exec(n);if(!c)throw new Error(`Invalid JSON-pointer: ${n}`);const h=+c[1];if(i=c[2],i==="#"){if(h>=e)throw new Error(l("property/index",h));return s[e-h]}if(h>e)throw new Error(l("data",h));if(r=t[e-h],!i)return r}let o=r;const a=i.split("/");for(const c of a)c&&(r=(0,_e._)`${r}${(0,_e.getProperty)((0,xo.unescapeJsonPointer)(c))}`,o=(0,_e._)`${o} && ${r}`);return o;function l(c,h){return`Cannot access ${c} ${h} levels up, current level is ${e}`}}Ji.getData=QP;var Qp={};Object.defineProperty(Qp,"__esModule",{value:!0});class H5 extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}}Qp.default=H5;var Fu={};Object.defineProperty(Fu,"__esModule",{value:!0});const vv=Un;class B5 extends Error{constructor(e,t,s,i){super(i||`can't resolve reference ${s} from id ${t}`),this.missingRef=(0,vv.resolveUrl)(e,t,s),this.missingSchema=(0,vv.normalizeId)((0,vv.getFullPath)(e,this.missingRef))}}Fu.default=B5;var Ls={};Object.defineProperty(Ls,"__esModule",{value:!0});Ls.resolveSchema=Ls.getCompilingSchema=Ls.resolveRef=Ls.compileSchema=Ls.SchemaEnv=void 0;const $i=Be,U5=Qp,Ba=jr,Gi=Un,kk=pe,q5=Ji;class T0{constructor(e){var t;this.refs={},this.dynamicAnchors={};let s;typeof e.schema=="object"&&(s=e.schema),this.schema=e.schema,this.schemaId=e.schemaId,this.root=e.root||this,this.baseId=(t=e.baseId)!==null&&t!==void 0?t:(0,Gi.normalizeId)(s==null?void 0:s[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=s==null?void 0:s.$async,this.refs={}}}Ls.SchemaEnv=T0;function H1(n){const e=eR.call(this,n);if(e)return e;const t=(0,Gi.getFullPath)(this.opts.uriResolver,n.root.baseId),{es5:s,lines:i}=this.opts.code,{ownProperties:r}=this.opts,o=new $i.CodeGen(this.scope,{es5:s,lines:i,ownProperties:r});let a;n.$async&&(a=o.scopeValue("Error",{ref:U5.default,code:(0,$i._)`require("ajv/dist/runtime/validation_error").default`}));const l=o.scopeName("validate");n.validateName=l;const c={gen:o,allErrors:this.opts.allErrors,data:Ba.default.data,parentData:Ba.default.parentData,parentDataProperty:Ba.default.parentDataProperty,dataNames:[Ba.default.data],dataPathArr:[$i.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:o.scopeValue("schema",this.opts.code.source===!0?{ref:n.schema,code:(0,$i.stringify)(n.schema)}:{ref:n.schema}),validateName:l,ValidationError:a,schema:n.schema,schemaEnv:n,rootId:t,baseId:n.baseId||t,schemaPath:$i.nil,errSchemaPath:n.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,$i._)`""`,opts:this.opts,self:this};let h;try{this._compilations.add(n),(0,q5.validateFunctionCode)(c),o.optimize(this.opts.code.optimize);const u=o.toString();h=`${o.scopeRefs(Ba.default.scope)}return ${u}`,this.opts.code.process&&(h=this.opts.code.process(h,n));const p=new Function(`${Ba.default.self}`,`${Ba.default.scope}`,h)(this,this.scope.get());if(this.scope.value(l,{ref:p}),p.errors=null,p.schema=n.schema,p.schemaEnv=n,n.$async&&(p.$async=!0),this.opts.code.source===!0&&(p.source={validateName:l,validateCode:u,scopeValues:o._values}),this.opts.unevaluated){const{props:m,items:y}=c;p.evaluated={props:m instanceof $i.Name?void 0:m,items:y instanceof $i.Name?void 0:y,dynamicProps:m instanceof $i.Name,dynamicItems:y instanceof $i.Name},p.source&&(p.source.evaluated=(0,$i.stringify)(p.evaluated))}return n.validate=p,n}catch(u){throw delete n.validate,delete n.validateName,h&&this.logger.error("Error compiling schema, function code:",h),u}finally{this._compilations.delete(n)}}Ls.compileSchema=H1;function V5(n,e,t){var s;t=(0,Gi.resolveUrl)(this.opts.uriResolver,e,t);const i=n.refs[t];if(i)return i;let r=K5.call(this,n,t);if(r===void 0){const o=(s=n.localRefs)===null||s===void 0?void 0:s[t],{schemaId:a}=this.opts;o&&(r=new T0({schema:o,schemaId:a,root:n,baseId:e}))}if(r!==void 0)return n.refs[t]=W5.call(this,r)}Ls.resolveRef=V5;function W5(n){return(0,Gi.inlineRef)(n.schema,this.opts.inlineRefs)?n.schema:n.validate?n:H1.call(this,n)}function eR(n){for(const e of this._compilations)if(G5(e,n))return e}Ls.getCompilingSchema=eR;function G5(n,e){return n.schema===e.schema&&n.root===e.root&&n.baseId===e.baseId}function K5(n,e){let t;for(;typeof(t=this.refs[e])=="string";)e=t;return t||this.schemas[e]||P0.call(this,n,e)}function P0(n,e){const t=this.opts.uriResolver.parse(e),s=(0,Gi._getFullPath)(this.opts.uriResolver,t);let i=(0,Gi.getFullPath)(this.opts.uriResolver,n.baseId,void 0);if(Object.keys(n.schema).length>0&&s===i)return bv.call(this,t,n);const r=(0,Gi.normalizeId)(s),o=this.refs[r]||this.schemas[r];if(typeof o=="string"){const a=P0.call(this,n,o);return typeof(a==null?void 0:a.schema)!="object"?void 0:bv.call(this,t,a)}if(typeof(o==null?void 0:o.schema)=="object"){if(o.validate||H1.call(this,o),r===(0,Gi.normalizeId)(e)){const{schema:a}=o,{schemaId:l}=this.opts,c=a[l];return c&&(i=(0,Gi.resolveUrl)(this.opts.uriResolver,i,c)),new T0({schema:a,schemaId:l,root:n,baseId:i})}return bv.call(this,t,o)}}Ls.resolveSchema=P0;const Z5=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function bv(n,{baseId:e,schema:t,root:s}){var i;if(((i=n.fragment)===null||i===void 0?void 0:i[0])!=="/")return;for(const a of n.fragment.slice(1).split("/")){if(typeof t=="boolean")return;const l=t[(0,kk.unescapeFragment)(a)];if(l===void 0)return;t=l;const c=typeof t=="object"&&t[this.opts.schemaId];!Z5.has(a)&&c&&(e=(0,Gi.resolveUrl)(this.opts.uriResolver,e,c))}let r;if(typeof t!="boolean"&&t.$ref&&!(0,kk.schemaHasRulesButRef)(t,this.RULES)){const a=(0,Gi.resolveUrl)(this.opts.uriResolver,e,t.$ref);r=P0.call(this,s,a)}const{schemaId:o}=this.opts;if(r=r||new T0({schema:t,schemaId:o,root:s,baseId:e}),r.schema!==r.root.schema)return r}const X5="https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",Y5="Meta-schema for $data reference (JSON AnySchema extension proposal)",J5="object",Q5=["$data"],eG={$data:{type:"string",anyOf:[{format:"relative-json-pointer"},{format:"json-pointer"}]}},tG=!1,nG={$id:X5,description:Y5,type:J5,required:Q5,properties:eG,additionalProperties:tG};var B1={};Object.defineProperty(B1,"__esModule",{value:!0});const tR=uP;tR.code='require("ajv/dist/runtime/uri").default';B1.default=tR;(function(n){Object.defineProperty(n,"__esModule",{value:!0}),n.CodeGen=n.Name=n.nil=n.stringify=n.str=n._=n.KeywordCxt=void 0;var e=Ji;Object.defineProperty(n,"KeywordCxt",{enumerable:!0,get:function(){return e.KeywordCxt}});var t=Be;Object.defineProperty(n,"_",{enumerable:!0,get:function(){return t._}}),Object.defineProperty(n,"str",{enumerable:!0,get:function(){return t.str}}),Object.defineProperty(n,"stringify",{enumerable:!0,get:function(){return t.stringify}}),Object.defineProperty(n,"nil",{enumerable:!0,get:function(){return t.nil}}),Object.defineProperty(n,"Name",{enumerable:!0,get:function(){return t.Name}}),Object.defineProperty(n,"CodeGen",{enumerable:!0,get:function(){return t.CodeGen}});const s=Qp,i=Fu,r=dc,o=Ls,a=Be,l=Un,c=mn,h=pe,u=nG,d=B1,p=(z,E)=>new RegExp(z,E);p.code="new RegExp";const m=["removeAdditional","useDefaults","coerceTypes"],y=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),v={errorDataPath:"",format:"`validateFormats: false` can be used instead.",nullable:'"nullable" keyword is supported by default.',jsonPointers:"Deprecated jsPropertySyntax can be used instead.",extendRefs:"Deprecated ignoreKeywordsWithRef can be used instead.",missingRefs:"Pass empty schema with $id that should be ignored to ajv.addSchema.",processCode:"Use option `code: {process: (code, schemaEnv: object) => string}`",sourceCode:"Use option `code: {source: true}`",strictDefaults:"It is default now, see option `strict`.",strictKeywords:"It is default now, see option `strict`.",uniqueItems:'"uniqueItems" keyword is always validated.',unknownFormats:"Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",cache:"Map is used as cache, schema object as key.",serialize:"Map is used as cache, schema object as key.",ajvErrors:"It is default now."},g={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},b=200;function _(z){var E,O,R,w,k,N,G,Z,ae,ie,Ae,ct,Ie,Fe,Je,st,tn,Pn,Et,As,Rn,ks,hs,us,Es;const ln=z.strict,cn=(E=z.code)===null||E===void 0?void 0:E.optimize,Mn=cn===!0||cn===void 0?1:cn||0,Xn=(R=(O=z.code)===null||O===void 0?void 0:O.regExp)!==null&&R!==void 0?R:p,Yn=(w=z.uriResolver)!==null&&w!==void 0?w:d.default;return{strictSchema:(N=(k=z.strictSchema)!==null&&k!==void 0?k:ln)!==null&&N!==void 0?N:!0,strictNumbers:(Z=(G=z.strictNumbers)!==null&&G!==void 0?G:ln)!==null&&Z!==void 0?Z:!0,strictTypes:(ie=(ae=z.strictTypes)!==null&&ae!==void 0?ae:ln)!==null&&ie!==void 0?ie:"log",strictTuples:(ct=(Ae=z.strictTuples)!==null&&Ae!==void 0?Ae:ln)!==null&&ct!==void 0?ct:"log",strictRequired:(Fe=(Ie=z.strictRequired)!==null&&Ie!==void 0?Ie:ln)!==null&&Fe!==void 0?Fe:!1,code:z.code?{...z.code,optimize:Mn,regExp:Xn}:{optimize:Mn,regExp:Xn},loopRequired:(Je=z.loopRequired)!==null&&Je!==void 0?Je:b,loopEnum:(st=z.loopEnum)!==null&&st!==void 0?st:b,meta:(tn=z.meta)!==null&&tn!==void 0?tn:!0,messages:(Pn=z.messages)!==null&&Pn!==void 0?Pn:!0,inlineRefs:(Et=z.inlineRefs)!==null&&Et!==void 0?Et:!0,schemaId:(As=z.schemaId)!==null&&As!==void 0?As:"$id",addUsedSchema:(Rn=z.addUsedSchema)!==null&&Rn!==void 0?Rn:!0,validateSchema:(ks=z.validateSchema)!==null&&ks!==void 0?ks:!0,validateFormats:(hs=z.validateFormats)!==null&&hs!==void 0?hs:!0,unicodeRegExp:(us=z.unicodeRegExp)!==null&&us!==void 0?us:!0,int32range:(Es=z.int32range)!==null&&Es!==void 0?Es:!0,uriResolver:Yn}}class x{constructor(E={}){this.schemas={},this.refs={},this.formats=Object.create(null),this._compilations=new Set,this._loading={},this._cache=new Map,E=this.opts={...E,..._(E)};const{es5:O,lines:R}=this.opts.code;this.scope=new a.ValueScope({scope:{},prefixes:y,es5:O,lines:R}),this.logger=B(E.logger);const w=E.validateFormats;E.validateFormats=!1,this.RULES=(0,r.getRules)(),A.call(this,v,E,"NOT SUPPORTED"),A.call(this,g,E,"DEPRECATED","warn"),this._metaOpts=q.call(this),E.formats&&I.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),E.keywords&&j.call(this,E.keywords),typeof E.meta=="object"&&this.addMetaSchema(E.meta),$.call(this),E.validateFormats=w}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){const{$data:E,meta:O,schemaId:R}=this.opts;let w=u;R==="id"&&(w={...u},w.id=w.$id,delete w.$id),O&&E&&this.addMetaSchema(w,w[R],!1)}defaultMeta(){const{meta:E,schemaId:O}=this.opts;return this.opts.defaultMeta=typeof E=="object"?E[O]||E:void 0}validate(E,O){let R;if(typeof E=="string"){if(R=this.getSchema(E),!R)throw new Error(`no schema with key or ref "${E}"`)}else R=this.compile(E);const w=R(O);return"$async"in R||(this.errors=R.errors),w}compile(E,O){const R=this._addSchema(E,O);return R.validate||this._compileSchemaEnv(R)}compileAsync(E,O){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");const{loadSchema:R}=this.opts;return w.call(this,E,O);async function w(ie,Ae){await k.call(this,ie.$schema);const ct=this._addSchema(ie,Ae);return ct.validate||N.call(this,ct)}async function k(ie){ie&&!this.getSchema(ie)&&await w.call(this,{$ref:ie},!0)}async function N(ie){try{return this._compileSchemaEnv(ie)}catch(Ae){if(!(Ae instanceof i.default))throw Ae;return G.call(this,Ae),await Z.call(this,Ae.missingSchema),N.call(this,ie)}}function G({missingSchema:ie,missingRef:Ae}){if(this.refs[ie])throw new Error(`AnySchema ${ie} is loaded but ${Ae} cannot be resolved`)}async function Z(ie){const Ae=await ae.call(this,ie);this.refs[ie]||await k.call(this,Ae.$schema),this.refs[ie]||this.addSchema(Ae,ie,O)}async function ae(ie){const Ae=this._loading[ie];if(Ae)return Ae;try{return await(this._loading[ie]=R(ie))}finally{delete this._loading[ie]}}}addSchema(E,O,R,w=this.opts.validateSchema){if(Array.isArray(E)){for(const N of E)this.addSchema(N,void 0,R,w);return this}let k;if(typeof E=="object"){const{schemaId:N}=this.opts;if(k=E[N],k!==void 0&&typeof k!="string")throw new Error(`schema ${N} must be string`)}return O=(0,l.normalizeId)(O||k),this._checkUnique(O),this.schemas[O]=this._addSchema(E,R,O,w,!0),this}addMetaSchema(E,O,R=this.opts.validateSchema){return this.addSchema(E,O,!0,R),this}validateSchema(E,O){if(typeof E=="boolean")return!0;let R;if(R=E.$schema,R!==void 0&&typeof R!="string")throw new Error("$schema must be a string");if(R=R||this.opts.defaultMeta||this.defaultMeta(),!R)return this.logger.warn("meta-schema not available"),this.errors=null,!0;const w=this.validate(R,E);if(!w&&O){const k="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(k);else throw new Error(k)}return w}getSchema(E){let O;for(;typeof(O=C.call(this,E))=="string";)E=O;if(O===void 0){const{schemaId:R}=this.opts,w=new o.SchemaEnv({schema:{},schemaId:R});if(O=o.resolveSchema.call(this,w,E),!O)return;this.refs[E]=O}return O.validate||this._compileSchemaEnv(O)}removeSchema(E){if(E instanceof RegExp)return this._removeAllSchemas(this.schemas,E),this._removeAllSchemas(this.refs,E),this;switch(typeof E){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{const O=C.call(this,E);return typeof O=="object"&&this._cache.delete(O.schema),delete this.schemas[E],delete this.refs[E],this}case"object":{const O=E;this._cache.delete(O);let R=E[this.opts.schemaId];return R&&(R=(0,l.normalizeId)(R),delete this.schemas[R],delete this.refs[R]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(E){for(const O of E)this.addKeyword(O);return this}addKeyword(E,O){let R;if(typeof E=="string")R=E,typeof O=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),O.keyword=R);else if(typeof E=="object"&&O===void 0){if(O=E,R=O.keyword,Array.isArray(R)&&!R.length)throw new Error("addKeywords: keyword must be string or non-empty array")}else throw new Error("invalid addKeywords parameters");if(D.call(this,R,O),!O)return(0,h.eachItem)(R,k=>X.call(this,k)),this;J.call(this,O);const w={...O,type:(0,c.getJSONTypes)(O.type),schemaType:(0,c.getJSONTypes)(O.schemaType)};return(0,h.eachItem)(R,w.type.length===0?k=>X.call(this,k,w):k=>w.type.forEach(N=>X.call(this,k,w,N))),this}getKeyword(E){const O=this.RULES.all[E];return typeof O=="object"?O.definition:!!O}removeKeyword(E){const{RULES:O}=this;delete O.keywords[E],delete O.all[E];for(const R of O.rules){const w=R.rules.findIndex(k=>k.keyword===E);w>=0&&R.rules.splice(w,1)}return this}addFormat(E,O){return typeof O=="string"&&(O=new RegExp(O)),this.formats[E]=O,this}errorsText(E=this.errors,{separator:O=", ",dataVar:R="data"}={}){return!E||E.length===0?"No errors":E.map(w=>`${R}${w.instancePath} ${w.message}`).reduce((w,k)=>w+O+k)}$dataMetaSchema(E,O){const R=this.RULES.all;E=JSON.parse(JSON.stringify(E));for(const w of O){const k=w.split("/").slice(1);let N=E;for(const G of k)N=N[G];for(const G in R){const Z=R[G];if(typeof Z!="object")continue;const{$data:ae}=Z.definition,ie=N[G];ae&&ie&&(N[G]=ye(ie))}}return E}_removeAllSchemas(E,O){for(const R in E){const w=E[R];(!O||O.test(R))&&(typeof w=="string"?delete E[R]:w&&!w.meta&&(this._cache.delete(w.schema),delete E[R]))}}_addSchema(E,O,R,w=this.opts.validateSchema,k=this.opts.addUsedSchema){let N;const{schemaId:G}=this.opts;if(typeof E=="object")N=E[G];else{if(this.opts.jtd)throw new Error("schema must be object");if(typeof E!="boolean")throw new Error("schema must be object or boolean")}let Z=this._cache.get(E);if(Z!==void 0)return Z;R=(0,l.normalizeId)(N||R);const ae=l.getSchemaRefs.call(this,E,R);return Z=new o.SchemaEnv({schema:E,schemaId:G,meta:O,baseId:R,localRefs:ae}),this._cache.set(Z.schema,Z),k&&!R.startsWith("#")&&(R&&this._checkUnique(R),this.refs[R]=Z),w&&this.validateSchema(E,!0),Z}_checkUnique(E){if(this.schemas[E]||this.refs[E])throw new Error(`schema with key or id "${E}" already exists`)}_compileSchemaEnv(E){if(E.meta?this._compileMetaSchema(E):o.compileSchema.call(this,E),!E.validate)throw new Error("ajv implementation error");return E.validate}_compileMetaSchema(E){const O=this.opts;this.opts=this._metaOpts;try{o.compileSchema.call(this,E)}finally{this.opts=O}}}x.ValidationError=s.default,x.MissingRefError=i.default,n.default=x;function A(z,E,O,R="error"){for(const w in z){const k=w;k in E&&this.logger[R](`${O}: option ${w}. ${z[k]}`)}}function C(z){return z=(0,l.normalizeId)(z),this.schemas[z]||this.refs[z]}function $(){const z=this.opts.schemas;if(z)if(Array.isArray(z))this.addSchema(z);else for(const E in z)this.addSchema(z[E],E)}function I(){for(const z in this.opts.formats){const E=this.opts.formats[z];E&&this.addFormat(z,E)}}function j(z){if(Array.isArray(z)){this.addVocabulary(z);return}this.logger.warn("keywords option as map is deprecated, pass array");for(const E in z){const O=z[E];O.keyword||(O.keyword=E),this.addKeyword(O)}}function q(){const z={...this.opts};for(const E of m)delete z[E];return z}const L={log(){},warn(){},error(){}};function B(z){if(z===!1)return L;if(z===void 0)return console;if(z.log&&z.warn&&z.error)return z;throw new Error("logger must implement log, warn and error methods")}const H=/^[a-z_$][a-z0-9_$:-]*$/i;function D(z,E){const{RULES:O}=this;if((0,h.eachItem)(z,R=>{if(O.keywords[R])throw new Error(`Keyword ${R} is already defined`);if(!H.test(R))throw new Error(`Keyword ${R} has invalid name`)}),!!E&&E.$data&&!("code"in E||"validate"in E))throw new Error('$data keyword must have "code" or "validate" function')}function X(z,E,O){var R;const w=E==null?void 0:E.post;if(O&&w)throw new Error('keyword with "post" flag cannot have "type"');const{RULES:k}=this;let N=w?k.post:k.rules.find(({type:Z})=>Z===O);if(N||(N={type:O,rules:[]},k.rules.push(N)),k.keywords[z]=!0,!E)return;const G={keyword:z,definition:{...E,type:(0,c.getJSONTypes)(E.type),schemaType:(0,c.getJSONTypes)(E.schemaType)}};E.before?te.call(this,N,G,E.before):N.rules.push(G),k.all[z]=G,(R=E.implements)===null||R===void 0||R.forEach(Z=>this.addKeyword(Z))}function te(z,E,O){const R=z.rules.findIndex(w=>w.keyword===O);R>=0?z.rules.splice(R,0,E):(z.rules.push(E),this.logger.warn(`rule ${O} is not defined`))}function J(z){let{metaSchema:E}=z;E!==void 0&&(z.$data&&this.opts.$data&&(E=ye(E)),z.validateSchema=this.compile(E,!0))}const Y={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function ye(z){return{anyOf:[z,Y]}}})(xP);var U1={},q1={},V1={};Object.defineProperty(V1,"__esModule",{value:!0});const sG={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};V1.default=sG;var fc={};Object.defineProperty(fc,"__esModule",{value:!0});fc.callRef=fc.getValidate=void 0;const iG=Fu,Ek=Ge,Is=Be,jc=jr,Ck=Ls,$m=pe,rG={keyword:"$ref",schemaType:"string",code(n){const{gen:e,schema:t,it:s}=n,{baseId:i,schemaEnv:r,validateName:o,opts:a,self:l}=s,{root:c}=r;if((t==="#"||t==="#/")&&i===c.baseId)return u();const h=Ck.resolveRef.call(l,c,i,t);if(h===void 0)throw new iG.default(s.opts.uriResolver,i,t);if(h instanceof Ck.SchemaEnv)return d(h);return p(h);function u(){if(r===c)return fg(n,o,r,r.$async);const m=e.scopeValue("root",{ref:c});return fg(n,(0,Is._)`${m}.validate`,c,c.$async)}function d(m){const y=nR(n,m);fg(n,y,m,m.$async)}function p(m){const y=e.scopeValue("schema",a.code.source===!0?{ref:m,code:(0,Is.stringify)(m)}:{ref:m}),v=e.name("valid"),g=n.subschema({schema:m,dataTypes:[],schemaPath:Is.nil,topSchemaRef:y,errSchemaPath:t},v);n.mergeEvaluated(g),n.ok(v)}}};function nR(n,e){const{gen:t}=n;return e.validate?t.scopeValue("validate",{ref:e.validate}):(0,Is._)`${t.scopeValue("wrapper",{ref:e})}.validate`}fc.getValidate=nR;function fg(n,e,t,s){const{gen:i,it:r}=n,{allErrors:o,schemaEnv:a,opts:l}=r,c=l.passContext?jc.default.this:Is.nil;s?h():u();function h(){if(!a.$async)throw new Error("async schema referenced by sync schema");const m=i.let("valid");i.try(()=>{i.code((0,Is._)`await ${(0,Ek.callValidateCode)(n,e,c)}`),p(e),o||i.assign(m,!0)},y=>{i.if((0,Is._)`!(${y} instanceof ${r.ValidationError})`,()=>i.throw(y)),d(y),o||i.assign(m,!1)}),n.ok(m)}function u(){n.result((0,Ek.callValidateCode)(n,e,c),()=>p(e),()=>d(e))}function d(m){const y=(0,Is._)`${m}.errors`;i.assign(jc.default.vErrors,(0,Is._)`${jc.default.vErrors} === null ? ${y} : ${jc.default.vErrors}.concat(${y})`),i.assign(jc.default.errors,(0,Is._)`${jc.default.vErrors}.length`)}function p(m){var y;if(!r.opts.unevaluated)return;const v=(y=t==null?void 0:t.validate)===null||y===void 0?void 0:y.evaluated;if(r.props!==!0)if(v&&!v.dynamicProps)v.props!==void 0&&(r.props=$m.mergeEvaluated.props(i,v.props,r.props));else{const g=i.var("props",(0,Is._)`${m}.evaluated.props`);r.props=$m.mergeEvaluated.props(i,g,r.props,Is.Name)}if(r.items!==!0)if(v&&!v.dynamicItems)v.items!==void 0&&(r.items=$m.mergeEvaluated.items(i,v.items,r.items));else{const g=i.var("items",(0,Is._)`${m}.evaluated.items`);r.items=$m.mergeEvaluated.items(i,g,r.items,Is.Name)}}}fc.callRef=fg;fc.default=rG;Object.defineProperty(q1,"__esModule",{value:!0});const oG=V1,aG=fc,lG=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",oG.default,aG.default];q1.default=lG;var W1={},G1={};Object.defineProperty(G1,"__esModule",{value:!0});const fy=Be,Lo=fy.operators,py={maximum:{okStr:"<=",ok:Lo.LTE,fail:Lo.GT},minimum:{okStr:">=",ok:Lo.GTE,fail:Lo.LT},exclusiveMaximum:{okStr:"<",ok:Lo.LT,fail:Lo.GTE},exclusiveMinimum:{okStr:">",ok:Lo.GT,fail:Lo.LTE}},cG={message:({keyword:n,schemaCode:e})=>(0,fy.str)`must be ${py[n].okStr} ${e}`,params:({keyword:n,schemaCode:e})=>(0,fy._)`{comparison: ${py[n].okStr}, limit: ${e}}`},hG={keyword:Object.keys(py),type:"number",schemaType:"number",$data:!0,error:cG,code(n){const{keyword:e,data:t,schemaCode:s}=n;n.fail$data((0,fy._)`${t} ${py[e].fail} ${s} || isNaN(${t})`)}};G1.default=hG;var K1={};Object.defineProperty(K1,"__esModule",{value:!0});const qd=Be,uG={message:({schemaCode:n})=>(0,qd.str)`must be multiple of ${n}`,params:({schemaCode:n})=>(0,qd._)`{multipleOf: ${n}}`},dG={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:uG,code(n){const{gen:e,data:t,schemaCode:s,it:i}=n,r=i.opts.multipleOfPrecision,o=e.let("res"),a=r?(0,qd._)`Math.abs(Math.round(${o}) - ${o}) > 1e-${r}`:(0,qd._)`${o} !== parseInt(${o})`;n.fail$data((0,qd._)`(${s} === 0 || (${o} = ${t}/${s}, ${a}))`)}};K1.default=dG;var Z1={},X1={};Object.defineProperty(X1,"__esModule",{value:!0});function sR(n){const e=n.length;let t=0,s=0,i;for(;s=55296&&i<=56319&&s(0,sl._)`{limit: ${n}}`},gG={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:mG,code(n){const{keyword:e,data:t,schemaCode:s,it:i}=n,r=e==="maxLength"?sl.operators.GT:sl.operators.LT,o=i.opts.unicode===!1?(0,sl._)`${t}.length`:(0,sl._)`${(0,fG.useFunc)(n.gen,pG.default)}(${t})`;n.fail$data((0,sl._)`${o} ${r} ${s}`)}};Z1.default=gG;var Y1={};Object.defineProperty(Y1,"__esModule",{value:!0});const yG=Ge,vG=pe,sh=Be,bG={message:({schemaCode:n})=>(0,sh.str)`must match pattern "${n}"`,params:({schemaCode:n})=>(0,sh._)`{pattern: ${n}}`},wG={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:bG,code(n){const{gen:e,data:t,$data:s,schema:i,schemaCode:r,it:o}=n,a=o.opts.unicodeRegExp?"u":"";if(s){const{regExp:l}=o.opts.code,c=l.code==="new RegExp"?(0,sh._)`new RegExp`:(0,vG.useFunc)(e,l),h=e.let("valid");e.try(()=>e.assign(h,(0,sh._)`${c}(${r}, ${a}).test(${t})`),()=>e.assign(h,!1)),n.fail$data((0,sh._)`!${h}`)}else{const l=(0,yG.usePattern)(n,i);n.fail$data((0,sh._)`!${l}.test(${t})`)}}};Y1.default=wG;var J1={};Object.defineProperty(J1,"__esModule",{value:!0});const Vd=Be,_G={message({keyword:n,schemaCode:e}){const t=n==="maxProperties"?"more":"fewer";return(0,Vd.str)`must NOT have ${t} than ${e} properties`},params:({schemaCode:n})=>(0,Vd._)`{limit: ${n}}`},SG={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:_G,code(n){const{keyword:e,data:t,schemaCode:s}=n,i=e==="maxProperties"?Vd.operators.GT:Vd.operators.LT;n.fail$data((0,Vd._)`Object.keys(${t}).length ${i} ${s}`)}};J1.default=SG;var Q1={};Object.defineProperty(Q1,"__esModule",{value:!0});const nd=Ge,Wd=Be,xG=pe,AG={message:({params:{missingProperty:n}})=>(0,Wd.str)`must have required property '${n}'`,params:({params:{missingProperty:n}})=>(0,Wd._)`{missingProperty: ${n}}`},kG={keyword:"required",type:"object",schemaType:"array",$data:!0,error:AG,code(n){const{gen:e,schema:t,schemaCode:s,data:i,$data:r,it:o}=n,{opts:a}=o;if(!r&&t.length===0)return;const l=t.length>=a.loopRequired;if(o.allErrors?c():h(),a.strictRequired){const p=n.parentSchema.properties,{definedProperties:m}=n.it;for(const y of t)if((p==null?void 0:p[y])===void 0&&!m.has(y)){const v=o.schemaEnv.baseId+o.errSchemaPath,g=`required property "${y}" is not defined at "${v}" (strictRequired)`;(0,xG.checkStrictMode)(o,g,o.opts.strictRequired)}}function c(){if(l||r)n.block$data(Wd.nil,u);else for(const p of t)(0,nd.checkReportMissingProp)(n,p)}function h(){const p=e.let("missing");if(l||r){const m=e.let("valid",!0);n.block$data(m,()=>d(p,m)),n.ok(m)}else e.if((0,nd.checkMissingProp)(n,t,p)),(0,nd.reportMissingProp)(n,p),e.else()}function u(){e.forOf("prop",s,p=>{n.setParams({missingProperty:p}),e.if((0,nd.noPropertyInData)(e,i,p,a.ownProperties),()=>n.error())})}function d(p,m){n.setParams({missingProperty:p}),e.forOf(p,s,()=>{e.assign(m,(0,nd.propertyInData)(e,i,p,a.ownProperties)),e.if((0,Wd.not)(m),()=>{n.error(),e.break()})},Wd.nil)}}};Q1.default=kG;var ex={};Object.defineProperty(ex,"__esModule",{value:!0});const Gd=Be,EG={message({keyword:n,schemaCode:e}){const t=n==="maxItems"?"more":"fewer";return(0,Gd.str)`must NOT have ${t} than ${e} items`},params:({schemaCode:n})=>(0,Gd._)`{limit: ${n}}`},CG={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:EG,code(n){const{keyword:e,data:t,schemaCode:s}=n,i=e==="maxItems"?Gd.operators.GT:Gd.operators.LT;n.fail$data((0,Gd._)`${t}.length ${i} ${s}`)}};ex.default=CG;var tx={},em={};Object.defineProperty(em,"__esModule",{value:!0});const iR=S0;iR.code='require("ajv/dist/runtime/equal").default';em.default=iR;Object.defineProperty(tx,"__esModule",{value:!0});const wv=mn,Nn=Be,$G=pe,TG=em,PG={message:({params:{i:n,j:e}})=>(0,Nn.str)`must NOT have duplicate items (items ## ${e} and ${n} are identical)`,params:({params:{i:n,j:e}})=>(0,Nn._)`{i: ${n}, j: ${e}}`},RG={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:PG,code(n){const{gen:e,data:t,$data:s,schema:i,parentSchema:r,schemaCode:o,it:a}=n;if(!s&&!i)return;const l=e.let("valid"),c=r.items?(0,wv.getSchemaTypes)(r.items):[];n.block$data(l,h,(0,Nn._)`${o} === false`),n.ok(l);function h(){const m=e.let("i",(0,Nn._)`${t}.length`),y=e.let("j");n.setParams({i:m,j:y}),e.assign(l,!0),e.if((0,Nn._)`${m} > 1`,()=>(u()?d:p)(m,y))}function u(){return c.length>0&&!c.some(m=>m==="object"||m==="array")}function d(m,y){const v=e.name("item"),g=(0,wv.checkDataTypes)(c,v,a.opts.strictNumbers,wv.DataType.Wrong),b=e.const("indices",(0,Nn._)`{}`);e.for((0,Nn._)`;${m}--;`,()=>{e.let(v,(0,Nn._)`${t}[${m}]`),e.if(g,(0,Nn._)`continue`),c.length>1&&e.if((0,Nn._)`typeof ${v} == "string"`,(0,Nn._)`${v} += "_"`),e.if((0,Nn._)`typeof ${b}[${v}] == "number"`,()=>{e.assign(y,(0,Nn._)`${b}[${v}]`),n.error(),e.assign(l,!1).break()}).code((0,Nn._)`${b}[${v}] = ${m}`)})}function p(m,y){const v=(0,$G.useFunc)(e,TG.default),g=e.name("outer");e.label(g).for((0,Nn._)`;${m}--;`,()=>e.for((0,Nn._)`${y} = ${m}; ${y}--;`,()=>e.if((0,Nn._)`${v}(${t}[${m}], ${t}[${y}])`,()=>{n.error(),e.assign(l,!1).break(g)})))}}};tx.default=RG;var nx={};Object.defineProperty(nx,"__esModule",{value:!0});const Cb=Be,MG=pe,IG=em,OG={message:"must be equal to constant",params:({schemaCode:n})=>(0,Cb._)`{allowedValue: ${n}}`},NG={keyword:"const",$data:!0,error:OG,code(n){const{gen:e,data:t,$data:s,schemaCode:i,schema:r}=n;s||r&&typeof r=="object"?n.fail$data((0,Cb._)`!${(0,MG.useFunc)(e,IG.default)}(${t}, ${i})`):n.fail((0,Cb._)`${r} !== ${t}`)}};nx.default=NG;var sx={};Object.defineProperty(sx,"__esModule",{value:!0});const md=Be,LG=pe,DG=em,jG={message:"must be equal to one of the allowed values",params:({schemaCode:n})=>(0,md._)`{allowedValues: ${n}}`},FG={keyword:"enum",schemaType:"array",$data:!0,error:jG,code(n){const{gen:e,data:t,$data:s,schema:i,schemaCode:r,it:o}=n;if(!s&&i.length===0)throw new Error("enum must have non-empty array");const a=i.length>=o.opts.loopEnum;let l;const c=()=>l??(l=(0,LG.useFunc)(e,DG.default));let h;if(a||s)h=e.let("valid"),n.block$data(h,u);else{if(!Array.isArray(i))throw new Error("ajv implementation error");const p=e.const("vSchema",r);h=(0,md.or)(...i.map((m,y)=>d(p,y)))}n.pass(h);function u(){e.assign(h,!1),e.forOf("v",r,p=>e.if((0,md._)`${c()}(${t}, ${p})`,()=>e.assign(h,!0).break()))}function d(p,m){const y=i[m];return typeof y=="object"&&y!==null?(0,md._)`${c()}(${t}, ${p}[${m}])`:(0,md._)`${t} === ${y}`}}};sx.default=FG;Object.defineProperty(W1,"__esModule",{value:!0});const zG=G1,HG=K1,BG=Z1,UG=Y1,qG=J1,VG=Q1,WG=ex,GG=tx,KG=nx,ZG=sx,XG=[zG.default,HG.default,BG.default,UG.default,qG.default,VG.default,WG.default,GG.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},KG.default,ZG.default];W1.default=XG;var ix={},zu={};Object.defineProperty(zu,"__esModule",{value:!0});zu.validateAdditionalItems=void 0;const il=Be,$b=pe,YG={message:({params:{len:n}})=>(0,il.str)`must NOT have more than ${n} items`,params:({params:{len:n}})=>(0,il._)`{limit: ${n}}`},JG={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:YG,code(n){const{parentSchema:e,it:t}=n,{items:s}=e;if(!Array.isArray(s)){(0,$b.checkStrictMode)(t,'"additionalItems" is ignored when "items" is not an array of schemas');return}rR(n,s)}};function rR(n,e){const{gen:t,schema:s,data:i,keyword:r,it:o}=n;o.items=!0;const a=t.const("len",(0,il._)`${i}.length`);if(s===!1)n.setParams({len:e.length}),n.pass((0,il._)`${a} <= ${e.length}`);else if(typeof s=="object"&&!(0,$b.alwaysValidSchema)(o,s)){const c=t.var("valid",(0,il._)`${a} <= ${e.length}`);t.if((0,il.not)(c),()=>l(c)),n.ok(c)}function l(c){t.forRange("i",e.length,a,h=>{n.subschema({keyword:r,dataProp:h,dataPropType:$b.Type.Num},c),o.allErrors||t.if((0,il.not)(c),()=>t.break())})}}zu.validateAdditionalItems=rR;zu.default=JG;var rx={},Hu={};Object.defineProperty(Hu,"__esModule",{value:!0});Hu.validateTuple=void 0;const $k=Be,pg=pe,QG=Ge,eK={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(n){const{schema:e,it:t}=n;if(Array.isArray(e))return oR(n,"additionalItems",e);t.items=!0,!(0,pg.alwaysValidSchema)(t,e)&&n.ok((0,QG.validateArray)(n))}};function oR(n,e,t=n.schema){const{gen:s,parentSchema:i,data:r,keyword:o,it:a}=n;h(i),a.opts.unevaluated&&t.length&&a.items!==!0&&(a.items=pg.mergeEvaluated.items(s,t.length,a.items));const l=s.name("valid"),c=s.const("len",(0,$k._)`${r}.length`);t.forEach((u,d)=>{(0,pg.alwaysValidSchema)(a,u)||(s.if((0,$k._)`${c} > ${d}`,()=>n.subschema({keyword:o,schemaProp:d,dataProp:d},l)),n.ok(l))});function h(u){const{opts:d,errSchemaPath:p}=a,m=t.length,y=m===u.minItems&&(m===u.maxItems||u[e]===!1);if(d.strictTuples&&!y){const v=`"${o}" is ${m}-tuple, but minItems or maxItems/${e} are not specified or different at path "${p}"`;(0,pg.checkStrictMode)(a,v,d.strictTuples)}}}Hu.validateTuple=oR;Hu.default=eK;Object.defineProperty(rx,"__esModule",{value:!0});const tK=Hu,nK={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:n=>(0,tK.validateTuple)(n,"items")};rx.default=nK;var ox={};Object.defineProperty(ox,"__esModule",{value:!0});const Tk=Be,sK=pe,iK=Ge,rK=zu,oK={message:({params:{len:n}})=>(0,Tk.str)`must NOT have more than ${n} items`,params:({params:{len:n}})=>(0,Tk._)`{limit: ${n}}`},aK={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:oK,code(n){const{schema:e,parentSchema:t,it:s}=n,{prefixItems:i}=t;s.items=!0,!(0,sK.alwaysValidSchema)(s,e)&&(i?(0,rK.validateAdditionalItems)(n,i):n.ok((0,iK.validateArray)(n)))}};ox.default=aK;var ax={};Object.defineProperty(ax,"__esModule",{value:!0});const pi=Be,Tm=pe,lK={message:({params:{min:n,max:e}})=>e===void 0?(0,pi.str)`must contain at least ${n} valid item(s)`:(0,pi.str)`must contain at least ${n} and no more than ${e} valid item(s)`,params:({params:{min:n,max:e}})=>e===void 0?(0,pi._)`{minContains: ${n}}`:(0,pi._)`{minContains: ${n}, maxContains: ${e}}`},cK={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:lK,code(n){const{gen:e,schema:t,parentSchema:s,data:i,it:r}=n;let o,a;const{minContains:l,maxContains:c}=s;r.opts.next?(o=l===void 0?1:l,a=c):o=1;const h=e.const("len",(0,pi._)`${i}.length`);if(n.setParams({min:o,max:a}),a===void 0&&o===0){(0,Tm.checkStrictMode)(r,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&o>a){(0,Tm.checkStrictMode)(r,'"minContains" > "maxContains" is always invalid'),n.fail();return}if((0,Tm.alwaysValidSchema)(r,t)){let y=(0,pi._)`${h} >= ${o}`;a!==void 0&&(y=(0,pi._)`${y} && ${h} <= ${a}`),n.pass(y);return}r.items=!0;const u=e.name("valid");a===void 0&&o===1?p(u,()=>e.if(u,()=>e.break())):o===0?(e.let(u,!0),a!==void 0&&e.if((0,pi._)`${i}.length > 0`,d)):(e.let(u,!1),d()),n.result(u,()=>n.reset());function d(){const y=e.name("_valid"),v=e.let("count",0);p(y,()=>e.if(y,()=>m(v)))}function p(y,v){e.forRange("i",0,h,g=>{n.subschema({keyword:"contains",dataProp:g,dataPropType:Tm.Type.Num,compositeRule:!0},y),v()})}function m(y){e.code((0,pi._)`${y}++`),a===void 0?e.if((0,pi._)`${y} >= ${o}`,()=>e.assign(u,!0).break()):(e.if((0,pi._)`${y} > ${a}`,()=>e.assign(u,!1).break()),o===1?e.assign(u,!0):e.if((0,pi._)`${y} >= ${o}`,()=>e.assign(u,!0)))}}};ax.default=cK;var aR={};(function(n){Object.defineProperty(n,"__esModule",{value:!0}),n.validateSchemaDeps=n.validatePropertyDeps=n.error=void 0;const e=Be,t=pe,s=Ge;n.error={message:({params:{property:l,depsCount:c,deps:h}})=>{const u=c===1?"property":"properties";return(0,e.str)`must have ${u} ${h} when property ${l} is present`},params:({params:{property:l,depsCount:c,deps:h,missingProperty:u}})=>(0,e._)`{property: ${l}, + missingProperty: ${u}, + depsCount: ${c}, + deps: ${h}}`};const i={keyword:"dependencies",type:"object",schemaType:"object",error:n.error,code(l){const[c,h]=r(l);o(l,c),a(l,h)}};function r({schema:l}){const c={},h={};for(const u in l){if(u==="__proto__")continue;const d=Array.isArray(l[u])?c:h;d[u]=l[u]}return[c,h]}function o(l,c=l.schema){const{gen:h,data:u,it:d}=l;if(Object.keys(c).length===0)return;const p=h.let("missing");for(const m in c){const y=c[m];if(y.length===0)continue;const v=(0,s.propertyInData)(h,u,m,d.opts.ownProperties);l.setParams({property:m,depsCount:y.length,deps:y.join(", ")}),d.allErrors?h.if(v,()=>{for(const g of y)(0,s.checkReportMissingProp)(l,g)}):(h.if((0,e._)`${v} && (${(0,s.checkMissingProp)(l,y,p)})`),(0,s.reportMissingProp)(l,p),h.else())}}n.validatePropertyDeps=o;function a(l,c=l.schema){const{gen:h,data:u,keyword:d,it:p}=l,m=h.name("valid");for(const y in c)(0,t.alwaysValidSchema)(p,c[y])||(h.if((0,s.propertyInData)(h,u,y,p.opts.ownProperties),()=>{const v=l.subschema({keyword:d,schemaProp:y},m);l.mergeValidEvaluated(v,m)},()=>h.var(m,!0)),l.ok(m))}n.validateSchemaDeps=a,n.default=i})(aR);var lx={};Object.defineProperty(lx,"__esModule",{value:!0});const lR=Be,hK=pe,uK={message:"property name must be valid",params:({params:n})=>(0,lR._)`{propertyName: ${n.propertyName}}`},dK={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:uK,code(n){const{gen:e,schema:t,data:s,it:i}=n;if((0,hK.alwaysValidSchema)(i,t))return;const r=e.name("valid");e.forIn("key",s,o=>{n.setParams({propertyName:o}),n.subschema({keyword:"propertyNames",data:o,dataTypes:["string"],propertyName:o,compositeRule:!0},r),e.if((0,lR.not)(r),()=>{n.error(!0),i.allErrors||e.break()})}),n.ok(r)}};lx.default=dK;var R0={};Object.defineProperty(R0,"__esModule",{value:!0});const Pm=Ge,Pi=Be,fK=jr,Rm=pe,pK={message:"must NOT have additional properties",params:({params:n})=>(0,Pi._)`{additionalProperty: ${n.additionalProperty}}`},mK={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:pK,code(n){const{gen:e,schema:t,parentSchema:s,data:i,errsCount:r,it:o}=n;if(!r)throw new Error("ajv implementation error");const{allErrors:a,opts:l}=o;if(o.props=!0,l.removeAdditional!=="all"&&(0,Rm.alwaysValidSchema)(o,t))return;const c=(0,Pm.allSchemaProperties)(s.properties),h=(0,Pm.allSchemaProperties)(s.patternProperties);u(),n.ok((0,Pi._)`${r} === ${fK.default.errors}`);function u(){e.forIn("key",i,v=>{!c.length&&!h.length?m(v):e.if(d(v),()=>m(v))})}function d(v){let g;if(c.length>8){const b=(0,Rm.schemaRefOrVal)(o,s.properties,"properties");g=(0,Pm.isOwnProperty)(e,b,v)}else c.length?g=(0,Pi.or)(...c.map(b=>(0,Pi._)`${v} === ${b}`)):g=Pi.nil;return h.length&&(g=(0,Pi.or)(g,...h.map(b=>(0,Pi._)`${(0,Pm.usePattern)(n,b)}.test(${v})`))),(0,Pi.not)(g)}function p(v){e.code((0,Pi._)`delete ${i}[${v}]`)}function m(v){if(l.removeAdditional==="all"||l.removeAdditional&&t===!1){p(v);return}if(t===!1){n.setParams({additionalProperty:v}),n.error(),a||e.break();return}if(typeof t=="object"&&!(0,Rm.alwaysValidSchema)(o,t)){const g=e.name("valid");l.removeAdditional==="failing"?(y(v,g,!1),e.if((0,Pi.not)(g),()=>{n.reset(),p(v)})):(y(v,g),a||e.if((0,Pi.not)(g),()=>e.break()))}}function y(v,g,b){const _={keyword:"additionalProperties",dataProp:v,dataPropType:Rm.Type.Str};b===!1&&Object.assign(_,{compositeRule:!0,createErrors:!1,allErrors:!1}),n.subschema(_,g)}}};R0.default=mK;var cx={};Object.defineProperty(cx,"__esModule",{value:!0});const gK=Ji,Pk=Ge,_v=pe,Rk=R0,yK={keyword:"properties",type:"object",schemaType:"object",code(n){const{gen:e,schema:t,parentSchema:s,data:i,it:r}=n;r.opts.removeAdditional==="all"&&s.additionalProperties===void 0&&Rk.default.code(new gK.KeywordCxt(r,Rk.default,"additionalProperties"));const o=(0,Pk.allSchemaProperties)(t);for(const u of o)r.definedProperties.add(u);r.opts.unevaluated&&o.length&&r.props!==!0&&(r.props=_v.mergeEvaluated.props(e,(0,_v.toHash)(o),r.props));const a=o.filter(u=>!(0,_v.alwaysValidSchema)(r,t[u]));if(a.length===0)return;const l=e.name("valid");for(const u of a)c(u)?h(u):(e.if((0,Pk.propertyInData)(e,i,u,r.opts.ownProperties)),h(u),r.allErrors||e.else().var(l,!0),e.endIf()),n.it.definedProperties.add(u),n.ok(l);function c(u){return r.opts.useDefaults&&!r.compositeRule&&t[u].default!==void 0}function h(u){n.subschema({keyword:"properties",schemaProp:u,dataProp:u},l)}}};cx.default=yK;var hx={};Object.defineProperty(hx,"__esModule",{value:!0});const Mk=Ge,Mm=Be,Ik=pe,Ok=pe,vK={keyword:"patternProperties",type:"object",schemaType:"object",code(n){const{gen:e,schema:t,data:s,parentSchema:i,it:r}=n,{opts:o}=r,a=(0,Mk.allSchemaProperties)(t),l=a.filter(y=>(0,Ik.alwaysValidSchema)(r,t[y]));if(a.length===0||l.length===a.length&&(!r.opts.unevaluated||r.props===!0))return;const c=o.strictSchema&&!o.allowMatchingProperties&&i.properties,h=e.name("valid");r.props!==!0&&!(r.props instanceof Mm.Name)&&(r.props=(0,Ok.evaluatedPropsToName)(e,r.props));const{props:u}=r;d();function d(){for(const y of a)c&&p(y),r.allErrors?m(y):(e.var(h,!0),m(y),e.if(h))}function p(y){for(const v in c)new RegExp(y).test(v)&&(0,Ik.checkStrictMode)(r,`property ${v} matches pattern ${y} (use allowMatchingProperties)`)}function m(y){e.forIn("key",s,v=>{e.if((0,Mm._)`${(0,Mk.usePattern)(n,y)}.test(${v})`,()=>{const g=l.includes(y);g||n.subschema({keyword:"patternProperties",schemaProp:y,dataProp:v,dataPropType:Ok.Type.Str},h),r.opts.unevaluated&&u!==!0?e.assign((0,Mm._)`${u}[${v}]`,!0):!g&&!r.allErrors&&e.if((0,Mm.not)(h),()=>e.break())})})}}};hx.default=vK;var ux={};Object.defineProperty(ux,"__esModule",{value:!0});const bK=pe,wK={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(n){const{gen:e,schema:t,it:s}=n;if((0,bK.alwaysValidSchema)(s,t)){n.fail();return}const i=e.name("valid");n.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},i),n.failResult(i,()=>n.reset(),()=>n.error())},error:{message:"must NOT be valid"}};ux.default=wK;var dx={};Object.defineProperty(dx,"__esModule",{value:!0});const _K=Ge,SK={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:_K.validateUnion,error:{message:"must match a schema in anyOf"}};dx.default=SK;var fx={};Object.defineProperty(fx,"__esModule",{value:!0});const mg=Be,xK=pe,AK={message:"must match exactly one schema in oneOf",params:({params:n})=>(0,mg._)`{passingSchemas: ${n.passing}}`},kK={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:AK,code(n){const{gen:e,schema:t,parentSchema:s,it:i}=n;if(!Array.isArray(t))throw new Error("ajv implementation error");if(i.opts.discriminator&&s.discriminator)return;const r=t,o=e.let("valid",!1),a=e.let("passing",null),l=e.name("_valid");n.setParams({passing:a}),e.block(c),n.result(o,()=>n.reset(),()=>n.error(!0));function c(){r.forEach((h,u)=>{let d;(0,xK.alwaysValidSchema)(i,h)?e.var(l,!0):d=n.subschema({keyword:"oneOf",schemaProp:u,compositeRule:!0},l),u>0&&e.if((0,mg._)`${l} && ${o}`).assign(o,!1).assign(a,(0,mg._)`[${a}, ${u}]`).else(),e.if(l,()=>{e.assign(o,!0),e.assign(a,u),d&&n.mergeEvaluated(d,mg.Name)})})}}};fx.default=kK;var px={};Object.defineProperty(px,"__esModule",{value:!0});const EK=pe,CK={keyword:"allOf",schemaType:"array",code(n){const{gen:e,schema:t,it:s}=n;if(!Array.isArray(t))throw new Error("ajv implementation error");const i=e.name("valid");t.forEach((r,o)=>{if((0,EK.alwaysValidSchema)(s,r))return;const a=n.subschema({keyword:"allOf",schemaProp:o},i);n.ok(i),n.mergeEvaluated(a)})}};px.default=CK;var mx={};Object.defineProperty(mx,"__esModule",{value:!0});const my=Be,cR=pe,$K={message:({params:n})=>(0,my.str)`must match "${n.ifClause}" schema`,params:({params:n})=>(0,my._)`{failingKeyword: ${n.ifClause}}`},TK={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:$K,code(n){const{gen:e,parentSchema:t,it:s}=n;t.then===void 0&&t.else===void 0&&(0,cR.checkStrictMode)(s,'"if" without "then" and "else" is ignored');const i=Nk(s,"then"),r=Nk(s,"else");if(!i&&!r)return;const o=e.let("valid",!0),a=e.name("_valid");if(l(),n.reset(),i&&r){const h=e.let("ifClause");n.setParams({ifClause:h}),e.if(a,c("then",h),c("else",h))}else i?e.if(a,c("then")):e.if((0,my.not)(a),c("else"));n.pass(o,()=>n.error(!0));function l(){const h=n.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},a);n.mergeEvaluated(h)}function c(h,u){return()=>{const d=n.subschema({keyword:h},a);e.assign(o,a),n.mergeValidEvaluated(d,o),u?e.assign(u,(0,my._)`${h}`):n.setParams({ifClause:h})}}}};function Nk(n,e){const t=n.schema[e];return t!==void 0&&!(0,cR.alwaysValidSchema)(n,t)}mx.default=TK;var gx={};Object.defineProperty(gx,"__esModule",{value:!0});const PK=pe,RK={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:n,parentSchema:e,it:t}){e.if===void 0&&(0,PK.checkStrictMode)(t,`"${n}" without "if" is ignored`)}};gx.default=RK;Object.defineProperty(ix,"__esModule",{value:!0});const MK=zu,IK=rx,OK=Hu,NK=ox,LK=ax,DK=aR,jK=lx,FK=R0,zK=cx,HK=hx,BK=ux,UK=dx,qK=fx,VK=px,WK=mx,GK=gx;function KK(n=!1){const e=[BK.default,UK.default,qK.default,VK.default,WK.default,GK.default,jK.default,FK.default,DK.default,zK.default,HK.default];return n?e.push(IK.default,NK.default):e.push(MK.default,OK.default),e.push(LK.default),e}ix.default=KK;var yx={},vx={};Object.defineProperty(vx,"__esModule",{value:!0});const Zt=Be,ZK={message:({schemaCode:n})=>(0,Zt.str)`must match format "${n}"`,params:({schemaCode:n})=>(0,Zt._)`{format: ${n}}`},XK={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:ZK,code(n,e){const{gen:t,data:s,$data:i,schema:r,schemaCode:o,it:a}=n,{opts:l,errSchemaPath:c,schemaEnv:h,self:u}=a;if(!l.validateFormats)return;i?d():p();function d(){const m=t.scopeValue("formats",{ref:u.formats,code:l.code.formats}),y=t.const("fDef",(0,Zt._)`${m}[${o}]`),v=t.let("fType"),g=t.let("format");t.if((0,Zt._)`typeof ${y} == "object" && !(${y} instanceof RegExp)`,()=>t.assign(v,(0,Zt._)`${y}.type || "string"`).assign(g,(0,Zt._)`${y}.validate`),()=>t.assign(v,(0,Zt._)`"string"`).assign(g,y)),n.fail$data((0,Zt.or)(b(),_()));function b(){return l.strictSchema===!1?Zt.nil:(0,Zt._)`${o} && !${g}`}function _(){const x=h.$async?(0,Zt._)`(${y}.async ? await ${g}(${s}) : ${g}(${s}))`:(0,Zt._)`${g}(${s})`,A=(0,Zt._)`(typeof ${g} == "function" ? ${x} : ${g}.test(${s}))`;return(0,Zt._)`${g} && ${g} !== true && ${v} === ${e} && !${A}`}}function p(){const m=u.formats[r];if(!m){b();return}if(m===!0)return;const[y,v,g]=_(m);y===e&&n.pass(x());function b(){if(l.strictSchema===!1){u.logger.warn(A());return}throw new Error(A());function A(){return`unknown format "${r}" ignored in schema at path "${c}"`}}function _(A){const C=A instanceof RegExp?(0,Zt.regexpCode)(A):l.code.formats?(0,Zt._)`${l.code.formats}${(0,Zt.getProperty)(r)}`:void 0,$=t.scopeValue("formats",{key:r,ref:A,code:C});return typeof A=="object"&&!(A instanceof RegExp)?[A.type||"string",A.validate,(0,Zt._)`${$}.validate`]:["string",A,$]}function x(){if(typeof m=="object"&&!(m instanceof RegExp)&&m.async){if(!h.$async)throw new Error("async format in sync schema");return(0,Zt._)`await ${g}(${s})`}return typeof v=="function"?(0,Zt._)`${g}(${s})`:(0,Zt._)`${g}.test(${s})`}}}};vx.default=XK;Object.defineProperty(yx,"__esModule",{value:!0});const YK=vx,JK=[YK.default];yx.default=JK;var Su={};Object.defineProperty(Su,"__esModule",{value:!0});Su.contentVocabulary=Su.metadataVocabulary=void 0;Su.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];Su.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"];Object.defineProperty(U1,"__esModule",{value:!0});const QK=q1,e9=W1,t9=ix,n9=yx,Lk=Su,s9=[QK.default,e9.default,(0,t9.default)(),n9.default,Lk.metadataVocabulary,Lk.contentVocabulary];U1.default=s9;var bx={},M0={};Object.defineProperty(M0,"__esModule",{value:!0});M0.DiscrError=void 0;var Dk;(function(n){n.Tag="tag",n.Mapping="mapping"})(Dk||(M0.DiscrError=Dk={}));Object.defineProperty(bx,"__esModule",{value:!0});const Bc=Be,Tb=M0,jk=Ls,i9=Fu,r9=pe,o9={message:({params:{discrError:n,tagName:e}})=>n===Tb.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:n,tag:e,tagName:t}})=>(0,Bc._)`{error: ${n}, tag: ${t}, tagValue: ${e}}`},a9={keyword:"discriminator",type:"object",schemaType:"object",error:o9,code(n){const{gen:e,data:t,schema:s,parentSchema:i,it:r}=n,{oneOf:o}=i;if(!r.opts.discriminator)throw new Error("discriminator: requires discriminator option");const a=s.propertyName;if(typeof a!="string")throw new Error("discriminator: requires propertyName");if(s.mapping)throw new Error("discriminator: mapping is not supported");if(!o)throw new Error("discriminator: requires oneOf keyword");const l=e.let("valid",!1),c=e.const("tag",(0,Bc._)`${t}${(0,Bc.getProperty)(a)}`);e.if((0,Bc._)`typeof ${c} == "string"`,()=>h(),()=>n.error(!1,{discrError:Tb.DiscrError.Tag,tag:c,tagName:a})),n.ok(l);function h(){const p=d();e.if(!1);for(const m in p)e.elseIf((0,Bc._)`${c} === ${m}`),e.assign(l,u(p[m]));e.else(),n.error(!1,{discrError:Tb.DiscrError.Mapping,tag:c,tagName:a}),e.endIf()}function u(p){const m=e.name("valid"),y=n.subschema({keyword:"oneOf",schemaProp:p},m);return n.mergeEvaluated(y,Bc.Name),m}function d(){var p;const m={},y=g(i);let v=!0;for(let x=0;xthis.addVocabulary(m)),this.opts.discriminator&&this.addKeyword(i.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;const m=this.opts.$data?this.$dataMetaSchema(r,o):r;this.addMetaSchema(m,a,!1),this.refs["http://json-schema.org/schema"]=a}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(a)?a:void 0)}}e.Ajv=l,n.exports=e=l,n.exports.Ajv=l,Object.defineProperty(e,"__esModule",{value:!0}),e.default=l;var c=Ji;Object.defineProperty(e,"KeywordCxt",{enumerable:!0,get:function(){return c.KeywordCxt}});var h=Be;Object.defineProperty(e,"_",{enumerable:!0,get:function(){return h._}}),Object.defineProperty(e,"str",{enumerable:!0,get:function(){return h.str}}),Object.defineProperty(e,"stringify",{enumerable:!0,get:function(){return h.stringify}}),Object.defineProperty(e,"nil",{enumerable:!0,get:function(){return h.nil}}),Object.defineProperty(e,"Name",{enumerable:!0,get:function(){return h.Name}}),Object.defineProperty(e,"CodeGen",{enumerable:!0,get:function(){return h.CodeGen}});var u=Qp;Object.defineProperty(e,"ValidationError",{enumerable:!0,get:function(){return u.default}});var d=Fu;Object.defineProperty(e,"MissingRefError",{enumerable:!0,get:function(){return d.default}})})(Sb,Sb.exports);var m9=Sb.exports;(function(n){Object.defineProperty(n,"__esModule",{value:!0}),n.formatLimitDefinition=void 0;const e=m9,t=Be,s=t.operators,i={formatMaximum:{okStr:"<=",ok:s.LTE,fail:s.GT},formatMinimum:{okStr:">=",ok:s.GTE,fail:s.LT},formatExclusiveMaximum:{okStr:"<",ok:s.LT,fail:s.GTE},formatExclusiveMinimum:{okStr:">",ok:s.GT,fail:s.LTE}},r={message:({keyword:a,schemaCode:l})=>(0,t.str)`should be ${i[a].okStr} ${l}`,params:({keyword:a,schemaCode:l})=>(0,t._)`{comparison: ${i[a].okStr}, limit: ${l}}`};n.formatLimitDefinition={keyword:Object.keys(i),type:"string",schemaType:"string",$data:!0,error:r,code(a){const{gen:l,data:c,schemaCode:h,keyword:u,it:d}=a,{opts:p,self:m}=d;if(!p.validateFormats)return;const y=new e.KeywordCxt(d,m.RULES.all.format.definition,"format");y.$data?v():g();function v(){const _=l.scopeValue("formats",{ref:m.formats,code:p.code.formats}),x=l.const("fmt",(0,t._)`${_}[${y.schemaCode}]`);a.fail$data((0,t.or)((0,t._)`typeof ${x} != "object"`,(0,t._)`${x} instanceof RegExp`,(0,t._)`typeof ${x}.compare != "function"`,b(x)))}function g(){const _=y.schema,x=m.formats[_];if(!x||x===!0)return;if(typeof x!="object"||x instanceof RegExp||typeof x.compare!="function")throw new Error(`"${u}": format "${_}" does not define "compare" function`);const A=l.scopeValue("formats",{key:_,ref:x,code:p.code.formats?(0,t._)`${p.code.formats}${(0,t.getProperty)(_)}`:void 0});a.fail$data(b(A))}function b(_){return(0,t._)`${_}.compare(${c}, ${h}) ${i[u].fail} 0`}},dependencies:["format"]};const o=a=>(a.addKeyword(n.formatLimitDefinition),a);n.default=o})(SP);(function(n,e){Object.defineProperty(e,"__esModule",{value:!0});const t=_P,s=SP,i=Be,r=new i.Name("fullFormats"),o=new i.Name("fastFormats"),a=(c,h={keywords:!0})=>{if(Array.isArray(h))return l(c,h,t.fullFormats,r),c;const[u,d]=h.mode==="fast"?[t.fastFormats,o]:[t.fullFormats,r],p=h.formats||t.formatNames;return l(c,p,u,d),h.keywords&&(0,s.default)(c),c};a.get=(c,h="full")=>{const d=(h==="fast"?t.fastFormats:t.fullFormats)[c];if(!d)throw new Error(`Unknown format "${c}"`);return d};function l(c,h,u,d){var p,m;(p=(m=c.opts.code).formats)!==null&&p!==void 0||(m.formats=(0,i._)`require("ajv-formats/dist/formats").${d}`);for(const y of h)c.addFormat(y,u[y])}n.exports=e=a,Object.defineProperty(e,"__esModule",{value:!0}),e.default=a})(_b,_b.exports);var g9=_b.exports;const y9=tS(g9);function v9(){const n=new s4({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return y9(n),n}class b9{constructor(e){this._ajv=e??v9()}getValidator(e){const t="$id"in e&&typeof e.$id=="string"?this._ajv.getSchema(e.$id)??this._ajv.compile(e):this._ajv.compile(e);return s=>t(s)?{valid:!0,data:s,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(t.errors)}}}class w9{constructor(e){this._client=e}async*callToolStream(e,t=lc,s){const i=this._client,r={...s,task:(s==null?void 0:s.task)??(i.isToolTask(e.name)?{}:void 0)},o=i.requestStream({method:"tools/call",params:e},t,r),a=i.getToolOutputValidator(e.name);for await(const l of o){if(l.type==="result"&&a){const c=l.result;if(!c.structuredContent&&!c.isError){yield{type:"error",error:new Ee(Re.InvalidRequest,`Tool ${e.name} has an output schema but did not return structured content`)};return}if(c.structuredContent)try{const h=a(c.structuredContent);if(!h.valid){yield{type:"error",error:new Ee(Re.InvalidParams,`Structured content does not match the tool's output schema: ${h.errorMessage}`)};return}}catch(h){if(h instanceof Ee){yield{type:"error",error:h};return}yield{type:"error",error:new Ee(Re.InvalidParams,`Failed to validate structured content: ${h instanceof Error?h.message:String(h)}`)};return}}yield l}}async getTask(e,t){return this._client.getTask({taskId:e},t)}async getTaskResult(e,t,s){return this._client.getTaskResult({taskId:e},t,s)}async listTasks(e,t){return this._client.listTasks(e?{cursor:e}:void 0,t)}async cancelTask(e,t){return this._client.cancelTask({taskId:e},t)}requestStream(e,t,s){return this._client.requestStream(e,t,s)}}function _9(n,e,t){var s;if(!n)throw new Error(`${t} does not support task creation (required for ${e})`);switch(e){case"tools/call":if(!((s=n.tools)!=null&&s.call))throw new Error(`${t} does not support task creation for tools/call (required for ${e})`);break}}function S9(n,e,t){var s,i;if(!n)throw new Error(`${t} does not support task creation (required for ${e})`);switch(e){case"sampling/createMessage":if(!((s=n.sampling)!=null&&s.createMessage))throw new Error(`${t} does not support task creation for sampling/createMessage (required for ${e})`);break;case"elicitation/create":if(!((i=n.elicitation)!=null&&i.create))throw new Error(`${t} does not support task creation for elicitation/create (required for ${e})`);break}}function gg(n,e){if(!(!n||e===null||typeof e!="object")){if(n.type==="object"&&n.properties&&typeof n.properties=="object"){const t=e,s=n.properties;for(const i of Object.keys(s)){const r=s[i];t[i]===void 0&&Object.prototype.hasOwnProperty.call(r,"default")&&(t[i]=r.default),t[i]!==void 0&&gg(r,t[i])}}if(Array.isArray(n.anyOf))for(const t of n.anyOf)typeof t!="boolean"&&gg(t,e);if(Array.isArray(n.oneOf))for(const t of n.oneOf)typeof t!="boolean"&&gg(t,e)}}function x9(n){if(!n)return{supportsFormMode:!1,supportsUrlMode:!1};const e=n.form!==void 0,t=n.url!==void 0;return{supportsFormMode:e||!e&&!t,supportsUrlMode:t}}class A9 extends mT{constructor(e,t){super(t),this._clientInfo=e,this._cachedToolOutputValidators=new Map,this._cachedKnownTaskTools=new Set,this._cachedRequiredTaskTools=new Set,this._listChangedDebounceTimers=new Map,this._capabilities=(t==null?void 0:t.capabilities)??{},this._jsonSchemaValidator=(t==null?void 0:t.jsonSchemaValidator)??new b9,t!=null&&t.listChanged&&(this._pendingListChangedConfig=t.listChanged)}_setupListChangedHandlers(e){var t,s,i,r,o,a;e.tools&&((s=(t=this._serverCapabilities)==null?void 0:t.tools)!=null&&s.listChanged)&&this._setupListChangedHandler("tools",LS,e.tools,async()=>(await this.listTools()).tools),e.prompts&&((r=(i=this._serverCapabilities)==null?void 0:i.prompts)!=null&&r.listChanged)&&this._setupListChangedHandler("prompts",IS,e.prompts,async()=>(await this.listPrompts()).prompts),e.resources&&((a=(o=this._serverCapabilities)==null?void 0:o.resources)!=null&&a.listChanged)&&this._setupListChangedHandler("resources",$S,e.resources,async()=>(await this.listResources()).resources)}get experimental(){return this._experimental||(this._experimental={tasks:new w9(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=SB(this._capabilities,e)}setRequestHandler(e,t){const s=fT(e),i=s==null?void 0:s.method;if(!i)throw new Error("Schema is missing a method literal");const r=pT(i);if(typeof r!="string")throw new Error("Schema method literal must be a string");const o=r;if(o==="elicitation/create"){const a=async(l,c)=>{var b,_;const h=Fo(hT,l);if(!h.success){const x=h.error instanceof Error?h.error.message:String(h.error);throw new Ee(Re.InvalidParams,`Invalid elicitation request: ${x}`)}const{params:u}=h.data;u.mode=u.mode??"form";const{supportsFormMode:d,supportsUrlMode:p}=x9(this._capabilities.elicitation);if(u.mode==="form"&&!d)throw new Ee(Re.InvalidParams,"Client does not support form-mode elicitation requests");if(u.mode==="url"&&!p)throw new Ee(Re.InvalidParams,"Client does not support URL-mode elicitation requests");const m=await Promise.resolve(t(l,c));if(u.task){const x=Fo(of,m);if(!x.success){const A=x.error instanceof Error?x.error.message:String(x.error);throw new Ee(Re.InvalidParams,`Invalid task creation result: ${A}`)}return x.data}const y=Fo(uT,m);if(!y.success){const x=y.error instanceof Error?y.error.message:String(y.error);throw new Ee(Re.InvalidParams,`Invalid elicitation result: ${x}`)}const v=y.data,g=u.mode==="form"?u.requestedSchema:void 0;if(u.mode==="form"&&v.action==="accept"&&v.content&&g&&(_=(b=this._capabilities.elicitation)==null?void 0:b.form)!=null&&_.applyDefaults)try{gg(g,v.content)}catch{}return v};return super.setRequestHandler(e,a)}if(o==="sampling/createMessage"){const a=async(l,c)=>{const h=Fo(DS,l);if(!h.success){const v=h.error instanceof Error?h.error.message:String(h.error);throw new Ee(Re.InvalidParams,`Invalid sampling request: ${v}`)}const{params:u}=h.data,d=await Promise.resolve(t(l,c));if(u.task){const v=Fo(of,d);if(!v.success){const g=v.error instanceof Error?v.error.message:String(v.error);throw new Ee(Re.InvalidParams,`Invalid task creation result: ${g}`)}return v.data}const m=u.tools||u.toolChoice?cT:lT,y=Fo(m,d);if(!y.success){const v=y.error instanceof Error?y.error.message:String(y.error);throw new Ee(Re.InvalidParams,`Invalid sampling result: ${v}`)}return y.data};return super.setRequestHandler(e,a)}return super.setRequestHandler(e,t)}assertCapability(e,t){var s;if(!((s=this._serverCapabilities)!=null&&s[e]))throw new Error(`Server does not support ${e} (required for ${t})`)}async connect(e,t){if(await super.connect(e),e.sessionId===void 0)try{const s=await this.request({method:"initialize",params:{protocolVersion:y0,capabilities:this._capabilities,clientInfo:this._clientInfo}},W$,t);if(s===void 0)throw new Error(`Server sent invalid initialize result: ${s}`);if(!Yz.includes(s.protocolVersion))throw new Error(`Server's protocol version is not supported: ${s.protocolVersion}`);this._serverCapabilities=s.capabilities,this._serverVersion=s.serverInfo,e.setProtocolVersion&&e.setProtocolVersion(s.protocolVersion),this._instructions=s.instructions,await this.notification({method:"notifications/initialized"}),this._pendingListChangedConfig&&(this._setupListChangedHandlers(this._pendingListChangedConfig),this._pendingListChangedConfig=void 0)}catch(s){throw this.close(),s}}getServerCapabilities(){return this._serverCapabilities}getServerVersion(){return this._serverVersion}getInstructions(){return this._instructions}assertCapabilityForMethod(e){var t,s,i,r,o;switch(e){case"logging/setLevel":if(!((t=this._serverCapabilities)!=null&&t.logging))throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!((s=this._serverCapabilities)!=null&&s.prompts))throw new Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":case"resources/subscribe":case"resources/unsubscribe":if(!((i=this._serverCapabilities)!=null&&i.resources))throw new Error(`Server does not support resources (required for ${e})`);if(e==="resources/subscribe"&&!this._serverCapabilities.resources.subscribe)throw new Error(`Server does not support resource subscriptions (required for ${e})`);break;case"tools/call":case"tools/list":if(!((r=this._serverCapabilities)!=null&&r.tools))throw new Error(`Server does not support tools (required for ${e})`);break;case"completion/complete":if(!((o=this._serverCapabilities)!=null&&o.completions))throw new Error(`Server does not support completions (required for ${e})`);break}}assertNotificationCapability(e){var t;switch(e){case"notifications/roots/list_changed":if(!((t=this._capabilities.roots)!=null&&t.listChanged))throw new Error(`Client does not support roots list changed notifications (required for ${e})`);break}}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case"sampling/createMessage":if(!this._capabilities.sampling)throw new Error(`Client does not support sampling capability (required for ${e})`);break;case"elicitation/create":if(!this._capabilities.elicitation)throw new Error(`Client does not support elicitation capability (required for ${e})`);break;case"roots/list":if(!this._capabilities.roots)throw new Error(`Client does not support roots capability (required for ${e})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Client does not support tasks capability (required for ${e})`);break}}assertTaskCapability(e){var t,s;_9((s=(t=this._serverCapabilities)==null?void 0:t.tasks)==null?void 0:s.requests,e,"Server")}assertTaskHandlerCapability(e){var t;this._capabilities&&S9((t=this._capabilities.tasks)==null?void 0:t.requests,e,"Client")}async ping(e){return this.request({method:"ping"},th,e)}async complete(e,t){return this.request({method:"completion/complete",params:e},dT,t)}async setLoggingLevel(e,t){return this.request({method:"logging/setLevel",params:{level:e}},th,t)}async getPrompt(e,t){return this.request({method:"prompts/get",params:e},iT,t)}async listPrompts(e,t){return this.request({method:"prompts/list",params:e},TS,t)}async listResources(e,t){return this.request({method:"resources/list",params:e},AS,t)}async listResourceTemplates(e,t){return this.request({method:"resources/templates/list",params:e},kS,t)}async readResource(e,t){return this.request({method:"resources/read",params:e},CS,t)}async subscribeResource(e,t){return this.request({method:"resources/subscribe",params:e},th,t)}async unsubscribeResource(e,t){return this.request({method:"resources/unsubscribe",params:e},th,t)}async callTool(e,t=lc,s){if(this.isToolTaskRequired(e.name))throw new Ee(Re.InvalidRequest,`Tool "${e.name}" requires task-based execution. Use client.experimental.tasks.callToolStream() instead.`);const i=await this.request({method:"tools/call",params:e},t,s),r=this.getToolOutputValidator(e.name);if(r){if(!i.structuredContent&&!i.isError)throw new Ee(Re.InvalidRequest,`Tool ${e.name} has an output schema but did not return structured content`);if(i.structuredContent)try{const o=r(i.structuredContent);if(!o.valid)throw new Ee(Re.InvalidParams,`Structured content does not match the tool's output schema: ${o.errorMessage}`)}catch(o){throw o instanceof Ee?o:new Ee(Re.InvalidParams,`Failed to validate structured content: ${o instanceof Error?o.message:String(o)}`)}}return i}isToolTask(e){var t,s,i,r;return(r=(i=(s=(t=this._serverCapabilities)==null?void 0:t.tasks)==null?void 0:s.requests)==null?void 0:i.tools)!=null&&r.call?this._cachedKnownTaskTools.has(e):!1}isToolTaskRequired(e){return this._cachedRequiredTaskTools.has(e)}cacheToolMetadata(e){var t;this._cachedToolOutputValidators.clear(),this._cachedKnownTaskTools.clear(),this._cachedRequiredTaskTools.clear();for(const s of e){if(s.outputSchema){const r=this._jsonSchemaValidator.getValidator(s.outputSchema);this._cachedToolOutputValidators.set(s.name,r)}const i=(t=s.execution)==null?void 0:t.taskSupport;(i==="required"||i==="optional")&&this._cachedKnownTaskTools.add(s.name),i==="required"&&this._cachedRequiredTaskTools.add(s.name)}}getToolOutputValidator(e){return this._cachedToolOutputValidators.get(e)}async listTools(e,t){const s=await this.request({method:"tools/list",params:e},NS,t);return this.cacheToolMetadata(s.tools),s}_setupListChangedHandler(e,t,s,i){const r=jH.safeParse(s);if(!r.success)throw new Error(`Invalid ${e} listChanged options: ${r.error.message}`);if(typeof s.onChanged!="function")throw new Error(`Invalid ${e} listChanged options: onChanged must be a function`);const{autoRefresh:o,debounceMs:a}=r.data,{onChanged:l}=s,c=async()=>{if(!o){l(null,null);return}try{const u=await i();l(null,u)}catch(u){const d=u instanceof Error?u:new Error(String(u));l(d,null)}},h=()=>{if(a){const u=this._listChangedDebounceTimers.get(e);u&&clearTimeout(u);const d=setTimeout(c,a);this._listChangedDebounceTimers.set(e,d)}else c()};this.setNotificationHandler(t,h)}async sendRootsListChanged(){return this.notification({method:"notifications/roots/list_changed"})}}var wx={};/*! + * content-type + * Copyright(c) 2015 Douglas Christopher Wilson + * MIT Licensed + */var Fk=/; *([!#$%&'*+.^_`|~0-9A-Za-z-]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'*+.^_`|~0-9A-Za-z-]+) */g,k9=/^[\u000b\u0020-\u007e\u0080-\u00ff]+$/,hR=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/,E9=/\\([\u000b\u0020-\u00ff])/g,C9=/([\\"])/g,uR=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;wx.format=$9;wx.parse=T9;function $9(n){if(!n||typeof n!="object")throw new TypeError("argument obj is required");var e=n.parameters,t=n.type;if(!t||!uR.test(t))throw new TypeError("invalid type");var s=t;if(e&&typeof e=="object")for(var i,r=Object.keys(e).sort(),o=0;o0&&!k9.test(e))throw new TypeError("invalid parameter value");return'"'+e.replace(C9,"\\$1")+'"'}function M9(n){this.parameters=Object.create(null),this.type=n}function I9(n){if(n)try{return wx.parse(n).type}catch{const e=(n.split(";",1)[0]??"").trim().toLowerCase();return e===""||n.slice(e.length).includes(",")?void 0:e}}function Pb(n){return n?n instanceof Headers?Object.fromEntries(n.entries()):Array.isArray(n)?Object.fromEntries(n):{...n}:{}}function O9(n=fetch,e){return e?async(t,s)=>{const i={...e,...s,headers:s!=null&&s.headers?{...Pb(e.headers),...Pb(s.headers)}:e.headers};return n(t,i)}:n}let _x;_x=globalThis.crypto;async function N9(n){return(await _x).getRandomValues(new Uint8Array(n))}async function L9(n){const e="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~",t=Math.pow(2,8)-Math.pow(2,8)%e.length;let s="";for(;s.length128)throw`Expected a length between 43 and 128. Received ${n}.`;const e=await D9(n),t=await j9(e);return{code_verifier:e,code_challenge:t}}const Hn=iz().superRefine((n,e)=>{if(!URL.canParse(n))return e.addIssue({code:Zz.custom,message:"URL must be parseable",fatal:!0}),WD}).refine(n=>{const e=new URL(n);return e.protocol!=="javascript:"&&e.protocol!=="data:"&&e.protocol!=="vbscript:"},{message:"URL cannot use javascript:, data:, or vbscript: scheme"}),z9=Vn({resource:F().url(),authorization_servers:re(Hn).optional(),jwks_uri:F().url().optional(),scopes_supported:re(F()).optional(),bearer_methods_supported:re(F()).optional(),resource_signing_alg_values_supported:re(F()).optional(),resource_name:F().optional(),resource_documentation:F().optional(),resource_policy_uri:F().url().optional(),resource_tos_uri:F().url().optional(),tls_client_certificate_bound_access_tokens:et().optional(),authorization_details_types_supported:re(F()).optional(),dpop_signing_alg_values_supported:re(F()).optional(),dpop_bound_access_tokens_required:et().optional()}),dR=Vn({issuer:F(),authorization_endpoint:Hn,token_endpoint:Hn,registration_endpoint:Hn.optional(),scopes_supported:re(F()).optional(),response_types_supported:re(F()),response_modes_supported:re(F()).optional(),grant_types_supported:re(F()).optional(),token_endpoint_auth_methods_supported:re(F()).optional(),token_endpoint_auth_signing_alg_values_supported:re(F()).optional(),service_documentation:Hn.optional(),revocation_endpoint:Hn.optional(),revocation_endpoint_auth_methods_supported:re(F()).optional(),revocation_endpoint_auth_signing_alg_values_supported:re(F()).optional(),introspection_endpoint:F().optional(),introspection_endpoint_auth_methods_supported:re(F()).optional(),introspection_endpoint_auth_signing_alg_values_supported:re(F()).optional(),code_challenge_methods_supported:re(F()).optional(),client_id_metadata_document_supported:et().optional()}),H9=Vn({issuer:F(),authorization_endpoint:Hn,token_endpoint:Hn,userinfo_endpoint:Hn.optional(),jwks_uri:Hn,registration_endpoint:Hn.optional(),scopes_supported:re(F()).optional(),response_types_supported:re(F()),response_modes_supported:re(F()).optional(),grant_types_supported:re(F()).optional(),acr_values_supported:re(F()).optional(),subject_types_supported:re(F()),id_token_signing_alg_values_supported:re(F()),id_token_encryption_alg_values_supported:re(F()).optional(),id_token_encryption_enc_values_supported:re(F()).optional(),userinfo_signing_alg_values_supported:re(F()).optional(),userinfo_encryption_alg_values_supported:re(F()).optional(),userinfo_encryption_enc_values_supported:re(F()).optional(),request_object_signing_alg_values_supported:re(F()).optional(),request_object_encryption_alg_values_supported:re(F()).optional(),request_object_encryption_enc_values_supported:re(F()).optional(),token_endpoint_auth_methods_supported:re(F()).optional(),token_endpoint_auth_signing_alg_values_supported:re(F()).optional(),display_values_supported:re(F()).optional(),claim_types_supported:re(F()).optional(),claims_supported:re(F()).optional(),service_documentation:F().optional(),claims_locales_supported:re(F()).optional(),ui_locales_supported:re(F()).optional(),claims_parameter_supported:et().optional(),request_parameter_supported:et().optional(),request_uri_parameter_supported:et().optional(),require_request_uri_registration:et().optional(),op_policy_uri:Hn.optional(),op_tos_uri:Hn.optional(),client_id_metadata_document_supported:et().optional()}),B9=K({...H9.shape,...dR.pick({code_challenge_methods_supported:!0}).shape}),U9=K({access_token:F(),id_token:F().optional(),token_type:F(),expires_in:Xz().optional(),scope:F().optional(),refresh_token:F().optional()}).strip(),q9=K({error:F(),error_description:F().optional(),error_uri:F().optional()}),zk=Hn.optional().or(W("").transform(()=>{})),V9=K({redirect_uris:re(Hn),token_endpoint_auth_method:F().optional(),grant_types:re(F()).optional(),response_types:re(F()).optional(),client_name:F().optional(),client_uri:Hn.optional(),logo_uri:zk,scope:F().optional(),contacts:re(F()).optional(),tos_uri:zk,policy_uri:F().optional(),jwks_uri:Hn.optional(),jwks:hS().optional(),software_id:F().optional(),software_version:F().optional(),software_statement:F().optional()}).strip(),W9=K({client_id:F(),client_secret:F().optional(),client_id_issued_at:je().optional(),client_secret_expires_at:je().optional()}).strip(),G9=V9.merge(W9);K({error:F(),error_description:F().optional()}).strip();K({token:F(),token_type_hint:F().optional()}).strip();function K9(n){const e=typeof n=="string"?new URL(n):new URL(n.href);return e.hash="",e}function Z9({requestedResource:n,configuredResource:e}){const t=typeof n=="string"?new URL(n):new URL(n.href),s=typeof e=="string"?new URL(e):new URL(e.href);if(t.origin!==s.origin||t.pathname.length=400&&n.status<500&&e!=="/"}async function a6(n,e,t,s){const i=new URL(n),r=(s==null?void 0:s.protocolVersion)??y0;let o;if(s!=null&&s.metadataUrl)o=new URL(s.metadataUrl);else{const l=r6(e,i.pathname);o=new URL(l,(s==null?void 0:s.metadataServerUrl)??i),o.search=i.search}let a=await Bk(o,r,t);if(!(s!=null&&s.metadataUrl)&&o6(a,i.pathname)){const l=new URL(`/.well-known/${e}`,i);a=await Bk(l,r,t)}return a}function l6(n){const e=typeof n=="string"?new URL(n):n,t=e.pathname!=="/",s=[];if(!t)return s.push({url:new URL("/.well-known/oauth-authorization-server",e.origin),type:"oauth"}),s.push({url:new URL("/.well-known/openid-configuration",e.origin),type:"oidc"}),s;let i=e.pathname;return i.endsWith("/")&&(i=i.slice(0,-1)),s.push({url:new URL(`/.well-known/oauth-authorization-server${i}`,e.origin),type:"oauth"}),s.push({url:new URL(`/.well-known/openid-configuration${i}`,e.origin),type:"oidc"}),s.push({url:new URL(`${i}/.well-known/openid-configuration`,e.origin),type:"oidc"}),s}async function mR(n,{fetchFn:e=fetch,protocolVersion:t=y0}={}){var r;const s={"MCP-Protocol-Version":t,Accept:"application/json"},i=l6(n);for(const{url:o,type:a}of i){const l=await Sx(o,s,e);if(l){if(!l.ok){if(await((r=l.body)==null?void 0:r.cancel()),l.status>=400&&l.status<500)continue;throw new Error(`HTTP ${l.status} trying to load ${a==="oauth"?"OAuth":"OpenID provider"} metadata from ${o}`)}return a==="oauth"?dR.parse(await l.json()):B9.parse(await l.json())}}}async function c6(n,e){let t,s;try{t=await pR(n,{resourceMetadataUrl:e==null?void 0:e.resourceMetadataUrl},e==null?void 0:e.fetchFn),t.authorization_servers&&t.authorization_servers.length>0&&(s=t.authorization_servers[0])}catch{}s||(s=String(new URL("/",n)));const i=await mR(s,{fetchFn:e==null?void 0:e.fetchFn});return{authorizationServerUrl:s,authorizationServerMetadata:i,resourceMetadata:t}}async function h6(n,{metadata:e,clientInformation:t,redirectUrl:s,scope:i,state:r,resource:o}){let a;if(e){if(a=new URL(e.authorization_endpoint),!e.response_types_supported.includes(Sv))throw new Error(`Incompatible auth server: does not support response type ${Sv}`);if(e.code_challenge_methods_supported&&!e.code_challenge_methods_supported.includes(xv))throw new Error(`Incompatible auth server: does not support code challenge method ${xv}`)}else a=new URL("/authorize",n);const l=await F9(),c=l.code_verifier,h=l.code_challenge;return a.searchParams.set("response_type",Sv),a.searchParams.set("client_id",t.client_id),a.searchParams.set("code_challenge",h),a.searchParams.set("code_challenge_method",xv),a.searchParams.set("redirect_uri",String(s)),r&&a.searchParams.set("state",r),i&&a.searchParams.set("scope",i),i!=null&&i.includes("offline_access")&&a.searchParams.append("prompt","consent"),o&&a.searchParams.set("resource",o.href),{authorizationUrl:a,codeVerifier:c}}function u6(n,e,t){return new URLSearchParams({grant_type:"authorization_code",code:n,code_verifier:e,redirect_uri:String(t)})}async function gR(n,{metadata:e,tokenRequestParams:t,clientInformation:s,addClientAuthentication:i,resource:r,fetchFn:o}){const a=e!=null&&e.token_endpoint?new URL(e.token_endpoint):new URL("/token",n),l=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"});if(r&&t.set("resource",r.href),i)await i(l,t,a,e);else if(s){const h=(e==null?void 0:e.token_endpoint_auth_methods_supported)??[],u=J9(s,h);Q9(u,s,l,t)}const c=await(o??fetch)(a,{method:"POST",headers:l,body:t});if(!c.ok)throw await fR(c);return U9.parse(await c.json())}async function d6(n,{metadata:e,clientInformation:t,refreshToken:s,resource:i,addClientAuthentication:r,fetchFn:o}){const a=new URLSearchParams({grant_type:"refresh_token",refresh_token:s}),l=await gR(n,{metadata:e,tokenRequestParams:a,clientInformation:t,addClientAuthentication:r,resource:i,fetchFn:o});return{refresh_token:s,...l}}async function f6(n,e,{metadata:t,resource:s,authorizationCode:i,fetchFn:r}={}){const o=n.clientMetadata.scope;let a;if(n.prepareTokenRequest&&(a=await n.prepareTokenRequest(o)),!a){if(!i)throw new Error("Either provider.prepareTokenRequest() or authorizationCode is required");if(!n.redirectUrl)throw new Error("redirectUrl is required for authorization_code flow");const c=await n.codeVerifier();a=u6(i,c,n.redirectUrl)}const l=await n.clientInformation();return gR(e,{metadata:t,tokenRequestParams:a,clientInformation:l??void 0,addClientAuthentication:n.addClientAuthentication,resource:s,fetchFn:r})}async function p6(n,{metadata:e,clientMetadata:t,scope:s,fetchFn:i}){let r;if(e){if(!e.registration_endpoint)throw new Error("Incompatible auth server: does not support dynamic client registration");r=new URL(e.registration_endpoint)}else r=new URL("/register",n);const o=await(i??fetch)(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...t,...s!==void 0?{scope:s}:{}})});if(!o.ok)throw await fR(o);return G9.parse(await o.json())}class Ev extends Error{constructor(e,t){super(e),this.name="ParseError",this.type=t.type,this.field=t.field,this.value=t.value,this.line=t.line}}const Uk=10,m6=13,Ua=32;function Cv(n){}function g6(n){if(typeof n=="function")throw new TypeError("`config` must be an object, got a function instead. Did you mean `createParser({onEvent: fn})`?");const{onEvent:e=Cv,onError:t=Cv,onRetry:s=Cv,onComment:i,maxBufferSize:r}=n,o=[];let a=0,l=!0,c,h="",u=0,d,p=!1;function m(A){if(p)throw new Error("Cannot feed parser: it was terminated after exceeding the configured max buffer size. Call `reset()` to resume parsing.");if(l&&(l=!1,A.charCodeAt(0)===239&&A.charCodeAt(1)===187&&A.charCodeAt(2)===191&&(A=A.slice(3))),o.length===0){const I=v(A);I!==""&&(o.push(I),a=I.length),y();return}if(A.indexOf(` +`)===-1&&A.indexOf("\r")===-1){o.push(A),a+=A.length,y();return}o.push(A);const C=o.join("");o.length=0,a=0;const $=v(C);$!==""&&(o.push($),a=$.length),y()}function y(){r!==void 0&&(a+h.length<=r||(p=!0,o.length=0,a=0,c=void 0,h="",u=0,d=void 0,t(new Ev(`Buffered data exceeded max buffer size of ${r} characters`,{type:"max-buffer-size-exceeded"}))))}function v(A){let C=0;if(A.indexOf("\r")===-1){let $=A.indexOf(` +`,C);for(;$!==-1;){if(C===$){u>0&&e({id:c,event:d,data:h}),c=void 0,h="",u=0,d=void 0,C=$+1,$=A.indexOf(` +`,C);continue}const I=A.charCodeAt(C);if(qk(A,C,I)){const j=A.charCodeAt(C+5)===Ua?C+6:C+5,q=A.slice(j,$);if(u===0&&A.charCodeAt($+1)===Uk){e({id:c,event:d,data:q}),c=void 0,h="",d=void 0,C=$+2,$=A.indexOf(` +`,C);continue}h=u===0?q:`${h} +${q}`,u++}else Vk(A,C,I)?d=A.slice(A.charCodeAt(C+6)===Ua?C+7:C+6,$)||void 0:g(A,C,$);C=$+1,$=A.indexOf(` +`,C)}return A.slice(C)}for(;C20?`${A.slice(0,20)}…`:A}"`,{type:"unknown-field",field:A,value:C,line:$}));break}}function _(){u>0&&e({id:c,event:d,data:h}),c=void 0,h="",u=0,d=void 0}function x(A={}){if(A.consume&&o.length>0){const C=o.join("");g(C,0,C.length)}l=!0,c=void 0,h="",u=0,d=void 0,o.length=0,a=0,p=!1}return{feed:m,reset:x}}function qk(n,e,t){return t===100&&n.charCodeAt(e+1)===97&&n.charCodeAt(e+2)===116&&n.charCodeAt(e+3)===97&&n.charCodeAt(e+4)===58}function Vk(n,e,t){return t===101&&n.charCodeAt(e+1)===118&&n.charCodeAt(e+2)===101&&n.charCodeAt(e+3)===110&&n.charCodeAt(e+4)===116&&n.charCodeAt(e+5)===58}class y6 extends TransformStream{constructor({onError:e,onRetry:t,onComment:s,maxBufferSize:i}={}){let r;super({start(o){r=g6({onEvent:a=>{o.enqueue(a)},onError(a){typeof e=="function"&&e(a),(e==="terminate"||a.type==="max-buffer-size-exceeded")&&o.error(a)},onRetry:t,onComment:s,maxBufferSize:i})},transform(o){r.feed(o)}})}}const v6={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2};class zc extends Error{constructor(e,t){super(`Streamable HTTP error: ${t}`),this.code=e}}class b6{constructor(e,t){this._hasCompletedAuthFlow=!1,this._url=e,this._resourceMetadataUrl=void 0,this._scope=void 0,this._requestInit=t==null?void 0:t.requestInit,this._authProvider=t==null?void 0:t.authProvider,this._fetch=t==null?void 0:t.fetch,this._fetchWithInit=O9(t==null?void 0:t.fetch,t==null?void 0:t.requestInit),this._sessionId=t==null?void 0:t.sessionId,this._reconnectionOptions=(t==null?void 0:t.reconnectionOptions)??v6}async _authThenStart(){var t;if(!this._authProvider)throw new Fc("No auth provider");let e;try{e=await Im(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(s){throw(t=this.onerror)==null||t.call(this,s),s}if(e!=="AUTHORIZED")throw new Fc;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){var s;const e={};if(this._authProvider){const i=await this._authProvider.tokens();i&&(e.Authorization=`Bearer ${i.access_token}`)}this._sessionId&&(e["mcp-session-id"]=this._sessionId),this._protocolVersion&&(e["mcp-protocol-version"]=this._protocolVersion);const t=Pb((s=this._requestInit)==null?void 0:s.headers);return new Headers({...e,...t})}async _startOrAuthSse(e){var s,i,r;const{resumptionToken:t}=e;try{const o=await this._commonHeaders();o.set("Accept","text/event-stream"),t&&o.set("last-event-id",t);const a=await(this._fetch??fetch)(this._url,{method:"GET",headers:o,signal:(s=this._abortController)==null?void 0:s.signal});if(!a.ok){if(await((i=a.body)==null?void 0:i.cancel()),a.status===401&&this._authProvider)return await this._authThenStart();if(a.status===405)return;throw new zc(a.status,`Failed to open SSE stream: ${a.statusText}`)}this._handleSseStream(a.body,e,!0)}catch(o){throw(r=this.onerror)==null||r.call(this,o),o}}_getNextReconnectionDelay(e){if(this._serverRetryMs!==void 0)return this._serverRetryMs;const t=this._reconnectionOptions.initialReconnectionDelay,s=this._reconnectionOptions.reconnectionDelayGrowFactor,i=this._reconnectionOptions.maxReconnectionDelay;return Math.min(t*Math.pow(s,e),i)}_scheduleReconnection(e,t=0){var r;const s=this._reconnectionOptions.maxRetries;if(t>=s){(r=this.onerror)==null||r.call(this,new Error(`Maximum reconnection attempts (${s}) exceeded.`));return}const i=this._getNextReconnectionDelay(t);this._reconnectionTimeout=setTimeout(()=>{this._startOrAuthSse(e).catch(o=>{var a;(a=this.onerror)==null||a.call(this,new Error(`Failed to reconnect SSE stream: ${o instanceof Error?o.message:String(o)}`)),this._scheduleReconnection(e,t+1)})},i)}_handleSseStream(e,t,s){if(!e)return;const{onresumptiontoken:i,replayMessageId:r}=t;let o,a=!1,l=!1;(async()=>{var h,u,d,p;try{const m=e.pipeThrough(new TextDecoderStream).pipeThrough(new y6({onRetry:g=>{this._serverRetryMs=g}})).getReader();for(;;){const{value:g,done:b}=await m.read();if(b)break;if(g.id&&(o=g.id,a=!0,i==null||i(g.id)),!!g.data&&(!g.event||g.event==="message"))try{const _=og.parse(JSON.parse(g.data));dd(_)&&(l=!0,r!==void 0&&(_.id=r)),(h=this.onmessage)==null||h.call(this,_)}catch(_){(u=this.onerror)==null||u.call(this,_)}}(s||a)&&!l&&this._abortController&&!this._abortController.signal.aborted&&this._scheduleReconnection({resumptionToken:o,onresumptiontoken:i,replayMessageId:r},0)}catch(m){if((d=this.onerror)==null||d.call(this,new Error(`SSE stream disconnected: ${m}`)),(s||a)&&!l&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:o,onresumptiontoken:i,replayMessageId:r},0)}catch(g){(p=this.onerror)==null||p.call(this,new Error(`Failed to reconnect: ${g instanceof Error?g.message:String(g)}`))}}})()}async start(){if(this._abortController)throw new Error("StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.");this._abortController=new AbortController}async finishAuth(e){if(!this._authProvider)throw new Fc("No auth provider");if(await Im(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new Fc("Failed to authorize")}async close(){var e,t;this._reconnectionTimeout&&(clearTimeout(this._reconnectionTimeout),this._reconnectionTimeout=void 0),(e=this._abortController)==null||e.abort(),(t=this.onclose)==null||t.call(this)}async send(e,t){var s,i,r,o,a,l;try{const{resumptionToken:c,onresumptiontoken:h}=t||{};if(c){this._startOrAuthSse({resumptionToken:c,replayMessageId:hb(e)?e.id:void 0}).catch(_=>{var x;return(x=this.onerror)==null?void 0:x.call(this,_)});return}const u=await this._commonHeaders();u.set("content-type","application/json"),u.set("accept","application/json, text/event-stream");const d={...this._requestInit,method:"POST",headers:u,body:JSON.stringify(e),signal:(s=this._abortController)==null?void 0:s.signal},p=await(this._fetch??fetch)(this._url,d),m=p.headers.get("mcp-session-id");if(m&&(this._sessionId=m),!p.ok){const _=await p.text().catch(()=>null);if(p.status===401&&this._authProvider){if(this._hasCompletedAuthFlow)throw new zc(401,"Server returned 401 after successful authentication");const{resourceMetadataUrl:x,scope:A}=Hk(p);if(this._resourceMetadataUrl=x,this._scope=A,await Im(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new Fc;return this._hasCompletedAuthFlow=!0,this.send(e)}if(p.status===403&&this._authProvider){const{resourceMetadataUrl:x,scope:A,error:C}=Hk(p);if(C==="insufficient_scope"){const $=p.headers.get("WWW-Authenticate");if(this._lastUpscopingHeader===$)throw new zc(403,"Server returned 403 after trying upscoping");if(A&&(this._scope=A),x&&(this._resourceMetadataUrl=x),this._lastUpscopingHeader=$??void 0,await Im(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})!=="AUTHORIZED")throw new Fc;return this.send(e)}}throw new zc(p.status,`Error POSTing to endpoint: ${_}`)}if(this._hasCompletedAuthFlow=!1,this._lastUpscopingHeader=void 0,p.status===202){await((i=p.body)==null?void 0:i.cancel()),fH(e)&&this._startOrAuthSse({resumptionToken:void 0}).catch(_=>{var x;return(x=this.onerror)==null?void 0:x.call(this,_)});return}const v=(Array.isArray(e)?e:[e]).filter(_=>"method"in _&&"id"in _&&_.id!==void 0).length>0,g=p.headers.get("content-type"),b=I9(g);if(v)if(b==="text/event-stream")this._handleSseStream(p.body,{onresumptiontoken:h},!1);else if(b==="application/json"){const _=await p.json(),x=Array.isArray(_)?_.map(A=>og.parse(A)):[og.parse(_)];for(const A of x)(r=this.onmessage)==null||r.call(this,A)}else throw await((o=p.body)==null?void 0:o.cancel()),new zc(-1,`Unexpected content type: ${g}`);else await((a=p.body)==null?void 0:a.cancel())}catch(c){throw(l=this.onerror)==null||l.call(this,c),c}}get sessionId(){return this._sessionId}async terminateSession(){var e,t,s;if(this._sessionId)try{const i=await this._commonHeaders(),r={...this._requestInit,method:"DELETE",headers:i,signal:(e=this._abortController)==null?void 0:e.signal},o=await(this._fetch??fetch)(this._url,r);if(await((t=o.body)==null?void 0:t.cancel()),!o.ok&&o.status!==405)throw new zc(o.status,`Failed to terminate session: ${o.statusText}`);this._sessionId=void 0}catch(i){throw(s=this.onerror)==null||s.call(this,i),i}}setProtocolVersion(e){this._protocolVersion=e}get protocolVersion(){return this._protocolVersion}async resumeStream(e,t){await this._startOrAuthSse({resumptionToken:e,onresumptiontoken:t==null?void 0:t.onresumptiontoken})}}const w6="https://mcp.excalidraw.com/mcp",_6="mcp.excalidraw.com",S6="/api/v1/chat/mcp-apps/excalidraw",yR="ui://excalidraw/mcp-app.html",x6=["read_me","create_view"],vR=new Set(["export_to_excalidraw","save_checkpoint","read_checkpoint"]),A6=256*1024,k6=1024*1024,E6=1024*1024,C6=240,$6=720,T6=525;function P6(n){return!Number.isFinite(n)||n<=0?T6:Math.max(C6,Math.min($6,Math.round(n*3/4)))}const R6={excalidraw:{id:"excalidraw",endpoint:w6,hostname:_6,resourceUri:yR,modelTools:x6,appTools:vR}};function M6(n){return R6[n]}function I6(){return new URL(on(S6),window.location.origin)}class O6{constructor(){oe(this,"client",new A9({name:"pwc-chat-mcp-app-host",version:"1"}));oe(this,"transport",new b6(I6(),{requestInit:{credentials:"include"}}));oe(this,"connected");oe(this,"bytes",0);oe(this,"closed",!1)}connect(){return this.closed?Promise.reject(new Error("App host client is closed")):(this.connected||(this.connected=this.client.connect(this.transport).then(()=>{},e=>{throw this.connected=void 0,this.retire(),e})),this.connected)}async readResource(e){if(e!==yR)throw new Error("Unapproved App resource");await this.connect();const s=(await this.client.readResource({uri:e})).contents[0];if(!s||!("text"in s)||typeof s.text!="string"||s.mimeType!=="text/html;profile=mcp-app")throw new Error("Incompatible App resource");this.consume(s.text,E6);const i=await j6(s.text);return{text:s.text,digest:i}}async callTool(e,t){if(!vR.has(e))throw new Error("Unapproved App tool");const s=JSON.stringify(t);this.consume(s);try{await this.connect();const i=await this.client.callTool({name:e,arguments:t});return this.consume(JSON.stringify(i)),i}catch(i){throw this.retire(),i}}close(){this.closed=!0,this.connected=void 0,this.transport.close()}retire(){this.close(),_a===this&&(_a=void 0)}consume(e,t=A6){const s=new TextEncoder().encode(e).byteLength;if(s>t||this.bytes+s>k6)throw new Error("App request exceeds host limit");this.bytes+=s}}let _a;function N6(){return _a??(_a=new O6),_a}function L6(){_a==null||_a.close(),_a=void 0}function D6(n){L6()}async function j6(n){const e=new TextEncoder().encode(n),t=await crypto.subtle.digest("SHA-256",e);return[...new Uint8Array(t)].map(s=>s.toString(16).padStart(2,"0")).join("")}function F6(n,e){let t=!1,s=0;const i=()=>{t||!n.contentWindow||(t=!0,e())};n.addEventListener("load",i);const r=window.requestAnimationFrame(()=>{s=window.requestAnimationFrame(i)});return()=>{t=!0,n.removeEventListener("load",i),window.cancelAnimationFrame(r),window.cancelAnimationFrame(s)}}const z6=({block:n})=>{const e=ee.useRef(null),t=ee.useRef(null),s=ee.useRef(!1),i=ee.useRef(n),r=ee.useRef(!1);i.current=n;const[o,a]=ee.useState(),[l,c]=ee.useState("loading"),[h,u]=ee.useState(n.height),[d,p]=ee.useState(!1),[m,y]=ee.useState(0),v=ee.useRef(null),g=n.input.elements,b=!!n.permissions.clipboardWrite;r.current=d;const _=ee.useCallback(()=>{p(!1),document.fullscreenElement&&document.exitFullscreen()},[]),x=ee.useCallback(()=>{var $,I;if(d){_();return}p(!0),(I=($=v.current)==null?void 0:$.requestFullscreen)==null||I.call($).catch(()=>{})},[_,d]),A=ee.useCallback(()=>{D6(),a(void 0),c("loading"),y($=>$+1)},[]);ee.useEffect(()=>{const $=v.current;if(!$)return;const I=()=>{r.current||u(P6($.clientWidth))};I();const j=new ResizeObserver(I);return j.observe($),()=>j.disconnect()},[]),ee.useEffect(()=>{if(!d)return;const $=v.current,I=q=>{q.key==="Escape"&&(document.fullscreenElement||_())},j=()=>{document.fullscreenElement||p(!1)};return window.addEventListener("keydown",I),document.addEventListener("fullscreenchange",j),()=>{window.removeEventListener("keydown",I),document.removeEventListener("fullscreenchange",j),document.fullscreenElement===$&&document.exitFullscreen()}},[_,d]),ee.useEffect(()=>{M6(n.provider);{c("unavailable");return}},[m,n.provider,n.resource_uri]),ee.useEffect(()=>{if(!o||l!=="ready")return;const $=e.current;if(!$)return;let I=null;const j=[],q=F6($,()=>{$.contentWindow&&(I=new VB(null,{name:"Papers with Code",version:"1"},{serverTools:{},openLinks:{},logging:{},...b?{clipboard:{write:{}}}:{}},{hostContext:{theme:document.documentElement.dataset.theme==="dark"?"dark":"light",displayMode:d?"fullscreen":"inline"}}),I.oncalltool=async({name:L,arguments:B})=>{if(i.current.public_fork&&L!=="export_to_excalidraw")throw new Error("Shared diagrams cannot mutate owner state");return N6().callTool(L,B??{})},I.onopenlink=async({url:L})=>{const B=new URL(L);if(B.protocol!=="https:"||B.hostname!=="excalidraw.com")throw new Error("External navigation denied");if(!window.confirm("This export opens Excalidraw and uploads the diagram to its service. Continue?"))throw new Error("Export cancelled");return window.open(B.href,"_blank","noopener,noreferrer"),{}},I.onsizechange=()=>{},I.oninitialized=()=>{const L=I;if(!L){c("error");return}s.current=!0;try{const B=JSON.parse(g),H={arguments:{elements:Array.isArray(B)?eU(B):B}};for(const D of[0,50,200,750])j.push(window.setTimeout(()=>{t.current===L&&L.sendToolInput(H)},D));L.sendToolResult(i.current.result)}catch{c("error")}},t.current=I,I.connect(new UB($.contentWindow??void 0,$.contentWindow)).catch(()=>c("error")))});return()=>{q(),j.forEach(L=>window.clearTimeout(L)),s.current=!1,I==null||I.teardownResource({}).catch(()=>{}),t.current===I&&(t.current=null)}},[o,l,d,g,b,m]),ee.useEffect(()=>{var $;l!=="ready"||!s.current||($=t.current)==null||$.sendToolResult(n.result).catch(()=>{})},[n.result,l]);const C=l==="unavailable"||l==="incompatible"||l==="error";return S.jsxs("section",{ref:v,className:`chat-mcp-app${d?" chat-mcp-app-fullscreen":""}`,"aria-label":"Interactive Excalidraw diagram",children:[S.jsx("header",{children:S.jsx("button",{type:"button",onClick:x,children:d?"Exit fullscreen":"Fullscreen"})}),l==="loading"&&S.jsx("div",{className:"chat-mcp-loading",role:"status",children:"Loading interactive diagram…"}),C&&S.jsxs("div",{className:"chat-mcp-error",children:["Interactive diagram unavailable. The cited text answer is still available.",S.jsx("button",{type:"button",onClick:A,children:"Retry diagram"})]}),o&&l==="ready"&&S.jsx("iframe",{ref:e,title:"Interactive Excalidraw diagram",sandbox:"allow-scripts",allow:b?"clipboard-write":void 0,srcDoc:o,style:{height:h}},m)]})};var Kd={};Kd.d=(n,e)=>{for(var t in e)Kd.o(e,t)&&!Kd.o(n,t)&&Object.defineProperty(n,t,{enumerable:!0,get:e[t]})};Kd.o=(n,e)=>Object.prototype.hasOwnProperty.call(n,e);var Me=globalThis.pdfjsLib={};Kd.d(Me,{AbortException:()=>$c,AnnotationEditorLayer:()=>e_,AnnotationEditorParamsType:()=>Te,AnnotationEditorType:()=>De,AnnotationEditorUIManager:()=>mc,AnnotationLayer:()=>jZ,AnnotationMode:()=>Bo,ColorPicker:()=>xy,DOMSVGFactory:()=>Ox,DrawLayer:()=>i_,FeatureTest:()=>bs,GlobalWorkerOptions:()=>yo,ImageKind:()=>yg,InvalidPDFException:()=>wR,MissingPDFException:()=>Cc,OPS:()=>Mi,OutputScale:()=>Gb,PDFDataRangeTransport:()=>gM,PDFDateString:()=>Cx,PDFWorker:()=>dh,PasswordResponses:()=>q6,PermissionFlag:()=>U6,PixelsPerInch:()=>Ta,RenderingCancelledException:()=>kx,TextLayer:()=>_w,UnexpectedResponseException:()=>L0,Util:()=>Se,VerbosityLevel:()=>I0,XfaLayer:()=>vM,build:()=>vZ,createValidAbsoluteUrl:()=>K6,fetchData:()=>j0,getDocument:()=>cZ,getFilenameFromUrl:()=>s8,getPdfFilenameFromUrl:()=>i8,getXfaPageViewport:()=>r8,isDataScheme:()=>F0,isPdfFile:()=>Ex,noContextMenu:()=>Si,normalizeUnicode:()=>e8,setLayerDimensions:()=>pc,shadow:()=>Xe,version:()=>yZ});const ls=typeof process=="object"&&process+""=="[object process]"&&!process.versions.nw&&!(process.versions.electron&&process.type&&process.type!=="browser"),bR=[1,0,0,1,0,0],Ub=[.001,0,0,.001,0,0],H6=1e7,$v=1.35,Qs={ANY:1,DISPLAY:2,PRINT:4,ANNOTATIONS_FORMS:16,ANNOTATIONS_STORAGE:32,ANNOTATIONS_DISABLE:64,IS_EDITING:128,OPLIST:256},Bo={DISABLE:0,ENABLE:1,ENABLE_FORMS:2,ENABLE_STORAGE:3},B6="pdfjs_internal_editor_",De={DISABLE:-1,NONE:0,FREETEXT:3,HIGHLIGHT:9,STAMP:13,INK:15},Te={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},U6={PRINT:4,MODIFY_CONTENTS:8,COPY:16,MODIFY_ANNOTATIONS:32,FILL_INTERACTIVE_FORMS:256,COPY_FOR_ACCESSIBILITY:512,ASSEMBLE:1024,PRINT_HIGH_QUALITY:2048},es={FILL:0,STROKE:1,FILL_STROKE:2,INVISIBLE:3,FILL_STROKE_MASK:3,ADD_TO_PATH_FLAG:4},yg={GRAYSCALE_1BPP:1,RGB_24BPP:2,RGBA_32BPP:3},hn={TEXT:1,LINK:2,FREETEXT:3,LINE:4,SQUARE:5,CIRCLE:6,POLYGON:7,POLYLINE:8,HIGHLIGHT:9,UNDERLINE:10,SQUIGGLY:11,STRIKEOUT:12,STAMP:13,CARET:14,INK:15,POPUP:16,FILEATTACHMENT:17,WIDGET:20},sd={SOLID:1,DASHED:2,BEVELED:3,INSET:4,UNDERLINE:5},I0={ERRORS:0,WARNINGS:1,INFOS:5},Mi={dependency:1,setLineWidth:2,setLineCap:3,setLineJoin:4,setMiterLimit:5,setDash:6,setRenderingIntent:7,setFlatness:8,setGState:9,save:10,restore:11,transform:12,moveTo:13,lineTo:14,curveTo:15,curveTo2:16,curveTo3:17,closePath:18,rectangle:19,stroke:20,closeStroke:21,fill:22,eoFill:23,fillStroke:24,eoFillStroke:25,closeFillStroke:26,closeEOFillStroke:27,endPath:28,clip:29,eoClip:30,beginText:31,endText:32,setCharSpacing:33,setWordSpacing:34,setHScale:35,setLeading:36,setFont:37,setTextRenderingMode:38,setTextRise:39,moveText:40,setLeadingMoveText:41,setTextMatrix:42,nextLine:43,showText:44,showSpacedText:45,nextLineShowText:46,nextLineSetSpacingShowText:47,setCharWidth:48,setCharWidthAndBounds:49,setStrokeColorSpace:50,setFillColorSpace:51,setStrokeColor:52,setStrokeColorN:53,setFillColor:54,setFillColorN:55,setStrokeGray:56,setFillGray:57,setStrokeRGBColor:58,setFillRGBColor:59,setStrokeCMYKColor:60,setFillCMYKColor:61,shadingFill:62,beginInlineImage:63,beginImageData:64,endInlineImage:65,paintXObject:66,markPoint:67,markPointProps:68,beginMarkedContent:69,beginMarkedContentProps:70,endMarkedContent:71,beginCompat:72,endCompat:73,paintFormXObjectBegin:74,paintFormXObjectEnd:75,beginGroup:76,endGroup:77,beginAnnotation:80,endAnnotation:81,paintImageMaskXObject:83,paintImageMaskXObjectGroup:84,paintImageXObject:85,paintInlineImageXObject:86,paintInlineImageXObjectGroup:87,paintImageXObjectRepeat:88,paintImageMaskXObjectRepeat:89,paintSolidColorImageMask:90,constructPath:91,setStrokeTransparent:92,setFillTransparent:93},q6={NEED_PASSWORD:1,INCORRECT_PASSWORD:2};let O0=I0.WARNINGS;function V6(n){Number.isInteger(n)&&(O0=n)}function W6(){return O0}function N0(n){O0>=I0.INFOS&&console.log(`Info: ${n}`)}function qe(n){O0>=I0.WARNINGS&&console.log(`Warning: ${n}`)}function Tt(n){throw new Error(n)}function yn(n,e){n||Tt(e)}function G6(n){switch(n==null?void 0:n.protocol){case"http:":case"https:":case"ftp:":case"mailto:":case"tel:":return!0;default:return!1}}function K6(n,e=null,t=null){if(!n)return null;try{if(t&&typeof n=="string"){if(t.addDefaultProtocol&&n.startsWith("www.")){const i=n.match(/\./g);(i==null?void 0:i.length)>=2&&(n=`http://${n}`)}if(t.tryConvertEncoding)try{n=Q6(n)}catch{}}const s=e?new URL(n,e):new URL(n);if(G6(s))return s}catch{}return null}function Xe(n,e,t,s=!1){return Object.defineProperty(n,e,{value:t,enumerable:!s,configurable:!0,writable:!1}),t}const Da=function(){function e(t,s){this.message=t,this.name=s}return e.prototype=new Error,e.constructor=e,e}();class qb extends Da{constructor(e,t){super(e,"PasswordException"),this.code=t}}class Vb extends Da{constructor(e,t){super(e,"UnknownErrorException"),this.details=t}}class wR extends Da{constructor(e){super(e,"InvalidPDFException")}}class Cc extends Da{constructor(e){super(e,"MissingPDFException")}}class L0 extends Da{constructor(e,t){super(e,"UnexpectedResponseException"),this.status=t}}class Z6 extends Da{constructor(e){super(e,"FormatError")}}class $c extends Da{constructor(e){super(e,"AbortException")}}function _R(n){(typeof n!="object"||(n==null?void 0:n.length)===void 0)&&Tt("Invalid argument for bytesToString");const e=n.length,t=8192;if(e>24&255,n>>16&255,n>>8&255,n&255)}function xx(n){const e=Object.create(null);for(const[t,s]of n)e[t]=s;return e}function Y6(){const n=new Uint8Array(4);return n[0]=1,new Uint32Array(n.buffer,0,1)[0]===1}function J6(){try{return new Function(""),!0}catch{return!1}}class bs{static get isLittleEndian(){return Xe(this,"isLittleEndian",Y6())}static get isEvalSupported(){return Xe(this,"isEvalSupported",J6())}static get isOffscreenCanvasSupported(){return Xe(this,"isOffscreenCanvasSupported",typeof OffscreenCanvas<"u")}static get platform(){return typeof navigator<"u"&&typeof(navigator==null?void 0:navigator.platform)=="string"?Xe(this,"platform",{isMac:navigator.platform.includes("Mac"),isWindows:navigator.platform.includes("Win"),isFirefox:typeof(navigator==null?void 0:navigator.userAgent)=="string"&&navigator.userAgent.includes("Firefox")}):Xe(this,"platform",{isMac:!1,isWindows:!1,isFirefox:!1})}static get isCSSRoundSupported(){var e,t;return Xe(this,"isCSSRoundSupported",(t=(e=globalThis.CSS)==null?void 0:e.supports)==null?void 0:t.call(e,"width: round(1.5px, 1px)"))}}const Tv=Array.from(Array(256).keys(),n=>n.toString(16).padStart(2,"0"));var Eo,vg,Wb;class Se{static makeHexColor(e,t,s){return`#${Tv[e]}${Tv[t]}${Tv[s]}`}static scaleMinMax(e,t){let s;e[0]?(e[0]<0&&(s=t[0],t[0]=t[2],t[2]=s),t[0]*=e[0],t[2]*=e[0],e[3]<0&&(s=t[1],t[1]=t[3],t[3]=s),t[1]*=e[3],t[3]*=e[3]):(s=t[0],t[0]=t[1],t[1]=s,s=t[2],t[2]=t[3],t[3]=s,e[1]<0&&(s=t[1],t[1]=t[3],t[3]=s),t[1]*=e[1],t[3]*=e[1],e[2]<0&&(s=t[0],t[0]=t[2],t[2]=s),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){const s=e[0]*t[0]+e[1]*t[2]+t[4],i=e[0]*t[1]+e[1]*t[3]+t[5];return[s,i]}static applyInverseTransform(e,t){const s=t[0]*t[3]-t[1]*t[2],i=(e[0]*t[3]-e[1]*t[2]+t[2]*t[5]-t[4]*t[3])/s,r=(-e[0]*t[1]+e[1]*t[0]+t[4]*t[1]-t[5]*t[0])/s;return[i,r]}static getAxialAlignedBoundingBox(e,t){const s=this.applyTransform(e,t),i=this.applyTransform(e.slice(2,4),t),r=this.applyTransform([e[0],e[3]],t),o=this.applyTransform([e[2],e[1]],t);return[Math.min(s[0],i[0],r[0],o[0]),Math.min(s[1],i[1],r[1],o[1]),Math.max(s[0],i[0],r[0],o[0]),Math.max(s[1],i[1],r[1],o[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]],s=e[0]*t[0]+e[1]*t[2],i=e[0]*t[1]+e[1]*t[3],r=e[2]*t[0]+e[3]*t[2],o=e[2]*t[1]+e[3]*t[3],a=(s+o)/2,l=Math.sqrt((s+o)**2-4*(s*o-r*i))/2,c=a+l||1,h=a-l||1;return[Math.sqrt(c),Math.sqrt(h)]}static normalizeRect(e){const t=e.slice(0);return e[0]>e[2]&&(t[0]=e[2],t[2]=e[0]),e[1]>e[3]&&(t[1]=e[3],t[3]=e[1]),t}static intersect(e,t){const s=Math.max(Math.min(e[0],e[2]),Math.min(t[0],t[2])),i=Math.min(Math.max(e[0],e[2]),Math.max(t[0],t[2]));if(s>i)return null;const r=Math.max(Math.min(e[1],e[3]),Math.min(t[1],t[3])),o=Math.min(Math.max(e[1],e[3]),Math.max(t[1],t[3]));return r>o?null:[s,r,i,o]}static bezierBoundingBox(e,t,s,i,r,o,a,l,c){return c?(c[0]=Math.min(c[0],e,a),c[1]=Math.min(c[1],t,l),c[2]=Math.max(c[2],e,a),c[3]=Math.max(c[3],t,l)):c=[Math.min(e,a),Math.min(t,l),Math.max(e,a),Math.max(t,l)],P(this,Eo,Wb).call(this,e,s,r,a,t,i,o,l,3*(-e+3*(s-r)+a),6*(e-2*s+r),3*(s-e),c),P(this,Eo,Wb).call(this,e,s,r,a,t,i,o,l,3*(-t+3*(i-o)+l),6*(t-2*i+o),3*(i-t),c),c}}Eo=new WeakSet,vg=function(e,t,s,i,r,o,a,l,c,h){if(c<=0||c>=1)return;const u=1-c,d=c*c,p=d*c,m=u*(u*(u*e+3*c*t)+3*d*s)+p*i,y=u*(u*(u*r+3*c*o)+3*d*a)+p*l;h[0]=Math.min(h[0],m),h[1]=Math.min(h[1],y),h[2]=Math.max(h[2],m),h[3]=Math.max(h[3],y)},Wb=function(e,t,s,i,r,o,a,l,c,h,u,d){if(Math.abs(c)<1e-12){Math.abs(h)>=1e-12&&P(this,Eo,vg).call(this,e,t,s,i,r,o,a,l,-u/h,d);return}const p=h**2-4*u*c;if(p<0)return;const m=Math.sqrt(p),y=2*c;P(this,Eo,vg).call(this,e,t,s,i,r,o,a,l,(-h+m)/y,d),P(this,Eo,vg).call(this,e,t,s,i,r,o,a,l,(-h-m)/y,d)},M(Se,Eo);function Q6(n){return decodeURIComponent(escape(n))}let Pv=null,Wk=null;function e8(n){return Pv||(Pv=/([\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,Wk=new Map([["ſt","ſt"]])),n.replaceAll(Pv,(e,t,s)=>t?t.normalize("NFKC"):Wk.get(s))}function t8(){if(typeof crypto<"u"&&typeof(crypto==null?void 0:crypto.randomUUID)=="function")return crypto.randomUUID();const n=new Uint8Array(32);if(typeof crypto<"u"&&typeof(crypto==null?void 0:crypto.getRandomValues)=="function")crypto.getRandomValues(n);else for(let e=0;e<32;e++)n[e]=Math.floor(Math.random()*255);return _R(n)}const Ax="pdfjs_internal_id_",Hr={BEZIER_CURVE_TO:0,MOVE_TO:1,LINE_TO:2,QUADRATIC_CURVE_TO:3,RESTORE:4,SAVE:5,SCALE:6,TRANSFORM:7,TRANSLATE:8};function n8(n){return Uint8Array.prototype.toBase64?n.toBase64():btoa(_R(n))}const Ur="http://www.w3.org/2000/svg",ol=class ol{};oe(ol,"CSS",96),oe(ol,"PDF",72),oe(ol,"PDF_TO_CSS_UNITS",ol.CSS/ol.PDF);let Ta=ol;async function j0(n,e="text"){if(gd(n,document.baseURI)){const t=await fetch(n);if(!t.ok)throw new Error(t.statusText);switch(e){case"arraybuffer":return t.arrayBuffer();case"blob":return t.blob();case"json":return t.json()}return t.text()}return new Promise((t,s)=>{const i=new XMLHttpRequest;i.open("GET",n,!0),i.responseType=e,i.onreadystatechange=()=>{if(i.readyState===XMLHttpRequest.DONE){if(i.status===200||i.status===0){switch(e){case"arraybuffer":case"blob":case"json":t(i.response);return}t(i.responseText);return}s(new Error(i.statusText))}},i.send(null)})}class tm{constructor({viewBox:e,scale:t,rotation:s,offsetX:i=0,offsetY:r=0,dontFlip:o=!1}){this.viewBox=e,this.scale=t,this.rotation=s,this.offsetX=i,this.offsetY=r;const a=(e[2]+e[0])/2,l=(e[3]+e[1])/2;let c,h,u,d;switch(s%=360,s<0&&(s+=360),s){case 180:c=-1,h=0,u=0,d=1;break;case 90:c=0,h=1,u=1,d=0;break;case 270:c=0,h=-1,u=-1,d=0;break;case 0:c=1,h=0,u=0,d=-1;break;default:throw new Error("PageViewport: Invalid rotation, must be a multiple of 90 degrees.")}o&&(u=-u,d=-d);let p,m,y,v;c===0?(p=Math.abs(l-e[1])*t+i,m=Math.abs(a-e[0])*t+r,y=(e[3]-e[1])*t,v=(e[2]-e[0])*t):(p=Math.abs(a-e[0])*t+i,m=Math.abs(l-e[1])*t+r,y=(e[2]-e[0])*t,v=(e[3]-e[1])*t),this.transform=[c*t,h*t,u*t,d*t,p-c*t*a-u*t*l,m-h*t*a-d*t*l],this.width=y,this.height=v}get rawDims(){const{viewBox:e}=this;return Xe(this,"rawDims",{pageWidth:e[2]-e[0],pageHeight:e[3]-e[1],pageX:e[0],pageY:e[1]})}clone({scale:e=this.scale,rotation:t=this.rotation,offsetX:s=this.offsetX,offsetY:i=this.offsetY,dontFlip:r=!1}={}){return new tm({viewBox:this.viewBox.slice(),scale:e,rotation:t,offsetX:s,offsetY:i,dontFlip:r})}convertToViewportPoint(e,t){return Se.applyTransform([e,t],this.transform)}convertToViewportRectangle(e){const t=Se.applyTransform([e[0],e[1]],this.transform),s=Se.applyTransform([e[2],e[3]],this.transform);return[t[0],t[1],s[0],s[1]]}convertToPdfPoint(e,t){return Se.applyInverseTransform([e,t],this.transform)}}class kx extends Da{constructor(e,t=0){super(e,"RenderingCancelledException"),this.extraDelay=t}}function F0(n){const e=n.length;let t=0;for(;t=1&&i<=12?i-1:0;let r=parseInt(t[3],10);r=r>=1&&r<=31?r:1;let o=parseInt(t[4],10);o=o>=0&&o<=23?o:0;let a=parseInt(t[5],10);a=a>=0&&a<=59?a:0;let l=parseInt(t[6],10);l=l>=0&&l<=59?l:0;const c=t[7]||"Z";let h=parseInt(t[8],10);h=h>=0&&h<=23?h:0;let u=parseInt(t[9],10)||0;return u=u>=0&&u<=59?u:0,c==="-"?(o+=h,a+=u):c==="+"&&(o-=h,a-=u),new Date(Date.UTC(s,i,r,o,a,l))}}_f=new WeakMap,M(Cx,_f);function r8(n,{scale:e=1,rotation:t=0}){const{width:s,height:i}=n.attributes.style,r=[0,0,parseInt(s),parseInt(i)];return new tm({viewBox:r,scale:e,rotation:t})}function $x(n){if(n.startsWith("#")){const e=parseInt(n.slice(1),16);return[(e&16711680)>>16,(e&65280)>>8,e&255]}return n.startsWith("rgb(")?n.slice(4,-1).split(",").map(e=>parseInt(e)):n.startsWith("rgba(")?n.slice(5,-1).split(",").map(e=>parseInt(e)).slice(0,3):(qe(`Not a valid color format: "${n}"`),[0,0,0])}function o8(n){const e=document.createElement("span");e.style.visibility="hidden",document.body.append(e);for(const t of n.keys()){e.style.color=t;const s=window.getComputedStyle(e).color;n.set(t,$x(s))}e.remove()}function Bt(n){const{a:e,b:t,c:s,d:i,e:r,f:o}=n.getTransform();return[e,t,s,i,r,o]}function Br(n){const{a:e,b:t,c:s,d:i,e:r,f:o}=n.getTransform().invertSelf();return[e,t,s,i,r,o]}function pc(n,e,t=!1,s=!0){if(e instanceof tm){const{pageWidth:i,pageHeight:r}=e.rawDims,{style:o}=n,a=bs.isCSSRoundSupported,l=`var(--scale-factor) * ${i}px`,c=`var(--scale-factor) * ${r}px`,h=a?`round(down, ${l}, var(--scale-round-x, 1px))`:`calc(${l})`,u=a?`round(down, ${c}, var(--scale-round-y, 1px))`:`calc(${c})`;!t||e.rotation%180===0?(o.width=h,o.height=u):(o.width=u,o.height=h)}s&&n.setAttribute("data-main-rotation",e.rotation)}class Gb{constructor(){const e=window.devicePixelRatio||1;this.sx=e,this.sy=e}get scaled(){return this.sx!==1||this.sy!==1}get symmetric(){return this.sx===this.sy}}var Vo,hl,Ii,ul,Sf,xf,Wy,SR,_s,xR,AR,bg,kR,Zb;const qr=class qr{constructor(e){M(this,_s);M(this,Vo,null);M(this,hl,null);M(this,Ii);M(this,ul,null);M(this,Sf,null);T(this,Ii,e),f(qr,xf)||T(qr,xf,Object.freeze({freetext:"pdfjs-editor-remove-freetext-button",highlight:"pdfjs-editor-remove-highlight-button",ink:"pdfjs-editor-remove-ink-button",stamp:"pdfjs-editor-remove-stamp-button"}))}render(){const e=T(this,Vo,document.createElement("div"));e.classList.add("editToolbar","hidden"),e.setAttribute("role","toolbar");const t=f(this,Ii)._uiManager._signal;e.addEventListener("contextmenu",Si,{signal:t}),e.addEventListener("pointerdown",P(qr,Wy,SR),{signal:t});const s=T(this,ul,document.createElement("div"));s.className="buttons",e.append(s);const i=f(this,Ii).toolbarPosition;if(i){const{style:r}=e,o=f(this,Ii)._uiManager.direction==="ltr"?1-i[0]:i[0];r.insetInlineEnd=`${100*o}%`,r.top=`calc(${100*i[1]}% + var(--editor-toolbar-vert-offset))`}return P(this,_s,kR).call(this),e}get div(){return f(this,Vo)}hide(){var e;f(this,Vo).classList.add("hidden"),(e=f(this,hl))==null||e.hideDropdown()}show(){var e;f(this,Vo).classList.remove("hidden"),(e=f(this,Sf))==null||e.shown()}async addAltText(e){const t=await e.render();P(this,_s,bg).call(this,t),f(this,ul).prepend(t,f(this,_s,Zb)),T(this,Sf,e)}addColorPicker(e){T(this,hl,e);const t=e.renderButton();P(this,_s,bg).call(this,t),f(this,ul).prepend(t,f(this,_s,Zb))}remove(){var e;f(this,Vo).remove(),(e=f(this,hl))==null||e.destroy(),T(this,hl,null)}};Vo=new WeakMap,hl=new WeakMap,Ii=new WeakMap,ul=new WeakMap,Sf=new WeakMap,xf=new WeakMap,Wy=new WeakSet,SR=function(e){e.stopPropagation()},_s=new WeakSet,xR=function(e){f(this,Ii)._focusEventsAllowed=!1,e.preventDefault(),e.stopPropagation()},AR=function(e){f(this,Ii)._focusEventsAllowed=!0,e.preventDefault(),e.stopPropagation()},bg=function(e){const t=f(this,Ii)._uiManager._signal;e.addEventListener("focusin",P(this,_s,xR).bind(this),{capture:!0,signal:t}),e.addEventListener("focusout",P(this,_s,AR).bind(this),{capture:!0,signal:t}),e.addEventListener("contextmenu",Si,{signal:t})},kR=function(){const{editorType:e,_uiManager:t}=f(this,Ii),s=document.createElement("button");s.className="delete",s.tabIndex=0,s.setAttribute("data-l10n-id",f(qr,xf)[e]),P(this,_s,bg).call(this,s),s.addEventListener("click",i=>{t.delete()},{signal:t._signal}),f(this,ul).append(s)},Zb=function(){const e=document.createElement("div");return e.className="divider",e},M(qr,Wy),M(qr,xf,null);let Kb=qr;var Af,dl,fl,Na,ER,CR,$R;class a8{constructor(e){M(this,Na);M(this,Af,null);M(this,dl,null);M(this,fl);T(this,fl,e)}show(e,t,s){const[i,r]=P(this,Na,CR).call(this,t,s),{style:o}=f(this,dl)||T(this,dl,P(this,Na,ER).call(this));e.append(f(this,dl)),o.insetInlineEnd=`${100*i}%`,o.top=`calc(${100*r}% + var(--editor-toolbar-vert-offset))`}hide(){f(this,dl).remove()}}Af=new WeakMap,dl=new WeakMap,fl=new WeakMap,Na=new WeakSet,ER=function(){const e=T(this,dl,document.createElement("div"));e.className="editToolbar",e.setAttribute("role","toolbar"),e.addEventListener("contextmenu",Si,{signal:f(this,fl)._signal});const t=T(this,Af,document.createElement("div"));return t.className="buttons",e.append(t),P(this,Na,$R).call(this),e},CR=function(e,t){let s=0,i=0;for(const r of e){const o=r.y+r.height;if(os){i=a,s=o;continue}t?a>i&&(i=a):a{f(this,fl).highlightSelection("floating_button")},{signal:s}),f(this,Af).append(e)};function wy(n,e,t){for(const s of t)e.addEventListener(s,n[s].bind(n))}function l8(n){return Math.round(Math.min(255,Math.max(1,255*n))).toString(16).padStart(2,"0")}var Gy;class c8{constructor(){M(this,Gy,0)}get id(){return`${B6}${ds(this,Gy)._++}`}}Gy=new WeakMap;var wh,kf,ns,_h,wg;const fA=class fA{constructor(){M(this,_h);M(this,wh,t8());M(this,kf,0);M(this,ns,null)}static get _isSVGFittingCanvas(){const e='data:image/svg+xml;charset=UTF-8,',s=new OffscreenCanvas(1,3).getContext("2d",{willReadFrequently:!0}),i=new Image;i.src=e;const r=i.decode().then(()=>(s.drawImage(i,0,0,1,1,0,0,1,3),new Uint32Array(s.getImageData(0,0,1,1).data.buffer)[0]===0));return Xe(this,"_isSVGFittingCanvas",r)}async getFromFile(e){const{lastModified:t,name:s,size:i,type:r}=e;return P(this,_h,wg).call(this,`${t}_${s}_${i}_${r}`,e)}async getFromUrl(e){return P(this,_h,wg).call(this,e,e)}async getFromBlob(e,t){const s=await t;return P(this,_h,wg).call(this,e,s)}async getFromId(e){f(this,ns)||T(this,ns,new Map);const t=f(this,ns).get(e);if(!t)return null;if(t.bitmap)return t.refCounter+=1,t;if(t.file)return this.getFromFile(t.file);if(t.blobPromise){const{blobPromise:s}=t;return delete t.blobPromise,this.getFromBlob(t.id,s)}return this.getFromUrl(t.url)}getFromCanvas(e,t){f(this,ns)||T(this,ns,new Map);let s=f(this,ns).get(e);if(s!=null&&s.bitmap)return s.refCounter+=1,s;const i=new OffscreenCanvas(t.width,t.height);return i.getContext("2d").drawImage(t,0,0),s={bitmap:i.transferToImageBitmap(),id:`image_${f(this,wh)}_${ds(this,kf)._++}`,refCounter:1,isSvg:!1},f(this,ns).set(e,s),f(this,ns).set(s.id,s),s}getSvgUrl(e){const t=f(this,ns).get(e);return t!=null&&t.isSvg?t.svgUrl:null}deleteId(e){var i;f(this,ns)||T(this,ns,new Map);const t=f(this,ns).get(e);if(!t||(t.refCounter-=1,t.refCounter!==0))return;const{bitmap:s}=t;if(!t.url&&!t.file){const r=new OffscreenCanvas(s.width,s.height);r.getContext("bitmaprenderer").transferFromImageBitmap(s),t.blobPromise=r.convertToBlob()}(i=s.close)==null||i.call(s),t.bitmap=null}isValidId(e){return e.startsWith(`image_${f(this,wh)}_`)}};wh=new WeakMap,kf=new WeakMap,ns=new WeakMap,_h=new WeakSet,wg=async function(e,t){f(this,ns)||T(this,ns,new Map);let s=f(this,ns).get(e);if(s===null)return null;if(s!=null&&s.bitmap)return s.refCounter+=1,s;try{s||(s={bitmap:null,id:`image_${f(this,wh)}_${ds(this,kf)._++}`,refCounter:0,isSvg:!1});let i;if(typeof t=="string"?(s.url=t,i=await j0(t,"blob")):t instanceof File?i=s.file=t:t instanceof Blob&&(i=t),i.type==="image/svg+xml"){const r=fA._isSVGFittingCanvas,o=new FileReader,a=new Image,l=new Promise((c,h)=>{a.onload=()=>{s.bitmap=a,s.isSvg=!0,c()},o.onload=async()=>{const u=s.svgUrl=o.result;a.src=await r?`${u}#svgView(preserveAspectRatio(none))`:u},a.onerror=o.onerror=h});o.readAsDataURL(i),await l}else s.bitmap=await createImageBitmap(i);s.refCounter=1}catch(i){console.error(i),s=null}return f(this,ns).set(e,s),s&&f(this,ns).set(s.id,s),s};let Xb=fA;var Sn,Wo,Ef,xn;class h8{constructor(e=128){M(this,Sn,[]);M(this,Wo,!1);M(this,Ef);M(this,xn,-1);T(this,Ef,e)}add({cmd:e,undo:t,post:s,mustExec:i,type:r=NaN,overwriteIfSameType:o=!1,keepUndo:a=!1}){if(i&&e(),f(this,Wo))return;const l={cmd:e,undo:t,post:s,type:r};if(f(this,xn)===-1){f(this,Sn).length>0&&(f(this,Sn).length=0),T(this,xn,0),f(this,Sn).push(l);return}if(o&&f(this,Sn)[f(this,xn)].type===r){a&&(l.undo=f(this,Sn)[f(this,xn)].undo),f(this,Sn)[f(this,xn)]=l;return}const c=f(this,xn)+1;c===f(this,Ef)?f(this,Sn).splice(0,1):(T(this,xn,c),cr===t[o]))return Zy._colorsMapping.get(s);return t}getHexCode(e){const t=this._colors.get(e);return t?Se.makeHexColor(...t):e}};oe(Zy,"_colorsMapping",new Map([["CanvasText",[0,0,0]],["Canvas",[255,255,255]]]));let Yb=Zy;var Sh,Vs,un,Dn,xh,Wr,Ah,Oi,Go,kh,pl,ar,Ni,ml,Cf,$f,Eh,Tf,lr,Ko,Ch,Zo,cr,Xy,Xo,Pf,Yo,gl,Rf,Mf,An,ut,Gr,yl,If,Of,Jo,hr,Kr,Nf,li,ue,_g,Jb,PR,RR,Sg,MR,IR,OR,Qb,NR,ew,tw,LR,fs,Do,DR,jR,nw,FR,yd,sw;const oh=class oh{constructor(e,t,s,i,r,o,a,l,c,h,u){M(this,ue);M(this,Sh,new AbortController);M(this,Vs,null);M(this,un,new Map);M(this,Dn,new Map);M(this,xh,null);M(this,Wr,null);M(this,Ah,null);M(this,Oi,new h8);M(this,Go,null);M(this,kh,0);M(this,pl,new Set);M(this,ar,null);M(this,Ni,null);M(this,ml,new Set);M(this,Cf,!1);M(this,$f,!1);M(this,Eh,!1);M(this,Tf,null);M(this,lr,null);M(this,Ko,null);M(this,Ch,null);M(this,Zo,!1);M(this,cr,null);M(this,Xy,new c8);M(this,Xo,!1);M(this,Pf,!1);M(this,Yo,null);M(this,gl,null);M(this,Rf,null);M(this,Mf,null);M(this,An,De.NONE);M(this,ut,new Set);M(this,Gr,null);M(this,yl,null);M(this,If,null);M(this,Of,{isEditing:!1,isEmpty:!0,hasSomethingToUndo:!1,hasSomethingToRedo:!1,hasSelectedEditor:!1,hasSelectedText:!1});M(this,Jo,[0,0]);M(this,hr,null);M(this,Kr,null);M(this,Nf,null);M(this,li,null);const d=this._signal=f(this,Sh).signal;T(this,Kr,e),T(this,Nf,t),T(this,xh,s),this._eventBus=i,i._on("editingaction",this.onEditingAction.bind(this),{signal:d}),i._on("pagechanging",this.onPageChanging.bind(this),{signal:d}),i._on("scalechanging",this.onScaleChanging.bind(this),{signal:d}),i._on("rotationchanging",this.onRotationChanging.bind(this),{signal:d}),i._on("setpreference",this.onSetPreference.bind(this),{signal:d}),i._on("switchannotationeditorparams",p=>this.updateParams(p.type,p.value),{signal:d}),P(this,ue,MR).call(this),P(this,ue,LR).call(this),P(this,ue,Qb).call(this),T(this,Wr,r.annotationStorage),T(this,Tf,r.filterFactory),T(this,yl,o),T(this,Ch,a||null),T(this,Cf,l),T(this,$f,c),T(this,Eh,h),T(this,Mf,u||null),this.viewParameters={realScale:Ta.PDF_TO_CSS_UNITS,rotation:0},this.isShiftKeyDown=!1}static get _keyboardManager(){const e=oh.prototype,t=o=>f(o,Kr).contains(document.activeElement)&&document.activeElement.tagName!=="BUTTON"&&o.hasSomethingToControl(),s=(o,{target:a})=>{if(a instanceof HTMLInputElement){const{type:l}=a;return l!=="text"&&l!=="number"}return!0},i=this.TRANSLATE_SMALL,r=this.TRANSLATE_BIG;return Xe(this,"_keyboardManager",new nm([[["ctrl+a","mac+meta+a"],e.selectAll,{checker:s}],[["ctrl+z","mac+meta+z"],e.undo,{checker:s}],[["ctrl+y","ctrl+shift+z","mac+meta+shift+z","ctrl+shift+Z","mac+meta+shift+Z"],e.redo,{checker:s}],[["Backspace","alt+Backspace","ctrl+Backspace","shift+Backspace","mac+Backspace","mac+alt+Backspace","mac+ctrl+Backspace","Delete","ctrl+Delete","shift+Delete","mac+Delete"],e.delete,{checker:s}],[["Enter","mac+Enter"],e.addNewEditorFromKeyboard,{checker:(o,{target:a})=>!(a instanceof HTMLButtonElement)&&f(o,Kr).contains(a)&&!o.isEnterHandled}],[[" ","mac+ "],e.addNewEditorFromKeyboard,{checker:(o,{target:a})=>!(a instanceof HTMLButtonElement)&&f(o,Kr).contains(document.activeElement)}],[["Escape","mac+Escape"],e.unselectAll],[["ArrowLeft","mac+ArrowLeft"],e.translateSelectedEditors,{args:[-i,0],checker:t}],[["ctrl+ArrowLeft","mac+shift+ArrowLeft"],e.translateSelectedEditors,{args:[-r,0],checker:t}],[["ArrowRight","mac+ArrowRight"],e.translateSelectedEditors,{args:[i,0],checker:t}],[["ctrl+ArrowRight","mac+shift+ArrowRight"],e.translateSelectedEditors,{args:[r,0],checker:t}],[["ArrowUp","mac+ArrowUp"],e.translateSelectedEditors,{args:[0,-i],checker:t}],[["ctrl+ArrowUp","mac+shift+ArrowUp"],e.translateSelectedEditors,{args:[0,-r],checker:t}],[["ArrowDown","mac+ArrowDown"],e.translateSelectedEditors,{args:[0,i],checker:t}],[["ctrl+ArrowDown","mac+shift+ArrowDown"],e.translateSelectedEditors,{args:[0,r],checker:t}]]))}destroy(){var e,t,s,i;(e=f(this,li))==null||e.resolve(),T(this,li,null),(t=f(this,Sh))==null||t.abort(),T(this,Sh,null),this._signal=null;for(const r of f(this,Dn).values())r.destroy();f(this,Dn).clear(),f(this,un).clear(),f(this,ml).clear(),T(this,Vs,null),f(this,ut).clear(),f(this,Oi).destroy(),(s=f(this,xh))==null||s.destroy(),(i=f(this,cr))==null||i.hide(),T(this,cr,null),f(this,lr)&&(clearTimeout(f(this,lr)),T(this,lr,null)),f(this,hr)&&(clearTimeout(f(this,hr)),T(this,hr,null))}combinedSignal(e){return AbortSignal.any([this._signal,e.signal])}get mlManager(){return f(this,Mf)}get useNewAltTextFlow(){return f(this,$f)}get useNewAltTextWhenAddingImage(){return f(this,Eh)}get hcmFilter(){return Xe(this,"hcmFilter",f(this,yl)?f(this,Tf).addHCMFilter(f(this,yl).foreground,f(this,yl).background):"none")}get direction(){return Xe(this,"direction",getComputedStyle(f(this,Kr)).direction)}get highlightColors(){return Xe(this,"highlightColors",f(this,Ch)?new Map(f(this,Ch).split(",").map(e=>e.split("=").map(t=>t.trim()))):null)}get highlightColorNames(){return Xe(this,"highlightColorNames",this.highlightColors?new Map(Array.from(this.highlightColors,e=>e.reverse())):null)}setMainHighlightColorPicker(e){T(this,Rf,e)}editAltText(e,t=!1){var s;(s=f(this,xh))==null||s.editAltText(this,e,t)}switchToMode(e,t){this._eventBus.on("annotationeditormodechanged",t,{once:!0,signal:this._signal}),this._eventBus.dispatch("showannotationeditorui",{source:this,mode:e})}setPreference(e,t){this._eventBus.dispatch("setpreference",{source:this,name:e,value:t})}onSetPreference({name:e,value:t}){switch(e){case"enableNewAltTextWhenAddingImage":T(this,Eh,t);break}}onPageChanging({pageNumber:e}){T(this,kh,e-1)}focusMainContainer(){f(this,Kr).focus()}findParent(e,t){for(const s of f(this,Dn).values()){const{x:i,y:r,width:o,height:a}=s.div.getBoundingClientRect();if(e>=i&&e<=i+o&&t>=r&&t<=r+a)return s}return null}disableUserSelect(e=!1){f(this,Nf).classList.toggle("noUserSelect",e)}addShouldRescale(e){f(this,ml).add(e)}removeShouldRescale(e){f(this,ml).delete(e)}onScaleChanging({scale:e}){this.commitOrRemove(),this.viewParameters.realScale=e*Ta.PDF_TO_CSS_UNITS;for(const t of f(this,ml))t.onScaleChanging()}onRotationChanging({pagesRotation:e}){this.commitOrRemove(),this.viewParameters.rotation=e}highlightSelection(e=""){const t=document.getSelection();if(!t||t.isCollapsed)return;const{anchorNode:s,anchorOffset:i,focusNode:r,focusOffset:o}=t,a=t.toString(),c=P(this,ue,_g).call(this,t).closest(".textLayer"),h=this.getSelectionBoxes(c);if(!h)return;t.empty();const u=P(this,ue,Jb).call(this,c),d=f(this,An)===De.NONE,p=()=>{u==null||u.createAndAddNewEditor({x:0,y:0},!1,{methodOfCreation:e,boxes:h,anchorNode:s,anchorOffset:i,focusNode:r,focusOffset:o,text:a}),d&&this.showAllEditors("highlight",!0,!0)};if(d){this.switchToMode(De.HIGHLIGHT,p);return}p()}addToAnnotationStorage(e){!e.isEmpty()&&f(this,Wr)&&!f(this,Wr).has(e.id)&&f(this,Wr).setValue(e.id,e)}blur(){if(this.isShiftKeyDown=!1,f(this,Zo)&&(T(this,Zo,!1),P(this,ue,Sg).call(this,"main_toolbar")),!this.hasSelection)return;const{activeElement:e}=document;for(const t of f(this,ut))if(t.div.contains(e)){T(this,gl,[t,e]),t._focusEventsAllowed=!1;break}}focus(){if(!f(this,gl))return;const[e,t]=f(this,gl);T(this,gl,null),t.addEventListener("focusin",()=>{e._focusEventsAllowed=!0},{once:!0,signal:this._signal}),t.focus()}addEditListeners(){P(this,ue,Qb).call(this),P(this,ue,ew).call(this)}removeEditListeners(){P(this,ue,NR).call(this),P(this,ue,tw).call(this)}dragOver(e){for(const{type:t}of e.dataTransfer.items)for(const s of f(this,Ni))if(s.isHandlingMimeForPasting(t)){e.dataTransfer.dropEffect="copy",e.preventDefault();return}}drop(e){for(const t of e.dataTransfer.items)for(const s of f(this,Ni))if(s.isHandlingMimeForPasting(t.type)){s.paste(t,this.currentLayer),e.preventDefault();return}}copy(e){var s;if(e.preventDefault(),(s=f(this,Vs))==null||s.commitOrRemove(),!this.hasSelection)return;const t=[];for(const i of f(this,ut)){const r=i.serialize(!0);r&&t.push(r)}t.length!==0&&e.clipboardData.setData("application/pdfjs",JSON.stringify(t))}cut(e){this.copy(e),this.delete()}async paste(e){e.preventDefault();const{clipboardData:t}=e;for(const r of t.items)for(const o of f(this,Ni))if(o.isHandlingMimeForPasting(r.type)){o.paste(r,this.currentLayer);return}let s=t.getData("application/pdfjs");if(!s)return;try{s=JSON.parse(s)}catch(r){qe(`paste: "${r.message}".`);return}if(!Array.isArray(s))return;this.unselectAll();const i=this.currentLayer;try{const r=[];for(const l of s){const c=await i.deserialize(l);if(!c)return;r.push(c)}const o=()=>{for(const l of r)P(this,ue,nw).call(this,l);P(this,ue,sw).call(this,r)},a=()=>{for(const l of r)l.remove()};this.addCommands({cmd:o,undo:a,mustExec:!0})}catch(r){qe(`paste: "${r.message}".`)}}keydown(e){!this.isShiftKeyDown&&e.key==="Shift"&&(this.isShiftKeyDown=!0),f(this,An)!==De.NONE&&!this.isEditorHandlingKeyboard&&oh._keyboardManager.exec(this,e)}keyup(e){this.isShiftKeyDown&&e.key==="Shift"&&(this.isShiftKeyDown=!1,f(this,Zo)&&(T(this,Zo,!1),P(this,ue,Sg).call(this,"main_toolbar")))}onEditingAction({name:e}){switch(e){case"undo":case"redo":case"delete":case"selectAll":this[e]();break;case"highlightSelection":this.highlightSelection("context_menu");break}}setEditingState(e){e?(P(this,ue,IR).call(this),P(this,ue,ew).call(this),P(this,ue,fs).call(this,{isEditing:f(this,An)!==De.NONE,isEmpty:P(this,ue,yd).call(this),hasSomethingToUndo:f(this,Oi).hasSomethingToUndo(),hasSomethingToRedo:f(this,Oi).hasSomethingToRedo(),hasSelectedEditor:!1})):(P(this,ue,OR).call(this),P(this,ue,tw).call(this),P(this,ue,fs).call(this,{isEditing:!1}),this.disableUserSelect(!1))}registerEditorTypes(e){if(!f(this,Ni)){T(this,Ni,e);for(const t of f(this,Ni))P(this,ue,Do).call(this,t.defaultPropertiesToUpdate)}}getId(){return f(this,Xy).id}get currentLayer(){return f(this,Dn).get(f(this,kh))}getLayer(e){return f(this,Dn).get(e)}get currentPageIndex(){return f(this,kh)}addLayer(e){f(this,Dn).set(e.pageIndex,e),f(this,Xo)?e.enable():e.disable()}removeLayer(e){f(this,Dn).delete(e.pageIndex)}async updateMode(e,t=null,s=!1){if(f(this,An)!==e&&!(f(this,li)&&(await f(this,li).promise,!f(this,li)))){if(T(this,li,Promise.withResolvers()),T(this,An,e),e===De.NONE){this.setEditingState(!1),P(this,ue,jR).call(this),f(this,li).resolve();return}this.setEditingState(!0),await P(this,ue,DR).call(this),this.unselectAll();for(const i of f(this,Dn).values())i.updateMode(e);if(!t){s&&this.addNewEditorFromKeyboard(),f(this,li).resolve();return}for(const i of f(this,un).values())i.annotationElementId===t?(this.setSelected(i),i.enterInEditMode()):i.unselect();f(this,li).resolve()}}addNewEditorFromKeyboard(){this.currentLayer.canCreateNewEmptyEditor()&&this.currentLayer.addNewEditor()}updateToolbar(e){e!==f(this,An)&&this._eventBus.dispatch("switchannotationeditormode",{source:this,mode:e})}updateParams(e,t){var s;if(f(this,Ni)){switch(e){case Te.CREATE:this.currentLayer.addNewEditor();return;case Te.HIGHLIGHT_DEFAULT_COLOR:(s=f(this,Rf))==null||s.updateColor(t);break;case Te.HIGHLIGHT_SHOW_ALL:this._eventBus.dispatch("reporttelemetry",{source:this,details:{type:"editing",data:{type:"highlight",action:"toggle_visibility"}}}),(f(this,If)||T(this,If,new Map)).set(e,t),this.showAllEditors("highlight",t);break}for(const i of f(this,ut))i.updateParams(e,t);for(const i of f(this,Ni))i.updateDefaultParams(e,t)}}showAllEditors(e,t,s=!1){var r;for(const o of f(this,un).values())o.editorType===e&&o.show(t);(((r=f(this,If))==null?void 0:r.get(Te.HIGHLIGHT_SHOW_ALL))??!0)!==t&&P(this,ue,Do).call(this,[[Te.HIGHLIGHT_SHOW_ALL,t]])}enableWaiting(e=!1){if(f(this,Pf)!==e){T(this,Pf,e);for(const t of f(this,Dn).values())e?t.disableClick():t.enableClick(),t.div.classList.toggle("waiting",e)}}getEditors(e){const t=[];for(const s of f(this,un).values())s.pageIndex===e&&t.push(s);return t}getEditor(e){return f(this,un).get(e)}addEditor(e){f(this,un).set(e.id,e)}removeEditor(e){var t;e.div.contains(document.activeElement)&&(f(this,lr)&&clearTimeout(f(this,lr)),T(this,lr,setTimeout(()=>{this.focusMainContainer(),T(this,lr,null)},0))),f(this,un).delete(e.id),this.unselect(e),(!e.annotationElementId||!f(this,pl).has(e.annotationElementId))&&((t=f(this,Wr))==null||t.remove(e.id))}addDeletedAnnotationElement(e){f(this,pl).add(e.annotationElementId),this.addChangedExistingAnnotation(e),e.deleted=!0}isDeletedAnnotationElement(e){return f(this,pl).has(e)}removeDeletedAnnotationElement(e){f(this,pl).delete(e.annotationElementId),this.removeChangedExistingAnnotation(e),e.deleted=!1}setActiveEditor(e){f(this,Vs)!==e&&(T(this,Vs,e),e&&P(this,ue,Do).call(this,e.propertiesToUpdate))}updateUI(e){f(this,ue,FR)===e&&P(this,ue,Do).call(this,e.propertiesToUpdate)}toggleSelected(e){if(f(this,ut).has(e)){f(this,ut).delete(e),e.unselect(),P(this,ue,fs).call(this,{hasSelectedEditor:this.hasSelection});return}f(this,ut).add(e),e.select(),P(this,ue,Do).call(this,e.propertiesToUpdate),P(this,ue,fs).call(this,{hasSelectedEditor:!0})}setSelected(e){for(const t of f(this,ut))t!==e&&t.unselect();f(this,ut).clear(),f(this,ut).add(e),e.select(),P(this,ue,Do).call(this,e.propertiesToUpdate),P(this,ue,fs).call(this,{hasSelectedEditor:!0})}isSelected(e){return f(this,ut).has(e)}get firstSelectedEditor(){return f(this,ut).values().next().value}unselect(e){e.unselect(),f(this,ut).delete(e),P(this,ue,fs).call(this,{hasSelectedEditor:this.hasSelection})}get hasSelection(){return f(this,ut).size!==0}get isEnterHandled(){return f(this,ut).size===1&&this.firstSelectedEditor.isEnterHandled}undo(){f(this,Oi).undo(),P(this,ue,fs).call(this,{hasSomethingToUndo:f(this,Oi).hasSomethingToUndo(),hasSomethingToRedo:!0,isEmpty:P(this,ue,yd).call(this)})}redo(){f(this,Oi).redo(),P(this,ue,fs).call(this,{hasSomethingToUndo:!0,hasSomethingToRedo:f(this,Oi).hasSomethingToRedo(),isEmpty:P(this,ue,yd).call(this)})}addCommands(e){f(this,Oi).add(e),P(this,ue,fs).call(this,{hasSomethingToUndo:!0,hasSomethingToRedo:!1,isEmpty:P(this,ue,yd).call(this)})}delete(){if(this.commitOrRemove(),!this.hasSelection)return;const e=[...f(this,ut)],t=()=>{for(const i of e)i.remove()},s=()=>{for(const i of e)P(this,ue,nw).call(this,i)};this.addCommands({cmd:t,undo:s,mustExec:!0})}commitOrRemove(){var e;(e=f(this,Vs))==null||e.commitOrRemove()}hasSomethingToControl(){return f(this,Vs)||this.hasSelection}selectAll(){for(const e of f(this,ut))e.commit();P(this,ue,sw).call(this,f(this,un).values())}unselectAll(){if(!(f(this,Vs)&&(f(this,Vs).commitOrRemove(),f(this,An)!==De.NONE))&&this.hasSelection){for(const e of f(this,ut))e.unselect();f(this,ut).clear(),P(this,ue,fs).call(this,{hasSelectedEditor:!1})}}translateSelectedEditors(e,t,s=!1){if(s||this.commitOrRemove(),!this.hasSelection)return;f(this,Jo)[0]+=e,f(this,Jo)[1]+=t;const[i,r]=f(this,Jo),o=[...f(this,ut)],a=1e3;f(this,hr)&&clearTimeout(f(this,hr)),T(this,hr,setTimeout(()=>{T(this,hr,null),f(this,Jo)[0]=f(this,Jo)[1]=0,this.addCommands({cmd:()=>{for(const l of o)f(this,un).has(l.id)&&l.translateInPage(i,r)},undo:()=>{for(const l of o)f(this,un).has(l.id)&&l.translateInPage(-i,-r)},mustExec:!1})},a));for(const l of o)l.translateInPage(e,t)}setUpDragSession(){if(this.hasSelection){this.disableUserSelect(!0),T(this,ar,new Map);for(const e of f(this,ut))f(this,ar).set(e,{savedX:e.x,savedY:e.y,savedPageIndex:e.pageIndex,newX:0,newY:0,newPageIndex:-1})}}endDragSession(){if(!f(this,ar))return!1;this.disableUserSelect(!1);const e=f(this,ar);T(this,ar,null);let t=!1;for(const[{x:i,y:r,pageIndex:o},a]of e)a.newX=i,a.newY=r,a.newPageIndex=o,t||(t=i!==a.savedX||r!==a.savedY||o!==a.savedPageIndex);if(!t)return!1;const s=(i,r,o,a)=>{if(f(this,un).has(i.id)){const l=f(this,Dn).get(a);l?i._setParentAndPosition(l,r,o):(i.pageIndex=a,i.x=r,i.y=o)}};return this.addCommands({cmd:()=>{for(const[i,{newX:r,newY:o,newPageIndex:a}]of e)s(i,r,o,a)},undo:()=>{for(const[i,{savedX:r,savedY:o,savedPageIndex:a}]of e)s(i,r,o,a)},mustExec:!0}),!0}dragSelectedEditors(e,t){if(f(this,ar))for(const s of f(this,ar).keys())s.drag(e,t)}rebuild(e){if(e.parent===null){const t=this.getLayer(e.pageIndex);t?(t.changeParent(e),t.addOrRebuild(e)):(this.addEditor(e),this.addToAnnotationStorage(e),e.rebuild())}else e.parent.addOrRebuild(e)}get isEditorHandlingKeyboard(){var e;return((e=this.getActive())==null?void 0:e.shouldGetKeyboardEvents())||f(this,ut).size===1&&this.firstSelectedEditor.shouldGetKeyboardEvents()}isActive(e){return f(this,Vs)===e}getActive(){return f(this,Vs)}getMode(){return f(this,An)}get imageManager(){return Xe(this,"imageManager",new Xb)}getSelectionBoxes(e){if(!e)return null;const t=document.getSelection();for(let c=0,h=t.rangeCount;c({x:(h-i)/o,y:1-(c+u-s)/r,width:d/o,height:u/r});break;case"180":a=(c,h,u,d)=>({x:1-(c+u-s)/r,y:1-(h+d-i)/o,width:u/r,height:d/o});break;case"270":a=(c,h,u,d)=>({x:1-(h+d-i)/o,y:(c-s)/r,width:d/o,height:u/r});break;default:a=(c,h,u,d)=>({x:(c-s)/r,y:(h-i)/o,width:u/r,height:d/o});break}const l=[];for(let c=0,h=t.rangeCount;c{d.type==="pointerup"&&d.button!==0||(c.abort(),l==null||l.toggleDrawing(!0),d.type==="pointerup"&&P(this,ue,Sg).call(this,"main_toolbar"))};window.addEventListener("pointerup",u,{signal:h}),window.addEventListener("blur",u,{signal:h})}},Sg=function(e=""){f(this,An)===De.HIGHLIGHT?this.highlightSelection(e):f(this,Cf)&&P(this,ue,PR).call(this)},MR=function(){document.addEventListener("selectionchange",P(this,ue,RR).bind(this),{signal:this._signal})},IR=function(){if(f(this,Ko))return;T(this,Ko,new AbortController);const e=this.combinedSignal(f(this,Ko));window.addEventListener("focus",this.focus.bind(this),{signal:e}),window.addEventListener("blur",this.blur.bind(this),{signal:e})},OR=function(){var e;(e=f(this,Ko))==null||e.abort(),T(this,Ko,null)},Qb=function(){if(f(this,Yo))return;T(this,Yo,new AbortController);const e=this.combinedSignal(f(this,Yo));window.addEventListener("keydown",this.keydown.bind(this),{signal:e}),window.addEventListener("keyup",this.keyup.bind(this),{signal:e})},NR=function(){var e;(e=f(this,Yo))==null||e.abort(),T(this,Yo,null)},ew=function(){if(f(this,Go))return;T(this,Go,new AbortController);const e=this.combinedSignal(f(this,Go));document.addEventListener("copy",this.copy.bind(this),{signal:e}),document.addEventListener("cut",this.cut.bind(this),{signal:e}),document.addEventListener("paste",this.paste.bind(this),{signal:e})},tw=function(){var e;(e=f(this,Go))==null||e.abort(),T(this,Go,null)},LR=function(){const e=this._signal;document.addEventListener("dragover",this.dragOver.bind(this),{signal:e}),document.addEventListener("drop",this.drop.bind(this),{signal:e})},fs=function(e){Object.entries(e).some(([s,i])=>f(this,Of)[s]!==i)&&(this._eventBus.dispatch("annotationeditorstateschanged",{source:this,details:Object.assign(f(this,Of),e)}),f(this,An)===De.HIGHLIGHT&&e.hasSelectedEditor===!1&&P(this,ue,Do).call(this,[[Te.HIGHLIGHT_FREE,!0]]))},Do=function(e){this._eventBus.dispatch("annotationeditorparamschanged",{source:this,details:e})},DR=async function(){if(!f(this,Xo)){T(this,Xo,!0);const e=[];for(const t of f(this,Dn).values())e.push(t.enable());await Promise.all(e);for(const t of f(this,un).values())t.enable()}},jR=function(){if(this.unselectAll(),f(this,Xo)){T(this,Xo,!1);for(const e of f(this,Dn).values())e.disable();for(const e of f(this,un).values())e.disable()}},nw=function(e){const t=f(this,Dn).get(e.pageIndex);t?t.addOrRebuild(e):(this.addEditor(e),this.addToAnnotationStorage(e))},FR=function(){let e=null;for(e of f(this,ut));return e},yd=function(){if(f(this,un).size===0)return!0;if(f(this,un).size===1)for(const e of f(this,un).values())return e.isEmpty();return!1},sw=function(e){for(const t of f(this,ut))t.unselect();f(this,ut).clear();for(const t of e)t.isEmpty()||(f(this,ut).add(t),t.select());P(this,ue,fs).call(this,{hasSelectedEditor:this.hasSelection})},oe(oh,"TRANSLATE_SMALL",1),oe(oh,"TRANSLATE_BIG",10);let mc=oh;var kn,ur,Li,$h,dr,Ws,Th,fr,Ts,Zr,vl,pr,Qo,Xi,vd,xg;const ps=class ps{constructor(e){M(this,Xi);M(this,kn,null);M(this,ur,!1);M(this,Li,null);M(this,$h,null);M(this,dr,null);M(this,Ws,null);M(this,Th,!1);M(this,fr,null);M(this,Ts,null);M(this,Zr,null);M(this,vl,null);M(this,pr,!1);T(this,Ts,e),T(this,pr,e._uiManager.useNewAltTextFlow),f(ps,Qo)||T(ps,Qo,Object.freeze({added:"pdfjs-editor-new-alt-text-added-button","added-label":"pdfjs-editor-new-alt-text-added-button-label",missing:"pdfjs-editor-new-alt-text-missing-button","missing-label":"pdfjs-editor-new-alt-text-missing-button-label",review:"pdfjs-editor-new-alt-text-to-review-button","review-label":"pdfjs-editor-new-alt-text-to-review-button-label"}))}static initialize(e){ps._l10n??(ps._l10n=e)}async render(){const e=T(this,Li,document.createElement("button"));e.className="altText",e.tabIndex="0";const t=T(this,$h,document.createElement("span"));e.append(t),f(this,pr)?(e.classList.add("new"),e.setAttribute("data-l10n-id",f(ps,Qo).missing),t.setAttribute("data-l10n-id",f(ps,Qo)["missing-label"])):(e.setAttribute("data-l10n-id","pdfjs-editor-alt-text-button"),t.setAttribute("data-l10n-id","pdfjs-editor-alt-text-button-label"));const s=f(this,Ts)._uiManager._signal;e.addEventListener("contextmenu",Si,{signal:s}),e.addEventListener("pointerdown",r=>r.stopPropagation(),{signal:s});const i=r=>{r.preventDefault(),f(this,Ts)._uiManager.editAltText(f(this,Ts)),f(this,pr)&&f(this,Ts)._reportTelemetry({action:"pdfjs.image.alt_text.image_status_label_clicked",data:{label:f(this,Xi,vd)}})};return e.addEventListener("click",i,{capture:!0,signal:s}),e.addEventListener("keydown",r=>{r.target===e&&r.key==="Enter"&&(T(this,Th,!0),i(r))},{signal:s}),await P(this,Xi,xg).call(this),e}finish(){f(this,Li)&&(f(this,Li).focus({focusVisible:f(this,Th)}),T(this,Th,!1))}isEmpty(){return f(this,pr)?f(this,kn)===null:!f(this,kn)&&!f(this,ur)}hasData(){return f(this,pr)?f(this,kn)!==null||!!f(this,Zr):this.isEmpty()}get guessedText(){return f(this,Zr)}async setGuessedText(e){f(this,kn)===null&&(T(this,Zr,e),T(this,vl,await ps._l10n.get("pdfjs-editor-new-alt-text-generated-alt-text-with-disclaimer",{generatedAltText:e})),P(this,Xi,xg).call(this))}toggleAltTextBadge(e=!1){var t;if(!f(this,pr)||f(this,kn)){(t=f(this,fr))==null||t.remove(),T(this,fr,null);return}if(!f(this,fr)){const s=T(this,fr,document.createElement("div"));s.className="noAltTextBadge",f(this,Ts).div.append(s)}f(this,fr).classList.toggle("hidden",!e)}serialize(e){let t=f(this,kn);return!e&&f(this,Zr)===t&&(t=f(this,vl)),{altText:t,decorative:f(this,ur),guessedText:f(this,Zr),textWithDisclaimer:f(this,vl)}}get data(){return{altText:f(this,kn),decorative:f(this,ur)}}set data({altText:e,decorative:t,guessedText:s,textWithDisclaimer:i,cancel:r=!1}){s&&(T(this,Zr,s),T(this,vl,i)),!(f(this,kn)===e&&f(this,ur)===t)&&(r||(T(this,kn,e),T(this,ur,t)),P(this,Xi,xg).call(this))}toggle(e=!1){f(this,Li)&&(!e&&f(this,Ws)&&(clearTimeout(f(this,Ws)),T(this,Ws,null)),f(this,Li).disabled=!e)}shown(){f(this,Ts)._reportTelemetry({action:"pdfjs.image.alt_text.image_status_label_displayed",data:{label:f(this,Xi,vd)}})}destroy(){var e,t;(e=f(this,Li))==null||e.remove(),T(this,Li,null),T(this,$h,null),T(this,dr,null),(t=f(this,fr))==null||t.remove(),T(this,fr,null)}};kn=new WeakMap,ur=new WeakMap,Li=new WeakMap,$h=new WeakMap,dr=new WeakMap,Ws=new WeakMap,Th=new WeakMap,fr=new WeakMap,Ts=new WeakMap,Zr=new WeakMap,vl=new WeakMap,pr=new WeakMap,Qo=new WeakMap,Xi=new WeakSet,vd=function(){return f(this,kn)&&"added"||f(this,kn)===null&&this.guessedText&&"review"||"missing"},xg=async function(){var i,r,o;const e=f(this,Li);if(!e)return;if(f(this,pr)){if(e.classList.toggle("done",!!f(this,kn)),e.setAttribute("data-l10n-id",f(ps,Qo)[f(this,Xi,vd)]),(i=f(this,$h))==null||i.setAttribute("data-l10n-id",f(ps,Qo)[`${f(this,Xi,vd)}-label`]),!f(this,kn)){(r=f(this,dr))==null||r.remove();return}}else{if(!f(this,kn)&&!f(this,ur)){e.classList.remove("done"),(o=f(this,dr))==null||o.remove();return}e.classList.add("done"),e.setAttribute("data-l10n-id","pdfjs-editor-alt-text-edit-button")}let t=f(this,dr);if(!t){T(this,dr,t=document.createElement("span")),t.className="tooltip",t.setAttribute("role","tooltip"),t.id=`alt-text-tooltip-${f(this,Ts).id}`;const a=100,l=f(this,Ts)._uiManager._signal;l.addEventListener("abort",()=>{clearTimeout(f(this,Ws)),T(this,Ws,null)},{once:!0}),e.addEventListener("mouseenter",()=>{T(this,Ws,setTimeout(()=>{T(this,Ws,null),f(this,dr).classList.add("show"),f(this,Ts)._reportTelemetry({action:"alt_text_tooltip"})},a))},{signal:l}),e.addEventListener("mouseleave",()=>{var c;f(this,Ws)&&(clearTimeout(f(this,Ws)),T(this,Ws,null)),(c=f(this,dr))==null||c.classList.remove("show")},{signal:l})}f(this,ur)?t.setAttribute("data-l10n-id","pdfjs-editor-alt-text-decorative-tooltip"):(t.removeAttribute("data-l10n-id"),t.textContent=f(this,kn)),t.parentNode||e.append(t);const s=f(this,Ts).getImageForAltText();s==null||s.setAttribute("aria-describedby",t.id)},M(ps,Qo,null),oe(ps,"_l10n",null);let _y=ps;var bl,Di,zt,Ph,wl,jn,_l,ea,Lf,Sl,ta,Df,xl,Xr,mr,Rh,Mh,ci,jf,Yy,He,iw,Ff,rw,ow,zR,HR,aw,lw,cw,BR,hw,UR,qR,VR,uw,bd;const ht=class ht{constructor(e){M(this,He);M(this,bl,null);M(this,Di,null);M(this,zt,null);M(this,Ph,!1);M(this,wl,!1);M(this,jn,null);M(this,_l,null);M(this,ea,null);M(this,Lf,"");M(this,Sl,!1);M(this,ta,null);M(this,Df,!1);M(this,xl,!1);M(this,Xr,!1);M(this,mr,null);M(this,Rh,0);M(this,Mh,0);M(this,ci,null);oe(this,"_editToolbar",null);oe(this,"_initialOptions",Object.create(null));oe(this,"_initialData",null);oe(this,"_isVisible",!0);oe(this,"_uiManager",null);oe(this,"_focusEventsAllowed",!0);M(this,jf,!1);M(this,Yy,ht._zIndex++);this.parent=e.parent,this.id=e.id,this.width=this.height=null,this.pageIndex=e.parent.pageIndex,this.name=e.name,this.div=null,this._uiManager=e.uiManager,this.annotationElementId=null,this._willKeepAspectRatio=!1,this._initialOptions.isCentered=e.isCentered,this._structTreeParentId=null;const{rotation:t,rawDims:{pageWidth:s,pageHeight:i,pageX:r,pageY:o}}=this.parent.viewport;this.rotation=t,this.pageRotation=(360+t-this._uiManager.viewParameters.rotation)%360,this.pageDimensions=[s,i],this.pageTranslation=[r,o];const[a,l]=this.parentDimensions;this.x=e.x/a,this.y=e.y/l,this.isAttachedToDOM=!1,this.deleted=!1}static get _resizerKeyboardManager(){const e=ht.prototype._resizeWithKeyboard,t=mc.TRANSLATE_SMALL,s=mc.TRANSLATE_BIG;return Xe(this,"_resizerKeyboardManager",new nm([[["ArrowLeft","mac+ArrowLeft"],e,{args:[-t,0]}],[["ctrl+ArrowLeft","mac+shift+ArrowLeft"],e,{args:[-s,0]}],[["ArrowRight","mac+ArrowRight"],e,{args:[t,0]}],[["ctrl+ArrowRight","mac+shift+ArrowRight"],e,{args:[s,0]}],[["ArrowUp","mac+ArrowUp"],e,{args:[0,-t]}],[["ctrl+ArrowUp","mac+shift+ArrowUp"],e,{args:[0,-s]}],[["ArrowDown","mac+ArrowDown"],e,{args:[0,t]}],[["ctrl+ArrowDown","mac+shift+ArrowDown"],e,{args:[0,s]}],[["Escape","mac+Escape"],ht.prototype._stopResizingWithKeyboard]]))}get editorType(){return Object.getPrototypeOf(this).constructor._type}static get _defaultLineColor(){return Xe(this,"_defaultLineColor",this._colorManager.getHexCode("CanvasText"))}static deleteAnnotationElement(e){const t=new u8({id:e.parent.getNextId(),parent:e.parent,uiManager:e._uiManager});t.annotationElementId=e.annotationElementId,t.deleted=!0,t._uiManager.addToAnnotationStorage(t)}static initialize(e,t){if(ht._l10n??(ht._l10n=e),ht._l10nResizer||(ht._l10nResizer=Object.freeze({topLeft:"pdfjs-editor-resizer-top-left",topMiddle:"pdfjs-editor-resizer-top-middle",topRight:"pdfjs-editor-resizer-top-right",middleRight:"pdfjs-editor-resizer-middle-right",bottomRight:"pdfjs-editor-resizer-bottom-right",bottomMiddle:"pdfjs-editor-resizer-bottom-middle",bottomLeft:"pdfjs-editor-resizer-bottom-left",middleLeft:"pdfjs-editor-resizer-middle-left"})),ht._borderLineWidth!==-1)return;const s=getComputedStyle(document.documentElement);ht._borderLineWidth=parseFloat(s.getPropertyValue("--outline-width"))||0}static updateDefaultParams(e,t){}static get defaultPropertiesToUpdate(){return[]}static isHandlingMimeForPasting(e){return!1}static paste(e,t){Tt("Not implemented")}get propertiesToUpdate(){return[]}get _isDraggable(){return f(this,jf)}set _isDraggable(e){var t;T(this,jf,e),(t=this.div)==null||t.classList.toggle("draggable",e)}get isEnterHandled(){return!0}center(){const[e,t]=this.pageDimensions;switch(this.parentRotation){case 90:this.x-=this.height*t/(e*2),this.y+=this.width*e/(t*2);break;case 180:this.x+=this.width/2,this.y+=this.height/2;break;case 270:this.x+=this.height*t/(e*2),this.y-=this.width*e/(t*2);break;default:this.x-=this.width/2,this.y-=this.height/2;break}this.fixAndSetPosition()}addCommands(e){this._uiManager.addCommands(e)}get currentLayer(){return this._uiManager.currentLayer}setInBackground(){this.div.style.zIndex=0}setInForeground(){this.div.style.zIndex=f(this,Yy)}setParent(e){e!==null?(this.pageIndex=e.pageIndex,this.pageDimensions=e.pageDimensions):P(this,He,bd).call(this),this.parent=e}focusin(e){this._focusEventsAllowed&&(f(this,Sl)?T(this,Sl,!1):this.parent.setSelected(this))}focusout(e){var s;if(!this._focusEventsAllowed||!this.isAttachedToDOM)return;const t=e.relatedTarget;t!=null&&t.closest(`#${this.id}`)||(e.preventDefault(),(s=this.parent)!=null&&s.isMultipleSelection||this.commitOrRemove())}commitOrRemove(){this.isEmpty()?this.remove():this.commit()}commit(){this.addToAnnotationStorage()}addToAnnotationStorage(){this._uiManager.addToAnnotationStorage(this)}setAt(e,t,s,i){const[r,o]=this.parentDimensions;[s,i]=this.screenToPageTranslation(s,i),this.x=(e+s)/r,this.y=(t+i)/o,this.fixAndSetPosition()}translate(e,t){P(this,He,iw).call(this,this.parentDimensions,e,t)}translateInPage(e,t){f(this,ta)||T(this,ta,[this.x,this.y]),P(this,He,iw).call(this,this.pageDimensions,e,t),this.div.scrollIntoView({block:"nearest"})}drag(e,t){f(this,ta)||T(this,ta,[this.x,this.y]);const[s,i]=this.parentDimensions;if(this.x+=e/s,this.y+=t/i,this.parent&&(this.x<0||this.x>1||this.y<0||this.y>1)){const{x:c,y:h}=this.div.getBoundingClientRect();this.parent.findNewParent(this,c,h)&&(this.x-=Math.floor(this.x),this.y-=Math.floor(this.y))}let{x:r,y:o}=this;const[a,l]=this.getBaseTranslation();r+=a,o+=l,this.div.style.left=`${(100*r).toFixed(2)}%`,this.div.style.top=`${(100*o).toFixed(2)}%`,this.div.scrollIntoView({block:"nearest"})}get _hasBeenMoved(){return!!f(this,ta)&&(f(this,ta)[0]!==this.x||f(this,ta)[1]!==this.y)}getBaseTranslation(){const[e,t]=this.parentDimensions,{_borderLineWidth:s}=ht,i=s/e,r=s/t;switch(this.rotation){case 90:return[-i,r];case 180:return[i,r];case 270:return[i,-r];default:return[-i,-r]}}get _mustFixPosition(){return!0}fixAndSetPosition(e=this.rotation){const[t,s]=this.pageDimensions;let{x:i,y:r,width:o,height:a}=this;if(o*=t,a*=s,i*=t,r*=s,this._mustFixPosition)switch(e){case 0:i=Math.max(0,Math.min(t-o,i)),r=Math.max(0,Math.min(s-a,r));break;case 90:i=Math.max(0,Math.min(t-a,i)),r=Math.min(s,Math.max(o,r));break;case 180:i=Math.min(t,Math.max(o,i)),r=Math.min(s,Math.max(a,r));break;case 270:i=Math.min(t,Math.max(a,i)),r=Math.max(0,Math.min(s-o,r));break}this.x=i/=t,this.y=r/=s;const[l,c]=this.getBaseTranslation();i+=l,r+=c;const{style:h}=this.div;h.left=`${(100*i).toFixed(2)}%`,h.top=`${(100*r).toFixed(2)}%`,this.moveInDOM()}screenToPageTranslation(e,t){var s;return P(s=ht,Ff,rw).call(s,e,t,this.parentRotation)}pageTranslationToScreen(e,t){var s;return P(s=ht,Ff,rw).call(s,e,t,360-this.parentRotation)}get parentScale(){return this._uiManager.viewParameters.realScale}get parentRotation(){return(this._uiManager.viewParameters.rotation+this.pageRotation)%360}get parentDimensions(){const{parentScale:e,pageDimensions:[t,s]}=this;return[t*e,s*e]}setDims(e,t){const[s,i]=this.parentDimensions;this.div.style.width=`${(100*e/s).toFixed(2)}%`,f(this,wl)||(this.div.style.height=`${(100*t/i).toFixed(2)}%`)}fixDims(){const{style:e}=this.div,{height:t,width:s}=e,i=s.endsWith("%"),r=!f(this,wl)&&t.endsWith("%");if(i&&r)return;const[o,a]=this.parentDimensions;i||(e.width=`${(100*parseFloat(s)/o).toFixed(2)}%`),!f(this,wl)&&!r&&(e.height=`${(100*parseFloat(t)/a).toFixed(2)}%`)}getInitialTranslation(){return[0,0]}altTextFinish(){var e;(e=f(this,zt))==null||e.finish()}async addEditToolbar(){return this._editToolbar||f(this,xl)?this._editToolbar:(this._editToolbar=new Kb(this),this.div.append(this._editToolbar.render()),f(this,zt)&&await this._editToolbar.addAltText(f(this,zt)),this._editToolbar)}removeEditToolbar(){var e;this._editToolbar&&(this._editToolbar.remove(),this._editToolbar=null,(e=f(this,zt))==null||e.destroy())}addContainer(e){var s;const t=(s=this._editToolbar)==null?void 0:s.div;t?t.before(e):this.div.append(e)}getClientDimensions(){return this.div.getBoundingClientRect()}async addAltTextButton(){f(this,zt)||(_y.initialize(ht._l10n),T(this,zt,new _y(this)),f(this,bl)&&(f(this,zt).data=f(this,bl),T(this,bl,null)),await this.addEditToolbar())}get altTextData(){var e;return(e=f(this,zt))==null?void 0:e.data}set altTextData(e){f(this,zt)&&(f(this,zt).data=e)}get guessedAltText(){var e;return(e=f(this,zt))==null?void 0:e.guessedText}async setGuessedAltText(e){var t;await((t=f(this,zt))==null?void 0:t.setGuessedText(e))}serializeAltText(e){var t;return(t=f(this,zt))==null?void 0:t.serialize(e)}hasAltText(){return!!f(this,zt)&&!f(this,zt).isEmpty()}hasAltTextData(){var e;return((e=f(this,zt))==null?void 0:e.hasData())??!1}render(){this.div=document.createElement("div"),this.div.setAttribute("data-editor-rotation",(360-this.rotation)%360),this.div.className=this.name,this.div.setAttribute("id",this.id),this.div.tabIndex=f(this,Ph)?-1:0,this._isVisible||this.div.classList.add("hidden"),this.setInForeground(),P(this,He,hw).call(this);const[e,t]=this.parentDimensions;this.parentRotation%180!==0&&(this.div.style.maxWidth=`${(100*t/e).toFixed(2)}%`,this.div.style.maxHeight=`${(100*e/t).toFixed(2)}%`);const[s,i]=this.getInitialTranslation();return this.translate(s,i),wy(this,this.div,["pointerdown"]),this.div}pointerdown(e){const{isMac:t}=bs.platform;if(e.button!==0||e.ctrlKey&&t){e.preventDefault();return}if(T(this,Sl,!0),this._isDraggable){P(this,He,BR).call(this,e);return}P(this,He,cw).call(this,e)}get isSelected(){return this._uiManager.isSelected(this)}moveInDOM(){f(this,mr)&&clearTimeout(f(this,mr)),T(this,mr,setTimeout(()=>{var e;T(this,mr,null),(e=this.parent)==null||e.moveEditorInDOM(this)},0))}_setParentAndPosition(e,t,s){e.changeParent(this),this.x=t,this.y=s,this.fixAndSetPosition()}getRect(e,t,s=this.rotation){const i=this.parentScale,[r,o]=this.pageDimensions,[a,l]=this.pageTranslation,c=e/i,h=t/i,u=this.x*r,d=this.y*o,p=this.width*r,m=this.height*o;switch(s){case 0:return[u+c+a,o-d-h-m+l,u+c+p+a,o-d-h+l];case 90:return[u+h+a,o-d+c+l,u+h+m+a,o-d+c+p+l];case 180:return[u-c-p+a,o-d+h+l,u-c+a,o-d+h+m+l];case 270:return[u-h-m+a,o-d-c-p+l,u-h+a,o-d-c+l];default:throw new Error("Invalid rotation")}}getRectInCurrentCoords(e,t){const[s,i,r,o]=e,a=r-s,l=o-i;switch(this.rotation){case 0:return[s,t-o,a,l];case 90:return[s,t-i,l,a];case 180:return[r,t-i,a,l];case 270:return[r,t-o,l,a];default:throw new Error("Invalid rotation")}}onceAdded(){}isEmpty(){return!1}enableEditMode(){T(this,xl,!0)}disableEditMode(){T(this,xl,!1)}isInEditMode(){return f(this,xl)}shouldGetKeyboardEvents(){return f(this,Xr)}needsToBeRebuilt(){return this.div&&!this.isAttachedToDOM}rebuild(){P(this,He,hw).call(this)}rotate(e){}serializeDeleted(){var e;return{id:this.annotationElementId,deleted:!0,pageIndex:this.pageIndex,popupRef:((e=this._initialData)==null?void 0:e.popupRef)||""}}serialize(e=!1,t=null){Tt("An editor must be serializable")}static async deserialize(e,t,s){const i=new this.prototype.constructor({parent:t,id:t.getNextId(),uiManager:s});i.rotation=e.rotation,T(i,bl,e.accessibilityData);const[r,o]=i.pageDimensions,[a,l,c,h]=i.getRectInCurrentCoords(e.rect,o);return i.x=a/r,i.y=l/o,i.width=c/r,i.height=h/o,i}get hasBeenModified(){return!!this.annotationElementId&&(this.deleted||this.serialize()!==null)}remove(){var e;if((e=f(this,ea))==null||e.abort(),T(this,ea,null),this.isEmpty()||this.commit(),this.parent?this.parent.remove(this):this._uiManager.removeEditor(this),f(this,mr)&&(clearTimeout(f(this,mr)),T(this,mr,null)),P(this,He,bd).call(this),this.removeEditToolbar(),f(this,ci)){for(const t of f(this,ci).values())clearTimeout(t);T(this,ci,null)}this.parent=null}get isResizable(){return!1}makeResizable(){this.isResizable&&(P(this,He,zR).call(this),f(this,jn).classList.remove("hidden"),wy(this,this.div,["keydown"]))}get toolbarPosition(){return null}keydown(e){if(!this.isResizable||e.target!==this.div||e.key!=="Enter")return;this._uiManager.setSelected(this),T(this,_l,{savedX:this.x,savedY:this.y,savedWidth:this.width,savedHeight:this.height});const t=f(this,jn).children;if(!f(this,Di)){T(this,Di,Array.from(t));const o=P(this,He,UR).bind(this),a=P(this,He,qR).bind(this),l=this._uiManager._signal;for(const c of f(this,Di)){const h=c.getAttribute("data-resizer-name");c.setAttribute("role","spinbutton"),c.addEventListener("keydown",o,{signal:l}),c.addEventListener("blur",a,{signal:l}),c.addEventListener("focus",P(this,He,VR).bind(this,h),{signal:l}),c.setAttribute("data-l10n-id",ht._l10nResizer[h])}}const s=f(this,Di)[0];let i=0;for(const o of t){if(o===s)break;i++}const r=(360-this.rotation+this.parentRotation)%360/90*(f(this,Di).length/4);if(r!==i){if(ri)for(let a=0;a{var i,r;(i=this.div)!=null&&i.classList.contains("selectedEditor")&&((r=this._editToolbar)==null||r.show())});return}(t=this._editToolbar)==null||t.show(),(s=f(this,zt))==null||s.toggleAltTextBadge(!1)}unselect(){var e,t,s,i,r;(e=f(this,jn))==null||e.classList.add("hidden"),(t=this.div)==null||t.classList.remove("selectedEditor"),(s=this.div)!=null&&s.contains(document.activeElement)&&this._uiManager.currentLayer.div.focus({preventScroll:!0}),(i=this._editToolbar)==null||i.hide(),(r=f(this,zt))==null||r.toggleAltTextBadge(!0)}updateParams(e,t){}disableEditing(){}enableEditing(){}enterInEditMode(){}getImageForAltText(){return null}get contentDiv(){return this.div}get isEditing(){return f(this,Df)}set isEditing(e){T(this,Df,e),this.parent&&(e?(this.parent.setSelected(this),this.parent.setActiveEditor(this)):this.parent.setActiveEditor(null))}setAspectRatio(e,t){T(this,wl,!0);const s=e/t,{style:i}=this.div;i.aspectRatio=s,i.height="auto"}static get MIN_SIZE(){return 16}static canCreateNewEmptyEditor(){return!0}get telemetryInitialData(){return{action:"added"}}get telemetryFinalData(){return null}_reportTelemetry(e,t=!1){if(t){f(this,ci)||T(this,ci,new Map);const{action:s}=e;let i=f(this,ci).get(s);i&&clearTimeout(i),i=setTimeout(()=>{this._reportTelemetry(e),f(this,ci).delete(s),f(this,ci).size===0&&T(this,ci,null)},ht._telemetryTimeout),f(this,ci).set(s,i);return}e.type||(e.type=this.editorType),this._uiManager._eventBus.dispatch("reporttelemetry",{source:this,details:{type:"editing",data:e}})}show(e=this._isVisible){this.div.classList.toggle("hidden",!e),this._isVisible=e}enable(){this.div&&(this.div.tabIndex=0),T(this,Ph,!1)}disable(){this.div&&(this.div.tabIndex=-1),T(this,Ph,!0)}renderAnnotationElement(e){let t=e.container.querySelector(".annotationContent");if(!t)t=document.createElement("div"),t.classList.add("annotationContent",this.editorType),e.container.prepend(t);else if(t.nodeName==="CANVAS"){const s=t;t=document.createElement("div"),t.classList.add("annotationContent",this.editorType),s.before(t)}return t}resetAnnotationElement(e){const{firstChild:t}=e.container;(t==null?void 0:t.nodeName)==="DIV"&&t.classList.contains("annotationContent")&&t.remove()}};bl=new WeakMap,Di=new WeakMap,zt=new WeakMap,Ph=new WeakMap,wl=new WeakMap,jn=new WeakMap,_l=new WeakMap,ea=new WeakMap,Lf=new WeakMap,Sl=new WeakMap,ta=new WeakMap,Df=new WeakMap,xl=new WeakMap,Xr=new WeakMap,mr=new WeakMap,Rh=new WeakMap,Mh=new WeakMap,ci=new WeakMap,jf=new WeakMap,Yy=new WeakMap,He=new WeakSet,iw=function([e,t],s,i){[s,i]=this.screenToPageTranslation(s,i),this.x+=s/e,this.y+=i/t,this.fixAndSetPosition()},Ff=new WeakSet,rw=function(e,t,s){switch(s){case 90:return[t,-e];case 180:return[-e,-t];case 270:return[-t,e];default:return[e,t]}},ow=function(e){switch(e){case 90:{const[t,s]=this.pageDimensions;return[0,-t/s,s/t,0]}case 180:return[-1,0,0,-1];case 270:{const[t,s]=this.pageDimensions;return[0,t/s,-s/t,0]}default:return[1,0,0,1]}},zR=function(){if(f(this,jn))return;T(this,jn,document.createElement("div")),f(this,jn).classList.add("resizers");const e=this._willKeepAspectRatio?["topLeft","topRight","bottomRight","bottomLeft"]:["topLeft","topMiddle","topRight","middleRight","bottomRight","bottomMiddle","bottomLeft","middleLeft"],t=this._uiManager._signal;for(const s of e){const i=document.createElement("div");f(this,jn).append(i),i.classList.add("resizer",s),i.setAttribute("data-resizer-name",s),i.addEventListener("pointerdown",P(this,He,HR).bind(this,s),{signal:t}),i.addEventListener("contextmenu",Si,{signal:t}),i.tabIndex=-1}this.div.prepend(f(this,jn))},HR=function(e,t){var m;t.preventDefault();const{isMac:s}=bs.platform;if(t.button!==0||t.ctrlKey&&s)return;(m=f(this,zt))==null||m.toggle(!1);const i=this._isDraggable;this._isDraggable=!1;const r=new AbortController,o=this._uiManager.combinedSignal(r);this.parent.togglePointerEvents(!1),window.addEventListener("pointermove",P(this,He,lw).bind(this,e),{passive:!0,capture:!0,signal:o}),window.addEventListener("contextmenu",Si,{signal:o});const a=this.x,l=this.y,c=this.width,h=this.height,u=this.parent.div.style.cursor,d=this.div.style.cursor;this.div.style.cursor=this.parent.div.style.cursor=window.getComputedStyle(t.target).cursor;const p=()=>{var y;r.abort(),this.parent.togglePointerEvents(!0),(y=f(this,zt))==null||y.toggle(!0),this._isDraggable=i,this.parent.div.style.cursor=u,this.div.style.cursor=d,P(this,He,aw).call(this,a,l,c,h)};window.addEventListener("pointerup",p,{signal:o}),window.addEventListener("blur",p,{signal:o})},aw=function(e,t,s,i){const r=this.x,o=this.y,a=this.width,l=this.height;r===e&&o===t&&a===s&&l===i||this.addCommands({cmd:()=>{this.width=a,this.height=l,this.x=r,this.y=o;const[c,h]=this.parentDimensions;this.setDims(c*a,h*l),this.fixAndSetPosition()},undo:()=>{this.width=s,this.height=i,this.x=e,this.y=t;const[c,h]=this.parentDimensions;this.setDims(c*s,h*i),this.fixAndSetPosition()},mustExec:!0})},lw=function(e,t){const[s,i]=this.parentDimensions,r=this.x,o=this.y,a=this.width,l=this.height,c=ht.MIN_SIZE/s,h=ht.MIN_SIZE/i,u=J=>Math.round(J*1e4)/1e4,d=P(this,He,ow).call(this,this.rotation),p=(J,Y)=>[d[0]*J+d[2]*Y,d[1]*J+d[3]*Y],m=P(this,He,ow).call(this,360-this.rotation),y=(J,Y)=>[m[0]*J+m[2]*Y,m[1]*J+m[3]*Y];let v,g,b=!1,_=!1;switch(e){case"topLeft":b=!0,v=(J,Y)=>[0,0],g=(J,Y)=>[J,Y];break;case"topMiddle":v=(J,Y)=>[J/2,0],g=(J,Y)=>[J/2,Y];break;case"topRight":b=!0,v=(J,Y)=>[J,0],g=(J,Y)=>[0,Y];break;case"middleRight":_=!0,v=(J,Y)=>[J,Y/2],g=(J,Y)=>[0,Y/2];break;case"bottomRight":b=!0,v=(J,Y)=>[J,Y],g=(J,Y)=>[0,0];break;case"bottomMiddle":v=(J,Y)=>[J/2,Y],g=(J,Y)=>[J/2,0];break;case"bottomLeft":b=!0,v=(J,Y)=>[0,Y],g=(J,Y)=>[J,0];break;case"middleLeft":_=!0,v=(J,Y)=>[0,Y/2],g=(J,Y)=>[J,Y/2];break}const x=v(a,l),A=g(a,l);let C=p(...A);const $=u(r+C[0]),I=u(o+C[1]);let j=1,q=1,[L,B]=this.screenToPageTranslation(t.movementX,t.movementY);if([L,B]=y(L/s,B/i),b){const J=Math.hypot(a,l);j=q=Math.max(Math.min(Math.hypot(A[0]-x[0]-L,A[1]-x[1]-B)/J,1/a,1/l),c/a,h/l)}else _?j=Math.max(c,Math.min(1,Math.abs(A[0]-x[0]-L)))/a:q=Math.max(h,Math.min(1,Math.abs(A[1]-x[1]-B)))/l;const H=u(a*j),D=u(l*q);C=p(...g(H,D));const X=$-C[0],te=I-C[1];this.width=H,this.height=D,this.x=X,this.y=te,this.setDims(s*H,i*D),this.fixAndSetPosition()},cw=function(e){const{isMac:t}=bs.platform;e.ctrlKey&&!t||e.shiftKey||e.metaKey&&t?this.parent.toggleSelected(this):this.parent.setSelected(this)},BR=function(e){const{isSelected:t}=this;this._uiManager.setUpDragSession();const s=new AbortController,i=this._uiManager.combinedSignal(s);if(t){this.div.classList.add("moving"),T(this,Rh,e.clientX),T(this,Mh,e.clientY);const o=a=>{const{clientX:l,clientY:c}=a,[h,u]=this.screenToPageTranslation(l-f(this,Rh),c-f(this,Mh));T(this,Rh,l),T(this,Mh,c),this._uiManager.dragSelectedEditors(h,u)};window.addEventListener("pointermove",o,{passive:!0,capture:!0,signal:i})}const r=()=>{s.abort(),t&&this.div.classList.remove("moving"),T(this,Sl,!1),this._uiManager.endDragSession()||P(this,He,cw).call(this,e)};window.addEventListener("pointerup",r,{signal:i}),window.addEventListener("blur",r,{signal:i})},hw=function(){if(f(this,ea)||!this.div)return;T(this,ea,new AbortController);const e=this._uiManager.combinedSignal(f(this,ea));this.div.addEventListener("focusin",this.focusin.bind(this),{signal:e}),this.div.addEventListener("focusout",this.focusout.bind(this),{signal:e})},UR=function(e){ht._resizerKeyboardManager.exec(this,e)},qR=function(e){var t;f(this,Xr)&&((t=e.relatedTarget)==null?void 0:t.parentNode)!==f(this,jn)&&P(this,He,bd).call(this)},VR=function(e){T(this,Lf,f(this,Xr)?e:"")},uw=function(e){if(f(this,Di))for(const t of f(this,Di))t.tabIndex=e},bd=function(){if(T(this,Xr,!1),P(this,He,uw).call(this,-1),f(this,_l)){const{savedX:e,savedY:t,savedWidth:s,savedHeight:i}=f(this,_l);P(this,He,aw).call(this,e,t,s,i),T(this,_l,null)}},M(ht,Ff),oe(ht,"_l10n",null),oe(ht,"_l10nResizer",null),oe(ht,"_borderLineWidth",-1),oe(ht,"_colorManager",new Yb),oe(ht,"_zIndex",1),oe(ht,"_telemetryTimeout",1e3);let ft=ht;class u8 extends ft{constructor(e){super(e),this.annotationElementId=e.annotationElementId,this.deleted=!0}serialize(){return this.serializeDeleted()}}const Zk=3285377520,ai=4294901760,nr=65535;class WR{constructor(e){this.h1=e?e&4294967295:Zk,this.h2=e?e&4294967295:Zk}update(e){let t,s;if(typeof e=="string"){t=new Uint8Array(e.length*2),s=0;for(let y=0,v=e.length;y>>8,t[s++]=g&255)}}else if(ArrayBuffer.isView(e))t=e.slice(),s=t.byteLength;else throw new Error("Invalid data format, must be a string or TypedArray.");const i=s>>2,r=s-i*4,o=new Uint32Array(t.buffer,0,i);let a=0,l=0,c=this.h1,h=this.h2;const u=3432918353,d=461845907,p=u&nr,m=d&nr;for(let y=0;y>>17,a=a*d&ai|a*m&nr,c^=a,c=c<<13|c>>>19,c=c*5+3864292196):(l=o[y],l=l*u&ai|l*p&nr,l=l<<15|l>>>17,l=l*d&ai|l*m&nr,h^=l,h=h<<13|h>>>19,h=h*5+3864292196);switch(a=0,r){case 3:a^=t[i*4+2]<<16;case 2:a^=t[i*4+1]<<8;case 1:a^=t[i*4],a=a*u&ai|a*p&nr,a=a<<15|a>>>17,a=a*d&ai|a*m&nr,i&1?c^=a:h^=a}this.h1=c,this.h2=h}hexdigest(){let e=this.h1,t=this.h2;return e^=t>>>1,e=e*3981806797&ai|e*36045&nr,t=t*4283543511&ai|((t<<16|e>>>16)*2950163797&ai)>>>16,e^=t>>>1,e=e*444984403&ai|e*60499&nr,t=t*3301882366&ai|((t<<16|e>>>16)*3120437893&ai)>>>16,e^=t>>>1,(e>>>0).toString(16).padStart(8,"0")+(t>>>0).toString(16).padStart(8,"0")}}const dw=Object.freeze({map:null,hash:"",transfer:void 0});var Al,kl,En,Jy,GR;class Tx{constructor(){M(this,Jy);M(this,Al,!1);M(this,kl,null);M(this,En,new Map);this.onSetModified=null,this.onResetModified=null,this.onAnnotationEditor=null}getValue(e,t){const s=f(this,En).get(e);return s===void 0?t:Object.assign(t,s)}getRawValue(e){return f(this,En).get(e)}remove(e){if(f(this,En).delete(e),f(this,En).size===0&&this.resetModified(),typeof this.onAnnotationEditor=="function"){for(const t of f(this,En).values())if(t instanceof ft)return;this.onAnnotationEditor(null)}}setValue(e,t){const s=f(this,En).get(e);let i=!1;if(s!==void 0)for(const[r,o]of Object.entries(t))s[r]!==o&&(i=!0,s[r]=o);else i=!0,f(this,En).set(e,t);i&&P(this,Jy,GR).call(this),t instanceof ft&&typeof this.onAnnotationEditor=="function"&&this.onAnnotationEditor(t.constructor._type)}has(e){return f(this,En).has(e)}getAll(){return f(this,En).size>0?xx(f(this,En)):null}setAll(e){for(const[t,s]of Object.entries(e))this.setValue(t,s)}get size(){return f(this,En).size}resetModified(){f(this,Al)&&(T(this,Al,!1),typeof this.onResetModified=="function"&&this.onResetModified())}get print(){return new KR(this)}get serializable(){if(f(this,En).size===0)return dw;const e=new Map,t=new WR,s=[],i=Object.create(null);let r=!1;for(const[o,a]of f(this,En)){const l=a instanceof ft?a.serialize(!1,i):a;l&&(e.set(o,l),t.update(`${o}:${JSON.stringify(l)}`),r||(r=!!l.bitmap))}if(r)for(const o of e.values())o.bitmap&&s.push(o.bitmap);return e.size>0?{map:e,hash:t.hexdigest(),transfer:s}:dw}get editorStats(){let e=null;const t=new Map;for(const s of f(this,En).values()){if(!(s instanceof ft))continue;const i=s.telemetryFinalData;if(!i)continue;const{type:r}=i;t.has(r)||t.set(r,Object.getPrototypeOf(s).constructor),e||(e=Object.create(null));const o=e[r]||(e[r]=new Map);for(const[a,l]of Object.entries(i)){if(a==="type")continue;let c=o.get(a);c||(c=new Map,o.set(a,c));const h=c.get(l)??0;c.set(l,h+1)}}for(const[s,i]of t)e[s]=i.computeTelemetryFinalData(e[s]);return e}resetModifiedIds(){T(this,kl,null)}get modifiedIds(){if(f(this,kl))return f(this,kl);const e=[];for(const t of f(this,En).values())!(t instanceof ft)||!t.annotationElementId||!t.serialize()||e.push(t.annotationElementId);return T(this,kl,{ids:new Set(e),hash:e.join(",")})}}Al=new WeakMap,kl=new WeakMap,En=new WeakMap,Jy=new WeakSet,GR=function(){f(this,Al)||(T(this,Al,!0),typeof this.onSetModified=="function"&&this.onSetModified())};var zf;class KR extends Tx{constructor(t){super();M(this,zf);const{map:s,hash:i,transfer:r}=t.serializable,o=structuredClone(s,r?{transfer:r}:null);T(this,zf,{map:o,hash:i,transfer:r})}get print(){Tt("Should not call PrintAnnotationStorage.print")}get serializable(){return f(this,zf)}get modifiedIds(){return Xe(this,"modifiedIds",{ids:new Set,hash:""})}}zf=new WeakMap;var Ih;class d8{constructor({ownerDocument:e=globalThis.document,styleElement:t=null}){M(this,Ih,new Set);this._document=e,this.nativeFontFaces=new Set,this.styleElement=null,this.loadingRequests=[],this.loadTestFontId=0}addNativeFontFace(e){this.nativeFontFaces.add(e),this._document.fonts.add(e)}removeNativeFontFace(e){this.nativeFontFaces.delete(e),this._document.fonts.delete(e)}insertRule(e){this.styleElement||(this.styleElement=this._document.createElement("style"),this._document.documentElement.getElementsByTagName("head")[0].append(this.styleElement));const t=this.styleElement.sheet;t.insertRule(e,t.cssRules.length)}clear(){for(const e of this.nativeFontFaces)this._document.fonts.delete(e);this.nativeFontFaces.clear(),f(this,Ih).clear(),this.styleElement&&(this.styleElement.remove(),this.styleElement=null)}async loadSystemFont({systemFontInfo:e,_inspectFont:t}){if(!(!e||f(this,Ih).has(e.loadedName))){if(yn(!this.disableFontFace,"loadSystemFont shouldn't be called when `disableFontFace` is set."),this.isFontLoadingAPISupported){const{loadedName:s,src:i,style:r}=e,o=new FontFace(s,i,r);this.addNativeFontFace(o);try{await o.load(),f(this,Ih).add(s),t==null||t(e)}catch{qe(`Cannot load system font: ${e.baseFontName}, installing it could help to improve PDF rendering.`),this.removeNativeFontFace(o)}return}Tt("Not implemented: loadSystemFont without the Font Loading API.")}}async bind(e){if(e.attached||e.missingFile&&!e.systemFontInfo)return;if(e.attached=!0,e.systemFontInfo){await this.loadSystemFont(e);return}if(this.isFontLoadingAPISupported){const s=e.createNativeFontFace();if(s){this.addNativeFontFace(s);try{await s.loaded}catch(i){throw qe(`Failed to load font '${s.family}': '${i}'.`),e.disableFontFace=!0,i}}return}const t=e.createFontFaceRule();if(t){if(this.insertRule(t),this.isSyncFontLoadingSupported)return;await new Promise(s=>{const i=this._queueLoadingCallback(s);this._prepareFontLoadEvent(e,i)})}}get isFontLoadingAPISupported(){var t;const e=!!((t=this._document)!=null&&t.fonts);return Xe(this,"isFontLoadingAPISupported",e)}get isSyncFontLoadingSupported(){let e=!1;return(ls||typeof navigator<"u"&&typeof(navigator==null?void 0:navigator.userAgent)=="string"&&/Mozilla\/5.0.*?rv:\d+.*? Gecko/.test(navigator.userAgent))&&(e=!0),Xe(this,"isSyncFontLoadingSupported",e)}_queueLoadingCallback(e){function t(){for(yn(!i.done,"completeRequest() cannot be called twice."),i.done=!0;s.length>0&&s[0].done;){const r=s.shift();setTimeout(r.callback,0)}}const{loadingRequests:s}=this,i={done:!1,complete:t,callback:e};return s.push(i),i}get _loadTestFont(){const e=atob("T1RUTwALAIAAAwAwQ0ZGIDHtZg4AAAOYAAAAgUZGVE1lkzZwAAAEHAAAABxHREVGABQAFQAABDgAAAAeT1MvMlYNYwkAAAEgAAAAYGNtYXABDQLUAAACNAAAAUJoZWFk/xVFDQAAALwAAAA2aGhlYQdkA+oAAAD0AAAAJGhtdHgD6AAAAAAEWAAAAAZtYXhwAAJQAAAAARgAAAAGbmFtZVjmdH4AAAGAAAAAsXBvc3T/hgAzAAADeAAAACAAAQAAAAEAALZRFsRfDzz1AAsD6AAAAADOBOTLAAAAAM4KHDwAAAAAA+gDIQAAAAgAAgAAAAAAAAABAAADIQAAAFoD6AAAAAAD6AABAAAAAAAAAAAAAAAAAAAAAQAAUAAAAgAAAAQD6AH0AAUAAAKKArwAAACMAooCvAAAAeAAMQECAAACAAYJAAAAAAAAAAAAAQAAAAAAAAAAAAAAAFBmRWQAwAAuAC4DIP84AFoDIQAAAAAAAQAAAAAAAAAAACAAIAABAAAADgCuAAEAAAAAAAAAAQAAAAEAAAAAAAEAAQAAAAEAAAAAAAIAAQAAAAEAAAAAAAMAAQAAAAEAAAAAAAQAAQAAAAEAAAAAAAUAAQAAAAEAAAAAAAYAAQAAAAMAAQQJAAAAAgABAAMAAQQJAAEAAgABAAMAAQQJAAIAAgABAAMAAQQJAAMAAgABAAMAAQQJAAQAAgABAAMAAQQJAAUAAgABAAMAAQQJAAYAAgABWABYAAAAAAAAAwAAAAMAAAAcAAEAAAAAADwAAwABAAAAHAAEACAAAAAEAAQAAQAAAC7//wAAAC7////TAAEAAAAAAAABBgAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMAAAAAAAD/gwAyAAAAAQAAAAAAAAAAAAAAAAAAAAABAAQEAAEBAQJYAAEBASH4DwD4GwHEAvgcA/gXBIwMAYuL+nz5tQXkD5j3CBLnEQACAQEBIVhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYAAABAQAADwACAQEEE/t3Dov6fAH6fAT+fPp8+nwHDosMCvm1Cvm1DAz6fBQAAAAAAAABAAAAAMmJbzEAAAAAzgTjFQAAAADOBOQpAAEAAAAAAAAADAAUAAQAAAABAAAAAgABAAAAAAAAAAAD6AAAAAAAAA==");return Xe(this,"_loadTestFont",e)}_prepareFontLoadEvent(e,t){function s(x,A){return x.charCodeAt(A)<<24|x.charCodeAt(A+1)<<16|x.charCodeAt(A+2)<<8|x.charCodeAt(A+3)&255}function i(x,A,C,$){const I=x.substring(0,A),j=x.substring(A+C);return I+$+j}let r,o;const a=this._document.createElement("canvas");a.width=1,a.height=1;const l=a.getContext("2d");let c=0;function h(x,A){if(++c>30){qe("Load test font never loaded."),A();return}if(l.font="30px "+x,l.fillText(".",0,20),l.getImageData(0,0,1,1).data[3]>0){A();return}setTimeout(h.bind(null,x,A))}const u=`lt${Date.now()}${this.loadTestFontId++}`;let d=this._loadTestFont;d=i(d,976,u.length,u);const m=16,y=1482184792;let v=s(d,m);for(r=0,o=u.length-3;r{_.remove(),t.complete()})}}Ih=new WeakMap;class f8{constructor(e,{disableFontFace:t=!1,inspectFont:s=null}){this.compiledGlyphs=Object.create(null);for(const i in e)this[i]=e[i];this.disableFontFace=t===!0,this._inspectFont=s}createNativeFontFace(){var t;if(!this.data||this.disableFontFace)return null;let e;if(!this.cssFontInfo)e=new FontFace(this.loadedName,this.data,{});else{const s={weight:this.cssFontInfo.fontWeight};this.cssFontInfo.italicAngle&&(s.style=`oblique ${this.cssFontInfo.italicAngle}deg`),e=new FontFace(this.cssFontInfo.fontFamily,this.data,s)}return(t=this._inspectFont)==null||t.call(this,this),e}createFontFaceRule(){var s;if(!this.data||this.disableFontFace)return null;const e=`url(data:${this.mimetype};base64,${n8(this.data)});`;let t;if(!this.cssFontInfo)t=`@font-face {font-family:"${this.loadedName}";src:${e}}`;else{let i=`font-weight: ${this.cssFontInfo.fontWeight};`;this.cssFontInfo.italicAngle&&(i+=`font-style: oblique ${this.cssFontInfo.italicAngle}deg;`),t=`@font-face {font-family:"${this.cssFontInfo.fontFamily}";${i}src:${e}}`}return(s=this._inspectFont)==null||s.call(this,this,e),t}getPathGenerator(e,t){if(this.compiledGlyphs[t]!==void 0)return this.compiledGlyphs[t];let s;try{s=e.get(this.loadedName+"_path_"+t)}catch(r){qe(`getPathGenerator - ignoring character: "${r}".`)}if(!Array.isArray(s)||s.length===0)return this.compiledGlyphs[t]=function(r,o){};const i=[];for(let r=0,o=s.length;rp.bezierCurveTo(a,l,c,h,u,d)),r+=6}break;case Hr.MOVE_TO:{const[a,l]=s.slice(r,r+2);i.push(c=>c.moveTo(a,l)),r+=2}break;case Hr.LINE_TO:{const[a,l]=s.slice(r,r+2);i.push(c=>c.lineTo(a,l)),r+=2}break;case Hr.QUADRATIC_CURVE_TO:{const[a,l,c,h]=s.slice(r,r+4);i.push(u=>u.quadraticCurveTo(a,l,c,h)),r+=4}break;case Hr.RESTORE:i.push(a=>a.restore());break;case Hr.SAVE:i.push(a=>a.save());break;case Hr.SCALE:yn(i.length===2,"Scale command is only valid at the third position.");break;case Hr.TRANSFORM:{const[a,l,c,h,u,d]=s.slice(r,r+6);i.push(p=>p.transform(a,l,c,h,u,d)),r+=6}break;case Hr.TRANSLATE:{const[a,l]=s.slice(r,r+2);i.push(c=>c.translate(a,l)),r+=2}break}return this.compiledGlyphs[t]=function(o,a){i[0](o),i[1](o),o.scale(a,-a);for(let l=2,c=i.length;l({cMapData:s,isCompressed:this.isCompressed})).catch(s=>{throw new Error(`Unable to load ${this.isCompressed?"binary ":""}CMap at: ${t}`)})}async _fetch(e){Tt("Abstract method `_fetch` called.")}}class YR extends XR{async _fetch(e){const t=await j0(e,this.isCompressed?"arraybuffer":"text");return t instanceof ArrayBuffer?new Uint8Array(t):D0(t)}}class JR{addFilter(e){return"none"}addHCMFilter(e,t){return"none"}addAlphaFilter(e){return"none"}addLuminosityFilter(e){return"none"}addHighlightHCMFilter(e,t,s,i,r){return"none"}destroy(e=!1){}}var El,Cl,gr,Yr,ss,Qy,$l,ge,ts,Uc,qc,Ag,Vc,QR,fw,Wc,wd,_d,pw,Sd;class m8 extends JR{constructor({docId:t,ownerDocument:s=globalThis.document}){super();M(this,ge);M(this,El);M(this,Cl);M(this,gr);M(this,Yr);M(this,ss);M(this,Qy);M(this,$l,0);T(this,Yr,t),T(this,ss,s)}addFilter(t){if(!t)return"none";let s=f(this,ge,ts).get(t);if(s)return s;const[i,r,o]=P(this,ge,Ag).call(this,t),a=t.length===1?i:`${i}${r}${o}`;if(s=f(this,ge,ts).get(a),s)return f(this,ge,ts).set(t,s),s;const l=`g_${f(this,Yr)}_transfer_map_${ds(this,$l)._++}`,c=P(this,ge,Vc).call(this,l);f(this,ge,ts).set(t,c),f(this,ge,ts).set(a,c);const h=P(this,ge,Wc).call(this,l);return P(this,ge,_d).call(this,i,r,o,h),c}addHCMFilter(t,s){var m;const i=`${t}-${s}`,r="base";let o=f(this,ge,Uc).get(r);if((o==null?void 0:o.key)===i||(o?((m=o.filter)==null||m.remove(),o.key=i,o.url="none",o.filter=null):(o={key:i,url:"none",filter:null},f(this,ge,Uc).set(r,o)),!t||!s))return o.url;const a=P(this,ge,Sd).call(this,t);t=Se.makeHexColor(...a);const l=P(this,ge,Sd).call(this,s);if(s=Se.makeHexColor(...l),f(this,ge,qc).style.color="",t==="#000000"&&s==="#ffffff"||t===s)return o.url;const c=new Array(256);for(let y=0;y<=255;y++){const v=y/255;c[y]=v<=.03928?v/12.92:((v+.055)/1.055)**2.4}const h=c.join(","),u=`g_${f(this,Yr)}_hcm_filter`,d=o.filter=P(this,ge,Wc).call(this,u);P(this,ge,_d).call(this,h,h,h,d),P(this,ge,fw).call(this,d);const p=(y,v)=>{const g=a[y]/255,b=l[y]/255,_=new Array(v+1);for(let x=0;x<=v;x++)_[x]=g+x/v*(b-g);return _.join(",")};return P(this,ge,_d).call(this,p(0,5),p(1,5),p(2,5),d),o.url=P(this,ge,Vc).call(this,u),o.url}addAlphaFilter(t){let s=f(this,ge,ts).get(t);if(s)return s;const[i]=P(this,ge,Ag).call(this,[t]),r=`alpha_${i}`;if(s=f(this,ge,ts).get(r),s)return f(this,ge,ts).set(t,s),s;const o=`g_${f(this,Yr)}_alpha_map_${ds(this,$l)._++}`,a=P(this,ge,Vc).call(this,o);f(this,ge,ts).set(t,a),f(this,ge,ts).set(r,a);const l=P(this,ge,Wc).call(this,o);return P(this,ge,pw).call(this,i,l),a}addLuminosityFilter(t){let s=f(this,ge,ts).get(t||"luminosity");if(s)return s;let i,r;if(t?([i]=P(this,ge,Ag).call(this,[t]),r=`luminosity_${i}`):r="luminosity",s=f(this,ge,ts).get(r),s)return f(this,ge,ts).set(t,s),s;const o=`g_${f(this,Yr)}_luminosity_map_${ds(this,$l)._++}`,a=P(this,ge,Vc).call(this,o);f(this,ge,ts).set(t,a),f(this,ge,ts).set(r,a);const l=P(this,ge,Wc).call(this,o);return P(this,ge,QR).call(this,l),t&&P(this,ge,pw).call(this,i,l),a}addHighlightHCMFilter(t,s,i,r,o){var b;const a=`${s}-${i}-${r}-${o}`;let l=f(this,ge,Uc).get(t);if((l==null?void 0:l.key)===a||(l?((b=l.filter)==null||b.remove(),l.key=a,l.url="none",l.filter=null):(l={key:a,url:"none",filter:null},f(this,ge,Uc).set(t,l)),!s||!i))return l.url;const[c,h]=[s,i].map(P(this,ge,Sd).bind(this));let u=Math.round(.2126*c[0]+.7152*c[1]+.0722*c[2]),d=Math.round(.2126*h[0]+.7152*h[1]+.0722*h[2]),[p,m]=[r,o].map(P(this,ge,Sd).bind(this));d{const C=new Array(256),$=(d-u)/A,I=_/255,j=(x-_)/(255*A);let q=0;for(let L=0;L<=A;L++){const B=Math.round(u+L*$),H=I+L*j;for(let D=q;D<=B;D++)C[D]=H;q=B+1}for(let L=q;L<256;L++)C[L]=C[q-1];return C.join(",")},v=`g_${f(this,Yr)}_hcm_${t}_filter`,g=l.filter=P(this,ge,Wc).call(this,v);return P(this,ge,fw).call(this,g),P(this,ge,_d).call(this,y(p[0],m[0],5),y(p[1],m[1],5),y(p[2],m[2],5),g),l.url=P(this,ge,Vc).call(this,v),l.url}destroy(t=!1){t&&f(this,ge,Uc).size!==0||(f(this,gr)&&(f(this,gr).parentNode.parentNode.remove(),T(this,gr,null)),f(this,Cl)&&(f(this,Cl).clear(),T(this,Cl,null)),T(this,$l,0))}}El=new WeakMap,Cl=new WeakMap,gr=new WeakMap,Yr=new WeakMap,ss=new WeakMap,Qy=new WeakMap,$l=new WeakMap,ge=new WeakSet,ts=function(){return f(this,Cl)||T(this,Cl,new Map)},Uc=function(){return f(this,Qy)||T(this,Qy,new Map)},qc=function(){if(!f(this,gr)){const t=f(this,ss).createElement("div"),{style:s}=t;s.visibility="hidden",s.contain="strict",s.width=s.height=0,s.position="absolute",s.top=s.left=0,s.zIndex=-1;const i=f(this,ss).createElementNS(Ur,"svg");i.setAttribute("width",0),i.setAttribute("height",0),T(this,gr,f(this,ss).createElementNS(Ur,"defs")),t.append(i),i.append(f(this,gr)),f(this,ss).body.append(t)}return f(this,gr)},Ag=function(t){if(t.length===1){const c=t[0],h=new Array(256);for(let d=0;d<256;d++)h[d]=c[d]/255;const u=h.join(",");return[u,u,u]}const[s,i,r]=t,o=new Array(256),a=new Array(256),l=new Array(256);for(let c=0;c<256;c++)o[c]=s[c]/255,a[c]=i[c]/255,l[c]=r[c]/255;return[o.join(","),a.join(","),l.join(",")]},Vc=function(t){if(f(this,El)===void 0){T(this,El,"");const s=f(this,ss).URL;s!==f(this,ss).baseURI&&(F0(s)?qe('#createUrl: ignore "data:"-URL for performance reasons.'):T(this,El,s.split("#",1)[0]))}return`url(${f(this,El)}#${t})`},QR=function(t){const s=f(this,ss).createElementNS(Ur,"feColorMatrix");s.setAttribute("type","matrix"),s.setAttribute("values","0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.3 0.59 0.11 0 0"),t.append(s)},fw=function(t){const s=f(this,ss).createElementNS(Ur,"feColorMatrix");s.setAttribute("type","matrix"),s.setAttribute("values","0.2126 0.7152 0.0722 0 0 0.2126 0.7152 0.0722 0 0 0.2126 0.7152 0.0722 0 0 0 0 0 1 0"),t.append(s)},Wc=function(t){const s=f(this,ss).createElementNS(Ur,"filter");return s.setAttribute("color-interpolation-filters","sRGB"),s.setAttribute("id",t),f(this,ge,qc).append(s),s},wd=function(t,s,i){const r=f(this,ss).createElementNS(Ur,s);r.setAttribute("type","discrete"),r.setAttribute("tableValues",i),t.append(r)},_d=function(t,s,i,r){const o=f(this,ss).createElementNS(Ur,"feComponentTransfer");r.append(o),P(this,ge,wd).call(this,o,"feFuncR",t),P(this,ge,wd).call(this,o,"feFuncG",s),P(this,ge,wd).call(this,o,"feFuncB",i)},pw=function(t,s){const i=f(this,ss).createElementNS(Ur,"feComponentTransfer");s.append(i),P(this,ge,wd).call(this,i,"feFuncA",t)},Sd=function(t){return f(this,ge,qc).style.color=t,$x(getComputedStyle(f(this,ge,qc)).getPropertyValue("color"))};class eM{constructor({baseUrl:e=null}){this.baseUrl=e}async fetch({filename:e}){if(!this.baseUrl)throw new Error("Ensure that the `standardFontDataUrl` API parameter is provided.");if(!e)throw new Error("Font filename must be specified.");const t=`${this.baseUrl}${e}`;return this._fetch(t).catch(s=>{throw new Error(`Unable to load font data at: ${t}`)})}async _fetch(e){Tt("Abstract method `_fetch` called.")}}class tM extends eM{async _fetch(e){const t=await j0(e,"arraybuffer");return new Uint8Array(t)}}if(ls){var mw=Promise.withResolvers(),Zd=null;(async()=>{const e=await ym(()=>import("./__vite-browser-external-BIHI7g3E.js"),[]),t=await ym(()=>import("./__vite-browser-external-BIHI7g3E.js"),[]),s=await ym(()=>import("./__vite-browser-external-BIHI7g3E.js"),[]),i=await ym(()=>import("./__vite-browser-external-BIHI7g3E.js"),[]);let r,o;return new Map(Object.entries({fs:e,http:t,https:s,url:i,canvas:r,path2d:o}))})().then(e=>{Zd=e,mw.resolve()},e=>{qe(`loadPackages: ${e}`),Zd=new Map,mw.resolve()})}class Pa{static get promise(){return mw.promise}static get(e){return Zd==null?void 0:Zd.get(e)}}async function nM(n){const t=await Pa.get("fs").promises.readFile(n);return new Uint8Array(t)}class g8 extends JR{}class y8 extends ZR{_createCanvas(e,t){return Pa.get("canvas").createCanvas(e,t)}}class v8 extends XR{async _fetch(e){return nM(e)}}class b8 extends eM{async _fetch(e){return nM(e)}}const vs={FILL:"Fill",STROKE:"Stroke",SHADING:"Shading"};function gw(n,e){if(!e)return;const t=e[2]-e[0],s=e[3]-e[1],i=new Path2D;i.rect(e[0],e[1],t,s),n.clip(i)}class Px{getPattern(){Tt("Abstract method `getPattern` called.")}}class w8 extends Px{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 t;this._type==="axial"?t=e.createLinearGradient(this._p0[0],this._p0[1],this._p1[0],this._p1[1]):this._type==="radial"&&(t=e.createRadialGradient(this._p0[0],this._p0[1],this._r0,this._p1[0],this._p1[1],this._r1));for(const s of this._colorStops)t.addColorStop(s[0],s[1]);return t}getPattern(e,t,s,i){let r;if(i===vs.STROKE||i===vs.FILL){const o=t.current.getClippedPathBoundingBox(i,Bt(e))||[0,0,0,0],a=Math.ceil(o[2]-o[0])||1,l=Math.ceil(o[3]-o[1])||1,c=t.cachedCanvases.getCanvas("pattern",a,l),h=c.context;h.clearRect(0,0,h.canvas.width,h.canvas.height),h.beginPath(),h.rect(0,0,h.canvas.width,h.canvas.height),h.translate(-o[0],-o[1]),s=Se.transform(s,[1,0,0,1,o[0],o[1]]),h.transform(...t.baseTransform),this.matrix&&h.transform(...this.matrix),gw(h,this._bbox),h.fillStyle=this._createGradient(h),h.fill(),r=e.createPattern(c.canvas,"no-repeat");const u=new DOMMatrix(s);r.setTransform(u)}else gw(e,this._bbox),r=this._createGradient(e);return r}}function Rv(n,e,t,s,i,r,o,a){const l=e.coords,c=e.colors,h=n.data,u=n.width*4;let d;l[t+1]>l[s+1]&&(d=t,t=s,s=d,d=r,r=o,o=d),l[s+1]>l[i+1]&&(d=s,s=i,i=d,d=o,o=a,a=d),l[t+1]>l[s+1]&&(d=t,t=s,s=d,d=r,r=o,o=d);const p=(l[t]+e.offsetX)*e.scaleX,m=(l[t+1]+e.offsetY)*e.scaleY,y=(l[s]+e.offsetX)*e.scaleX,v=(l[s+1]+e.offsetY)*e.scaleY,g=(l[i]+e.offsetX)*e.scaleX,b=(l[i+1]+e.offsetY)*e.scaleY;if(m>=b)return;const _=c[r],x=c[r+1],A=c[r+2],C=c[o],$=c[o+1],I=c[o+2],j=c[a],q=c[a+1],L=c[a+2],B=Math.round(m),H=Math.round(b);let D,X,te,J,Y,ye,z,E;for(let O=B;O<=H;O++){if(Ob?G=1:v===b?G=0:G=(v-O)/(v-b),D=y-(y-g)*G,X=C-(C-j)*G,te=$-($-q)*G,J=I-(I-L)*G}let R;Ob?R=1:R=(m-O)/(m-b),Y=p-(p-g)*R,ye=_-(_-j)*R,z=x-(x-q)*R,E=A-(A-L)*R;const w=Math.round(Math.min(D,Y)),k=Math.round(Math.max(D,Y));let N=u*O+w*4;for(let G=w;G<=k;G++)R=(D-G)/(D-Y),R<0?R=0:R>1&&(R=1),h[N++]=X-(X-ye)*R|0,h[N++]=te-(te-z)*R|0,h[N++]=J-(J-E)*R|0,h[N++]=255}}function _8(n,e,t){const s=e.coords,i=e.colors;let r,o;switch(e.type){case"lattice":const a=e.verticesPerRow,l=Math.floor(s.length/a)-1,c=a-1;for(r=0;r=q?x=l:C=!0,j>=L?A=c:$=!0;const B=this.getSizeAndScale(x,this.ctx.canvas.width,b),H=this.getSizeAndScale(A,this.ctx.canvas.height,_),D=e.cachedCanvases.getCanvas("pattern",B.size,H.size),X=D.context,te=a.createCanvasGraphics(X);if(te.groupLevel=e.groupLevel,this.setFillAndStrokeStyleToContext(te,i,o),X.translate(-B.scale*h,-H.scale*u),te.transform(B.scale,0,0,H.scale,0,0),X.save(),this.clipBbox(te,h,u,d,p),te.baseTransform=Bt(te.ctx),te.executeOperatorList(s),te.endDrawing(),X.restore(),C||$){const J=D.canvas;C&&(x=l),$&&(A=c);const Y=this.getSizeAndScale(x,this.ctx.canvas.width,b),ye=this.getSizeAndScale(A,this.ctx.canvas.height,_),z=Y.size,E=ye.size,O=e.cachedCanvases.getCanvas("pattern-workaround",z,E),R=O.context,w=C?Math.floor(m/l):0,k=$?Math.floor(y/c):0;for(let N=0;N<=w;N++)for(let G=0;G<=k;G++)R.drawImage(J,z*N,E*G,z,E,0,0,z,E);return{canvas:O.canvas,scaleX:Y.scale,scaleY:ye.scale,offsetX:h,offsetY:u}}return{canvas:D.canvas,scaleX:B.scale,scaleY:H.scale,offsetX:h,offsetY:u}}getSizeAndScale(e,t,s){const i=Math.max(e0.MAX_PATTERN_SIZE,t);let r=Math.ceil(e*s);return r>=i?r=i:s=r/e,{scale:s,size:r}}clipBbox(e,t,s,i,r){const o=i-t,a=r-s;e.ctx.rect(t,s,o,a),e.current.updateRectMinMax(Bt(e.ctx),[t,s,i,r]),e.clip(),e.endPath()}setFillAndStrokeStyleToContext(e,t,s){const i=e.ctx,r=e.current;switch(t){case Xk.COLORED:const o=this.ctx;i.fillStyle=o.fillStyle,i.strokeStyle=o.strokeStyle,r.fillColor=o.fillStyle,r.strokeColor=o.strokeStyle;break;case Xk.UNCOLORED:const a=Se.makeHexColor(s[0],s[1],s[2]);i.fillStyle=a,i.strokeStyle=a,r.fillColor=a,r.strokeColor=a;break;default:throw new Z6(`Unsupported paint type: ${t}`)}}getPattern(e,t,s,i){let r=s;i!==vs.SHADING&&(r=Se.transform(r,t.baseTransform),this.matrix&&(r=Se.transform(r,this.matrix)));const o=this.createPatternCanvas(t);let a=new DOMMatrix(r);a=a.translate(o.offsetX,o.offsetY),a=a.scale(1/o.scaleX,1/o.scaleY);const l=e.createPattern(o.canvas,"repeat");return l.setTransform(a),l}};oe(e0,"MAX_PATTERN_SIZE",3e3);let yw=e0;function k8({src:n,srcPos:e=0,dest:t,width:s,height:i,nonBlackColor:r=4294967295,inverseDecode:o=!1}){const a=bs.isLittleEndian?4278190080:255,[l,c]=o?[r,a]:[a,r],h=s>>3,u=s&7,d=n.length;t=new Uint32Array(t.buffer);let p=0;for(let m=0;m{n.save=n.__originalSave,n.restore=n.__originalRestore,n.rotate=n.__originalRotate,n.scale=n.__originalScale,n.translate=n.__originalTranslate,n.transform=n.__originalTransform,n.setTransform=n.__originalSetTransform,n.resetTransform=n.__originalResetTransform,n.clip=n.__originalClip,n.moveTo=n.__originalMoveTo,n.lineTo=n.__originalLineTo,n.bezierCurveTo=n.__originalBezierCurveTo,n.rect=n.__originalRect,n.closePath=n.__originalClosePath,n.beginPath=n.__originalBeginPath,delete n._removeMirroring},n.save=function(){e.save(),this.__originalSave()},n.restore=function(){e.restore(),this.__originalRestore()},n.translate=function(s,i){e.translate(s,i),this.__originalTranslate(s,i)},n.scale=function(s,i){e.scale(s,i),this.__originalScale(s,i)},n.transform=function(s,i,r,o,a,l){e.transform(s,i,r,o,a,l),this.__originalTransform(s,i,r,o,a,l)},n.setTransform=function(s,i,r,o,a,l){e.setTransform(s,i,r,o,a,l),this.__originalSetTransform(s,i,r,o,a,l)},n.resetTransform=function(){e.resetTransform(),this.__originalResetTransform()},n.rotate=function(s){e.rotate(s),this.__originalRotate(s)},n.clip=function(s){e.clip(s),this.__originalClip(s)},n.moveTo=function(t,s){e.moveTo(t,s),this.__originalMoveTo(t,s)},n.lineTo=function(t,s){e.lineTo(t,s),this.__originalLineTo(t,s)},n.bezierCurveTo=function(t,s,i,r,o,a){e.bezierCurveTo(t,s,i,r,o,a),this.__originalBezierCurveTo(t,s,i,r,o,a)},n.rect=function(t,s,i,r){e.rect(t,s,i,r),this.__originalRect(t,s,i,r)},n.closePath=function(){e.closePath(),this.__originalClosePath()},n.beginPath=function(){e.beginPath(),this.__originalBeginPath()}}class $8{constructor(e){this.canvasFactory=e,this.cache=Object.create(null)}getCanvas(e,t,s){let i;return this.cache[e]!==void 0?(i=this.cache[e],this.canvasFactory.reset(i,t,s)):(i=this.canvasFactory.create(t,s),this.cache[e]=i),i}delete(e){delete this.cache[e]}clear(){for(const e in this.cache){const t=this.cache[e];this.canvasFactory.destroy(t),delete this.cache[e]}}}function Om(n,e,t,s,i,r,o,a,l,c){const[h,u,d,p,m,y]=Bt(n);if(u===0&&d===0){const b=o*h+m,_=Math.round(b),x=a*p+y,A=Math.round(x),C=(o+l)*h+m,$=Math.abs(Math.round(C)-_)||1,I=(a+c)*p+y,j=Math.abs(Math.round(I)-A)||1;return n.setTransform(Math.sign(h),0,0,Math.sign(p),_,A),n.drawImage(e,t,s,i,r,0,0,$,j),n.setTransform(h,u,d,p,m,y),[$,j]}if(h===0&&p===0){const b=a*d+m,_=Math.round(b),x=o*u+y,A=Math.round(x),C=(a+c)*d+m,$=Math.abs(Math.round(C)-_)||1,I=(o+l)*u+y,j=Math.abs(Math.round(I)-A)||1;return n.setTransform(0,Math.sign(u),Math.sign(d),0,_,A),n.drawImage(e,t,s,i,r,0,0,j,$),n.setTransform(h,u,d,p,m,y),[j,$]}n.drawImage(e,t,s,i,r,o,a,l,c);const v=Math.hypot(h,u),g=Math.hypot(d,p);return[v*l,g*c]}function T8(n){const{width:e,height:t}=n;if(e>eE||t>eE)return null;const s=1e3,i=new Uint8Array([0,2,4,0,1,0,5,4,8,10,0,8,0,2,1,0]),r=e+1;let o=new Uint8Array(r*(t+1)),a,l,c;const h=e+7&-8;let u=new Uint8Array(h*t),d=0;for(const g of n.data){let b=128;for(;b>0;)u[d++]=g&b?0:255,b>>=1}let p=0;for(d=0,u[d]!==0&&(o[0]=1,++p),l=1;l>2)+(u[d+1]?4:0)+(u[d-h+1]?8:0),i[g]&&(o[c+l]=i[g],++p),d++;if(u[d-h]!==u[d]&&(o[c+l]=u[d]?2:4,++p),p>s)return null}for(d=h*(t-1),c=a*r,u[d]!==0&&(o[c]=8,++p),l=1;ls)return null;const m=new Int32Array([0,r,-1,0,-r,0,0,0,1]),y=new Path2D;for(a=0;p&&a<=t;a++){let g=a*r;const b=g+e;for(;g>4,o[g]&=x>>2|x<<2),y.lineTo(g%r,g/r|0),o[g]||--p}while(_!==g);--a}return u=null,o=null,function(g){g.save(),g.scale(1/e,-1/t),g.translate(0,-t),g.fill(y),g.beginPath(),g.restore()}}class tE{constructor(e,t){this.alphaIsShape=!1,this.fontSize=0,this.fontSizeScale=1,this.textMatrix=bR,this.textMatrixScale=1,this.fontMatrix=Ub,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=es.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,t])}clone(){const e=Object.create(this);return e.clipBox=this.clipBox.slice(),e}setCurrentPoint(e,t){this.x=e,this.y=t}updatePathMinMax(e,t,s){[t,s]=Se.applyTransform([t,s],e),this.minX=Math.min(this.minX,t),this.minY=Math.min(this.minY,s),this.maxX=Math.max(this.maxX,t),this.maxY=Math.max(this.maxY,s)}updateRectMinMax(e,t){const s=Se.applyTransform(t,e),i=Se.applyTransform(t.slice(2),e),r=Se.applyTransform([t[0],t[3]],e),o=Se.applyTransform([t[2],t[1]],e);this.minX=Math.min(this.minX,s[0],i[0],r[0],o[0]),this.minY=Math.min(this.minY,s[1],i[1],r[1],o[1]),this.maxX=Math.max(this.maxX,s[0],i[0],r[0],o[0]),this.maxY=Math.max(this.maxY,s[1],i[1],r[1],o[1])}updateScalingPathMinMax(e,t){Se.scaleMinMax(e,t),this.minX=Math.min(this.minX,t[0]),this.minY=Math.min(this.minY,t[1]),this.maxX=Math.max(this.maxX,t[2]),this.maxY=Math.max(this.maxY,t[3])}updateCurvePathMinMax(e,t,s,i,r,o,a,l,c,h){const u=Se.bezierBoundingBox(t,s,i,r,o,a,l,c,h);h||this.updateRectMinMax(e,u)}getPathBoundingBox(e=vs.FILL,t=null){const s=[this.minX,this.minY,this.maxX,this.maxY];if(e===vs.STROKE){t||Tt("Stroke bounding box must include transform.");const i=Se.singularValueDecompose2dScale(t),r=i[0]*this.lineWidth/2,o=i[1]*this.lineWidth/2;s[0]-=r,s[1]-=o,s[2]+=r,s[3]+=o}return s}updateClipFromPath(){const e=Se.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=vs.FILL,t=null){return Se.intersect(this.clipBox,this.getPathBoundingBox(e,t))}}function nE(n,e){if(typeof ImageData<"u"&&e instanceof ImageData){n.putImageData(e,0,0);return}const t=e.height,s=e.width,i=t%Os,r=(t-i)/Os,o=i===0?r:r+1,a=n.createImageData(s,Os);let l=0,c;const h=e.data,u=a.data;let d,p,m,y;if(e.kind===yg.GRAYSCALE_1BPP){const v=h.byteLength,g=new Uint32Array(u.buffer,0,u.byteLength>>2),b=g.length,_=s+7>>3,x=4294967295,A=bs.isLittleEndian?4278190080:255;for(d=0;d_?s:C*8-7,j=I&-8;let q=0,L=0;for(;$>=1}for(;c=r&&(m=i,y=s*m),c=0,p=y;p--;)u[c++]=h[l++],u[c++]=h[l++],u[c++]=h[l++],u[c++]=255;n.putImageData(a,0,d*Os)}else throw new Error(`bad image kind: ${e.kind}`)}function sE(n,e){if(e.bitmap){n.drawImage(e.bitmap,0,0);return}const t=e.height,s=e.width,i=t%Os,r=(t-i)/Os,o=i===0?r:r+1,a=n.createImageData(s,Os);let l=0;const c=e.data,h=a.data;for(let u=0;uQk&&typeof s=="function",h=c?Date.now()+E8:0;let u=0;const d=this.commonObjs,p=this.objs;let m;for(;;){if(i!==void 0&&a===i.nextBreakPoint)return i.breakIt(a,s),a;if(m=o[a],m!==Mi.dependency)this[m].apply(this,r[a]);else for(const y of r[a]){const v=y.startsWith("g_")?d:p;if(!v.has(y))return v.get(y,s),a}if(a++,a===l)return a;if(c&&++u>Qk){if(Date.now()>h)return s(),a;u=0}}}endDrawing(){P(this,La,vw).call(this),this.cachedCanvases.clear(),this.cachedPatterns.clear();for(const e of this._cachedBitmapsMap.values()){for(const t of e.values())typeof HTMLCanvasElement<"u"&&t instanceof HTMLCanvasElement&&(t.width=t.height=0);e.clear()}this._cachedBitmapsMap.clear(),P(this,La,bw).call(this)}_scaleImage(e,t){const s=e.width??e.displayWidth,i=e.height??e.displayHeight;let r=Math.max(Math.hypot(t[0],t[1]),1),o=Math.max(Math.hypot(t[2],t[3]),1),a=s,l=i,c="prescale1",h,u;for(;r>2&&a>1||o>2&&l>1;){let d=a,p=l;r>2&&a>1&&(d=a>=16384?Math.floor(a/2)-1||1:Math.ceil(a/2),r/=a/d),o>2&&l>1&&(p=l>=16384?Math.floor(l/2)-1||1:Math.ceil(l)/2,o/=l/p),h=this.cachedCanvases.getCanvas(c,d,p),u=h.context,u.clearRect(0,0,d,p),u.drawImage(e,0,0,a,l,0,0,d,p),e=h.canvas,a=d,l=p,c=c==="prescale1"?"prescale2":"prescale1"}return{img:e,paintWidth:a,paintHeight:l}}_createMaskCanvas(e){const t=this.ctx,{width:s,height:i}=e,r=this.current.fillColor,o=this.current.patternFill,a=Bt(t);let l,c,h,u;if((e.bitmap||e.data)&&e.count>1){const I=e.bitmap||e.data.buffer;c=JSON.stringify(o?a:[a.slice(0,4),r]),l=this._cachedBitmapsMap.get(I),l||(l=new Map,this._cachedBitmapsMap.set(I,l));const j=l.get(c);if(j&&!o){const q=Math.round(Math.min(a[0],a[2])+a[4]),L=Math.round(Math.min(a[1],a[3])+a[5]);return{canvas:j,offsetX:q,offsetY:L}}h=j}h||(u=this.cachedCanvases.getCanvas("maskCanvas",s,i),sE(u.context,e));let d=Se.transform(a,[1/s,0,0,-1/i,0,0]);d=Se.transform(d,[1,0,0,1,0,-i]);const[p,m,y,v]=Se.getAxialAlignedBoundingBox([0,0,s,i],d),g=Math.round(y-p)||1,b=Math.round(v-m)||1,_=this.cachedCanvases.getCanvas("fillCanvas",g,b),x=_.context,A=p,C=m;x.translate(-A,-C),x.transform(...d),h||(h=this._scaleImage(u.canvas,Br(x)),h=h.img,l&&o&&l.set(c,h)),x.imageSmoothingEnabled=iE(Bt(x),e.interpolate),Om(x,h,0,0,h.width,h.height,0,0,s,i),x.globalCompositeOperation="source-in";const $=Se.transform(Br(x),[1,0,0,1,-A,-C]);return x.fillStyle=o?r.getPattern(t,this,$,vs.FILL):r,x.fillRect(0,0,s,i),l&&!o&&(this.cachedCanvases.delete("fillCanvas"),l.set(c,_.canvas)),{canvas:_.canvas,offsetX:Math.round(A),offsetY:Math.round(C)}}setLineWidth(e){e!==this.current.lineWidth&&(this._cachedScaleForStroking[0]=-1),this.current.lineWidth=e,this.ctx.lineWidth=e}setLineCap(e){this.ctx.lineCap=P8[e]}setLineJoin(e){this.ctx.lineJoin=R8[e]}setMiterLimit(e){this.ctx.miterLimit=e}setDash(e,t){const s=this.ctx;s.setLineDash!==void 0&&(s.setLineDash(e),s.lineDashOffset=t)}setRenderingIntent(e){}setFlatness(e){}setGState(e){for(const[t,s]of e)switch(t){case"LW":this.setLineWidth(s);break;case"LC":this.setLineCap(s);break;case"LJ":this.setLineJoin(s);break;case"ML":this.setMiterLimit(s);break;case"D":this.setDash(s[0],s[1]);break;case"RI":this.setRenderingIntent(s);break;case"FL":this.setFlatness(s);break;case"Font":this.setFont(s[0],s[1]);break;case"CA":this.current.strokeAlpha=s;break;case"ca":this.current.fillAlpha=s,this.ctx.globalAlpha=s;break;case"BM":this.ctx.globalCompositeOperation=s;break;case"SMask":this.current.activeSMask=s?this.tempSMask:null,this.tempSMask=null,this.checkSMaskState();break;case"TR":this.ctx.filter=this.current.transferMaps=this.filterFactory.addFilter(s);break}}get inSMaskMode(){return!!this.suspendedCtx}checkSMaskState(){const 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,t=this.ctx.canvas.height,s="smaskGroupAt"+this.groupLevel,i=this.cachedCanvases.getCanvas(s,e,t);this.suspendedCtx=this.ctx,this.ctx=i.context;const r=this.ctx;r.setTransform(...Bt(this.suspendedCtx)),id(this.suspendedCtx,r),C8(r,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(),id(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 t=this.current.activeSMask,s=this.suspendedCtx;this.composeSMask(s,t,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()}composeSMask(e,t,s,i){const r=i[0],o=i[1],a=i[2]-r,l=i[3]-o;a===0||l===0||(this.genericComposeSMask(t.context,s,a,l,t.subtype,t.backdrop,t.transferMap,r,o,t.offsetX,t.offsetY),e.save(),e.globalAlpha=1,e.globalCompositeOperation="source-over",e.setTransform(1,0,0,1,0,0),e.drawImage(s.canvas,0,0),e.restore())}genericComposeSMask(e,t,s,i,r,o,a,l,c,h,u){let d=e.canvas,p=l-h,m=c-u;if(o){const v=Se.makeHexColor(...o);if(p<0||m<0||p+s>d.width||m+i>d.height){const g=this.cachedCanvases.getCanvas("maskExtension",s,i),b=g.context;b.drawImage(d,-p,-m),b.globalCompositeOperation="destination-atop",b.fillStyle=v,b.fillRect(0,0,s,i),b.globalCompositeOperation="source-over",d=g.canvas,p=m=0}else{e.save(),e.globalAlpha=1,e.setTransform(1,0,0,1,0,0);const g=new Path2D;g.rect(p,m,s,i),e.clip(g),e.globalCompositeOperation="destination-atop",e.fillStyle=v,e.fillRect(p,m,s,i),e.restore()}}t.save(),t.globalAlpha=1,t.setTransform(1,0,0,1,0,0),r==="Alpha"&&a?t.filter=this.filterFactory.addAlphaFilter(a):r==="Luminosity"&&(t.filter=this.filterFactory.addLuminosityFilter(a));const y=new Path2D;y.rect(l,c,s,i),t.clip(y),t.globalCompositeOperation="destination-in",t.drawImage(d,p,m,s,i,l,c,s,i),t.restore()}save(){this.inSMaskMode?(id(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(),id(this.suspendedCtx,this.ctx)):this.ctx.restore(),this.checkSMaskState(),this.pendingClip=null,this._cachedScaleForStroking[0]=-1,this._cachedGetSinglePixelWidth=null)}transform(e,t,s,i,r,o){this.ctx.transform(e,t,s,i,r,o),this._cachedScaleForStroking[0]=-1,this._cachedGetSinglePixelWidth=null}constructPath(e,t,s){const i=this.ctx,r=this.current;let o=r.x,a=r.y,l,c;const h=Bt(i),u=h[0]===0&&h[3]===0||h[1]===0&&h[2]===0,d=u?s.slice(0):null;for(let p=0,m=0,y=e.length;pJk&&(c=Jk),this.current.fontSizeScale=t/c,this.ctx.font=`${l} ${a} ${c}px ${o}`}setTextRenderingMode(e){this.current.textRenderingMode=e}setTextRise(e){this.current.textRise=e}moveText(e,t){this.current.x=this.current.lineX+=e,this.current.y=this.current.lineY+=t}setLeadingMoveText(e,t){this.setLeading(-t),this.moveText(e,t)}setTextMatrix(e,t,s,i,r,o){this.current.textMatrix=[e,t,s,i,r,o],this.current.textMatrixScale=Math.hypot(e,t),this.current.x=this.current.lineX=0,this.current.y=this.current.lineY=0}nextLine(){this.moveText(0,this.current.leading)}paintChar(e,t,s,i){const r=this.ctx,o=this.current,a=o.font,l=o.textRenderingMode,c=o.fontSize/o.fontSizeScale,h=l&es.FILL_STROKE_MASK,u=!!(l&es.ADD_TO_PATH_FLAG),d=o.patternFill&&!a.missingFile;let p;(a.disableFontFace||u||d)&&(p=a.getPathGenerator(this.commonObjs,e)),a.disableFontFace||d?(r.save(),r.translate(t,s),r.beginPath(),p(r,c),i&&r.setTransform(...i),(h===es.FILL||h===es.FILL_STROKE)&&r.fill(),(h===es.STROKE||h===es.FILL_STROKE)&&r.stroke(),r.restore()):((h===es.FILL||h===es.FILL_STROKE)&&r.fillText(e,t,s),(h===es.STROKE||h===es.FILL_STROKE)&&r.strokeText(e,t,s)),u&&(this.pendingTextPaths||(this.pendingTextPaths=[])).push({transform:Bt(r),x:t,y:s,fontSize:c,addToPath:p})}get isFontSubpixelAAEnabled(){const{context:e}=this.cachedCanvases.getCanvas("isFontSubpixelAAEnabled",10,10);e.scale(1.5,1),e.fillText("I",0,10);const t=e.getImageData(0,0,10,10).data;let s=!1;for(let i=3;i0&&t[i]<255){s=!0;break}return Xe(this,"isFontSubpixelAAEnabled",s)}showText(e){const t=this.current,s=t.font;if(s.isType3Font)return this.showType3Text(e);const i=t.fontSize;if(i===0)return;const r=this.ctx,o=t.fontSizeScale,a=t.charSpacing,l=t.wordSpacing,c=t.fontDirection,h=t.textHScale*c,u=e.length,d=s.vertical,p=d?1:-1,m=s.defaultVMetrics,y=i*t.fontMatrix[0],v=t.textRenderingMode===es.FILL&&!s.disableFontFace&&!t.patternFill;r.save(),r.transform(...t.textMatrix),r.translate(t.x,t.y+t.textRise),c>0?r.scale(h,-1):r.scale(h,1);let g;if(t.patternFill){r.save();const C=t.fillColor.getPattern(r,this,Br(r),vs.FILL);g=Bt(r),r.restore(),r.fillStyle=C}let b=t.lineWidth;const _=t.textMatrixScale;if(_===0||b===0){const C=t.textRenderingMode&es.FILL_STROKE_MASK;(C===es.STROKE||C===es.FILL_STROKE)&&(b=this.getSinglePixelWidth())}else b/=_;if(o!==1&&(r.scale(o,o),b/=o),r.lineWidth=b,s.isInvalidPDFjsFont){const C=[];let $=0;for(const I of e)C.push(I.unicode),$+=I.width;r.fillText(C.join(""),0,0),t.x+=$*y*h,r.restore(),this.compose();return}let x=0,A;for(A=0;A0){const X=r.measureText(j).width*1e3/i*o;if(Hnew pA(o,this.commonObjs,this.objs,this.canvasFactory,this.filterFactory,{optionalContentConfig:this.optionalContentConfig,markedContentStack:this.markedContentStack})};t=new yw(e,s,this.ctx,r,i)}else t=this._getPattern(e[1],e[2]);return t}setStrokeColorN(){this.current.strokeColor=this.getColorN_Pattern(arguments)}setFillColorN(){this.current.fillColor=this.getColorN_Pattern(arguments),this.current.patternFill=!0}setStrokeRGBColor(e,t,s){this.ctx.strokeStyle=this.current.strokeColor=Se.makeHexColor(e,t,s)}setStrokeTransparent(){this.ctx.strokeStyle=this.current.strokeColor="transparent"}setFillRGBColor(e,t,s){this.ctx.fillStyle=this.current.fillColor=Se.makeHexColor(e,t,s),this.current.patternFill=!1}setFillTransparent(){this.ctx.fillStyle=this.current.fillColor="transparent",this.current.patternFill=!1}_getPattern(e,t=null){let s;return this.cachedPatterns.has(e)?s=this.cachedPatterns.get(e):(s=A8(this.getObject(e)),this.cachedPatterns.set(e,s)),t&&(s.matrix=t),s}shadingFill(e){if(!this.contentVisible)return;const t=this.ctx;this.save();const s=this._getPattern(e);t.fillStyle=s.getPattern(t,this,Br(t),vs.SHADING);const i=Br(t);if(i){const{width:r,height:o}=t.canvas,[a,l,c,h]=Se.getAxialAlignedBoundingBox([0,0,r,o],i);this.ctx.fillRect(a,l,c-a,h-l)}else this.ctx.fillRect(-1e10,-1e10,2e10,2e10);this.compose(this.current.getClippedPathBoundingBox()),this.restore()}beginInlineImage(){Tt("Should not call beginInlineImage")}beginImageData(){Tt("Should not call beginImageData")}paintFormXObjectBegin(e,t){if(this.contentVisible&&(this.save(),this.baseTransformStack.push(this.baseTransform),e&&this.transform(...e),this.baseTransform=Bt(this.ctx),t)){const s=t[2]-t[0],i=t[3]-t[1];this.ctx.rect(t[0],t[1],s,i),this.current.updateRectMinMax(Bt(this.ctx),t),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 t=this.ctx;e.isolated||N0("TODO: Support non-isolated groups."),e.knockout&&qe("Knockout groups not supported.");const s=Bt(t);if(e.matrix&&t.transform(...e.matrix),!e.bbox)throw new Error("Bounding box is required.");let i=Se.getAxialAlignedBoundingBox(e.bbox,Bt(t));const r=[0,0,t.canvas.width,t.canvas.height];i=Se.intersect(i,r)||[0,0,0,0];const o=Math.floor(i[0]),a=Math.floor(i[1]),l=Math.max(Math.ceil(i[2])-o,1),c=Math.max(Math.ceil(i[3])-a,1);this.current.startNewPathAndClipBox([0,0,l,c]);let h="groupAt"+this.groupLevel;e.smask&&(h+="_smask_"+this.smaskCounter++%2);const u=this.cachedCanvases.getCanvas(h,l,c),d=u.context;d.translate(-o,-a),d.transform(...s),e.smask?this.smaskStack.push({canvas:u.canvas,context:d,offsetX:o,offsetY:a,subtype:e.smask.subtype,backdrop:e.smask.backdrop,transferMap:e.smask.transferMap||null,startTransformInverse:null}):(t.setTransform(1,0,0,1,0,0),t.translate(o,a),t.save()),id(t,d),this.ctx=d,this.setGState([["BM","source-over"],["ca",1],["CA",1]]),this.groupStack.push(t),this.groupLevel++}endGroup(e){if(!this.contentVisible)return;this.groupLevel--;const t=this.ctx,s=this.groupStack.pop();if(this.ctx=s,this.ctx.imageSmoothingEnabled=!1,e.smask)this.tempSMask=this.smaskStack.pop(),this.restore();else{this.ctx.restore();const i=Bt(this.ctx);this.restore(),this.ctx.save(),this.ctx.setTransform(...i);const r=Se.getAxialAlignedBoundingBox([0,0,t.canvas.width,t.canvas.height],i);this.ctx.drawImage(t.canvas,0,0),this.ctx.restore(),this.compose(r)}}beginAnnotation(e,t,s,i,r){if(P(this,La,vw).call(this),Nm(this.ctx),this.ctx.save(),this.save(),this.baseTransform&&this.ctx.setTransform(...this.baseTransform),t){const o=t[2]-t[0],a=t[3]-t[1];if(r&&this.annotationCanvasMap){s=s.slice(),s[4]-=t[0],s[5]-=t[1],t=t.slice(),t[0]=t[1]=0,t[2]=o,t[3]=a;const[l,c]=Se.singularValueDecompose2dScale(Bt(this.ctx)),{viewportScale:h}=this,u=Math.ceil(o*this.outputScaleX*h),d=Math.ceil(a*this.outputScaleY*h);this.annotationCanvas=this.canvasFactory.create(u,d);const{canvas:p,context:m}=this.annotationCanvas;this.annotationCanvasMap.set(e,p),this.annotationCanvas.savedCtx=this.ctx,this.ctx=m,this.ctx.save(),this.ctx.setTransform(l,0,0,-c,0,a*c),Nm(this.ctx)}else Nm(this.ctx),this.endPath(),this.ctx.rect(t[0],t[1],o,a),this.ctx.clip(),this.ctx.beginPath()}this.current=new tE(this.ctx.canvas.width,this.ctx.canvas.height),this.transform(...s),this.transform(...i)}endAnnotation(){this.annotationCanvas&&(this.ctx.restore(),P(this,La,bw).call(this),this.ctx=this.annotationCanvas.savedCtx,delete this.annotationCanvas.savedCtx,delete this.annotationCanvas)}paintImageMaskXObject(e){if(!this.contentVisible)return;const t=e.count;e=this.getObject(e.data,e),e.count=t;const s=this.ctx,i=this.processingType3;if(i&&(i.compiled===void 0&&(i.compiled=T8(e)),i.compiled)){i.compiled(s);return}const r=this._createMaskCanvas(e),o=r.canvas;s.save(),s.setTransform(1,0,0,1,0,0),s.drawImage(o,r.offsetX,r.offsetY),s.restore(),this.compose()}paintImageMaskXObjectRepeat(e,t,s=0,i=0,r,o){if(!this.contentVisible)return;e=this.getObject(e.data,e);const a=this.ctx;a.save();const l=Bt(a);a.transform(t,s,i,r,0,0);const c=this._createMaskCanvas(e);a.setTransform(1,0,0,1,c.offsetX-l[4],c.offsetY-l[5]);for(let h=0,u=o.length;hu?h/u:1,a=c>u?c/u:1}}this._cachedScaleForStroking[0]=o,this._cachedScaleForStroking[1]=a}return this._cachedScaleForStroking}rescaleAndStroke(e){const{ctx:t}=this,{lineWidth:s}=this.current,[i,r]=this.getScaleForStroking();if(t.lineWidth=s||1,i===1&&r===1){t.stroke();return}const o=t.getLineDash();if(e&&t.save(),t.scale(i,r),o.length>0){const a=Math.max(i,r);t.setLineDash(o.map(l=>l/a)),t.lineDashOffset/=a}t.stroke(),e&&t.restore()}isContentVisible(){for(let e=this.markedContentStack.length-1;e>=0;e--)if(!this.markedContentStack[e].visible)return!1;return!0}};La=new WeakSet,vw=function(){for(;this.stateStack.length||this.inSMaskMode;)this.restore();this.current.activeSMask=null,this.ctx.restore(),this.transparentCanvas&&(this.ctx=this.compositeCtx,this.ctx.save(),this.ctx.setTransform(1,0,0,1,0,0),this.ctx.drawImage(this.transparentCanvas,0,0),this.ctx.restore(),this.transparentCanvas=null)},bw=function(){if(this.pageColors){const e=this.filterFactory.addHCMFilter(this.pageColors.foreground,this.pageColors.background);if(e!=="none"){const t=this.ctx.filter;this.ctx.filter=e,this.ctx.drawImage(this.ctx.canvas,0,0),this.ctx.filter=t}}};let uh=pA;for(const n in Mi)uh.prototype[n]!==void 0&&(uh.prototype[Mi[n]]=uh.prototype[n]);var Bf,Uf;class yo{static get workerPort(){return f(this,Bf)}static set workerPort(e){if(!(typeof Worker<"u"&&e instanceof Worker)&&e!==null)throw new Error("Invalid `workerPort` type.");T(this,Bf,e)}static get workerSrc(){return f(this,Uf)}static set workerSrc(e){if(typeof e!="string")throw new Error("Invalid `workerSrc` type.");T(this,Uf,e)}}Bf=new WeakMap,Uf=new WeakMap,M(yo,Bf,null),M(yo,Uf,"");const Lm={DATA:1,ERROR:2},sn={CANCEL:1,CANCEL_COMPLETE:2,CLOSE:3,ENQUEUE:4,ERROR:5,PULL:6,PULL_COMPLETE:7,START_COMPLETE:8};function Us(n){switch(n instanceof Error||typeof n=="object"&&n!==null||Tt('wrapReason: Expected "reason" to be a (possibly cloned) Error.'),n.name){case"AbortException":return new $c(n.message);case"MissingPDFException":return new Cc(n.message);case"PasswordException":return new qb(n.message,n.code);case"UnexpectedResponseException":return new L0(n.message,n.status);case"UnknownErrorException":return new Vb(n.message,n.details);default:return new Vb(n.message,n.toString())}}var Oh,_i,sM,iM,rM,kg;class xd{constructor(e,t,s){M(this,_i);M(this,Oh,new AbortController);this.sourceName=e,this.targetName=t,this.comObj=s,this.callbackId=1,this.streamId=1,this.streamSinks=Object.create(null),this.streamControllers=Object.create(null),this.callbackCapabilities=Object.create(null),this.actionHandler=Object.create(null),s.addEventListener("message",P(this,_i,sM).bind(this),{signal:f(this,Oh).signal})}on(e,t){const s=this.actionHandler;if(s[e])throw new Error(`There is already an actionName called "${e}"`);s[e]=t}send(e,t,s){this.comObj.postMessage({sourceName:this.sourceName,targetName:this.targetName,action:e,data:t},s)}sendWithPromise(e,t,s){const i=this.callbackId++,r=Promise.withResolvers();this.callbackCapabilities[i]=r;try{this.comObj.postMessage({sourceName:this.sourceName,targetName:this.targetName,action:e,callbackId:i,data:t},s)}catch(o){r.reject(o)}return r.promise}sendWithStream(e,t,s,i){const r=this.streamId++,o=this.sourceName,a=this.targetName,l=this.comObj;return new ReadableStream({start:c=>{const h=Promise.withResolvers();return this.streamControllers[r]={controller:c,startCall:h,pullCall:null,cancelCall:null,isClosed:!1},l.postMessage({sourceName:o,targetName:a,action:e,streamId:r,data:t,desiredSize:c.desiredSize},i),h.promise},pull:c=>{const h=Promise.withResolvers();return this.streamControllers[r].pullCall=h,l.postMessage({sourceName:o,targetName:a,stream:sn.PULL,streamId:r,desiredSize:c.desiredSize}),h.promise},cancel:c=>{yn(c instanceof Error,"cancel must have a valid reason");const h=Promise.withResolvers();return this.streamControllers[r].cancelCall=h,this.streamControllers[r].isClosed=!0,l.postMessage({sourceName:o,targetName:a,stream:sn.CANCEL,streamId:r,reason:Us(c)}),h.promise}},s)}destroy(){var e;(e=f(this,Oh))==null||e.abort(),T(this,Oh,null)}}Oh=new WeakMap,_i=new WeakSet,sM=function({data:e}){if(e.targetName!==this.sourceName)return;if(e.stream){P(this,_i,rM).call(this,e);return}if(e.callback){const s=e.callbackId,i=this.callbackCapabilities[s];if(!i)throw new Error(`Cannot resolve callback ${s}`);if(delete this.callbackCapabilities[s],e.callback===Lm.DATA)i.resolve(e.data);else if(e.callback===Lm.ERROR)i.reject(Us(e.reason));else throw new Error("Unexpected callback case");return}const t=this.actionHandler[e.action];if(!t)throw new Error(`Unknown action from worker: ${e.action}`);if(e.callbackId){const s=this.sourceName,i=e.sourceName,r=this.comObj;new Promise(function(o){o(t(e.data))}).then(function(o){r.postMessage({sourceName:s,targetName:i,callback:Lm.DATA,callbackId:e.callbackId,data:o})},function(o){r.postMessage({sourceName:s,targetName:i,callback:Lm.ERROR,callbackId:e.callbackId,reason:Us(o)})});return}if(e.streamId){P(this,_i,iM).call(this,e);return}t(e.data)},iM=function(e){const t=e.streamId,s=this.sourceName,i=e.sourceName,r=this.comObj,o=this,a=this.actionHandler[e.action],l={enqueue(c,h=1,u){if(this.isCancelled)return;const d=this.desiredSize;this.desiredSize-=h,d>0&&this.desiredSize<=0&&(this.sinkCapability=Promise.withResolvers(),this.ready=this.sinkCapability.promise),r.postMessage({sourceName:s,targetName:i,stream:sn.ENQUEUE,streamId:t,chunk:c},u)},close(){this.isCancelled||(this.isCancelled=!0,r.postMessage({sourceName:s,targetName:i,stream:sn.CLOSE,streamId:t}),delete o.streamSinks[t])},error(c){yn(c instanceof Error,"error must have a valid reason"),!this.isCancelled&&(this.isCancelled=!0,r.postMessage({sourceName:s,targetName:i,stream:sn.ERROR,streamId:t,reason:Us(c)}))},sinkCapability:Promise.withResolvers(),onPull:null,onCancel:null,isCancelled:!1,desiredSize:e.desiredSize,ready:null};l.sinkCapability.resolve(),l.ready=l.sinkCapability.promise,this.streamSinks[t]=l,new Promise(function(c){c(a(e.data,l))}).then(function(){r.postMessage({sourceName:s,targetName:i,stream:sn.START_COMPLETE,streamId:t,success:!0})},function(c){r.postMessage({sourceName:s,targetName:i,stream:sn.START_COMPLETE,streamId:t,reason:Us(c)})})},rM=function(e){const t=e.streamId,s=this.sourceName,i=e.sourceName,r=this.comObj,o=this.streamControllers[t],a=this.streamSinks[t];switch(e.stream){case sn.START_COMPLETE:e.success?o.startCall.resolve():o.startCall.reject(Us(e.reason));break;case sn.PULL_COMPLETE:e.success?o.pullCall.resolve():o.pullCall.reject(Us(e.reason));break;case sn.PULL:if(!a){r.postMessage({sourceName:s,targetName:i,stream:sn.PULL_COMPLETE,streamId:t,success:!0});break}a.desiredSize<=0&&e.desiredSize>0&&a.sinkCapability.resolve(),a.desiredSize=e.desiredSize,new Promise(function(l){var c;l((c=a.onPull)==null?void 0:c.call(a))}).then(function(){r.postMessage({sourceName:s,targetName:i,stream:sn.PULL_COMPLETE,streamId:t,success:!0})},function(l){r.postMessage({sourceName:s,targetName:i,stream:sn.PULL_COMPLETE,streamId:t,reason:Us(l)})});break;case sn.ENQUEUE:if(yn(o,"enqueue should have stream controller"),o.isClosed)break;o.controller.enqueue(e.chunk);break;case sn.CLOSE:if(yn(o,"close should have stream controller"),o.isClosed)break;o.isClosed=!0,o.controller.close(),P(this,_i,kg).call(this,o,t);break;case sn.ERROR:yn(o,"error should have stream controller"),o.controller.error(Us(e.reason)),P(this,_i,kg).call(this,o,t);break;case sn.CANCEL_COMPLETE:e.success?o.cancelCall.resolve():o.cancelCall.reject(Us(e.reason)),P(this,_i,kg).call(this,o,t);break;case sn.CANCEL:if(!a)break;new Promise(function(l){var c;l((c=a.onCancel)==null?void 0:c.call(a,Us(e.reason)))}).then(function(){r.postMessage({sourceName:s,targetName:i,stream:sn.CANCEL_COMPLETE,streamId:t,success:!0})},function(l){r.postMessage({sourceName:s,targetName:i,stream:sn.CANCEL_COMPLETE,streamId:t,reason:Us(l)})}),a.sinkCapability.reject(Us(e.reason)),a.isCancelled=!0,delete this.streamSinks[t];break;default:throw new Error("Unexpected stream case")}},kg=async function(e,t){var s,i,r;await Promise.allSettled([(s=e.startCall)==null?void 0:s.promise,(i=e.pullCall)==null?void 0:i.promise,(r=e.cancelCall)==null?void 0:r.promise]),delete this.streamControllers[t]};var Tl,qf;class I8{constructor({parsedData:e,rawData:t}){M(this,Tl);M(this,qf);T(this,Tl,e),T(this,qf,t)}getRaw(){return f(this,qf)}get(e){return f(this,Tl).get(e)??null}getAll(){return xx(f(this,Tl))}has(e){return f(this,Tl).has(e)}}Tl=new WeakMap,qf=new WeakMap;const Gc=Symbol("INTERNAL");var Vf,Wf,Gf,Nh;class O8{constructor(e,{name:t,intent:s,usage:i,rbGroups:r}){M(this,Vf,!1);M(this,Wf,!1);M(this,Gf,!1);M(this,Nh,!0);T(this,Vf,!!(e&Qs.DISPLAY)),T(this,Wf,!!(e&Qs.PRINT)),this.name=t,this.intent=s,this.usage=i,this.rbGroups=r}get visible(){if(f(this,Gf))return f(this,Nh);if(!f(this,Nh))return!1;const{print:e,view:t}=this.usage;return f(this,Vf)?(t==null?void 0:t.viewState)!=="OFF":f(this,Wf)?(e==null?void 0:e.printState)!=="OFF":!0}_setVisible(e,t,s=!1){e!==Gc&&Tt("Internal method `_setVisible` called."),T(this,Gf,s),T(this,Nh,t)}}Vf=new WeakMap,Wf=new WeakMap,Gf=new WeakMap,Nh=new WeakMap;var na,dt,Lh,Dh,Kf,ww;class N8{constructor(e,t=Qs.DISPLAY){M(this,Kf);M(this,na,null);M(this,dt,new Map);M(this,Lh,null);M(this,Dh,null);if(this.renderingIntent=t,this.name=null,this.creator=null,e!==null){this.name=e.name,this.creator=e.creator,T(this,Dh,e.order);for(const s of e.groups)f(this,dt).set(s.id,new O8(t,s));if(e.baseState==="OFF")for(const s of f(this,dt).values())s._setVisible(Gc,!1);for(const s of e.on)f(this,dt).get(s)._setVisible(Gc,!0);for(const s of e.off)f(this,dt).get(s)._setVisible(Gc,!1);T(this,Lh,this.getHash())}}isVisible(e){if(f(this,dt).size===0)return!0;if(!e)return N0("Optional content group not defined."),!0;if(e.type==="OCG")return f(this,dt).has(e.id)?f(this,dt).get(e.id).visible:(qe(`Optional content group not found: ${e.id}`),!0);if(e.type==="OCMD"){if(e.expression)return P(this,Kf,ww).call(this,e.expression);if(!e.policy||e.policy==="AnyOn"){for(const t of e.ids){if(!f(this,dt).has(t))return qe(`Optional content group not found: ${t}`),!0;if(f(this,dt).get(t).visible)return!0}return!1}else if(e.policy==="AllOn"){for(const t of e.ids){if(!f(this,dt).has(t))return qe(`Optional content group not found: ${t}`),!0;if(!f(this,dt).get(t).visible)return!1}return!0}else if(e.policy==="AnyOff"){for(const t of e.ids){if(!f(this,dt).has(t))return qe(`Optional content group not found: ${t}`),!0;if(!f(this,dt).get(t).visible)return!0}return!1}else if(e.policy==="AllOff"){for(const t of e.ids){if(!f(this,dt).has(t))return qe(`Optional content group not found: ${t}`),!0;if(f(this,dt).get(t).visible)return!1}return!0}return qe(`Unknown optional content policy ${e.policy}.`),!0}return qe(`Unknown group type ${e.type}.`),!0}setVisibility(e,t=!0,s=!0){var r;const i=f(this,dt).get(e);if(!i){qe(`Optional content group not found: ${e}`);return}if(s&&t&&i.rbGroups.length)for(const o of i.rbGroups)for(const a of o)a!==e&&((r=f(this,dt).get(a))==null||r._setVisible(Gc,!1,!0));i._setVisible(Gc,!!t,!0),T(this,na,null)}setOCGState({state:e,preserveRB:t}){let s;for(const i of e){switch(i){case"ON":case"OFF":case"Toggle":s=i;continue}const r=f(this,dt).get(i);if(r)switch(s){case"ON":this.setVisibility(i,!0,t);break;case"OFF":this.setVisibility(i,!1,t);break;case"Toggle":this.setVisibility(i,!r.visible,t);break}}T(this,na,null)}get hasInitialVisibility(){return f(this,Lh)===null||this.getHash()===f(this,Lh)}getOrder(){return f(this,dt).size?f(this,Dh)?f(this,Dh).slice():[...f(this,dt).keys()]:null}getGroups(){return f(this,dt).size>0?xx(f(this,dt)):null}getGroup(e){return f(this,dt).get(e)||null}getHash(){if(f(this,na)!==null)return f(this,na);const e=new WR;for(const[t,s]of f(this,dt))e.update(`${t}:${s.visible}`);return T(this,na,e.hexdigest())}}na=new WeakMap,dt=new WeakMap,Lh=new WeakMap,Dh=new WeakMap,Kf=new WeakSet,ww=function(e){const t=e.length;if(t<2)return!0;const s=e[0];for(let i=1;i0){const l=r instanceof Uint8Array&&r.byteLength===r.buffer.byteLength?r.buffer:new Uint8Array(r).buffer;this._queuedChunks.push(l)}this._pdfDataRangeTransport=e,this._isStreamingSupported=!s,this._isRangeSupported=!t,this._contentLength=i,this._fullRequestReader=null,this._rangeReaders=[],e.addRangeListener((l,c)=>{this._onReceiveData({begin:l,chunk:c})}),e.addProgressListener((l,c)=>{this._onProgress({loaded:l,total:c})}),e.addProgressiveReadListener(l=>{this._onReceiveData({chunk:l})}),e.addProgressiveDoneListener(()=>{this._onProgressiveDone()}),e.transportReady()}_onReceiveData({begin:e,chunk:t}){const s=t instanceof Uint8Array&&t.byteLength===t.buffer.byteLength?t.buffer:new Uint8Array(t).buffer;if(e===void 0)this._fullRequestReader?this._fullRequestReader._enqueue(s):this._queuedChunks.push(s);else{const i=this._rangeReaders.some(function(r){return r._begin!==e?!1:(r._enqueue(s),!0)});yn(i,"_onReceiveData - no `PDFDataTransportStreamRangeReader` instance found.")}}get _progressiveDataLength(){var e;return((e=this._fullRequestReader)==null?void 0:e._loaded)??0}_onProgress(e){var t,s,i,r;e.total===void 0?(s=(t=this._rangeReaders[0])==null?void 0:t.onProgress)==null||s.call(t,{loaded:e.loaded}):(r=(i=this._fullRequestReader)==null?void 0:i.onProgress)==null||r.call(i,{loaded:e.loaded,total:e.total})}_onProgressiveDone(){var e;(e=this._fullRequestReader)==null||e.progressiveDone(),this._progressiveDone=!0}_removeRangeReader(e){const t=this._rangeReaders.indexOf(e);t>=0&&this._rangeReaders.splice(t,1)}getFullReader(){yn(!this._fullRequestReader,"PDFDataTransportStream.getFullReader can only be called once.");const e=this._queuedChunks;return this._queuedChunks=null,new D8(this,e,this._progressiveDone,this._contentDispositionFilename)}getRangeReader(e,t){if(t<=this._progressiveDataLength)return null;const s=new j8(this,e,t);return this._pdfDataRangeTransport.requestDataRange(e,t),this._rangeReaders.push(s),s}cancelAllRequests(e){var t;(t=this._fullRequestReader)==null||t.cancel(e);for(const s of this._rangeReaders.slice(0))s.cancel(e);this._pdfDataRangeTransport.abort()}}class D8{constructor(e,t,s=!1,i=null){this._stream=e,this._done=s||!1,this._filename=Ex(i)?i:null,this._queuedChunks=t||[],this._loaded=0;for(const r of this._queuedChunks)this._loaded+=r.byteLength;this._requests=[],this._headersReady=Promise.resolve(),e._fullRequestReader=this,this.onProgress=null}_enqueue(e){this._done||(this._requests.length>0?this._requests.shift().resolve({value:e,done:!1}):this._queuedChunks.push(e),this._loaded+=e.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 e=Promise.withResolvers();return this._requests.push(e),e.promise}cancel(e){this._done=!0;for(const t of this._requests)t.resolve({value:void 0,done:!0});this._requests.length=0}progressiveDone(){this._done||(this._done=!0)}}class j8{constructor(e,t,s){this._stream=e,this._begin=t,this._end=s,this._queuedChunk=null,this._requests=[],this._done=!1,this.onProgress=null}_enqueue(e){if(!this._done){if(this._requests.length===0)this._queuedChunk=e;else{this._requests.shift().resolve({value:e,done:!1});for(const s of this._requests)s.resolve({value:void 0,done:!0});this._requests.length=0}this._done=!0,this._stream._removeRangeReader(this)}}get isStreamingSupported(){return!1}async read(){if(this._queuedChunk){const t=this._queuedChunk;return this._queuedChunk=null,{value:t,done:!1}}if(this._done)return{value:void 0,done:!0};const e=Promise.withResolvers();return this._requests.push(e),e.promise}cancel(e){this._done=!0;for(const t of this._requests)t.resolve({value:void 0,done:!0});this._requests.length=0,this._stream._removeRangeReader(this)}}function F8(n){let e=!0,t=s("filename\\*","i").exec(n);if(t){t=t[1];let h=a(t);return h=unescape(h),h=l(h),h=c(h),r(h)}if(t=o(n),t){const h=c(t);return r(h)}if(t=s("filename","i").exec(n),t){t=t[1];let h=a(t);return h=c(h),r(h)}function s(h,u){return new RegExp("(?:^|;)\\s*"+h+'\\s*=\\s*([^";\\s][^;\\s]*|"(?:[^"\\\\]|\\\\"?)+"?)',u)}function i(h,u){if(h){if(!/^[\x00-\xFF]+$/.test(u))return u;try{const d=new TextDecoder(h,{fatal:!0}),p=D0(u);u=d.decode(p),e=!1}catch{}}return u}function r(h){return e&&/[\x80-\xff]/.test(h)&&(h=i("utf-8",h),e&&(h=i("iso-8859-1",h))),h}function o(h){const u=[];let d;const p=s("filename\\*((?!0\\d)\\d+)(\\*?)","ig");for(;(d=p.exec(h))!==null;){let[,y,v,g]=d;if(y=parseInt(y,10),y in u){if(y===0)break;continue}u[y]=[v,g]}const m=[];for(let y=0;y{if(!oM(r.status))throw z0(r.status,i);this._reader=r.body.getReader(),this._headersCapability.resolve();const o=r.headers,{allowRangeRequests:a,suggestedLength:l}=Mx({responseHeaders:o,isHttp:e.isHttp,rangeChunkSize:this._rangeChunkSize,disableRange:this._disableRange});this._isRangeSupported=a,this._contentLength=l||this._contentLength,this._filename=Ix(o),!this._isStreamingSupported&&this._isRangeSupported&&this.cancel(new $c("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(){var s;await this._headersCapability.promise;const{value:e,done:t}=await this._reader.read();return t?{value:e,done:t}:(this._loaded+=e.byteLength,(s=this.onProgress)==null||s.call(this,{loaded:this._loaded,total:this._contentLength}),{value:lM(e),done:!1})}cancel(e){var t;(t=this._reader)==null||t.cancel(e),this._abortController.abort()}}class H8{constructor(e,t,s){this._stream=e,this._reader=null,this._loaded=0;const i=e.source;this._withCredentials=i.withCredentials||!1,this._readCapability=Promise.withResolvers(),this._isStreamingSupported=!i.disableStream,this._abortController=new AbortController;const r=new Headers(e.headers);r.append("Range",`bytes=${t}-${s-1}`);const o=i.url;fetch(o,aM(r,this._withCredentials,this._abortController)).then(a=>{if(!oM(a.status))throw z0(a.status,o);this._readCapability.resolve(),this._reader=a.body.getReader()}).catch(this._readCapability.reject),this.onProgress=null}get isStreamingSupported(){return this._isStreamingSupported}async read(){var s;await this._readCapability.promise;const{value:e,done:t}=await this._reader.read();return t?{value:e,done:t}:(this._loaded+=e.byteLength,(s=this.onProgress)==null||s.call(this,{loaded:this._loaded}),{value:lM(e),done:!1})}cancel(e){var t;(t=this._reader)==null||t.cancel(e),this._abortController.abort()}}const Mv=200,Iv=206;function B8(n){const e=n.response;return typeof e!="string"?e:D0(e).buffer}class U8{constructor({url:e,httpHeaders:t,withCredentials:s}){this.url=e,this.isHttp=/^https?:/i.test(e),this.headers=Rx(this.isHttp,t),this.withCredentials=s||!1,this.currXhrId=0,this.pendingRequests=Object.create(null)}requestRange(e,t,s){const i={begin:e,end:t};for(const r in s)i[r]=s[r];return this.request(i)}requestFull(e){return this.request(e)}request(e){const t=new XMLHttpRequest,s=this.currXhrId++,i=this.pendingRequests[s]={xhr:t};t.open("GET",this.url),t.withCredentials=this.withCredentials;for(const[r,o]of this.headers)t.setRequestHeader(r,o);return this.isHttp&&"begin"in e&&"end"in e?(t.setRequestHeader("Range",`bytes=${e.begin}-${e.end-1}`),i.expectedStatus=Iv):i.expectedStatus=Mv,t.responseType="arraybuffer",e.onError&&(t.onerror=function(r){e.onError(t.status)}),t.onreadystatechange=this.onStateChange.bind(this,s),t.onprogress=this.onProgress.bind(this,s),i.onHeadersReceived=e.onHeadersReceived,i.onDone=e.onDone,i.onError=e.onError,i.onProgress=e.onProgress,t.send(null),s}onProgress(e,t){var i;const s=this.pendingRequests[e];s&&((i=s.onProgress)==null||i.call(s,t))}onStateChange(e,t){var l,c,h;const s=this.pendingRequests[e];if(!s)return;const i=s.xhr;if(i.readyState>=2&&s.onHeadersReceived&&(s.onHeadersReceived(),delete s.onHeadersReceived),i.readyState!==4||!(e in this.pendingRequests))return;if(delete this.pendingRequests[e],i.status===0&&this.isHttp){(l=s.onError)==null||l.call(s,i.status);return}const r=i.status||Mv;if(!(r===Mv&&s.expectedStatus===Iv)&&r!==s.expectedStatus){(c=s.onError)==null||c.call(s,i.status);return}const a=B8(i);if(r===Iv){const u=i.getResponseHeader("Content-Range"),d=/bytes (\d+)-(\d+)\/(\d+)/.exec(u);s.onDone({begin:parseInt(d[1],10),chunk:a})}else a?s.onDone({begin:0,chunk:a}):(h=s.onError)==null||h.call(s,i.status)}getRequestXhr(e){return this.pendingRequests[e].xhr}isPendingRequest(e){return e in this.pendingRequests}abortRequest(e){const t=this.pendingRequests[e].xhr;delete this.pendingRequests[e],t.abort()}}class q8{constructor(e){this._source=e,this._manager=new U8(e),this._rangeChunkSize=e.rangeChunkSize,this._fullRequestReader=null,this._rangeRequestReaders=[]}_onRangeRequestReaderClosed(e){const t=this._rangeRequestReaders.indexOf(e);t>=0&&this._rangeRequestReaders.splice(t,1)}getFullReader(){return yn(!this._fullRequestReader,"PDFNetworkStream.getFullReader can only be called once."),this._fullRequestReader=new V8(this._manager,this._source),this._fullRequestReader}getRangeReader(e,t){const s=new W8(this._manager,e,t);return s.onClosed=this._onRangeRequestReaderClosed.bind(this),this._rangeRequestReaders.push(s),s}cancelAllRequests(e){var t;(t=this._fullRequestReader)==null||t.cancel(e);for(const s of this._rangeRequestReaders.slice(0))s.cancel(e)}}class V8{constructor(e,t){this._manager=e;const s={onHeadersReceived:this._onHeadersReceived.bind(this),onDone:this._onDone.bind(this),onError:this._onError.bind(this),onProgress:this._onProgress.bind(this)};this._url=t.url,this._fullRequestId=e.requestFull(s),this._headersCapability=Promise.withResolvers(),this._disableRange=t.disableRange||!1,this._contentLength=t.length,this._rangeChunkSize=t.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 e=this._fullRequestId,t=this._manager.getRequestXhr(e),s=new Headers(t.getAllResponseHeaders().trim().split(/[\r\n]+/).map(o=>{const[a,...l]=o.split(": ");return[a,l.join(": ")]})),{allowRangeRequests:i,suggestedLength:r}=Mx({responseHeaders:s,isHttp:this._manager.isHttp,rangeChunkSize:this._rangeChunkSize,disableRange:this._disableRange});i&&(this._isRangeSupported=!0),this._contentLength=r||this._contentLength,this._filename=Ix(s),this._isRangeSupported&&this._manager.abortRequest(e),this._headersCapability.resolve()}_onDone(e){if(e&&(this._requests.length>0?this._requests.shift().resolve({value:e.chunk,done:!1}):this._cachedChunks.push(e.chunk)),this._done=!0,!(this._cachedChunks.length>0)){for(const t of this._requests)t.resolve({value:void 0,done:!0});this._requests.length=0}}_onError(e){this._storedError=z0(e,this._url),this._headersCapability.reject(this._storedError);for(const t of this._requests)t.reject(this._storedError);this._requests.length=0,this._cachedChunks.length=0}_onProgress(e){var t;(t=this.onProgress)==null||t.call(this,{loaded:e.loaded,total:e.lengthComputable?e.total:this._contentLength})}get filename(){return this._filename}get isRangeSupported(){return this._isRangeSupported}get isStreamingSupported(){return this._isStreamingSupported}get contentLength(){return this._contentLength}get headersReady(){return this._headersCapability.promise}async read(){if(this._storedError)throw this._storedError;if(this._cachedChunks.length>0)return{value:this._cachedChunks.shift(),done:!1};if(this._done)return{value:void 0,done:!0};const e=Promise.withResolvers();return this._requests.push(e),e.promise}cancel(e){this._done=!0,this._headersCapability.reject(e);for(const t of this._requests)t.resolve({value:void 0,done:!0});this._requests.length=0,this._manager.isPendingRequest(this._fullRequestId)&&this._manager.abortRequest(this._fullRequestId),this._fullRequestReader=null}}class W8{constructor(e,t,s){this._manager=e;const i={onDone:this._onDone.bind(this),onError:this._onError.bind(this),onProgress:this._onProgress.bind(this)};this._url=e.url,this._requestId=e.requestRange(t,s,i),this._requests=[],this._queuedChunk=null,this._done=!1,this._storedError=void 0,this.onProgress=null,this.onClosed=null}_close(){var e;(e=this.onClosed)==null||e.call(this,this)}_onDone(e){const t=e.chunk;this._requests.length>0?this._requests.shift().resolve({value:t,done:!1}):this._queuedChunk=t,this._done=!0;for(const s of this._requests)s.resolve({value:void 0,done:!0});this._requests.length=0,this._close()}_onError(e){this._storedError=z0(e,this._url);for(const t of this._requests)t.reject(this._storedError);this._requests.length=0,this._queuedChunk=null}_onProgress(e){var t;this.isStreamingSupported||(t=this.onProgress)==null||t.call(this,{loaded:e.loaded})}get isStreamingSupported(){return!1}async read(){if(this._storedError)throw this._storedError;if(this._queuedChunk!==null){const t=this._queuedChunk;return this._queuedChunk=null,{value:t,done:!1}}if(this._done)return{value:void 0,done:!0};const e=Promise.withResolvers();return this._requests.push(e),e.promise}cancel(e){this._done=!0;for(const t of this._requests)t.resolve({value:void 0,done:!0});this._requests.length=0,this._manager.isPendingRequest(this._requestId)&&this._manager.abortRequest(this._requestId),this._close()}}const G8=/^[a-z][a-z0-9\-+.]+:/i;function K8(n){if(G8.test(n))return new URL(n);const e=Pa.get("url");return new URL(e.pathToFileURL(n))}function cM(n,e,t){return n.protocol==="http:"?Pa.get("http").request(n,{headers:e},t):Pa.get("https").request(n,{headers:e},t)}class Z8{constructor(e){this.source=e,this.url=K8(e.url),this.isHttp=this.url.protocol==="http:"||this.url.protocol==="https:",this.isFsUrl=this.url.protocol==="file:",this.headers=Rx(this.isHttp,e.httpHeaders),this._fullRequestReader=null,this._rangeRequestReaders=[]}get _progressiveDataLength(){var e;return((e=this._fullRequestReader)==null?void 0:e._loaded)??0}getFullReader(){return yn(!this._fullRequestReader,"PDFNodeStream.getFullReader can only be called once."),this._fullRequestReader=this.isFsUrl?new J8(this):new X8(this),this._fullRequestReader}getRangeReader(e,t){if(t<=this._progressiveDataLength)return null;const s=this.isFsUrl?new Q8(this,e,t):new Y8(this,e,t);return this._rangeRequestReaders.push(s),s}cancelAllRequests(e){var t;(t=this._fullRequestReader)==null||t.cancel(e);for(const s of this._rangeRequestReaders.slice(0))s.cancel(e)}}class hM{constructor(e){this._url=e.url,this._done=!1,this._storedError=null,this.onProgress=null;const t=e.source;this._contentLength=t.length,this._loaded=0,this._filename=null,this._disableRange=t.disableRange||!1,this._rangeChunkSize=t.rangeChunkSize,!this._rangeChunkSize&&!this._disableRange&&(this._disableRange=!0),this._isStreamingSupported=!t.disableStream,this._isRangeSupported=!t.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(){var s;if(await this._readCapability.promise,this._done)return{value:void 0,done:!0};if(this._storedError)throw this._storedError;const e=this._readableStream.read();return e===null?(this._readCapability=Promise.withResolvers(),this.read()):(this._loaded+=e.length,(s=this.onProgress)==null||s.call(this,{loaded:this._loaded,total:this._contentLength}),{value:new Uint8Array(e).buffer,done:!1})}cancel(e){if(!this._readableStream){this._error(e);return}this._readableStream.destroy(e)}_error(e){this._storedError=e,this._readCapability.resolve()}_setReadableStream(e){this._readableStream=e,e.on("readable",()=>{this._readCapability.resolve()}),e.on("end",()=>{e.destroy(),this._done=!0,this._readCapability.resolve()}),e.on("error",t=>{this._error(t)}),!this._isStreamingSupported&&this._isRangeSupported&&this._error(new $c("streaming is disabled")),this._storedError&&this._readableStream.destroy(this._storedError)}}class uM{constructor(e){this._url=e.url,this._done=!1,this._storedError=null,this.onProgress=null,this._loaded=0,this._readableStream=null,this._readCapability=Promise.withResolvers();const t=e.source;this._isStreamingSupported=!t.disableStream}get isStreamingSupported(){return this._isStreamingSupported}async read(){var s;if(await this._readCapability.promise,this._done)return{value:void 0,done:!0};if(this._storedError)throw this._storedError;const e=this._readableStream.read();return e===null?(this._readCapability=Promise.withResolvers(),this.read()):(this._loaded+=e.length,(s=this.onProgress)==null||s.call(this,{loaded:this._loaded}),{value:new Uint8Array(e).buffer,done:!1})}cancel(e){if(!this._readableStream){this._error(e);return}this._readableStream.destroy(e)}_error(e){this._storedError=e,this._readCapability.resolve()}_setReadableStream(e){this._readableStream=e,e.on("readable",()=>{this._readCapability.resolve()}),e.on("end",()=>{e.destroy(),this._done=!0,this._readCapability.resolve()}),e.on("error",t=>{this._error(t)}),this._storedError&&this._readableStream.destroy(this._storedError)}}class X8 extends hM{constructor(e){super(e);const t=Object.fromEntries(e.headers),s=i=>{if(i.statusCode===404){const l=new Cc(`Missing PDF "${this._url}".`);this._storedError=l,this._headersCapability.reject(l);return}this._headersCapability.resolve(),this._setReadableStream(i);const r=new Headers(this._readableStream.headers),{allowRangeRequests:o,suggestedLength:a}=Mx({responseHeaders:r,isHttp:e.isHttp,rangeChunkSize:this._rangeChunkSize,disableRange:this._disableRange});this._isRangeSupported=o,this._contentLength=a||this._contentLength,this._filename=Ix(r)};this._request=cM(this._url,t,s),this._request.on("error",i=>{this._storedError=i,this._headersCapability.reject(i)}),this._request.end()}}class Y8 extends uM{constructor(e,t,s){super(e);const i=Object.fromEntries(e.headers);i.Range=`bytes=${t}-${s-1}`;const r=o=>{if(o.statusCode===404){const a=new Cc(`Missing PDF "${this._url}".`);this._storedError=a;return}this._setReadableStream(o)};this._request=cM(this._url,i,r),this._request.on("error",o=>{this._storedError=o}),this._request.end()}}class J8 extends hM{constructor(e){super(e);const t=Pa.get("fs");t.promises.lstat(this._url).then(s=>{this._contentLength=s.size,this._setReadableStream(t.createReadStream(this._url)),this._headersCapability.resolve()},s=>{s.code==="ENOENT"&&(s=new Cc(`Missing PDF "${this._url}".`)),this._storedError=s,this._headersCapability.reject(s)})}}class Q8 extends uM{constructor(e,t,s){super(e);const i=Pa.get("fs");this._setReadableStream(i.createReadStream(this._url,{start:t,end:s-1}))}}const eZ=1e5,Cs=30,tZ=.8;var KC,sa,Ps,Zf,Xf,Pl,Jr,Yf,Jf,Rl,jh,Fh,ia,zh,Qf,Hh,Ml,ep,tp,Wt,Il,Ol,np,ra,Bh,To,dM,fM,Sw,si,Eg,xw,pM,mM;let _w=(Wt=class{constructor({textContentSource:e,container:t,viewport:s}){M(this,To);M(this,sa,Promise.withResolvers());M(this,Ps,null);M(this,Zf,!1);M(this,Xf,!!((KC=globalThis.FontInspector)!=null&&KC.enabled));M(this,Pl,null);M(this,Jr,null);M(this,Yf,0);M(this,Jf,0);M(this,Rl,null);M(this,jh,null);M(this,Fh,0);M(this,ia,0);M(this,zh,Object.create(null));M(this,Qf,[]);M(this,Hh,null);M(this,Ml,[]);M(this,ep,new WeakMap);M(this,tp,null);var l;if(e instanceof ReadableStream)T(this,Hh,e);else if(typeof e=="object")T(this,Hh,new ReadableStream({start(c){c.enqueue(e),c.close()}}));else throw new Error('No "textContentSource" parameter specified.');T(this,Ps,T(this,jh,t)),T(this,ia,s.scale*(globalThis.devicePixelRatio||1)),T(this,Fh,s.rotation),T(this,Jr,{div:null,properties:null,ctx:null});const{pageWidth:i,pageHeight:r,pageX:o,pageY:a}=s.rawDims;T(this,tp,[1,0,0,-1,-o,a+r]),T(this,Jf,i),T(this,Yf,r),P(l=Wt,si,pM).call(l),pc(t,s),f(this,sa).promise.finally(()=>{f(Wt,Bh).delete(this),T(this,Jr,null),T(this,zh,null)}).catch(()=>{})}static get fontFamilyMap(){const{isWindows:e,isFirefox:t}=bs.platform;return Xe(this,"fontFamilyMap",new Map([["sans-serif",`${e&&t?"Calibri, ":""}sans-serif`],["monospace",`${e&&t?"Lucida Console, ":""}monospace`]]))}render(){const e=()=>{f(this,Rl).read().then(({value:t,done:s})=>{if(s){f(this,sa).resolve();return}f(this,Pl)??T(this,Pl,t.lang),Object.assign(f(this,zh),t.styles),P(this,To,dM).call(this,t.items),e()},f(this,sa).reject)};return T(this,Rl,f(this,Hh).getReader()),f(Wt,Bh).add(this),e(),f(this,sa).promise}update({viewport:e,onBefore:t=null}){var r;const s=e.scale*(globalThis.devicePixelRatio||1),i=e.rotation;if(i!==f(this,Fh)&&(t==null||t(),T(this,Fh,i),pc(f(this,jh),{rotation:i})),s!==f(this,ia)){t==null||t(),T(this,ia,s);const o={div:null,properties:null,ctx:P(r=Wt,si,Eg).call(r,f(this,Pl))};for(const a of f(this,Ml))o.properties=f(this,ep).get(a),o.div=a,P(this,To,Sw).call(this,o)}}cancel(){var t;const e=new $c("TextLayer task cancelled.");(t=f(this,Rl))==null||t.cancel(e).catch(()=>{}),T(this,Rl,null),f(this,sa).reject(e)}get textDivs(){return f(this,Ml)}get textContentItemsStr(){return f(this,Qf)}static cleanup(){if(!(f(this,Bh).size>0)){f(this,Il).clear();for(const{canvas:e}of f(this,Ol).values())e.remove();f(this,Ol).clear()}}},sa=new WeakMap,Ps=new WeakMap,Zf=new WeakMap,Xf=new WeakMap,Pl=new WeakMap,Jr=new WeakMap,Yf=new WeakMap,Jf=new WeakMap,Rl=new WeakMap,jh=new WeakMap,Fh=new WeakMap,ia=new WeakMap,zh=new WeakMap,Qf=new WeakMap,Hh=new WeakMap,Ml=new WeakMap,ep=new WeakMap,tp=new WeakMap,Il=new WeakMap,Ol=new WeakMap,np=new WeakMap,ra=new WeakMap,Bh=new WeakMap,To=new WeakSet,dM=function(e){var i,r;if(f(this,Zf))return;(r=f(this,Jr)).ctx??(r.ctx=P(i=Wt,si,Eg).call(i,f(this,Pl)));const t=f(this,Ml),s=f(this,Qf);for(const o of e){if(t.length>eZ){qe("Ignoring additional textDivs for performance reasons."),T(this,Zf,!0);return}if(o.str===void 0){if(o.type==="beginMarkedContentProps"||o.type==="beginMarkedContent"){const a=f(this,Ps);T(this,Ps,document.createElement("span")),f(this,Ps).classList.add("markedContent"),o.id!==null&&f(this,Ps).setAttribute("id",`${o.id}`),a.append(f(this,Ps))}else o.type==="endMarkedContent"&&T(this,Ps,f(this,Ps).parentNode);continue}s.push(o.str),P(this,To,fM).call(this,o)}},fM=function(e){var y;const t=document.createElement("span"),s={angle:0,canvasWidth:0,hasText:e.str!=="",hasEOL:e.hasEOL,fontSize:0};f(this,Ml).push(t);const i=Se.transform(f(this,tp),e.transform);let r=Math.atan2(i[1],i[0]);const o=f(this,zh)[e.fontName];o.vertical&&(r+=Math.PI/2);let a=f(this,Xf)&&o.fontSubstitution||o.fontFamily;a=Wt.fontFamilyMap.get(a)||a;const l=Math.hypot(i[2],i[3]),c=l*P(y=Wt,si,mM).call(y,a,f(this,Pl));let h,u;r===0?(h=i[4],u=i[5]-c):(h=i[4]+c*Math.sin(r),u=i[5]-c*Math.cos(r));const d="calc(var(--scale-factor)*",p=t.style;f(this,Ps)===f(this,jh)?(p.left=`${(100*h/f(this,Jf)).toFixed(2)}%`,p.top=`${(100*u/f(this,Yf)).toFixed(2)}%`):(p.left=`${d}${h.toFixed(2)}px)`,p.top=`${d}${u.toFixed(2)}px)`),p.fontSize=`${d}${(f(Wt,ra)*l).toFixed(2)}px)`,p.fontFamily=a,s.fontSize=l,t.setAttribute("role","presentation"),t.textContent=e.str,t.dir=e.dir,f(this,Xf)&&(t.dataset.fontName=o.fontSubstitutionLoadedName||e.fontName),r!==0&&(s.angle=r*(180/Math.PI));let m=!1;if(e.str.length>1)m=!0;else if(e.str!==" "&&e.transform[0]!==e.transform[3]){const v=Math.abs(e.transform[0]),g=Math.abs(e.transform[3]);v!==g&&Math.max(v,g)/Math.min(v,g)>1.5&&(m=!0)}if(m&&(s.canvasWidth=o.vertical?e.height:e.width),f(this,ep).set(t,s),f(this,Jr).div=t,f(this,Jr).properties=s,P(this,To,Sw).call(this,f(this,Jr)),s.hasText&&f(this,Ps).append(t),s.hasEOL){const v=document.createElement("br");v.setAttribute("role","presentation"),f(this,Ps).append(v)}},Sw=function(e){var a;const{div:t,properties:s,ctx:i}=e,{style:r}=t;let o="";if(f(Wt,ra)>1&&(o=`scale(${1/f(Wt,ra)})`),s.canvasWidth!==0&&s.hasText){const{fontFamily:l}=r,{canvasWidth:c,fontSize:h}=s;P(a=Wt,si,xw).call(a,i,h*f(this,ia),l);const{width:u}=i.measureText(t.textContent);u>0&&(o=`scaleX(${c*f(this,ia)/u}) ${o}`)}s.angle!==0&&(o=`rotate(${s.angle}deg) ${o}`),o.length>0&&(r.transform=o)},si=new WeakSet,Eg=function(e=null){let t=f(this,Ol).get(e||(e=""));if(!t){const s=document.createElement("canvas");s.className="hiddenCanvasElement",s.lang=e,document.body.append(s),t=s.getContext("2d",{alpha:!1,willReadFrequently:!0}),f(this,Ol).set(e,t),f(this,np).set(t,{size:0,family:""})}return t},xw=function(e,t,s){const i=f(this,np).get(e);t===i.size&&s===i.family||(e.font=`${t}px ${s}`,i.size=t,i.family=s)},pM=function(){if(f(this,ra)!==null)return;const e=document.createElement("div");e.style.opacity=0,e.style.lineHeight=1,e.style.fontSize="1px",e.style.position="absolute",e.textContent="X",document.body.append(e),T(this,ra,e.getBoundingClientRect().height),e.remove()},mM=function(e,t){const s=f(this,Il).get(e);if(s)return s;const i=P(this,si,Eg).call(this,t);i.canvas.width=i.canvas.height=Cs,P(this,si,xw).call(this,i,Cs,e);const r=i.measureText("");let o=r.fontBoundingBoxAscent,a=Math.abs(r.fontBoundingBoxDescent);if(o){const h=o/(o+a);return f(this,Il).set(e,h),i.canvas.width=i.canvas.height=0,h}i.strokeStyle="red",i.clearRect(0,0,Cs,Cs),i.strokeText("g",0,0);let l=i.getImageData(0,0,Cs,Cs).data;a=0;for(let h=l.length-1-3;h>=0;h-=4)if(l[h]>0){a=Math.ceil(h/4/Cs);break}i.clearRect(0,0,Cs,Cs),i.strokeText("A",0,Cs),l=i.getImageData(0,0,Cs,Cs).data,o=0;for(let h=0,u=l.length;h0){o=Cs-Math.floor(h/4/Cs);break}i.canvas.width=i.canvas.height=0;const c=o?o/(o+a):tZ;return f(this,Il).set(e,c),c},M(Wt,si),M(Wt,Il,new Map),M(Wt,Ol,new Map),M(Wt,np,new WeakMap),M(Wt,ra,null),M(Wt,Bh,new Set),Wt);class hf{static textContent(e){const t=[],s={items:t,styles:Object.create(null)};function i(r){var l;if(!r)return;let o=null;const a=r.name;if(a==="#text")o=r.value;else if(hf.shouldBuildText(a))(l=r==null?void 0:r.attributes)!=null&&l.textContent?o=r.attributes.textContent:r.value&&(o=r.value);else return;if(o!==null&&t.push({str:o}),!!r.children)for(const c of r.children)i(c)}return i(e),s}static shouldBuildText(e){return!(e==="textarea"||e==="input"||e==="option"||e==="select")}}const nZ=65536,sZ=100,iZ=5e3,rZ=ls?y8:p8,oZ=ls?v8:YR,aZ=ls?g8:m8,lZ=ls?b8:tM;function cZ(n={}){typeof n=="string"||n instanceof URL?n={url:n}:(n instanceof ArrayBuffer||ArrayBuffer.isView(n))&&(n={data:n});const e=new Aw,{docId:t}=e,s=n.url?hZ(n.url):null,i=n.data?uZ(n.data):null,r=n.httpHeaders||null,o=n.withCredentials===!0,a=n.password??null,l=n.range instanceof gM?n.range:null,c=Number.isInteger(n.rangeChunkSize)&&n.rangeChunkSize>0?n.rangeChunkSize:nZ;let h=n.worker instanceof dh?n.worker:null;const u=n.verbosity,d=typeof n.docBaseUrl=="string"&&!F0(n.docBaseUrl)?n.docBaseUrl:null,p=typeof n.cMapUrl=="string"?n.cMapUrl:null,m=n.cMapPacked!==!1,y=n.CMapReaderFactory||oZ,v=typeof n.standardFontDataUrl=="string"?n.standardFontDataUrl:null,g=n.StandardFontDataFactory||lZ,b=n.stopAtErrors!==!0,_=Number.isInteger(n.maxImageSize)&&n.maxImageSize>-1?n.maxImageSize:-1,x=n.isEvalSupported!==!1,A=typeof n.isOffscreenCanvasSupported=="boolean"?n.isOffscreenCanvasSupported:!ls,C=typeof n.isChrome=="boolean"?n.isChrome:!bs.platform.isFirefox&&typeof window<"u"&&!!(window!=null&&window.chrome),$=Number.isInteger(n.canvasMaxAreaInBytes)?n.canvasMaxAreaInBytes:-1,I=typeof n.disableFontFace=="boolean"?n.disableFontFace:ls,j=n.fontExtraProperties===!0,q=n.enableXfa===!0,L=n.ownerDocument||globalThis.document,B=n.disableRange===!0,H=n.disableStream===!0,D=n.disableAutoFetch===!0,X=n.pdfBug===!0,te=n.CanvasFactory||rZ,J=n.FilterFactory||aZ,Y=n.enableHWA===!0,ye=l?l.length:n.length??NaN,z=typeof n.useSystemFonts=="boolean"?n.useSystemFonts:!ls&&!I,E=typeof n.useWorkerFetch=="boolean"?n.useWorkerFetch:y===YR&&g===tM&&p&&v&&gd(p,document.baseURI)&&gd(v,document.baseURI);n.canvasFactory&&Kk("`canvasFactory`-instance option, please use `CanvasFactory` instead."),n.filterFactory&&Kk("`filterFactory`-instance option, please use `FilterFactory` instead.");const O=null;V6(u);const R={canvasFactory:new te({ownerDocument:L,enableHWA:Y}),filterFactory:new J({docId:t,ownerDocument:L}),cMapReaderFactory:E?null:new y({baseUrl:p,isCompressed:m}),standardFontDataFactory:E?null:new g({baseUrl:v})};if(!h){const N={verbosity:u,port:yo.workerPort};h=N.port?dh.fromPort(N):new dh(N),e._worker=h}const w={docId:t,apiVersion:"4.8.69",data:i,password:a,disableAutoFetch:D,rangeChunkSize:c,length:ye,docBaseUrl:d,enableXfa:q,evaluatorOptions:{maxImageSize:_,disableFontFace:I,ignoreErrors:b,isEvalSupported:x,isOffscreenCanvasSupported:A,isChrome:C,canvasMaxAreaInBytes:$,fontExtraProperties:j,useSystemFonts:z,cMapUrl:E?p:null,standardFontDataUrl:E?v:null}},k={disableFontFace:I,fontExtraProperties:j,ownerDocument:L,pdfBug:X,styleElement:O,loadingParams:{disableAutoFetch:D,enableXfa:q}};return h.promise.then(function(){if(e.destroyed)throw new Error("Loading aborted");if(h.destroyed)throw new Error("Worker was destroyed");const N=h.messageHandler.sendWithPromise("GetDocRequest",w,i?[i.buffer]:null);let G;if(l)G=new L8(l,{disableRange:B,disableStream:H});else if(!i){if(!s)throw new Error("getDocument - no `url` parameter provided.");let Z;ls?Z=typeof fetch<"u"&&typeof Response<"u"&&"body"in Response.prototype&&gd(s)?oE:Z8:Z=gd(s)?oE:q8,G=new Z({url:s,length:ye,httpHeaders:r,withCredentials:o,rangeChunkSize:c,disableRange:B,disableStream:H})}return N.then(Z=>{if(e.destroyed)throw new Error("Loading aborted");if(h.destroyed)throw new Error("Worker was destroyed");const ae=new xd(t,Z,h.port),ie=new mZ(ae,e,G,k,R);e._transport=ie,ae.send("Ready",null)})}).catch(e._capability.reject),e}function hZ(n){if(n instanceof URL)return n.href;try{return new URL(n,window.location).href}catch{if(ls&&typeof n=="string")return n}throw new Error("Invalid PDF url data: either string or URL-object is expected in the url property.")}function uZ(n){if(ls&&typeof Buffer<"u"&&n instanceof Buffer)throw new Error("Please provide binary data as `Uint8Array`, rather than `Buffer`.");if(n instanceof Uint8Array&&n.byteLength===n.buffer.byteLength)return n;if(typeof n=="string")return D0(n);if(n instanceof ArrayBuffer||ArrayBuffer.isView(n)||typeof n=="object"&&!isNaN(n==null?void 0:n.length))return new Uint8Array(n);throw new Error("Invalid PDF binary data: either TypedArray, string, or array-like object is expected in the data property.")}function aE(n){return typeof n=="object"&&Number.isInteger(n==null?void 0:n.num)&&n.num>=0&&Number.isInteger(n==null?void 0:n.gen)&&n.gen>=0}var t0;const n0=class n0{constructor(){this._capability=Promise.withResolvers(),this._transport=null,this._worker=null,this.docId=`d${ds(n0,t0)._++}`,this.destroyed=!1,this.onPassword=null,this.onProgress=null}get promise(){return this._capability.promise}async destroy(){var e,t,s;this.destroyed=!0;try{(e=this._worker)!=null&&e.port&&(this._worker._pendingDestroy=!0),await((t=this._transport)==null?void 0:t.destroy())}catch(i){throw(s=this._worker)!=null&&s.port&&delete this._worker._pendingDestroy,i}this._transport=null,this._worker&&(this._worker.destroy(),this._worker=null)}};t0=new WeakMap,M(n0,t0,0);let Aw=n0,gM=class{constructor(e,t,s=!1,i=null){this.length=e,this.initialData=t,this.progressiveDone=s,this.contentDispositionFilename=i,this._rangeListeners=[],this._progressListeners=[],this._progressiveReadListeners=[],this._progressiveDoneListeners=[],this._readyCapability=Promise.withResolvers()}addRangeListener(e){this._rangeListeners.push(e)}addProgressListener(e){this._progressListeners.push(e)}addProgressiveReadListener(e){this._progressiveReadListeners.push(e)}addProgressiveDoneListener(e){this._progressiveDoneListeners.push(e)}onDataRange(e,t){for(const s of this._rangeListeners)s(e,t)}onDataProgress(e,t){this._readyCapability.promise.then(()=>{for(const s of this._progressListeners)s(e,t)})}onDataProgressiveRead(e){this._readyCapability.promise.then(()=>{for(const t of this._progressiveReadListeners)t(e)})}onDataProgressiveDone(){this._readyCapability.promise.then(()=>{for(const e of this._progressiveDoneListeners)e()})}transportReady(){this._readyCapability.resolve()}requestDataRange(e,t){Tt("Abstract method PDFDataRangeTransport.requestDataRange")}abort(){}};class dZ{constructor(e,t){this._pdfInfo=e,this._transport=t}get annotationStorage(){return this._transport.annotationStorage}get canvasFactory(){return this._transport.canvasFactory}get filterFactory(){return this._transport.filterFactory}get numPages(){return this._pdfInfo.numPages}get fingerprints(){return this._pdfInfo.fingerprints}get isPureXfa(){return Xe(this,"isPureXfa",!!this._transport._htmlForXfa)}get allXfaHtml(){return this._transport._htmlForXfa}getPage(e){return this._transport.getPage(e)}getPageIndex(e){return this._transport.getPageIndex(e)}getDestinations(){return this._transport.getDestinations()}getDestination(e){return this._transport.getDestination(e)}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:e="display"}={}){const{renderingIntent:t}=this._transport.getRenderingIntent(e);return this._transport.getOptionalContentConfig(t)}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(e=!1){return this._transport.startCleanup(e||this.isPureXfa)}destroy(){return this.loadingTask.destroy()}cachedPageNumber(e){return this._transport.cachedPageNumber(e)}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()}}var oa,Qr,gi,Kc,Cg;class fZ{constructor(e,t,s,i=!1){M(this,gi);M(this,oa,null);M(this,Qr,!1);this._pageIndex=e,this._pageInfo=t,this._transport=s,this._stats=i?new Gk:null,this._pdfBug=i,this.commonObjs=s.commonObjs,this.objs=new yM,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:e,rotation:t=this.rotate,offsetX:s=0,offsetY:i=0,dontFlip:r=!1}={}){return new tm({viewBox:this.view,scale:e,rotation:t,offsetX:s,offsetY:i,dontFlip:r})}getAnnotations({intent:e="display"}={}){const{renderingIntent:t}=this._transport.getRenderingIntent(e);return this._transport.getAnnotations(this._pageIndex,t)}getJSActions(){return this._transport.getPageJSActions(this._pageIndex)}get filterFactory(){return this._transport.filterFactory}get isPureXfa(){return Xe(this,"isPureXfa",!!this._transport._htmlForXfa)}async getXfa(){var e;return((e=this._transport._htmlForXfa)==null?void 0:e.children[this._pageIndex])||null}render({canvasContext:e,viewport:t,intent:s="display",annotationMode:i=Bo.ENABLE,transform:r=null,background:o=null,optionalContentConfigPromise:a=null,annotationCanvasMap:l=null,pageColors:c=null,printAnnotationStorage:h=null,isEditing:u=!1}){var x,A;(x=this._stats)==null||x.time("Overall");const d=this._transport.getRenderingIntent(s,i,h,u),{renderingIntent:p,cacheKey:m}=d;T(this,Qr,!1),P(this,gi,Cg).call(this),a||(a=this._transport.getOptionalContentConfig(p));let y=this._intentStates.get(m);y||(y=Object.create(null),this._intentStates.set(m,y)),y.streamReaderCancelTimeout&&(clearTimeout(y.streamReaderCancelTimeout),y.streamReaderCancelTimeout=null);const v=!!(p&Qs.PRINT);y.displayReadyCapability||(y.displayReadyCapability=Promise.withResolvers(),y.operatorList={fnArray:[],argsArray:[],lastChunk:!1,separateAnnots:null},(A=this._stats)==null||A.time("Page Request"),this._pumpOperatorList(d));const g=C=>{var $;y.renderTasks.delete(b),(this._maybeCleanupAfterRender||v)&&T(this,Qr,!0),P(this,gi,Kc).call(this,!v),C?(b.capability.reject(C),this._abortOperatorList({intentState:y,reason:C instanceof Error?C:new Error(C)})):b.capability.resolve(),this._stats&&(this._stats.timeEnd("Rendering"),this._stats.timeEnd("Overall"),($=globalThis.Stats)!=null&&$.enabled&&globalThis.Stats.add(this.pageNumber,this._stats))},b=new Ew({callback:g,params:{canvasContext:e,viewport:t,transform:r,background:o},objs:this.objs,commonObjs:this.commonObjs,annotationCanvasMap:l,operatorList:y.operatorList,pageIndex:this._pageIndex,canvasFactory:this._transport.canvasFactory,filterFactory:this._transport.filterFactory,useRequestAnimationFrame:!v,pdfBug:this._pdfBug,pageColors:c});(y.renderTasks||(y.renderTasks=new Set)).add(b);const _=b.task;return Promise.all([y.displayReadyCapability.promise,a]).then(([C,$])=>{var I;if(this.destroyed){g();return}if((I=this._stats)==null||I.time("Rendering"),!($.renderingIntent&p))throw new Error("Must use the same `intent`-argument when calling the `PDFPageProxy.render` and `PDFDocumentProxy.getOptionalContentConfig` methods.");b.initializeGraphics({transparency:C,optionalContentConfig:$}),b.operatorListChanged()}).catch(g),_}getOperatorList({intent:e="display",annotationMode:t=Bo.ENABLE,printAnnotationStorage:s=null,isEditing:i=!1}={}){var c;function r(){a.operatorList.lastChunk&&(a.opListReadCapability.resolve(a.operatorList),a.renderTasks.delete(l))}const o=this._transport.getRenderingIntent(e,t,s,i,!0);let a=this._intentStates.get(o.cacheKey);a||(a=Object.create(null),this._intentStates.set(o.cacheKey,a));let l;return a.opListReadCapability||(l=Object.create(null),l.operatorListChanged=r,a.opListReadCapability=Promise.withResolvers(),(a.renderTasks||(a.renderTasks=new Set)).add(l),a.operatorList={fnArray:[],argsArray:[],lastChunk:!1,separateAnnots:null},(c=this._stats)==null||c.time("Page Request"),this._pumpOperatorList(o)),a.opListReadCapability.promise}streamTextContent({includeMarkedContent:e=!1,disableNormalization:t=!1}={}){return this._transport.messageHandler.sendWithStream("GetTextContent",{pageIndex:this._pageIndex,includeMarkedContent:e===!0,disableNormalization:t===!0},{highWaterMark:100,size(i){return i.items.length}})}getTextContent(e={}){if(this._transport._htmlForXfa)return this.getXfa().then(s=>hf.textContent(s));const t=this.streamTextContent(e);return new Promise(function(s,i){function r(){o.read().then(function({value:l,done:c}){if(c){s(a);return}a.lang??(a.lang=l.lang),Object.assign(a.styles,l.styles),a.items.push(...l.items),r()},i)}const o=t.getReader(),a={items:[],styles:Object.create(null),lang:null};r()})}getStructTree(){return this._transport.getStructTree(this._pageIndex)}_destroy(){this.destroyed=!0;const e=[];for(const t of this._intentStates.values())if(this._abortOperatorList({intentState:t,reason:new Error("Page was destroyed."),force:!0}),!t.opListReadCapability)for(const s of t.renderTasks)e.push(s.completed),s.cancel();return this.objs.clear(),T(this,Qr,!1),P(this,gi,Cg).call(this),Promise.all(e)}cleanup(e=!1){T(this,Qr,!0);const t=P(this,gi,Kc).call(this,!1);return e&&t&&this._stats&&(this._stats=new Gk),t}_startRenderPage(e,t){var i,r;const s=this._intentStates.get(t);s&&((i=this._stats)==null||i.timeEnd("Page Request"),(r=s.displayReadyCapability)==null||r.resolve(e))}_renderPageChunk(e,t){for(let s=0,i=e.length;s{l.read().then(({value:u,done:d})=>{if(d){c.streamReader=null;return}this._transport.destroyed||(this._renderPageChunk(u,c),h())},u=>{if(c.streamReader=null,!this._transport.destroyed){if(c.operatorList){c.operatorList.lastChunk=!0;for(const d of c.renderTasks)d.operatorListChanged();P(this,gi,Kc).call(this,!0)}if(c.displayReadyCapability)c.displayReadyCapability.reject(u);else if(c.opListReadCapability)c.opListReadCapability.reject(u);else throw u}})};h()}_abortOperatorList({intentState:e,reason:t,force:s=!1}){if(e.streamReader){if(e.streamReaderCancelTimeout&&(clearTimeout(e.streamReaderCancelTimeout),e.streamReaderCancelTimeout=null),!s){if(e.renderTasks.size>0)return;if(t instanceof kx){let i=sZ;t.extraDelay>0&&t.extraDelay<1e3&&(i+=t.extraDelay),e.streamReaderCancelTimeout=setTimeout(()=>{e.streamReaderCancelTimeout=null,this._abortOperatorList({intentState:e,reason:t,force:!0})},i);return}}if(e.streamReader.cancel(new $c(t.message)).catch(()=>{}),e.streamReader=null,!this._transport.destroyed){for(const[i,r]of this._intentStates)if(r===e){this._intentStates.delete(i);break}this.cleanup()}}}get stats(){return this._stats}}oa=new WeakMap,Qr=new WeakMap,gi=new WeakSet,Kc=function(e=!1){if(P(this,gi,Cg).call(this),!f(this,Qr)||this.destroyed)return!1;if(e)return T(this,oa,setTimeout(()=>{T(this,oa,null),P(this,gi,Kc).call(this,!1)},iZ)),!1;for(const{renderTasks:t,operatorList:s}of this._intentStates.values())if(t.size>0||!s.lastChunk)return!1;return this._intentStates.clear(),this.objs.clear(),T(this,Qr,!1),!0},Cg=function(){f(this,oa)&&(clearTimeout(f(this,oa)),T(this,oa,null))};var eo,s0;class pZ{constructor(){M(this,eo,new Map);M(this,s0,Promise.resolve())}postMessage(e,t){const s={data:structuredClone(e,t?{transfer:t}:null)};f(this,s0).then(()=>{for(const[i]of f(this,eo))i.call(this,s)})}addEventListener(e,t,s=null){let i=null;if((s==null?void 0:s.signal)instanceof AbortSignal){const{signal:r}=s;if(r.aborted){qe("LoopbackPort - cannot use an `aborted` signal.");return}const o=()=>this.removeEventListener(e,t);i=()=>r.removeEventListener("abort",o),r.addEventListener("abort",o)}f(this,eo).set(t,i)}removeEventListener(e,t){const s=f(this,eo).get(t);s==null||s(),f(this,eo).delete(t)}terminate(){for(const[,e]of f(this,eo))e==null||e();f(this,eo).clear()}}eo=new WeakMap,s0=new WeakMap;var i0,Nl,Ll,Uh,$g,qh,Tg;const Mt=class Mt{constructor({name:e=null,port:t=null,verbosity:s=W6()}={}){M(this,Uh);var i;if(this.name=e,this.destroyed=!1,this.verbosity=s,this._readyCapability=Promise.withResolvers(),this._port=null,this._webWorker=null,this._messageHandler=null,t){if((i=f(Mt,Ll))!=null&&i.has(t))throw new Error("Cannot use more than one PDFWorker per port.");(f(Mt,Ll)||T(Mt,Ll,new WeakMap)).set(t,this),this._initializeFromPort(t);return}this._initialize()}get promise(){return ls?Promise.all([Pa.promise,this._readyCapability.promise]):this._readyCapability.promise}get port(){return this._port}get messageHandler(){return this._messageHandler}_initializeFromPort(e){this._port=e,this._messageHandler=new xd("main","worker",e),this._messageHandler.on("ready",function(){}),P(this,Uh,$g).call(this)}_initialize(){if(f(Mt,Nl)||f(Mt,qh,Tg)){this._setupFakeWorker();return}let{workerSrc:e}=Mt;try{Mt._isSameOrigin(window.location.href,e)||(e=Mt._createCDNWrapper(new URL(e,window.location).href));const t=new Worker(e,{type:"module"}),s=new xd("main","worker",t),i=()=>{r.abort(),s.destroy(),t.terminate(),this.destroyed?this._readyCapability.reject(new Error("Worker was destroyed")):this._setupFakeWorker()},r=new AbortController;t.addEventListener("error",()=>{this._webWorker||i()},{signal:r.signal}),s.on("test",a=>{if(r.abort(),this.destroyed||!a){i();return}this._messageHandler=s,this._port=t,this._webWorker=t,P(this,Uh,$g).call(this)}),s.on("ready",a=>{if(r.abort(),this.destroyed){i();return}try{o()}catch{this._setupFakeWorker()}});const o=()=>{const a=new Uint8Array;s.send("test",a,[a.buffer])};o();return}catch{N0("The worker has been disabled.")}this._setupFakeWorker()}_setupFakeWorker(){f(Mt,Nl)||(qe("Setting up fake worker."),T(Mt,Nl,!0)),Mt._setupFakeWorkerGlobal.then(e=>{if(this.destroyed){this._readyCapability.reject(new Error("Worker was destroyed"));return}const t=new pZ;this._port=t;const s=`fake${ds(Mt,i0)._++}`,i=new xd(s+"_worker",s,t);e.setup(i,t),this._messageHandler=new xd(s,s+"_worker",t),P(this,Uh,$g).call(this)}).catch(e=>{this._readyCapability.reject(new Error(`Setting up fake worker failed: "${e.message}".`))})}destroy(){var e;this.destroyed=!0,this._webWorker&&(this._webWorker.terminate(),this._webWorker=null),(e=f(Mt,Ll))==null||e.delete(this._port),this._port=null,this._messageHandler&&(this._messageHandler.destroy(),this._messageHandler=null)}static fromPort(e){var s;if(!(e!=null&&e.port))throw new Error("PDFWorker.fromPort - invalid method signature.");const t=(s=f(this,Ll))==null?void 0:s.get(e.port);if(t){if(t._pendingDestroy)throw new Error("PDFWorker.fromPort - the worker is being destroyed.\nPlease remember to await `PDFDocumentLoadingTask.destroy()`-calls.");return t}return new Mt(e)}static get workerSrc(){if(yo.workerSrc)return yo.workerSrc;throw new Error('No "GlobalWorkerOptions.workerSrc" specified.')}static get _setupFakeWorkerGlobal(){return Xe(this,"_setupFakeWorkerGlobal",(async()=>f(this,qh,Tg)?f(this,qh,Tg):(await import(this.workerSrc)).WorkerMessageHandler)())}};i0=new WeakMap,Nl=new WeakMap,Ll=new WeakMap,Uh=new WeakSet,$g=function(){this._readyCapability.resolve(),this._messageHandler.send("configure",{verbosity:this.verbosity})},qh=new WeakSet,Tg=function(){var e;try{return((e=globalThis.pdfjsWorker)==null?void 0:e.WorkerMessageHandler)||null}catch{return null}},M(Mt,qh),M(Mt,i0,0),M(Mt,Nl,!1),M(Mt,Ll),ls&&(T(Mt,Nl,!0),yo.workerSrc||(yo.workerSrc="./pdf.worker.mjs")),Mt._isSameOrigin=(e,t)=>{let s;try{if(s=new URL(e),!s.origin||s.origin==="null")return!1}catch{return!1}const i=new URL(t,s);return s.origin===i.origin},Mt._createCDNWrapper=e=>{const t=`await import("${e}");`;return URL.createObjectURL(new Blob([t],{type:"text/javascript"}))};let dh=Mt;var to,yr,Vh,Wh,vr,Dl,Ad;class mZ{constructor(e,t,s,i,r){M(this,Dl);M(this,to,new Map);M(this,yr,new Map);M(this,Vh,new Map);M(this,Wh,new Map);M(this,vr,null);this.messageHandler=e,this.loadingTask=t,this.commonObjs=new yM,this.fontLoader=new d8({ownerDocument:i.ownerDocument,styleElement:i.styleElement}),this.loadingParams=i.loadingParams,this._params=i,this.canvasFactory=r.canvasFactory,this.filterFactory=r.filterFactory,this.cMapReaderFactory=r.cMapReaderFactory,this.standardFontDataFactory=r.standardFontDataFactory,this.destroyed=!1,this.destroyCapability=null,this._networkStream=s,this._fullReader=null,this._lastProgress=null,this.downloadInfoCapability=Promise.withResolvers(),this.setupMessageHandler()}get annotationStorage(){return Xe(this,"annotationStorage",new Tx)}getRenderingIntent(e,t=Bo.ENABLE,s=null,i=!1,r=!1){let o=Qs.DISPLAY,a=dw;switch(e){case"any":o=Qs.ANY;break;case"display":break;case"print":o=Qs.PRINT;break;default:qe(`getRenderingIntent - invalid intent: ${e}`)}const l=o&Qs.PRINT&&s instanceof KR?s:this.annotationStorage;switch(t){case Bo.DISABLE:o+=Qs.ANNOTATIONS_DISABLE;break;case Bo.ENABLE:break;case Bo.ENABLE_FORMS:o+=Qs.ANNOTATIONS_FORMS;break;case Bo.ENABLE_STORAGE:o+=Qs.ANNOTATIONS_STORAGE,a=l.serializable;break;default:qe(`getRenderingIntent - invalid annotationMode: ${t}`)}i&&(o+=Qs.IS_EDITING),r&&(o+=Qs.OPLIST);const{ids:c,hash:h}=l.modifiedIds,u=[o,a.hash,h];return{renderingIntent:o,cacheKey:u.join("_"),annotationStorageSerializable:a,modifiedIds:c}}destroy(){var s;if(this.destroyCapability)return this.destroyCapability.promise;this.destroyed=!0,this.destroyCapability=Promise.withResolvers(),(s=f(this,vr))==null||s.reject(new Error("Worker was destroyed during onPassword callback"));const e=[];for(const i of f(this,yr).values())e.push(i._destroy());f(this,yr).clear(),f(this,Vh).clear(),f(this,Wh).clear(),this.hasOwnProperty("annotationStorage")&&this.annotationStorage.resetModified();const t=this.messageHandler.sendWithPromise("Terminate",null);return e.push(t),Promise.all(e).then(()=>{var i;this.commonObjs.clear(),this.fontLoader.clear(),f(this,to).clear(),this.filterFactory.destroy(),_w.cleanup(),(i=this._networkStream)==null||i.cancelAllRequests(new $c("Worker was terminated.")),this.messageHandler&&(this.messageHandler.destroy(),this.messageHandler=null),this.destroyCapability.resolve()},this.destroyCapability.reject),this.destroyCapability.promise}setupMessageHandler(){const{messageHandler:e,loadingTask:t}=this;e.on("GetReader",(s,i)=>{yn(this._networkStream,"GetReader - no `IPDFStream` instance available."),this._fullReader=this._networkStream.getFullReader(),this._fullReader.onProgress=r=>{this._lastProgress={loaded:r.loaded,total:r.total}},i.onPull=()=>{this._fullReader.read().then(function({value:r,done:o}){if(o){i.close();return}yn(r instanceof ArrayBuffer,"GetReader - expected an ArrayBuffer."),i.enqueue(new Uint8Array(r),1,[r])}).catch(r=>{i.error(r)})},i.onCancel=r=>{this._fullReader.cancel(r),i.ready.catch(o=>{if(!this.destroyed)throw o})}}),e.on("ReaderHeadersReady",async s=>{var a;await this._fullReader.headersReady;const{isStreamingSupported:i,isRangeSupported:r,contentLength:o}=this._fullReader;return(!i||!r)&&(this._lastProgress&&((a=t.onProgress)==null||a.call(t,this._lastProgress)),this._fullReader.onProgress=l=>{var c;(c=t.onProgress)==null||c.call(t,{loaded:l.loaded,total:l.total})}),{isStreamingSupported:i,isRangeSupported:r,contentLength:o}}),e.on("GetRangeReader",(s,i)=>{yn(this._networkStream,"GetRangeReader - no `IPDFStream` instance available.");const r=this._networkStream.getRangeReader(s.begin,s.end);if(!r){i.close();return}i.onPull=()=>{r.read().then(function({value:o,done:a}){if(a){i.close();return}yn(o instanceof ArrayBuffer,"GetRangeReader - expected an ArrayBuffer."),i.enqueue(new Uint8Array(o),1,[o])}).catch(o=>{i.error(o)})},i.onCancel=o=>{r.cancel(o),i.ready.catch(a=>{if(!this.destroyed)throw a})}}),e.on("GetDoc",({pdfInfo:s})=>{this._numPages=s.numPages,this._htmlForXfa=s.htmlForXfa,delete s.htmlForXfa,t._capability.resolve(new dZ(s,this))}),e.on("DocException",function(s){let i;switch(s.name){case"PasswordException":i=new qb(s.message,s.code);break;case"InvalidPDFException":i=new wR(s.message);break;case"MissingPDFException":i=new Cc(s.message);break;case"UnexpectedResponseException":i=new L0(s.message,s.status);break;case"UnknownErrorException":i=new Vb(s.message,s.details);break;default:Tt("DocException - expected a valid Error.")}t._capability.reject(i)}),e.on("PasswordRequest",s=>{if(T(this,vr,Promise.withResolvers()),t.onPassword){const i=r=>{r instanceof Error?f(this,vr).reject(r):f(this,vr).resolve({password:r})};try{t.onPassword(i,s.code)}catch(r){f(this,vr).reject(r)}}else f(this,vr).reject(new qb(s.message,s.code));return f(this,vr).promise}),e.on("DataLoaded",s=>{var i;(i=t.onProgress)==null||i.call(t,{loaded:s.length,total:s.length}),this.downloadInfoCapability.resolve(s)}),e.on("StartRenderPage",s=>{if(this.destroyed)return;f(this,yr).get(s.pageIndex)._startRenderPage(s.transparency,s.cacheKey)}),e.on("commonobj",([s,i,r])=>{var o;if(this.destroyed||this.commonObjs.has(s))return null;switch(i){case"Font":const{disableFontFace:a,fontExtraProperties:l,pdfBug:c}=this._params;if("error"in r){const p=r.error;qe(`Error during font loading: ${p}`),this.commonObjs.resolve(s,p);break}const h=c&&((o=globalThis.FontInspector)!=null&&o.enabled)?(p,m)=>globalThis.FontInspector.fontAdded(p,m):null,u=new f8(r,{disableFontFace:a,inspectFont:h});this.fontLoader.bind(u).catch(()=>e.sendWithPromise("FontFallback",{id:s})).finally(()=>{!l&&u.data&&(u.data=null),this.commonObjs.resolve(s,u)});break;case"CopyLocalImage":const{imageRef:d}=r;yn(d,"The imageRef must be defined.");for(const p of f(this,yr).values())for(const[,m]of p.objs)if((m==null?void 0:m.ref)===d)return m.dataLen?(this.commonObjs.resolve(s,structuredClone(m)),m.dataLen):null;break;case"FontPath":case"Image":case"Pattern":this.commonObjs.resolve(s,r);break;default:throw new Error(`Got unknown common object type ${i}`)}return null}),e.on("obj",([s,i,r,o])=>{var l;if(this.destroyed)return;const a=f(this,yr).get(i);if(!a.objs.has(s)){if(a._intentStates.size===0){(l=o==null?void 0:o.bitmap)==null||l.close();return}switch(r){case"Image":a.objs.resolve(s,o),(o==null?void 0:o.dataLen)>H6&&(a._maybeCleanupAfterRender=!0);break;case"Pattern":a.objs.resolve(s,o);break;default:throw new Error(`Got unknown object type ${r}`)}}}),e.on("DocProgress",s=>{var i;this.destroyed||(i=t.onProgress)==null||i.call(t,{loaded:s.loaded,total:s.total})}),e.on("FetchBuiltInCMap",async s=>{if(this.destroyed)throw new Error("Worker was destroyed.");if(!this.cMapReaderFactory)throw new Error("CMapReaderFactory not initialized, see the `useWorkerFetch` parameter.");return this.cMapReaderFactory.fetch(s)}),e.on("FetchStandardFontData",async s=>{if(this.destroyed)throw new Error("Worker was destroyed.");if(!this.standardFontDataFactory)throw new Error("StandardFontDataFactory not initialized, see the `useWorkerFetch` parameter.");return this.standardFontDataFactory.fetch(s)})}getData(){return this.messageHandler.sendWithPromise("GetData",null)}saveDocument(){var s;this.annotationStorage.size<=0&&qe("saveDocument called while `annotationStorage` is empty, please use the getData-method instead.");const{map:e,transfer:t}=this.annotationStorage.serializable;return this.messageHandler.sendWithPromise("SaveDocument",{isPureXfa:!!this._htmlForXfa,numPages:this._numPages,annotationStorage:e,filename:((s=this._fullReader)==null?void 0:s.filename)??null},t).finally(()=>{this.annotationStorage.resetModified()})}getPage(e){if(!Number.isInteger(e)||e<=0||e>this._numPages)return Promise.reject(new Error("Invalid page request."));const t=e-1,s=f(this,Vh).get(t);if(s)return s;const i=this.messageHandler.sendWithPromise("GetPage",{pageIndex:t}).then(r=>{if(this.destroyed)throw new Error("Transport destroyed");r.refStr&&f(this,Wh).set(r.refStr,e);const o=new fZ(t,r,this,this._params.pdfBug);return f(this,yr).set(t,o),o});return f(this,Vh).set(t,i),i}getPageIndex(e){return aE(e)?this.messageHandler.sendWithPromise("GetPageIndex",{num:e.num,gen:e.gen}):Promise.reject(new Error("Invalid pageIndex request."))}getAnnotations(e,t){return this.messageHandler.sendWithPromise("GetAnnotations",{pageIndex:e,intent:t})}getFieldObjects(){return P(this,Dl,Ad).call(this,"GetFieldObjects")}hasJSActions(){return P(this,Dl,Ad).call(this,"HasJSActions")}getCalculationOrderIds(){return this.messageHandler.sendWithPromise("GetCalculationOrderIds",null)}getDestinations(){return this.messageHandler.sendWithPromise("GetDestinations",null)}getDestination(e){return typeof e!="string"?Promise.reject(new Error("Invalid destination request.")):this.messageHandler.sendWithPromise("GetDestination",{id:e})}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 P(this,Dl,Ad).call(this,"GetDocJSActions")}getPageJSActions(e){return this.messageHandler.sendWithPromise("GetPageJSActions",{pageIndex:e})}getStructTree(e){return this.messageHandler.sendWithPromise("GetStructTree",{pageIndex:e})}getOutline(){return this.messageHandler.sendWithPromise("GetOutline",null)}getOptionalContentConfig(e){return P(this,Dl,Ad).call(this,"GetOptionalContentConfig").then(t=>new N8(t,e))}getPermissions(){return this.messageHandler.sendWithPromise("GetPermissions",null)}getMetadata(){const e="GetMetadata",t=f(this,to).get(e);if(t)return t;const s=this.messageHandler.sendWithPromise(e,null).then(i=>{var r,o;return{info:i[0],metadata:i[1]?new I8(i[1]):null,contentDispositionFilename:((r=this._fullReader)==null?void 0:r.filename)??null,contentLength:((o=this._fullReader)==null?void 0:o.contentLength)??null}});return f(this,to).set(e,s),s}getMarkInfo(){return this.messageHandler.sendWithPromise("GetMarkInfo",null)}async startCleanup(e=!1){if(!this.destroyed){await this.messageHandler.sendWithPromise("Cleanup",null);for(const t of f(this,yr).values())if(!t.cleanup())throw new Error(`startCleanup: Page ${t.pageNumber} is currently rendering.`);this.commonObjs.clear(),e||this.fontLoader.clear(),f(this,to).clear(),this.filterFactory.destroy(!0),_w.cleanup()}}cachedPageNumber(e){if(!aE(e))return null;const t=e.gen===0?`${e.num}R`:`${e.num}R${e.gen}`;return f(this,Wh).get(t)??null}}to=new WeakMap,yr=new WeakMap,Vh=new WeakMap,Wh=new WeakMap,vr=new WeakMap,Dl=new WeakSet,Ad=function(e,t=null){const s=f(this,to).get(e);if(s)return s;const i=this.messageHandler.sendWithPromise(e,t);return f(this,to).set(e,i),i};const Dm=Symbol("INITIAL_DATA");var ji,sp,kw;class yM{constructor(){M(this,sp);M(this,ji,Object.create(null))}get(e,t=null){if(t){const i=P(this,sp,kw).call(this,e);return i.promise.then(()=>t(i.data)),null}const s=f(this,ji)[e];if(!s||s.data===Dm)throw new Error(`Requesting object that isn't resolved yet ${e}.`);return s.data}has(e){const t=f(this,ji)[e];return!!t&&t.data!==Dm}resolve(e,t=null){const s=P(this,sp,kw).call(this,e);s.data=t,s.resolve()}clear(){var e;for(const t in f(this,ji)){const{data:s}=f(this,ji)[t];(e=s==null?void 0:s.bitmap)==null||e.close()}T(this,ji,Object.create(null))}*[Symbol.iterator](){for(const e in f(this,ji)){const{data:t}=f(this,ji)[e];t!==Dm&&(yield[e,t])}}}ji=new WeakMap,sp=new WeakSet,kw=function(e){var t;return(t=f(this,ji))[e]||(t[e]={...Promise.withResolvers(),data:Dm})};var aa;class gZ{constructor(e){M(this,aa,null);T(this,aa,e),this.onContinue=null}get promise(){return f(this,aa).capability.promise}cancel(e=0){f(this,aa).cancel(null,e)}get separateAnnots(){const{separateAnnots:e}=f(this,aa).operatorList;if(!e)return!1;const{annotationCanvasMap:t}=f(this,aa);return e.form||e.canvas&&(t==null?void 0:t.size)>0}}aa=new WeakMap;var la,jl;const al=class al{constructor({callback:e,params:t,objs:s,commonObjs:i,annotationCanvasMap:r,operatorList:o,pageIndex:a,canvasFactory:l,filterFactory:c,useRequestAnimationFrame:h=!1,pdfBug:u=!1,pageColors:d=null}){M(this,la,null);this.callback=e,this.params=t,this.objs=s,this.commonObjs=i,this.annotationCanvasMap=r,this.operatorListIdx=null,this.operatorList=o,this._pageIndex=a,this.canvasFactory=l,this.filterFactory=c,this._pdfBug=u,this.pageColors=d,this.running=!1,this.graphicsReadyCallback=null,this.graphicsReady=!1,this._useRequestAnimationFrame=h===!0&&typeof window<"u",this.cancelled=!1,this.capability=Promise.withResolvers(),this.task=new gZ(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=t.canvasContext.canvas}get completed(){return this.capability.promise.catch(function(){})}initializeGraphics({transparency:e=!1,optionalContentConfig:t}){var a,l;if(this.cancelled)return;if(this._canvas){if(f(al,jl).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.");f(al,jl).add(this._canvas)}this._pdfBug&&((a=globalThis.StepperManager)!=null&&a.enabled)&&(this.stepper=globalThis.StepperManager.create(this._pageIndex),this.stepper.init(this.operatorList),this.stepper.nextBreakPoint=this.stepper.getNextBreakPoint());const{canvasContext:s,viewport:i,transform:r,background:o}=this.params;this.gfx=new uh(s,this.commonObjs,this.objs,this.canvasFactory,this.filterFactory,{optionalContentConfig:t},this.annotationCanvasMap,this.pageColors),this.gfx.beginDrawing({transform:r,viewport:i,transparency:e,background:o}),this.operatorListIdx=0,this.graphicsReady=!0,(l=this.graphicsReadyCallback)==null||l.call(this)}cancel(e=null,t=0){var s;this.running=!1,this.cancelled=!0,(s=this.gfx)==null||s.endDrawing(),f(this,la)&&(window.cancelAnimationFrame(f(this,la)),T(this,la,null)),f(al,jl).delete(this._canvas),this.callback(e||new kx(`Rendering cancelled, page ${this._pageIndex+1}`,t))}operatorListChanged(){var e;if(!this.graphicsReady){this.graphicsReadyCallback||(this.graphicsReadyCallback=this._continueBound);return}(e=this.stepper)==null||e.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?T(this,la,window.requestAnimationFrame(()=>{T(this,la,null),this._nextBound().catch(this._cancelBound)})):Promise.resolve().then(this._nextBound).catch(this._cancelBound)}async _next(){this.cancelled||(this.operatorListIdx=this.gfx.executeOperatorList(this.operatorList,this.operatorListIdx,this._continueBound,this.stepper),this.operatorListIdx===this.operatorList.argsArray.length&&(this.running=!1,this.operatorList.lastChunk&&(this.gfx.endDrawing(),f(al,jl).delete(this._canvas),this.callback())))}};la=new WeakMap,jl=new WeakMap,M(al,jl,new WeakSet);let Ew=al;const yZ="4.8.69",vZ="3634dab10";function lE(n){return Math.floor(Math.max(0,Math.min(1,n))*255).toString(16).padStart(2,"0")}function rd(n){return Math.max(0,Math.min(255,255*n))}class cE{static CMYK_G([e,t,s,i]){return["G",1-Math.min(1,.3*e+.59*s+.11*t+i)]}static G_CMYK([e]){return["CMYK",0,0,0,1-e]}static G_RGB([e]){return["RGB",e,e,e]}static G_rgb([e]){return e=rd(e),[e,e,e]}static G_HTML([e]){const t=lE(e);return`#${t}${t}${t}`}static RGB_G([e,t,s]){return["G",.3*e+.59*t+.11*s]}static RGB_rgb(e){return e.map(rd)}static RGB_HTML(e){return`#${e.map(lE).join("")}`}static T_HTML(){return"#00000000"}static T_rgb(){return[null]}static CMYK_RGB([e,t,s,i]){return["RGB",1-Math.min(1,e+i),1-Math.min(1,s+i),1-Math.min(1,t+i)]}static CMYK_rgb([e,t,s,i]){return[rd(1-Math.min(1,e+i)),rd(1-Math.min(1,s+i)),rd(1-Math.min(1,t+i))]}static CMYK_HTML(e){const t=this.CMYK_RGB(e).slice(1);return this.RGB_HTML(t)}static RGB_CMYK([e,t,s]){const i=1-e,r=1-t,o=1-s,a=Math.min(i,r,o);return["CMYK",i,r,o,a]}}class bZ{create(e,t,s=!1){if(e<=0||t<=0)throw new Error("Invalid SVG dimensions");const i=this._createSVG("svg:svg");return i.setAttribute("version","1.1"),s||(i.setAttribute("width",`${e}px`),i.setAttribute("height",`${t}px`)),i.setAttribute("preserveAspectRatio","none"),i.setAttribute("viewBox",`0 0 ${e} ${t}`),i}createElement(e){if(typeof e!="string")throw new Error("Invalid SVG element type");return this._createSVG(e)}_createSVG(e){Tt("Abstract method `_createSVG` called.")}}class Ox extends bZ{_createSVG(e){return document.createElementNS(Ur,e)}}class vM{static setupStorage(e,t,s,i,r){const o=i.getValue(t,{value:null});switch(s.name){case"textarea":if(o.value!==null&&(e.textContent=o.value),r==="print")break;e.addEventListener("input",a=>{i.setValue(t,{value:a.target.value})});break;case"input":if(s.attributes.type==="radio"||s.attributes.type==="checkbox"){if(o.value===s.attributes.xfaOn?e.setAttribute("checked",!0):o.value===s.attributes.xfaOff&&e.removeAttribute("checked"),r==="print")break;e.addEventListener("change",a=>{i.setValue(t,{value:a.target.checked?a.target.getAttribute("xfaOn"):a.target.getAttribute("xfaOff")})})}else{if(o.value!==null&&e.setAttribute("value",o.value),r==="print")break;e.addEventListener("input",a=>{i.setValue(t,{value:a.target.value})})}break;case"select":if(o.value!==null){e.setAttribute("value",o.value);for(const a of s.children)a.attributes.value===o.value?a.attributes.selected=!0:a.attributes.hasOwnProperty("selected")&&delete a.attributes.selected}e.addEventListener("input",a=>{const l=a.target.options,c=l.selectedIndex===-1?"":l[l.selectedIndex].value;i.setValue(t,{value:c})});break}}static setAttributes({html:e,element:t,storage:s=null,intent:i,linkService:r}){const{attributes:o}=t,a=e instanceof HTMLAnchorElement;o.type==="radio"&&(o.name=`${o.name}-${i}`);for(const[l,c]of Object.entries(o))if(c!=null)switch(l){case"class":c.length&&e.setAttribute(l,c.join(" "));break;case"dataId":break;case"id":e.setAttribute("data-element-id",c);break;case"style":Object.assign(e.style,c);break;case"textContent":e.textContent=c;break;default:(!a||l!=="href"&&l!=="newWindow")&&e.setAttribute(l,c)}a&&r.addLinkAttributes(e,o.href,o.newWindow),s&&o.dataId&&this.setupStorage(e,o.dataId,t,s)}static render(e){var u,d;const t=e.annotationStorage,s=e.linkService,i=e.xfaHtml,r=e.intent||"display",o=document.createElement(i.name);i.attributes&&this.setAttributes({html:o,element:i,intent:r,linkService:s});const a=r!=="richText",l=e.div;if(l.append(o),e.viewport){const p=`matrix(${e.viewport.transform.join(",")})`;l.style.transform=p}a&&l.setAttribute("class","xfaLayer xfaFont");const c=[];if(i.children.length===0){if(i.value){const p=document.createTextNode(i.value);o.append(p),a&&hf.shouldBuildText(i.name)&&c.push(p)}return{textDivs:c}}const h=[[i,-1,o]];for(;h.length>0;){const[p,m,y]=h.at(-1);if(m+1===p.children.length){h.pop();continue}const v=p.children[++h.at(-1)[1]];if(v===null)continue;const{name:g}=v;if(g==="#text"){const _=document.createTextNode(v.value);c.push(_),y.append(_);continue}const b=(u=v==null?void 0:v.attributes)!=null&&u.xmlns?document.createElementNS(v.attributes.xmlns,g):document.createElement(g);if(y.append(b),v.attributes&&this.setAttributes({html:b,element:v,storage:t,intent:r,linkService:s}),((d=v.children)==null?void 0:d.length)>0)h.push([v,-1,b]);else if(v.value){const _=document.createTextNode(v.value);a&&hf.shouldBuildText(g)&&c.push(_),b.append(_)}}for(const p of l.querySelectorAll(".xfaNonInteractive input, .xfaNonInteractive textarea"))p.setAttribute("readOnly",!0);return{textDivs:c}}static update(e){const t=`matrix(${e.viewport.transform.join(",")})`;e.div.style.transform=t,e.div.hidden=!1}}const sm=1e3,wZ=9,gc=new WeakSet;function Ao(n){return{width:n[2]-n[0],height:n[3]-n[1]}}class _Z{static create(e){switch(e.data.annotationType){case hn.LINK:return new bM(e);case hn.TEXT:return new SZ(e);case hn.WIDGET:switch(e.data.fieldType){case"Tx":return new xZ(e);case"Btn":return e.data.radioButton?new SM(e):e.data.checkBox?new kZ(e):new EZ(e);case"Ch":return new CZ(e);case"Sig":return new AZ(e)}return new Tc(e);case hn.POPUP:return new $w(e);case hn.FREETEXT:return new CM(e);case hn.LINE:return new TZ(e);case hn.SQUARE:return new PZ(e);case hn.CIRCLE:return new RZ(e);case hn.POLYLINE:return new $M(e);case hn.CARET:return new IZ(e);case hn.INK:return new Nx(e);case hn.POLYGON:return new MZ(e);case hn.HIGHLIGHT:return new TM(e);case hn.UNDERLINE:return new OZ(e);case hn.SQUIGGLY:return new NZ(e);case hn.STRIKEOUT:return new LZ(e);case hn.STAMP:return new PM(e);case hn.FILEATTACHMENT:return new DZ(e);default:return new en(e)}}}var Fl,Gh,Kh,ip,Cw;const mA=class mA{constructor(e,{isRenderable:t=!1,ignoreBorder:s=!1,createQuadrilaterals:i=!1}={}){M(this,ip);M(this,Fl,null);M(this,Gh,!1);M(this,Kh,null);this.isRenderable=t,this.data=e.data,this.layer=e.layer,this.linkService=e.linkService,this.downloadManager=e.downloadManager,this.imageResourcesPath=e.imageResourcesPath,this.renderForms=e.renderForms,this.svgFactory=e.svgFactory,this.annotationStorage=e.annotationStorage,this.enableScripting=e.enableScripting,this.hasJSActions=e.hasJSActions,this._fieldObjects=e.fieldObjects,this.parent=e.parent,t&&(this.container=this._createContainer(s)),i&&this._createQuadrilaterals()}static _hasPopupData({titleObj:e,contentsObj:t,richText:s}){return!!(e!=null&&e.str||t!=null&&t.str||s!=null&&s.str)}get _isEditable(){return this.data.isEditable}get hasPopupData(){return mA._hasPopupData(this.data)}updateEdited(e){var s;if(!this.container)return;f(this,Fl)||T(this,Fl,{rect:this.data.rect.slice(0)});const{rect:t}=e;t&&P(this,ip,Cw).call(this,t),(s=f(this,Kh))==null||s.popup.updateEdited(e)}resetEdited(){var e;f(this,Fl)&&(P(this,ip,Cw).call(this,f(this,Fl).rect),(e=f(this,Kh))==null||e.popup.resetEdited(),T(this,Fl,null))}_createContainer(e){const{data:t,parent:{page:s,viewport:i}}=this,r=document.createElement("section");r.setAttribute("data-annotation-id",t.id),this instanceof Tc||(r.tabIndex=sm);const{style:o}=r;if(o.zIndex=this.parent.zIndex++,t.alternativeText&&(r.title=t.alternativeText),t.noRotate&&r.classList.add("norotate"),!t.rect||this instanceof $w){const{rotation:y}=t;return!t.hasOwnCanvas&&y!==0&&this.setRotation(y,r),r}const{width:a,height:l}=Ao(t.rect);if(!e&&t.borderStyle.width>0){o.borderWidth=`${t.borderStyle.width}px`;const y=t.borderStyle.horizontalCornerRadius,v=t.borderStyle.verticalCornerRadius;if(y>0||v>0){const b=`calc(${y}px * var(--scale-factor)) / calc(${v}px * var(--scale-factor))`;o.borderRadius=b}else if(this instanceof SM){const b=`calc(${a}px * var(--scale-factor)) / calc(${l}px * var(--scale-factor))`;o.borderRadius=b}switch(t.borderStyle.style){case sd.SOLID:o.borderStyle="solid";break;case sd.DASHED:o.borderStyle="dashed";break;case sd.BEVELED:qe("Unimplemented border style: beveled");break;case sd.INSET:qe("Unimplemented border style: inset");break;case sd.UNDERLINE:o.borderBottomStyle="solid";break}const g=t.borderColor||null;g?(T(this,Gh,!0),o.borderColor=Se.makeHexColor(g[0]|0,g[1]|0,g[2]|0)):o.borderWidth=0}const c=Se.normalizeRect([t.rect[0],s.view[3]-t.rect[1]+s.view[1],t.rect[2],s.view[3]-t.rect[3]+s.view[1]]),{pageWidth:h,pageHeight:u,pageX:d,pageY:p}=i.rawDims;o.left=`${100*(c[0]-d)/h}%`,o.top=`${100*(c[1]-p)/u}%`;const{rotation:m}=t;return t.hasOwnCanvas||m===0?(o.width=`${100*a/h}%`,o.height=`${100*l/u}%`):this.setRotation(m,r),r}setRotation(e,t=this.container){if(!this.data.rect)return;const{pageWidth:s,pageHeight:i}=this.parent.viewport.rawDims,{width:r,height:o}=Ao(this.data.rect);let a,l;e%180===0?(a=100*r/s,l=100*o/i):(a=100*o/s,l=100*r/i),t.style.width=`${a}%`,t.style.height=`${l}%`,t.setAttribute("data-main-rotation",(360-e)%360)}get _commonActions(){const e=(t,s,i)=>{const r=i.detail[t],o=r[0],a=r.slice(1);i.target.style[s]=cE[`${o}_HTML`](a),this.annotationStorage.setValue(this.data.id,{[s]:cE[`${o}_rgb`](a)})};return Xe(this,"_commonActions",{display:t=>{const{display:s}=t.detail,i=s%2===1;this.container.style.visibility=i?"hidden":"visible",this.annotationStorage.setValue(this.data.id,{noView:i,noPrint:s===1||s===2})},print:t=>{this.annotationStorage.setValue(this.data.id,{noPrint:!t.detail.print})},hidden:t=>{const{hidden:s}=t.detail;this.container.style.visibility=s?"hidden":"visible",this.annotationStorage.setValue(this.data.id,{noPrint:s,noView:s})},focus:t=>{setTimeout(()=>t.target.focus({preventScroll:!1}),0)},userName:t=>{t.target.title=t.detail.userName},readonly:t=>{t.target.disabled=t.detail.readonly},required:t=>{this._setRequired(t.target,t.detail.required)},bgColor:t=>{e("bgColor","backgroundColor",t)},fillColor:t=>{e("fillColor","backgroundColor",t)},fgColor:t=>{e("fgColor","color",t)},textColor:t=>{e("textColor","color",t)},borderColor:t=>{e("borderColor","borderColor",t)},strokeColor:t=>{e("strokeColor","borderColor",t)},rotation:t=>{const s=t.detail.rotation;this.setRotation(s),this.annotationStorage.setValue(this.data.id,{rotation:s})}})}_dispatchEventFromSandbox(e,t){const s=this._commonActions;for(const i of Object.keys(t.detail)){const r=e[i]||s[i];r==null||r(t)}}_setDefaultPropertiesFromJS(e){if(!this.enableScripting)return;const t=this.annotationStorage.getRawValue(this.data.id);if(!t)return;const s=this._commonActions;for(const[i,r]of Object.entries(t)){const o=s[i];if(o){const a={detail:{[i]:r},target:e};o(a),delete t[i]}}}_createQuadrilaterals(){if(!this.container)return;const{quadPoints:e}=this.data;if(!e)return;const[t,s,i,r]=this.data.rect.map(y=>Math.fround(y));if(e.length===8){const[y,v,g,b]=e.subarray(2,6);if(i===y&&r===v&&t===g&&s===b)return}const{style:o}=this.container;let a;if(f(this,Gh)){const{borderColor:y,borderWidth:v}=o;o.borderWidth=0,a=["url('data:image/svg+xml;utf8,",'',``],this.container.classList.add("hasBorder")}const l=i-t,c=r-s,{svgFactory:h}=this,u=h.createElement("svg");u.classList.add("quadrilateralsContainer"),u.setAttribute("width",0),u.setAttribute("height",0);const d=h.createElement("defs");u.append(d);const p=h.createElement("clipPath"),m=`clippath_${this.data.id}`;p.setAttribute("id",m),p.setAttribute("clipPathUnits","objectBoundingBox"),d.append(p);for(let y=2,v=e.length;y`)}f(this,Gh)&&(a.push("')"),o.backgroundImage=a.join("")),this.container.append(u),this.container.style.clipPath=`url(#${m})`}_createPopup(){const{data:e}=this,t=T(this,Kh,new $w({data:{color:e.color,titleObj:e.titleObj,modificationDate:e.modificationDate,contentsObj:e.contentsObj,richText:e.richText,parentRect:e.rect,borderStyle:0,id:`popup_${e.id}`,rotation:e.rotation},parent:this.parent,elements:[this]}));this.parent.div.append(t.render())}render(){Tt("Abstract method `AnnotationElement.render` called")}_getElementsByName(e,t=null){const s=[];if(this._fieldObjects){const i=this._fieldObjects[e];if(i)for(const{page:r,id:o,exportValues:a}of i){if(r===-1||o===t)continue;const l=typeof a=="string"?a:null,c=document.querySelector(`[data-element-id="${o}"]`);if(c&&!gc.has(c)){qe(`_getElementsByName - element not allowed: ${o}`);continue}s.push({id:o,exportValue:l,domElement:c})}return s}for(const i of document.getElementsByName(e)){const{exportValue:r}=i,o=i.getAttribute("data-element-id");o!==t&&gc.has(i)&&s.push({id:o,exportValue:r,domElement:i})}return s}show(){var e;this.container&&(this.container.hidden=!1),(e=this.popup)==null||e.maybeShow()}hide(){var e;this.container&&(this.container.hidden=!0),(e=this.popup)==null||e.forceHide()}getElementsToTriggerPopup(){return this.container}addHighlightArea(){const e=this.getElementsToTriggerPopup();if(Array.isArray(e))for(const t of e)t.classList.add("highlightArea");else e.classList.add("highlightArea")}_editOnDoubleClick(){if(!this._isEditable)return;const{annotationEditorType:e,data:{id:t}}=this;this.container.addEventListener("dblclick",()=>{var s;(s=this.linkService.eventBus)==null||s.dispatch("switchannotationeditormode",{source:this,mode:e,editId:t})})}};Fl=new WeakMap,Gh=new WeakMap,Kh=new WeakMap,ip=new WeakSet,Cw=function(e){const{container:{style:t},data:{rect:s,rotation:i},parent:{viewport:{rawDims:{pageWidth:r,pageHeight:o,pageX:a,pageY:l}}}}=this;s==null||s.splice(0,4,...e);const{width:c,height:h}=Ao(e);t.left=`${100*(e[0]-a)/r}%`,t.top=`${100*(o-e[3]+l)/o}%`,i===0?(t.width=`${100*c/r}%`,t.height=`${100*h/o}%`):this.setRotation(i)};let en=mA;var ti,Ka,wM,_M;class bM extends en{constructor(t,s=null){super(t,{isRenderable:!0,ignoreBorder:!!(s!=null&&s.ignoreBorder),createQuadrilaterals:!0});M(this,ti);this.isTooltipOnly=t.data.isTooltipOnly}render(){const{data:t,linkService:s}=this,i=document.createElement("a");i.setAttribute("data-element-id",t.id);let r=!1;return t.url?(s.addLinkAttributes(i,t.url,t.newWindow),r=!0):t.action?(this._bindNamedAction(i,t.action),r=!0):t.attachment?(P(this,ti,wM).call(this,i,t.attachment,t.attachmentDest),r=!0):t.setOCGState?(P(this,ti,_M).call(this,i,t.setOCGState),r=!0):t.dest?(this._bindLink(i,t.dest),r=!0):(t.actions&&(t.actions.Action||t.actions["Mouse Up"]||t.actions["Mouse Down"])&&this.enableScripting&&this.hasJSActions&&(this._bindJSAction(i,t),r=!0),t.resetForm?(this._bindResetFormAction(i,t.resetForm),r=!0):this.isTooltipOnly&&!r&&(this._bindLink(i,""),r=!0)),this.container.classList.add("linkAnnotation"),r&&this.container.append(i),this.container}_bindLink(t,s){t.href=this.linkService.getDestinationHash(s),t.onclick=()=>(s&&this.linkService.goToDestination(s),!1),(s||s==="")&&P(this,ti,Ka).call(this)}_bindNamedAction(t,s){t.href=this.linkService.getAnchorUrl(""),t.onclick=()=>(this.linkService.executeNamedAction(s),!1),P(this,ti,Ka).call(this)}_bindJSAction(t,s){t.href=this.linkService.getAnchorUrl("");const i=new Map([["Action","onclick"],["Mouse Up","onmouseup"],["Mouse Down","onmousedown"]]);for(const r of Object.keys(s.actions)){const o=i.get(r);o&&(t[o]=()=>{var a;return(a=this.linkService.eventBus)==null||a.dispatch("dispatcheventinsandbox",{source:this,detail:{id:s.id,name:r}}),!1})}t.onclick||(t.onclick=()=>!1),P(this,ti,Ka).call(this)}_bindResetFormAction(t,s){const i=t.onclick;if(i||(t.href=this.linkService.getAnchorUrl("")),P(this,ti,Ka).call(this),!this._fieldObjects){qe('_bindResetFormAction - "resetForm" action not supported, ensure that the `fieldObjects` parameter is provided.'),i||(t.onclick=()=>!1);return}t.onclick=()=>{var u;i==null||i();const{fields:r,refs:o,include:a}=s,l=[];if(r.length!==0||o.length!==0){const d=new Set(o);for(const p of r){const m=this._fieldObjects[p]||[];for(const{id:y}of m)d.add(y)}for(const p of Object.values(this._fieldObjects))for(const m of p)d.has(m.id)===a&&l.push(m)}else for(const d of Object.values(this._fieldObjects))l.push(...d);const c=this.annotationStorage,h=[];for(const d of l){const{id:p}=d;switch(h.push(p),d.type){case"text":{const y=d.defaultValue||"";c.setValue(p,{value:y});break}case"checkbox":case"radiobutton":{const y=d.defaultValue===d.exportValues;c.setValue(p,{value:y});break}case"combobox":case"listbox":{const y=d.defaultValue||"";c.setValue(p,{value:y});break}default:continue}const m=document.querySelector(`[data-element-id="${p}"]`);if(m){if(!gc.has(m)){qe(`_bindResetFormAction - element not allowed: ${p}`);continue}}else continue;m.dispatchEvent(new Event("resetform"))}return this.enableScripting&&((u=this.linkService.eventBus)==null||u.dispatch("dispatcheventinsandbox",{source:this,detail:{id:"app",ids:h,name:"ResetForm"}})),!1}}}ti=new WeakSet,Ka=function(){this.container.setAttribute("data-internal-link","")},wM=function(t,s,i=null){t.href=this.linkService.getAnchorUrl(""),s.description&&(t.title=s.description),t.onclick=()=>{var r;return(r=this.downloadManager)==null||r.openOrDownloadData(s.content,s.filename,i),!1},P(this,ti,Ka).call(this)},_M=function(t,s){t.href=this.linkService.getAnchorUrl(""),t.onclick=()=>(this.linkService.executeSetOCGState(s),!1),P(this,ti,Ka).call(this)};class SZ extends en{constructor(e){super(e,{isRenderable:!0})}render(){this.container.classList.add("textAnnotation");const e=document.createElement("img");return e.src=this.imageResourcesPath+"annotation-"+this.data.name.toLowerCase()+".svg",e.setAttribute("data-l10n-id","pdfjs-text-annotation-type"),e.setAttribute("data-l10n-args",JSON.stringify({type:this.data.name})),!this.data.popupRef&&this.hasPopupData&&this._createPopup(),this.container.append(e),this.container}}class Tc extends en{render(){return this.container}showElementAndHideCanvas(e){var t;this.data.hasOwnCanvas&&(((t=e.previousSibling)==null?void 0:t.nodeName)==="CANVAS"&&(e.previousSibling.hidden=!0),e.hidden=!1)}_getKeyModifier(e){return bs.platform.isMac?e.metaKey:e.ctrlKey}_setEventListener(e,t,s,i,r){s.includes("mouse")?e.addEventListener(s,o=>{var a;(a=this.linkService.eventBus)==null||a.dispatch("dispatcheventinsandbox",{source:this,detail:{id:this.data.id,name:i,value:r(o),shift:o.shiftKey,modifier:this._getKeyModifier(o)}})}):e.addEventListener(s,o=>{var a;if(s==="blur"){if(!t.focused||!o.relatedTarget)return;t.focused=!1}else if(s==="focus"){if(t.focused)return;t.focused=!0}r&&((a=this.linkService.eventBus)==null||a.dispatch("dispatcheventinsandbox",{source:this,detail:{id:this.data.id,name:i,value:r(o)}}))})}_setEventListeners(e,t,s,i){var r,o,a;for(const[l,c]of s)(c==="Action"||(r=this.data.actions)!=null&&r[c])&&((c==="Focus"||c==="Blur")&&(t||(t={focused:!1})),this._setEventListener(e,t,l,c,i),c==="Focus"&&!((o=this.data.actions)!=null&&o.Blur)?this._setEventListener(e,t,"blur","Blur",null):c==="Blur"&&!((a=this.data.actions)!=null&&a.Focus)&&this._setEventListener(e,t,"focus","Focus",null))}_setBackgroundColor(e){const t=this.data.backgroundColor||null;e.style.backgroundColor=t===null?"transparent":Se.makeHexColor(t[0],t[1],t[2])}_setTextStyle(e){const t=["left","center","right"],{fontColor:s}=this.data.defaultAppearanceData,i=this.data.defaultAppearanceData.fontSize||wZ,r=e.style;let o;const a=2,l=c=>Math.round(10*c)/10;if(this.data.multiLine){const c=Math.abs(this.data.rect[3]-this.data.rect[1]-a),h=Math.round(c/($v*i))||1,u=c/h;o=Math.min(i,l(u/$v))}else{const c=Math.abs(this.data.rect[3]-this.data.rect[1]-a);o=Math.min(i,l(c/$v))}r.fontSize=`calc(${o}px * var(--scale-factor))`,r.color=Se.makeHexColor(s[0],s[1],s[2]),this.data.textAlignment!==null&&(r.textAlign=t[this.data.textAlignment])}_setRequired(e,t){t?e.setAttribute("required",!0):e.removeAttribute("required"),e.setAttribute("aria-required",t)}}class xZ extends Tc{constructor(e){const t=e.renderForms||e.data.hasOwnCanvas||!e.data.hasAppearance&&!!e.data.fieldValue;super(e,{isRenderable:t})}setPropertyOnSiblings(e,t,s,i){const r=this.annotationStorage;for(const o of this._getElementsByName(e.name,e.id))o.domElement&&(o.domElement[t]=s),r.setValue(o.id,{[i]:s})}render(){var i,r;const e=this.annotationStorage,t=this.data.id;this.container.classList.add("textWidgetAnnotation");let s=null;if(this.renderForms){const o=e.getValue(t,{value:this.data.fieldValue});let a=o.value||"";const l=e.getValue(t,{charLimit:this.data.maxLen}).charLimit;l&&a.length>l&&(a=a.slice(0,l));let c=o.formattedValue||((i=this.data.textContent)==null?void 0:i.join(` +`))||null;c&&this.data.comb&&(c=c.replaceAll(/\s+/g,""));const h={userValue:a,formattedValue:c,lastCommittedValue:null,commitKey:1,focused:!1};this.data.multiLine?(s=document.createElement("textarea"),s.textContent=c??a,this.data.doNotScroll&&(s.style.overflowY="hidden")):(s=document.createElement("input"),s.type="text",s.setAttribute("value",c??a),this.data.doNotScroll&&(s.style.overflowX="hidden")),this.data.hasOwnCanvas&&(s.hidden=!0),gc.add(s),s.setAttribute("data-element-id",t),s.disabled=this.data.readOnly,s.name=this.data.fieldName,s.tabIndex=sm,this._setRequired(s,this.data.required),l&&(s.maxLength=l),s.addEventListener("input",d=>{e.setValue(t,{value:d.target.value}),this.setPropertyOnSiblings(s,"value",d.target.value,"value"),h.formattedValue=null}),s.addEventListener("resetform",d=>{const p=this.data.defaultFieldValue??"";s.value=h.userValue=p,h.formattedValue=null});let u=d=>{const{formattedValue:p}=h;p!=null&&(d.target.value=p),d.target.scrollLeft=0};if(this.enableScripting&&this.hasJSActions){s.addEventListener("focus",p=>{var y;if(h.focused)return;const{target:m}=p;h.userValue&&(m.value=h.userValue),h.lastCommittedValue=m.value,h.commitKey=1,(y=this.data.actions)!=null&&y.Focus||(h.focused=!0)}),s.addEventListener("updatefromsandbox",p=>{this.showElementAndHideCanvas(p.target);const m={value(y){h.userValue=y.detail.value??"",e.setValue(t,{value:h.userValue.toString()}),y.target.value=h.userValue},formattedValue(y){const{formattedValue:v}=y.detail;h.formattedValue=v,v!=null&&y.target!==document.activeElement&&(y.target.value=v),e.setValue(t,{formattedValue:v})},selRange(y){y.target.setSelectionRange(...y.detail.selRange)},charLimit:y=>{var _;const{charLimit:v}=y.detail,{target:g}=y;if(v===0){g.removeAttribute("maxLength");return}g.setAttribute("maxLength",v);let b=h.userValue;!b||b.length<=v||(b=b.slice(0,v),g.value=h.userValue=b,e.setValue(t,{value:b}),(_=this.linkService.eventBus)==null||_.dispatch("dispatcheventinsandbox",{source:this,detail:{id:t,name:"Keystroke",value:b,willCommit:!0,commitKey:1,selStart:g.selectionStart,selEnd:g.selectionEnd}}))}};this._dispatchEventFromSandbox(m,p)}),s.addEventListener("keydown",p=>{var v;h.commitKey=1;let m=-1;if(p.key==="Escape"?m=0:p.key==="Enter"&&!this.data.multiLine?m=2:p.key==="Tab"&&(h.commitKey=3),m===-1)return;const{value:y}=p.target;h.lastCommittedValue!==y&&(h.lastCommittedValue=y,h.userValue=y,(v=this.linkService.eventBus)==null||v.dispatch("dispatcheventinsandbox",{source:this,detail:{id:t,name:"Keystroke",value:y,willCommit:!0,commitKey:m,selStart:p.target.selectionStart,selEnd:p.target.selectionEnd}}))});const d=u;u=null,s.addEventListener("blur",p=>{var y,v;if(!h.focused||!p.relatedTarget)return;(y=this.data.actions)!=null&&y.Blur||(h.focused=!1);const{value:m}=p.target;h.userValue=m,h.lastCommittedValue!==m&&((v=this.linkService.eventBus)==null||v.dispatch("dispatcheventinsandbox",{source:this,detail:{id:t,name:"Keystroke",value:m,willCommit:!0,commitKey:h.commitKey,selStart:p.target.selectionStart,selEnd:p.target.selectionEnd}})),d(p)}),(r=this.data.actions)!=null&&r.Keystroke&&s.addEventListener("beforeinput",p=>{var A;h.lastCommittedValue=null;const{data:m,target:y}=p,{value:v,selectionStart:g,selectionEnd:b}=y;let _=g,x=b;switch(p.inputType){case"deleteWordBackward":{const C=v.substring(0,g).match(/\w*[^\w]*$/);C&&(_-=C[0].length);break}case"deleteWordForward":{const C=v.substring(g).match(/^[^\w]*\w*/);C&&(x+=C[0].length);break}case"deleteContentBackward":g===b&&(_-=1);break;case"deleteContentForward":g===b&&(x+=1);break}p.preventDefault(),(A=this.linkService.eventBus)==null||A.dispatch("dispatcheventinsandbox",{source:this,detail:{id:t,name:"Keystroke",value:v,change:m||"",willCommit:!1,selStart:_,selEnd:x}})}),this._setEventListeners(s,h,[["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"]],p=>p.target.value)}if(u&&s.addEventListener("blur",u),this.data.comb){const p=(this.data.rect[2]-this.data.rect[0])/l;s.classList.add("comb"),s.style.letterSpacing=`calc(${p}px * var(--scale-factor) - 1ch)`}}else s=document.createElement("div"),s.textContent=this.data.fieldValue,s.style.verticalAlign="middle",s.style.display="table-cell",this.data.hasOwnCanvas&&(s.hidden=!0);return this._setTextStyle(s),this._setBackgroundColor(s),this._setDefaultPropertiesFromJS(s),this.container.append(s),this.container}}class AZ extends Tc{constructor(e){super(e,{isRenderable:!!e.data.hasOwnCanvas})}}class kZ extends Tc{constructor(e){super(e,{isRenderable:e.renderForms})}render(){const e=this.annotationStorage,t=this.data,s=t.id;let i=e.getValue(s,{value:t.exportValue===t.fieldValue}).value;typeof i=="string"&&(i=i!=="Off",e.setValue(s,{value:i})),this.container.classList.add("buttonWidgetAnnotation","checkBox");const r=document.createElement("input");return gc.add(r),r.setAttribute("data-element-id",s),r.disabled=t.readOnly,this._setRequired(r,this.data.required),r.type="checkbox",r.name=t.fieldName,i&&r.setAttribute("checked",!0),r.setAttribute("exportValue",t.exportValue),r.tabIndex=sm,r.addEventListener("change",o=>{const{name:a,checked:l}=o.target;for(const c of this._getElementsByName(a,s)){const h=l&&c.exportValue===t.exportValue;c.domElement&&(c.domElement.checked=h),e.setValue(c.id,{value:h})}e.setValue(s,{value:l})}),r.addEventListener("resetform",o=>{const a=t.defaultFieldValue||"Off";o.target.checked=a===t.exportValue}),this.enableScripting&&this.hasJSActions&&(r.addEventListener("updatefromsandbox",o=>{const a={value(l){l.target.checked=l.detail.value!=="Off",e.setValue(s,{value:l.target.checked})}};this._dispatchEventFromSandbox(a,o)}),this._setEventListeners(r,null,[["change","Validate"],["change","Action"],["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"]],o=>o.target.checked)),this._setBackgroundColor(r),this._setDefaultPropertiesFromJS(r),this.container.append(r),this.container}}class SM extends Tc{constructor(e){super(e,{isRenderable:e.renderForms})}render(){this.container.classList.add("buttonWidgetAnnotation","radioButton");const e=this.annotationStorage,t=this.data,s=t.id;let i=e.getValue(s,{value:t.fieldValue===t.buttonValue}).value;if(typeof i=="string"&&(i=i!==t.buttonValue,e.setValue(s,{value:i})),i)for(const o of this._getElementsByName(t.fieldName,s))e.setValue(o.id,{value:!1});const r=document.createElement("input");if(gc.add(r),r.setAttribute("data-element-id",s),r.disabled=t.readOnly,this._setRequired(r,this.data.required),r.type="radio",r.name=t.fieldName,i&&r.setAttribute("checked",!0),r.tabIndex=sm,r.addEventListener("change",o=>{const{name:a,checked:l}=o.target;for(const c of this._getElementsByName(a,s))e.setValue(c.id,{value:!1});e.setValue(s,{value:l})}),r.addEventListener("resetform",o=>{const a=t.defaultFieldValue;o.target.checked=a!=null&&a===t.buttonValue}),this.enableScripting&&this.hasJSActions){const o=t.buttonValue;r.addEventListener("updatefromsandbox",a=>{const l={value:c=>{const h=o===c.detail.value;for(const u of this._getElementsByName(c.target.name)){const d=h&&u.id===s;u.domElement&&(u.domElement.checked=d),e.setValue(u.id,{value:d})}}};this._dispatchEventFromSandbox(l,a)}),this._setEventListeners(r,null,[["change","Validate"],["change","Action"],["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"]],a=>a.target.checked)}return this._setBackgroundColor(r),this._setDefaultPropertiesFromJS(r),this.container.append(r),this.container}}class EZ extends bM{constructor(e){super(e,{ignoreBorder:e.data.hasAppearance})}render(){const e=super.render();e.classList.add("buttonWidgetAnnotation","pushButton");const t=e.lastChild;return this.enableScripting&&this.hasJSActions&&t&&(this._setDefaultPropertiesFromJS(t),t.addEventListener("updatefromsandbox",s=>{this._dispatchEventFromSandbox({},s)})),e}}class CZ extends Tc{constructor(e){super(e,{isRenderable:e.renderForms})}render(){this.container.classList.add("choiceWidgetAnnotation");const e=this.annotationStorage,t=this.data.id,s=e.getValue(t,{value:this.data.fieldValue}),i=document.createElement("select");gc.add(i),i.setAttribute("data-element-id",t),i.disabled=this.data.readOnly,this._setRequired(i,this.data.required),i.name=this.data.fieldName,i.tabIndex=sm;let r=this.data.combo&&this.data.options.length>0;this.data.combo||(i.size=this.data.options.length,this.data.multiSelect&&(i.multiple=!0)),i.addEventListener("resetform",h=>{const u=this.data.defaultFieldValue;for(const d of i.options)d.selected=d.value===u});for(const h of this.data.options){const u=document.createElement("option");u.textContent=h.displayValue,u.value=h.exportValue,s.value.includes(h.exportValue)&&(u.setAttribute("selected",!0),r=!1),i.append(u)}let o=null;if(r){const h=document.createElement("option");h.value=" ",h.setAttribute("hidden",!0),h.setAttribute("selected",!0),i.prepend(h),o=()=>{h.remove(),i.removeEventListener("input",o),o=null},i.addEventListener("input",o)}const a=h=>{const u=h?"value":"textContent",{options:d,multiple:p}=i;return p?Array.prototype.filter.call(d,m=>m.selected).map(m=>m[u]):d.selectedIndex===-1?null:d[d.selectedIndex][u]};let l=a(!1);const c=h=>{const u=h.target.options;return Array.prototype.map.call(u,d=>({displayValue:d.textContent,exportValue:d.value}))};return this.enableScripting&&this.hasJSActions?(i.addEventListener("updatefromsandbox",h=>{const u={value(d){o==null||o();const p=d.detail.value,m=new Set(Array.isArray(p)?p:[p]);for(const y of i.options)y.selected=m.has(y.value);e.setValue(t,{value:a(!0)}),l=a(!1)},multipleSelection(d){i.multiple=!0},remove(d){const p=i.options,m=d.detail.remove;p[m].selected=!1,i.remove(m),p.length>0&&Array.prototype.findIndex.call(p,v=>v.selected)===-1&&(p[0].selected=!0),e.setValue(t,{value:a(!0),items:c(d)}),l=a(!1)},clear(d){for(;i.length!==0;)i.remove(0);e.setValue(t,{value:null,items:[]}),l=a(!1)},insert(d){const{index:p,displayValue:m,exportValue:y}=d.detail.insert,v=i.children[p],g=document.createElement("option");g.textContent=m,g.value=y,v?v.before(g):i.append(g),e.setValue(t,{value:a(!0),items:c(d)}),l=a(!1)},items(d){const{items:p}=d.detail;for(;i.length!==0;)i.remove(0);for(const m of p){const{displayValue:y,exportValue:v}=m,g=document.createElement("option");g.textContent=y,g.value=v,i.append(g)}i.options.length>0&&(i.options[0].selected=!0),e.setValue(t,{value:a(!0),items:c(d)}),l=a(!1)},indices(d){const p=new Set(d.detail.indices);for(const m of d.target.options)m.selected=p.has(m.index);e.setValue(t,{value:a(!0)}),l=a(!1)},editable(d){d.target.disabled=!d.detail.editable}};this._dispatchEventFromSandbox(u,h)}),i.addEventListener("input",h=>{var p;const u=a(!0),d=a(!1);e.setValue(t,{value:u}),h.preventDefault(),(p=this.linkService.eventBus)==null||p.dispatch("dispatcheventinsandbox",{source:this,detail:{id:t,name:"Keystroke",value:l,change:d,changeEx:u,willCommit:!1,commitKey:1,keyDown:!1}})}),this._setEventListeners(i,null,[["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"],["input","Action"],["input","Validate"]],h=>h.target.value)):i.addEventListener("input",function(h){e.setValue(t,{value:a(!0)})}),this.data.combo&&this._setTextStyle(i),this._setBackgroundColor(i),this._setDefaultPropertiesFromJS(i),this.container.append(i),this.container}}class $w extends en{constructor(e){const{data:t,elements:s}=e;super(e,{isRenderable:en._hasPopupData(t)}),this.elements=s,this.popup=null}render(){this.container.classList.add("popupAnnotation");const e=this.popup=new $Z({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}),t=[];for(const s of this.elements)s.popup=e,s.container.ariaHasPopup="dialog",t.push(s.data.id),s.addHighlightArea();return this.container.setAttribute("aria-controls",t.map(s=>`${Ax}${s}`).join(",")),this.container}}var Zh,r0,o0,Xh,zl,Vt,no,Yh,rp,op,Jh,so,Fi,io,ap,ro,lp,Hl,Bl,mt,Pg,Tw,xM,AM,kM,EM,Rg,Mg,Pw;class $Z{constructor({container:e,color:t,elements:s,titleObj:i,modificationDate:r,contentsObj:o,richText:a,parent:l,rect:c,parentRect:h,open:u}){M(this,mt);M(this,Zh,P(this,mt,kM).bind(this));M(this,r0,P(this,mt,Pw).bind(this));M(this,o0,P(this,mt,Mg).bind(this));M(this,Xh,P(this,mt,Rg).bind(this));M(this,zl,null);M(this,Vt,null);M(this,no,null);M(this,Yh,null);M(this,rp,null);M(this,op,null);M(this,Jh,null);M(this,so,!1);M(this,Fi,null);M(this,io,null);M(this,ap,null);M(this,ro,null);M(this,lp,null);M(this,Hl,null);M(this,Bl,!1);var d;T(this,Vt,e),T(this,lp,i),T(this,no,o),T(this,ro,a),T(this,op,l),T(this,zl,t),T(this,ap,c),T(this,Jh,h),T(this,rp,s),T(this,Yh,Cx.toDateObject(r)),this.trigger=s.flatMap(p=>p.getElementsToTriggerPopup());for(const p of this.trigger)p.addEventListener("click",f(this,Xh)),p.addEventListener("mouseenter",f(this,o0)),p.addEventListener("mouseleave",f(this,r0)),p.classList.add("popupTriggerArea");for(const p of s)(d=p.container)==null||d.addEventListener("keydown",f(this,Zh));f(this,Vt).hidden=!0,u&&P(this,mt,Rg).call(this)}render(){if(f(this,Fi))return;const e=T(this,Fi,document.createElement("div"));if(e.className="popup",f(this,zl)){const r=e.style.outlineColor=Se.makeHexColor(...f(this,zl));CSS.supports("background-color","color-mix(in srgb, red 30%, white)")?e.style.backgroundColor=`color-mix(in srgb, ${r} 30%, white)`:e.style.backgroundColor=Se.makeHexColor(...f(this,zl).map(a=>Math.floor(.7*(255-a)+a)))}const t=document.createElement("span");t.className="header";const s=document.createElement("h1");if(t.append(s),{dir:s.dir,str:s.textContent}=f(this,lp),e.append(t),f(this,Yh)){const r=document.createElement("span");r.classList.add("popupDate"),r.setAttribute("data-l10n-id","pdfjs-annotation-date-time-string"),r.setAttribute("data-l10n-args",JSON.stringify({dateObj:f(this,Yh).valueOf()})),t.append(r)}const i=f(this,mt,Pg);if(i)vM.render({xfaHtml:i,intent:"richText",div:e}),e.lastChild.classList.add("richText","popupContent");else{const r=this._formatContents(f(this,no));e.append(r)}f(this,Vt).append(e)}_formatContents({str:e,dir:t}){const s=document.createElement("p");s.classList.add("popupContent"),s.dir=t;const i=e.split(/(?:\r\n?|\n)/);for(let r=0,o=i.length;r{o.key==="Enter"&&(r?o.metaKey:o.ctrlKey)&&P(this,mp,Rw).call(this)}),!s.popupRef&&this.hasPopupData?this._createPopup():i.classList.add("popupTriggerArea"),t.append(i),t}getElementsToTriggerPopup(){return f(this,pp)}addHighlightArea(){this.container.classList.add("highlightArea")}}pp=new WeakMap,mp=new WeakSet,Rw=function(){var t;(t=this.downloadManager)==null||t.openOrDownloadData(this.content,this.filename)};var gp,Ul,ql,yp,Ac,RM,Mw,ZC;let jZ=(ZC=class{constructor({div:e,accessibilityManager:t,annotationCanvasMap:s,annotationEditorUIManager:i,page:r,viewport:o,structTreeLayer:a}){M(this,Ac);M(this,gp,null);M(this,Ul,null);M(this,ql,new Map);M(this,yp,null);this.div=e,T(this,gp,t),T(this,Ul,s),T(this,yp,a||null),this.page=r,this.viewport=o,this.zIndex=0,this._annotationEditorUIManager=i}hasEditableAnnotations(){return f(this,ql).size>0}async render(e){var o;const{annotations:t}=e,s=this.div;pc(s,this.viewport);const i=new Map,r={data:null,layer:s,linkService:e.linkService,downloadManager:e.downloadManager,imageResourcesPath:e.imageResourcesPath||"",renderForms:e.renderForms!==!1,svgFactory:new Ox,annotationStorage:e.annotationStorage||new Tx,enableScripting:e.enableScripting===!0,hasJSActions:e.hasJSActions,fieldObjects:e.fieldObjects,parent:this,elements:null};for(const a of t){if(a.noHTML)continue;const l=a.annotationType===hn.POPUP;if(l){const u=i.get(a.id);if(!u)continue;r.elements=u}else{const{width:u,height:d}=Ao(a.rect);if(u<=0||d<=0)continue}r.data=a;const c=_Z.create(r);if(!c.isRenderable)continue;if(!l&&a.popupRef){const u=i.get(a.popupRef);u?u.push(c):i.set(a.popupRef,[c])}const h=c.render();a.hidden&&(h.style.visibility="hidden"),await P(this,Ac,RM).call(this,h,a.id),c._isEditable&&(f(this,ql).set(c.data.id,c),(o=this._annotationEditorUIManager)==null||o.renderAnnotationElement(c))}P(this,Ac,Mw).call(this)}update({viewport:e}){const t=this.div;this.viewport=e,pc(t,{rotation:e.rotation}),P(this,Ac,Mw).call(this),t.hidden=!1}getEditableAnnotations(){return Array.from(f(this,ql).values())}getEditableAnnotation(e){return f(this,ql).get(e)}},gp=new WeakMap,Ul=new WeakMap,ql=new WeakMap,yp=new WeakMap,Ac=new WeakSet,RM=async function(e,t){var o,a;const s=e.firstChild||e,i=s.id=`${Ax}${t}`,r=await((o=f(this,yp))==null?void 0:o.getAriaAttributes(i));if(r)for(const[l,c]of r)s.setAttribute(l,c);this.div.append(e),(a=f(this,gp))==null||a.moveElementInDOM(this.div,e,s,!1)},Mw=function(){if(!f(this,Ul))return;const e=this.div;for(const[t,s]of f(this,Ul)){const i=e.querySelector(`[data-annotation-id="${t}"]`);if(!i)continue;s.className="annotationContent";const{firstChild:r}=i;r?r.nodeName==="CANVAS"?r.replaceWith(s):r.classList.contains("annotationContent")?r.after(s):r.before(s):i.append(s)}f(this,Ul).clear()},ZC);const jm=/\r\n?|\n/g;var zi,Gs,vp,Vl,Ks,an,MM,IM,OM,Ig,Co,Og,Ng,NM,Ow,LM;const At=class At extends ft{constructor(t){super({...t,name:"freeTextEditor"});M(this,an);M(this,zi);M(this,Gs,"");M(this,vp,`${this.id}-editor`);M(this,Vl,null);M(this,Ks);T(this,zi,t.color||At._defaultColor||ft._defaultLineColor),T(this,Ks,t.fontSize||At._defaultFontSize)}static get _keyboardManager(){const t=At.prototype,s=o=>o.isEmpty(),i=mc.TRANSLATE_SMALL,r=mc.TRANSLATE_BIG;return Xe(this,"_keyboardManager",new nm([[["ctrl+s","mac+meta+s","ctrl+p","mac+meta+p"],t.commitOrRemove,{bubbles:!0}],[["ctrl+Enter","mac+meta+Enter","Escape","mac+Escape"],t.commitOrRemove],[["ArrowLeft","mac+ArrowLeft"],t._translateEmpty,{args:[-i,0],checker:s}],[["ctrl+ArrowLeft","mac+shift+ArrowLeft"],t._translateEmpty,{args:[-r,0],checker:s}],[["ArrowRight","mac+ArrowRight"],t._translateEmpty,{args:[i,0],checker:s}],[["ctrl+ArrowRight","mac+shift+ArrowRight"],t._translateEmpty,{args:[r,0],checker:s}],[["ArrowUp","mac+ArrowUp"],t._translateEmpty,{args:[0,-i],checker:s}],[["ctrl+ArrowUp","mac+shift+ArrowUp"],t._translateEmpty,{args:[0,-r],checker:s}],[["ArrowDown","mac+ArrowDown"],t._translateEmpty,{args:[0,i],checker:s}],[["ctrl+ArrowDown","mac+shift+ArrowDown"],t._translateEmpty,{args:[0,r],checker:s}]]))}static initialize(t,s){ft.initialize(t,s);const i=getComputedStyle(document.documentElement);this._internalPadding=parseFloat(i.getPropertyValue("--freetext-padding"))}static updateDefaultParams(t,s){switch(t){case Te.FREETEXT_SIZE:At._defaultFontSize=s;break;case Te.FREETEXT_COLOR:At._defaultColor=s;break}}updateParams(t,s){switch(t){case Te.FREETEXT_SIZE:P(this,an,MM).call(this,s);break;case Te.FREETEXT_COLOR:P(this,an,IM).call(this,s);break}}static get defaultPropertiesToUpdate(){return[[Te.FREETEXT_SIZE,At._defaultFontSize],[Te.FREETEXT_COLOR,At._defaultColor||ft._defaultLineColor]]}get propertiesToUpdate(){return[[Te.FREETEXT_SIZE,f(this,Ks)],[Te.FREETEXT_COLOR,f(this,zi)]]}_translateEmpty(t,s){this._uiManager.translateSelectedEditors(t,s,!0)}getInitialTranslation(){const t=this.parentScale;return[-At._internalPadding*t,-(At._internalPadding+f(this,Ks))*t]}rebuild(){this.parent&&(super.rebuild(),this.div!==null&&(this.isAttachedToDOM||this.parent.add(this)))}enableEditMode(){if(this.isInEditMode())return;this.parent.setEditingState(!1),this.parent.updateToolbar(De.FREETEXT),super.enableEditMode(),this.overlayDiv.classList.remove("enabled"),this.editorDiv.contentEditable=!0,this._isDraggable=!1,this.div.removeAttribute("aria-activedescendant"),T(this,Vl,new AbortController);const t=this._uiManager.combinedSignal(f(this,Vl));this.editorDiv.addEventListener("keydown",this.editorDivKeydown.bind(this),{signal:t}),this.editorDiv.addEventListener("focus",this.editorDivFocus.bind(this),{signal:t}),this.editorDiv.addEventListener("blur",this.editorDivBlur.bind(this),{signal:t}),this.editorDiv.addEventListener("input",this.editorDivInput.bind(this),{signal:t}),this.editorDiv.addEventListener("paste",this.editorDivPaste.bind(this),{signal:t})}disableEditMode(){var t;this.isInEditMode()&&(this.parent.setEditingState(!0),super.disableEditMode(),this.overlayDiv.classList.add("enabled"),this.editorDiv.contentEditable=!1,this.div.setAttribute("aria-activedescendant",f(this,vp)),this._isDraggable=!0,(t=f(this,Vl))==null||t.abort(),T(this,Vl,null),this.div.focus({preventScroll:!0}),this.isEditing=!1,this.parent.div.classList.add("freetextEditing"))}focusin(t){this._focusEventsAllowed&&(super.focusin(t),t.target!==this.editorDiv&&this.editorDiv.focus())}onceAdded(){var t;this.width||(this.enableEditMode(),this.editorDiv.focus(),(t=this._initialOptions)!=null&&t.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()}commit(){if(!this.isInEditMode())return;super.commit(),this.disableEditMode();const t=f(this,Gs),s=T(this,Gs,P(this,an,OM).call(this).trimEnd());if(t===s)return;const i=r=>{if(T(this,Gs,r),!r){this.remove();return}P(this,an,Ng).call(this),this._uiManager.rebuild(this),P(this,an,Ig).call(this)};this.addCommands({cmd:()=>{i(s)},undo:()=>{i(t)},mustExec:!1}),P(this,an,Ig).call(this)}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){At._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,s;this.width&&(t=this.x,s=this.y),super.render(),this.editorDiv=document.createElement("div"),this.editorDiv.className="internal",this.editorDiv.setAttribute("id",f(this,vp)),this.editorDiv.setAttribute("data-l10n-id","pdfjs-free-text2"),this.editorDiv.setAttribute("data-l10n-attrs","default-content"),this.enableEditing(),this.editorDiv.contentEditable=!0;const{style:i}=this.editorDiv;if(i.fontSize=`calc(${f(this,Ks)}px * var(--scale-factor))`,i.color=f(this,zi),this.div.append(this.editorDiv),this.overlayDiv=document.createElement("div"),this.overlayDiv.classList.add("overlay","enabled"),this.div.append(this.overlayDiv),wy(this,this.div,["dblclick","keydown"]),this.width){const[r,o]=this.parentDimensions;if(this.annotationElementId){const{position:a}=this._initialData;let[l,c]=this.getInitialTranslation();[l,c]=this.pageTranslationToScreen(l,c);const[h,u]=this.pageDimensions,[d,p]=this.pageTranslation;let m,y;switch(this.rotation){case 0:m=t+(a[0]-d)/h,y=s+this.height-(a[1]-p)/u;break;case 90:m=t+(a[0]-d)/h,y=s-(a[1]-p)/u,[l,c]=[c,-l];break;case 180:m=t-this.width+(a[0]-d)/h,y=s-(a[1]-p)/u,[l,c]=[-l,-c];break;case 270:m=t+(a[0]-d-this.height*u)/h,y=s+(a[1]-p-this.width*h)/u,[l,c]=[-c,l];break}this.setAt(m*r,y*o,l,c)}else this.setAt(t*r,s*o,this.width*r,this.height*o);P(this,an,Ng).call(this),this._isDraggable=!0,this.editorDiv.contentEditable=!1}else this._isDraggable=!1,this.editorDiv.contentEditable=!0;return this.div}editorDivPaste(t){var m,y,v;const s=t.clipboardData||window.clipboardData,{types:i}=s;if(i.length===1&&i[0]==="text/plain")return;t.preventDefault();const r=P(m=At,Co,Ow).call(m,s.getData("text")||"").replaceAll(jm,` +`);if(!r)return;const o=window.getSelection();if(!o.rangeCount)return;this.editorDiv.normalize(),o.deleteFromDocument();const a=o.getRangeAt(0);if(!r.includes(` +`)){a.insertNode(document.createTextNode(r)),this.editorDiv.normalize(),o.collapseToStart();return}const{startContainer:l,startOffset:c}=a,h=[],u=[];if(l.nodeType===Node.TEXT_NODE){const g=l.parentElement;if(u.push(l.nodeValue.slice(c).replaceAll(jm,"")),g!==this.editorDiv){let b=h;for(const _ of this.editorDiv.childNodes){if(_===g){b=u;continue}b.push(P(y=At,Co,Og).call(y,_))}}h.push(l.nodeValue.slice(0,c).replaceAll(jm,""))}else if(l===this.editorDiv){let g=h,b=0;for(const _ of this.editorDiv.childNodes)b++===c&&(g=u),g.push(P(v=At,Co,Og).call(v,_))}T(this,Gs,`${h.join(` +`)}${r}${u.join(` +`)}`),P(this,an,Ng).call(this);const d=new Range;let p=h.reduce((g,b)=>g+b.length,0);for(const{firstChild:g}of this.editorDiv.childNodes)if(g.nodeType===Node.TEXT_NODE){const b=g.nodeValue.length;if(p<=b){d.setStart(g,p),d.setEnd(g,p);break}p-=b}o.removeAllRanges(),o.addRange(d)}get contentDiv(){return this.editorDiv}static async deserialize(t,s,i){var a;let r=null;if(t instanceof CM){const{data:{defaultAppearanceData:{fontSize:l,fontColor:c},rect:h,rotation:u,id:d,popupRef:p},textContent:m,textPosition:y,parent:{page:{pageNumber:v}}}=t;if(!m||m.length===0)return null;r=t={annotationType:De.FREETEXT,color:Array.from(c),fontSize:l,value:m.join(` +`),position:y,pageIndex:v-1,rect:h.slice(0),rotation:u,id:d,deleted:!1,popupRef:p}}const o=await super.deserialize(t,s,i);return T(o,Ks,t.fontSize),T(o,zi,Se.makeHexColor(...t.color)),T(o,Gs,P(a=At,Co,Ow).call(a,t.value)),o.annotationElementId=t.id||null,o._initialData=r,o}serialize(t=!1){if(this.isEmpty())return null;if(this.deleted)return this.serializeDeleted();const s=At._internalPadding*this.parentScale,i=this.getRect(s,s),r=ft._colorManager.convert(this.isAttachedToDOM?getComputedStyle(this.editorDiv).color:f(this,zi)),o={annotationType:De.FREETEXT,color:r,fontSize:f(this,Ks),value:P(this,an,NM).call(this),pageIndex:this.pageIndex,rect:i,rotation:this.rotation,structTreeParentId:this._structTreeParentId};return t?o:this.annotationElementId&&!P(this,an,LM).call(this,o)?null:(o.id=this.annotationElementId,o)}renderAnnotationElement(t){const s=super.renderAnnotationElement(t);if(this.deleted)return s;const{style:i}=s;i.fontSize=`calc(${f(this,Ks)}px * var(--scale-factor))`,i.color=f(this,zi),s.replaceChildren();for(const o of f(this,Gs).split(` +`)){const a=document.createElement("div");a.append(o?document.createTextNode(o):document.createElement("br")),s.append(a)}const r=At._internalPadding*this.parentScale;return t.updateEdited({rect:this.getRect(r,r),popupContent:f(this,Gs)}),s}resetAnnotationElement(t){super.resetAnnotationElement(t),t.resetEdited()}};zi=new WeakMap,Gs=new WeakMap,vp=new WeakMap,Vl=new WeakMap,Ks=new WeakMap,an=new WeakSet,MM=function(t){const s=r=>{this.editorDiv.style.fontSize=`calc(${r}px * var(--scale-factor))`,this.translate(0,-(r-f(this,Ks))*this.parentScale),T(this,Ks,r),P(this,an,Ig).call(this)},i=f(this,Ks);this.addCommands({cmd:s.bind(this,t),undo:s.bind(this,i),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:Te.FREETEXT_SIZE,overwriteIfSameType:!0,keepUndo:!0})},IM=function(t){const s=r=>{T(this,zi,this.editorDiv.style.color=r)},i=f(this,zi);this.addCommands({cmd:s.bind(this,t),undo:s.bind(this,i),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:Te.FREETEXT_COLOR,overwriteIfSameType:!0,keepUndo:!0})},OM=function(){var i;const t=[];this.editorDiv.normalize();let s=null;for(const r of this.editorDiv.childNodes)(s==null?void 0:s.nodeType)===Node.TEXT_NODE&&r.nodeName==="BR"||(t.push(P(i=At,Co,Og).call(i,r)),s=r);return t.join(` +`)},Ig=function(){const[t,s]=this.parentDimensions;let i;if(this.isAttachedToDOM)i=this.div.getBoundingClientRect();else{const{currentLayer:r,div:o}=this,a=o.style.display,l=o.classList.contains("hidden");o.classList.remove("hidden"),o.style.display="hidden",r.div.append(this.div),i=o.getBoundingClientRect(),o.remove(),o.style.display=a,o.classList.toggle("hidden",l)}this.rotation%180===this.parentRotation%180?(this.width=i.width/t,this.height=i.height/s):(this.width=i.height/t,this.height=i.width/s),this.fixAndSetPosition()},Co=new WeakSet,Og=function(t){return(t.nodeType===Node.TEXT_NODE?t.nodeValue:t.innerText).replaceAll(jm,"")},Ng=function(){if(this.editorDiv.replaceChildren(),!!f(this,Gs))for(const t of f(this,Gs).split(` +`)){const s=document.createElement("div");s.append(t?document.createTextNode(t):document.createElement("br")),this.editorDiv.append(s)}},NM=function(){return f(this,Gs).replaceAll(" "," ")},Ow=function(t){return t.replaceAll(" "," ")},LM=function(t){const{value:s,fontSize:i,color:r,pageIndex:o}=this._initialData;return this._hasBeenMoved||t.value!==s||t.fontSize!==i||t.color.some((a,l)=>a!==r[l])||t.pageIndex!==o},M(At,Co),oe(At,"_freeTextDefaultContent",""),oe(At,"_internalPadding",0),oe(At,"_defaultColor",null),oe(At,"_defaultFontSize",10),oe(At,"_type","freetext"),oe(At,"_editorType",De.FREETEXT);let Iw=At;class DM{toSVGPath(){Tt("Abstract method `toSVGPath` must be implemented.")}get box(){Tt("Abstract getter `box` must be implemented.")}serialize(e,t){Tt("Abstract method `serialize` must be implemented.")}get classNamesForDrawing(){Tt("Abstract getter `classNamesForDrawing` must be implemented.")}get classNamesForOutlining(){Tt("Abstract getter `classNamesForOutlining` must be implemented.")}get mustRemoveSelfIntersections(){return!1}}var Zs,Hi,Qh,eu,br,Ve,Wl,Gl,bp,wp,tu,nu,ca,_p,a0,l0,wn,kd,jM,FM,zM,HM,BM,UM;const Vr=class Vr{constructor({x:e,y:t},s,i,r,o,a=0){M(this,wn);M(this,Zs);M(this,Hi,[]);M(this,Qh);M(this,eu);M(this,br,[]);M(this,Ve,new Float64Array(18));M(this,Wl);M(this,Gl);M(this,bp);M(this,wp);M(this,tu);M(this,nu);M(this,ca,[]);T(this,Zs,s),T(this,nu,r*i),T(this,eu,o),f(this,Ve).set([NaN,NaN,NaN,NaN,e,t],6),T(this,Qh,a),T(this,wp,f(Vr,_p)*i),T(this,bp,f(Vr,l0)*i),T(this,tu,i),f(this,ca).push(e,t)}isEmpty(){return isNaN(f(this,Ve)[8])}add({x:e,y:t}){var j;T(this,Wl,e),T(this,Gl,t);const[s,i,r,o]=f(this,Zs);let[a,l,c,h]=f(this,Ve).subarray(8,12);const u=e-c,d=t-h,p=Math.hypot(u,d);if(p=6;i-=6)isNaN(t[i])?s.push(`L${t[i+4]} ${t[i+5]}`):s.push(`C${t[i]} ${t[i+1]} ${t[i+2]} ${t[i+3]} ${t[i+4]} ${t[i+5]}`);return P(this,wn,FM).call(this,s),s.join(" ")}newFreeDrawOutline(e,t,s,i,r,o){return new qM(e,t,s,i,r,o)}getOutlines(){var u;const e=f(this,br),t=f(this,Hi),s=f(this,Ve),[i,r,o,a]=f(this,Zs),l=new Float64Array((((u=f(this,ca))==null?void 0:u.length)??0)+2);for(let d=0,p=l.length-2;d=6;d-=6)for(let p=0;p<6;p+=2){if(isNaN(t[d+p])){c[h]=c[h+1]=NaN,h+=2;continue}c[h]=t[d+p],c[h+1]=t[d+p+1],h+=2}return P(this,wn,BM).call(this,c,h),this.newFreeDrawOutline(c,l,f(this,Zs),f(this,tu),f(this,Qh),f(this,eu))}};Zs=new WeakMap,Hi=new WeakMap,Qh=new WeakMap,eu=new WeakMap,br=new WeakMap,Ve=new WeakMap,Wl=new WeakMap,Gl=new WeakMap,bp=new WeakMap,wp=new WeakMap,tu=new WeakMap,nu=new WeakMap,ca=new WeakMap,_p=new WeakMap,a0=new WeakMap,l0=new WeakMap,wn=new WeakSet,kd=function(){const e=f(this,Ve).subarray(4,6),t=f(this,Ve).subarray(16,18),[s,i,r,o]=f(this,Zs);return[(f(this,Wl)+(e[0]-t[0])/2-s)/r,(f(this,Gl)+(e[1]-t[1])/2-i)/o,(f(this,Wl)+(t[0]-e[0])/2-s)/r,(f(this,Gl)+(t[1]-e[1])/2-i)/o]},jM=function(){const[e,t,s,i]=f(this,Zs),[r,o,a,l]=P(this,wn,kd).call(this);return`M${(f(this,Ve)[2]-e)/s} ${(f(this,Ve)[3]-t)/i} L${(f(this,Ve)[4]-e)/s} ${(f(this,Ve)[5]-t)/i} L${r} ${o} L${a} ${l} L${(f(this,Ve)[16]-e)/s} ${(f(this,Ve)[17]-t)/i} L${(f(this,Ve)[14]-e)/s} ${(f(this,Ve)[15]-t)/i} Z`},FM=function(e){const t=f(this,Hi);e.push(`L${t[4]} ${t[5]} Z`)},zM=function(e){const[t,s,i,r]=f(this,Zs),o=f(this,Ve).subarray(4,6),a=f(this,Ve).subarray(16,18),[l,c,h,u]=P(this,wn,kd).call(this);e.push(`L${(o[0]-t)/i} ${(o[1]-s)/r} L${l} ${c} L${h} ${u} L${(a[0]-t)/i} ${(a[1]-s)/r}`)},HM=function(e){const t=f(this,Ve),[s,i,r,o]=f(this,Zs),[a,l,c,h]=P(this,wn,kd).call(this),u=new Float64Array(36);return u.set([NaN,NaN,NaN,NaN,(t[2]-s)/r,(t[3]-i)/o,NaN,NaN,NaN,NaN,(t[4]-s)/r,(t[5]-i)/o,NaN,NaN,NaN,NaN,a,l,NaN,NaN,NaN,NaN,c,h,NaN,NaN,NaN,NaN,(t[16]-s)/r,(t[17]-i)/o,NaN,NaN,NaN,NaN,(t[14]-s)/r,(t[15]-i)/o],0),this.newFreeDrawOutline(u,e,f(this,Zs),f(this,tu),f(this,Qh),f(this,eu))},BM=function(e,t){const s=f(this,Hi);return e.set([NaN,NaN,NaN,NaN,s[4],s[5]],t),t+=6},UM=function(e,t){const s=f(this,Ve).subarray(4,6),i=f(this,Ve).subarray(16,18),[r,o,a,l]=f(this,Zs),[c,h,u,d]=P(this,wn,kd).call(this);return e.set([NaN,NaN,NaN,NaN,(s[0]-r)/a,(s[1]-o)/l,NaN,NaN,NaN,NaN,c,h,NaN,NaN,NaN,NaN,u,d,NaN,NaN,NaN,NaN,(i[0]-r)/a,(i[1]-o)/l],t),t+=24},M(Vr,_p,8),M(Vr,a0,2),M(Vr,l0,f(Vr,_p)+f(Vr,a0));let Sy=Vr;var su,Kl,oo,Sp,Xs,xp,Xt,Fs,Ed,Cd,VM;class qM extends DM{constructor(t,s,i,r,o,a){super();M(this,Fs);M(this,su);M(this,Kl,null);M(this,oo);M(this,Sp);M(this,Xs);M(this,xp);M(this,Xt);T(this,Xt,t),T(this,Xs,s),T(this,su,i),T(this,xp,r),T(this,oo,o),T(this,Sp,a),P(this,Fs,VM).call(this,a);const{x:l,y:c,width:h,height:u}=f(this,Kl);for(let d=0,p=t.length;dt[0]-s[0]||t[1]-s[1]||t[2]-s[2]);const e=[];for(const t of f(this,ha))t[3]?(e.push(...P(this,Ss,Nw).call(this,t)),P(this,Ss,GM).call(this,t)):(P(this,Ss,KM).call(this,t),e.push(...P(this,Ss,Nw).call(this,t)));return P(this,Ss,WM).call(this,e)}}Ap=new WeakMap,ha=new WeakMap,Bi=new WeakMap,Ss=new WeakSet,WM=function(e){const t=[],s=new Set;for(const o of e){const[a,l,c]=o;t.push([a,l,o],[a,c,o])}t.sort((o,a)=>o[1]-a[1]||o[0]-a[0]);for(let o=0,a=t.length;o0;){const o=s.values().next().value;let[a,l,c,h,u]=o;s.delete(o);let d=a,p=l;for(r=[a,c],i.push(r);;){let m;if(s.has(h))m=h;else if(s.has(u))m=u;else break;s.delete(m),[a,l,c,h,u]=m,d!==a&&(r.push(d,p,a,p===l?l:c),d=a),p=p===l?c:l}r.push(d,p)}return new FZ(i,f(this,Ap))},Lg=function(e){const t=f(this,Bi);let s=0,i=t.length-1;for(;s<=i;){const r=s+i>>1,o=t[r][0];if(o===e)return r;o=0;i--){const[r,o]=f(this,Bi)[i];if(r!==e)break;if(r===e&&o===t){f(this,Bi).splice(i,1);return}}},Nw=function(e){const[t,s,i]=e,r=[[t,s,i]],o=P(this,Ss,Lg).call(this,i);for(let a=0;a=l){if(p>c)r[h][1]=c;else{if(u===1)return[];r.splice(h,1),h--,u--}continue}r[h][2]=l,p>c&&r.push([t,c,p])}}}return r};var kp,iu;class FZ extends DM{constructor(t,s){super();M(this,kp);M(this,iu);T(this,iu,t),T(this,kp,s)}toSVGPath(){const t=[];for(const s of f(this,iu)){let[i,r]=s;t.push(`M${i} ${r}`);for(let o=2;o-1?(T(this,Rs,!0),P(this,Oe,Dg).call(this,t),P(this,Oe,Xa).call(this)):f(this,ao)&&(T(this,lu,t.anchorNode),T(this,Pp,t.anchorOffset),T(this,Rp,t.focusNode),T(this,Mp,t.focusOffset),P(this,Oe,zw).call(this),P(this,Oe,Xa).call(this),this.rotate(this.rotation))}static get _keyboardManager(){const t=ot.prototype;return Xe(this,"_keyboardManager",new nm([[["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]}]]))}get telemetryInitialData(){return{action:"added",type:f(this,Rs)?"free_highlight":"highlight",color:this._uiManager.highlightColorNames.get(this.color),thickness:f(this,ui),methodOfCreation:f(this,Ip)}}get telemetryFinalData(){return{type:"highlight",color:this._uiManager.highlightColorNames.get(this.color)}}static computeTelemetryFinalData(t){return{numberOfColors:t.get("color").size}}static initialize(t,s){var i;ft.initialize(t,s),ot._defaultColor||(ot._defaultColor=((i=s.highlightColors)==null?void 0:i.values().next().value)||"#fff066")}static updateDefaultParams(t,s){switch(t){case Te.HIGHLIGHT_DEFAULT_COLOR:ot._defaultColor=s;break;case Te.HIGHLIGHT_THICKNESS:ot._defaultThickness=s;break}}translateInPage(t,s){}get toolbarPosition(){return f(this,hu)}updateParams(t,s){switch(t){case Te.HIGHLIGHT_COLOR:P(this,Oe,XM).call(this,s);break;case Te.HIGHLIGHT_THICKNESS:P(this,Oe,YM).call(this,s);break}}static get defaultPropertiesToUpdate(){return[[Te.HIGHLIGHT_DEFAULT_COLOR,ot._defaultColor],[Te.HIGHLIGHT_THICKNESS,ot._defaultThickness]]}get propertiesToUpdate(){return[[Te.HIGHLIGHT_COLOR,this.color||ot._defaultColor],[Te.HIGHLIGHT_THICKNESS,f(this,ui)||ot._defaultThickness],[Te.HIGHLIGHT_FREE,f(this,Rs)]]}async addEditToolbar(){const t=await super.addEditToolbar();return t?(this._uiManager.highlightColors&&(T(this,cu,new xy({editor:this})),t.addColorPicker(f(this,cu))),t):null}disableEditing(){super.disableEditing(),this.div.classList.toggle("disabled",!0)}enableEditing(){super.enableEditing(),this.div.classList.toggle("disabled",!1)}fixAndSetPosition(){return super.fixAndSetPosition(P(this,Oe,$d).call(this))}getBaseTranslation(){return[0,0]}getRect(t,s){return super.getRect(t,s,P(this,Oe,$d).call(this))}onceAdded(){this.annotationElementId||this.parent.addUndoableEditor(this),this.div.focus()}remove(){P(this,Oe,Hw).call(this),this._reportTelemetry({action:"deleted"}),super.remove()}rebuild(){this.parent&&(super.rebuild(),this.div!==null&&(P(this,Oe,Xa).call(this),this.isAttachedToDOM||this.parent.add(this)))}setParent(t){var i;let s=!1;this.parent&&!t?P(this,Oe,Hw).call(this):t&&(P(this,Oe,Xa).call(this,t),s=!this.parent&&((i=this.div)==null?void 0:i.classList.contains("selectedEditor"))),super.setParent(t),this.show(this._isVisible),s&&this.select()}rotate(t){var r,o,a;const{drawLayer:s}=this.parent;let i;f(this,Rs)?(t=(t-this.rotation+360)%360,i=P(r=ot,yi,Zc).call(r,f(this,Vi).box,t)):i=P(o=ot,yi,Zc).call(o,this,t),s.rotate(f(this,is),t),s.rotate(f(this,fn),t),s.updateBox(f(this,is),i),s.updateBox(f(this,fn),P(a=ot,yi,Zc).call(a,f(this,hi).box,t))}render(){if(this.div)return this.div;const t=super.render();f(this,uu)&&(t.setAttribute("aria-label",f(this,uu)),t.setAttribute("role","mark")),f(this,Rs)?t.classList.add("free"):this.div.addEventListener("keydown",P(this,Oe,QM).bind(this),{signal:this._uiManager._signal});const s=T(this,Yl,document.createElement("div"));t.append(s),s.setAttribute("aria-hidden","true"),s.className="internal",s.style.clipPath=f(this,Xl);const[i,r]=this.parentDimensions;return this.setDims(this.width*i,this.height*r),wy(this,f(this,Yl),["pointerover","pointerleave"]),this.enableEditing(),t}pointerover(){this.isSelected||this.parent.drawLayer.addClass(f(this,fn),"hovered")}pointerleave(){this.isSelected||this.parent.drawLayer.removeClass(f(this,fn),"hovered")}_moveCaret(t){switch(this.parent.unselect(this),t){case 0:case 2:P(this,Oe,jg).call(this,!0);break;case 1:case 3:P(this,Oe,jg).call(this,!1);break}}select(){var t,s;super.select(),f(this,fn)&&((t=this.parent)==null||t.drawLayer.removeClass(f(this,fn),"hovered"),(s=this.parent)==null||s.drawLayer.addClass(f(this,fn),"selected"))}unselect(){var t;super.unselect(),f(this,fn)&&((t=this.parent)==null||t.drawLayer.removeClass(f(this,fn),"selected"),f(this,Rs)||P(this,Oe,jg).call(this,!1))}get _mustFixPosition(){return!f(this,Rs)}show(t=this._isVisible){super.show(t),this.parent&&(this.parent.drawLayer.show(f(this,is),t),this.parent.drawLayer.show(f(this,fn),t))}static startHighlighting(t,s,{target:i,x:r,y:o}){const{x:a,y:l,width:c,height:h}=i.getBoundingClientRect(),u=new AbortController,d=t.combinedSignal(u),p=y=>{y.preventDefault(),y.stopPropagation()},m=y=>{u.abort(),P(this,yi,sI).call(this,t,y)};window.addEventListener("blur",m,{signal:d}),window.addEventListener("pointerup",m,{signal:d}),window.addEventListener("pointerdown",p,{capture:!0,passive:!1,signal:d}),window.addEventListener("contextmenu",Si,{signal:d}),i.addEventListener("pointermove",P(this,yi,nI).bind(this,t),{signal:d}),this._freeHighlight=new Lw({x:r,y:o},[a,l,c,h],t.scale,this._defaultThickness/2,s,.001),{id:this._freeHighlightId,clipPathId:this._freeHighlightClipId}=t.drawLayer.draw(this._freeHighlight,this._defaultColor,this._defaultOpacity,!0)}static async deserialize(t,s,i){var y,v,g,b;let r=null;if(t instanceof TM){const{data:{quadPoints:_,rect:x,rotation:A,id:C,color:$,opacity:I,popupRef:j},parent:{page:{pageNumber:q}}}=t;r=t={annotationType:De.HIGHLIGHT,color:Array.from($),opacity:I,quadPoints:_,boxes:null,pageIndex:q-1,rect:x.slice(0),rotation:A,id:C,deleted:!1,popupRef:j}}else if(t instanceof Nx){const{data:{inkLists:_,rect:x,rotation:A,id:C,color:$,borderStyle:{rawWidth:I},popupRef:j},parent:{page:{pageNumber:q}}}=t;r=t={annotationType:De.HIGHLIGHT,color:Array.from($),thickness:I,inkLists:_,boxes:null,pageIndex:q-1,rect:x.slice(0),rotation:A,id:C,deleted:!1,popupRef:j}}const{color:o,quadPoints:a,inkLists:l,opacity:c}=t,h=await super.deserialize(t,s,i);h.color=Se.makeHexColor(...o),T(h,lo,c||1),l&&T(h,ui,t.thickness),h.annotationElementId=t.id||null,h._initialData=r;const[u,d]=h.pageDimensions,[p,m]=h.pageTranslation;if(a){const _=T(h,ao,[]);for(let x=0;x=0)T(this,is,s),T(this,Xl,i),this.parent.drawLayer.finalizeLine(s,t),T(this,fn,this.parent.drawLayer.drawOutline(f(this,hi)));else if(this.parent){const p=this.parent.viewport.rotation;this.parent.drawLayer.updateLine(f(this,is),t),this.parent.drawLayer.updateBox(f(this,is),P(u=ot,yi,Zc).call(u,f(this,Vi).box,(p-this.rotation+360)%360)),this.parent.drawLayer.updateLine(f(this,fn),f(this,hi)),this.parent.drawLayer.updateBox(f(this,fn),P(d=ot,yi,Zc).call(d,f(this,hi).box,p))}const{x:o,y:a,width:l,height:c}=t.box;switch(this.rotation){case 0:this.x=o,this.y=a,this.width=l,this.height=c;break;case 90:{const[p,m]=this.parentDimensions;this.x=a,this.y=1-o,this.width=l*m/p,this.height=c*p/m;break}case 180:this.x=1-o,this.y=1-a,this.width=l,this.height=c;break;case 270:{const[p,m]=this.parentDimensions;this.x=1-a,this.y=o,this.width=l*m/p,this.height=c*p/m;break}}const{lastPoint:h}=f(this,hi).box;T(this,hu,[(h[0]-o)/l,(h[1]-a)/c])},XM=function(t){const s=(o,a)=>{var l,c,h;this.color=o,(l=this.parent)==null||l.drawLayer.changeColor(f(this,is),o),(c=f(this,cu))==null||c.updateColor(o),T(this,lo,a),(h=this.parent)==null||h.drawLayer.changeOpacity(f(this,is),a)},i=this.color,r=f(this,lo);this.addCommands({cmd:s.bind(this,t,ot._defaultOpacity),undo:s.bind(this,i,r),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:Te.HIGHLIGHT_COLOR,overwriteIfSameType:!0,keepUndo:!0}),this._reportTelemetry({action:"color_changed",color:this._uiManager.highlightColorNames.get(t)},!0)},YM=function(t){const s=f(this,ui),i=r=>{T(this,ui,r),P(this,Oe,JM).call(this,r)};this.addCommands({cmd:i.bind(this,t),undo:i.bind(this,s),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:Te.INK_THICKNESS,overwriteIfSameType:!0,keepUndo:!0}),this._reportTelemetry({action:"thickness_changed",thickness:t},!0)},JM=function(t){if(!f(this,Rs))return;P(this,Oe,Dg).call(this,{highlightOutlines:f(this,Vi).getNewOutline(t/2)}),this.fixAndSetPosition();const[s,i]=this.parentDimensions;this.setDims(this.width*s,this.height*i)},Hw=function(){f(this,is)===null||!this.parent||(this.parent.drawLayer.remove(f(this,is)),T(this,is,null),this.parent.drawLayer.remove(f(this,fn)),T(this,fn,null))},Xa=function(t=this.parent){f(this,is)===null&&({id:ds(this,is)._,clipPathId:ds(this,Xl)._}=t.drawLayer.draw(f(this,Vi),this.color,f(this,lo)),T(this,fn,t.drawLayer.drawOutline(f(this,hi))),f(this,Yl)&&(f(this,Yl).style.clipPath=f(this,Xl)))},yi=new WeakSet,Zc=function({x:t,y:s,width:i,height:r},o){switch(o){case 90:return{x:1-s-r,y:t,width:r,height:i};case 180:return{x:1-t-i,y:1-s-r,width:i,height:r};case 270:return{x:s,y:1-t-i,width:r,height:i}}return{x:t,y:s,width:i,height:r}},QM=function(t){ot._keyboardManager.exec(this,t)},jg=function(t){if(!f(this,lu))return;const s=window.getSelection();t?s.setPosition(f(this,lu),f(this,Pp)):s.setPosition(f(this,Rp),f(this,Mp))},$d=function(){return f(this,Rs)?this.rotation:0},eI=function(){if(f(this,Rs))return null;const[t,s]=this.pageDimensions,[i,r]=this.pageTranslation,o=f(this,ao),a=new Float32Array(o.length*8);let l=0;for(const{x:c,y:h,width:u,height:d}of o){const p=c*t+i,m=(1-h-d)*s+r;a[l]=a[l+4]=p,a[l+1]=a[l+3]=m,a[l+2]=a[l+6]=p+u*t,a[l+5]=a[l+7]=m+d*s,l+=8}return a},tI=function(t){return f(this,Vi).serialize(t,P(this,Oe,$d).call(this))},nI=function(t,s){this._freeHighlight.add(s)&&t.drawLayer.updatePath(this._freeHighlightId,this._freeHighlight)},sI=function(t,s){this._freeHighlight.isEmpty()?t.drawLayer.remove(this._freeHighlightId):t.createAndAddNewEditor(s,!1,{highlightId:this._freeHighlightId,highlightOutlines:this._freeHighlight.getOutlines(),clipPathId:this._freeHighlightClipId,methodOfCreation:"main_toolbar"}),this._freeHighlightId=-1,this._freeHighlight=null,this._freeHighlightClipId=""},iI=function(t){const{color:s}=this._initialData;return t.color.some((i,r)=>i!==s[r])},M(ot,yi),oe(ot,"_defaultColor",null),oe(ot,"_defaultOpacity",1),oe(ot,"_defaultThickness",12),oe(ot,"_type","highlight"),oe(ot,"_editorType",De.HIGHLIGHT),oe(ot,"_freeHighlightId",-1),oe(ot,"_freeHighlight",null),oe(ot,"_freeHighlightClipId","");let Ay=ot;var Jl,Ql,wr,co,di,ec,tc,nc,ho,du,sc,ic,da,ce,rI,oI,aI,lI,Uw,cI,qw,hI,uI,dI,fI,pI,Ya,Vw,Ww,Gw,Fg,zg,Xc,Kw,Hg,Po,mI,Zw,gI,yI,Xw,Bg,Td;const Ft=class Ft extends ft{constructor(t){super({...t,name:"inkEditor"});M(this,ce);M(this,Jl,0);M(this,Ql,0);M(this,wr,null);M(this,co,new Path2D);M(this,di,!1);M(this,ec,null);M(this,tc,!1);M(this,nc,!1);M(this,ho,null);M(this,du,null);M(this,sc,0);M(this,ic,0);M(this,da,null);this.color=t.color||null,this.thickness=t.thickness||null,this.opacity=t.opacity||null,this.paths=[],this.bezierPath2D=[],this.allRawPaths=[],this.currentPath=[],this.scaleFactor=1,this.translationX=this.translationY=0,this.x=0,this.y=0,this._willKeepAspectRatio=!0}static initialize(t,s){ft.initialize(t,s)}static updateDefaultParams(t,s){switch(t){case Te.INK_THICKNESS:Ft._defaultThickness=s;break;case Te.INK_COLOR:Ft._defaultColor=s;break;case Te.INK_OPACITY:Ft._defaultOpacity=s/100;break}}updateParams(t,s){switch(t){case Te.INK_THICKNESS:P(this,ce,rI).call(this,s);break;case Te.INK_COLOR:P(this,ce,oI).call(this,s);break;case Te.INK_OPACITY:P(this,ce,aI).call(this,s);break}}static get defaultPropertiesToUpdate(){return[[Te.INK_THICKNESS,Ft._defaultThickness],[Te.INK_COLOR,Ft._defaultColor||ft._defaultLineColor],[Te.INK_OPACITY,Math.round(Ft._defaultOpacity*100)]]}get propertiesToUpdate(){return[[Te.INK_THICKNESS,this.thickness||Ft._defaultThickness],[Te.INK_COLOR,this.color||Ft._defaultColor||ft._defaultLineColor],[Te.INK_OPACITY,Math.round(100*(this.opacity??Ft._defaultOpacity))]]}rebuild(){this.parent&&(super.rebuild(),this.div!==null&&(this.canvas||(P(this,ce,Fg).call(this),P(this,ce,zg).call(this)),this.isAttachedToDOM||(this.parent.add(this),P(this,ce,Xc).call(this)),P(this,ce,Td).call(this)))}remove(){var t;this.canvas!==null&&(this.isEmpty()||this.commit(),this.canvas.width=this.canvas.height=0,this.canvas.remove(),this.canvas=null,f(this,wr)&&(clearTimeout(f(this,wr)),T(this,wr,null)),(t=f(this,ho))==null||t.disconnect(),T(this,ho,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,s]=this.parentDimensions,i=this.width*t,r=this.height*s;this.setDimensions(i,r)}enableEditMode(){f(this,di)||this.canvas===null||(super.enableEditMode(),this._isDraggable=!1,P(this,ce,Vw).call(this))}disableEditMode(){!this.isInEditMode()||this.canvas===null||(super.disableEditMode(),this._isDraggable=!this.isEmpty(),this.div.classList.remove("editing"),P(this,ce,Ww).call(this))}onceAdded(){this._isDraggable=!this.isEmpty()}isEmpty(){return this.paths.length===0||this.paths.length===1&&this.paths[0].length===0}commit(){f(this,di)||(super.commit(),this.isEditing=!1,this.disableEditMode(),this.setInForeground(),T(this,di,!0),this.div.classList.add("disabled"),P(this,ce,Td).call(this,!0),this.select(),this.parent.addInkEditorIfNeeded(!0),this.moveInDOM(),this.div.focus({preventScroll:!0}))}focusin(t){this._focusEventsAllowed&&(super.focusin(t),this.enableEditMode())}canvasPointerdown(t){t.button!==0||!this.isInEditMode()||f(this,di)||(this.setInForeground(),t.preventDefault(),this.div.contains(document.activeElement)||this.div.focus({preventScroll:!0}),P(this,ce,cI).call(this,t.offsetX,t.offsetY))}canvasPointermove(t){t.preventDefault(),P(this,ce,qw).call(this,t.offsetX,t.offsetY)}canvasPointerup(t){t.preventDefault(),P(this,ce,Gw).call(this,t)}canvasPointerleave(t){P(this,ce,Gw).call(this,t)}get isResizable(){return!this.isEmpty()&&f(this,di)}render(){if(this.div)return this.div;let t,s;this.width&&(t=this.x,s=this.y),super.render(),this.div.setAttribute("data-l10n-id","pdfjs-ink");const[i,r,o,a]=P(this,ce,lI).call(this);if(this.setAt(i,r,0,0),this.setDims(o,a),P(this,ce,Fg).call(this),this.width){const[l,c]=this.parentDimensions;this.setAspectRatio(this.width*l,this.height*c),this.setAt(t*l,s*c,this.width*l,this.height*c),T(this,nc,!0),P(this,ce,Xc).call(this),this.setDims(this.width*l,this.height*c),P(this,ce,Ya).call(this),this.div.classList.add("disabled")}else this.div.classList.add("editing"),this.enableEditMode();return P(this,ce,zg).call(this),this.div}setDimensions(t,s){const i=Math.round(t),r=Math.round(s);if(f(this,sc)===i&&f(this,ic)===r)return;T(this,sc,i),T(this,ic,r),this.canvas.style.visibility="hidden";const[o,a]=this.parentDimensions;this.width=t/o,this.height=s/a,this.fixAndSetPosition(),f(this,di)&&P(this,ce,Kw).call(this,t,s),P(this,ce,Xc).call(this),P(this,ce,Ya).call(this),this.canvas.style.visibility="visible",this.fixDims()}static async deserialize(t,s,i){var v,g,b;if(t instanceof Nx)return null;const r=await super.deserialize(t,s,i);r.thickness=t.thickness,r.color=Se.makeHexColor(...t.color),r.opacity=t.opacity;const[o,a]=r.pageDimensions,l=r.width*o,c=r.height*a,h=r.parentScale,u=t.thickness/2;T(r,di,!0),T(r,sc,Math.round(l)),T(r,ic,Math.round(c));const{paths:d,rect:p,rotation:m}=t;for(let{bezier:_}of d){_=P(v=Ft,Po,gI).call(v,_,p,m);const x=[];r.paths.push(x);let A=h*(_[0]-u),C=h*(_[1]-u);for(let I=2,j=_.length;I{this.thickness=r,P(this,ce,Td).call(this)},i=this.thickness;this.addCommands({cmd:s.bind(this,t),undo:s.bind(this,i),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:Te.INK_THICKNESS,overwriteIfSameType:!0,keepUndo:!0})},oI=function(t){const s=r=>{this.color=r,P(this,ce,Ya).call(this)},i=this.color;this.addCommands({cmd:s.bind(this,t),undo:s.bind(this,i),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:Te.INK_COLOR,overwriteIfSameType:!0,keepUndo:!0})},aI=function(t){const s=r=>{this.opacity=r,P(this,ce,Ya).call(this)};t/=100;const i=this.opacity;this.addCommands({cmd:s.bind(this,t),undo:s.bind(this,i),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:Te.INK_OPACITY,overwriteIfSameType:!0,keepUndo:!0})},lI=function(){const{parentRotation:t,parentDimensions:[s,i]}=this;switch(t){case 90:return[0,i,i,s];case 180:return[s,i,s,i];case 270:return[s,0,i,s];default:return[0,0,s,i]}},Uw=function(){const{ctx:t,color:s,opacity:i,thickness:r,parentScale:o,scaleFactor:a}=this;t.lineWidth=r*o/a,t.lineCap="round",t.lineJoin="round",t.miterLimit=10,t.strokeStyle=`${s}${l8(i)}`},cI=function(t,s){this.canvas.addEventListener("contextmenu",Si,{signal:this._uiManager._signal}),P(this,ce,Ww).call(this),T(this,ec,new AbortController);const i=this._uiManager.combinedSignal(f(this,ec));this.canvas.addEventListener("pointerleave",this.canvasPointerleave.bind(this),{signal:i}),this.canvas.addEventListener("pointermove",this.canvasPointermove.bind(this),{signal:i}),this.canvas.addEventListener("pointerup",this.canvasPointerup.bind(this),{signal:i}),this.isEditing=!0,f(this,nc)||(T(this,nc,!0),P(this,ce,Xc).call(this),this.thickness||(this.thickness=Ft._defaultThickness),this.color||(this.color=Ft._defaultColor||ft._defaultLineColor),this.opacity??(this.opacity=Ft._defaultOpacity)),this.currentPath.push([t,s]),T(this,tc,!1),P(this,ce,Uw).call(this),T(this,da,()=>{P(this,ce,dI).call(this),f(this,da)&&window.requestAnimationFrame(f(this,da))}),window.requestAnimationFrame(f(this,da))},qw=function(t,s){const[i,r]=this.currentPath.at(-1);if(this.currentPath.length>1&&t===i&&s===r)return;const o=this.currentPath;let a=f(this,co);if(o.push([t,s]),T(this,tc,!0),o.length<=2){a.moveTo(...o[0]),a.lineTo(t,s);return}o.length===3&&(T(this,co,a=new Path2D),a.moveTo(...o[0])),P(this,ce,fI).call(this,a,...o.at(-3),...o.at(-2),t,s)},hI=function(){if(this.currentPath.length===0)return;const t=this.currentPath.at(-1);f(this,co).lineTo(...t)},uI=function(t,s){T(this,da,null),t=Math.min(Math.max(t,0),this.canvas.width),s=Math.min(Math.max(s,0),this.canvas.height),P(this,ce,qw).call(this,t,s),P(this,ce,hI).call(this);let i;if(this.currentPath.length!==1)i=P(this,ce,pI).call(this);else{const c=[t,s];i=[[c,c.slice(),c.slice(),c]]}const r=f(this,co),o=this.currentPath;this.currentPath=[],T(this,co,new Path2D);const a=()=>{this.allRawPaths.push(o),this.paths.push(i),this.bezierPath2D.push(r),this._uiManager.rebuild(this)},l=()=>{this.allRawPaths.pop(),this.paths.pop(),this.bezierPath2D.pop(),this.paths.length===0?this.remove():(this.canvas||(P(this,ce,Fg).call(this),P(this,ce,zg).call(this)),P(this,ce,Td).call(this))};this.addCommands({cmd:a,undo:l,mustExec:!0})},dI=function(){if(!f(this,tc))return;T(this,tc,!1);const t=Math.ceil(this.thickness*this.parentScale),s=this.currentPath.slice(-3),i=s.map(a=>a[0]),r=s.map(a=>a[1]);Math.min(...i)-t,Math.max(...i)+t,Math.min(...r)-t,Math.max(...r)+t;const{ctx:o}=this;o.save(),o.clearRect(0,0,this.canvas.width,this.canvas.height);for(const a of this.bezierPath2D)o.stroke(a);o.stroke(f(this,co)),o.restore()},fI=function(t,s,i,r,o,a,l){const c=(s+r)/2,h=(i+o)/2,u=(r+a)/2,d=(o+l)/2;t.bezierCurveTo(c+2*(r-c)/3,h+2*(o-h)/3,u+2*(r-u)/3,d+2*(o-d)/3,u,d)},pI=function(){const t=this.currentPath;if(t.length<=2)return[[t[0],t[0],t.at(-1),t.at(-1)]];const s=[];let i,[r,o]=t[0];for(i=1;i{T(this,wr,null),this.canvas.removeEventListener("contextmenu",Si)},10)),P(this,ce,uI).call(this,t.offsetX,t.offsetY),this.addToAnnotationStorage(),this.setInBackground()},Fg=function(){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")},zg=function(){T(this,ho,new ResizeObserver(t=>{const s=t[0].contentRect;s.width&&s.height&&this.setDimensions(s.width,s.height)})),f(this,ho).observe(this.div),this._uiManager._signal.addEventListener("abort",()=>{var t;(t=f(this,ho))==null||t.disconnect(),T(this,ho,null)},{once:!0})},Xc=function(){if(!f(this,nc))return;const[t,s]=this.parentDimensions;this.canvas.width=Math.ceil(this.width*t),this.canvas.height=Math.ceil(this.height*s),P(this,ce,Hg).call(this)},Kw=function(t,s){const i=P(this,ce,Bg).call(this),r=(t-i)/f(this,Ql),o=(s-i)/f(this,Jl);this.scaleFactor=Math.min(r,o)},Hg=function(){const t=P(this,ce,Bg).call(this)/2;this.ctx.setTransform(this.scaleFactor,0,0,this.scaleFactor,this.translationX*this.scaleFactor+t,this.translationY*this.scaleFactor+t)},Po=new WeakSet,mI=function(t){const s=new Path2D;for(let i=0,r=t.length;i`image/${s}`))}static get supportedTypesStr(){return Xe(this,"supportedTypesStr",this.supportedTypes.join(","))}static isHandlingMimeForPasting(t){return this.supportedTypes.includes(t)}static paste(t,s){s.pasteEditor(De.STAMP,{bitmapFile:t.getAsFile()})}altTextFinish(){this._uiManager.useNewAltTextFlow&&(this.div.hidden=!1),super.altTextFinish()}get telemetryFinalData(){var t;return{type:"stamp",hasAltText:!!((t=this.altTextData)!=null&&t.altText)}}static computeTelemetryFinalData(t){const s=t.get("hasAltText");return{hasAltText:s.get(!0)??0,hasNoAltText:s.get(!1)??0}}async mlGuessAltText(t=null,s=!0){if(this.hasAltTextData())return null;const{mlManager:i}=this._uiManager;if(!i)throw new Error("No ML.");if(!await i.isEnabledFor("altText"))throw new Error("ML isn't enabled for alt text.");const{data:r,width:o,height:a}=t||this.copyCanvas(null,null,!0).imageData,l=await i.guess({name:"altText",request:{data:r,width:o,height:a,channels:r.length/(o*a)}});if(!l)throw new Error("No response from the AI service.");if(l.error)throw new Error("Error from the AI service.");if(l.cancel)return null;if(!l.output)throw new Error("No valid response from the AI service.");const c=l.output;return await this.setGuessedAltText(c),s&&!this.hasAltTextData()&&(this.altTextData={alt:c,decorative:!1}),c}remove(){var t,s;f(this,Fn)&&(T(this,Ht,null),this._uiManager.imageManager.deleteId(f(this,Fn)),(t=f(this,_r))==null||t.remove(),T(this,_r,null),(s=f(this,fo))==null||s.disconnect(),T(this,fo,null),f(this,Sr)&&(clearTimeout(f(this,Sr)),T(this,Sr,null))),super.remove()}rebuild(){if(!this.parent){f(this,Fn)&&P(this,Ze,Ug).call(this);return}super.rebuild(),this.div!==null&&(f(this,Fn)&&f(this,_r)===null&&P(this,Ze,Ug).call(this),this.isAttachedToDOM||this.parent.add(this))}onceAdded(){this._isDraggable=!0,this.div.focus()}isEmpty(){return!(f(this,fa)||f(this,Ht)||f(this,uo)||f(this,pa)||f(this,Fn))}get isResizable(){return!0}render(){if(this.div)return this.div;let t,s;if(this.width&&(t=this.x,s=this.y),super.render(),this.div.hidden=!0,this.div.setAttribute("role","figure"),this.addAltTextButton(),f(this,Ht)?P(this,Ze,Jw).call(this):P(this,Ze,Ug).call(this),this.width&&!this.annotationElementId){const[i,r]=this.parentDimensions;this.setAt(t*i,s*r,this.width*i,this.height*r)}return this.div}copyCanvas(t,s,i=!1){var p;t||(t=224);const{width:r,height:o}=f(this,Ht),a=new Gb;let l=f(this,Ht),c=r,h=o,u=null;if(s){if(r>s||o>s){const I=Math.min(s/r,s/o);c=Math.floor(r*I),h=Math.floor(o*I)}u=document.createElement("canvas");const m=u.width=Math.ceil(c*a.sx),y=u.height=Math.ceil(h*a.sy);f(this,Ys)||(l=P(this,Ze,qg).call(this,m,y));const v=u.getContext("2d");v.filter=this._uiManager.hcmFilter;let g="white",b="#cfcfd8";this._uiManager.hcmFilter!=="none"?b="black":(p=window.matchMedia)!=null&&p.call(window,"(prefers-color-scheme: dark)").matches&&(g="#8f8f9d",b="#42414d");const _=15,x=_*a.sx,A=_*a.sy,C=new OffscreenCanvas(x*2,A*2),$=C.getContext("2d");$.fillStyle=g,$.fillRect(0,0,x*2,A*2),$.fillStyle=b,$.fillRect(0,0,x,A),$.fillRect(x,A,x,A),v.fillStyle=v.createPattern(C,"repeat"),v.fillRect(0,0,m,y),v.drawImage(l,0,0,l.width,l.height,0,0,m,y)}let d=null;if(i){let m,y;if(a.symmetric&&l.widtht||o>t){const b=Math.min(t/r,t/o);m=Math.floor(r*b),y=Math.floor(o*b),f(this,Ys)||(l=P(this,Ze,qg).call(this,m,y))}const g=new OffscreenCanvas(m,y).getContext("2d",{willReadFrequently:!0});g.drawImage(l,0,0,l.width,l.height,0,0,m,y),d={width:m,height:y,data:g.getImageData(0,0,m,y).data}}return{canvas:u,width:c,height:h,imageData:d}}getImageForAltText(){return f(this,_r)}static async deserialize(t,s,i){var y;let r=null;if(t instanceof PM){const{data:{rect:v,rotation:g,id:b,structParent:_,popupRef:x},container:A,parent:{page:{pageNumber:C}}}=t,$=A.querySelector("canvas"),I=i.imageManager.getFromCanvas(A.id,$);$.remove();const j=((y=await s._structTree.getAriaAttributes(`${Ax}${b}`))==null?void 0:y.get("aria-label"))||"";r=t={annotationType:De.STAMP,bitmapId:I.id,bitmap:I.bitmap,pageIndex:C-1,rect:v.slice(0),rotation:g,id:b,deleted:!1,accessibilityData:{decorative:!1,altText:j},isSvg:!1,structParent:_,popupRef:x}}const o=await super.deserialize(t,s,i),{rect:a,bitmap:l,bitmapUrl:c,bitmapId:h,isSvg:u,accessibilityData:d}=t;h&&i.imageManager.isValidId(h)?(T(o,Fn,h),l&&T(o,Ht,l)):T(o,uo,c),T(o,Ys,u);const[p,m]=o.pageDimensions;return o.width=(a[2]-a[0])/p,o.height=(a[3]-a[1])/m,o.annotationElementId=t.id||null,d&&(o.altTextData=d),o._initialData=r,T(o,pu,!!r),o}serialize(t=!1,s=null){if(this.isEmpty())return null;if(this.deleted)return this.serializeDeleted();const i={annotationType:De.STAMP,bitmapId:f(this,Fn),pageIndex:this.pageIndex,rect:this.getRect(0,0),rotation:this.rotation,isSvg:f(this,Ys),structTreeParentId:this._structTreeParentId};if(t)return i.bitmapUrl=P(this,Ze,Vg).call(this,!0),i.accessibilityData=this.serializeAltText(!0),i;const{decorative:r,altText:o}=this.serializeAltText(!1);if(!r&&o&&(i.accessibilityData={type:"Figure",alt:o}),this.annotationElementId){const l=P(this,Ze,wI).call(this,i);if(l.isSame)return null;l.isSameAltText?delete i.accessibilityData:i.accessibilityData.structParent=this._initialData.structParent??-1}if(i.id=this.annotationElementId,s===null)return i;s.stamps||(s.stamps=new Map);const a=f(this,Ys)?(i.rect[2]-i.rect[0])*(i.rect[3]-i.rect[1]):null;if(!s.stamps.has(f(this,Fn)))s.stamps.set(f(this,Fn),{area:a,serialized:i}),i.bitmap=P(this,Ze,Vg).call(this,!1);else if(f(this,Ys)){const l=s.stamps.get(f(this,Fn));a>l.area&&(l.area=a,l.serialized.bitmap.close(),l.serialized.bitmap=P(this,Ze,Vg).call(this,!1))}return i}renderAnnotationElement(t){return t.updateEdited({rect:this.getRect(0,0)}),null}};Ht=new WeakMap,Fn=new WeakMap,fa=new WeakMap,uo=new WeakMap,pa=new WeakMap,fu=new WeakMap,_r=new WeakMap,fo=new WeakMap,Sr=new WeakMap,Ys=new WeakMap,pu=new WeakMap,Ze=new WeakSet,Pd=function(t,s=!1){if(!t){this.remove();return}T(this,Ht,t.bitmap),s||(T(this,Fn,t.id),T(this,Ys,t.isSvg)),t.file&&T(this,fu,t.file.name),P(this,Ze,Jw).call(this)},Rd=function(){if(T(this,fa,null),this._uiManager.enableWaiting(!1),!!f(this,_r)){if(this._uiManager.useNewAltTextWhenAddingImage&&this._uiManager.useNewAltTextFlow&&f(this,Ht)){this._editToolbar.hide(),this._uiManager.editAltText(this,!0);return}if(!this._uiManager.useNewAltTextWhenAddingImage&&this._uiManager.useNewAltTextFlow&&f(this,Ht)){this._reportTelemetry({action:"pdfjs.image.image_added",data:{alt_text_modal:!1,alt_text_type:"empty"}});try{this.mlGuessAltText()}catch{}}this.div.focus()}},Ug=function(){if(f(this,Fn)){this._uiManager.enableWaiting(!0),this._uiManager.imageManager.getFromId(f(this,Fn)).then(i=>P(this,Ze,Pd).call(this,i,!0)).finally(()=>P(this,Ze,Rd).call(this));return}if(f(this,uo)){const i=f(this,uo);T(this,uo,null),this._uiManager.enableWaiting(!0),T(this,fa,this._uiManager.imageManager.getFromUrl(i).then(r=>P(this,Ze,Pd).call(this,r)).finally(()=>P(this,Ze,Rd).call(this)));return}if(f(this,pa)){const i=f(this,pa);T(this,pa,null),this._uiManager.enableWaiting(!0),T(this,fa,this._uiManager.imageManager.getFromFile(i).then(r=>P(this,Ze,Pd).call(this,r)).finally(()=>P(this,Ze,Rd).call(this)));return}const t=document.createElement("input");t.type="file",t.accept=nf.supportedTypesStr;const s=this._uiManager._signal;T(this,fa,new Promise(i=>{t.addEventListener("change",async()=>{if(!t.files||t.files.length===0)this.remove();else{this._uiManager.enableWaiting(!0);const r=await this._uiManager.imageManager.getFromFile(t.files[0]);this._reportTelemetry({action:"pdfjs.image.image_selected",data:{alt_text_modal:this._uiManager.useNewAltTextFlow}}),P(this,Ze,Pd).call(this,r)}i()},{signal:s}),t.addEventListener("cancel",()=>{this.remove(),i()},{signal:s})}).finally(()=>P(this,Ze,Rd).call(this))),t.click()},Jw=function(){const{div:t}=this;let{width:s,height:i}=f(this,Ht);const[r,o]=this.pageDimensions,a=.75;if(this.width)s=this.width*r,i=this.height*o;else if(s>a*r||i>a*o){const u=Math.min(a*r/s,a*o/i);s*=u,i*=u}const[l,c]=this.parentDimensions;this.setDims(s*l/r,i*c/o),this._uiManager.enableWaiting(!1);const h=T(this,_r,document.createElement("canvas"));h.setAttribute("role","img"),this.addContainer(h),(!this._uiManager.useNewAltTextWhenAddingImage||!this._uiManager.useNewAltTextFlow||this.annotationElementId)&&(t.hidden=!1),P(this,Ze,Qw).call(this,s,i),P(this,Ze,bI).call(this),f(this,pu)||(this.parent.addUndoableEditor(this),T(this,pu,!0)),this._reportTelemetry({action:"inserted_image"}),f(this,fu)&&h.setAttribute("aria-label",f(this,fu))},vI=function(t,s){var a;const[i,r]=this.parentDimensions;this.width=t/i,this.height=s/r,(a=this._initialOptions)!=null&&a.isCentered?this.center():this.fixAndSetPosition(),this._initialOptions=null,f(this,Sr)!==null&&clearTimeout(f(this,Sr)),T(this,Sr,setTimeout(()=>{T(this,Sr,null),P(this,Ze,Qw).call(this,t,s)},200))},qg=function(t,s){const{width:i,height:r}=f(this,Ht);let o=i,a=r,l=f(this,Ht);for(;o>2*t||a>2*s;){const c=o,h=a;o>2*t&&(o=o>=16384?Math.floor(o/2)-1:Math.ceil(o/2)),a>2*s&&(a=a>=16384?Math.floor(a/2)-1:Math.ceil(a/2));const u=new OffscreenCanvas(o,a);u.getContext("2d").drawImage(l,0,0,c,h,0,0,o,a),l=u.transferToImageBitmap()}return l},Qw=function(t,s){const i=new Gb,r=Math.ceil(t*i.sx),o=Math.ceil(s*i.sy),a=f(this,_r);if(!a||a.width===r&&a.height===o)return;a.width=r,a.height=o;const l=f(this,Ys)?f(this,Ht):P(this,Ze,qg).call(this,r,o),c=a.getContext("2d");c.filter=this._uiManager.hcmFilter,c.drawImage(l,0,0,l.width,l.height,0,0,r,o)},Vg=function(t){if(t){if(f(this,Ys)){const r=this._uiManager.imageManager.getSvgUrl(f(this,Fn));if(r)return r}const s=document.createElement("canvas");return{width:s.width,height:s.height}=f(this,Ht),s.getContext("2d").drawImage(f(this,Ht),0,0),s.toDataURL()}if(f(this,Ys)){const[s,i]=this.pageDimensions,r=Math.round(this.width*s*Ta.PDF_TO_CSS_UNITS),o=Math.round(this.height*i*Ta.PDF_TO_CSS_UNITS),a=new OffscreenCanvas(r,o);return a.getContext("2d").drawImage(f(this,Ht),0,0,f(this,Ht).width,f(this,Ht).height,0,0,r,o),a.transferToImageBitmap()}return structuredClone(f(this,Ht))},bI=function(){this._uiManager._signal&&(T(this,fo,new ResizeObserver(t=>{const s=t[0].contentRect;s.width&&s.height&&P(this,Ze,vI).call(this,s.width,s.height)})),f(this,fo).observe(this.div),this._uiManager._signal.addEventListener("abort",()=>{var t;(t=f(this,fo))==null||t.disconnect(),T(this,fo,null)},{once:!0}))},wI=function(t){var c;const{rect:s,pageIndex:i,accessibilityData:{altText:r}}=this._initialData,o=t.rect.every((h,u)=>Math.abs(h-s[u])<1),a=t.pageIndex===i,l=(((c=t.accessibilityData)==null?void 0:c.alt)||"")===r;return{isSame:o&&a&&l,isSameAltText:l}},oe(nf,"_type","stamp"),oe(nf,"_editorType",De.STAMP);let Yw=nf;var rc,mu,xr,ma,po,Js,ga,gu,yu,rs,mo,ke,ya,Gn,_I,t_,n_,s_,Wg;const Ri=class Ri{constructor({uiManager:e,pageIndex:t,div:s,structTreeLayer:i,accessibilityManager:r,annotationLayer:o,drawLayer:a,textLayer:l,viewport:c,l10n:h}){M(this,Gn);M(this,rc);M(this,mu,!1);M(this,xr,null);M(this,ma,null);M(this,po,null);M(this,Js,new Map);M(this,ga,!1);M(this,gu,!1);M(this,yu,!1);M(this,rs,null);M(this,mo,null);M(this,ke);const u=[...f(Ri,ya).values()];if(!Ri._initialized){Ri._initialized=!0;for(const d of u)d.initialize(h,e)}e.registerEditorTypes(u),T(this,ke,e),this.pageIndex=t,this.div=s,T(this,rc,r),T(this,xr,o),this.viewport=c,T(this,rs,l),this.drawLayer=a,this._structTree=i,f(this,ke).addLayer(this)}get isEmpty(){return f(this,Js).size===0}get isInvisible(){return this.isEmpty&&f(this,ke).getMode()===De.NONE}updateToolbar(e){f(this,ke).updateToolbar(e)}updateMode(e=f(this,ke).getMode()){switch(P(this,Gn,Wg).call(this),e){case De.NONE:this.disableTextSelection(),this.togglePointerEvents(!1),this.toggleAnnotationLayerPointerEvents(!0),this.disableClick();return;case De.INK:this.addInkEditorIfNeeded(!1),this.disableTextSelection(),this.togglePointerEvents(!0),this.disableClick();break;case De.HIGHLIGHT:this.enableTextSelection(),this.togglePointerEvents(!1),this.disableClick();break;default:this.disableTextSelection(),this.togglePointerEvents(!0),this.enableClick()}this.toggleAnnotationLayerPointerEvents(!1);const{classList:t}=this.div;for(const s of f(Ri,ya).values())t.toggle(`${s._type}Editing`,e===s._editorType);this.div.hidden=!1}hasTextLayer(e){var t;return e===((t=f(this,rs))==null?void 0:t.div)}addInkEditorIfNeeded(e){if(f(this,ke).getMode()!==De.INK)return;if(!e){for(const s of f(this,Js).values())if(s.isEmpty()){s.setInBackground();return}}this.createAndAddNewEditor({offsetX:0,offsetY:0},!1).setInBackground()}setEditingState(e){f(this,ke).setEditingState(e)}addCommands(e){f(this,ke).addCommands(e)}toggleDrawing(e=!1){this.div.classList.toggle("drawing",!e)}togglePointerEvents(e=!1){this.div.classList.toggle("disabled",!e)}toggleAnnotationLayerPointerEvents(e=!1){var t;(t=f(this,xr))==null||t.div.classList.toggle("disabled",!e)}async enable(){this.div.tabIndex=0,this.togglePointerEvents(!0);const e=new Set;for(const s of f(this,Js).values())s.enableEditing(),s.show(!0),s.annotationElementId&&(f(this,ke).removeChangedExistingAnnotation(s),e.add(s.annotationElementId));if(!f(this,xr))return;const t=f(this,xr).getEditableAnnotations();for(const s of t){if(s.hide(),f(this,ke).isDeletedAnnotationElement(s.data.id)||e.has(s.data.id))continue;const i=await this.deserialize(s);i&&(this.addOrRebuild(i),i.enableEditing())}}disable(){var i;T(this,yu,!0),this.div.tabIndex=-1,this.togglePointerEvents(!1);const e=new Map,t=new Map;for(const r of f(this,Js).values())if(r.disableEditing(),!!r.annotationElementId){if(r.serialize()!==null){e.set(r.annotationElementId,r);continue}else t.set(r.annotationElementId,r);(i=this.getEditableAnnotation(r.annotationElementId))==null||i.show(),r.remove()}if(f(this,xr)){const r=f(this,xr).getEditableAnnotations();for(const o of r){const{id:a}=o.data;if(f(this,ke).isDeletedAnnotationElement(a))continue;let l=t.get(a);if(l){l.resetAnnotationElement(o),l.show(!1),o.show();continue}l=e.get(a),l&&(f(this,ke).addChangedExistingAnnotation(l),l.renderAnnotationElement(o)&&l.show(!1)),o.show()}}P(this,Gn,Wg).call(this),this.isEmpty&&(this.div.hidden=!0);const{classList:s}=this.div;for(const r of f(Ri,ya).values())s.remove(`${r._type}Editing`);this.disableTextSelection(),this.toggleAnnotationLayerPointerEvents(!0),T(this,yu,!1)}getEditableAnnotation(e){var t;return((t=f(this,xr))==null?void 0:t.getEditableAnnotation(e))||null}setActiveEditor(e){f(this,ke).getActive()!==e&&f(this,ke).setActiveEditor(e)}enableTextSelection(){var e;if(this.div.tabIndex=-1,(e=f(this,rs))!=null&&e.div&&!f(this,mo)){T(this,mo,new AbortController);const t=f(this,ke).combinedSignal(f(this,mo));f(this,rs).div.addEventListener("pointerdown",P(this,Gn,_I).bind(this),{signal:t}),f(this,rs).div.classList.add("highlighting")}}disableTextSelection(){var e;this.div.tabIndex=0,(e=f(this,rs))!=null&&e.div&&f(this,mo)&&(f(this,mo).abort(),T(this,mo,null),f(this,rs).div.classList.remove("highlighting"))}enableClick(){if(f(this,ma))return;T(this,ma,new AbortController);const e=f(this,ke).combinedSignal(f(this,ma));this.div.addEventListener("pointerdown",this.pointerdown.bind(this),{signal:e}),this.div.addEventListener("pointerup",this.pointerup.bind(this),{signal:e})}disableClick(){var e;(e=f(this,ma))==null||e.abort(),T(this,ma,null)}attach(e){f(this,Js).set(e.id,e);const{annotationElementId:t}=e;t&&f(this,ke).isDeletedAnnotationElement(t)&&f(this,ke).removeDeletedAnnotationElement(e)}detach(e){var t;f(this,Js).delete(e.id),(t=f(this,rc))==null||t.removePointerInTextLayer(e.contentDiv),!f(this,yu)&&e.annotationElementId&&f(this,ke).addDeletedAnnotationElement(e)}remove(e){this.detach(e),f(this,ke).removeEditor(e),e.div.remove(),e.isAttachedToDOM=!1,f(this,gu)||this.addInkEditorIfNeeded(!1)}changeParent(e){var t;e.parent!==this&&(e.parent&&e.annotationElementId&&(f(this,ke).addDeletedAnnotationElement(e.annotationElementId),ft.deleteAnnotationElement(e),e.annotationElementId=null),this.attach(e),(t=e.parent)==null||t.detach(e),e.setParent(this),e.div&&e.isAttachedToDOM&&(e.div.remove(),this.div.append(e.div)))}add(e){if(!(e.parent===this&&e.isAttachedToDOM)){if(this.changeParent(e),f(this,ke).addEditor(e),this.attach(e),!e.isAttachedToDOM){const t=e.render();this.div.append(t),e.isAttachedToDOM=!0}e.fixAndSetPosition(),e.onceAdded(),f(this,ke).addToAnnotationStorage(e),e._reportTelemetry(e.telemetryInitialData)}}moveEditorInDOM(e){var s;if(!e.isAttachedToDOM)return;const{activeElement:t}=document;e.div.contains(t)&&!f(this,po)&&(e._focusEventsAllowed=!1,T(this,po,setTimeout(()=>{T(this,po,null),e.div.contains(document.activeElement)?e._focusEventsAllowed=!0:(e.div.addEventListener("focusin",()=>{e._focusEventsAllowed=!0},{once:!0,signal:f(this,ke)._signal}),t.focus())},0))),e._structTreeParentId=(s=f(this,rc))==null?void 0:s.moveElementInDOM(this.div,e.div,e.contentDiv,!0)}addOrRebuild(e){e.needsToBeRebuilt()?(e.parent||(e.parent=this),e.rebuild(),e.show()):this.add(e)}addUndoableEditor(e){const t=()=>e._uiManager.rebuild(e),s=()=>{e.remove()};this.addCommands({cmd:t,undo:s,mustExec:!1})}getNextId(){return f(this,ke).getId()}combinedSignal(e){return f(this,ke).combinedSignal(e)}canCreateNewEmptyEditor(){var e;return(e=f(this,Gn,t_))==null?void 0:e.canCreateNewEmptyEditor()}pasteEditor(e,t){f(this,ke).updateToolbar(e),f(this,ke).updateMode(e);const{offsetX:s,offsetY:i}=P(this,Gn,s_).call(this),r=this.getNextId(),o=P(this,Gn,n_).call(this,{parent:this,id:r,x:s,y:i,uiManager:f(this,ke),isCentered:!0,...t});o&&this.add(o)}async deserialize(e){var t;return await((t=f(Ri,ya).get(e.annotationType??e.annotationEditorType))==null?void 0:t.deserialize(e,this,f(this,ke)))||null}createAndAddNewEditor(e,t,s={}){const i=this.getNextId(),r=P(this,Gn,n_).call(this,{parent:this,id:i,x:e.offsetX,y:e.offsetY,uiManager:f(this,ke),isCentered:t,...s});return r&&this.add(r),r}addNewEditor(){this.createAndAddNewEditor(P(this,Gn,s_).call(this),!0)}setSelected(e){f(this,ke).setSelected(e)}toggleSelected(e){f(this,ke).toggleSelected(e)}unselect(e){f(this,ke).unselect(e)}pointerup(e){const{isMac:t}=bs.platform;if(!(e.button!==0||e.ctrlKey&&t)&&e.target===this.div&&f(this,ga)){if(T(this,ga,!1),!f(this,mu)){T(this,mu,!0);return}if(f(this,ke).getMode()===De.STAMP){f(this,ke).unselectAll();return}this.createAndAddNewEditor(e,!1)}}pointerdown(e){if(f(this,ke).getMode()===De.HIGHLIGHT&&this.enableTextSelection(),f(this,ga)){T(this,ga,!1);return}const{isMac:t}=bs.platform;if(e.button!==0||e.ctrlKey&&t||e.target!==this.div)return;T(this,ga,!0);const s=f(this,ke).getActive();T(this,mu,!s||s.isEmpty())}findNewParent(e,t,s){const i=f(this,ke).findParent(t,s);return i===null||i===this?!1:(i.changeParent(e),!0)}destroy(){var e,t;((e=f(this,ke).getActive())==null?void 0:e.parent)===this&&(f(this,ke).commitOrRemove(),f(this,ke).setActiveEditor(null)),f(this,po)&&(clearTimeout(f(this,po)),T(this,po,null));for(const s of f(this,Js).values())(t=f(this,rc))==null||t.removePointerInTextLayer(s.contentDiv),s.setParent(null),s.isAttachedToDOM=!1,s.div.remove();this.div=null,f(this,Js).clear(),f(this,ke).removeLayer(this)}render({viewport:e}){this.viewport=e,pc(this.div,e);for(const t of f(this,ke).getEditors(this.pageIndex))this.add(t),t.rebuild();this.updateMode()}update({viewport:e}){f(this,ke).commitOrRemove(),P(this,Gn,Wg).call(this);const t=this.viewport.rotation,s=e.rotation;if(this.viewport=e,pc(this.div,{rotation:s}),t!==s)for(const i of f(this,Js).values())i.rotate(s);this.addInkEditorIfNeeded(!1)}get pageDimensions(){const{pageWidth:e,pageHeight:t}=this.viewport.rawDims;return[e,t]}get scale(){return f(this,ke).viewParameters.realScale}};rc=new WeakMap,mu=new WeakMap,xr=new WeakMap,ma=new WeakMap,po=new WeakMap,Js=new WeakMap,ga=new WeakMap,gu=new WeakMap,yu=new WeakMap,rs=new WeakMap,mo=new WeakMap,ke=new WeakMap,ya=new WeakMap,Gn=new WeakSet,_I=function(e){f(this,ke).unselectAll();const{target:t}=e;if(t===f(this,rs).div||(t.getAttribute("role")==="img"||t.classList.contains("endOfContent"))&&f(this,rs).div.contains(t)){const{isMac:s}=bs.platform;if(e.button!==0||e.ctrlKey&&s)return;f(this,ke).showAllEditors("highlight",!0,!0),f(this,rs).div.classList.add("free"),this.toggleDrawing(),Ay.startHighlighting(this,f(this,ke).direction==="ltr",{target:f(this,rs).div,x:e.x,y:e.y}),f(this,rs).div.addEventListener("pointerup",()=>{f(this,rs).div.classList.remove("free"),this.toggleDrawing(!0)},{once:!0,signal:f(this,ke)._signal}),e.preventDefault()}},t_=function(){return f(Ri,ya).get(f(this,ke).getMode())},n_=function(e){const t=f(this,Gn,t_);return t?new t.prototype.constructor(e):null},s_=function(){const{x:e,y:t,width:s,height:i}=this.div.getBoundingClientRect(),r=Math.max(0,e),o=Math.max(0,t),a=Math.min(window.innerWidth,e+s),l=Math.min(window.innerHeight,t+i),c=(r+a)/2-e,h=(o+l)/2-t,[u,d]=this.viewport.rotation%180===0?[c,h]:[h,c];return{offsetX:u,offsetY:d}},Wg=function(){T(this,gu,!0);for(const e of f(this,Js).values())e.isEmpty()&&e.remove();T(this,gu,!1)},oe(Ri,"_initialized",!1),M(Ri,ya,new Map([Iw,Bw,Yw,Ay].map(e=>[e._editorType,e])));let e_=Ri;var Ar,Op,rn,go,Np,r_,kc,o_,SI;const Ln=class Ln{constructor({pageIndex:e}){M(this,kc);M(this,Ar,null);M(this,Op,0);M(this,rn,new Map);M(this,go,new Map);this.pageIndex=e}setParent(e){if(!f(this,Ar)){T(this,Ar,e);return}if(f(this,Ar)!==e){if(f(this,rn).size>0)for(const t of f(this,rn).values())t.remove(),e.append(t);T(this,Ar,e)}}static get _svgFactory(){return Xe(this,"_svgFactory",new Ox)}draw(e,t,s,i=!1){const r=ds(this,Op)._++,o=P(this,kc,o_).call(this,e.box);o.classList.add(...e.classNamesForDrawing);const a=Ln._svgFactory.createElement("defs");o.append(a);const l=Ln._svgFactory.createElement("path");a.append(l);const c=`path_p${this.pageIndex}_${r}`;l.setAttribute("id",c),l.setAttribute("d",e.toSVGPath()),i&&f(this,go).set(r,l);const h=P(this,kc,SI).call(this,a,c),u=Ln._svgFactory.createElement("use");return o.append(u),o.setAttribute("fill",t),o.setAttribute("fill-opacity",s),u.setAttribute("href",`#${c}`),f(this,rn).set(r,o),{id:r,clipPathId:`url(#${h})`}}drawOutline(e){const t=ds(this,Op)._++,s=P(this,kc,o_).call(this,e.box);s.classList.add(...e.classNamesForOutlining);const i=Ln._svgFactory.createElement("defs");s.append(i);const r=Ln._svgFactory.createElement("path");i.append(r);const o=`path_p${this.pageIndex}_${t}`;r.setAttribute("id",o),r.setAttribute("d",e.toSVGPath()),r.setAttribute("vector-effect","non-scaling-stroke");let a;if(e.mustRemoveSelfIntersections){const h=Ln._svgFactory.createElement("mask");i.append(h),a=`mask_p${this.pageIndex}_${t}`,h.setAttribute("id",a),h.setAttribute("maskUnits","objectBoundingBox");const u=Ln._svgFactory.createElement("rect");h.append(u),u.setAttribute("width","1"),u.setAttribute("height","1"),u.setAttribute("fill","white");const d=Ln._svgFactory.createElement("use");h.append(d),d.setAttribute("href",`#${o}`),d.setAttribute("stroke","none"),d.setAttribute("fill","black"),d.setAttribute("fill-rule","nonzero"),d.classList.add("mask")}const l=Ln._svgFactory.createElement("use");s.append(l),l.setAttribute("href",`#${o}`),a&&l.setAttribute("mask",`url(#${a})`);const c=l.cloneNode();return s.append(c),l.classList.add("mainOutline"),c.classList.add("secondaryOutline"),f(this,rn).set(t,s),t}finalizeLine(e,t){const s=f(this,go).get(e);f(this,go).delete(e),this.updateBox(e,t.box),s.setAttribute("d",t.toSVGPath())}updateLine(e,t){f(this,rn).get(e).firstChild.firstChild.setAttribute("d",t.toSVGPath())}updatePath(e,t){f(this,go).get(e).setAttribute("d",t.toSVGPath())}updateBox(e,t){var s;P(s=Ln,Np,r_).call(s,f(this,rn).get(e),t)}show(e,t){f(this,rn).get(e).classList.toggle("hidden",!t)}rotate(e,t){f(this,rn).get(e).setAttribute("data-main-rotation",t)}changeColor(e,t){f(this,rn).get(e).setAttribute("fill",t)}changeOpacity(e,t){f(this,rn).get(e).setAttribute("fill-opacity",t)}addClass(e,t){f(this,rn).get(e).classList.add(t)}removeClass(e,t){f(this,rn).get(e).classList.remove(t)}getSVGRoot(e){return f(this,rn).get(e)}remove(e){f(this,go).delete(e),f(this,Ar)!==null&&(f(this,rn).get(e).remove(),f(this,rn).delete(e))}destroy(){T(this,Ar,null);for(const e of f(this,rn).values())e.remove();f(this,rn).clear(),f(this,go).clear()}};Ar=new WeakMap,Op=new WeakMap,rn=new WeakMap,go=new WeakMap,Np=new WeakSet,r_=function(e,{x:t=0,y:s=0,width:i=1,height:r=1}={}){const{style:o}=e;o.top=`${100*s}%`,o.left=`${100*t}%`,o.width=`${100*i}%`,o.height=`${100*r}%`},kc=new WeakSet,o_=function(e){var s;const t=Ln._svgFactory.create(1,1,!0);return f(this,Ar).append(t),t.setAttribute("aria-hidden",!0),P(s=Ln,Np,r_).call(s,t,e),t},SI=function(e,t){const s=Ln._svgFactory.createElement("clipPath");e.append(s);const i=`clip_${t}`;s.setAttribute("id",i),s.setAttribute("clipPathUnits","objectBoundingBox");const r=Ln._svgFactory.createElement("use");return s.append(r),r.setAttribute("href",`#${t}`),r.classList.add("clip"),i},M(Ln,Np);let i_=Ln;Me.AbortException;Me.AnnotationEditorLayer;Me.AnnotationEditorParamsType;Me.AnnotationEditorType;Me.AnnotationEditorUIManager;var xI=Me.AnnotationLayer,AI=Me.AnnotationMode;Me.ColorPicker;Me.DOMSVGFactory;Me.DrawLayer;Me.FeatureTest;var H0=Me.GlobalWorkerOptions;Me.ImageKind;Me.InvalidPDFException;Me.MissingPDFException;Me.OPS;Me.OutputScale;var HZ=Me.PDFDataRangeTransport;Me.PDFDateString;Me.PDFWorker;Me.PasswordResponses;Me.PermissionFlag;Me.PixelsPerInch;Me.RenderingCancelledException;var kI=Me.TextLayer;Me.UnexpectedResponseException;Me.Util;Me.VerbosityLevel;Me.XfaLayer;Me.build;Me.createValidAbsoluteUrl;Me.fetchData;var EI=Me.getDocument;Me.getFilenameFromUrl;Me.getPdfFilenameFromUrl;Me.getXfaPageViewport;Me.isDataScheme;Me.isPdfFile;Me.noContextMenu;Me.normalizeUnicode;Me.setLayerDimensions;Me.shadow;var a_=Me.version;const BZ=Object.freeze(Object.defineProperty({__proto__:null,AnnotationLayer:xI,AnnotationMode:AI,GlobalWorkerOptions:H0,PDFDataRangeTransport:HZ,TextLayer:kI,getDocument:EI,version:a_},Symbol.toStringTag,{value:"Module"}));var _n=function(n,e,t){if(t||arguments.length===2)for(var s=0,i=e.length,r;s{yt(this.pdfDocument),yt(e),typeof e=="string"?this.pdfDocument.getDestination(e).then(t):Array.isArray(e)?t(e):e.then(t)}).then(t=>{yt(Array.isArray(t));const s=t[0];new Promise(i=>{yt(this.pdfDocument),s instanceof Object?this.pdfDocument.getPageIndex(s).then(r=>{i(r)}).catch(()=>{yt(!1)}):typeof s=="number"?i(s):yt(!1)}).then(i=>{const r=i+1;yt(this.pdfViewer),yt(r>=1&&r<=this.pagesCount),this.pdfViewer.scrollPageIntoView({dest:t,pageIndex:i,pageNumber:r})})})}navigateTo(e){this.goToDestination(e)}goToPage(e){const t=e-1;yt(this.pdfViewer),yt(e>=1&&e<=this.pagesCount),this.pdfViewer.scrollPageIntoView({pageIndex:t,pageNumber:e})}addLinkAttributes(e,t,s){e.href=t,e.rel=this.externalLinkRel||uX,e.target=s?"_blank":this.externalLinkTarget||""}getDestinationHash(){return"#"}getAnchorUrl(){return"#"}setHash(){}executeNamedAction(){}cachePageRef(){}isPageVisible(){return!0}isPageCached(){return!0}executeSetOCGState(){}}const fE={NEED_PASSWORD:1,INCORRECT_PASSWORD:2},B0=typeof window<"u",TI=B0&&window.location.protocol==="file:";function fX(n){return typeof n<"u"}function qa(n){return fX(n)&&n!==null}function pX(n){return typeof n=="string"}function mX(n){return n instanceof ArrayBuffer}function gX(n){return yt(B0),n instanceof Blob}function l_(n){return pX(n)&&/^data:/.test(n)}function pE(n){yt(l_(n));const[e="",t=""]=n.split(",");return e.split(";").indexOf("base64")!==-1?atob(t):unescape(t)}function yX(){return B0&&window.devicePixelRatio||1}const PI="On Chromium based browsers, you can use --allow-file-access-from-files flag for debugging purposes.";function mE(){as(!TI,`Loading PDF as base64 strings/URLs may not work on protocols other than HTTP/HTTPS. ${PI}`)}function vX(){as(!TI,`Loading PDF.js worker may not work on protocols other than HTTP/HTTPS. ${PI}`)}function yc(n){n!=null&&n.cancel&&n.cancel()}function c_(n,e){return Object.defineProperty(n,"width",{get(){return this.view[2]*e},configurable:!0}),Object.defineProperty(n,"height",{get(){return this.view[3]*e},configurable:!0}),Object.defineProperty(n,"originalWidth",{get(){return this.view[2]},configurable:!0}),Object.defineProperty(n,"originalHeight",{get(){return this.view[3]},configurable:!0}),n}function bX(n){return n.name==="RenderingCancelledException"}function wX(n){return new Promise((e,t)=>{const s=new FileReader;s.onload=()=>{if(!s.result)return t(new Error("Error while reading a file."));e(s.result)},s.onerror=i=>{if(!i.target)return t(new Error("Error while reading a file."));const{error:r}=i.target;if(!r)return t(new Error("Error while reading a file."));switch(r.code){case r.NOT_FOUND_ERR:return t(new Error("Error while reading a file: File not found."));case r.SECURITY_ERR:return t(new Error("Error while reading a file: Security error."));case r.ABORT_ERR:return t(new Error("Error while reading a file: Aborted."));default:return t(new Error("Error while reading a file."))}},s.readAsArrayBuffer(n)})}function _X(n,e){switch(e.type){case"RESOLVE":return{value:e.value,error:void 0};case"REJECT":return{value:!1,error:e.error};case"RESET":return{value:void 0,error:void 0};default:return n}}function Au(){return U.useReducer(_X,{value:void 0,error:void 0})}var SX=function(n,e,t,s){function i(r){return r instanceof t?r:new t(function(o){o(r)})}return new(t||(t=Promise))(function(r,o){function a(h){try{c(s.next(h))}catch(u){o(u)}}function l(h){try{c(s.throw(h))}catch(u){o(u)}}function c(h){h.done?r(h.value):i(h.value).then(a,l)}c((s=s.apply(n,e||[])).next())})},gE=function(n,e){var t={};for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&e.indexOf(s)<0&&(t[s]=n[s]);if(n!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,s=Object.getOwnPropertySymbols(n);i{switch(e){case fE.NEED_PASSWORD:{const t=prompt("Enter the password to open this PDF file.");n(t);break}case fE.INCORRECT_PASSWORD:{const t=prompt("Invalid password. Please try again.");n(t);break}}};function yE(n){return typeof n=="object"&&n!==null&&("data"in n||"range"in n||"url"in n)}const kX=U.forwardRef(function(e,t){var{children:s,className:i,error:r="Failed to load PDF file.",externalLinkRel:o,externalLinkTarget:a,file:l,inputRef:c,imageResourcesPath:h,loading:u="Loading PDF…",noData:d="No PDF file specified.",onItemClick:p,onLoadError:m,onLoadProgress:y,onLoadSuccess:v,onPassword:g=AX,onSourceError:b,onSourceSuccess:_,options:x,renderMode:A,rotate:C}=e,$=gE(e,["children","className","error","externalLinkRel","externalLinkTarget","file","inputRef","imageResourcesPath","loading","noData","onItemClick","onLoadError","onLoadProgress","onLoadSuccess","onPassword","onSourceError","onSourceSuccess","options","renderMode","rotate"]);const[I,j]=Au(),{value:q,error:L}=I,[B,H]=Au(),{value:D,error:X}=B,te=U.useRef(new dX),J=U.useRef([]),Y=U.useRef(void 0),ye=U.useRef(void 0);l&&l!==Y.current&&yE(l)&&(as(!fh(l,Y.current),`File prop passed to changed, but it's equal to previous one. This might result in unnecessary reloads. Consider memoizing the value passed to "file" prop.`),Y.current=l),x&&x!==ye.current&&(as(!fh(x,ye.current),`Options prop passed to changed, but it's equal to previous one. This might result in unnecessary reloads. Consider memoizing the value passed to "options" prop.`),ye.current=x);const z=U.useRef({scrollPageIntoView:Ie=>{const{dest:Fe,pageNumber:Je,pageIndex:st=Je-1}=Ie;if(p){p({dest:Fe,pageIndex:st,pageNumber:Je});return}const tn=J.current[st];if(tn){tn.scrollIntoView();return}as(!1,`An internal link leading to page ${Je} was clicked, but neither was provided with onItemClick nor it was able to find the page within itself. Either provide onItemClick to and handle navigating by yourself or ensure that all pages are rendered within .`)}});U.useImperativeHandle(t,()=>({linkService:te,pages:J,viewer:z}),[]);function E(){_&&_()}function O(){L&&(as(!1,L.toString()),b&&b(L))}function R(){j({type:"RESET"})}U.useEffect(R,[l,j]);const w=U.useCallback(()=>SX(this,void 0,void 0,function*(){if(!l)return null;if(typeof l=="string")return l_(l)?{data:pE(l)}:(mE(),{url:l});if(l instanceof xX)return{range:l};if(mX(l))return{data:l};if(B0&&gX(l))return{data:yield wX(l)};if(yt(typeof l=="object"),yt(yE(l)),"url"in l&&typeof l.url=="string"){if(l_(l.url)){const{url:Ie}=l,Fe=gE(l,["url"]),Je=pE(Ie);return Object.assign({data:Je},Fe)}mE()}return l}),[l]);U.useEffect(()=>{const Ie=im(w());return Ie.promise.then(Fe=>{j({type:"RESOLVE",value:Fe})}).catch(Fe=>{j({type:"REJECT",error:Fe})}),()=>{yc(Ie)}},[w,j]),U.useEffect(()=>{if(!(typeof q>"u")){if(q===!1){O();return}E()}},[q]);function k(){D&&(v&&v(D),J.current=new Array(D.numPages),te.current.setDocument(D))}function N(){X&&(as(!1,X.toString()),m&&m(X))}U.useEffect(function(){H({type:"RESET"})},[H,q]),U.useEffect(function(){if(!q)return;const Fe=x?Object.assign(Object.assign({},q),x):q,Je=EI(Fe);y&&(Je.onProgress=y),g&&(Je.onPassword=g);const st=Je,tn=st.promise.then(Pn=>{H({type:"RESOLVE",value:Pn})}).catch(Pn=>{st.destroyed||H({type:"REJECT",error:Pn})});return()=>{tn.finally(()=>st.destroy())}},[x,H,q]),U.useEffect(()=>{if(!(typeof D>"u")){if(D===!1){N();return}k()}},[D]),U.useEffect(function(){te.current.setViewer(z.current),te.current.setExternalLinkRel(o),te.current.setExternalLinkTarget(a)},[o,a]);const G=U.useCallback((Ie,Fe)=>{J.current[Ie]=Fe},[]),Z=U.useCallback(Ie=>{delete J.current[Ie]},[]),ae=U.useMemo(()=>({imageResourcesPath:h,linkService:te.current,onItemClick:p,pdf:D,registerPage:G,renderMode:A,rotate:C,unregisterPage:Z}),[h,p,D,G,A,C,Z]),ie=U.useMemo(()=>CI($,()=>D),[$,D]);function Ae(){return S.jsx($I.Provider,{value:ae,children:s})}function ct(){return l?D==null?S.jsx(ph,{type:"loading",children:typeof u=="function"?u():u}):D===!1?S.jsx(ph,{type:"error",children:typeof r=="function"?r():r}):Ae():S.jsx(ph,{type:"no-data",children:typeof d=="function"?d():d})}return S.jsx("div",Object.assign({className:c0("react-pdf__Document",i),ref:c,style:{"--scale-factor":"1"}},ie,{children:ct()}))});function RI(){return U.useContext($I)}function MI(){for(var n=[],e=0;eTX(e),[e]),s=U.useMemo(()=>!U0(e)||NI(e)?null:e.children.map((i,r)=>S.jsx(DI,{node:i},r)),[e]);return S.jsx("span",Object.assign({className:n},t,{children:s}))}function q0(){return U.useContext(II)}function PX(){const n=q0();yt(n);const{onGetStructTreeError:e,onGetStructTreeSuccess:t}=n,[s,i]=Au(),{value:r,error:o}=s,{customTextRenderer:a,page:l}=n;function c(){r&&t&&t(r)}function h(){o&&(as(!1,o.toString()),e&&e(o))}return U.useEffect(function(){i({type:"RESET"})},[i,l]),U.useEffect(function(){if(a||!l)return;const d=im(l.getStructTree()),p=d;return d.promise.then(m=>{i({type:"RESOLVE",value:m})}).catch(m=>{i({type:"REJECT",error:m})}),()=>yc(p)},[a,l,i]),U.useEffect(()=>{if(r!==void 0){if(r===!1){h();return}c()}},[r]),r?S.jsx(DI,{className:"react-pdf__Page__structTree structTree",node:r}):null}const vE=AI;function RX(n){const e=q0();yt(e);const t=Object.assign(Object.assign({},e),n),{_className:s,canvasBackground:i,devicePixelRatio:r=yX(),onRenderError:o,onRenderSuccess:a,page:l,renderForms:c,renderTextLayer:h,rotate:u,scale:d}=t,{canvasRef:p}=n;yt(l);const m=U.useRef(null);function y(){l&&a&&a(c_(l,d))}function v(x){bX(x)||(as(!1,x.toString()),o&&o(x))}const g=U.useMemo(()=>l.getViewport({scale:d*r,rotation:u}),[r,l,u,d]),b=U.useMemo(()=>l.getViewport({scale:d,rotation:u}),[l,u,d]);U.useEffect(function(){if(!l)return;l.cleanup();const{current:A}=m;if(!A)return;A.width=g.width,A.height=g.height,A.style.width=`${Math.floor(b.width)}px`,A.style.height=`${Math.floor(b.height)}px`,A.style.visibility="hidden";const C={annotationMode:c?vE.ENABLE_FORMS:vE.ENABLE,canvasContext:A.getContext("2d",{alpha:!1}),viewport:g};i&&(C.background=i);const $=l.render(C),I=$;return $.promise.then(()=>{A.style.visibility="",y()}).catch(v),()=>yc(I)},[i,l,c,g,b]);const _=U.useCallback(()=>{const{current:x}=m;x&&(x.width=0,x.height=0)},[]);return U.useEffect(()=>_,[_]),S.jsx("canvas",{className:`${s}__canvas`,dir:"ltr",ref:MI(p,m),style:{display:"block",userSelect:"none"},children:h?S.jsx(PX,{}):null})}function MX(n){return"str"in n}function IX(){const n=q0();yt(n);const{customTextRenderer:e,onGetTextError:t,onGetTextSuccess:s,onRenderTextLayerError:i,onRenderTextLayerSuccess:r,page:o,pageIndex:a,pageNumber:l,rotate:c,scale:h}=n;yt(o);const[u,d]=Au(),{value:p,error:m}=u,y=U.useRef(null);as(Number.parseInt(window.getComputedStyle(document.body).getPropertyValue("--react-pdf-text-layer"),10)===1,"TextLayer styles not found. Read more: https://github.com/wojtekmaj/react-pdf#support-for-text-layer");function v(){p&&s&&s(p)}function g(){m&&(as(!1,m.toString()),t&&t(m))}U.useEffect(function(){d({type:"RESET"})},[o,d]),U.useEffect(function(){if(!o)return;const I=im(o.getTextContent()),j=I;return I.promise.then(q=>{d({type:"RESOLVE",value:q})}).catch(q=>{d({type:"REJECT",error:q})}),()=>yc(j)},[o,d]),U.useEffect(()=>{if(p!==void 0){if(p===!1){g();return}v()}},[p]);const b=U.useCallback(()=>{r&&r()},[r]),_=U.useCallback($=>{as(!1,$.toString()),i&&i($)},[i]);function x(){const $=y.current;$&&$.classList.add("selecting")}function A(){const $=y.current;$&&$.classList.remove("selecting")}const C=U.useMemo(()=>o.getViewport({scale:h,rotation:c}),[o,c,h]);return U.useLayoutEffect(function(){if(!o||!p)return;const{current:I}=y;if(!I)return;I.innerHTML="";const j=o.streamTextContent({includeMarkedContent:!0}),q={container:I,textContentSource:j,viewport:C},L=new kI(q),B=L;return L.render().then(()=>{const H=document.createElement("div");H.className="endOfContent",I.append(H);const D=I.querySelectorAll('[role="presentation"]');if(e){let X=0;p.items.forEach((te,J)=>{if(!MX(te))return;const Y=D[X];if(!Y)return;const ye=e(Object.assign({pageIndex:a,pageNumber:l,itemIndex:J},te));Y.innerHTML=ye,X+=te.str&&te.hasEOL?2:1})}b()}).catch(_),()=>yc(B)},[e,_,b,o,a,l,p,C]),S.jsx("div",{className:c0("react-pdf__Page__textContent","textLayer"),onMouseUp:A,onMouseDown:x,ref:y})}function OX(){const n=RI(),e=q0();yt(e);const t=Object.assign(Object.assign({},n),e),{imageResourcesPath:s,linkService:i,onGetAnnotationsError:r,onGetAnnotationsSuccess:o,onRenderAnnotationLayerError:a,onRenderAnnotationLayerSuccess:l,page:c,pdf:h,renderForms:u,rotate:d,scale:p=1}=t;yt(h),yt(c),yt(i);const[m,y]=Au(),{value:v,error:g}=m,b=U.useRef(null);as(Number.parseInt(window.getComputedStyle(document.body).getPropertyValue("--react-pdf-annotation-layer"),10)===1,"AnnotationLayer styles not found. Read more: https://github.com/wojtekmaj/react-pdf#support-for-annotations");function _(){v&&o&&o(v)}function x(){g&&(as(!1,g.toString()),r&&r(g))}U.useEffect(function(){y({type:"RESET"})},[y,c]),U.useEffect(function(){if(!c)return;const j=im(c.getAnnotations()),q=j;return j.promise.then(L=>{y({type:"RESOLVE",value:L})}).catch(L=>{y({type:"REJECT",error:L})}),()=>{yc(q)}},[y,c]),U.useEffect(()=>{if(v!==void 0){if(v===!1){x();return}_()}},[v]);function A(){l&&l()}function C(I){as(!1,`${I}`),a&&a(I)}const $=U.useMemo(()=>c.getViewport({scale:p,rotation:d}),[c,d,p]);return U.useEffect(function(){if(!h||!c||!i||!v)return;const{current:j}=b;if(!j)return;const q=$.clone({dontFlip:!0}),L={accessibilityManager:null,annotationCanvasMap:null,annotationEditorUIManager:null,div:j,l10n:null,page:c,structTreeLayer:null,viewport:q},B={annotations:v,annotationStorage:h.annotationStorage,div:j,imageResourcesPath:s,linkService:i,page:c,renderForms:u,viewport:q};j.innerHTML="";try{new xI(L).render(B),A()}catch(H){C(H)}return()=>{}},[v,s,i,c,h,u,$]),S.jsx("div",{className:c0("react-pdf__Page__annotations","annotationLayer"),ref:b})}var NX=function(n,e){var t={};for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&e.indexOf(s)<0&&(t[s]=n[s]);if(n!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,s=Object.getOwnPropertySymbols(n);i{if(!ie)return null;let cn=1;const Mn=w??bE;if(N||p){const Xn=ie.getViewport({scale:1,rotation:Je});N?cn=N/Xn.width:p&&(cn=p/Xn.height)}return Mn*cn},[p,ie,Je,w,N]);U.useEffect(function(){return()=>{qa(Ie)&&i&&k&&k(Ie)}},[i,J,Ie,k]);function tn(){if(I){if(!ie||!st)return;I(c_(ie,st))}if(i&&Y){if(!qa(Ie)||!ct.current)return;Y(Ie,ct.current)}}function Pn(){Ae&&(as(!1,Ae.toString()),$&&$(Ae))}U.useEffect(function(){ae({type:"RESET"})},[ae,J,Ie]),U.useEffect(function(){if(!J||!Fe)return;const Mn=im(J.getPage(Fe)),Xn=Mn;return Mn.promise.then(Yn=>{ae({type:"RESOLVE",value:Yn})}).catch(Yn=>{ae({type:"REJECT",error:Yn})}),()=>yc(Xn)},[ae,J,Fe]),U.useEffect(()=>{if(ie!==void 0){if(ie===!1){Pn();return}tn()}},[ie,st]);const Et=U.useMemo(()=>ie&&qa(Ie)&&Fe&&qa(Je)&&qa(st)?{_className:s,canvasBackground:r,customTextRenderer:h,devicePixelRatio:u,onGetAnnotationsError:g,onGetAnnotationsSuccess:b,onGetStructTreeError:_,onGetStructTreeSuccess:x,onGetTextError:A,onGetTextSuccess:C,onRenderAnnotationLayerError:j,onRenderAnnotationLayerSuccess:q,onRenderError:L,onRenderSuccess:B,onRenderTextLayerError:H,onRenderTextLayerSuccess:D,page:ie,pageIndex:Ie,pageNumber:Fe,renderForms:z,renderTextLayer:O,rotate:Je,scale:st}:null,[s,r,h,u,g,b,_,x,A,C,j,q,L,B,H,D,ie,Ie,Fe,z,O,Je,st]),As=U.useMemo(()=>CI(G,()=>ie&&(st?c_(ie,st):void 0)),[G,ie,st]),Rn=`${Ie}@${st}/${Je}`;function ks(){switch(E){case"custom":return yt(c),S.jsx(c,{},`${Rn}_custom`);case"none":return null;case"canvas":default:return S.jsx(RX,{canvasRef:o},`${Rn}_canvas`)}}function hs(){return O?S.jsx(IX,{},`${Rn}_text`):null}function us(){return ye?S.jsx(OX,{},`${Rn}_annotations`):null}function Es(){return S.jsxs(II.Provider,{value:Et,children:[ks(),hs(),us(),a]})}function ln(){return Fe?J===null||ie===void 0||ie===null?S.jsx(ph,{type:"loading",children:typeof y=="function"?y():y}):J===!1||ie===!1?S.jsx(ph,{type:"error",children:typeof d=="function"?d():d}):Es():S.jsx(ph,{type:"no-data",children:typeof v=="function"?v():v})}return S.jsx("div",Object.assign({className:c0(s,l),"data-page-number":Fe,ref:MI(m,ct),style:{"--scale-factor":`${st}`,backgroundColor:r||"white",position:"relative",minWidth:"min-content",minHeight:"min-content"}},As,{children:ln()}))}vX();H0.workerSrc="pdf.worker.mjs";const DX="/assets/pdf.worker.min-GB3t0DcA.js";H0.workerSrc=DX;function jX(){if(!H0.workerSrc)throw new Error("The bundled PDF worker is not configured.");if(a_!=="4.8.69")throw new Error(`PDF runtime version mismatch (${a_}).`)}const FX=280,zX=new Set(["ArrowLeft","ArrowRight","ArrowUp","ArrowDown","Home","End","PageUp","PageDown","A"]);function HX({enabled:n,pagesRoot:e,routeId:t,paperVersion:s,numPages:i,resetKey:r,onSelect:o,onError:a}){const l=U.useRef(!1),c=U.useRef(!1),h=U.useRef(""),u=U.useRef(0),d=U.useRef(0),p=U.useRef(""),m=U.useRef(o),y=U.useRef(a);m.current=o,y.current=a,U.useEffect(()=>{l.current=!1,c.current=!1,h.current="",p.current="",window.clearTimeout(u.current),cancelAnimationFrame(d.current),d.current=0},[t,s,r]),U.useEffect(()=>{if(!n){l.current=!1,c.current=!1,window.clearTimeout(u.current),cancelAnimationFrame(d.current),d.current=0;return}const v=()=>{var j,q;const $=jL({selection:window.getSelection(),pagesRoot:e.current,routeId:t,paperVersion:s,numPages:i});if(!$.ok){$.error&&((j=y.current)==null||j.call(y,$.error));return}const I=FL($.selection);I!==h.current&&(h.current=I,(q=m.current)==null||q.call(m,$.selection))},g=()=>{window.clearTimeout(u.current),cancelAnimationFrame(d.current),d.current=requestAnimationFrame(()=>{d.current=0,v()})},b=$=>{const I=e.current;!I||!$.isPrimary||$.pointerType==="mouse"&&$.button!==0||!($.target instanceof Node)||!I.contains($.target)||(l.current=!0,c.current=!1,h.current="",window.clearTimeout(u.current),cancelAnimationFrame(d.current),d.current=0)},_=$=>{!l.current||!$.isPrimary||(l.current=!1,g())},x=$=>{!l.current||!$.isPrimary||(l.current=!1,c.current=!0,p.current="",window.clearTimeout(u.current),cancelAnimationFrame(d.current),d.current=0)},A=$=>{var L,B;const I=e.current;if(!I||l.current||!($.target instanceof Node&&!!((B=(L=$.target instanceof Element?$.target:$.target.parentElement)==null?void 0:L.closest)!=null&&B.call(L,".textLayer, .reader-web-document")&&I.contains($.target))))return;const q=($.key==="a"||$.key==="A")&&($.metaKey||$.ctrlKey);($.shiftKey||zX.has($.key)||q)&&(c.current=!1,h.current="",g())},C=()=>{if(l.current||c.current)return;const $=window.getSelection(),I=$&&$.rangeCount===1?`${$.toString()}\0${$.anchorNode?1:0}\0${$.focusNode?1:0}`:"";p.current=I,window.clearTimeout(u.current),u.current=window.setTimeout(()=>{p.current===I&&v()},FX)};return document.addEventListener("pointerdown",b,!0),document.addEventListener("pointerup",_,!0),document.addEventListener("pointercancel",x,!0),document.addEventListener("keyup",A,!0),document.addEventListener("selectionchange",C),()=>{document.removeEventListener("pointerdown",b,!0),document.removeEventListener("pointerup",_,!0),document.removeEventListener("pointercancel",x,!0),document.removeEventListener("keyup",A,!0),document.removeEventListener("selectionchange",C),window.clearTimeout(u.current),cancelAnimationFrame(d.current)}},[n,i,e,s,t])}const BX=.25,UX=4,wE=[.25,.33,.5,.67,.75,.9,1,1.1,1.25,1.5,1.75,2,2.5,3,4];function h_(n){return Math.max(BX,Math.min(UX,n))}function Fm(n,e){const t=e>0?wE:[...wE].reverse();return t.find(s=>(s-n)*e>.005)??t[t.length-1]}function qX({paperTitle:n,paperHref:e,resources:t,label:s,children:i}){const r=U.useRef(null);return U.useLayoutEffect(()=>{const o=r.current,a=document.querySelector(".app-header .brand-mark");if(!o||!a)return;const l=()=>{const h=a.getBoundingClientRect().left-o.getBoundingClientRect().left;o.style.setProperty("--reader-title-inset",`${Math.max(10,h)}px`)};l();const c=new ResizeObserver(l);return c.observe(o),c.observe(a),()=>c.disconnect()},[]),S.jsxs("div",{ref:r,className:"pdf-toolbar","aria-label":s,children:[S.jsxs("div",{className:"pdf-toolbar-paper",children:[S.jsxs(Ld,{className:"pdf-toolbar-back",to:e,"aria-label":"Back",children:[S.jsx(tD,{size:15,strokeWidth:1.8,"aria-hidden":"true"}),S.jsx("span",{children:"Back"})]}),S.jsx(Ld,{className:"pdf-toolbar-title",to:e,title:n,"aria-label":`${n} — open paper page`,children:n}),(t==null?void 0:t.repository)&&S.jsxs("a",{className:"pdf-toolbar-resource",href:t.repository.href,target:"_blank",rel:"noopener noreferrer",title:"Official GitHub repository","aria-label":"Open official GitHub repository",children:[S.jsx(u0,{size:15,strokeWidth:1.8,"aria-hidden":"true"}),S.jsxs("span",{"aria-label":`${t.repository.stars} GitHub stars`,children:["★ ",t.repository.stars.toLocaleString()]})]}),(t==null?void 0:t.projectPage)&&S.jsxs("a",{className:"pdf-toolbar-resource",href:t.projectPage.href,target:"_blank",rel:"noopener noreferrer",title:t.projectPage.href,"aria-label":`Open project page at ${t.projectPage.label}`,children:[S.jsx(s$,{size:14,strokeWidth:1.8,"aria-hidden":"true"}),S.jsx("span",{children:t.projectPage.label})]}),(t==null?void 0:t.huggingFace)&&S.jsxs("a",{className:"pdf-toolbar-resource",href:t.huggingFace.href,target:"_blank",rel:"noopener noreferrer","aria-label":`Open ${t.huggingFace.count} Hugging Face ${t.huggingFace.count===1?"artifact":"artifacts"}`,children:[S.jsx("span",{"aria-hidden":"true",children:"🤗"}),S.jsxs("span",{children:[t.huggingFace.count," HF ",t.huggingFace.count===1?"artifact":"artifacts"]})]})]}),i]})}function VX({paperTitle:n,paperHref:e,resources:t,page:s,pages:i,zoomPercent:r,searchOpen:o,searchQuery:a,searchMatch:l,searchCount:c,searching:h,onPage:u,onZoom:d,onZoomIn:p,onZoomOut:m,onToggleSearch:y,onCloseSearch:v,onSearchQuery:g,onSearch:b}){const _=A=>{A.preventDefault();const C=Number(new FormData(A.currentTarget).get("page"));Number.isInteger(C)&&u(C)},x=A=>{A.preventDefault();const C=A.currentTarget.elements.namedItem("zoom"),$=Number.parseFloat(C.value),I=Number.isFinite($)&&$>0?h_($/100):r/100;C.value=`${Math.round(I*100)}%`,d(I)};return S.jsxs(qX,{paperTitle:n,paperHref:e,resources:t,label:"PDF controls",children:[S.jsxs("div",{className:"pdf-toolbar-controls",children:[S.jsxs("div",{className:"pdf-toolbar-group",children:[S.jsx("button",{type:"button",onClick:()=>u(s-1),disabled:s<=1,"aria-label":"Previous page",children:S.jsx(oD,{size:16,"aria-hidden":"true"})}),S.jsxs("form",{onSubmit:_,className:"pdf-page-form",children:[S.jsx("label",{className:"sr-only",htmlFor:"pdf-current-page",children:"Current page"}),S.jsx("input",{id:"pdf-current-page",name:"page",type:"number",min:1,max:i||1,defaultValue:s,"aria-label":`Page ${s} of ${i||"unknown"}`},s),S.jsxs("span",{"aria-hidden":"true",children:["/ ",i||"—"]})]}),S.jsx("button",{type:"button",onClick:()=>u(s+1),disabled:!i||s>=i,"aria-label":"Next page",children:S.jsx(ML,{size:16,"aria-hidden":"true"})})]}),S.jsxs("div",{className:"pdf-toolbar-group",children:[S.jsx("button",{type:"button",onClick:m,"aria-label":"Zoom out",children:S.jsx(cD,{size:15,"aria-hidden":"true"})}),S.jsx("form",{onSubmit:x,className:"pdf-zoom-form",children:S.jsx("input",{className:"pdf-zoom-value",name:"zoom",inputMode:"decimal",defaultValue:`${r}%`,onFocus:A=>A.currentTarget.select(),onBlur:A=>{var C;return(C=A.currentTarget.form)==null?void 0:C.requestSubmit()},"aria-label":`Zoom ${r}%`},r)}),S.jsx("button",{type:"button",onClick:p,"aria-label":"Zoom in",children:S.jsx(nD,{size:15,"aria-hidden":"true"})})]}),S.jsxs("button",{type:"button",className:"pdf-toolbar-search",onClick:y,"aria-label":"Search","aria-expanded":o,"aria-controls":"pdf-search-controls",children:[S.jsx(sD,{size:14,strokeWidth:2,"aria-hidden":"true"}),S.jsx("span",{children:"Search"})]})]}),o&&S.jsxs("div",{id:"pdf-search-controls",className:"pdf-search-controls",children:[S.jsx("label",{className:"sr-only",htmlFor:"pdf-search-input",children:"Search document"}),S.jsx("input",{id:"pdf-search-input",autoFocus:!0,value:a,onChange:A=>g(A.target.value),placeholder:"Search document"}),S.jsx("span",{role:"status",children:h&&!c?"Searching…":a?`${c?l+1:0} of ${c}${h?"+":""}`:""}),S.jsx("button",{type:"button",onClick:()=>b(-1),disabled:!c,"aria-label":"Previous match",children:S.jsx(i$,{size:16,"aria-hidden":"true"})}),S.jsx("button",{type:"button",onClick:()=>b(1),disabled:!c,"aria-label":"Next match",children:S.jsx(r$,{size:16,"aria-hidden":"true"})}),S.jsx("button",{type:"button",onClick:v,"aria-label":"Close search",title:"Close search",children:S.jsx(h0,{size:16,"aria-hidden":"true"})})]})]})}function _E(n){let e;try{e=new URL(n)}catch{return null}if(!["http:","https:"].includes(e.protocol)||!/^(www\.)?arxiv\.org$/i.test(e.hostname))return null;const t=e.pathname.match(/^\/(?:abs|pdf|html)\/(\d{4}\.\d{4,5}|[a-z-]+(?:\.[A-Z]{2})?\/\d{7})(?:v\d+)?(?:\.pdf)?\/?$/i);return(t==null?void 0:t[1])??null}const WX=8,GX=12,KX=300,ZX=6;function XX(n){const e=n.replace(/^\s*\[[^\]]{1,6}\]\s*/,"").split(/[.?!](?=\s|$|[A-Z])/).map(o=>o.replace(/\s+/g," ").trim()).filter(Boolean),t=o=>o.length<=KX&&o.split(" ").length>=3&&/[a-z]/i.test(o)&&!/https?:\/\//i.test(o)&&!/^arxiv preprint/i.test(o),s=(o,a)=>a.length-o.length,i=e.filter(t).sort(s),r=e.slice(0,-1).map((o,a)=>`${o}. ${e[a+1]}`).filter(t).sort(s);return[...new Set([...i,...r])].slice(0,WX)}function YX(n){const e=[];let t;for(const s of n){if(!("str"in s))continue;const i=s.transform[5];(!t||Math.abs(i-t.baseline)>1)&&(t={text:"",x:s.transform[4],baseline:i},e.push(t)),t.text+=s.str,s.hasEOL&&(t=void 0)}return e.map(s=>({...s,text:s.text.trim()})).filter(s=>s.text)}function u_([n,e,t,s]){return{x:i=>Math.round((i-n)/(t-n)*1e3),y:i=>Math.round((s-i)/(s-e)*1e3)}}const JX=/\[(\d{1,3}(?:\s*[,;\u2013-]\s*\d{1,3})*)\]/g;function QX(n){return n.split(/[,;]/).flatMap(e=>{const[t,s=t]=e.split(/[\u2013-]/).map(Number);return s>=t&&s-t<50?Array.from({length:s-t+1},(i,r)=>t+r):[t]})}function eY(n,e){const t=u_(e),s=new Map,i=[];let r;for(const o of n)"str"in o&&((!r||Math.abs(o.transform[5]-r.parts[0].item.transform[5])>1)&&(r={text:"",parts:[]},i.push(r)),r.parts.push({start:r.text.length,item:o}),r.text+=o.str,o.hasEOL&&(r=void 0));for(const{text:o,parts:a}of i){const l=h=>a.filter(u=>u.start<=h).pop()??a[0],c=h=>{const{start:u,item:d}=l(h);return d.transform[4]+d.width*Math.min(1,(h-u)/Math.max(d.str.length,1))};for(const h of o.matchAll(JX)){const u=h.index??0,{item:d}=l(u),p=d.transform[5],m=d.height||Math.abs(d.transform[3]),y=[t.x(c(u)),t.y(p+m),t.x(c(u+h[0].length)),t.y(p)+3];for(const v of QX(h[1]))s.set(v,[...s.get(v)??[],y])}}return s}function tY(n,e){let t;const s=new Map,i=new Map,r=new Map;let o,a;const l=x=>{let A=i.get(x);return A||(A=n.getPage(x).then(async C=>({view:C.view,content:await C.getTextContent()})),i.set(x,A)),A},c=x=>{let A=s.get(x);return A||(A=n.getPage(x).then(C=>C.getAnnotations()),s.set(x,A)),A},h=()=>t??(t=(async()=>{var C;const x=await n.getDestinations(),A=[];for(const[$,I]of Object.entries(x)){if(!/^cite[.:]/i.test($)||((C=I[1])==null?void 0:C.name)!=="XYZ"||typeof I[2]!="number"||typeof I[3]!="number")continue;const j=typeof I[0]=="number"?I[0]+1:await n.getPageIndex(I[0])+1;A.push({name:$,page:j,x:I[2],y:I[3]})}return A.length?A:u()})()),u=async()=>{var C;const x=[];for(let $=Math.max(1,n.numPages-GX+1);$<=n.numPages;$++)x.push(...YX((await l($)).content.items).map(I=>({...I,page:$})));const A=x.flatMap(($,I)=>/^(?:[\dIVX]+\.?\s*)?(?:references|bibliography)$/i.test($.text)?[I]:[]);for(const $ of A.reverse()){const I=[];let j=0;for(const q of x.slice($+1)){const L=Number((C=q.text.match(/^\[(\d{1,3})\]/))==null?void 0:C[1]);L>j&&L<=j+3&&(j=L,I.push({name:`text:${L}`,page:q.page,x:q.x,y:q.baseline}))}if(I.length)return I}return[]},d=x=>{let A=r.get(x);return A||(A=(async()=>{const C=await h(),$=C.find(E=>E.name===x);if(!$)return null;const I=C.filter(E=>E.page===$.page),j=I.filter(E=>Math.abs(E.x-$.x)<24),q=Math.max(0,...j.filter(E=>E.y<$.y-1).map(E=>E.y)),L=Math.min(1/0,...I.filter(E=>E.x>$.x+24).map(E=>E.x-4)),B=new Set,H=(E,O)=>E>=$.x-4&&Eq;for(const E of await c($.page)){if(!E.url||!E.rect)continue;const O=_E(E.url);if(!O)continue;const[R,w,k,N]=E.rect;H((R+k)/2,(w+N)/2)&&B.add(O)}const{view:D,content:X}=await l($.page),te=X.items.filter(E=>"str"in E&&H(E.transform[4],E.transform[5])),J=te.map(E=>E.str+(E.hasEOL?" ":"")).join(""),Y=te.filter(E=>E.str.trim()).sort((E,O)=>O.transform[5]-E.transform[5]),ye=Y.findIndex((E,O)=>O>0&&Y[O-1].transform[5]-E.transform[5]>2.5*Math.max(Math.abs(E.transform[3]),1));ye>0&&(Y.length=ye);let z=null;if(Y.length){const{x:E,y:O}=u_(D);z=[E(Math.min(...Y.map(R=>R.transform[4]))),O(Math.max(...Y.map(R=>R.transform[5]+R.height))),E(Math.max(...Y.map(R=>R.transform[4]+R.width))),O(Math.min(...Y.map(R=>R.transform[5])))+3]}for(const E of J.replace(/\s/g,"").matchAll(/(?:arxiv:|arxiv\.org\/(?:abs|pdf|html)\/)(\d{4}\.\d{4,5}|[a-z-]+(?:\.[A-Z]{2})?\/\d{7})(?:v\d+)?/gi))B.add(E[1]);return{arxivId:B.size===1?[...B][0]:null,titles:XX(J),box:z}})(),r.set(x,A)),A},p=()=>o??(o=(async()=>{const x=new Map;if(!e)return x;try{const A=await h(),C=[];for(const $ of A){const I=await d($.name);I&&(I.arxivId||I.titles.length)&&C.push({key:$.name,arxiv_id:I.arxivId,titles:I.titles})}return C.length?await e(C):x}catch{return x}})()),m=()=>a??(a=(async()=>{const x=new Map,A=(H,D,X)=>{const te=x.get(H)??[],J=te[te.length-1],Y=J==null?void 0:J[J.length-1];(Y==null?void 0:Y.page)===D&&Math.abs(Y.bbox[1]-X[1])<5&&X[0]>=Y.bbox[0]&&X[0]-Y.bbox[2]<15?Y.bbox=[Y.bbox[0],Math.min(Y.bbox[1],X[1]),Math.max(Y.bbox[2],X[2]),Math.max(Y.bbox[3],X[3])]:(Y==null?void 0:Y.page)===D&&X[1]>Y.bbox[1]&&X[1]-Y.bbox[3]<10&&X[0]{if(I){const{view:J,content:Y}=await l(H),ye=H<$.page?Y.items:Y.items.filter(z=>"str"in z&&z.transform[5]>$.y+1);return[...eY(ye,J)].flatMap(([z,E])=>E.map(O=>[`text:${z}`,O]))}const D=(await c(H)).filter(J=>typeof J.dest=="string"&&/^cite[.:]/i.test(J.dest));if(!D.length)return[];const{x:X,y:te}=u_((await n.getPage(H)).view);return D.flatMap(({dest:J,rect:Y})=>Y?[[J,[X(Y[0]),te(Y[3]),X(Y[2]),te(Y[1])]]]:[])},q=I?$.page:n.numPages,L=[],B=H=>L[H]??(L[H]=j(H).catch(()=>[]));for(let H=1;H<=q;H++){for(let D=H+1;D<=Math.min(q,H+ZX);D++)B(D);for(const[D,X]of await B(H))A(D,H,X)}return x})());e&&p();const y=async x=>{const A=await d(x);return A?A.arxivId??(await p()).get(x)??null:null};return Object.assign(async x=>x.url?_E(x.url):typeof x.dest!="string"||!/^cite[.:]/i.test(x.dest)?null:y(x.dest),{bibliographyLinks:async x=>{const A=(await h()).filter($=>$.page===x);return(await Promise.all(A.map(async({name:$})=>{const[I,j]=await Promise.all([d($),y($)]);return I!=null&&I.box&&j?{name:$,routeId:j,box:I.box}:null}))).filter($=>$!==null)},citationsOf:async x=>(await m()).get(x)??[],referenceOf:async x=>{var $;const A=(await h()).find(I=>I.name===x),C=A&&(($=await d(x))==null?void 0:$.box);return C?{page:A.page,bbox:C}:null}})}function nY({anchor:n,routeId:e,internal:t,dest:s,onShowReference:i}){U.useEffect(()=>{const a=n.style.display;return n.style.display="none",()=>{n.style.display=a}},[n]);const r=n.parentElement;if(!r)return null;const o=()=>{if(!s||!i)return n.click();i(s).then(a=>{a||n.click()})};return IL.createPortal(S.jsx(d0,{routeId:e,to:n.href,target:t?void 0:"_blank",className:"pdf-paper-preview-link",title:/^\d+$/.test(e)?"Preview paper":`Preview arXiv:${e}`,ariaLabel:`${t?"Citation":"arXiv paper"} ${e}`,cardOpensPaper:!0,onClick:t?a=>{a.preventDefault(),o()}:void 0,previewFooter:()=>S.jsxs("div",{className:"pdf-paper-preview-actions",children:[S.jsx("a",{href:`/paper/${encodeURIComponent(e)}`,target:"_blank",rel:"noopener noreferrer",children:"Open paper ↗"}),t&&S.jsx("button",{type:"button",onClick:o,children:"Jump to reference"})]}),children:null}),r)}function sY({routeId:n,box:[e,t,s,i],citations:r=[],onShowCitations:o}){return S.jsx("div",{className:"pdf-bibliography-link",style:{left:`${e/10}%`,top:`${t/10}%`,width:`${(s-e)/10}%`,height:`${(i-t)/10}%`},children:S.jsx(d0,{routeId:n,to:`/paper/${encodeURIComponent(n)}`,target:"_blank",className:"pdf-paper-preview-link",title:/^\d+$/.test(n)?"Preview paper":`Preview arXiv:${n}`,ariaLabel:`Reference ${n}`,cardOpensPaper:!0,previewFooter:()=>S.jsxs("div",{className:"pdf-paper-preview-actions",children:[S.jsx("a",{href:`/paper/${encodeURIComponent(n)}`,target:"_blank",rel:"noopener noreferrer",children:"Open paper ↗"}),r.length>0&&o&&S.jsx("button",{type:"button",onClick:()=>o(r),children:r.length>1?`Jump to citations (${r.length})`:"Jump to citation"})]}),children:null})})}const iY=()=>typeof window.matchMedia=="function"&&window.matchMedia("(hover: none), (pointer: coarse)").matches;function rY({id:n,name:e,avatarUrl:t,box:[s,i,r,o]}){var p,m,y,v;const[a,l]=U.useState(!1),c=`/authors/${encodeURIComponent(n)}`,h=bo({queryKey:["author",n],queryFn:()=>rD.getAuthor(n),enabled:a,staleTime:5*60*1e3,retry:!1}),u=(p=h.data)==null?void 0:p.paper_count,d=(m=h.data)==null?void 0:m.hf_username;return S.jsx("div",{className:"pdf-author-link",style:{left:`${s/10}%`,top:`${i/10}%`,width:`${(r-s)/10}%`,height:`${(o-i)/10}%`},children:S.jsxs(Lp,{open:a,onOpenChange:g=>{(!g||!iY())&&l(g)},openDelay:150,closeDelay:100,children:[S.jsx(Dp,{asChild:!0,children:S.jsx(Ld,{to:c,target:"_blank",rel:"noopener noreferrer","aria-label":`Author ${e}`,onClick:()=>l(!1)})}),S.jsxs(jp,{className:"paper-preview-pop",side:"bottom",align:"start",collisionPadding:12,children:[S.jsxs(Ld,{className:"pdf-author-card",to:c,target:"_blank",rel:"noopener noreferrer",onClick:()=>l(!1),children:[S.jsx(iD,{url:((y=h.data)==null?void 0:y.hf_avatar_url)??t,className:"pdf-author-card-avatar"}),S.jsxs("div",{className:"pdf-author-card-meta",children:[S.jsx("div",{className:"paper-preview-title",children:((v=h.data)==null?void 0:v.full_name)??e}),S.jsxs("div",{className:"paper-preview-auth",children:[u!=null&&`${u.toLocaleString()} ${u===1?"paper":"papers"}`,u!=null&&d&&" · ",d&&`@${d}`]})]})]}),S.jsx("div",{className:"pdf-paper-preview-actions",children:S.jsx(Ld,{to:c,target:"_blank",rel:"noopener noreferrer",onClick:()=>l(!1),children:"Open author page ↗"})})]})]})})}const SE=0,oY=1,Yc=2,Md=3,aY=4,lY=2,cY={ł:"l",ø:"o",đ:"d",ð:"d",ı:"i",ß:"ss",æ:"ae",œ:"oe",þ:"th"};function Lx(n){return n.normalize("NFKD").toLocaleLowerCase().replace(/[^\p{L}]/gu,"").replace(/[łøđðıßæœþ]/g,e=>cY[e])}function hY(n){return/[\p{M}\p{Sk}'’ʼ\-‐‑]/u.test(n)?oY:/[\s.]/u.test(n)?Yc:Md}function uY(n){const e=n.map(s=>({letters:Lx(s),capitalized:new RegExp("^\\P{L}*\\p{Lu}","u").test(s)})).filter(s=>s.letters),t=e.reduce((s,i)=>s+i.letters.length,0);return e.length>=2&&t>=aY?e:null}function dY(n){const e=new Map;for(const t of n){const s=t.name.split(/[\s.]+/).filter(Boolean),i=s.filter((o,a)=>a===0||a===s.length-1||Lx(o).length>1),r=new Set;for(const o of[s,i]){const a=uY(o);if(!a)continue;const l=a.map(h=>h.letters).join(" ");if(r.has(l))continue;r.add(l);const c=e.get(l);e.set(l,c===void 0?{authorId:t.id,words:a}:(c==null?void 0:c.authorId)===t.id?c:null)}}return[...e.values()].filter(t=>t!==null)}function fY(n,e){const t=dY(e);if(!t.length)return[];const s=[],i=[],r=[],o=[],a=[],l=[];let c=Md,h=!1;n.forEach((v,g)=>{g>0&&v.item!==n[g-1].item&&(c=Math.max(c,Yc));for(let b=0;b{if(!u.startsWith(g.letters,v)||g.capitalized&&!i[v])return!1;for(let b=v+1;br[v]===Yc&&i[v]&&r[v+1]===Yc,m=(v,g)=>{if(r[g]0){if(r[b]===SE||r[b]===Md)return-1;for(let A=0;A=Yc&&!o[b]?b:-1},y=[];for(const v of t){const g=v.words[0].letters;for(let b=u.indexOf(g);b>=0;b=u.indexOf(g,b+1)){const _=m(v,b);_>b&&!y.some(x=>x.authorId===v.authorId&&x.from===b)&&y.push({authorId:v.authorId,start:a[b],end:l[_-1],from:b,to:_})}}return y.filter(v=>!y.some(g=>g.authorId!==v.authorId&&g.from=v.to-v.from)).sort((v,g)=>v.from-g.from).map(({authorId:v,start:g,end:b})=>({authorId:v,start:g,end:b}))}function pY(n,e){const t=n.querySelector(".textLayer");if(!t||!e.length)return[];const s=[],i=[],r=new Map,o=document.createTreeWalker(t,NodeFilter.SHOW_TEXT);for(let c=o.nextNode();c;c=o.nextNode()){const h=c.parentElement,u=(h==null?void 0:h.tagName)==="MARK"?h.parentElement:h;u&&(r.has(u)||r.set(u,r.size),s.push(c),i.push({text:c.data,item:r.get(u)}))}const a=n.getBoundingClientRect();if(!a.width||!a.height)return[];const l=(c,h,u)=>Math.round((c-h)/u*1e3);return fY(i,e).flatMap(({authorId:c,start:h,end:u})=>{const d=document.createRange();d.setStart(s[h.run],h.offset),d.setEnd(s[u.run],u.offset);const p=[];for(const m of d.getClientRects()){if(!m.width||!m.height)continue;const y=p.find(v=>m.top({authorId:c,box:[l(m.left,a.left,a.width),l(m.top,a.top,a.height),l(m.right,a.left,a.width),l(m.bottom,a.top,a.height)]}))})}function mY(n,e,t,s){const i=U.useRef([]),r=U.useRef(0),[o,a]=U.useState([]);U.useEffect(()=>()=>{r.current+=1},[]);const l=U.useCallback(h=>{i.current=h},[]),c=U.useCallback(()=>{var d;const h=++r.current;if(a([]),!t)return;const u=new Map(Array.from(((d=n.current)==null?void 0:d.querySelectorAll("[data-annotation-id] a:not(.pdf-paper-preview-link)"))??[]).map(p=>{var m;return[(m=p.parentElement)==null?void 0:m.dataset.annotationId,p]}));Promise.all(i.current.map(async p=>{const m=u.get(p.id);if(!m)return null;const y=await t(p).catch(()=>null);return y?{anchor:m,routeId:y,internal:!p.url,dest:typeof p.dest=="string"?p.dest:void 0}:null})).then(p=>{if(r.current!==h)return;const m=p.filter(y=>y!==null&&y.anchor.isConnected);m.length&&(s==null||s([...new Set(m.map(y=>y.routeId))])),a(m)})},[s,n,t]);return U.useEffect(()=>{const h=n.current;if(!h||!e||!t)return;let u=requestAnimationFrame(c);const d=new MutationObserver(p=>{p.some(m=>[...m.addedNodes].some(y=>y instanceof Element&&y.matches(".linkAnnotation")))&&(cancelAnimationFrame(u),u=requestAnimationFrame(c))});return d.observe(h,{childList:!0,subtree:!0}),()=>{d.disconnect(),cancelAnimationFrame(u),r.current+=1}},[c,n,t,e]),{paperLinks:o,onAnnotations:l}}const gY=3,yY=6;function vY(n,e){let t=0,s=0;return n.querySelectorAll(".pdf-outline-tick").forEach((i,r)=>{const o=i.getBoundingClientRect(),a=o.top+o.height/2;(r===0||Math.abs(a-e){if(!i)return;const _=x=>{x.key==="Escape"&&(x.preventDefault(),r(!1))};return window.addEventListener("keydown",_,{capture:!0}),()=>window.removeEventListener("keydown",_,{capture:!0})},[i]);const u=o==null?void 0:o.position;if(U.useEffect(()=>{const _=h.current,x=u===void 0?null:_==null?void 0:_.querySelectorAll("li")[u];!_||!x||(_.scrollTop=x.offsetTop+x.offsetHeight/2-_.clientHeight/2)},[u]),!n.length)return null;const d=_=>{const{position:x,center:A}=vY(_.currentTarget,_.clientY),C=A-_.currentTarget.parentElement.getBoundingClientRect().top;a({position:x,top:C,dragged:c.current})},p=()=>{l.current=null,a(null)},m=_=>{var x,A;c.current=!1,_.pointerType!=="mouse"&&((A=(x=_.currentTarget).setPointerCapture)==null||A.call(x,_.pointerId),l.current=_.clientY,d(_))},y=_=>{if(_.pointerType!=="mouse"){if(l.current===null)return;Math.abs(_.clientY-l.current)>yY&&(c.current=!0)}d(_)},v=_=>{_.pointerType!=="mouse"&&(c.current&&o&&(_.currentTarget.blur(),r(!1),t(n[o.position])),p())},g=_=>o?Math.max(0,1-Math.abs(_-o.position)/gY):0,b=o!=null&&o.dragged&&!i?n[o.position]:null;return S.jsxs("nav",{className:`pdf-outline${i?" is-pinned":""}`,"aria-label":"Paper sections",children:[S.jsx("button",{type:"button",className:"pdf-outline-rail","aria-label":"Table of contents","aria-expanded":i,"aria-controls":s,onClick:()=>{if(c.current){c.current=!1;return}r(_=>!_)},onPointerDown:m,onPointerMove:y,onPointerUp:v,onPointerCancel:()=>{c.current=!1,p()},onPointerLeave:_=>{_.pointerType==="mouse"&&p()},children:n.map((_,x)=>S.jsx("span",{className:`pdf-outline-tick level-${_.level}${_.index===e?" is-active":""}${(o==null?void 0:o.position)===x?" is-scrubbed":""}`,style:{"--pop":g(x)}},_.index))}),b&&S.jsx("span",{className:"pdf-outline-scrub-label",style:{top:o.top},"aria-hidden":"true",children:b.title}),S.jsx("div",{id:s,ref:h,className:"pdf-outline-panel",children:S.jsx("ol",{children:n.map((_,x)=>S.jsx("li",{className:`level-${_.level}`,children:S.jsx("a",{className:(o==null?void 0:o.position)===x?"is-scrubbed":void 0,href:`#pdf-section-${_.index}`,"aria-current":_.index===e?"location":void 0,onClick:A=>{A.preventDefault(),A.currentTarget.blur(),r(!1),t(_)},children:_.title})},_.index))})})]})}function wY({index:n,count:e,onStep:t,onClose:s}){return S.jsxs("div",{className:"pdf-citation-steps",role:"group","aria-label":"Citations of this reference",children:[S.jsxs("span",{role:"status",children:["Citation ",n+1," of ",e]}),S.jsx("button",{type:"button",onClick:()=>t(-1),"aria-label":"Previous citation",title:"Previous citation",children:S.jsx(i$,{size:16,"aria-hidden":"true"})}),S.jsx("button",{type:"button",onClick:()=>t(1),"aria-label":"Next citation",title:"Next citation",children:S.jsx(r$,{size:16,"aria-hidden":"true"})}),S.jsx("button",{type:"button",onClick:s,"aria-label":"Close citations",title:"Close citations",children:S.jsx(h0,{size:16,"aria-hidden":"true"})})]})}const _Y=/^#pdf-section-(\d+)$/,SY=2;function xY(n){const e=_Y.exec(n);return e?Number(e[1]):void 0}function AY(n,e){let t=-1;return n.forEach((s,i)=>{s<=e&&(t=i)}),t}async function kY(n,e){return typeof e=="string"?n.getDestination(e):Array.isArray(e)?e:null}async function EY(n,e){const[t,s,,i]=e;let r;if(typeof t=="number")r=t;else if(t&&typeof t=="object"&&"num"in t)r=await n.getPageIndex(t);else return null;if(!Number.isInteger(r)||r<0||r>=n.numPages)return null;const o=r+1;if((s==null?void 0:s.name)!=="XYZ"||typeof i!="number")return{page:o,offset:0};const a=(await n.getPage(o)).view,[,l,,c]=a,h=c-l;return h>0?{page:o,offset:Math.min(1,Math.max(0,(c-i)/h))}:{page:o,offset:0}}async function CY(n){const e=await n.getOutline(),t=[],s=async(i,r)=>{var o;for(const a of i){const l=a.title.replace(/\s+/g," ").trim(),c=await kY(n,a.dest).catch(()=>null),h=c?await EY(n,c).catch(()=>null):null;l&&h&&t.push({index:t.length,title:l,level:r,...h}),r+1{let r=e.get(i);return r||(r=n.getPage(i).then(o=>o.getTextContent()).then(o=>o.items.map(a=>"str"in a?a.str:"").join(" ").toLocaleLowerCase()),r.catch(()=>e.delete(i)),e.set(i,r)),r};async function*s(){for(let i=1;i<=n.numPages;i+=1){const r=Math.min(n.numPages,i+$Y);for(let o=i+1;o<=r;o+=1)t(o).catch(()=>{});yield[i,await t(i).catch(()=>"")]}}return{pageText:t,pages:s}}function PY(n,e){let t=0;for(let s=n.indexOf(e);s>=0;s=n.indexOf(e,s+e.length))t+=1;return t}const RY=8,MY=24,IY=72,xE=1.35,OY=16e6;function NY(n,e){const t=Math.sqrt(OY/(n*n*e));return Math.min(window.devicePixelRatio||1,2,t)}function Ov(n,e){const t=n.getBoundingClientRect().top,s=e??t+n.clientHeight/2;for(const i of n.querySelectorAll("[data-page]")){const r=i.getBoundingClientRect();if(r.bottom"']/g,e=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[e]??e)}function DY(n,e,t){const s=e.trim().toLocaleLowerCase();if(!s)return od(n);const i=n.toLocaleLowerCase(),r=`pdf-search-highlight${t?" is-active":""}`;let o=0,a=i.indexOf(s);if(a<0)return od(n);let l="";for(;a>=0;)l+=od(n.slice(o,a)),l+=`${od(n.slice(a,a+s.length))}`,o=a+s.length,a=i.indexOf(s,o);return l+od(n.slice(o))}function jY({page:n,width:e,aspect:t,searchQuery:s,activeSearchPage:i,resolveCitation:r,warmPreviews:o,highlightBoxes:a,highlightKey:l,highlightBrief:c,onShowCitations:h,onShowReference:u,authors:d}){const p=U.useRef(null),[m,y]=U.useState(n<=2),{paperLinks:v,onAnnotations:g}=mY(p,m,r,o),[b,_]=U.useState([]);U.useEffect(()=>{if(!m||!r)return;let E=!0;return r.bibliographyLinks(n).then(async O=>{if(!E||(O.length&&(o==null||o([...new Set(O.map(w=>w.routeId))])),_(O),!O.length))return;const R=await Promise.all(O.map(w=>r.citationsOf(w.name)));E&&_(O.map((w,k)=>({...w,citations:R[k]})))}).catch(()=>{}),()=>{E=!1}},[n,r,m,o]);const x=n===i,A=U.useMemo(()=>s?({str:E})=>DY(E,s,x):void 0,[x,s]),[C,$]=U.useState(e);!m&&C!==e&&$(e);const[I,j]=U.useState(0),q=U.useCallback(()=>j(E=>E+1),[]),[L,B]=U.useState([]);U.useEffect(()=>{var O;if(!(d!=null&&d.length))return B([]);const E=(O=p.current)==null?void 0:O.querySelector(".pdf-page-layer:not(.is-pending)");E!=null&&E.querySelector(".textLayer")&&B(pY(E,d))},[d,I]);const H=C===e?[e]:[C,e],[D,X]=U.useState(),[te,J]=U.useState(!1);!m&&te&&J(!1);const Y=U.useRef(),ye=U.useRef(0),z=U.useCallback(E=>{var w;J(!0);const O=++ye.current,R=(w=p.current)==null?void 0:w.querySelector(`[data-layer-width="${E}"] canvas`);R==null||R.toBlob(k=>{!k||O!==ye.current||(Y.current&&URL.revokeObjectURL(Y.current),Y.current=URL.createObjectURL(k),X(Y.current))},"image/webp",.9)},[]);return U.useEffect(()=>()=>{ye.current+=1,Y.current&&URL.revokeObjectURL(Y.current)},[]),U.useEffect(()=>{const E=p.current;if(!E)return;const O=E.closest(".pdf-scroll"),R=new IntersectionObserver(([k])=>{k.isIntersecting&&y(!0)},{root:O,rootMargin:"250% 0px"}),w=new IntersectionObserver(([k])=>{k.isIntersecting||y(!1)},{root:O,rootMargin:"600% 0px"});return R.observe(E),w.observe(E),()=>{R.disconnect(),w.disconnect()}},[]),S.jsxs("div",{ref:p,className:"pdf-page","data-page":n,style:{minHeight:Math.round(e*t)},children:[m&&H.map(E=>{const O=E===C,R=O?()=>z(E):()=>{$(E),z(E)};return S.jsx("div",{"data-layer-width":E,className:O?"pdf-page-layer":"pdf-page-layer is-pending",style:O&&E!==e?{"--pdf-layer-scale":e/E}:void 0,"aria-hidden":O?void 0:!0,children:S.jsx(LX,{pageNumber:n,width:E,devicePixelRatio:NY(E,t),renderTextLayer:O,renderAnnotationLayer:O,onGetAnnotationsSuccess:g,onRenderSuccess:R,onRenderError:O?void 0:()=>$(E),onRenderTextLayerSuccess:O&&d?q:void 0,loading:null,customTextRenderer:A})},E)}),D&&!te&&S.jsx("img",{className:"pdf-page-snapshot",src:D,alt:"","aria-hidden":"true"}),m&&v.map(E=>{var O;return S.jsx(nY,{...E,onShowReference:u},(O=E.anchor.parentElement)==null?void 0:O.dataset.annotationId)}),m&&r&&b.map(E=>S.jsx(sY,{...E,onShowCitations:h},E.name)),m&&d&&L.map(({authorId:E,box:O})=>{const R=d.find(w=>w.id===E);return R&&S.jsx(rY,{...R,box:O},`${E}-${O.join(",")}`)}),a==null?void 0:a.map(([E,O,R,w],k)=>S.jsx("div",{className:`pdf-citation-highlight${c?" is-brief":""}`,"aria-hidden":"true",style:{left:`${E/10}%`,top:`${O/10}%`,width:`${(R-E)/10}%`,height:`${(w-O)/10}%`}},`${l}-${k}`))]})}function FY({downloadUrl:n,page:e,pages:t,zoomPercent:s,onPage:i,onZoomIn:r,onZoomOut:o,onFitWidth:a}){const l=c=>{c.preventDefault();const h=Number(new FormData(c.currentTarget).get("page"));Number.isInteger(h)&&i(h)};return S.jsxs("div",{className:"paper-pdf-toolbar","aria-label":"Paper preview controls",children:[S.jsxs("div",{className:"paper-pdf-toolbar-group",children:[S.jsx("button",{type:"button",onClick:()=>i(e-1),disabled:e<=1,"aria-label":"Previous page",children:"Previous"}),S.jsxs("form",{onSubmit:l,children:[S.jsx("label",{className:"sr-only",htmlFor:"paper-pdf-current-page",children:"Current page"}),S.jsx("input",{id:"paper-pdf-current-page",name:"page",type:"number",min:1,max:t||1,defaultValue:e,"aria-label":`Page ${e} of ${t||"unknown"}`},e)]}),S.jsxs("span",{role:"status","aria-live":"polite",children:["Page ",e," of ",t||"—"]}),S.jsx("button",{type:"button",onClick:()=>i(e+1),disabled:!t||e>=t,"aria-label":"Next page",children:"Next"})]}),S.jsxs("div",{className:"paper-pdf-toolbar-group",children:[S.jsx("button",{type:"button",onClick:o,"aria-label":"Zoom out",children:"−"}),S.jsxs("output",{"aria-live":"polite",children:[s,"%"]}),S.jsx("button",{type:"button",onClick:r,"aria-label":"Zoom in",children:"+"}),S.jsx("button",{type:"button",onClick:a,children:"Fit to width"}),S.jsx("a",{href:n,download:!0,children:"Download PDF"})]})]})}function zY({url:n,downloadUrl:e=n,paperKey:t,paperTitle:s,paperHref:i,resources:r,initialPage:o=1,resizeActive:a=!1,selectionEnabled:l=!1,paperVersion:c="",onPaperSelection:h,onPaperSelectionError:u,onPageChange:d,onClose:p,loadErrorMessage:m,chrome:y="reader",highlight:v,authors:g}){const b=U.useRef(null),_=U.useRef(null),x=U.useRef(null),[A,C]=U.useState(),[$,I]=U.useState();U.useEffect(()=>{C(void 0),I(void 0)},[v==null?void 0:v.nonce,n]);const j=A??v,q=j&&`${A?"jump":"cited"}-${j.nonce}`,[L,B]=U.useState(),H=A&&L!==q?void 0:j,D=U.useCallback(se=>{C(le=>({boxes:se,nonce:((le==null?void 0:le.nonce)??0)+1}))},[]),X=U.useCallback(se=>{I({citations:se,index:0}),D(se[0])},[D]),te=!!($&&$.citations.length>1),J=se=>{if(!$)return;const{citations:le}=$,Ue=($.index+se+le.length)%le.length;I({citations:le,index:Ue}),D(le[Ue])},Y=U.useRef(null),ye=U.useRef(),[z,E]=U.useState(),O=U.useCallback(async se=>{const le=await(z==null?void 0:z.referenceOf(se).catch(()=>null));return le&&D([le]),!!le},[z,D]),R=XC(),w=U.useMemo(()=>ZL(R),[R]),k=U.useRef(()=>{}),N=U.useRef(0),G=U.useRef(!1),Z=U.useRef(),ae=U.useRef(0),ie=U.useRef(),Ae=U.useRef(0),ct=U.useRef(0),Ie=U.useRef(1),Fe=U.useRef(1),Je=U.useRef(1),st=U.useRef(!1),[tn,Pn]=U.useState(0),[Et,As]=U.useState(0),[Rn,ks]=U.useState(xE),[hs,us]=U.useState([]),[Es,ln]=U.useState(-1),[cn,Mn]=U.useState(),Xn=U.useRef(()=>{}),[Yn,Pc]=U.useState(o),[Vu,V]=U.useState(),[me,Pe]=U.useState(700),[it,Lt]=U.useState(1),[Mo,Ei]=U.useState(""),[Rc,iv]=U.useState(!1),[dm,rv]=U.useState(""),[AL,fm]=U.useState(""),[kL,Wu]=U.useState(!1),[Mc,Gu]=U.useState([]),[ov,pm]=U.useState(0),av=Math.max(120,Math.round(me*it)),EL=U.useMemo(()=>y==="canvas"?{withCredentials:!0}:{disableStream:!0,disableAutoFetch:!0},[y]);HX({enabled:l&&!!c,pagesRoot:x,routeId:t,paperVersion:c,numPages:Et||void 0,resetKey:`${t}-${tn}`,onSelect:h,onError:u}),U.useEffect(()=>{jX()},[]),U.useEffect(()=>{var se;cancelAnimationFrame(Ae.current),window.clearTimeout(ct.current),Ae.current=0,ct.current=0,ae.current=0,As(0),ks(xE),us([]),ln(-1),Mn(void 0),E(void 0),Pc(o),V(void 0),Lt(1),Ie.current=1,Fe.current=1,Je.current=1,st.current=!1,(se=x.current)==null||se.style.setProperty("--pdf-live-scale","1"),Ei(""),ye.current=void 0,rv(""),fm(""),Gu([])},[o,t,tn]),U.useEffect(()=>{const se=_.current;if(!se)return;const le=()=>{var nn;const Dt=Math.max(240,se.clientWidth-10);a&&(st.current=!0);const gt=a||st.current;Je.current=gt?Dt/me:1,(nn=x.current)==null||nn.style.setProperty("--pdf-live-scale",String(Je.current)),gt||Pe(Dt)};le();const Ue=new ResizeObserver(le);return Ue.observe(se),()=>Ue.disconnect()},[me,a]),U.useLayoutEffect(()=>{var le;Ie.current=it,(le=x.current)==null||le.style.setProperty("--pdf-live-scale",String(st.current?Je.current:1));const se=_.current;se&&Z.current&&AE(se,Z.current),Z.current=void 0,G.current&&(se&&(se.scrollLeft=Math.max(0,(se.scrollWidth-se.clientWidth)/2)),G.current=!1)},[av,a,it]);const Ic=U.useCallback(se=>{window.clearTimeout(ct.current);const le=h_(se(Fe.current));Fe.current=le,G.current=le!==Ie.current,G.current&&_.current&&(Z.current=Ov(_.current)),Lt(le)},[]);U.useEffect(()=>{const se=_.current;if(!se)return;const le=Ue=>{Ue.ctrlKey&&(Ue.preventDefault(),ae.current+=Ue.deltaY,ie.current=Ue.clientY,!Ae.current&&(Ae.current=requestAnimationFrame(()=>{var jt;const Dt=ae.current;ae.current=0,Ae.current=0;const gt=h_(Fe.current*Math.exp(-Dt*.002));Fe.current=gt;const nn=Ov(se,ie.current);(jt=x.current)==null||jt.style.setProperty("--pdf-live-scale",String(Je.current*gt/Ie.current)),nn&&AE(se,nn),window.clearTimeout(ct.current),ct.current=window.setTimeout(()=>{G.current=gt!==Ie.current,G.current&&(Z.current=Ov(se,ie.current)),Lt(Fe.current)},180)})))};return se.addEventListener("wheel",le,{passive:!1}),()=>{se.removeEventListener("wheel",le),cancelAnimationFrame(Ae.current),window.clearTimeout(ct.current),Ae.current=0,ct.current=0,ae.current=0}},[]);const Ku=U.useCallback(se=>{const le=Math.max(1,Math.min(Et||1,se));Pc(le),d==null||d(le)},[d,Et]),mm=U.useCallback(()=>{N.current+=1,iv(!1),rv(""),fm(""),Gu([]),pm(0),Wu(!1)},[]);U.useEffect(()=>{const se=_.current;if(!se||!Et)return;let le=0,Ue=0;const Dt=(jt=!1)=>{window.clearTimeout(Ue),cancelAnimationFrame(le),le=requestAnimationFrame(()=>{const In=se.getBoundingClientRect().top,Bs=In+se.clientHeight/2;let Xu=Yn,gm=Number.POSITIVE_INFINITY;const Yu=new Map;se.querySelectorAll("[data-page]").forEach(Oc=>{const zr=Oc.getBoundingClientRect();Yu.set(Number(Oc.dataset.page),zr);const yA=Bs>=zr.top&&Bs<=zr.bottom?0:Math.min(Math.abs(Bs-zr.top),Math.abs(Bs-zr.bottom));yA{const zr=Yu.get(Oc.page);return zr?zr.top+zr.height*Oc.offset:Number.POSITIVE_INFINITY});ln(AY(TL,In+MY))})},gt=()=>{cancelAnimationFrame(le),window.clearTimeout(Ue),Ue=window.setTimeout(()=>Dt(!0),150)},nn=()=>Dt(!0);return se.addEventListener("scroll",gt,{passive:!0}),se.addEventListener("scrollend",nn),Dt(),()=>{se.removeEventListener("scroll",gt),se.removeEventListener("scrollend",nn),window.clearTimeout(Ue),cancelAnimationFrame(le)}},[hs,Yn,av,Et,Ku]),U.useEffect(()=>{const se=le=>{le.defaultPrevented||((le.ctrlKey||le.metaKey)&&le.key.toLowerCase()==="f"?(le.preventDefault(),iv(!0)):le.key==="Escape"&&Rc?(le.preventDefault(),mm()):le.key==="Escape"&&te?(le.preventDefault(),I(void 0)):le.key==="Escape"&&!le.repeat&&p&&(le.preventDefault(),p()))};return window.addEventListener("keydown",se),()=>window.removeEventListener("keydown",se)},[te,mm,p,Rc]),U.useEffect(()=>{const se=ye.current;if(!Rc||!se)return;const le=se.pages();(async()=>{for(;ye.current===se&&!(await le.next()).done;);})().catch(()=>{})},[Et,Rc]),U.useEffect(()=>{const se=ye.current,le=dm.trim().toLocaleLowerCase(),Ue=++N.current;if(!se||!le){fm(""),Gu([]),pm(0),Wu(!1);return}Wu(!0);const Dt=window.setTimeout(()=>void(async()=>{fm(dm.trim()),Gu([]),pm(0);const gt=[];for await(const[nn,jt]of se.pages()){if(N.current!==Ue)return;const In=PY(jt,le);if(In){gt.length||Zu(nn);for(let Bs=0;Bs{N.current===Ue&&Wu(!1)}),120);return()=>window.clearTimeout(Dt)},[dm,Et]);const Zu=se=>{var Dt,gt;const le=Math.max(1,Math.min(Et||1,se)),Ue=window.matchMedia("(prefers-reduced-motion: reduce)").matches?"instant":"smooth";V(Ue==="smooth"?le:void 0),(gt=(Dt=_.current)==null?void 0:Dt.querySelector(`[data-page="${le}"]`))==null||gt.scrollIntoView({block:"start",behavior:Ue}),Ue==="instant"&&Ku(le)};U.useEffect(()=>{const se=j==null?void 0:j.boxes[0],le=_.current,Ue=se&&(le==null?void 0:le.querySelector(`[data-page="${se.page}"]`));if(!se||!le||!Ue)return;const Dt=window.matchMedia("(prefers-reduced-motion: reduce)").matches?"instant":"smooth",gt=Ue.getBoundingClientRect(),nn=gt.top-le.getBoundingClientRect().top+le.scrollTop+gt.height*se.bbox[1]/1e3;V(Dt==="smooth"?se.page:void 0),le.scrollTo({top:Math.max(0,nn-IY),behavior:Dt}),Dt==="instant"&&Ku(se.page);let jt=0;const In=()=>{window.clearTimeout(jt),B(q)},Bs=()=>{window.clearTimeout(jt),jt=window.setTimeout(In,150)};return Bs(),le.addEventListener("scroll",Bs,{passive:!0}),le.addEventListener("scrollend",In),()=>{window.clearTimeout(jt),le.removeEventListener("scroll",Bs),le.removeEventListener("scrollend",In)}},[q,Et,Rn]);const gA=(se,le)=>{const Ue=_.current,Dt=Ue==null?void 0:Ue.querySelector(`[data-page="${se.page}"]`);if(!Ue||!Dt)return;const gt=le??(window.matchMedia("(prefers-reduced-motion: reduce)").matches?"instant":"smooth"),nn=Dt.getBoundingClientRect(),jt=nn.top-Ue.getBoundingClientRect().top+Ue.scrollTop+nn.height*se.offset;V(gt==="smooth"?se.page:void 0),Mn(gt==="smooth"?se.index:void 0),Ue.scrollTo({top:Math.max(0,jt-RY),behavior:gt}),gt==="instant"&&Ku(se.page),y==="reader"&&window.history.replaceState(window.history.state,"",`#pdf-section-${se.index}`)};U.useLayoutEffect(()=>{k.current=Zu,Xn.current=gA});const CL=se=>{if(!Mc.length)return;const le=(ov+se+Mc.length)%Mc.length;pm(le),Zu(Mc[le])},$L=U.useMemo(()=>Array.from({length:Et},(se,le)=>le+1),[Et]);return S.jsxs("div",{ref:b,className:"pdf-viewer",children:[y==="canvas"?S.jsx(FY,{downloadUrl:e,page:Vu??Yn,pages:Et,zoomPercent:Math.round(it*100),onPage:Zu,onZoomIn:()=>Ic(se=>Fm(se,1)),onZoomOut:()=>Ic(se=>Fm(se,-1)),onFitWidth:()=>Ic(()=>1)}):S.jsx(VX,{paperTitle:s,paperHref:i,resources:r,page:Vu??Yn,pages:Et,zoomPercent:Math.round(it*100),searchOpen:Rc,searchQuery:dm,searchMatch:ov,searchCount:Mc.length,searching:kL,onPage:Zu,onZoom:se=>Ic(()=>se),onZoomIn:()=>Ic(se=>Fm(se,1)),onZoomOut:()=>Ic(se=>Fm(se,-1)),onToggleSearch:()=>Rc?mm():iv(!0),onCloseSearch:mm,onSearchQuery:rv,onSearch:CL}),S.jsxs("div",{className:"pdf-scroll-frame",children:[S.jsx("div",{ref:_,className:"pdf-scroll",role:"region","aria-label":y==="canvas"?`${s} PDF preview`:"Paper PDF",children:Mo?S.jsxs("div",{className:"pdf-error",role:"alert",children:[S.jsx("p",{children:Mo}),S.jsxs("div",{children:[S.jsx("button",{type:"button",onClick:()=>Pn(se=>se+1),children:"Retry"})," ",S.jsx("a",{href:e,target:"_blank",rel:"noopener noreferrer",children:"Open PDF"})]})]}):S.jsx(kX,{file:n,options:EL,loading:S.jsx("div",{className:"pdf-loading",role:"status",children:y==="canvas"?"Loading paper preview…":"Loading paper…"}),onLoadSuccess:se=>{Y.current=se,ye.current=TY(se),y==="reader"&&E(()=>tY(se,w.lookup)),As(se.numPages),Ei("");const le=se.getPage(1).then(jt=>{const[In,Bs,Xu,gm]=jt.view,Yu=(gm-Bs)/(Xu-In);Y.current===se&&Yu>0&&ks(Yu)},()=>{}),Ue=Math.max(1,Math.min(se.numPages,o)),Dt=()=>{var jt,In;Ue<=1||((In=(jt=_.current)==null?void 0:jt.querySelector(`[data-page="${Ue}"]`))==null||In.scrollIntoView({block:"start"}),Pc(Ue),d==null||d(Ue))},gt=jt=>void le.then(()=>{requestAnimationFrame(()=>requestAnimationFrame(()=>{Y.current===se&&jt()}))}),nn=y==="reader"?xY(window.location.hash):void 0;nn===void 0&>(Dt),CY(se).catch(()=>[]).then(jt=>{if(Y.current!==se||(us(jt),nn===void 0))return;const In=jt[nn];gt(()=>In?Xn.current(In,"instant"):Dt())})},onLoadError:se=>Ei(m||LY(se)),externalLinkTarget:"_blank",onItemClick:({pageNumber:se})=>k.current(se),children:S.jsx("div",{ref:x,className:"pdf-pages",style:{"--pdf-live-scale":Je.current},children:$L.map(se=>S.jsx(jY,{page:se,width:av,aspect:Rn,searchQuery:AL,activeSearchPage:Mc[ov],resolveCitation:z,warmPreviews:w.warm,highlightBoxes:H==null?void 0:H.boxes.filter(le=>le.page===se).map(le=>le.bbox),highlightKey:q,highlightBrief:!!A,onShowCitations:X,onShowReference:O,authors:se===1&&y==="reader"?g:void 0},se))})},`${t}-${tn}`)}),$&&te&&S.jsx(wY,{index:$.index,count:$.citations.length,onStep:J,onClose:()=>I(void 0)}),S.jsx(bY,{entries:hs,activeIndex:cn??Es,onSelect:gA})]})]})}let d_=[],jI=[];(()=>{let n="lc,34,7n,7,7b,19,,,,2,,2,,,20,b,1c,l,g,,2t,7,2,6,2,2,,4,z,,u,r,2j,b,1m,9,9,,o,4,,9,,3,,5,17,3,1n,9,16,o,,x,1i,3,,i,,7,a,2,t,3,1k,,,7,2,2,2,3,9,,a,2,q,,2,3,1k,,,5,4,2,2,3,3,,u,2,3,,b,3,1k,,,8,,3,,3,k,2,m,6,,3,1k,,,7,2,2,2,3,7,3,a,2,u,,1n,5,3,3,,4,9,,14,5,1j,,,7,,3,,4,7,2,b,2,t,3,1k,,,7,,3,,4,7,2,b,2,f,,c,4,1j,2,,7,,3,,4,9,,a,2,t,3,1y,,4,6,,,,8,i,2,1p,,,8,c,8,2q,,,a,b,7,21,2,r,,,,,,4,2,1d,k,,2,5,b,,10,9,,2u,b,,6,n,4,4,3,g,4,d,,,3,6,,f,,jj,3,qa,4,s,3,t,2,u,2,1s,w,9,,19,3,,,39,2,y,,3a,c,4,c,63,5,1l,a,,,,,2,o,2,,1c,1a,2,c,k,5,1b,h,12,9,c,3,u,d,1k,e,1c,k,48,3,,l,4,,6,,2,3,5i,1s,ek,,5f,x,2da,3,3x,,2o,w,fe,6,2x,2,n9w,4,,a,w,2,28,2,7k,,3,,4,,n,5,4,,2b,2,1e,i,q,i,d,,12,8,p,d,18,4,1b,e,10,,1v,e,c,,8,2,1a,,1f,,,3,2,2,5,2,,,15,5,5,2,6k,8,,2,fn4,,kh,g,g,g,a6,2,gt,,6a,,45,5,1ae,3,,2,5,4,14,3,4,,4l,2,fx,4,1t,5,8t,2,25,6,1y,b,1d,4,3e,3,1h,f,15,,2,2,a,4,19,b,7,,1p,3,10,e,g,2,18,,c,3,1c,e,8,4,,2,2k,c,6,,2,,4d,c,l,4,1j,2,,7,2,2,2,3,9,,a,2,2,7,3,5,1v,9,,,2,,,4,,5,,,e,2,2a,i,n,,29,k,6j,7,2,9,r,2,2a,h,2y,d,2t,3,2,a,74,f,6t,6,,2,2,4,,,,2,3x,7,2,7,3,,s,a,14,7,,4,8,,9,b,1a,g,5i,8,5j,8,,8,2a,m,,e,3e,6,3,,,2,,7,,,1u,5,,2,,5,9n,4,9,2,,,1c,7,3,5,n,,44l,,6,f,8ug,i,1xc,5,1n,7,t4,,,1j,7,4,29,,b,2,f57,2,3mp,1a,2,n,f2,5,3,6,8,8,2,7,u,4,44,3,1iz,1j,4,1e,8,,e,,m,5,,f,11s,7,,h,2,7,,2,,5,2s,,4g,7,af,,1p,4,e4,4,72,2,6r,,2,,7,2,5,,d6,7,31,7,240,5".split(",").map(e=>e?parseInt(e,36):1);for(let e=0,t=0;e>1;if(n=jI[s])e=s+1;else return!0;if(e==t)return!1}}function kE(n){return n>=127462&&n<=127487}const EE=8205;function BY(n,e,t=!0,s=!0){return(t?FI:UY)(n,e,s)}function FI(n,e,t){if(e==n.length)return e;e&&zI(n.charCodeAt(e))&&HI(n.charCodeAt(e-1))&&e--;let s=Nv(n,e);for(e+=CE(s);e=0&&kE(Nv(n,o));)r++,o-=2;if(r%2==0)break;e+=2}else break}return e}function UY(n,e,t){for(;e>1;){let s=FI(n,e-2,t);if(s=56320&&n<57344}function HI(n){return n>=55296&&n<56320}function CE(n){return n<65536?1:2}let lt=class BI{lineAt(e){if(e<0||e>this.length)throw new RangeError(`Invalid position ${e} in document of length ${this.length}`);return this.lineInner(e,!1,1,0)}line(e){if(e<1||e>this.lines)throw new RangeError(`Invalid line number ${e} in ${this.lines}-line document`);return this.lineInner(e,!0,1,0)}replace(e,t,s){[e,t]=ku(this,e,t);let i=[];return this.decompose(0,e,i,2),s.length&&s.decompose(0,s.length,i,3),this.decompose(t,this.length,i,1),Cr.from(i,this.length-(t-e)+s.length)}append(e){return this.replace(this.length,this.length,e)}slice(e,t=this.length){[e,t]=ku(this,e,t);let s=[];return this.decompose(e,t,s,0),Cr.from(s,t-e)}eq(e){if(e==this)return!0;if(e.length!=this.length||e.lines!=this.lines)return!1;let t=this.scanIdentical(e,1),s=this.length-this.scanIdentical(e,-1),i=new Xd(this),r=new Xd(e);for(let o=t,a=t;;){if(i.next(o),r.next(o),o=0,i.lineBreak!=r.lineBreak||i.done!=r.done||i.value!=r.value)return!1;if(a+=i.value.length,i.done||a>=s)return!0}}iter(e=1){return new Xd(this,e)}iterRange(e,t=this.length){return new UI(this,e,t)}iterLines(e,t){let s;if(e==null)s=this.iter();else{t==null&&(t=this.lines+1);let i=this.line(e).from;s=this.iterRange(i,Math.max(i,t==this.lines+1?this.length:t<=1?0:this.line(t-1).to))}return new qI(s)}toString(){return this.sliceString(0)}toJSON(){let e=[];return this.flatten(e),e}constructor(){}static of(e){if(e.length==0)throw new RangeError("A document must have at least one line");return e.length==1&&!e[0]?BI.empty:e.length<=32?new Yt(e):Cr.from(Yt.split(e,[]))}};class Yt extends lt{constructor(e,t=qY(e)){super(),this.text=e,this.length=t}get lines(){return this.text.length}get children(){return null}lineInner(e,t,s,i){for(let r=0;;r++){let o=this.text[r],a=i+o.length;if((t?s:a)>=e)return new VY(i,a,s,o);i=a+1,s++}}decompose(e,t,s,i){let r=e<=0&&t>=this.length?this:new Yt($E(this.text,e,t),Math.min(t,this.length)-Math.max(0,e));if(i&1){let o=s.pop(),a=Gg(r.text,o.text.slice(),0,r.length);if(a.length<=32)s.push(new Yt(a,o.length+r.length));else{let l=a.length>>1;s.push(new Yt(a.slice(0,l)),new Yt(a.slice(l)))}}else s.push(r)}replace(e,t,s){if(!(s instanceof Yt))return super.replace(e,t,s);[e,t]=ku(this,e,t);let i=Gg(this.text,Gg(s.text,$E(this.text,0,e)),t),r=this.length+s.length-(t-e);return i.length<=32?new Yt(i,r):Cr.from(Yt.split(i,[]),r)}sliceString(e,t=this.length,s=` +`){[e,t]=ku(this,e,t);let i="";for(let r=0,o=0;r<=t&&oe&&o&&(i+=s),er&&(i+=a.slice(Math.max(0,e-r),t-r)),r=l+1}return i}flatten(e){for(let t of this.text)e.push(t)}scanIdentical(){return 0}static split(e,t){let s=[],i=-1;for(let r of e)s.push(r),i+=r.length+1,s.length==32&&(t.push(new Yt(s,i)),s=[],i=-1);return i>-1&&t.push(new Yt(s,i)),t}}class Cr extends lt{constructor(e,t){super(),this.children=e,this.length=t,this.lines=0;for(let s of e)this.lines+=s.lines}lineInner(e,t,s,i){for(let r=0;;r++){let o=this.children[r],a=i+o.length,l=s+o.lines-1;if((t?l:a)>=e)return o.lineInner(e,t,s,i);i=a+1,s=l+1}}decompose(e,t,s,i){for(let r=0,o=0;o<=t&&r=o){let c=i&((o<=e?1:0)|(l>=t?2:0));o>=e&&l<=t&&!c?s.push(a):a.decompose(e-o,t-o,s,c)}o=l+1}}replace(e,t,s){if([e,t]=ku(this,e,t),s.lines=r&&t<=a){let l=o.replace(e-r,t-r,s),c=this.lines-o.lines+l.lines;if(l.lines>4&&l.lines>c>>6){let h=this.children.slice();return h[i]=l,new Cr(h,this.length-(t-e)+s.length)}return super.replace(r,a,l)}r=a+1}return super.replace(e,t,s)}sliceString(e,t=this.length,s=` +`){[e,t]=ku(this,e,t);let i="";for(let r=0,o=0;re&&r&&(i+=s),eo&&(i+=a.sliceString(e-o,t-o,s)),o=l+1}return i}flatten(e){for(let t of this.children)t.flatten(e)}scanIdentical(e,t){if(!(e instanceof Cr))return 0;let s=0,[i,r,o,a]=t>0?[0,0,this.children.length,e.children.length]:[this.children.length-1,e.children.length-1,-1,-1];for(;;i+=t,r+=t){if(i==o||r==a)return s;let l=this.children[i],c=e.children[r];if(l!=c)return s+l.scanIdentical(c,t);s+=l.length+1}}static from(e,t=e.reduce((s,i)=>s+i.length+1,-1)){let s=0;for(let p of e)s+=p.lines;if(s<32){let p=[];for(let m of e)m.flatten(p);return new Yt(p,t)}let i=Math.max(32,s>>5),r=i<<1,o=i>>1,a=[],l=0,c=-1,h=[];function u(p){let m;if(p.lines>r&&p instanceof Cr)for(let y of p.children)u(y);else p.lines>o&&(l>o||!l)?(d(),a.push(p)):p instanceof Yt&&l&&(m=h[h.length-1])instanceof Yt&&p.lines+m.lines<=32?(l+=p.lines,c+=p.length+1,h[h.length-1]=new Yt(m.text.concat(p.text),m.length+1+p.length)):(l+p.lines>i&&d(),l+=p.lines,c+=p.length+1,h.push(p))}function d(){l!=0&&(a.push(h.length==1?h[0]:Cr.from(h,c)),c=-1,l=h.length=0)}for(let p of e)u(p);return d(),a.length==1?a[0]:new Cr(a,t)}}lt.empty=new Yt([""],0);function qY(n){let e=-1;for(let t of n)e+=t.length+1;return e}function Gg(n,e,t=0,s=1e9){for(let i=0,r=0,o=!0;r=t&&(l>s&&(a=a.slice(0,s-i)),i0?1:(e instanceof Yt?e.text.length:e.children.length)<<1]}nextInner(e,t){for(this.done=this.lineBreak=!1;;){let s=this.nodes.length-1,i=this.nodes[s],r=this.offsets[s],o=r>>1,a=i instanceof Yt?i.text.length:i.children.length;if(o==(t>0?a:0)){if(s==0)return this.done=!0,this.value="",this;t>0&&this.offsets[s-1]++,this.nodes.pop(),this.offsets.pop()}else if((r&1)==(t>0?0:1)){if(this.offsets[s]+=t,e==0)return this.lineBreak=!0,this.value=` +`,this;e--}else if(i instanceof Yt){let l=i.text[o+(t<0?-1:0)];if(this.offsets[s]+=t,l.length>Math.max(0,e))return this.value=e==0?l:t>0?l.slice(e):l.slice(0,l.length-e),this;e-=l.length}else{let l=i.children[o+(t<0?-1:0)];e>l.length?(e-=l.length,this.offsets[s]+=t):(t<0&&this.offsets[s]--,this.nodes.push(l),this.offsets.push(t>0?1:(l instanceof Yt?l.text.length:l.children.length)<<1))}}}next(e=0){return e<0&&(this.nextInner(-e,-this.dir),e=this.value.length),this.nextInner(e,this.dir)}}class UI{constructor(e,t,s){this.value="",this.done=!1,this.cursor=new Xd(e,t>s?-1:1),this.pos=t>s?e.length:0,this.from=Math.min(t,s),this.to=Math.max(t,s)}nextInner(e,t){if(t<0?this.pos<=this.from:this.pos>=this.to)return this.value="",this.done=!0,this;e+=Math.max(0,t<0?this.pos-this.to:this.from-this.pos);let s=t<0?this.pos-this.from:this.to-this.pos;e>s&&(e=s),s-=e;let{value:i}=this.cursor.next(e);return this.pos+=(i.length+e)*t,this.value=i.length<=s?i:t<0?i.slice(i.length-s):i.slice(0,s),this.done=!this.value,this}next(e=0){return e<0?e=Math.max(e,this.from-this.pos):e>0&&(e=Math.min(e,this.to-this.pos)),this.nextInner(e,this.cursor.dir)}get lineBreak(){return this.cursor.lineBreak&&this.value!=""}}class qI{constructor(e){this.inner=e,this.afterBreak=!0,this.value="",this.done=!1}next(e=0){let{done:t,lineBreak:s,value:i}=this.inner.next(e);return t&&this.afterBreak?(this.value="",this.afterBreak=!1):t?(this.done=!0,this.value=""):s?this.afterBreak?this.value="":(this.afterBreak=!0,this.next()):(this.value=i,this.afterBreak=!1),this}get lineBreak(){return!1}}typeof Symbol<"u"&&(lt.prototype[Symbol.iterator]=function(){return this.iter()},Xd.prototype[Symbol.iterator]=UI.prototype[Symbol.iterator]=qI.prototype[Symbol.iterator]=function(){return this});class VY{constructor(e,t,s,i){this.from=e,this.to=t,this.number=s,this.text=i}get length(){return this.to-this.from}}function ku(n,e,t){return e=Math.max(0,Math.min(n.length,e)),[e,Math.max(e,Math.min(n.length,t))]}function $n(n,e,t=!0,s=!0){return BY(n,e,t,s)}function WY(n){return n>=56320&&n<57344}function GY(n){return n>=55296&&n<56320}function VI(n,e){let t=n.charCodeAt(e);if(!GY(t)||e+1==n.length)return t;let s=n.charCodeAt(e+1);return WY(s)?(t-55296<<10)+(s-56320)+65536:t}function KY(n){return n<=65535?String.fromCharCode(n):(n-=65536,String.fromCharCode((n>>10)+55296,(n&1023)+56320))}function WI(n){return n<65536?1:2}const f_=/\r\n?|\n/;var ni=function(n){return n[n.Simple=0]="Simple",n[n.TrackDel=1]="TrackDel",n[n.TrackBefore=2]="TrackBefore",n[n.TrackAfter=3]="TrackAfter",n}(ni||(ni={}));class Lr{constructor(e){this.sections=e}get length(){let e=0;for(let t=0;te)return r+(e-i);r+=a}else{if(s!=ni.Simple&&c>=e&&(s==ni.TrackDel&&ie||s==ni.TrackBefore&&ie))return null;if(c>e||c==e&&t<0&&!a)return e==i||t<0?r:r+l;r+=l}i=c}if(e>i)throw new RangeError(`Position ${e} is out of range for changeset of length ${i}`);return r}touchesRange(e,t=e){for(let s=0,i=0;s=0&&i<=t&&a>=e)return it?"cover":!0;i=a}return!1}toString(){let e="";for(let t=0;t=0?":"+i:"")}return e}toJSON(){return this.sections}static fromJSON(e){if(!Array.isArray(e)||e.length%2||e.some(t=>typeof t!="number"))throw new RangeError("Invalid JSON representation of ChangeDesc");return new Lr(e)}static create(e){return new Lr(e)}}class gn extends Lr{constructor(e,t){super(e),this.inserted=t}apply(e){if(this.length!=e.length)throw new RangeError("Applying change set to a document with the wrong length");return p_(this,(t,s,i,r,o)=>e=e.replace(i,i+(s-t),o),!1),e}mapDesc(e,t=!1){return m_(this,e,t,!0)}invert(e){let t=this.sections.slice(),s=[];for(let i=0,r=0;i=0){t[i]=a,t[i+1]=o;let l=i>>1;for(;s.length0&&Sa(s,t,r.text),r.forward(h),a+=h}let c=e[o++];for(;a>1].toJSON()))}return e}static of(e,t,s){let i=[],r=[],o=0,a=null;function l(h=!1){if(!h&&!i.length)return;od||u<0||d>t)throw new RangeError(`Invalid change range ${u} to ${d} (in doc of length ${t})`);let m=p?typeof p=="string"?lt.of(p.split(s||f_)):p:lt.empty,y=m.length;if(u==d&&y==0)return;uo&&os(i,u-o,-1),os(i,d-u,y),Sa(r,i,m),o=d}}return c(e),l(!a),a}static empty(e){return new gn(e?[e,-1]:[],[])}static fromJSON(e){if(!Array.isArray(e))throw new RangeError("Invalid JSON representation of ChangeSet");let t=[],s=[];for(let i=0;ia&&typeof o!="string"))throw new RangeError("Invalid JSON representation of ChangeSet");if(r.length==1)t.push(r[0],0);else{for(;s.length=0&&t<=0&&t==n[i+1]?n[i]+=e:i>=0&&e==0&&n[i]==0?n[i+1]+=t:s?(n[i]+=e,n[i+1]+=t):n.push(e,t)}function Sa(n,e,t){if(t.length==0)return;let s=e.length-2>>1;if(s>1])),!(t||o==n.sections.length||n.sections[o+1]<0);)a=n.sections[o++],l=n.sections[o++];e(i,c,r,h,u),i=c,r=h}}}function m_(n,e,t,s=!1){let i=[],r=s?[]:null,o=new uf(n),a=new uf(e);for(let l=-1;;){if(o.done&&a.len||a.done&&o.len)throw new Error("Mismatched change set lengths");if(o.ins==-1&&a.ins==-1){let c=Math.min(o.len,a.len);os(i,c,-1),o.forward(c),a.forward(c)}else if(a.ins>=0&&(o.ins<0||l==o.i||o.off==0&&(a.len=0&&l=0){let c=0,h=o.len;for(;h;)if(a.ins==-1){let u=Math.min(h,a.len);c+=u,h-=u,a.forward(u)}else if(a.ins==0&&a.lenl||o.ins>=0&&o.len>l)&&(a||s.length>c),r.forward2(l),o.forward(l)}}}}class uf{constructor(e){this.set=e,this.i=0,this.next()}next(){let{sections:e}=this.set;this.i>1;return t>=e.length?lt.empty:e[t]}textBit(e){let{inserted:t}=this.set,s=this.i-2>>1;return s>=t.length&&!e?lt.empty:t[s].slice(this.off,e==null?void 0:this.off+e)}forward(e){e==this.len?this.next():(this.len-=e,this.off+=e)}forward2(e){this.ins==-1?this.forward(e):e==this.ins?this.next():(this.ins-=e,this.off+=e)}}class Uo{constructor(e,t,s,i){this.from=e,this.to=t,this.flags=s,this.goalColumn=i}get anchor(){return this.flags&32?this.to:this.from}get head(){return this.flags&32?this.from:this.to}get empty(){return this.from==this.to}get assoc(){return this.flags&8?-1:this.flags&16?1:0}get undirectional(){return(this.flags&64)>0}get bidiLevel(){let e=this.flags&7;return e==7?null:e}map(e,t=-1){let s,i;return this.empty?s=i=e.mapPos(this.from,t):(s=e.mapPos(this.from,1),i=e.mapPos(this.to,-1)),s==this.from&&i==this.to?this:new Uo(s,i,this.flags,this.goalColumn)}extend(e,t=e,s=0){if(e<=this.anchor&&t>=this.anchor)return ne.range(e,t,void 0,void 0,s);let i=Math.abs(e-this.anchor)>Math.abs(t-this.anchor)?e:t;return ne.range(this.anchor,i,void 0,void 0,s)}eq(e,t=!1){return this.anchor==e.anchor&&this.head==e.head&&this.goalColumn==e.goalColumn&&(!t||!this.empty||this.assoc==e.assoc)}toJSON(){return{anchor:this.anchor,head:this.head}}static fromJSON(e){if(!e||typeof e.anchor!="number"||typeof e.head!="number")throw new RangeError("Invalid JSON representation for SelectionRange");return ne.range(e.anchor,e.head)}static create(e,t,s,i){return new Uo(e,t,s,i)}}class ne{constructor(e,t){this.ranges=e,this.mainIndex=t}map(e,t=-1){return e.empty?this:ne.create(this.ranges.map(s=>s.map(e,t)),this.mainIndex)}eq(e,t=!1){if(this.ranges.length!=e.ranges.length||this.mainIndex!=e.mainIndex)return!1;for(let s=0;se.toJSON()),main:this.mainIndex}}static fromJSON(e){if(!e||!Array.isArray(e.ranges)||typeof e.main!="number"||e.main>=e.ranges.length)throw new RangeError("Invalid JSON representation for EditorSelection");return new ne(e.ranges.map(t=>Uo.fromJSON(t)),e.main)}static single(e,t=e){return new ne([ne.range(e,t)],0)}static create(e,t=0){if(e.length==0)throw new RangeError("A selection needs at least one range");for(let s=0,i=0;ii.from-r.from),t=e.indexOf(s);for(let i=1;ir.head?ne.range(l,a):ne.range(a,l))}}return new ne(e,t)}}function KI(n,e){for(let t of n.ranges)if(t.to>e)throw new RangeError("Selection points outside of document")}let Dx=0;class be{constructor(e,t,s,i,r){this.combine=e,this.compareInput=t,this.compare=s,this.isStatic=i,this.id=Dx++,this.default=e([]),this.extensions=typeof r=="function"?r(this):r}get reader(){return this}static define(e={}){return new be(e.combine||(t=>t),e.compareInput||((t,s)=>t===s),e.compare||(e.combine?(t,s)=>t===s:jx),!!e.static,e.enables)}of(e){return new Kg([],this,0,e)}compute(e,t){if(this.isStatic)throw new Error("Can't compute a static facet");return new Kg(e,this,1,t)}computeN(e,t){if(this.isStatic)throw new Error("Can't compute a static facet");return new Kg(e,this,2,t)}from(e,t){return t||(t=s=>s),this.compute([e],s=>t(s.field(e)))}}function jx(n,e){return n==e||n.length==e.length&&n.every((t,s)=>t===e[s])}class Kg{constructor(e,t,s,i){this.dependencies=e,this.facet=t,this.type=s,this.value=i,this.id=Dx++}dynamicSlot(e){var t;let s=this.value,i=this.facet.compareInput,r=this.id,o=e[r]>>1,a=this.type==2,l=!1,c=!1,h=[];for(let u of this.dependencies)u=="doc"?l=!0:u=="selection"?c=!0:((t=e[u.id])!==null&&t!==void 0?t:1)&1||h.push(e[u.id]);return{create(u){return u.values[o]=s(u),1},update(u,d){if(l&&d.docChanged||c&&(d.docChanged||d.selection)||g_(u,h)){let p=s(u);if(a?!TE(p,u.values[o],i):!i(p,u.values[o]))return u.values[o]=p,1}return 0},reconfigure:(u,d)=>{let p,m=d.config.address[r];if(m!=null){let y=Ey(d,m);if(this.dependencies.every(v=>v instanceof be?d.facet(v)===u.facet(v):v instanceof Fr?d.field(v,!1)==u.field(v,!1):!0)||(a?TE(p=s(u),y,i):i(p=s(u),y)))return u.values[o]=y,0}else p=s(u);return u.values[o]=p,1}}}get extension(){return this}}function TE(n,e,t){if(n.length!=e.length)return!1;for(let s=0;sn[l.id]),i=t.map(l=>l.type),r=s.filter(l=>!(l&1)),o=n[e.id]>>1;function a(l){let c=[];for(let h=0;hs===i),e);return e.provide&&(t.provides=e.provide(t)),t}create(e){let t=e.facet(zm).find(s=>s.field==this);return((t==null?void 0:t.create)||this.createF)(e)}slot(e){let t=e[this.id]>>1;return{create:s=>(s.values[t]=this.create(s),1),update:(s,i)=>{let r=s.values[t],o=this.updateF(r,i);return this.compareF(r,o)?0:(s.values[t]=o,1)},reconfigure:(s,i)=>{let r=s.facet(zm),o=i.facet(zm),a;return(a=r.find(l=>l.field==this))&&a!=o.find(l=>l.field==this)?(s.values[t]=a.create(s),1):i.config.address[this.id]!=null?(s.values[t]=i.field(this),0):(s.values[t]=this.create(s),1)}}}init(e){return[this,zm.of({field:this,create:e})]}get extension(){return this}}const rl={lowest:4,low:3,default:2,high:1,highest:0};function ad(n){return e=>new ZI(e,n)}const V0={highest:ad(rl.highest),high:ad(rl.high),default:ad(rl.default),low:ad(rl.low),lowest:ad(rl.lowest)};class ZI{constructor(e,t){this.inner=e,this.prec=t}get extension(){return this}}class rm{of(e){return new y_(this,e)}reconfigure(e){return rm.reconfigure.of({compartment:this,extension:e})}get(e){return e.config.compartments.get(this)}}class y_{constructor(e,t){this.compartment=e,this.inner=t}get extension(){return this}}class ky{constructor(e,t,s,i,r,o){for(this.base=e,this.compartments=t,this.dynamicSlots=s,this.address=i,this.staticValues=r,this.facets=o,this.statusTemplate=[];this.statusTemplate.length>1]}static resolve(e,t,s){let i=[],r=Object.create(null),o=new Map;for(let d of XY(e,t,o))d instanceof Fr?i.push(d):(r[d.facet.id]||(r[d.facet.id]=[])).push(d);let a=Object.create(null),l=[],c=[];for(let d of i)a[d.id]=c.length<<1,c.push(p=>d.slot(p));let h=s==null?void 0:s.config.facets;for(let d in r){let p=r[d],m=p[0].facet,y=h&&h[d]||[];if(p.every(v=>v.type==0))if(a[m.id]=l.length<<1|1,jx(y,p))l.push(s.facet(m));else{let v=m.combine(p.map(g=>g.value));l.push(s&&m.compare(v,s.facet(m))?s.facet(m):v)}else{for(let v of p)v.type==0?(a[v.id]=l.length<<1|1,l.push(v.value)):(a[v.id]=c.length<<1,c.push(g=>v.dynamicSlot(g)));a[m.id]=c.length<<1,c.push(v=>ZY(v,m,p))}}let u=c.map(d=>d(a));return new ky(e,o,u,a,l,r)}}function XY(n,e,t){let s=[[],[],[],[],[]],i=new Map;function r(o,a){let l=i.get(o);if(l!=null){if(l<=a)return;let c=s[l].indexOf(o);c>-1&&s[l].splice(c,1),o instanceof y_&&t.delete(o.compartment)}if(i.set(o,a),Array.isArray(o))for(let c of o)r(c,a);else if(o instanceof y_){if(t.has(o.compartment))throw new RangeError("Duplicate use of compartment in extensions");let c=e.get(o.compartment)||o.inner;t.set(o.compartment,c),r(c,a)}else if(o instanceof ZI)r(o.inner,o.prec);else if(o instanceof Fr)s[a].push(o),o.provides&&r(o.provides,a);else if(o instanceof Kg)s[a].push(o),o.facet.extensions&&r(o.facet.extensions,rl.default);else{let c=o.extension;if(!c)throw new Error(`Unrecognized extension value in extension set (${o}).`);if(c==o)throw new Error(`Unrecognized extension value in extension set (${o}). This sometimes happens because multiple instances of @codemirror/state are loaded, breaking instanceof checks.`);r(c,a)}}return r(n,rl.default),s.reduce((o,a)=>o.concat(a))}function Yd(n,e){if(e&1)return 2;let t=e>>1,s=n.status[t];if(s==4)throw new Error("Cyclic dependency between fields and/or facets");if(s&2)return s;n.status[t]=4;let i=n.computeSlot(n,n.config.dynamicSlots[t]);return n.status[t]=2|i}function Ey(n,e){return e&1?n.config.staticValues[e>>1]:n.values[e>>1]}const XI=be.define(),v_=be.define({combine:n=>n.some(e=>e),static:!0}),YI=be.define({combine:n=>n.length?n[0]:void 0,static:!0}),JI=be.define(),QI=be.define(),eO=be.define(),tO=be.define({combine:n=>n.length?n[0]:!1});class ja{constructor(e,t){this.type=e,this.value=t}static define(){return new YY}}class YY{of(e){return new ja(this,e)}}class JY{constructor(e){this.map=e}of(e){return new _t(this,e)}}class _t{constructor(e,t){this.type=e,this.value=t}map(e){let t=this.type.map(this.value,e);return t===void 0?void 0:t==this.value?this:new _t(this.type,t)}is(e){return this.type==e}static define(e={}){return new JY(e.map||(t=>t))}static mapEffects(e,t){if(!e.length)return e;let s=[];for(let i of e){let r=i.map(t);r&&s.push(r)}return s}}_t.reconfigure=_t.define();_t.appendConfig=_t.define();class bn{constructor(e,t,s,i,r,o){this.startState=e,this.changes=t,this.selection=s,this.effects=i,this.annotations=r,this.scrollIntoView=o,this._doc=null,this._state=null,s&&KI(s,t.newLength),r.some(a=>a.type==bn.time)||(this.annotations=r.concat(bn.time.of(Date.now())))}static create(e,t,s,i,r,o){return new bn(e,t,s,i,r,o)}get newDoc(){return this._doc||(this._doc=this.changes.apply(this.startState.doc))}get newSelection(){return this.selection||this.startState.selection.map(this.changes)}get state(){return this._state||this.startState.applyTransaction(this),this._state}annotation(e){for(let t of this.annotations)if(t.type==e)return t.value}get docChanged(){return!this.changes.empty}get reconfigured(){return this.startState.config!=this.state.config}isUserEvent(e){let t=this.annotation(bn.userEvent);return!!(t&&(t==e||t.length>e.length&&t.slice(0,e.length)==e&&t[e.length]=="."))}}bn.time=ja.define();bn.userEvent=ja.define();bn.addToHistory=ja.define();bn.remote=ja.define();function QY(n,e){let t=[];for(let s=0,i=0;;){let r,o;if(s=n[s]))r=n[s++],o=n[s++];else if(i=0;i--){let r=s[i](n);r instanceof bn?n=r:Array.isArray(r)&&r.length==1&&r[0]instanceof bn?n=r[0]:n=sO(e,mh(r),!1)}return n}function t7(n){let e=n.startState,t=e.facet(eO),s=n;for(let i=t.length-1;i>=0;i--){let r=t[i](n);r&&Object.keys(r).length&&(s=nO(s,b_(e,r,n.changes.newLength),!0))}return s==n?n:bn.create(e,n.changes,n.selection,s.effects,s.annotations,s.scrollIntoView)}const n7=[];function mh(n){return n==null?n7:Array.isArray(n)?n:[n]}var Qt=function(n){return n[n.Word=0]="Word",n[n.Space=1]="Space",n[n.Other=2]="Other",n}(Qt||(Qt={}));const s7=/[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/;let w_;try{w_=new RegExp("[\\p{Alphabetic}\\p{Number}_]","u")}catch{}function i7(n){if(w_)return w_.test(n);for(let e=0;e"€"&&(t.toUpperCase()!=t.toLowerCase()||s7.test(t)))return!0}return!1}function r7(n){return e=>{if(!/\S/.test(e))return Qt.Space;if(i7(e))return Qt.Word;for(let t=0;t-1)return Qt.Word;return Qt.Other}}class at{constructor(e,t,s,i,r,o){this.config=e,this.doc=t,this.selection=s,this.values=i,this.status=e.statusTemplate.slice(),this.computeSlot=r,o&&(o._state=this);for(let a=0;ai.set(c,l)),t=null),i.set(a.value.compartment,a.value.extension)):a.is(_t.reconfigure)?(t=null,s=a.value):a.is(_t.appendConfig)&&(t=null,s=mh(s).concat(a.value));let r;t?r=e.startState.values.slice():(t=ky.resolve(s,i,this),r=new at(t,this.doc,this.selection,t.dynamicSlots.map(()=>null),(l,c)=>c.reconfigure(l,this),null).values);let o=e.startState.facet(v_)?e.newSelection:e.newSelection.asSingle();new at(t,e.newDoc,o,r,(a,l)=>l.update(a,e),e)}replaceSelection(e){return typeof e=="string"&&(e=this.toText(e)),this.changeByRange(t=>({changes:{from:t.from,to:t.to,insert:e},range:ne.cursor(t.from+e.length)}))}changeByRange(e){let t=this.selection,s=e(t.ranges[0]),i=this.changes(s.changes),r=[s.range],o=mh(s.effects);for(let a=1;ao.spec.fromJSON(a,l)))}}return at.create({doc:e.doc,selection:ne.fromJSON(e.selection),extensions:t.extensions?i.concat([t.extensions]):i})}static create(e={}){let t=ky.resolve(e.extensions||[],new Map),s=e.doc instanceof lt?e.doc:lt.of((e.doc||"").split(t.staticFacet(at.lineSeparator)||f_)),i=e.selection?e.selection instanceof ne?e.selection:ne.single(e.selection.anchor,e.selection.head):ne.single(0);return KI(i,s.length),t.staticFacet(v_)||(i=i.asSingle()),new at(t,s,i,t.dynamicSlots.map(()=>null),(r,o)=>o.create(r),null)}get tabSize(){return this.facet(at.tabSize)}get lineBreak(){return this.facet(at.lineSeparator)||` +`}get readOnly(){return this.facet(tO)}phrase(e,...t){for(let s of this.facet(at.phrases))if(Object.prototype.hasOwnProperty.call(s,e)){e=s[e];break}return t.length&&(e=e.replace(/\$(\$|\d*)/g,(s,i)=>{if(i=="$")return"$";let r=+(i||1);return!r||r>t.length?s:t[r-1]})),e}languageDataAt(e,t,s=-1){let i=[];for(let r of this.facet(XI))for(let o of r(this,t,s))Object.prototype.hasOwnProperty.call(o,e)&&i.push(o[e]);return i}charCategorizer(e){let t=this.languageDataAt("wordChars",e);return r7(t.length?t[0]:"")}wordAt(e){let{text:t,from:s,length:i}=this.doc.lineAt(e),r=this.charCategorizer(e),o=e-s,a=e-s;for(;o>0;){let l=$n(t,o,!1);if(r(t.slice(l,o))!=Qt.Word)break;o=l}for(;an.length?n[0]:4});at.lineSeparator=YI;at.readOnly=tO;at.phrases=be.define({compare(n,e){let t=Object.keys(n),s=Object.keys(e);return t.length==s.length&&t.every(i=>n[i]==e[i])}});at.languageData=XI;at.changeFilter=JI;at.transactionFilter=QI;at.transactionExtender=eO;rm.reconfigure=_t.define();function Bu(n,e,t={}){let s={};for(let i of n)for(let r of Object.keys(i)){let o=i[r],a=s[r];if(a===void 0)s[r]=o;else if(!(a===o||o===void 0))if(Object.hasOwnProperty.call(t,r))s[r]=t[r](a,o);else throw new Error("Config merge conflict for field "+r)}for(let i in e)s[i]===void 0&&(s[i]=e[i]);return s}class vc{eq(e){return this==e}range(e,t=e){return __.create(e,t,this)}}vc.prototype.startSide=vc.prototype.endSide=0;vc.prototype.point=!1;vc.prototype.mapMode=ni.TrackDel;function Fx(n,e){return n==e||n.constructor==e.constructor&&n.eq(e)}let __=class iO{constructor(e,t,s){this.from=e,this.to=t,this.value=s}static create(e,t,s){return new iO(e,t,s)}};function S_(n,e){return n.from-e.from||n.value.startSide-e.value.startSide}class zx{constructor(e,t,s,i){this.from=e,this.to=t,this.value=s,this.maxPoint=i}get length(){return this.to[this.to.length-1]}findIndex(e,t,s,i=0){let r=s?this.to:this.from;for(let o=i,a=r.length;;){if(o==a)return o;let l=o+a>>1,c=r[l]-e||(s?this.value[l].endSide:this.value[l].startSide)-t;if(l==o)return c>=0?o:a;c>=0?a=l:o=l+1}}between(e,t,s,i){for(let r=this.findIndex(t,-1e9,!0),o=this.findIndex(s,1e9,!1,r);rp||d==p&&c.startSide>0&&c.endSide<=0)continue;(p-d||c.endSide-c.startSide)<0||(o<0&&(o=d),c.point&&(a=Math.max(a,p-d)),s.push(c),i.push(d-o),r.push(p-o))}return{mapped:s.length?new zx(i,r,s,a):null,pos:o}}}class rt{constructor(e,t,s,i){this.chunkPos=e,this.chunk=t,this.nextLayer=s,this.maxPoint=i}static create(e,t,s,i){return new rt(e,t,s,i)}get length(){let e=this.chunk.length-1;return e<0?0:Math.max(this.chunkEnd(e),this.nextLayer.length)}get size(){if(this.isEmpty)return 0;let e=this.nextLayer.size;for(let t of this.chunk)e+=t.value.length;return e}chunkEnd(e){return this.chunkPos[e]+this.chunk[e].length}update(e){let{add:t=[],sort:s=!1,filterFrom:i=0,filterTo:r=this.length}=e,o=e.filter;if(t.length==0&&!o)return this;if(s&&(t=t.slice().sort(S_)),this.isEmpty)return t.length?rt.of(t):this;let a=new rO(this,null,-1).goto(0),l=0,c=[],h=new df;for(;a.value||l=0){let u=t[l++];h.addInner(u.from,u.to,u.value)||c.push(u)}else a.rangeIndex==1&&a.chunkIndexthis.chunkEnd(a.chunkIndex)||ra.to||r=r&&e<=r+o.length&&o.between(r,e-r,t-r,s)===!1)return}this.nextLayer.between(e,t,s)}}iter(e=0){return ff.from([this]).goto(e)}get isEmpty(){return this.nextLayer==this}static iter(e,t=0){return ff.from(e).goto(t)}static compare(e,t,s,i,r=-1){let o=e.filter(u=>u.maxPoint>0||!u.isEmpty&&u.maxPoint>=r),a=t.filter(u=>u.maxPoint>0||!u.isEmpty&&u.maxPoint>=r),l=PE(o,a,s),c=new ld(o,l,r),h=new ld(a,l,r);s.iterGaps((u,d,p)=>RE(c,u,h,d,p,i)),s.empty&&s.length==0&&RE(c,0,h,0,0,i)}static eq(e,t,s=0,i){i==null&&(i=999999999);let r=e.filter(h=>!h.isEmpty&&t.indexOf(h)<0),o=t.filter(h=>!h.isEmpty&&e.indexOf(h)<0);if(r.length!=o.length)return!1;if(!r.length)return!0;let a=PE(r,o),l=new ld(r,a,0).goto(s),c=new ld(o,a,0).goto(s);for(;;){if(l.to!=c.to||!x_(l.active,c.active)||l.point&&(!c.point||!Fx(l.point,c.point)))return!1;if(l.to>i)return!0;l.next(),c.next()}}static spans(e,t,s,i,r=-1){let o=new ld(e,null,r).goto(t),a=t,l=o.openStart;for(;;){let c=Math.min(o.to,s);if(o.point){let h=o.activeForPoint(o.to),u=o.pointFroma&&(i.span(a,c,o.active,l),l=o.openEnd(c));if(o.to>s)return l+(o.point&&o.to>s?1:0);a=o.to,o.next()}}static of(e,t=!1){let s=new df;for(let i of e instanceof __?[e]:t?o7(e):e)s.add(i.from,i.to,i.value);return s.finish()}static join(e){if(!e.length)return rt.empty;let t=e[e.length-1];for(let s=e.length-2;s>=0;s--)for(let i=e[s];i!=rt.empty;i=i.nextLayer)t=new rt(i.chunkPos,i.chunk,t,Math.max(i.maxPoint,t.maxPoint));return t}}rt.empty=new rt([],[],null,-1);function o7(n){if(n.length>1)for(let e=n[0],t=1;t0)return n.slice().sort(S_);e=s}return n}rt.empty.nextLayer=rt.empty;class df{finishChunk(e){this.chunks.push(new zx(this.from,this.to,this.value,this.maxPoint)),this.chunkPos.push(this.chunkStart),this.chunkStart=-1,this.setMaxPoint=Math.max(this.setMaxPoint,this.maxPoint),this.maxPoint=-1,e&&(this.from=[],this.to=[],this.value=[])}constructor(){this.chunks=[],this.chunkPos=[],this.chunkStart=-1,this.last=null,this.lastFrom=-1e9,this.lastTo=-1e9,this.from=[],this.to=[],this.value=[],this.maxPoint=-1,this.setMaxPoint=-1,this.nextLayer=null}add(e,t,s){this.addInner(e,t,s)||(this.nextLayer||(this.nextLayer=new df)).add(e,t,s)}addInner(e,t,s){let i=e-this.lastTo||s.startSide-this.last.endSide;if(i<=0&&(e-this.lastFrom||s.startSide-this.last.startSide)<0)throw new Error("Ranges must be added sorted by `from` position and `startSide`");return i<0?!1:(this.from.length==250&&this.finishChunk(!0),this.chunkStart<0&&(this.chunkStart=e),this.from.push(e-this.chunkStart),this.to.push(t-this.chunkStart),this.last=s,this.lastFrom=e,this.lastTo=t,this.value.push(s),s.point&&(this.maxPoint=Math.max(this.maxPoint,t-e)),!0)}addChunk(e,t){if((e-this.lastTo||t.value[0].startSide-this.last.endSide)<0)return!1;this.from.length&&this.finishChunk(!0),this.setMaxPoint=Math.max(this.setMaxPoint,t.maxPoint),this.chunks.push(t),this.chunkPos.push(e);let s=t.value.length-1;return this.last=t.value[s],this.lastFrom=t.from[s]+e,this.lastTo=t.to[s]+e,!0}finish(){return this.finishInner(rt.empty)}finishInner(e){if(this.from.length&&this.finishChunk(!1),this.chunks.length==0)return e;let t=rt.create(this.chunkPos,this.chunks,this.nextLayer?this.nextLayer.finishInner(e):e,this.setMaxPoint);return this.from=null,t}}function PE(n,e,t){let s=new Map;for(let r of n)for(let o=0;o=this.minPoint)break}}setRangeIndex(e){if(e==this.layer.chunk[this.chunkIndex].value.length){if(this.chunkIndex++,this.skip)for(;this.chunkIndex=s&&i.push(new rO(o,t,s,r));return i.length==1?i[0]:new ff(i)}get startSide(){return this.value?this.value.startSide:0}goto(e,t=-1e9){for(let s of this.heap)s.goto(e,t);for(let s=this.heap.length>>1;s>=0;s--)Lv(this.heap,s);return this.next(),this}forward(e,t){for(let s of this.heap)s.forward(e,t);for(let s=this.heap.length>>1;s>=0;s--)Lv(this.heap,s);(this.to-e||this.value.endSide-t)<0&&this.next()}next(){if(this.heap.length==0)this.from=this.to=1e9,this.value=null,this.rank=-1;else{let e=this.heap[0];this.from=e.from,this.to=e.to,this.value=e.value,this.rank=e.rank,e.value&&e.next(),Lv(this.heap,0)}}}function Lv(n,e){for(let t=n[e];;){let s=(e<<1)+1;if(s>=n.length)break;let i=n[s];if(s+1=0&&(i=n[s+1],s++),t.compare(i)<0)break;n[s]=t,n[e]=i,e=s}}class ld{constructor(e,t,s){this.minPoint=s,this.active=[],this.activeTo=[],this.activeRank=[],this.minActive=-1,this.point=null,this.pointFrom=0,this.pointRank=0,this.to=-1e9,this.endSide=0,this.openStart=-1,this.cursor=ff.from(e,t,s)}goto(e,t=-1e9){return this.cursor.goto(e,t),this.active.length=this.activeTo.length=this.activeRank.length=0,this.minActive=-1,this.to=e,this.endSide=t,this.openStart=-1,this.next(),this}forward(e,t){for(;this.minActive>-1&&(this.activeTo[this.minActive]-e||this.active[this.minActive].endSide-t)<0;)this.removeActive(this.minActive);this.cursor.forward(e,t)}removeActive(e){Hm(this.active,e),Hm(this.activeTo,e),Hm(this.activeRank,e),this.minActive=ME(this.active,this.activeTo)}addActive(e){let t=0,{value:s,to:i,rank:r}=this.cursor;for(;t0;)t++;Bm(this.active,t,s),Bm(this.activeTo,t,i),Bm(this.activeRank,t,r),e&&Bm(e,t,this.cursor.from),this.minActive=ME(this.active,this.activeTo)}next(){let e=this.to,t=this.point;this.point=null;let s=this.openStart<0?[]:null;for(;;){let i=this.minActive;if(i>-1&&(this.activeTo[i]-this.cursor.from||this.active[i].endSide-this.cursor.startSide)<0){if(this.activeTo[i]>e){this.to=this.activeTo[i],this.endSide=this.active[i].endSide;break}this.removeActive(i),s&&Hm(s,i)}else if(this.cursor.value)if(this.cursor.from>e){this.to=this.cursor.from,this.endSide=this.cursor.startSide;break}else{let r=this.cursor.value;if(!r.point)this.addActive(s),this.cursor.next();else if(t&&this.cursor.to==this.to&&this.cursor.from=0&&s[i]=0&&!(this.activeRank[s]e||this.activeTo[s]==e&&this.active[s].endSide>=this.point.endSide)&&t.push(this.active[s]);return t.reverse()}openEnd(e){let t=0;for(let s=this.activeTo.length-1;s>=0&&this.activeTo[s]>e;s--)t++;return t}}function RE(n,e,t,s,i,r){n.goto(e),t.goto(s);let o=s+i,a=s,l=s-e,c=!!r.boundChange;for(let h=!1;;){let u=n.to+l-t.to,d=u||n.endSide-t.endSide,p=d<0?n.to+l:t.to,m=Math.min(p,o);if(n.point||t.point?(n.point&&t.point&&Fx(n.point,t.point)&&x_(n.activeForPoint(n.to),t.activeForPoint(t.to))||r.comparePoint(a,m,n.point,t.point),h=!1):(h&&r.boundChange(a),m>a&&!x_(n.active,t.active)&&r.compareRange(a,m,n.active,t.active),c&&mo)break;a=p,d<=0&&n.next(),d>=0&&t.next()}}function x_(n,e){if(n.length!=e.length)return!1;for(let t=0;t=e;s--)n[s+1]=n[s];n[e]=t}function ME(n,e){let t=-1,s=1e9;for(let i=0;i=e)return i;if(i==n.length)break;r+=n.charCodeAt(i)==9?t-r%t:1,i=$n(n,i)}return n.length}const A_="ͼ",IE=typeof Symbol>"u"?"__"+A_:Symbol.for(A_),k_=typeof Symbol>"u"?"__styleSet"+Math.floor(Math.random()*1e8):Symbol("styleSet"),OE=typeof globalThis<"u"?globalThis:typeof window<"u"?window:{};class Eu{constructor(e,t){this.rules=[];let{finish:s}=t||{};function i(o){return/^@/.test(o)?[o]:o.split(/,\s*/)}function r(o,a,l,c){let h=[],u=/^@(\w+)\b/.exec(o[0]),d=u&&u[1]=="keyframes";if(u&&a==null)return l.push(o[0]+";");for(let p in a){let m=a[p];if(/&/.test(p))r(p.split(/,\s*/).map(y=>o.map(v=>y.replace(/&/,v))).reduce((y,v)=>y.concat(v)),m,l);else if(m&&typeof m=="object"){if(!u)throw new RangeError("The value of a property ("+p+") should be a primitive value.");r(i(p),m,h,d)}else m!=null&&h.push(p.replace(/_.*/,"").replace(/[A-Z]/g,y=>"-"+y.toLowerCase())+": "+m+";")}(h.length||d)&&l.push((s&&!u&&!c?o.map(s):o).join(", ")+" {"+h.join(" ")+"}")}for(let o in e)r(i(o),e[o],this.rules)}getRules(){return this.rules.join(` +`)}static newName(){let e=OE[IE]||1;return OE[IE]=e+1,A_+e.toString(36)}static mount(e,t,s){let i=e[k_],r=s&&s.nonce;i?r&&i.setNonce(r):i=new l7(e,r),i.mount(Array.isArray(t)?t:[t],e)}}let NE=new Map;class l7{constructor(e,t){let s=e.ownerDocument||e,i=s.defaultView;if(!e.head&&e.adoptedStyleSheets&&i.CSSStyleSheet){let r=NE.get(s);if(r)return e[k_]=r;this.sheet=new i.CSSStyleSheet,NE.set(s,this)}else this.styleTag=s.createElement("style"),t&&this.styleTag.setAttribute("nonce",t);this.modules=[],e[k_]=this}mount(e,t){let s=this.sheet,i=0,r=0;for(let o=0;o-1&&(this.modules.splice(l,1),r--,l=-1),l==-1){if(this.modules.splice(r++,0,a),s)for(let c=0;c",191:"?",192:"~",219:"{",220:"|",221:"}",222:'"'},c7=typeof navigator<"u"&&/Mac/.test(navigator.platform),h7=typeof navigator<"u"&&/MSIE \d|Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent);for(var qn=0;qn<10;qn++)Ra[48+qn]=Ra[96+qn]=String(qn);for(var qn=1;qn<=24;qn++)Ra[qn+111]="F"+qn;for(var qn=65;qn<=90;qn++)Ra[qn]=String.fromCharCode(qn+32),pf[qn]=String.fromCharCode(qn);for(var Dv in Ra)pf.hasOwnProperty(Dv)||(pf[Dv]=Ra[Dv]);function u7(n){var e=c7&&n.metaKey&&n.shiftKey&&!n.ctrlKey&&!n.altKey||h7&&n.shiftKey&&n.key&&n.key.length==1||n.key=="Unidentified",t=!e&&n.key||(n.shiftKey?pf:Ra)[n.keyCode]||n.key||"Unidentified";return t=="Esc"&&(t="Escape"),t=="Del"&&(t="Delete"),t=="Left"&&(t="ArrowLeft"),t=="Up"&&(t="ArrowUp"),t=="Right"&&(t="ArrowRight"),t=="Down"&&(t="ArrowDown"),t}function Cn(){var n=arguments[0];typeof n=="string"&&(n=document.createElement(n));var e=1,t=arguments[1];if(t&&typeof t=="object"&&t.nodeType==null&&!Array.isArray(t)){for(var s in t)if(Object.prototype.hasOwnProperty.call(t,s)){var i=t[s];typeof i=="string"?n.setAttribute(s,i):i!=null&&(n[s]=i)}e++}for(;e2);var de={mac:jE||/Mac/.test(ys.platform),windows:/Win/.test(ys.platform),linux:/Linux|X11/.test(ys.platform),ie:G0,ie_version:aO?E_.documentMode||6:$_?+$_[1]:C_?+C_[1]:0,gecko:LE,gecko_version:LE?+(/Firefox\/(\d+)/.exec(ys.userAgent)||[0,0])[1]:0,chrome:!!jv,chrome_version:jv?+jv[1]:0,ios:jE,android:/Android\b/.test(ys.userAgent),webkit:DE,webkit_version:DE?+(/\bAppleWebKit\/(\d+)/.exec(ys.userAgent)||[0,0])[1]:0,safari:T_,safari_version:T_?+(/\bVersion\/(\d+(\.\d+)?)/.exec(ys.userAgent)||[0,0])[1]:0,tabSize:E_.documentElement.style.tabSize!=null?"tab-size":"-moz-tab-size"};function Hx(n,e){for(let t in n)t=="class"&&e.class?e.class+=" "+n.class:t=="style"&&e.style?e.style+=";"+n.style:e[t]=n[t];return e}const Cy=Object.create(null);function Bx(n,e,t){if(n==e)return!0;n||(n=Cy),e||(e=Cy);let s=Object.keys(n),i=Object.keys(e);if(s.length-0!=i.length-0)return!1;for(let r of s)if(r!=t&&(i.indexOf(r)==-1||n[r]!==e[r]))return!1;return!0}function d7(n,e){for(let t=n.attributes.length-1;t>=0;t--){let s=n.attributes[t].name;e[s]==null&&n.removeAttribute(s)}for(let t in e){let s=e[t];t=="style"?n.style.cssText=s:n.getAttribute(t)!=s&&n.setAttribute(t,s)}}function FE(n,e,t){let s=!1;if(e)for(let i in e)t&&i in t||(s=!0,i=="style"?n.style.cssText="":n.removeAttribute(i));if(t)for(let i in t)e&&e[i]==t[i]||(s=!0,i=="style"?n.style.cssText=t[i]:n.setAttribute(i,t[i]));return s}function f7(n){let e=Object.create(null);for(let t=0;t0?3e8:-4e8:t>0?1e8:-1e8,new bc(e,t,t,s,e.widget||null,!1)}static replace(e){let t=!!e.block,s,i;if(e.isBlockGap)s=-5e8,i=4e8;else{let{start:r,end:o}=lO(e,t);s=(r?t?-3e8:-1:5e8)-1,i=(o?t?2e8:1:-6e8)+1}return new bc(e,s,i,t,e.widget||null,!0)}static line(e){return new am(e)}static set(e,t=!1){return rt.of(e,t)}hasHeight(){return this.widget?this.widget.estimatedHeight>-1:!1}}Qe.none=rt.empty;class om extends Qe{constructor(e){let{start:t,end:s}=lO(e);super(t?-1:5e8,s?1:-6e8,null,e),this.tagName=e.tagName||"span",this.attrs=e.class&&e.attributes?Hx(e.attributes,{class:e.class}):e.class?{class:e.class}:e.attributes||Cy}eq(e){return this==e||e instanceof om&&this.tagName==e.tagName&&Bx(this.attrs,e.attrs)}range(e,t=e){if(e>=t)throw new RangeError("Mark decorations may not be empty");return super.range(e,t)}}om.prototype.point=!1;class am extends Qe{constructor(e){super(-2e8,-2e8,null,e)}eq(e){return e instanceof am&&this.spec.class==e.spec.class&&Bx(this.spec.attributes,e.spec.attributes)}range(e,t=e){if(t!=e)throw new RangeError("Line decoration ranges must be zero-length");return super.range(e,t)}}am.prototype.mapMode=ni.TrackBefore;am.prototype.point=!0;class bc extends Qe{constructor(e,t,s,i,r,o){super(t,s,r,e),this.block=i,this.isReplace=o,this.mapMode=i?t<=0?ni.TrackBefore:ni.TrackAfter:ni.TrackDel}get type(){return this.startSide!=this.endSide?Wn.WidgetRange:this.startSide<=0?Wn.WidgetBefore:Wn.WidgetAfter}get heightRelevant(){return this.block||!!this.widget&&(this.widget.estimatedHeight>=5||this.widget.lineBreaks>0)}eq(e){return e instanceof bc&&p7(this.widget,e.widget)&&this.block==e.block&&this.startSide==e.startSide&&this.endSide==e.endSide}range(e,t=e){if(this.isReplace&&(e>t||e==t&&this.startSide>0&&this.endSide<=0))throw new RangeError("Invalid range for replacement decoration");if(!this.isReplace&&t!=e)throw new RangeError("Widget decorations can only have zero-length ranges");return super.range(e,t)}}bc.prototype.point=!0;function lO(n,e=!1){let{inclusiveStart:t,inclusiveEnd:s}=n;return t==null&&(t=n.inclusive),s==null&&(s=n.inclusive),{start:t??e,end:s??e}}function p7(n,e){return n==e||!!(n&&e&&n.compare(e))}function gh(n,e,t,s=0){let i=t.length-1;i>=0&&t[i]+s>=n?t[i]=Math.max(t[i],e):t.push(n,e)}class mf extends vc{constructor(e,t,s){super(),this.tagName=e,this.attributes=t,this.rank=s}eq(e){return e==this||e instanceof mf&&this.tagName==e.tagName&&Bx(this.attributes,e.attributes)}static create(e){return new mf(e.tagName,e.attributes||Cy,e.rank==null?50:Math.max(0,Math.min(e.rank,100)))}static set(e,t=!1){return rt.of(e,t)}}mf.prototype.startSide=mf.prototype.endSide=-1;function gf(n){let e;return n.nodeType==11?e=n.getSelection?n:n.ownerDocument:e=n,e.getSelection()}function P_(n,e){return e?n==e||n.contains(e.nodeType!=1?e.parentNode:e):!1}function Jd(n,e){if(!e.anchorNode)return!1;try{return P_(n,e.anchorNode)}catch{return!1}}function Zg(n){return n.nodeType==3?yf(n,0,n.nodeValue.length).getClientRects():n.nodeType==1?n.getClientRects():[]}function Qd(n,e,t,s){return t?zE(n,e,t,s,-1)||zE(n,e,t,s,1):!1}function Ma(n){for(var e=0;;e++)if(n=n.previousSibling,!n)return e}function $y(n){return n.nodeType==1&&/^(DIV|P|LI|UL|OL|BLOCKQUOTE|DD|DT|H\d|SECTION|PRE)$/.test(n.nodeName)}function zE(n,e,t,s,i){for(;;){if(n==t&&e==s)return!0;if(e==(i<0?0:$o(n))){if(n.nodeName=="DIV")return!1;let r=n.parentNode;if(!r||r.nodeType!=1)return!1;e=Ma(n)+(i<0?0:1),n=r}else if(n.nodeType==1){if(n=n.childNodes[e+(i<0?-1:0)],n.nodeType==1&&n.contentEditable=="false")return!1;e=i<0?$o(n):0}else return!1}}function $o(n){return n.nodeType==3?n.nodeValue.length:n.childNodes.length}function Ty(n,e){let{left:t,right:s}=n;if(t==s)return n;let i=e?t:s;return{left:i,right:i,top:n.top,bottom:n.bottom}}function m7(n){let e=n.visualViewport;return e?{left:0,right:e.width,top:0,bottom:e.height}:{left:0,right:n.innerWidth,top:0,bottom:n.innerHeight}}function cO(n,e){let t=e.width/n.offsetWidth,s=e.height/n.offsetHeight;return(t>.995&&t<1.005||!isFinite(t)||Math.abs(e.width-n.offsetWidth)<1)&&(t=1),(s>.995&&s<1.005||!isFinite(s)||Math.abs(e.height-n.offsetHeight)<1)&&(s=1),{scaleX:t,scaleY:s}}function g7(n,e,t,s,i,r,o,a){let l=n.ownerDocument,c=l.defaultView||window;for(let h=n,u=!1;h&&!u;)if(h.nodeType==1){let d,p=h==l.body,m=1,y=1;if(p)d=m7(c);else{if(/^(fixed|sticky)$/.test(getComputedStyle(h).position)&&(u=!0),h.scrollHeight<=h.clientHeight&&h.scrollWidth<=h.clientWidth){h=h.assignedSlot||h.parentNode;continue}let b=h.getBoundingClientRect();({scaleX:m,scaleY:y}=cO(h,b)),d={left:b.left,right:b.left+h.clientWidth*m,top:b.top,bottom:b.top+h.clientHeight*y}}let v=0,g=0;if(i=="nearest")e.top0&&e.bottom>d.bottom+g&&(g=e.bottom-d.bottom+o)):e.bottom>d.bottom-o&&(g=e.bottom-d.bottom+o,t<0&&e.top-g0&&e.right>d.right+v&&(v=e.right-d.right+r)):e.right>d.right-r&&(v=e.right-d.right+r,t<0&&e.leftd.bottom||e.leftd.right)&&(e={left:Math.max(e.left,d.left),right:Math.min(e.right,d.right),top:Math.max(e.top,d.top),bottom:Math.min(e.bottom,d.bottom)}),h=h.assignedSlot||h.parentNode}else if(h.nodeType==11)h=h.host;else break}function hO(n,e=!0){let t=n.ownerDocument,s=null,i=null;for(let r=n.parentNode;r&&!(r==t.body||(!e||s)&&i);)if(r.nodeType==1)!i&&r.scrollHeight>r.clientHeight&&(i=r),e&&!s&&r.scrollWidth>r.clientWidth&&(s=r),r=r.assignedSlot||r.parentNode;else if(r.nodeType==11)r=r.host;else break;return{x:s,y:i}}class y7{constructor(){this.anchorNode=null,this.anchorOffset=0,this.focusNode=null,this.focusOffset=0}eq(e){return this.anchorNode==e.anchorNode&&this.anchorOffset==e.anchorOffset&&this.focusNode==e.focusNode&&this.focusOffset==e.focusOffset}setRange(e){let{anchorNode:t,focusNode:s}=e;this.set(t,Math.min(e.anchorOffset,t?$o(t):0),s,Math.min(e.focusOffset,s?$o(s):0))}set(e,t,s,i){this.anchorNode=e,this.anchorOffset=t,this.focusNode=s,this.focusOffset=i}}function uO(n){let e=[];for(let t=n;t;t=t.nodeType==11?t.host:t.parentNode)t.nodeType==1&&e.push({node:t,left:t.scrollLeft,top:t.scrollTop});return e}function dO(n,e=!0){for(let{node:t,left:s,top:i}of n)e&&t.scrollTop!=i&&(t.scrollTop=i),t.scrollLeft!=s&&(t.scrollLeft=s)}let Ja=null;de.safari&&de.safari_version>=26&&(Ja=!1);function fO(n){if(n.setActive)return n.setActive();if(Ja)return n.focus(Ja);let e=uO(n);n.focus(Ja==null?{get preventScroll(){return Ja={preventScroll:!0},!0}}:void 0),Ja||(Ja=!1,dO(e))}let HE;function yf(n,e,t=e){let s=HE||(HE=document.createRange());return s.setEnd(n,t),s.setStart(n,e),s}function yh(n,e,t,s){let i={key:e,code:e,keyCode:t,which:t,cancelable:!0};s&&({altKey:i.altKey,ctrlKey:i.ctrlKey,shiftKey:i.shiftKey,metaKey:i.metaKey}=s);let r=new KeyboardEvent("keydown",i);r.synthetic=!0,n.dispatchEvent(r);let o=new KeyboardEvent("keyup",i);return o.synthetic=!0,n.dispatchEvent(o),r.defaultPrevented||o.defaultPrevented}function v7(n){for(;n;){if(n&&(n.nodeType==9||n.nodeType==11&&n.host))return n;n=n.assignedSlot||n.parentNode}return null}function b7(n,e){let t=e.focusNode,s=e.focusOffset;if(!t||e.anchorNode!=t||e.anchorOffset!=s)return!1;for(s=Math.min(s,$o(t));;)if(s){if(t.nodeType!=1)return!1;let i=t.childNodes[s-1];i.contentEditable=="false"?s--:(t=i,s=$o(t))}else{if(t==n)return!0;s=Ma(t),t=t.parentNode}}function pO(n){return n instanceof Window?n.pageYOffset>Math.max(0,n.document.documentElement.scrollHeight-n.innerHeight-4):n.scrollTop>Math.max(1,n.scrollHeight-n.clientHeight-4)}function mO(n,e){for(let t=n,s=e;;){if(t.nodeType==3&&s>0)return{node:t,offset:s};if(t.nodeType==1&&s>0){if(t.contentEditable=="false")return null;t=t.childNodes[s-1],s=$o(t)}else if(t.parentNode&&!$y(t))s=Ma(t),t=t.parentNode;else return null}}function gO(n,e){for(let t=n,s=e;;){if(t.nodeType==3&&s=t){if(a.level==s)return o;(r<0||(i!=0?i<0?a.fromt:e[r].level>a.level))&&(r=o)}}if(r<0)throw new RangeError("Index out of range");return r}}function bO(n,e){if(n.length!=e.length)return!1;for(let t=0;t=0;y-=3)if(sr[y+1]==-p){let v=sr[y+2],g=v&2?i:v&4?v&1?r:i:0;g&&(wt[u]=wt[sr[y]]=g),a=y;break}}else{if(sr.length==189)break;sr[a++]=u,sr[a++]=d,sr[a++]=l}else if((m=wt[u])==2||m==1){let y=m==i;l=y?0:1;for(let v=a-3;v>=0;v-=3){let g=sr[v+2];if(g&2)break;if(y)sr[v+2]|=2;else{if(g&4)break;sr[v+2]|=4}}}}}function k7(n,e,t,s){for(let i=0,r=s;i<=t.length;i++){let o=i?t[i-1].to:n,a=il;)m==v&&(m=t[--y].from,v=y?t[y-1].to:n),wt[--m]=p;l=h}else r=c,l++}}}function M_(n,e,t,s,i,r,o){let a=s%2?2:1;if(s%2==i%2)for(let l=e,c=0;ll&&o.push(new Rr(l,y.from,p));let v=y.direction==wc!=!(p%2);I_(n,v?s+1:s,i,y.inner,y.from,y.to,o),l=y.to}m=y.to}else{if(m==t||(h?wt[m]!=a:wt[m]==a))break;m++}d?M_(n,l,m,s+1,i,d,o):le;){let h=!0,u=!1;if(!c||l>r[c-1].to){let y=wt[l-1];y!=a&&(h=!1,u=y==16)}let d=!h&&a==1?[]:null,p=h?s:s+1,m=l;e:for(;;)if(c&&m==r[c-1].to){if(u)break e;let y=r[--c];if(!h)for(let v=y.from,g=c;;){if(v==e)break e;if(g&&r[g-1].to==v)v=r[--g].from;else{if(wt[v-1]==a)break e;break}}if(d)d.push(y);else{y.towt.length;)wt[wt.length]=256;let s=[],i=e==wc?0:1;return I_(n,i,i,t,0,n.length,s),s}function wO(n){return[new Rr(0,n,0)]}let _O="";function C7(n,e,t,s,i){var r;let o=s.head-n.from,a=Rr.find(e,o,(r=s.bidiLevel)!==null&&r!==void 0?r:-1,s.assoc),l=e[a],c=l.side(i,t);if(o==c){let d=a+=i?1:-1;if(d<0||d>=e.length)return null;l=e[a=d],o=l.side(!i,t),c=l.side(i,t)}let h=$n(n.text,o,l.forward(i,t));(hl.to)&&(h=c),_O=n.text.slice(Math.min(o,h),Math.max(o,h));let u=a==(i?e.length-1:0)?null:e[a+(i?1:-1)];return u&&h==c&&u.level+(i?0:1)n.some(e=>e)}),TO=be.define({combine:n=>n.some(e=>e)}),PO=be.define();class vh{constructor(e,t,s,i,r,o=!1){this.range=e,this.y=t,this.x=s,this.yMargin=i,this.xMargin=r,this.isSnapshot=o}map(e){return e.empty?this:new vh(this.range.map(e),this.y,this.x,this.yMargin,this.xMargin,this.isSnapshot)}clip(e){return this.range.to<=e.doc.length?this:new vh(ne.cursor(e.doc.length),this.y,this.x,this.yMargin,this.xMargin,this.isSnapshot)}}const Um=_t.define({map:(n,e)=>n.map(e)}),RO=_t.define();function Mr(n,e,t){let s=n.facet(kO);s.length?s[0](e):window.onerror&&window.onerror(String(e),t,void 0,void 0,e)||(t?console.error(t+":",e):console.error(e))}const vo=be.define({combine:n=>n.length?n[0]:!0});let T7=0;const ih=be.define({combine(n){return n.filter((e,t)=>{for(let s=0;s{let l=[];return o&&l.push(Z0.of(c=>{let h=c.plugin(a);return h?o(h):Qe.none})),r&&l.push(r(a)),l})}static fromClass(e,t){return ii.define((s,i)=>new e(s,i),t)}}class Fv{constructor(e){this.spec=e,this.mustUpdate=null,this.value=null}get plugin(){return this.spec&&this.spec.plugin}update(e){if(this.value){if(this.mustUpdate){let t=this.mustUpdate;if(this.mustUpdate=null,this.value.update)try{this.value.update(t)}catch(s){if(Mr(t.state,s,"CodeMirror plugin crashed"),this.value.destroy)try{this.value.destroy()}catch{}this.deactivate()}}}else if(this.spec)try{this.value=this.spec.plugin.create(e,this.spec.arg)}catch(t){Mr(e.state,t,"CodeMirror plugin crashed"),this.deactivate()}return this}destroy(e){var t;if(!((t=this.value)===null||t===void 0)&&t.destroy)try{this.value.destroy()}catch(s){Mr(e.state,s,"CodeMirror plugin crashed")}}deactivate(){this.spec=this.value=null}}const MO=be.define(),Wx=be.define(),Z0=be.define(),IO=be.define(),Gx=be.define(),lm=be.define(),OO=be.define();function BE(n,e){let t=n.state.facet(OO);if(!t.length)return t;let s=t.map(r=>r instanceof Function?r(n):r),i=[];return rt.spans(s,e.from,e.to,{point(){},span(r,o,a,l){let c=r-e.from,h=o-e.from,u=i;for(let d=a.length-1;d>=0;d--,l--){let p=a[d].spec.bidiIsolate,m;if(p==null&&(p=$7(e.text,c,h)),l>0&&u.length&&(m=u[u.length-1]).to==c&&m.direction==p)m.to=h,u=m.inner;else{let y={from:c,to:h,direction:p,inner:[]};u.push(y),u=y.inner}}}}),i}const NO=be.define();function LO(n){let e=0,t=0,s=0,i=0;for(let r of n.state.facet(NO)){let o=r(n);o&&(o.left!=null&&(e=Math.max(e,o.left)),o.right!=null&&(t=Math.max(t,o.right)),o.top!=null&&(s=Math.max(s,o.top)),o.bottom!=null&&(i=Math.max(i,o.bottom)))}return{left:e,right:t,top:s,bottom:i}}const Id=be.define();class vi{constructor(e,t,s,i){this.fromA=e,this.toA=t,this.fromB=s,this.toB=i}join(e){return new vi(Math.min(this.fromA,e.fromA),Math.max(this.toA,e.toA),Math.min(this.fromB,e.fromB),Math.max(this.toB,e.toB))}addToSet(e){let t=e.length,s=this;for(;t>0;t--){let i=e[t-1];if(!(i.fromA>s.toA)){if(i.toAi.push(new vi(r,o,a,l))),this.changedRanges=i}static create(e,t,s){return new Py(e,t,s)}get viewportChanged(){return(this.flags&4)>0}get viewportMoved(){return(this.flags&8)>0}get heightChanged(){return(this.flags&2)>0}get geometryChanged(){return this.docChanged||(this.flags&18)>0}get focusChanged(){return(this.flags&1)>0}get docChanged(){return!this.changes.empty}get selectionSet(){return this.transactions.some(e=>e.selection)}get empty(){return this.flags==0&&this.transactions.length==0}}const P7=[];class Gt{constructor(e,t,s=0){this.dom=e,this.length=t,this.flags=s,this.parent=null,e.cmTile=this}get breakAfter(){return this.flags&1}get children(){return P7}isWidget(){return!1}get isHidden(){return!1}isComposite(){return!1}isLine(){return!1}isText(){return!1}isBlock(){return!1}get domAttrs(){return null}sync(e){if(this.flags|=2,this.flags&4){this.flags&=-5;let t=this.domAttrs;t&&d7(this.dom,t)}}toString(){return this.constructor.name+(this.children.length?`(${this.children})`:"")+(this.breakAfter?"#":"")}destroy(){this.parent=null}setDOM(e){this.dom=e,e.cmTile=this}get posAtStart(){return this.parent?this.parent.posBefore(this):0}get posAtEnd(){return this.posAtStart+this.length}posBefore(e,t=this.posAtStart){let s=t;for(let i of this.children){if(i==e)return s;s+=i.length+i.breakAfter}throw new RangeError("Invalid child in posBefore")}posAfter(e){return this.posBefore(e)+e.length}covers(e){return!0}coordsIn(e,t,s){return null}domPosFor(e,t){let s=Ma(this.dom),i=this.length?e>0:t>0;return new Zi(this.parent.dom,s+(i?1:0),e==0||e==this.length)}markDirty(e){this.flags&=-3,e&&(this.flags|=4),this.parent&&this.parent.flags&2&&this.parent.markDirty(!1)}get overrideDOMText(){return null}get root(){for(let e=this;e;e=e.parent)if(e instanceof Y0)return e;return null}static get(e){return e.cmTile}}class X0 extends Gt{constructor(e){super(e,0),this._children=[]}isComposite(){return!0}get children(){return this._children}get lastChild(){return this.children.length?this.children[this.children.length-1]:null}append(e){this.children.push(e),e.parent=this}sync(e){if(this.flags&2)return;super.sync(e);let t=this.dom,s=null,i,r=(e==null?void 0:e.node)==t?e:null,o=0;for(let a of this.children){if(a.sync(e),o+=a.length+a.breakAfter,i=s?s.nextSibling:t.firstChild,r&&i!=a.dom&&(r.written=!0),a.dom.parentNode==t)for(;i&&i!=a.dom;)i=UE(i);else t.insertBefore(a.dom,i);s=a.dom}for(i=s?s.nextSibling:t.firstChild,r&&i&&(r.written=!0);i;)i=UE(i);this.length=o}}function UE(n){let e=n.nextSibling;return n.parentNode.removeChild(n),e}class Y0 extends X0{constructor(e,t){super(t),this.view=e}owns(e){for(;e;e=e.parent)if(e==this)return!0;return!1}isBlock(){return!0}nearest(e){for(;;){if(!e)return null;let t=Gt.get(e);if(t&&this.owns(t))return t;e=e.parentNode}}blockTiles(e){for(let t=[],s=this,i=0,r=0;;)if(i==s.children.length){if(!t.length)return;s=s.parent,s.breakAfter&&r++,i=t.pop()}else{let o=s.children[i++];if(o instanceof ko)t.push(i),s=o,i=0;else{let a=r+o.length,l=e(o,r);if(l!==void 0)return l;r=a+o.breakAfter}}}resolveBlock(e,t){let s,i=-1,r,o=-1;if(this.blockTiles((a,l)=>{let c=l+a.length;if(e>=l&&e<=c){if(a.isWidget()&&t>=-1&&t<=1){if(a.flags&32)return!0;a.flags&16&&(s=void 0)}(le||e==l&&(t>1?a.length:a.covers(-1)))&&(!r||!a.isWidget()&&r.isWidget())&&(r=a,o=e-l)}}),!s&&!r)throw new Error("No tile at position "+e);return s&&t<0||!r?{tile:s,offset:i}:{tile:r,offset:o}}}class ko extends X0{constructor(e,t){super(e),this.wrapper=t}isBlock(){return!0}covers(e){return this.children.length?e<0?this.children[0].covers(-1):this.lastChild.covers(1):!1}get domAttrs(){return this.wrapper.attributes}static of(e,t){let s=new ko(t||document.createElement(e.tagName),e);return t||(s.flags|=4),s}}class Cu extends X0{constructor(e,t){super(e),this.attrs=t}isLine(){return!0}static start(e,t,s){let i=new Cu(t||document.createElement("div"),e);return(!t||!s)&&(i.flags|=4),i}get domAttrs(){return this.attrs}resolveInline(e,t,s){let i=null,r=-1,o=null,a=-1;function l(h,u){for(let d=0,p=0;d=u&&(m.isComposite()?l(m,u-p):(!o||o.isHidden&&(t>0&&!(o.flags&32)||s&&M7(o,m)))&&(y>u||m.flags&32&&t<=1)?(o=m,a=u-p):(p=-1)&&(i=m,r=u-p)),p=y}}l(this,e);let c=(t<0?i:o)||i||o;return c?{tile:c,offset:c==i?r:a}:null}coordsIn(e,t,s){let i=this.resolveInline(e,t,!0);return i?i.tile.coordsIn(Math.max(0,i.offset),t,s):R7(this)}domIn(e,t){let s=this.resolveInline(e,t);if(s){let{tile:i,offset:r}=s;if(this.dom.contains(i.dom))return i.isText()?new Zi(i.dom,Math.min(i.dom.nodeValue.length,r)):i.domPosFor(r,i.flags&16?1:i.flags&32?-1:t);let o=s.tile.parent,a=!1;for(let l of o.children){if(a)return new Zi(l.dom,0);l==s.tile&&(a=!0)}}return new Zi(this.dom,0)}}function R7(n){let e=n.dom.lastChild;if(!e)return n.dom.getBoundingClientRect();let t=Zg(e);return t[t.length-1]||null}function M7(n,e){let t=n.coordsIn(0,1),s=e.coordsIn(0,1);return t&&s&&s.topi&&(e=i);let r=e,o=e,a=0;e==0&&t<0||e==i&&t>=0?de.chrome||de.gecko||(e?(r--,a=1):o=0)?0:l.length-1];return de.safari&&!a&&c.width==0&&(c=Array.prototype.find.call(l,h=>h.width)||c),s==null?c:Ty(c,(a?a>0:t<0)==s)}static of(e,t){let s=new cl(t||document.createTextNode(e),e);return t||(s.flags|=2),s}}class _c extends Gt{constructor(e,t,s,i){super(e,t,i),this.widget=s}isWidget(){return!0}get isHidden(){return this.widget.isHidden}covers(e){return this.flags&48?!1:(this.flags&(e<0?64:128))>0}coordsIn(e,t){return this.coordsInWidget(e,t,!1)}coordsInWidget(e,t,s){let i=this.widget.coordsAt(this.dom,e,t);if(i)return i;if(s)return Ty(this.dom.getBoundingClientRect(),this.length?e==0:t<=0);{let r=this.dom.getClientRects(),o=null;if(!r.length)return null;let a=this.flags&16?!0:this.flags&32?!1:e>0;for(let l=a?r.length-1:0;o=r[l],!(e>0?l==0:l==r.length-1||o.top0==s)}}class I7{constructor(e){this.index=0,this.beforeBreak=!1,this.parents=[],this.tile=e}advance(e,t,s){let{tile:i,index:r,beforeBreak:o,parents:a}=this;for(;e||t>0;)if(i.isComposite())if(o){if(!e)break;s&&s.break(),e--,o=!1}else if(r==i.children.length){if(!e&&!a.length)break;s&&s.leave(i),o=!!i.breakAfter,{tile:i,index:r}=a.pop(),r++}else{let l=i.children[r],c=l.breakAfter;(t>0?l.length<=e:l.length=0;a--){let l=t.marks[a],c=i.lastChild;if(c instanceof Ds&&c.mark.eq(l.mark))c.dom!=l.dom&&c.setDOM(zv(l.dom)),i=c;else{if(this.cache.reused.get(l)){let u=Gt.get(l.dom);u&&u.setDOM(zv(l.dom))}let h=Ds.of(l.mark,l.dom);i.append(h),i=h}this.cache.reused.set(l,2)}let r=Gt.get(e.text);r&&this.cache.reused.set(r,2);let o=new cl(e.text,e.text.nodeValue);o.flags|=8,this.pos=e.range.toB,i.append(o)}addInlineWidget(e,t,s){let i=this.afterWidget&&e.flags&48&&(this.afterWidget.flags&48)==(e.flags&48);i||this.flushBuffer();let r=this.ensureMarks(t,s);!i&&!(e.flags&16)&&r.append(this.getBuffer(1)),r.append(e),this.pos+=e.length,this.afterWidget=e}addMark(e,t,s){this.flushBuffer(),this.ensureMarks(t,s).append(e),this.pos+=e.length,this.afterWidget=null}addBlockWidget(e){this.getBlockPos().append(e),this.pos+=e.length,this.lastBlock=e,this.endLine()}continueWidget(e){let t=this.afterWidget||this.lastBlock;t.length+=e,this.pos+=e}addLineStart(e,t){var s;e||(e=DO);let i=Cu.start(e,t||((s=this.cache.find(Cu))===null||s===void 0?void 0:s.dom),!!t);this.getBlockPos().append(this.lastBlock=this.curLine=i)}addLine(e){this.getBlockPos().append(e),this.pos+=e.length,this.lastBlock=e,this.endLine()}addBreak(){this.lastBlock.flags|=1,this.endLine(),this.pos++}addLineStartIfNotCovered(e){this.blockPosCovered()||this.addLineStart(e)}ensureLine(e){this.curLine||this.addLineStart(e)}ensureMarks(e,t){var s;let i=this.curLine;for(let r=e.length-1;r>=0;r--){let o=e[r],a;if(t>0&&(a=i.lastChild)&&a instanceof Ds&&a.mark.eq(o))i=a,t--;else{let l=Ds.of(o,(s=this.cache.find(Ds,c=>c.mark.eq(o)))===null||s===void 0?void 0:s.dom);i.append(l),i=l,t=0}}return i}endLine(){if(this.curLine){this.flushBuffer();let e=this.curLine.lastChild;(!e||!qE(this.curLine,!1)||e.dom.nodeName!="BR"&&e.isWidget()&&!(de.ios&&qE(this.curLine,!0)))&&this.curLine.append(this.cache.findWidget(Hv,0,32)||new _c(Hv.toDOM(),0,Hv,32)),this.curLine=this.afterWidget=null}}updateBlockWrappers(){this.wrapperPos>this.pos+1e4&&(this.blockWrappers.goto(this.pos),this.wrappers.length=0);for(let e=this.wrappers.length-1;e>=0;e--)this.wrappers[e].to=this.pos){let t=e.rank*102+e.value.rank,s=new O7(e.from,e.to,e.value,t),i=this.wrappers.length;for(;i>0&&(this.wrappers[i-1].rank-s.rank||this.wrappers[i-1].to-s.to)<0;)i--;this.wrappers.splice(i,0,s)}this.wrapperPos=this.pos}getBlockPos(){var e;this.updateBlockWrappers();let t=this.root;for(let s of this.wrappers){let i=t.lastChild;if(s.fromo.wrapper.eq(s.wrapper)))===null||e===void 0?void 0:e.dom);t.append(r),t=r}}return t}blockPosCovered(){let e=this.lastBlock;return e!=null&&!e.breakAfter&&(!e.isWidget()||(e.flags&160)>0)}getBuffer(e){let t=2|(e<0?16:32),s=this.cache.find(Ry,void 0,1);return s&&(s.flags=t),s||new Ry(t)}flushBuffer(){this.afterWidget&&!(this.afterWidget.flags&32)&&(this.afterWidget.parent.append(this.getBuffer(-1)),this.afterWidget=null)}}class L7{constructor(e){this.skipCount=0,this.text="",this.textOff=0,this.cursor=e.iter()}skip(e){this.textOff+e<=this.text.length?this.textOff+=e:(this.skipCount+=e-(this.text.length-this.textOff),this.text="",this.textOff=0)}next(e){if(this.textOff==this.text.length){let{value:i,lineBreak:r,done:o}=this.cursor.next(this.skipCount);if(this.skipCount=0,o)throw new Error("Ran out of text content when drawing inline views");this.text=i;let a=this.textOff=Math.min(e,i.length);return r?null:i.slice(0,a)}let t=Math.min(this.text.length,this.textOff+e),s=this.text.slice(this.textOff,t);return this.textOff=t,s}}const My=[_c,Cu,cl,Ds,Ry,ko,Y0];for(let n=0;n[]),this.index=My.map(()=>0),this.reused=new Map}add(e){let t=e.constructor.bucket,s=this.buckets[t];s.length<6?s.push(e):s[this.index[t]=(this.index[t]+1)%6]=e}find(e,t,s=2){let i=e.bucket,r=this.buckets[i],o=this.index[i];for(let a=0;a{if(this.cache.add(o),o.isComposite())return!1},enter:o=>this.cache.add(o),leave:()=>{},break:()=>{}}}run(e,t){let s=t&&this.getCompositionContext(t.text);for(let i=0,r=0,o=0;;){let a=oi){let c=l-i;this.preserve(c,!o,!a),i=l,r+=c}if(!a)break;t&&a.fromA<=t.range.fromA&&a.toA>=t.range.toA?(this.forward(a.fromA,t.range.fromA,t.range.fromA{if(o.isWidget())if(this.openWidget)this.builder.continueWidget(l-a);else{let c=l>0||a{o.isLine()?this.builder.addLineStart(o.attrs,this.cache.maybeReuse(o)):(this.cache.add(o),o instanceof Ds&&i.unshift(o.mark)),this.openWidget=!1},leave:o=>{o.isLine()?i.length&&(i.length=r=0):o instanceof Ds&&(i.shift(),r=Math.min(r,i.length))},break:()=>{this.builder.addBreak(),this.openWidget=!1}}),this.text.skip(e)}emit(e,t){let s=null,i=this.builder,r=-1,o=rt.spans(this.decorations,e,t,{point:(a,l,c,h,u,d)=>{if(c instanceof bc){if(this.disallowBlockEffectsFor[d]){if(c.block)throw new RangeError("Block decorations may not be specified via plugins");if(l>this.view.state.doc.lineAt(a).to)throw new RangeError("Decorations that replace line breaks may not be specified via plugins")}if(r=h.length,u>h.length)i.continueWidget(l-a);else{let p=c.widget||(c.block?$u.block:$u.inline),m=F7(c),y=this.cache.findWidget(p,l-a,m)||_c.of(p,this.view,l-a,m);c.block?(c.startSide>0&&i.addLineStartIfNotCovered(s),i.addBlockWidget(y)):(i.ensureLine(s),i.addInlineWidget(y,h,u))}s=null}else s=z7(s,c);l>a&&this.text.skip(l-a)},span:(a,l,c,h)=>{for(let u=a;u-1&&(this.openWidget=o>r),this.openWidget||i.addLineStartIfNotCovered(s),this.openMarks=o}forward(e,t,s=1){t-e<=10?this.old.advance(t-e,s,this.reuseWalker):(this.old.advance(5,-1,this.reuseWalker),this.old.advance(t-e-10,-1),this.old.advance(5,s,this.reuseWalker))}getCompositionContext(e){let t=[],s=null;for(let i=e.parentNode;;i=i.parentNode){let r=Gt.get(i);if(i==this.view.contentDOM)break;r instanceof Ds?t.push(r):r!=null&&r.isLine()?s=r:r instanceof ko||(i.nodeName=="DIV"&&!s&&i!=this.view.contentDOM?s=new Cu(i,DO):s||t.push(Ds.of(new om({tagName:i.nodeName.toLowerCase(),attributes:f7(i)}),i)))}return{line:s,marks:t}}}function qE(n,e){let t=s=>{for(let i of s.children)if((e?i.isText():i.length)||t(i))return!0;return!1};return t(n)}function F7(n){let e=n.isReplace?(n.startSide<0?64:0)|(n.endSide>0?128:0):n.startSide>0?32:16;return n.block&&(e|=256),e}const DO={class:"cm-line"};function z7(n,e){let t=e.spec.attributes,s=e.spec.class;return!t&&!s||(n||(n={class:"cm-line"}),t&&Hx(t,n),s&&(n.class+=" "+s)),n}function H7(n){let e=[];for(let t=n.parents.length;t>1;t--){let s=t==n.parents.length?n.tile:n.parents[t].tile;s instanceof Ds&&e.push(s.mark)}return e}function zv(n){let e=Gt.get(n);return e&&e.setDOM(n.cloneNode()),n}class $u extends K0{constructor(e){super(),this.tag=e}eq(e){return e.tag==this.tag}toDOM(){return document.createElement(this.tag)}updateDOM(e){return e.nodeName.toLowerCase()==this.tag}get isHidden(){return!0}}$u.inline=new $u("span");$u.block=new $u("div");const Hv=new class extends K0{toDOM(){return document.createElement("br")}get isHidden(){return!0}get editable(){return!0}};class VE{constructor(e){this.view=e,this.decorations=[],this.blockWrappers=[],this.dynamicDecorationMap=[!1],this.domChanged=null,this.hasComposition=null,this.editContextFormatting=Qe.none,this.lastCompositionAfterCursor=!1,this.minWidth=0,this.minWidthFrom=0,this.minWidthTo=0,this.impreciseAnchor=null,this.impreciseHead=null,this.forceSelection=!1,this.lastUpdate=Date.now(),this.updateDeco(),this.tile=new Y0(e,e.contentDOM),this.updateInner([new vi(0,0,0,e.state.doc.length)],null)}update(e){var t;let s=e.changedRanges;this.minWidth>0&&s.length&&(s.every(({fromA:h,toA:u})=>uthis.minWidthTo)?(this.minWidthFrom=e.changes.mapPos(this.minWidthFrom,1),this.minWidthTo=e.changes.mapPos(this.minWidthTo,1)):this.minWidth=this.minWidthFrom=this.minWidthTo=0),this.updateEditContextFormatting(e);let i=-1;this.view.inputState.composing>=0&&!this.view.observer.editContext&&(!((t=this.domChanged)===null||t===void 0)&&t.newSel?i=this.domChanged.newSel.head:!X7(e.changes,this.hasComposition)&&!e.selectionSet&&(i=e.state.selection.main.head));let r=i>-1?U7(this.view,e.changes,i):null;if(this.domChanged=null,this.hasComposition){let{from:h,to:u}=this.hasComposition;s=new vi(h,u,e.changes.mapPos(h,-1),e.changes.mapPos(u,1)).addToSet(s.slice())}this.hasComposition=r?{from:r.range.fromB,to:r.range.toB}:null,(de.ie||de.chrome)&&!r&&e&&e.state.doc.lines!=e.startState.doc.lines&&(this.forceSelection=!0);let o=this.decorations,a=this.blockWrappers;this.updateDeco();let l=W7(o,this.decorations,e.changes);l.length&&(s=vi.extendWithRanges(s,l));let c=K7(a,this.blockWrappers,e.changes);return c.length&&(s=vi.extendWithRanges(s,c)),r&&!s.some(h=>h.fromA<=r.range.fromA&&h.toA>=r.range.toA)&&(s=r.range.addToSet(s.slice())),this.tile.flags&2&&s.length==0?!1:(this.updateInner(s,r),e.transactions.length&&(this.lastUpdate=Date.now()),!0)}updateInner(e,t){this.view.viewState.mustMeasureContent=!0;let{observer:s}=this.view;s.ignore(()=>{if(t||e.length){let o=this.tile,a=new j7(this.view,o,this.blockWrappers,this.decorations,this.dynamicDecorationMap);t&&Gt.get(t.text)&&a.cache.reused.set(Gt.get(t.text),2),this.tile=a.run(e,t),N_(o,a.cache.reused)}this.tile.dom.style.height=this.view.viewState.contentHeight/this.view.scaleY+"px",this.tile.dom.style.flexBasis=this.minWidth?this.minWidth+"px":"";let r=de.chrome||de.ios?{node:s.selectionRange.focusNode,written:!1}:void 0;this.tile.sync(r),r&&(r.written||s.selectionRange.focusNode!=r.node||!this.tile.dom.contains(r.node))&&(this.forceSelection=!0),this.tile.dom.style.height=""});let i=[];if(this.view.viewport.from||this.view.viewport.to-1)&&Jd(s,this.view.observer.selectionRange)&&!(i&&s.contains(i));if(!(r||t||o))return;let a=this.forceSelection;this.forceSelection=!1;let l=this.view.state.selection.main,c,h;if(l.empty?h=c=this.inlineDOMNearPos(l.anchor,l.assoc||1):(h=this.inlineDOMNearPos(l.head,l.head==l.from?1:-1),c=this.inlineDOMNearPos(l.anchor,l.anchor==l.from?1:-1)),de.gecko&&l.empty&&!this.hasComposition&&B7(c)){let d=document.createTextNode("");this.view.observer.ignore(()=>c.node.insertBefore(d,c.node.childNodes[c.offset]||null)),c=h=new Zi(d,0),a=!0}let u=this.view.observer.selectionRange;(a||!u.focusNode||(!Qd(c.node,c.offset,u.anchorNode,u.anchorOffset)||!Qd(h.node,h.offset,u.focusNode,u.focusOffset))&&!this.suppressWidgetCursorChange(u,l))&&(this.view.observer.ignore(()=>{de.android&&de.chrome&&s.contains(u.focusNode)&&Z7(u.focusNode,s)&&(s.blur(),s.focus({preventScroll:!0}));let d=gf(this.view.root);if(d)if(l.empty){if(de.gecko){let p=q7(c.node,c.offset);if(p&&p!=3){let m=(p==1?mO:gO)(c.node,c.offset);m&&(c=new Zi(m.node,m.offset))}}d.collapse(c.node,c.offset),l.bidiLevel!=null&&d.caretBidiLevel!==void 0&&(d.caretBidiLevel=l.bidiLevel)}else if(d.extend){d.collapse(c.node,c.offset);try{d.extend(h.node,h.offset)}catch{}}else{let p=document.createRange();l.anchor>l.head&&([c,h]=[h,c]),p.setEnd(h.node,h.offset),p.setStart(c.node,c.offset),d.removeAllRanges(),d.addRange(p)}o&&this.view.root.activeElement==s&&(s.blur(),i&&i.focus())}),this.view.observer.setSelectionRange(c,h)),this.impreciseAnchor=c.precise?null:new Zi(u.anchorNode,u.anchorOffset),this.impreciseHead=h.precise?null:new Zi(u.focusNode,u.focusOffset)}suppressWidgetCursorChange(e,t){return this.hasComposition&&t.empty&&Qd(e.focusNode,e.focusOffset,e.anchorNode,e.anchorOffset)&&this.posFromDOM(e.focusNode,e.focusOffset)==t.head}enforceCursorAssoc(){if(this.hasComposition)return;let{view:e}=this,t=e.state.selection.main,s=gf(e.root),{anchorNode:i,anchorOffset:r}=e.observer.selectionRange;if(!s||!t.empty||!t.assoc||!s.modify)return;let o=this.lineAt(t.head,t.assoc);if(!o)return;let a=o.posAtStart;if(t.head==a||t.head==a+o.length)return;let l=this.coordsAt(t.head,-1),c=this.coordsAt(t.head,1);if(!l||!c||l.bottom>c.top)return;let h=this.domAtPos(t.head+t.assoc,t.assoc);s.collapse(h.node,h.offset),s.modify("move",t.assoc<0?"forward":"backward","lineboundary"),e.observer.readSelectionRange();let u=e.observer.selectionRange;e.docView.posFromDOM(u.anchorNode,u.anchorOffset)!=t.from&&s.collapse(i,r)}posFromDOM(e,t){let s=this.tile.nearest(e);if(!s)return this.tile.dom.compareDocumentPosition(e)&2?0:this.view.state.doc.length;let i=s.posAtStart;if(s.isComposite()){let r;if(e==s.dom)r=s.dom.childNodes[t];else{let o=$o(e)==0?0:t==0?-1:1;for(;;){let a=e.parentNode;if(a==s.dom)break;o==0&&a.firstChild!=a.lastChild&&(e==a.firstChild?o=-1:o=1),e=a}o<0?r=e:r=e.nextSibling}if(r==s.dom.firstChild)return i;for(;r&&!Gt.get(r);)r=r.nextSibling;if(!r)return i+s.length;for(let o=0,a=i;;o++){let l=s.children[o];if(l.dom==r)return a;a+=l.length+l.breakAfter}}else return s.isText()?e==s.dom?i+t:i+(t?s.length:0):i}domAtPos(e,t){let{tile:s,offset:i}=this.tile.resolveBlock(e,t);return s.isWidget()?s.domPosFor(i,t):s.domIn(i,t)}inlineDOMNearPos(e,t){let s,i=-1,r=!1,o,a=-1,l=!1;return this.tile.blockTiles((c,h)=>{if(c.isWidget()){if(c.flags&32&&h>=e)return!0;c.flags&16&&(r=!0)}else{let u=h+c.length;if(h<=e&&(s=c,i=e-h,r=u=e&&!o&&(o=c,a=e-h,l=h>e),h>e&&o)return!0}}),!s&&!o?this.domAtPos(e,t):(r&&o?s=null:l&&s&&(o=null),s&&t<0||!o?s.domIn(i,t):o.domIn(a,t))}coordsAt(e,t,s){let{tile:i,offset:r}=this.tile.resolveBlock(e,t);return i.isWidget()?i.widget instanceof Bv?null:i.coordsInWidget(r,t,!0):i.coordsIn(r,t,s)}lineAt(e,t){let{tile:s}=this.tile.resolveBlock(e,t);return s.isLine()?s:null}coordsForChar(e){let{tile:t,offset:s}=this.tile.resolveBlock(e,1);if(!t.isLine())return null;function i(r,o){if(r.isComposite())for(let a of r.children){if(a.length>=o){let l=i(a,o);if(l)return l}if(o-=a.length,o<0)break}else if(r.isText()&&oMath.max(this.view.scrollDOM.clientWidth,this.minWidth)+1,a=-1,l=this.view.textDirection==It.LTR,c=0,h=(u,d,p)=>{for(let m=0;mi);m++){let y=u.children[m],v=d+y.length,g=y.dom.getBoundingClientRect(),{height:b}=g;if(p&&!m&&(c+=g.top-p.top),y instanceof ko)v>s&&h(y,d,g);else if(d>=s&&(c>0&&t.push(-c),t.push(b+c),c=0,o)){let _=y.dom.lastChild,x=_?Zg(_):[];if(x.length){let A=x[x.length-1],C=l?A.right-g.left:g.right-A.left;C>a&&(a=C,this.minWidth=r,this.minWidthFrom=d,this.minWidthTo=v)}}p&&m==u.children.length-1&&(c+=p.bottom-g.bottom),d=v+y.breakAfter}};return h(this.tile,0,null),t}textDirectionAt(e){let{tile:t}=this.tile.resolveBlock(e,1);return getComputedStyle(t.dom).direction=="rtl"?It.RTL:It.LTR}measureTextSize(){let e=this.tile.blockTiles(o=>{if(o.isLine()&&o.children.length&&o.length<=20){let a=0,l;for(let c of o.children){if(!c.isText()||/[^ -~]/.test(c.text))return;let h=Zg(c.dom);if(h.length!=1)return;a+=h[0].width,l=h[0].height}if(a)return{lineHeight:o.dom.getBoundingClientRect().height,charWidth:a/o.length,textHeight:l}}});if(e)return e;let t=document.createElement("div"),s,i,r;return t.className="cm-line",t.style.width="99999px",t.style.position="absolute",t.textContent="abc def ghi jkl mno pqr stu",this.view.observer.ignore(()=>{this.tile.dom.appendChild(t);let o=Zg(t.firstChild)[0];s=t.getBoundingClientRect().height,i=o&&o.width?o.width/27:7,r=o&&o.height?o.height:s,t.remove()}),{lineHeight:s,charWidth:i,textHeight:r}}computeBlockGapDeco(){let e=[],t=this.view.viewState;for(let s=0,i=0;;i++){let r=i==t.viewports.length?null:t.viewports[i],o=r?r.from-1:this.view.state.doc.length;if(o>s){let a=(t.lineBlockAt(o).bottom-t.lineBlockAt(s).top)/this.view.scaleY;e.push(Qe.replace({widget:new Bv(a),block:!0,inclusive:!0,isBlockGap:!0}).range(s,o))}if(!r)break;s=r.to+1}return Qe.set(e)}updateDeco(){let e=1,t=this.view.state.facet(Z0).map(r=>(this.dynamicDecorationMap[e++]=typeof r=="function")?r(this.view):r),s=!1,i=this.view.state.facet(Gx).map((r,o)=>{let a=typeof r=="function";return a&&(s=!0),a?r(this.view):r});for(i.length&&(this.dynamicDecorationMap[e++]=s,t.push(rt.join(i))),this.decorations=[this.editContextFormatting,...t,this.computeBlockGapDeco(),this.view.viewState.lineGapDeco];etypeof r=="function"?r(this.view):r)}scrollIntoView(e){if(e.isSnapshot){let c=this.view.viewState.lineBlockAt(e.range.head);this.view.scrollDOM.scrollTop=c.top-e.yMargin,this.view.scrollDOM.scrollLeft=e.xMargin;return}for(let c of this.view.state.facet(PO))try{if(c(this.view,e.range,e))return!0}catch(h){Mr(this.view.state,h,"scroll handler")}let{range:t}=e,s=this.coordsAt(t.head,t.assoc||(t.head>t.anchor?-1:1)),i;if(!s)return;!t.empty&&(i=this.coordsAt(t.anchor,t.anchor>t.head?-1:1))&&(s={left:Math.min(s.left,i.left),top:Math.min(s.top,i.top),right:Math.max(s.right,i.right),bottom:Math.max(s.bottom,i.bottom)});let r=LO(this.view),o={left:s.left-r.left,top:s.top-r.top,right:s.right+r.right,bottom:s.bottom+r.bottom},{offsetWidth:a,offsetHeight:l}=this.view.scrollDOM;if(g7(this.view.scrollDOM,o,t.head1&&(s.top>window.visualViewport.offsetTop+window.visualViewport.height||s.bottoms.isWidget()||s.children.some(t);return t(this.tile.resolveBlock(e,1).tile)}destroy(){N_(this.tile)}}function N_(n,e){let t=e==null?void 0:e.get(n);if(t!=1){t==null&&n.destroy();for(let s of n.children)N_(s,e)}}function B7(n){return n.node.nodeType==1&&n.node.firstChild&&(n.offset==0||n.node.childNodes[n.offset-1].contentEditable=="false")&&(n.offset==n.node.childNodes.length||n.node.childNodes[n.offset].contentEditable=="false")}function jO(n,e){let t=n.observer.selectionRange;if(!t.focusNode)return null;let s=mO(t.focusNode,t.focusOffset),i=gO(t.focusNode,t.focusOffset),r=s||i;if(i&&s&&i.node!=s.node){let a=Gt.get(i.node);if(!a||a.isText()&&a.text!=i.node.nodeValue)r=i;else if(n.docView.lastCompositionAfterCursor){let l=Gt.get(s.node);!l||l.isText()&&l.text!=s.node.nodeValue||(r=i)}}if(n.docView.lastCompositionAfterCursor=r!=s,!r)return null;let o=e-r.offset;return{from:o,to:o+r.node.nodeValue.length,node:r.node}}function U7(n,e,t){let s=jO(n,t);if(!s)return null;let{node:i,from:r,to:o}=s,a=i.nodeValue;if(/[\n\r]/.test(a)||n.state.doc.sliceString(s.from,s.to)!=a)return null;let l=e.invertedDesc;return{range:new vi(l.mapPos(r),l.mapPos(o),r,o),text:i}}function q7(n,e){return n.nodeType!=1?0:(e&&n.childNodes[e-1].contentEditable=="false"?1:0)|(e{se.from&&(t=!0)}),t}class Bv extends K0{constructor(e){super(),this.height=e}toDOM(){let e=document.createElement("div");return e.className="cm-gap",this.updateDOM(e),e}eq(e){return e.height==this.height}updateDOM(e){return e.style.height=this.height+"px",!0}get editable(){return!0}get estimatedHeight(){return this.height}ignoreEvent(){return!1}}function Y7(n,e,t=1){let s=n.charCategorizer(e),i=n.doc.lineAt(e),r=e-i.from;if(i.length==0)return ne.cursor(e);r==0?t=1:r==i.length&&(t=-1);let o=r,a=r;t<0?o=$n(i.text,r,!1):a=$n(i.text,r);let l=s(i.text.slice(o,a));for(;o>0;){let c=$n(i.text,o,!1);if(s(i.text.slice(c,o))!=l)break;o=c}for(;an.defaultLineHeight*1.5){let a=n.viewState.heightOracle.textHeight,l=Math.floor((i-t.top-(n.defaultLineHeight-a)*.5)/a);r+=l*n.viewState.heightOracle.lineLength}let o=n.state.sliceDoc(t.from,t.to);return t.from+a7(o,r,n.state.tabSize)}function L_(n,e,t){let s=n.lineBlockAt(e);if(Array.isArray(s.type)){let i;for(let r of s.type){if(r.from>e)break;if(!(r.toe)return r;(!i||r.type==Wn.Text&&(i.type!=r.type||(t<0?r.frome)))&&(i=r)}}return i||s}return s}function Q7(n,e,t,s){let i=L_(n,e.head,e.assoc||-1),r=!s||i.type!=Wn.Text||!(n.lineWrapping||i.widgetLineBreaks)?null:n.coordsAtPos(e.assoc<0&&e.head>i.from?e.head-1:e.head);if(r){let o=n.dom.getBoundingClientRect(),a=n.textDirectionAt(i.from),l=n.posAtCoords({x:t==(a==It.LTR)?o.right-1:o.left+1,y:(r.top+r.bottom)/2});if(l!=null)return ne.cursor(l,t?-1:1)}return ne.cursor(t?i.to:i.from,t?-1:1)}function WE(n,e,t,s){let i=n.state.doc.lineAt(e.head),r=n.bidiSpans(i),o=n.textDirectionAt(i.from);for(let a=e,l=null;;){let c=C7(i,r,o,a,t),h=_O;if(!c){if(i.number==(t?n.state.doc.lines:1))return a;h=` +`,i=n.state.doc.line(i.number+(t?1:-1)),r=n.bidiSpans(i),c=n.visualLineSide(i,!t)}if(l){if(!l(h))return a}else{if(!s)return c;l=s(h)}a=c}}function eJ(n,e,t){let s=n.state.charCategorizer(e),i=s(t);return r=>{let o=s(r);return i==Qt.Space&&(i=o),i==o}}function tJ(n,e,t,s){let i=e.head,r=t?1:-1;if(i==(t?n.state.doc.length:0))return ne.cursor(i,e.assoc);let o=e.goalColumn,a,l=n.contentDOM.getBoundingClientRect(),c=n.coordsAtPos(i,e.assoc||((e.empty?t:e.head==e.from)?1:-1)),h=n.documentTop;if(c)o==null&&(o=c.left-l.left),a=r<0?c.top:c.bottom;else{let m=n.viewState.lineBlockAt(i);o==null&&(o=Math.min(l.right-l.left,n.defaultCharacterWidth*(i-m.from))),a=(r<0?m.top:m.bottom)+h}let u=l.left+o,d=n.viewState.heightOracle.textHeight>>1,p=s??d;for(let m=0;;m+=d){let y=a+(p+m)*r,v=D_(n,{x:u,y},!1,r);if(t?y>l.bottom:ya:b{if(e>r&&ei(n)),t.from,e.head>t.from?-1:1);return s==t.from?t:ne.cursor(s,sn.viewState.docHeight)return new $r(n.state.doc.length,-1);if(c=n.elementAtHeight(l),s==null)break;if(c.type==Wn.Text){if(s<0?c.ton.viewport.to)break;let d=n.docView.coordsAt(s<0?c.from:c.to,s>0?-1:1);if(d&&(s<0?d.top<=l+r:d.bottom>=l+r))break}let u=n.viewState.heightOracle.textHeight/2;l=s>0?c.bottom+u:c.top-u}if(n.viewport.from>=c.to||n.viewport.to<=c.from){if(t)return null;if(c.type==Wn.Text){let u=J7(n,i,c,o,a);return new $r(u,u==c.from?1:-1)}}if(c.type!=Wn.Text)return l<(c.top+c.bottom)/2?new $r(c.from,1):new $r(c.to,-1);let h=n.docView.lineAt(c.from,2);return(!h||h.length!=c.length)&&(h=n.docView.lineAt(c.from,-2)),new nJ(n,o,a,n.textDirectionAt(c.from)).scanTile(h,c.from)}class nJ{constructor(e,t,s,i){this.view=e,this.x=t,this.y=s,this.baseDir=i,this.line=null,this.spans=null}bidiSpansAt(e){return(!this.line||this.line.from>e||this.line.to1||s.length&&(s[0].level!=this.baseDir||s[0].to+i.from>1;t:if(o.has(y)){for(let b=1;b=r&&(_-=m),!o.has(_)){y=_;break t}}break e}o.add(y);let v=t(y),g=0;if(v)for(let b=0;b1))if(_.bottomthis.y)(!c||c.top>_.top)&&(c=_),g=-1;else{let x=_.left>this.x?this.x-_.left:_.right(m+m+y)/3)return this.y=l.bottom-1,this.scan(e,t,!0);if(c&&c.top<(m+y+y)/3)return this.y=c.top+1,this.scan(e,t,!0)}let p=(a?this.dirAt(e[h],1):this.baseDir)==It.LTR;return{i:h,after:this.x>(d.left+d.right)/2==p}}scanText(e,t){let s=[];for(let r=0;r{let o=s[r]-t,a=s[r+1]-t;return yf(e.dom,o,a).getClientRects()});return i.after?new $r(s[i.i+1],-1):new $r(s[i.i],1)}scanTile(e,t){if(!e.length)return new $r(t,1);if(e.children.length==1){let a=e.children[0];if(a.isText())return this.scanText(a,t);if(a.isComposite())return this.scanTile(a,t)}let s=[t];for(let a=0,l=t;a{let l=e.children[a];return l.flags&48?null:(l.dom.nodeType==1?l.dom:yf(l.dom,0,l.length)).getClientRects()}),r=e.children[i.i],o=s[i.i];return r.isText()?this.scanText(r,o):r.isComposite()?this.scanTile(r,o):i.after?new $r(s[i.i+1],-1):new $r(o,1)}}const Jc="￿";class sJ{constructor(e,t){this.points=e,this.view=t,this.text="",this.lineSeparator=t.state.facet(at.lineSeparator)}append(e){this.text+=e}lineBreak(){this.text+=Jc}readRange(e,t){if(!e)return this;let s=e.parentNode;for(let i=e;;){this.findPointBefore(s,i);let r=this.text.length;this.readNode(i);let o=Gt.get(i),a=i.nextSibling;if(a==t){o!=null&&o.breakAfter&&!a&&s!=this.view.contentDOM&&this.lineBreak();break}let l=Gt.get(a);(o&&l?o.breakAfter:(o?o.breakAfter:$y(i))||$y(a)&&(i.nodeName!="BR"||o!=null&&o.isWidget())&&this.text.length>r)&&!rJ(a,t)&&this.lineBreak(),i=a}return this.findPointBefore(s,t),this}readTextNode(e){let t=e.nodeValue;for(let s of this.points)s.node==e&&(s.pos=this.text.length+Math.min(s.offset,t.length));for(let s=0,i=this.lineSeparator?null:/\r\n?|\n/g;;){let r=-1,o=1,a;if(this.lineSeparator?(r=t.indexOf(this.lineSeparator,s),o=this.lineSeparator.length):(a=i.exec(t))&&(r=a.index,o=a[0].length),this.append(t.slice(s,r<0?t.length:r)),r<0)break;if(this.lineBreak(),o>1)for(let l of this.points)l.node==e&&l.pos>this.text.length&&(l.pos-=o-1);s=r+o}}readNode(e){let t=Gt.get(e),s=t&&t.overrideDOMText;if(s!=null){this.findPointInside(e,s.length);for(let i=s.iter();!i.next().done;)i.lineBreak?this.lineBreak():this.append(i.value)}else e.nodeType==3?this.readTextNode(e):e.nodeName=="BR"?e.nextSibling&&this.lineBreak():e.nodeType==1&&this.readRange(e.firstChild,null)}findPointBefore(e,t){for(let s of this.points)s.node==e&&e.childNodes[s.offset]==t&&(s.pos=this.text.length)}findPointInside(e,t){for(let s of this.points)(e.nodeType==3?s.node==e:e.contains(s.node))&&(s.pos=this.text.length+(iJ(e,s.node,s.offset)?t:0))}}function iJ(n,e,t){for(;;){if(!e||t<$o(e))return!1;if(e==n)return!0;t=Ma(e)+1,e=e.parentNode}}function rJ(n,e){let t;for(;!(n==e||!n);n=n.nextSibling){let s=Gt.get(n);if(!(s!=null&&s.isWidget()))return!1;s&&(t||(t=[])).push(s)}if(t)for(let s of t){let i=s.overrideDOMText;if(i!=null&&i.length)return!1}return!0}class GE{constructor(e,t){this.node=e,this.offset=t,this.pos=-1}}class oJ{constructor(e,t,s,i){this.typeOver=i,this.bounds=null,this.text="",this.domChanged=t>-1;let{impreciseHead:r,impreciseAnchor:o}=e.docView,a=e.state.selection;if(e.state.readOnly&&t>-1)this.newSel=null;else if(t>-1&&(this.bounds=zO(e.docView.tile,t,s,0))){let l=r||o?[]:lJ(e),c=new sJ(l,e);c.readRange(this.bounds.startDOM,this.bounds.endDOM),this.text=c.text,this.newSel=cJ(l,this.bounds.from)}else{let l=e.observer.selectionRange,c=r&&r.node==l.focusNode&&r.offset==l.focusOffset||!P_(e.contentDOM,l.focusNode)?a.main.head:e.docView.posFromDOM(l.focusNode,l.focusOffset),h=o&&o.node==l.anchorNode&&o.offset==l.anchorOffset||!P_(e.contentDOM,l.anchorNode)?a.main.anchor:e.docView.posFromDOM(l.anchorNode,l.anchorOffset),u=e.viewport;if((de.ios||de.chrome)&&c!=h&&Math.min(c,h)<=a.main.from&&Math.max(c,h)>=a.main.to&&(u.from>0||u.to-1&&a.ranges.length>1)this.newSel=a.replaceRange(ne.range(h,c));else if(e.lineWrapping&&h==c&&!(a.main.empty&&a.main.head==c)&&e.inputState.lastTouchTime>Date.now()-100){let d=e.coordsAtPos(c,-1),p=0;d&&(p=e.inputState.lastTouchY<=d.bottom?-1:1),this.newSel=ne.create([ne.cursor(c,p)])}else this.newSel=ne.single(h,c)}}}function zO(n,e,t,s){if(n.isComposite()){let i=-1,r=-1,o=-1,a=-1;for(let l=0,c=s,h=s;lt)return zO(u,e,t,c);if(d>=e&&i==-1&&(i=l,r=c),c>t&&u.dom.parentNode==n.dom){o=l,a=h;break}h=d,c=d+u.breakAfter}return{from:r,to:a<0?s+n.length:a,startDOM:(i?n.children[i-1].dom.nextSibling:null)||n.dom.firstChild,endDOM:o=0?n.children[o].dom:null}}else return n.isText()?{from:s,to:s+n.length,startDOM:n.dom,endDOM:n.dom.nextSibling}:null}function HO(n,e){let t,{newSel:s}=e,{state:i}=n,r=i.selection.main,o=n.inputState.lastKeyTime>Date.now()-100?n.inputState.lastKeyCode:-1;if(e.bounds){let{from:a,to:l}=e.bounds,c=r.from,h=null;(o===8||de.android&&e.text.length=a&&r.to<=l&&(e.typeOver||u!=e.text)&&u.slice(0,r.from-a)==e.text.slice(0,r.from-a)&&u.slice(r.to-a)==e.text.slice(d=e.text.length-(u.length-(r.to-a)))?t={from:r.from,to:r.to,insert:lt.of(e.text.slice(r.from-a,d).split(Jc))}:(p=BO(u,e.text,c-a,h))&&(de.chrome&&o==13&&p.toB==p.from+2&&e.text.slice(p.from,p.toB)==Jc+Jc&&p.toB--,t={from:a+p.from,to:a+p.toA,insert:lt.of(e.text.slice(p.from,p.toB).split(Jc))})}else s&&(!n.hasFocus&&i.facet(vo)||Iy(s,r))&&(s=null);if(!t&&!s)return!1;if((de.mac||de.android)&&t&&t.from==t.to&&t.from==r.head-1&&/^\. ?$/.test(t.insert.toString())&&n.contentDOM.getAttribute("autocorrect")=="off"?(s&&t.insert.length==2&&(s=ne.single(s.main.anchor-1,s.main.head-1)),t={from:t.from,to:t.to,insert:lt.of([t.insert.toString().replace("."," ")])}):i.doc.lineAt(r.from).toDate.now()-50?t={from:r.from,to:r.to,insert:i.toText(n.inputState.insertingText)}:de.chrome&&t&&t.from==t.to&&t.from==r.head&&t.insert.toString()==` + `&&n.lineWrapping&&(s&&(s=ne.single(s.main.anchor-1,s.main.head-1)),t={from:r.from,to:r.to,insert:lt.of([" "])}),t)return Kx(n,t,s,o);if(s&&!Iy(s,r)){let a=!1,l="select";return n.inputState.lastSelectionTime>Date.now()-50&&(n.inputState.lastSelectionOrigin=="select"&&(a=!0),l=n.inputState.lastSelectionOrigin,l=="select.pointer"&&(s=FO(i.facet(lm).map(c=>c(n)),s))),n.dispatch({selection:s,scrollIntoView:a,userEvent:l}),!0}else return!1}function Kx(n,e,t,s=-1){if(de.ios&&n.inputState.flushIOSKey(e))return!0;let i=n.state.selection.main;if(de.android&&(e.to==i.to&&(e.from==i.from||e.from==i.from-1&&n.state.sliceDoc(e.from,i.from)==" ")&&e.insert.length==1&&e.insert.lines==2&&yh(n.contentDOM,"Enter",13)||(e.from==i.from-1&&e.to==i.to&&e.insert.length==0||s==8&&e.insert.lengthi.head)&&yh(n.contentDOM,"Backspace",8)||e.from==i.from&&e.to==i.to+1&&e.insert.length==0&&yh(n.contentDOM,"Delete",46)))return!0;let r=e.insert.toString();n.inputState.composing>=0&&n.inputState.composing++;let o,a=()=>o||(o=aJ(n,e,t));return n.state.facet(EO).some(l=>l(n,e.from,e.to,r,a))||n.dispatch(a()),!0}function aJ(n,e,t){let s,i=n.state,r=i.selection.main,o=-1;if(e.from==e.to&&e.fromr.to){let l=e.fromu(n)),c,l);e.from==h&&(o=h)}if(o>-1)s={changes:e,selection:ne.cursor(e.from+e.insert.length,-1)};else if(e.from>=r.from&&e.to<=r.to&&e.to-e.from>=(r.to-r.from)/3&&(!t||t.main.empty&&t.main.from==e.from+e.insert.length)&&n.inputState.composing<0){let l=r.frome.to?i.sliceDoc(e.to,r.to):"";s=i.replaceSelection(n.state.toText(l+e.insert.sliceString(0,void 0,n.state.lineBreak)+c))}else{let l=i.changes(e),c=t&&t.main.to<=l.newLength?t.main:void 0;if(i.selection.ranges.length>1&&(n.inputState.composing>=0||n.inputState.compositionPendingChange)&&e.to<=r.to+10&&e.to>=r.to-10){let h=n.state.sliceDoc(e.from,e.to),u,d=t&&jO(n,t.main.head);if(d){let m=e.insert.length-(e.to-e.from);u={from:d.from,to:d.to-m}}else u=n.state.doc.lineAt(r.head);let p=r.to-e.to;s=i.changeByRange(m=>{if(m.from==r.from&&m.to==r.to)return{changes:l,range:c||m.map(l)};let y=m.to-p,v=y-h.length;if(n.state.sliceDoc(v,y)!=h||y>=u.from&&v<=u.to)return{range:m};let g=i.changes({from:v,to:y,insert:e.insert}),b=m.to-r.to;return{changes:g,range:c?ne.range(Math.max(0,c.anchor+b),Math.max(0,c.head+b)):m.map(g)}})}else s={changes:l,selection:c&&i.selection.replaceRange(c)}}let a="input.type";return(n.composing||n.inputState.compositionPendingChange&&n.inputState.compositionEndedAt>Date.now()-50)&&(n.inputState.compositionPendingChange=!1,a+=".compose",n.inputState.compositionFirstChange&&(a+=".start",n.inputState.compositionFirstChange=!1)),i.update(s,{userEvent:a,scrollIntoView:!0})}function BO(n,e,t,s){let i=Math.min(n.length,e.length),r=0;for(;r0&&a>0&&n.charCodeAt(o-1)==e.charCodeAt(a-1);)o--,a--;if(s=="end"){let l=Math.max(0,r-Math.min(o,a));t-=o+l-r}if(o=o?r-t:0;r-=l,a=r+(a-o),o=r}else if(a=a?r-t:0;r-=l,o=r+(o-a),a=r}return{from:r,toA:o,toB:a}}function lJ(n){let e=[];if(n.root.activeElement!=n.contentDOM)return e;let{anchorNode:t,anchorOffset:s,focusNode:i,focusOffset:r}=n.observer.selectionRange;return t&&(e.push(new GE(t,s)),(i!=t||r!=s)&&e.push(new GE(i,r))),e}function cJ(n,e){if(n.length==0)return null;let t=n[0].pos,s=n.length==2?n[1].pos:t;return t>-1&&s>-1?ne.single(t+e,s+e):null}function Iy(n,e){return e.head==n.main.head&&e.anchor==n.main.anchor}class hJ{setSelectionOrigin(e){this.lastSelectionOrigin=e,this.lastSelectionTime=Date.now()}constructor(e){this.view=e,this.lastKeyCode=0,this.lastKeyTime=0,this.touchActive=!1,this.lastTouchTime=0,this.lastTouchX=0,this.lastTouchY=0,this.lastFocusTime=0,this.lastScrollTop=0,this.lastScrollLeft=0,this.lastWheelEvent=0,this.pendingIOSKey=void 0,this.lastIOSMomentumScroll=0,this.tabFocusMode=-1,this.lastSelectionOrigin=null,this.lastSelectionTime=0,this.lastContextMenu=0,this.scrollHandlers=[],this.handlers=Object.create(null),this.composing=-1,this.compositionFirstChange=null,this.compositionEndedAt=0,this.compositionPendingKey=!1,this.compositionPendingChange=!1,this.insertingText="",this.insertingTextAt=0,this.mouseSelection=null,this.draggedContent=null,this.handleEvent=this.handleEvent.bind(this),this.notifiedFocused=e.hasFocus,de.safari&&e.contentDOM.addEventListener("input",()=>null),de.gecko&&EJ(e.contentDOM.ownerDocument)}handleEvent(e){!bJ(this.view,e)||this.ignoreDuringComposition(e)||e.type=="keydown"&&this.keydown(e)||(this.view.updateState!=0?Promise.resolve().then(()=>this.runHandlers(e.type,e)):this.runHandlers(e.type,e))}runHandlers(e,t){let s=this.handlers[e];if(s){for(let i of s.observers)i(this.view,t);for(let i of s.handlers){if(t.defaultPrevented)break;if(i(this.view,t)){t.preventDefault();break}}}}ensureHandlers(e){let t=dJ(e),s=this.handlers,i=this.view.contentDOM;for(let r in t)if(r!="scroll"){let o=!t[r].handlers.length,a=s[r];a&&o!=!a.handlers.length&&(i.removeEventListener(r,this.handleEvent),a=null),a||i.addEventListener(r,this.handleEvent,{passive:o})}for(let r in s)r!="scroll"&&!t[r]&&i.removeEventListener(r,this.handleEvent);this.handlers=t}keydown(e){if(this.lastKeyCode=e.keyCode,this.lastKeyTime=Date.now(),e.keyCode==9&&this.tabFocusMode>-1&&(!this.tabFocusMode||Date.now()<=this.tabFocusMode))return!0;if(this.tabFocusMode>0&&e.keyCode!=27&&qO.indexOf(e.keyCode)<0&&(this.tabFocusMode=-1),de.android&&de.chrome&&!e.synthetic&&(e.keyCode==13||e.keyCode==8))return this.view.observer.delayAndroidKey(e.key,e.keyCode),!0;if(de.ios&&!e.synthetic&&!e.altKey&&!e.metaKey&&(UO.some(t=>t.keyCode==e.keyCode)&&!e.ctrlKey||fJ.indexOf(e.key)>-1&&e.ctrlKey)){let t={ctrlKey:e.ctrlKey,altKey:e.altKey,metaKey:e.metaKey,shiftKey:e.shiftKey};return t.shiftKey&&de.ios&&!/^(off|none)$/.test(this.view.contentDOM.autocapitalize)&&uJ(this.view.win)&&(t.shiftKey=!1),this.pendingIOSKey={key:e.key,keyCode:e.keyCode,mods:t},setTimeout(()=>this.flushIOSKey(),250),!0}return e.keyCode!=229&&this.view.observer.forceFlush(),!1}flushIOSKey(e){let t=this.pendingIOSKey;return!t||t.key=="Enter"&&e&&e.from0?!0:de.safari&&!de.ios&&this.compositionPendingKey&&Date.now()-this.compositionEndedAt<100?(this.compositionPendingKey=!1,!0):!1}startMouseSelection(e){this.mouseSelection&&this.mouseSelection.destroy(),this.mouseSelection=e}update(e){this.view.observer.update(e),this.mouseSelection&&this.mouseSelection.update(e),this.draggedContent&&e.docChanged&&(this.draggedContent=this.draggedContent.map(e.changes)),e.transactions.length&&(this.lastKeyCode=this.lastSelectionTime=0)}destroy(){this.mouseSelection&&this.mouseSelection.destroy()}}function uJ(n){return n.visualViewport?n.visualViewport.height*n.visualViewport.scale/n.document.documentElement.clientHeight<.85:!1}function KE(n,e){return(t,s)=>{try{return e.call(n,s,t)}catch(i){Mr(t.state,i)}}}function dJ(n){let e=Object.create(null);function t(s){return e[s]||(e[s]={observers:[],handlers:[]})}for(let s of n){let i=s.spec,r=i&&i.plugin.domEventHandlers,o=i&&i.plugin.domEventObservers;if(r)for(let a in r){let l=r[a];l&&t(a).handlers.push(KE(s.value,l))}if(o)for(let a in o){let l=o[a];l&&t(a).observers.push(KE(s.value,l))}}for(let s in Qi)t(s).handlers.push(Qi[s]);for(let s in xs)t(s).observers.push(xs[s]);return e}const UO=[{key:"Backspace",keyCode:8,inputType:"deleteContentBackward"},{key:"Enter",keyCode:13,inputType:"insertParagraph"},{key:"Enter",keyCode:13,inputType:"insertLineBreak"},{key:"Delete",keyCode:46,inputType:"deleteContentForward"}],fJ="dthko",qO=[16,17,18,20,91,92,224,225],qm=6;function Vm(n){return Math.max(0,n)*.7+8}function pJ(n,e){return Math.max(Math.abs(n.clientX-e.clientX),Math.abs(n.clientY-e.clientY))}class mJ{constructor(e,t,s,i){this.view=e,this.startEvent=t,this.style=s,this.mustSelect=i,this.scrollSpeed={x:0,y:0},this.scrolling=-1,this.lastEvent=t,this.scrollParents=hO(e.contentDOM),this.atoms=e.state.facet(lm).map(o=>o(e));let r=e.contentDOM.ownerDocument;r.addEventListener("mousemove",this.move=this.move.bind(this)),r.addEventListener("mouseup",this.up=this.up.bind(this)),this.extend=t.shiftKey,this.multiple=e.state.facet(at.allowMultipleSelections)&&gJ(e,t),this.dragging=vJ(e,t)&&GO(t)==1?null:!1}start(e){this.dragging===!1&&this.select(e)}move(e){if(e.buttons==0)return this.destroy();if(this.dragging||this.dragging==null&&pJ(this.startEvent,e)<10)return;this.select(this.lastEvent=e);let t=0,s=0,i=0,r=0,o=this.view.win.innerWidth,a=this.view.win.innerHeight;this.scrollParents.x&&({left:i,right:o}=this.scrollParents.x.getBoundingClientRect()),this.scrollParents.y&&({top:r,bottom:a}=this.scrollParents.y.getBoundingClientRect());let l=LO(this.view);e.clientX-l.left<=i+qm?t=-Vm(i-e.clientX):e.clientX+l.right>=o-qm&&(t=Vm(e.clientX-o)),e.clientY-l.top<=r+qm?s=-Vm(r-e.clientY):e.clientY+l.bottom>=a-qm&&(s=Vm(e.clientY-a)),this.setScrollSpeed(t,s)}up(e){this.dragging==null&&this.select(this.lastEvent),this.dragging||e.preventDefault(),this.destroy()}destroy(){this.setScrollSpeed(0,0);let e=this.view.contentDOM.ownerDocument;e.removeEventListener("mousemove",this.move),e.removeEventListener("mouseup",this.up),this.view.inputState.mouseSelection=this.view.inputState.draggedContent=null}setScrollSpeed(e,t){this.scrollSpeed={x:e,y:t},e||t?this.scrolling<0&&(this.scrolling=setInterval(()=>this.scroll(),50)):this.scrolling>-1&&(clearInterval(this.scrolling),this.scrolling=-1)}scroll(){let{x:e,y:t}=this.scrollSpeed;e&&this.scrollParents.x&&(this.scrollParents.x.scrollLeft+=e,e=0),t&&this.scrollParents.y&&(this.scrollParents.y.scrollTop+=t,t=0),(e||t)&&this.view.win.scrollBy(e,t),this.dragging===!1&&this.select(this.lastEvent)}select(e){let{view:t}=this,s=FO(this.atoms,this.style.get(e,this.extend,this.multiple));(this.mustSelect||!s.eq(t.state.selection,this.dragging===!1))&&this.view.dispatch({selection:s,userEvent:"select.pointer"}),this.mustSelect=!1}update(e){e.transactions.some(t=>t.isUserEvent("input.type"))?this.destroy():this.style.update(e)&&setTimeout(()=>this.select(this.lastEvent),20)}}function gJ(n,e){let t=n.state.facet(SO);return t.length?t[0](e):de.mac?e.metaKey:e.ctrlKey}function yJ(n,e){let t=n.state.facet(xO);return t.length?t[0](e):de.mac?!e.altKey:!e.ctrlKey}function vJ(n,e){let{main:t}=n.state.selection;if(t.empty)return!1;let s=gf(n.root);if(!s||s.rangeCount==0)return!0;let i=s.getRangeAt(0).getClientRects();for(let r=0;r=e.clientX&&o.top<=e.clientY&&o.bottom>=e.clientY)return!0}return!1}function bJ(n,e){if(!e.bubbles)return!0;if(e.defaultPrevented)return!1;for(let t=e.target,s;t!=n.contentDOM;t=t.parentNode)if(!t||t.nodeType==11||(s=Gt.get(t))&&s.isWidget()&&!s.isHidden&&s.widget.ignoreEvent(e))return!1;return!0}const Qi=Object.create(null),xs=Object.create(null),VO=de.ie&&de.ie_version<15||de.ios&&de.webkit_version<604;function wJ(n){let e=n.dom.parentNode;if(!e)return;let t=e.appendChild(document.createElement("textarea"));t.style.cssText="position: fixed; left: -10000px; top: 10px",t.focus(),setTimeout(()=>{n.focus(),t.remove(),WO(n,t.value)},50)}function J0(n,e,t){for(let s of n.facet(e))t=s(t,n);return t}function WO(n,e){e=J0(n.state,qx,e);let{state:t}=n,s,i=1,r=t.toText(e),o=r.lines==t.selection.ranges.length;if(j_!=null&&t.selection.ranges.every(l=>l.empty)&&j_==r.toString()){let l=-1;s=t.changeByRange(c=>{let h=t.doc.lineAt(c.from);if(h.from==l)return{range:c};l=h.from;let u=t.toText((o?r.line(i++).text:e)+t.lineBreak);return{changes:{from:h.from,insert:u},range:ne.cursor(c.from+u.length)}})}else o?s=t.changeByRange(l=>{let c=r.line(i++);return{changes:{from:l.from,to:l.to,insert:c.text},range:ne.cursor(l.from+c.length)}}):s=t.replaceSelection(r);n.dispatch(s,{userEvent:"input.paste",scrollIntoView:!0})}xs.scroll=n=>{let e=n.inputState;e.lastScrollTop=n.scrollDOM.scrollTop,e.lastScrollLeft=n.scrollDOM.scrollLeft,de.ios&&!e.touchActive&&(e.lastIOSMomentumScroll=Date.now())};xs.wheel=xs.mousewheel=n=>{n.inputState.lastWheelEvent=Date.now()};Qi.keydown=(n,e)=>(n.inputState.setSelectionOrigin("select"),e.keyCode==27&&n.inputState.tabFocusMode!=0&&(n.inputState.tabFocusMode=Date.now()+2e3),!1);xs.touchstart=(n,e)=>{let t=n.inputState,s=e.targetTouches[0];t.touchActive=!0,t.lastTouchTime=Date.now(),s&&(t.lastTouchX=s.clientX,t.lastTouchY=s.clientY),t.setSelectionOrigin("select.pointer")};xs.touchmove=n=>{n.inputState.setSelectionOrigin("select.pointer")};xs.touchend=(n,e)=>{n.inputState.touchActive=!1};Qi.mousedown=(n,e)=>{if(n.observer.flush(),n.inputState.lastTouchTime>Date.now()-2e3)return!1;let t=null;for(let s of n.state.facet(AO))if(t=s(n,e),t)break;if(!t&&e.button==0&&(t=SJ(n,e)),t){let s=!n.hasFocus;n.inputState.startMouseSelection(new mJ(n,e,t,s)),s&&n.observer.ignore(()=>{fO(n.contentDOM);let r=n.root.activeElement;r&&!r.contains(n.contentDOM)&&r.blur()});let i=n.inputState.mouseSelection;if(i)return i.start(e),i.dragging===!1}else n.inputState.setSelectionOrigin("select.pointer");return!1};function ZE(n,e,t,s){if(s==1)return ne.cursor(e,t);if(s==2)return Y7(n.state,e,t);{let i=n.docView.lineAt(e,t),r=n.state.doc.lineAt(i?i.posAtEnd:e),o=i?i.posAtStart:r.from,a=i?i.posAtEnd:r.to;return aDate.now()-400&&Math.abs(e.clientX-n.clientX)<2&&Math.abs(e.clientY-n.clientY)<2?(YE+1)%3:1}function SJ(n,e){let t=n.posAndSideAtCoords({x:e.clientX,y:e.clientY},!1),s=GO(e),i=n.state.selection;return{update(r){r.docChanged&&(t.pos=r.changes.mapPos(t.pos),i=i.map(r.changes))},get(r,o,a){let l=n.posAndSideAtCoords({x:r.clientX,y:r.clientY},!1),c,h=ZE(n,l.pos,l.assoc,s);if(t.pos!=l.pos&&!o){let u=ZE(n,t.pos,t.assoc,s),d=Math.min(u.from,h.from),p=Math.max(u.to,h.to);h=d1&&(c=xJ(i,l.pos))?c:a?i.addRange(h):ne.create([h])}}}function xJ(n,e){for(let t=0;t=e)return ne.create(n.ranges.slice(0,t).concat(n.ranges.slice(t+1)),n.mainIndex==t?0:n.mainIndex-(n.mainIndex>t?1:0))}return null}Qi.dragstart=(n,e)=>{let{selection:{main:t}}=n.state;if(e.target.draggable){let i=n.docView.tile.nearest(e.target);if(i&&i.isWidget()){let r=i.posAtStart,o=r+i.length;(r>=t.to||o<=t.from)&&(t=ne.undirectionalRange(r,o))}}let{inputState:s}=n;return s.mouseSelection&&(s.mouseSelection.dragging=!0),s.draggedContent=t,e.dataTransfer&&(e.dataTransfer.setData("Text",J0(n.state,Vx,n.state.sliceDoc(t.from,t.to))),e.dataTransfer.effectAllowed="copyMove"),!1};Qi.dragend=n=>(n.inputState.draggedContent=null,!1);function QE(n,e,t,s){if(t=J0(n.state,qx,t),!t)return;let i=n.posAtCoords({x:e.clientX,y:e.clientY},!1),{draggedContent:r}=n.inputState,o=s&&r&&yJ(n,e)?{from:r.from,to:r.to}:null,a={from:i,insert:t},l=n.state.changes(o?[o,a]:a);n.focus(),n.dispatch({changes:l,selection:{anchor:l.mapPos(i,-1),head:l.mapPos(i,1)},userEvent:o?"move.drop":"input.drop"}),n.inputState.draggedContent=null}Qi.drop=(n,e)=>{if(!e.dataTransfer)return!1;if(n.state.readOnly)return!0;let t=e.dataTransfer.files;if(t&&t.length){let s=Array(t.length),i=0,r=()=>{++i==t.length&&QE(n,e,s.filter(o=>o!=null).join(n.state.lineBreak),!1)};for(let o=0;o{/[\x00-\x08\x0e-\x1f]{2}/.test(a.result)||(s[o]=a.result),r()},a.readAsText(t[o])}return!0}else{let s=e.dataTransfer.getData("Text");if(s)return QE(n,e,s,!0),!0}return!1};Qi.paste=(n,e)=>{if(n.state.readOnly)return!0;n.observer.flush();let t=VO?null:e.clipboardData;return t?(WO(n,t.getData("text/plain")||t.getData("text/uri-list")),!0):(wJ(n),!1)};function AJ(n,e){let t=n.dom.parentNode;if(!t)return;let s=t.appendChild(document.createElement("textarea"));s.style.cssText="position: fixed; left: -10000px; top: 10px",s.value=e,s.focus(),s.selectionEnd=e.length,s.selectionStart=0,setTimeout(()=>{s.remove(),n.focus()},50)}function kJ(n){let e=[],t=[],s=!1;for(let i of n.selection.ranges)i.empty||(e.push(n.sliceDoc(i.from,i.to)),t.push(i));if(!e.length){let i=-1;for(let{from:r}of n.selection.ranges){let o=n.doc.lineAt(r);o.number>i&&(e.push(o.text),t.push({from:o.from,to:Math.min(n.doc.length,o.to+1)})),i=o.number}s=!0}return{text:J0(n,Vx,e.join(n.lineBreak)),ranges:t,linewise:s}}let j_=null;Qi.copy=Qi.cut=(n,e)=>{if(!Jd(n.contentDOM,n.observer.selectionRange))return!1;let{text:t,ranges:s,linewise:i}=kJ(n.state);if(!t&&!i)return!1;j_=i?t:null,e.type=="cut"&&!n.state.readOnly&&n.dispatch({changes:s,scrollIntoView:!0,userEvent:"delete.cut"});let r=VO?null:e.clipboardData;return r?(r.clearData(),r.setData("text/plain",t),!0):(AJ(n,t),!1)};const KO=ja.define();function ZO(n,e){let t=[];for(let s of n.facet(CO)){let i=s(n,e);i&&t.push(i)}return t.length?n.update({effects:t,annotations:KO.of(!0)}):null}function XO(n){setTimeout(()=>{let e=n.hasFocus;if(e!=n.inputState.notifiedFocused){let t=ZO(n.state,e);t?n.dispatch(t):n.update([])}},10)}xs.focus=n=>{n.inputState.lastFocusTime=Date.now(),!n.scrollDOM.scrollTop&&(n.inputState.lastScrollTop||n.inputState.lastScrollLeft)&&(n.scrollDOM.scrollTop=n.inputState.lastScrollTop,n.scrollDOM.scrollLeft=n.inputState.lastScrollLeft),XO(n)};xs.blur=n=>{n.observer.clearSelectionRange(),XO(n)};xs.compositionstart=xs.compositionupdate=n=>{n.observer.editContext||(n.inputState.compositionFirstChange==null&&(n.inputState.compositionFirstChange=!0),n.inputState.composing<0&&(n.inputState.composing=0))};xs.compositionend=n=>{n.observer.editContext||(n.inputState.composing=-1,n.inputState.compositionEndedAt=Date.now(),n.inputState.compositionPendingKey=!0,n.inputState.compositionPendingChange=n.observer.pendingRecords().length>0,n.inputState.compositionFirstChange=null,de.chrome&&de.android?n.observer.flushSoon():n.inputState.compositionPendingChange?Promise.resolve().then(()=>n.observer.flush()):setTimeout(()=>{n.inputState.composing<0&&n.docView.hasComposition&&n.update([])},50))};xs.contextmenu=n=>{n.inputState.lastContextMenu=Date.now()};Qi.beforeinput=(n,e)=>{var t,s;if((e.inputType=="insertText"||e.inputType=="insertCompositionText")&&(n.inputState.insertingText=e.data,n.inputState.insertingTextAt=Date.now()),e.inputType=="insertReplacementText"&&n.observer.editContext){let r=(t=e.dataTransfer)===null||t===void 0?void 0:t.getData("text/plain"),o=e.getTargetRanges();if(r&&o.length){let a=o[0],l=n.posAtDOM(a.startContainer,a.startOffset),c=n.posAtDOM(a.endContainer,a.endOffset);return Kx(n,{from:l,to:c,insert:n.state.toText(r)},null),!0}}let i;if(de.chrome&&de.android&&(i=UO.find(r=>r.inputType==e.inputType))&&(n.observer.delayAndroidKey(i.key,i.keyCode),i.key=="Backspace"||i.key=="Delete")){let r=((s=window.visualViewport)===null||s===void 0?void 0:s.height)||0;setTimeout(()=>{var o;(((o=window.visualViewport)===null||o===void 0?void 0:o.height)||0)>r+10&&n.hasFocus&&(n.contentDOM.blur(),n.focus())},100)}return de.ios&&e.inputType=="deleteContentForward"&&n.observer.flushSoon(),de.safari&&e.inputType=="insertText"&&n.inputState.composing>=0&&setTimeout(()=>xs.compositionend(n,e),20),!1};const eC=new Set;function EJ(n){eC.has(n)||(eC.add(n),n.addEventListener("copy",()=>{}),n.addEventListener("cut",()=>{}))}const tC=["pre-wrap","normal","pre-line","break-spaces"];let Tu=!1;function nC(){Tu=!1}class CJ{constructor(e){this.lineWrapping=e,this.doc=lt.empty,this.heightSamples={},this.lineHeight=14,this.charWidth=7,this.textHeight=14,this.lineLength=30}heightForGap(e,t){let s=this.doc.lineAt(t).number-this.doc.lineAt(e).number+1;return this.lineWrapping&&(s+=Math.max(0,Math.ceil((t-e-s*this.lineLength*.5)/this.lineLength))),this.lineHeight*s}heightForLine(e){return this.lineWrapping?(1+Math.max(0,Math.ceil((e-this.lineLength)/Math.max(1,this.lineLength-5))))*this.lineHeight:this.lineHeight}setDoc(e){return this.doc=e,this}mustRefreshForWrapping(e){return tC.indexOf(e)>-1!=this.lineWrapping}mustRefreshForHeights(e){let t=!1;for(let s=0;s-1,l=Math.abs(t-this.lineHeight)>.3||this.lineWrapping!=a;if(this.lineWrapping=a,this.lineHeight=t,this.charWidth=s,this.textHeight=i,this.lineLength=r,l){this.heightSamples={};for(let c=0;c0}set outdated(e){this.flags=(e?2:0)|this.flags&-3}setHeight(e){this.height!=e&&(Math.abs(this.height-e)>Xg&&(Tu=!0),this.height=e)}replace(e,t,s){return ws.of(s)}decomposeLeft(e,t){t.push(this)}decomposeRight(e,t){t.push(this)}applyChanges(e,t,s,i){let r=this,o=s.doc;for(let a=i.length-1;a>=0;a--){let{fromA:l,toA:c,fromB:h,toB:u}=i[a],d=r.lineAt(l,kt.ByPosNoHeight,s.setDoc(t),0,0),p=d.to>=c?d:r.lineAt(c,kt.ByPosNoHeight,s,0,0);for(u+=p.to-c,c=p.to;a>0&&d.from<=i[a-1].toA;)l=i[a-1].fromA,h=i[a-1].fromB,a--,lr*2){let a=e[t-1];a.break?e.splice(--t,1,a.left,null,a.right):e.splice(--t,1,a.left,a.right),s+=1+a.break,i-=a.size}else if(r>i*2){let a=e[s];a.break?e.splice(s,1,a.left,null,a.right):e.splice(s,1,a.left,a.right),s+=2+a.break,r-=a.size}else break;else if(i=r&&o(this.lineAt(0,kt.ByPos,s,i,r))}setMeasuredHeight(e){let t=e.heights[e.index++];t<0?(this.spaceAbove=-t,t=e.heights[e.index++]):this.spaceAbove=0,this.setHeight(t)}updateHeight(e,t=0,s=!1,i){return i&&i.from<=t&&i.more&&this.setMeasuredHeight(i),this.outdated=!1,this}toString(){return`block(${this.length})`}}class ei extends YO{constructor(e,t,s){super(e,t,null),this.collapsed=0,this.widgetHeight=0,this.breaks=0,this.spaceAbove=s}mainBlock(e,t){return new Ki(t,this.length,e+this.spaceAbove,this.height-this.spaceAbove,this.breaks)}replace(e,t,s){let i=s[0];return s.length==1&&(i instanceof ei||i instanceof zn&&i.flags&4)&&Math.abs(this.length-i.length)<10?(i instanceof zn?i=new ei(i.length,this.height,this.spaceAbove):i.height=this.height,this.outdated||(i.outdated=!1),i):ws.of(s)}updateHeight(e,t=0,s=!1,i){return i&&i.from<=t&&i.more?this.setMeasuredHeight(i):(s||this.outdated)&&(this.spaceAbove=0,this.setHeight(Math.max(this.widgetHeight,e.heightForLine(this.length-this.collapsed))+this.breaks*e.lineHeight)),this.outdated=!1,this}toString(){return`line(${this.length}${this.collapsed?-this.collapsed:""}${this.widgetHeight?":"+this.widgetHeight:""})`}}class zn extends ws{constructor(e){super(e,0)}heightMetrics(e,t){let s=e.doc.lineAt(t).number,i=e.doc.lineAt(t+this.length).number,r=i-s+1,o,a=0;if(e.lineWrapping){let l=Math.min(this.height,e.lineHeight*r);o=l/r,this.length>r+1&&(a=(this.height-l)/(this.length-r-1))}else o=this.height/r;return{firstLine:s,lastLine:i,perLine:o,perChar:a}}blockAt(e,t,s,i){let{firstLine:r,lastLine:o,perLine:a,perChar:l}=this.heightMetrics(t,i);if(t.lineWrapping){let c=i+(e0){let r=s[s.length-1];r instanceof zn?s[s.length-1]=new zn(r.length+i):s.push(null,new zn(i-1))}if(e>0){let r=s[0];r instanceof zn?s[0]=new zn(e+r.length):s.unshift(new zn(e-1),null)}return ws.of(s)}decomposeLeft(e,t){t.push(new zn(e-1),null)}decomposeRight(e,t){t.push(null,new zn(this.length-e-1))}updateHeight(e,t=0,s=!1,i){let r=t+this.length;if(i&&i.from<=t+this.length&&i.more){let o=[],a=Math.max(t,i.from),l=-1;for(i.from>t&&o.push(new zn(i.from-t-1).updateHeight(e,t));a<=r&&i.more;){let h=e.doc.lineAt(a).length;o.length&&o.push(null);let u=i.heights[i.index++],d=0;u<0&&(d=-u,u=i.heights[i.index++]),l==-1?l=u:Math.abs(u-l)>=Xg&&(l=-2);let p=new ei(h,u,d);p.outdated=!1,o.push(p),a+=h+1}a<=r&&o.push(null,new zn(r-a).updateHeight(e,a));let c=ws.of(o);return(l<0||Math.abs(c.height-this.height)>=Xg||Math.abs(l-this.heightMetrics(e,t).perLine)>=Xg)&&(Tu=!0),Oy(this,c)}else(s||this.outdated)&&(this.setHeight(e.heightForGap(t,t+this.length)),this.outdated=!1);return this}toString(){return`gap(${this.length})`}}class PJ extends ws{constructor(e,t,s){super(e.length+t+s.length,e.height+s.height,t|(e.outdated||s.outdated?2:0)),this.left=e,this.right=s,this.size=e.size+s.size}get break(){return this.flags&1}blockAt(e,t,s,i){let r=s+this.left.height;return ea))return c;let h=t==kt.ByPosNoHeight?kt.ByPosNoHeight:kt.ByPos;return l?c.join(this.right.lineAt(a,h,s,o,a)):this.left.lineAt(a,h,s,i,r).join(c)}forEachLine(e,t,s,i,r,o){let a=i+this.left.height,l=r+this.left.length+this.break;if(this.break)e=l&&this.right.forEachLine(e,t,s,a,l,o);else{let c=this.lineAt(l,kt.ByPos,s,i,r);e=e&&c.from<=t&&o(c),t>c.to&&this.right.forEachLine(c.to+1,t,s,a,l,o)}}replace(e,t,s){let i=this.left.length+this.break;if(tthis.left.length)return this.balanced(this.left,this.right.replace(e-i,t-i,s));let r=[];e>0&&this.decomposeLeft(e,r);let o=r.length;for(let a of s)r.push(a);if(e>0&&sC(r,o-1),t=s&&t.push(null)),e>s&&this.right.decomposeLeft(e-s,t)}decomposeRight(e,t){let s=this.left.length,i=s+this.break;if(e>=i)return this.right.decomposeRight(e-i,t);e2*t.size||t.size>2*e.size?ws.of(this.break?[e,null,t]:[e,t]):(this.left=Oy(this.left,e),this.right=Oy(this.right,t),this.setHeight(e.height+t.height),this.outdated=e.outdated||t.outdated,this.size=e.size+t.size,this.length=e.length+this.break+t.length,this)}updateHeight(e,t=0,s=!1,i){let{left:r,right:o}=this,a=t+r.length+this.break,l=null;return i&&i.from<=t+r.length&&i.more?l=r=r.updateHeight(e,t,s,i):r.updateHeight(e,t,s),i&&i.from<=a+o.length&&i.more?l=o=o.updateHeight(e,a,s,i):o.updateHeight(e,a,s),l?this.balanced(r,o):(this.height=this.left.height+this.right.height,this.outdated=!1,this)}toString(){return this.left+(this.break?" ":"-")+this.right}}function sC(n,e){let t,s;n[e]==null&&(t=n[e-1])instanceof zn&&(s=n[e+1])instanceof zn&&n.splice(e-1,3,new zn(t.length+1+s.length))}const RJ=5;class Zx{constructor(e,t){this.pos=e,this.oracle=t,this.nodes=[],this.lineStart=-1,this.lineEnd=-1,this.covering=null,this.writtenTo=e}get isCovered(){return this.covering&&this.nodes[this.nodes.length-1]==this.covering}span(e,t){if(this.lineStart>-1){let s=Math.min(t,this.lineEnd),i=this.nodes[this.nodes.length-1];i instanceof ei?i.length+=s-this.pos:(s>this.pos||!this.isCovered)&&this.nodes.push(new ei(s-this.pos,-1,0)),this.writtenTo=s,t>s&&(this.nodes.push(null),this.writtenTo++,this.lineStart=-1)}this.pos=t}point(e,t,s){if(e=RJ)&&this.addLineDeco(i,r,o)}else t>e&&this.span(e,t);this.lineEnd>-1&&this.lineEnd-1)return;let{from:e,to:t}=this.oracle.doc.lineAt(this.pos);this.lineStart=e,this.lineEnd=t,this.writtenToe&&this.nodes.push(new ei(this.pos-e,-1,0)),this.writtenTo=this.pos}blankContent(e,t){let s=new zn(t-e);return this.oracle.doc.lineAt(e).to==t&&(s.flags|=4),s}ensureLine(){this.enterLine();let e=this.nodes.length?this.nodes[this.nodes.length-1]:null;if(e instanceof ei)return e;let t=new ei(0,-1,0);return this.nodes.push(t),t}addBlock(e){this.enterLine();let t=e.deco;t&&t.startSide>0&&!this.isCovered&&this.ensureLine(),this.nodes.push(e),this.writtenTo=this.pos=this.pos+e.length,t&&t.endSide>0&&(this.covering=e)}addLineDeco(e,t,s){let i=this.ensureLine();i.length+=s,i.collapsed+=s,i.widgetHeight=Math.max(i.widgetHeight,e),i.breaks+=t,this.writtenTo=this.pos=this.pos+s}finish(e){let t=this.nodes.length==0?null:this.nodes[this.nodes.length-1];this.lineStart>-1&&!(t instanceof ei)&&!this.isCovered?this.nodes.push(new ei(0,-1,0)):(this.writtenToh.clientHeight||h.scrollWidth>h.clientWidth)&&u.overflow!="visible"){let d=h.getBoundingClientRect();r=Math.max(r,d.left),o=Math.min(o,d.right),a=Math.max(a,d.top),l=Math.min(c==n.parentNode?i.innerHeight:l,d.bottom)}c=u.position=="absolute"||u.position=="fixed"?h.offsetParent:h.parentNode}else if(c.nodeType==11)c=c.host;else break;return{left:r-t.left,right:Math.max(r,o)-t.left,top:a-(t.top+e),bottom:Math.max(a,l)-(t.top+e)}}function NJ(n){let e=n.getBoundingClientRect(),t=n.ownerDocument.defaultView||window;return e.left0&&e.top0}function LJ(n,e){let t=n.getBoundingClientRect();return{left:0,right:t.right-t.left,top:e,bottom:t.bottom-(t.top+e)}}class qv{constructor(e,t,s,i){this.from=e,this.to=t,this.size=s,this.displaySize=i}static same(e,t){if(e.length!=t.length)return!1;for(let s=0;stypeof i!="function"&&i.class=="cm-lineWrapping");this.heightOracle=new CJ(s),this.stateDeco=oC(t),this.heightMap=ws.empty().applyChanges(this.stateDeco,lt.empty,this.heightOracle.setDoc(t.doc),[new vi(0,0,0,t.doc.length)]);for(let i=0;i<2&&(this.viewport=this.getViewport(0,null),!!this.updateForViewport());i++);this.updateViewportLines(),this.lineGaps=this.ensureLineGaps([]),this.lineGapDeco=Qe.set(this.lineGaps.map(i=>i.draw(this,!1))),this.scrollParent=e.scrollDOM,this.computeVisibleRanges()}updateForViewport(){let e=[this.viewport],{main:t}=this.state.selection;for(let s=0;s<=1;s++){let i=s?t.head:t.anchor;if(!e.some(({from:r,to:o})=>i>=r&&i<=o)){let{from:r,to:o}=this.lineBlockAt(i);e.push(new Wm(r,o))}}return this.viewports=e.sort((s,i)=>s.from-i.from),this.updateScaler()}updateScaler(){let e=this.scaler;return this.scaler=this.heightMap.height<=7e6?rC:new Xx(this.heightOracle,this.heightMap,this.viewports),e.eq(this.scaler)?0:2}updateViewportLines(){this.viewportLines=[],this.heightMap.forEachLine(this.viewport.from,this.viewport.to,this.heightOracle.setDoc(this.state.doc),0,0,e=>{this.viewportLines.push(Od(e,this.scaler))})}update(e,t=null){this.state=e.state;let s=this.stateDeco;this.stateDeco=oC(this.state);let i=e.changedRanges,r=vi.extendWithRanges(i,MJ(s,this.stateDeco,e?e.changes:gn.empty(this.state.doc.length))),o=this.heightMap.height,a=this.scrolledToBottom?null:this.scrollAnchorAt(this.scrollOffset);nC(),this.heightMap=this.heightMap.applyChanges(this.stateDeco,e.startState.doc,this.heightOracle.setDoc(this.state.doc),r),(this.heightMap.height!=o||Tu)&&(e.flags|=2),a?(this.scrollAnchorPos=e.changes.mapPos(a.from,-1),this.scrollAnchorHeight=a.top):(this.scrollAnchorPos=-1,this.scrollAnchorHeight=o);let l=r.length?this.mapViewport(this.viewport,e.changes):this.viewport;(t&&(t.range.headl.to)||!this.viewportIsAppropriate(l))&&(l=this.getViewport(0,t));let c=l.from!=this.viewport.from||l.to!=this.viewport.to;this.viewport=l,e.flags|=this.updateForViewport(),(c||!e.changes.empty||e.flags&2)&&this.updateViewportLines(),(this.lineGaps.length||this.viewport.to-this.viewport.from>4e3)&&this.updateLineGaps(this.ensureLineGaps(this.mapLineGaps(this.lineGaps,e.changes))),e.flags|=this.computeVisibleRanges(e.changes),t&&(this.scrollTarget=t),!this.mustEnforceCursorAssoc&&(e.selectionSet||e.focusChanged)&&e.view.lineWrapping&&e.state.selection.main.empty&&e.state.selection.main.assoc&&!e.state.facet(TO)&&(this.mustEnforceCursorAssoc=!0)}measure(){let{view:e}=this,t=e.contentDOM,s=window.getComputedStyle(t),i=this.heightOracle,r=s.whiteSpace;this.defaultTextDirection=s.direction=="rtl"?It.RTL:It.LTR;let o=this.heightOracle.mustRefreshForWrapping(r)||this.mustMeasureContent==="refresh",a=t.getBoundingClientRect(),l=o||this.mustMeasureContent||this.contentDOMHeight!=a.height;this.contentDOMHeight=a.height,this.mustMeasureContent=!1;let c=0,h=0;if(a.width&&a.height){let{scaleX:A,scaleY:C}=cO(t,a);(A>.005&&Math.abs(this.scaleX-A)>.005||C>.005&&Math.abs(this.scaleY-C)>.005)&&(this.scaleX=A,this.scaleY=C,c|=16,o=l=!0)}let u=(parseInt(s.paddingTop)||0)*this.scaleY,d=(parseInt(s.paddingBottom)||0)*this.scaleY;(this.paddingTop!=u||this.paddingBottom!=d)&&(this.paddingTop=u,this.paddingBottom=d,c|=18),this.editorWidth!=e.scrollDOM.clientWidth&&(i.lineWrapping&&(l=!0),this.editorWidth=e.scrollDOM.clientWidth,c|=16);let p=hO(this.view.contentDOM,!1).y;p!=this.scrollParent&&(this.scrollParent=p,this.scrollAnchorHeight=-1,this.scrollOffset=0);let m=this.getScrollOffset();this.scrollOffset!=m&&(this.scrollAnchorHeight=-1,this.scrollOffset=m),this.scrolledToBottom=pO(this.scrollParent||e.win);let y=(this.printing?LJ:OJ)(t,this.paddingTop),v=y.top-this.pixelViewport.top,g=y.bottom-this.pixelViewport.bottom;this.pixelViewport=y;let b=this.pixelViewport.bottom>this.pixelViewport.top&&this.pixelViewport.right>this.pixelViewport.left;if(b!=this.inView&&(this.inView=b,b&&(l=!0)),!this.inView&&!this.scrollTarget&&!NJ(e.dom))return 0;let _=a.width;if((this.contentDOMWidth!=_||this.editorHeight!=e.scrollDOM.clientHeight)&&(this.contentDOMWidth=a.width,this.editorHeight=e.scrollDOM.clientHeight,c|=16),l){let A=e.docView.measureVisibleLineHeights(this.viewport);if(i.mustRefreshForHeights(A)&&(o=!0),o||i.lineWrapping&&Math.abs(_-this.contentDOMWidth)>i.charWidth){let{lineHeight:C,charWidth:$,textHeight:I}=e.docView.measureTextSize();o=C>0&&i.refresh(r,C,$,I,Math.max(5,_/$),A),o&&(e.docView.minWidth=0,c|=16)}v>0&&g>0?h=Math.max(v,g):v<0&&g<0&&(h=Math.min(v,g)),nC();for(let C of this.viewports){let $=C.from==this.viewport.from?A:e.docView.measureVisibleLineHeights(C);this.heightMap=(o?ws.empty().applyChanges(this.stateDeco,lt.empty,this.heightOracle,[new vi(0,0,0,e.state.doc.length)]):this.heightMap).updateHeight(i,0,o,new $J(C.from,$))}Tu&&(c|=2)}let x=!this.viewportIsAppropriate(this.viewport,h)||this.scrollTarget&&(this.scrollTarget.range.headthis.viewport.to);return x&&(c&2&&(c|=this.updateScaler()),this.viewport=this.getViewport(h,this.scrollTarget),c|=this.updateForViewport()),(c&2||x)&&this.updateViewportLines(),(this.lineGaps.length||this.viewport.to-this.viewport.from>4e3)&&this.updateLineGaps(this.ensureLineGaps(o?[]:this.lineGaps,e)),c|=this.computeVisibleRanges(),this.mustEnforceCursorAssoc&&(this.mustEnforceCursorAssoc=!1,e.docView.enforceCursorAssoc()),c}get visibleTop(){return this.scaler.fromDOM(this.pixelViewport.top)}get visibleBottom(){return this.scaler.fromDOM(this.pixelViewport.bottom)}getViewport(e,t){let s=.5-Math.max(-.5,Math.min(.5,e/1e3/2)),i=this.heightMap,r=this.heightOracle,{visibleTop:o,visibleBottom:a}=this,l=new Wm(i.lineAt(o-s*1e3,kt.ByHeight,r,0,0).from,i.lineAt(a+(1-s)*1e3,kt.ByHeight,r,0,0).to);if(t){let{head:c}=t.range;if(cl.to){let h=Math.min(this.editorHeight,this.pixelViewport.bottom-this.pixelViewport.top),u=i.lineAt(c,kt.ByPos,r,0,0),d;t.y=="center"?d=(u.top+u.bottom)/2-h/2:t.y=="start"||t.y=="nearest"&&c=a+Math.max(10,Math.min(s,250)))&&i>o-2*1e3&&r>1,o=i<<1;if(this.defaultTextDirection!=It.LTR&&!s)return[];let a=[],l=(h,u,d,p)=>{if(u-hh&&gg.from>=d.from&&g.to<=d.to&&Math.abs(g.from-h)g.fromb));if(!v){if(u_.from<=u&&_.to>=u)){let _=t.moveToLineBoundary(ne.cursor(u),!1,!0).head;_>h&&(u=_)}let g=this.gapSize(d,h,u,p),b=s||g<2e6?g:2e6;v=new qv(h,u,g,b)}a.push(v)},c=h=>{if(h.length2e6)for(let C of e)C.from>=h.from&&C.fromh.from&&l(h.from,p,h,u),mt.draw(this,this.heightOracle.lineWrapping))))}computeVisibleRanges(e){let t=this.stateDeco;this.lineGaps.length&&(t=t.concat(this.lineGapDeco));let s=[];rt.spans(t,this.viewport.from,this.viewport.to,{span(r,o){s.push({from:r,to:o})},point(){}},20);let i=0;if(s.length!=this.visibleRanges.length)i=12;else for(let r=0;r=this.viewport.from&&e<=this.viewport.to&&this.viewportLines.find(t=>t.from<=e&&t.to>=e)||Od(this.heightMap.lineAt(e,kt.ByPos,this.heightOracle,0,0),this.scaler)}lineBlockAtHeight(e){return e>=this.viewportLines[0].top&&e<=this.viewportLines[this.viewportLines.length-1].bottom&&this.viewportLines.find(t=>t.top<=e&&t.bottom>=e)||Od(this.heightMap.lineAt(this.scaler.fromDOM(e),kt.ByHeight,this.heightOracle,0,0),this.scaler)}getScrollOffset(){return(this.scrollParent==this.view.scrollDOM?this.scrollParent.scrollTop:(this.scrollParent?this.scrollParent.getBoundingClientRect().top:0)-this.view.contentDOM.getBoundingClientRect().top)*this.scaleY}scrollAnchorAt(e){let t=this.lineBlockAtHeight(e+8);return t.from>=this.viewport.from||this.viewportLines[0].top-e>200?t:this.viewportLines[0]}elementAtHeight(e){return Od(this.heightMap.blockAt(this.scaler.fromDOM(e),this.heightOracle,0,0),this.scaler)}get docHeight(){return this.scaler.toDOM(this.heightMap.height)}get contentHeight(){return this.docHeight+this.paddingTop+this.paddingBottom}}class Wm{constructor(e,t){this.from=e,this.to=t}}function jJ(n,e,t){let s=[],i=n,r=0;return rt.spans(t,n,e,{span(){},point(o,a){o>i&&(s.push({from:i,to:o}),r+=o-i),i=a}},20),i=1)return e[e.length-1].to;let s=Math.floor(n*t);for(let i=0;;i++){let{from:r,to:o}=e[i],a=o-r;if(s<=a)return r+s;s-=a}}function Km(n,e){let t=0;for(let{from:s,to:i}of n.ranges){if(e<=i){t+=e-s;break}t+=i-s}return t/n.total}function FJ(n,e){for(let t of n)if(e(t))return t}const rC={toDOM(n){return n},fromDOM(n){return n},scale:1,eq(n){return n==this}};function oC(n){let e=n.facet(Z0).filter(s=>typeof s!="function"),t=n.facet(Gx).filter(s=>typeof s!="function");return t.length&&e.push(rt.join(t)),e}class Xx{constructor(e,t,s){let i=0,r=0,o=0;this.viewports=s.map(({from:a,to:l})=>{let c=t.lineAt(a,kt.ByPos,e,0,0).top,h=t.lineAt(l,kt.ByPos,e,0,0).bottom;return i+=h-c,{from:a,to:l,top:c,bottom:h,domTop:0,domBottom:0}}),this.scale=(7e6-i)/(t.height-i);for(let a of this.viewports)a.domTop=o+(a.top-r)*this.scale,o=a.domBottom=a.domTop+(a.bottom-a.top),r=a.bottom}toDOM(e){for(let t=0,s=0,i=0;;t++){let r=tt.from==e.viewports[s].from&&t.to==e.viewports[s].to):!1}}function Od(n,e){if(e.scale==1)return n;let t=e.toDOM(n.top),s=e.toDOM(n.bottom);return new Ki(n.from,n.length,t,s-t,Array.isArray(n._content)?n._content.map(i=>Od(i,e)):n._content)}const Zm=be.define({combine:n=>n.join(" ")}),F_=be.define({combine:n=>n.indexOf(!0)>-1}),z_=Eu.newName(),JO=Eu.newName(),QO=Eu.newName(),eN={"&light":"."+JO,"&dark":"."+QO};function H_(n,e,t){return new Eu(e,{finish(s){return/&/.test(s)?s.replace(/&\w*/,i=>{if(i=="&")return n;if(!t||!t[i])throw new RangeError(`Unsupported selector: ${i}`);return t[i]}):n+" "+s}})}const zJ=H_("."+z_,{"&":{position:"relative !important",boxSizing:"border-box","&.cm-focused":{outline:"1px dotted #212121"},display:"flex !important",flexDirection:"column"},".cm-scroller":{display:"flex !important",alignItems:"flex-start !important",fontFamily:"monospace",lineHeight:1.4,height:"100%",overflowX:"auto",position:"relative",zIndex:0,overflowAnchor:"none"},".cm-content":{margin:0,flexGrow:2,flexShrink:0,display:"block",whiteSpace:"pre",wordWrap:"normal",boxSizing:"border-box",minHeight:"100%",padding:"4px 0",outline:"none","&[contenteditable=true]":{WebkitUserModify:"read-write-plaintext-only"}},".cm-lineWrapping":{whiteSpace_fallback:"pre-wrap",whiteSpace:"break-spaces",wordBreak:"break-word",overflowWrap:"anywhere",flexShrink:1},"&light .cm-content":{caretColor:"black"},"&dark .cm-content":{caretColor:"white"},".cm-line":{display:"block",padding:"0 2px 0 6px"},".cm-layer":{userSelect:"none",position:"absolute",left:0,top:0,contain:"size style","& > *":{position:"absolute"}},"&light .cm-selectionBackground":{background:"#d9d9d9"},"&dark .cm-selectionBackground":{background:"#222"},"&light.cm-focused > .cm-scroller > .cm-selectionLayer .cm-selectionBackground":{background:"#d7d4f0"},"&dark.cm-focused > .cm-scroller > .cm-selectionLayer .cm-selectionBackground":{background:"#233"},".cm-cursorLayer":{pointerEvents:"none"},"&.cm-focused > .cm-scroller > .cm-cursorLayer":{animation:"steps(1) cm-blink 1.2s infinite"},"@keyframes cm-blink":{"0%":{},"50%":{opacity:0},"100%":{}},"@keyframes cm-blink2":{"0%":{},"50%":{opacity:0},"100%":{}},".cm-cursor, .cm-dropCursor":{borderLeft:"1.2px solid black",marginLeft:"-0.6px",pointerEvents:"none"},".cm-cursor":{display:"none"},"&dark .cm-cursor":{borderLeftColor:"#ddd"},".cm-selectionHandle":{backgroundColor:"currentColor",width:"1.5px"},".cm-selectionHandle-start::before, .cm-selectionHandle-end::before":{content:'""',backgroundColor:"inherit",borderRadius:"50%",width:"8px",height:"8px",position:"absolute",left:"-3.25px"},".cm-selectionHandle-start::before":{top:"-8px"},".cm-selectionHandle-end::before":{bottom:"-8px"},".cm-dropCursor":{position:"absolute"},"&.cm-focused > .cm-scroller > .cm-cursorLayer .cm-cursor":{display:"block"},".cm-iso":{unicodeBidi:"isolate"},".cm-announced":{position:"fixed",top:"-10000px"},"@media print":{".cm-announced":{display:"none"}},"&light .cm-activeLine":{backgroundColor:"#cceeff44"},"&dark .cm-activeLine":{backgroundColor:"#99eeff33"},"&light .cm-specialChar":{color:"red"},"&dark .cm-specialChar":{color:"#f78"},".cm-gutters":{flexShrink:0,display:"flex",height:"100%",boxSizing:"border-box",zIndex:200},".cm-gutters-before":{insetInlineStart:0},".cm-gutters-after":{insetInlineEnd:0},"&light .cm-gutters":{backgroundColor:"#f5f5f5",color:"#6c6c6c",border:"0px solid #ddd","&.cm-gutters-before":{borderRightWidth:"1px"},"&.cm-gutters-after":{borderLeftWidth:"1px"}},"&dark .cm-gutters":{backgroundColor:"#333338",color:"#ccc"},".cm-gutter":{display:"flex !important",flexDirection:"column",flexShrink:0,boxSizing:"border-box",minHeight:"100%",overflow:"hidden"},".cm-gutterElement":{boxSizing:"border-box"},".cm-lineNumbers .cm-gutterElement":{padding:"0 3px 0 5px",minWidth:"20px",textAlign:"right",whiteSpace:"nowrap"},"&light .cm-activeLineGutter":{backgroundColor:"#e2f2ff"},"&dark .cm-activeLineGutter":{backgroundColor:"#222227"},".cm-panels":{boxSizing:"border-box",position:"sticky",left:0,right:0,zIndex:300},"&light .cm-panels":{backgroundColor:"#f5f5f5",color:"black"},".cm-panels-top":{top:"0"},".cm-panels-bottom":{bottom:"0"},"&light .cm-panels-top":{borderBottom:"1px solid #ddd"},"&light .cm-panels-bottom":{borderTop:"1px solid #ddd"},"&dark .cm-panels":{backgroundColor:"#333338",color:"white"},".cm-dialog":{padding:"2px 19px 4px 6px",position:"relative","& label":{fontSize:"80%"}},".cm-dialog-close":{position:"absolute",top:"3px",right:"4px",backgroundColor:"inherit",border:"none",font:"inherit",fontSize:"14px",padding:"0"},".cm-tab":{display:"inline-block",overflow:"hidden",verticalAlign:"bottom"},".cm-widgetBuffer":{verticalAlign:"text-top",height:"1em",width:0,display:"inline"},".cm-placeholder":{color:"#888",display:"inline-block",verticalAlign:"top",userSelect:"none"},".cm-highlightSpace":{backgroundImage:"radial-gradient(circle at 50% 55%, #aaa 20%, transparent 5%)",backgroundPosition:"center"},".cm-highlightTab":{backgroundImage:`url('data:image/svg+xml,')`,backgroundSize:"auto 100%",backgroundPosition:"right 90%",backgroundRepeat:"no-repeat"},".cm-trailingSpace":{backgroundColor:"#ff332255"},".cm-button":{verticalAlign:"middle",color:"inherit",fontSize:"70%",padding:".2em 1em",borderRadius:"1px"},"&light .cm-button":{backgroundImage:"linear-gradient(#eff1f5, #d9d9df)",border:"1px solid #888","&:active":{backgroundImage:"linear-gradient(#b4b4b4, #d0d3d6)"}},"&dark .cm-button":{backgroundImage:"linear-gradient(#393939, #111)",border:"1px solid #888","&:active":{backgroundImage:"linear-gradient(#111, #333)"}},".cm-textfield":{verticalAlign:"middle",color:"inherit",fontSize:"70%",border:"1px solid silver",padding:".2em .5em"},"&light .cm-textfield":{backgroundColor:"white"},"&dark .cm-textfield":{border:"1px solid #555",backgroundColor:"inherit"}},eN),HJ={childList:!0,characterData:!0,subtree:!0,attributes:!0,characterDataOldValue:!0},Vv=de.ie&&de.ie_version<=11;class BJ{constructor(e){this.view=e,this.active=!1,this.editContext=null,this.selectionRange=new y7,this.selectionChanged=!1,this.delayedFlush=-1,this.resizeTimeout=-1,this.queue=[],this.delayedAndroidKey=null,this.flushingAndroidKey=-1,this.lastChange=0,this.scrollTargets=[],this.intersection=null,this.resizeScroll=null,this.intersecting=!1,this.gapIntersection=null,this.gaps=[],this.printQuery=null,this.parentCheck=-1,this.dom=e.contentDOM,this.observer=new MutationObserver(t=>{for(let s of t)this.queue.push(s);(de.ie&&de.ie_version<=11||de.ios&&e.composing)&&t.some(s=>s.type=="childList"&&s.removedNodes.length||s.type=="characterData"&&s.oldValue.length>s.target.nodeValue.length)?this.flushSoon():this.flush()}),window.EditContext&&de.android&&e.constructor.EDIT_CONTEXT!==!1&&!(de.chrome&&de.chrome_version<126)&&(this.editContext=new qJ(e),e.state.facet(vo)&&(e.contentDOM.editContext=this.editContext.editContext)),Vv&&(this.onCharData=t=>{this.queue.push({target:t.target,type:"characterData",oldValue:t.prevValue}),this.flushSoon()}),this.onSelectionChange=this.onSelectionChange.bind(this),this.onResize=this.onResize.bind(this),this.onPrint=this.onPrint.bind(this),this.onScroll=this.onScroll.bind(this),window.matchMedia&&(this.printQuery=window.matchMedia("print")),typeof ResizeObserver=="function"&&(this.resizeScroll=new ResizeObserver(()=>{var t;((t=this.view.docView)===null||t===void 0?void 0:t.lastUpdate){this.parentCheck<0&&(this.parentCheck=setTimeout(this.listenForScroll.bind(this),1e3)),t.length>0&&t[t.length-1].intersectionRatio>0!=this.intersecting&&(this.intersecting=!this.intersecting,this.intersecting!=this.view.inView&&this.onScrollChanged(document.createEvent("Event")))},{threshold:[0,.001]}),this.intersection.observe(this.dom),this.gapIntersection=new IntersectionObserver(t=>{t.length>0&&t[t.length-1].intersectionRatio>0&&this.onScrollChanged(document.createEvent("Event"))},{})),this.listenForScroll(),this.readSelectionRange()}onScrollChanged(e){this.view.inputState.runHandlers("scroll",e),this.intersecting&&this.view.measure()}onScroll(e){this.intersecting&&this.flush(!1),this.editContext&&this.view.requestMeasure(this.editContext.measureReq),this.onScrollChanged(e)}onResize(){this.resizeTimeout<0&&(this.resizeTimeout=setTimeout(()=>{this.resizeTimeout=-1,this.view.requestMeasure()},50))}onPrint(e){(e.type=="change"||!e.type)&&!e.matches||(this.view.viewState.printing=!0,this.view.measure(),setTimeout(()=>{this.view.viewState.printing=!1,this.view.requestMeasure()},500))}updateGaps(e){if(this.gapIntersection&&(e.length!=this.gaps.length||this.gaps.some((t,s)=>t!=e[s]))){this.gapIntersection.disconnect();for(let t of e)this.gapIntersection.observe(t);this.gaps=e}}onSelectionChange(e){let t=this.selectionChanged;if(!this.readSelectionRange()||this.delayedAndroidKey)return;let{view:s}=this,i=this.selectionRange;if(s.state.facet(vo)?s.root.activeElement!=this.dom:!Jd(this.dom,i))return;let r=i.anchorNode&&s.docView.tile.nearest(i.anchorNode);if(r&&r.isWidget()&&r.widget.ignoreEvent(e)){t||(this.selectionChanged=!1);return}(de.ie&&de.ie_version<=11||de.android&&de.chrome)&&!s.state.selection.main.empty&&i.focusNode&&Qd(i.focusNode,i.focusOffset,i.anchorNode,i.anchorOffset)?this.flushSoon():this.flush(!1)}readSelectionRange(){let{view:e}=this,t=gf(e.root);if(!t)return!1;let s=de.safari&&e.root.nodeType==11&&e.root.activeElement==this.dom&&UJ(this.view,t)||t;if(!s||this.selectionRange.eq(s))return!1;let i=Jd(this.dom,s);return i&&!this.selectionChanged&&e.inputState.lastFocusTime>Date.now()-200&&e.inputState.lastTouchTime{let r=this.delayedAndroidKey;r&&(this.clearDelayedAndroidKey(),this.view.inputState.lastKeyCode=r.keyCode,this.view.inputState.lastKeyTime=Date.now(),!this.flush()&&r.force&&yh(this.dom,r.key,r.keyCode))};this.flushingAndroidKey=this.view.win.requestAnimationFrame(i)}(!this.delayedAndroidKey||e=="Enter")&&(this.delayedAndroidKey={key:e,keyCode:t,force:this.lastChange{this.delayedFlush=-1,this.flush()}))}forceFlush(){this.delayedFlush>=0&&(this.view.win.cancelAnimationFrame(this.delayedFlush),this.delayedFlush=-1),this.flush()}pendingRecords(){for(let e of this.observer.takeRecords())this.queue.push(e);return this.queue}processRecords(){let e=this.pendingRecords();e.length&&(this.queue=[]);let t=-1,s=-1,i=!1;for(let r of e){let o=this.readMutation(r);o&&(o.typeOver&&(i=!0),t==-1?{from:t,to:s}=o:(t=Math.min(o.from,t),s=Math.max(o.to,s)))}return{from:t,to:s,typeOver:i}}readChange(){let{from:e,to:t,typeOver:s}=this.processRecords(),i=this.selectionChanged&&Jd(this.dom,this.selectionRange);if(e<0&&!i)return null;e>-1&&(this.lastChange=Date.now()),this.view.inputState.lastFocusTime=0,this.selectionChanged=!1;let r=new oJ(this.view,e,t,s);return this.view.docView.domChanged={newSel:r.newSel?r.newSel.main:null},r}flush(e=!0){if(this.delayedFlush>=0||this.delayedAndroidKey)return!1;e&&this.readSelectionRange();let t=this.readChange();if(!t)return this.view.requestMeasure(),!1;let s=this.view.state,i=HO(this.view,t);return this.view.state==s&&(t.domChanged||t.newSel&&!Iy(this.view.state.selection,t.newSel.main))&&this.view.update([]),i}readMutation(e){let t=this.view.docView.tile.nearest(e.target);if(!t||t.isWidget())return null;if(t.markDirty(e.type=="attributes"),e.type=="childList"){let s=aC(t,e.previousSibling||e.target.previousSibling,-1),i=aC(t,e.nextSibling||e.target.nextSibling,1);return{from:s?t.posAfter(s):t.posAtStart,to:i?t.posBefore(i):t.posAtEnd,typeOver:!1}}else return e.type=="characterData"?{from:t.posAtStart,to:t.posAtEnd,typeOver:e.target.nodeValue==e.oldValue}:null}setWindow(e){e!=this.win&&(this.removeWindowListeners(this.win),this.win=e,this.addWindowListeners(this.win))}addWindowListeners(e){e.addEventListener("resize",this.onResize),this.printQuery?this.printQuery.addEventListener?this.printQuery.addEventListener("change",this.onPrint):this.printQuery.addListener(this.onPrint):e.addEventListener("beforeprint",this.onPrint),e.addEventListener("scroll",this.onScroll),e.document.addEventListener("selectionchange",this.onSelectionChange)}removeWindowListeners(e){e.removeEventListener("scroll",this.onScroll),e.removeEventListener("resize",this.onResize),this.printQuery?this.printQuery.removeEventListener?this.printQuery.removeEventListener("change",this.onPrint):this.printQuery.removeListener(this.onPrint):e.removeEventListener("beforeprint",this.onPrint),e.document.removeEventListener("selectionchange",this.onSelectionChange)}update(e){this.editContext&&(this.editContext.update(e),e.startState.facet(vo)!=e.state.facet(vo)&&(e.view.contentDOM.editContext=e.state.facet(vo)?this.editContext.editContext:null))}destroy(){var e,t,s;this.stop(),(e=this.intersection)===null||e===void 0||e.disconnect(),(t=this.gapIntersection)===null||t===void 0||t.disconnect(),(s=this.resizeScroll)===null||s===void 0||s.disconnect();for(let i of this.scrollTargets)i.removeEventListener("scroll",this.onScroll);this.removeWindowListeners(this.win),clearTimeout(this.parentCheck),clearTimeout(this.resizeTimeout),this.win.cancelAnimationFrame(this.delayedFlush),this.win.cancelAnimationFrame(this.flushingAndroidKey),this.editContext&&(this.view.contentDOM.editContext=null,this.editContext.destroy())}}function aC(n,e,t){for(;e;){let s=Gt.get(e);if(s&&s.parent==n)return s;let i=e.parentNode;e=i!=n.dom?i:t>0?e.nextSibling:e.previousSibling}return null}function lC(n,e){let t=e.startContainer,s=e.startOffset,i=e.endContainer,r=e.endOffset,o=n.docView.domAtPos(n.state.selection.main.anchor,1);return Qd(o.node,o.offset,i,r)&&([t,s,i,r]=[i,r,t,s]),{anchorNode:t,anchorOffset:s,focusNode:i,focusOffset:r}}function UJ(n,e){if(e.getComposedRanges){let i=e.getComposedRanges(n.root)[0];if(i)return lC(n,i)}let t=null;function s(i){i.preventDefault(),i.stopImmediatePropagation(),t=i.getTargetRanges()[0]}return n.contentDOM.addEventListener("beforeinput",s,!0),n.dom.ownerDocument.execCommand("indent"),n.contentDOM.removeEventListener("beforeinput",s,!0),t?lC(n,t):null}class qJ{constructor(e){this.from=0,this.to=0,this.pendingContextChange=null,this.handlers=Object.create(null),this.composing=null,this.resetRange(e.state);let t=this.editContext=new window.EditContext({text:e.state.doc.sliceString(this.from,this.to),selectionStart:this.toContextPos(Math.max(this.from,Math.min(this.to,e.state.selection.main.anchor))),selectionEnd:this.toContextPos(e.state.selection.main.head)});this.handlers.textupdate=s=>{let i=e.state.selection.main,{anchor:r,head:o}=i,a=this.toEditorPos(s.updateRangeStart),l=this.toEditorPos(s.updateRangeEnd);e.inputState.composing>=0&&!this.composing&&(this.composing={contextBase:s.updateRangeStart,editorBase:a,drifted:!1});let c=l-a>s.text.length;a==this.from&&rthis.to&&(l=r);let h=BO(e.state.sliceDoc(a,l),s.text,(c?i.from:i.to)-a,c?"end":null);if(!h){let d=ne.single(this.toEditorPos(s.selectionStart),this.toEditorPos(s.selectionEnd));Iy(d,i)||e.dispatch({selection:d,userEvent:"select"});return}let u={from:h.from+a,to:h.toA+a,insert:lt.of(s.text.slice(h.from,h.toB).split(` +`))};if((de.mac||de.android)&&u.from==o-1&&/^\. ?$/.test(s.text)&&e.contentDOM.getAttribute("autocorrect")=="off"&&(u={from:a,to:l,insert:lt.of([s.text.replace("."," ")])}),this.pendingContextChange=u,!e.state.readOnly){let d=this.to-this.from+(u.to-u.from+u.insert.length);Kx(e,u,ne.single(this.toEditorPos(s.selectionStart,d),this.toEditorPos(s.selectionEnd,d)))}this.pendingContextChange&&(this.revertPending(e.state),this.setSelection(e.state)),u.from=0&&!/[\\p{Alphabetic}\\p{Number}_]/.test(t.text.slice(Math.max(0,s.updateRangeStart-1),Math.min(t.text.length,s.updateRangeStart+1)))&&this.handlers.compositionend(s)},this.handlers.characterboundsupdate=s=>{let i=[],r=null;for(let o=this.toEditorPos(s.rangeStart),a=this.toEditorPos(s.rangeEnd);o{let i=[];for(let r of s.getTextFormats()){let o=r.underlineStyle,a=r.underlineThickness;if(!/none/i.test(o)&&!/none/i.test(a)){let l=this.toEditorPos(r.rangeStart),c=this.toEditorPos(r.rangeEnd);if(l{e.inputState.composing<0&&(e.inputState.composing=0,e.inputState.compositionFirstChange=!0)},this.handlers.compositionend=()=>{if(e.inputState.composing=-1,e.inputState.compositionFirstChange=null,this.composing){let{drifted:s}=this.composing;this.composing=null,s&&this.reset(e.state)}};for(let s in this.handlers)t.addEventListener(s,this.handlers[s]);this.measureReq={read:s=>{let i=gf(s.root);i&&i.rangeCount&&this.editContext.updateSelectionBounds(i.getRangeAt(0).getBoundingClientRect())}}}applyEdits(e){let t=0,s=!1,i=this.pendingContextChange;return e.changes.iterChanges((r,o,a,l,c)=>{if(s)return;let h=c.length-(o-r);if(i&&o>=i.to)if(i.from==r&&i.to==o&&i.insert.eq(c)){i=this.pendingContextChange=null,t+=h,this.to+=h;return}else i=null,this.revertPending(e.state);if(r+=t,o+=t,o<=this.from)this.from+=h,this.to+=h;else if(rthis.to||this.to-this.from+c.length>3e4){s=!0;return}this.editContext.updateText(this.toContextPos(r),this.toContextPos(o),c.toString()),this.to+=h}t+=h}),i&&!s&&this.revertPending(e.state),!s}update(e){let t=this.pendingContextChange,s=e.startState.selection.main;this.composing&&(this.composing.drifted||!e.changes.touchesRange(s.from,s.to)&&e.transactions.some(i=>!i.isUserEvent("input.type")&&i.changes.touchesRange(this.from,this.to)))?(this.composing.drifted=!0,this.composing.editorBase=e.changes.mapPos(this.composing.editorBase)):!this.applyEdits(e)||!this.rangeIsValid(e.state)?(this.pendingContextChange=null,this.reset(e.state)):(e.docChanged||e.selectionSet||t)&&this.setSelection(e.state),(e.geometryChanged||e.docChanged||e.selectionSet)&&e.view.requestMeasure(this.measureReq)}resetRange(e){let{head:t}=e.selection.main;this.from=Math.max(0,t-1e4),this.to=Math.min(e.doc.length,t+1e4)}reset(e){this.resetRange(e),this.editContext.updateText(0,this.editContext.text.length,e.doc.sliceString(this.from,this.to)),this.setSelection(e)}revertPending(e){let t=this.pendingContextChange;this.pendingContextChange=null,this.editContext.updateText(this.toContextPos(t.from),this.toContextPos(t.from+t.insert.length),e.doc.sliceString(t.from,t.to))}setSelection(e){let{main:t}=e.selection,s=this.toContextPos(Math.max(this.from,Math.min(this.to,t.anchor))),i=this.toContextPos(t.head);(this.editContext.selectionStart!=s||this.editContext.selectionEnd!=i)&&this.editContext.updateSelection(s,i)}rangeIsValid(e){let{head:t}=e.selection.main;return!(this.from>0&&t-this.from<500||this.to1e4*3)}toEditorPos(e,t=this.to-this.from){e=Math.min(e,t);let s=this.composing;return s&&s.drifted?s.editorBase+(e-s.contextBase):e+this.from}toContextPos(e){let t=this.composing;return t&&t.drifted?t.contextBase+(e-t.editorBase):e-this.from}destroy(){for(let e in this.handlers)this.editContext.removeEventListener(e,this.handlers[e])}}class xe{get state(){return this.viewState.state}get viewport(){return this.viewState.viewport}get visibleRanges(){return this.viewState.visibleRanges}get inView(){return this.viewState.inView}get composing(){return!!this.inputState&&this.inputState.composing>0}get compositionStarted(){return!!this.inputState&&this.inputState.composing>=0}get root(){return this._root}get win(){return this.dom.ownerDocument.defaultView||window}constructor(e={}){var t;this.plugins=[],this.pluginMap=new Map,this.editorAttrs={},this.contentAttrs={},this.bidiCache=[],this.destroyed=!1,this.updateState=2,this.measureScheduled=-1,this.measureRequests=[],this.contentDOM=document.createElement("div"),this.scrollDOM=document.createElement("div"),this.scrollDOM.tabIndex=-1,this.scrollDOM.className="cm-scroller",this.scrollDOM.appendChild(this.contentDOM),this.announceDOM=document.createElement("div"),this.announceDOM.className="cm-announced",this.announceDOM.setAttribute("aria-live","polite"),this.dom=document.createElement("div"),this.dom.appendChild(this.announceDOM),this.dom.appendChild(this.scrollDOM),e.parent&&e.parent.appendChild(this.dom);let{dispatch:s}=e;this.dispatchTransactions=e.dispatchTransactions||s&&(i=>i.forEach(r=>s(r,this)))||(i=>this.update(i)),this.dispatch=this.dispatch.bind(this),this._root=e.root||v7(e.parent)||document,this.viewState=new iC(this,e.state||at.create(e)),e.scrollTo&&e.scrollTo.is(Um)&&(this.viewState.scrollTarget=e.scrollTo.value.clip(this.viewState.state)),this.plugins=this.state.facet(ih).map(i=>new Fv(i));for(let i of this.plugins)i.update(this);this.observer=new BJ(this),this.inputState=new hJ(this),this.inputState.ensureHandlers(this.plugins),this.docView=new VE(this),this.mountStyles(),this.updateAttrs(),this.updateState=0,this.requestMeasure(),!((t=document.fonts)===null||t===void 0)&&t.ready&&document.fonts.ready.then(()=>{this.viewState.mustMeasureContent="refresh",this.requestMeasure()})}dispatch(...e){let t=e.length==1&&e[0]instanceof bn?e:e.length==1&&Array.isArray(e[0])?e[0]:[this.state.update(...e)];this.dispatchTransactions(t,this)}update(e){if(this.updateState!=0)throw new Error("Calls to EditorView.update are not allowed while an update is in progress");let t=!1,s=!1,i,r=this.state;for(let d of e){if(d.startState!=r)throw new RangeError("Trying to update state with a transaction that doesn't start from the previous state.");r=d.state}if(this.destroyed){this.viewState.state=r;return}let o=this.hasFocus,a=0,l=null;e.some(d=>d.annotation(KO))?(this.inputState.notifiedFocused=o,a=1):o!=this.inputState.notifiedFocused&&(this.inputState.notifiedFocused=o,l=ZO(r,o),l||(a=1));let c=this.observer.delayedAndroidKey,h=null;if(c?(this.observer.clearDelayedAndroidKey(),h=this.observer.readChange(),(h&&!this.state.doc.eq(r.doc)||!this.state.selection.eq(r.selection))&&(h=null)):this.observer.clear(),r.facet(at.phrases)!=this.state.facet(at.phrases))return this.setState(r);i=Py.create(this,r,e),i.flags|=a;let u=this.viewState.scrollTarget;try{this.updateState=2;for(let d of e){if(u&&(u=u.map(d.changes)),d.scrollIntoView){let{main:p}=d.state.selection,{x:m,y}=this.state.facet(xe.cursorScrollMargin);u=new vh(p.empty?p:ne.cursor(p.head,p.head>p.anchor?-1:1),"nearest","nearest",y,m)}for(let p of d.effects)p.is(Um)&&(u=p.value.clip(this.state))}this.viewState.update(i,u),this.bidiCache=Ny.update(this.bidiCache,i.changes),i.empty||(this.updatePlugins(i),this.inputState.update(i)),t=this.docView.update(i),this.state.facet(Id)!=this.styleModules&&this.mountStyles(),s=this.updateAttrs(),this.showAnnouncements(e),this.docView.updateSelection(t,e.some(d=>d.isUserEvent("select.pointer")))}finally{this.updateState=0}if(i.startState.facet(Zm)!=i.state.facet(Zm)&&(this.viewState.mustMeasureContent=!0),(t||s||u||this.viewState.mustEnforceCursorAssoc||this.viewState.mustMeasureContent)&&this.requestMeasure(),t&&this.docViewUpdate(),!i.empty)for(let d of this.state.facet(O_))try{d(i)}catch(p){Mr(this.state,p,"update listener")}(l||h)&&Promise.resolve().then(()=>{l&&this.state==l.startState&&this.dispatch(l),h&&!HO(this,h)&&c.force&&yh(this.contentDOM,c.key,c.keyCode)})}setState(e){if(this.updateState!=0)throw new Error("Calls to EditorView.setState are not allowed while an update is in progress");if(this.destroyed){this.viewState.state=e;return}this.updateState=2;let t=this.hasFocus;try{for(let s of this.plugins)s.destroy(this);this.viewState=new iC(this,e),this.plugins=e.facet(ih).map(s=>new Fv(s)),this.pluginMap.clear();for(let s of this.plugins)s.update(this);this.docView.destroy(),this.docView=new VE(this),this.inputState.ensureHandlers(this.plugins),this.mountStyles(),this.updateAttrs(),this.bidiCache=[]}finally{this.updateState=0}t&&this.focus(),this.requestMeasure()}updatePlugins(e){let t=e.startState.facet(ih),s=e.state.facet(ih);if(t!=s){let i=[];for(let r of s){let o=t.indexOf(r);if(o<0)i.push(new Fv(r));else{let a=this.plugins[o];a.mustUpdate=e,i.push(a)}}for(let r of this.plugins)r.mustUpdate!=e&&r.destroy(this);this.plugins=i,this.pluginMap.clear()}else for(let i of this.plugins)i.mustUpdate=e;for(let i=0;i-1&&this.win.cancelAnimationFrame(this.measureScheduled),this.observer.delayedAndroidKey){this.measureScheduled=-1,this.requestMeasure();return}this.measureScheduled=0,e&&this.observer.forceFlush();let t=null,s=this.viewState.scrollParent,i=this.viewState.getScrollOffset(),{scrollAnchorPos:r,scrollAnchorHeight:o}=this.viewState;Math.abs(i-this.viewState.scrollOffset)>1&&(o=-1),this.viewState.scrollAnchorHeight=-1;try{for(let a=0;;a++){if(o<0)if(pO(s||this.win))r=-1,o=this.viewState.heightMap.height;else{let p=this.viewState.scrollAnchorAt(i);r=p.from,o=p.top}this.updateState=1;let l=this.viewState.measure();if(!l&&!this.measureRequests.length&&this.viewState.scrollTarget==null)break;if(a>5){console.warn(this.measureRequests.length?"Measure loop restarted more than 5 times":"Viewport failed to stabilize");break}let c=[];l&4||([this.measureRequests,c]=[c,this.measureRequests]);let h=c.map(p=>{try{return p.read(this)}catch(m){return Mr(this.state,m),cC}}),u=Py.create(this,this.state,[]),d=!1;u.flags|=l,t?t.flags|=l:t=u,this.updateState=2,u.empty||(this.updatePlugins(u),this.inputState.update(u),this.updateAttrs(),d=this.docView.update(u),d&&this.docViewUpdate());for(let p=0;p1||m<-1)&&!(de.ios&&this.inputState.lastIOSMomentumScroll>Date.now()-100)&&(s==this.scrollDOM||this.hasFocus||Math.max(this.inputState.lastWheelEvent,this.inputState.lastTouchTime)>Date.now()-100)){i=i+m,s?r<0?s.scrollTop=s.scrollHeight:s.scrollTop+=m:this.win.scrollBy(0,m),o=-1;continue}}break}}}finally{this.updateState=0,this.measureScheduled=-1}if(t&&!t.empty)for(let a of this.state.facet(O_))a(t)}get themeClasses(){return z_+" "+(this.state.facet(F_)?QO:JO)+" "+this.state.facet(Zm)}updateAttrs(){let e=hC(this,MO,{class:"cm-editor"+(this.hasFocus?" cm-focused ":" ")+this.themeClasses}),t={spellcheck:"false",autocorrect:"off",autocapitalize:"off",writingsuggestions:"false",translate:"no",contenteditable:this.state.facet(vo)?"true":"false",class:"cm-content",style:`${de.tabSize}: ${this.state.tabSize}`,role:"textbox","aria-multiline":"true"};this.state.readOnly&&(t["aria-readonly"]="true"),hC(this,Wx,t);let s=this.observer.ignore(()=>{let i=FE(this.contentDOM,this.contentAttrs,t),r=FE(this.dom,this.editorAttrs,e);return i||r});return this.editorAttrs=e,this.contentAttrs=t,s}showAnnouncements(e){let t=!0;for(let s of e)for(let i of s.effects)if(i.is(xe.announce)){t&&(this.announceDOM.textContent=""),t=!1;let r=this.announceDOM.appendChild(document.createElement("div"));r.textContent=i.value}}mountStyles(){this.styleModules=this.state.facet(Id);let e=this.state.facet(xe.cspNonce);Eu.mount(this.root,this.styleModules.concat(zJ).reverse(),e?{nonce:e}:void 0)}readMeasured(){if(this.updateState==2)throw new Error("Reading the editor layout isn't allowed during an update");this.updateState==0&&this.measureScheduled>-1&&this.measure(!1)}requestMeasure(e){if(this.measureScheduled<0&&(this.measureScheduled=this.win.requestAnimationFrame(()=>this.measure())),e){if(this.measureRequests.indexOf(e)>-1)return;if(e.key!=null){for(let t=0;ts.plugin==e)||null),t&&t.update(this).value}get documentTop(){return this.contentDOM.getBoundingClientRect().top+this.viewState.paddingTop}get documentPadding(){return{top:this.viewState.paddingTop,bottom:this.viewState.paddingBottom}}get scaleX(){return this.viewState.scaleX}get scaleY(){return this.viewState.scaleY}elementAtHeight(e){return this.readMeasured(),this.viewState.elementAtHeight(e)}lineBlockAtHeight(e){return this.readMeasured(),this.viewState.lineBlockAtHeight(e)}get viewportLineBlocks(){return this.viewState.viewportLines}lineBlockAt(e){return this.viewState.lineBlockAt(e)}get contentHeight(){return this.viewState.contentHeight}moveByChar(e,t,s){return Uv(this,e,WE(this,e,t,s))}moveByGroup(e,t){return Uv(this,e,WE(this,e,t,s=>eJ(this,e.head,s)))}visualLineSide(e,t){let s=this.bidiSpans(e),i=this.textDirectionAt(e.from),r=s[t?s.length-1:0];return ne.cursor(r.side(t,i)+e.from,r.forward(!t,i)?1:-1)}moveToLineBoundary(e,t,s=!0){return Q7(this,e,t,s)}moveVertically(e,t,s){return Uv(this,e,tJ(this,e,t,s))}domAtPos(e,t=1){return this.docView.domAtPos(e,t)}posAtDOM(e,t=0){return this.docView.posFromDOM(e,t)}posAtCoords(e,t=!0){this.readMeasured();let s=D_(this,e,t);return s&&s.pos}posAndSideAtCoords(e,t=!0){return this.readMeasured(),D_(this,e,t)}coordsAtPos(e,t=1){this.readMeasured();let s=this.state.doc.lineAt(e),i=this.bidiSpans(s),r=i[Rr.find(i,e-s.from,-1,t)];return this.docView.coordsAt(e,t,r.dir==It.RTL)}coordsForChar(e){return this.readMeasured(),this.docView.coordsForChar(e)}get defaultCharacterWidth(){return this.viewState.heightOracle.charWidth}get defaultLineHeight(){return this.viewState.heightOracle.lineHeight}get textDirection(){return this.viewState.defaultTextDirection}textDirectionAt(e){return!this.state.facet($O)||ethis.viewport.to?this.textDirection:(this.readMeasured(),this.docView.textDirectionAt(e))}get lineWrapping(){return this.viewState.heightOracle.lineWrapping}bidiSpans(e){if(e.length>VJ)return wO(e.length);let t=this.textDirectionAt(e.from),s;for(let r of this.bidiCache)if(r.from==e.from&&r.dir==t&&(r.fresh||bO(r.isolates,s=BE(this,e))))return r.order;s||(s=BE(this,e));let i=E7(e.text,t,s);return this.bidiCache.push(new Ny(e.from,e.to,t,s,!0,i)),i}get hasFocus(){var e;return(this.dom.ownerDocument.hasFocus()||de.safari&&((e=this.inputState)===null||e===void 0?void 0:e.lastContextMenu)>Date.now()-3e4)&&this.root.activeElement==this.contentDOM}focus(){this.observer.ignore(()=>{fO(this.contentDOM),this.docView.updateSelection()})}setRoot(e){this._root!=e&&(this._root=e,this.observer.setWindow((e.nodeType==9?e:e.ownerDocument).defaultView||window),this.mountStyles())}destroy(){this.root.activeElement==this.contentDOM&&this.contentDOM.blur();for(let e of this.plugins)e.destroy(this);this.plugins=[],this.inputState.destroy(),this.docView.destroy(),this.dom.remove(),this.observer.destroy(),this.measureScheduled>-1&&this.win.cancelAnimationFrame(this.measureScheduled),this.destroyed=!0}static scrollIntoView(e,t={}){var s,i,r,o;return Um.of(new vh(typeof e=="number"?ne.cursor(e):e,(s=t.y)!==null&&s!==void 0?s:"nearest",(i=t.x)!==null&&i!==void 0?i:"nearest",(r=t.yMargin)!==null&&r!==void 0?r:5,(o=t.xMargin)!==null&&o!==void 0?o:5))}scrollSnapshot(){let{scrollTop:e,scrollLeft:t}=this.scrollDOM,s=this.viewState.scrollAnchorAt(e);return Um.of(new vh(ne.cursor(s.from),"start","start",s.top-e,t,!0))}setTabFocusMode(e){e==null?this.inputState.tabFocusMode=this.inputState.tabFocusMode<0?0:-1:typeof e=="boolean"?this.inputState.tabFocusMode=e?0:-1:this.inputState.tabFocusMode!=0&&(this.inputState.tabFocusMode=Date.now()+e)}static domEventHandlers(e){return ii.define(()=>({}),{eventHandlers:e})}static domEventObservers(e){return ii.define(()=>({}),{eventObservers:e})}static theme(e,t){let s=Eu.newName(),i=[Zm.of(s),Id.of(H_(`.${s}`,e))];return t&&t.dark&&i.push(F_.of(!0)),i}static baseTheme(e){return V0.lowest(Id.of(H_("."+z_,e,eN)))}static findFromDOM(e){var t;let s=e.querySelector(".cm-content"),i=s&&Gt.get(s)||Gt.get(e);return((t=i==null?void 0:i.root)===null||t===void 0?void 0:t.view)||null}}xe.styleModule=Id;xe.inputHandler=EO;xe.clipboardInputFilter=qx;xe.clipboardOutputFilter=Vx;xe.scrollHandler=PO;xe.focusChangeEffect=CO;xe.perLineTextDirection=$O;xe.exceptionSink=kO;xe.updateListener=O_;xe.editable=vo;xe.mouseSelectionStyle=AO;xe.dragMovesSelection=xO;xe.clickAddsSelectionRange=SO;xe.decorations=Z0;xe.blockWrappers=IO;xe.outerDecorations=Gx;xe.atomicRanges=lm;xe.bidiIsolatedRanges=OO;xe.cursorScrollMargin=be.define({combine:n=>{let e=5,t=5;for(let s of n)typeof s=="number"?e=t=s:{x:e,y:t}=s;return{x:e,y:t}}});xe.scrollMargins=NO;xe.darkTheme=F_;xe.cspNonce=be.define({combine:n=>n.length?n[0]:""});xe.contentAttributes=Wx;xe.editorAttributes=MO;xe.lineWrapping=xe.contentAttributes.of({class:"cm-lineWrapping"});xe.announce=_t.define();const VJ=4096,cC={};class Ny{constructor(e,t,s,i,r,o){this.from=e,this.to=t,this.dir=s,this.isolates=i,this.fresh=r,this.order=o}static update(e,t){if(t.empty&&!e.some(r=>r.fresh))return e;let s=[],i=e.length?e[e.length-1].dir:It.LTR;for(let r=Math.max(0,e.length-10);r=0;i--){let r=s[i],o=typeof r=="function"?r(n):r;o&&Hx(o,t)}return t}const WJ=de.mac?"mac":de.windows?"win":de.linux?"linux":"key";function GJ(n,e){const t=n.split(/-(?!$)/);let s=t[t.length-1];s=="Space"&&(s=" ");let i,r,o,a;for(let l=0;ls.concat(i),[]))),t}function ZJ(n,e,t){return sN(nN(n.state),e,n,t)}let qo=null;const XJ=4e3;function YJ(n,e=WJ){let t=Object.create(null),s=Object.create(null),i=(o,a)=>{let l=s[o];if(l==null)s[o]=a;else if(l!=a)throw new Error("Key binding "+o+" is used both as a regular binding and as a multi-stroke prefix")},r=(o,a,l,c,h)=>{var u,d;let p=t[o]||(t[o]=Object.create(null)),m=a.split(/ (?!$)/).map(g=>GJ(g,e));for(let g=1;g{let x=qo={view:_,prefix:b,scope:o};return setTimeout(()=>{qo==x&&(qo=null)},XJ),!0}]})}let y=m.join(" ");i(y,!1);let v=p[y]||(p[y]={preventDefault:!1,stopPropagation:!1,run:((d=(u=p._any)===null||u===void 0?void 0:u.run)===null||d===void 0?void 0:d.slice())||[]});l&&v.run.push(l),c&&(v.preventDefault=!0),h&&(v.stopPropagation=!0)};for(let o of n){let a=o.scope?o.scope.split(" "):["editor"];if(o.any)for(let c of a){let h=t[c]||(t[c]=Object.create(null));h._any||(h._any={preventDefault:!1,stopPropagation:!1,run:[]});let{any:u}=o;for(let d in h)h[d].run.push(p=>u(p,B_))}let l=o[e]||o.key;if(l)for(let c of a)r(c,l,o.run,o.preventDefault,o.stopPropagation),o.shift&&r(c,"Shift-"+l,o.shift,o.preventDefault,o.stopPropagation)}return t}let B_=null;function sN(n,e,t,s){B_=e;let i=u7(e),r=VI(i,0),o=WI(r)==i.length&&i!=" ",a="",l=!1,c=!1,h=!1;qo&&qo.view==t&&qo.scope==s&&(a=qo.prefix+" ",qO.indexOf(e.keyCode)<0&&(c=!0,qo=null));let u=new Set,d=v=>{if(v){for(let g of v.run)if(!u.has(g)&&(u.add(g),g(t)))return v.stopPropagation&&(h=!0),!0;v.preventDefault&&(v.stopPropagation&&(h=!0),c=!0)}return!1},p=n[s],m,y;return p&&(d(p[a+Xm(i,e,!o)])?l=!0:o&&(e.altKey||e.metaKey||e.ctrlKey)&&!(de.windows&&e.ctrlKey&&e.altKey)&&!(de.mac&&e.altKey&&!(e.ctrlKey||e.metaKey))&&(m=Ra[e.keyCode])&&m!=i?(d(p[a+Xm(m,e,!0)])||e.shiftKey&&(y=pf[e.keyCode])!=i&&y!=m&&d(p[a+Xm(y,e,!1)]))&&(l=!0):o&&e.shiftKey&&d(p[a+Xm(i,e,!0)])&&(l=!0),!l&&d(p._any)&&(l=!0)),c&&(l=!0),l&&h&&e.stopPropagation(),B_=null,l}class oc{constructor(e,t,s,i,r){this.className=e,this.left=t,this.top=s,this.width=i,this.height=r}draw(){let e=document.createElement("div");return e.className=this.className,this.adjust(e),e}update(e,t){return t.className!=this.className?!1:(this.adjust(e),!0)}adjust(e){e.style.left=this.left+"px",e.style.top=this.top+"px",this.width!=null&&(e.style.width=this.width+"px"),e.style.height=this.height+"px"}eq(e){return this.left==e.left&&this.top==e.top&&this.width==e.width&&this.height==e.height&&this.className==e.className}static forRange(e,t,s){if(s.empty){let i=e.coordsAtPos(s.head,s.assoc||1);if(!i)return[];let r=iN(e);return[new oc(t,i.left-r.left,i.top-r.top,null,i.bottom-i.top)]}else return JJ(e,t,s)}}function iN(n){let e=n.scrollDOM.getBoundingClientRect();return{left:(n.textDirection==It.LTR?e.left:e.right-n.scrollDOM.clientWidth*n.scaleX)-n.scrollDOM.scrollLeft*n.scaleX,top:e.top-n.scrollDOM.scrollTop*n.scaleY}}function dC(n,e,t,s){let i=n.coordsAtPos(e,t*2);if(!i)return s;let r=n.dom.getBoundingClientRect(),o=(i.top+i.bottom)/2,a=n.posAtCoords({x:r.left+1,y:o}),l=n.posAtCoords({x:r.right-1,y:o});return a==null||l==null?s:{from:Math.max(s.from,Math.min(a,l)),to:Math.min(s.to,Math.max(a,l))}}function JJ(n,e,t){if(t.to<=n.viewport.from||t.from>=n.viewport.to)return[];let s=Math.max(t.from,n.viewport.from),i=Math.min(t.to,n.viewport.to),r=n.textDirection==It.LTR,o=n.contentDOM,a=o.getBoundingClientRect(),l=iN(n),c=o.querySelector(".cm-line"),h=c&&window.getComputedStyle(c),u=a.left+(h?parseInt(h.paddingLeft)+Math.min(0,parseInt(h.textIndent)):0),d=a.right-(h?parseInt(h.paddingRight):0),p=L_(n,s,1),m=L_(n,i,-1),y=p.type==Wn.Text?p:null,v=m.type==Wn.Text?m:null;if(y&&(n.lineWrapping||p.widgetLineBreaks)&&(y=dC(n,s,1,y)),v&&(n.lineWrapping||m.widgetLineBreaks)&&(v=dC(n,i,-1,v)),y&&v&&y.from==v.from&&y.to==v.to)return b(_(t.from,t.to,y));{let A=y?_(t.from,null,y):x(p,!1),C=v?_(null,t.to,v):x(m,!0),$=[];return(y||p).to<(v||m).from-(y&&v?1:0)||p.widgetLineBreaks>1&&A.bottom+n.defaultLineHeight/2B&&D.from=te)break;z>X&&L(Math.max(ye,X),A==null&&ye<=B,Math.min(z,te),C==null&&z>=H,Y.dir)}if(X=J.to+1,X>=te)break}return q.length==0&&L(B,A==null,H,C==null,n.textDirection),{top:I,bottom:j,horizontal:q}}function x(A,C){let $=a.top+(C?A.top:A.bottom);return{top:$,bottom:$,horizontal:[]}}}function QJ(n,e){return n.constructor==e.constructor&&n.eq(e)}class eQ{constructor(e,t){this.view=e,this.layer=t,this.drawn=[],this.scaleX=1,this.scaleY=1,this.measureReq={read:this.measure.bind(this),write:this.draw.bind(this)},this.dom=e.scrollDOM.appendChild(document.createElement("div")),this.dom.classList.add("cm-layer"),t.above&&this.dom.classList.add("cm-layer-above"),t.class&&this.dom.classList.add(t.class),this.scale(),this.dom.setAttribute("aria-hidden","true"),this.setOrder(e.state),e.requestMeasure(this.measureReq),t.mount&&t.mount(this.dom,e)}update(e){e.startState.facet(Yg)!=e.state.facet(Yg)&&this.setOrder(e.state),(this.layer.update(e,this.dom)||e.geometryChanged)&&(this.scale(),e.view.requestMeasure(this.measureReq))}docViewUpdate(e){this.layer.updateOnDocViewUpdate!==!1&&e.requestMeasure(this.measureReq)}setOrder(e){let t=0,s=e.facet(Yg);for(;t!QJ(t,this.drawn[s]))){let t=this.dom.firstChild,s=0;for(let i of e)i.update&&t&&i.constructor&&this.drawn[s].constructor&&i.update(t,this.drawn[s])?(t=t.nextSibling,s++):this.dom.insertBefore(i.draw(),t);for(;t;){let i=t.nextSibling;t.remove(),t=i}this.drawn=e,de.webkit&&(this.dom.style.display=this.dom.firstChild?"":"none")}}destroy(){this.layer.destroy&&this.layer.destroy(this.dom,this.view),this.dom.remove()}}const Yg=be.define();function rN(n){return[ii.define(e=>new eQ(e,n)),Yg.of(n)]}const Pu=be.define({combine(n){return Bu(n,{cursorBlinkRate:1200,drawRangeCursor:!0,iosSelectionHandles:!0},{cursorBlinkRate:(e,t)=>Math.min(e,t),drawRangeCursor:(e,t)=>e||t})}});function tQ(n={}){return[Pu.of(n),nQ,sQ,rQ,TO.of(!0)]}function oN(n){return n.startState.facet(Pu)!=n.state.facet(Pu)}const nQ=rN({above:!0,markers(n){let{state:e}=n,t=e.facet(Pu),s=[];for(let i of e.selection.ranges){let r=i==e.selection.main;if(i.empty||t.drawRangeCursor&&!(r&&de.ios&&t.iosSelectionHandles)){let o=r?"cm-cursor cm-cursor-primary":"cm-cursor cm-cursor-secondary",a=i.empty?i:ne.cursor(i.head,i.assoc);for(let l of oc.forRange(n,o,a))s.push(l)}}return s},update(n,e){n.transactions.some(s=>s.selection)&&(e.style.animationName=e.style.animationName=="cm-blink"?"cm-blink2":"cm-blink");let t=oN(n);return t&&fC(n.state,e),n.docChanged||n.selectionSet||t},mount(n,e){fC(e.state,n)},class:"cm-cursorLayer"});function fC(n,e){e.style.animationDuration=n.facet(Pu).cursorBlinkRate+"ms"}const sQ=rN({above:!1,markers(n){let e=[],{main:t,ranges:s}=n.state.selection;for(let i of s)if(!i.empty)for(let r of oc.forRange(n,"cm-selectionBackground",i))e.push(r);if(de.ios&&!t.empty&&n.state.facet(Pu).iosSelectionHandles){for(let i of oc.forRange(n,"cm-selectionHandle cm-selectionHandle-start",ne.cursor(t.from,1)))e.push(i);for(let i of oc.forRange(n,"cm-selectionHandle cm-selectionHandle-end",ne.cursor(t.to,1)))e.push(i)}return e},update(n,e){return n.docChanged||n.selectionSet||n.viewportChanged||oN(n)},class:"cm-selectionLayer"}),iQ=de.gecko&&de.gecko_version==153?"#ffffff01":"transparent",rQ=V0.highest(xe.theme({".cm-line":{"& ::selection, &::selection":{backgroundColor:`${iQ} !important`},caretColor:"transparent !important"},".cm-content":{caretColor:"transparent !important","& :focus":{caretColor:"initial !important","&::selection, & ::selection":{backgroundColor:"Highlight !important"}}}}));function oQ(){return lQ}const aQ=Qe.line({class:"cm-activeLine"}),lQ=ii.fromClass(class{constructor(n){this.decorations=this.getDeco(n)}update(n){(n.docChanged||n.selectionSet)&&(this.decorations=this.getDeco(n.view))}getDeco(n){let e=-1,t=[];for(let s of n.state.selection.ranges){let i=n.lineBlockAt(s.head);i.from>e&&(t.push(aQ.range(i.from)),e=i.from)}return Qe.set(t)}},{decorations:n=>n.decorations}),pC=be.define({combine(n){let e,t;for(let s of n)e=e||s.topContainer,t=t||s.bottomContainer;return{topContainer:e,bottomContainer:t}}});function aN(n,e){let t=n.plugin(lN),s=t?t.specs.indexOf(e):-1;return s>-1?t.panels[s]:null}const lN=ii.fromClass(class{constructor(n){this.input=n.state.facet(Ly),this.specs=this.input.filter(t=>t),this.panels=this.specs.map(t=>t(n));let e=n.state.facet(pC);this.top=new Ym(n,!0,e.topContainer),this.bottom=new Ym(n,!1,e.bottomContainer),this.top.sync(this.panels.filter(t=>t.top)),this.bottom.sync(this.panels.filter(t=>!t.top));for(let t of this.panels)t.dom.classList.add("cm-panel"),t.mount&&t.mount()}update(n){let e=n.state.facet(pC);this.top.container!=e.topContainer&&(this.top.sync([]),this.top=new Ym(n.view,!0,e.topContainer)),this.bottom.container!=e.bottomContainer&&(this.bottom.sync([]),this.bottom=new Ym(n.view,!1,e.bottomContainer)),this.top.syncClasses(),this.bottom.syncClasses();let t=n.state.facet(Ly);if(t!=this.input){let s=t.filter(l=>l),i=[],r=[],o=[],a=[];for(let l of s){let c=this.specs.indexOf(l),h;c<0?(h=l(n.view),a.push(h)):(h=this.panels[c],h.update&&h.update(n)),i.push(h),(h.top?r:o).push(h)}this.specs=s,this.panels=i,this.top.sync(r),this.bottom.sync(o);for(let l of a)l.dom.classList.add("cm-panel"),l.mount&&l.mount()}else for(let s of this.panels)s.update&&s.update(n)}destroy(){this.top.sync([]),this.bottom.sync([])}},{provide:n=>xe.scrollMargins.of(e=>{let t=e.plugin(n);return t&&{top:t.top.scrollMargin(),bottom:t.bottom.scrollMargin()}})});class Ym{constructor(e,t,s){this.view=e,this.top=t,this.container=s,this.dom=void 0,this.classes="",this.panels=[],this.syncClasses()}sync(e){for(let t of this.panels)t.destroy&&e.indexOf(t)<0&&t.destroy();this.panels=e,this.syncDOM()}syncDOM(){if(this.panels.length==0){this.dom&&(this.dom.remove(),this.dom=void 0);return}if(!this.dom){this.dom=document.createElement("div"),this.dom.className=this.top?"cm-panels cm-panels-top":"cm-panels cm-panels-bottom";let t=this.container||this.view.dom;t.insertBefore(this.dom,this.top?t.firstChild:null)}let e=this.dom.firstChild;for(let t of this.panels)if(t.dom.parentNode==this.dom){for(;e!=t.dom;)e=mC(e);e=e.nextSibling}else this.dom.insertBefore(t.dom,e);for(;e;)e=mC(e)}scrollMargin(){return!this.dom||this.container?0:Math.max(0,this.top?this.dom.getBoundingClientRect().bottom-Math.max(0,this.view.scrollDOM.getBoundingClientRect().top):Math.min(innerHeight,this.view.scrollDOM.getBoundingClientRect().bottom)-this.dom.getBoundingClientRect().top)}syncClasses(){if(!(!this.container||this.classes==this.view.themeClasses)){for(let e of this.classes.split(" "))e&&this.container.classList.remove(e);for(let e of(this.classes=this.view.themeClasses).split(" "))e&&this.container.classList.add(e)}}}function mC(n){let e=n.nextSibling;return n.remove(),e}const Ly=be.define({enables:lN});function cQ(n,e){let t,s=new Promise(o=>t=o),i=o=>hQ(o,e,t);n.state.field(Wv,!1)?n.dispatch({effects:cN.of(i)}):n.dispatch({effects:_t.appendConfig.of(Wv.init(()=>[i]))});let r=hN.of(i);return{close:r,result:s.then(o=>((n.win.queueMicrotask||(l=>n.win.setTimeout(l,10)))(()=>{n.state.field(Wv).indexOf(i)>-1&&n.dispatch({effects:r})}),o))}}const Wv=Fr.define({create(){return[]},update(n,e){for(let t of e.effects)t.is(cN)?n=[t.value].concat(n):t.is(hN)&&(n=n.filter(s=>s!=t.value));return n},provide:n=>Ly.computeN([n],e=>e.field(n))}),cN=_t.define(),hN=_t.define();function hQ(n,e,t){let s=e.content?e.content(n,()=>o(null)):null;if(!s){if(s=Cn("form"),e.input){let a=Cn("input",e.input);/^(text|password|number|email|tel|url)$/.test(a.type)&&a.classList.add("cm-textfield"),a.name||(a.name="input"),s.appendChild(Cn("label",(e.label||"")+": ",a))}else s.appendChild(document.createTextNode(e.label||""));s.appendChild(document.createTextNode(" ")),s.appendChild(Cn("button",{class:"cm-button",type:"submit"},e.submitLabel||"OK"))}let i=s.nodeName=="FORM"?[s]:s.querySelectorAll("form");for(let a=0;a{c.keyCode==27?(c.preventDefault(),o(null)):c.keyCode==13&&(c.preventDefault(),o(l))}),l.addEventListener("submit",c=>{c.preventDefault(),o(l)})}let r=Cn("div",s,Cn("button",{onclick:()=>o(null),"aria-label":n.state.phrase("close"),class:"cm-dialog-close",type:"button"},["×"]));e.class&&(r.className=e.class),r.classList.add("cm-dialog");function o(a){r.contains(r.ownerDocument.activeElement)&&n.focus(),t(a)}return{dom:r,top:e.top,mount:()=>{if(e.focus){let a;typeof e.focus=="string"?a=s.querySelector(e.focus):a=s.querySelector("input")||s.querySelector("button"),a&&"select"in a?a.select():a&&"focus"in a&&a.focus()}}}}class Sc extends vc{compare(e){return this==e||this.constructor==e.constructor&&this.eq(e)}eq(e){return!1}destroy(e){}}Sc.prototype.elementClass="";Sc.prototype.toDOM=void 0;Sc.prototype.mapMode=ni.TrackBefore;Sc.prototype.startSide=Sc.prototype.endSide=-1;Sc.prototype.point=!0;const Gv=be.define(),uQ=be.define(),Jg=be.define(),gC=be.define({combine:n=>n.some(e=>e)});function dQ(n){return[fQ]}const fQ=ii.fromClass(class{constructor(n){this.view=n,this.domAfter=null,this.prevViewport=n.viewport,this.dom=document.createElement("div"),this.dom.className="cm-gutters cm-gutters-before",this.dom.setAttribute("aria-hidden","true"),this.dom.style.minHeight=this.view.contentHeight/this.view.scaleY+"px",this.gutters=n.state.facet(Jg).map(e=>new vC(n,e)),this.fixed=!n.state.facet(gC);for(let e of this.gutters)e.config.side=="after"?this.getDOMAfter().appendChild(e.dom):this.dom.appendChild(e.dom);this.fixed&&(this.dom.style.position="sticky"),this.syncGutters(!1),n.scrollDOM.insertBefore(this.dom,n.contentDOM)}getDOMAfter(){return this.domAfter||(this.domAfter=document.createElement("div"),this.domAfter.className="cm-gutters cm-gutters-after",this.domAfter.setAttribute("aria-hidden","true"),this.domAfter.style.minHeight=this.view.contentHeight/this.view.scaleY+"px",this.domAfter.style.position=this.fixed?"sticky":"",this.view.scrollDOM.appendChild(this.domAfter)),this.domAfter}update(n){if(this.updateGutters(n)){let e=this.prevViewport,t=n.view.viewport,s=Math.min(e.to,t.to)-Math.max(e.from,t.from);this.syncGutters(s<(t.to-t.from)*.8)}if(n.geometryChanged){let e=this.view.contentHeight/this.view.scaleY+"px";this.dom.style.minHeight=e,this.domAfter&&(this.domAfter.style.minHeight=e)}this.view.state.facet(gC)!=!this.fixed&&(this.fixed=!this.fixed,this.dom.style.position=this.fixed?"sticky":"",this.domAfter&&(this.domAfter.style.position=this.fixed?"sticky":"")),this.prevViewport=n.view.viewport}syncGutters(n){let e=this.dom.nextSibling;n&&(this.dom.remove(),this.domAfter&&this.domAfter.remove());let t=rt.iter(this.view.state.facet(Gv),this.view.viewport.from),s=[],i=this.gutters.map(r=>new pQ(r,this.view.viewport,-this.view.documentPadding.top));for(let r of this.view.viewportLineBlocks)if(s.length&&(s=[]),Array.isArray(r.type)){let o=!0;for(let a of r.type)if(a.type==Wn.Text&&o){U_(t,s,a.from);for(let l of i)l.line(this.view,a,s);o=!1}else if(a.widget)for(let l of i)l.widget(this.view,a)}else if(r.type==Wn.Text){U_(t,s,r.from);for(let o of i)o.line(this.view,r,s)}else if(r.widget)for(let o of i)o.widget(this.view,r);for(let r of i)r.finish();n&&(this.view.scrollDOM.insertBefore(this.dom,e),this.domAfter&&this.view.scrollDOM.appendChild(this.domAfter))}updateGutters(n){let e=n.startState.facet(Jg),t=n.state.facet(Jg),s=n.docChanged||n.heightChanged||n.viewportChanged||!rt.eq(n.startState.facet(Gv),n.state.facet(Gv),n.view.viewport.from,n.view.viewport.to);if(e==t)for(let i of this.gutters)i.update(n)&&(s=!0);else{s=!0;let i=[];for(let r of t){let o=e.indexOf(r);o<0?i.push(new vC(this.view,r)):(this.gutters[o].update(n),i.push(this.gutters[o]))}for(let r of this.gutters)r.dom.remove(),i.indexOf(r)<0&&r.destroy();for(let r of i)r.config.side=="after"?this.getDOMAfter().appendChild(r.dom):this.dom.appendChild(r.dom);this.gutters=i}return s}destroy(){for(let n of this.gutters)n.destroy();this.dom.remove(),this.domAfter&&this.domAfter.remove()}},{provide:n=>xe.scrollMargins.of(e=>{let t=e.plugin(n);if(!t||t.gutters.length==0||!t.fixed)return null;let s=t.dom.offsetWidth*e.scaleX,i=t.domAfter?t.domAfter.offsetWidth*e.scaleX:0;return e.textDirection==It.LTR?{left:s,right:i}:{right:s,left:i}})});function yC(n){return Array.isArray(n)?n:[n]}function U_(n,e,t){for(;n.value&&n.from<=t;)n.from==t&&e.push(n.value),n.next()}class pQ{constructor(e,t,s){this.gutter=e,this.height=s,this.i=0,this.cursor=rt.iter(e.markers,t.from)}addElement(e,t,s){let{gutter:i}=this,r=(t.top-this.height)/e.scaleY,o=t.height/e.scaleY;if(this.i==i.elements.length){let a=new uN(e,o,r,s);i.elements.push(a),i.dom.appendChild(a.dom)}else i.elements[this.i].update(e,o,r,s);this.height=t.bottom,this.i++}line(e,t,s){let i=[];U_(this.cursor,i,t.from),s.length&&(i=i.concat(s));let r=this.gutter.config.lineMarker(e,t,i);r&&i.unshift(r);let o=this.gutter;i.length==0&&!o.config.renderEmptyElements||this.addElement(e,t,i)}widget(e,t){let s=this.gutter.config.widgetMarker(e,t.widget,t),i=s?[s]:null;for(let r of e.state.facet(uQ)){let o=r(e,t.widget,t);o&&(i||(i=[])).push(o)}i&&this.addElement(e,t,i)}finish(){let e=this.gutter;for(;e.elements.length>this.i;){let t=e.elements.pop();e.dom.removeChild(t.dom),t.destroy()}}}class vC{constructor(e,t){this.view=e,this.config=t,this.elements=[],this.spacer=null,this.dom=document.createElement("div"),this.dom.className="cm-gutter"+(this.config.class?" "+this.config.class:"");for(let s in t.domEventHandlers)this.dom.addEventListener(s,i=>{let r=i.target,o;if(r!=this.dom&&this.dom.contains(r)){for(;r.parentNode!=this.dom;)r=r.parentNode;let l=r.getBoundingClientRect();o=(l.top+l.bottom)/2}else o=i.clientY;let a=e.lineBlockAtHeight(o-e.documentTop);t.domEventHandlers[s](e,a,i)&&i.preventDefault()});this.markers=yC(t.markers(e)),t.initialSpacer&&(this.spacer=new uN(e,0,0,[t.initialSpacer(e)]),this.dom.appendChild(this.spacer.dom),this.spacer.dom.style.cssText+="visibility: hidden; pointer-events: none")}update(e){let t=this.markers;if(this.markers=yC(this.config.markers(e.view)),this.spacer&&this.config.updateSpacer){let i=this.config.updateSpacer(this.spacer.markers[0],e);i!=this.spacer.markers[0]&&this.spacer.update(e.view,0,0,[i])}let s=e.view.viewport;return!rt.eq(this.markers,t,s.from,s.to)||(this.config.lineMarkerChange?this.config.lineMarkerChange(e):!1)}destroy(){for(let e of this.elements)e.destroy()}}class uN{constructor(e,t,s,i){this.height=-1,this.above=0,this.markers=[],this.dom=document.createElement("div"),this.dom.className="cm-gutterElement",this.update(e,t,s,i)}update(e,t,s,i){this.height!=t&&(this.height=t,this.dom.style.height=t+"px"),this.above!=s&&(this.dom.style.marginTop=(this.above=s)?s+"px":""),mQ(this.markers,i)||this.setMarkers(e,i)}setMarkers(e,t){let s="cm-gutterElement",i=this.dom.firstChild;for(let r=0,o=0;;){let a=o,l=rr(a,l,c)||o(a,l,c):o}return s}})}});class Kv extends Sc{constructor(e){super(),this.number=e}eq(e){return this.number==e.number}toDOM(){return document.createTextNode(this.number)}}function Zv(n,e){return n.state.facet(rh).formatNumber(e,n.state)}const vQ=Jg.compute([rh],n=>({class:"cm-lineNumbers",renderEmptyElements:!1,markers(e){return e.state.facet(gQ)},lineMarker(e,t,s){return s.some(i=>i.toDOM)?null:new Kv(Zv(e,e.state.doc.lineAt(t.from).number))},widgetMarker:(e,t,s)=>{for(let i of e.state.facet(yQ)){let r=i(e,t,s);if(r)return r}return null},lineMarkerChange:e=>e.startState.facet(rh)!=e.state.facet(rh),initialSpacer(e){return new Kv(Zv(e,bC(e.state.doc.lines)))},updateSpacer(e,t){let s=Zv(t.view,bC(t.view.state.doc.lines));return s==e.number?e:new Kv(s)},domEventHandlers:n.facet(rh).domEventHandlers,side:"before"}));function bQ(n={}){return[rh.of(n),dQ(),vQ]}function bC(n){let e=9;for(;e{throw new Error("This node type doesn't define a deserialize function")}),this.combine=e.combine||null}add(e){if(this.perNode)throw new RangeError("Can't add per-node props to node types");return typeof e!="function"&&(e=zs.match(e)),t=>{let s=e(t);return s===void 0?null:[this,s]}}}nt.closedBy=new nt({deserialize:n=>n.split(" ")});nt.openedBy=new nt({deserialize:n=>n.split(" ")});nt.group=new nt({deserialize:n=>n.split(" ")});nt.isolate=new nt({deserialize:n=>{if(n&&n!="rtl"&&n!="ltr"&&n!="auto")throw new RangeError("Invalid value for isolate: "+n);return n||"auto"}});nt.contextHash=new nt({perNode:!0});nt.lookAhead=new nt({perNode:!0});nt.mounted=new nt({perNode:!0});class tf{constructor(e,t,s,i=!1){this.tree=e,this.overlay=t,this.parser=s,this.bracketed=i}static get(e){return e&&e.props&&e.props[nt.mounted.id]}}const SQ=Object.create(null);class zs{constructor(e,t,s,i=0){this.name=e,this.props=t,this.id=s,this.flags=i}static define(e){let t=e.props&&e.props.length?Object.create(null):SQ,s=(e.top?1:0)|(e.skipped?2:0)|(e.error?4:0)|(e.name==null?8:0),i=new zs(e.name||"",t,e.id,s);if(e.props){for(let r of e.props)if(Array.isArray(r)||(r=r(i)),r){if(r[0].perNode)throw new RangeError("Can't store a per-node prop on a node type");t[r[0].id]=r[1]}}return i}prop(e){return this.props[e.id]}get isTop(){return(this.flags&1)>0}get isSkipped(){return(this.flags&2)>0}get isError(){return(this.flags&4)>0}get isAnonymous(){return(this.flags&8)>0}is(e){if(typeof e=="string"){if(this.name==e)return!0;let t=this.prop(nt.group);return t?t.indexOf(e)>-1:!1}return this.id==e}static match(e){let t=Object.create(null);for(let s in e)for(let i of s.split(" "))t[i]=e[s];return s=>{for(let i=s.prop(nt.group),r=-1;r<(i?i.length:0);r++){let o=t[r<0?s.name:i[r]];if(o)return o}}}}zs.none=new zs("",Object.create(null),0,8);class Yx{constructor(e){this.types=e;for(let t=0;t0;for(let l=this.cursor(o|Jt.IncludeAnonymous);;){let c=!1;if(l.from<=r&&l.to>=i&&(!a&&l.type.isAnonymous||t(l)!==!1)){if(l.firstChild())continue;c=!0}for(;c&&s&&(a||!l.type.isAnonymous)&&s(l),!l.nextSibling();){if(!l.parent())return;c=!0}}}prop(e){return e.perNode?this.props?this.props[e.id]:void 0:this.type.prop(e)}get propValues(){let e=[];if(this.props)for(let t in this.props)e.push([+t,this.props[t]]);return e}balance(e={}){return this.children.length<=8?this:eA(zs.none,this.children,this.positions,0,this.children.length,0,this.length,(t,s,i)=>new Ot(this.type,t,s,i,this.propValues),e.makeTree||((t,s,i)=>new Ot(zs.none,t,s,i)))}static build(e){return EQ(e)}}Ot.empty=new Ot(zs.none,[],[],0);class Jx{constructor(e,t){this.buffer=e,this.index=t}get id(){return this.buffer[this.index-4]}get start(){return this.buffer[this.index-3]}get end(){return this.buffer[this.index-2]}get size(){return this.buffer[this.index-1]}get pos(){return this.index}next(){this.index-=4}fork(){return new Jx(this.buffer,this.index)}}class Ia{constructor(e,t,s){this.buffer=e,this.length=t,this.set=s}get type(){return zs.none}toString(){let e=[];for(let t=0;t0));l=o[l+3]);return a}slice(e,t,s){let i=this.buffer,r=new Uint16Array(t-e),o=0;for(let a=e,l=0;a=e&&te;case 1:return t<=e&&s>e;case 2:return s>e;case 4:return!0}}function vf(n,e,t,s){for(var i;n.from==n.to||(t<1?n.from>=e:n.from>e)||(t>-1?n.to<=e:n.to0?a.length:-1;e!=c;e+=t){let h=a[e],u=l[e]+o.from,d;if(!(!(r&Jt.EnterBracketed&&h instanceof Ot&&(d=tf.get(h))&&!d.overlay&&d.bracketed&&s>=u&&s<=u+h.length)&&!dN(i,s,u,u+h.length))){if(h instanceof Ia){if(r&Jt.ExcludeBuffers)continue;let p=h.findChild(0,h.buffer.length,t,s-u,i);if(p>-1)return new xa(new xQ(o,h,e,u),null,p)}else if(r&Jt.IncludeAnonymous||!h.type.isAnonymous||Qx(h)){let p;if(!(r&Jt.IgnoreMounts)&&(p=tf.get(h))&&!p.overlay)return new wi(p.tree,u,e,o);let m=new wi(h,u,e,o);return r&Jt.IncludeAnonymous||!m.type.isAnonymous?m:m.nextChild(t<0?h.children.length-1:0,t,s,i,r)}}}if(r&Jt.IncludeAnonymous||!o.type.isAnonymous||(o.index>=0?e=o.index+t:e=t<0?-1:o._parent._tree.children.length,o=o._parent,!o))return null}}get firstChild(){return this.nextChild(0,1,0,4)}get lastChild(){return this.nextChild(this._tree.children.length-1,-1,0,4)}childAfter(e){return this.nextChild(0,1,e,2)}childBefore(e){return this.nextChild(this._tree.children.length-1,-1,e,-2)}prop(e){return this._tree.prop(e)}enter(e,t,s=0){let i;if(!(s&Jt.IgnoreOverlays)&&(i=tf.get(this._tree))&&i.overlay){let r=e-this.from,o=s&Jt.EnterBracketed&&i.bracketed;for(let{from:a,to:l}of i.overlay)if((t>0||o?a<=r:a=r:l>r))return new wi(i.tree,i.overlay[0].from+this.from,-1,this)}return this.nextChild(0,1,e,t,s)}nextSignificantParent(){let e=this;for(;e.type.isAnonymous&&e._parent;)e=e._parent;return e}get parent(){return this._parent?this._parent.nextSignificantParent():null}get nextSibling(){return this._parent&&this.index>=0?this._parent.nextChild(this.index+1,1,0,4):null}get prevSibling(){return this._parent&&this.index>=0?this._parent.nextChild(this.index-1,-1,0,4):null}get tree(){return this._tree}toTree(){return this._tree}toString(){return this._tree.toString()}}function _C(n,e,t,s){let i=n.cursor(),r=[];if(!i.firstChild())return r;if(t!=null){for(let o=!1;!o;)if(o=i.type.is(t),!i.nextSibling())return r}for(;;){if(s!=null&&i.type.is(s))return r;if(i.type.is(e)&&r.push(i.node),!i.nextSibling())return s==null?r:[]}}function q_(n,e,t=e.length-1){for(let s=n;t>=0;s=s.parent){if(!s)return!1;if(!s.type.isAnonymous){if(e[t]&&e[t]!=s.name)return!1;t--}}return!0}class xQ{constructor(e,t,s,i){this.parent=e,this.buffer=t,this.index=s,this.start=i}}class xa extends fN{get name(){return this.type.name}get from(){return this.context.start+this.context.buffer.buffer[this.index+1]}get to(){return this.context.start+this.context.buffer.buffer[this.index+2]}constructor(e,t,s){super(),this.context=e,this._parent=t,this.index=s,this.type=e.buffer.set.types[e.buffer.buffer[s]]}child(e,t,s){let{buffer:i}=this.context,r=i.findChild(this.index+4,i.buffer[this.index+3],e,t-this.context.start,s);return r<0?null:new xa(this.context,this,r)}get firstChild(){return this.child(1,0,4)}get lastChild(){return this.child(-1,0,4)}childAfter(e){return this.child(1,e,2)}childBefore(e){return this.child(-1,e,-2)}prop(e){return this.type.prop(e)}enter(e,t,s=0){if(s&Jt.ExcludeBuffers)return null;let{buffer:i}=this.context,r=i.findChild(this.index+4,i.buffer[this.index+3],t>0?1:-1,e-this.context.start,t);return r<0?null:new xa(this.context,this,r)}get parent(){return this._parent||this.context.parent.nextSignificantParent()}externalSibling(e){return this._parent?null:this.context.parent.nextChild(this.context.index+e,e,0,4)}get nextSibling(){let{buffer:e}=this.context,t=e.buffer[this.index+3];return t<(this._parent?e.buffer[this._parent.index+3]:e.buffer.length)?new xa(this.context,this._parent,t):this.externalSibling(1)}get prevSibling(){let{buffer:e}=this.context,t=this._parent?this._parent.index+4:0;return this.index==t?this.externalSibling(-1):new xa(this.context,this._parent,e.findChild(t,this.index,-1,0,4))}get tree(){return null}toTree(){let e=[],t=[],{buffer:s}=this.context,i=this.index+4,r=s.buffer[this.index+3];if(r>i){let o=s.buffer[this.index+1];e.push(s.slice(i,r,o)),t.push(0)}return new Ot(this.type,e,t,this.to-this.from)}toString(){return this.context.buffer.childString(this.index)}}function pN(n){if(!n.length)return null;let e=0,t=n[0];for(let r=1;rt.from||o.to=e){let a=new wi(o.tree,o.overlay[0].from+r.from,-1,r);(i||(i=[s])).push(vf(a,e,t,!1))}}return i?pN(i):s}class V_{get name(){return this.type.name}constructor(e,t=0){if(this.buffer=null,this.stack=[],this.index=0,this.bufferNode=null,this.mode=t&~Jt.EnterBracketed,e instanceof wi)this.yieldNode(e);else{this._tree=e.context.parent,this.buffer=e.context;for(let s=e._parent;s;s=s._parent)this.stack.unshift(s.index);this.bufferNode=e,this.yieldBuf(e.index)}}yieldNode(e){return e?(this._tree=e,this.type=e.type,this.from=e.from,this.to=e.to,!0):!1}yieldBuf(e,t){this.index=e;let{start:s,buffer:i}=this.buffer;return this.type=t||i.set.types[i.buffer[e]],this.from=s+i.buffer[e+1],this.to=s+i.buffer[e+2],!0}yield(e){return e?e instanceof wi?(this.buffer=null,this.yieldNode(e)):(this.buffer=e.context,this.yieldBuf(e.index,e.type)):!1}toString(){return this.buffer?this.buffer.buffer.childString(this.index):this._tree.toString()}enterChild(e,t,s){if(!this.buffer)return this.yield(this._tree.nextChild(e<0?this._tree._tree.children.length-1:0,e,t,s,this.mode));let{buffer:i}=this.buffer,r=i.findChild(this.index+4,i.buffer[this.index+3],e,t-this.buffer.start,s);return r<0?!1:(this.stack.push(this.index),this.yieldBuf(r))}firstChild(){return this.enterChild(1,0,4)}lastChild(){return this.enterChild(-1,0,4)}childAfter(e){return this.enterChild(1,e,2)}childBefore(e){return this.enterChild(-1,e,-2)}enter(e,t,s=this.mode){return this.buffer?s&Jt.ExcludeBuffers?!1:this.enterChild(1,e,t):this.yield(this._tree.enter(e,t,s))}parent(){if(!this.buffer)return this.yieldNode(this.mode&Jt.IncludeAnonymous?this._tree._parent:this._tree.parent);if(this.stack.length)return this.yieldBuf(this.stack.pop());let e=this.mode&Jt.IncludeAnonymous?this.buffer.parent:this.buffer.parent.nextSignificantParent();return this.buffer=null,this.yieldNode(e)}sibling(e){if(!this.buffer)return this._tree._parent?this.yield(this._tree.index<0?null:this._tree._parent.nextChild(this._tree.index+e,e,0,4,this.mode)):!1;let{buffer:t}=this.buffer,s=this.stack.length-1;if(e<0){let i=s<0?0:this.stack[s]+4;if(this.index!=i)return this.yieldBuf(t.findChild(i,this.index,-1,0,4))}else{let i=t.buffer[this.index+3];if(i<(s<0?t.buffer.length:t.buffer[this.stack[s]+3]))return this.yieldBuf(i)}return s<0?this.yield(this.buffer.parent.nextChild(this.buffer.index+e,e,0,4,this.mode)):!1}nextSibling(){return this.sibling(1)}prevSibling(){return this.sibling(-1)}atLastNode(e){let t,s,{buffer:i}=this;if(i){if(e>0){if(this.index-1)for(let r=t+e,o=e<0?-1:s._tree.children.length;r!=o;r+=e){let a=s._tree.children[r];if(this.mode&Jt.IncludeAnonymous||a instanceof Ia||!a.type.isAnonymous||Qx(a))return!1}return!0}move(e,t){if(t&&this.enterChild(e,0,4))return!0;for(;;){if(this.sibling(e))return!0;if(this.atLastNode(e)||!this.parent())return!1}}next(e=!0){return this.move(1,e)}prev(e=!0){return this.move(-1,e)}moveTo(e,t=0){for(;(this.from==this.to||(t<1?this.from>=e:this.from>e)||(t>-1?this.to<=e:this.to=0;){for(let o=e;o;o=o._parent)if(o.index==i){if(i==this.index)return o;t=o,s=r+1;break e}i=this.stack[--r]}for(let i=s;i=0;r--){if(r<0)return q_(this._tree,e,i);let o=s[t.buffer[this.stack[r]]];if(!o.isAnonymous){if(e[i]&&e[i]!=o.name)return!1;i--}}return!0}}function Qx(n){return n.children.some(e=>e instanceof Ia||!e.type.isAnonymous||Qx(e))}function EQ(n){var e;let{buffer:t,nodeSet:s,maxBufferLength:i=wQ,reused:r=[],minRepeatType:o=s.types.length}=n,a=Array.isArray(t)?new Jx(t,t.length):t,l=s.types,c=0,h=0;function u(A,C,$,I,j,q){let{id:L,start:B,end:H,size:D}=a,X=h,te=c;if(D<0)if(a.next(),D==-1){let E=r[L];$.push(E),I.push(B-A);return}else if(D==-3){c=L;return}else if(D==-4){h=L;return}else throw new RangeError(`Unrecognized record size: ${D}`);let J=l[L],Y,ye,z=B-A;if(H-B<=i&&(ye=v(a.pos-C,j))){let E=new Uint16Array(ye.size-ye.skip),O=a.pos-ye.size,R=E.length;for(;a.pos>O;)R=g(ye.start,E,R);Y=new Ia(E,H-ye.start,s),z=ye.start-A}else{let E=a.pos-D;a.next();let O=[],R=[],w=L>=o?L:-1,k=0,N=H;for(;a.pos>E;)w>=0&&a.id==w&&a.size>=0?(a.end<=N-i&&(m(O,R,B,k,a.end,N,w,X,te),k=O.length,N=a.end),a.next()):q>2500?d(B,E,O,R):u(B,E,O,R,w,q+1);if(w>=0&&k>0&&k-1&&k>0){let G=p(J,te);Y=eA(J,O,R,0,O.length,0,H-B,G,G)}else Y=y(J,O,R,H-B,X-H,te)}$.push(Y),I.push(z)}function d(A,C,$,I){let j=[],q=0,L=-1;for(;a.pos>C;){let{id:B,start:H,end:D,size:X}=a;if(X>4)a.next();else{if(L>-1&&H=0;D-=3)B[X++]=j[D],B[X++]=j[D+1]-H,B[X++]=j[D+2]-H,B[X++]=X;$.push(new Ia(B,j[2]-H,s)),I.push(H-A)}}function p(A,C){return($,I,j)=>{let q=0,L=$.length-1,B,H;if(L>=0&&(B=$[L])instanceof Ot){if(!L&&B.type==A&&B.length==j)return B;(H=B.prop(nt.lookAhead))&&(q=I[L]+B.length+H)}return y(A,$,I,j,q,C)}}function m(A,C,$,I,j,q,L,B,H){let D=[],X=[];for(;A.length>I;)D.push(A.pop()),X.push(C.pop()+$-j);A.push(y(s.types[L],D,X,q-j,B-q,H)),C.push(j-$)}function y(A,C,$,I,j,q,L){if(q){let B=[nt.contextHash,q];L=L?[B].concat(L):[B]}if(j>25){let B=[nt.lookAhead,j];L=L?[B].concat(L):[B]}return new Ot(A,C,$,I,L)}function v(A,C){let $=a.fork(),I=0,j=0,q=0,L=$.end-i,B={size:0,start:0,skip:0};e:for(let H=$.pos-A;$.pos>H;){let D=$.size;if($.id==C&&D>=0){B.size=I,B.start=j,B.skip=q,q+=4,I+=4,$.next();continue}let X=$.pos-D;if(D<0||X=o?4:0,J=$.start;for($.next();$.pos>X;){if($.size<0)if($.size==-3||$.size==-4)te+=4;else break e;else $.id>=o&&(te+=4);$.next()}j=J,I+=D,q+=te}return(C<0||I==A)&&(B.size=I,B.start=j,B.skip=q),B.size>4?B:void 0}function g(A,C,$){let{id:I,start:j,end:q,size:L}=a;if(a.next(),L>=0&&I4){let H=a.pos-(L-4);for(;a.pos>H;)$=g(A,C,$)}C[--$]=B,C[--$]=q-A,C[--$]=j-A,C[--$]=I}else L==-3?c=I:L==-4&&(h=I);return $}let b=[],_=[];for(;a.pos>0;)u(n.start||0,n.bufferStart||0,b,_,-1,0);let x=(e=n.length)!==null&&e!==void 0?e:b.length?_[0]+b[0].length:0;return new Ot(l[n.topID],b.reverse(),_.reverse(),x)}const SC=new WeakMap;function Qg(n,e){if(!n.isAnonymous||e instanceof Ia||e.type!=n)return 1;let t=SC.get(e);if(t==null){t=1;for(let s of e.children){if(s.type!=n||!(s instanceof Ot)){t=1;break}t+=Qg(n,s)}SC.set(e,t)}return t}function eA(n,e,t,s,i,r,o,a,l){let c=0;for(let m=s;m=h)break;C+=$}if(_==x+1){if(C>h){let $=m[x];p($.children,$.positions,0,$.children.length,y[x]+b);continue}u.push(m[x])}else{let $=y[_-1]+m[_-1].length-A;u.push(eA(n,m,y,x,_,A,$,null,l))}d.push(A+b-r)}}return p(e,t,s,i,0),(a||l)(u,d,o)}class ac{constructor(e,t,s,i,r=!1,o=!1){this.from=e,this.to=t,this.tree=s,this.offset=i,this.open=(r?1:0)|(o?2:0)}get openStart(){return(this.open&1)>0}get openEnd(){return(this.open&2)>0}static addTree(e,t=[],s=!1){let i=[new ac(0,e.length,e,0,!1,s)];for(let r of t)r.to>e.length&&i.push(r);return i}static applyChanges(e,t,s=128){if(!t.length)return e;let i=[],r=1,o=e.length?e[0]:null;for(let a=0,l=0,c=0;;a++){let h=a=s)for(;o&&o.from=d.from||u<=d.to||c){let p=Math.max(d.from,l)-c,m=Math.min(d.to,u)-c;d=p>=m?null:new ac(p,m,d.tree,d.offset+c,a>0,!!h)}if(d&&i.push(d),o.to>u)break;o=rnew Xv(i.from,i.to)):[new Xv(0,0)]:[new Xv(0,e.length)],this.createParse(e,t||[],s)}parse(e,t,s){let i=this.startParse(e,t,s);for(;;){let r=i.advance();if(r)return r}}}class CQ{constructor(e){this.string=e}get length(){return this.string.length}chunk(e){return this.string.slice(e)}get lineChunks(){return!1}read(e,t){return this.string.slice(e,t)}}new nt({perNode:!0});let $Q=0;class mi{constructor(e,t,s,i){this.name=e,this.set=t,this.base=s,this.modified=i,this.id=$Q++}toString(){let{name:e}=this;for(let t of this.modified)t.name&&(e=`${t.name}(${e})`);return e}static define(e,t){let s=typeof e=="string"?e:"?";if(e instanceof mi&&(t=e),t!=null&&t.base)throw new Error("Can not derive from a modified tag");let i=new mi(s,[],null,[]);if(i.set.push(i),t)for(let r of t.set)i.set.push(r);return i}static defineModifier(e){let t=new Dy(e);return s=>s.modified.indexOf(t)>-1?s:Dy.get(s.base||s,s.modified.concat(t).sort((i,r)=>i.id-r.id))}}let TQ=0;class Dy{constructor(e){this.name=e,this.instances=[],this.id=TQ++}static get(e,t){if(!t.length)return e;let s=t[0].instances.find(a=>a.base==e&&PQ(t,a.modified));if(s)return s;let i=[],r=new mi(e.name,i,e,t);for(let a of t)a.instances.push(r);let o=RQ(t);for(let a of e.set)if(!a.modified.length)for(let l of o)i.push(Dy.get(a,l));return r}}function PQ(n,e){return n.length==e.length&&n.every((t,s)=>t==e[s])}function RQ(n){let e=[[]];for(let t=0;ts.length-t.length)}function MQ(n){let e=Object.create(null);for(let t in n){let s=n[t];Array.isArray(s)||(s=[s]);for(let i of t.split(" "))if(i){let r=[],o=2,a=i;for(let u=0;;){if(a=="..."&&u>0&&u+3==i.length){o=1;break}let d=/^"(?:[^"\\]|\\.)*?"|[^\/!]+/.exec(a);if(!d)throw new RangeError("Invalid path: "+i);if(r.push(d[0]=="*"?"":d[0][0]=='"'?JSON.parse(d[0]):d[0]),u+=d[0].length,u==i.length)break;let p=i[u++];if(u==i.length&&p=="!"){o=0;break}if(p!="/")throw new RangeError("Invalid path: "+i);a=i.slice(u)}let l=r.length-1,c=r[l];if(!c)throw new RangeError("Invalid path: "+i);let h=new jy(s,o,l>0?r.slice(0,l):null);e[c]=h.sort(e[c])}}return IQ.add(e)}const IQ=new nt({combine(n,e){let t,s,i;for(;n||e;){if(!n||e&&n.depth>=e.depth?(i=e,e=e.next):(i=n,n=n.next),t&&t.mode==i.mode&&!i.context&&!t.context)continue;let r=new jy(i.tags,i.mode,i.context);t?t.next=r:s=r,t=r}return s}});class jy{constructor(e,t,s,i){this.tags=e,this.mode=t,this.context=s,this.next=i}get opaque(){return this.mode==0}get inherit(){return this.mode==1}sort(e){return!e||e.depth{let o=i;for(let a of r)for(let l of a.set){let c=t[l.id];if(c){o=o?o+" "+c:c;break}}return o},scope:s}}const he=mi.define,Qm=he(),zo=he(),xC=he(zo),AC=he(zo),Ho=he(),eg=he(Ho),Yv=he(Ho),or=he(),Va=he(or),ir=he(),rr=he(),W_=he(),cd=he(W_),tg=he(),ze={comment:Qm,lineComment:he(Qm),blockComment:he(Qm),docComment:he(Qm),name:zo,variableName:he(zo),typeName:xC,tagName:he(xC),propertyName:AC,attributeName:he(AC),className:he(zo),labelName:he(zo),namespace:he(zo),macroName:he(zo),literal:Ho,string:eg,docString:he(eg),character:he(eg),attributeValue:he(eg),number:Yv,integer:he(Yv),float:he(Yv),bool:he(Ho),regexp:he(Ho),escape:he(Ho),color:he(Ho),url:he(Ho),keyword:ir,self:he(ir),null:he(ir),atom:he(ir),unit:he(ir),modifier:he(ir),operatorKeyword:he(ir),controlKeyword:he(ir),definitionKeyword:he(ir),moduleKeyword:he(ir),operator:rr,derefOperator:he(rr),arithmeticOperator:he(rr),logicOperator:he(rr),bitwiseOperator:he(rr),compareOperator:he(rr),updateOperator:he(rr),definitionOperator:he(rr),typeOperator:he(rr),controlOperator:he(rr),punctuation:W_,separator:he(W_),bracket:cd,angleBracket:he(cd),squareBracket:he(cd),paren:he(cd),brace:he(cd),content:or,heading:Va,heading1:he(Va),heading2:he(Va),heading3:he(Va),heading4:he(Va),heading5:he(Va),heading6:he(Va),contentSeparator:he(or),list:he(or),quote:he(or),emphasis:he(or),strong:he(or),link:he(or),monospace:he(or),strikethrough:he(or),inserted:he(),deleted:he(),changed:he(),invalid:he(),meta:tg,documentMeta:he(tg),annotation:he(tg),processingInstruction:he(tg),definition:mi.defineModifier("definition"),constant:mi.defineModifier("constant"),function:mi.defineModifier("function"),standard:mi.defineModifier("standard"),local:mi.defineModifier("local"),special:mi.defineModifier("special")};for(let n in ze){let e=ze[n];e instanceof mi&&(e.name=n)}OQ([{tag:ze.link,class:"tok-link"},{tag:ze.heading,class:"tok-heading"},{tag:ze.emphasis,class:"tok-emphasis"},{tag:ze.strong,class:"tok-strong"},{tag:ze.keyword,class:"tok-keyword"},{tag:ze.atom,class:"tok-atom"},{tag:ze.bool,class:"tok-bool"},{tag:ze.url,class:"tok-url"},{tag:ze.labelName,class:"tok-labelName"},{tag:ze.inserted,class:"tok-inserted"},{tag:ze.deleted,class:"tok-deleted"},{tag:ze.literal,class:"tok-literal"},{tag:ze.string,class:"tok-string"},{tag:ze.number,class:"tok-number"},{tag:[ze.regexp,ze.escape,ze.special(ze.string)],class:"tok-string2"},{tag:ze.variableName,class:"tok-variableName"},{tag:ze.local(ze.variableName),class:"tok-variableName tok-local"},{tag:ze.definition(ze.variableName),class:"tok-variableName tok-definition"},{tag:ze.special(ze.variableName),class:"tok-variableName2"},{tag:ze.definition(ze.propertyName),class:"tok-propertyName tok-definition"},{tag:ze.typeName,class:"tok-typeName"},{tag:ze.namespace,class:"tok-namespace"},{tag:ze.className,class:"tok-className"},{tag:ze.macroName,class:"tok-macroName"},{tag:ze.propertyName,class:"tok-propertyName"},{tag:ze.operator,class:"tok-operator"},{tag:ze.comment,class:"tok-comment"},{tag:ze.meta,class:"tok-meta"},{tag:ze.invalid,class:"tok-invalid"},{tag:ze.punctuation,class:"tok-punctuation"}]);var Jv;const Nd=new nt;function NQ(n){return be.define({combine:n?e=>e.concat(n):void 0})}const LQ=new nt;class Ir{constructor(e,t,s=[],i=""){this.data=e,this.name=i,at.prototype.hasOwnProperty("tree")||Object.defineProperty(at.prototype,"tree",{get(){return Oa(this)}}),this.parser=t,this.extension=[Iu.of(this),at.languageData.of((r,o,a)=>{let l=kC(r,o,a),c=l.type.prop(Nd);if(!c)return[];let h=r.facet(c),u=l.type.prop(LQ);if(u){let d=l.resolve(o-l.from,a);for(let p of u)if(p.test(d,r)){let m=r.facet(p.facet);return p.type=="replace"?m:m.concat(h)}}return h})].concat(s)}isActiveAt(e,t,s=-1){return kC(e,t,s).type.prop(Nd)==this.data}findRegions(e){let t=e.facet(Iu);if((t==null?void 0:t.data)==this.data)return[{from:0,to:e.doc.length}];if(!t||!t.allowsNesting)return[];let s=[],i=(r,o)=>{if(r.prop(Nd)==this.data){s.push({from:o,to:o+r.length});return}let a=r.prop(nt.mounted);if(a){if(a.tree.prop(Nd)==this.data){if(a.overlay)for(let l of a.overlay)s.push({from:l.from+o,to:l.to+o});else s.push({from:o,to:o+r.length});return}else if(a.overlay){let l=s.length;if(i(a.tree,a.overlay[0].from+o),s.length>l)return}}for(let l=0;l=this.cursorPos?this.doc.sliceString(e,t):this.string.slice(e-s,t-s)}}let hd=null;class Ru{constructor(e,t,s=[],i,r,o,a,l){this.parser=e,this.state=t,this.fragments=s,this.tree=i,this.treeLen=r,this.viewport=o,this.skipped=a,this.scheduleOn=l,this.parse=null,this.tempSkipped=[]}static create(e,t,s){return new Ru(e,t,[],Ot.empty,0,s,[],null)}startParse(){return this.parser.startParse(new DQ(this.state.doc),this.fragments)}work(e,t){return t!=null&&t>=this.state.doc.length&&(t=void 0),this.tree!=Ot.empty&&this.isDone(t??this.state.doc.length)?(this.takeTree(),!0):this.withContext(()=>{var s;if(typeof e=="number"){let i=Date.now()+e;e=()=>Date.now()>i}for(this.parse||(this.parse=this.startParse()),t!=null&&(this.parse.stoppedAt==null||this.parse.stoppedAt>t)&&t=this.treeLen&&((this.parse.stoppedAt==null||this.parse.stoppedAt>e)&&this.parse.stopAt(e),this.withContext(()=>{for(;!(t=this.parse.advance()););}),this.treeLen=e,this.tree=t,this.fragments=this.withoutTempSkipped(ac.addTree(this.tree,this.fragments,!0)),this.parse=null)}withContext(e){let t=hd;hd=this;try{return e()}finally{hd=t}}withoutTempSkipped(e){for(let t;t=this.tempSkipped.pop();)e=EC(e,t.from,t.to);return e}changes(e,t){let{fragments:s,tree:i,treeLen:r,viewport:o,skipped:a}=this;if(this.takeTree(),!e.empty){let l=[];if(e.iterChangedRanges((c,h,u,d)=>l.push({fromA:c,toA:h,fromB:u,toB:d})),s=ac.applyChanges(s,l),i=Ot.empty,r=0,o={from:e.mapPos(o.from,-1),to:e.mapPos(o.to,1)},this.skipped.length){a=[];for(let c of this.skipped){let h=e.mapPos(c.from,1),u=e.mapPos(c.to,-1);he.from&&(this.fragments=EC(this.fragments,i,r),this.skipped.splice(s--,1))}return this.skipped.length>=t?!1:(this.reset(),!0)}reset(){this.parse&&(this.takeTree(),this.parse=null)}skipUntilInView(e,t){this.skipped.push({from:e,to:t})}static getSkippingParser(e){return new class extends mN{createParse(t,s,i){let r=i[0].from,o=i[i.length-1].to;return{parsedPos:r,advance(){let l=hd;if(l){for(let c of i)l.tempSkipped.push(c);e&&(l.scheduleOn=l.scheduleOn?Promise.all([l.scheduleOn,e]):e)}return this.parsedPos=o,new Ot(zs.none,[],[],o-r)},stoppedAt:null,stopAt(){}}}}}isDone(e){e=Math.min(e,this.state.doc.length);let t=this.fragments;return this.treeLen>=e&&t.length&&t[0].from==0&&t[0].to>=e}static get(){return hd}}function EC(n,e,t){return ac.applyChanges(n,[{fromA:e,toA:t,fromB:e,toB:t}])}class Mu{constructor(e){this.context=e,this.tree=e.tree}apply(e){if(!e.docChanged&&this.tree==this.context.tree)return this;let t=this.context.changes(e.changes,e.state),s=this.context.treeLen==e.startState.doc.length?void 0:Math.max(e.changes.mapPos(this.context.treeLen),t.viewport.to);return t.work(20,s)||t.takeTree(),new Mu(t)}static init(e){let t=Math.min(3e3,e.doc.length),s=Ru.create(e.facet(Iu).parser,e,{from:0,to:t});return s.work(20,t)||s.takeTree(),new Mu(s)}}Ir.state=Fr.define({create:Mu.init,update(n,e){for(let t of e.effects)if(t.is(Ir.setState))return t.value;return e.startState.facet(Iu)!=e.state.facet(Iu)?Mu.init(e.state):n.apply(e)}});let gN=n=>{let e=setTimeout(()=>n(),500);return()=>clearTimeout(e)};typeof requestIdleCallback<"u"&&(gN=n=>{let e=-1,t=setTimeout(()=>{e=requestIdleCallback(n,{timeout:400})},100);return()=>e<0?clearTimeout(t):cancelIdleCallback(e)});const Qv=typeof navigator<"u"&&(!((Jv=navigator.scheduling)===null||Jv===void 0)&&Jv.isInputPending)?()=>navigator.scheduling.isInputPending():null,jQ=ii.fromClass(class{constructor(e){this.view=e,this.working=null,this.workScheduled=0,this.chunkEnd=-1,this.chunkBudget=-1,this.work=this.work.bind(this),this.scheduleWork()}update(e){let t=this.view.state.field(Ir.state).context;(t.updateViewport(e.view.viewport)||this.view.viewport.to>t.treeLen)&&this.scheduleWork(),(e.docChanged||e.selectionSet)&&(this.view.hasFocus&&(this.chunkBudget+=50),this.scheduleWork()),this.checkAsyncSchedule(t)}scheduleWork(){if(this.working)return;let{state:e}=this.view,t=e.field(Ir.state);(t.tree!=t.context.tree||!t.context.isDone(e.doc.length))&&(this.working=gN(this.work))}work(e){this.working=null;let t=Date.now();if(this.chunkEndi+1e3,l=r.context.work(()=>Qv&&Qv()||Date.now()>o,i+(a?0:1e5));this.chunkBudget-=Date.now()-t,(l||this.chunkBudget<=0)&&(r.context.takeTree(),this.view.dispatch({effects:Ir.setState.of(new Mu(r.context))})),this.chunkBudget>0&&!(l&&!a)&&this.scheduleWork(),this.checkAsyncSchedule(r.context)}checkAsyncSchedule(e){e.scheduleOn&&(this.workScheduled++,e.scheduleOn.then(()=>this.scheduleWork()).catch(t=>Mr(this.view.state,t)).then(()=>this.workScheduled--),e.scheduleOn=null)}destroy(){this.working&&this.working()}isWorking(){return!!(this.working||this.workScheduled>0)}},{eventHandlers:{focus(){this.scheduleWork()}}}),Iu=be.define({combine(n){return n.length?n[0]:null},enables:n=>[Ir.state,jQ,xe.contentAttributes.compute([n],e=>{let t=e.facet(n);return t&&t.name?{"data-language":t.name}:{}})]}),FQ=be.define(),tA=be.define({combine:n=>{if(!n.length)return" ";let e=n[0];if(!e||/\S/.test(e)||Array.from(e).some(t=>t!=e[0]))throw new Error("Invalid indent unit: "+JSON.stringify(n[0]));return e}});function xc(n){let e=n.facet(tA);return e.charCodeAt(0)==9?n.tabSize*e.length:e.length}function Fy(n,e){let t="",s=n.tabSize,i=n.facet(tA)[0];if(i==" "){for(;e>=s;)t+=" ",e-=s;i=" "}for(let r=0;r=e?zQ(n,t,e):null}class Q0{constructor(e,t={}){this.state=e,this.options=t,this.unit=xc(e)}lineAt(e,t=1){let s=this.state.doc.lineAt(e),{simulateBreak:i,simulateDoubleBreak:r}=this.options;return i!=null&&i>=s.from&&i<=s.to?r&&i==e?{text:"",from:e}:(t<0?i-1&&(r+=o-this.countColumn(s,s.search(/\S|$/))),r}countColumn(e,t=e.length){return W0(e,this.state.tabSize,t)}lineIndent(e,t=1){let{text:s,from:i}=this.lineAt(e,t),r=this.options.overrideIndentation;if(r){let o=r(i);if(o>-1)return o}return this.countColumn(s,s.search(/\S|$/))}get simulatedBreak(){return this.options.simulateBreak||null}}const vN=new nt;function zQ(n,e,t){let s=e.resolveStack(t),i=e.resolveInner(t,-1).resolve(t,0).enterUnfinishedNodesBefore(t);if(i!=s.node){let r=[];for(let o=i;o&&!(o.froms.node.to||o.from==s.node.from&&o.type==s.node.type);o=o.parent)r.push(o);for(let o=r.length-1;o>=0;o--)s={node:r[o],next:s}}return bN(s,n,t)}function bN(n,e,t){for(let s=n;s;s=s.next){let i=BQ(s.node);if(i)return i(nA.create(e,t,s))}return 0}function HQ(n){return n.pos==n.options.simulateBreak&&n.options.simulateDoubleBreak}function BQ(n){let e=n.type.prop(vN);if(e)return e;let t=n.firstChild,s;if(t&&(s=t.type.prop(nt.closedBy))){let i=n.lastChild,r=i&&s.indexOf(i.name)>-1;return o=>WQ(o,!0,1,void 0,r&&!HQ(o)?i.from:void 0)}return n.parent==null?UQ:null}function UQ(){return 0}class nA extends Q0{constructor(e,t,s){super(e.state,e.options),this.base=e,this.pos=t,this.context=s}get node(){return this.context.node}static create(e,t,s){return new nA(e,t,s)}get textAfter(){return this.textAfterPos(this.pos)}get baseIndent(){return this.baseIndentFor(this.node)}baseIndentFor(e){let t=this.state.doc.lineAt(e.from);for(;;){let s=e.resolve(t.from);for(;s.parent&&s.parent.from==s.from;)s=s.parent;if(qQ(s,e))break;t=this.state.doc.lineAt(s.from)}return this.lineIndent(t.from)}continue(){return bN(this.context.next,this.base,this.pos)}}function qQ(n,e){for(let t=e;t;t=t.parent)if(n==t)return!0;return!1}function VQ(n){let e=n.node,t=e.childAfter(e.from),s=e.lastChild;if(!t)return null;let i=n.options.simulateBreak,r=n.state.doc.lineAt(t.from),o=i==null||i<=r.from?r.to:Math.min(r.to,i);for(let a=t.to;;){let l=e.childAfter(a);if(!l||l==s)return null;if(!l.type.isSkipped){if(l.from>=o)return null;let c=/^ */.exec(r.text.slice(t.to-r.from))[0].length;return{from:t.from,to:t.to+c}}a=l.to}}function WQ(n,e,t,s,i){let r=n.textAfter,o=r.match(/^\s*/)[0].length,a=s&&r.slice(o,o+s.length)==s||i==n.pos+o,l=VQ(n);return l?a?n.column(l.from):n.column(l.to):n.baseIndent+(a?0:n.unit*t)}const GQ=xe.baseTheme({"&.cm-focused .cm-matchingBracket":{backgroundColor:"#328c8252"},"&.cm-focused .cm-nonmatchingBracket":{backgroundColor:"#bb555544"}}),wN=1e4,_N="()[]{}",SN=be.define({combine(n){return Bu(n,{afterCursor:!0,brackets:_N,maxScanDistance:wN,renderMatch:XQ})}}),KQ=Qe.mark({class:"cm-matchingBracket"}),ZQ=Qe.mark({class:"cm-nonmatchingBracket"});function XQ(n){let e=[],t=n.matched?KQ:ZQ;return e.push(t.range(n.start.from,n.start.to)),n.end&&e.push(t.range(n.end.from,n.end.to)),e}function CC(n){let e=[],t=n.facet(SN);for(let s of n.selection.ranges){if(!s.empty)continue;let i=Or(n,s.head,-1,t)||s.head>0&&Or(n,s.head-1,1,t)||t.afterCursor&&(Or(n,s.head,1,t)||s.headn.decorations}),JQ=[YQ,GQ];function QQ(n={}){return[SN.of(n),JQ]}const eee=new nt;function G_(n,e,t){let s=n.prop(e<0?nt.openedBy:nt.closedBy);if(s)return s;if(n.name.length==1){let i=t.indexOf(n.name);if(i>-1&&i%2==(e<0?1:0))return[t[i+e]]}return null}function K_(n){let e=n.type.prop(eee);return e?e(n.node):n}function Or(n,e,t,s={}){let i=s.maxScanDistance||wN,r=s.brackets||_N,o=Oa(n),a=o.resolveInner(e,t);for(let l=a;l;l=l.parent){let c=G_(l.type,t,r);if(c&&l.from0?e>=h.from&&eh.from&&e<=h.to))return tee(n,e,t,l,h,c,r)}}return nee(n,e,t,o,a.type,i,r)}function tee(n,e,t,s,i,r,o){let a=s.parent,l={from:i.from,to:i.to},c=0,h=a==null?void 0:a.cursor();if(h&&(t<0?h.childBefore(s.from):h.childAfter(s.to)))do if(t<0?h.to<=s.from:h.from>=s.to){if(c==0&&r.indexOf(h.type.name)>-1&&h.from0)return null;let c={from:t<0?e-1:e,to:t>0?e+1:e},h=n.doc.iterRange(e,t>0?n.doc.length:0),u=0;for(let d=0;!h.next().done&&d<=r;){let p=h.value;t<0&&(d+=p.length);let m=e+d*t;for(let y=t>0?0:p.length-1,v=t>0?p.length:-1;y!=v;y+=t){let g=o.indexOf(p[y]);if(!(g<0||s.resolveInner(m+y,1).type!=i))if(g%2==0==t>0)u++;else{if(u==1)return{start:c,end:{from:m+y,to:m+y+1},matched:g>>1==l>>1};u--}}t>0&&(d+=p.length)}return h.done?{start:c,matched:!1}:null}function $C(n,e,t,s=0,i=0){e==null&&(e=n.search(/[^\s\u00a0]/),e==-1&&(e=n.length));let r=i;for(let o=s;o=this.string.length}sol(){return this.pos==0}peek(){return this.string.charAt(this.pos)||void 0}next(){if(this.post}eatSpace(){let e=this.pos;for(;/[\s\u00a0]/.test(this.string.charAt(this.pos));)++this.pos;return this.pos>e}skipToEnd(){this.pos=this.string.length}skipTo(e){let t=this.string.indexOf(e,this.pos);if(t>-1)return this.pos=t,!0}backUp(e){this.pos-=e}column(){return this.lastColumnPoss?o.toLowerCase():o,r=this.string.substr(this.pos,e.length);return i(r)==i(e)?(t!==!1&&(this.pos+=e.length),!0):null}else{let i=this.string.slice(this.pos).match(e);return i&&i.index>0?null:(i&&t!==!1&&(this.pos+=i[0].length),i)}}current(){return this.string.slice(this.start,this.pos)}}function see(n){return{name:n.name||"",token:n.token,blankLine:n.blankLine||(()=>{}),startState:n.startState||(()=>!0),copyState:n.copyState||iee,indent:n.indent||(()=>null),languageData:n.languageData||{},tokenTable:n.tokenTable||rA,mergeTokens:n.mergeTokens!==!1}}function iee(n){if(typeof n!="object")return n;let e={};for(let t in n){let s=n[t];e[t]=s instanceof Array?s.slice():s}return e}const TC=new WeakMap;class sA extends Ir{constructor(e){let t=NQ(e.languageData),s=see(e),i,r=new class extends mN{createParse(o,a,l){return new oee(i,o,a,l)}};super(t,r,[],e.name),this.topNode=cee(t,this),i=this,this.streamParser=s,this.stateAfter=new nt({perNode:!0}),this.tokenTable=e.tokenTable?new CN(s.tokenTable):lee}static define(e){return new sA(e)}getIndent(e){let t,{overrideIndentation:s}=e.options;s&&(t=TC.get(e.state),t!=null&&t1e4)return null;for(;r=s&&t+e.length<=i&&e.prop(n.stateAfter);if(r)return{state:n.streamParser.copyState(r),pos:t+e.length};for(let o=e.children.length-1;o>=0;o--){let a=e.children[o],l=t+e.positions[o],c=a instanceof Ot&&l=e.length)return e;!i&&t==0&&e.type==n.topNode&&(i=!0);for(let r=e.children.length-1;r>=0;r--){let o=e.positions[r],a=e.children[r],l;if(ot&&iA(n,r.tree,0-r.offset,t,a),c;if(l&&l.pos<=s&&(c=AN(n,r.tree,t+r.offset,l.pos+r.offset,!1)))return{state:l.state,tree:c}}return{state:n.streamParser.startState(i?xc(i):4),tree:Ot.empty}}class oee{constructor(e,t,s,i){this.lang=e,this.input=t,this.fragments=s,this.ranges=i,this.stoppedAt=null,this.chunks=[],this.chunkPos=[],this.chunk=[],this.chunkReused=void 0,this.rangeIndex=0,this.to=i[i.length-1].to;let r=Ru.get(),o=i[0].from,{state:a,tree:l}=ree(e,s,o,this.to,r==null?void 0:r.state);this.state=a,this.parsedPos=this.chunkStart=o+l.length;for(let c=0;cc.from<=r.viewport.from&&c.to>=r.viewport.from)&&(this.state=this.lang.streamParser.startState(xc(r.state)),r.skipUntilInView(this.parsedPos,r.viewport.from),this.parsedPos=r.viewport.from),this.moveRangeIndex()}advance(){let e=Ru.get(),t=this.stoppedAt==null?this.to:Math.min(this.to,this.stoppedAt),s=Math.min(t,this.chunkStart+512);for(e&&(s=Math.min(s,e.viewport.to));this.parsedPos=t?this.finish():e&&this.parsedPos>=e.viewport.to?(e.skipUntilInView(this.parsedPos,t),this.finish()):null}stopAt(e){this.stoppedAt=e}lineAfter(e){let t=this.input.chunk(e);if(this.input.lineChunks)t==` +`&&(t="");else{let s=t.indexOf(` +`);s>-1&&(t=t.slice(0,s))}return e+t.length<=this.to?t:t.slice(0,this.to-e)}nextLine(){let e=this.parsedPos,t=this.lineAfter(e),s=e+t.length;for(let i=this.rangeIndex;;){let r=this.ranges[i].to;if(r>=s||(t=t.slice(0,r-(s-t.length)),i++,i==this.ranges.length))break;let o=this.ranges[i].from,a=this.lineAfter(o);t+=a,s=o+a.length}return{line:t,end:s}}skipGapsTo(e,t,s){for(;;){let i=this.ranges[this.rangeIndex].to,r=e+t;if(s>0?i>r:i>=r)break;let o=this.ranges[++this.rangeIndex].from;t+=o-i}return t}moveRangeIndex(){for(;this.ranges[this.rangeIndex].to1){i=this.skipGapsTo(t,i,1),t+=i;let a=this.chunk.length;i=this.skipGapsTo(s,i,-1),s+=i,r+=this.chunk.length-a}let o=this.chunk.length-4;return this.lang.streamParser.mergeTokens&&r==4&&o>=0&&this.chunk[o]==e&&this.chunk[o+2]==t?this.chunk[o+2]=s:this.chunk.push(e,t,s,r),i}parseLine(e){let{line:t,end:s}=this.nextLine(),i=0,{streamParser:r}=this.lang,o=new xN(t,e?e.state.tabSize:4,e?xc(e.state):2);if(o.eol())r.blankLine(this.state,o.indentUnit);else for(;!o.eol();){let a=kN(r.token,o,this.state);if(a&&(i=this.emitToken(this.lang.tokenTable.resolve(a),this.parsedPos+o.start,this.parsedPos+o.pos,i)),o.start>1e4)break}this.parsedPos=s,this.moveRangeIndex(),this.parsedPose.start)return i}throw new Error("Stream parser failed to advance stream.")}const rA=Object.create(null),bf=[zs.none],aee=new Yx(bf),PC=[],RC=Object.create(null),EN=Object.create(null);for(let[n,e]of[["variable","variableName"],["variable-2","variableName.special"],["string-2","string.special"],["def","variableName.definition"],["tag","tagName"],["attribute","attributeName"],["type","typeName"],["builtin","variableName.standard"],["qualifier","modifier"],["error","invalid"],["header","heading"],["property","propertyName"]])EN[n]=$N(rA,e);class CN{constructor(e){this.extra=e,this.table=Object.assign(Object.create(null),EN)}resolve(e){return e?this.table[e]||(this.table[e]=$N(this.extra,e)):0}}const lee=new CN(rA);function eb(n,e){PC.indexOf(n)>-1||(PC.push(n),console.warn(e))}function $N(n,e){let t=[];for(let a of e.split(" ")){let l=[];for(let c of a.split(".")){let h=n[c]||ze[c];h?typeof h=="function"?l.length?l=l.map(h):eb(c,`Modifier ${c} used at start of tag`):l.length?eb(c,`Tag ${c} used as modifier`):l=Array.isArray(h)?h:[h]:eb(c,`Unknown highlighting tag ${c}`)}for(let c of l)t.push(c)}if(!t.length)return 0;let s=e.replace(/ /g,"_"),i=s+" "+t.map(a=>a.id),r=RC[i];if(r)return r.id;let o=RC[i]=zs.define({id:bf.length,name:s,props:[MQ({[s]:t})]});return bf.push(o),o.id}function cee(n,e){let t=zs.define({id:bf.length,name:"Document",props:[Nd.add(()=>n),vN.add(()=>s=>e.getIndent(s))],top:!0});return bf.push(t),t}It.RTL,It.LTR;const hee=n=>{let{state:e}=n,t=e.doc.lineAt(e.selection.main.from),s=aA(n.state,t.from);return s.line?uee(n):s.block?fee(n):!1};function oA(n,e){return({state:t,dispatch:s})=>{if(t.readOnly)return!1;let i=n(e,t);return i?(s(t.update(i)),!0):!1}}const uee=oA(gee,0),dee=oA(TN,0),fee=oA((n,e)=>TN(n,e,mee(e)),0);function aA(n,e){let t=n.languageDataAt("commentTokens",e,1);return t.length?t[0]:{}}const ud=50;function pee(n,{open:e,close:t},s,i){let r=n.sliceDoc(s-ud,s),o=n.sliceDoc(i,i+ud),a=/\s*$/.exec(r)[0].length,l=/^\s*/.exec(o)[0].length,c=r.length-a;if(r.slice(c-e.length,c)==e&&o.slice(l,l+t.length)==t)return{open:{pos:s-a,margin:a&&1},close:{pos:i+l,margin:l&&1}};let h,u;i-s<=2*ud?h=u=n.sliceDoc(s,i):(h=n.sliceDoc(s,s+ud),u=n.sliceDoc(i-ud,i));let d=/^\s*/.exec(h)[0].length,p=/\s*$/.exec(u)[0].length,m=u.length-p-t.length;return h.slice(d,d+e.length)==e&&u.slice(m,m+t.length)==t?{open:{pos:s+d+e.length,margin:/\s/.test(h.charAt(d+e.length))?1:0},close:{pos:i-p-t.length,margin:/\s/.test(u.charAt(m-1))?1:0}}:null}function mee(n){let e=[];for(let t of n.selection.ranges){let s=n.doc.lineAt(t.from),i=t.to<=s.to?s:n.doc.lineAt(t.to);i.from>s.from&&i.from==t.to&&(i=t.to==s.to+1?s:n.doc.lineAt(t.to-1));let r=e.length-1;r>=0&&e[r].to>s.from?e[r].to=i.to:e.push({from:s.from+/^\s*/.exec(s.text)[0].length,to:i.to})}return e}function TN(n,e,t=e.selection.ranges){let s=t.map(r=>aA(e,r.from).block);if(!s.every(r=>r))return null;let i=t.map((r,o)=>pee(e,s[o],r.from,r.to));if(n!=2&&!i.every(r=>r))return{changes:e.changes(t.map((r,o)=>i[o]?[]:[{from:r.from,insert:s[o].open+" "},{from:r.to,insert:" "+s[o].close}]))};if(n!=1&&i.some(r=>r)){let r=[];for(let o=0,a;oi&&(r==o||o>u.from)){i=u.from;let d=/^\s*/.exec(u.text)[0].length,p=d==u.length,m=u.text.slice(d,d+c.length)==c?d:-1;dr.comment<0&&(!r.empty||r.single))){let r=[];for(let{line:a,token:l,indent:c,empty:h,single:u}of s)(u||!h)&&r.push({from:a.from+c,insert:l+" "});let o=e.changes(r);return{changes:o,selection:e.selection.map(o,1)}}else if(n!=1&&s.some(r=>r.comment>=0)){let r=[];for(let{line:o,comment:a,token:l}of s)if(a>=0){let c=o.from+a,h=c+l.length;o.text[h-o.from]==" "&&h++,r.push({from:c,to:h})}return{changes:r}}return null}const Z_=ja.define(),yee=ja.define(),vee=be.define(),PN=be.define({combine(n){return Bu(n,{minDepth:100,newGroupDelay:500,joinToEvent:(e,t)=>t},{minDepth:Math.max,newGroupDelay:Math.min,joinToEvent:(e,t)=>(s,i)=>e(s,i)||t(s,i)})}}),RN=Fr.define({create(){return Nr.empty},update(n,e){let t=e.state.facet(PN),s=e.annotation(Z_);if(s){let l=js.fromTransaction(e,s.selection),c=s.side,h=c==0?n.undone:n.done;return l?h=zy(h,h.length,t.minDepth,l):h=ON(h,e.startState.selection),new Nr(c==0?s.rest:h,c==0?h:s.rest)}let i=e.annotation(yee);if((i=="full"||i=="before")&&(n=n.isolate()),e.annotation(bn.addToHistory)===!1)return e.changes.empty?n:n.addMapping(e.changes.desc);let r=js.fromTransaction(e),o=e.annotation(bn.time),a=e.annotation(bn.userEvent);return r?n=n.addChanges(r,o,a,t,e):e.selection&&(n=n.addSelection(e.startState.selection,o,a,t.newGroupDelay)),(i=="full"||i=="after")&&(n=n.isolate()),n},toJSON(n){return{done:n.done.map(e=>e.toJSON()),undone:n.undone.map(e=>e.toJSON())}},fromJSON(n){return new Nr(n.done.map(js.fromJSON),n.undone.map(js.fromJSON))}});function bee(n={}){return[RN,PN.of(n),xe.domEventHandlers({beforeinput(e,t){let s=e.inputType=="historyUndo"?MN:e.inputType=="historyRedo"?X_:null;return s?(e.preventDefault(),s(t)):!1}})]}function ev(n,e){return function({state:t,dispatch:s}){if(!e&&t.readOnly)return!1;let i=t.field(RN,!1);if(!i)return!1;let r=i.pop(n,t,e);return r?(s(r),!0):!1}}const MN=ev(0,!1),X_=ev(1,!1),wee=ev(0,!0),_ee=ev(1,!0);class js{constructor(e,t,s,i,r){this.changes=e,this.effects=t,this.mapped=s,this.startSelection=i,this.selectionsAfter=r}setSelAfter(e){return new js(this.changes,this.effects,this.mapped,this.startSelection,e)}toJSON(){var e,t,s;return{changes:(e=this.changes)===null||e===void 0?void 0:e.toJSON(),mapped:(t=this.mapped)===null||t===void 0?void 0:t.toJSON(),startSelection:(s=this.startSelection)===null||s===void 0?void 0:s.toJSON(),selectionsAfter:this.selectionsAfter.map(i=>i.toJSON())}}static fromJSON(e){return new js(e.changes&&gn.fromJSON(e.changes),[],e.mapped&&Lr.fromJSON(e.mapped),e.startSelection&&ne.fromJSON(e.startSelection),e.selectionsAfter.map(ne.fromJSON))}static fromTransaction(e,t){let s=bi;for(let i of e.startState.facet(vee)){let r=i(e);r.length&&(s=s.concat(r))}return!s.length&&e.changes.empty?null:new js(e.changes.invert(e.startState.doc),s,void 0,t||e.startState.selection,bi)}static selection(e){return new js(void 0,bi,void 0,void 0,e)}}function zy(n,e,t,s){let i=e+1>t+20?e-t-1:0,r=n.slice(i,e);return r.push(s),r}function See(n,e){let t=[],s=!1;return n.iterChangedRanges((i,r)=>t.push(i,r)),e.iterChangedRanges((i,r,o,a)=>{for(let l=0;l=c&&o<=h&&(s=!0)}}),s}function xee(n,e){return n.ranges.length==e.ranges.length&&n.ranges.filter((t,s)=>t.empty!=e.ranges[s].empty).length===0}function IN(n,e){return n.length?e.length?n.concat(e):n:e}const bi=[],Aee=200;function ON(n,e){if(n.length){let t=n[n.length-1],s=t.selectionsAfter.slice(Math.max(0,t.selectionsAfter.length-Aee));return s.length&&s[s.length-1].eq(e)?n:(s.push(e),zy(n,n.length-1,1e9,t.setSelAfter(s)))}else return[js.selection([e])]}function kee(n){let e=n[n.length-1],t=n.slice();return t[n.length-1]=e.setSelAfter(e.selectionsAfter.slice(0,e.selectionsAfter.length-1)),t}function tb(n,e){if(!n.length)return n;let t=n.length,s=bi;for(;t;){let i=Eee(n[t-1],e,s);if(i.changes&&!i.changes.empty||i.effects.length){let r=n.slice(0,t);return r[t-1]=i,r}else e=i.mapped,t--,s=i.selectionsAfter}return s.length?[js.selection(s)]:bi}function Eee(n,e,t){let s=IN(n.selectionsAfter.length?n.selectionsAfter.map(a=>a.map(e)):bi,t);if(!n.changes)return js.selection(s);let i=n.changes.map(e),r=e.mapDesc(n.changes,!0),o=n.mapped?n.mapped.composeDesc(r):r;return new js(i,_t.mapEffects(n.effects,e),o,n.startSelection.map(r),s)}const Cee=/^(input\.type|delete)($|\.)/;class Nr{constructor(e,t,s=0,i=void 0){this.done=e,this.undone=t,this.prevTime=s,this.prevUserEvent=i}isolate(){return this.prevTime?new Nr(this.done,this.undone):this}addChanges(e,t,s,i,r){let o=this.done,a=o[o.length-1];return a&&a.changes&&!a.changes.empty&&e.changes&&(!s||Cee.test(s))&&(!a.selectionsAfter.length&&t-this.prevTime0&&t-this.prevTimet.empty?n.moveByChar(t,e):tv(t,e))}function cs(n){return n.textDirectionAt(n.state.selection.main.head)==It.LTR}const LN=n=>NN(n,!cs(n)),DN=n=>NN(n,cs(n));function jN(n,e){return tr(n,t=>t.empty?n.moveByGroup(t,e):tv(t,e))}const Tee=n=>jN(n,!cs(n)),Pee=n=>jN(n,cs(n));function Ree(n,e,t){if(e.type.prop(t))return!0;let s=e.to-e.from;return s&&(s>2||/[^\s,.;:]/.test(n.sliceDoc(e.from,e.to)))||e.firstChild}function nv(n,e,t){let s=Oa(n).resolveInner(e.head),i=t?nt.closedBy:nt.openedBy;for(let l=e.head;;){let c=t?s.childAfter(l):s.childBefore(l);if(!c)break;Ree(n,c,i)?s=c:l=t?c.to:c.from}let r=s.type.prop(i),o,a;return r&&(o=t?Or(n,s.from,1):Or(n,s.to,-1))&&o.matched?a=t?o.end.to:o.end.from:a=t?s.to:s.from,ne.cursor(a,t?-1:1)}const Mee=n=>tr(n,e=>nv(n.state,e,!cs(n))),Iee=n=>tr(n,e=>nv(n.state,e,cs(n)));function FN(n,e){return tr(n,t=>{if(!t.empty)return tv(t,e);let s=n.moveVertically(t,e);return s.head!=t.head?s:n.moveToLineBoundary(t,e)})}const zN=n=>FN(n,!1),HN=n=>FN(n,!0);function BN(n){let e=n.scrollDOM.clientHeighto.empty?n.moveVertically(o,e,t.height):tv(o,e));if(i.eq(s.selection))return!1;let r;if(t.selfScroll){let o=n.coordsAtPos(s.selection.main.head),a=n.scrollDOM.getBoundingClientRect(),l=a.top+t.marginTop,c=a.bottom-t.marginBottom;o&&o.top>l&&o.bottomUN(n,!1),Y_=n=>UN(n,!0);function Fa(n,e,t){let s=n.lineBlockAt(e.head),i=n.moveToLineBoundary(e,t);if(i.head==e.head&&i.head!=(t?s.to:s.from)&&(i=n.moveToLineBoundary(e,t,!1)),!t&&i.head==s.from&&s.length){let r=/^\s*/.exec(n.state.sliceDoc(s.from,Math.min(s.from+100,s.to)))[0].length;r&&e.head!=s.from+r&&(i=ne.cursor(s.from+r))}return i}const Oee=n=>tr(n,e=>Fa(n,e,!0)),Nee=n=>tr(n,e=>Fa(n,e,!1)),Lee=n=>tr(n,e=>Fa(n,e,!cs(n))),Dee=n=>tr(n,e=>Fa(n,e,cs(n))),jee=n=>tr(n,e=>ne.cursor(n.lineBlockAt(e.head).from,1)),Fee=n=>tr(n,e=>ne.cursor(n.lineBlockAt(e.head).to,-1));function zee(n,e,t){let s=!1,i=Uu(n.selection,r=>{let o=Or(n,r.head,-1)||Or(n,r.head,1)||r.head>0&&Or(n,r.head-1,1)||r.headzee(n,e);function ki(n,e,t){let s=Uu(n.state.selection,i=>{i.undirectional&&i.head>=i.anchor!=e&&(i=ne.range(i.head,i.anchor));let r=t(i);return ne.range(i.anchor,r.head,r.goalColumn,r.bidiLevel||void 0,r.assoc)});return s.eq(n.state.selection)?!1:(n.dispatch(er(n.state,s)),!0)}function qN(n,e){return ki(n,e,t=>n.moveByChar(t,e))}const VN=n=>qN(n,!cs(n)),WN=n=>qN(n,cs(n));function GN(n,e){return ki(n,e,t=>n.moveByGroup(t,e))}const Bee=n=>GN(n,!cs(n)),Uee=n=>GN(n,cs(n)),qee=n=>{let e=!cs(n);return ki(n,e,t=>nv(n.state,t,e))},Vee=n=>{let e=cs(n);return ki(n,e,t=>nv(n.state,t,e))};function KN(n,e){return ki(n,e,t=>n.moveVertically(t,e))}const ZN=n=>KN(n,!1),XN=n=>KN(n,!0);function YN(n,e){return ki(n,e,t=>n.moveVertically(t,e,BN(n).height))}const IC=n=>YN(n,!1),OC=n=>YN(n,!0),Wee=n=>ki(n,!0,e=>Fa(n,e,!0)),Gee=n=>ki(n,!1,e=>Fa(n,e,!1)),Kee=n=>{let e=!cs(n);return ki(n,e,t=>Fa(n,t,e))},Zee=n=>{let e=cs(n);return ki(n,e,t=>Fa(n,t,e))},Xee=n=>ki(n,!1,e=>ne.cursor(n.lineBlockAt(e.head).from)),Yee=n=>ki(n,!0,e=>ne.cursor(n.lineBlockAt(e.head).to)),NC=({state:n,dispatch:e})=>(e(er(n,{anchor:0})),!0),LC=({state:n,dispatch:e})=>(e(er(n,{anchor:n.doc.length})),!0),DC=({state:n,dispatch:e})=>(e(er(n,{anchor:n.selection.main.anchor,head:0})),!0),jC=({state:n,dispatch:e})=>(e(er(n,{anchor:n.selection.main.anchor,head:n.doc.length})),!0),Jee=({state:n,dispatch:e})=>(e(n.update({selection:{anchor:0,head:n.doc.length},userEvent:"select"})),!0),Qee=({state:n,dispatch:e})=>{let t=sv(n).map(({from:s,to:i})=>ne.undirectionalRange(s,Math.min(i+1,n.doc.length)));return e(n.update({selection:ne.create(t),userEvent:"select"})),!0},ete=({state:n,dispatch:e})=>{let t=Uu(n.selection,s=>{let i=Oa(n),r=i.resolveStack(s.from,1);if(s.empty){let o=i.resolveStack(s.from,-1);o.node.from>=r.node.from&&o.node.to<=r.node.to&&(r=o)}for(let o=r;o;o=o.next){let{node:a}=o;if((a.from=s.to||a.to>s.to&&a.from<=s.from)&&o.next)return ne.undirectionalRange(a.from,a.to)}return s});return t.eq(n.selection)?!1:(e(er(n,t)),!0)};function JN(n,e){let{state:t}=n,s=t.selection,i=t.selection.ranges.slice();for(let r of t.selection.ranges){let o=t.doc.lineAt(r.head);if(e?o.to0)for(let a=r;;){let l=n.moveVertically(a,e);if(l.heado.to){i.some(c=>c.head==l.head)||i.push(l);break}else{if(l.head==a.head)break;a=l}}}return i.length==s.ranges.length?!1:(n.dispatch(er(t,ne.create(i,i.length-1))),!0)}const tte=n=>JN(n,!1),nte=n=>JN(n,!0),ste=({state:n,dispatch:e})=>{let t=n.selection,s=null;return t.ranges.length>1?s=ne.create([t.main]):t.main.empty||(s=ne.create([ne.cursor(t.main.head)])),s?(e(er(n,s)),!0):!1};function cm(n,e){if(n.state.readOnly)return!1;let t="delete.selection",{state:s}=n,i=s.changeByRange(r=>{let{from:o,to:a}=r;if(o==a){let l=e(r);lo&&(t="delete.forward",l=ng(n,l,!0)),o=Math.min(o,l),a=Math.max(a,l)}else o=ng(n,o,!1),a=ng(n,a,!0);return o==a?{range:r}:{changes:{from:o,to:a},range:ne.cursor(o,oi(n)))s.between(e,e,(i,r)=>{ie&&(e=t?r:i)});return e}const QN=(n,e,t)=>cm(n,s=>{let i=s.from,{state:r}=n,o=r.doc.lineAt(i),a,l;if(t&&!e&&i>o.from&&iQN(n,!1,!0),eL=n=>QN(n,!0,!1),tL=(n,e)=>cm(n,t=>{let s=t.head,{state:i}=n,r=i.doc.lineAt(s),o=i.charCategorizer(s);for(let a=null;;){if(s==(e?r.to:r.from)){s==t.head&&r.number!=(e?i.doc.lines:1)&&(s+=e?1:-1);break}let l=$n(r.text,s-r.from,e)+r.from,c=r.text.slice(Math.min(s,l)-r.from,Math.max(s,l)-r.from),h=o(c);if(a!=null&&h!=a)break;(c!=" "||s!=t.head)&&(a=h),s=l}return s}),nL=n=>tL(n,!1),ite=n=>tL(n,!0),rte=n=>cm(n,e=>{let t=n.lineBlockAt(e.head).to;return e.headcm(n,e=>{let t=n.moveToLineBoundary(e,!1).head;return e.head>t?t:Math.max(0,e.head-1)}),ate=n=>cm(n,e=>{let t=n.moveToLineBoundary(e,!0).head;return e.head{if(n.readOnly)return!1;let t=n.changeByRange(s=>({changes:{from:s.from,to:s.to,insert:lt.of(["",""])},range:ne.cursor(s.from)}));return e(n.update(t,{scrollIntoView:!0,userEvent:"input"})),!0},cte=({state:n,dispatch:e})=>{if(n.readOnly)return!1;let t=n.changeByRange(s=>{if(!s.empty||s.from==0||s.from==n.doc.length)return{range:s};let i=s.from,r=n.doc.lineAt(i),o=i==r.from?i-1:$n(r.text,i-r.from,!1)+r.from,a=i==r.to?i+1:$n(r.text,i-r.from,!0)+r.from;return{changes:{from:o,to:a,insert:n.doc.slice(i,a).append(n.doc.slice(o,i))},range:ne.cursor(a)}});return t.changes.empty?!1:(e(n.update(t,{scrollIntoView:!0,userEvent:"move.character"})),!0)};function sv(n){let e=[],t=-1;for(let s of n.selection.ranges){let i=n.doc.lineAt(s.from),r=n.doc.lineAt(s.to);if(!s.empty&&s.to==r.from&&(r=n.doc.lineAt(s.to-1)),t>=i.number){let o=e[e.length-1];o.to=r.to,o.ranges.push(s)}else e.push({from:i.from,to:r.to,ranges:[s]});t=r.number+1}return e}function sL(n,e,t){if(n.readOnly)return!1;let s=[],i=[];for(let r of sv(n)){if(t?r.to==n.doc.length:r.from==0)continue;let o=n.doc.lineAt(t?r.to+1:r.from-1),a=o.length+1;if(t){s.push({from:r.to,to:o.to},{from:r.from,insert:o.text+n.lineBreak});for(let l of r.ranges)i.push(ne.range(Math.min(n.doc.length,l.anchor+a),Math.min(n.doc.length,l.head+a)))}else{s.push({from:o.from,to:r.from},{from:r.to,insert:n.lineBreak+o.text});for(let l of r.ranges)i.push(ne.range(l.anchor-a,l.head-a))}}return s.length?(e(n.update({changes:s,scrollIntoView:!0,selection:ne.create(i,n.selection.mainIndex),userEvent:"move.line"})),!0):!1}const hte=({state:n,dispatch:e})=>sL(n,e,!1),ute=({state:n,dispatch:e})=>sL(n,e,!0);function iL(n,e,t){if(n.readOnly)return!1;let s=[];for(let r of sv(n))t?s.push({from:r.from,insert:n.doc.slice(r.from,r.to)+n.lineBreak}):s.push({from:r.to,insert:n.lineBreak+n.doc.slice(r.from,r.to)});let i=n.changes(s);return e(n.update({changes:i,selection:n.selection.map(i,t?1:-1),scrollIntoView:!0,userEvent:"input.copyline"})),!0}const dte=({state:n,dispatch:e})=>iL(n,e,!1),fte=({state:n,dispatch:e})=>iL(n,e,!0),pte=n=>{if(n.state.readOnly)return!1;let{state:e}=n,t=e.changes(sv(e).map(({from:i,to:r})=>(i>0?i--:r{let r;if(n.lineWrapping){let o=n.lineBlockAt(i.head),a=n.coordsAtPos(i.head,i.assoc||1);a&&(r=o.bottom+n.documentTop-a.bottom+n.defaultLineHeight/2)}return n.moveVertically(i,!0,r)}).map(t);return n.dispatch({changes:t,selection:s,scrollIntoView:!0,userEvent:"delete.line"}),!0};function mte(n,e){if(/\(\)|\[\]|\{\}/.test(n.sliceDoc(e-1,e+1)))return{from:e,to:e};let t=Oa(n).resolveInner(e),s=t.childBefore(e),i=t.childAfter(e),r;return s&&i&&s.to<=e&&i.from>=e&&(r=s.type.prop(nt.closedBy))&&r.indexOf(i.name)>-1&&n.doc.lineAt(s.to).from==n.doc.lineAt(i.from).from&&!/\S/.test(n.sliceDoc(s.to,i.from))?{from:s.to,to:i.from}:null}const FC=rL(!1),gte=rL(!0);function rL(n){return({state:e,dispatch:t})=>{if(e.readOnly)return!1;let s=e.changeByRange(i=>{let{from:r,to:o}=i,a=e.doc.lineAt(r),l=!n&&r==o&&mte(e,r);n&&(r=o=(o<=a.to?a:e.doc.lineAt(o)).to);let c=new Q0(e,{simulateBreak:r,simulateDoubleBreak:!!l}),h=yN(c,r);for(h==null&&(h=W0(/^\s*/.exec(e.doc.lineAt(r).text)[0],e.tabSize));oa.from&&r{let i=[];for(let o=s.from;o<=s.to;){let a=n.doc.lineAt(o);a.number>t&&(s.empty||s.to>a.from)&&(e(a,i,s),t=a.number),o=a.to+1}let r=n.changes(i);return{changes:i,range:ne.range(r.mapPos(s.anchor,1),r.mapPos(s.head,1))}})}const yte=({state:n,dispatch:e})=>{if(n.readOnly)return!1;let t=Object.create(null),s=new Q0(n,{overrideIndentation:r=>{let o=t[r];return o??-1}}),i=lA(n,(r,o,a)=>{let l=yN(s,r.from);if(l==null)return;/\S/.test(r.text)||(l=0);let c=/^\s*/.exec(r.text)[0],h=Fy(n,l);(c!=h||a.fromn.readOnly?!1:(e(n.update(lA(n,(t,s)=>{s.push({from:t.from,insert:n.facet(tA)})}),{userEvent:"input.indent"})),!0),aL=({state:n,dispatch:e})=>n.readOnly?!1:(e(n.update(lA(n,(t,s)=>{let i=/^\s*/.exec(t.text)[0];if(!i)return;let r=W0(i,n.tabSize),o=0,a=Fy(n,Math.max(0,r-xc(n)));for(;o(n.setTabFocusMode(),!0),bte=[{key:"Ctrl-b",run:LN,shift:VN,preventDefault:!0},{key:"Ctrl-f",run:DN,shift:WN},{key:"Ctrl-p",run:zN,shift:ZN},{key:"Ctrl-n",run:HN,shift:XN},{key:"Ctrl-a",run:jee,shift:Xee},{key:"Ctrl-e",run:Fee,shift:Yee},{key:"Ctrl-d",run:eL},{key:"Ctrl-h",run:J_},{key:"Ctrl-k",run:rte},{key:"Ctrl-Alt-h",run:nL},{key:"Ctrl-o",run:lte},{key:"Ctrl-t",run:cte},{key:"Ctrl-v",run:Y_}],wte=[{key:"ArrowLeft",run:LN,shift:VN,preventDefault:!0},{key:"Mod-ArrowLeft",mac:"Alt-ArrowLeft",run:Tee,shift:Bee,preventDefault:!0},{mac:"Cmd-ArrowLeft",run:Lee,shift:Kee,preventDefault:!0},{key:"ArrowRight",run:DN,shift:WN,preventDefault:!0},{key:"Mod-ArrowRight",mac:"Alt-ArrowRight",run:Pee,shift:Uee,preventDefault:!0},{mac:"Cmd-ArrowRight",run:Dee,shift:Zee,preventDefault:!0},{key:"ArrowUp",run:zN,shift:ZN,preventDefault:!0},{mac:"Cmd-ArrowUp",run:NC,shift:DC},{mac:"Ctrl-ArrowUp",run:MC,shift:IC},{key:"ArrowDown",run:HN,shift:XN,preventDefault:!0},{mac:"Cmd-ArrowDown",run:LC,shift:jC},{mac:"Ctrl-ArrowDown",run:Y_,shift:OC},{key:"PageUp",run:MC,shift:IC},{key:"PageDown",run:Y_,shift:OC},{key:"Home",run:Nee,shift:Gee,preventDefault:!0},{key:"Mod-Home",run:NC,shift:DC},{key:"End",run:Oee,shift:Wee,preventDefault:!0},{key:"Mod-End",run:LC,shift:jC},{key:"Enter",run:FC,shift:FC},{key:"Mod-a",run:Jee},{key:"Backspace",run:J_,shift:J_,preventDefault:!0},{key:"Delete",run:eL,preventDefault:!0},{key:"Mod-Backspace",mac:"Alt-Backspace",run:nL,preventDefault:!0},{key:"Mod-Delete",mac:"Alt-Delete",run:ite,preventDefault:!0},{mac:"Mod-Backspace",run:ote,preventDefault:!0},{mac:"Mod-Delete",run:ate,preventDefault:!0}].concat(bte.map(n=>({mac:n.key,run:n.run,shift:n.shift}))),_te=[{key:"Alt-ArrowLeft",mac:"Ctrl-ArrowLeft",run:Mee,shift:qee},{key:"Alt-ArrowRight",mac:"Ctrl-ArrowRight",run:Iee,shift:Vee},{key:"Alt-ArrowUp",run:hte},{key:"Shift-Alt-ArrowUp",run:dte},{key:"Alt-ArrowDown",run:ute},{key:"Shift-Alt-ArrowDown",run:fte},{key:"Mod-Alt-ArrowUp",run:tte},{key:"Mod-Alt-ArrowDown",run:nte},{key:"Escape",run:ste},{key:"Mod-Enter",run:gte},{key:"Alt-l",mac:"Ctrl-l",run:Qee},{key:"Mod-i",run:ete,preventDefault:!0},{key:"Mod-[",run:aL},{key:"Mod-]",run:oL},{key:"Mod-Alt-\\",run:yte},{key:"Shift-Mod-k",run:pte},{key:"Shift-Mod-\\",run:Hee},{key:"Mod-/",run:hee},{key:"Alt-A",mac:"Ctrl-A",run:dee},{key:"Ctrl-m",mac:"Shift-Alt-m",run:vte}].concat(wte),Ste={key:"Tab",run:oL,shift:aL};function lL(n){function e(u,d){u.cmdState.push(d)}function t(u){return u.cmdState.length>0?u.cmdState[u.cmdState.length-1]:null}function s(u){var d=u.cmdState.pop();d&&d.closeBracket()}function i(u){for(var d=u.cmdState,p=d.length-1;p>=0;p--){var m=d[p];if(m.name!="DEFAULT")return m}return{styleIdentifier:function(){return null}}}function r(u,d,p){return function(){this.name=u,this.bracketNo=0,this.style=d,this.styles=p,this.argument=null,this.styleIdentifier=function(){return this.styles[this.bracketNo-1]||null},this.openBracket=function(){return this.bracketNo++,"bracket"},this.closeBracket=function(){}}}var o={};o.importmodule=r("importmodule","tag",["string","builtin"]),o.documentclass=r("documentclass","tag",["","atom"]),o.usepackage=r("usepackage","tag",["atom"]),o.begin=r("begin","tag",["atom"]),o.end=r("end","tag",["atom"]),o.label=r("label","tag",["atom"]),o.ref=r("ref","tag",["atom"]),o.eqref=r("eqref","tag",["atom"]),o.cite=r("cite","tag",["atom"]),o.bibitem=r("bibitem","tag",["atom"]),o.Bibitem=r("Bibitem","tag",["atom"]),o.RBibitem=r("RBibitem","tag",["atom"]),o.DEFAULT=function(){this.name="DEFAULT",this.style="tag",this.styleIdentifier=this.openBracket=this.closeBracket=function(){}};function a(u,d){u.f=d}function l(u,d){var p;if(u.match(/^\\[a-zA-Z@\xc0-\u1fff\u2060-\uffff]+/)){var m=u.current().slice(1);return p=o.hasOwnProperty(m)?o[m]:o.DEFAULT,p=new p,e(d,p),a(d,h),p.style}if(u.match(/^\\[$&%#{}_]/)||u.match(/^\\[,;!\/\\]/))return"tag";if(u.match("\\["))return a(d,function(v,g){return c(v,g,"\\]")}),"keyword";if(u.match("\\("))return a(d,function(v,g){return c(v,g,"\\)")}),"keyword";if(u.match("$$"))return a(d,function(v,g){return c(v,g,"$$")}),"keyword";if(u.match("$"))return a(d,function(v,g){return c(v,g,"$")}),"keyword";var y=u.next();if(y=="%")return u.skipToEnd(),"comment";if(y=="}"||y=="]"){if(p=t(d),p)p.closeBracket(y),a(d,h);else return"error";return"bracket"}else return y=="{"||y=="["?(p=o.DEFAULT,p=new p,e(d,p),"bracket"):/\d/.test(y)?(u.eatWhile(/[\w.%]/),"atom"):(u.eatWhile(/[\w\-_]/),p=i(d),p.name=="begin"&&(p.argument=u.current()),p.styleIdentifier())}function c(u,d,p){if(u.eatSpace())return null;if(p&&u.match(p))return a(d,l),"keyword";if(u.match(/^\\[a-zA-Z@]+/))return"tag";if(u.match(/^[a-zA-Z]+/))return"variableName.special";if(u.match(/^\\[$&%#{}_]/)||u.match(/^\\[,;!\/]/)||u.match(/^[\^_&]/))return"tag";if(u.match(/^[+\-<>|=,\/@!*:;'"`~#?]/))return null;if(u.match(/^(\d+\.\d*|\d*\.\d+|\d+)/))return"number";var m=u.next();return m=="{"||m=="}"||m=="["||m=="]"||m=="("||m==")"?"bracket":m=="%"?(u.skipToEnd(),"comment"):"error"}function h(u,d){var p=u.peek(),m;return p=="{"||p=="["?(m=t(d),m.openBracket(p),u.eat(p),a(d,l),"bracket"):/[ \t\r]/.test(p)?(u.eat(p),null):(a(d,l),s(d),l(u,d))}return{name:"stex",startState:function(){var u=n?function(d,p){return c(d,p)}:l;return{cmdState:[],f:u}},copyState:function(u){return{cmdState:u.cmdState.slice(),f:u.f}},token:function(u,d){return d.f(u,d)},blankLine:function(u){u.f=l,u.cmdState.length=0},languageData:{commentTokens:{line:"%"}}}}const xte=lL(!1);lL(!0);const zC=typeof String.prototype.normalize=="function"?n=>n.normalize("NFKD"):n=>n;class Ou{constructor(e,t,s=0,i=e.length,r,o){this.test=o,this.value={from:0,to:0,precise:!1},this.done=!1,this.matches=[],this.buffer="",this.bufferPos=0,this.iter=e.iterRange(s,i),this.bufferStart=s,this.normalize=r?a=>r(zC(a)):zC,this.query=this.normalize(t)}peek(){if(this.bufferPos==this.buffer.length){if(this.bufferStart+=this.buffer.length,this.iter.next(),this.iter.done)return-1;this.bufferPos=0,this.buffer=this.iter.value}return VI(this.buffer,this.bufferPos)}next(){for(;this.matches.length;)this.matches.pop();return this.nextOverlapping()}nextOverlapping(){for(;;){let e=this.peek();if(e<0)return this.done=!0,this;let t=KY(e),s=this.bufferStart+this.bufferPos;this.bufferPos+=WI(e);let i=this.normalize(t);if(i.length)for(let r=0,o=s,a=!0;;r++){let l=i.charCodeAt(r),c=this.match(l,o,a,this.bufferPos+this.bufferStart,r==i.length-1);if(c)return this.value=c,this;if(r==i.length-1)break;a&&rthis.to&&(this.curLine=this.curLine.slice(0,this.to-this.curLineStart)),this.iter.next())}nextLine(){this.curLineStart=this.curLineStart+this.curLine.length+1,this.curLineStart>this.to?this.curLine="":this.getLine(0)}next(){for(let e=this.matchPos-this.curLineStart;;){this.re.lastIndex=e;let t=this.matchPos<=this.to&&this.re.exec(this.curLine);if(t){let s=this.curLineStart+t.index,i=s+t[0].length;if(this.matchPos=Hy(this.text,i+(s==i?1:0)),s==this.curLineStart+this.curLine.length&&this.nextLine(),(sthis.value.to)&&(!this.test||this.test(s,i,t)))return this.value={from:s,to:i,precise:!0,match:t},this;e=this.matchPos-this.curLineStart}else if(this.curLineStart+this.curLine.length=s||i.to<=t){let a=new bh(t,e.sliceString(t,s));return nb.set(e,a),a}if(i.from==t&&i.to==s)return i;let{text:r,from:o}=i;return o>t&&(r=e.sliceString(t,o)+r,o=t),i.to=this.to?this.to:this.text.lineAt(e).to}next(){for(;;){let e=this.re.lastIndex=this.matchPos-this.flat.from,t=this.re.exec(this.flat.text);if(t&&!t[0]&&t.index==e&&(this.re.lastIndex=e+1,t=this.re.exec(this.flat.text)),t){let s=this.flat.from+t.index,i=s+t[0].length;if((this.flat.to>=this.to||t.index+t[0].length<=this.flat.text.length-10)&&(!this.test||this.test(s,i,t)))return this.value={from:s,to:i,precise:!0,match:t},this.matchPos=Hy(this.text,i+(s==i?1:0)),this}if(this.flat.to==this.to)return this.done=!0,this;this.flat=bh.get(this.text,this.flat.from,this.chunkEnd(this.flat.from+this.flat.text.length*2))}}}typeof Symbol<"u"&&(hL.prototype[Symbol.iterator]=uL.prototype[Symbol.iterator]=function(){return this});function Ate(n){try{return new RegExp(n,cA),!0}catch{return!1}}function Hy(n,e){if(e>=n.length)return e;let t=n.lineAt(e),s;for(;e=56320&&s<57344;)e++;return e}const kte=n=>{let{state:e}=n,t=String(e.doc.lineAt(n.state.selection.main.head).number),{close:s,result:i}=cQ(n,{label:e.phrase("Go to line"),input:{type:"text",name:"line",value:t},focus:!0,submitLabel:e.phrase("go")});return i.then(r=>{let o=r&&/^([+-])?(\d+)?(:\d+)?(%)?$/.exec(r.elements.line.value);if(!o){n.dispatch({effects:s});return}let a=e.doc.lineAt(e.selection.main.head),[,l,c,h,u]=o,d=h?+h.slice(1):0,p=c?+c:a.number;if(c&&u){let v=p/100;l&&(v=v*(l=="-"?-1:1)+a.number/e.doc.lines),p=Math.round(e.doc.lines*v)}else c&&l&&(p=p*(l=="-"?-1:1)+a.number);let m=e.doc.line(Math.max(1,Math.min(e.doc.lines,p))),y=ne.cursor(m.from+Math.max(0,Math.min(d,m.length)));n.dispatch({effects:[s,xe.scrollIntoView(y.from,{y:"center"})],selection:y})}),!0},Ete={highlightWordAroundCursor:!1,minSelectionLength:1,maxMatches:100,wholeWords:!1},Cte=be.define({combine(n){return Bu(n,Ete,{highlightWordAroundCursor:(e,t)=>e||t,minSelectionLength:Math.min,maxMatches:Math.min})}});function $te(n){return[Ite,Mte]}const Tte=Qe.mark({class:"cm-selectionMatch"}),Pte=Qe.mark({class:"cm-selectionMatch cm-selectionMatch-main"});function HC(n,e,t,s){return(t==0||n(e.sliceDoc(t-1,t))!=Qt.Word)&&(s==e.doc.length||n(e.sliceDoc(s,s+1))!=Qt.Word)}function Rte(n,e,t,s){return n(e.sliceDoc(t,t+1))==Qt.Word&&n(e.sliceDoc(s-1,s))==Qt.Word}const Mte=ii.fromClass(class{constructor(n){this.decorations=this.getDeco(n)}update(n){(n.selectionSet||n.docChanged||n.viewportChanged)&&(this.decorations=this.getDeco(n.view))}getDeco(n){let e=n.state.facet(Cte),{state:t}=n,s=t.selection;if(s.ranges.length>1)return Qe.none;let i=s.main,r,o=null;if(i.empty){if(!e.highlightWordAroundCursor)return Qe.none;let l=t.wordAt(i.head);if(!l)return Qe.none;o=t.charCategorizer(i.head),r=t.sliceDoc(l.from,l.to)}else{let l=i.to-i.from;if(l200)return Qe.none;if(e.wholeWords){if(r=t.sliceDoc(i.from,i.to),o=t.charCategorizer(i.head),!(HC(o,t,i.from,i.to)&&Rte(o,t,i.from,i.to)))return Qe.none}else if(r=t.sliceDoc(i.from,i.to),!r)return Qe.none}let a=[];for(let l of n.visibleRanges){let c=new Ou(t.doc,r,l.from,l.to);for(;!c.next().done;){let{from:h,to:u}=c.value;if((!o||HC(o,t,h,u))&&(i.empty&&h<=i.from&&u>=i.to?a.push(Pte.range(h,u)):(h>=i.to||u<=i.from)&&a.push(Tte.range(h,u)),a.length>e.maxMatches))return Qe.none}}return Qe.set(a)}},{decorations:n=>n.decorations}),Ite=xe.baseTheme({".cm-selectionMatch":{backgroundColor:"#99ff7780"},".cm-searchMatch .cm-selectionMatch":{backgroundColor:"transparent"}}),Ote=({state:n,dispatch:e})=>{let{selection:t}=n,s=ne.create(t.ranges.map(i=>n.wordAt(i.head)||ne.cursor(i.head)),t.mainIndex);return s.eq(t)?!1:(e(n.update({selection:s})),!0)};function Nte(n,e){let{main:t,ranges:s}=n.selection,i=n.wordAt(t.head),r=i&&i.from==t.from&&i.to==t.to;for(let o=!1,a=new Ou(n.doc,e,s[s.length-1].to);;)if(a.next(),a.done){if(o)return null;a=new Ou(n.doc,e,0,Math.max(0,s[s.length-1].from-1)),o=!0}else{if(o&&s.some(l=>l.from==a.value.from))continue;if(r){let l=n.wordAt(a.value.from);if(!l||l.from!=a.value.from||l.to!=a.value.to)continue}return a.value}}const Lte=({state:n,dispatch:e})=>{let{ranges:t}=n.selection;if(t.some(r=>r.from===r.to))return Ote({state:n,dispatch:e});let s=n.sliceDoc(t[0].from,t[0].to);if(n.selection.ranges.some(r=>n.sliceDoc(r.from,r.to)!=s))return!1;let i=Nte(n,s);return i?(e(n.update({selection:n.selection.addRange(ne.range(i.from,i.to),!1),effects:xe.scrollIntoView(i.to)})),!0):!1},qu=be.define({combine(n){return Bu(n,{top:!1,caseSensitive:!1,literal:!1,regexp:!1,wholeWord:!1,createPanel:e=>new Xte(e),scrollToMatch:e=>xe.scrollIntoView(e)})}});class dL{constructor(e){this.search=e.search,this.caseSensitive=!!e.caseSensitive,this.literal=!!e.literal,this.regexp=!!e.regexp,this.replace=e.replace||"",this.valid=!!this.search&&(!this.regexp||Ate(this.search)),this.unquoted=this.unquote(this.search),this.wholeWord=!!e.wholeWord,this.test=e.test}unquote(e){return this.literal?e:e.replace(/\\([nrt\\])/g,(t,s)=>s=="n"?` +`:s=="r"?"\r":s=="t"?" ":"\\")}eq(e){return this.search==e.search&&this.replace==e.replace&&this.caseSensitive==e.caseSensitive&&this.regexp==e.regexp&&this.wholeWord==e.wholeWord&&this.test==e.test}create(){return this.regexp?new Bte(this):new Fte(this)}getCursor(e,t=0,s){let i=e.doc?e:at.create({doc:e});return s==null&&(s=i.doc.length),this.regexp?eh(this,i,t,s):Qc(this,i,t,s)}}class fL{constructor(e){this.spec=e}}function Dte(n,e,t){return(s,i,r,o)=>{if(t&&!t(s,i,r,o))return!1;let a=s>=o&&i<=o+r.length?r.slice(s-o,i-o):e.doc.sliceString(s,i);return n(a,e,s,i)}}function Qc(n,e,t,s){let i;return n.wholeWord&&(i=jte(e.doc,e.charCategorizer(e.selection.main.head))),n.test&&(i=Dte(n.test,e,i)),new Ou(e.doc,n.unquoted,t,s,n.caseSensitive?void 0:r=>r.toLowerCase(),i)}function jte(n,e){return(t,s,i,r)=>((r>t||r+i.length=t)return null;i.push(s.value)}return i}highlight(e,t,s,i){let r=Qc(this.spec,e,Math.max(0,t-this.spec.unquoted.length),Math.min(s+this.spec.unquoted.length,e.doc.length));for(;!r.next().done;)i(r.value.from,r.value.to)}}function zte(n,e,t){return(s,i,r)=>(!t||t(s,i,r))&&n(r[0],e,s,i)}function eh(n,e,t,s){let i;return n.wholeWord&&(i=Hte(e.charCategorizer(e.selection.main.head))),n.test&&(i=zte(n.test,e,i)),new hL(e.doc,n.search,{ignoreCase:!n.caseSensitive,test:i},t,s)}function By(n,e){return n.slice($n(n,e,!1),e)}function Uy(n,e){return n.slice(e,$n(n,e))}function Hte(n){return(e,t,s)=>!s[0].length||(n(By(s.input,s.index))!=Qt.Word||n(Uy(s.input,s.index))!=Qt.Word)&&(n(Uy(s.input,s.index+s[0].length))!=Qt.Word||n(By(s.input,s.index+s[0].length))!=Qt.Word)}class Bte extends fL{nextMatch(e,t,s){let i=eh(this.spec,e,s,e.doc.length).next();return i.done&&(i=eh(this.spec,e,0,t).next()),i.done?null:i.value}prevMatchInRange(e,t,s){for(let i=1;;i++){let r=Math.max(t,s-i*1e4),o=eh(this.spec,e,r,s),a=null;for(;!o.next().done;)a=o.value;if(a&&(r==t||a.from>r+10))return a;if(r==t)return null}}prevMatch(e,t,s){return this.prevMatchInRange(e,0,t)||this.prevMatchInRange(e,s,e.doc.length)}getReplacement(e){return this.spec.unquote(this.spec.replace).replace(/\$([$&]|\d+)/g,(t,s)=>{if(s=="&")return e.match[0];if(s=="$")return"$";for(let i=s.length;i>0;i--){let r=+s.slice(0,i);if(r>0&&r=t)return null;i.push(s.value)}return i}highlight(e,t,s,i){let r=eh(this.spec,e,Math.max(0,t-250),Math.min(s+250,e.doc.length));for(;!r.next().done;)i(r.value.from,r.value.to)}}const wf=_t.define(),hA=_t.define(),Ea=Fr.define({create(n){return new sb(Q_(n).create(),null)},update(n,e){for(let t of e.effects)t.is(wf)?n=new sb(t.value.create(),n.panel):t.is(hA)&&(n=new sb(n.query,t.value?uA:null));return n},provide:n=>Ly.from(n,e=>e.panel)});class sb{constructor(e,t){this.query=e,this.panel=t}}const Ute=Qe.mark({class:"cm-searchMatch"}),qte=Qe.mark({class:"cm-searchMatch cm-searchMatch-selected"}),Vte=ii.fromClass(class{constructor(n){this.view=n,this.decorations=this.highlight(n.state.field(Ea))}update(n){let e=n.state.field(Ea);(e!=n.startState.field(Ea)||n.docChanged||n.selectionSet||n.viewportChanged)&&(this.decorations=this.highlight(e))}highlight({query:n,panel:e}){if(!e||!n.spec.valid)return Qe.none;let{view:t}=this,s=new df;for(let i=0,r=t.visibleRanges,o=r.length;ir[i+1].from-2*250;)l=r[++i].to;n.highlight(t.state,a,l,(c,h)=>{let u=t.state.selection.ranges.some(d=>d.from==c&&d.to==h);s.add(c,h,u?qte:Ute)})}return s.finish()}},{decorations:n=>n.decorations});function hm(n){return e=>{let t=e.state.field(Ea,!1);return t&&t.query.spec.valid?n(e,t):gL(e)}}const qy=hm((n,{query:e})=>{let{to:t}=n.state.selection.main,s=e.nextMatch(n.state,t,t);if(!s)return!1;let i=ne.single(s.from,s.to),r=n.state.facet(qu);return n.dispatch({selection:i,effects:[dA(n,s),r.scrollToMatch(i.main,n)],userEvent:"select.search"}),mL(n),!0}),Vy=hm((n,{query:e})=>{let{state:t}=n,{from:s}=t.selection.main,i=e.prevMatch(t,s,s);if(!i)return!1;let r=ne.single(i.from,i.to),o=n.state.facet(qu);return n.dispatch({selection:r,effects:[dA(n,i),o.scrollToMatch(r.main,n)],userEvent:"select.search"}),mL(n),!0}),Wte=hm((n,{query:e})=>{let t=e.matchAll(n.state,1e3);return!t||!t.length?!1:(n.dispatch({selection:ne.create(t.map(s=>ne.range(s.from,s.to))),userEvent:"select.search.matches"}),!0)}),Gte=({state:n,dispatch:e})=>{let t=n.selection;if(t.ranges.length>1||t.main.empty)return!1;let{from:s,to:i}=t.main,r=[],o=0;for(let a=new Ou(n.doc,n.sliceDoc(s,i));!a.next().done;){if(r.length>1e3)return!1;a.value.from==s&&(o=r.length),r.push(ne.range(a.value.from,a.value.to))}return e(n.update({selection:ne.create(r,o),userEvent:"select.search.matches"})),!0},BC=hm((n,{query:e})=>{let{state:t}=n,{from:s,to:i}=t.selection.main;if(t.readOnly)return!1;let r=e.nextMatch(t,s,s);if(!r)return!1;let o=r,a=[],l,c,h=[];o.precise?o.from==s&&o.to==i&&(c=t.toText(e.getReplacement(o)),a.push({from:o.from,to:o.to,insert:c}),o=e.nextMatch(t,o.from,o.to),h.push(xe.announce.of(t.phrase("replaced match on line $",t.doc.lineAt(s).number)+"."))):o=e.nextMatch(t,o.from,o.to);let u=n.state.changes(a);return o&&(l=ne.single(o.from,o.to).map(u),h.push(dA(n,o)),h.push(t.facet(qu).scrollToMatch(l.main,n))),n.dispatch({changes:u,selection:l,effects:h,userEvent:"input.replace"}),!0}),Kte=hm((n,{query:e})=>{if(n.state.readOnly)return!1;let t=[];for(let i of e.matchAll(n.state,1e9)){let{from:r,to:o,precise:a}=i;a&&t.push({from:r,to:o,insert:e.getReplacement(i)})}if(!t.length)return!1;let s=n.state.phrase("replaced $ matches",t.length)+".";return n.dispatch({changes:t,effects:xe.announce.of(s),userEvent:"input.replace.all"}),!0});function uA(n){return n.state.facet(qu).createPanel(n)}function Q_(n,e){var t,s,i,r,o;let a=n.selection.main,l=a.empty||a.to>a.from+100?"":n.sliceDoc(a.from,a.to);if(e&&!l)return e;let c=n.facet(qu);return new dL({search:((t=e==null?void 0:e.literal)!==null&&t!==void 0?t:c.literal)?l:l.replace(/\n/g,"\\n"),caseSensitive:(s=e==null?void 0:e.caseSensitive)!==null&&s!==void 0?s:c.caseSensitive,literal:(i=e==null?void 0:e.literal)!==null&&i!==void 0?i:c.literal,regexp:(r=e==null?void 0:e.regexp)!==null&&r!==void 0?r:c.regexp,wholeWord:(o=e==null?void 0:e.wholeWord)!==null&&o!==void 0?o:c.wholeWord})}function pL(n){let e=aN(n,uA);return e&&e.dom.querySelector("[main-field]")}function mL(n){let e=pL(n);e&&e==n.root.activeElement&&e.select()}const gL=n=>{let e=n.state.field(Ea,!1);if(e&&e.panel){let t=pL(n);if(t&&t!=n.root.activeElement){let s=Q_(n.state,e.query.spec);s.valid&&n.dispatch({effects:wf.of(s)}),t.focus(),t.select()}}else n.dispatch({effects:[hA.of(!0),e?wf.of(Q_(n.state,e.query.spec)):_t.appendConfig.of(Jte)]});return!0},yL=n=>{let e=n.state.field(Ea,!1);if(!e||!e.panel)return!1;let t=aN(n,uA);return t&&t.dom.contains(n.root.activeElement)&&n.focus(),n.dispatch({effects:hA.of(!1)}),!0},Zte=[{key:"Mod-f",run:gL,scope:"editor search-panel"},{key:"F3",run:qy,shift:Vy,scope:"editor search-panel",preventDefault:!0},{key:"Mod-g",run:qy,shift:Vy,scope:"editor search-panel",preventDefault:!0},{key:"Escape",run:yL,scope:"editor search-panel"},{key:"Mod-Shift-l",run:Gte},{key:"Mod-Alt-g",run:kte},{key:"Mod-d",run:Lte,preventDefault:!0}];class Xte{constructor(e){this.view=e;let t=this.query=e.state.field(Ea).query.spec;this.commit=this.commit.bind(this),this.searchField=Cn("input",{value:t.search,placeholder:qs(e,"Find"),"aria-label":qs(e,"Find"),class:"cm-textfield",name:"search",form:"","main-field":"true",onchange:this.commit,onkeyup:this.commit}),this.replaceField=Cn("input",{value:t.replace,placeholder:qs(e,"Replace"),"aria-label":qs(e,"Replace"),class:"cm-textfield",name:"replace",form:"",onchange:this.commit,onkeyup:this.commit}),this.caseField=Cn("input",{type:"checkbox",name:"case",form:"",checked:t.caseSensitive,onchange:this.commit}),this.reField=Cn("input",{type:"checkbox",name:"re",form:"",checked:t.regexp,onchange:this.commit}),this.wordField=Cn("input",{type:"checkbox",name:"word",form:"",checked:t.wholeWord,onchange:this.commit});function s(i,r,o){return Cn("button",{class:"cm-button",name:i,onclick:r,type:"button"},o)}this.dom=Cn("div",{onkeydown:i=>this.keydown(i),class:"cm-search"},[this.searchField,s("next",()=>qy(e),[qs(e,"next")]),s("prev",()=>Vy(e),[qs(e,"previous")]),s("select",()=>Wte(e),[qs(e,"all")]),Cn("label",null,[this.caseField,qs(e,"match case")]),Cn("label",null,[this.reField,qs(e,"regexp")]),Cn("label",null,[this.wordField,qs(e,"by word")]),...e.state.readOnly?[]:[Cn("br"),this.replaceField,s("replace",()=>BC(e),[qs(e,"replace")]),s("replaceAll",()=>Kte(e),[qs(e,"replace all")])],Cn("button",{name:"close",onclick:()=>yL(e),"aria-label":qs(e,"close"),type:"button"},["×"])])}commit(){let e=new dL({search:this.searchField.value,caseSensitive:this.caseField.checked,regexp:this.reField.checked,wholeWord:this.wordField.checked,replace:this.replaceField.value});e.eq(this.query)||(this.query=e,this.view.dispatch({effects:wf.of(e)}))}keydown(e){ZJ(this.view,e,"search-panel")?e.preventDefault():e.keyCode==13&&e.target==this.searchField?(e.preventDefault(),(e.shiftKey?Vy:qy)(this.view)):e.keyCode==13&&e.target==this.replaceField&&(e.preventDefault(),BC(this.view))}update(e){for(let t of e.transactions)for(let s of t.effects)s.is(wf)&&!s.value.eq(this.query)&&this.setQuery(s.value)}setQuery(e){this.query=e,this.searchField.value=e.search,this.replaceField.value=e.replace,this.caseField.checked=e.caseSensitive,this.reField.checked=e.regexp,this.wordField.checked=e.wholeWord}mount(){this.searchField.select()}get pos(){return 80}get top(){return this.view.state.facet(qu).top}}function qs(n,e){return n.state.phrase(e)}const sg=30,ig=/[\s\.,:;?!]/;function dA(n,{from:e,to:t}){let s=n.state.doc.lineAt(e),i=n.state.doc.lineAt(t).to,r=Math.max(s.from,e-sg),o=Math.min(i,t+sg),a=n.state.sliceDoc(r,o);if(r!=s.from){for(let l=0;la.length-sg;l--)if(!ig.test(a[l-1])&&ig.test(a[l])){a=a.slice(0,l);break}}return xe.announce.of(`${n.state.phrase("current match")}. ${a} ${n.state.phrase("on line")} ${s.number}.`)}const Yte=xe.baseTheme({".cm-panel.cm-search":{padding:"2px 6px 4px",position:"relative","& [name=close]":{position:"absolute",top:"0",right:"4px",backgroundColor:"inherit",border:"none",font:"inherit",padding:0,margin:0},"& input, & button, & label":{margin:".2em .6em .2em 0"},"& input[type=checkbox]":{marginRight:".2em"},"& label":{fontSize:"80%",whiteSpace:"pre"}},"&light .cm-searchMatch":{backgroundColor:"#ffff0054"},"&dark .cm-searchMatch":{backgroundColor:"#00ffff8a"},"&light .cm-searchMatch-selected":{backgroundColor:"#ff6a0054"},"&dark .cm-searchMatch-selected":{backgroundColor:"#ff00ff8a"}}),Jte=[Ea,V0.low(Vte),Yte],Qte=({path:n,value:e,readOnly:t,onChange:s})=>{const i=ee.useRef(null),r=ee.useRef(null),o=ee.useRef(new rm),a=ee.useRef(s);return a.current=s,ee.useEffect(()=>{if(!i.current)return;const l=at.create({doc:e,extensions:[bQ(),tQ(),oQ(),bee(),$te(),QQ(),sA.define(xte),tN.of([..._te,...$ee,...Zte,Ste]),xe.contentAttributes.of({"aria-label":`Editing ${n}`,class:"ph-no-capture","data-ph-no-autocapture":"true","data-ph-no-capture":"true"}),o.current.of(xe.editable.of(!t)),xe.updateListener.of(c=>{c.docChanged&&a.current(c.state.doc.toString())})]});return r.current=new xe({state:l,parent:i.current}),()=>{var c;return(c=r.current)==null?void 0:c.destroy()}},[n]),ee.useEffect(()=>{const l=r.current;!l||l.state.doc.toString()===e||l.dispatch({changes:{from:0,to:l.state.doc.length,insert:e}})},[e]),ee.useEffect(()=>{var l;(l=r.current)==null||l.dispatch({effects:o.current.reconfigure(xe.editable.of(!t))})},[t]),S.jsx("div",{className:"latex-source-editor ph-no-capture","data-ph-no-autocapture":"true","data-ph-no-capture":"true","data-testid":"latex-source-editor",ref:i})},ene="pwc:artifact-navigation";function use(){return typeof window>"u"?!0:window.dispatchEvent(new Event(ene,{cancelable:!0}))}const vL=()=>({open:!1,selectedKey:null,selected:null,selectedVersionId:null,tab:"preview",sourceFile:null,panelPercent:55,requestNonce:0,registry:{},autoOpened:{},manuallyClosed:{}});function tne(n,e){if(e.type==="reset")return{...vL(),panelPercent:n.panelPercent};if(e.type==="register"){const t=n.registry[e.key];if(t&&JSON.stringify(t)===JSON.stringify(e.block))return n;const s={...n.registry,[e.key]:e.block},i=n.selectedKey===e.key?e.block:n.selected,r=(t==null?void 0:t.status)==="generating"&&e.block.status==="ready",o=e.autoOpenOnMount&&!t&&e.block.status==="ready"&&!Object.values(n.autoOpened).some(Boolean);return(r||o)&&!n.autoOpened[e.key]&&!n.manuallyClosed[e.key]?{...n,registry:s,open:!0,selectedKey:e.key,selected:e.block,selectedVersionId:e.block.version_id??null,tab:"preview",sourceFile:null,requestNonce:n.requestNonce+1,autoOpened:{...n.autoOpened,[e.key]:!0}}:{...n,registry:s,selected:i}}return e.type==="unregister"?n:e.type==="open"?{...n,open:!0,selectedKey:e.key,selected:e.block,selectedVersionId:e.block.version_id??null,tab:"preview",sourceFile:null,requestNonce:n.requestNonce+1,manuallyClosed:{...n.manuallyClosed,[e.key]:!1}}:e.type==="close"?{...n,open:!1,manuallyClosed:n.selectedKey?{...n.manuallyClosed,[n.selectedKey]:!0}:n.manuallyClosed}:e.type==="tab"?{...n,tab:e.tab}:e.type==="source"?{...n,sourceFile:e.path}:e.type==="version"?{...n,selectedVersionId:e.versionId,tab:"preview",sourceFile:null}:{...n,panelPercent:e.percent}}function eS(n){return n.publication_id||n.public_capability||n.version_id||`${n.scope}:${n.identifier}:${n.version??"pending"}`}const bL=ee.createContext(null),dse=({children:n,workspaceKey:e,autoOpenOnMount:t=!1,onAskAiFix:s})=>{const[i,r]=ee.useReducer(tne,void 0,vL),o=ee.useRef(null),a=ee.useRef(e);ee.useEffect(()=>{a.current!==e&&(a.current=e,o.current=null,r({type:"reset"}))},[e]);const l=ee.useCallback(()=>{r({type:"close"}),window.setTimeout(()=>{var _;(_=o.current)!=null&&_.isConnected&&o.current.focus()},0)},[]),c=ee.useCallback(_=>r({type:"register",key:eS(_),block:_,autoOpenOnMount:t}),[t]),h=ee.useCallback(_=>r({type:"unregister",key:_}),[]),u=ee.useCallback((_,x)=>{const A=document.activeElement;o.current=x??(A instanceof HTMLElement&&A!==document.body?A:null),r({type:"open",key:eS(_),block:_})},[]),d=ee.useCallback(_=>r({type:"tab",tab:_}),[]),p=ee.useCallback(_=>r({type:"source",path:_}),[]),m=ee.useCallback(_=>r({type:"version",versionId:_}),[]),y=ee.useCallback(_=>r({type:"width",percent:_}),[]),v=ee.useCallback(_=>s==null?void 0:s(_),[s]),g=ee.useCallback(()=>r({type:"reset"}),[]),b=ee.useMemo(()=>({state:i,autoOpenOnMount:t,register:c,unregister:h,open:u,close:l,setTab:d,setSourceFile:p,setVersion:m,setPanelPercent:y,askAiToFix:v,reset:g}),[v,t,l,u,c,g,y,p,d,m,i,h]);return S.jsx(bL.Provider,{value:b,children:n})};function um(){const n=ee.useContext(bL);if(!n)throw new Error("Poster artifacts require an ArtifactPanelProvider");return n}function nne(n,e,t){return on(`/api/v1/chat/artifacts/${encodeURIComponent(n)}/versions/${encodeURIComponent(e)}/source/${t.split("/").map(encodeURIComponent).join("/")}`)}function sne(n,e,t){return on(`/api/v1/chat/artifacts/${encodeURIComponent(n)}/versions/${encodeURIComponent(e)}/figures/${t.split("/").map(encodeURIComponent).join("/")}`)}function ine(n){return on(`/api/v1/chat/artifacts/${encodeURIComponent(n)}/export/pdf`)}function UC(n,e){return on(`/api/v1/chat/artifacts/${encodeURIComponent(n)}/versions/${encodeURIComponent(e)}/export/source.zip`)}function rg(n){return`pwc:latex-paper-draft:${n}`}function rne(n,e){const t=Object.keys(n).sort(),s=Object.keys(e).sort();return t.length===s.length&&t.every((i,r)=>i===s[r]&&n[i]===e[i])}function qC(n){return!n.includes("\\")&&/^(?!\/)(?!.*(?:^|\/)\.\.?\/)[^\0]{1,300}\.(?:tex|bib)$/iu.test(n)}function one(n){var s,i;const e=((s=n.provenance)==null?void 0:s.action)??(n.actor_type==="restore"?"restore":n.actor_type==="ai"?"ai_draft":"human_save"),t={human_save:"Human save",ai_draft:"AI draft",ai_repair:"AI repair",restore:"Restore"}[e];return(i=n.provenance)!=null&&i.model_identity?`${t} · ${n.provenance.model_identity}`:t}const ane=({block:n,forceDialog:e=!1})=>{var us,Es,ln,cn,Mn,Xn,Yn,Pc,Vu;const t=um(),s=XC(),i=t.close,[r,o]=ee.useState(()=>{var V;return typeof window<"u"&&((V=window.matchMedia)==null?void 0:V.call(window,"(max-width: 760px)").matches)}),[a,l]=ee.useState({}),[c,h]=ee.useState({}),[u,d]=ee.useState(null),[p,m]=ee.useState(!1),[y,v]=ee.useState(!1),[g,b]=ee.useState(null),[_,x]=ee.useState(!1),[A,C]=ee.useState(null),$=ee.useRef(null),I=ee.useRef(null),j=ee.useRef(!1),q=e||r,L=u!==null&&!rne(a,c);ee.useEffect(()=>{var Pe,it;const V=(Pe=window.matchMedia)==null?void 0:Pe.call(window,"(max-width: 760px)");if(!V)return;const me=()=>o(V.matches);return me(),(it=V.addEventListener)==null||it.call(V,"change",me),()=>{var Lt;return(Lt=V.removeEventListener)==null?void 0:Lt.call(V,"change",me)}},[]),ee.useEffect(()=>{var Pe,it;if(!q)return;(it=(Pe=I.current)==null?void 0:Pe.querySelector("[data-artifact-close]"))==null||it.focus(),window.history.pushState({...window.history.state,pwcArtifactPanel:!0},""),j.current=!0;const V=()=>{if(L&&!window.confirm("Leave this view? Unsaved paper edits remain in this browser.")){window.history.pushState({...window.history.state,pwcArtifactPanel:!0},""),j.current=!0;return}j.current=!1,i()},me=Lt=>{Lt.key==="Escape"&&(Lt.preventDefault(),!(L&&!window.confirm("Leave this view? Unsaved paper edits remain in this browser."))&&(i(),j.current&&(j.current=!1,window.history.back())))};return window.addEventListener("popstate",V),document.addEventListener("keydown",me),()=>{window.removeEventListener("popstate",V),document.removeEventListener("keydown",me)}},[i,q,L]),ee.useEffect(()=>{if(!q)return;const V=me=>{if(me.key!=="Tab"||!I.current)return;const Pe=[...I.current.querySelectorAll('button:not([disabled]), a[href], input:not([disabled]), select:not([disabled]), [contenteditable="true"], [tabindex]:not([tabindex="-1"])')];if(!Pe.length)return;const it=Pe[0],Lt=Pe.at(-1);me.shiftKey&&document.activeElement===it?(me.preventDefault(),Lt.focus()):!me.shiftKey&&document.activeElement===Lt&&(me.preventDefault(),it.focus())};return document.addEventListener("keydown",V),()=>document.removeEventListener("keydown",V)},[q]),ee.useEffect(()=>{const V=me=>{L&&(me.preventDefault(),me.returnValue="")};return window.addEventListener("beforeunload",V),()=>window.removeEventListener("beforeunload",V)},[L]),ee.useEffect(()=>{const V=me=>{L&&!window.confirm("Leave this view? Unsaved paper edits remain in this browser.")&&me.preventDefault()};return window.addEventListener("pwc:artifact-navigation",V),()=>window.removeEventListener("pwc:artifact-navigation",V)},[L]);const B=bo({queryKey:["chat-latex-paper",n.artifact_id],queryFn:async()=>{const V=await fetch(on(`/api/v1/chat/artifacts/${encodeURIComponent(n.artifact_id)}`),{credentials:"include",cache:"no-store"});if(!V.ok)throw new Error("Could not load paper details");return V.json()},enabled:!!n.artifact_id,staleTime:5e3}),H=B.data,D=H==null?void 0:H.source_head,X=H==null?void 0:H.preview_head,te=bo({queryKey:["chat-latex-paper-history",n.artifact_id,A],queryFn:async()=>{const V=new URLSearchParams({limit:"20"});A&&V.set("cursor",A);const me=await fetch(on(`/api/v1/chat/artifacts/${encodeURIComponent(n.artifact_id)}/versions?${V}`),{credentials:"include",cache:"no-store"});if(!me.ok)throw new Error("Could not load paper history");return me.json()},enabled:_&&!!n.artifact_id,staleTime:Number.POSITIVE_INFINITY}),J=bo({queryKey:["chat-latex-paper-manifest",n.artifact_id,D==null?void 0:D.version_id],queryFn:async()=>{const V=await fetch(on(`/api/v1/chat/artifacts/${encodeURIComponent(n.artifact_id)}/versions/${encodeURIComponent(D.version_id)}/manifest`),{credentials:"include",cache:"no-store"});if(!V.ok)throw new Error("Could not load paper files");return V.json()},enabled:t.state.tab==="files"&&!!(D!=null&&D.version_id),staleTime:Number.POSITIVE_INFINITY}),Y=((us=J.data)==null?void 0:us.files.filter(V=>V.media_type==="text/x-tex"||V.media_type==="application/x-bibtex"))??[],ye=((Es=J.data)==null?void 0:Es.files.filter(V=>V.media_type==="image/png"||V.media_type==="image/jpeg"||V.media_type==="application/pdf"))??[],z=bo({queryKey:["chat-latex-paper-source-files",n.artifact_id,D==null?void 0:D.version_id],queryFn:async()=>Object.fromEntries(await Promise.all(Y.map(async V=>{const me=await fetch(nne(n.artifact_id,D.version_id,V.path),{credentials:"include",cache:"no-store"});if(!me.ok)throw new Error("Could not load paper source");return[V.path,await me.text()]}))),enabled:t.state.tab==="files"&&!!(D!=null&&D.version_id&&Y.length),staleTime:Number.POSITIVE_INFINITY});ee.useEffect(()=>{m(!1)},[D==null?void 0:D.version_id]),ee.useEffect(()=>{var Lt;if(!(D!=null&&D.version_id)||!z.data||$.current===D.version_id)return;const V=z.data;let me=V,Pe=!1,it=D.version_id;try{const Mo=window.localStorage.getItem(rg(n.artifact_id)),Ei=Mo?JSON.parse(Mo):null;Ei!=null&&Ei.files&&typeof Ei.files=="object"&&(me=Ei.files,Pe=Ei.parentVersionId!==D.version_id,it=Ei.parentVersionId)}catch{}$.current=D.version_id,l(me),h(V),d(it),v(Pe),m(!0),Pe&&b("This local draft is based on an older paper version. Copy or discard it before saving the latest version."),(!t.state.sourceFile||!me[t.state.sourceFile])&&t.setSourceFile(((Lt=J.data)==null?void 0:Lt.root_document)??null)},[n.artifact_id,(ln=J.data)==null?void 0:ln.root_document,t,D==null?void 0:D.version_id,z.data]),ee.useEffect(()=>{if(!u||!n.artifact_id)return;const V=rg(n.artifact_id);if(!L){window.localStorage.removeItem(V);return}window.localStorage.setItem(V,JSON.stringify({parentVersionId:u,files:a}))},[n.artifact_id,L,u,a]);const E=vm({mutationFn:async()=>{var Pe;if(!(D!=null&&D.version_id))throw new Error("Paper source is not ready to save");const V=await fetch(on(`/api/v1/chat/artifacts/${encodeURIComponent(n.artifact_id)}/save-compile`),{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"},body:JSON.stringify({expected_parent_version_id:D.version_id,files:Object.entries(a).map(([it,Lt])=>({path:it,content:Lt}))})}),me=await V.json().catch(()=>null);if(!V.ok)throw new Error(((Pe=me==null?void 0:me.detail)==null?void 0:Pe.message)??"Could not save paper");return me},onSuccess:V=>{var me,Pe;s.setQueryData(["chat-latex-paper",n.artifact_id],V),s.invalidateQueries({queryKey:["chat-latex-paper-manifest",n.artifact_id]}),s.invalidateQueries({queryKey:["chat-latex-paper-source-files",n.artifact_id]}),$.current=((me=V.source_head)==null?void 0:me.version_id)??null,h(a),d(((Pe=V.source_head)==null?void 0:Pe.version_id)??null),window.localStorage.removeItem(rg(n.artifact_id)),b(null),v(!1),t.setTab("preview")},onError:V=>b(V instanceof Error?V.message:"Could not save paper")}),O=vm({mutationFn:async V=>{var it;if(!(D!=null&&D.version_id))throw new Error("Paper source is not ready to restore");const me=await fetch(on(`/api/v1/chat/artifacts/${encodeURIComponent(n.artifact_id)}/versions/restore`),{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"},body:JSON.stringify({source_version_id:V,expected_parent_version_id:D.version_id})}),Pe=await me.json().catch(()=>null);if(!me.ok)throw new Error(((it=Pe==null?void 0:Pe.detail)==null?void 0:it.message)??"Could not restore paper version");return Pe},onSuccess:V=>{s.setQueryData(["chat-latex-paper",n.artifact_id],V),s.invalidateQueries({queryKey:["chat-latex-paper-history",n.artifact_id]}),s.invalidateQueries({queryKey:["chat-latex-paper-manifest",n.artifact_id]}),s.invalidateQueries({queryKey:["chat-latex-paper-source-files",n.artifact_id]}),$.current=null,m(!1),C(null),b(null),t.setTab("preview")},onError:V=>b(V instanceof Error?V.message:"Could not restore paper version")}),R=vm({mutationFn:async V=>{var Lt;if(!(D!=null&&D.version_id))throw new Error("Paper source is not ready to upload a figure");if(L)throw new Error("Save or discard text edits before uploading a figure");const me=new FormData;me.set("expected_parent_version_id",D.version_id),me.set("path",`figures/${V.name}`),me.set("figure",V);const Pe=await fetch(on(`/api/v1/chat/artifacts/${encodeURIComponent(n.artifact_id)}/figures`),{method:"POST",credentials:"include",body:me}),it=await Pe.json().catch(()=>null);if(!Pe.ok)throw new Error(((Lt=it==null?void 0:it.detail)==null?void 0:Lt.message)??"Could not upload figure");return it},onSuccess:V=>{s.setQueryData(["chat-latex-paper",n.artifact_id],V),s.invalidateQueries({queryKey:["chat-latex-paper-manifest",n.artifact_id]}),s.invalidateQueries({queryKey:["chat-latex-paper-source-files",n.artifact_id]}),b(null)},onError:V=>b(V instanceof Error?V.message:"Could not upload figure")}),k=vm({mutationFn:async()=>{const V=await fetch(on(`/api/v1/chat/artifacts/${encodeURIComponent(n.artifact_id)}/refresh-compile`),{method:"POST",credentials:"include"});if(!V.ok)throw new Error("Could not refresh paper compilation");return V.json()},onSuccess:V=>s.setQueryData(["chat-latex-paper",n.artifact_id],V)}).mutate,N=D==null?void 0:D.version_id,G=D==null?void 0:D.compile_status;ee.useEffect(()=>{if(!N||!n.artifact_id||!["queued","compiling"].includes(G??""))return;const V=window.setTimeout(()=>k(),2e3);return()=>window.clearTimeout(V)},[n.artifact_id,k,G,N]);const Z=t.state.sourceFile??((cn=J.data)==null?void 0:cn.root_document)??null,ae=(H==null?void 0:H.editing_enabled)===!0&&!!(D!=null&&D.version_id)&&p&&!y&&!E.isPending,ie=new Map(((Mn=te.data)==null?void 0:Mn.items.map(V=>[V.version_id,V.version]))??[]),Ae=X?on(`/api/v1/chat/artifacts/${encodeURIComponent(n.artifact_id)}/versions/${encodeURIComponent(X.version_id)}/preview`):null,ct=!!(D&&X&&D.version_id!==X.version_id),Ie=()=>!L||window.confirm("Leave this view? Unsaved paper edits remain in this browser."),Fe=V=>V!==t.state.tab&&!Ie()?!1:(t.setTab(V),!0),Je=V=>{var Pe,it;if(!["ArrowLeft","ArrowRight","Home","End"].includes(V.key))return;V.preventDefault();const me=V.key==="ArrowLeft"||V.key==="Home"?"preview":"files";Fe(me)&&((it=(Pe=V.currentTarget.parentElement)==null?void 0:Pe.querySelector(`#paper-${me}-tab`))==null||it.focus())},st=V=>{V!==Z&&L&&!window.confirm("Switch files? Unsaved edits stay in this browser.")||t.setSourceFile(V)},tn=()=>{const V=window.prompt("New TeX or BibTeX file name","section.tex");if(V){if(!qC(V)||a[V]){b("Choose a new safe .tex or .bib filename.");return}if(Object.keys(a).length>=100){b("A paper can contain at most 100 files.");return}l({...a,[V]:""}),b(null),t.setSourceFile(V)}},Pn=()=>{var Pe;if(!Z||Z===((Pe=J.data)==null?void 0:Pe.root_document))return;const V=window.prompt("Rename file",Z);if(!V||V===Z)return;if(!qC(V)||a[V]){b("Choose a new safe .tex or .bib filename.");return}const me={...a,[V]:a[Z]};delete me[Z],l(me),t.setSourceFile(V)},Et=()=>{var me,Pe;if(!Z||Z===((me=J.data)==null?void 0:me.root_document)||!window.confirm(`Delete ${Z}?`))return;const V={...a};delete V[Z],l(V),t.setSourceFile(((Pe=J.data)==null?void 0:Pe.root_document)??null)},As=()=>{!y||!window.confirm("Discard this stale local draft?")||(window.localStorage.removeItem(rg(n.artifact_id)),l(c),d((D==null?void 0:D.version_id)??null),v(!1),b(null))},Rn=()=>{Ie()&&(i(),q&&j.current&&(j.current=!1,window.history.back()))},ks=()=>{if(!D||D.compile_status!=="failed"||D.repair_exhausted)return;const V=(D.compile_diagnostics??[]).slice(0,20).map(me=>`${me.file??"project"}${me.line?`:${me.line}`:""}: ${me.message}`).join(` +`);t.askAiToFix(`Repair the failed paper source version ${D.version_id}. Use pwc-paper to inspect and repair it; make no more than three attempts. Compiler diagnostics: +${V||"No compiler diagnostic was available."}`)},hs=V=>{!V||!Fe("files")||t.setSourceFile(V)};return S.jsxs("section",{ref:I,className:`chat-artifact-panel${q?" is-dialog":" is-docked"}`,role:q?"dialog":"complementary","aria-modal":q?!0:void 0,"aria-labelledby":"latex-paper-title","data-testid":"latex-paper-panel",children:[S.jsxs("header",{children:[S.jsxs("div",{children:[S.jsx("span",{children:"Private paper"}),S.jsx("h2",{id:"latex-paper-title",children:n.title}),S.jsxs("p",{className:"chat-paper-status",role:"status","aria-live":"polite",children:[D?`Source v${D.version} · ${D.compile_status}`:"Preparing paper source",ct?" · Preview out of date":""]}),S.jsx("p",{className:"chat-paper-privacy-note",children:"This paper is private to this chat. Source, figures, and PDFs are stored privately; AI-authored text needs your review."})]}),S.jsxs("div",{className:"chat-artifact-header-actions",children:[S.jsx("button",{type:"button","aria-expanded":_,"aria-controls":"paper-version-history",onClick:()=>{C(null),x(!_)},children:"Version history"}),S.jsx("button",{type:"button","data-artifact-close":!0,"aria-label":q?"Back to conversation":"Close paper",onClick:Rn,children:S.jsx(h0,{})})]})]}),S.jsxs("nav",{"aria-label":"Paper views",role:"tablist",children:[S.jsx("button",{type:"button",id:"paper-preview-tab",role:"tab","aria-selected":t.state.tab==="preview","aria-controls":"paper-preview-panel",tabIndex:t.state.tab==="preview"?0:-1,className:t.state.tab==="preview"?"active":"",onClick:()=>Fe("preview"),onKeyDown:Je,children:"Preview"}),S.jsx("button",{type:"button",id:"paper-files-tab",role:"tab","aria-selected":t.state.tab==="files","aria-controls":"paper-files-panel",tabIndex:t.state.tab==="files"?0:-1,className:t.state.tab==="files"?"active":"",onClick:()=>Fe("files"),onKeyDown:Je,children:"Files"})]}),S.jsxs("div",{id:t.state.tab==="preview"?"paper-preview-panel":"paper-files-panel",role:"tabpanel","aria-labelledby":t.state.tab==="preview"?"paper-preview-tab":"paper-files-tab",className:"chat-artifact-panel-body",children:[t.state.tab==="preview"?B.isError?S.jsxs("div",{role:"alert",children:["Could not load paper details. ",S.jsx("button",{type:"button",onClick:()=>void B.refetch(),children:"Retry paper details"})]}):Ae?S.jsx(zY,{url:Ae,downloadUrl:ine(n.artifact_id),paperKey:`${n.artifact_id}:${X==null?void 0:X.version_id}`,paperTitle:n.title,paperHref:"/chat",chrome:"canvas"},X==null?void 0:X.version_id):D?D.compile_status==="failed"?S.jsx("p",{role:"alert",children:"No compiled preview is available for this failed source version. Review the diagnostics or fix the paper in Files."}):["queued","compiling"].includes(D.compile_status)?S.jsx("p",{role:"status",children:"Preview is compiling. The stored source is available in Files."}):S.jsx("p",{role:"alert",children:"No compiled preview is available for this source version."}):S.jsx("p",{role:"status",children:"Paper source and compiled preview are not available yet."}):S.jsxs("div",{className:"chat-artifact-source-workspace",children:[S.jsxs("nav",{"aria-label":"Paper source files",children:[Y.map(V=>S.jsx("button",{type:"button","aria-pressed":Z===V.path,onClick:()=>st(V.path),children:V.path},V.path)),ae&&S.jsxs("button",{type:"button",className:"latex-file-action","aria-label":"Add TeX file",onClick:tn,children:[S.jsx(aD,{})," Add file"]}),ae&&S.jsxs("label",{className:"latex-file-action",children:["Upload figure",S.jsx("input",{"aria-label":"Upload figure",type:"file",accept:"image/png,image/jpeg,application/pdf,.png,.jpg,.jpeg,.pdf",disabled:R.isPending,onChange:V=>{var Pe;const me=(Pe=V.currentTarget.files)==null?void 0:Pe[0];V.currentTarget.value="",me&&R.mutate(me)}})]}),ye.map(V=>D&&S.jsx("a",{href:sne(n.artifact_id,D.version_id,V.path),download:!0,children:V.path},V.path))]}),S.jsxs("div",{className:"latex-editor-column",children:[Z&&a[Z]!==void 0?S.jsx(Qte,{path:Z,value:a[Z],readOnly:!ae,onChange:V=>l({...a,[Z]:V})}):S.jsx("p",{children:z.isError?"Source could not be loaded.":"Loading source…"}),ae&&Z&&Z!==((Xn=J.data)==null?void 0:Xn.root_document)&&S.jsxs("div",{className:"latex-file-buttons",children:[S.jsxs("button",{type:"button",onClick:Pn,children:[S.jsx(o$,{})," Rename"]}),S.jsxs("button",{type:"button",onClick:Et,children:[S.jsx(WL,{})," Delete"]})]})]})]}),_&&S.jsxs("section",{id:"paper-version-history",className:"chat-artifact-history","aria-label":"Paper version history",children:[S.jsx("h3",{children:"Version history"}),te.isLoading&&S.jsx("p",{children:"Loading history…"}),te.isError&&S.jsx("p",{role:"alert",children:"Paper history could not be loaded."}),(Yn=te.data)==null?void 0:Yn.items.map(V=>{var me,Pe,it,Lt;return S.jsxs("article",{children:[S.jsxs("strong",{children:["v",V.version," · ",V.compile_status]}),S.jsx("span",{children:one(V)}),V.created_at&&S.jsx("time",{dateTime:V.created_at,children:V.created_at}),V.parent_version_id&&S.jsxs("span",{children:["Parent ",ie.has(V.parent_version_id)?`v${ie.get(V.parent_version_id)}`:V.parent_version_id]}),(me=V.provenance)!=null&&me.changed_files.length?S.jsxs("span",{children:["Changed: ",V.provenance.changed_files.join(", ")]}):null,((Pe=V.provenance)==null?void 0:Pe.restored_from_version_id)&&S.jsxs("span",{children:["Restored from ",V.provenance.restored_from_version_id]}),((it=V.provenance)==null?void 0:it.change_summary)&&S.jsx("p",{children:V.provenance.change_summary}),(Lt=V.provenance)==null?void 0:Lt.reference_changes.map(Mo=>S.jsx("p",{children:Mo},Mo)),S.jsx("a",{href:UC(n.artifact_id,V.version_id),download:!0,children:"Source ZIP"}),(H==null?void 0:H.editing_enabled)&&(D==null?void 0:D.version_id)&&V.version_id!==D.version_id&&S.jsxs("button",{type:"button",disabled:O.isPending||L,onClick:()=>O.mutate(V.version_id),children:["Restore version ",V.version]})]},V.version_id)}),((Pc=te.data)==null?void 0:Pc.next_cursor)&&S.jsx("button",{type:"button",onClick:()=>C(te.data.next_cursor??null),children:"Load older versions"})]})]}),S.jsxs("footer",{children:[S.jsxs("div",{className:"chat-artifact-metadata","aria-live":"polite",children:[ct&&S.jsx("strong",{children:"Out of date"}),(Vu=D==null?void 0:D.compile_diagnostics)==null?void 0:Vu.map((V,me)=>S.jsxs("button",{type:"button",onClick:()=>hs(V.file),className:"latex-compile-diagnostic",children:[V.file?`${V.file}${V.line?`:${V.line}`:""}: `:"",V.message]},`${V.file??"global"}:${V.line??""}:${me}`)),g&&S.jsx("span",{role:"alert",children:g}),y&&S.jsx("button",{type:"button",onClick:As,children:"Discard stale local draft"})]}),S.jsxs("div",{className:"chat-artifact-actions",children:[(D==null?void 0:D.compile_status)==="failed"&&!D.repair_exhausted&&S.jsx("button",{type:"button",onClick:ks,children:"Ask AI to fix"}),(D==null?void 0:D.compile_status)==="failed"&&D.repair_exhausted&&S.jsx("span",{role:"status",children:"AI repair attempts exhausted"}),t.state.tab==="files"&&ae&&S.jsxs("button",{type:"button",disabled:!L,onClick:()=>E.mutate(),children:[S.jsx(hD,{}),E.isPending?"Saving…":"Save & Compile"]}),D&&S.jsxs("a",{href:UC(n.artifact_id,D.version_id),download:!0,children:[S.jsx(sS,{})," Source ZIP"]})]})]})]})},lne="https://github.com/Chenruishuo/posterly/tree/b9f42e5578a49a27525a68f85376bb3bb25af86f";function cne(){if(typeof window>"u")return null;const n=window.location.pathname.match(/^\/share\/([^/]+)/u);return n?decodeURIComponent(n[1]):null}function wL(n){if(n.scope==="public"){const s=cne();if(!s||!n.public_capability)return null;const i=`/api/v1/chat/shares/${encodeURIComponent(s)}/artifacts/${encodeURIComponent(n.public_capability)}`;return{preview:on(`${i}/preview`),png:on(`${i}/download/png`),pdf:on(`${i}/download/pdf`),manifest:null,source:null,gate:null,download:null}}if(!n.artifact_id||!n.version_id)return null;const e=`/api/v1/chat/artifacts/${encodeURIComponent(n.artifact_id)}/versions/${encodeURIComponent(n.version_id)}`,t=(s,i)=>on(`${e}/${s}/${i.split("/").map(encodeURIComponent).join("/")}`);return{preview:on(`${e}/preview`),png:t("download","poster.png"),pdf:null,manifest:on(`${e}/manifest`),source:s=>t("source",s),gate:s=>t("source",s),download:s=>t("download",s)}}const _L=n=>({passed:"Passed",warnings:"Passed with warnings",failed:"Draft—checks failed"})[n??"passed"];function hne(){const[n,e]=ee.useState(()=>{var t;return typeof window<"u"&&((t=window.matchMedia)==null?void 0:t.call(window,"(max-width: 760px)").matches)});return ee.useEffect(()=>{var i,r;const t=(i=window.matchMedia)==null?void 0:i.call(window,"(max-width: 760px)");if(!t)return;const s=()=>e(t.matches);return s(),(r=t.addEventListener)==null||r.call(t,"change",s),()=>{var o;return(o=t.removeEventListener)==null?void 0:o.call(t,"change",s)}},[]),n}const une=({forceDialog:n=!1,readerFallback:e=!1})=>{var A,C,$,I;const t=um(),s=t.close,{state:i}=t,r=i.selected,o=hne(),a=n||o,l=ee.useRef(null),c=ee.useRef(!1),h=bo({queryKey:["chat-artifact-versions",r==null?void 0:r.artifact_id],queryFn:async()=>{const j=await fetch(on(`/api/v1/chat/artifacts/${encodeURIComponent(r.artifact_id)}`),{credentials:"include",cache:"no-store"});if(!j.ok)throw new Error("Could not load poster versions");return(await j.json()).versions},enabled:i.open&&(r==null?void 0:r.scope)==="owner"&&!!r.artifact_id,staleTime:Number.POSITIVE_INFINITY}),u=(A=h.data)==null?void 0:A.find(j=>j.version_id===i.selectedVersionId),d=r&&u?{...r,version_id:u.version_id,version:u.version,gate_status:u.gate_status,total_bytes:u.total_bytes}:r,p=d?wL(d):null,y=bo({queryKey:["chat-artifact-manifest",d==null?void 0:d.version_id],queryFn:async()=>{const j=await fetch(p.manifest,{credentials:"include",cache:"no-store"});if(!j.ok)throw new Error("Could not load poster details");return j.json()},enabled:i.open&&(d==null?void 0:d.scope)==="owner"&&!!(p!=null&&p.manifest),staleTime:Number.POSITIVE_INFINITY}).data,v=i.sourceFile??(y==null?void 0:y.entrypoint)??null,g=bo({queryKey:["chat-artifact-source",d==null?void 0:d.version_id,v],queryFn:async()=>{const j=await fetch(p.source(v),{credentials:"include",cache:"no-store"});if(!j.ok)throw new Error("Source could not be loaded");return j.text()},enabled:i.open&&i.tab==="source"&&(d==null?void 0:d.scope)==="owner"&&!!(v&&(p!=null&&p.source)),staleTime:Number.POSITIVE_INFINITY});if(ee.useEffect(()=>{var q,L;if(!i.open||!a)return;(L=(q=l.current)==null?void 0:q.querySelector("[data-artifact-close]"))==null||L.focus(),window.history.pushState({...window.history.state,pwcArtifactPanel:!0},""),c.current=!0;const j=()=>{c.current=!1,s()};return window.addEventListener("popstate",j),()=>window.removeEventListener("popstate",j)},[s,a,i.open]),ee.useEffect(()=>{if(!i.open||!a)return;const j=q=>{if(q.key==="Escape"){q.preventDefault(),s(),c.current&&(c.current=!1,window.history.back());return}if(q.key!=="Tab"||!l.current)return;const L=[...l.current.querySelectorAll('button:not([disabled]), a[href], select:not([disabled]), [tabindex]:not([tabindex="-1"])')];if(!L.length)return;const B=L[0],H=L.at(-1);q.shiftKey&&document.activeElement===B?(q.preventDefault(),H.focus()):!q.shiftKey&&document.activeElement===H&&(q.preventDefault(),B.focus())};return document.addEventListener("keydown",j),()=>document.removeEventListener("keydown",j)},[s,a,i.open]),!i.open||!d||!p)return null;const b=()=>{s(),a&&c.current&&(c.current=!1,window.history.back())},_=(C=y==null?void 0:y.downloads[0])==null?void 0:C.path,x=d.scope==="public"?p.pdf:_&&p.download?p.download(_):null;return S.jsxs("section",{ref:l,className:`chat-artifact-panel${a?" is-dialog":" is-docked"}${e?" is-reader-fallback":""}`,role:a?"dialog":"complementary","aria-modal":a?!0:void 0,"aria-label":d.title,"data-testid":"artifact-panel",children:[S.jsxs("header",{children:[S.jsxs("div",{children:[S.jsx("span",{children:"Posterly artifact"}),S.jsx("h2",{children:d.title})]}),((($=h.data)==null?void 0:$.length)??0)>1&&S.jsxs("label",{className:"chat-artifact-version",children:["Version",S.jsx("select",{"aria-label":"Poster version",value:d.version_id,onChange:j=>t.setVersion(j.target.value),children:[...h.data??[]].reverse().map(j=>S.jsxs("option",{value:j.version_id,children:["v",j.version]},j.version_id))})]}),S.jsx("button",{type:"button","data-artifact-close":!0,"aria-label":a?"Back to conversation":"Close poster",onClick:b,children:S.jsx(h0,{})})]}),S.jsxs("nav",{"aria-label":"Poster views",children:[S.jsx("button",{type:"button","aria-pressed":i.tab==="preview",className:i.tab==="preview"?"active":"",onClick:()=>t.setTab("preview"),children:"Preview"}),d.scope==="owner"&&S.jsx("button",{type:"button","aria-pressed":i.tab==="source",className:i.tab==="source"?"active":"",onClick:()=>t.setTab("source"),children:"Source"})]}),S.jsx("div",{className:"chat-artifact-panel-body",children:i.tab==="preview"?S.jsx("img",{src:p.preview,alt:`Full preview of ${d.title}`}):S.jsxs("div",{className:"chat-artifact-source-workspace",children:[(((I=y==null?void 0:y.source_files)==null?void 0:I.length)??0)>1&&S.jsx("nav",{"aria-label":"Poster source files",children:y.source_files.map(j=>S.jsx("button",{type:"button","aria-pressed":v===j,onClick:()=>t.setSourceFile(j),children:j},j))}),S.jsx("pre",{children:S.jsx("code",{children:g.isError?"Source could not be loaded.":g.data??"Loading source…"})})]})}),S.jsxs("footer",{children:[S.jsxs("div",{className:"chat-artifact-metadata",children:[S.jsx("strong",{children:_L(d.gate_status)}),y&&S.jsxs("span",{children:[y.canvas.width," × ",y.canvas.height," ",y.canvas.unit," · ",y.canvas.orientation," · ",y.direction]}),y==null?void 0:y.gate_summary.map(j=>S.jsx("span",{children:j},j))]}),S.jsxs("div",{className:"chat-artifact-actions",children:[S.jsxs("a",{href:p.png,download:!0,children:[S.jsx(wA,{})," PNG"]}),d.gate_status!=="failed"&&x&&S.jsxs("a",{href:x,download:!0,children:[S.jsx(wA,{})," PDF"]}),d.scope==="owner"&&y&&p.source&&S.jsxs("a",{href:p.source(y.entrypoint),download:!0,children:[S.jsx(sS,{})," HTML"]}),d.scope==="owner"&&y&&p.gate&&S.jsx("a",{href:p.gate(y.gate_report),download:!0,children:"Gate report"}),S.jsxs("a",{href:lne,target:"_blank",rel:"noreferrer",children:[S.jsx(s$,{})," Posterly source · AGPL-3.0"]})]})]})]})},VC=n=>{var t;const{state:e}=um();return((t=e.selected)==null?void 0:t.artifact_kind)==="latex_paper"?S.jsx(ane,{block:e.selected,...n}):S.jsx(une,{...n})},dne=({block:n})=>{const e=um(),t=e.register,s=e.unregister,i=eS(n);if(ee.useEffect(()=>{t(n)},[n,t]),ee.useEffect(()=>()=>s(i),[i,s]),n.status==="generating")return S.jsxs("div",{className:"chat-artifact-card chat-artifact-generating",role:"status",children:[S.jsx("span",{className:"chat-artifact-pulse","aria-hidden":"true"}),S.jsxs("span",{children:[S.jsx("strong",{children:n.title}),S.jsx("small",{children:"Publishing Posterly preview…"})]})]});if(n.status==="error")return S.jsxs("div",{className:"chat-artifact-card chat-artifact-error",role:"alert",children:[S.jsx(sS,{"aria-hidden":"true"}),S.jsxs("span",{children:[S.jsx("strong",{children:n.title}),S.jsx("small",{children:n.error_message??"Poster publication failed."})]})]});const r=wL(n);if(!r)return null;const o=e.state.open&&e.state.selectedKey===i;return S.jsxs("button",{type:"button",className:`chat-artifact-card${o?" is-selected":""}`,"aria-pressed":o,onClick:a=>e.open(n,a.currentTarget),children:[S.jsx("img",{src:r.preview,alt:`Preview of ${n.title}`}),S.jsxs("span",{className:"chat-artifact-card-copy",children:[S.jsxs("span",{className:"chat-artifact-kicker",children:[S.jsx(lD,{"aria-hidden":"true"})," Posterly · v",n.version]}),S.jsx("strong",{children:n.title}),S.jsx("small",{className:`chat-artifact-gate chat-artifact-gate-${n.gate_status}`,children:_L(n.gate_status)})]})]})};function fne(n){if(!n.authors.length)return"";const e=n.authors.slice(0,3).map(t=>t.name).join(", ");return n.authors.length>3?`${e}, et al.`:e}function pne(n){var t;if(n.conference)return n.conference;const e=(t=n.published)==null?void 0:t.slice(0,4);if(n.arxiv_id)return e?`arXiv ${e}`:"arXiv";if(n.source_url)try{return new URL(n.source_url).hostname.replace(/^www\./,"")}catch{}return e??"external"}function mne(n,e=240){const t=n.content.trim();return t.length<=e?t:`${t.slice(0,e).trimEnd()}…`}const gne="https://huggingface.co/pro",yne="https://huggingface.co/docs/inference-providers/pricing",vne="https://paperswithcode.co/chat",SL=()=>S.jsx("span",{className:"chat-caret"}),bne=n=>{var t;if(!n.streaming)return!1;const e=(t=n.blocks)==null?void 0:t.at(-1);return e?e.kind==="reasoning"?!e.active:e.kind==="tool"?e.status!=="running":!1:!0},wne=n=>{var p,m;const e=n.currentTarget,t=e.ownerDocument,s=(p=t.caretPositionFromPoint)==null?void 0:p.call(t,n.clientX,n.clientY),i=s?null:(m=t.caretRangeFromPoint)==null?void 0:m.call(t,n.clientX,n.clientY),r=(s==null?void 0:s.offsetNode)??(i==null?void 0:i.startContainer),o=(s==null?void 0:s.offset)??(i==null?void 0:i.startOffset);if(!(r instanceof Text)||o===void 0||!e.contains(r))return;const a=r.data,l=/[\p{L}\p{M}\p{N}_'-]/u;let c=Math.min(o,a.length),h=c;for(;c>0&&l.test(a[c-1]);)c-=1;for(;h"]+/gi,WC=/[.,;:!?'"\]}>*_]+$/,Sne=n=>{let e=n.replace(WC,"");for(;e.endsWith(")")&&e.split("(").length{const t=[];let s=0;for(const i of n.matchAll(_ne)){const r=Sne(i[0]);r.endsWith("://")||(t.push(n.slice(s,i.index)),t.push(S.jsx("a",{className:"chat-user-link",href:r,target:"_blank",rel:"noopener noreferrer",children:r},`${e}-${i.index}`)),s=i.index+r.length)}return t.push(n.slice(s)),t},xne=({text:n,mentions:e})=>{const t=[];let s=0;for(const i of[...e].sort((r,o)=>r.start-o.start)){const r=n.slice(i.start,i.end);i.startn.length||r!==i.title&&r!==`@${i.title}`||(t.push(...GC(n.slice(s,i.start),`text-${s}`)),t.push(S.jsxs("span",{className:"chat-inline-paper-mention",children:[S.jsx(n$,{size:13,"aria-hidden":"true"}),S.jsx(d0,{routeId:i.route_id,className:"chat-inline-paper-link",children:r.startsWith("@")?r.slice(1):r})]},i.key)),s=i.end)}return t.push(...GC(n.slice(s),`text-${s}`)),S.jsx(S.Fragment,{children:t})},Ane=({block:n,papers:e,citations:t,webCitations:s,onToggle:i})=>n.active?S.jsxs("div",{className:"chat-reason-live",children:[S.jsxs("div",{className:"chat-reason-live-head",children:[S.jsx(nS,{})," ",S.jsx("span",{children:"Thinking…"})]}),S.jsxs("div",{className:"chat-reason-live-body chat-answer chat-reason-markdown",children:[S.jsx(ib,{text:n.text,streaming:!0,papers:e,citations:t,webCitations:s}),S.jsx(SL,{})]})]}):S.jsxs("div",{className:"chat-reason-done",children:[S.jsxs("button",{type:"button",className:"chat-reason-done-head",onClick:i,"aria-expanded":n.open,children:[S.jsx(zL,{}),S.jsx("span",{children:"Thought for a few seconds"}),S.jsx(e$,{open:n.open})]}),n.open&&S.jsx("div",{className:"chat-reason-done-body chat-answer chat-reason-markdown",children:S.jsx(ib,{text:n.text,papers:e,citations:t,webCitations:s})})]}),kne=({block:n,papers:e,onToggle:t})=>{var d,p,m,y;const s=n.status==="running",i=s&&n.argumentState==="streaming",r=n.schema_version===2||!!n.content,o=n.status==="error"||n.status==="denied",a=typeof n.args.query=="string"?n.args.query:"",l=typeof n.args.command=="string"?n.args.command:typeof n.args.file_path=="string"?n.args.file_path:a,c=n.name.startsWith("pwc_")?Object.entries(n.args).filter(([,v])=>v!=null&&v!=="").map(([v,g])=>`${v}=${typeof g=="string"?g:JSON.stringify(g)}`).join(" · "):r?l:`("${a}")`,h=((d=n.content)==null?void 0:d.map(v=>v.text).join(""))??"",u=i?"streaming arguments…":s?"running…":r?`${n.status} · ${n.took_ms??0} ms`:`${n.hits} results · ${n.took_ms} ms`;return S.jsxs("div",{className:`chat-tool${s?" chat-tool-running":""}${o?" chat-tool-failed":""}`,children:[S.jsxs("button",{type:"button",className:"chat-tool-head",onClick:t,"aria-expanded":n.open,children:[S.jsxs("span",{className:"chat-tool-head-left",children:[s?S.jsx(nS,{}):S.jsx(HL,{}),S.jsx("code",{className:"chat-tool-name",children:n.name}),S.jsx("span",{className:"chat-tool-query",title:c,children:c})]}),S.jsxs("span",{className:"chat-tool-head-right",children:[S.jsx("span",{className:"chat-tool-status",children:u}),S.jsx(e$,{open:n.open})]})]}),n.open&&S.jsxs("div",{className:"chat-tool-body",children:[S.jsxs("div",{className:"chat-tool-args",children:[S.jsxs("span",{className:"chat-tool-label",children:["arguments",n.arguments_redacted?" · redacted":""]}),S.jsx("pre",{children:n.argumentState==="streaming"&&!n.arguments_redacted&&n.argumentText||JSON.stringify(n.args,null,2)})]}),!s&&r?S.jsxs(S.Fragment,{children:[S.jsxs("div",{className:"chat-tool-output-head",children:[S.jsx("span",{className:"chat-tool-label",children:"result"}),S.jsx("button",{type:"button",className:"chat-tool-copy",onClick:()=>void navigator.clipboard.writeText(h),children:"Copy"})]}),S.jsx("pre",{className:"chat-tool-output",children:S.jsx("code",{children:h})}),((p=n.metadata)==null?void 0:p.output_truncated)&&S.jsx("div",{className:"chat-tool-truncated",children:"Output was truncated."})]}):s?null:S.jsxs(S.Fragment,{children:[S.jsxs("div",{className:"chat-tool-label chat-tool-results-label",children:["returned ",((m=n.results)==null?void 0:m.length)??0," papers"]}),S.jsx("ol",{className:"chat-tool-results",children:(y=n.results)==null?void 0:y.map(v=>S.jsxs("li",{className:"chat-hit",children:[S.jsx("div",{className:"chat-hit-top",children:S.jsx(h$,{routeId:v.route_id,paper:e[v.route_id],className:"chat-hit-title",children:v.title})}),S.jsx("div",{className:"chat-hit-meta",children:[fne(v.metadata),pne(v.metadata)].filter(Boolean).join(" · ")}),S.jsxs("div",{className:"chat-hit-snippet",children:[mne(v),v.content_truncated&&S.jsx("span",{className:"chat-hit-truncated",children:" (truncated)"})]})]},v.route_id))})]})]})]})},Ene=({block:n,papers:e,citations:t,webCitations:s,streaming:i})=>S.jsxs("div",{className:"chat-answer",children:[S.jsx(ib,{text:n.text,streaming:i,papers:e,citations:t,webCitations:s}),i&&!!n.text.trim()&&S.jsx(SL,{})]}),Cne=({block:n})=>S.jsx(z6,{block:n}),xL=n=>{const e=ee.useRef(null),t=ee.useCallback(()=>{const s=e.current;if(!s)return;s.style.height="auto";const i=Math.max(120,window.innerHeight*.4);s.style.height=`${Math.min(s.scrollHeight,i)}px`,s.style.overflowY=s.scrollHeight>i?"auto":"hidden"},[]);return ee.useLayoutEffect(()=>{var s,i;(s=e.current)==null||s.focus(),(i=e.current)==null||i.setSelectionRange(n.length,n.length),t()},[t,n.length]),{textareaRef:e,resize:t}},$ne=({id:n,text:e,paperSelection:t,editNotice:s,onCancel:i,onResend:r,onResendDraft:o})=>{const[a,l]=ee.useState(e),[c,h]=ee.useState(t),[u,d]=ee.useState(!1),{textareaRef:p,resize:m}=xL(e);ee.useLayoutEffect(m,[m,a]);const y=!!a.trim()&&a.length<=8e3,v=()=>{if(!y||u)return;d(!0),((o==null?void 0:o({text:a,paperMentions:[],...c?{paperSelection:c}:{}}))??(r==null?void 0:r(a))??!1)||d(!1)};return S.jsx("div",{className:"chat-msg chat-msg-user chat-msg-user-editing","data-message-id":n,children:S.jsxs("div",{className:"chat-inline-editor",children:[c&&S.jsx(f0,{selection:c,editable:!0,onRemove:()=>h(void 0)}),S.jsx("textarea",{ref:p,className:"chat-inline-editor-textarea","aria-label":"Edit message",value:a,maxLength:8e3,onChange:g=>l(g.target.value),onKeyDown:g=>{g.key==="Escape"?(g.preventDefault(),i==null||i()):g.key==="Enter"&&!g.shiftKey&&!g.nativeEvent.isComposing&&(g.preventDefault(),v())}}),s&&S.jsx("div",{className:"chat-inline-editor-notice",children:s}),S.jsxs("div",{className:"chat-inline-editor-actions",children:[S.jsx("button",{type:"button",onClick:i,children:"Cancel"}),S.jsx("button",{type:"button",className:"chat-inline-editor-send",disabled:!y||u,onClick:v,children:"Send"})]})]})})},Tne=({id:n,text:e,paperMentions:t,paperSelection:s,enabled:i,editNotice:r,onCancel:o,onResend:a,onResendDraft:l})=>{const[c,h]=ee.useState({text:e,paperMentions:t,...s?{paperSelection:s}:{}}),[u,d]=ee.useState(!1),[p,m]=ee.useState(0),{textareaRef:y,resize:v}=xL(e),g=YC({draft:c,onChange:h,enabled:i,textareaRef:y});ee.useLayoutEffect(v,[v,c.text]);const b=!!c.text.trim()&&c.text.length<=8e3&&(i||c.paperMentions.length===0),_=()=>{if(!b||u)return;d(!0),((l==null?void 0:l(c))??(a==null?void 0:a(c.text))??!1)||d(!1)};return S.jsx("div",{className:"chat-msg chat-msg-user chat-msg-user-editing","data-message-id":n,children:S.jsxs("div",{className:"chat-inline-editor",children:[c.paperSelection&&S.jsx(f0,{selection:c.paperSelection,editable:!0,onRemove:()=>h({text:c.text,paperMentions:c.paperMentions})}),S.jsxs("div",{className:"chat-inline-editor-textarea-wrap",children:[S.jsx(JC,{text:c.text,mentions:c.paperMentions,scrollTop:p,variant:"editor"}),S.jsx("textarea",{ref:y,className:"chat-inline-editor-textarea","aria-label":"Edit message",value:c.text,maxLength:8e3,role:"combobox","aria-autocomplete":"list","aria-expanded":g.open,"aria-controls":g.open?g.pickerId:void 0,"aria-activedescendant":g.open&&g.results.length?`${g.optionIdPrefix}-${g.activeIndex}`:void 0,onChange:x=>g.updateText(x.target.value,x.target.selectionStart),onSelect:x=>g.refresh(x.currentTarget.selectionStart),onScroll:x=>m(x.currentTarget.scrollTop),onKeyDown:x=>{g.keyDown(x)||(x.key==="Escape"?(x.preventDefault(),o==null||o()):x.key==="Enter"&&!x.shiftKey&&!x.nativeEvent.isComposing&&(x.preventDefault(),_()))}}),S.jsx(QC,{open:g.open,query:g.query,results:g.results,activeIndex:g.activeIndex,loading:g.loading,error:g.error,onSelect:g.select,id:g.pickerId,optionIdPrefix:g.optionIdPrefix})]}),!i&&c.paperMentions.length>0&&S.jsx("div",{className:"chat-inline-editor-notice",role:"status",children:"Paper mentions are currently disabled. Remove them before sending."}),r&&S.jsx("div",{className:"chat-inline-editor-notice",children:r}),S.jsxs("div",{className:"chat-inline-editor-actions",children:[S.jsx("button",{type:"button",onClick:o,children:"Cancel"}),S.jsx("button",{type:"button",className:"chat-inline-editor-send",disabled:!b||u,onClick:_,children:"Send"})]})]})})},fse=({id:n,text:e,paperMentions:t=[],paperSelection:s,paperMentionsEnabled:i=!1,editingAllowed:r=!1,editing:o=!1,editNotice:a,onEdit:l,onCancel:c,onResend:h,onResendDraft:u})=>{const[d,p]=ee.useState(!1),m=ee.useRef(null);ee.useEffect(()=>()=>{m.current!==null&&window.clearTimeout(m.current)},[]);const y=async()=>{var v;if((v=navigator.clipboard)!=null&&v.writeText)try{await navigator.clipboard.writeText(e),p(!0),m.current!==null&&window.clearTimeout(m.current),m.current=window.setTimeout(()=>p(!1),1500)}catch{}};return o?!i&&t.length===0?S.jsx($ne,{id:n,text:e,paperSelection:s,editNotice:a,onCancel:c,onResend:h,onResendDraft:u}):S.jsx(Tne,{id:n,text:e,paperMentions:t,paperSelection:s,enabled:i,editNotice:a,onCancel:c,onResend:h,onResendDraft:u}):S.jsx("div",{className:"chat-msg chat-msg-user","data-message-id":n,children:S.jsxs("div",{className:"chat-user-message-wrap",children:[s&&S.jsx(f0,{selection:s}),S.jsx("div",{className:"chat-bubble",onDoubleClick:wne,children:S.jsx(xne,{text:e,mentions:t})}),S.jsxs("div",{className:"chat-user-actions",children:[S.jsx("button",{type:"button",className:"chat-user-action","aria-label":d?"Message copied":"Copy message",title:d?"Copied":"Copy",onClick:()=>void y(),children:d?S.jsx(OL,{"aria-hidden":"true"}):S.jsx(QL,{"aria-hidden":"true"})}),r&&S.jsx("button",{type:"button",className:"chat-user-action","aria-label":"Edit message",title:"Edit",onClick:l,children:S.jsx(o$,{"aria-hidden":"true"})})]})]})})},pse=({msg:n,papers:e,onToggleBlock:t,onRetryCompaction:s,onRetryWithLuna:i,onArchiveOldChats:r,onArchiveOldestChats:o,archivePending:a=null,hfBilling:l=null,openRouterFallbackEnabled:c=!1,feedbackEnabled:h=!1})=>{var j,q,L,B;const[u,d]=ee.useState(null),[p,m]=ee.useState(!1),[y,v]=ee.useState(!1),[g,b]=ee.useState(!1),[_,x]=ee.useState(""),A=ee.useRef(null),C=`chat-feedback-panel-${n.id}`,$=h&&!n.streaming&&!n.error&&!!((j=n.blocks)!=null&&j.some(H=>H.kind==="answer"&&H.text.trim()));ee.useEffect(()=>{var H;g&&((H=A.current)==null||H.focus())},[g]);const I=async(H,D)=>{if(!p){m(!0),v(!1);try{D===void 0?await bA.reportFeedback(n.id,H):await bA.reportFeedback(n.id,H,D),d(H),b(!1),x("")}catch{v(!0)}finally{m(!1)}}};return S.jsx("div",{className:"chat-msg chat-msg-assistant",children:S.jsxs("div",{className:"chat-msg-blocks",children:[(q=n.blocks)==null?void 0:q.map((H,D)=>{var ye;const X=`${n.id}-${D}`,te="citations"in H&&H.citations!==void 0?H.citations:n.citations??[],J=Object.fromEntries(te.filter(z=>(z.kind==="catalog_paper"||z.kind==="paper"||!z.kind&&z.route_id)&&z.route_id).map(z=>[z.route_id,z])),Y=Object.fromEntries(te.filter(z=>(z.kind==="external_source"||z.kind==="web")&&z.url).map(z=>[z.url,z]));return H.kind==="reasoning"?S.jsx(Ane,{block:H,papers:e,citations:J,webCitations:Y,onToggle:()=>t(n.id,D)},X):H.kind==="tool"?S.jsx(kne,{block:H,papers:e,onToggle:()=>t(n.id,D)},X):H.kind==="app"?S.jsx(Cne,{block:H},H.instance_id||X):H.kind==="artifact"?S.jsx(dne,{block:H},H.publication_id||H.version_id||X):S.jsx(Ene,{block:H,papers:e,citations:J,webCitations:Y,streaming:!!(n.streaming&&D===(((ye=n.blocks)==null?void 0:ye.length)??0)-1)},X)}),n.streaming&&n.compacting&&S.jsx(fD,{}),!n.compacting&&bne(n)&&S.jsx("div",{className:"chat-waiting",role:"status","aria-live":"polite",children:S.jsx("span",{className:"chat-thinking",children:(((L=n.blocks)==null?void 0:L.length)??0)===0?n.status??"Thinking…":"Thinking…"})}),n.error&&S.jsxs("div",{className:"chat-error",children:[((B=n.blocks)==null?void 0:B.some(H=>H.kind==="answer"&&H.text.trim()))&&S.jsx("strong",{children:"Incomplete—response interrupted. "}),["context_too_large","provider_error","persistence_error"].includes(n.errorCode??"")&&s&&S.jsx("button",{type:"button",onClick:s,children:"Retry"}),S.jsx("span",{children:n.errorCode==="chat_disabled_interrupted"?"Chat was disabled while this response was running. The partial response is saved. Please try again later.":n.errorCode==="chat_session_quota_exceeded"?n.error:`The assistant hit an error: ${n.error}`}),["hf_inference_billing_required","hf_inference_credential_expired"].includes(n.errorCode??"")&&S.jsx("a",{href:"/settings",children:"Re-sign in with Hugging Face"}),n.errorCode==="hf_inference_billing_exhausted"&&S.jsxs(S.Fragment,{children:[i&&S.jsx("button",{type:"button",onClick:i,children:"Retry with GPT-6 Luna"}),(l==null?void 0:l.account_type)==="Free"&&!l.bill_to?S.jsx("a",{href:gne,target:"_blank",rel:"noreferrer",children:"Upgrade to Hugging Face PRO — $9/month for 20× more included credits"}):S.jsx("a",{href:(l==null?void 0:l.usage_url)??"/settings",target:l?"_blank":void 0,rel:l?"noreferrer":void 0,children:"Review Hugging Face usage and billing"}),S.jsx("a",{href:yne,target:"_blank",rel:"noreferrer",children:"Inference Providers pricing and billing details"})]}),n.errorCode==="hf_sponsored_unavailable"&&i&&S.jsx("button",{type:"button",onClick:i,children:"Retry with GPT-6 Luna"}),n.errorCode==="openrouter_monthly_budget_exhausted"&&S.jsxs(S.Fragment,{children:[c?S.jsx("span",{children:"This response started on the shared allowance. Your connected OpenRouter key will be used when you explicitly retry."}):S.jsx("a",{href:"/settings#openrouter-byok",children:"Connect your own OpenRouter key"}),S.jsx("span",{children:"Or select a Hugging Face-backed model and explicitly retry."})]}),n.errorCode==="openrouter_staging_funding_disabled"&&S.jsx("a",{href:vne,children:"Continue on paperswithcode.co"}),n.errorCode==="openrouter_unavailable"&&S.jsxs(S.Fragment,{children:[S.jsx("a",{href:"/settings#openrouter-byok",children:"Bring your own key in Settings"}),S.jsx("a",{href:"https://github.com/huggingface/paperswithcode-feedback",target:"_blank",rel:"noreferrer",children:"File an issue"})]}),n.errorCode==="openrouter_byok_billing_error"&&S.jsx("a",{href:"https://openrouter.ai/settings/credits",target:"_blank",rel:"noreferrer",children:"Review OpenRouter billing"}),["openrouter_byok_credential_invalid","openrouter_byok_rate_limit"].includes(n.errorCode??"")&&S.jsx("a",{href:"/settings#openrouter-byok",children:"Review OpenRouter settings"}),n.errorCode==="chat_session_quota_exceeded"&&(r||o)&&S.jsxs("span",{className:"chat-error-actions",children:[r&&S.jsx("button",{type:"button",disabled:a!==null,onClick:r,children:a==="old"?"Archiving…":"Archive chats older than 30 days"}),o&&S.jsx("button",{type:"button",disabled:a!==null,onClick:o,children:a==="oldest"?"Archiving…":"Archive oldest 50 chats"})]})]}),!n.streaming&&n.finishReason&&!["success","scope_blocked"].includes(n.finishReason)&&S.jsx("div",{className:"chat-finish-note",children:["tool_limit","max_turns"].includes(n.finishReason)?"The assistant stopped at the execution limit.":`The assistant stopped early (${n.finishReason.replace(/_/g," ")}).`}),$&&S.jsxs("div",{className:"chat-feedback","aria-label":"Rate this response",children:[S.jsx("span",{className:"chat-feedback-label",children:u===null?"Was this helpful?":"Thanks for your feedback"}),S.jsx("button",{type:"button",className:`chat-feedback-action${u===!0?" chat-feedback-action-selected":""}`,"aria-label":"Helpful response","aria-pressed":u===!0,disabled:p,onClick:()=>{b(!1),I(!0)},children:S.jsx(eD,{"aria-hidden":"true"})}),S.jsx("button",{type:"button",className:`chat-feedback-action${u===!1?" chat-feedback-action-selected":""}`,"aria-label":"Unhelpful response","aria-pressed":u===!1,"aria-expanded":g,"aria-controls":C,disabled:p,onClick:()=>{v(!1),b(!0)},children:S.jsx(uD,{"aria-hidden":"true"})}),y&&S.jsx("span",{className:"chat-feedback-error",role:"status",children:"Couldn’t send feedback."})]}),$&&g&&S.jsxs("div",{className:"chat-feedback-panel",id:C,role:"group","aria-labelledby":`${C}-title`,children:[S.jsx("div",{className:"chat-feedback-panel-title",id:`${C}-title`,children:"Additional feedback"}),S.jsx("label",{className:"chat-feedback-panel-label",htmlFor:`${C}-comment`,children:"Tell us what went wrong (optional)"}),S.jsx("textarea",{ref:A,id:`${C}-comment`,className:"chat-feedback-comment",value:_,maxLength:500,rows:4,disabled:p,onChange:H=>x(H.target.value),onKeyDown:H=>{H.key==="Escape"&&(H.preventDefault(),b(!1))}}),S.jsxs("div",{className:"chat-feedback-panel-actions",children:[S.jsx("button",{type:"button",className:"chat-feedback-skip",disabled:p,onClick:()=>void I(!1),children:"Skip"}),S.jsx("button",{type:"button",className:"chat-feedback-submit",disabled:p,onClick:()=>void I(!1,_.trim()||void 0),children:p?"Submitting…":"Submit"})]})]})]})})},Pne={chat:{breakpoint:760,left:360,right:360},shared:{breakpoint:760,left:360,right:360},reader:{breakpoint:1260,left:840,right:420}};function Wa(n,e,t,s){if(!n)return Math.max(25,Math.min(75,e));const i=Math.max(25,s/n*100),r=Math.min(75,(n-t)/n*100);return Math.max(i,Math.min(r,e))}const mse=({children:n,variant:e})=>{var b;const t=um(),s=Pne[e],i=ee.useRef(null),r=ee.useRef(null),o=ee.useRef(null),a=ee.useRef(null),[l,c]=ee.useState(0),h=ee.useRef(!1),u=ee.useRef(t.state.panelPercent);ee.useLayoutEffect(()=>{const _=i.current;if(!_)return;const x=()=>c(_.clientWidth||window.innerWidth);if(x(),typeof ResizeObserver>"u")return;const A=new ResizeObserver(x);return A.observe(_),()=>A.disconnect()},[]);const d=t.state.open&&l>=s.breakpoint,p=Wa(l,t.state.panelPercent,s.left,s.right),m=((b=t.state.selected)==null?void 0:b.artifact_kind)==="latex_paper"?"paper":"poster",y=_=>{var A;const x=Wa(l,_,s.left,s.right);u.current=x,r.current&&(r.current.style.width=`${100-x}%`),o.current&&(o.current.style.width=`${x}%`),(A=a.current)==null||A.setAttribute("aria-valuenow",String(Math.round(x)))},v=_=>{var A;const x=(A=i.current)==null?void 0:A.getBoundingClientRect();x!=null&&x.width&&y((x.right-_)/x.width*100)},g=()=>{h.current&&(h.current=!1,t.setPanelPercent(u.current))};return S.jsxs("div",{ref:i,className:`chat-artifact-workspace chat-artifact-workspace-${e}${d?" has-docked-artifact":""}`,"data-artifact-layout":d?"split":t.state.open?"dialog":"closed",children:[S.jsx("div",{ref:r,className:"chat-artifact-workspace-content",style:d?{width:`${100-p}%`}:void 0,children:n}),d&&S.jsxs(S.Fragment,{children:[S.jsx("div",{ref:a,className:"chat-artifact-resize-handle",role:"separator","aria-label":`Resize conversation and ${m} panels`,"aria-orientation":"vertical","aria-valuemin":Math.ceil(Wa(l,0,s.left,s.right)),"aria-valuemax":Math.floor(Wa(l,100,s.left,s.right)),"aria-valuenow":Math.round(p),tabIndex:0,onPointerDown:_=>{h.current=!0,_.currentTarget.setPointerCapture(_.pointerId),v(_.clientX)},onPointerMove:_=>{h.current&&v(_.clientX)},onPointerUp:g,onPointerCancel:g,onLostPointerCapture:g,onDoubleClick:()=>t.setPanelPercent(55),onKeyDown:_=>{(_.key==="ArrowLeft"||_.key==="ArrowRight")&&(_.preventDefault(),t.setPanelPercent(Wa(l,p+(_.key==="ArrowLeft"?2:-2),s.left,s.right))),_.key==="Home"&&t.setPanelPercent(Wa(l,25,s.left,s.right)),_.key==="End"&&t.setPanelPercent(Wa(l,75,s.left,s.right))}}),S.jsx("div",{ref:o,className:"chat-artifact-workspace-pane",style:{width:`${p}%`},children:S.jsx(VC,{})})]}),t.state.open&&!d&&S.jsx(VC,{forceDialog:!0,readerFallback:e==="reader"})]})};export{dse as A,ese as C,zY as P,qX as R,fse as U,mse as a,pse as b,um as c,tse as d,TD as e,use as f,eS as g,HX as u};