@cmmd-center/forge 0.13.145 → 0.13.147
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bin.cjs +2 -2
- package/dist/bin.mjs +2 -2
- package/dist/client/assets/{DiffPanel-AFcxOGec.js → DiffPanel-CRtOf1s5.js} +2 -2
- package/dist/client/assets/{DiffPanel.logic-B6HwSAPK.js → DiffPanel.logic-CmcQ9FUZ.js} +2 -2
- package/dist/client/assets/{DiffWorkerPoolProvider-CPaAxbdi.js → DiffWorkerPoolProvider-Bkez9ZCy.js} +2 -2
- package/dist/client/assets/{PullRequestCodePanel-D6FHc9jK.js → PullRequestCodePanel-5jqG5E0W.js} +2 -2
- package/dist/client/assets/{Virtualizer-dYU21qI9.js → Virtualizer-CUdui9JA.js} +2 -2
- package/dist/client/assets/{WorkerPoolContext-CV6s1EQI.js → WorkerPoolContext-Dx0gHk2i.js} +44 -44
- package/dist/client/assets/{cmmdForgeRuntimeListResource-Dms9ZD2I.js → cmmdForgeRuntimeListResource-2SDxX78O.js} +4 -4
- package/dist/client/assets/{currentForgeWorkspaceStore-H6HxAqJy.js → currentForgeWorkspaceStore-hnA9s1Di.js} +2 -2
- package/dist/client/assets/index-w8XUlHFk.js +301 -0
- package/dist/client/index.html +6 -6
- package/dist/forge-build.json +1 -1
- package/package.json +1 -1
- package/dist/client/assets/index-DH8z2b5W.js +0 -301
|
@@ -1,36 +1,36 @@
|
|
|
1
1
|
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/workspaceReadinessAtom-D6bgTvKb.js","assets/rolldown-runtime-hePW80VL.js","assets/atomRegistry-C1yW8tyM.js","assets/Stream-mUTFnSY9.js","assets/angular-html-B8mrqUL5.js","assets/html-XwrE-1r6.js","assets/javascript-obGGvMPs.js","assets/css-CNuuLpMC.js","assets/angular-ts-Bzix210W.js","assets/scss-YesllqfO.js","assets/apl-Dhin1L29.js","assets/xml-BlnrEAEy.js","assets/java-DdHNQ9hk.js","assets/json-DAgxKhMr.js","assets/astro-B-4NNgOP.js","assets/typescript-BydbNFcO.js","assets/postcss-BXeXVLqQ.js","assets/tsx-CUOciP0b.js","assets/blade-Wr94ul2N.js","assets/html-derivative-i4STDFnl.js","assets/sql-ClgswhA6.js","assets/bsl-BkkzgIyY.js","assets/sdbl-bTVj8UrX.js","assets/c-iCihek07.js","assets/cairo-DLTphjLi.js","assets/python-gzcpVVnB.js","assets/cobol-Cw2-KvLW.js","assets/coffee-CiiSLhB6.js","assets/cpp-DjoE5qBx.js","assets/regexp-DR20uMnK.js","assets/glsl-D5MA2a_X.js","assets/crystal-wCJpIkgB.js","assets/shellscript-Da78Ox-3.js","assets/edge-DCY0a-ow.js","assets/elixir-DP304Xio.js","assets/elm-o4NJxfws.js","assets/erb-BcNYoZVd.js","assets/ruby-2bd251b9.js","assets/haml-CwEpbK1d.js","assets/graphql-Ctjuxyvl.js","assets/jsx-gTgmArGx.js","assets/lua-FONpmTUP.js","assets/yaml-Du_6cdrH.js","assets/erlang-Cphh6RMH.js","assets/markdown-BYOwaDjH.js","assets/fortran-fixed-form-DEKoE2YW.js","assets/fortran-free-form-CYNrtFtB.js","assets/fsharp-D13ZGOAj.js","assets/gdresource-C0sCabJj.js","assets/gdshader-CBce3t8t.js","assets/gdscript-Cp2uCuqX.js","assets/git-commit-BSykSTBG.js","assets/diff-woXpYk--.js","assets/git-rebase-BDPpS8w6.js","assets/glimmer-js-BONyzAsu.js","assets/glimmer-ts-f9c0GCOe.js","assets/hack-7ztQ7Up-.js","assets/handlebars-ryMP1rBR.js","assets/http-kmH8AyfE.js","assets/hurl-DCZHXKU4.js","assets/csv-Dx-8-gkx.js","assets/hxml-B0Qn7Nwc.js","assets/haxe-OTjmBuCE.js","assets/jinja-B-tLrNsM.js","assets/jison-CBjhYtSs.js","assets/julia-CjHxn3vf.js","assets/r-D6UWEOL2.js","assets/just-CZ9bduw9.js","assets/perl-BAov3eih.js","assets/latex-D9bvcAJr.js","assets/tex-0w6-Dtgt.js","assets/liquid-G0MH4h_m.js","assets/marko-DV5GrDmo.js","assets/less-DVTAwKKz.js","assets/mdc-cg1lnqpW.js","assets/nextflow-BJtWHP5T.js","assets/nextflow-groovy-DJMQeKeT.js","assets/nginx-BTMw9COX.js","assets/nim-B6yJ_yaC.js","assets/php-Cg76ANFt.js","assets/pug-DkgDHZci.js","assets/qml-_a-QhfPD.js","assets/razor-D3EoCAik.js","assets/csharp-Ct8U2NOr.js","assets/rst-YTmaoyaq.js","assets/cmake-Bj61d0ZC.js","assets/sas-B6p8-ynO.js","assets/shaderlab-TOUzSsQk.js","assets/hlsl-Cvrh5tZx.js","assets/shellsession-CVsQGYfZ.js","assets/soy-DEd-qcad.js","assets/sparql-D_iOobhT.js","assets/turtle-ByJddavk.js","assets/stata-RoaAgbqU.js","assets/surrealql-DIn4NJsS.js","assets/svelte-Bj3Hmc9F.js","assets/templ-TjxbArHn.js","assets/go-rLFTqkRN.js","assets/ts-tags-DFwAVxhO.js","assets/twig-BbcH-NR0.js","assets/vue-BNi0qJZP.js","assets/vue-html-DkKkQnZL.js","assets/vue-vine-DFaKYU4X.js","assets/stylus-B6D30XZt.js","assets/xsl-BOPS8gLt.js"])))=>i.map(i=>d[i]);
|
|
2
|
-
import{n as e,r as t,t as n}from"./rolldown-runtime-hePW80VL.js";import{$ as r,$t as i,Aa as a,An as o,Ar as s,At as c,B as l,Br as u,Bt as d,Ci as f,Dn as p,Ei as m,En as h,Er as g,Fa as _,Fi as v,Fn as y,Gn as b,Gt as x,Ha as ee,Hn as te,Hr as ne,Ht as re,Ia as ie,It as ae,J as oe,Jt as se,Kt as ce,L as le,La as ue,Ln as de,Lt as fe,M as pe,Ma as me,Mr as he,Ni as ge,Nn as _e,Nt as ve,Pi as ye,Pn as be,Pt as xe,Qi as Se,Rn as Ce,Rr as we,Rt as Te,Si as Ee,Ta as De,Tn as Oe,Tr as ke,Tt as Ae,Ua as je,Un as Me,Ur as Ne,Ut as Pe,V as Fe,Va as Ie,Vn as Le,Vr as Re,Vt as ze,W as Be,Wa as Ve,Wn as He,Wr as Ue,Wt as We,X as Ge,Yi as Ke,Yt as qe,Z as Je,Zi as Ye,_ as Xe,_t as Ze,an as Qe,at as $e,bn as et,br as tt,bt as nt,ca as rt,ci as it,ct as at,dn as ot,ea as st,en as ct,et as lt,fi as ut,gi as dt,gn as ft,hn as pt,hr as mt,ht,in as gt,it as _t,ja as vt,jn as yt,jr as bt,jt as xt,ki as St,kr as Ct,kt as wt,li as Tt,ln as Et,m as Dt,mn as Ot,mr as kt,na as At,ni as jt,nt as Mt,oa as Nt,or as Pt,pn as Ft,pt as It,q as Lt,qt as Rt,r as zt,rn as Bt,rr as Vt,rt as Ht,sn as Ut,un as Wt,ut as Gt,vn as Kt,vr as qt,wn as Jt,wr as Yt,wt as Xt,xi as Zt,xn as Qt,y as $t,yi as en,yn as tn,z as nn,zn as rn,zt as an}from"./Stream-mUTFnSY9.js";import{i as on,l as sn,n as cn,o as ln,s as un}from"./atomRegistry-C1yW8tyM.js";import{Sn as dn}from"./CompositeItem-DTyKsv13.js";import{$ as fn,A as pn,B as mn,Bn as hn,C as gn,D as _n,Dt as vn,G as yn,H as S,Hn as C,Jn as bn,Kn as xn,L as Sn,Ln as Cn,M as wn,N as Tn,O as En,Q as Dn,Qt as On,Rt as kn,S as An,Sn as jn,T as Mn,Tn as Nn,U as Pn,Un as Fn,Vn as In,Wn as Ln,Wt as Rn,X as zn,Y as Bn,Yt as Vn,Z as Hn,_n as Un,at as Wn,ct as Gn,dn as Kn,dt as qn,fn as Jn,gn as Yn,gt as Xn,hn as Zn,ht as Qn,in as $n,it as er,ln as tr,lt as nr,mn as rr,mt as ir,ot as ar,pn as or,qn as sr,rn as cr,st as lr,t as ur,tn as dr,tt as fr,un as pr,ut as mr,vt as hr,w as gr,wn as _r,yn as vr,yt as yr,zn as br}from"./cmmdForgeRuntimeListResource-Dms9ZD2I.js";import{$t as xr,A as Sr,At as Cr,Bt as wr,C as Tr,Ct as Er,Dt as Dr,En as Or,Et as kr,G as Ar,Gn as jr,Gt as Mr,Hn as Nr,Ht as Pr,In as w,Jt as Fr,Kn as Ir,Kt as Lr,Lt as Rr,Mt as zr,Nn as Br,Nt as Vr,Ot as Hr,Q as Ur,Qt as Wr,R as Gr,Rt as Kr,Sn as qr,U as Jr,Un as Yr,Ut as Xr,Vn as Zr,Vt as Qr,W as $r,Wn as ei,Wt as ti,Xt as ni,Yn as ri,Yt as ii,Zt as ai,_n as oi,_t as si,an as ci,b as li,c as ui,cn as di,dt as fi,en as pi,er as mi,ft as hi,gn as gi,gt as _i,hn as vi,in as yi,j as bi,jt as xi,kn as Si,l as Ci,mt as wi,nn as Ti,nt as Ei,on as Di,pn as Oi,qt as ki,rt as Ai,s as T,sn as ji,tn as Mi,tt as Ni,ut as Pi,vn as E,vt as Fi,w as Ii,x as Li,xn as Ri,yn as zi,zn as Bi,zt as Vi}from"./src-B_wrKHuq.js";import{$ as Hi,A as Ui,B as Wi,C as Gi,D as Ki,E as qi,F as Ji,G as Yi,H as Xi,I as Zi,J as Qi,K as $i,L as ea,N as ta,O as na,P as ra,Q as ia,R as aa,T as oa,U as sa,W as ca,X as la,Y as ua,Z as da,_ as fa,et as pa,it as ma,nt as ha,q as ga,rt as _a,tt as va,w as ya}from"./cmmdAuthRedirect-DRkKjx0G.js";import{d as ba,f as xa,n as Sa,t as Ca}from"./utils-xQJ3ak-X.js";import{t as D}from"./preload-helper-Czpn1I53.js";import{t as wa}from"./react-D4GEJ3ir.js";import{t as Ta}from"./transport-CgH8pQK3.js";import{a as Ea,i as Da,n as Oa,r as ka,t as Aa}from"./debouncer-BEV7Iuwb.js";import{n as ja,t as Ma}from"./workspaceReadinessAtom-D6bgTvKb.js";import{a as Na,c as Pa,n as Fa,r as Ia,s as La,u as Ra}from"./themePalette-BWvBK22X.js";function za(e){return e[e.length-1]}function Ba(e,t){return typeof e==`function`?e(t):e}var Va=Object.prototype.hasOwnProperty,Ha=Object.prototype.propertyIsEnumerable;function Ua(e){for(let t in e)if(Va.call(e,t))return!0;return!1}var Wa=()=>Object.create(null),Ga=(e,t)=>Ka(e,t,Wa);function Ka(e,t,n=()=>({}),r=0){if(e===t)return e;if(r>500)return t;let i=t,a=Xa(e)&&Xa(i);if(!a&&!(Ja(e)&&Ja(i)))return i;let o=a?e:qa(e);if(!o)return i;let s=a?i:qa(i);if(!s)return i;let c=o.length,l=s.length,u=a?Array(l):n(),d=0;for(let t=0;t<l;t++){let o=a?t:s[t],l=e[o],f=i[o];if(l===f){u[o]=l,(a?t<c:Va.call(e,o))&&d++;continue}if(l===null||f===null||typeof l!=`object`||typeof f!=`object`){u[o]=f;continue}let p=Ka(l,f,n,r+1);u[o]=p,p===l&&d++}return c===l&&d===c?e:u}function qa(e){let t=Object.keys(e);if(t.length!==Object.getOwnPropertyNames(e).length)return!1;let n=Object.getOwnPropertySymbols(e);if(n.length===0)return t;for(let r of n){if(!Ha.call(e,r))return!1;t.push(r)}return t}function Ja(e){if(!Ya(e))return!1;let t=e.constructor;if(t===void 0)return!0;let n=t.prototype;return!(!Ya(n)||!n.hasOwnProperty(`isPrototypeOf`))}function Ya(e){return Object.prototype.toString.call(e)===`[object Object]`}function Xa(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function Za(e,t,n){if(e===t)return!0;if(typeof e!=typeof t)return!1;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let r=0,i=e.length;r<i;r++)if(!Za(e[r],t[r],n))return!1;return!0}if(Ja(e)&&Ja(t)){let r=n?.ignoreUndefined??!0;if(n?.partial){for(let i in t)if((!r||t[i]!==void 0)&&!Za(e[i],t[i],n))return!1;return!0}let i=0;if(!r)i=Object.keys(e).length;else for(let t in e)e[t]!==void 0&&i++;let a=0;for(let o in t)if((!r||t[o]!==void 0)&&(a++,a>i||!Za(e[o],t[o],n)))return!1;return i===a}return!1}var Qa=/[\x00-\x1f\x7f"<>`{}]/g;function $a(e){return e.replace(Qa,e=>`%`+e.charCodeAt(0).toString(16).toUpperCase().padStart(2,`0`))}function eo(e){let t;try{t=decodeURI(e)}catch{t=e.replaceAll(/%[0-9A-F]{2}/gi,e=>{try{return decodeURI(e)}catch{return e}})}return $a(t)}var to=[`http:`,`https:`,`mailto:`,`tel:`];function no(e,t){if(!e)return!1;try{let n=new URL(e);return!t.has(n.protocol)}catch{return!1}}function ro(e){if(!e||!/[%\\\x00-\x1f\x7f]/.test(e)&&!e.startsWith(`//`))return{path:e,handledProtocolRelativeURL:!1};let t=/%25|%5C/gi,n=0,r=``,i;for(;(i=t.exec(e))!==null;)r+=eo(e.slice(n,i.index))+i[0],n=t.lastIndex;r+=eo(n?e.slice(n):e);let a=!1;return r.startsWith(`//`)&&(a=!0,r=`/`+r.replace(/^\/+/,``)),{path:r,handledProtocolRelativeURL:a}}function io(e){return/\s|[^\u0000-\u007F]/.test(e)?e.replace(/\s|[^\u0000-\u007F]/gu,encodeURIComponent):e}function ao(e,t){if(e===t)return!0;if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}function oo(){throw Error(`Invariant failed`)}var O=t(Ve(),1),so=O.createContext(null);function co(e){return O.useContext(so)}var lo=O.createContext(void 0),uo=O.createContext(void 0),fo=dn();function po(e,t){return e===t}function mo(e,t,n=po){let r=(0,O.useCallback)(t=>{if(!e)return()=>{};let{unsubscribe:n}=e.subscribe(t);return n},[e]),i=(0,O.useCallback)(()=>e?.get(),[e]);return(0,fo.useSyncExternalStoreWithSelector)(r,i,i,t,n)}var ho={};function go(e,t){let n=O.useRef();return r=>{let i=e?.select?e.select(r):r;return e?.structuralSharing??t.options.defaultStructuralSharing?n.current=Ka(n.current,i):i}}function _o(e){let t=co(),n=O.useContext(e.from?uo:lo),r=e.from??n,i=t.stores.getMatchStore(r),a=go(e,t),o=mo(i,e=>e?a(e):ho);if(o!==ho)return o;(e.shouldThrow??!0)&&oo()}function vo(e){return _o({from:e.from,shouldThrow:e.shouldThrow,structuralSharing:e.structuralSharing,strict:e.strict,select:t=>{let n=e.strict===!1?t.params:t._strictParams;return e.select?e.select(n):n}})}var yo=class{constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(e){return this.listeners.add(e),this.onSubscribe(),()=>{this.listeners.delete(e),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}},bo=new class extends yo{#e;#t;#n;constructor(){super(),this.#n=e=>{if(typeof window<`u`&&window.addEventListener){let t=()=>e();return window.addEventListener(`visibilitychange`,t,!1),()=>{window.removeEventListener(`visibilitychange`,t)}}}}onSubscribe(){this.#t||this.setEventListener(this.#n)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(e){this.#n=e,this.#t?.(),this.#t=e(e=>{typeof e==`boolean`?this.setFocused(e):this.onFocus()})}setFocused(e){this.#e!==e&&(this.#e=e,this.onFocus())}onFocus(){let e=this.isFocused();this.listeners.forEach(t=>{t(e)})}isFocused(){return typeof this.#e==`boolean`?this.#e:globalThis.document?.visibilityState!==`hidden`}},xo={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e)},So=new class{#e=xo;setTimeoutProvider(e){this.#e=e}setTimeout(e,t){return this.#e.setTimeout(e,t)}clearTimeout(e){this.#e.clearTimeout(e)}setInterval(e,t){return this.#e.setInterval(e,t)}clearInterval(e){this.#e.clearInterval(e)}};function Co(e){setTimeout(e,0)}var wo=typeof window>`u`||`Deno`in globalThis;function To(){}function Eo(e,t){return typeof e==`function`?e(t):e}function Do(e){return typeof e==`number`&&e>=0&&e!==1/0}function Oo(e,t){return Math.max(e+(t||0)-Date.now(),0)}function ko(e,t){return typeof e==`function`?e(t):e}function Ao(e,t){return typeof e==`function`?e(t):e}function jo(e,t){let{type:n=`all`,exact:r,fetchStatus:i,predicate:a,queryKey:o,stale:s}=e;if(o){if(r){if(t.queryHash!==No(o,t.options))return!1}else if(!Fo(t.queryKey,o))return!1}if(n!==`all`){let e=t.isActive();if(n===`active`&&!e||n===`inactive`&&e)return!1}return!(typeof s==`boolean`&&t.isStale()!==s||i&&i!==t.state.fetchStatus||a&&!a(t))}function Mo(e,t){let{exact:n,status:r,predicate:i,mutationKey:a}=e;if(a){if(!t.options.mutationKey)return!1;if(n){if(Po(t.options.mutationKey)!==Po(a))return!1}else if(!Fo(t.options.mutationKey,a))return!1}return!(r&&t.state.status!==r||i&&!i(t))}function No(e,t){return(t?.queryKeyHashFn||Po)(e)}function Po(e){return JSON.stringify(e,(e,t)=>Bo(t)?Object.keys(t).sort().reduce((e,n)=>(e[n]=t[n],e),{}):t)}function Fo(e,t){if(e===t)return!0;if(typeof e!=typeof t)return!1;if(e&&t&&typeof e==`object`&&typeof t==`object`){if(Array.isArray(e)&&Array.isArray(t)){for(let n=0;n<t.length;n++)if(!Fo(e[n],t[n]))return!1;return!0}let n=Object.keys(t);for(let r of n)if(!Fo(e[r],t[r]))return!1;return!0}return!1}var Io=Object.prototype.hasOwnProperty;function Lo(e,t,n=0){if(e===t)return e;if(n>500)return t;let r=zo(e)&&zo(t);if(!r&&!(Bo(e)&&Bo(t)))return t;let i=(r?e:Object.keys(e)).length,a=r?t:Object.keys(t),o=a.length,s=r?Array(o):{},c=0;for(let l=0;l<o;l++){let o=r?l:a[l],u=e[o],d=t[o];if(u===d){s[o]=u,(r?l<i:Io.call(e,o))&&c++;continue}if(u===null||d===null||typeof u!=`object`||typeof d!=`object`){s[o]=d;continue}let f=Lo(u,d,n+1);s[o]=f,f===u&&c++}return i===o&&c===i?e:s}function Ro(e,t){if(!t||Object.keys(e).length!==Object.keys(t).length)return!1;for(let n in e)if(e[n]!==t[n])return!1;return!0}function zo(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function Bo(e){if(!Vo(e))return!1;let t=e.constructor;if(t===void 0)return!0;let n=t.prototype;return!(!Vo(n)||!n.hasOwnProperty(`isPrototypeOf`)||Object.getPrototypeOf(e)!==Object.prototype)}function Vo(e){return Object.prototype.toString.call(e)===`[object Object]`}function Ho(e){return new Promise(t=>{So.setTimeout(t,e)})}function Uo(e,t,n){return typeof n.structuralSharing==`function`?n.structuralSharing(e,t):n.structuralSharing===!1?t:Lo(e,t)}function Wo(e){return e}function Go(e,t,n=0){let r=[...e,t];return n&&r.length>n?r.slice(1):r}function Ko(e,t,n=0){let r=[t,...e];return n&&r.length>n?r.slice(0,-1):r}var qo=Symbol();function Jo(e,t){return!e.queryFn&&t?.initialPromise?()=>t.initialPromise:!e.queryFn||e.queryFn===qo?()=>Promise.reject(Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}function Yo(e,t){return typeof e==`function`?e(...t):!!e}function Xo(e,t,n){let r=!1,i;return Object.defineProperty(e,"signal",{enumerable:!0,get:()=>(i??=t(),r?i:(r=!0,i.aborted?n():i.addEventListener(`abort`,n,{once:!0}),i))}),e}var Zo=(()=>{let e=()=>wo;return{isServer(){return e()},setIsServer(t){e=t}}})();function Qo(){let e,t,n=new Promise((n,r)=>{e=n,t=r});n.status=`pending`,n.catch(()=>{});function r(e){Object.assign(n,e),delete n.resolve,delete n.reject}return n.resolve=t=>{r({status:`fulfilled`,value:t}),e(t)},n.reject=e=>{r({status:`rejected`,reason:e}),t(e)},n}var $o=Co;function es(){let e=[],t=0,n=e=>{e()},r=e=>{e()},i=$o,a=r=>{t?e.push(r):i(()=>{n(r)})},o=()=>{let t=e;e=[],t.length&&i(()=>{r(()=>{t.forEach(e=>{n(e)})})})};return{batch:e=>{let n;t++;try{n=e()}finally{t--,t||o()}return n},batchCalls:e=>(...t)=>{a(()=>{e(...t)})},schedule:a,setNotifyFunction:e=>{n=e},setBatchNotifyFunction:e=>{r=e},setScheduler:e=>{i=e}}}var ts=es(),ns=new class extends yo{#e=!0;#t;#n;constructor(){super(),this.#n=e=>{if(typeof window<`u`&&window.addEventListener){let t=()=>e(!0),n=()=>e(!1);return window.addEventListener(`online`,t,!1),window.addEventListener(`offline`,n,!1),()=>{window.removeEventListener(`online`,t),window.removeEventListener(`offline`,n)}}}}onSubscribe(){this.#t||this.setEventListener(this.#n)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(e){this.#n=e,this.#t?.(),this.#t=e(this.setOnline.bind(this))}setOnline(e){this.#e!==e&&(this.#e=e,this.listeners.forEach(t=>{t(e)}))}isOnline(){return this.#e}};function rs(e){return Math.min(1e3*2**e,3e4)}function is(e){return(e??`online`)!==`online`||ns.isOnline()}var as=class extends Error{constructor(e){super(`CancelledError`),this.revert=e?.revert,this.silent=e?.silent}};function os(e){let t=!1,n=0,r,i=Qo(),a=()=>i.status!==`pending`,o=t=>{if(!a()){let n=new as(t);f(n),e.onCancel?.(n)}},s=()=>{t=!0},c=()=>{t=!1},l=()=>bo.isFocused()&&(e.networkMode===`always`||ns.isOnline())&&e.canRun(),u=()=>is(e.networkMode)&&e.canRun(),d=e=>{a()||(r?.(),i.resolve(e))},f=e=>{a()||(r?.(),i.reject(e))},p=()=>new Promise(t=>{r=e=>{(a()||l())&&t(e)},e.onPause?.()}).then(()=>{r=void 0,a()||e.onContinue?.()}),m=()=>{if(a())return;let r,i=n===0?e.initialPromise:void 0;try{r=i??e.fn()}catch(e){r=Promise.reject(e)}Promise.resolve(r).then(d).catch(r=>{if(a())return;let i=e.retry??(Zo.isServer()?0:3),o=e.retryDelay??rs,s=typeof o==`function`?o(n,r):o,c=i===!0||typeof i==`number`&&n<i||typeof i==`function`&&i(n,r);if(t||!c){f(r);return}n++,e.onFail?.(n,r),Ho(s).then(()=>l()?void 0:p()).then(()=>{t?f(r):m()})})};return{promise:i,status:()=>i.status,cancel:o,continue:()=>(r?.(),i),cancelRetry:s,continueRetry:c,canStart:u,start:()=>(u()?m():p().then(m),i)}}var ss=class{#e;destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),Do(this.gcTime)&&(this.#e=So.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(Zo.isServer()?1/0:3e5))}clearGcTimeout(){this.#e!==void 0&&(So.clearTimeout(this.#e),this.#e=void 0)}};function cs(e){return{onFetch:(t,n)=>{let r=t.options,i=t.fetchOptions?.meta?.fetchMore?.direction,a=t.state.data?.pages||[],o=t.state.data?.pageParams||[],s={pages:[],pageParams:[]},c=0,l=async()=>{let n=!1,l=e=>{Xo(e,()=>t.signal,()=>n=!0)},u=Jo(t.options,t.fetchOptions),d=async(e,r,i)=>{if(n)return Promise.reject(t.signal.reason);if(r==null&&e.pages.length)return Promise.resolve(e);let a=(()=>{let e={client:t.client,queryKey:t.queryKey,pageParam:r,direction:i?`backward`:`forward`,meta:t.options.meta};return l(e),e})(),o=await u(a),{maxPages:s}=t.options,c=i?Ko:Go;return{pages:c(e.pages,o,s),pageParams:c(e.pageParams,r,s)}};if(i&&a.length){let e=i===`backward`,t=e?us:ls,n={pages:a,pageParams:o};s=await d(n,t(r,n),e)}else{let t=e??a.length;do{let e=c===0?o[0]??r.initialPageParam:ls(r,s);if(c>0&&e==null)break;s=await d(s,e),c++}while(c<t)}return s};t.fetchFn=t.options.persister?()=>t.options.persister?.(l,{client:t.client,queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},n):l}}}function ls(e,{pages:t,pageParams:n}){let r=t.length-1;return t.length>0?e.getNextPageParam(t[r],t,n[r],n):void 0}function us(e,{pages:t,pageParams:n}){return t.length>0?e.getPreviousPageParam?.(t[0],t,n[0],n):void 0}function ds(e,t){return t?ls(e,t)!=null:!1}function fs(e,t){return!t||!e.getPreviousPageParam?!1:us(e,t)!=null}var ps=class extends ss{#e;#t;#n;#r;#i;#a;#o;#s;constructor(e){super(),this.#s=!1,this.#o=e.defaultOptions,this.setOptions(e.options),this.observers=[],this.#i=e.client,this.#r=this.#i.getQueryCache(),this.queryKey=e.queryKey,this.queryHash=e.queryHash,this.#t=gs(this.options),this.state=e.state??this.#t,this.scheduleGc()}get meta(){return this.options.meta}get queryType(){return this.#e}get promise(){return this.#a?.promise}setOptions(e){if(this.options={...this.#o,...e},e?._type&&(this.#e=e._type),this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){let e=gs(this.options);e.data!==void 0&&(this.setState(hs(e.data,e.dataUpdatedAt)),this.#t=e)}}optionalRemove(){!this.observers.length&&this.state.fetchStatus===`idle`&&this.#r.remove(this)}setData(e,t){let n=Uo(this.state.data,e,this.options);return this.#l({data:n,type:`success`,dataUpdatedAt:t?.updatedAt,manual:t?.manual}),n}setState(e){this.#l({type:`setState`,state:e})}cancel(e){let t=this.#a?.promise;return this.#a?.cancel(e),t?t.then(To).catch(To):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}get resetState(){return this.#t}reset(){this.destroy(),this.setState(this.resetState)}isActive(){return this.observers.some(e=>Ao(e.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===qo||!this.isFetched()}isFetched(){return this.state.dataUpdateCount+this.state.errorUpdateCount>0}isStatic(){return this.getObserversCount()>0&&this.observers.some(e=>ko(e.options.staleTime,this)===`static`)}isStale(){return this.getObserversCount()>0?this.observers.some(e=>e.getCurrentResult().isStale):this.state.data===void 0||this.state.isInvalidated}isStaleByTime(e=0){return this.state.data===void 0?!0:e===`static`?!1:this.state.isInvalidated?!0:!Oo(this.state.dataUpdatedAt,e)}onFocus(){this.observers.find(e=>e.shouldFetchOnWindowFocus())?.refetch({cancelRefetch:!1}),this.#a?.continue()}onOnline(){this.observers.find(e=>e.shouldFetchOnReconnect())?.refetch({cancelRefetch:!1}),this.#a?.continue()}addObserver(e){this.observers.includes(e)||(this.observers.push(e),this.clearGcTimeout(),this.#r.notify({type:`observerAdded`,query:this,observer:e}))}removeObserver(e){this.observers.includes(e)&&(this.observers=this.observers.filter(t=>t!==e),this.observers.length||(this.#a&&(this.#s||this.#c()?this.#a.cancel({revert:!0}):this.#a.cancelRetry()),this.scheduleGc()),this.#r.notify({type:`observerRemoved`,query:this,observer:e}))}getObserversCount(){return this.observers.length}#c(){return this.state.fetchStatus===`paused`&&this.state.status===`pending`}invalidate(){this.state.isInvalidated||this.#l({type:`invalidate`})}async fetch(e,t){if(this.state.fetchStatus!==`idle`&&this.#a?.status()!==`rejected`){if(this.state.data!==void 0&&t?.cancelRefetch)this.cancel({silent:!0});else if(this.#a)return this.#a.continueRetry(),this.#a.promise}if(e&&this.setOptions(e),!this.options.queryFn){let e=this.observers.find(e=>e.options.queryFn);e&&this.setOptions(e.options)}let n=new AbortController,r=e=>{Object.defineProperty(e,"signal",{enumerable:!0,get:()=>(this.#s=!0,n.signal)})},i=()=>{let e=Jo(this.options,t),n=(()=>{let e={client:this.#i,queryKey:this.queryKey,meta:this.meta};return r(e),e})();return this.#s=!1,this.options.persister?this.options.persister(e,n,this):e(n)},a=(()=>{let e={fetchOptions:t,options:this.options,queryKey:this.queryKey,client:this.#i,state:this.state,fetchFn:i};return r(e),e})();(this.#e===`infinite`?cs(this.options.pages):this.options.behavior)?.onFetch(a,this),this.#n=this.state,(this.state.fetchStatus===`idle`||this.state.fetchMeta!==a.fetchOptions?.meta)&&this.#l({type:`fetch`,meta:a.fetchOptions?.meta}),this.#a=os({initialPromise:t?.initialPromise,fn:a.fetchFn,onCancel:e=>{e instanceof as&&e.revert&&this.setState({...this.#n,fetchStatus:`idle`}),n.abort()},onFail:(e,t)=>{this.#l({type:`failed`,failureCount:e,error:t})},onPause:()=>{this.#l({type:`pause`})},onContinue:()=>{this.#l({type:`continue`})},retry:a.options.retry,retryDelay:a.options.retryDelay,networkMode:a.options.networkMode,canRun:()=>!0});try{let e=await this.#a.start();if(e===void 0)throw Error(`${this.queryHash} data is undefined`);return this.setData(e),this.#r.config.onSuccess?.(e,this),this.#r.config.onSettled?.(e,this.state.error,this),e}catch(e){if(e instanceof as){if(e.silent)return this.#a.promise;if(e.revert){if(this.state.data===void 0)throw e;return this.state.data}}throw this.#l({type:`error`,error:e}),this.#r.config.onError?.(e,this),this.#r.config.onSettled?.(this.state.data,e,this),e}finally{this.scheduleGc()}}#l(e){let t=t=>{switch(e.type){case`failed`:return{...t,fetchFailureCount:e.failureCount,fetchFailureReason:e.error};case`pause`:return{...t,fetchStatus:`paused`};case`continue`:return{...t,fetchStatus:`fetching`};case`fetch`:return{...t,...ms(t.data,this.options),fetchMeta:e.meta??null};case`success`:let n={...t,...hs(e.data,e.dataUpdatedAt),dataUpdateCount:t.dataUpdateCount+1,...!e.manual&&{fetchStatus:`idle`,fetchFailureCount:0,fetchFailureReason:null}};return this.#n=e.manual?n:void 0,n;case`error`:let r=e.error;return{...t,error:r,errorUpdateCount:t.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:t.fetchFailureCount+1,fetchFailureReason:r,fetchStatus:`idle`,status:`error`,isInvalidated:!0};case`invalidate`:return{...t,isInvalidated:!0};case`setState`:return{...t,...e.state}}};this.state=t(this.state),ts.batch(()=>{this.observers.forEach(e=>{e.onQueryUpdate()}),this.#r.notify({query:this,type:`updated`,action:e})})}};function ms(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:is(t.networkMode)?`fetching`:`paused`,...e===void 0&&{error:null,status:`pending`}}}function hs(e,t){return{data:e,dataUpdatedAt:t??Date.now(),error:null,isInvalidated:!1,status:`success`}}function gs(e){let t=typeof e.initialData==`function`?e.initialData():e.initialData,n=t!==void 0,r=n?typeof e.initialDataUpdatedAt==`function`?e.initialDataUpdatedAt():e.initialDataUpdatedAt:0;return{data:t,dataUpdateCount:0,dataUpdatedAt:n?r??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:n?`success`:`pending`,fetchStatus:`idle`}}var _s=class extends yo{constructor(e,t){super(),this.options=t,this.#e=e,this.#s=null,this.#o=Qo(),this.bindMethods(),this.setOptions(t)}#e;#t=void 0;#n=void 0;#r=void 0;#i;#a;#o;#s;#c;#l;#u;#d;#f;#p;#m=new Set;bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(this.#t.addObserver(this),ys(this.#t,this.options)?this.#h():this.updateResult(),this.#y())}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return bs(this.#t,this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return bs(this.#t,this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,this.#b(),this.#x(),this.#t.removeObserver(this)}setOptions(e){let t=this.options,n=this.#t;if(this.options=this.#e.defaultQueryOptions(e),this.options.enabled!==void 0&&typeof this.options.enabled!=`boolean`&&typeof this.options.enabled!=`function`&&typeof Ao(this.options.enabled,this.#t)!=`boolean`)throw Error(`Expected enabled to be a boolean or a callback that returns a boolean`);this.#S(),this.#t.setOptions(this.options),t._defaulted&&!Ro(this.options,t)&&this.#e.getQueryCache().notify({type:`observerOptionsUpdated`,query:this.#t,observer:this});let r=this.hasListeners();r&&xs(this.#t,n,this.options,t)&&this.#h(),this.updateResult(),r&&(this.#t!==n||Ao(this.options.enabled,this.#t)!==Ao(t.enabled,this.#t)||ko(this.options.staleTime,this.#t)!==ko(t.staleTime,this.#t))&&this.#g();let i=this.#_();r&&(this.#t!==n||Ao(this.options.enabled,this.#t)!==Ao(t.enabled,this.#t)||i!==this.#p)&&this.#v(i)}getOptimisticResult(e){let t=this.#e.getQueryCache().build(this.#e,e),n=this.createResult(t,e);return Cs(this,n)&&(this.#r=n,this.#a=this.options,this.#i=this.#t.state),n}getCurrentResult(){return this.#r}trackResult(e,t){return new Proxy(e,{get:(e,n)=>(this.trackProp(n),t?.(n),n===`promise`&&(this.trackProp(`data`),!this.options.experimental_prefetchInRender&&this.#o.status===`pending`&&this.#o.reject(Error(`experimental_prefetchInRender feature flag is not enabled`))),Reflect.get(e,n))})}trackProp(e){this.#m.add(e)}getCurrentQuery(){return this.#t}refetch({...e}={}){return this.fetch({...e})}fetchOptimistic(e){let t=this.#e.defaultQueryOptions(e),n=this.#e.getQueryCache().build(this.#e,t);return n.fetch().then(()=>this.createResult(n,t))}fetch(e){return this.#h({...e,cancelRefetch:e.cancelRefetch??!0}).then(()=>(this.updateResult(),this.#r))}#h(e){this.#S();let t=this.#t.fetch(this.options,e);return e?.throwOnError||(t=t.catch(To)),t}#g(){this.#b();let e=ko(this.options.staleTime,this.#t);if(Zo.isServer()||this.#r.isStale||!Do(e))return;let t=Oo(this.#r.dataUpdatedAt,e)+1;this.#d=So.setTimeout(()=>{this.#r.isStale||this.updateResult()},t)}#_(){return(typeof this.options.refetchInterval==`function`?this.options.refetchInterval(this.#t):this.options.refetchInterval)??!1}#v(e){this.#x(),this.#p=e,!(Zo.isServer()||Ao(this.options.enabled,this.#t)===!1||!Do(this.#p)||this.#p===0)&&(this.#f=So.setInterval(()=>{(this.options.refetchIntervalInBackground||bo.isFocused())&&this.#h()},this.#p))}#y(){this.#g(),this.#v(this.#_())}#b(){this.#d!==void 0&&(So.clearTimeout(this.#d),this.#d=void 0)}#x(){this.#f!==void 0&&(So.clearInterval(this.#f),this.#f=void 0)}createResult(e,t){let n=this.#t,r=this.options,i=this.#r,a=this.#i,o=this.#a,s=e===n?this.#n:e.state,{state:c}=e,l={...c},u=!1,d;if(t._optimisticResults){let i=this.hasListeners(),a=!i&&ys(e,t),o=i&&xs(e,n,t,r);(a||o)&&(l={...l,...ms(c.data,e.options)}),t._optimisticResults===`isRestoring`&&(l.fetchStatus=`idle`)}let{error:f,errorUpdatedAt:p,status:m}=l;d=l.data;let h=!1;if(t.placeholderData!==void 0&&d===void 0&&m===`pending`){let e;i?.isPlaceholderData&&t.placeholderData===o?.placeholderData?(e=i.data,h=!0):e=typeof t.placeholderData==`function`?t.placeholderData(this.#u?.state.data,this.#u):t.placeholderData,e!==void 0&&(m=`success`,d=Uo(i?.data,e,t),u=!0)}if(t.select&&d!==void 0&&!h)if(i&&d===a?.data&&t.select===this.#c)d=this.#l;else try{this.#c=t.select,d=t.select(d),d=Uo(i?.data,d,t),this.#l=d,this.#s=null}catch(e){this.#s=e}this.#s&&(f=this.#s,d=this.#l,p=Date.now(),m=`error`);let g=l.fetchStatus===`fetching`,_=m===`pending`,v=m===`error`,y=_&&g,b=d!==void 0,x={status:m,fetchStatus:l.fetchStatus,isPending:_,isSuccess:m===`success`,isError:v,isInitialLoading:y,isLoading:y,data:d,dataUpdatedAt:l.dataUpdatedAt,error:f,errorUpdatedAt:p,failureCount:l.fetchFailureCount,failureReason:l.fetchFailureReason,errorUpdateCount:l.errorUpdateCount,isFetched:e.isFetched(),isFetchedAfterMount:l.dataUpdateCount>s.dataUpdateCount||l.errorUpdateCount>s.errorUpdateCount,isFetching:g,isRefetching:g&&!_,isLoadingError:v&&!b,isPaused:l.fetchStatus===`paused`,isPlaceholderData:u,isRefetchError:v&&b,isStale:Ss(e,t),refetch:this.refetch,promise:this.#o,isEnabled:Ao(t.enabled,e)!==!1};if(this.options.experimental_prefetchInRender){let t=x.data!==void 0,r=x.status===`error`&&!t,i=e=>{r?e.reject(x.error):t&&e.resolve(x.data)},a=()=>{let e=this.#o=x.promise=Qo();i(e)},o=this.#o;switch(o.status){case`pending`:e.queryHash===n.queryHash&&i(o);break;case`fulfilled`:(r||x.data!==o.value)&&a();break;case`rejected`:(!r||x.error!==o.reason)&&a()}}return x}updateResult(){let e=this.#r,t=this.createResult(this.#t,this.options);this.#i=this.#t.state,this.#a=this.options,this.#i.data!==void 0&&(this.#u=this.#t),!Ro(t,e)&&(this.#r=t,this.#C({listeners:(()=>{if(!e)return!0;let{notifyOnChangeProps:t}=this.options,n=typeof t==`function`?t():t;if(n===`all`||!n&&!this.#m.size)return!0;let r=new Set(n??this.#m);return this.options.throwOnError&&r.add(`error`),Object.keys(this.#r).some(t=>{let n=t;return this.#r[n]!==e[n]&&r.has(n)})})()}))}#S(){let e=this.#e.getQueryCache().build(this.#e,this.options);if(e===this.#t)return;let t=this.#t;this.#t=e,this.#n=e.state,this.hasListeners()&&(t?.removeObserver(this),e.addObserver(this))}onQueryUpdate(){this.updateResult(),this.hasListeners()&&this.#y()}#C(e){ts.batch(()=>{e.listeners&&this.listeners.forEach(e=>{e(this.#r)}),this.#e.getQueryCache().notify({query:this.#t,type:`observerResultsUpdated`})})}};function vs(e,t){return Ao(t.enabled,e)!==!1&&e.state.data===void 0&&(e.state.status!==`error`||Ao(t.retryOnMount,e)!==!1)}function ys(e,t){return vs(e,t)||e.state.data!==void 0&&bs(e,t,t.refetchOnMount)}function bs(e,t,n){if(Ao(t.enabled,e)!==!1&&ko(t.staleTime,e)!==`static`){let r=typeof n==`function`?n(e):n;return r===`always`||r!==!1&&Ss(e,t)}return!1}function xs(e,t,n,r){return(e!==t||Ao(r.enabled,e)===!1)&&(!n.suspense||e.state.status!==`error`)&&Ss(e,n)}function Ss(e,t){return Ao(t.enabled,e)!==!1&&e.isStaleByTime(ko(t.staleTime,e))}function Cs(e,t){return!Ro(e.getCurrentResult(),t)}var k=je(),ws=O.createContext(void 0),Ts=e=>{let t=O.useContext(ws);if(e)return e;if(!t)throw Error(`No QueryClient set, use QueryClientProvider to set one`);return t},Es=({client:e,children:t})=>(O.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),(0,k.jsx)(ws.Provider,{value:e,children:t})),Ds=O.createContext(!1),Os=()=>O.useContext(Ds);Ds.Provider;function ks(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var As=O.createContext(ks()),js=()=>O.useContext(As),Ms=(e,t,n)=>{let r=n?.state.error&&typeof e.throwOnError==`function`?Yo(e.throwOnError,[n.state.error,n]):e.throwOnError;(e.suspense||e.experimental_prefetchInRender||r)&&(t.isReset()||(e.retryOnMount=!1))},Ns=e=>{O.useEffect(()=>{e.clearReset()},[e])},Ps=({result:e,errorResetBoundary:t,throwOnError:n,query:r,suspense:i})=>e.isError&&!t.isReset()&&!e.isFetching&&r&&(i&&e.data===void 0||Yo(n,[e.error,r])),Fs=e=>{if(e.suspense){let t=1e3,n=e=>e===`static`?e:Math.max(e??t,t),r=e.staleTime;e.staleTime=typeof r==`function`?(...e)=>n(r(...e)):n(r),typeof e.gcTime==`number`&&(e.gcTime=Math.max(e.gcTime,t))}},Is=(e,t)=>e.isLoading&&e.isFetching&&!t,Ls=(e,t)=>e?.suspense&&t.isPending,Rs=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});function zs(e,t,n){let r=Os(),i=js(),a=Ts(n),o=a.defaultQueryOptions(e);a.getDefaultOptions().queries?._experimental_beforeQuery?.(o);let s=a.getQueryCache().get(o.queryHash),c=e.subscribed!==!1;o._optimisticResults=r?`isRestoring`:c?`optimistic`:void 0,Fs(o),Ms(o,i,s),Ns(i);let l=!a.getQueryCache().get(o.queryHash),[u]=O.useState(()=>new t(a,o)),d=u.getOptimisticResult(o),f=!r&&c;if(O.useSyncExternalStore(O.useCallback(e=>{let t=f?u.subscribe(ts.batchCalls(e)):To;return u.updateResult(),t},[u,f]),()=>u.getCurrentResult(),()=>u.getCurrentResult()),O.useEffect(()=>{u.setOptions(o)},[o,u]),Ls(o,d))throw Rs(o,u,i);if(Ps({result:d,errorResetBoundary:i,throwOnError:o.throwOnError,query:s,suspense:o.suspense}))throw d.error;return a.getDefaultOptions().queries?._experimental_afterQuery?.(o,d),o.experimental_prefetchInRender&&!Zo.isServer()&&Is(d,r)&&(l?Rs(o,u,i):s?.promise)?.catch(To).finally(()=>{u.updateResult()}),o.notifyOnChangeProps?d:u.trackResult(d)}function Bs(e,t){return zs(e,_s,t)}function Vs(e){return e}var Hs=g,Us=globalThis.Number,Ws=e=>{if(e===`NaN`)return v(NaN);if(e===`Infinity`)return v(1/0);if(e===`-Infinity`)return v(-1/0);if(e.trim()===``)return ye();let t=Us(e);return Us.isNaN(t)?ye():v(t)},Gs=[[`GET`,`get`],[`POST`,`post`],[`PUT`,`put`],[`DELETE`,`del`],[`PATCH`,`patch`],[`HEAD`,`head`],[`OPTIONS`,`options`],[`TRACE`,`trace`]],Ks=`~effect/http/HttpClientRequest`,qs={[Ks]:Ks,...Se,toJSON(){return{_id:`HttpClientRequest`,method:this.method,url:this.url,urlParams:this.urlParams,hash:this.hash,headers:Nt(this.headers),body:this.body.toJSON()}},pipe(){return Ie(this,arguments)}};function Js(e,t,n,r,i,a){let o=Object.create(qs);return o.method=e,o.url=t,o.urlParams=n,o.hash=r,o.headers=i,o.body=a,o}var Ys=Js(`GET`,``,Wr,ye(),Pr,ni),Xs=e=>(t,n)=>Qs(Ys,{method:e,url:t,...n??void 0}),Zs=Xs(`POST`),Qs=_(2,(e,t)=>{let n=e;return t.method&&(n=$s(n,t.method)),t.url&&(n=ic(n,t.url)),t.headers&&(n=tc(n,t.headers)),t.urlParams&&(n=ac(n,t.urlParams)),t.hash&&(n=oc(n,t.hash)),t.body&&(n=sc(n,t.body)),t.accept&&(n=nc(n,t.accept)),t.acceptJson&&(n=rc(n)),n}),$s=_(2,(e,t)=>Js(t,e.url,e.urlParams,e.hash,e.headers,e.body)),ec=_(3,(e,t,n)=>Js(e.method,e.url,e.urlParams,e.hash,Fr(e.headers,t,n),e.body)),tc=_(2,(e,t)=>Js(e.method,e.url,e.urlParams,e.hash,ii(e.headers,t),e.body)),nc=_(2,(e,t)=>ec(e,`Accept`,t)),rc=nc(`application/json`),ic=_(2,(e,t)=>{if(typeof t==`string`)return Js(e.method,t,e.urlParams,e.hash,e.headers,e.body);let n=new URL(t.toString()),r=xr(n.searchParams),i=Zt(n.hash===``?void 0:n.hash.slice(1));return n.search=``,n.hash=``,Js(e.method,n.toString(),r,i,e.headers,e.body)}),ac=_(2,(e,t)=>Js(e.method,e.url,Mi(e.urlParams,t),e.hash,e.headers,e.body)),oc=_(2,(e,t)=>Js(e.method,e.url,e.urlParams,v(t),e.headers,e.body)),sc=_(2,(e,t)=>{let n=e.headers;return t._tag===`Empty`||t._tag===`FormData`?n=ki(ki(n,`Content-Type`),`Content-length`):(t.contentType&&(n=Fr(n,`content-type`,t.contentType)),t.contentLength!==void 0&&(n=Fr(n,`content-length`,t.contentLength.toString()))),Js(e.method,e.url,e.urlParams,e.hash,n,t)}),cc=e=>ti({b3:`${e.traceId}-${e.spanId}-${e.sampled?`1`:`0`}${ge(e.parent,{onNone:()=>``,onSome:e=>`-${e.spanId}`})}`,traceparent:`00-${e.traceId}-${e.spanId}-${e.sampled?`01`:`00`}`}),lc=`~effect/http/HttpClient`,uc=Tt(`effect/HttpClient`),dc=_(2,(e,t)=>pc(n=>t(e.postprocess(n)),e.preprocess)),fc=dc(Mt(Kr)),pc=(e,t)=>{let n=Object.create(mc);return n.preprocess=t,n.postprocess=e,n.execute=function(n){return e(t(n))},n},mc={[lc]:lc,pipe(){return Ie(this,arguments)},...Se,toJSON(){return{_id:`effect/HttpClient`}},...Object.fromEntries(Gs.map(([e,t])=>[t,function(t,n){return this.execute(Xs(e)(t,n))}]))},hc=e=>pc(t=>Mt(t,t=>Kt(n=>{let i=Sc.get(t),a=i??new AbortController,o=pi(t.url,t.urlParams,m(t.hash));if(jt(o))return r(new Ti({reason:new yi({request:t,cause:o.failure})}));let s=o.success;if(n.getRef(Ct)||n.getRef(_c)(t)){let r=e(t,s,a.signal,n);return i?r:Ft(e=>Ae(e(r),{onSuccess(e){return xc.register(e,a),ct(new Cc(e,a))},onFailure(e){return kt(e)&&a.abort(),lt(e)}}))}return pt(n.getRef(yc)(t),{kind:`client`},r=>{r.attribute(`http.request.method`,t.method),r.attribute(`server.address`,s.origin),s.port!==``&&r.attribute(`server.port`,+s.port),r.attribute(`url.full`,s.toString()),r.attribute(`url.path`,s.pathname),r.attribute(`url.scheme`,s.protocol.slice(0,-1));let o=s.search.slice(1);o!==``&&r.attribute(`url.query`,o);let c=n.getRef(Qr),l=Lr(t.headers,c);for(let e in l)r.attribute(`http.request.header.${e}`,String(l[e]));return t=n.getRef(vc)?tc(t,cc(r)):t,Ft(o=>o(e(t,s,a.signal,n)).pipe(tn(r,{captureStackTrace:!1}),Ae({onSuccess:e=>{r.attribute(`http.response.status_code`,e.status);let t=Lr(e.headers,c);for(let e in t)r.attribute(`http.response.header.${e}`,String(t[e]));return i?ct(e):(xc.register(e,a),ct(new Cc(e,a)))},onFailure(e){return!i&&kt(e)&&a.abort(),lt(e)}})))})})),ct),gc=_(2,(e,t)=>{let n=Oe(t),r=n?`errors-and-responses`:t.retryOn??`errors-and-responses`,i=n?t:t.schedule,o=i&&h(i),s=n?void 0:t.times;return dc(e,ie(r===`errors-only`?ue:ae({schedule:o,times:s,while:Ec}),r===`response-only`?ue:fe({while:n||t.while===void 0?wc:a(wc,t.while),schedule:i,times:s})))}),_c=it(`effect/http/HttpClient/TracerDisabledWhen`,{defaultValue:()=>vt}),vc=it(`effect/HttpClient/TracerPropagationEnabled`,{defaultValue:me}),yc=it(`effect/http/HttpClient/SpanNameGenerator`,{defaultValue:()=>e=>`http.client ${e.method}`}),bc=e=>yt(uc)(oe(t=>nt(e,e=>dc(e,Ot(e=>dt(t,e)))))),xc=(()=>{if(`FinalizationRegistry`in globalThis&&globalThis.FinalizationRegistry){let e=new FinalizationRegistry(e=>{e.abort()});return{register(t,n){e.register(t,n,t)},unregister(t){e.unregister(t)}}}let e=new Map;return{register(t,n){e.set(t,setTimeout(()=>n.abort(),5e3))},unregister(t){let n=e.get(t);n!==void 0&&(clearTimeout(n),e.delete(t))}}})(),Sc=new WeakMap,Cc=class{original;controller;constructor(e,t){this.original=e,this.controller=t}[Rr]=Rr;[wr]=wr;applyInterrupt(e){return Bt(()=>(xc.unregister(this.original),wt(e,()=>gt(()=>{this.controller.abort()}))))}get request(){return this.original.request}get status(){return this.original.status}get headers(){return this.original.headers}get cookies(){return this.original.cookies}get remoteAddress(){return this.original.remoteAddress}get formData(){return this.applyInterrupt(this.original.formData)}get text(){return this.applyInterrupt(this.original.text)}get json(){return this.applyInterrupt(this.original.json)}get urlParamsBody(){return this.applyInterrupt(this.original.urlParamsBody)}get arrayBuffer(){return this.applyInterrupt(this.original.arrayBuffer)}get stream(){return Xe(()=>(xc.unregister(this.original),zt(this.original.stream,gt(()=>{this.controller.abort()}))))}toJSON(){return this.original.toJSON()}[st](){return this.original[st]()}pipe(){return Ie(this,arguments)}},wc=e=>tt(e)||Tc(e),Tc=e=>Di(e)&&(e.reason._tag===`TransportError`||e.reason._tag===`StatusCodeError`&&Ec(e.reason.response)),Ec=e=>e.status===408||e.status===429||e.status===500||e.status===502||e.status===503||e.status===504,Dc=`~effect/ManagedRuntime`,Oc=(e,t)=>{let n=t?.memoMap??_e(),r=He(`parallel`),i=te(r,`sequential`),a={onFiberStart:le(r)},s=e=>e?{...e,onFiberStart:e.onFiberStart?t=>{a.onFiberStart(t),e.onFiberStart(t)}:a.onFiberStart}:a,c,l=Kt(t=>(c||=d(Qe(o(e,n,i),e=>gt(()=>{u.cachedContext=e})),{...a,scheduler:t.currentScheduler}),_t(pe(c)))),u={[Dc]:Dc,memoMap:n,scope:r,contextEffect:l,cachedContext:void 0,context(){return u.cachedContext===void 0?re(u.contextEffect):Promise.resolve(u.cachedContext)},dispose(){return re(u.disposeEffect)},disposeEffect:Bt(()=>(u.contextEffect=Ge(`ManagedRuntime disposed`),u.cachedContext=void 0,Le(u.scope,Pt))),runFork(e,t){return u.cachedContext===void 0?d(kc(u,e),s(t)):ze(u.cachedContext)(e,s(t))},runCallback(e,t){return u.cachedContext===void 0?Te(kc(u,e),s(t)):an(u.cachedContext)(e,s(t))},runSyncExit(e){return u.cachedContext===void 0?Rt(kc(u,e)):se(u.cachedContext)(e)},runSync(e){return u.cachedContext===void 0?ce(kc(u,e)):qe(u.cachedContext)(e)},runPromiseExit(e,t){return u.cachedContext===void 0?Pe(kc(u,e),s(t)):We(u.cachedContext)(e,s(t))},runPromise(e,t){return u.cachedContext===void 0?re(kc(u,e),s(t)):x(u.cachedContext)(e,s(t))}};return u};function kc(e,t){return Mt(e.contextEffect,e=>ve(t,e))}var Ac={accept:!1,observe:!1,missingFrameCount:0,startsNewStream:!1};function jc(e){let t=e===!0;return{accept:t,observe:t,missingFrameCount:0,startsNewStream:t}}function Mc(e,t){let n=e.streamGeneration===void 0&&e.streamId===void 0,r=t.streamGeneration!==void 0||t.streamId!==void 0;return n&&r?jc(t.keyframe):null}function Nc(e,t){return e.streamGeneration===void 0||t.streamGeneration===void 0?null:t.streamGeneration<e.streamGeneration?Ac:t.streamGeneration>e.streamGeneration?jc(t.keyframe):null}function Pc(e,t){if(!e.streamId||!t.streamId)return null;if(e.streamId!==t.streamId)return jc(t.keyframe);if(t.sequence<=e.observedSequence)return Ac;let n=Math.max(0,t.sequence-e.observedSequence-1);return{accept:n===0||t.keyframe===!0,observe:!0,missingFrameCount:n,startsNewStream:!1}}function Fc(e,t){if(t.sequence>e.acceptedSequence)return{accept:!0,observe:!0,missingFrameCount:0,startsNewStream:!1};if(!e.acceptedCapturedAt)return Ac;let n=Date.parse(e.acceptedCapturedAt),r=Date.parse(t.capturedAt);return Number.isNaN(n)||Number.isNaN(r)||r<=n?Ac:{accept:!0,observe:!0,missingFrameCount:0,startsNewStream:!1}}function Ic(e,t){return Mc(e,t)??Nc(e,t)??Pc(e,t)??Fc(e,t)}function Lc(e,t){let n=Ic(e,t);if(!n.observe)return{accept:n.accept,observe:n.observe,missingFrameCount:n.missingFrameCount,state:e};let r=n.startsNewStream?t.sequence:Math.max(e.observedSequence,t.sequence),i={...e,observedSequence:r,gapCount:e.gapCount+n.missingFrameCount},a=n.accept?{...i,acceptedSequence:t.sequence,acceptedCapturedAt:t.capturedAt,...t.streamId?{streamId:t.streamId}:{},...t.streamGeneration===void 0?{}:{streamGeneration:t.streamGeneration}}:i;return{accept:n.accept,observe:n.observe,missingFrameCount:n.missingFrameCount,state:a}}function Rc(e){return{_tag:`Value`,value:e}}function zc(e,t){return{_tag:`Record`,keys:e,value:t}}function Bc(e,t){return{_tag:`Array`,length:e,value:t}}mi(`SourceError`);var Vc=it(`effect/ConfigProvider`,{defaultValue:()=>Wc()}),Hc={...Ke,toJSON(){return{_id:`ConfigProvider`}}};function Uc(e,t,n){let r=Object.create(Hc);return r.get=e,r.mapInput=t,r.prefix=n,r.load=r=>(t&&(r=t(r)),n&&(r=[...n,...r]),e(r)),r}function Wc(e){let t=e?.env??{APP_VERSION:`0.13.4`,BASE_URL:`/`,DEV:!1,MODE:`production`,PROD:!0,SSR:!1,TSS_INLINE_CSS_ENABLED:`false`,VITE_COMMIT_SHA:``,VITE_HOSTED_APP_CHANNEL:``,VITE_HTTP_URL:``,VITE_SENTRY_COMMIT_SHA:`ccee17906caa33ee1121ad57b882116aac6ca527`,VITE_SENTRY_DEBUG:``,VITE_SENTRY_DSN:``,VITE_SENTRY_ENABLED:``,VITE_SENTRY_ENVIRONMENT:`production`,VITE_SENTRY_PROFILES_SAMPLE_RATE:``,VITE_SENTRY_RELEASE:`forge-web@0.13.4+ccee17906caa33ee1121ad57b882116aac6ca527`,VITE_SENTRY_REPLAYS_ON_ERROR_SAMPLE_RATE:``,VITE_SENTRY_REPLAYS_SESSION_SAMPLE_RATE:``,VITE_SENTRY_TRACES_SAMPLE_RATE:``,VITE_WS_URL:``},n=Gc(t);return Uc(e=>ct(qc(n,t,e)))}function Gc(e){let t={};for(let[n,r]of Object.entries(e)){if(r===void 0)continue;let e=n.split(`_`),i=t;for(let t of e)i.children??={},i=i.children[t]??={};i.value=r}return t}var Kc=/^(0|[1-9][0-9]*)$/;function qc(e,t,n){let r=t[n.map(String).join(`_`)],i=Jc(e,n),a=i?.children?Object.keys(i.children):[];return a.length===0?r===void 0?void 0:Rc(r):a.every(e=>Kc.test(e))?Bc(Math.max(...a.map(e=>parseInt(e,10)))+1,r):zc(new Set(a),r)}function Jc(e,t){if(t.length===0)return e;let n=e;for(let e of t)if(n=n?.children?.[String(e)],!n)return;return n}var Yc=`~effect/Config`,Xc=class{_tag=`ConfigError`;name=`ConfigError`;cause;constructor(e){this.cause=e}get message(){return this.cause.toString()}toString(){return`ConfigError(${this.message})`}},Zc={...Ke,...Ye,[Yc]:Yc,asEffect(){return Mt(Vc.asEffect(),e=>this.parse(e))},toJSON(){return{_id:`Config`}}};function Qc(e){let t=Object.create(Zc);return t.parse=e,t}var $c=$e(function*(e,t){let n=yield*e.load(t);if(n!==void 0)switch(n._tag){case`Value`:return n.value;case`Record`:{if(n.value!==void 0)return n.value;let r={};for(let i of n.keys){let n=yield*$c(e,[...t,i]);n!==void 0&&(r[i]=n)}return r}case`Array`:{if(n.value!==void 0)return n.value;let r=[];for(let i=0;i<n.length;i++)r.push(yield*$c(e,[...t,i]));return r}}}),el=$e(function*(e,t,n){switch(e._tag){case`Objects`:{let r={};for(let i of e.propertySignatures){let e=i.name;if(typeof e==`string`){let a=yield*el(i.type,t,[...n,e]);a!==void 0&&(r[e]=a)}}if(e.indexSignatures.length>0){let i=yield*t.load(n);if(i&&i._tag===`Record`)for(let a of e.indexSignatures){let e=Nr(a.parameter);for(let o of i.keys)if(!Object.hasOwn(r,o)&&e(o)){let e=yield*el(a.type,t,[...n,o]);e!==void 0&&(r[o]=e)}}}return r}case`Arrays`:{let r=yield*t.load(n);if(r&&r._tag===`Value`)return r.value;let i=[];for(let r=0;r<e.elements.length;r++)i.push(yield*el(e.elements[r],t,[...n,r]));return i}case`Union`:return yield*$c(t,n);case`Suspend`:return yield*el(e.thunk(),t,n);default:{let e=yield*t.load(n);return e===void 0?void 0:e._tag===`Value`||e._tag===`Record`&&e.value!==void 0||e._tag===`Array`&&e.value!==void 0?e.value:void 0}}});function tl(e,t){let n=Bi(e),r=Yr(n),i=jr(n.ast),a=typeof t==`string`?[t]:t??[];return Qc(e=>{let t=e.prefix?[...e.prefix,...a]:a;return el(i,e,a).pipe(Ht(e=>r(e).pipe(Xt(e=>new Zr(t.length>0?new ri(t,e):e)))),Xt(e=>new Xc(e)))})}var nl=(e,t,n)=>{let r=oi(e,t),i=E.pipe(Or(oi(E,E),Ir(n)),Or(r));return qr([r,i])},A=ee();function rl(e){return new Promise(t=>globalThis.setTimeout(t,e))}function il(){let e=Error(`The environment connection attempt was cancelled.`);return e.name=`AbortError`,e}function al(e){if(e?.aborted)throw il()}function ol(e,t){return t?t.aborted?Promise.reject(il()):new Promise((n,r)=>{let i=()=>r(il());t.addEventListener(`abort`,i,{once:!0}),e.then(n,r).finally(()=>{t.removeEventListener(`abort`,i)})}):e}function sl(e,t){return t?t.aborted?Promise.reject(il()):new Promise((n,r)=>{let i=globalThis.setTimeout(()=>{t.removeEventListener(`abort`,a),n()},e),a=()=>{globalThis.clearTimeout(i),r(il())};t.addEventListener(`abort`,a,{once:!0})}):rl(e)}var cl=Object.freeze({connectionState:`disconnected`,authState:`unknown`,lastError:null,lastErrorAt:null,role:null,descriptor:null,serverConfig:null,connectedAt:null,disconnectedAt:null,providerAuthority:null}),ll=()=>({...cl}),j=wa()(e=>({byId:{},ensure:t=>e(e=>e.byId[t]?e:{byId:{...e.byId,[t]:ll()}}),patch:(t,n)=>e(e=>({byId:{...e.byId,[t]:{...e.byId[t]??ll(),...n}}})),clear:t=>e(e=>{let{[t]:n,...r}=e.byId;return{byId:r}}),reset:()=>e({byId:{}})}));function ul(e){let t=er(e.environmentId);if(t?.lastAuthenticatedPullRequestCapability!==void 0)return{...e,lastAuthenticatedPullRequestCapability:t.lastAuthenticatedPullRequestCapability};let n=j.getState().byId?.[e.environmentId];return n?.authState===`authenticated`&&n.descriptor?{...e,lastAuthenticatedPullRequestCapability:n.descriptor.capabilities.pullRequests===!0}:e}function dl(e){return!!e.runtimeId?.trim()||vr(e.environmentId).isCloud}function fl(e,t){return e.environmentId===t.environmentId&&e.httpBaseUrl===t.httpBaseUrl&&e.wsBaseUrl===t.wsBaseUrl&&e.runtimeId===t.runtimeId&&e.cmmdOrganizationId===t.cmmdOrganizationId}function pl(e){return e.replacedRecord===null&&e.existing!==null&&fl(e.existing,e.record)}function ml(e){let t=e.replacesEnvironmentId?Hr.make(e.replacesEnvironmentId):null,n=t&&t!==e.environmentId?er(t):null;return{existing:er(e.environmentId)??n,replacedRecord:n}}async function hl(e){return{records:lr(),bearerToken:e?await nr(e.environmentId):null}}async function gl(e){let t=e.replacedRecord?.environmentId??e.record.environmentId;await rr(e.rollback.records),await mr(e.record.environmentId).catch(()=>void 0),e.rollback.bearerToken&&await Xn(t,e.rollback.bearerToken)}async function _l(e){try{e.replacedRecord?await qn(e.replacedRecord.environmentId,e.record):await Gn(e.record),al(e.signal),await mr(e.record.environmentId),e.replacedRecord&&await mr(e.replacedRecord.environmentId),al(e.signal)}catch(t){try{await gl(e)}catch(e){let n=AggregateError([t,e],`Cloud Environment rollback failed.`);throw n.cause=t,n}throw t}}function vl(e){return{lastError:e instanceof Error?e.message:String(e),lastErrorAt:new Date().toISOString()}}var yl=new Map;function bl(e,t){return e.acquire(t?{signal:t}:{})}function xl(e,t){yl.set(e,t)}function Sl(e){return yl.has(e)}function Cl(e,t){let n=yl.get(e);if(t&&n!==t){t.dispose();return}n?.dispose(),yl.delete(e)}async function wl(e){let t=yl.get(e);if(t)return(await t.acquire()).bearerToken;let n=er(e);return n&&dl(n)?null:nr(e)}function Tl(){return{executionCount:0,isPending:!1,lastArgs:void 0,lastExecutionTime:0,nextExecutionTime:0,status:`idle`,maybeExecuteCount:0}}var El={enabled:!0,leading:!0,trailing:!0,wait:0},Dl=class{#e;constructor(e,t){this.fn=e,this.store=new Da(Tl()),this.setOptions=e=>{this.options={...this.options,...e},this.#n()||this.cancel()},this.#t=e=>{this.store.setState(t=>{let n={...t,...e},{isPending:r}=n;return{...n,status:this.#n()?r?`pending`:`idle`:`disabled`}}),Oa(`Throttler`,this)},this.#n=()=>!!Ea(this.options.enabled,this),this.#r=()=>Ea(this.options.wait,this),this.maybeExecute=(...e)=>{this.#t({maybeExecuteCount:this.store.state.maybeExecuteCount+1});let t=Date.now(),n=t-this.store.state.lastExecutionTime,r=this.#r();if(this.options.leading&&n>=r)this.#i(...e);else if(this.#t({lastArgs:e}),!this.#e&&this.options.trailing){let e=r-(this.store.state.lastExecutionTime?t-this.store.state.lastExecutionTime:0);this.#t({isPending:!0}),this.#e=setTimeout(()=>{let{lastArgs:e}=this.store.state;e!==void 0&&this.#i(...e)},e)}},this.#i=(...e)=>{if(!this.#n())return;this.fn(...e);let t=Date.now(),n=t+this.#r();this.#a(),this.#t({executionCount:this.store.state.executionCount+1,lastExecutionTime:t,nextExecutionTime:n,isPending:!1,lastArgs:void 0}),this.options.onExecute?.(e,this),setTimeout(()=>{this.store.state.isPending||this.#t({nextExecutionTime:void 0})},this.#r())},this.flush=()=>{this.store.state.isPending&&this.store.state.lastArgs&&this.#i(...this.store.state.lastArgs)},this.#a=()=>{this.#e&&=(clearTimeout(this.#e),void 0)},this.cancel=()=>{this.#a(),this.#t({lastArgs:void 0,isPending:!1})},this.reset=()=>{this.#t(Tl())},this.key=t.key,this.options={...El,...t},this.#t(this.options.initialState??{}),this.key&&ka.on(`d-Throttler`,e=>{e.payload.key===this.key&&(this.#t(e.payload.store.state),this.setOptions(e.payload.options))})}#t;#n;#r;#i;#a},Ol={all:[`projects`],searchContents:(e,t,n,r,i,a,o)=>[`projects`,`search-contents`,e??null,t,n,r,i,a,o],searchEntries:(e,t,n,r)=>[`projects`,`search-entries`,e??null,t,n,r]},kl={all:[`providers`],checkpointDiff:e=>[`providers`,`checkpointDiff`,e.environmentId??null,e.threadId,e.fromTurnCount,e.toTurnCount,e.cacheScope??null]};function Al(e){let t=null,n=!1;function r(){return t}function i(){n=!0,t?.queryInvalidationThrottler.maybeExecute()}function a(){t?.stop(),t=null}function o(r){if(t?.queryClient===r)return t.refCount+=1,()=>{!t||t.queryClient!==r||(--t.refCount,t.refCount===0&&a())};a(),n=!1;let i=new Dl(()=>{n&&(n=!1,r.invalidateQueries({queryKey:kl.all}),r.invalidateQueries({queryKey:Ol.all}))},{wait:100,leading:!1,trailing:!0});e.createPrimaryEnvironmentConnection(),ea().catch(()=>void 0);let o=ir.subscribe(()=>{Wn()&&e.syncSavedEnvironmentConnections(lr())});return Qn().then(()=>e.syncSavedEnvironmentConnections(lr())).catch(()=>void 0),t={queryClient:r,queryInvalidationThrottler:i,refCount:1,stop:()=>{o(),i.cancel()}},()=>{!t||t.queryClient!==r||(--t.refCount,t.refCount===0&&a())}}return{readActiveService:r,notifyProviderInvalidation:i,stopActiveService:a,start:o}}var jl=class extends Error{status;constructor(e,t){super(e),this.name=`RemoteEnvironmentAuthHttpError`,this.status=t}};function Ml(e,t){let n=new URL(e);return n.pathname=`${n.pathname.endsWith(`/`)?n.pathname.slice(0,-1):n.pathname}${t.startsWith(`/`)?t:`/${t}`}`,n.search=``,n.hash=``,n.toString()}async function Nl(e,t){let n=await e.text();if(!n)return t;try{let e=JSON.parse(n);if(typeof e.error==`string`&&e.error.length>0)return e.error}catch{}return n}async function Pl(e){let t=Ml(e.httpBaseUrl,e.pathname),n;try{n=await fetch(t,{method:e.method??`GET`,headers:{...e.body===void 0?{}:{"content-type":`application/json`},...e.bearerToken?{authorization:`Bearer ${e.bearerToken}`}:{}},...e.body===void 0?{}:{body:JSON.stringify(e.body)},...e.signal?{signal:e.signal}:{}})}catch(e){throw Error(`Failed to fetch remote auth endpoint ${t} (${e.message}).`,{cause:e})}if(!n.ok)throw new jl(await Nl(n,`Remote auth request failed (${n.status}).`),n.status);return await n.json()}async function Fl(e){return Pl({httpBaseUrl:e.httpBaseUrl,pathname:`/api/auth/session`,bearerToken:e.bearerToken,...e.signal?{signal:e.signal}:{}})}async function Il(e){return Pl({httpBaseUrl:e.httpBaseUrl,pathname:`/.well-known/forge/environment`,...e.bearerToken?{bearerToken:e.bearerToken}:{}})}async function Ll(e){return Pl({httpBaseUrl:e.httpBaseUrl,pathname:`/api/auth/ws-token`,method:`POST`,bearerToken:e.bearerToken})}async function Rl(e){let t=new URL(e.wsBaseUrl,window.location.origin);if(e.runtimeTicket)return t.searchParams.set(`runtimeTicket`,e.runtimeTicket),t.searchParams.delete(`wsToken`),t.toString();let n=await Ll({httpBaseUrl:e.httpBaseUrl,bearerToken:e.bearerToken});return t.searchParams.set(`wsToken`,n.token),t.toString()}function zl(e,t){if(t){ja(t,e);return}Ma(e)}function Bl(e){let t=null,n=[];for(let r of e.split(/\r?\n/)){if(r.startsWith(`event:`)){t=r.slice(6).trim();continue}r.startsWith(`data:`)&&n.push(r.slice(5).trimStart())}return{eventName:t,data:n.join(`
|
|
2
|
+
import{n as e,r as t,t as n}from"./rolldown-runtime-hePW80VL.js";import{$ as r,$t as i,Aa as a,An as o,Ar as s,At as c,B as l,Br as u,Bt as d,Ci as f,Dn as p,Ei as m,En as h,Er as g,Fa as _,Fi as v,Fn as y,Gn as b,Gt as x,Ha as ee,Hn as te,Hr as ne,Ht as re,Ia as ie,It as ae,J as oe,Jt as se,Kt as ce,L as le,La as ue,Ln as de,Lt as fe,M as pe,Ma as me,Mr as he,Ni as ge,Nn as _e,Nt as ve,Pi as ye,Pn as be,Pt as xe,Qi as Se,Rn as Ce,Rr as we,Rt as Te,Si as Ee,Ta as De,Tn as Oe,Tr as ke,Tt as Ae,Ua as je,Un as Me,Ur as Ne,Ut as Pe,V as Fe,Va as Ie,Vn as Le,Vr as Re,Vt as ze,W as Be,Wa as Ve,Wn as He,Wr as Ue,Wt as We,X as Ge,Yi as Ke,Yt as qe,Z as Je,Zi as Ye,_ as Xe,_t as Ze,an as Qe,at as $e,bn as et,br as tt,bt as nt,ca as rt,ci as it,ct as at,dn as ot,ea as st,en as ct,et as lt,fi as ut,gi as dt,gn as ft,hn as pt,hr as mt,ht,in as gt,it as _t,ja as vt,jn as yt,jr as bt,jt as xt,ki as St,kr as Ct,kt as wt,li as Tt,ln as Et,m as Dt,mn as Ot,mr as kt,na as At,ni as jt,nt as Mt,oa as Nt,or as Pt,pn as Ft,pt as It,q as Lt,qt as Rt,r as zt,rn as Bt,rr as Vt,rt as Ht,sn as Ut,un as Wt,ut as Gt,vn as Kt,vr as qt,wn as Jt,wr as Yt,wt as Xt,xi as Zt,xn as Qt,y as $t,yi as en,yn as tn,z as nn,zn as rn,zt as an}from"./Stream-mUTFnSY9.js";import{i as on,l as sn,n as cn,o as ln,s as un}from"./atomRegistry-C1yW8tyM.js";import{Sn as dn}from"./CompositeItem-DTyKsv13.js";import{$ as fn,A as pn,B as mn,Bn as hn,C as gn,D as _n,Dt as vn,G as yn,H as S,Hn as C,Jn as bn,Kn as xn,L as Sn,Ln as Cn,M as wn,N as Tn,O as En,Q as Dn,Qt as On,Rt as kn,S as An,Sn as jn,T as Mn,Tn as Nn,U as Pn,Un as Fn,Vn as In,Wn as Ln,Wt as Rn,X as zn,Y as Bn,Yt as Vn,Z as Hn,_n as Un,at as Wn,ct as Gn,dn as Kn,dt as qn,fn as Jn,gn as Yn,gt as Xn,hn as Zn,ht as Qn,in as $n,it as er,ln as tr,lt as nr,mn as rr,mt as ir,ot as ar,pn as or,qn as sr,rn as cr,st as lr,t as ur,tn as dr,tt as fr,un as pr,ut as mr,vt as hr,w as gr,wn as _r,yn as vr,yt as yr,zn as br}from"./cmmdForgeRuntimeListResource-2SDxX78O.js";import{$t as xr,A as Sr,At as Cr,Bt as wr,C as Tr,Ct as Er,Dt as Dr,En as Or,Et as kr,G as Ar,Gn as jr,Gt as Mr,Hn as Nr,Ht as Pr,In as w,Jt as Fr,Kn as Ir,Kt as Lr,Lt as Rr,Mt as zr,Nn as Br,Nt as Vr,Ot as Hr,Q as Ur,Qt as Wr,R as Gr,Rt as Kr,Sn as qr,U as Jr,Un as Yr,Ut as Xr,Vn as Zr,Vt as Qr,W as $r,Wn as ei,Wt as ti,Xt as ni,Yn as ri,Yt as ii,Zt as ai,_n as oi,_t as si,an as ci,b as li,c as ui,cn as di,dt as fi,en as pi,er as mi,ft as hi,gn as gi,gt as _i,hn as vi,in as yi,j as bi,jt as xi,kn as Si,l as Ci,mt as wi,nn as Ti,nt as Ei,on as Di,pn as Oi,qt as ki,rt as Ai,s as T,sn as ji,tn as Mi,tt as Ni,ut as Pi,vn as E,vt as Fi,w as Ii,x as Li,xn as Ri,yn as zi,zn as Bi,zt as Vi}from"./src-B_wrKHuq.js";import{$ as Hi,A as Ui,B as Wi,C as Gi,D as Ki,E as qi,F as Ji,G as Yi,H as Xi,I as Zi,J as Qi,K as $i,L as ea,N as ta,O as na,P as ra,Q as ia,R as aa,T as oa,U as sa,W as ca,X as la,Y as ua,Z as da,_ as fa,et as pa,it as ma,nt as ha,q as ga,rt as _a,tt as va,w as ya}from"./cmmdAuthRedirect-DRkKjx0G.js";import{d as ba,f as xa,n as Sa,t as Ca}from"./utils-xQJ3ak-X.js";import{t as D}from"./preload-helper-Czpn1I53.js";import{t as wa}from"./react-D4GEJ3ir.js";import{t as Ta}from"./transport-CgH8pQK3.js";import{a as Ea,i as Da,n as Oa,r as ka,t as Aa}from"./debouncer-BEV7Iuwb.js";import{n as ja,t as Ma}from"./workspaceReadinessAtom-D6bgTvKb.js";import{a as Na,c as Pa,n as Fa,r as Ia,s as La,u as Ra}from"./themePalette-BWvBK22X.js";function za(e){return e[e.length-1]}function Ba(e,t){return typeof e==`function`?e(t):e}var Va=Object.prototype.hasOwnProperty,Ha=Object.prototype.propertyIsEnumerable;function Ua(e){for(let t in e)if(Va.call(e,t))return!0;return!1}var Wa=()=>Object.create(null),Ga=(e,t)=>Ka(e,t,Wa);function Ka(e,t,n=()=>({}),r=0){if(e===t)return e;if(r>500)return t;let i=t,a=Xa(e)&&Xa(i);if(!a&&!(Ja(e)&&Ja(i)))return i;let o=a?e:qa(e);if(!o)return i;let s=a?i:qa(i);if(!s)return i;let c=o.length,l=s.length,u=a?Array(l):n(),d=0;for(let t=0;t<l;t++){let o=a?t:s[t],l=e[o],f=i[o];if(l===f){u[o]=l,(a?t<c:Va.call(e,o))&&d++;continue}if(l===null||f===null||typeof l!=`object`||typeof f!=`object`){u[o]=f;continue}let p=Ka(l,f,n,r+1);u[o]=p,p===l&&d++}return c===l&&d===c?e:u}function qa(e){let t=Object.keys(e);if(t.length!==Object.getOwnPropertyNames(e).length)return!1;let n=Object.getOwnPropertySymbols(e);if(n.length===0)return t;for(let r of n){if(!Ha.call(e,r))return!1;t.push(r)}return t}function Ja(e){if(!Ya(e))return!1;let t=e.constructor;if(t===void 0)return!0;let n=t.prototype;return!(!Ya(n)||!n.hasOwnProperty(`isPrototypeOf`))}function Ya(e){return Object.prototype.toString.call(e)===`[object Object]`}function Xa(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function Za(e,t,n){if(e===t)return!0;if(typeof e!=typeof t)return!1;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let r=0,i=e.length;r<i;r++)if(!Za(e[r],t[r],n))return!1;return!0}if(Ja(e)&&Ja(t)){let r=n?.ignoreUndefined??!0;if(n?.partial){for(let i in t)if((!r||t[i]!==void 0)&&!Za(e[i],t[i],n))return!1;return!0}let i=0;if(!r)i=Object.keys(e).length;else for(let t in e)e[t]!==void 0&&i++;let a=0;for(let o in t)if((!r||t[o]!==void 0)&&(a++,a>i||!Za(e[o],t[o],n)))return!1;return i===a}return!1}var Qa=/[\x00-\x1f\x7f"<>`{}]/g;function $a(e){return e.replace(Qa,e=>`%`+e.charCodeAt(0).toString(16).toUpperCase().padStart(2,`0`))}function eo(e){let t;try{t=decodeURI(e)}catch{t=e.replaceAll(/%[0-9A-F]{2}/gi,e=>{try{return decodeURI(e)}catch{return e}})}return $a(t)}var to=[`http:`,`https:`,`mailto:`,`tel:`];function no(e,t){if(!e)return!1;try{let n=new URL(e);return!t.has(n.protocol)}catch{return!1}}function ro(e){if(!e||!/[%\\\x00-\x1f\x7f]/.test(e)&&!e.startsWith(`//`))return{path:e,handledProtocolRelativeURL:!1};let t=/%25|%5C/gi,n=0,r=``,i;for(;(i=t.exec(e))!==null;)r+=eo(e.slice(n,i.index))+i[0],n=t.lastIndex;r+=eo(n?e.slice(n):e);let a=!1;return r.startsWith(`//`)&&(a=!0,r=`/`+r.replace(/^\/+/,``)),{path:r,handledProtocolRelativeURL:a}}function io(e){return/\s|[^\u0000-\u007F]/.test(e)?e.replace(/\s|[^\u0000-\u007F]/gu,encodeURIComponent):e}function ao(e,t){if(e===t)return!0;if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}function oo(){throw Error(`Invariant failed`)}var O=t(Ve(),1),so=O.createContext(null);function co(e){return O.useContext(so)}var lo=O.createContext(void 0),uo=O.createContext(void 0),fo=dn();function po(e,t){return e===t}function mo(e,t,n=po){let r=(0,O.useCallback)(t=>{if(!e)return()=>{};let{unsubscribe:n}=e.subscribe(t);return n},[e]),i=(0,O.useCallback)(()=>e?.get(),[e]);return(0,fo.useSyncExternalStoreWithSelector)(r,i,i,t,n)}var ho={};function go(e,t){let n=O.useRef();return r=>{let i=e?.select?e.select(r):r;return e?.structuralSharing??t.options.defaultStructuralSharing?n.current=Ka(n.current,i):i}}function _o(e){let t=co(),n=O.useContext(e.from?uo:lo),r=e.from??n,i=t.stores.getMatchStore(r),a=go(e,t),o=mo(i,e=>e?a(e):ho);if(o!==ho)return o;(e.shouldThrow??!0)&&oo()}function vo(e){return _o({from:e.from,shouldThrow:e.shouldThrow,structuralSharing:e.structuralSharing,strict:e.strict,select:t=>{let n=e.strict===!1?t.params:t._strictParams;return e.select?e.select(n):n}})}var yo=class{constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(e){return this.listeners.add(e),this.onSubscribe(),()=>{this.listeners.delete(e),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}},bo=new class extends yo{#e;#t;#n;constructor(){super(),this.#n=e=>{if(typeof window<`u`&&window.addEventListener){let t=()=>e();return window.addEventListener(`visibilitychange`,t,!1),()=>{window.removeEventListener(`visibilitychange`,t)}}}}onSubscribe(){this.#t||this.setEventListener(this.#n)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(e){this.#n=e,this.#t?.(),this.#t=e(e=>{typeof e==`boolean`?this.setFocused(e):this.onFocus()})}setFocused(e){this.#e!==e&&(this.#e=e,this.onFocus())}onFocus(){let e=this.isFocused();this.listeners.forEach(t=>{t(e)})}isFocused(){return typeof this.#e==`boolean`?this.#e:globalThis.document?.visibilityState!==`hidden`}},xo={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e)},So=new class{#e=xo;setTimeoutProvider(e){this.#e=e}setTimeout(e,t){return this.#e.setTimeout(e,t)}clearTimeout(e){this.#e.clearTimeout(e)}setInterval(e,t){return this.#e.setInterval(e,t)}clearInterval(e){this.#e.clearInterval(e)}};function Co(e){setTimeout(e,0)}var wo=typeof window>`u`||`Deno`in globalThis;function To(){}function Eo(e,t){return typeof e==`function`?e(t):e}function Do(e){return typeof e==`number`&&e>=0&&e!==1/0}function Oo(e,t){return Math.max(e+(t||0)-Date.now(),0)}function ko(e,t){return typeof e==`function`?e(t):e}function Ao(e,t){return typeof e==`function`?e(t):e}function jo(e,t){let{type:n=`all`,exact:r,fetchStatus:i,predicate:a,queryKey:o,stale:s}=e;if(o){if(r){if(t.queryHash!==No(o,t.options))return!1}else if(!Fo(t.queryKey,o))return!1}if(n!==`all`){let e=t.isActive();if(n===`active`&&!e||n===`inactive`&&e)return!1}return!(typeof s==`boolean`&&t.isStale()!==s||i&&i!==t.state.fetchStatus||a&&!a(t))}function Mo(e,t){let{exact:n,status:r,predicate:i,mutationKey:a}=e;if(a){if(!t.options.mutationKey)return!1;if(n){if(Po(t.options.mutationKey)!==Po(a))return!1}else if(!Fo(t.options.mutationKey,a))return!1}return!(r&&t.state.status!==r||i&&!i(t))}function No(e,t){return(t?.queryKeyHashFn||Po)(e)}function Po(e){return JSON.stringify(e,(e,t)=>Bo(t)?Object.keys(t).sort().reduce((e,n)=>(e[n]=t[n],e),{}):t)}function Fo(e,t){if(e===t)return!0;if(typeof e!=typeof t)return!1;if(e&&t&&typeof e==`object`&&typeof t==`object`){if(Array.isArray(e)&&Array.isArray(t)){for(let n=0;n<t.length;n++)if(!Fo(e[n],t[n]))return!1;return!0}let n=Object.keys(t);for(let r of n)if(!Fo(e[r],t[r]))return!1;return!0}return!1}var Io=Object.prototype.hasOwnProperty;function Lo(e,t,n=0){if(e===t)return e;if(n>500)return t;let r=zo(e)&&zo(t);if(!r&&!(Bo(e)&&Bo(t)))return t;let i=(r?e:Object.keys(e)).length,a=r?t:Object.keys(t),o=a.length,s=r?Array(o):{},c=0;for(let l=0;l<o;l++){let o=r?l:a[l],u=e[o],d=t[o];if(u===d){s[o]=u,(r?l<i:Io.call(e,o))&&c++;continue}if(u===null||d===null||typeof u!=`object`||typeof d!=`object`){s[o]=d;continue}let f=Lo(u,d,n+1);s[o]=f,f===u&&c++}return i===o&&c===i?e:s}function Ro(e,t){if(!t||Object.keys(e).length!==Object.keys(t).length)return!1;for(let n in e)if(e[n]!==t[n])return!1;return!0}function zo(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function Bo(e){if(!Vo(e))return!1;let t=e.constructor;if(t===void 0)return!0;let n=t.prototype;return!(!Vo(n)||!n.hasOwnProperty(`isPrototypeOf`)||Object.getPrototypeOf(e)!==Object.prototype)}function Vo(e){return Object.prototype.toString.call(e)===`[object Object]`}function Ho(e){return new Promise(t=>{So.setTimeout(t,e)})}function Uo(e,t,n){return typeof n.structuralSharing==`function`?n.structuralSharing(e,t):n.structuralSharing===!1?t:Lo(e,t)}function Wo(e){return e}function Go(e,t,n=0){let r=[...e,t];return n&&r.length>n?r.slice(1):r}function Ko(e,t,n=0){let r=[t,...e];return n&&r.length>n?r.slice(0,-1):r}var qo=Symbol();function Jo(e,t){return!e.queryFn&&t?.initialPromise?()=>t.initialPromise:!e.queryFn||e.queryFn===qo?()=>Promise.reject(Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}function Yo(e,t){return typeof e==`function`?e(...t):!!e}function Xo(e,t,n){let r=!1,i;return Object.defineProperty(e,"signal",{enumerable:!0,get:()=>(i??=t(),r?i:(r=!0,i.aborted?n():i.addEventListener(`abort`,n,{once:!0}),i))}),e}var Zo=(()=>{let e=()=>wo;return{isServer(){return e()},setIsServer(t){e=t}}})();function Qo(){let e,t,n=new Promise((n,r)=>{e=n,t=r});n.status=`pending`,n.catch(()=>{});function r(e){Object.assign(n,e),delete n.resolve,delete n.reject}return n.resolve=t=>{r({status:`fulfilled`,value:t}),e(t)},n.reject=e=>{r({status:`rejected`,reason:e}),t(e)},n}var $o=Co;function es(){let e=[],t=0,n=e=>{e()},r=e=>{e()},i=$o,a=r=>{t?e.push(r):i(()=>{n(r)})},o=()=>{let t=e;e=[],t.length&&i(()=>{r(()=>{t.forEach(e=>{n(e)})})})};return{batch:e=>{let n;t++;try{n=e()}finally{t--,t||o()}return n},batchCalls:e=>(...t)=>{a(()=>{e(...t)})},schedule:a,setNotifyFunction:e=>{n=e},setBatchNotifyFunction:e=>{r=e},setScheduler:e=>{i=e}}}var ts=es(),ns=new class extends yo{#e=!0;#t;#n;constructor(){super(),this.#n=e=>{if(typeof window<`u`&&window.addEventListener){let t=()=>e(!0),n=()=>e(!1);return window.addEventListener(`online`,t,!1),window.addEventListener(`offline`,n,!1),()=>{window.removeEventListener(`online`,t),window.removeEventListener(`offline`,n)}}}}onSubscribe(){this.#t||this.setEventListener(this.#n)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(e){this.#n=e,this.#t?.(),this.#t=e(this.setOnline.bind(this))}setOnline(e){this.#e!==e&&(this.#e=e,this.listeners.forEach(t=>{t(e)}))}isOnline(){return this.#e}};function rs(e){return Math.min(1e3*2**e,3e4)}function is(e){return(e??`online`)!==`online`||ns.isOnline()}var as=class extends Error{constructor(e){super(`CancelledError`),this.revert=e?.revert,this.silent=e?.silent}};function os(e){let t=!1,n=0,r,i=Qo(),a=()=>i.status!==`pending`,o=t=>{if(!a()){let n=new as(t);f(n),e.onCancel?.(n)}},s=()=>{t=!0},c=()=>{t=!1},l=()=>bo.isFocused()&&(e.networkMode===`always`||ns.isOnline())&&e.canRun(),u=()=>is(e.networkMode)&&e.canRun(),d=e=>{a()||(r?.(),i.resolve(e))},f=e=>{a()||(r?.(),i.reject(e))},p=()=>new Promise(t=>{r=e=>{(a()||l())&&t(e)},e.onPause?.()}).then(()=>{r=void 0,a()||e.onContinue?.()}),m=()=>{if(a())return;let r,i=n===0?e.initialPromise:void 0;try{r=i??e.fn()}catch(e){r=Promise.reject(e)}Promise.resolve(r).then(d).catch(r=>{if(a())return;let i=e.retry??(Zo.isServer()?0:3),o=e.retryDelay??rs,s=typeof o==`function`?o(n,r):o,c=i===!0||typeof i==`number`&&n<i||typeof i==`function`&&i(n,r);if(t||!c){f(r);return}n++,e.onFail?.(n,r),Ho(s).then(()=>l()?void 0:p()).then(()=>{t?f(r):m()})})};return{promise:i,status:()=>i.status,cancel:o,continue:()=>(r?.(),i),cancelRetry:s,continueRetry:c,canStart:u,start:()=>(u()?m():p().then(m),i)}}var ss=class{#e;destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),Do(this.gcTime)&&(this.#e=So.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(Zo.isServer()?1/0:3e5))}clearGcTimeout(){this.#e!==void 0&&(So.clearTimeout(this.#e),this.#e=void 0)}};function cs(e){return{onFetch:(t,n)=>{let r=t.options,i=t.fetchOptions?.meta?.fetchMore?.direction,a=t.state.data?.pages||[],o=t.state.data?.pageParams||[],s={pages:[],pageParams:[]},c=0,l=async()=>{let n=!1,l=e=>{Xo(e,()=>t.signal,()=>n=!0)},u=Jo(t.options,t.fetchOptions),d=async(e,r,i)=>{if(n)return Promise.reject(t.signal.reason);if(r==null&&e.pages.length)return Promise.resolve(e);let a=(()=>{let e={client:t.client,queryKey:t.queryKey,pageParam:r,direction:i?`backward`:`forward`,meta:t.options.meta};return l(e),e})(),o=await u(a),{maxPages:s}=t.options,c=i?Ko:Go;return{pages:c(e.pages,o,s),pageParams:c(e.pageParams,r,s)}};if(i&&a.length){let e=i===`backward`,t=e?us:ls,n={pages:a,pageParams:o};s=await d(n,t(r,n),e)}else{let t=e??a.length;do{let e=c===0?o[0]??r.initialPageParam:ls(r,s);if(c>0&&e==null)break;s=await d(s,e),c++}while(c<t)}return s};t.fetchFn=t.options.persister?()=>t.options.persister?.(l,{client:t.client,queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},n):l}}}function ls(e,{pages:t,pageParams:n}){let r=t.length-1;return t.length>0?e.getNextPageParam(t[r],t,n[r],n):void 0}function us(e,{pages:t,pageParams:n}){return t.length>0?e.getPreviousPageParam?.(t[0],t,n[0],n):void 0}function ds(e,t){return t?ls(e,t)!=null:!1}function fs(e,t){return!t||!e.getPreviousPageParam?!1:us(e,t)!=null}var ps=class extends ss{#e;#t;#n;#r;#i;#a;#o;#s;constructor(e){super(),this.#s=!1,this.#o=e.defaultOptions,this.setOptions(e.options),this.observers=[],this.#i=e.client,this.#r=this.#i.getQueryCache(),this.queryKey=e.queryKey,this.queryHash=e.queryHash,this.#t=gs(this.options),this.state=e.state??this.#t,this.scheduleGc()}get meta(){return this.options.meta}get queryType(){return this.#e}get promise(){return this.#a?.promise}setOptions(e){if(this.options={...this.#o,...e},e?._type&&(this.#e=e._type),this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){let e=gs(this.options);e.data!==void 0&&(this.setState(hs(e.data,e.dataUpdatedAt)),this.#t=e)}}optionalRemove(){!this.observers.length&&this.state.fetchStatus===`idle`&&this.#r.remove(this)}setData(e,t){let n=Uo(this.state.data,e,this.options);return this.#l({data:n,type:`success`,dataUpdatedAt:t?.updatedAt,manual:t?.manual}),n}setState(e){this.#l({type:`setState`,state:e})}cancel(e){let t=this.#a?.promise;return this.#a?.cancel(e),t?t.then(To).catch(To):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}get resetState(){return this.#t}reset(){this.destroy(),this.setState(this.resetState)}isActive(){return this.observers.some(e=>Ao(e.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===qo||!this.isFetched()}isFetched(){return this.state.dataUpdateCount+this.state.errorUpdateCount>0}isStatic(){return this.getObserversCount()>0&&this.observers.some(e=>ko(e.options.staleTime,this)===`static`)}isStale(){return this.getObserversCount()>0?this.observers.some(e=>e.getCurrentResult().isStale):this.state.data===void 0||this.state.isInvalidated}isStaleByTime(e=0){return this.state.data===void 0?!0:e===`static`?!1:this.state.isInvalidated?!0:!Oo(this.state.dataUpdatedAt,e)}onFocus(){this.observers.find(e=>e.shouldFetchOnWindowFocus())?.refetch({cancelRefetch:!1}),this.#a?.continue()}onOnline(){this.observers.find(e=>e.shouldFetchOnReconnect())?.refetch({cancelRefetch:!1}),this.#a?.continue()}addObserver(e){this.observers.includes(e)||(this.observers.push(e),this.clearGcTimeout(),this.#r.notify({type:`observerAdded`,query:this,observer:e}))}removeObserver(e){this.observers.includes(e)&&(this.observers=this.observers.filter(t=>t!==e),this.observers.length||(this.#a&&(this.#s||this.#c()?this.#a.cancel({revert:!0}):this.#a.cancelRetry()),this.scheduleGc()),this.#r.notify({type:`observerRemoved`,query:this,observer:e}))}getObserversCount(){return this.observers.length}#c(){return this.state.fetchStatus===`paused`&&this.state.status===`pending`}invalidate(){this.state.isInvalidated||this.#l({type:`invalidate`})}async fetch(e,t){if(this.state.fetchStatus!==`idle`&&this.#a?.status()!==`rejected`){if(this.state.data!==void 0&&t?.cancelRefetch)this.cancel({silent:!0});else if(this.#a)return this.#a.continueRetry(),this.#a.promise}if(e&&this.setOptions(e),!this.options.queryFn){let e=this.observers.find(e=>e.options.queryFn);e&&this.setOptions(e.options)}let n=new AbortController,r=e=>{Object.defineProperty(e,"signal",{enumerable:!0,get:()=>(this.#s=!0,n.signal)})},i=()=>{let e=Jo(this.options,t),n=(()=>{let e={client:this.#i,queryKey:this.queryKey,meta:this.meta};return r(e),e})();return this.#s=!1,this.options.persister?this.options.persister(e,n,this):e(n)},a=(()=>{let e={fetchOptions:t,options:this.options,queryKey:this.queryKey,client:this.#i,state:this.state,fetchFn:i};return r(e),e})();(this.#e===`infinite`?cs(this.options.pages):this.options.behavior)?.onFetch(a,this),this.#n=this.state,(this.state.fetchStatus===`idle`||this.state.fetchMeta!==a.fetchOptions?.meta)&&this.#l({type:`fetch`,meta:a.fetchOptions?.meta}),this.#a=os({initialPromise:t?.initialPromise,fn:a.fetchFn,onCancel:e=>{e instanceof as&&e.revert&&this.setState({...this.#n,fetchStatus:`idle`}),n.abort()},onFail:(e,t)=>{this.#l({type:`failed`,failureCount:e,error:t})},onPause:()=>{this.#l({type:`pause`})},onContinue:()=>{this.#l({type:`continue`})},retry:a.options.retry,retryDelay:a.options.retryDelay,networkMode:a.options.networkMode,canRun:()=>!0});try{let e=await this.#a.start();if(e===void 0)throw Error(`${this.queryHash} data is undefined`);return this.setData(e),this.#r.config.onSuccess?.(e,this),this.#r.config.onSettled?.(e,this.state.error,this),e}catch(e){if(e instanceof as){if(e.silent)return this.#a.promise;if(e.revert){if(this.state.data===void 0)throw e;return this.state.data}}throw this.#l({type:`error`,error:e}),this.#r.config.onError?.(e,this),this.#r.config.onSettled?.(this.state.data,e,this),e}finally{this.scheduleGc()}}#l(e){let t=t=>{switch(e.type){case`failed`:return{...t,fetchFailureCount:e.failureCount,fetchFailureReason:e.error};case`pause`:return{...t,fetchStatus:`paused`};case`continue`:return{...t,fetchStatus:`fetching`};case`fetch`:return{...t,...ms(t.data,this.options),fetchMeta:e.meta??null};case`success`:let n={...t,...hs(e.data,e.dataUpdatedAt),dataUpdateCount:t.dataUpdateCount+1,...!e.manual&&{fetchStatus:`idle`,fetchFailureCount:0,fetchFailureReason:null}};return this.#n=e.manual?n:void 0,n;case`error`:let r=e.error;return{...t,error:r,errorUpdateCount:t.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:t.fetchFailureCount+1,fetchFailureReason:r,fetchStatus:`idle`,status:`error`,isInvalidated:!0};case`invalidate`:return{...t,isInvalidated:!0};case`setState`:return{...t,...e.state}}};this.state=t(this.state),ts.batch(()=>{this.observers.forEach(e=>{e.onQueryUpdate()}),this.#r.notify({query:this,type:`updated`,action:e})})}};function ms(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:is(t.networkMode)?`fetching`:`paused`,...e===void 0&&{error:null,status:`pending`}}}function hs(e,t){return{data:e,dataUpdatedAt:t??Date.now(),error:null,isInvalidated:!1,status:`success`}}function gs(e){let t=typeof e.initialData==`function`?e.initialData():e.initialData,n=t!==void 0,r=n?typeof e.initialDataUpdatedAt==`function`?e.initialDataUpdatedAt():e.initialDataUpdatedAt:0;return{data:t,dataUpdateCount:0,dataUpdatedAt:n?r??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:n?`success`:`pending`,fetchStatus:`idle`}}var _s=class extends yo{constructor(e,t){super(),this.options=t,this.#e=e,this.#s=null,this.#o=Qo(),this.bindMethods(),this.setOptions(t)}#e;#t=void 0;#n=void 0;#r=void 0;#i;#a;#o;#s;#c;#l;#u;#d;#f;#p;#m=new Set;bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(this.#t.addObserver(this),ys(this.#t,this.options)?this.#h():this.updateResult(),this.#y())}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return bs(this.#t,this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return bs(this.#t,this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,this.#b(),this.#x(),this.#t.removeObserver(this)}setOptions(e){let t=this.options,n=this.#t;if(this.options=this.#e.defaultQueryOptions(e),this.options.enabled!==void 0&&typeof this.options.enabled!=`boolean`&&typeof this.options.enabled!=`function`&&typeof Ao(this.options.enabled,this.#t)!=`boolean`)throw Error(`Expected enabled to be a boolean or a callback that returns a boolean`);this.#S(),this.#t.setOptions(this.options),t._defaulted&&!Ro(this.options,t)&&this.#e.getQueryCache().notify({type:`observerOptionsUpdated`,query:this.#t,observer:this});let r=this.hasListeners();r&&xs(this.#t,n,this.options,t)&&this.#h(),this.updateResult(),r&&(this.#t!==n||Ao(this.options.enabled,this.#t)!==Ao(t.enabled,this.#t)||ko(this.options.staleTime,this.#t)!==ko(t.staleTime,this.#t))&&this.#g();let i=this.#_();r&&(this.#t!==n||Ao(this.options.enabled,this.#t)!==Ao(t.enabled,this.#t)||i!==this.#p)&&this.#v(i)}getOptimisticResult(e){let t=this.#e.getQueryCache().build(this.#e,e),n=this.createResult(t,e);return Cs(this,n)&&(this.#r=n,this.#a=this.options,this.#i=this.#t.state),n}getCurrentResult(){return this.#r}trackResult(e,t){return new Proxy(e,{get:(e,n)=>(this.trackProp(n),t?.(n),n===`promise`&&(this.trackProp(`data`),!this.options.experimental_prefetchInRender&&this.#o.status===`pending`&&this.#o.reject(Error(`experimental_prefetchInRender feature flag is not enabled`))),Reflect.get(e,n))})}trackProp(e){this.#m.add(e)}getCurrentQuery(){return this.#t}refetch({...e}={}){return this.fetch({...e})}fetchOptimistic(e){let t=this.#e.defaultQueryOptions(e),n=this.#e.getQueryCache().build(this.#e,t);return n.fetch().then(()=>this.createResult(n,t))}fetch(e){return this.#h({...e,cancelRefetch:e.cancelRefetch??!0}).then(()=>(this.updateResult(),this.#r))}#h(e){this.#S();let t=this.#t.fetch(this.options,e);return e?.throwOnError||(t=t.catch(To)),t}#g(){this.#b();let e=ko(this.options.staleTime,this.#t);if(Zo.isServer()||this.#r.isStale||!Do(e))return;let t=Oo(this.#r.dataUpdatedAt,e)+1;this.#d=So.setTimeout(()=>{this.#r.isStale||this.updateResult()},t)}#_(){return(typeof this.options.refetchInterval==`function`?this.options.refetchInterval(this.#t):this.options.refetchInterval)??!1}#v(e){this.#x(),this.#p=e,!(Zo.isServer()||Ao(this.options.enabled,this.#t)===!1||!Do(this.#p)||this.#p===0)&&(this.#f=So.setInterval(()=>{(this.options.refetchIntervalInBackground||bo.isFocused())&&this.#h()},this.#p))}#y(){this.#g(),this.#v(this.#_())}#b(){this.#d!==void 0&&(So.clearTimeout(this.#d),this.#d=void 0)}#x(){this.#f!==void 0&&(So.clearInterval(this.#f),this.#f=void 0)}createResult(e,t){let n=this.#t,r=this.options,i=this.#r,a=this.#i,o=this.#a,s=e===n?this.#n:e.state,{state:c}=e,l={...c},u=!1,d;if(t._optimisticResults){let i=this.hasListeners(),a=!i&&ys(e,t),o=i&&xs(e,n,t,r);(a||o)&&(l={...l,...ms(c.data,e.options)}),t._optimisticResults===`isRestoring`&&(l.fetchStatus=`idle`)}let{error:f,errorUpdatedAt:p,status:m}=l;d=l.data;let h=!1;if(t.placeholderData!==void 0&&d===void 0&&m===`pending`){let e;i?.isPlaceholderData&&t.placeholderData===o?.placeholderData?(e=i.data,h=!0):e=typeof t.placeholderData==`function`?t.placeholderData(this.#u?.state.data,this.#u):t.placeholderData,e!==void 0&&(m=`success`,d=Uo(i?.data,e,t),u=!0)}if(t.select&&d!==void 0&&!h)if(i&&d===a?.data&&t.select===this.#c)d=this.#l;else try{this.#c=t.select,d=t.select(d),d=Uo(i?.data,d,t),this.#l=d,this.#s=null}catch(e){this.#s=e}this.#s&&(f=this.#s,d=this.#l,p=Date.now(),m=`error`);let g=l.fetchStatus===`fetching`,_=m===`pending`,v=m===`error`,y=_&&g,b=d!==void 0,x={status:m,fetchStatus:l.fetchStatus,isPending:_,isSuccess:m===`success`,isError:v,isInitialLoading:y,isLoading:y,data:d,dataUpdatedAt:l.dataUpdatedAt,error:f,errorUpdatedAt:p,failureCount:l.fetchFailureCount,failureReason:l.fetchFailureReason,errorUpdateCount:l.errorUpdateCount,isFetched:e.isFetched(),isFetchedAfterMount:l.dataUpdateCount>s.dataUpdateCount||l.errorUpdateCount>s.errorUpdateCount,isFetching:g,isRefetching:g&&!_,isLoadingError:v&&!b,isPaused:l.fetchStatus===`paused`,isPlaceholderData:u,isRefetchError:v&&b,isStale:Ss(e,t),refetch:this.refetch,promise:this.#o,isEnabled:Ao(t.enabled,e)!==!1};if(this.options.experimental_prefetchInRender){let t=x.data!==void 0,r=x.status===`error`&&!t,i=e=>{r?e.reject(x.error):t&&e.resolve(x.data)},a=()=>{let e=this.#o=x.promise=Qo();i(e)},o=this.#o;switch(o.status){case`pending`:e.queryHash===n.queryHash&&i(o);break;case`fulfilled`:(r||x.data!==o.value)&&a();break;case`rejected`:(!r||x.error!==o.reason)&&a()}}return x}updateResult(){let e=this.#r,t=this.createResult(this.#t,this.options);this.#i=this.#t.state,this.#a=this.options,this.#i.data!==void 0&&(this.#u=this.#t),!Ro(t,e)&&(this.#r=t,this.#C({listeners:(()=>{if(!e)return!0;let{notifyOnChangeProps:t}=this.options,n=typeof t==`function`?t():t;if(n===`all`||!n&&!this.#m.size)return!0;let r=new Set(n??this.#m);return this.options.throwOnError&&r.add(`error`),Object.keys(this.#r).some(t=>{let n=t;return this.#r[n]!==e[n]&&r.has(n)})})()}))}#S(){let e=this.#e.getQueryCache().build(this.#e,this.options);if(e===this.#t)return;let t=this.#t;this.#t=e,this.#n=e.state,this.hasListeners()&&(t?.removeObserver(this),e.addObserver(this))}onQueryUpdate(){this.updateResult(),this.hasListeners()&&this.#y()}#C(e){ts.batch(()=>{e.listeners&&this.listeners.forEach(e=>{e(this.#r)}),this.#e.getQueryCache().notify({query:this.#t,type:`observerResultsUpdated`})})}};function vs(e,t){return Ao(t.enabled,e)!==!1&&e.state.data===void 0&&(e.state.status!==`error`||Ao(t.retryOnMount,e)!==!1)}function ys(e,t){return vs(e,t)||e.state.data!==void 0&&bs(e,t,t.refetchOnMount)}function bs(e,t,n){if(Ao(t.enabled,e)!==!1&&ko(t.staleTime,e)!==`static`){let r=typeof n==`function`?n(e):n;return r===`always`||r!==!1&&Ss(e,t)}return!1}function xs(e,t,n,r){return(e!==t||Ao(r.enabled,e)===!1)&&(!n.suspense||e.state.status!==`error`)&&Ss(e,n)}function Ss(e,t){return Ao(t.enabled,e)!==!1&&e.isStaleByTime(ko(t.staleTime,e))}function Cs(e,t){return!Ro(e.getCurrentResult(),t)}var k=je(),ws=O.createContext(void 0),Ts=e=>{let t=O.useContext(ws);if(e)return e;if(!t)throw Error(`No QueryClient set, use QueryClientProvider to set one`);return t},Es=({client:e,children:t})=>(O.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),(0,k.jsx)(ws.Provider,{value:e,children:t})),Ds=O.createContext(!1),Os=()=>O.useContext(Ds);Ds.Provider;function ks(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var As=O.createContext(ks()),js=()=>O.useContext(As),Ms=(e,t,n)=>{let r=n?.state.error&&typeof e.throwOnError==`function`?Yo(e.throwOnError,[n.state.error,n]):e.throwOnError;(e.suspense||e.experimental_prefetchInRender||r)&&(t.isReset()||(e.retryOnMount=!1))},Ns=e=>{O.useEffect(()=>{e.clearReset()},[e])},Ps=({result:e,errorResetBoundary:t,throwOnError:n,query:r,suspense:i})=>e.isError&&!t.isReset()&&!e.isFetching&&r&&(i&&e.data===void 0||Yo(n,[e.error,r])),Fs=e=>{if(e.suspense){let t=1e3,n=e=>e===`static`?e:Math.max(e??t,t),r=e.staleTime;e.staleTime=typeof r==`function`?(...e)=>n(r(...e)):n(r),typeof e.gcTime==`number`&&(e.gcTime=Math.max(e.gcTime,t))}},Is=(e,t)=>e.isLoading&&e.isFetching&&!t,Ls=(e,t)=>e?.suspense&&t.isPending,Rs=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});function zs(e,t,n){let r=Os(),i=js(),a=Ts(n),o=a.defaultQueryOptions(e);a.getDefaultOptions().queries?._experimental_beforeQuery?.(o);let s=a.getQueryCache().get(o.queryHash),c=e.subscribed!==!1;o._optimisticResults=r?`isRestoring`:c?`optimistic`:void 0,Fs(o),Ms(o,i,s),Ns(i);let l=!a.getQueryCache().get(o.queryHash),[u]=O.useState(()=>new t(a,o)),d=u.getOptimisticResult(o),f=!r&&c;if(O.useSyncExternalStore(O.useCallback(e=>{let t=f?u.subscribe(ts.batchCalls(e)):To;return u.updateResult(),t},[u,f]),()=>u.getCurrentResult(),()=>u.getCurrentResult()),O.useEffect(()=>{u.setOptions(o)},[o,u]),Ls(o,d))throw Rs(o,u,i);if(Ps({result:d,errorResetBoundary:i,throwOnError:o.throwOnError,query:s,suspense:o.suspense}))throw d.error;return a.getDefaultOptions().queries?._experimental_afterQuery?.(o,d),o.experimental_prefetchInRender&&!Zo.isServer()&&Is(d,r)&&(l?Rs(o,u,i):s?.promise)?.catch(To).finally(()=>{u.updateResult()}),o.notifyOnChangeProps?d:u.trackResult(d)}function Bs(e,t){return zs(e,_s,t)}function Vs(e){return e}var Hs=g,Us=globalThis.Number,Ws=e=>{if(e===`NaN`)return v(NaN);if(e===`Infinity`)return v(1/0);if(e===`-Infinity`)return v(-1/0);if(e.trim()===``)return ye();let t=Us(e);return Us.isNaN(t)?ye():v(t)},Gs=[[`GET`,`get`],[`POST`,`post`],[`PUT`,`put`],[`DELETE`,`del`],[`PATCH`,`patch`],[`HEAD`,`head`],[`OPTIONS`,`options`],[`TRACE`,`trace`]],Ks=`~effect/http/HttpClientRequest`,qs={[Ks]:Ks,...Se,toJSON(){return{_id:`HttpClientRequest`,method:this.method,url:this.url,urlParams:this.urlParams,hash:this.hash,headers:Nt(this.headers),body:this.body.toJSON()}},pipe(){return Ie(this,arguments)}};function Js(e,t,n,r,i,a){let o=Object.create(qs);return o.method=e,o.url=t,o.urlParams=n,o.hash=r,o.headers=i,o.body=a,o}var Ys=Js(`GET`,``,Wr,ye(),Pr,ni),Xs=e=>(t,n)=>Qs(Ys,{method:e,url:t,...n??void 0}),Zs=Xs(`POST`),Qs=_(2,(e,t)=>{let n=e;return t.method&&(n=$s(n,t.method)),t.url&&(n=ic(n,t.url)),t.headers&&(n=tc(n,t.headers)),t.urlParams&&(n=ac(n,t.urlParams)),t.hash&&(n=oc(n,t.hash)),t.body&&(n=sc(n,t.body)),t.accept&&(n=nc(n,t.accept)),t.acceptJson&&(n=rc(n)),n}),$s=_(2,(e,t)=>Js(t,e.url,e.urlParams,e.hash,e.headers,e.body)),ec=_(3,(e,t,n)=>Js(e.method,e.url,e.urlParams,e.hash,Fr(e.headers,t,n),e.body)),tc=_(2,(e,t)=>Js(e.method,e.url,e.urlParams,e.hash,ii(e.headers,t),e.body)),nc=_(2,(e,t)=>ec(e,`Accept`,t)),rc=nc(`application/json`),ic=_(2,(e,t)=>{if(typeof t==`string`)return Js(e.method,t,e.urlParams,e.hash,e.headers,e.body);let n=new URL(t.toString()),r=xr(n.searchParams),i=Zt(n.hash===``?void 0:n.hash.slice(1));return n.search=``,n.hash=``,Js(e.method,n.toString(),r,i,e.headers,e.body)}),ac=_(2,(e,t)=>Js(e.method,e.url,Mi(e.urlParams,t),e.hash,e.headers,e.body)),oc=_(2,(e,t)=>Js(e.method,e.url,e.urlParams,v(t),e.headers,e.body)),sc=_(2,(e,t)=>{let n=e.headers;return t._tag===`Empty`||t._tag===`FormData`?n=ki(ki(n,`Content-Type`),`Content-length`):(t.contentType&&(n=Fr(n,`content-type`,t.contentType)),t.contentLength!==void 0&&(n=Fr(n,`content-length`,t.contentLength.toString()))),Js(e.method,e.url,e.urlParams,e.hash,n,t)}),cc=e=>ti({b3:`${e.traceId}-${e.spanId}-${e.sampled?`1`:`0`}${ge(e.parent,{onNone:()=>``,onSome:e=>`-${e.spanId}`})}`,traceparent:`00-${e.traceId}-${e.spanId}-${e.sampled?`01`:`00`}`}),lc=`~effect/http/HttpClient`,uc=Tt(`effect/HttpClient`),dc=_(2,(e,t)=>pc(n=>t(e.postprocess(n)),e.preprocess)),fc=dc(Mt(Kr)),pc=(e,t)=>{let n=Object.create(mc);return n.preprocess=t,n.postprocess=e,n.execute=function(n){return e(t(n))},n},mc={[lc]:lc,pipe(){return Ie(this,arguments)},...Se,toJSON(){return{_id:`effect/HttpClient`}},...Object.fromEntries(Gs.map(([e,t])=>[t,function(t,n){return this.execute(Xs(e)(t,n))}]))},hc=e=>pc(t=>Mt(t,t=>Kt(n=>{let i=Sc.get(t),a=i??new AbortController,o=pi(t.url,t.urlParams,m(t.hash));if(jt(o))return r(new Ti({reason:new yi({request:t,cause:o.failure})}));let s=o.success;if(n.getRef(Ct)||n.getRef(_c)(t)){let r=e(t,s,a.signal,n);return i?r:Ft(e=>Ae(e(r),{onSuccess(e){return xc.register(e,a),ct(new Cc(e,a))},onFailure(e){return kt(e)&&a.abort(),lt(e)}}))}return pt(n.getRef(yc)(t),{kind:`client`},r=>{r.attribute(`http.request.method`,t.method),r.attribute(`server.address`,s.origin),s.port!==``&&r.attribute(`server.port`,+s.port),r.attribute(`url.full`,s.toString()),r.attribute(`url.path`,s.pathname),r.attribute(`url.scheme`,s.protocol.slice(0,-1));let o=s.search.slice(1);o!==``&&r.attribute(`url.query`,o);let c=n.getRef(Qr),l=Lr(t.headers,c);for(let e in l)r.attribute(`http.request.header.${e}`,String(l[e]));return t=n.getRef(vc)?tc(t,cc(r)):t,Ft(o=>o(e(t,s,a.signal,n)).pipe(tn(r,{captureStackTrace:!1}),Ae({onSuccess:e=>{r.attribute(`http.response.status_code`,e.status);let t=Lr(e.headers,c);for(let e in t)r.attribute(`http.response.header.${e}`,String(t[e]));return i?ct(e):(xc.register(e,a),ct(new Cc(e,a)))},onFailure(e){return!i&&kt(e)&&a.abort(),lt(e)}})))})})),ct),gc=_(2,(e,t)=>{let n=Oe(t),r=n?`errors-and-responses`:t.retryOn??`errors-and-responses`,i=n?t:t.schedule,o=i&&h(i),s=n?void 0:t.times;return dc(e,ie(r===`errors-only`?ue:ae({schedule:o,times:s,while:Ec}),r===`response-only`?ue:fe({while:n||t.while===void 0?wc:a(wc,t.while),schedule:i,times:s})))}),_c=it(`effect/http/HttpClient/TracerDisabledWhen`,{defaultValue:()=>vt}),vc=it(`effect/HttpClient/TracerPropagationEnabled`,{defaultValue:me}),yc=it(`effect/http/HttpClient/SpanNameGenerator`,{defaultValue:()=>e=>`http.client ${e.method}`}),bc=e=>yt(uc)(oe(t=>nt(e,e=>dc(e,Ot(e=>dt(t,e)))))),xc=(()=>{if(`FinalizationRegistry`in globalThis&&globalThis.FinalizationRegistry){let e=new FinalizationRegistry(e=>{e.abort()});return{register(t,n){e.register(t,n,t)},unregister(t){e.unregister(t)}}}let e=new Map;return{register(t,n){e.set(t,setTimeout(()=>n.abort(),5e3))},unregister(t){let n=e.get(t);n!==void 0&&(clearTimeout(n),e.delete(t))}}})(),Sc=new WeakMap,Cc=class{original;controller;constructor(e,t){this.original=e,this.controller=t}[Rr]=Rr;[wr]=wr;applyInterrupt(e){return Bt(()=>(xc.unregister(this.original),wt(e,()=>gt(()=>{this.controller.abort()}))))}get request(){return this.original.request}get status(){return this.original.status}get headers(){return this.original.headers}get cookies(){return this.original.cookies}get remoteAddress(){return this.original.remoteAddress}get formData(){return this.applyInterrupt(this.original.formData)}get text(){return this.applyInterrupt(this.original.text)}get json(){return this.applyInterrupt(this.original.json)}get urlParamsBody(){return this.applyInterrupt(this.original.urlParamsBody)}get arrayBuffer(){return this.applyInterrupt(this.original.arrayBuffer)}get stream(){return Xe(()=>(xc.unregister(this.original),zt(this.original.stream,gt(()=>{this.controller.abort()}))))}toJSON(){return this.original.toJSON()}[st](){return this.original[st]()}pipe(){return Ie(this,arguments)}},wc=e=>tt(e)||Tc(e),Tc=e=>Di(e)&&(e.reason._tag===`TransportError`||e.reason._tag===`StatusCodeError`&&Ec(e.reason.response)),Ec=e=>e.status===408||e.status===429||e.status===500||e.status===502||e.status===503||e.status===504,Dc=`~effect/ManagedRuntime`,Oc=(e,t)=>{let n=t?.memoMap??_e(),r=He(`parallel`),i=te(r,`sequential`),a={onFiberStart:le(r)},s=e=>e?{...e,onFiberStart:e.onFiberStart?t=>{a.onFiberStart(t),e.onFiberStart(t)}:a.onFiberStart}:a,c,l=Kt(t=>(c||=d(Qe(o(e,n,i),e=>gt(()=>{u.cachedContext=e})),{...a,scheduler:t.currentScheduler}),_t(pe(c)))),u={[Dc]:Dc,memoMap:n,scope:r,contextEffect:l,cachedContext:void 0,context(){return u.cachedContext===void 0?re(u.contextEffect):Promise.resolve(u.cachedContext)},dispose(){return re(u.disposeEffect)},disposeEffect:Bt(()=>(u.contextEffect=Ge(`ManagedRuntime disposed`),u.cachedContext=void 0,Le(u.scope,Pt))),runFork(e,t){return u.cachedContext===void 0?d(kc(u,e),s(t)):ze(u.cachedContext)(e,s(t))},runCallback(e,t){return u.cachedContext===void 0?Te(kc(u,e),s(t)):an(u.cachedContext)(e,s(t))},runSyncExit(e){return u.cachedContext===void 0?Rt(kc(u,e)):se(u.cachedContext)(e)},runSync(e){return u.cachedContext===void 0?ce(kc(u,e)):qe(u.cachedContext)(e)},runPromiseExit(e,t){return u.cachedContext===void 0?Pe(kc(u,e),s(t)):We(u.cachedContext)(e,s(t))},runPromise(e,t){return u.cachedContext===void 0?re(kc(u,e),s(t)):x(u.cachedContext)(e,s(t))}};return u};function kc(e,t){return Mt(e.contextEffect,e=>ve(t,e))}var Ac={accept:!1,observe:!1,missingFrameCount:0,startsNewStream:!1};function jc(e){let t=e===!0;return{accept:t,observe:t,missingFrameCount:0,startsNewStream:t}}function Mc(e,t){let n=e.streamGeneration===void 0&&e.streamId===void 0,r=t.streamGeneration!==void 0||t.streamId!==void 0;return n&&r?jc(t.keyframe):null}function Nc(e,t){return e.streamGeneration===void 0||t.streamGeneration===void 0?null:t.streamGeneration<e.streamGeneration?Ac:t.streamGeneration>e.streamGeneration?jc(t.keyframe):null}function Pc(e,t){if(!e.streamId||!t.streamId)return null;if(e.streamId!==t.streamId)return jc(t.keyframe);if(t.sequence<=e.observedSequence)return Ac;let n=Math.max(0,t.sequence-e.observedSequence-1);return{accept:n===0||t.keyframe===!0,observe:!0,missingFrameCount:n,startsNewStream:!1}}function Fc(e,t){if(t.sequence>e.acceptedSequence)return{accept:!0,observe:!0,missingFrameCount:0,startsNewStream:!1};if(!e.acceptedCapturedAt)return Ac;let n=Date.parse(e.acceptedCapturedAt),r=Date.parse(t.capturedAt);return Number.isNaN(n)||Number.isNaN(r)||r<=n?Ac:{accept:!0,observe:!0,missingFrameCount:0,startsNewStream:!1}}function Ic(e,t){return Mc(e,t)??Nc(e,t)??Pc(e,t)??Fc(e,t)}function Lc(e,t){let n=Ic(e,t);if(!n.observe)return{accept:n.accept,observe:n.observe,missingFrameCount:n.missingFrameCount,state:e};let r=n.startsNewStream?t.sequence:Math.max(e.observedSequence,t.sequence),i={...e,observedSequence:r,gapCount:e.gapCount+n.missingFrameCount},a=n.accept?{...i,acceptedSequence:t.sequence,acceptedCapturedAt:t.capturedAt,...t.streamId?{streamId:t.streamId}:{},...t.streamGeneration===void 0?{}:{streamGeneration:t.streamGeneration}}:i;return{accept:n.accept,observe:n.observe,missingFrameCount:n.missingFrameCount,state:a}}function Rc(e){return{_tag:`Value`,value:e}}function zc(e,t){return{_tag:`Record`,keys:e,value:t}}function Bc(e,t){return{_tag:`Array`,length:e,value:t}}mi(`SourceError`);var Vc=it(`effect/ConfigProvider`,{defaultValue:()=>Wc()}),Hc={...Ke,toJSON(){return{_id:`ConfigProvider`}}};function Uc(e,t,n){let r=Object.create(Hc);return r.get=e,r.mapInput=t,r.prefix=n,r.load=r=>(t&&(r=t(r)),n&&(r=[...n,...r]),e(r)),r}function Wc(e){let t=e?.env??{APP_VERSION:`0.13.4`,BASE_URL:`/`,DEV:!1,MODE:`production`,PROD:!0,SSR:!1,TSS_INLINE_CSS_ENABLED:`false`,VITE_COMMIT_SHA:``,VITE_HOSTED_APP_CHANNEL:``,VITE_HTTP_URL:``,VITE_SENTRY_COMMIT_SHA:`6d3e14bfc816cecc19c733eb9e9f9aecbaccf580`,VITE_SENTRY_DEBUG:``,VITE_SENTRY_DSN:``,VITE_SENTRY_ENABLED:``,VITE_SENTRY_ENVIRONMENT:`production`,VITE_SENTRY_PROFILES_SAMPLE_RATE:``,VITE_SENTRY_RELEASE:`forge-web@0.13.4+6d3e14bfc816cecc19c733eb9e9f9aecbaccf580`,VITE_SENTRY_REPLAYS_ON_ERROR_SAMPLE_RATE:``,VITE_SENTRY_REPLAYS_SESSION_SAMPLE_RATE:``,VITE_SENTRY_TRACES_SAMPLE_RATE:``,VITE_WS_URL:``},n=Gc(t);return Uc(e=>ct(qc(n,t,e)))}function Gc(e){let t={};for(let[n,r]of Object.entries(e)){if(r===void 0)continue;let e=n.split(`_`),i=t;for(let t of e)i.children??={},i=i.children[t]??={};i.value=r}return t}var Kc=/^(0|[1-9][0-9]*)$/;function qc(e,t,n){let r=t[n.map(String).join(`_`)],i=Jc(e,n),a=i?.children?Object.keys(i.children):[];return a.length===0?r===void 0?void 0:Rc(r):a.every(e=>Kc.test(e))?Bc(Math.max(...a.map(e=>parseInt(e,10)))+1,r):zc(new Set(a),r)}function Jc(e,t){if(t.length===0)return e;let n=e;for(let e of t)if(n=n?.children?.[String(e)],!n)return;return n}var Yc=`~effect/Config`,Xc=class{_tag=`ConfigError`;name=`ConfigError`;cause;constructor(e){this.cause=e}get message(){return this.cause.toString()}toString(){return`ConfigError(${this.message})`}},Zc={...Ke,...Ye,[Yc]:Yc,asEffect(){return Mt(Vc.asEffect(),e=>this.parse(e))},toJSON(){return{_id:`Config`}}};function Qc(e){let t=Object.create(Zc);return t.parse=e,t}var $c=$e(function*(e,t){let n=yield*e.load(t);if(n!==void 0)switch(n._tag){case`Value`:return n.value;case`Record`:{if(n.value!==void 0)return n.value;let r={};for(let i of n.keys){let n=yield*$c(e,[...t,i]);n!==void 0&&(r[i]=n)}return r}case`Array`:{if(n.value!==void 0)return n.value;let r=[];for(let i=0;i<n.length;i++)r.push(yield*$c(e,[...t,i]));return r}}}),el=$e(function*(e,t,n){switch(e._tag){case`Objects`:{let r={};for(let i of e.propertySignatures){let e=i.name;if(typeof e==`string`){let a=yield*el(i.type,t,[...n,e]);a!==void 0&&(r[e]=a)}}if(e.indexSignatures.length>0){let i=yield*t.load(n);if(i&&i._tag===`Record`)for(let a of e.indexSignatures){let e=Nr(a.parameter);for(let o of i.keys)if(!Object.hasOwn(r,o)&&e(o)){let e=yield*el(a.type,t,[...n,o]);e!==void 0&&(r[o]=e)}}}return r}case`Arrays`:{let r=yield*t.load(n);if(r&&r._tag===`Value`)return r.value;let i=[];for(let r=0;r<e.elements.length;r++)i.push(yield*el(e.elements[r],t,[...n,r]));return i}case`Union`:return yield*$c(t,n);case`Suspend`:return yield*el(e.thunk(),t,n);default:{let e=yield*t.load(n);return e===void 0?void 0:e._tag===`Value`||e._tag===`Record`&&e.value!==void 0||e._tag===`Array`&&e.value!==void 0?e.value:void 0}}});function tl(e,t){let n=Bi(e),r=Yr(n),i=jr(n.ast),a=typeof t==`string`?[t]:t??[];return Qc(e=>{let t=e.prefix?[...e.prefix,...a]:a;return el(i,e,a).pipe(Ht(e=>r(e).pipe(Xt(e=>new Zr(t.length>0?new ri(t,e):e)))),Xt(e=>new Xc(e)))})}var nl=(e,t,n)=>{let r=oi(e,t),i=E.pipe(Or(oi(E,E),Ir(n)),Or(r));return qr([r,i])},A=ee();function rl(e){return new Promise(t=>globalThis.setTimeout(t,e))}function il(){let e=Error(`The environment connection attempt was cancelled.`);return e.name=`AbortError`,e}function al(e){if(e?.aborted)throw il()}function ol(e,t){return t?t.aborted?Promise.reject(il()):new Promise((n,r)=>{let i=()=>r(il());t.addEventListener(`abort`,i,{once:!0}),e.then(n,r).finally(()=>{t.removeEventListener(`abort`,i)})}):e}function sl(e,t){return t?t.aborted?Promise.reject(il()):new Promise((n,r)=>{let i=globalThis.setTimeout(()=>{t.removeEventListener(`abort`,a),n()},e),a=()=>{globalThis.clearTimeout(i),r(il())};t.addEventListener(`abort`,a,{once:!0})}):rl(e)}var cl=Object.freeze({connectionState:`disconnected`,authState:`unknown`,lastError:null,lastErrorAt:null,role:null,descriptor:null,serverConfig:null,connectedAt:null,disconnectedAt:null,providerAuthority:null}),ll=()=>({...cl}),j=wa()(e=>({byId:{},ensure:t=>e(e=>e.byId[t]?e:{byId:{...e.byId,[t]:ll()}}),patch:(t,n)=>e(e=>({byId:{...e.byId,[t]:{...e.byId[t]??ll(),...n}}})),clear:t=>e(e=>{let{[t]:n,...r}=e.byId;return{byId:r}}),reset:()=>e({byId:{}})}));function ul(e){let t=er(e.environmentId);if(t?.lastAuthenticatedPullRequestCapability!==void 0)return{...e,lastAuthenticatedPullRequestCapability:t.lastAuthenticatedPullRequestCapability};let n=j.getState().byId?.[e.environmentId];return n?.authState===`authenticated`&&n.descriptor?{...e,lastAuthenticatedPullRequestCapability:n.descriptor.capabilities.pullRequests===!0}:e}function dl(e){return!!e.runtimeId?.trim()||vr(e.environmentId).isCloud}function fl(e,t){return e.environmentId===t.environmentId&&e.httpBaseUrl===t.httpBaseUrl&&e.wsBaseUrl===t.wsBaseUrl&&e.runtimeId===t.runtimeId&&e.cmmdOrganizationId===t.cmmdOrganizationId}function pl(e){return e.replacedRecord===null&&e.existing!==null&&fl(e.existing,e.record)}function ml(e){let t=e.replacesEnvironmentId?Hr.make(e.replacesEnvironmentId):null,n=t&&t!==e.environmentId?er(t):null;return{existing:er(e.environmentId)??n,replacedRecord:n}}async function hl(e){return{records:lr(),bearerToken:e?await nr(e.environmentId):null}}async function gl(e){let t=e.replacedRecord?.environmentId??e.record.environmentId;await rr(e.rollback.records),await mr(e.record.environmentId).catch(()=>void 0),e.rollback.bearerToken&&await Xn(t,e.rollback.bearerToken)}async function _l(e){try{e.replacedRecord?await qn(e.replacedRecord.environmentId,e.record):await Gn(e.record),al(e.signal),await mr(e.record.environmentId),e.replacedRecord&&await mr(e.replacedRecord.environmentId),al(e.signal)}catch(t){try{await gl(e)}catch(e){let n=AggregateError([t,e],`Cloud Environment rollback failed.`);throw n.cause=t,n}throw t}}function vl(e){return{lastError:e instanceof Error?e.message:String(e),lastErrorAt:new Date().toISOString()}}var yl=new Map;function bl(e,t){return e.acquire(t?{signal:t}:{})}function xl(e,t){yl.set(e,t)}function Sl(e){return yl.has(e)}function Cl(e,t){let n=yl.get(e);if(t&&n!==t){t.dispose();return}n?.dispose(),yl.delete(e)}async function wl(e){let t=yl.get(e);if(t)return(await t.acquire()).bearerToken;let n=er(e);return n&&dl(n)?null:nr(e)}function Tl(){return{executionCount:0,isPending:!1,lastArgs:void 0,lastExecutionTime:0,nextExecutionTime:0,status:`idle`,maybeExecuteCount:0}}var El={enabled:!0,leading:!0,trailing:!0,wait:0},Dl=class{#e;constructor(e,t){this.fn=e,this.store=new Da(Tl()),this.setOptions=e=>{this.options={...this.options,...e},this.#n()||this.cancel()},this.#t=e=>{this.store.setState(t=>{let n={...t,...e},{isPending:r}=n;return{...n,status:this.#n()?r?`pending`:`idle`:`disabled`}}),Oa(`Throttler`,this)},this.#n=()=>!!Ea(this.options.enabled,this),this.#r=()=>Ea(this.options.wait,this),this.maybeExecute=(...e)=>{this.#t({maybeExecuteCount:this.store.state.maybeExecuteCount+1});let t=Date.now(),n=t-this.store.state.lastExecutionTime,r=this.#r();if(this.options.leading&&n>=r)this.#i(...e);else if(this.#t({lastArgs:e}),!this.#e&&this.options.trailing){let e=r-(this.store.state.lastExecutionTime?t-this.store.state.lastExecutionTime:0);this.#t({isPending:!0}),this.#e=setTimeout(()=>{let{lastArgs:e}=this.store.state;e!==void 0&&this.#i(...e)},e)}},this.#i=(...e)=>{if(!this.#n())return;this.fn(...e);let t=Date.now(),n=t+this.#r();this.#a(),this.#t({executionCount:this.store.state.executionCount+1,lastExecutionTime:t,nextExecutionTime:n,isPending:!1,lastArgs:void 0}),this.options.onExecute?.(e,this),setTimeout(()=>{this.store.state.isPending||this.#t({nextExecutionTime:void 0})},this.#r())},this.flush=()=>{this.store.state.isPending&&this.store.state.lastArgs&&this.#i(...this.store.state.lastArgs)},this.#a=()=>{this.#e&&=(clearTimeout(this.#e),void 0)},this.cancel=()=>{this.#a(),this.#t({lastArgs:void 0,isPending:!1})},this.reset=()=>{this.#t(Tl())},this.key=t.key,this.options={...El,...t},this.#t(this.options.initialState??{}),this.key&&ka.on(`d-Throttler`,e=>{e.payload.key===this.key&&(this.#t(e.payload.store.state),this.setOptions(e.payload.options))})}#t;#n;#r;#i;#a},Ol={all:[`projects`],searchContents:(e,t,n,r,i,a,o)=>[`projects`,`search-contents`,e??null,t,n,r,i,a,o],searchEntries:(e,t,n,r)=>[`projects`,`search-entries`,e??null,t,n,r]},kl={all:[`providers`],checkpointDiff:e=>[`providers`,`checkpointDiff`,e.environmentId??null,e.threadId,e.fromTurnCount,e.toTurnCount,e.cacheScope??null]};function Al(e){let t=null,n=!1;function r(){return t}function i(){n=!0,t?.queryInvalidationThrottler.maybeExecute()}function a(){t?.stop(),t=null}function o(r){if(t?.queryClient===r)return t.refCount+=1,()=>{!t||t.queryClient!==r||(--t.refCount,t.refCount===0&&a())};a(),n=!1;let i=new Dl(()=>{n&&(n=!1,r.invalidateQueries({queryKey:kl.all}),r.invalidateQueries({queryKey:Ol.all}))},{wait:100,leading:!1,trailing:!0});e.createPrimaryEnvironmentConnection(),ea().catch(()=>void 0);let o=ir.subscribe(()=>{Wn()&&e.syncSavedEnvironmentConnections(lr())});return Qn().then(()=>e.syncSavedEnvironmentConnections(lr())).catch(()=>void 0),t={queryClient:r,queryInvalidationThrottler:i,refCount:1,stop:()=>{o(),i.cancel()}},()=>{!t||t.queryClient!==r||(--t.refCount,t.refCount===0&&a())}}return{readActiveService:r,notifyProviderInvalidation:i,stopActiveService:a,start:o}}var jl=class extends Error{status;constructor(e,t){super(e),this.name=`RemoteEnvironmentAuthHttpError`,this.status=t}};function Ml(e,t){let n=new URL(e);return n.pathname=`${n.pathname.endsWith(`/`)?n.pathname.slice(0,-1):n.pathname}${t.startsWith(`/`)?t:`/${t}`}`,n.search=``,n.hash=``,n.toString()}async function Nl(e,t){let n=await e.text();if(!n)return t;try{let e=JSON.parse(n);if(typeof e.error==`string`&&e.error.length>0)return e.error}catch{}return n}async function Pl(e){let t=Ml(e.httpBaseUrl,e.pathname),n;try{n=await fetch(t,{method:e.method??`GET`,headers:{...e.body===void 0?{}:{"content-type":`application/json`},...e.bearerToken?{authorization:`Bearer ${e.bearerToken}`}:{}},...e.body===void 0?{}:{body:JSON.stringify(e.body)},...e.signal?{signal:e.signal}:{}})}catch(e){throw Error(`Failed to fetch remote auth endpoint ${t} (${e.message}).`,{cause:e})}if(!n.ok)throw new jl(await Nl(n,`Remote auth request failed (${n.status}).`),n.status);return await n.json()}async function Fl(e){return Pl({httpBaseUrl:e.httpBaseUrl,pathname:`/api/auth/session`,bearerToken:e.bearerToken,...e.signal?{signal:e.signal}:{}})}async function Il(e){return Pl({httpBaseUrl:e.httpBaseUrl,pathname:`/.well-known/forge/environment`,...e.bearerToken?{bearerToken:e.bearerToken}:{}})}async function Ll(e){return Pl({httpBaseUrl:e.httpBaseUrl,pathname:`/api/auth/ws-token`,method:`POST`,bearerToken:e.bearerToken})}async function Rl(e){let t=new URL(e.wsBaseUrl,window.location.origin);if(e.runtimeTicket)return t.searchParams.set(`runtimeTicket`,e.runtimeTicket),t.searchParams.delete(`wsToken`),t.toString();let n=await Ll({httpBaseUrl:e.httpBaseUrl,bearerToken:e.bearerToken});return t.searchParams.set(`wsToken`,n.token),t.toString()}function zl(e,t){if(t){ja(t,e);return}Ma(e)}function Bl(e){let t=null,n=[];for(let r of e.split(/\r?\n/)){if(r.startsWith(`event:`)){t=r.slice(6).trim();continue}r.startsWith(`data:`)&&n.push(r.slice(5).trimStart())}return{eventName:t,data:n.join(`
|
|
3
3
|
`)}}function Vl(e,t){let n=Bl(e);if(n.eventName!==`phase`||!n.data)return!1;try{let e=JSON.parse(n.data);return zl(e,t),e.phase===`app-ready`||e.phase===`error`}catch{return!1}}async function Hl(e,t,n){if(!e.body)return;let r=e.body.getReader(),i=new TextDecoder,a=``;for(;!n.aborted;){let{done:e,value:n}=await r.read();if(e)break;a+=i.decode(n,{stream:!0});let o=a.indexOf(`
|
|
4
4
|
|
|
5
5
|
`);for(;o!==-1;){let e=a.slice(0,o);if(a=a.slice(o+2),Vl(e,t))return;o=a.indexOf(`
|
|
6
6
|
|
|
7
|
-
`)}}}var Ul=(e=`/api/workspace/readiness`)=>{if(typeof fetch>`u`)return{close:()=>{}};let t=typeof e==`string`?{url:e}:e,n=!1,r=new AbortController;return fetch(t.url,{credentials:t.bearerToken?`omit`:`include`,signal:r.signal,...t.bearerToken?{headers:{Authorization:`Bearer ${t.bearerToken}`}}:{}}).then(e=>{if(e.ok)return Hl(e,t.environmentId,r.signal)}).catch(()=>{}),{close:()=>{n||(n=!0,r.abort())}}},Wl=6e4;function Gl(e){let t=new URL(e.target.httpBaseUrl);return t.pathname=`${t.pathname.endsWith(`/`)?t.pathname.slice(0,-1):t.pathname}/api/workspace/readiness`,t.search=``,t.hash=``,t.toString()}function Kl(e){let t=new Set,n=null,r=!1,i=!1;return{hasWaiters:()=>t.size>0,wait:()=>{if(r)return Promise.reject(n);if(i)return Promise.resolve();let a=null,o=null,s=new Promise((e,n)=>{o={resolve:e,reject:n},t.add(o)}),c=new Promise((t,n)=>{a=globalThis.setTimeout(()=>{n(Error(`Timed out while waiting for ${e.label} (${e.environmentId}) to stream its shell snapshot.`))},e.timeoutMs)});return Promise.race([s,c]).finally(()=>{a!==null&&globalThis.clearTimeout(a),o!==null&&t.delete(o)})},resolve:()=>{r=!1,n=null,i=!0;let e=[...t];t.clear();for(let t of e)t.resolve()},reject:e=>{r=!0,n=e,i=!1;let a=[...t];t.clear();for(let t of a)t.reject(e)},reset:()=>{r=!1,n=null,i=!1}}}function ql(e){let t=e.knownEnvironment.environmentId;if(!t)throw Error(`Known environment ${e.knownEnvironment.label} is missing its environmentId.`);let n=!1,r=!1,i=null,a=null,o=Kl({environmentId:t,label:e.knownEnvironment.label,timeoutMs:e.bootstrapTimeoutMs??Wl}),s=e.readiness?(e.readiness.openStream??Ul)({url:Gl(e.knownEnvironment),environmentId:t,...e.readiness.bearerToken?{bearerToken:e.readiness.bearerToken}:{}}):null,c=t=>{if(!r){r=!0;let n=Error(t);_(),e.client.dispose(),e.onIdentityMismatch?.(n)}return!1},l=(n,r)=>{if(e.tolerateReportedEnvironmentIdentity)return a===null?(a=n,!0):a===n||c(`Environment connection ${t} reported a changed runtime identity (${a} -> ${n}) via ${r}.`);let i=e.resolveEnvironmentId?.()??t;return i===n||c(`Environment connection ${i} changed identity to ${n} via ${r}.`)},u=()=>e.resolveEnvironmentId?.()??t,d=e.client.server.subscribeLifecycle(t=>{t.type===`welcome`&&l(t.payload.environment.environmentId,`server lifecycle welcome`)&&e.onWelcome?.(t.payload,u())}),f=e.client.server.subscribeConfig(t=>{if(t.type===`snapshot`){if(!l(t.config.environment.environmentId,`server config snapshot`))return;i=t.config,e.onConfigSnapshot?.(t.config);return}if(t.type!==`providerStatuses`||!i)return;let n={...i,providers:t.payload.providers};i=n,e.onConfigSnapshot?.(n)}),p=e.client.orchestration.subscribeShell(t=>{if(t.kind===`snapshot`){e.syncShellSnapshot(t.snapshot,u()),o.resolve();return}e.applyShellEvent(t,u())},{onResubscribe:()=>{n||o.reset()},onError:t=>{if(!n){if(o.hasWaiters()){o.reject(t);return}e.onShellSubscriptionError?.(t,u())}}}),m=e.client.terminal.onEvent(t=>{e.applyTerminalEvent(t,u())}),h=e.client.browser?.onEvent({},t=>{e.applyBrowserEvent(t,u())}),g=e.client.server.subscribeWorkspaceReadiness(e=>{n||D(async()=>{let{setWorkspaceReadinessPhaseForEnvironment:e}=await import(`./workspaceReadinessAtom-D6bgTvKb.js`).then(e=>e.r);return{setWorkspaceReadinessPhaseForEnvironment:e}},__vite__mapDeps([0,1,2,3])).then(({setWorkspaceReadinessPhaseForEnvironment:t})=>{n||t(u(),e)})}),_=()=>{n||(n=!0,e.onDispose?.(),s?.close(),p(),m(),h?.(),d(),f(),g())};return{kind:e.kind,environmentId:t,knownEnvironment:e.knownEnvironment,client:e.client,ensureBootstrapped:()=>o.wait(),reconnect:async()=>{o.reset();try{await e.client.reconnect(),await e.refreshMetadata?.(),await o.wait()}catch(e){throw o.reject(e),e}},...e.ensureProviderAuthority?{ensureProviderAuthority:e.ensureProviderAuthority}:{},dispose:async()=>{_(),await e.client.dispose()}}}var Jl=it(`effect/http/FetchHttpClient/Fetch`,{defaultValue:()=>globalThis.fetch}),Yl=class extends Tt()(`effect/http/FetchHttpClient/RequestInit`){},Xl=bc(ct(hc((e,t,n,r)=>{let i=r.getRef(Jl),a=r.context.mapUnsafe.get(Yl.key)??{},o=a.headers?Mr(Xr(a.headers),e.headers):e.headers,s=r=>nt(ot({try:()=>i(t,{...a,method:e.method,headers:o,body:r,duplex:e.body._tag===`Stream`?`half`:void 0,signal:n}),catch:t=>new Ti({reason:new ci({request:e,cause:t})})}),t=>Vi(e,t));switch(e.body._tag){case`Raw`:case`Uint8Array`:return s(e.body.body);case`FormData`:return s(e.body.formData);case`Stream`:return Mt($t(e.body.stream),s)}return s(void 0)}))),Zl=Jt.pipe(h,Qt(e=>{if(Di(e)&&e.reason._tag===`StatusCodeError`&&e.reason.response.status===429){let t=Ee(e.reason.response.headers[`retry-after`]).pipe(en(Ws),f(()=>5));return ct(ne(t))}return ct(ne(1))})),Ql=$e(function*(e){let t=yield*Lt(),n=ut(t,Hs),r=ut(t,Ce),a=ze(t),o=u(we(e.exportInterval),Ue),s,c=fc(ut(t,uc)).pipe(dc(xe(vc,!1)),gc({schedule:Zl,times:3})),d=ti({"user-agent":`effect-opentelemetry-${e.label}/0.0.0`});e.headers&&(d=Mr(Xr(e.headers),d));let f=Zs(e.url,{headers:d}),p=[],m=Bt(()=>{if(s!==void 0&&n.currentTimeMillisUnsafe()<s)return ft;s!==void 0&&(s=void 0);let t=p;if(e.maxBatchSize!==`disabled`){if(p.length===0)return ft;p=[]}return c.execute(sc(f,e.body(t))).pipe(Fe,et(!1))}).pipe(Be(e=>s===void 0?(s=n.currentTimeMillisUnsafe()+6e4,p=[],Ze(`Disabling exporter for 60 seconds`,e)):ft),l({package:`@effect/opentelemetry`,module:e.label}));return yield*rn(r,m.pipe(It,ht,Et(e.shutdownTimeout))),yield*i(o).pipe(nn(m),at,Gt(r)),{push(t){s===void 0&&(p.push(t),e.maxBatchSize!==`disabled`&&p.length>=e.maxBatchSize&&le(a(m),r))}}}),$l=e=>{let t=e.attributes?nu(Object.entries(e.attributes)):[];return t.push({key:`service.name`,value:{stringValue:e.serviceName}}),e.serviceVersion&&t.push({key:`service.version`,value:{stringValue:e.serviceVersion}}),{attributes:t,droppedAttributesCount:0}},eu=$e(function*(e){let t={...yield*tl(Ri(nl(E,E)),`OTEL_RESOURCE_ATTRIBUTES`),...e?.attributes},n=e?.serviceName??t[`service.name`]??(yield*tl(E,`OTEL_SERVICE_NAME`));delete t[`service.name`];let r=e?.serviceVersion??t[`service.version`]??(yield*tl(Ri(E),`OTEL_SERVICE_VERSION`));return delete t[`service.version`],$l({serviceName:n,serviceVersion:r,attributes:t})},c),tu=e=>{let t=e.attributes.find(e=>e.key===`service.name`);if(!t||!t.value.stringValue)throw Error(`Resource does not contain a service name`);return t.value.stringValue},nu=e=>{let t=[];for(let[n,r]of e)t.push({key:n,value:ru(r)});return t},ru=e=>{if(Array.isArray(e))return{arrayValue:{values:e.map(ru)}};switch(typeof e){case`string`:return{stringValue:e};case`bigint`:return{intValue:Number(e)};case`number`:return Number.isInteger(e)?{intValue:e}:{doubleValue:e};case`boolean`:return{boolValue:e};default:return{stringValue:At(e)}}},iu=class extends Tt()(`effect/observability/OtlpSerialization`){},au=de(iu,{traces:e=>ai(e),metrics:e=>ai(e),logs:e=>ai(e)}),ou=$e(function*(e){let t=yield*eu(e.resource),n=yield*iu,r={name:tu(t)},i=yield*Ql({label:`OtlpTracer`,url:e.url,headers:e.headers,exportInterval:e.exportInterval??ne(5),maxBatchSize:e.maxBatchSize??1e3,body(e){let i={resourceSpans:[{resource:t,scopeSpans:[{scope:r,spans:e}]}]};return n.traces(i)},shutdownTimeout:e.shutdownTimeout??ne(3)});function a(e){e.sampled&&i.push(uu(e))}return he({span(e){return cu({...e,status:{_tag:`Started`,startTime:e.startTime},attributes:new Map,export:a})},context:e.context?function(t,n){return n.currentSpan===void 0?t[`~effect/Effect/evaluate`](n):e.context(t,n.currentSpan)}:void 0})}),su={_tag:`Span`,end(e,t){this.status={_tag:`Ended`,startTime:this.status.startTime,endTime:e,exit:t},this.export(this)},attribute(e,t){this.attributes.set(e,t)},event(e,t,n){this.events.push([e,t,n])},addLinks(e){this.links.push(...e)}},cu=e=>{let t=Object.assign(Object.create(su),e);return t.traceId=St(t.parent)?t.parent.value.traceId:lu(32),t.spanId=lu(16),t.events=[],t},lu=e=>{let t=``;for(let n=0;n<e;n++)t+=`0123456789abcdef`[Math.floor(Math.random()*16)];return t},uu=e=>{let t=e.status,n=nu(e.attributes.entries()),r=e.events.map(([e,t,n])=>({name:e,timeUnixNano:String(t),attributes:n?nu(Object.entries(n)):[],droppedAttributesCount:0})),i;if(t.exit._tag===`Success`)i=pu;else if(mt(t.exit.cause))i={code:du.Ok,message:`Interrupted`},n.push({key:`span.label`,value:{stringValue:`⚠︎ Interrupted`}},{key:`status.interrupted`,value:{boolValue:!0}});else{let e=Yt(t.exit.cause);if(i={code:du.Error},e.length>0){i.message=e[0].message;for(let n of e)r.push({name:`exception`,timeUnixNano:String(t.endTime),droppedAttributesCount:0,attributes:[{key:`exception.type`,value:{stringValue:n.name}},{key:`exception.message`,value:{stringValue:n.message}},{key:`exception.stacktrace`,value:{stringValue:n.stack??`No stack trace available`}}]})}}return{traceId:e.traceId,spanId:e.spanId,parentSpanId:ge(e.parent,{onNone:()=>void 0,onSome:e=>e.spanId}),name:e.name,kind:fu[e.kind],startTimeUnixNano:String(t.startTime),endTimeUnixNano:String(t.endTime),attributes:n,droppedAttributesCount:0,events:r,droppedEventsCount:0,status:i,links:e.links.map(e=>({traceId:e.span.traceId,spanId:e.span.spanId,attributes:nu(Object.entries(e.attributes)),droppedAttributesCount:0})),droppedLinksCount:0}},du={Unset:0,Ok:1,Error:2},fu={unspecified:0,internal:1,server:2,client:3,producer:4,consumer:5},pu={code:du.Ok},mu=1e4,hu={serviceName:`forge-web`,attributes:{"service.runtime":`forge-web`,"service.mode":bn?`electron`:`browser`,"service.version":Cn}},gu=be(Xl,au,de(_c,()=>!0)),_u=null,vu=null,yu=null,bu=null,xu=0,Su=Promise.resolve(),Cu=de(bt,he({span(e){return _u?.span(e)??new s(e)}}));function wu(e={}){return e.exportIntervalMs===void 0&&bu!==null||(Su=Su.finally(()=>Tu(e))),Su}async function Tu(e){let t=Ji(`/api/observability/v1/traces`),n=ra()?.bearerToken,r=Math.max(10,e.exportIntervalMs??mu),i=`${t}|${r}|${n?`bearer`:`cookie`}`;if(bu===i&&_u!==null)return;bu=i;let a=++xu,o=vu,s=yu;_u=null,vu=null,yu=null,await Eu(o,s);let c=Oc(gu),l=c.runSync(Me());try{let e=await c.runPromise(b(l)(ou({url:t,...n?{headers:{Authorization:`Bearer ${n}`}}:{},exportInterval:`${r} millis`,resource:hu})));if(a!==xu){await Eu(c,l);return}_u=e,vu=c,yu=l}catch(e){await Eu(c,l),a===xu&&console.warn(`Failed to configure client tracing exporter`,{error:Du(e),otlpTracesUrl:t})}}async function Eu(e,t){e!==null&&t!==null&&await e.runPromise(Le(t,Pt)).catch(()=>void 0).finally(()=>{e.dispose()})}function Du(e){return e instanceof Error&&e.message.trim().length>0?e.message:String(e)}var Ou=15e3,ku=new Map,Au=un([]).pipe(ln,sn(`slow-rpc-ack-requests`));function ju(e){cn.set(Au,[...e])}function Mu(){return cn.get(Au)}var Nu=`global`;function Pu(e){return!(e.split(`.`).at(-1)??e).startsWith(`subscribe`)}function Fu(e,t,n=Nu){if(!Pu(t))return;Bu(e,n),Hu();let r=Date.now(),i={clientId:n,requestId:e,startedAt:new Date(r).toISOString(),startedAtMs:r,tag:t,thresholdMs:Ou},a=zu(n,e),o=setTimeout(()=>{ku.delete(a),Vu(i)},Ou);ku.set(a,{request:i,timeoutId:o})}function Iu(e,t=Nu){Bu(e,t);let n=Mu();n.some(n=>n.clientId===t&&n.requestId===e)&&ju(n.filter(n=>n.clientId!==t||n.requestId!==e))}function Lu(e){for(let[t,n]of ku)n.request.clientId===e&&(clearTimeout(n.timeoutId),ku.delete(t));ju(Mu().filter(t=>t.clientId!==e))}function Ru(){for(let e of ku.values())clearTimeout(e.timeoutId);ku.clear(),ju([])}function zu(e,t){return`${e}:${t}`}function Bu(e,t){let n=zu(t,e),r=ku.get(n);r&&(clearTimeout(r.timeoutId),ku.delete(n))}function Vu(e){let t=[...Mu(),e];if(t.length<=256){ju(t);return}ju(t.slice(-256))}function Hu(){for(;ku.size>=256;){let e=ku.keys().next().value;if(e===void 0)return;let t=ku.get(e);if(!t)return;Bu(t.request.requestId,t.request.clientId)}}function Uu(){return ma(Au)}var Wu=ia(ui),Gu=1;function Ku(e){return e instanceof Error&&e.message.trim().length>0?e.message:String(e)}function qu(e){let t=new URL(e);if(t.protocol!==`ws:`&&t.protocol!==`wss:`)throw Error(`Unsupported websocket transport URL protocol: ${t.protocol}`);return t.pathname=`/ws`,t.toString()}function Ju(){return{onAttempt:ya,onOpen:Ki,onError:e=>{qi(e)},onClose:e=>{oa(e)},trackGlobalConnection:!0}}function Yu(e){let t=Ju(),n=e?.trackGlobalConnection??!0;return{onAttempt:r=>{n&&t.onAttempt(r),e?.onAttempt?.(r)},onOpen:()=>{n&&t.onOpen(),e?.onOpen?.()},onError:r=>{n&&t.onError(r),e?.onError?.(r)},onClose:r=>{n&&t.onClose(r),e?.onClose?.(r)},trackGlobalConnection:n}}function Xu(e,t){let n=Gu;Gu+=1;let r=Yu(t),i=typeof e==`function`?xt(()=>e()).pipe(nt(e=>qu(e)),Ut(e=>gt(()=>{r.onError(Ku(e))})),c):qu(e),a=de(va,(e,t)=>{r.onAttempt(e);let n=new globalThis.WebSocket(e,t);return n.addEventListener(`open`,()=>{r.onOpen()},{once:!0}),n.addEventListener(`error`,()=>{r.onError(`Unable to connect to the Forge server WebSocket.`)},{once:!0}),n.addEventListener(`close`,e=>{r.onClose({code:e.code,reason:e.reason})},{once:!0}),n}),o=ha(i).pipe(y(a)),s=Qt(p(fa),e=>ct(Re(Gi(e)??0)));return yt(da,nt(Hi({retryPolicy:s,retryTransientErrors:!0}),e=>({...e,run:(t,r)=>{let i=`${n}:${String(t)}`;return e.run(t,e=>(e._tag===`Chunk`||e._tag===`Exit`?Iu(e.requestId,i):(e._tag===`ClientProtocolError`||e._tag===`Defect`)&&Lu(i),r(e))).pipe(Je(gt(()=>{Lu(i)})))},send:(t,r,i)=>{let a=`${n}:${String(t)}`;return r._tag===`Request`&&Fu(r.id,r.tag,a),e.send(t,r,i)}}))).pipe(y(be(o,pa)))}var Zu=/^all fibers interrupted without error$/i;function Qu(e){return On(e)||Zu.test(e.trim())}var $u=Re(250),ed=()=>void 0,td=class extends Error{name=`WsRequestTimeoutError`;timeoutMs;constructor(e){let t=Ne(we(e));super(`WebSocket RPC request timed out after ${t}ms.`),this.timeoutMs=t}},nd=new Set([`OrchestrationGetSnapshotError`]);function rd(e){if(typeof e!=`object`||!e)return!1;let t=e._tag;return typeof t==`string`&&nd.has(t)}function id(e){let t=e instanceof Error?e.message.trim():``;return t.length>0?t:typeof e==`object`&&e?ad(e):String(e)}function ad(e){try{return JSON.stringify(e)}catch{let t=e;return[typeof t._tag==`string`?t._tag:void 0,typeof t.message==`string`?t.message:void 0].filter(Boolean).join(`: `)||Object.prototype.toString.call(e)}}var od=4e3,sd=1e4,cd=500,ld=class{url;lifecycleHandlers;disposed=!1;hasReportedTransportDisconnect=!1;reconnectChain=Promise.resolve();session;heartbeatTimer=null;heartbeatInFlight=!1;protocol;timing;constructor(e,t,n,r){this.url=e,this.lifecycleHandlers=t,this.protocol=n??null,this.timing={heartbeatIntervalMs:r?.heartbeatIntervalMs??od,heartbeatTimeoutMs:r?.heartbeatTimeoutMs??sd,sessionCloseGraceMs:r?.sessionCloseGraceMs??cd},this.session=this.createSession(),this.startHeartbeat()}startHeartbeat(){this.heartbeatTimer===null&&(this.heartbeatTimer=setInterval(()=>{if(this.disposed||this.heartbeatInFlight)return;this.heartbeatInFlight=!0;let e=this.session;this.request(e=>e[T.serverHeartbeat]({}),{timeout:this.timing.heartbeatTimeoutMs}).catch(async()=>{this.disposed||e!==this.session||await this.reconnect()}).finally(()=>{this.heartbeatInFlight=!1})},this.timing.heartbeatIntervalMs))}async request(e,t){if(this.disposed)throw Error(`Transport disposed`);let n=this.session,i=await n.clientPromise,a=Bt(()=>e(i)),o=t?.timeout,s=o===void 0?a:a.pipe(Wt({duration:o,orElse:()=>r(new td(o))}));return await n.runtime.runPromise(s,{signal:t?.signal})}async requestStream(e,t,n){if(this.disposed)throw Error(`Transport disposed`);let r=this.session,i=this.runStreamOnSession(r,e,t,()=>!0,()=>void 0),a=()=>i.cancel();n?.signal?.aborted&&a(),n?.signal?.addEventListener(`abort`,a,{once:!0});try{await i.completed}catch(e){if(n?.signal?.aborted){let e=Error(`RPC stream request was cancelled.`);throw e.name=`AbortError`,e}throw e}finally{n?.signal?.removeEventListener(`abort`,a)}}subscribe(e,t,n){if(this.disposed)return()=>void 0;let r={active:!0,hasReceivedValue:!1,cancelCurrentStream:ed},i=Ne(we(n?.retryDelay??$u));return this.runSubscriptionLoop(e,t,n,r,i),()=>{r.active=!1,r.cancelCurrentStream()}}async runSubscriptionLoop(e,t,n,r,i){for(;r.active&&!this.disposed;){let a=this.session;try{this.notifyResubscribe(r,n);let i=this.startSubscriptionStream(a,e,t,r);r.cancelCurrentStream=i.cancel,await i.completed,r.cancelCurrentStream=ed}catch(e){if(r.cancelCurrentStream=ed,!await this.handleSubscriptionFailure(e,a,r,n,i))return}}}notifyResubscribe(e,t){if(e.hasReceivedValue)try{t?.onResubscribe?.()}catch{}}startSubscriptionStream(e,t,n,r){return this.runStreamOnSession(e,t,n,()=>r.active,()=>{this.hasReportedTransportDisconnect=!1,r.hasReceivedValue=!0})}async handleSubscriptionFailure(e,t,n,r,i){if(!n.active||this.disposed)return!1;if(t!==this.session)return!0;let a=id(e);return Qu(a)?(this.hasReportedTransportDisconnect||console.warn(`WebSocket RPC subscription disconnected`,{error:a}),this.hasReportedTransportDisconnect=!0,await ud(i),!0):(this.reportNonTransportSubscriptionError(e,r),!1)}reportNonTransportSubscriptionError(e,t){rd(e)||Vn(e,{route:`ws-subscribe`,reason:`non-transport-error`}),t?.onError?.(e)}async reconnect(){if(this.disposed)throw Error(`Transport disposed`);let e=this.reconnectChain.then(async()=>{if(this.disposed)throw Error(`Transport disposed`);let e=this.session;this.session=this.createSession(),await this.closeSession(e)});this.reconnectChain=e.catch(e=>{Vn(e,{route:`ws-reconnect`})}),await e}async dispose(){this.disposed||(this.disposed=!0,this.heartbeatTimer!==null&&this.heartbeatTimer!==void 0&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null),await this.closeSession(this.session))}async closeSession(e){let t=e.runtime.runPromise(Le(e.clientScope,Pt)),n=!1,r=null,i=new Promise(e=>{r=setTimeout(()=>{n=!0,e()},this.timing.sessionCloseGraceMs)});try{await Promise.race([t,i])}finally{r!==null&&clearTimeout(r),n&&(console.warn(`WebSocket session close exceeded its grace period; forcing disposal`,{graceMs:this.timing.sessionCloseGraceMs}),t.catch(()=>void 0)),await e.runtime.dispose()}}createSession(){let e=this.protocol??{layer:Xu(this.url,this.lifecycleHandlers),makeClient:Wu},t=Oc(be(e.layer,Cu)),n=t.runSync(Me());return{runtime:t,clientScope:n,clientPromise:t.runPromise(b(n)(e.makeClient))}}runStreamOnSession(e,t,n,r,i){let a,o,s=new Promise((e,t)=>{a=e,o=t});return{cancel:e.runtime.runCallback(xt(()=>e.clientPromise).pipe(Mt(e=>Dt(t(e),e=>gt(()=>{if(r()){i();try{n(e)}catch{}}})))),{onExit:e=>{if(Vt(e)){a();return}o(ke(e.cause))}}),completed:s}}};function ud(e){return new Promise(t=>{setTimeout(t,e)})}var dd=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/`,fd=/^[A-Za-z0-9_-]+$/;function pd(e){let t=``;for(let n=0;n<e.byteLength;n+=3){let r=e[n]??0,i=e[n+1]??0,a=e[n+2]??0,o=r<<16|i<<8|a;t+=dd[o>>>18&63],t+=dd[o>>>12&63],n+1<e.byteLength&&(t+=dd[o>>>6&63]),n+2<e.byteLength&&(t+=dd[o&63])}return t.replaceAll(`+`,`-`).replaceAll(`/`,`_`)}function md(e){if(e.length===0||!fd.test(e))throw Error(`Bulk transfer chunk is not valid base64url data.`);let t=e.replaceAll(`-`,`+`).replaceAll(`_`,`/`),n=Math.floor(t.length*6/8),r=new Uint8Array(n),i=0,a=0,o=0;for(let e of t){let t=dd.indexOf(e);if(t<0)throw Error(`Bulk transfer chunk is not valid base64url data.`);i=i<<6|t,a+=6,a>=8&&(a-=8,r[o]=i>>>a&255,o+=1)}return r}async function hd(e){let t=new Uint8Array(e.byteLength);t.set(e);let n=await crypto.subtle.digest(`SHA-256`,t.buffer);return Array.from(new Uint8Array(n),e=>e.toString(16).padStart(2,`0`)).join(``)}async function gd(e,t){let n=t?.chunkBytes??262144;if(!Number.isSafeInteger(n)||n<1||n>262144)throw Error(`Bulk transfer chunk size must be between 1 and ${$r}.`);let r=t?.transferId??crypto.randomUUID().replaceAll(`-`,`_`),i=[];for(let t=0;t<e.byteLength;t+=n){let a=e.slice(t,Math.min(t+n,e.byteLength));i.push({kind:`chunk`,transferId:r,offset:t,bytes:a.byteLength,data:pd(a),sha256:await hd(a)})}return{totalBytes:e.byteLength,sha256:await hd(e),chunks:i}}async function _d(e){let t=md(e.data);if(t.byteLength!==e.bytes)throw Error(`Bulk transfer chunk byte count mismatch at offset ${e.offset}: expected ${e.bytes}, received ${t.byteLength}.`);if(await hd(t)!==e.sha256)throw Error(`Bulk transfer chunk integrity mismatch at offset ${e.offset}.`);return t}async function vd(e){let t=new Map,n=[],r=0;for(let i of e.chunks){let e=t.get(i.offset);if(e!==void 0){if(e.bytes!==i.bytes||e.sha256!==i.sha256||e.data!==i.data)throw Error(`Bulk transfer has a conflicting duplicate chunk at offset ${i.offset}.`);continue}if(i.offset!==r)throw Error(`Bulk transfer chunk offset mismatch: expected ${r}, received ${i.offset}.`);let a=await _d(i);t.set(i.offset,i),n.push({chunk:i,bytes:a}),r+=a.byteLength}if(r!==e.totalBytes)throw Error(`Bulk transfer total byte count mismatch: expected ${e.totalBytes}, received ${r}.`);let i=new Uint8Array(e.totalBytes);for(let e of n)i.set(e.bytes,e.chunk.offset);if(await hd(i)!==e.sha256)throw Error(`Bulk transfer payload integrity mismatch.`);return i}var yd=`forge`,bd=RegExp(`^(?:${yd}|t3code)\\/(?:[0-9a-f]{8}|[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12})$`);function xd(){return`${yd}/${ce(xa).replace(/-/g,``).slice(0,8).toLowerCase()}`}function Sd(e){return bd.test(e.trim().toLowerCase())}function Cd(e){let t=e.trim().replace(/\/+$/g,``).replace(/\.git$/i,``).toLowerCase();if(/^(?:ssh|https?|git):\/\//i.test(t))try{let e=new URL(t),n=e.pathname.split(`/`).filter(e=>e.length>0).join(`/`);if(e.hostname&&n.includes(`/`))return`${e.hostname}/${n}`}catch{return t}let n=/^git@([^:/\s]+)[:/]([^/\s]+(?:\/[^/\s]+)+)$/i.exec(t);return n?.[1]&&n[2]?`${n[1]}/${n[2]}`:t}function wd(e){let t=e?.trim()??``;if(t.length===0)return null;let n=/^(?:git@github\.com:|ssh:\/\/git@github\.com\/|https:\/\/github\.com\/|git:\/\/github\.com\/)([^/\s]+\/[^/\s]+?)(?:\.git)?\/?$/i.exec(t)?.[1]?.trim()??``;return n.length>0?n:null}function Td(e){let t=e.trim();if(t.length===0)return null;if(t.startsWith(`git@`)){let e=t.slice(4),n=e.search(/[:/]/);return n<=0?null:e.slice(0,n).toLowerCase()}try{return new URL(t).hostname.toLowerCase()}catch{return null}}function Ed(e){return`https://${e}`}function Dd(e){return e===`github.com`||e.includes(`github`)}function Od(e){return e===`gitlab.com`||e.includes(`gitlab`)}function kd(e){return e===`bitbucket.org`}function Ad(e){return e===`dev.azure.com`||e===`ssh.dev.azure.com`||e===`vs-ssh.visualstudio.com`||e.endsWith(`.visualstudio.com`)}function jd(e){let t=Td(e);if(!t)return null;let n=Cd(e),r=`${t}/`;if(!n.startsWith(r))return null;let i=n.slice(r.length);return i.includes(`/`)?Dd(t)?{kind:`github`,name:t===`github.com`?`GitHub`:`GitHub Self-Hosted`,host:t,repositoryPath:i,baseUrl:Ed(t)}:Od(t)?{kind:`gitlab`,name:t===`gitlab.com`?`GitLab`:`GitLab Self-Hosted`,host:t,repositoryPath:i,baseUrl:Ed(t)}:kd(t)?{kind:`bitbucket`,name:`Bitbucket Cloud`,host:t,repositoryPath:i,baseUrl:Ed(t)}:Ad(t)?{kind:`azure-devops`,name:`Azure DevOps`,host:t,repositoryPath:i,baseUrl:Ed(t)}:{kind:`unknown`,name:t,host:t,repositoryPath:i,baseUrl:Ed(t)}:null}var Md={hasUpstream:!1,aheadCount:0,behindCount:0,pr:null,defaultBranch:null,diffVsBase:null};function Nd(e,t){return{...e,...t??Md}}function Pd(e){return{hasUpstream:e.hasUpstream,aheadCount:e.aheadCount,behindCount:e.behindCount,pr:e.pr,defaultBranch:e.defaultBranch,diffVsBase:e.diffVsBase}}function Fd(e){return{isRepo:e.isRepo,...e.hostingProvider?{hostingProvider:e.hostingProvider}:{},hasOriginRemote:e.hasOriginRemote,isDefaultBranch:e.isDefaultBranch,branch:e.branch,hasWorkingTreeChanges:e.hasWorkingTreeChanges,workingTree:e.workingTree}}function Id(e,t){switch(t._tag){case`snapshot`:return Nd(t.local,t.remote);case`localUpdated`:return Nd(t.local,e?Pd(e):null);case`remoteUpdated`:return Nd(e===null?{isRepo:!0,hasOriginRemote:!1,isDefaultBranch:!1,branch:null,hasWorkingTreeChanges:!1,workingTree:{files:[],insertions:0,deletions:0}}:Fd(e),t.remote)}}var Ld=262144,Rd=250;function zd(e){if(e instanceof Error)return e.message;try{return JSON.stringify(e)}catch{return String(e)}}function Bd(e){return new Promise(t=>setTimeout(t,e))}function Vd(e){let t=crypto.randomUUID(),n=Xi({controllerId:t,maxPendingWriteBytes:Ld}),r=!1,i=e=>{if(!e.sessionEpoch)throw Error(`Connected Forge runtime does not support epoch-fenced terminal controls.`);n.register({threadId:e.threadId,terminalId:e.terminalId,sessionEpoch:e.sessionEpoch})},a=async e=>{for(;!r;)try{return await e()}catch(e){if(!On(zd(e)))throw e;await Bd(Rd)}throw Error(`Terminal control client was disposed before acknowledgement.`)};return{terminal:{open:async t=>{let n=await e.request(e=>e[T.terminalOpen]({...t,terminalId:t.terminalId??`default`}));return i(n),n},write:async t=>{let r=t.terminalId??`default`;await n.enqueue({threadId:t.threadId,terminalId:r,writeBytes:new TextEncoder().encode(t.data).byteLength,execute:n=>a(()=>e.request(e=>e[T.terminalWrite]({...t,terminalId:r,...n})))})},resize:async t=>{let r=t.terminalId??`default`;await n.enqueue({threadId:t.threadId,terminalId:r,execute:n=>a(()=>e.request(e=>e[T.terminalResize]({...t,terminalId:r,...n})))})},signal:async t=>{let r=t.terminalId??`default`;await n.enqueue({threadId:t.threadId,terminalId:r,execute:n=>a(()=>e.request(e=>e[T.terminalSignal]({...t,terminalId:r,...n})))})},clear:async t=>{let r=t.terminalId??`default`;await n.enqueue({threadId:t.threadId,terminalId:r,execute:n=>a(()=>e.request(e=>e[T.terminalClear]({...t,terminalId:r,...n})))})},restart:async t=>{let r=t.terminalId??`default`,o=null;if(await n.enqueue({threadId:t.threadId,terminalId:r,execute:async n=>{o=(await a(()=>e.request(e=>e[T.terminalRestart]({...t,terminalId:r,...n})))).snapshot}}),o===null)throw Error(`Terminal restart completed without a snapshot.`);return i(o),o},close:async t=>{let r=t.terminalId?[t.terminalId]:n.terminalIds(t.threadId);for(let i of r)await n.enqueue({threadId:t.threadId,terminalId:i,execute:n=>a(()=>e.request(e=>e[T.terminalClose]({...t,terminalId:i,...n})))}),n.remove(t.threadId,i)},onEvent:t=>e.subscribe(e=>e[T.subscribeTerminalEvents]({}),e=>{(e.type===`started`||e.type===`restarted`)&&i(e.snapshot),t(e)})},dispose:()=>{r=!0,n.dispose()}}}function Hd(e){return{createUploadUrl:t=>e.request(e=>e[T.attachmentsCreateUploadUrl](t)),delete:t=>e.request(e=>e[T.attachmentsDelete](t))}}function Ud(e){return{environmentPreflight:t=>e.request(e=>e[T.workspaceEnvironmentPreflight](t)),listDirectory:t=>e.request(e=>e[T.workspaceListDirectory](t)),ensureScratch:t=>e.request(e=>e[T.workspaceEnsureScratch](t))}}async function Wd(e,t){await e.request(e=>e[T.workspaceCancelWriteFile]({transferId:t})).catch(()=>void 0)}var Gd=2e4,Kd=12e4,qd=3e5;function Jd(e){if(e instanceof td)return!0;let t=e instanceof Error?e.message:String(e);return On(t)}async function Yd(e,t){let n=t.type===`thread.turn.start`&&t.bootstrap!==void 0?qd:Gd,r=()=>e.request(e=>e[Ai.dispatchCommand](t),{timeout:n});try{return await r()}catch(t){if(!Jd(t))throw t;return await e.reconnect(),await r()}}function Xd(e){if(!e?.aborted)return;let t=Error(`Bulk transfer was cancelled.`);throw t.name=`AbortError`,t}async function Zd(e,t,n){let r={started:null,completed:null,chunks:[],protocolError:null,receivedBytes:0};if(await e.requestStream(t,e=>Qd(r,e,n),n),r.protocolError!==null)throw r.protocolError;let i=r.started,a=r.completed;if(i===null||a===null)throw Error(`Bulk transfer stream completed without start and completion metadata.`);if(a.transferId!==i.transferId||a.totalBytes!==i.totalBytes||a.sha256!==i.sha256)throw Error(`Bulk transfer completion metadata mismatch.`);return await vd({totalBytes:i.totalBytes,sha256:i.sha256,chunks:r.chunks})}function Qd(e,t,n){if(e.protocolError===null){if(t.kind===`started`){$d(e,t,n);return}if(e.started===null||t.transferId!==e.started.transferId){e.protocolError=Error(`Bulk transfer event identity mismatch.`);return}if(t.kind===`chunk`){ef(e,t,n);return}e.completed=t,n?.onProgress?.({completedBytes:t.totalBytes,totalBytes:t.totalBytes})}}function $d(e,t,n){if(e.started!==null||t.totalBytes>16777216){e.protocolError=Error(`Bulk transfer started with invalid or oversized metadata.`);return}e.started=t,n?.onProgress?.({completedBytes:0,totalBytes:t.totalBytes})}function ef(e,t,n){let r=e.started;if(r!==null){if(e.receivedBytes+=t.bytes,e.receivedBytes>r.totalBytes){e.protocolError=Error(`Bulk transfer exceeded its declared byte count.`);return}e.chunks.push(t),n?.onProgress?.({completedBytes:e.receivedBytes,totalBytes:r.totalBytes})}}async function tf(e,t,n){let r=new TextEncoder().encode(t.contents);if(r.byteLength>16777216)throw Error(`Project file exceeds the ${Ar}-byte write limit.`);let i=await gd(r),a=i.chunks[0]?.transferId??crypto.randomUUID().replaceAll(`-`,`_`),o=!1;try{Xd(n?.signal);let r=await nf(e,t,a,i);return o=!0,n?.onProgress?.({completedBytes:r.nextOffset,totalBytes:i.totalBytes}),await rf(e,a,i,r,n),{relativePath:t.relativePath}}catch(t){throw o&&await Wd(e,a),t}}function nf(e,t,n,r){return e.request(e=>e[T.workspaceBeginWriteFile]({transferId:n,cwd:t.cwd,relativePath:t.relativePath,totalBytes:r.totalBytes,sha256:r.sha256}))}async function rf(e,t,n,r,i){if(r.state!==`completed`){for(let t of n.chunks){if(t.offset<r.nextOffset)continue;Xd(i?.signal);let{kind:a,...o}=t,s=await e.request(e=>e[T.workspaceWriteFileChunk](o));i?.onProgress?.({completedBytes:s.nextOffset,totalBytes:n.totalBytes})}Xd(i?.signal),await e.request(e=>e[T.workspaceCommitWriteFile]({transferId:t}))}}function af(e){let t=Vd(e);return{dispose:()=>(t.dispose(),e.dispose()),reconnect:async()=>{na(),await e.reconnect()},terminal:t.terminal,browser:{openSession:t=>e.request(e=>e[T.browserOpenSession](t)),listSessions:t=>e.request(e=>e[T.browserListSessions](t)),closeSession:t=>e.request(e=>e[T.browserCloseSession](t)),getSession:t=>e.request(e=>e[T.browserGetSession](t)),command:t=>e.request(e=>e[T.browserCommand](t)),clearBrowsingData:t=>e.request(e=>e[T.browserClearBrowsingData](t)),attachDisplay:t=>e.request(e=>e[T.browserAttachDisplay](t)),addDisplayIceCandidate:t=>e.request(e=>e[T.browserAddDisplayIceCandidate](t)),onEvent:(t,n,r)=>e.subscribe(e=>e[T.subscribeBrowserEvents](t),n,r)},computer:{input:t=>e.request(e=>e[T.computerInput](t))},threadDevRuntime:{get:t=>e.request(e=>e[T.threadDevRuntimeGet](t)),allocatePort:t=>e.request(e=>e[T.threadDevRuntimeAllocatePort](t)),release:t=>e.request(e=>e[T.threadDevRuntimeRelease](t))},devTunnel:{register:t=>e.request(e=>e[T.devTunnelRegister](t)),unregister:t=>e.request(e=>e[T.devTunnelUnregister](t)),list:t=>e.request(e=>e[T.devTunnelList](t))},attachments:Hd(e),projects:{searchContents:(t,n)=>e.request(e=>e[T.projectsSearchContents](t),n),searchEntries:t=>e.request(e=>e[T.projectsSearchEntries](t)),readFile:(t,n)=>Zd(e,e=>e[T.workspaceReadFile](t),n),writeFile:(t,n)=>tf(e,t,n)},projectCheckoutDeletion:{preview:t=>e.request(e=>e[T.projectCheckoutDeletionPreview](t)),execute:t=>e.request(e=>e[T.projectCheckoutDeletionExecute](t))},workspace:Ud(e),shell:{openInEditor:t=>e.request(e=>e[T.shellOpenInEditor](t))},git:{pull:t=>e.request(e=>e[T.gitPull](t)),refreshStatus:t=>e.request(e=>e[T.gitRefreshStatus](t)),onStatus:(t,n,r)=>{let i=null;return e.subscribe(e=>e[T.subscribeGitStatus](t),e=>{i=Id(i,e),n(i)},r)},runStackedAction:async(t,n)=>{let r=null;if(await e.requestStream(e=>e[T.gitRunStackedAction](t),e=>{n?.onProgress?.(e),e.kind===`action_finished`&&(r=e.result)}),r)return r;throw Error(`Git action stream completed without a final result.`)},listBranches:t=>e.request(e=>e[T.gitListBranches](t)),createWorktree:t=>e.request(e=>e[T.gitCreateWorktree](t)),removeWorktree:t=>e.request(e=>e[T.gitRemoveWorktree](t)),createBranch:t=>e.request(e=>e[T.gitCreateBranch](t)),checkout:t=>e.request(e=>e[T.gitCheckout](t)),init:t=>e.request(e=>e[T.gitInit](t)),resolvePullRequest:t=>e.request(e=>e[T.gitResolvePullRequest](t)),preparePullRequestThread:t=>e.request(e=>e[T.gitPreparePullRequestThread](t))},pullRequests:{list:t=>e.request(e=>e[T.pullRequestsList](t)),listStats:t=>e.request(e=>e[T.pullRequestsListStats](t)),detail:t=>e.request(e=>e[T.pullRequestsDetail](t)),activity:t=>e.request(e=>e[T.pullRequestsActivity](t)),threadComments:t=>e.request(e=>e[T.pullRequestsThreadComments](t)),diffFileContents:t=>e.request(e=>e[T.pullRequestsDiffFileContents](t)),runAction:t=>e.request(e=>e[T.pullRequestsRunAction](t)),update:t=>e.request(e=>e[T.pullRequestsUpdate](t)),comment:t=>e.request(e=>e[T.pullRequestsComment](t)),updateComment:t=>e.request(e=>e[T.pullRequestsUpdateComment](t)),submitReview:t=>e.request(e=>e[T.pullRequestsSubmitReview](t)),replyToThread:t=>e.request(e=>e[T.pullRequestsReplyToThread](t)),setThreadResolution:t=>e.request(e=>e[T.pullRequestsSetThreadResolution](t)),setReaction:t=>e.request(e=>e[T.pullRequestsSetReaction](t)),invalidate:t=>e.request(e=>e[T.pullRequestsInvalidate](t)),reviewerCandidates:t=>e.request(e=>e[T.pullRequestsReviewerCandidates](t)),requestReviewers:t=>e.request(e=>e[T.pullRequestsRequestReviewers](t))},server:{getConfig:()=>e.request(e=>e[T.serverGetConfig]({})),refreshProviders:()=>e.request(e=>e[T.serverRefreshProviders]({})),startProviderAuth:t=>e.request(e=>e[T.serverStartProviderAuth](t)),repairProviderAuthRuntime:t=>e.request(e=>e[T.serverRepairProviderAuthRuntime](t)),disconnectProviderAuth:t=>e.request(e=>e[T.serverDisconnectProviderAuth](t)),getProviderAuthSession:t=>e.request(e=>e[T.serverGetProviderAuthSession](t)),cancelProviderAuth:t=>e.request(e=>e[T.serverCancelProviderAuth](t)),submitProviderAuthCode:t=>e.request(e=>e[T.serverSubmitProviderAuthCode](t)),syncPersonalCodexToCloud:t=>e.request(e=>e[T.serverSyncPersonalCodexToCloud](t)),syncPersonalClaudeToCloud:t=>e.request(e=>e[T.serverSyncPersonalClaudeToCloud](t)),upsertKeybinding:t=>e.request(e=>e[T.serverUpsertKeybinding](t)),removeKeybinding:t=>e.request(e=>e[T.serverRemoveKeybinding](t)),getSettings:()=>e.request(e=>e[T.serverGetSettings]({})),updateSettings:t=>e.request(e=>e[T.serverUpdateSettings]({patch:t})),updateEnvironmentDisplayName:t=>e.request(e=>e[T.serverUpdateEnvironmentDisplayName](t)),getTraceDiagnostics:t=>e.request(e=>e[T.serverGetTraceDiagnostics](t)),subscribeConfig:(t,n)=>e.subscribe(e=>e[T.subscribeServerConfig]({}),t,n),subscribeLifecycle:(t,n)=>e.subscribe(e=>e[T.subscribeServerLifecycle]({}),t,n),subscribeAuthAccess:(t,n)=>e.subscribe(e=>e[T.subscribeAuthAccess]({}),t,n),subscribeWorkspaceReadiness:(t,n)=>e.subscribe(e=>e[T.subscribeWorkspaceReadiness]({}),t,n)},usage:{getSummary:t=>e.request(e=>e[T.usageGetSummary](t),{timeout:Kd})},orchestration:{dispatchCommand:t=>Yd(e,t),searchThreads:t=>e.request(e=>e[Ai.searchThreads](t),{timeout:1e4}),getTurnDiff:(t,n)=>Zd(e,e=>e[Ai.streamTurnDiff](t),n).then(e=>({...t,diff:new TextDecoder().decode(e)})),getFullThreadDiff:(t,n)=>Zd(e,e=>e[Ai.streamFullThreadDiff](t),n).then(e=>({...t,fromTurnCount:0,diff:new TextDecoder().decode(e)})),subscribeShell:(t,n)=>e.subscribe(e=>e[Ai.subscribeShell]({}),t,n),subscribeThread:(t,n,r)=>e.subscribe(e=>e[Ai.subscribeThread](t),n,r)}}}function of(){if(typeof window>`u`)return;let e=Zi();if(!(e?.primaryMode!==`cloud`||!e.bearerToken))return{bearerToken:e.bearerToken,httpBaseUrl:e.httpBaseUrl,wsBaseUrl:e.wsBaseUrl}}function sf(){if(typeof window>`u`)return;let e=Zi(),t=e?.primaryMode===`cloud`?e.desktopLocal:e;if(!(!t?.httpBaseUrl||!t.wsBaseUrl||!t.bearerToken))return{bearerToken:t.bearerToken,httpBaseUrl:t.httpBaseUrl,wsBaseUrl:t.wsBaseUrl,label:t.label}}function cf(e){let t=sr(e);if(!t)throw Error(`Unable to resolve websocket URL for ${e?.label??`primary environment`}.`);return af(new ld(async()=>{await ea().catch(()=>null);let e=of();if(e)try{return await Rl(e)}catch(e){throw Rn(e)&&Ui(`ws-token`),e}return kn(t)}))}function lf(e){return af(new ld(()=>Rl(e),{trackGlobalConnection:!1,onAttempt:()=>e.onConnecting(e.environmentId),onOpen:()=>e.onConnected(e.environmentId),onError:t=>e.onError(e.environmentId,t),onClose:t=>e.onDisconnected(e.environmentId,t.reason)}))}function uf(e){return typeof e==`string`?e:typeof e==`object`&&e&&`detail`in e&&typeof e.detail==`string`?e.detail:e instanceof Error?e.message:String(e)}function df(e){return e.match(/blocked by policy for\s+([^.\s]+(?:\.[^.\s]+)*)\.?/i)?.[1]||(e.match(/navigation to\s+([^.\s]+(?:\.[^.\s]+)*)\s+is restricted/i)?.[1]??null)}function ff(e){let t=uf(e).trim()||`Unknown browser error.`,n=df(t);return/blocked by policy|restricted to allowed domains/i.test(t)?{title:`Browser navigation blocked`,cause:`${n??`This URL`} is not allowed by the current browser policy.`,nextAction:`Use an allowed URL or update the browser allowed-domain setting.`,technicalDetail:t}:/does not match thread|session .*not found|no active browser tab|tab .*not found/i.test(t)?{title:`Browser session is stale`,cause:`Forge no longer has a matching live browser session for this thread.`,nextAction:`Restart the browser session from the Browser options menu.`,technicalDetail:t}:/screenshot|capture|Page\.capture/i.test(t)?{title:`Browser screenshot failed`,cause:`The browser could not capture the current page frame.`,nextAction:`Reload the page, then try the screenshot again.`,technicalDetail:t}:/timed out|timeout/i.test(t)?{title:`Browser action timed out`,cause:`Forge did not receive a response from the browser runtime in time.`,nextAction:`Retry the action. If it keeps failing, restart the browser session.`,technicalDetail:t}:/runtime is not available|browser.*unavailable|not supported|disabled/i.test(t)?{title:`Browser session unavailable`,cause:`This environment does not currently expose the in-app browser runtime.`,nextAction:`Use a workspace with browser support or restart Forge after browser support is enabled.`,technicalDetail:t}:/navigate|navigation|net::|ERR_/i.test(t)?{title:`Browser navigation failed`,cause:`The browser could not load the requested page.`,nextAction:`Check the URL and network access, then try again.`,technicalDetail:t}:{title:`Browser action failed`,cause:`Forge could not complete the browser action.`,nextAction:`Retry the action. If it keeps failing, restart the browser session from the Browser options menu.`,technicalDetail:t}}function pf(e){let t=ff(e);return`${t.cause} ${t.nextAction}`}function mf(e){let t=ff(e);return`${t.title}: ${t.cause} ${t.nextAction}`}var hf={session:null,selectedBrowserId:null,sessionsByBrowserId:{},lastActivityByTabId:{},lastSnapshotContentByTabId:{},lastScreenshotDataUrlByTabId:{},lastScreenshotMetaByTabId:{},lastConsoleLogsByTabId:{},lastConsoleLogsMetaByTabId:{},lastFrameByTabId:{},lastFrameSequenceByTabId:{},lastObservedFrameSequenceByTabId:{},lastFrameStreamIdByTabId:{},lastFrameStreamGenerationByTabId:{},frameGapCountByTabId:{},lastFrameMetaByTabId:{},displayIceCandidatesByClientId:{},lastError:null};function gf(e){return Ln(e)}function _f(e){let t=e.status===`reconnecting`&&e.reason===`network_unreachable`;return e.transport===`remote-webrtc`&&(e.status===`connected`||e.status===`connecting`||e.status===`reconnecting`)&&(e.reason!==`network_unreachable`||t)&&e.reason!==`unsupported_host`}function vf(e){return e.transport!==`remote-webrtc`||e.status===`failed`||e.status===`unsupported`?!1:e.reason!==`network_unreachable`&&e.reason!==`unsupported_host`}function yf(e){let{currentSession:t,nextSession:n}=e;return!t||t.browserId!==n.browserId||t.sessionId!==n.sessionId||!_f(t.display)||!vf(n.display)?n:{...n,display:{...t.display,viewport:n.display.viewport??n.viewport??t.display.viewport,devicePixelRatio:n.display.devicePixelRatio??t.display.devicePixelRatio,iceServers:n.display.iceServers??t.display.iceServers,reconnect:t.display.reconnect??n.display.reconnect}}}function bf(e){let{storedSession:t,nextSession:n}=e;if(!t||t.browserId!==n.browserId||t.sessionId!==n.sessionId)return!1;let r=n.tabs.some(e=>e.navigationStatus===`pending`),i=t.tabs.some(e=>e.navigationStatus===`complete`||e.navigationStatus===`failed`);if(!r||!i)return!1;let a=Date.parse(t.updatedAt),o=Date.parse(n.updatedAt);return Number.isNaN(a)||Number.isNaN(o)?!1:o<a}function M(e,t,n){return e[t]===n?e:{...e,[t]:n}}function xf(e){switch(e.type){case`tab.updated`:return e.payload.tab.tabId;case`tab.closed`:case`snapshot.ready`:case`screenshot.ready`:case`frame.ready`:case`console.logs.ready`:case`display.iceCandidate`:case`display.metrics`:return e.payload.tabId;case`action.failed`:return e.payload.tabId??null;case`display.updated`:case`session.started`:case`session.updated`:case`session.closed`:return null}}function Sf(e,t){let n=xf(t);return n?{...e,lastActivityByTabId:{...e.lastActivityByTabId,[n]:{actor:t.agentId?`agent`:`human`,agentId:t.agentId,browserId:t.browserId,eventType:t.type,...t.type===`action.failed`?{commandType:t.payload.commandType}:{},...t.type===`action.failed`?{message:t.payload.message}:{},createdAt:t.createdAt}}}:e}function Cf(e){switch(e.type){case`session.started`:case`session.updated`:case`tab.updated`:case`snapshot.ready`:case`screenshot.ready`:case`frame.ready`:case`display.updated`:return!0;case`session.closed`:case`tab.closed`:case`console.logs.ready`:case`action.failed`:case`display.iceCandidate`:case`display.metrics`:return!1}}function wf(e){return e===null?`end-of-candidates`:JSON.stringify([e.candidate,e.sdpMid??null,e.sdpMLineIndex??null,e.usernameFragment??null])}function Tf(e,t){let n=wf(t);return e.some(e=>wf(e)===n)?e:[...e,t]}function Ef(e){if(e.type!==`session.closed`)return null;switch(e.payload.reason){case`idle_timeout`:return`The browser was closed after being idle. Reopen the preview to restore this thread's browser.`;case`runtime_shutdown`:return`The browser runtime shut down. Reopen the preview to restore this thread's browser.`;case`thread_archived`:case`clear_browsing_data`:case`user_closed`:case void 0:return null}}function Df(e){let t=e.event.payload.display;return t.status===`failed`||t.status===`unsupported`?t.detail??`Browser display is unavailable.`:e.currentLastError&&/browser display/i.test(e.currentLastError)?null:e.currentLastError}function Of(e,t){let n=e.sessionsByBrowserId[t.browserId]??(e.session?.browserId===t.browserId?e.session:null);if(!n)return!0;let r=n.sessionId===t.payload.sessionId,i=!t.sessionEpoch||!n.sessionEpoch||t.sessionEpoch===n.sessionEpoch;return r&&i}function kf(e,t){let n=e.lastFrameSequenceByTabId[t]??0;return{acceptedSequence:n,observedSequence:e.lastObservedFrameSequenceByTabId[t]??n,...e.lastFrameStreamIdByTabId[t]?{streamId:e.lastFrameStreamIdByTabId[t]}:{},...e.lastFrameStreamGenerationByTabId[t]===void 0?{}:{streamGeneration:e.lastFrameStreamGenerationByTabId[t]},...e.lastFrameMetaByTabId[t]?.capturedAt?{acceptedCapturedAt:e.lastFrameMetaByTabId[t].capturedAt}:{},gapCount:e.frameGapCountByTabId[t]??0}}function Af(e,t){let n=t.payload.tabId,r=Lc(kf(e,n),{sequence:t.payload.sequence,capturedAt:t.payload.capturedAt,...t.payload.streamId?{streamId:t.payload.streamId}:{},...t.payload.streamGeneration===void 0?{}:{streamGeneration:t.payload.streamGeneration},...t.payload.keyframe===void 0?{}:{keyframe:t.payload.keyframe}});return{decision:r,observedSequence:r.state.observedSequence,frameGapCount:r.state.gapCount}}function jf(e,t,n){let r=t.payload.tabId;return{...e,lastObservedFrameSequenceByTabId:{...e.lastObservedFrameSequenceByTabId,[r]:n.observedSequence},frameGapCountByTabId:{...e.frameGapCountByTabId,[r]:n.frameGapCount}}}function Mf(e,t){let n=t.payload.tabId;return{...e,lastFrameByTabId:{...e.lastFrameByTabId,[n]:t.payload.imageDataUrl},lastFrameSequenceByTabId:{...e.lastFrameSequenceByTabId,[n]:t.payload.sequence},lastFrameStreamIdByTabId:t.payload.streamId?{...e.lastFrameStreamIdByTabId,[n]:t.payload.streamId}:e.lastFrameStreamIdByTabId,lastFrameStreamGenerationByTabId:t.payload.streamGeneration===void 0?e.lastFrameStreamGenerationByTabId:{...e.lastFrameStreamGenerationByTabId,[n]:t.payload.streamGeneration},lastFrameMetaByTabId:{...e.lastFrameMetaByTabId,[n]:{capturedAt:t.payload.capturedAt,url:t.payload.url,viewport:t.payload.viewport}},lastError:null}}function Nf(e){let{current:t,event:n,pendingAutoRevealKeys:r,state:i,threadKey:a}=e;if(!Of(t,n))return i;let o=Af(t,n);if(!o.decision.observe)return i;let s=jf(t,n,o),c=o.decision.accept?Mf(s,n):s;return{browserStateByThreadKey:M(i.browserStateByThreadKey,a,c),pendingAutoRevealKeys:r}}var Pf=wa(e=>({browserStateByThreadKey:{},pendingAutoRevealKeys:new Set,setSessionSnapshot:(t,n)=>e(e=>{let r=gf(t),i=e.browserStateByThreadKey[r]??hf,a=n?yf({currentSession:i.sessionsByBrowserId[n.browserId]??i.session,nextSession:n}):null;return{browserStateByThreadKey:M(e.browserStateByThreadKey,r,{...i,session:a,selectedBrowserId:a?.browserId??i.selectedBrowserId,sessionsByBrowserId:a?{...i.sessionsByBrowserId,[a.browserId]:a}:i.sessionsByBrowserId,lastError:a?null:i.lastError})}}),selectBrowserSession:(t,n)=>e(e=>{let r=gf(t),i=e.browserStateByThreadKey[r]??hf,a=i.sessionsByBrowserId[n]??i.session;return{browserStateByThreadKey:M(e.browserStateByThreadKey,r,{...i,selectedBrowserId:n,session:a})}}),applyBrowserEvent:(t,n)=>e(e=>{let r=gf(t),i=Cf(n)?new Set(e.pendingAutoRevealKeys).add(r):e.pendingAutoRevealKeys,a=Sf(e.browserStateByThreadKey[r]??hf,n);switch(n.type){case`session.started`:{if(bf({storedSession:a.sessionsByBrowserId[n.payload.snapshot.browserId]??a.session,nextSession:n.payload.snapshot}))return e;let t=yf({currentSession:a.sessionsByBrowserId[n.payload.snapshot.browserId]??a.session,nextSession:n.payload.snapshot});return{browserStateByThreadKey:M(e.browserStateByThreadKey,r,{...a,session:t,selectedBrowserId:a.selectedBrowserId??t.browserId,sessionsByBrowserId:{...a.sessionsByBrowserId,[t.browserId]:t},lastError:null}),pendingAutoRevealKeys:i}}case`session.updated`:{let t=yf({currentSession:a.sessionsByBrowserId[n.payload.snapshot.browserId]??a.session,nextSession:n.payload.snapshot});return{browserStateByThreadKey:M(e.browserStateByThreadKey,r,{...a,session:a.selectedBrowserId&&a.selectedBrowserId!==n.payload.snapshot.browserId?a.session:t,selectedBrowserId:a.selectedBrowserId??n.payload.snapshot.browserId,sessionsByBrowserId:{...a.sessionsByBrowserId,[t.browserId]:t},lastError:null}),pendingAutoRevealKeys:i}}case`session.closed`:let t=a.selectedBrowserId===n.browserId||a.session?.browserId===n.browserId;return{browserStateByThreadKey:M(e.browserStateByThreadKey,r,{...a,session:t?null:a.session,selectedBrowserId:t?null:a.selectedBrowserId,sessionsByBrowserId:Object.fromEntries(Object.entries(a.sessionsByBrowserId).filter(([e])=>e!==n.browserId)),lastError:Ef(n)})};case`display.updated`:{let t=a.session;if(!t||t.sessionId!==n.payload.sessionId)return{browserStateByThreadKey:M(e.browserStateByThreadKey,r,a),pendingAutoRevealKeys:i};let o={...t,display:n.payload.display,updatedAt:n.createdAt};return{browserStateByThreadKey:M(e.browserStateByThreadKey,r,{...a,session:o,sessionsByBrowserId:{...a.sessionsByBrowserId,[o.browserId]:o},lastError:Df({currentLastError:a.lastError,event:n})}),pendingAutoRevealKeys:i}}case`tab.updated`:{let t=a.session;if(!t||t.sessionId!==n.payload.sessionId)return{browserStateByThreadKey:M(e.browserStateByThreadKey,r,a),pendingAutoRevealKeys:i};let o=t.tabs.map(e=>e.tabId===n.payload.tab.tabId?{...n.payload.tab,isActive:e.tabId===t.activeTabId}:{...e,isActive:e.tabId===t.activeTabId}).concat(t.tabs.some(e=>e.tabId===n.payload.tab.tabId)?[]:[{...n.payload.tab,isActive:n.payload.tab.tabId===t.activeTabId}]);return{browserStateByThreadKey:M(e.browserStateByThreadKey,r,{...a,session:{...t,tabs:o},lastError:null}),pendingAutoRevealKeys:i}}case`tab.closed`:{let t=a.session;if(!t||t.sessionId!==n.payload.sessionId)return e;let i=t.tabs.filter(e=>e.tabId!==n.payload.tabId);return{browserStateByThreadKey:M(e.browserStateByThreadKey,r,{...a,session:{...t,tabs:i,activeTabId:t.activeTabId===n.payload.tabId?i[0]?.tabId??null:t.activeTabId}})}}case`snapshot.ready`:return{browserStateByThreadKey:M(e.browserStateByThreadKey,r,{...a,lastSnapshotContentByTabId:{...a.lastSnapshotContentByTabId,[n.payload.tabId]:n.payload.content},lastError:null}),pendingAutoRevealKeys:i};case`screenshot.ready`:return{browserStateByThreadKey:M(e.browserStateByThreadKey,r,{...a,lastScreenshotDataUrlByTabId:{...a.lastScreenshotDataUrlByTabId,[n.payload.tabId]:n.payload.imageDataUrl},lastScreenshotMetaByTabId:{...a.lastScreenshotMetaByTabId,[n.payload.tabId]:{captureId:n.payload.captureId,capturedAt:n.payload.capturedAt,url:n.payload.url,viewport:n.payload.viewport}},lastError:null}),pendingAutoRevealKeys:i};case`frame.ready`:return Nf({state:e,current:a,event:n,threadKey:r,pendingAutoRevealKeys:i});case`console.logs.ready`:return{browserStateByThreadKey:M(e.browserStateByThreadKey,r,{...a,lastConsoleLogsByTabId:{...a.lastConsoleLogsByTabId,[n.payload.tabId]:n.payload.logs},lastConsoleLogsMetaByTabId:{...a.lastConsoleLogsMetaByTabId,[n.payload.tabId]:{capturedAt:n.createdAt,tabId:n.payload.tabId,count:n.payload.logs.length}},lastError:null})};case`display.iceCandidate`:{let t=a.displayIceCandidatesByClientId[n.payload.clientId]??[];return{browserStateByThreadKey:M(e.browserStateByThreadKey,r,{...a,displayIceCandidatesByClientId:{...a.displayIceCandidatesByClientId,[n.payload.clientId]:Tf(t,n.payload.candidate)}}),pendingAutoRevealKeys:i}}case`display.metrics`:return{browserStateByThreadKey:M(e.browserStateByThreadKey,r,a),pendingAutoRevealKeys:i};case`action.failed`:return{browserStateByThreadKey:M(e.browserStateByThreadKey,r,{...a,lastError:mf(n.payload.message)})};default:return e}}),clearBrowserState:t=>e(e=>{let n=gf(t);if(!(n in e.browserStateByThreadKey))return e;let{[n]:r,...i}=e.browserStateByThreadKey;return{browserStateByThreadKey:i}}),consumeAutoReveal:t=>e(e=>{if(!e.pendingAutoRevealKeys.has(t))return e;let n=new Set(e.pendingAutoRevealKeys);return n.delete(t),{pendingAutoRevealKeys:n}})}));function Ff(e,t){return t?e[gf(t)]??null:null}function If(e){if(e!==void 0)return Object.fromEntries(Object.entries(e).toSorted(([e],[t])=>e.localeCompare(t)))}function Lf(e){return{...e,...e.projectIds===void 0?{}:{projectIds:[...e.projectIds].toSorted((e,t)=>e.localeCompare(t))},...e.cursors===void 0?{}:{cursors:If(e.cursors)}}}var Rf={all:e=>[`pullRequests`,e],list:(e,t)=>[`pullRequests`,e,`list`,Lf(t)],stats:(e,t)=>[`pullRequests`,e,`stats`,[...t].toSorted((e,t)=>`${e.projectId}:${e.repository}#${e.number}`.localeCompare(`${t.projectId}:${t.repository}#${t.number}`))],detail:(e,t)=>[`pullRequests`,e,`detail`,t],activity:(e,t)=>[`pullRequests`,e,`activity`,t],diff:(e,t)=>[`pullRequests`,e,`diff`,t],threadComments:(e,t)=>[`pullRequests`,e,`thread-comments`,t],diffFileContents:(e,t)=>[`pullRequests`,e,`diff-file-contents`,t],reviewerCandidates:(e,t)=>[`pullRequests`,e,`reviewer-candidates`,t]},zf=Hr.make(`command-authority`);function Bf(e){return e[0]===`pullRequests`&&e[1]===zf&&e[2]===`detail`}function Vf(e){return e[0]===`pullRequests`&&e[1]===zf&&e[2]===`list`}function Hf(e,t){let n;try{n=e()}catch{return}return{getItem:e=>{let r=e=>e===null?null:JSON.parse(e,t?.reviver),i=n.getItem(e)??null;return i instanceof Promise?i.then(r):r(i)},setItem:(e,r)=>n.setItem(e,JSON.stringify(r,t?.replacer)),removeItem:e=>n.removeItem(e)}}var Uf=e=>t=>{try{let n=e(t);return n instanceof Promise?n:{then(e){return Uf(e)(n)},catch(e){return this}}}catch(e){return{then(e){return this},catch(t){return Uf(t)(e)}}}},Wf=(e,t)=>(n,r,i)=>{let a={storage:Hf(()=>window.localStorage),partialize:e=>e,version:0,merge:(e,t)=>({...t,...e}),...t},o=!1,s=0,c=new Set,l=new Set,u=a.storage;if(!u)return e((...e)=>{console.warn(`[zustand persist middleware] Unable to update item '${a.name}', the given storage is currently unavailable.`),n(...e)},r,i);let d=()=>{let e=a.partialize({...r()});return u.setItem(a.name,{state:e,version:a.version})},f=i.setState;i.setState=(e,t)=>(f(e,t),d());let p=e((...e)=>(n(...e),d()),r,i);i.getInitialState=()=>p;let m,h=()=>{if(!u)return;let e=++s;o=!1,c.forEach(e=>e(r()??p));let t=a.onRehydrateStorage?.call(a,r()??p)||void 0;return Uf(u.getItem.bind(u))(a.name).then(e=>{if(e)if(typeof e.version==`number`&&e.version!==a.version){if(a.migrate){let t=a.migrate(e.state,e.version);return t instanceof Promise?t.then(e=>[!0,e]):[!0,t]}console.error(`State loaded from storage couldn't be migrated since no migrate function was provided`)}else return[!1,e.state];return[!1,void 0]}).then(t=>{if(e!==s)return;let[i,o]=t;if(m=a.merge(o,r()??p),n(m,!0),i)return d()}).then(()=>{e===s&&(t?.(r(),void 0),m=r(),o=!0,l.forEach(e=>e(m)))}).catch(n=>{e===s&&t?.(void 0,n)})};return i.persist={setOptions:e=>{a={...a,...e},e.storage&&(u=e.storage)},clearStorage:()=>{++s,u?.removeItem(a.name)},getOptions:()=>a,rehydrate:()=>h(),hasHydrated:()=>o,onHydrate:e=>(c.add(e),()=>{c.delete(e)}),onFinishHydration:e=>(l.add(e),()=>{l.delete(e)})},a.skipHydration||h(),m||p},Gf=/^(localhost|[a-z0-9.-]+\.localhost|127(?:\.\d{1,3}){3}|\[[0:]+1\]|::1)(?::\d+)?(?:[/?#]|$)/i,Kf=/https?:\/\/[^\s"'`<>]+/gu,qf=new RegExp(String.raw`\u001B(?:\][\s\S]*?(?:\u0007|\u001B\\)|[@-_][0-?]*[ -/]*[@-~])`,`gu`),Jf=/(https?:\/\/(?:localhost|[a-z0-9.-]+\.localhost|127(?:\.\d{1,3}){3}|\[[0:]+1\]|::1|10(?:\.\d{1,3}){3}|172\.(?:1[6-9]|2\d|3[01])(?:\.\d{1,3}){2}|192\.168(?:\.\d{1,3}){2}):)\s+(\d{1,5})(?=[/?#\s]|$)/giu;function Yf(e){let t=e.trim();if(!t||/^[a-z][a-z0-9+.-]*:\/\//i.test(t)&&!/^https?:\/\//i.test(t))return null;let n=t.split(/[/:?#]/,1)[0]??``,r=Gf.test(t)||Qf(n)?`http`:`https`,i=/^https?:\/\//i.test(t)?t:`${r}://${t}`;try{let e=new URL(i);return e.protocol!==`http:`&&e.protocol!==`https:`?null:e.toString()}catch{return null}}function Xf(e){try{let t=new URL(e);return t.protocol===`http:`||t.protocol===`https:`}catch{return!1}}function Zf(e){try{let t=new URL(e);return aa(t.hostname)}catch{return!1}}function Qf(e){return Wi(e)}function $f(e){try{let t=new URL(e);if(t.protocol!==`http:`||!Zf(t.toString())&&!Qf(t.hostname)||!t.port)return null;let n=Number(t.port);return Number.isInteger(n)&&n>0&&n<=65535?n:null}catch{return null}}function ep(e){let t=e.replace(/[.,;!?]+$/u,``);for(;t.endsWith(`)`)||t.endsWith(`]`)||t.endsWith(`}`);){let e=t.at(-1);if(!e)break;let n=e===`)`?`(`:e===`]`?`[`:`{`;if(t.split(n).length-1>=t.split(e).length-1)break;t=t.slice(0,-1)}return t}function tp(e){return e.replace(qf,``).replaceAll(/./gsu,e=>np(e)?``:e).replace(Jf,`$1$2`)}function np(e){let t=e.charCodeAt(0);return t>=0&&t<=8||t===11||t===12||t>=14&&t<=31||t===127}function rp(e){let t=null,n=null,r=tp(e);Kf.lastIndex=0;for(let e of r.matchAll(Kf)){let r=Yf(ep(e[0]));!r||!$f(r)||(t=r,Zf(r)&&(n=r))}return n??t}function ip(e){let t=null;for(let n of e){let e=n.event,r=rp(e.type===`output`?e.data:e.type===`started`||e.type===`restarted`?e.snapshot.history:``);r&&(t=r)}return t}function ap(e){switch(e.type){case`activity`:return e.hasRunningSubprocess;case`started`:case`restarted`:case`exited`:return!1;default:return null}}var op=`full-access`,sp=`default`,cp=`default`,lp=`forge:terminal-state:v1`,up=[],dp=200,fp=8;function pp(e,t){if(t<=3&&e&&typeof e==`object`){let t=e;return{terminalStateByThreadKey:Ap(t.terminalStateByThreadKey??{}),terminalPreviewUrlByThreadKey:Object.fromEntries(Object.entries(t.terminalPreviewUrlByThreadKey??{}).filter(([e,t])=>!!hn(e)&&typeof t?.url==`string`&&!!$f(t.url)&&typeof t?.observedAt==`string`))}}return{terminalStateByThreadKey:{},terminalPreviewUrlByThreadKey:{}}}function mp(){return _n(typeof window<`u`?window.localStorage:void 0)}function hp(e){let t=[...new Set(e.map(e=>e.trim()).filter(e=>e.length>0))];return t.length>0?t:[cp]}function gp(e,t){if(e.length===0)return[];let n=new Set(t);return[...new Set(e)].map(e=>e.trim()).filter(e=>e.length>0&&n.has(e))}function _p(e){return`group-${e}`}function vp(e,t){let n=e,r=2;for(;t.has(n);)n=`${e}-${r}`,r+=1;return t.add(n),n}function yp(e,t){return e.findIndex(e=>e.terminalIds.includes(t))}function bp(e){return[...new Set(e.map(e=>e.trim()).filter(e=>e.length>0))]}function xp(e,t){let n=new Set(t),r=new Set,i=[],a=new Set;for(let t of e){let e=bp(t.terminalIds).filter(e=>!(!n.has(e)||r.has(e)));if(e.length===0)continue;for(let t of e)r.add(t);let o=t.id.trim().length>0?t.id.trim():_p(e[0]??`default`);i.push({id:vp(o,a),terminalIds:e})}for(let e of t)r.has(e)||i.push({id:vp(_p(e),a),terminalIds:[e]});return i.length===0?[{id:_p(cp),terminalIds:[cp]}]:i}function Sp(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1)if(e[n]!==t[n])return!1;return!0}function Cp(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1){let r=e[n],i=t[n];if(!r||!i||r.id!==i.id||!Sp(r.terminalIds,i.terminalIds))return!1}return!0}function wp(e,t){return e.terminalOpen===t.terminalOpen&&e.terminalHeight===t.terminalHeight&&e.activeTerminalId===t.activeTerminalId&&e.activeTerminalGroupId===t.activeTerminalGroupId&&Sp(e.terminalIds,t.terminalIds)&&Sp(e.runningTerminalIds,t.runningTerminalIds)&&Cp(e.terminalGroups,t.terminalGroups)}var Tp=Object.freeze({terminalOpen:!1,terminalHeight:280,terminalIds:[cp],runningTerminalIds:[],activeTerminalId:cp,terminalGroups:[{id:_p(cp),terminalIds:[cp]}],activeTerminalGroupId:_p(cp)});function Ep(){return{...Tp,terminalIds:[...Tp.terminalIds],runningTerminalIds:[...Tp.runningTerminalIds],terminalGroups:Vp(Tp.terminalGroups)}}function Dp(){return Tp}function Op(e){let t=hp(e.terminalIds),n=t.length>0?t:[cp],r=gp(e.runningTerminalIds,n),i=n.includes(e.activeTerminalId)?e.activeTerminalId:n[0]??`default`,a=xp(e.terminalGroups,n),o=a.some(t=>t.id===e.activeTerminalGroupId)?e.activeTerminalGroupId:null,s=a.find(e=>e.terminalIds.includes(i))?.id??null,c={terminalOpen:e.terminalOpen,terminalHeight:Number.isFinite(e.terminalHeight)&&e.terminalHeight>0?e.terminalHeight:280,terminalIds:n,runningTerminalIds:r,activeTerminalId:i,terminalGroups:a,activeTerminalGroupId:o??s??a[0]?.id??_p(`default`)};return wp(e,c)?e:c}function kp(e){let t=Op(e);if(t.terminalIds.length<=fp)return t;let n=new Set,r=e=>{!e||n.size>=fp||t.terminalIds.includes(e)&&n.add(e)};r(cp),r(t.activeTerminalId);for(let e of t.runningTerminalIds)r(e);for(let e of t.terminalIds.toReversed())r(e);let i=t.terminalIds.filter(e=>n.has(e)),a=i[i.length-1]??i[0]??`default`,o=i.includes(t.activeTerminalId)?t.activeTerminalId:a;return Op({...t,terminalIds:i.length>0?i:[cp],runningTerminalIds:t.runningTerminalIds.filter(e=>n.has(e)),activeTerminalId:o,terminalGroups:t.terminalGroups.map(e=>({id:e.id,terminalIds:e.terminalIds.filter(e=>n.has(e))})).filter(e=>e.terminalIds.length>0)})}function Ap(e){return Object.fromEntries(Object.entries(e).flatMap(([e,t])=>hn(e)?[[e,kp(t)]]:[]))}function jp(e){return wp(Op(e),Tp)}function Mp(e){return e.trim().length>0}function Np(e){return Ln(e)}function Pp(e,t){return`${Np(e)}\u0000${t}`}function Fp(e,t){return Pp(e,t)}function Ip(e){let t=Date.parse(e);return Number.isFinite(t)?t:0}function Lp(e,t){let n=rp(e);return n?{url:n,observedAt:t}:null}function Rp(e){return Lp(e.history,e.updatedAt)}function zp(e){return e.type===`output`?Lp(e.data,e.createdAt):e.type===`started`||e.type===`restarted`?Lp(e.snapshot.history,e.snapshot.updatedAt):null}function Bp(e,t,n){if(!n)return e;let r=Np(t),i=e[r];return i&&Ip(i.observedAt)>Ip(n.observedAt)||i?.url===n.url&&i.observedAt===n.observedAt?e:{...e,[r]:n}}function Vp(e){return e.map(e=>({id:e.id,terminalIds:[...e.terminalIds]}))}function Hp(e,t,n,r){let i=Pp(n,r.terminalId),a=e[i]??up,o={id:t,event:r},s=a.length>=dp?[...a.slice(1),o]:[...a,o];return{terminalEventEntriesByKey:{...e,[i]:s},nextTerminalEventId:t+1}}function Up(e,t,n,r){let i=Pp(n,r.terminalId);return{terminalEventEntriesByKey:{...e,[i]:[{id:t,event:r}]},nextTerminalEventId:t+1}}function Wp(e){return e.sessionEpoch&&e.sequence!==void 0?{sessionEpoch:e.sessionEpoch,sequence:e.sequence}:null}function Gp(e,t,n){return!t||!e?!1:t.sessionEpoch===e.sessionEpoch?n?t.sequence<e.sequence:t.sequence<=e.sequence:!n}function Kp(e,t){let n={...e},r=!1;for(let e of Object.keys(n))e.startsWith(`${t}\u0000`)&&(delete n[e],r=!0);return r?n:e}function qp(e){return{terminalId:e.terminalId,cwd:e.snapshot.cwd,worktreePath:e.snapshot.worktreePath}}function Jp(e,t){let n=qp(t);return e?.runtimeEnv&&e.cwd===n.cwd&&e.worktreePath===n.worktreePath&&(e.terminalId===void 0||e.terminalId===t.terminalId)?{...n,runtimeEnv:e.runtimeEnv}:n}function Yp(e,t,n){let r=Op(e);if(!Mp(t))return r;let i=!r.terminalIds.includes(t),a=i?[...r.terminalIds,t]:r.terminalIds,o=Vp(r.terminalGroups),s=yp(o,t);if(s>=0&&(o[s].terminalIds=o[s].terminalIds.filter(e=>e!==t),o[s].terminalIds.length===0&&o.splice(s,1)),n===`new`){let e=new Set(o.map(e=>e.id)),n=vp(_p(t),e);return o.push({id:n,terminalIds:[t]}),Op({...r,terminalOpen:!0,terminalIds:a,activeTerminalId:t,terminalGroups:o,activeTerminalGroupId:n})}let c=o.findIndex(e=>e.id===r.activeTerminalGroupId);if(c<0&&(c=yp(o,r.activeTerminalId)),c<0){let e=new Set(o.map(e=>e.id)),t=vp(_p(r.activeTerminalId),e);o.push({id:t,terminalIds:[r.activeTerminalId]}),c=o.length-1}let l=o[c];if(!l||i&&!l.terminalIds.includes(t)&&l.terminalIds.length>=4)return r;if(!l.terminalIds.includes(t)){let e=l.terminalIds.indexOf(r.activeTerminalId);e>=0?l.terminalIds.splice(e+1,0,t):l.terminalIds.push(t)}return Op({...r,terminalOpen:!0,terminalIds:a,activeTerminalId:t,terminalGroups:o,activeTerminalGroupId:l.id})}function Xp(e,t){let n=Op(e);return n.terminalOpen===t?n:{...n,terminalOpen:t}}function Zp(e,t){let n=Op(e);return!Number.isFinite(t)||t<=0||n.terminalHeight===t?n:{...n,terminalHeight:t}}function Qp(e,t){return Yp(e,t,`split`)}function $p(e,t,n){let r=Yp(e,t,`new`);return n?.openDrawer===!1?{...r,terminalOpen:e.terminalOpen}:r}function em(e,t){let n=Op(e);if(!n.terminalIds.includes(t))return n;let r=n.terminalGroups.find(e=>e.terminalIds.includes(t))?.id??n.activeTerminalGroupId;return n.activeTerminalId===t&&n.activeTerminalGroupId===r?n:{...n,activeTerminalId:t,activeTerminalGroupId:r}}function tm(e,t){let n=Op(e);if(!n.terminalIds.includes(t))return n;let r=n.terminalIds.filter(e=>e!==t);if(r.length===0)return Ep();let i=n.terminalIds.indexOf(t),a=n.activeTerminalId===t?r[Math.min(i,r.length-1)]??r[0]??`default`:n.activeTerminalId,o=n.terminalGroups.map(e=>({...e,terminalIds:e.terminalIds.filter(e=>e!==t)})).filter(e=>e.terminalIds.length>0),s=o.find(e=>e.terminalIds.includes(a))?.id??o[0]?.id??_p(a);return Op({terminalOpen:n.terminalOpen,terminalHeight:n.terminalHeight,terminalIds:r,runningTerminalIds:n.runningTerminalIds.filter(e=>e!==t),activeTerminalId:a,terminalGroups:o,activeTerminalGroupId:s})}function nm(e,t,n){let r=Op(e);if(!r.terminalIds.includes(t)||n===r.runningTerminalIds.includes(t))return r;let i=new Set(r.runningTerminalIds);return n?i.add(t):i.delete(t),{...r,runningTerminalIds:[...i]}}function rm(e,t){return!t||t.threadId.length===0?Dp():e[Np(t)]??Dp()}function im(e,t,n){if(t.threadId.length===0)return e;let r=Np(t),i=rm(e,t),a=n(i);if(a===i)return e;if(jp(a)){if(e[r]===void 0)return e;let{[r]:t,...n}=e;return n}return{...e,[r]:a}}function am(e,t,n){return!t||t.threadId.length===0||n.trim().length===0?up:e[Pp(t,n)]??up}function om(e,t,n){return!t||t.threadId.length===0||n.trim().length===0?null:e[Fp(t,n)]??null}function sm(e,t){if(!t||t.threadId.length===0)return[];let n=`${Np(t)}\u0000`;return Object.entries(e).filter(([e])=>e.startsWith(n)).map(([,e])=>e)}function cm(e,t){return!t||t.threadId.length===0?null:e[Np(t)]??null}var lm=wa()(Wf(e=>{let t=(t,n)=>{e(e=>{let r=im(e.terminalStateByThreadKey,t,n);return r===e.terminalStateByThreadKey?e:{terminalStateByThreadKey:r}})};return{terminalStateByThreadKey:{},terminalLaunchContextByThreadKey:{},terminalEventEntriesByKey:{},terminalSessionSnapshotByKey:{},terminalStreamCursorByKey:{},terminalPreviewUrlByThreadKey:{},nextTerminalEventId:1,setTerminalOpen:(e,n)=>t(e,e=>Xp(e,n)),setTerminalHeight:(e,n)=>t(e,e=>Zp(e,n)),splitTerminal:(e,n)=>t(e,e=>Qp(e,n)),newTerminal:(e,n,r)=>t(e,e=>$p(e,n,r)),ensureTerminal:(e,n,r)=>t(e,e=>{let t=e;return e.terminalIds.includes(n)||(t=$p(t,n)),r?.active===!1&&(t={...t,activeTerminalId:e.activeTerminalId,activeTerminalGroupId:e.activeTerminalGroupId}),(r?.active??!0)&&(t=em(t,n)),r?.open&&(t=Xp(t,!0)),Op(t)}),setActiveTerminal:(e,n)=>t(e,e=>em(e,n)),closeTerminal:(e,n)=>t(e,e=>tm(e,n)),setTerminalLaunchContext:(t,n)=>e(e=>({terminalLaunchContextByThreadKey:{...e.terminalLaunchContextByThreadKey,[Np(t)]:n}})),clearTerminalLaunchContext:t=>e(e=>{let n=Np(t);if(!e.terminalLaunchContextByThreadKey[n])return e;let{[n]:r,...i}=e.terminalLaunchContextByThreadKey;return{terminalLaunchContextByThreadKey:i}}),setTerminalActivity:(e,n,r)=>t(e,e=>nm(e,n,r)),recordTerminalEvent:(t,n)=>e(e=>{let r=Fp(t,n.terminalId),i=Wp(n),a=n.type===`started`||n.type===`restarted`;if(Gp(e.terminalStreamCursorByKey[r],i,a))return e;let o=a&&i?Up(e.terminalEventEntriesByKey,e.nextTerminalEventId,t,n):Hp(e.terminalEventEntriesByKey,e.nextTerminalEventId,t,n),s=i?{...e.terminalStreamCursorByKey,[r]:i}:e.terminalStreamCursorByKey,c=Bp(e.terminalPreviewUrlByThreadKey,t,zp(n));return n.type!==`started`&&n.type!==`restarted`?{...o,terminalStreamCursorByKey:s,terminalPreviewUrlByThreadKey:c}:{...o,terminalStreamCursorByKey:s,terminalPreviewUrlByThreadKey:c,terminalSessionSnapshotByKey:{...e.terminalSessionSnapshotByKey,[Fp(t,n.terminalId)]:n.snapshot}}}),applyTerminalEvent:(t,n)=>e(e=>{let r=Np(t),i=Fp(t,n.terminalId),a=Wp(n),o=n.type===`started`||n.type===`restarted`;if(Gp(e.terminalStreamCursorByKey[i],a,o))return e;let s=e.terminalStateByThreadKey,c=e.terminalLaunchContextByThreadKey,l=e.terminalSessionSnapshotByKey,u=Bp(e.terminalPreviewUrlByThreadKey,t,zp(n));(n.type===`started`||n.type===`restarted`)&&(l={...l,[Fp(t,n.terminalId)]:n.snapshot},s=im(s,t,e=>{let t=e.activeTerminalId===n.terminalId,r=e;return e.terminalIds.includes(n.terminalId)||(r=$p(r,n.terminalId)),t?(r=em(r,n.terminalId),r=Xp(r,!0)):(r=em(r,e.activeTerminalId),r=Xp(r,e.terminalOpen)),Op(r)}),c={...c,[r]:Jp(c[r],n)});let d=ap(n);d!==null&&(s=im(s,t,e=>nm(e,n.terminalId,d)));let f=o&&a?Up(e.terminalEventEntriesByKey,e.nextTerminalEventId,t,n):Hp(e.terminalEventEntriesByKey,e.nextTerminalEventId,t,n),p=a?{...e.terminalStreamCursorByKey,[i]:a}:e.terminalStreamCursorByKey;return{terminalStateByThreadKey:s,terminalLaunchContextByThreadKey:c,terminalSessionSnapshotByKey:l,terminalStreamCursorByKey:p,terminalPreviewUrlByThreadKey:u,...f}}),setTerminalSessionSnapshot:(t,n)=>e(e=>({terminalSessionSnapshotByKey:{...e.terminalSessionSnapshotByKey,[Fp(t,n.terminalId)]:n},terminalPreviewUrlByThreadKey:Bp(e.terminalPreviewUrlByThreadKey,t,Rp(n))})),clearTerminalState:t=>e(e=>{let n=Np(t),r=im(e.terminalStateByThreadKey,t,()=>Ep()),i=e.terminalLaunchContextByThreadKey[n]!==void 0,a=e.terminalPreviewUrlByThreadKey[n]!==void 0,{[n]:o,...s}=e.terminalLaunchContextByThreadKey,{[n]:c,...l}=e.terminalPreviewUrlByThreadKey,u={...e.terminalEventEntriesByKey},d=!1;for(let e of Object.keys(u))e.startsWith(`${n}\u0000`)&&(delete u[e],d=!0);let f={...e.terminalSessionSnapshotByKey},p=!1;for(let e of Object.keys(f))e.startsWith(`${n}\u0000`)&&(delete f[e],p=!0);let m=Kp(e.terminalStreamCursorByKey,n);return r===e.terminalStateByThreadKey&&!i&&!a&&!d&&!p&&m===e.terminalStreamCursorByKey?e:{terminalStateByThreadKey:r,terminalLaunchContextByThreadKey:s,terminalPreviewUrlByThreadKey:l,terminalEventEntriesByKey:u,terminalSessionSnapshotByKey:f,terminalStreamCursorByKey:m}}),removeTerminalState:t=>e(e=>{let n=Np(t),r=e.terminalStateByThreadKey[n]!==void 0,i=e.terminalLaunchContextByThreadKey[n]!==void 0,a=e.terminalPreviewUrlByThreadKey[n]!==void 0,o={...e.terminalEventEntriesByKey},s=!1;for(let e of Object.keys(o))e.startsWith(`${n}\u0000`)&&(delete o[e],s=!0);let c={...e.terminalSessionSnapshotByKey},l=!1;for(let e of Object.keys(c))e.startsWith(`${n}\u0000`)&&(delete c[e],l=!0);let u=Kp(e.terminalStreamCursorByKey,n);if(!r&&!i&&!a&&!s&&!l&&u===e.terminalStreamCursorByKey)return e;let d={...e.terminalStateByThreadKey};delete d[n];let f={...e.terminalLaunchContextByThreadKey};delete f[n];let p={...e.terminalPreviewUrlByThreadKey};return delete p[n],{terminalStateByThreadKey:d,terminalLaunchContextByThreadKey:f,terminalPreviewUrlByThreadKey:p,terminalEventEntriesByKey:o,terminalSessionSnapshotByKey:c,terminalStreamCursorByKey:u}}),removeOrphanedTerminalStates:t=>e(e=>{let n=Object.keys(e.terminalStateByThreadKey).filter(e=>!t.has(e)),r=Object.keys(e.terminalLaunchContextByThreadKey).filter(e=>!t.has(e)),i=Object.keys(e.terminalPreviewUrlByThreadKey).filter(e=>!t.has(e)),a={...e.terminalEventEntriesByKey},o=!1;for(let e of Object.keys(a)){let[n]=e.split(`\0`);n&&!t.has(n)&&(delete a[e],o=!0)}let s={...e.terminalSessionSnapshotByKey},c=!1;for(let e of Object.keys(s)){let[n]=e.split(`\0`);n&&!t.has(n)&&(delete s[e],c=!0)}let l={...e.terminalStreamCursorByKey},u=!1;for(let e of Object.keys(l)){let[n]=e.split(`\0`);n&&!t.has(n)&&(delete l[e],u=!0)}if(n.length===0&&r.length===0&&i.length===0&&!o&&!c&&!u)return e;let d={...e.terminalStateByThreadKey};for(let e of n)delete d[e];let f={...e.terminalLaunchContextByThreadKey};for(let e of r)delete f[e];let p={...e.terminalPreviewUrlByThreadKey};for(let e of i)delete p[e];return{terminalStateByThreadKey:d,terminalLaunchContextByThreadKey:f,terminalPreviewUrlByThreadKey:p,terminalEventEntriesByKey:a,terminalSessionSnapshotByKey:s,terminalStreamCursorByKey:l}})}},{name:lp,version:4,storage:Hf(mp),migrate:pp,partialize:e=>({terminalStateByThreadKey:Ap(e.terminalStateByThreadKey),terminalPreviewUrlByThreadKey:e.terminalPreviewUrlByThreadKey})}));function um(e){return!!(e.prompt.trim()||e.images.length||e.terminalContexts.length||e.persistedAttachments.length||e.stagedSubmission)}function dm(e,t,n){let r=Ln(t),i=Ln(n);if(r===i)return e;let a=e[r];if(!a)return e;let o=e[i];if(o&&um(o)&&!fm(a,o))return null;let s={...e,[i]:{...a,...wm(a,o)}};return delete s[r],s}function fm(e,t){let n=e.stagedSubmission;return!n||!pm(n)||!mm(e,n)||!hm(n,t.stagedSubmission)?!1:gm(e,t)}function pm(e){return!!e.commandId&&!!e.messageId}function mm(e,t){return[e.prompt===t.prompt,bm(e.persistedAttachments,t.attachments),bm(e.terminalContexts,t.terminalContexts)].every(Boolean)}function hm(e,t){return!t||_m(e,t)}function gm(e,t){return[e.prompt===t.prompt,e.lastGeneratedPullRequestPrompt===t.lastGeneratedPullRequestPrompt,Sm(e.images,t.images),xm(e.nonPersistedImageIds,t.nonPersistedImageIds),e.nonPersistedImageIds.length===0,Sm(e.persistedAttachments,t.persistedAttachments),Sm(e.terminalContexts,t.terminalContexts),Cm(e.modelSelectionByProvider,t.modelSelectionByProvider),e.activeProvider===t.activeProvider,e.runtimeMode===t.runtimeMode,e.interactionMode===t.interactionMode].every(Boolean)}function _m(e,t){return[e.commandId===t.commandId&&e.messageId===t.messageId,e.prompt===t.prompt,bm(e.attachments,t.attachments),bm(e.terminalContexts,t.terminalContexts),vm(e.modelSelection,t.modelSelection),vm(e.runtimeMode,t.runtimeMode),vm(e.interactionMode,t.interactionMode),ym(e.executionIntent,t.executionIntent)].every(Boolean)}function vm(e,t){return e===void 0||t===void 0||JSON.stringify(e)===JSON.stringify(t)}function ym(e,t){return!e||!t||e.runtimeId===t.runtimeId}function bm(e,t){return e.length===t.length&&e.every((e,n)=>e.id===t[n]?.id)}function xm(e,t){return e.length===t.length&&e.every((e,n)=>e===t[n])}function Sm(e,t){return e.length===t.length&&e.every((e,n)=>JSON.stringify(e)===JSON.stringify(t[n]))}function Cm(e,t){let n=Object.keys(e).toSorted();return xm(n,Object.keys(t).toSorted())?n.every(n=>JSON.stringify(e[n])===JSON.stringify(t[n])):!1}function wm(e,t){let n=t??e,r=e.stagedSubmission?e:n,i=e.stagedSubmission?n:e;return{modelSelectionByProvider:{...i.modelSelectionByProvider,...r.modelSelectionByProvider},activeProvider:r.activeProvider??i.activeProvider,runtimeMode:r.runtimeMode??i.runtimeMode,interactionMode:r.interactionMode??i.interactionMode}}var Tm=/\n*<terminal_context>\n([\s\S]*?)\n<\/terminal_context>\s*$/,Em=/^\s*<cmmd_context>\n?([\s\S]*?)\n?<\/cmmd_context>\s*/;function Dm(e){return e.replace(/\r\n/g,`
|
|
8
|
-
`).replace(/^\n+|\n+$/g,``)}function
|
|
9
|
-
`).map((t,n)=>` ${e.lineStart+n} | ${t}`)}function
|
|
10
|
-
`)}function
|
|
7
|
+
`)}}}var Ul=(e=`/api/workspace/readiness`)=>{if(typeof fetch>`u`)return{close:()=>{}};let t=typeof e==`string`?{url:e}:e,n=!1,r=new AbortController;return fetch(t.url,{credentials:t.bearerToken?`omit`:`include`,signal:r.signal,...t.bearerToken?{headers:{Authorization:`Bearer ${t.bearerToken}`}}:{}}).then(e=>{if(e.ok)return Hl(e,t.environmentId,r.signal)}).catch(()=>{}),{close:()=>{n||(n=!0,r.abort())}}},Wl=6e4;function Gl(e){let t=new URL(e.target.httpBaseUrl);return t.pathname=`${t.pathname.endsWith(`/`)?t.pathname.slice(0,-1):t.pathname}/api/workspace/readiness`,t.search=``,t.hash=``,t.toString()}function Kl(e){let t=new Set,n=null,r=!1,i=!1;return{hasWaiters:()=>t.size>0,wait:()=>{if(r)return Promise.reject(n);if(i)return Promise.resolve();let a=null,o=null,s=new Promise((e,n)=>{o={resolve:e,reject:n},t.add(o)}),c=new Promise((t,n)=>{a=globalThis.setTimeout(()=>{n(Error(`Timed out while waiting for ${e.label} (${e.environmentId}) to stream its shell snapshot.`))},e.timeoutMs)});return Promise.race([s,c]).finally(()=>{a!==null&&globalThis.clearTimeout(a),o!==null&&t.delete(o)})},resolve:()=>{r=!1,n=null,i=!0;let e=[...t];t.clear();for(let t of e)t.resolve()},reject:e=>{r=!0,n=e,i=!1;let a=[...t];t.clear();for(let t of a)t.reject(e)},reset:()=>{r=!1,n=null,i=!1}}}function ql(e){let t=e.knownEnvironment.environmentId;if(!t)throw Error(`Known environment ${e.knownEnvironment.label} is missing its environmentId.`);let n=!1,r=!1,i=null,a=null,o=Kl({environmentId:t,label:e.knownEnvironment.label,timeoutMs:e.bootstrapTimeoutMs??Wl}),s=e.readiness?(e.readiness.openStream??Ul)({url:Gl(e.knownEnvironment),environmentId:t,...e.readiness.bearerToken?{bearerToken:e.readiness.bearerToken}:{}}):null,c=t=>{if(!r){r=!0;let n=Error(t);_(),e.client.dispose(),e.onIdentityMismatch?.(n)}return!1},l=(n,r)=>{if(e.tolerateReportedEnvironmentIdentity)return a===null?(a=n,!0):a===n||c(`Environment connection ${t} reported a changed runtime identity (${a} -> ${n}) via ${r}.`);let i=e.resolveEnvironmentId?.()??t;return i===n||c(`Environment connection ${i} changed identity to ${n} via ${r}.`)},u=()=>e.resolveEnvironmentId?.()??t,d=e.client.server.subscribeLifecycle(t=>{t.type===`welcome`&&l(t.payload.environment.environmentId,`server lifecycle welcome`)&&e.onWelcome?.(t.payload,u())}),f=e.client.server.subscribeConfig(t=>{if(t.type===`snapshot`){if(!l(t.config.environment.environmentId,`server config snapshot`))return;i=t.config,e.onConfigSnapshot?.(t.config);return}if(t.type!==`providerStatuses`||!i)return;let n={...i,providers:t.payload.providers};i=n,e.onConfigSnapshot?.(n)}),p=e.client.orchestration.subscribeShell(t=>{if(t.kind===`snapshot`){e.syncShellSnapshot(t.snapshot,u()),o.resolve();return}e.applyShellEvent(t,u())},{onResubscribe:()=>{n||o.reset()},onError:t=>{if(!n){if(o.hasWaiters()){o.reject(t);return}e.onShellSubscriptionError?.(t,u())}}}),m=e.client.terminal.onEvent(t=>{e.applyTerminalEvent(t,u())}),h=e.client.browser?.onEvent({},t=>{e.applyBrowserEvent(t,u())}),g=e.client.server.subscribeWorkspaceReadiness(e=>{n||D(async()=>{let{setWorkspaceReadinessPhaseForEnvironment:e}=await import(`./workspaceReadinessAtom-D6bgTvKb.js`).then(e=>e.r);return{setWorkspaceReadinessPhaseForEnvironment:e}},__vite__mapDeps([0,1,2,3])).then(({setWorkspaceReadinessPhaseForEnvironment:t})=>{n||t(u(),e)})}),_=()=>{n||(n=!0,e.onDispose?.(),s?.close(),p(),m(),h?.(),d(),f(),g())};return{kind:e.kind,environmentId:t,knownEnvironment:e.knownEnvironment,client:e.client,ensureBootstrapped:()=>o.wait(),reconnect:async()=>{o.reset();try{await e.client.reconnect(),await e.refreshMetadata?.(),await o.wait()}catch(e){throw o.reject(e),e}},...e.ensureProviderAuthority?{ensureProviderAuthority:e.ensureProviderAuthority}:{},dispose:async()=>{_(),await e.client.dispose()}}}var Jl=it(`effect/http/FetchHttpClient/Fetch`,{defaultValue:()=>globalThis.fetch}),Yl=class extends Tt()(`effect/http/FetchHttpClient/RequestInit`){},Xl=bc(ct(hc((e,t,n,r)=>{let i=r.getRef(Jl),a=r.context.mapUnsafe.get(Yl.key)??{},o=a.headers?Mr(Xr(a.headers),e.headers):e.headers,s=r=>nt(ot({try:()=>i(t,{...a,method:e.method,headers:o,body:r,duplex:e.body._tag===`Stream`?`half`:void 0,signal:n}),catch:t=>new Ti({reason:new ci({request:e,cause:t})})}),t=>Vi(e,t));switch(e.body._tag){case`Raw`:case`Uint8Array`:return s(e.body.body);case`FormData`:return s(e.body.formData);case`Stream`:return Mt($t(e.body.stream),s)}return s(void 0)}))),Zl=Jt.pipe(h,Qt(e=>{if(Di(e)&&e.reason._tag===`StatusCodeError`&&e.reason.response.status===429){let t=Ee(e.reason.response.headers[`retry-after`]).pipe(en(Ws),f(()=>5));return ct(ne(t))}return ct(ne(1))})),Ql=$e(function*(e){let t=yield*Lt(),n=ut(t,Hs),r=ut(t,Ce),a=ze(t),o=u(we(e.exportInterval),Ue),s,c=fc(ut(t,uc)).pipe(dc(xe(vc,!1)),gc({schedule:Zl,times:3})),d=ti({"user-agent":`effect-opentelemetry-${e.label}/0.0.0`});e.headers&&(d=Mr(Xr(e.headers),d));let f=Zs(e.url,{headers:d}),p=[],m=Bt(()=>{if(s!==void 0&&n.currentTimeMillisUnsafe()<s)return ft;s!==void 0&&(s=void 0);let t=p;if(e.maxBatchSize!==`disabled`){if(p.length===0)return ft;p=[]}return c.execute(sc(f,e.body(t))).pipe(Fe,et(!1))}).pipe(Be(e=>s===void 0?(s=n.currentTimeMillisUnsafe()+6e4,p=[],Ze(`Disabling exporter for 60 seconds`,e)):ft),l({package:`@effect/opentelemetry`,module:e.label}));return yield*rn(r,m.pipe(It,ht,Et(e.shutdownTimeout))),yield*i(o).pipe(nn(m),at,Gt(r)),{push(t){s===void 0&&(p.push(t),e.maxBatchSize!==`disabled`&&p.length>=e.maxBatchSize&&le(a(m),r))}}}),$l=e=>{let t=e.attributes?nu(Object.entries(e.attributes)):[];return t.push({key:`service.name`,value:{stringValue:e.serviceName}}),e.serviceVersion&&t.push({key:`service.version`,value:{stringValue:e.serviceVersion}}),{attributes:t,droppedAttributesCount:0}},eu=$e(function*(e){let t={...yield*tl(Ri(nl(E,E)),`OTEL_RESOURCE_ATTRIBUTES`),...e?.attributes},n=e?.serviceName??t[`service.name`]??(yield*tl(E,`OTEL_SERVICE_NAME`));delete t[`service.name`];let r=e?.serviceVersion??t[`service.version`]??(yield*tl(Ri(E),`OTEL_SERVICE_VERSION`));return delete t[`service.version`],$l({serviceName:n,serviceVersion:r,attributes:t})},c),tu=e=>{let t=e.attributes.find(e=>e.key===`service.name`);if(!t||!t.value.stringValue)throw Error(`Resource does not contain a service name`);return t.value.stringValue},nu=e=>{let t=[];for(let[n,r]of e)t.push({key:n,value:ru(r)});return t},ru=e=>{if(Array.isArray(e))return{arrayValue:{values:e.map(ru)}};switch(typeof e){case`string`:return{stringValue:e};case`bigint`:return{intValue:Number(e)};case`number`:return Number.isInteger(e)?{intValue:e}:{doubleValue:e};case`boolean`:return{boolValue:e};default:return{stringValue:At(e)}}},iu=class extends Tt()(`effect/observability/OtlpSerialization`){},au=de(iu,{traces:e=>ai(e),metrics:e=>ai(e),logs:e=>ai(e)}),ou=$e(function*(e){let t=yield*eu(e.resource),n=yield*iu,r={name:tu(t)},i=yield*Ql({label:`OtlpTracer`,url:e.url,headers:e.headers,exportInterval:e.exportInterval??ne(5),maxBatchSize:e.maxBatchSize??1e3,body(e){let i={resourceSpans:[{resource:t,scopeSpans:[{scope:r,spans:e}]}]};return n.traces(i)},shutdownTimeout:e.shutdownTimeout??ne(3)});function a(e){e.sampled&&i.push(uu(e))}return he({span(e){return cu({...e,status:{_tag:`Started`,startTime:e.startTime},attributes:new Map,export:a})},context:e.context?function(t,n){return n.currentSpan===void 0?t[`~effect/Effect/evaluate`](n):e.context(t,n.currentSpan)}:void 0})}),su={_tag:`Span`,end(e,t){this.status={_tag:`Ended`,startTime:this.status.startTime,endTime:e,exit:t},this.export(this)},attribute(e,t){this.attributes.set(e,t)},event(e,t,n){this.events.push([e,t,n])},addLinks(e){this.links.push(...e)}},cu=e=>{let t=Object.assign(Object.create(su),e);return t.traceId=St(t.parent)?t.parent.value.traceId:lu(32),t.spanId=lu(16),t.events=[],t},lu=e=>{let t=``;for(let n=0;n<e;n++)t+=`0123456789abcdef`[Math.floor(Math.random()*16)];return t},uu=e=>{let t=e.status,n=nu(e.attributes.entries()),r=e.events.map(([e,t,n])=>({name:e,timeUnixNano:String(t),attributes:n?nu(Object.entries(n)):[],droppedAttributesCount:0})),i;if(t.exit._tag===`Success`)i=pu;else if(mt(t.exit.cause))i={code:du.Ok,message:`Interrupted`},n.push({key:`span.label`,value:{stringValue:`⚠︎ Interrupted`}},{key:`status.interrupted`,value:{boolValue:!0}});else{let e=Yt(t.exit.cause);if(i={code:du.Error},e.length>0){i.message=e[0].message;for(let n of e)r.push({name:`exception`,timeUnixNano:String(t.endTime),droppedAttributesCount:0,attributes:[{key:`exception.type`,value:{stringValue:n.name}},{key:`exception.message`,value:{stringValue:n.message}},{key:`exception.stacktrace`,value:{stringValue:n.stack??`No stack trace available`}}]})}}return{traceId:e.traceId,spanId:e.spanId,parentSpanId:ge(e.parent,{onNone:()=>void 0,onSome:e=>e.spanId}),name:e.name,kind:fu[e.kind],startTimeUnixNano:String(t.startTime),endTimeUnixNano:String(t.endTime),attributes:n,droppedAttributesCount:0,events:r,droppedEventsCount:0,status:i,links:e.links.map(e=>({traceId:e.span.traceId,spanId:e.span.spanId,attributes:nu(Object.entries(e.attributes)),droppedAttributesCount:0})),droppedLinksCount:0}},du={Unset:0,Ok:1,Error:2},fu={unspecified:0,internal:1,server:2,client:3,producer:4,consumer:5},pu={code:du.Ok},mu=1e4,hu={serviceName:`forge-web`,attributes:{"service.runtime":`forge-web`,"service.mode":bn?`electron`:`browser`,"service.version":Cn}},gu=be(Xl,au,de(_c,()=>!0)),_u=null,vu=null,yu=null,bu=null,xu=0,Su=Promise.resolve(),Cu=de(bt,he({span(e){return _u?.span(e)??new s(e)}}));function wu(e={}){return e.exportIntervalMs===void 0&&bu!==null||(Su=Su.finally(()=>Tu(e))),Su}async function Tu(e){let t=Ji(`/api/observability/v1/traces`),n=ra()?.bearerToken,r=Math.max(10,e.exportIntervalMs??mu),i=`${t}|${r}|${n?`bearer`:`cookie`}`;if(bu===i&&_u!==null)return;bu=i;let a=++xu,o=vu,s=yu;_u=null,vu=null,yu=null,await Eu(o,s);let c=Oc(gu),l=c.runSync(Me());try{let e=await c.runPromise(b(l)(ou({url:t,...n?{headers:{Authorization:`Bearer ${n}`}}:{},exportInterval:`${r} millis`,resource:hu})));if(a!==xu){await Eu(c,l);return}_u=e,vu=c,yu=l}catch(e){await Eu(c,l),a===xu&&console.warn(`Failed to configure client tracing exporter`,{error:Du(e),otlpTracesUrl:t})}}async function Eu(e,t){e!==null&&t!==null&&await e.runPromise(Le(t,Pt)).catch(()=>void 0).finally(()=>{e.dispose()})}function Du(e){return e instanceof Error&&e.message.trim().length>0?e.message:String(e)}var Ou=15e3,ku=new Map,Au=un([]).pipe(ln,sn(`slow-rpc-ack-requests`));function ju(e){cn.set(Au,[...e])}function Mu(){return cn.get(Au)}var Nu=`global`,Pu=new Set([`server.heartbeat`]);function Fu(e){return!(e.split(`.`).at(-1)??e).startsWith(`subscribe`)&&!Pu.has(e)}function Iu(e,t,n=Nu){if(!Fu(t))return;Vu(e,n),Uu();let r=Date.now(),i={clientId:n,requestId:e,startedAt:new Date(r).toISOString(),startedAtMs:r,tag:t,thresholdMs:Ou},a=Bu(n,e),o=setTimeout(()=>{ku.delete(a),Hu(i)},Ou);ku.set(a,{request:i,timeoutId:o})}function Lu(e,t=Nu){Vu(e,t);let n=Mu();n.some(n=>n.clientId===t&&n.requestId===e)&&ju(n.filter(n=>n.clientId!==t||n.requestId!==e))}function Ru(e){for(let[t,n]of ku)n.request.clientId===e&&(clearTimeout(n.timeoutId),ku.delete(t));ju(Mu().filter(t=>t.clientId!==e))}function zu(){for(let e of ku.values())clearTimeout(e.timeoutId);ku.clear(),ju([])}function Bu(e,t){return`${e}:${t}`}function Vu(e,t){let n=Bu(t,e),r=ku.get(n);r&&(clearTimeout(r.timeoutId),ku.delete(n))}function Hu(e){let t=[...Mu(),e];if(t.length<=256){ju(t);return}ju(t.slice(-256))}function Uu(){for(;ku.size>=256;){let e=ku.keys().next().value;if(e===void 0)return;let t=ku.get(e);if(!t)return;Vu(t.request.requestId,t.request.clientId)}}function Wu(){return ma(Au)}var Gu=ia(ui),Ku=1;function qu(e){return e instanceof Error&&e.message.trim().length>0?e.message:String(e)}function Ju(e){let t=new URL(e);if(t.protocol!==`ws:`&&t.protocol!==`wss:`)throw Error(`Unsupported websocket transport URL protocol: ${t.protocol}`);return t.pathname=`/ws`,t.toString()}function Yu(){return{onAttempt:ya,onOpen:Ki,onError:e=>{qi(e)},onClose:e=>{oa(e)},trackGlobalConnection:!0}}function Xu(e){let t=Yu(),n=e?.trackGlobalConnection??!0;return{onAttempt:r=>{n&&t.onAttempt(r),e?.onAttempt?.(r)},onOpen:()=>{n&&t.onOpen(),e?.onOpen?.()},onError:r=>{n&&t.onError(r),e?.onError?.(r)},onClose:r=>{n&&t.onClose(r),e?.onClose?.(r)},trackGlobalConnection:n}}function Zu(e,t){let n=Ku;Ku+=1;let r=Xu(t),i=typeof e==`function`?xt(()=>e()).pipe(nt(e=>Ju(e)),Ut(e=>gt(()=>{r.onError(qu(e))})),c):Ju(e),a=de(va,(e,t)=>{r.onAttempt(e);let n=new globalThis.WebSocket(e,t);return n.addEventListener(`open`,()=>{r.onOpen()},{once:!0}),n.addEventListener(`error`,()=>{r.onError(`Unable to connect to the Forge server WebSocket.`)},{once:!0}),n.addEventListener(`close`,e=>{r.onClose({code:e.code,reason:e.reason})},{once:!0}),n}),o=ha(i).pipe(y(a)),s=Qt(p(fa),e=>ct(Re(Gi(e)??0)));return yt(da,nt(Hi({retryPolicy:s,retryTransientErrors:!0}),e=>({...e,run:(t,r)=>{let i=`${n}:${String(t)}`;return e.run(t,e=>(e._tag===`Chunk`||e._tag===`Exit`?Lu(e.requestId,i):(e._tag===`ClientProtocolError`||e._tag===`Defect`)&&Ru(i),r(e))).pipe(Je(gt(()=>{Ru(i)})))},send:(t,r,i)=>{let a=`${n}:${String(t)}`;return r._tag===`Request`&&Iu(r.id,r.tag,a),e.send(t,r,i)}}))).pipe(y(be(o,pa)))}var Qu=/^all fibers interrupted without error$/i;function $u(e){return On(e)||Qu.test(e.trim())}var ed=Re(250),td=()=>void 0,nd=class extends Error{name=`WsRequestTimeoutError`;timeoutMs;constructor(e){let t=Ne(we(e));super(`WebSocket RPC request timed out after ${t}ms.`),this.timeoutMs=t}},rd=new Set([`OrchestrationGetSnapshotError`]);function id(e){if(typeof e!=`object`||!e)return!1;let t=e._tag;return typeof t==`string`&&rd.has(t)}function ad(e){let t=e instanceof Error?e.message.trim():``;return t.length>0?t:typeof e==`object`&&e?od(e):String(e)}function od(e){try{return JSON.stringify(e)}catch{let t=e;return[typeof t._tag==`string`?t._tag:void 0,typeof t.message==`string`?t.message:void 0].filter(Boolean).join(`: `)||Object.prototype.toString.call(e)}}var sd=4e3,cd=1e4,ld=500,ud=class{url;lifecycleHandlers;disposed=!1;hasReportedTransportDisconnect=!1;reconnectChain=Promise.resolve();session;heartbeatTimer=null;heartbeatInFlight=!1;protocol;timing;constructor(e,t,n,r){this.url=e,this.lifecycleHandlers=t,this.protocol=n??null,this.timing={heartbeatIntervalMs:r?.heartbeatIntervalMs??sd,heartbeatTimeoutMs:r?.heartbeatTimeoutMs??cd,sessionCloseGraceMs:r?.sessionCloseGraceMs??ld},this.session=this.createSession(),this.startHeartbeat()}startHeartbeat(){this.heartbeatTimer===null&&(this.heartbeatTimer=setInterval(()=>{if(this.disposed||this.heartbeatInFlight)return;this.heartbeatInFlight=!0;let e=this.session;this.request(e=>e[T.serverHeartbeat]({}),{timeout:this.timing.heartbeatTimeoutMs}).catch(async()=>{this.disposed||e!==this.session||await this.reconnect()}).finally(()=>{this.heartbeatInFlight=!1})},this.timing.heartbeatIntervalMs))}async request(e,t){if(this.disposed)throw Error(`Transport disposed`);let n=this.session,i=await n.clientPromise,a=Bt(()=>e(i)),o=t?.timeout,s=o===void 0?a:a.pipe(Wt({duration:o,orElse:()=>r(new nd(o))}));return await n.runtime.runPromise(s,{signal:t?.signal})}async requestStream(e,t,n){if(this.disposed)throw Error(`Transport disposed`);let r=this.session,i=this.runStreamOnSession(r,e,t,()=>!0,()=>void 0),a=()=>i.cancel();n?.signal?.aborted&&a(),n?.signal?.addEventListener(`abort`,a,{once:!0});try{await i.completed}catch(e){if(n?.signal?.aborted){let e=Error(`RPC stream request was cancelled.`);throw e.name=`AbortError`,e}throw e}finally{n?.signal?.removeEventListener(`abort`,a)}}subscribe(e,t,n){if(this.disposed)return()=>void 0;let r={active:!0,hasReceivedValue:!1,cancelCurrentStream:td},i=Ne(we(n?.retryDelay??ed));return this.runSubscriptionLoop(e,t,n,r,i),()=>{r.active=!1,r.cancelCurrentStream()}}async runSubscriptionLoop(e,t,n,r,i){for(;r.active&&!this.disposed;){let a=this.session;try{this.notifyResubscribe(r,n);let i=this.startSubscriptionStream(a,e,t,r);r.cancelCurrentStream=i.cancel,await i.completed,r.cancelCurrentStream=td}catch(e){if(r.cancelCurrentStream=td,!await this.handleSubscriptionFailure(e,a,r,n,i))return}}}notifyResubscribe(e,t){if(e.hasReceivedValue)try{t?.onResubscribe?.()}catch{}}startSubscriptionStream(e,t,n,r){return this.runStreamOnSession(e,t,n,()=>r.active,()=>{this.hasReportedTransportDisconnect=!1,r.hasReceivedValue=!0})}async handleSubscriptionFailure(e,t,n,r,i){if(!n.active||this.disposed)return!1;if(t!==this.session)return!0;let a=ad(e);return $u(a)?(this.hasReportedTransportDisconnect||console.warn(`WebSocket RPC subscription disconnected`,{error:a}),this.hasReportedTransportDisconnect=!0,await dd(i),!0):(this.reportNonTransportSubscriptionError(e,r),!1)}reportNonTransportSubscriptionError(e,t){id(e)||Vn(e,{route:`ws-subscribe`,reason:`non-transport-error`}),t?.onError?.(e)}async reconnect(){if(this.disposed)throw Error(`Transport disposed`);let e=this.reconnectChain.then(async()=>{if(this.disposed)throw Error(`Transport disposed`);let e=this.session;this.session=this.createSession(),await this.closeSession(e)});this.reconnectChain=e.catch(e=>{Vn(e,{route:`ws-reconnect`})}),await e}async dispose(){this.disposed||(this.disposed=!0,this.heartbeatTimer!==null&&this.heartbeatTimer!==void 0&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null),await this.closeSession(this.session))}async closeSession(e){let t=e.runtime.runPromise(Le(e.clientScope,Pt)),n=!1,r=null,i=new Promise(e=>{r=setTimeout(()=>{n=!0,e()},this.timing.sessionCloseGraceMs)});try{await Promise.race([t,i])}finally{r!==null&&clearTimeout(r),n&&(console.warn(`WebSocket session close exceeded its grace period; forcing disposal`,{graceMs:this.timing.sessionCloseGraceMs}),t.catch(()=>void 0)),await e.runtime.dispose()}}createSession(){let e=this.protocol??{layer:Zu(this.url,this.lifecycleHandlers),makeClient:Gu},t=Oc(be(e.layer,Cu)),n=t.runSync(Me());return{runtime:t,clientScope:n,clientPromise:t.runPromise(b(n)(e.makeClient))}}runStreamOnSession(e,t,n,r,i){let a,o,s=new Promise((e,t)=>{a=e,o=t});return{cancel:e.runtime.runCallback(xt(()=>e.clientPromise).pipe(Mt(e=>Dt(t(e),e=>gt(()=>{if(r()){i();try{n(e)}catch{}}})))),{onExit:e=>{if(Vt(e)){a();return}o(ke(e.cause))}}),completed:s}}};function dd(e){return new Promise(t=>{setTimeout(t,e)})}var fd=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/`,pd=/^[A-Za-z0-9_-]+$/;function md(e){let t=``;for(let n=0;n<e.byteLength;n+=3){let r=e[n]??0,i=e[n+1]??0,a=e[n+2]??0,o=r<<16|i<<8|a;t+=fd[o>>>18&63],t+=fd[o>>>12&63],n+1<e.byteLength&&(t+=fd[o>>>6&63]),n+2<e.byteLength&&(t+=fd[o&63])}return t.replaceAll(`+`,`-`).replaceAll(`/`,`_`)}function hd(e){if(e.length===0||!pd.test(e))throw Error(`Bulk transfer chunk is not valid base64url data.`);let t=e.replaceAll(`-`,`+`).replaceAll(`_`,`/`),n=Math.floor(t.length*6/8),r=new Uint8Array(n),i=0,a=0,o=0;for(let e of t){let t=fd.indexOf(e);if(t<0)throw Error(`Bulk transfer chunk is not valid base64url data.`);i=i<<6|t,a+=6,a>=8&&(a-=8,r[o]=i>>>a&255,o+=1)}return r}async function gd(e){let t=new Uint8Array(e.byteLength);t.set(e);let n=await crypto.subtle.digest(`SHA-256`,t.buffer);return Array.from(new Uint8Array(n),e=>e.toString(16).padStart(2,`0`)).join(``)}async function _d(e,t){let n=t?.chunkBytes??262144;if(!Number.isSafeInteger(n)||n<1||n>262144)throw Error(`Bulk transfer chunk size must be between 1 and ${$r}.`);let r=t?.transferId??crypto.randomUUID().replaceAll(`-`,`_`),i=[];for(let t=0;t<e.byteLength;t+=n){let a=e.slice(t,Math.min(t+n,e.byteLength));i.push({kind:`chunk`,transferId:r,offset:t,bytes:a.byteLength,data:md(a),sha256:await gd(a)})}return{totalBytes:e.byteLength,sha256:await gd(e),chunks:i}}async function vd(e){let t=hd(e.data);if(t.byteLength!==e.bytes)throw Error(`Bulk transfer chunk byte count mismatch at offset ${e.offset}: expected ${e.bytes}, received ${t.byteLength}.`);if(await gd(t)!==e.sha256)throw Error(`Bulk transfer chunk integrity mismatch at offset ${e.offset}.`);return t}async function yd(e){let t=new Map,n=[],r=0;for(let i of e.chunks){let e=t.get(i.offset);if(e!==void 0){if(e.bytes!==i.bytes||e.sha256!==i.sha256||e.data!==i.data)throw Error(`Bulk transfer has a conflicting duplicate chunk at offset ${i.offset}.`);continue}if(i.offset!==r)throw Error(`Bulk transfer chunk offset mismatch: expected ${r}, received ${i.offset}.`);let a=await vd(i);t.set(i.offset,i),n.push({chunk:i,bytes:a}),r+=a.byteLength}if(r!==e.totalBytes)throw Error(`Bulk transfer total byte count mismatch: expected ${e.totalBytes}, received ${r}.`);let i=new Uint8Array(e.totalBytes);for(let e of n)i.set(e.bytes,e.chunk.offset);if(await gd(i)!==e.sha256)throw Error(`Bulk transfer payload integrity mismatch.`);return i}var bd=`forge`,xd=RegExp(`^(?:${bd}|t3code)\\/(?:[0-9a-f]{8}|[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12})$`);function Sd(){return`${bd}/${ce(xa).replace(/-/g,``).slice(0,8).toLowerCase()}`}function Cd(e){return xd.test(e.trim().toLowerCase())}function wd(e){let t=e.trim().replace(/\/+$/g,``).replace(/\.git$/i,``).toLowerCase();if(/^(?:ssh|https?|git):\/\//i.test(t))try{let e=new URL(t),n=e.pathname.split(`/`).filter(e=>e.length>0).join(`/`);if(e.hostname&&n.includes(`/`))return`${e.hostname}/${n}`}catch{return t}let n=/^git@([^:/\s]+)[:/]([^/\s]+(?:\/[^/\s]+)+)$/i.exec(t);return n?.[1]&&n[2]?`${n[1]}/${n[2]}`:t}function Td(e){let t=e?.trim()??``;if(t.length===0)return null;let n=/^(?:git@github\.com:|ssh:\/\/git@github\.com\/|https:\/\/github\.com\/|git:\/\/github\.com\/)([^/\s]+\/[^/\s]+?)(?:\.git)?\/?$/i.exec(t)?.[1]?.trim()??``;return n.length>0?n:null}function Ed(e){let t=e.trim();if(t.length===0)return null;if(t.startsWith(`git@`)){let e=t.slice(4),n=e.search(/[:/]/);return n<=0?null:e.slice(0,n).toLowerCase()}try{return new URL(t).hostname.toLowerCase()}catch{return null}}function Dd(e){return`https://${e}`}function Od(e){return e===`github.com`||e.includes(`github`)}function kd(e){return e===`gitlab.com`||e.includes(`gitlab`)}function Ad(e){return e===`bitbucket.org`}function jd(e){return e===`dev.azure.com`||e===`ssh.dev.azure.com`||e===`vs-ssh.visualstudio.com`||e.endsWith(`.visualstudio.com`)}function Md(e){let t=Ed(e);if(!t)return null;let n=wd(e),r=`${t}/`;if(!n.startsWith(r))return null;let i=n.slice(r.length);return i.includes(`/`)?Od(t)?{kind:`github`,name:t===`github.com`?`GitHub`:`GitHub Self-Hosted`,host:t,repositoryPath:i,baseUrl:Dd(t)}:kd(t)?{kind:`gitlab`,name:t===`gitlab.com`?`GitLab`:`GitLab Self-Hosted`,host:t,repositoryPath:i,baseUrl:Dd(t)}:Ad(t)?{kind:`bitbucket`,name:`Bitbucket Cloud`,host:t,repositoryPath:i,baseUrl:Dd(t)}:jd(t)?{kind:`azure-devops`,name:`Azure DevOps`,host:t,repositoryPath:i,baseUrl:Dd(t)}:{kind:`unknown`,name:t,host:t,repositoryPath:i,baseUrl:Dd(t)}:null}var Nd={hasUpstream:!1,aheadCount:0,behindCount:0,pr:null,defaultBranch:null,diffVsBase:null};function Pd(e,t){return{...e,...t??Nd}}function Fd(e){return{hasUpstream:e.hasUpstream,aheadCount:e.aheadCount,behindCount:e.behindCount,pr:e.pr,defaultBranch:e.defaultBranch,diffVsBase:e.diffVsBase}}function Id(e){return{isRepo:e.isRepo,...e.hostingProvider?{hostingProvider:e.hostingProvider}:{},hasOriginRemote:e.hasOriginRemote,isDefaultBranch:e.isDefaultBranch,branch:e.branch,hasWorkingTreeChanges:e.hasWorkingTreeChanges,workingTree:e.workingTree}}function Ld(e,t){switch(t._tag){case`snapshot`:return Pd(t.local,t.remote);case`localUpdated`:return Pd(t.local,e?Fd(e):null);case`remoteUpdated`:return Pd(e===null?{isRepo:!0,hasOriginRemote:!1,isDefaultBranch:!1,branch:null,hasWorkingTreeChanges:!1,workingTree:{files:[],insertions:0,deletions:0}}:Id(e),t.remote)}}var Rd=262144,zd=250;function Bd(e){if(e instanceof Error)return e.message;try{return JSON.stringify(e)}catch{return String(e)}}function Vd(e){return new Promise(t=>setTimeout(t,e))}function Hd(e){let t=crypto.randomUUID(),n=Xi({controllerId:t,maxPendingWriteBytes:Rd}),r=!1,i=e=>{if(!e.sessionEpoch)throw Error(`Connected Forge runtime does not support epoch-fenced terminal controls.`);n.register({threadId:e.threadId,terminalId:e.terminalId,sessionEpoch:e.sessionEpoch})},a=async e=>{for(;!r;)try{return await e()}catch(e){if(!On(Bd(e)))throw e;await Vd(zd)}throw Error(`Terminal control client was disposed before acknowledgement.`)};return{terminal:{open:async t=>{let n=await e.request(e=>e[T.terminalOpen]({...t,terminalId:t.terminalId??`default`}));return i(n),n},write:async t=>{let r=t.terminalId??`default`;await n.enqueue({threadId:t.threadId,terminalId:r,writeBytes:new TextEncoder().encode(t.data).byteLength,execute:n=>a(()=>e.request(e=>e[T.terminalWrite]({...t,terminalId:r,...n})))})},resize:async t=>{let r=t.terminalId??`default`;await n.enqueue({threadId:t.threadId,terminalId:r,execute:n=>a(()=>e.request(e=>e[T.terminalResize]({...t,terminalId:r,...n})))})},signal:async t=>{let r=t.terminalId??`default`;await n.enqueue({threadId:t.threadId,terminalId:r,execute:n=>a(()=>e.request(e=>e[T.terminalSignal]({...t,terminalId:r,...n})))})},clear:async t=>{let r=t.terminalId??`default`;await n.enqueue({threadId:t.threadId,terminalId:r,execute:n=>a(()=>e.request(e=>e[T.terminalClear]({...t,terminalId:r,...n})))})},restart:async t=>{let r=t.terminalId??`default`,o=null;if(await n.enqueue({threadId:t.threadId,terminalId:r,execute:async n=>{o=(await a(()=>e.request(e=>e[T.terminalRestart]({...t,terminalId:r,...n})))).snapshot}}),o===null)throw Error(`Terminal restart completed without a snapshot.`);return i(o),o},close:async t=>{let r=t.terminalId?[t.terminalId]:n.terminalIds(t.threadId);for(let i of r)await n.enqueue({threadId:t.threadId,terminalId:i,execute:n=>a(()=>e.request(e=>e[T.terminalClose]({...t,terminalId:i,...n})))}),n.remove(t.threadId,i)},onEvent:t=>e.subscribe(e=>e[T.subscribeTerminalEvents]({}),e=>{(e.type===`started`||e.type===`restarted`)&&i(e.snapshot),t(e)})},dispose:()=>{r=!0,n.dispose()}}}function Ud(e){return{createUploadUrl:t=>e.request(e=>e[T.attachmentsCreateUploadUrl](t)),delete:t=>e.request(e=>e[T.attachmentsDelete](t))}}function Wd(e){return{environmentPreflight:t=>e.request(e=>e[T.workspaceEnvironmentPreflight](t)),listDirectory:t=>e.request(e=>e[T.workspaceListDirectory](t)),ensureScratch:t=>e.request(e=>e[T.workspaceEnsureScratch](t))}}async function Gd(e,t){await e.request(e=>e[T.workspaceCancelWriteFile]({transferId:t})).catch(()=>void 0)}var Kd=2e4,qd=12e4,Jd=3e5;function Yd(e){if(e instanceof nd)return!0;let t=e instanceof Error?e.message:String(e);return On(t)}async function Xd(e,t){let n=t.type===`thread.turn.start`&&t.bootstrap!==void 0?Jd:Kd,r=()=>e.request(e=>e[Ai.dispatchCommand](t),{timeout:n});try{return await r()}catch(t){if(!Yd(t))throw t;return await e.reconnect(),await r()}}function Zd(e){if(!e?.aborted)return;let t=Error(`Bulk transfer was cancelled.`);throw t.name=`AbortError`,t}async function Qd(e,t,n){let r={started:null,completed:null,chunks:[],protocolError:null,receivedBytes:0};if(await e.requestStream(t,e=>$d(r,e,n),n),r.protocolError!==null)throw r.protocolError;let i=r.started,a=r.completed;if(i===null||a===null)throw Error(`Bulk transfer stream completed without start and completion metadata.`);if(a.transferId!==i.transferId||a.totalBytes!==i.totalBytes||a.sha256!==i.sha256)throw Error(`Bulk transfer completion metadata mismatch.`);return await yd({totalBytes:i.totalBytes,sha256:i.sha256,chunks:r.chunks})}function $d(e,t,n){if(e.protocolError===null){if(t.kind===`started`){ef(e,t,n);return}if(e.started===null||t.transferId!==e.started.transferId){e.protocolError=Error(`Bulk transfer event identity mismatch.`);return}if(t.kind===`chunk`){tf(e,t,n);return}e.completed=t,n?.onProgress?.({completedBytes:t.totalBytes,totalBytes:t.totalBytes})}}function ef(e,t,n){if(e.started!==null||t.totalBytes>16777216){e.protocolError=Error(`Bulk transfer started with invalid or oversized metadata.`);return}e.started=t,n?.onProgress?.({completedBytes:0,totalBytes:t.totalBytes})}function tf(e,t,n){let r=e.started;if(r!==null){if(e.receivedBytes+=t.bytes,e.receivedBytes>r.totalBytes){e.protocolError=Error(`Bulk transfer exceeded its declared byte count.`);return}e.chunks.push(t),n?.onProgress?.({completedBytes:e.receivedBytes,totalBytes:r.totalBytes})}}async function nf(e,t,n){let r=new TextEncoder().encode(t.contents);if(r.byteLength>16777216)throw Error(`Project file exceeds the ${Ar}-byte write limit.`);let i=await _d(r),a=i.chunks[0]?.transferId??crypto.randomUUID().replaceAll(`-`,`_`),o=!1;try{Zd(n?.signal);let r=await rf(e,t,a,i);return o=!0,n?.onProgress?.({completedBytes:r.nextOffset,totalBytes:i.totalBytes}),await af(e,a,i,r,n),{relativePath:t.relativePath}}catch(t){throw o&&await Gd(e,a),t}}function rf(e,t,n,r){return e.request(e=>e[T.workspaceBeginWriteFile]({transferId:n,cwd:t.cwd,relativePath:t.relativePath,totalBytes:r.totalBytes,sha256:r.sha256}))}async function af(e,t,n,r,i){if(r.state!==`completed`){for(let t of n.chunks){if(t.offset<r.nextOffset)continue;Zd(i?.signal);let{kind:a,...o}=t,s=await e.request(e=>e[T.workspaceWriteFileChunk](o));i?.onProgress?.({completedBytes:s.nextOffset,totalBytes:n.totalBytes})}Zd(i?.signal),await e.request(e=>e[T.workspaceCommitWriteFile]({transferId:t}))}}function of(e){let t=Hd(e);return{dispose:()=>(t.dispose(),e.dispose()),reconnect:async()=>{na(),await e.reconnect()},terminal:t.terminal,browser:{openSession:t=>e.request(e=>e[T.browserOpenSession](t)),listSessions:t=>e.request(e=>e[T.browserListSessions](t)),closeSession:t=>e.request(e=>e[T.browserCloseSession](t)),getSession:t=>e.request(e=>e[T.browserGetSession](t)),command:t=>e.request(e=>e[T.browserCommand](t)),clearBrowsingData:t=>e.request(e=>e[T.browserClearBrowsingData](t)),attachDisplay:t=>e.request(e=>e[T.browserAttachDisplay](t)),addDisplayIceCandidate:t=>e.request(e=>e[T.browserAddDisplayIceCandidate](t)),onEvent:(t,n,r)=>e.subscribe(e=>e[T.subscribeBrowserEvents](t),n,r)},computer:{input:t=>e.request(e=>e[T.computerInput](t))},threadDevRuntime:{get:t=>e.request(e=>e[T.threadDevRuntimeGet](t)),allocatePort:t=>e.request(e=>e[T.threadDevRuntimeAllocatePort](t)),release:t=>e.request(e=>e[T.threadDevRuntimeRelease](t))},devTunnel:{register:t=>e.request(e=>e[T.devTunnelRegister](t)),unregister:t=>e.request(e=>e[T.devTunnelUnregister](t)),list:t=>e.request(e=>e[T.devTunnelList](t))},attachments:Ud(e),projects:{searchContents:(t,n)=>e.request(e=>e[T.projectsSearchContents](t),n),searchEntries:t=>e.request(e=>e[T.projectsSearchEntries](t)),readFile:(t,n)=>Qd(e,e=>e[T.workspaceReadFile](t),n),writeFile:(t,n)=>nf(e,t,n)},projectCheckoutDeletion:{preview:t=>e.request(e=>e[T.projectCheckoutDeletionPreview](t)),execute:t=>e.request(e=>e[T.projectCheckoutDeletionExecute](t))},workspace:Wd(e),shell:{openInEditor:t=>e.request(e=>e[T.shellOpenInEditor](t))},git:{pull:t=>e.request(e=>e[T.gitPull](t)),refreshStatus:t=>e.request(e=>e[T.gitRefreshStatus](t)),onStatus:(t,n,r)=>{let i=null;return e.subscribe(e=>e[T.subscribeGitStatus](t),e=>{i=Ld(i,e),n(i)},r)},runStackedAction:async(t,n)=>{let r=null;if(await e.requestStream(e=>e[T.gitRunStackedAction](t),e=>{n?.onProgress?.(e),e.kind===`action_finished`&&(r=e.result)}),r)return r;throw Error(`Git action stream completed without a final result.`)},listBranches:t=>e.request(e=>e[T.gitListBranches](t)),createWorktree:t=>e.request(e=>e[T.gitCreateWorktree](t)),removeWorktree:t=>e.request(e=>e[T.gitRemoveWorktree](t)),createBranch:t=>e.request(e=>e[T.gitCreateBranch](t)),checkout:t=>e.request(e=>e[T.gitCheckout](t)),init:t=>e.request(e=>e[T.gitInit](t)),resolvePullRequest:t=>e.request(e=>e[T.gitResolvePullRequest](t)),preparePullRequestThread:t=>e.request(e=>e[T.gitPreparePullRequestThread](t))},pullRequests:{list:t=>e.request(e=>e[T.pullRequestsList](t)),listStats:t=>e.request(e=>e[T.pullRequestsListStats](t)),detail:t=>e.request(e=>e[T.pullRequestsDetail](t)),activity:t=>e.request(e=>e[T.pullRequestsActivity](t)),threadComments:t=>e.request(e=>e[T.pullRequestsThreadComments](t)),diffFileContents:t=>e.request(e=>e[T.pullRequestsDiffFileContents](t)),runAction:t=>e.request(e=>e[T.pullRequestsRunAction](t)),update:t=>e.request(e=>e[T.pullRequestsUpdate](t)),comment:t=>e.request(e=>e[T.pullRequestsComment](t)),updateComment:t=>e.request(e=>e[T.pullRequestsUpdateComment](t)),submitReview:t=>e.request(e=>e[T.pullRequestsSubmitReview](t)),replyToThread:t=>e.request(e=>e[T.pullRequestsReplyToThread](t)),setThreadResolution:t=>e.request(e=>e[T.pullRequestsSetThreadResolution](t)),setReaction:t=>e.request(e=>e[T.pullRequestsSetReaction](t)),invalidate:t=>e.request(e=>e[T.pullRequestsInvalidate](t)),reviewerCandidates:t=>e.request(e=>e[T.pullRequestsReviewerCandidates](t)),requestReviewers:t=>e.request(e=>e[T.pullRequestsRequestReviewers](t))},server:{getConfig:()=>e.request(e=>e[T.serverGetConfig]({})),refreshProviders:()=>e.request(e=>e[T.serverRefreshProviders]({})),startProviderAuth:t=>e.request(e=>e[T.serverStartProviderAuth](t)),repairProviderAuthRuntime:t=>e.request(e=>e[T.serverRepairProviderAuthRuntime](t)),disconnectProviderAuth:t=>e.request(e=>e[T.serverDisconnectProviderAuth](t)),getProviderAuthSession:t=>e.request(e=>e[T.serverGetProviderAuthSession](t)),cancelProviderAuth:t=>e.request(e=>e[T.serverCancelProviderAuth](t)),submitProviderAuthCode:t=>e.request(e=>e[T.serverSubmitProviderAuthCode](t)),syncPersonalCodexToCloud:t=>e.request(e=>e[T.serverSyncPersonalCodexToCloud](t)),syncPersonalClaudeToCloud:t=>e.request(e=>e[T.serverSyncPersonalClaudeToCloud](t)),upsertKeybinding:t=>e.request(e=>e[T.serverUpsertKeybinding](t)),removeKeybinding:t=>e.request(e=>e[T.serverRemoveKeybinding](t)),getSettings:()=>e.request(e=>e[T.serverGetSettings]({})),updateSettings:t=>e.request(e=>e[T.serverUpdateSettings]({patch:t})),updateEnvironmentDisplayName:t=>e.request(e=>e[T.serverUpdateEnvironmentDisplayName](t)),getTraceDiagnostics:t=>e.request(e=>e[T.serverGetTraceDiagnostics](t)),subscribeConfig:(t,n)=>e.subscribe(e=>e[T.subscribeServerConfig]({}),t,n),subscribeLifecycle:(t,n)=>e.subscribe(e=>e[T.subscribeServerLifecycle]({}),t,n),subscribeAuthAccess:(t,n)=>e.subscribe(e=>e[T.subscribeAuthAccess]({}),t,n),subscribeWorkspaceReadiness:(t,n)=>e.subscribe(e=>e[T.subscribeWorkspaceReadiness]({}),t,n)},usage:{getSummary:t=>e.request(e=>e[T.usageGetSummary](t),{timeout:qd})},orchestration:{dispatchCommand:t=>Xd(e,t),searchThreads:t=>e.request(e=>e[Ai.searchThreads](t),{timeout:1e4}),getTurnDiff:(t,n)=>Qd(e,e=>e[Ai.streamTurnDiff](t),n).then(e=>({...t,diff:new TextDecoder().decode(e)})),getFullThreadDiff:(t,n)=>Qd(e,e=>e[Ai.streamFullThreadDiff](t),n).then(e=>({...t,fromTurnCount:0,diff:new TextDecoder().decode(e)})),subscribeShell:(t,n)=>e.subscribe(e=>e[Ai.subscribeShell]({}),t,n),subscribeThread:(t,n,r)=>e.subscribe(e=>e[Ai.subscribeThread](t),n,r)}}}function sf(){if(typeof window>`u`)return;let e=Zi();if(!(e?.primaryMode!==`cloud`||!e.bearerToken))return{bearerToken:e.bearerToken,httpBaseUrl:e.httpBaseUrl,wsBaseUrl:e.wsBaseUrl}}function cf(){if(typeof window>`u`)return;let e=Zi(),t=e?.primaryMode===`cloud`?e.desktopLocal:e;if(!(!t?.httpBaseUrl||!t.wsBaseUrl||!t.bearerToken))return{bearerToken:t.bearerToken,httpBaseUrl:t.httpBaseUrl,wsBaseUrl:t.wsBaseUrl,label:t.label}}function lf(e){let t=sr(e);if(!t)throw Error(`Unable to resolve websocket URL for ${e?.label??`primary environment`}.`);return of(new ud(async()=>{await ea().catch(()=>null);let e=sf();if(e)try{return await Rl(e)}catch(e){throw Rn(e)&&Ui(`ws-token`),e}return kn(t)}))}function uf(e){return of(new ud(()=>Rl(e),{trackGlobalConnection:!1,onAttempt:()=>e.onConnecting(e.environmentId),onOpen:()=>e.onConnected(e.environmentId),onError:t=>e.onError(e.environmentId,t),onClose:t=>e.onDisconnected(e.environmentId,t.reason)}))}function df(e){return typeof e==`string`?e:typeof e==`object`&&e&&`detail`in e&&typeof e.detail==`string`?e.detail:e instanceof Error?e.message:String(e)}function ff(e){return e.match(/blocked by policy for\s+([^.\s]+(?:\.[^.\s]+)*)\.?/i)?.[1]||(e.match(/navigation to\s+([^.\s]+(?:\.[^.\s]+)*)\s+is restricted/i)?.[1]??null)}function pf(e){let t=df(e).trim()||`Unknown browser error.`,n=ff(t);return/blocked by policy|restricted to allowed domains/i.test(t)?{title:`Browser navigation blocked`,cause:`${n??`This URL`} is not allowed by the current browser policy.`,nextAction:`Use an allowed URL or update the browser allowed-domain setting.`,technicalDetail:t}:/does not match thread|session .*not found|no active browser tab|tab .*not found/i.test(t)?{title:`Browser session is stale`,cause:`Forge no longer has a matching live browser session for this thread.`,nextAction:`Restart the browser session from the Browser options menu.`,technicalDetail:t}:/screenshot|capture|Page\.capture/i.test(t)?{title:`Browser screenshot failed`,cause:`The browser could not capture the current page frame.`,nextAction:`Reload the page, then try the screenshot again.`,technicalDetail:t}:/timed out|timeout/i.test(t)?{title:`Browser action timed out`,cause:`Forge did not receive a response from the browser runtime in time.`,nextAction:`Retry the action. If it keeps failing, restart the browser session.`,technicalDetail:t}:/runtime is not available|browser.*unavailable|not supported|disabled/i.test(t)?{title:`Browser session unavailable`,cause:`This environment does not currently expose the in-app browser runtime.`,nextAction:`Use a workspace with browser support or restart Forge after browser support is enabled.`,technicalDetail:t}:/navigate|navigation|net::|ERR_/i.test(t)?{title:`Browser navigation failed`,cause:`The browser could not load the requested page.`,nextAction:`Check the URL and network access, then try again.`,technicalDetail:t}:{title:`Browser action failed`,cause:`Forge could not complete the browser action.`,nextAction:`Retry the action. If it keeps failing, restart the browser session from the Browser options menu.`,technicalDetail:t}}function mf(e){let t=pf(e);return`${t.cause} ${t.nextAction}`}function hf(e){let t=pf(e);return`${t.title}: ${t.cause} ${t.nextAction}`}var gf={session:null,selectedBrowserId:null,sessionsByBrowserId:{},lastActivityByTabId:{},lastSnapshotContentByTabId:{},lastScreenshotDataUrlByTabId:{},lastScreenshotMetaByTabId:{},lastConsoleLogsByTabId:{},lastConsoleLogsMetaByTabId:{},lastFrameByTabId:{},lastFrameSequenceByTabId:{},lastObservedFrameSequenceByTabId:{},lastFrameStreamIdByTabId:{},lastFrameStreamGenerationByTabId:{},frameGapCountByTabId:{},lastFrameMetaByTabId:{},displayIceCandidatesByClientId:{},lastError:null};function _f(e){return Ln(e)}function vf(e){let t=e.status===`reconnecting`&&e.reason===`network_unreachable`;return e.transport===`remote-webrtc`&&(e.status===`connected`||e.status===`connecting`||e.status===`reconnecting`)&&(e.reason!==`network_unreachable`||t)&&e.reason!==`unsupported_host`}function yf(e){return e.transport!==`remote-webrtc`||e.status===`failed`||e.status===`unsupported`?!1:e.reason!==`network_unreachable`&&e.reason!==`unsupported_host`}function bf(e){let{currentSession:t,nextSession:n}=e;return!t||t.browserId!==n.browserId||t.sessionId!==n.sessionId||!vf(t.display)||!yf(n.display)?n:{...n,display:{...t.display,viewport:n.display.viewport??n.viewport??t.display.viewport,devicePixelRatio:n.display.devicePixelRatio??t.display.devicePixelRatio,iceServers:n.display.iceServers??t.display.iceServers,reconnect:t.display.reconnect??n.display.reconnect}}}function xf(e){let{storedSession:t,nextSession:n}=e;if(!t||t.browserId!==n.browserId||t.sessionId!==n.sessionId)return!1;let r=n.tabs.some(e=>e.navigationStatus===`pending`),i=t.tabs.some(e=>e.navigationStatus===`complete`||e.navigationStatus===`failed`);if(!r||!i)return!1;let a=Date.parse(t.updatedAt),o=Date.parse(n.updatedAt);return Number.isNaN(a)||Number.isNaN(o)?!1:o<a}function M(e,t,n){return e[t]===n?e:{...e,[t]:n}}function Sf(e){switch(e.type){case`tab.updated`:return e.payload.tab.tabId;case`tab.closed`:case`snapshot.ready`:case`screenshot.ready`:case`frame.ready`:case`console.logs.ready`:case`display.iceCandidate`:case`display.metrics`:return e.payload.tabId;case`action.failed`:return e.payload.tabId??null;case`display.updated`:case`session.started`:case`session.updated`:case`session.closed`:return null}}function Cf(e,t){let n=Sf(t);return n?{...e,lastActivityByTabId:{...e.lastActivityByTabId,[n]:{actor:t.agentId?`agent`:`human`,agentId:t.agentId,browserId:t.browserId,eventType:t.type,...t.type===`action.failed`?{commandType:t.payload.commandType}:{},...t.type===`action.failed`?{message:t.payload.message}:{},createdAt:t.createdAt}}}:e}function wf(e){switch(e.type){case`session.started`:case`session.updated`:case`tab.updated`:case`snapshot.ready`:case`screenshot.ready`:case`frame.ready`:case`display.updated`:return!0;case`session.closed`:case`tab.closed`:case`console.logs.ready`:case`action.failed`:case`display.iceCandidate`:case`display.metrics`:return!1}}function Tf(e){return e===null?`end-of-candidates`:JSON.stringify([e.candidate,e.sdpMid??null,e.sdpMLineIndex??null,e.usernameFragment??null])}function Ef(e,t){let n=Tf(t);return e.some(e=>Tf(e)===n)?e:[...e,t]}function Df(e){if(e.type!==`session.closed`)return null;switch(e.payload.reason){case`idle_timeout`:return`The browser was closed after being idle. Reopen the preview to restore this thread's browser.`;case`runtime_shutdown`:return`The browser runtime shut down. Reopen the preview to restore this thread's browser.`;case`thread_archived`:case`clear_browsing_data`:case`user_closed`:case void 0:return null}}function Of(e){let t=e.event.payload.display;return t.status===`failed`||t.status===`unsupported`?t.detail??`Browser display is unavailable.`:e.currentLastError&&/browser display/i.test(e.currentLastError)?null:e.currentLastError}function kf(e,t){let n=e.sessionsByBrowserId[t.browserId]??(e.session?.browserId===t.browserId?e.session:null);if(!n)return!0;let r=n.sessionId===t.payload.sessionId,i=!t.sessionEpoch||!n.sessionEpoch||t.sessionEpoch===n.sessionEpoch;return r&&i}function Af(e,t){let n=e.lastFrameSequenceByTabId[t]??0;return{acceptedSequence:n,observedSequence:e.lastObservedFrameSequenceByTabId[t]??n,...e.lastFrameStreamIdByTabId[t]?{streamId:e.lastFrameStreamIdByTabId[t]}:{},...e.lastFrameStreamGenerationByTabId[t]===void 0?{}:{streamGeneration:e.lastFrameStreamGenerationByTabId[t]},...e.lastFrameMetaByTabId[t]?.capturedAt?{acceptedCapturedAt:e.lastFrameMetaByTabId[t].capturedAt}:{},gapCount:e.frameGapCountByTabId[t]??0}}function jf(e,t){let n=t.payload.tabId,r=Lc(Af(e,n),{sequence:t.payload.sequence,capturedAt:t.payload.capturedAt,...t.payload.streamId?{streamId:t.payload.streamId}:{},...t.payload.streamGeneration===void 0?{}:{streamGeneration:t.payload.streamGeneration},...t.payload.keyframe===void 0?{}:{keyframe:t.payload.keyframe}});return{decision:r,observedSequence:r.state.observedSequence,frameGapCount:r.state.gapCount}}function Mf(e,t,n){let r=t.payload.tabId;return{...e,lastObservedFrameSequenceByTabId:{...e.lastObservedFrameSequenceByTabId,[r]:n.observedSequence},frameGapCountByTabId:{...e.frameGapCountByTabId,[r]:n.frameGapCount}}}function Nf(e,t){let n=t.payload.tabId;return{...e,lastFrameByTabId:{...e.lastFrameByTabId,[n]:t.payload.imageDataUrl},lastFrameSequenceByTabId:{...e.lastFrameSequenceByTabId,[n]:t.payload.sequence},lastFrameStreamIdByTabId:t.payload.streamId?{...e.lastFrameStreamIdByTabId,[n]:t.payload.streamId}:e.lastFrameStreamIdByTabId,lastFrameStreamGenerationByTabId:t.payload.streamGeneration===void 0?e.lastFrameStreamGenerationByTabId:{...e.lastFrameStreamGenerationByTabId,[n]:t.payload.streamGeneration},lastFrameMetaByTabId:{...e.lastFrameMetaByTabId,[n]:{capturedAt:t.payload.capturedAt,url:t.payload.url,viewport:t.payload.viewport}},lastError:null}}function Pf(e){let{current:t,event:n,pendingAutoRevealKeys:r,state:i,threadKey:a}=e;if(!kf(t,n))return i;let o=jf(t,n);if(!o.decision.observe)return i;let s=Mf(t,n,o),c=o.decision.accept?Nf(s,n):s;return{browserStateByThreadKey:M(i.browserStateByThreadKey,a,c),pendingAutoRevealKeys:r}}var Ff=wa(e=>({browserStateByThreadKey:{},pendingAutoRevealKeys:new Set,setSessionSnapshot:(t,n)=>e(e=>{let r=_f(t),i=e.browserStateByThreadKey[r]??gf,a=n?bf({currentSession:i.sessionsByBrowserId[n.browserId]??i.session,nextSession:n}):null;return{browserStateByThreadKey:M(e.browserStateByThreadKey,r,{...i,session:a,selectedBrowserId:a?.browserId??i.selectedBrowserId,sessionsByBrowserId:a?{...i.sessionsByBrowserId,[a.browserId]:a}:i.sessionsByBrowserId,lastError:a?null:i.lastError})}}),selectBrowserSession:(t,n)=>e(e=>{let r=_f(t),i=e.browserStateByThreadKey[r]??gf,a=i.sessionsByBrowserId[n]??i.session;return{browserStateByThreadKey:M(e.browserStateByThreadKey,r,{...i,selectedBrowserId:n,session:a})}}),applyBrowserEvent:(t,n)=>e(e=>{let r=_f(t),i=wf(n)?new Set(e.pendingAutoRevealKeys).add(r):e.pendingAutoRevealKeys,a=Cf(e.browserStateByThreadKey[r]??gf,n);switch(n.type){case`session.started`:{if(xf({storedSession:a.sessionsByBrowserId[n.payload.snapshot.browserId]??a.session,nextSession:n.payload.snapshot}))return e;let t=bf({currentSession:a.sessionsByBrowserId[n.payload.snapshot.browserId]??a.session,nextSession:n.payload.snapshot});return{browserStateByThreadKey:M(e.browserStateByThreadKey,r,{...a,session:t,selectedBrowserId:a.selectedBrowserId??t.browserId,sessionsByBrowserId:{...a.sessionsByBrowserId,[t.browserId]:t},lastError:null}),pendingAutoRevealKeys:i}}case`session.updated`:{let t=bf({currentSession:a.sessionsByBrowserId[n.payload.snapshot.browserId]??a.session,nextSession:n.payload.snapshot});return{browserStateByThreadKey:M(e.browserStateByThreadKey,r,{...a,session:a.selectedBrowserId&&a.selectedBrowserId!==n.payload.snapshot.browserId?a.session:t,selectedBrowserId:a.selectedBrowserId??n.payload.snapshot.browserId,sessionsByBrowserId:{...a.sessionsByBrowserId,[t.browserId]:t},lastError:null}),pendingAutoRevealKeys:i}}case`session.closed`:let t=a.selectedBrowserId===n.browserId||a.session?.browserId===n.browserId;return{browserStateByThreadKey:M(e.browserStateByThreadKey,r,{...a,session:t?null:a.session,selectedBrowserId:t?null:a.selectedBrowserId,sessionsByBrowserId:Object.fromEntries(Object.entries(a.sessionsByBrowserId).filter(([e])=>e!==n.browserId)),lastError:Df(n)})};case`display.updated`:{let t=a.session;if(!t||t.sessionId!==n.payload.sessionId)return{browserStateByThreadKey:M(e.browserStateByThreadKey,r,a),pendingAutoRevealKeys:i};let o={...t,display:n.payload.display,updatedAt:n.createdAt};return{browserStateByThreadKey:M(e.browserStateByThreadKey,r,{...a,session:o,sessionsByBrowserId:{...a.sessionsByBrowserId,[o.browserId]:o},lastError:Of({currentLastError:a.lastError,event:n})}),pendingAutoRevealKeys:i}}case`tab.updated`:{let t=a.session;if(!t||t.sessionId!==n.payload.sessionId)return{browserStateByThreadKey:M(e.browserStateByThreadKey,r,a),pendingAutoRevealKeys:i};let o=t.tabs.map(e=>e.tabId===n.payload.tab.tabId?{...n.payload.tab,isActive:e.tabId===t.activeTabId}:{...e,isActive:e.tabId===t.activeTabId}).concat(t.tabs.some(e=>e.tabId===n.payload.tab.tabId)?[]:[{...n.payload.tab,isActive:n.payload.tab.tabId===t.activeTabId}]);return{browserStateByThreadKey:M(e.browserStateByThreadKey,r,{...a,session:{...t,tabs:o},lastError:null}),pendingAutoRevealKeys:i}}case`tab.closed`:{let t=a.session;if(!t||t.sessionId!==n.payload.sessionId)return e;let i=t.tabs.filter(e=>e.tabId!==n.payload.tabId);return{browserStateByThreadKey:M(e.browserStateByThreadKey,r,{...a,session:{...t,tabs:i,activeTabId:t.activeTabId===n.payload.tabId?i[0]?.tabId??null:t.activeTabId}})}}case`snapshot.ready`:return{browserStateByThreadKey:M(e.browserStateByThreadKey,r,{...a,lastSnapshotContentByTabId:{...a.lastSnapshotContentByTabId,[n.payload.tabId]:n.payload.content},lastError:null}),pendingAutoRevealKeys:i};case`screenshot.ready`:return{browserStateByThreadKey:M(e.browserStateByThreadKey,r,{...a,lastScreenshotDataUrlByTabId:{...a.lastScreenshotDataUrlByTabId,[n.payload.tabId]:n.payload.imageDataUrl},lastScreenshotMetaByTabId:{...a.lastScreenshotMetaByTabId,[n.payload.tabId]:{captureId:n.payload.captureId,capturedAt:n.payload.capturedAt,url:n.payload.url,viewport:n.payload.viewport}},lastError:null}),pendingAutoRevealKeys:i};case`frame.ready`:return Pf({state:e,current:a,event:n,threadKey:r,pendingAutoRevealKeys:i});case`console.logs.ready`:return{browserStateByThreadKey:M(e.browserStateByThreadKey,r,{...a,lastConsoleLogsByTabId:{...a.lastConsoleLogsByTabId,[n.payload.tabId]:n.payload.logs},lastConsoleLogsMetaByTabId:{...a.lastConsoleLogsMetaByTabId,[n.payload.tabId]:{capturedAt:n.createdAt,tabId:n.payload.tabId,count:n.payload.logs.length}},lastError:null})};case`display.iceCandidate`:{let t=a.displayIceCandidatesByClientId[n.payload.clientId]??[];return{browserStateByThreadKey:M(e.browserStateByThreadKey,r,{...a,displayIceCandidatesByClientId:{...a.displayIceCandidatesByClientId,[n.payload.clientId]:Ef(t,n.payload.candidate)}}),pendingAutoRevealKeys:i}}case`display.metrics`:return{browserStateByThreadKey:M(e.browserStateByThreadKey,r,a),pendingAutoRevealKeys:i};case`action.failed`:return{browserStateByThreadKey:M(e.browserStateByThreadKey,r,{...a,lastError:hf(n.payload.message)})};default:return e}}),clearBrowserState:t=>e(e=>{let n=_f(t);if(!(n in e.browserStateByThreadKey))return e;let{[n]:r,...i}=e.browserStateByThreadKey;return{browserStateByThreadKey:i}}),consumeAutoReveal:t=>e(e=>{if(!e.pendingAutoRevealKeys.has(t))return e;let n=new Set(e.pendingAutoRevealKeys);return n.delete(t),{pendingAutoRevealKeys:n}})}));function If(e,t){return t?e[_f(t)]??null:null}function Lf(e){if(e!==void 0)return Object.fromEntries(Object.entries(e).toSorted(([e],[t])=>e.localeCompare(t)))}function Rf(e){return{...e,...e.projectIds===void 0?{}:{projectIds:[...e.projectIds].toSorted((e,t)=>e.localeCompare(t))},...e.cursors===void 0?{}:{cursors:Lf(e.cursors)}}}var zf={all:e=>[`pullRequests`,e],list:(e,t)=>[`pullRequests`,e,`list`,Rf(t)],stats:(e,t)=>[`pullRequests`,e,`stats`,[...t].toSorted((e,t)=>`${e.projectId}:${e.repository}#${e.number}`.localeCompare(`${t.projectId}:${t.repository}#${t.number}`))],detail:(e,t)=>[`pullRequests`,e,`detail`,t],activity:(e,t)=>[`pullRequests`,e,`activity`,t],diff:(e,t)=>[`pullRequests`,e,`diff`,t],threadComments:(e,t)=>[`pullRequests`,e,`thread-comments`,t],diffFileContents:(e,t)=>[`pullRequests`,e,`diff-file-contents`,t],reviewerCandidates:(e,t)=>[`pullRequests`,e,`reviewer-candidates`,t]},Bf=Hr.make(`command-authority`);function Vf(e){return e[0]===`pullRequests`&&e[1]===Bf&&e[2]===`detail`}function Hf(e){return e[0]===`pullRequests`&&e[1]===Bf&&e[2]===`list`}function Uf(e,t){let n;try{n=e()}catch{return}return{getItem:e=>{let r=e=>e===null?null:JSON.parse(e,t?.reviver),i=n.getItem(e)??null;return i instanceof Promise?i.then(r):r(i)},setItem:(e,r)=>n.setItem(e,JSON.stringify(r,t?.replacer)),removeItem:e=>n.removeItem(e)}}var Wf=e=>t=>{try{let n=e(t);return n instanceof Promise?n:{then(e){return Wf(e)(n)},catch(e){return this}}}catch(e){return{then(e){return this},catch(t){return Wf(t)(e)}}}},Gf=(e,t)=>(n,r,i)=>{let a={storage:Uf(()=>window.localStorage),partialize:e=>e,version:0,merge:(e,t)=>({...t,...e}),...t},o=!1,s=0,c=new Set,l=new Set,u=a.storage;if(!u)return e((...e)=>{console.warn(`[zustand persist middleware] Unable to update item '${a.name}', the given storage is currently unavailable.`),n(...e)},r,i);let d=()=>{let e=a.partialize({...r()});return u.setItem(a.name,{state:e,version:a.version})},f=i.setState;i.setState=(e,t)=>(f(e,t),d());let p=e((...e)=>(n(...e),d()),r,i);i.getInitialState=()=>p;let m,h=()=>{if(!u)return;let e=++s;o=!1,c.forEach(e=>e(r()??p));let t=a.onRehydrateStorage?.call(a,r()??p)||void 0;return Wf(u.getItem.bind(u))(a.name).then(e=>{if(e)if(typeof e.version==`number`&&e.version!==a.version){if(a.migrate){let t=a.migrate(e.state,e.version);return t instanceof Promise?t.then(e=>[!0,e]):[!0,t]}console.error(`State loaded from storage couldn't be migrated since no migrate function was provided`)}else return[!1,e.state];return[!1,void 0]}).then(t=>{if(e!==s)return;let[i,o]=t;if(m=a.merge(o,r()??p),n(m,!0),i)return d()}).then(()=>{e===s&&(t?.(r(),void 0),m=r(),o=!0,l.forEach(e=>e(m)))}).catch(n=>{e===s&&t?.(void 0,n)})};return i.persist={setOptions:e=>{a={...a,...e},e.storage&&(u=e.storage)},clearStorage:()=>{++s,u?.removeItem(a.name)},getOptions:()=>a,rehydrate:()=>h(),hasHydrated:()=>o,onHydrate:e=>(c.add(e),()=>{c.delete(e)}),onFinishHydration:e=>(l.add(e),()=>{l.delete(e)})},a.skipHydration||h(),m||p},Kf=/^(localhost|[a-z0-9.-]+\.localhost|127(?:\.\d{1,3}){3}|\[[0:]+1\]|::1)(?::\d+)?(?:[/?#]|$)/i,qf=/https?:\/\/[^\s"'`<>]+/gu,Jf=new RegExp(String.raw`\u001B(?:\][\s\S]*?(?:\u0007|\u001B\\)|[@-_][0-?]*[ -/]*[@-~])`,`gu`),Yf=/(https?:\/\/(?:localhost|[a-z0-9.-]+\.localhost|127(?:\.\d{1,3}){3}|\[[0:]+1\]|::1|10(?:\.\d{1,3}){3}|172\.(?:1[6-9]|2\d|3[01])(?:\.\d{1,3}){2}|192\.168(?:\.\d{1,3}){2}):)\s+(\d{1,5})(?=[/?#\s]|$)/giu;function Xf(e){let t=e.trim();if(!t||/^[a-z][a-z0-9+.-]*:\/\//i.test(t)&&!/^https?:\/\//i.test(t))return null;let n=t.split(/[/:?#]/,1)[0]??``,r=Kf.test(t)||$f(n)?`http`:`https`,i=/^https?:\/\//i.test(t)?t:`${r}://${t}`;try{let e=new URL(i);return e.protocol!==`http:`&&e.protocol!==`https:`?null:e.toString()}catch{return null}}function Zf(e){try{let t=new URL(e);return t.protocol===`http:`||t.protocol===`https:`}catch{return!1}}function Qf(e){try{let t=new URL(e);return aa(t.hostname)}catch{return!1}}function $f(e){return Wi(e)}function ep(e){try{let t=new URL(e);if(t.protocol!==`http:`||!Qf(t.toString())&&!$f(t.hostname)||!t.port)return null;let n=Number(t.port);return Number.isInteger(n)&&n>0&&n<=65535?n:null}catch{return null}}function tp(e){let t=e.replace(/[.,;!?]+$/u,``);for(;t.endsWith(`)`)||t.endsWith(`]`)||t.endsWith(`}`);){let e=t.at(-1);if(!e)break;let n=e===`)`?`(`:e===`]`?`[`:`{`;if(t.split(n).length-1>=t.split(e).length-1)break;t=t.slice(0,-1)}return t}function np(e){return e.replace(Jf,``).replaceAll(/./gsu,e=>rp(e)?``:e).replace(Yf,`$1$2`)}function rp(e){let t=e.charCodeAt(0);return t>=0&&t<=8||t===11||t===12||t>=14&&t<=31||t===127}function ip(e){let t=null,n=null,r=np(e);qf.lastIndex=0;for(let e of r.matchAll(qf)){let r=Xf(tp(e[0]));!r||!ep(r)||(t=r,Qf(r)&&(n=r))}return n??t}function ap(e){let t=null;for(let n of e){let e=n.event,r=ip(e.type===`output`?e.data:e.type===`started`||e.type===`restarted`?e.snapshot.history:``);r&&(t=r)}return t}function op(e){switch(e.type){case`activity`:return e.hasRunningSubprocess;case`started`:case`restarted`:case`exited`:return!1;default:return null}}var sp=`full-access`,cp=`default`,lp=`default`,up=`forge:terminal-state:v1`,dp=[],fp=200,pp=8;function mp(e,t){if(t<=3&&e&&typeof e==`object`){let t=e;return{terminalStateByThreadKey:jp(t.terminalStateByThreadKey??{}),terminalPreviewUrlByThreadKey:Object.fromEntries(Object.entries(t.terminalPreviewUrlByThreadKey??{}).filter(([e,t])=>!!hn(e)&&typeof t?.url==`string`&&!!ep(t.url)&&typeof t?.observedAt==`string`))}}return{terminalStateByThreadKey:{},terminalPreviewUrlByThreadKey:{}}}function hp(){return _n(typeof window<`u`?window.localStorage:void 0)}function gp(e){let t=[...new Set(e.map(e=>e.trim()).filter(e=>e.length>0))];return t.length>0?t:[lp]}function _p(e,t){if(e.length===0)return[];let n=new Set(t);return[...new Set(e)].map(e=>e.trim()).filter(e=>e.length>0&&n.has(e))}function vp(e){return`group-${e}`}function yp(e,t){let n=e,r=2;for(;t.has(n);)n=`${e}-${r}`,r+=1;return t.add(n),n}function bp(e,t){return e.findIndex(e=>e.terminalIds.includes(t))}function xp(e){return[...new Set(e.map(e=>e.trim()).filter(e=>e.length>0))]}function Sp(e,t){let n=new Set(t),r=new Set,i=[],a=new Set;for(let t of e){let e=xp(t.terminalIds).filter(e=>!(!n.has(e)||r.has(e)));if(e.length===0)continue;for(let t of e)r.add(t);let o=t.id.trim().length>0?t.id.trim():vp(e[0]??`default`);i.push({id:yp(o,a),terminalIds:e})}for(let e of t)r.has(e)||i.push({id:yp(vp(e),a),terminalIds:[e]});return i.length===0?[{id:vp(lp),terminalIds:[lp]}]:i}function Cp(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1)if(e[n]!==t[n])return!1;return!0}function wp(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1){let r=e[n],i=t[n];if(!r||!i||r.id!==i.id||!Cp(r.terminalIds,i.terminalIds))return!1}return!0}function Tp(e,t){return e.terminalOpen===t.terminalOpen&&e.terminalHeight===t.terminalHeight&&e.activeTerminalId===t.activeTerminalId&&e.activeTerminalGroupId===t.activeTerminalGroupId&&Cp(e.terminalIds,t.terminalIds)&&Cp(e.runningTerminalIds,t.runningTerminalIds)&&wp(e.terminalGroups,t.terminalGroups)}var Ep=Object.freeze({terminalOpen:!1,terminalHeight:280,terminalIds:[lp],runningTerminalIds:[],activeTerminalId:lp,terminalGroups:[{id:vp(lp),terminalIds:[lp]}],activeTerminalGroupId:vp(lp)});function Dp(){return{...Ep,terminalIds:[...Ep.terminalIds],runningTerminalIds:[...Ep.runningTerminalIds],terminalGroups:Hp(Ep.terminalGroups)}}function Op(){return Ep}function kp(e){let t=gp(e.terminalIds),n=t.length>0?t:[lp],r=_p(e.runningTerminalIds,n),i=n.includes(e.activeTerminalId)?e.activeTerminalId:n[0]??`default`,a=Sp(e.terminalGroups,n),o=a.some(t=>t.id===e.activeTerminalGroupId)?e.activeTerminalGroupId:null,s=a.find(e=>e.terminalIds.includes(i))?.id??null,c={terminalOpen:e.terminalOpen,terminalHeight:Number.isFinite(e.terminalHeight)&&e.terminalHeight>0?e.terminalHeight:280,terminalIds:n,runningTerminalIds:r,activeTerminalId:i,terminalGroups:a,activeTerminalGroupId:o??s??a[0]?.id??vp(`default`)};return Tp(e,c)?e:c}function Ap(e){let t=kp(e);if(t.terminalIds.length<=pp)return t;let n=new Set,r=e=>{!e||n.size>=pp||t.terminalIds.includes(e)&&n.add(e)};r(lp),r(t.activeTerminalId);for(let e of t.runningTerminalIds)r(e);for(let e of t.terminalIds.toReversed())r(e);let i=t.terminalIds.filter(e=>n.has(e)),a=i[i.length-1]??i[0]??`default`,o=i.includes(t.activeTerminalId)?t.activeTerminalId:a;return kp({...t,terminalIds:i.length>0?i:[lp],runningTerminalIds:t.runningTerminalIds.filter(e=>n.has(e)),activeTerminalId:o,terminalGroups:t.terminalGroups.map(e=>({id:e.id,terminalIds:e.terminalIds.filter(e=>n.has(e))})).filter(e=>e.terminalIds.length>0)})}function jp(e){return Object.fromEntries(Object.entries(e).flatMap(([e,t])=>hn(e)?[[e,Ap(t)]]:[]))}function Mp(e){return Tp(kp(e),Ep)}function Np(e){return e.trim().length>0}function Pp(e){return Ln(e)}function Fp(e,t){return`${Pp(e)}\u0000${t}`}function Ip(e,t){return Fp(e,t)}function Lp(e){let t=Date.parse(e);return Number.isFinite(t)?t:0}function Rp(e,t){let n=ip(e);return n?{url:n,observedAt:t}:null}function zp(e){return Rp(e.history,e.updatedAt)}function Bp(e){return e.type===`output`?Rp(e.data,e.createdAt):e.type===`started`||e.type===`restarted`?Rp(e.snapshot.history,e.snapshot.updatedAt):null}function Vp(e,t,n){if(!n)return e;let r=Pp(t),i=e[r];return i&&Lp(i.observedAt)>Lp(n.observedAt)||i?.url===n.url&&i.observedAt===n.observedAt?e:{...e,[r]:n}}function Hp(e){return e.map(e=>({id:e.id,terminalIds:[...e.terminalIds]}))}function Up(e,t,n,r){let i=Fp(n,r.terminalId),a=e[i]??dp,o={id:t,event:r},s=a.length>=fp?[...a.slice(1),o]:[...a,o];return{terminalEventEntriesByKey:{...e,[i]:s},nextTerminalEventId:t+1}}function Wp(e,t,n,r){let i=Fp(n,r.terminalId);return{terminalEventEntriesByKey:{...e,[i]:[{id:t,event:r}]},nextTerminalEventId:t+1}}function Gp(e){return e.sessionEpoch&&e.sequence!==void 0?{sessionEpoch:e.sessionEpoch,sequence:e.sequence}:null}function Kp(e,t,n){return!t||!e?!1:t.sessionEpoch===e.sessionEpoch?n?t.sequence<e.sequence:t.sequence<=e.sequence:!n}function qp(e,t){let n={...e},r=!1;for(let e of Object.keys(n))e.startsWith(`${t}\u0000`)&&(delete n[e],r=!0);return r?n:e}function Jp(e){return{terminalId:e.terminalId,cwd:e.snapshot.cwd,worktreePath:e.snapshot.worktreePath}}function Yp(e,t){let n=Jp(t);return e?.runtimeEnv&&e.cwd===n.cwd&&e.worktreePath===n.worktreePath&&(e.terminalId===void 0||e.terminalId===t.terminalId)?{...n,runtimeEnv:e.runtimeEnv}:n}function Xp(e,t,n){let r=kp(e);if(!Np(t))return r;let i=!r.terminalIds.includes(t),a=i?[...r.terminalIds,t]:r.terminalIds,o=Hp(r.terminalGroups),s=bp(o,t);if(s>=0&&(o[s].terminalIds=o[s].terminalIds.filter(e=>e!==t),o[s].terminalIds.length===0&&o.splice(s,1)),n===`new`){let e=new Set(o.map(e=>e.id)),n=yp(vp(t),e);return o.push({id:n,terminalIds:[t]}),kp({...r,terminalOpen:!0,terminalIds:a,activeTerminalId:t,terminalGroups:o,activeTerminalGroupId:n})}let c=o.findIndex(e=>e.id===r.activeTerminalGroupId);if(c<0&&(c=bp(o,r.activeTerminalId)),c<0){let e=new Set(o.map(e=>e.id)),t=yp(vp(r.activeTerminalId),e);o.push({id:t,terminalIds:[r.activeTerminalId]}),c=o.length-1}let l=o[c];if(!l||i&&!l.terminalIds.includes(t)&&l.terminalIds.length>=4)return r;if(!l.terminalIds.includes(t)){let e=l.terminalIds.indexOf(r.activeTerminalId);e>=0?l.terminalIds.splice(e+1,0,t):l.terminalIds.push(t)}return kp({...r,terminalOpen:!0,terminalIds:a,activeTerminalId:t,terminalGroups:o,activeTerminalGroupId:l.id})}function Zp(e,t){let n=kp(e);return n.terminalOpen===t?n:{...n,terminalOpen:t}}function Qp(e,t){let n=kp(e);return!Number.isFinite(t)||t<=0||n.terminalHeight===t?n:{...n,terminalHeight:t}}function $p(e,t){return Xp(e,t,`split`)}function em(e,t,n){let r=Xp(e,t,`new`);return n?.openDrawer===!1?{...r,terminalOpen:e.terminalOpen}:r}function tm(e,t){let n=kp(e);if(!n.terminalIds.includes(t))return n;let r=n.terminalGroups.find(e=>e.terminalIds.includes(t))?.id??n.activeTerminalGroupId;return n.activeTerminalId===t&&n.activeTerminalGroupId===r?n:{...n,activeTerminalId:t,activeTerminalGroupId:r}}function nm(e,t){let n=kp(e);if(!n.terminalIds.includes(t))return n;let r=n.terminalIds.filter(e=>e!==t);if(r.length===0)return Dp();let i=n.terminalIds.indexOf(t),a=n.activeTerminalId===t?r[Math.min(i,r.length-1)]??r[0]??`default`:n.activeTerminalId,o=n.terminalGroups.map(e=>({...e,terminalIds:e.terminalIds.filter(e=>e!==t)})).filter(e=>e.terminalIds.length>0),s=o.find(e=>e.terminalIds.includes(a))?.id??o[0]?.id??vp(a);return kp({terminalOpen:n.terminalOpen,terminalHeight:n.terminalHeight,terminalIds:r,runningTerminalIds:n.runningTerminalIds.filter(e=>e!==t),activeTerminalId:a,terminalGroups:o,activeTerminalGroupId:s})}function rm(e,t,n){let r=kp(e);if(!r.terminalIds.includes(t)||n===r.runningTerminalIds.includes(t))return r;let i=new Set(r.runningTerminalIds);return n?i.add(t):i.delete(t),{...r,runningTerminalIds:[...i]}}function im(e,t){return!t||t.threadId.length===0?Op():e[Pp(t)]??Op()}function am(e,t,n){if(t.threadId.length===0)return e;let r=Pp(t),i=im(e,t),a=n(i);if(a===i)return e;if(Mp(a)){if(e[r]===void 0)return e;let{[r]:t,...n}=e;return n}return{...e,[r]:a}}function om(e,t,n){return!t||t.threadId.length===0||n.trim().length===0?dp:e[Fp(t,n)]??dp}function sm(e,t,n){return!t||t.threadId.length===0||n.trim().length===0?null:e[Ip(t,n)]??null}function cm(e,t){if(!t||t.threadId.length===0)return[];let n=`${Pp(t)}\u0000`;return Object.entries(e).filter(([e])=>e.startsWith(n)).map(([,e])=>e)}function lm(e,t){return!t||t.threadId.length===0?null:e[Pp(t)]??null}var um=wa()(Gf(e=>{let t=(t,n)=>{e(e=>{let r=am(e.terminalStateByThreadKey,t,n);return r===e.terminalStateByThreadKey?e:{terminalStateByThreadKey:r}})};return{terminalStateByThreadKey:{},terminalLaunchContextByThreadKey:{},terminalEventEntriesByKey:{},terminalSessionSnapshotByKey:{},terminalStreamCursorByKey:{},terminalPreviewUrlByThreadKey:{},nextTerminalEventId:1,setTerminalOpen:(e,n)=>t(e,e=>Zp(e,n)),setTerminalHeight:(e,n)=>t(e,e=>Qp(e,n)),splitTerminal:(e,n)=>t(e,e=>$p(e,n)),newTerminal:(e,n,r)=>t(e,e=>em(e,n,r)),ensureTerminal:(e,n,r)=>t(e,e=>{let t=e;return e.terminalIds.includes(n)||(t=em(t,n)),r?.active===!1&&(t={...t,activeTerminalId:e.activeTerminalId,activeTerminalGroupId:e.activeTerminalGroupId}),(r?.active??!0)&&(t=tm(t,n)),r?.open&&(t=Zp(t,!0)),kp(t)}),setActiveTerminal:(e,n)=>t(e,e=>tm(e,n)),closeTerminal:(e,n)=>t(e,e=>nm(e,n)),setTerminalLaunchContext:(t,n)=>e(e=>({terminalLaunchContextByThreadKey:{...e.terminalLaunchContextByThreadKey,[Pp(t)]:n}})),clearTerminalLaunchContext:t=>e(e=>{let n=Pp(t);if(!e.terminalLaunchContextByThreadKey[n])return e;let{[n]:r,...i}=e.terminalLaunchContextByThreadKey;return{terminalLaunchContextByThreadKey:i}}),setTerminalActivity:(e,n,r)=>t(e,e=>rm(e,n,r)),recordTerminalEvent:(t,n)=>e(e=>{let r=Ip(t,n.terminalId),i=Gp(n),a=n.type===`started`||n.type===`restarted`;if(Kp(e.terminalStreamCursorByKey[r],i,a))return e;let o=a&&i?Wp(e.terminalEventEntriesByKey,e.nextTerminalEventId,t,n):Up(e.terminalEventEntriesByKey,e.nextTerminalEventId,t,n),s=i?{...e.terminalStreamCursorByKey,[r]:i}:e.terminalStreamCursorByKey,c=Vp(e.terminalPreviewUrlByThreadKey,t,Bp(n));return n.type!==`started`&&n.type!==`restarted`?{...o,terminalStreamCursorByKey:s,terminalPreviewUrlByThreadKey:c}:{...o,terminalStreamCursorByKey:s,terminalPreviewUrlByThreadKey:c,terminalSessionSnapshotByKey:{...e.terminalSessionSnapshotByKey,[Ip(t,n.terminalId)]:n.snapshot}}}),applyTerminalEvent:(t,n)=>e(e=>{let r=Pp(t),i=Ip(t,n.terminalId),a=Gp(n),o=n.type===`started`||n.type===`restarted`;if(Kp(e.terminalStreamCursorByKey[i],a,o))return e;let s=e.terminalStateByThreadKey,c=e.terminalLaunchContextByThreadKey,l=e.terminalSessionSnapshotByKey,u=Vp(e.terminalPreviewUrlByThreadKey,t,Bp(n));(n.type===`started`||n.type===`restarted`)&&(l={...l,[Ip(t,n.terminalId)]:n.snapshot},s=am(s,t,e=>{let t=e.activeTerminalId===n.terminalId,r=e;return e.terminalIds.includes(n.terminalId)||(r=em(r,n.terminalId)),t?(r=tm(r,n.terminalId),r=Zp(r,!0)):(r=tm(r,e.activeTerminalId),r=Zp(r,e.terminalOpen)),kp(r)}),c={...c,[r]:Yp(c[r],n)});let d=op(n);d!==null&&(s=am(s,t,e=>rm(e,n.terminalId,d)));let f=o&&a?Wp(e.terminalEventEntriesByKey,e.nextTerminalEventId,t,n):Up(e.terminalEventEntriesByKey,e.nextTerminalEventId,t,n),p=a?{...e.terminalStreamCursorByKey,[i]:a}:e.terminalStreamCursorByKey;return{terminalStateByThreadKey:s,terminalLaunchContextByThreadKey:c,terminalSessionSnapshotByKey:l,terminalStreamCursorByKey:p,terminalPreviewUrlByThreadKey:u,...f}}),setTerminalSessionSnapshot:(t,n)=>e(e=>({terminalSessionSnapshotByKey:{...e.terminalSessionSnapshotByKey,[Ip(t,n.terminalId)]:n},terminalPreviewUrlByThreadKey:Vp(e.terminalPreviewUrlByThreadKey,t,zp(n))})),clearTerminalState:t=>e(e=>{let n=Pp(t),r=am(e.terminalStateByThreadKey,t,()=>Dp()),i=e.terminalLaunchContextByThreadKey[n]!==void 0,a=e.terminalPreviewUrlByThreadKey[n]!==void 0,{[n]:o,...s}=e.terminalLaunchContextByThreadKey,{[n]:c,...l}=e.terminalPreviewUrlByThreadKey,u={...e.terminalEventEntriesByKey},d=!1;for(let e of Object.keys(u))e.startsWith(`${n}\u0000`)&&(delete u[e],d=!0);let f={...e.terminalSessionSnapshotByKey},p=!1;for(let e of Object.keys(f))e.startsWith(`${n}\u0000`)&&(delete f[e],p=!0);let m=qp(e.terminalStreamCursorByKey,n);return r===e.terminalStateByThreadKey&&!i&&!a&&!d&&!p&&m===e.terminalStreamCursorByKey?e:{terminalStateByThreadKey:r,terminalLaunchContextByThreadKey:s,terminalPreviewUrlByThreadKey:l,terminalEventEntriesByKey:u,terminalSessionSnapshotByKey:f,terminalStreamCursorByKey:m}}),removeTerminalState:t=>e(e=>{let n=Pp(t),r=e.terminalStateByThreadKey[n]!==void 0,i=e.terminalLaunchContextByThreadKey[n]!==void 0,a=e.terminalPreviewUrlByThreadKey[n]!==void 0,o={...e.terminalEventEntriesByKey},s=!1;for(let e of Object.keys(o))e.startsWith(`${n}\u0000`)&&(delete o[e],s=!0);let c={...e.terminalSessionSnapshotByKey},l=!1;for(let e of Object.keys(c))e.startsWith(`${n}\u0000`)&&(delete c[e],l=!0);let u=qp(e.terminalStreamCursorByKey,n);if(!r&&!i&&!a&&!s&&!l&&u===e.terminalStreamCursorByKey)return e;let d={...e.terminalStateByThreadKey};delete d[n];let f={...e.terminalLaunchContextByThreadKey};delete f[n];let p={...e.terminalPreviewUrlByThreadKey};return delete p[n],{terminalStateByThreadKey:d,terminalLaunchContextByThreadKey:f,terminalPreviewUrlByThreadKey:p,terminalEventEntriesByKey:o,terminalSessionSnapshotByKey:c,terminalStreamCursorByKey:u}}),removeOrphanedTerminalStates:t=>e(e=>{let n=Object.keys(e.terminalStateByThreadKey).filter(e=>!t.has(e)),r=Object.keys(e.terminalLaunchContextByThreadKey).filter(e=>!t.has(e)),i=Object.keys(e.terminalPreviewUrlByThreadKey).filter(e=>!t.has(e)),a={...e.terminalEventEntriesByKey},o=!1;for(let e of Object.keys(a)){let[n]=e.split(`\0`);n&&!t.has(n)&&(delete a[e],o=!0)}let s={...e.terminalSessionSnapshotByKey},c=!1;for(let e of Object.keys(s)){let[n]=e.split(`\0`);n&&!t.has(n)&&(delete s[e],c=!0)}let l={...e.terminalStreamCursorByKey},u=!1;for(let e of Object.keys(l)){let[n]=e.split(`\0`);n&&!t.has(n)&&(delete l[e],u=!0)}if(n.length===0&&r.length===0&&i.length===0&&!o&&!c&&!u)return e;let d={...e.terminalStateByThreadKey};for(let e of n)delete d[e];let f={...e.terminalLaunchContextByThreadKey};for(let e of r)delete f[e];let p={...e.terminalPreviewUrlByThreadKey};for(let e of i)delete p[e];return{terminalStateByThreadKey:d,terminalLaunchContextByThreadKey:f,terminalPreviewUrlByThreadKey:p,terminalEventEntriesByKey:a,terminalSessionSnapshotByKey:s,terminalStreamCursorByKey:l}})}},{name:up,version:4,storage:Uf(hp),migrate:mp,partialize:e=>({terminalStateByThreadKey:jp(e.terminalStateByThreadKey),terminalPreviewUrlByThreadKey:e.terminalPreviewUrlByThreadKey})}));function dm(e){return!!(e.prompt.trim()||e.images.length||e.terminalContexts.length||e.persistedAttachments.length||e.stagedSubmission)}function fm(e,t,n){let r=Ln(t),i=Ln(n);if(r===i)return e;let a=e[r];if(!a)return e;let o=e[i];if(o&&dm(o)&&!pm(a,o))return null;let s={...e,[i]:{...a,...Tm(a,o)}};return delete s[r],s}function pm(e,t){let n=e.stagedSubmission;return!n||!mm(n)||!hm(e,n)||!gm(n,t.stagedSubmission)?!1:_m(e,t)}function mm(e){return!!e.commandId&&!!e.messageId}function hm(e,t){return[e.prompt===t.prompt,xm(e.persistedAttachments,t.attachments),xm(e.terminalContexts,t.terminalContexts)].every(Boolean)}function gm(e,t){return!t||vm(e,t)}function _m(e,t){return[e.prompt===t.prompt,e.lastGeneratedPullRequestPrompt===t.lastGeneratedPullRequestPrompt,Cm(e.images,t.images),Sm(e.nonPersistedImageIds,t.nonPersistedImageIds),e.nonPersistedImageIds.length===0,Cm(e.persistedAttachments,t.persistedAttachments),Cm(e.terminalContexts,t.terminalContexts),wm(e.modelSelectionByProvider,t.modelSelectionByProvider),e.activeProvider===t.activeProvider,e.runtimeMode===t.runtimeMode,e.interactionMode===t.interactionMode].every(Boolean)}function vm(e,t){return[e.commandId===t.commandId&&e.messageId===t.messageId,e.prompt===t.prompt,xm(e.attachments,t.attachments),xm(e.terminalContexts,t.terminalContexts),ym(e.modelSelection,t.modelSelection),ym(e.runtimeMode,t.runtimeMode),ym(e.interactionMode,t.interactionMode),bm(e.executionIntent,t.executionIntent)].every(Boolean)}function ym(e,t){return e===void 0||t===void 0||JSON.stringify(e)===JSON.stringify(t)}function bm(e,t){return!e||!t||e.runtimeId===t.runtimeId}function xm(e,t){return e.length===t.length&&e.every((e,n)=>e.id===t[n]?.id)}function Sm(e,t){return e.length===t.length&&e.every((e,n)=>e===t[n])}function Cm(e,t){return e.length===t.length&&e.every((e,n)=>JSON.stringify(e)===JSON.stringify(t[n]))}function wm(e,t){let n=Object.keys(e).toSorted();return Sm(n,Object.keys(t).toSorted())?n.every(n=>JSON.stringify(e[n])===JSON.stringify(t[n])):!1}function Tm(e,t){let n=t??e,r=e.stagedSubmission?e:n,i=e.stagedSubmission?n:e;return{modelSelectionByProvider:{...i.modelSelectionByProvider,...r.modelSelectionByProvider},activeProvider:r.activeProvider??i.activeProvider,runtimeMode:r.runtimeMode??i.runtimeMode,interactionMode:r.interactionMode??i.interactionMode}}var Em=/\n*<terminal_context>\n([\s\S]*?)\n<\/terminal_context>\s*$/,Dm=/^\s*<cmmd_context>\n?([\s\S]*?)\n?<\/cmmd_context>\s*/;function Om(e){return e.replace(/\r\n/g,`
|
|
8
|
+
`).replace(/^\n+|\n+$/g,``)}function km(e){return Om(e.text).length>0}function Am(e){return!km(e)}function jm(e){return e.filter(e=>km(e))}function Mm(e){let t=Om(e.text),n=e.terminalId.trim(),r=e.terminalLabel.trim();if(t.length===0||n.length===0||r.length===0)return null;let i=Math.max(1,Math.floor(e.lineStart));return{terminalId:n,terminalLabel:r,lineStart:i,lineEnd:Math.max(i,Math.floor(e.lineEnd)),text:t}}function Nm(e){return e.lineStart===e.lineEnd?`line ${e.lineStart}`:`lines ${e.lineStart}-${e.lineEnd}`}function Pm(e){return`${e.terminalLabel} ${Nm(e)}`}function Fm(e){return`@${e.terminalLabel.trim().toLowerCase().replace(/\s+/g,`-`)}:${e.lineStart===e.lineEnd?`${e.lineStart}`:`${e.lineStart}-${e.lineEnd}`}`}function Im(e){return Om(e.text).split(`
|
|
9
|
+
`).map((t,n)=>` ${e.lineStart+n} | ${t}`)}function Lm(e){let t=e.map(e=>Mm(e)).filter(e=>e!==null);if(t.length===0)return``;let n=[];for(let e=0;e<t.length;e+=1){let r=t[e];n.push(`- ${Pm(r)}:`),n.push(...Im(r)),e<t.length-1&&n.push(``)}return[`<terminal_context>`,...n,`</terminal_context>`].join(`
|
|
10
|
+
`)}function Rm(e,t){let n=0,r=``;for(let i of e){if(i!==``){r+=i;continue}let e=t[n]??null;n+=1,e&&(r+=Fm(e))}return r}function zm(e,t){let n=Rm(e,t).trim(),r=Lm(t);return r.length===0?n:n.length>0?`${n}\n\n${r}`:r}function Bm(e){let t=Em.exec(e);if(!t)return{promptText:e,contextCount:0,previewTitle:null,contexts:[]};let n=e.slice(0,t.index).replace(/\n+$/,``),r=Um(t[1]??``);return{promptText:n,contextCount:r.length,previewTitle:r.length>0?r.map(({header:e,body:t})=>t.length>0?`${e}\n${t}`:e).join(`
|
|
11
11
|
|
|
12
|
-
`):null,contexts:r}}function
|
|
12
|
+
`):null,contexts:r}}function Vm(e){let t=Dm.exec(e);if(!t)return{promptText:e,cmmdContext:null};let n=(t[1]??``).trim();return{promptText:e.slice(t[0].length).replace(/^\n+/,``),cmmdContext:n.length>0?{body:n}:null}}function Hm(e){let t=Vm(e),n=Bm(t.promptText);return{visibleText:n.promptText,copyText:e,contextCount:n.contextCount,previewTitle:n.previewTitle,contexts:n.contexts,cmmdContext:t.cmmdContext}}function Um(e){let t=[],n=null,r=()=>{n&&=(t.push({header:n.header,body:n.bodyLines.join(`
|
|
13
13
|
`).trimEnd()}),null)};for(let t of e.split(`
|
|
14
|
-
`)){let e=/^- (.+):$/.exec(t);if(e){r(),n={header:e[1],bodyLines:[]};continue}if(n){if(t.startsWith(` `)){n.bodyLines.push(t.slice(2));continue}t.length===0&&n.bodyLines.push(``)}}return r(),t}function
|
|
15
|
-
`||e===` `||e===`\r`}function Km(e,t){let n=Math.max(0,Math.min(e.length,Math.floor(t))),r=`${Gm(e[n-1])?``:` `} `,i=e[n]===` `?n+1:n;return{prompt:`${e.slice(0,n)}${r}${e.slice(i)}`,cursor:n+r.length,contextIndex:Um(e.slice(0,n))}}function qm(e){return e.replaceAll(``,``)}function Jm(e,t){if(t<0)return{prompt:e,cursor:e.length};let n=0;for(let r=0;r<e.length;r+=1)if(e[r]===``){if(n===t)return{prompt:e.slice(0,r)+e.slice(r+1),cursor:r};n+=1}return{prompt:e,cursor:e.length}}var Ym=e=>Symbol.iterator in e,Xm=e=>`entries`in e,Zm=(e,t)=>{let n=e instanceof Map?e:new Map(e.entries()),r=t instanceof Map?t:new Map(t.entries());if(n.size!==r.size)return!1;for(let[e,t]of n)if(!r.has(e)||!Object.is(t,r.get(e)))return!1;return!0},Qm=(e,t)=>{let n=e[Symbol.iterator](),r=t[Symbol.iterator](),i=n.next(),a=r.next();for(;!i.done&&!a.done;){if(!Object.is(i.value,a.value))return!1;i=n.next(),a=r.next()}return!!i.done&&!!a.done};function $m(e,t){return Object.is(e,t)?!0:typeof e!=`object`||!e||typeof t!=`object`||!t||Object.getPrototypeOf(e)!==Object.getPrototypeOf(t)?!1:Ym(e)&&Ym(t)?Xm(e)&&Xm(t)?Zm(e,t):Qm(e,t):Zm({entries:()=>Object.entries(e)},{entries:()=>Object.entries(t)})}function eh(e){let t=O.useRef(void 0);return n=>{let r=e(n);return $m(t.current,r)?t.current:t.current=r}}var th=[`draftsByThreadKey`,`draftThreadsByThreadKey`,`logicalProjectDraftThreadKeyByLogicalProjectKey`],nh=[`stickyModelSelectionByProvider`,`stickyActiveProvider`];function rh(e){let t=ah(e.nextLocal,e.version,!1);if(!t)return e.currentStored??e.nextLocal;if(e.currentStored!==null&&e.canMigrate!==void 0&&!e.canMigrate(e.currentStored,e.version))return e.currentStored;if(e.previousLocal===e.currentStored&&(e.canMigrate??ih)(e.currentStored,e.version))return e.nextLocal;let n=ah(e.previousLocal,e.version,!0),r=ah(e.currentStored,e.version,!0);if(!r||!n)return e.currentStored??e.nextLocal;let i={...r.state};for(let e of th)i[e]=lh(n.state[e],r.state[e],t.state[e]);for(let e of nh)uh(n.state[e],t.state[e])||(i[e]=t.state[e]);return JSON.stringify({...r,version:e.version,state:i})}function ih(e,t){if(e===null)return!0;try{let n=JSON.parse(e);return!dh(n)||!dh(n.state)||typeof n.version!=`number`||!Number.isInteger(n.version)?!1:n.version>=1&&n.version<t}catch{return!1}}function ah(e,t,n){if(e===null)return n?{version:t,state:ch()}:null;let r=oh(e);return r&&sh(r,t)?{version:t,state:r.state}:null}function oh(e){try{let t=JSON.parse(e);return dh(t)?t:null}catch{return null}}function sh(e,t){let n=e.state;return e.version!==t||!dh(n)?!1:th.every(e=>dh(n[e]))}function ch(){return Object.fromEntries(th.map(e=>[e,{}]))}function lh(e,t,n){let r={...t};for(let t of new Set([...Object.keys(e),...Object.keys(n)]))uh(e[t],n[t])||(t in n?r[t]=n[t]:delete r[t]);return r}function uh(e,t){return JSON.stringify(e)===JSON.stringify(t)}function dh(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function fh(e){let t;return{getItem:n=>{let r=e.storage.getItem(n);return t===void 0&&(t=r),r},setItem:(n,r)=>{let i=e.storage.getItem(n),a=rh({previousLocal:t??null,currentStored:i,nextLocal:r,version:e.version,...e.canMigrate===void 0?{}:{canMigrate:e.canMigrate}});(a!==i||i===r)&&(e.storage.setItem(n,a),t=r)},removeItem:n=>{e.storage.removeItem(n),t=null}}}function ph(e){let t=e.auth.status!==`unauthenticated`||e.auth.provenance?.credentialScope===`proxied`;return e.enabled&&e.installed&&e.status===`ready`&&t&&e.models.length>0}var mh={providers:{codex:!0,claude:!1,cmmd:!0},meteredEgressApproved:{codex:!1,claude:!1,cmmd:!1},allowedWallets:[`personal`],updatedAt:`1970-01-01T00:00:00.000Z`};function hh(e){if(e==null)return mh;let t=e.providers,n=e.meteredEgressApproved,r=e.allowedWallets;return{providers:{...mh.providers,...t},meteredEgressApproved:{...mh.meteredEgressApproved,...n},allowedWallets:Array.isArray(r)&&r.length>0?r:mh.allowedWallets,updatedAt:typeof e.updatedAt==`string`?e.updatedAt:mh.updatedAt}}function gh(e){switch(e){case`codex`:return`codex`;case`claudeAgent`:return`claude`;case`cmmd`:case`apex`:return`cmmd`;default:return null}}var _h=[`codex`,`claudeAgent`,`cmmd`];function vh(e,t){if(t==null)return null;let n=t.providers;if(typeof n!=`object`||!n)return null;let r=n[e];return typeof r==`boolean`?r:null}function yh(e,t){let n=gh(e);if(n===null)return{offered:!1,reason:`unknown-provider`};let r=vh(n,t);return r===!0?{offered:!0}:r===!1?{offered:!1,reason:`org-disabled`}:hh(t).providers[n]===!0?{offered:!0}:{offered:!1,reason:`policy-unavailable`}}function bh(e,t){return yh(e,t).offered}function xh(e,t){return Sh(e,t).offered}function Sh(e,t){return t===null?{offered:!0}:yh(e,t)}function Ch(e,t){return hh(t).allowedWallets.includes(e)}function wh(e){return Ch(`personal`,e)}function Th(e){return e===`claudeAgent`||e===`codex`}function Eh(e,t){return e!==`claudeAgent`||wh(t)||bh(`claudeAgent`,t)}function Dh(e){return e.isDebugDisclosureEnabled||Th(e.provider)&&wh(e.policy)?!1:!bh(e.provider===`apex`?`apex`:e.provider,e.policy)}function Oh(e){if(!Ph(e)||!Array.isArray(e.accounts))throw Error(`CMMD returned invalid provider accounts.`);return{accounts:e.accounts.filter(kh)}}function kh(e){return Ph(e)?jh(e.provider)&&Mh(e.providerAccountId)&&Ah(e)&&Nh(e.accountEmail)&&Nh(e.accountDisplayName)&&Nh(e.planType)&&typeof e.isDefault==`boolean`&&typeof e.needsReconnect==`boolean`:!1}function Ah(e){return(e.credentialTarget===`primary`||e.credentialTarget===`linked`)&&Array.isArray(e.legacyProviderAccountIds)&&e.legacyProviderAccountIds.every(Mh)}function jh(e){return e===`codex`||e===`claudeAgent`}function Mh(e){return typeof e==`string`&&e.trim().length>0}function Nh(e){return typeof e==`string`||e===null}function Ph(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Fh(e){let t=vr(e);return t.legacyRuntimeId===null?t.shape===`durable-environment`&&typeof e==`string`?e:null:t.legacyRuntimeId}var Ih=class extends Error{constructor(e){super(e===`auth`?`Your CMMD session expired. Sign in again to verify Claude runtime readiness.`:`CMMD denied access to verify Claude runtime readiness. Check your organization permissions.`),this.name=`ForgeProviderAccessAuthorityError`}};async function Lh(e){if(!e.enabled||e.readinessTargetId===null)return null;try{return Bh(await e.load(e.readinessTargetId),e.readinessTargetId)}catch(e){if(e instanceof Ta&&(e.kind===`auth`||e.kind===`permission`))throw new Ih(e.kind);return null}}var Rh=new Set([`not_connected`,`pending`,`claimed`,`activating`,`applied`,`failed`,`stale`]),zh=[`generationId`,`nativeVerifiedAt`,`reason`,`lastErrorCode`,`lastErrorMessage`];function Bh(e,t){if(!Jh(e)||!Kh(e)||!Vh(e,t))throw Error(`CMMD returned invalid Claude runtime readiness.`);return e}function Vh(e,t){if(e.deliveryReceipt===null)return e.nativeExecutable!==!0;if(!Jh(e.deliveryReceipt))return!1;let n=e.deliveryReceipt,r=Jh(n.identity)?n.identity:null;return r!==null&&Hh(n,t)&&Gh(r,e.generationId)}function Hh(e,t){return Uh(e,t)&&Wh(e)}function Uh(e,t){return typeof e.receiptId==`string`&&e.receiptId.trim().length>0&&e.runtimeId===t&&typeof e.machineId==`string`&&e.machineId.trim().length>0&&typeof e.credentialEpoch==`number`&&Number.isSafeInteger(e.credentialEpoch)&&e.credentialEpoch>=0}function Wh(e){return typeof e.issuedAt==`string`&&Number.isFinite(Date.parse(e.issuedAt))&&e.expiresAt===null}function Gh(e,t){return e.kind===`credential_generation`&&e.provider===`claude`&&typeof e.credentialGenerationId==`string`&&e.credentialGenerationId===t}function Kh(e){return typeof e.connected==`boolean`&&Rh.has(String(e.deliveryStatus))&&typeof e.nativeExecutable==`boolean`&&zh.every(t=>qh(e[t]))}function qh(e){return e===null||typeof e==`string`}function Jh(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var Yh={credential_expired_refreshing:`CREDENTIAL_EXPIRED_REFRESHING`,credential_reconnect_required:`CREDENTIAL_RECONNECT_REQUIRED`,credential_not_connected:`CREDENTIAL_RECONNECT_REQUIRED`,credential_generation_not_applied:`CREDENTIAL_GENERATION_NOT_APPLIED`,runtime_unavailable:`RUNTIME_UNAVAILABLE`};function Xh(e){return typeof e!=`string`||!Object.hasOwn(Yh,e)?null:Yh[e]??null}var Zh=new Set([`pending`,`claimed`,`activating`]),Qh=2e3;function $h(e){return{readinessTargetId:e,dataUpdatedAt:0,consecutiveUnavailableResponses:0,consecutiveFailedResponses:0}}function eg(e){let t=e.current.readinessTargetId===e.readinessTargetId?e.current:$h(e.readinessTargetId);return e.dataUpdatedAt===0||e.dataUpdatedAt===t.dataUpdatedAt?t:{readinessTargetId:e.readinessTargetId,dataUpdatedAt:e.dataUpdatedAt,consecutiveUnavailableResponses:e.readinessUnavailable?t.consecutiveUnavailableResponses+1:0,consecutiveFailedResponses:e.deliveryStatus===`failed`?t.consecutiveFailedResponses+1:0}}function tg(e,t){if(!e.claudeOffered||!e.claudeConnected)return!1;let n=Xh(e.reason);return n===`CREDENTIAL_EXPIRED_REFRESHING`?!0:e.deliveryStatus===`failed`?n!==`CREDENTIAL_RECONNECT_REQUIRED`&&t.consecutiveFailedResponses<16:e.deliveryStatus===null?t.consecutiveUnavailableResponses>0&&t.consecutiveUnavailableResponses<3:Zh.has(e.deliveryStatus)}function ng(e){return e.credentialMode===`runtime`?e.provider&&ph(e.provider)?{eligible:!0}:{eligible:!1,reason:`runtime-unavailable`}:e.access.status===`loading`?{eligible:!1,reason:`access-loading`}:e.access.status===`error`?{eligible:!1,reason:`access-error`}:rg({provider:e.provider,providerKind:e.providerKind,policy:e.access.policy,personalConnections:e.access.personalConnections,personalReconnectRequired:e.access.personalReconnectRequired,claudeRuntimeReadiness:e.access.claudeRuntimeReadiness})}function rg(e){return!e.provider||!ph(e.provider)?{eligible:!1,reason:`runtime-unavailable`}:e.policy===null?{eligible:!1,reason:`access-error`}:bh(e.providerKind,e.policy)?ag({providerKind:e.providerKind,policy:e.policy,personalConnections:e.personalConnections,personalReconnectRequired:e.personalReconnectRequired,claudeRuntimeReadiness:e.claudeRuntimeReadiness,stage:`live-runtime`}):{eligible:!1,reason:`not-offered`}}function ig(e){return e.access.status===`loading`?{eligible:!1,reason:`access-loading`}:e.access.status===`error`||e.access.policy===null?{eligible:!1,reason:`access-error`}:bh(e.providerKind,e.access.policy)?ag({providerKind:e.providerKind,policy:e.access.policy,personalConnections:e.access.personalConnections,personalReconnectRequired:e.access.personalReconnectRequired,claudeRuntimeReadiness:e.access.claudeRuntimeReadiness,stage:`provisioning`}):{eligible:!1,reason:`not-offered`}}function ag(e){return e.providerKind===`cmmd`||e.providerKind===`apex`?{eligible:!0}:e.providerKind!==`codex`&&e.providerKind!==`claudeAgent`?{eligible:!1,reason:`not-offered`}:og({providerKind:e.providerKind,personalConnections:e.personalConnections,personalReconnectRequired:e.personalReconnectRequired,claudeRuntimeReadiness:e.claudeRuntimeReadiness,workspaceWalletAllowed:Ch(`workspace`,e.policy),stage:e.stage})}function og(e){return sg(e.workspaceWalletAllowed)?{eligible:!0}:cg(e.providerKind,e.personalReconnectRequired)?{eligible:!1,reason:`personal-credential-reconnect-required`}:lg(e.providerKind,e.personalConnections)?fg(e)?{eligible:!1,reason:`environment-not-running`}:ug(e)?{eligible:!0}:{eligible:!1,reason:`native-runtime-not-ready`}:{eligible:!1,reason:`personal-credential-required`}}function sg(e){return e&&!1}function cg(e,t){return e===`codex`&&t?.codex===!0}function lg(e,t){return t?.[e]===!0}function ug(e){return e.providerKind!==`claudeAgent`||e.stage===`provisioning`||pg(e.claudeRuntimeReadiness)}var dg=`runtime_unavailable`;function fg(e){return e.providerKind!==`claudeAgent`||e.stage===`provisioning`?!1:e.claudeRuntimeReadiness?.reason===dg}function pg(e){if(!mg(e))return!1;let t=e.deliveryReceipt?.identity;return t?.kind===`credential_generation`&&t.provider===`claude`&&t.credentialGenerationId===e.generationId}function mg(e){return e?.connected===!0&&e.nativeExecutable===!0&&typeof e.generationId==`string`&&e.generationId.trim().length>0}function hg(e){if(e.status!==`ready`)return!1;if(e.policy===null)return!0;let t=e.policy.providers,n=Ch(`workspace`,e.policy);return t.cmmd?!0:Ch(`personal`,e.policy)||n?t.codex&&e.personalConnections?.codex===!0||t.claude&&e.personalConnections?.claudeAgent===!0:!1}var gg={providers:{codex:!1,claude:!1,cmmd:!1},meteredEgressApproved:{codex:!1,claude:!1,cmmd:!1},allowedWallets:[`personal`],updatedAt:`1970-01-01T00:00:00.000Z`},_g=[`cmmd`,`forge-provider-access`],vg=Qh;function yg(e,t){return!(t instanceof Ih)&&e<3}function bg(e,t=null){return[..._g,e,t]}async function xg(e){e.queryClient.setQueriesData({queryKey:_g},t=>Sg(t,e.provider,e.connected)),await e.queryClient.invalidateQueries({queryKey:_g,refetchType:`all`})}function Sg(e,t,n){return e?.status!==`ready`||e.personalConnections===null?e:{...e,personalConnections:{...e.personalConnections,[t]:n},...t===`codex`?{personalReconnectRequired:{codex:!1}}:{},...t===`claudeAgent`?{claudeRuntimeReadiness:null}:{}}}async function Cg(e,t=null){if(e===`runtime`)return{status:`ready`,policy:null,personalConnections:null,providerAccounts:[],claudeRuntimeReadiness:null};let n=$n(),r=Ag(await n.getOrgProviderPolicy());Ch(`workspace`,r);let[i,a,o,s]=await Promise.all([Eg(()=>n.getProviderAccounts()),Dg({enabled:r.providers.codex,load:()=>n.getUserCodexCredential(),provider:`codex`}),Dg({enabled:r.providers.claude,load:()=>n.getUserClaudeCredential(),provider:`claudeAgent`}),Lh({enabled:r.providers.claude,readinessTargetId:t,load:e=>n.getClaudeRuntimeReadiness(e)})]),c=i.accounts.filter(e=>e.provider===`codex`?r.providers.codex:r.providers.claude),l=wg(c),u=l.codex||a.connected,d=l.claudeAgent||o.connected,f=c.some(e=>e.provider===`codex`&&e.needsReconnect)||a.reconnectRequired;return{status:`ready`,policy:r,personalConnections:{codex:u,claudeAgent:d},providerAccounts:c,...f?{personalReconnectRequired:{codex:!0}}:{},claudeRuntimeReadiness:s}}function wg(e){return{codex:e.some(e=>e.provider===`codex`&&!e.needsReconnect),claudeAgent:e.some(e=>e.provider===`claudeAgent`&&!e.needsReconnect)}}function Tg(e,t){if(e.status!==`ready`)return;let n=e.providerAccounts??[];return(n.find(e=>e.provider===t&&e.isDefault&&!e.needsReconnect)??n.find(e=>e.provider===t&&!e.needsReconnect))?.providerAccountId}async function Eg(e){try{return Oh(await e())}catch{return{accounts:[]}}}async function Dg(e){if(!e.enabled)return{connected:!1,reconnectRequired:!1};try{return Pg(await e.load(),e.provider)}catch{return{connected:!1,reconnectRequired:!1}}}function Og(e){let t=e?.policy?.providers.claude===!0,n=e?.personalConnections?.claudeAgent===!0;return{claudeOffered:t,claudeConnected:n,deliveryStatus:e?.claudeRuntimeReadiness?.deliveryStatus??null,reason:e?.claudeRuntimeReadiness?.reason??null,readinessUnavailable:t&&n&&e?.claudeRuntimeReadiness===null}}function kg(e){let t=(0,A.c)(21),n;t[0]!==e.environmentId||t[1]!==e.runtimeId?(n=e.environmentId==null?e.runtimeId??null:Fh(e.environmentId),t[0]=e.environmentId,t[1]=e.runtimeId,t[2]=n):n=t[2];let r=n,i;t[3]===r?i=t[4]:(i=$h(r),t[3]=r,t[4]=i);let a=(0,O.useRef)(i),o;t[5]!==e.credentialMode||t[6]!==r?(o=bg(e.credentialMode,r),t[5]=e.credentialMode,t[6]=r,t[7]=o):o=t[7];let s;t[8]===r?s=t[9]:(s=()=>Cg(`cmmd-cloud`,r),t[8]=r,t[9]=s);let c=e.enabled&&e.credentialMode===`cmmd-cloud`,l;t[10]===r?l=t[11]:(l=e=>{if(e.state.error instanceof Ih)return!1;let t=Og(e.state.data);return a.current=eg({current:a.current,readinessTargetId:r,dataUpdatedAt:e.state.dataUpdatedAt,readinessUnavailable:r!==null&&t.readinessUnavailable,deliveryStatus:t.deliveryStatus}),r!==null&&tg(t,a.current)?vg:!1},t[10]=r,t[11]=l);let u;t[12]!==o||t[13]!==s||t[14]!==c||t[15]!==l?(u={queryKey:o,queryFn:s,enabled:c,retry:yg,staleTime:3e4,refetchInterval:l},t[12]=o,t[13]=s,t[14]=c,t[15]=l,t[16]=u):u=t[16];let d=Bs(u);if(!e.enabled){let e;return t[17]===Symbol.for(`react.memo_cache_sentinel`)?(e={status:`loading`},t[17]=e):e=t[17],e}if(e.credentialMode===`runtime`){let e;return t[18]===Symbol.for(`react.memo_cache_sentinel`)?(e={status:`ready`,policy:null,personalConnections:null,providerAccounts:[],claudeRuntimeReadiness:null},t[18]=e):e=t[18],e}if(d.isPending){let e;return t[19]===Symbol.for(`react.memo_cache_sentinel`)?(e={status:`loading`},t[19]=e):e=t[19],e}if(d.isError||!d.data){let e;return t[20]===Symbol.for(`react.memo_cache_sentinel`)?(e={status:`error`},t[20]=e):e=t[20],e}return d.data}function Ag(e){if(!Ig(e)||!Ig(e.providers))throw Error(`CMMD returned an invalid organization provider policy.`);let{providers:t,meteredEgressApproved:n,allowedWallets:r,updatedAt:i}=e,a=Ng(r,i);if(!Mg(t)||a===null)throw Error(`CMMD returned an invalid organization provider policy.`);return{providers:{codex:t.codex,claude:t.claude,cmmd:t.cmmd},meteredEgressApproved:jg(n),allowedWallets:[...new Set(a.allowedWallets)],updatedAt:a.updatedAt}}function jg(e){return Ig(e)&&Mg(e)?{codex:e.codex,claude:e.claude,cmmd:e.cmmd}:{codex:!1,claude:!1,cmmd:!1}}function Mg(e){return typeof e.codex==`boolean`&&typeof e.claude==`boolean`&&typeof e.cmmd==`boolean`}function Ng(e,t){return Array.isArray(e)&&e.length>0&&e.every(Fg)&&typeof t==`string`&&t.trim().length>0?{allowedWallets:e,updatedAt:t}:null}function Pg(e,t){if(!Ig(e)||typeof e.connected!=`boolean`)throw Error(`CMMD returned an invalid ${t} connection state.`);if(!e.connected)return{connected:!1,reconnectRequired:!1};if(t===`codex`){if(typeof e.needsReconnect!=`boolean`)throw Error(`CMMD returned an invalid Codex connection state.`);return{connected:!e.needsReconnect,reconnectRequired:e.needsReconnect}}if(typeof e.generationId!=`string`||e.generationId.trim().length===0)throw Error(`CMMD returned an invalid Claude connection state.`);return{connected:!0,reconnectRequired:!1}}function Fg(e){return e===`personal`||e===`workspace`}function Ig(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Lg(e){return e.status===`ready`?e.policy:gg}var Rg=[`cursor`,`opencode`,`gemini`],zg={state:`usable`},Bg={state:`withheld`,reason:`unbuilt`},Vg={state:`withheld`,reason:`not-on-this-environment`};function Hg(e){return Rg.includes(e)}function Ug(e){return e===`gemini`?null:e}function Wg(e,t){if(e===void 0)return t?Vg:zg;if(e.availability===`unavailable`){let t=e.unavailableReason??`not-on-this-environment`,n=t===`not-on-this-environment`&&e.availabilityCheck===`could-not-check`?`could-not-check`:e.unavailableDetail;return n===void 0?{state:`withheld`,reason:t}:{state:`withheld`,reason:t,detail:n}}return e.availability===`available`||ph(e)||Gg(e)?zg:Vg}function Gg(e){return e.installed&&e.auth.status===`unauthenticated`&&e.auth.provenance?.credentialScope!==`proxied`}function Kg(e,t){let n=ig({providerKind:e,access:t});return n.eligible?null:qg(n.reason)}function qg(e){switch(e){case`access-loading`:return{state:`unresolved`,cause:`loading`};case`access-error`:return{state:`unresolved`,cause:`error`};case`not-offered`:return{state:`withheld`,reason:`not-offered`};case`personal-credential-required`:return{state:`withheld`,reason:`not-usable`,detail:`no-connection`};case`personal-credential-reconnect-required`:return{state:`withheld`,reason:`not-usable`,detail:`reconnect-required`};case`native-runtime-not-ready`:return{state:`withheld`,reason:`not-usable`,detail:`delivery-pending`};case`environment-not-running`:return{state:`withheld`,reason:`not-usable`,detail:`environment-not-running`};case`runtime-unavailable`:return null}}function Jg(e){if(Hg(e.provider))return{pick:Bg,run:Bg};let t=Ug(e.provider);return t===null?{pick:Bg,run:Bg}:Yg({...e,providerKind:t})}function Yg(e){return{pick:Qg(e,`pick`),run:Qg(e,`run`)}}function Xg(e){return Qg(e,`pick`)}function Zg(e){return e.providers.filter(t=>Qg({providerKind:t.provider,snapshot:t,access:e.access,credentialMode:e.credentialMode,hasLiveInventory:e.hasLiveInventory},`run`).state===`usable`)}function Qg(e,t){let{providerKind:n}=e;if(e.snapshot?.unavailableReason===`unbuilt`)return Bg;if(e.credentialMode===`runtime`)return $g({...e,providerKind:n},t);if(e.access.status!==`ready`)return{state:`unresolved`,cause:e.access.status};if(!Sh(n,e.access.policy).offered)return{state:`withheld`,reason:`not-offered`};let r=Kg(n,e.access);return r===null?$g({...e,providerKind:n},t):r}function $g(e,t){let n=ng({provider:e.snapshot,providerKind:e.providerKind,access:e.access,credentialMode:e.credentialMode});if(!n.eligible&&n.reason===`environment-not-running`)return{state:`withheld`,reason:`not-usable`,detail:`environment-not-running`};if(!n.eligible&&n.reason===`native-runtime-not-ready`)return{state:`withheld`,reason:`not-usable`,detail:`delivery-pending`};let r=Wg(e.snapshot,e.hasLiveInventory);return!n.eligible&&n.reason===`runtime-unavailable`&&t===`run`?e_(r,e.hasLiveInventory)?zg:Vg:r}function e_(e,t){return e.state===`withheld`&&e.reason===`not-on-this-environment`&&(e.detail===`could-not-check`||!t)}var t_={reasoningEffortLevels:[],supportsFastMode:!1,supportsThinkingToggle:!1,contextWindowOptions:[],promptInjectedEffortLevels:[]},n_=[`codex`,`claudeAgent`,`apex`];function r_(e){for(let t of n_){let n=e.find(e=>e.provider===t);if(n&&a_(n))return t}return e.find(a_)?.provider??null}function i_(e,t){return e.find(e=>e.provider===t)?.models??[]}function a_(e){return ph(e)}function o_(e,t){let n=t??r_(e)??`codex`,r=e.find(e=>e.provider===n);if(r&&a_(r)||n===`codex`)return n;for(let t of n_){let n=e.find(e=>e.provider===t);if(n&&a_(n))return t}return`codex`}function s_(e){return e.providers.filter(t=>Xg({providerKind:t.provider,snapshot:t,access:e.access,credentialMode:e.credentialMode,hasLiveInventory:!0}).state===`usable`)}function c_(e,t,n,r){let i=s_({providers:e,access:n,credentialMode:r});return t&&i.some(e=>e.provider===t)?t:r_(i)}function l_(e,t,n,r){return t==null?c_(e,null,n,r):Zg({providers:e,access:n,credentialMode:r,hasLiveInventory:!0}).some(e=>e.provider===t)?t:null}function u_(e,t,n){let r=Dn(t,n);return e.find(e=>e.slug===r)?.capabilities??t_}function d_(e,t,n){let r=i_(e,t).filter(e=>!e.isLegacy);return r.find(e=>e.slug===n)?.slug??r.find(e=>e.isDefault)?.slug??r.find(e=>e.slug===Fi[t])?.slug??r.find(e=>!e.isCustom)?.slug??r[0]?.slug??Fi[t]}function f_(e){let{provider:t,model:n,models:r,prompt:i,modelOptions:a}=e,o=u_(r,n,t),s=a?.[t],c=s?`effort`in s?s.effort:`reasoningEffort`in s?s.reasoningEffort:null:null,l=fn(o,c)??null,u=t===`codex`?Hn(o,s):zn(o,s),d=o.promptInjectedEffortLevels.length>0&&Bn(i);return{provider:t,promptEffort:l,modelOptionsForDispatch:u,...d?{composerFrameClassName:`ultrathink-frame`}:{},...d?{composerSurfaceClassName:`shadow-[0_0_0_1px_rgba(255,255,255,0.04)_inset]`}:{},...d?{modelPickerIconClassName:`ultrathink-chroma`}:{}}}function p_(e,t,n,r){return i_(t,n).map(({slug:e,name:t,isCustom:n,isDefault:r,isLegacy:i})=>({slug:e,name:t,isCustom:n,isDefault:r,isLegacy:i}))}function m_(e,t,n,r,i){let a=fr(e,r,p_(t,n,e,r));if(a&&!yn(a,e))return a;let o=h_(n,e,i),s=p_(t,n,o,r),c=fr(o,r,s)??d_(n,o);return e&&yn(c,e)?d_(n,e):c}function h_(e,t,n){return!t||!bh(t,n)?o_(e,`codex`):o_(e,t)}function g_(e,t,n,r){return{codex:p_(e,t,`codex`,n===`codex`?r:void 0),claudeAgent:p_(e,t,`claudeAgent`,n===`claudeAgent`?r:void 0),ollama:p_(e,t,`ollama`,n===`ollama`?r:void 0),cmmd:p_(e,t,`cmmd`,n===`cmmd`?r:void 0),apex:p_(e,t,`apex`,n===`apex`?r:void 0),cursor:p_(e,t,`cursor`,n===`cursor`?r:void 0),opencode:p_(e,t,`opencode`,n===`opencode`?r:void 0)}}function __(e,t,n){let r=e.textGenerationModelSelection??{provider:`codex`,model:si.codex},i=h_(t,r.provider,n),a=m_(i,e,t,i===r.provider?r.model:null,n),{modelOptionsForDispatch:o}=f_({provider:i,model:a,models:i_(t,i),prompt:``,modelOptions:{[i]:i===r.provider?r.options:void 0}});return{provider:i,model:a,...o?{options:o}:{}}}function v_(e){return e?.options?{[e.provider]:e.options}:null}function y_(e){if(!e)return null;let t={};for(let[n,r]of Object.entries(e))r?.options&&(t[n]=r.options);return Object.keys(t).length>0?t:null}function b_(e){if(e.activeSelection&&`providerAccountId`in e.activeSelection)return e.activeSelection.providerAccountId;for(let t of e.candidates)if(t?.provider===e.selectedProvider&&`providerAccountId`in t)return t.providerAccountId}function x_(e){let t=t=>t!==void 0&&yn(t,e.selectedProvider)?void 0:t,n=t(e.threadModelSelection?.provider===e.selectedProvider?e.threadModelSelection.model:void 0),r=t(e.projectModelSelection?.provider===e.selectedProvider?e.projectModelSelection.model:void 0),i=Dn(n??r,e.selectedProvider)??d_(e.providers,e.selectedProvider),a=e.draft?.modelSelectionByProvider?.[e.selectedProvider],o=b_({activeSelection:a,selectedProvider:e.selectedProvider,candidates:[e.threadModelSelection,e.projectModelSelection]}),s=t(a?.model),c=s?m_(e.selectedProvider,e.settings,e.providers,s):i,l=y_(e.draft?.modelSelectionByProvider)??v_(e.threadModelSelection)??v_(e.projectModelSelection)??null;return{selectedModel:c,...o?{selectedProviderAccountId:o}:{},modelOptions:l}}var S_=zi({id:E,name:E,mimeType:E,sizeBytes:gi,dataUrl:E}),C_=zi({id:E,name:E,mimeType:E,sizeBytes:gi}),w_=zi({id:E,threadId:zr,createdAt:E,terminalId:E,terminalLabel:E,lineStart:gi,lineEnd:gi}),T_=zi({prompt:E,attachments:ji(S_),files:w(ji(C_)),terminalContexts:ji(w_),startedAt:E,commandId:w(Dr),messageId:w(Cr),modelSelection:w(Ei),runtimeMode:w(hi),interactionMode:w(Pi),executionIntent:w(zi({runtimeId:E,intentId:w(E)}))});function E_(e,t){return Array.isArray(e)?e.flatMap(e=>t(e)??[]):[]}function D_(e){if(!(!e||typeof e.runtimeId!=`string`))return{runtimeId:e.runtimeId,...typeof e.intentId==`string`?{intentId:e.intentId}:{}}}function O_(e){return{...typeof e.commandId==`string`?{commandId:Dr.make(e.commandId)}:{},...typeof e.messageId==`string`?{messageId:Cr.make(e.messageId)}:{}}}function k_(e,t){let n=t.modelSelection(e.modelSelection);return{...n?{modelSelection:n}:{},...t.runtimeMode(e.runtimeMode)?{runtimeMode:e.runtimeMode}:{},...e.interactionMode==="default"||e.interactionMode===`plan`?{interactionMode:e.interactionMode}:{}}}function A_(e,t){if(!e||typeof e!=`object`)return null;let n=e;if(typeof n.prompt!=`string`||typeof n.startedAt!=`string`)return null;let r=D_(n.executionIntent);return{prompt:n.prompt,attachments:E_(n.attachments,t.attachment),files:E_(n.files,t.file),terminalContexts:E_(n.terminalContexts,t.terminalContext),startedAt:n.startedAt,...O_(n),...k_(n,t),...r?{executionIntent:r}:{}}}function j_(e){return{id:e.id,threadId:e.threadId,createdAt:e.createdAt,terminalId:e.terminalId,terminalLabel:e.terminalLabel,lineStart:e.lineStart,lineEnd:e.lineEnd}}function M_(e){return{prompt:e.prompt,attachments:[...e.attachments],files:[...e.files],terminalContexts:e.terminalContexts.map(j_),startedAt:e.startedAt,...e.commandId?{commandId:e.commandId}:{},...e.messageId?{messageId:e.messageId}:{},...e.modelSelection?{modelSelection:e.modelSelection}:{},...e.runtimeMode?{runtimeMode:e.runtimeMode}:{},...e.interactionMode?{interactionMode:e.interactionMode}:{},...e.executionIntent?{executionIntent:e.executionIntent}:{}}}function N_(e){return e?{...e,attachments:[...e.attachments],files:[...e.files??[]],terminalContexts:e.terminalContexts.map(e=>({...e,text:``}))}:null}function P_(e,t,n,r){let i=e[t];if(i?.stagedSubmission)return null;let a=B_(i??F_(),r,n);return a?{previousDraft:i,restoredDraft:a,drafts:{...e,[t]:a}}:null}function F_(){return{prompt:``,images:[],files:[],nonPersistedImageIds:[],persistedAttachments:[],terminalContexts:[],modelSelectionByProvider:{},activeProvider:null,runtimeMode:null,interactionMode:null,stagedSubmission:null}}function I_(e){return`${e.mimeType}\u0000${e.sizeBytes}\u0000${e.name}`}function L_(e){return`${e.terminalId}\u0000${e.lineStart}\u0000${e.lineEnd}`}function R_(e,t){let n=t.terminalId.trim(),r=t.terminalLabel.trim(),i=Dm(t.text);if(!n||!r)return null;let a=Math.max(1,Math.floor(t.lineStart));return{...t,threadId:e,terminalId:n,terminalLabel:r,lineStart:a,lineEnd:Math.max(a,Math.floor(t.lineEnd)),text:i}}function z_(e,t){let n=new Set,r=new Set,i=[];for(let a of t){let t=R_(e,a);if(!t)continue;let o=L_(t);n.has(t.id)||r.has(o)||(i.push(t),n.add(t.id),r.add(o))}return i}function B_(e,t,n){let r=H_(e,t);if(!r)return null;let i=V_(e.files??[],t.files);if(r.images.length+i.length>8)return null;let a=U_(e,t,n),o=[e.prompt,t.prompt].filter(e=>e.length>0).join(`
|
|
16
|
-
`);return{...e,prompt:Wm(o,a.contexts.length),images:r.images,files:i,persistedAttachments:r.attachments,terminalContexts:a.contexts,stashTerminalContexts:[...e.stashTerminalContexts??[],...a.restoredSnapshots]}}function V_(e,t){let n=new Set(e.map(e=>e.id));return[...e,...t.filter(e=>!n.has(e.id))]}function H_(e,t){let n=new Map(t.attachments.map(e=>[e.id,e])),r=[...e.images],i=e.persistedAttachments.filter(t=>e.images.some(e=>e.id===t.id)),a=new Set(r.map(e=>e.id)),o=new Set(r.map(I_));for(let e of t.images){let t=n.get(e.id);if(!t)return null;let s=I_(e);a.has(e.id)||o.has(s)||(r.push(e),i.push(t),a.add(e.id),o.add(s))}return r.length>8?null:{images:r,attachments:i}}function U_(e,t,n){let r=[...e.terminalContexts],i=new Set(r.map(e=>e.id)),a=new Set(r.map(L_)),o=[];for(let e of t.terminalContexts){let t=R_(n,e);!t||i.has(t.id)||a.has(L_(t))||(r.push(t),o.push(t),i.add(t.id),a.add(L_(t)))}return{contexts:r,restoredSnapshots:o}}function W_(e,t){return e.prompt===t.prompt&&JSON.stringify(e.attachments)===JSON.stringify(t.persistedAttachments)&&JSON.stringify(e.files??[])===JSON.stringify((t.files??[]).map(({file:e,type:t,...n})=>n))&&JSON.stringify(e.terminalContexts??[])===JSON.stringify(t.terminalContexts.map(({text:e,...t})=>t))&&JSON.stringify(e.stashTerminalContexts??[])===JSON.stringify(t.stashTerminalContexts??[])}function G_(e){typeof URL<`u`&&e.startsWith(`blob:`)&&URL.revokeObjectURL(e)}function K_(e){if(!e||typeof e!=`object`)return null;let{id:t,name:n,mimeType:r,sizeBytes:i,dataUrl:a}=e;return typeof t!=`string`||typeof n!=`string`||typeof r!=`string`||typeof i!=`number`||!Number.isFinite(i)||typeof a!=`string`||t.length===0||a.length===0?null:{id:t,name:n,mimeType:r,sizeBytes:i,dataUrl:a}}function q_(e){if(!e||typeof e!=`object`)return null;let{id:t,name:n,mimeType:r,sizeBytes:i}=e;return typeof t!=`string`||t.length===0||typeof n!=`string`||typeof r!=`string`||typeof i!=`number`||!Number.isSafeInteger(i)||i<0?null:{id:t,name:n,mimeType:r,sizeBytes:i}}async function J_(e,t){let n=await Promise.all(e.map(async e=>{let n=await t.read(e);return{...e,type:`file`,file:n}}));return n.length===e.length?n:null}function Y_(e){let t=X_(e.dataUrl,e.mimeType);return t?new File([t.content],e.name,{type:t.mimeType}):null}function X_(e,t){let n=e.indexOf(`,`),r=n===-1?e:e.slice(0,n),i=n===-1?``:e.slice(n+1);if(i.length===0)return null;try{return r.includes(`;base64`)?{content:$_(i),mimeType:t}:{content:Q_(i),mimeType:Z_(r,t)}}catch{return null}}function Z_(e,t){return!e.startsWith(`data:`)||!e.includes(`;`)?t:e.slice(5,e.indexOf(`;`))||t}function Q_(e){return decodeURIComponent(e)}function $_(e){let t=atob(e),n=new Uint8Array(new ArrayBuffer(t.length));for(let e=0;e<t.length;e+=1)n[e]=t.charCodeAt(e);return n}function ev(e){return e.flatMap(e=>{let t=Y_(e);return t?[{type:`image`,id:e.id,name:e.name,mimeType:e.mimeType,sizeBytes:e.sizeBytes,previewUrl:e.dataUrl,file:t}]:[]})}function tv(e){return{prompt:e.prompt,images:[...e.images],files:[...e.files??[]],persistedAttachments:[...e.persistedAttachments],terminalContexts:[...e.terminalContexts]}}function nv({file:e,previewUrl:t,...n}){return n}function rv(e,t){return e.prompt===t.prompt&&JSON.stringify(e.images.map(nv))===JSON.stringify(t.images.map(nv))&&JSON.stringify((e.files??[]).map(({file:e,...t})=>t))===JSON.stringify(t.files.map(({file:e,...t})=>t))&&JSON.stringify(e.persistedAttachments)===JSON.stringify(t.persistedAttachments)&&JSON.stringify(e.terminalContexts)===JSON.stringify(t.terminalContexts)}function iv(e){let{lastGeneratedPullRequestPrompt:t,...n}=e;return{...n,prompt:``,images:[],files:[],nonPersistedImageIds:[],persistedAttachments:[],terminalContexts:[],stashTerminalContexts:[]}}function N(e){return e.prompt.length===0&&e.lastGeneratedPullRequestPrompt===void 0&&e.images.length===0&&(e.files?.length??0)===0&&e.persistedAttachments.length===0&&e.terminalContexts.length===0&&Object.keys(e.modelSelectionByProvider).length===0&&e.activeProvider===null&&e.runtimeMode===null&&e.interactionMode===null&&e.stagedSubmission==null}function av(e){switch(e){case`codex`:case`claudeAgent`:case`ollama`:case`cmmd`:case`apex`:case`cursor`:case`opencode`:return e;default:return null}}function ov(e){return _i.some(t=>t===e)}function sv(e){return wi.some(t=>t===e)}function cv(e,t,n){let r=e&&typeof e==`object`?e:null,i=r?.codex&&typeof r.codex==`object`?r.codex:null,a=r?.claudeAgent&&typeof r.claudeAgent==`object`?r.claudeAgent:null,o=ov(i?.reasoningEffort)?i.reasoningEffort:t===`codex`&&ov(n?.effort)?n.effort:void 0,s=i?.fastMode===!0?!0:i?.fastMode===!1?!1:t===`codex`&&n?.codexFastMode===!0||typeof n?.serviceTier==`string`&&n.serviceTier===`fast`||void 0,c=o!==void 0||s!==void 0?{...o===void 0?{}:{reasoningEffort:o},...s===void 0?{}:{fastMode:s}}:void 0,l=a?.thinking===!0||a?.thinking!==!1&&void 0,u=sv(a?.effort)?a.effort:void 0,d=a?.fastMode===!0||a?.fastMode!==!1&&void 0,f=typeof a?.contextWindow==`string`&&a.contextWindow.length>0?a.contextWindow:void 0,p=l!==void 0||u!==void 0||d!==void 0||f!==void 0?{...l===void 0?{}:{thinking:l},...u===void 0?{}:{effort:u},...d===void 0?{}:{fastMode:d},...f===void 0?{}:{contextWindow:f}}:void 0;return!c&&!p?null:{...c?{codex:c}:{},...p?{claudeAgent:p}:{}}}function lv(e,t){let n=e&&typeof e==`object`?e:null,r=av(n?.provider??t?.provider);if(r===null)return null;let i=n?.model??t?.model;if(typeof i!=`string`)return null;let a=Dn(i,r);if(!a)return null;let o=cv(n?.options?{[r]:n.options}:t?.modelOptions,r,r===`codex`?t?.legacyCodex:void 0),s=r===`codex`?o?.codex:o?.claudeAgent,c=n?.providerAccountId,l=typeof c==`string`&&c.trim().length>0?c.trim():void 0;return{provider:r,model:a,...l?{providerAccountId:l}:{},...s?{options:s}:{}}}function uv(e,t){if(e===null)return null;let n=t?.[e.provider];return{provider:e.provider,model:e.model,...`providerAccountId`in e&&e.providerAccountId?{providerAccountId:e.providerAccountId}:{},...n?{options:n}:{}}}function dv(e,t){return e?.options===void 0?cv(t):fv(cv(t),e.provider,e.options)}function fv(e,t,n){let{[t]:r,...i}=e??{},a=cv({[t]:n},t);return cv({...i,...a||{}})}function pv(e,t){let n={};if(t)for(let r of[`codex`,`claudeAgent`]){let i=t[r];i&&Object.keys(i).length>0&&(n[r]={provider:r,model:e?.provider===r?e.model:Fi[r],options:i})}return e&&(n[e.provider]=e),n}var mv=`forge:composer-drafts:v1`,hv=5,gv=Oi([`local`,`worktree`]),_v=Br(hi),vv=300,yv=fh({storage:typeof localStorage<`u`?localStorage:gr(),version:hv,canMigrate:Ev}),bv=gn(yv,vv);typeof window<`u`&&typeof window.addEventListener==`function`&&window.addEventListener(`beforeunload`,()=>{bv.flush()});var xv=zi({prompt:E,lastGeneratedPullRequestPrompt:w(E),attachments:ji(S_),files:w(ji(C_)),terminalContexts:w(ji(w_)),stashTerminalContexts:w(ji(zi({...w_.fields,text:E}))),modelSelectionByProvider:w(oi(fi,w(Ei))),activeProvider:w(vi(fi)),runtimeMode:w(hi),interactionMode:w(Pi),stagedSubmission:w(T_)});zi({effort:w(Oi(_i)),codexFastMode:w(di),serviceTier:w(E)}),zi({provider:w(fi),model:w(E),modelOptions:w(vi(Er))}),zi({stickyProvider:w(fi),stickyModel:w(E),stickyModelOptions:w(vi(Er))});var Sv=zi({threadId:zr,environmentId:E,projectId:xi,logicalProjectKey:w(E),createdAt:E,runtimeMode:hi,interactionMode:Pi,branch:vi(E),worktreePath:vi(E),envMode:gv,promotedTo:w(vi(zi({environmentId:E,threadId:E}))),anchorKind:w(Ur),anchorCmmdId:w(vi(E)),linkedPullRequest:w(vi(Ni))}),Cv=zi({draftsByThreadKey:oi(E,xv),draftThreadsByThreadKey:oi(E,Sv),logicalProjectDraftThreadKeyByLogicalProjectKey:oi(E,E),stickyModelSelectionByProvider:w(oi(fi,w(Ei))),stickyActiveProvider:w(vi(fi))}),wv=zi({version:gi,state:Cv}),Tv=Si(wv);function Ev(e,t){if(e===null)return!0;try{let n=JSON.parse(e);if(!n||typeof n!=`object`)return!1;let r=n;return r.version===t?(Tv(n),!0):typeof r.version==`number`&&Number.isInteger(r.version)&&r.version>=1&&r.version<t&&r.state!==null&&typeof r.state==`object`}catch{return!1}}function Dv(e){if(e===null)return new Set;try{let t=Tv(JSON.parse(e));if(t.version!==hv)return null;let n=new Set;for(let e of Object.values(t.state.draftsByThreadKey)){for(let t of e.files??[])n.add(t.id);for(let t of e.stagedSubmission?.files??[])n.add(t.id)}return n}catch{return null}}function Ov(){bv.flush()}var kv=Object.freeze({draftsByThreadKey:{},draftThreadsByThreadKey:{},logicalProjectDraftThreadKeyByLogicalProjectKey:{},stickyModelSelectionByProvider:{},stickyActiveProvider:null}),Av=[],jv=[],Mv=[],Nv=[],Pv=[];Object.freeze(Av),Object.freeze(Mv),Object.freeze(Nv);var Fv=Object.freeze({}),Iv=Object.freeze({activeProvider:null,modelSelectionByProvider:Fv}),Lv=Object.freeze({prompt:``,images:Av,files:jv,nonPersistedImageIds:Mv,persistedAttachments:Nv,terminalContexts:Pv,modelSelectionByProvider:Fv,activeProvider:null,runtimeMode:null,interactionMode:null,stagedSubmission:null});function Rv(){return{prompt:``,images:[],files:[],nonPersistedImageIds:[],persistedAttachments:[],terminalContexts:[],modelSelectionByProvider:{},activeProvider:null,runtimeMode:null,interactionMode:null,stagedSubmission:null}}function zv(e){if(!e||typeof e!=`object`)return null;let t=e,n=t.id,r=t.threadId,i=t.createdAt,a=t.lineStart,o=t.lineEnd;if(typeof n!=`string`||n.length===0||typeof r!=`string`||r.length===0||typeof i!=`string`||i.length===0||typeof a!=`number`||!Number.isFinite(a)||typeof o!=`number`||!Number.isFinite(o))return null;let s=typeof t.terminalId==`string`?t.terminalId.trim():``,c=typeof t.terminalLabel==`string`?t.terminalLabel.trim():``;if(s.length===0||c.length===0)return null;let l=Math.max(1,Math.floor(a));return{id:n,threadId:r,createdAt:i,terminalId:s,terminalLabel:c,lineStart:l,lineEnd:Math.max(l,Math.floor(o))}}function Bv(e,t){return e===`local`||e===`worktree`?e:t?`worktree`:`local`}function Vv(e){return Fn(e)}function Hv(e){return e.trim()}function Uv(e){return typeof e==`string`?e.trim():Ln(e)}function Wv(e,t){let n=hn(e);return n?Uv(n):t?.environmentId?Uv(C(t.environmentId,e)):e}function Gv(e){return hn(e)}function Kv(e,t){if(typeof t==`string`){let e=t.trim();return e.length>0?ba.make(e):null}return t}function P(e,t){let n=Kv(e,t);if(!n)return null;if(typeof n!=`string`){let t=Uv(n);if(e.draftsByThreadKey[t])return t;for(let[t,r]of Object.entries(e.draftThreadsByThreadKey))if(r.environmentId===n.environmentId&&r.threadId===n.threadId)return t;return t}let r=Uv(n);return r.length>0?r:null}function qv(e,t){let n=Kv(e,t);return n?typeof n==`string`?e.draftThreadsByThreadKey[n]?.threadId??zr.make(n):n.threadId:null}function Jv(e,t){let n=P(e,t);return n?e.draftsByThreadKey[n]??null:null}function Yv(e,t){return Object.values(e).includes(t)}function Xv(e,t){return{draftId:e,...t}}function Zv(e,t,n,r,i){let a=r!==void 0&&(r.environmentId!==e.environmentId||r.projectId!==e.projectId),o=i?.worktreePath===void 0?a?null:r?.worktreePath??null:i.worktreePath??null,s=i?.branch===void 0?a?null:r?.branch??null:i.branch??null,c=i?.anchorKind===void 0?r?.anchorKind:i.anchorKind??void 0;return{threadId:t,environmentId:e.environmentId,projectId:e.projectId,logicalProjectKey:n,createdAt:i?.createdAt??r?.createdAt??new Date().toISOString(),runtimeMode:i?.runtimeMode??r?.runtimeMode??`full-access`,interactionMode:i?.interactionMode??r?.interactionMode??`default`,branch:s,worktreePath:o,envMode:i?.envMode??(o?`worktree`:a?`local`:r?.envMode??`local`),promotedTo:null,cmmdTaskId:i?.cmmdTaskId===void 0?r?.cmmdTaskId??null:i.cmmdTaskId,anchorCmmdId:i?.anchorCmmdId===void 0?r?.anchorCmmdId??null:i.anchorCmmdId,linkedPullRequest:i?.linkedPullRequest===void 0?r?.linkedPullRequest??null:i.linkedPullRequest,...c===void 0?{}:{anchorKind:c}}}function Qv(e,t){return!e||!t?e===t:e.environmentId===t.environmentId&&e.threadId===t.threadId}function $v(e){return e?.promotedTo!==null&&e?.promotedTo!==void 0}function ey(e,t){return!!e&&e.threadId===t.threadId&&e.environmentId===t.environmentId&&e.projectId===t.projectId&&e.logicalProjectKey===t.logicalProjectKey&&e.createdAt===t.createdAt&&e.runtimeMode===t.runtimeMode&&e.interactionMode===t.interactionMode&&e.branch===t.branch&&e.worktreePath===t.worktreePath&&e.envMode===t.envMode&&(e.anchorKind??void 0)===(t.anchorKind??void 0)&&(e.anchorCmmdId??null)===(t.anchorCmmdId??null)&&ty(e.linkedPullRequest,t.linkedPullRequest)&&Qv(e.promotedTo,t.promotedTo)}function ty(e,t){return(e?.projectId??null)===(t?.projectId??null)&&(e?.projectRepositoryId??null)===(t?.projectRepositoryId??null)&&(e?.provider??null)===(t?.provider??null)&&(e?.host??null)===(t?.host??null)&&(e?.repository??null)===(t?.repository??null)&&(e?.number??null)===(t?.number??null)&&(e?.url??null)===(t?.url??null)}function ny(e,t){let n=Object.fromEntries(Object.entries(e.logicalProjectDraftThreadKeyByLogicalProjectKey).filter(([,e])=>e!==t)),{[t]:r,...i}=e.draftThreadsByThreadKey,{[t]:a,...o}=e.draftsByThreadKey;return{draftsByThreadKey:o,draftThreadsByThreadKey:i,logicalProjectDraftThreadKeyByLogicalProjectKey:n}}function ry(e,t){let n={},r=new Map;if(t&&typeof t==`object`)for(let[e,n]of Object.entries(t)){if(typeof n!=`string`||n.length===0)continue;let t=br(e);if(!t)continue;let i=hn(n);if(i){r.set(i.threadId,i.environmentId);continue}r.set(n,t.environmentId)}if(e&&typeof e==`object`)for(let[t,i]of Object.entries(e)){if(typeof t!=`string`||t.length===0||!i||typeof i!=`object`)continue;let e=i,a=hn(t),o=Wv(t),s=a?.threadId??(typeof e.threadId==`string`&&e.threadId.length>0?e.threadId:t),c=a?.environmentId??(typeof e.environmentId==`string`&&e.environmentId.length>0?e.environmentId:r.get(t)),l=e.projectId,u=e.createdAt,d=e.branch,f=e.worktreePath,p=typeof f==`string`?f:null,m=e.promotedTo,h=m&&typeof m==`object`?m:null,g=h&&typeof h.environmentId==`string`&&h.environmentId.length>0&&typeof h.threadId==`string`&&h.threadId.length>0?C(h.environmentId,h.threadId):null;if(typeof l!=`string`||l.length===0||c===void 0)continue;let _=c;n[o]={threadId:s,environmentId:_,projectId:l,logicalProjectKey:typeof e.logicalProjectKey==`string`&&e.logicalProjectKey.length>0?e.logicalProjectKey:a?Vv(In(_,l)):t,createdAt:typeof u==`string`&&u.length>0?u:new Date().toISOString(),runtimeMode:_v(e.runtimeMode)?e.runtimeMode:op,interactionMode:e.interactionMode===`plan`||e.interactionMode==="default"?e.interactionMode:sp,branch:typeof d==`string`?d:null,worktreePath:p,envMode:Bv(e.envMode,p),promotedTo:g}}let i={};if(t&&typeof t==`object`)for(let[e,a]of Object.entries(t)){if(typeof a!=`string`||a.length===0)continue;let t=br(e),o=hn(a),s=Wv(a);if(i[e]=s,o&&r.set(o.threadId,o.environmentId),!t){let t=n[s];t&&!t.logicalProjectKey&&(n[s]={...t,logicalProjectKey:e});continue}n[s]?(n[s]?.projectId!==t.projectId||n[s]?.environmentId!==t.environmentId)&&(n[s]={...n[s],threadId:n[s].threadId,environmentId:t.environmentId,projectId:t.projectId,logicalProjectKey:e}):n[s]={threadId:o?.threadId??s,environmentId:t.environmentId,projectId:t.projectId,logicalProjectKey:e,createdAt:new Date().toISOString(),runtimeMode:op,interactionMode:sp,branch:null,worktreePath:null,envMode:`local`,promotedTo:null}}return{draftThreadsByThreadKey:n,logicalProjectDraftThreadKeyByLogicalProjectKey:i}}function iy(e,t){if(!e||typeof e!=`object`)return{};let n=new Map;for(let[e,r]of Object.entries(t)){let t=Gv(e);t&&n.set(t.threadId,r.environmentId)}let r={};for(let[i,a]of Object.entries(e)){if(typeof i!=`string`||i.length===0||!a||typeof a!=`object`)continue;let e=a,o=typeof e.prompt==`string`?e.prompt:``,s=typeof e.lastGeneratedPullRequestPrompt==`string`?e.lastGeneratedPullRequestPrompt:void 0,c=Array.isArray(e.attachments)?e.attachments.flatMap(e=>{let t=K_(e);return t?[t]:[]}):[],l=Array.isArray(e.files)?e.files.flatMap(e=>{let t=q_(e);return t?[t]:[]}):[],u=Array.isArray(e.terminalContexts)?e.terminalContexts.flatMap(e=>{let t=zv(e);return t?[t]:[]}):[],d=Array.isArray(e.stashTerminalContexts)?e.stashTerminalContexts.flatMap(e=>{let t=zv(e),n=typeof e.text==`string`?e.text:``;return t&&n.length>0?[{...t,text:n}]:[]}):[],f=_v(e.runtimeMode)?e.runtimeMode:null,p=e.interactionMode===`plan`||e.interactionMode==="default"?e.interactionMode:null,m=A_(e.stagedSubmission,{attachment:K_,file:q_,terminalContext:zv,modelSelection:e=>lv(e)??null,runtimeMode:_v}),h=Wm(o,u.length),g=a,_={},v=null;if(e.modelSelectionByProvider&&typeof e.modelSelectionByProvider==`object`)_=e.modelSelectionByProvider,v=av(e.activeProvider);else{let e=cv(g.modelOptions,void 0,g)??null,t=lv(g.modelSelection,{provider:g.provider,model:g.model,modelOptions:e??g.modelOptions,legacyCodex:g}),n=dv(t,e),r=uv(t,n);_=pv(r,n),v=r?.provider??null}let y=Object.keys(_).length>0||v!==null;if(o.length===0&&c.length===0&&l.length===0&&u.length===0&&d.length===0&&!y&&!f&&!p&&!m)continue;let b=hn(i)===null?t[i]===void 0?(()=>{let e=n.get(i);return e?Wv(i,{environmentId:e}):i})():i:Wv(i);r[b]={prompt:h,...s===void 0?{}:{lastGeneratedPullRequestPrompt:s},attachments:c,...l.length>0?{files:l}:{},...u.length>0?{terminalContexts:u}:{},...d.length>0?{stashTerminalContexts:d}:{},...y?{modelSelectionByProvider:_,activeProvider:v}:{},...f?{runtimeMode:f}:{},...p?{interactionMode:p}:{},...m?{stagedSubmission:m}:{}}}return r}function ay(e){if(!e||typeof e!=`object`)return kv;let t=e,n=t.draftsByThreadKey??t.draftsByThreadId,r=t.draftThreadsByThreadKey??t.draftThreadsByThreadId,i=t.logicalProjectDraftThreadKeyByLogicalProjectKey??t.projectDraftThreadKeyByProjectKey??t.projectDraftThreadIdByProjectKey??t.projectDraftThreadIdByProjectId,a=cv(t.stickyModelOptions)??{},o=lv(t.stickyModelSelection,{provider:t.stickyProvider??`codex`,model:t.stickyModel,modelOptions:a}),s=dv(o,a),c=pv(uv(o,s),s),l=av(t.stickyProvider)??null,{draftThreadsByThreadKey:u,logicalProjectDraftThreadKeyByLogicalProjectKey:d}=ry(r,i);return{draftsByThreadKey:iy(n,u),draftThreadsByThreadKey:u,logicalProjectDraftThreadKeyByLogicalProjectKey:d,stickyModelSelectionByProvider:c,stickyActiveProvider:l}}function oy(e){let t={};for(let[n,r]of Object.entries(e.draftsByThreadKey)){if(typeof n!=`string`||n.length===0)continue;let e=Object.keys(r.modelSelectionByProvider).length>0||r.activeProvider!==null;r.prompt.length===0&&r.lastGeneratedPullRequestPrompt===void 0&&r.persistedAttachments.length===0&&(r.files?.length??0)===0&&r.terminalContexts.length===0&&!e&&r.runtimeMode===null&&r.interactionMode===null&&r.stagedSubmission==null||(t[n]={prompt:r.prompt,...r.lastGeneratedPullRequestPrompt===void 0?{}:{lastGeneratedPullRequestPrompt:r.lastGeneratedPullRequestPrompt},attachments:r.persistedAttachments,...(r.files?.length??0)>0?{files:r.files.map(({file:e,type:t,...n})=>n)}:{},...r.terminalContexts.length>0?{terminalContexts:r.terminalContexts.map(e=>({id:e.id,threadId:e.threadId,createdAt:e.createdAt,terminalId:e.terminalId,terminalLabel:e.terminalLabel,lineStart:e.lineStart,lineEnd:e.lineEnd}))}:{},...r.stashTerminalContexts&&r.stashTerminalContexts.length>0?{stashTerminalContexts:r.stashTerminalContexts.map(e=>({id:e.id,threadId:e.threadId,createdAt:e.createdAt,terminalId:e.terminalId,terminalLabel:e.terminalLabel,lineStart:e.lineStart,lineEnd:e.lineEnd,text:e.text}))}:{},...e?{modelSelectionByProvider:r.modelSelectionByProvider,activeProvider:r.activeProvider}:{},...r.runtimeMode?{runtimeMode:r.runtimeMode}:{},...r.interactionMode?{interactionMode:r.interactionMode}:{},...r.stagedSubmission?{stagedSubmission:M_(r.stagedSubmission)}:{}})}return{draftsByThreadKey:t,draftThreadsByThreadKey:e.draftThreadsByThreadKey,logicalProjectDraftThreadKeyByLogicalProjectKey:e.logicalProjectDraftThreadKeyByLogicalProjectKey,stickyModelSelectionByProvider:e.stickyModelSelectionByProvider,stickyActiveProvider:e.stickyActiveProvider}}function sy(e){if(!e||typeof e!=`object`)return kv;let t=e,{draftThreadsByThreadKey:n,logicalProjectDraftThreadKeyByLogicalProjectKey:r}=ry(t.draftThreadsByThreadKey??t.draftThreadsByThreadId,t.logicalProjectDraftThreadKeyByLogicalProjectKey??t.projectDraftThreadKeyByProjectKey??t.projectDraftThreadIdByProjectKey??t.projectDraftThreadIdByProjectId),i={},a=null;if(t.stickyModelSelectionByProvider&&typeof t.stickyModelSelectionByProvider==`object`)i=t.stickyModelSelectionByProvider,a=av(t.stickyActiveProvider);else{let e=cv(t.stickyModelOptions)??{},n=lv(t.stickyModelSelection,{provider:t.stickyProvider,model:t.stickyModel,modelOptions:e}),r=dv(n,e);i=pv(uv(n,r),r),a=av(t.stickyProvider)}return{draftsByThreadKey:iy(t.draftsByThreadKey??t.draftsByThreadId,n),draftThreadsByThreadKey:n,logicalProjectDraftThreadKeyByLogicalProjectKey:r,stickyModelSelectionByProvider:i,stickyActiveProvider:a}}function cy(e){if(e.length===0)return[];try{let t=jn(mv,wv);return!t||t.version!==hv?[]:(t.state.draftsByThreadKey[e]?.attachments??[]).map(e=>e.id)}catch{return[]}}function ly(e){if(e.length===0)return null;try{let t=bv.getItem(mv);if(typeof t!=`string`)return null;let n=Tv(JSON.parse(t));return!n||n.version!==hv?null:n.state.draftsByThreadKey[e]??null}catch{return null}}function uy(e,t,n){let r=new Set;try{bv.flush(),r=new Set(cy(e))}catch{r=new Set}n(n=>{let i=n.draftsByThreadKey[e];if(!i)return n;let a=new Set(i.images.map(e=>e.id)),o=t.filter(e=>a.has(e.id)&&r.has(e.id)),s=i.images.map(e=>e.id).filter(e=>!r.has(e)),c={...i,persistedAttachments:o,nonPersistedImageIds:s},l={...n.draftsByThreadKey};return N(c)?delete l[e]:l[e]=c,{draftsByThreadKey:l}})}function dy(e,t){return e.length>0?e:t?.prompt??``}function fy(e,t){return e?.length?e:t??[]}function py(e){let t=e.stagedSubmission;return{prompt:dy(e.prompt,t),attachments:fy(e.attachments,t?.attachments),files:fy(e.files,t?.files),terminalContexts:fy(e.terminalContexts,t?.terminalContexts)}}function my(e){let t=e.modelSelectionByProvider??{},n=av(e.activeProvider)??null,r=py(e);return{prompt:r.prompt,...e.lastGeneratedPullRequestPrompt===void 0?{}:{lastGeneratedPullRequestPrompt:e.lastGeneratedPullRequestPrompt},images:ev(r.attachments),files:r.files.map(e=>({...e,type:`file`,file:null})),nonPersistedImageIds:[],persistedAttachments:[...r.attachments],terminalContexts:r.terminalContexts.map(t=>{let n=e.stashTerminalContexts?.find(e=>e.id===t.id);return Object.assign({},t,{text:n?.text??``})}),...e.stashTerminalContexts&&e.stashTerminalContexts.length>0?{stashTerminalContexts:e.stashTerminalContexts.map(e=>({...e}))}:{},modelSelectionByProvider:t,activeProvider:n,runtimeMode:e.runtimeMode??null,interactionMode:e.interactionMode??null,stagedSubmission:N_(e.stagedSubmission)}}function hy(e){return{threadId:e.threadId,environmentId:e.environmentId,projectId:e.projectId,logicalProjectKey:e.logicalProjectKey??Vv(In(e.environmentId,e.projectId)),createdAt:e.createdAt,runtimeMode:e.runtimeMode,interactionMode:e.interactionMode,branch:e.branch,worktreePath:e.worktreePath,envMode:e.envMode,promotedTo:e.promotedTo?C(e.promotedTo.environmentId,e.promotedTo.threadId):null,linkedPullRequest:e.linkedPullRequest??null}}var gy=wa()(Wf((e,t)=>{let n=e;return{draftsByThreadKey:{},draftThreadsByThreadKey:{},logicalProjectDraftThreadKeyByLogicalProjectKey:{},stickyModelSelectionByProvider:{},stickyActiveProvider:null,getComposerDraft:e=>Jv(t(),e),getDraftThreadByLogicalProjectKey:e=>t().getDraftSessionByLogicalProjectKey(e),getDraftSessionByLogicalProjectKey:e=>{let n=Hv(e);if(n.length===0)return null;let r=t().logicalProjectDraftThreadKeyByLogicalProjectKey[n];if(!r)return null;let i=t().draftThreadsByThreadKey[r];return!i||$v(i)?null:Xv(ba.make(r),i)},getDraftThreadByProjectRef:e=>t().getDraftSessionByProjectRef(e),getDraftSessionByProjectRef:e=>{for(let[n,r]of Object.entries(t().draftThreadsByThreadKey))if(!$v(r)&&r.projectId===e.projectId&&r.environmentId===e.environmentId)return Xv(ba.make(n),r);return null},getDraftSession:e=>t().draftThreadsByThreadKey[e]??null,getDraftSessionByRef:e=>{for(let n of Object.values(t().draftThreadsByThreadKey))if(n.environmentId===e.environmentId&&n.threadId===e.threadId)return n;return null},getDraftThread:e=>typeof e==`string`?t().getDraftSession(ba.make(e)):t().getDraftSessionByRef(e),getDraftThreadByRef:e=>t().getDraftSessionByRef(e),listDraftThreadKeys:()=>Object.values(t().draftThreadsByThreadKey).map(e=>Ln(C(e.environmentId,e.threadId))),hasDraftThreadsInEnvironment:e=>Object.values(t().draftThreadsByThreadKey).some(t=>t.environmentId===e),setLogicalProjectDraftThreadId:(e,t,r,i)=>{let a=Hv(e);a.length!==0&&r.length!==0&&n(e=>{let n=e.draftThreadsByThreadKey[r],o=e.logicalProjectDraftThreadKeyByLogicalProjectKey[a],s=Zv(t,i?.threadId??n?.threadId??zr.make(r),a,n,i);if(o===r&&ey(n,s))return e;let c={...e.logicalProjectDraftThreadKeyByLogicalProjectKey,[a]:r},l={...e.draftThreadsByThreadKey,[r]:s},u=e.draftsByThreadKey,d=o===void 0?void 0:l[o];return o&&o!==r&&!Yv(c,o)&&!$v(d)&&(delete l[o],e.draftsByThreadKey[o]!==void 0&&(u={...e.draftsByThreadKey},delete u[o])),{draftsByThreadKey:u,draftThreadsByThreadKey:l,logicalProjectDraftThreadKeyByLogicalProjectKey:c}})},setProjectDraftThreadId:(e,n,r)=>{t().setLogicalProjectDraftThreadId(Vv(e),e,n,r)},setDraftThreadContext:(e,r)=>{let i=P(t(),e)??``;i.length!==0&&n(e=>{let t=e.draftThreadsByThreadKey[i];if(!t)return e;let n=r.projectRef??{environmentId:t.environmentId,projectId:t.projectId};if(n.projectId.length===0||n.environmentId.length===0)return e;let a=n.environmentId!==t.environmentId||n.projectId!==t.projectId,o=r.worktreePath===void 0?a?null:t.worktreePath:r.worktreePath??null,s=r.branch===void 0?a?null:t.branch:r.branch??null,c=r.anchorKind===void 0?t.anchorKind:r.anchorKind??void 0,l={threadId:t.threadId,environmentId:n.environmentId,projectId:n.projectId,logicalProjectKey:t.logicalProjectKey,createdAt:r.createdAt===void 0?t.createdAt:r.createdAt||t.createdAt,runtimeMode:r.runtimeMode??t.runtimeMode,interactionMode:r.interactionMode??t.interactionMode,branch:s,worktreePath:o,envMode:r.envMode??(o?`worktree`:a?`local`:t.envMode??`local`),promotedTo:t.promotedTo??null,cmmdTaskId:r.cmmdTaskId===void 0?t.cmmdTaskId??null:r.cmmdTaskId,anchorCmmdId:r.anchorCmmdId===void 0?t.anchorCmmdId??null:r.anchorCmmdId,linkedPullRequest:r.linkedPullRequest===void 0?t.linkedPullRequest??null:r.linkedPullRequest,...c===void 0?{}:{anchorKind:c}};return l.environmentId===t.environmentId&&l.projectId===t.projectId&&l.logicalProjectKey===t.logicalProjectKey&&l.createdAt===t.createdAt&&l.runtimeMode===t.runtimeMode&&l.interactionMode===t.interactionMode&&l.branch===t.branch&&l.worktreePath===t.worktreePath&&l.envMode===t.envMode&&(l.anchorKind??void 0)===(t.anchorKind??void 0)&&(l.anchorCmmdId??null)===(t.anchorCmmdId??null)&&ty(l.linkedPullRequest,t.linkedPullRequest)&&Qv(l.promotedTo,t.promotedTo)?e:{draftThreadsByThreadKey:{...e.draftThreadsByThreadKey,[i]:l}}})},clearProjectDraftThreadId:e=>{n(t=>{let n=Object.entries(t.draftThreadsByThreadKey).find(([,t])=>t.projectId===e.projectId&&t.environmentId===e.environmentId);return n?ny(t,n[0]):t})},clearProjectDraftThreadById:(e,r)=>{let i=P(t(),r)??``;i.length!==0&&n(t=>{let n=t.draftThreadsByThreadKey[i];return!n||n.projectId!==e.projectId||n.environmentId!==e.environmentId?t:ny(t,i)})},markDraftThreadPromoting:(e,r)=>{let i=P(t(),e);i&&n(e=>{let t=e.draftThreadsByThreadKey[i];if(!t)return e;let n=r??C(t.environmentId,t.threadId);return Qv(t.promotedTo,n)?e:{draftThreadsByThreadKey:{...e.draftThreadsByThreadKey,[i]:{...t,promotedTo:n}}}})},finalizePromotedDraftThread:e=>{let r=P(t(),e)??``;r.length!==0&&n(e=>{let t=e.draftThreadsByThreadKey[r];if(!$v(t))return e;let n=Uv(t.promotedTo),i=e.draftsByThreadKey[n],a=e.draftsByThreadKey[r];return ny(a?{...e,draftsByThreadKey:{...e.draftsByThreadKey,[n]:i?{...i,modelSelectionByProvider:{...i.modelSelectionByProvider,...a.modelSelectionByProvider},activeProvider:a.activeProvider,runtimeMode:a.runtimeMode,interactionMode:a.interactionMode}:a}}:e,r)})},clearDraftThread:e=>{let r=P(t(),e)??``;if(r.length===0)return;let i=t().draftsByThreadKey[r];if(i)for(let e of i.images)G_(e.previewUrl);n(e=>{let t=e.draftThreadsByThreadKey[r]!==void 0,n=Object.values(e.logicalProjectDraftThreadKeyByLogicalProjectKey).includes(r),i=e.draftsByThreadKey[r]!==void 0;return!t&&!n&&!i?e:ny(e,r)})},setStickyModelSelection:e=>{let t=lv(e);n(e=>{if(!t)return e;let n={...e.stickyModelSelectionByProvider,[t.provider]:t};return rt(e.stickyModelSelectionByProvider,n)?e.stickyActiveProvider===t.provider?e:{stickyActiveProvider:t.provider}:{stickyModelSelectionByProvider:n,stickyActiveProvider:t.provider}})},applyStickyState:e=>{let r=P(t(),e)??``;r.length!==0&&n(e=>{let t=e.stickyModelSelectionByProvider,n=e.stickyActiveProvider;if(Object.keys(t).length===0&&n===null)return e;let i=e.draftsByThreadKey[r]??Rv(),a={...i.modelSelectionByProvider};for(let[e,n]of Object.entries(t))if(n){let t=a[e];a[e]={...n,model:t?.model??n.model}}if(rt(i.modelSelectionByProvider,a)&&i.activeProvider===n)return e;let o={...i,modelSelectionByProvider:a,activeProvider:n},s={...e.draftsByThreadKey};return N(o)?delete s[r]:s[r]=o,{draftsByThreadKey:s}})},setPrompt:(e,r)=>{let i=P(t(),e)??``;i.length!==0&&n(e=>{let t=e.draftsByThreadKey[i]??Rv();if(t.prompt===r)return e;let n={...t,prompt:r},a={...e.draftsByThreadKey};return N(n)?delete a[i]:a[i]=n,{draftsByThreadKey:a}})},setGeneratedPullRequestPrompt:(e,r)=>{let i=P(t(),e)??``;i.length!==0&&n(e=>{let t=e.draftsByThreadKey[i]??Rv();return{draftsByThreadKey:{...e.draftsByThreadKey,[i]:{...t,lastGeneratedPullRequestPrompt:r}}}})},setPendingAutoSubmit:(e,r)=>{let i=P(t(),e)??``;i.length!==0&&n(e=>{let t=e.draftsByThreadKey[i]??Rv();if((t.pendingAutoSubmit??!1)===r)return e;let n=r?{...t,pendingAutoSubmit:!0}:(()=>{let{pendingAutoSubmit:e,...n}=t;return n})(),a={...e.draftsByThreadKey};return N(n)?delete a[i]:a[i]=n,{draftsByThreadKey:a}})},stageComposerSubmission:(e,r,i,a,o,s,c)=>{let l=P(t(),e)??``;l.length!==0&&(n(e=>{let t=e.draftsByThreadKey[l];if(!t)return e;let n={prompt:t.prompt,attachments:[...c??t.persistedAttachments],files:(t.files??[]).map(({file:e,type:t,...n})=>n),terminalContexts:[...t.terminalContexts],startedAt:r,commandId:i,messageId:a,...o?{executionIntent:o}:{},...s},u={...e.draftsByThreadKey};return u[l]={...t,stagedSubmission:n},{draftsByThreadKey:u}}),bv.flush())},setStagedComposerExecutionIntent:(e,r)=>{let i=P(t(),e)??``;i.length!==0&&(n(e=>{let t=e.draftsByThreadKey[i];return t?.stagedSubmission?{draftsByThreadKey:{...e.draftsByThreadKey,[i]:{...t,stagedSubmission:{...t.stagedSubmission,executionIntent:r}}}}:e}),bv.flush())},clearStagedComposerSubmission:e=>{let r=P(t(),e)??``;r.length!==0&&n(e=>{let t=e.draftsByThreadKey[r];if(!t?.stagedSubmission)return e;let n={...t,stagedSubmission:null},i={...e.draftsByThreadKey};return N(n)?delete i[r]:i[r]=n,{draftsByThreadKey:i}})},setTerminalContexts:(e,r,i)=>{let a=P(t(),e),o=qv(t(),e);if(!a||!o)return;let s=z_(o,r);n(e=>{let t=e.draftsByThreadKey[a]??Rv(),n={...t,prompt:Wm(t.prompt,s.length),terminalContexts:s,...i?.preserveTextForReload?{stashTerminalContexts:s}:{stashTerminalContexts:[]}},r={...e.draftsByThreadKey};return N(n)?delete r[a]:r[a]=n,{draftsByThreadKey:r}})},setModelSelection:(e,r)=>{let i=P(t(),e)??``;if(i.length===0)return;let a=lv(r);n(e=>{let t=e.draftsByThreadKey[i];if(!t&&a===null)return e;let n=t??Rv(),r={...n.modelSelectionByProvider};if(a){let e=r[a.provider];a.options===void 0?r[a.provider]={provider:a.provider,model:a.model,...`providerAccountId`in a&&a.providerAccountId?{providerAccountId:a.providerAccountId}:e&&`providerAccountId`in e&&e.providerAccountId?{providerAccountId:e.providerAccountId}:{},...e?.options?{options:e.options}:{}}:r[a.provider]=a}let o=a?.provider??n.activeProvider;if(rt(n.modelSelectionByProvider,r)&&n.activeProvider===o)return e;let s={...n,modelSelectionByProvider:r,activeProvider:o},c={...e.draftsByThreadKey};return N(s)?delete c[i]:c[i]=s,{draftsByThreadKey:c}})},setModelOptions:(e,r)=>{let i=P(t(),e)??``;if(i.length===0)return;let a=cv(r);n(e=>{let t=e.draftsByThreadKey[i];if(!t&&a===null)return e;let n=t??Rv(),r={...n.modelSelectionByProvider};for(let e of[`codex`,`claudeAgent`]){if(!a||!(e in a))continue;let t=a[e],n=r[e];if(t)r[e]={provider:e,model:n?.model??Fi[e],...n&&`providerAccountId`in n&&n.providerAccountId?{providerAccountId:n.providerAccountId}:{},options:t};else if(n?.options){let{options:t,...i}=n;r[e]=i}}if(rt(n.modelSelectionByProvider,r))return e;let o={...n,modelSelectionByProvider:r},s={...e.draftsByThreadKey};return N(o)?delete s[i]:s[i]=o,{draftsByThreadKey:s}})},setProviderModelOptions:(e,r,i,a)=>{let o=P(t(),e)??``;if(o.length===0)return;let s=av(r);if(s===null)return;let c=cv({[s]:i},s)?.[s];n(e=>{let t=e.draftsByThreadKey[o]??Rv(),n={...t.modelSelectionByProvider},r=n[s];if(c)n[s]={provider:s,model:r?.model??Fi[s],...r&&`providerAccountId`in r&&r.providerAccountId?{providerAccountId:r.providerAccountId}:{},options:c};else if(r?.options){let{options:e,...t}=r;n[s]=t}let i=e.stickyModelSelectionByProvider,l=e.stickyActiveProvider;if(a?.persistSticky===!0){i={...e.stickyModelSelectionByProvider};let n=i[s]??t.modelSelectionByProvider[s]??{provider:s,model:Fi[s]};if(c)i[s]={...n,provider:s,options:c};else if(n.options){let{options:e,...t}=n;i[s]=t}l=t.activeProvider??s}if(rt(t.modelSelectionByProvider,n)&&rt(e.stickyModelSelectionByProvider,i)&&e.stickyActiveProvider===l)return e;let u={...t,modelSelectionByProvider:n},d={...e.draftsByThreadKey};return N(u)?delete d[o]:d[o]=u,{draftsByThreadKey:d,...a?.persistSticky===!0?{stickyModelSelectionByProvider:i,stickyActiveProvider:l}:{}}})},setRuntimeMode:(e,r)=>{let i=P(t(),e)??``;if(i.length===0)return;let a=_v(r)?r:null;n(e=>{let t=e.draftsByThreadKey[i];if(!t&&a===null)return e;let n=t??Rv();if(n.runtimeMode===a)return e;let r={...n,runtimeMode:a},o={...e.draftsByThreadKey};return N(r)?delete o[i]:o[i]=r,{draftsByThreadKey:o}})},setInteractionMode:(e,r)=>{let i=P(t(),e)??``;if(i.length===0)return;let a=r===`plan`||r==="default"?r:null;n(e=>{let t=e.draftsByThreadKey[i];if(!t&&a===null)return e;let n=t??Rv();if(n.interactionMode===a)return e;let r={...n,interactionMode:a},o={...e.draftsByThreadKey};return N(r)?delete o[i]:o[i]=r,{draftsByThreadKey:o}})},addImage:(e,n)=>{let r=P(t(),e),i=qv(t(),e);!r||!i||t().addImages(typeof e==`string`?ba.make(r):e,[n])},addImages:(e,r)=>{let i=P(t(),e)??``;i.length!==0&&r.length!==0&&n(e=>{let t=e.draftsByThreadKey[i]??Rv(),n=new Set(t.images.map(e=>e.id)),a=new Set(t.images.map(e=>I_(e))),o=new Set(t.images.map(e=>e.previewUrl)),s=[];for(let e of r){let t=I_(e);if(n.has(e.id)||a.has(t)){o.has(e.previewUrl)||G_(e.previewUrl);continue}s.push(e),n.add(e.id),a.add(t),o.add(e.previewUrl)}return s.length===0?e:{draftsByThreadKey:{...e.draftsByThreadKey,[i]:{...t,images:[...t.images,...s]}}}})},addFiles:(e,r)=>{let i=P(t(),e)??``;i.length!==0&&r.length!==0&&n(e=>{let t=e.draftsByThreadKey[i]??Rv(),n=new Set((t.files??[]).map(e=>e.id)),a=Math.max(0,8-t.images.length-(t.files?.length??0)),o=r.filter(e=>!n.has(e.id)).slice(0,a);return o.length===0?e:{draftsByThreadKey:{...e.draftsByThreadKey,[i]:{...t,files:[...t.files??[],...o]}}}})},setFiles:(e,r)=>{let i=P(t(),e)??``;i.length!==0&&n(e=>{let t=e.draftsByThreadKey[i]??Rv();return{draftsByThreadKey:{...e.draftsByThreadKey,[i]:{...t,files:[...r]}}}})},removeImage:(e,r)=>{let i=P(t(),e)??``;if(i.length===0)return;let a=t().draftsByThreadKey[i];if(!a)return;let o=a.images.find(e=>e.id===r);o&&G_(o.previewUrl),n(e=>{let t=e.draftsByThreadKey[i];if(!t)return e;let n={...t,images:t.images.filter(e=>e.id!==r),nonPersistedImageIds:t.nonPersistedImageIds.filter(e=>e!==r),persistedAttachments:t.persistedAttachments.filter(e=>e.id!==r)},a={...e.draftsByThreadKey};return N(n)?delete a[i]:a[i]=n,{draftsByThreadKey:a}})},insertTerminalContext:(e,r,i,a)=>{let o=P(t(),e),s=qv(t(),e);if(!o||!s)return!1;let c=!1;return n(e=>{let t=e.draftsByThreadKey[o]??Rv(),n=R_(s,i);if(!n)return e;let l=L_(n);if(t.terminalContexts.some(e=>e.id===n.id)||t.terminalContexts.some(e=>L_(e)===l))return e;c=!0;let u=Math.max(0,Math.min(t.terminalContexts.length,a)),d={...t,prompt:r,terminalContexts:[...t.terminalContexts.slice(0,u),n,...t.terminalContexts.slice(u)]};return{draftsByThreadKey:{...e.draftsByThreadKey,[o]:d}}}),c},addTerminalContext:(e,n)=>{let r=P(t(),e),i=qv(t(),e);!r||!i||t().addTerminalContexts(typeof e==`string`?ba.make(r):e,[n])},addTerminalContexts:(e,r)=>{let i=P(t(),e),a=qv(t(),e);!i||!a||r.length===0||n(e=>{let t=e.draftsByThreadKey[i]??Rv(),n=z_(a,[...t.terminalContexts,...r]).slice(t.terminalContexts.length);return n.length===0?e:{draftsByThreadKey:{...e.draftsByThreadKey,[i]:{...t,prompt:Wm(t.prompt,t.terminalContexts.length+n.length),terminalContexts:[...t.terminalContexts,...n]}}}})},removeTerminalContext:(e,r)=>{let i=P(t(),e)??``;i.length!==0&&r.length!==0&&n(e=>{let t=e.draftsByThreadKey[i];if(!t)return e;let n={...t,terminalContexts:t.terminalContexts.filter(e=>e.id!==r)},a={...e.draftsByThreadKey};return N(n)?delete a[i]:a[i]=n,{draftsByThreadKey:a}})},clearTerminalContexts:e=>{let r=P(t(),e)??``;r.length!==0&&n(e=>{let t=e.draftsByThreadKey[r];if(!t||t.terminalContexts.length===0)return e;let n={...t,terminalContexts:[]},i={...e.draftsByThreadKey};return N(n)?delete i[r]:i[r]=n,{draftsByThreadKey:i}})},clearPersistedAttachments:e=>{let r=P(t(),e)??``;r.length!==0&&n(e=>{let t=e.draftsByThreadKey[r];if(!t)return e;let n={...t,persistedAttachments:[],nonPersistedImageIds:[]},i={...e.draftsByThreadKey};return N(n)?delete i[r]:i[r]=n,{draftsByThreadKey:i}})},syncPersistedAttachments:(e,r)=>{let i=P(t(),e);if(!i)return;let a=new Set(r.map(e=>e.id));n(e=>{let t=e.draftsByThreadKey[i];if(!t)return e;let n={...t,persistedAttachments:r,nonPersistedImageIds:t.nonPersistedImageIds.filter(e=>!a.has(e))},o={...e.draftsByThreadKey};return N(n)?delete o[i]:o[i]=n,{draftsByThreadKey:o}}),Promise.resolve().then(()=>{uy(i,r,n)})},moveComposerDraft:(e,r)=>{let i=dm(t().draftsByThreadKey,e,r);return i!==null&&(n({draftsByThreadKey:i}),bv.flush(),!0)},clearComposerContent:e=>{let r=P(t(),e)??``;r.length!==0&&n(e=>{let t=e.draftsByThreadKey[r];if(!t)return e;let n=iv(t),i={...e.draftsByThreadKey};return N(n)?delete i[r]:i[r]=n,{draftsByThreadKey:i}})},clearComposerContentIfUnchanged:(e,r)=>{let i=P(t(),e)??``;if(i.length===0)return!1;let a=!1;return n(e=>{let t=e.draftsByThreadKey[i];if(!t||!rv(t,r))return e;let n=iv(t),o={...e.draftsByThreadKey};return N(n)?delete o[i]:o[i]=n,a=!0,{draftsByThreadKey:o}}),a},restoreComposerStash:(e,r)=>{let i=P(t(),e)??``,a=qv(t(),e);if(i.length===0||!a)return!1;let o,s;if(n(e=>{let t=P_(e.draftsByThreadKey,i,a,r);return t?(o=t.previousDraft,s=t.restoredDraft,{draftsByThreadKey:t.drafts}):e}),!s)return!1;let c=!1;try{bv.flush();let e=ly(i),n=t().draftsByThreadKey[i];e!==null&&n===s&&W_(e,n)&&(c=!0)}catch{}if(c&&(r.onPersisted?.()??!0))return!0;n(e=>{if(e.draftsByThreadKey[i]!==s)return e;let t={...e.draftsByThreadKey};return o?t[i]=o:delete t[i],{draftsByThreadKey:t}});try{bv.flush()}catch{}return!1}}},{name:mv,version:hv,storage:Hf(()=>bv),migrate:ay,partialize:oy,merge:(e,t)=>{let n=sy(e),r=Object.fromEntries(Object.entries(n.draftsByThreadKey).map(([e,t])=>[e,my(t)])),i=Object.fromEntries(Object.entries(n.draftThreadsByThreadKey).map(([e,t])=>[e,hy(t)]));return{...t,draftsByThreadKey:r,draftThreadsByThreadKey:i,logicalProjectDraftThreadKeyByLogicalProjectKey:n.logicalProjectDraftThreadKeyByLogicalProjectKey,stickyModelSelectionByProvider:n.stickyModelSelectionByProvider??{},stickyActiveProvider:n.stickyActiveProvider??null}}}));function _y(e){let t=(0,A.c)(2),n;return t[0]===e?n=t[1]:(n=t=>Jv(t,e)??Lv,t[0]=e,t[1]=n),gy(n)}function vy(e){let t=(0,A.c)(2),n;return t[0]===e?n=t[1]:(n=t=>{let n=Jv(t,e);return n?{activeProvider:n.activeProvider,modelSelectionByProvider:n.modelSelectionByProvider}:Iv},t[0]=e,t[1]=n),gy(eh(n))}function yy(e){let t=gy.getState();for(let[n,r]of Object.entries(t.draftThreadsByThreadKey))r.environmentId===e.environmentId&&r.threadId===e.threadId&&t.markDraftThreadPromoting(ba.make(n),e)}function by(e){for(let t of e)yy(t)}function xy(e){let t=gy.getState();for(let[n,r]of Object.entries(t.draftThreadsByThreadKey))r.promotedTo&&r.promotedTo.environmentId===e.environmentId&&r.promotedTo.threadId===e.threadId&&t.finalizePromotedDraftThread(ba.make(n))}var Sy=null;function Cy(e){Sy=e}function wy(){if(Sy===null)throw Error(`Environment event handling was used before the service was configured.`);return Sy}function Ty(e){let t=new Set,n=new Map(e.snapshotThreads.map(e=>[e.key,e]));for(let n of e.snapshotThreads)n.deletedAt===null&&n.archivedAt===null&&t.add(n.key);for(let r of e.draftThreadKeys){let e=n.get(r);e&&(e.deletedAt!==null||e.archivedAt!==null)||t.add(r)}return t}function Ey(e){let t=new Map,n=!1;for(let r of e)switch(r.type){case`thread.turn-diff-completed`:case`thread.reverted`:n=!0;break;case`thread.created`:t.set(r.payload.threadId,{clearPromotedDraft:!0,clearDeletedThread:!1,removeTerminalState:!1});break;case`thread.deleted`:t.set(r.payload.threadId,{clearPromotedDraft:!1,clearDeletedThread:!0,removeTerminalState:!0});break;case`thread.archived`:t.set(r.payload.threadId,{clearPromotedDraft:!1,clearDeletedThread:!1,removeTerminalState:!0});break;case`thread.unarchived`:t.set(r.payload.threadId,{clearPromotedDraft:!1,clearDeletedThread:!1,removeTerminalState:!1})}let r=[],i=[],a=[];for(let[e,n]of t)n.clearPromotedDraft&&r.push(e),n.clearDeletedThread&&i.push(e),n.removeTerminalState&&a.push(e);return{promoteDraftThreadIds:r,clearDeletedThreadIds:i,removeTerminalStateThreadIds:a,needsProviderInvalidation:n}}var Dy={threadRef:null,open:!1,minimized:!1,dock:`floating`,position:null};function Oy(e){return{x:Math.max(12,Math.min(e.position.x,e.viewportWidth-e.width-12)),y:Math.max(12,Math.min(e.position.y,e.viewportHeight-e.height-12))}}function ky(e,t){return{...e,threadRef:t,open:!0,minimized:!1}}function Ay(e){let t=e.companion.threadRef;return!e.companion.open||t===null?!1:e.routeThreadRef?.environmentId!==t.environmentId||e.routeThreadRef.threadId!==t.threadId}function jy(e){if(!e||typeof e!=`object`)return null;let t=e;return typeof t.snoozedAt!=`string`||t.snoozedAt.length===0||typeof t.snoozedUntil!=`string`||t.snoozedUntil.length===0?null:{snoozedAt:t.snoozedAt,snoozedUntil:t.snoozedUntil}}function My(e){if(!e||typeof e!=`object`)return{};let t={};for(let[n,r]of Object.entries(e)){if(typeof n!=`string`||n.length===0)continue;let e=jy(r);e&&(t[n]=e)}return t}function Ny(e,t,n){let r=n??new Date().toISOString(),i=Date.parse(r),a=e.threadLastVisitedAtById[t],o=a?Date.parse(a):NaN;return Number.isFinite(o)&&Number.isFinite(i)&&o>=i?e:{...e,threadLastVisitedAtById:{...e.threadLastVisitedAtById,[t]:r}}}function Py(e,t,n){if(!n)return e;let r=Date.parse(n);if(Number.isNaN(r))return e;let i=new Date(r-1).toISOString();return e.threadLastVisitedAtById[t]===i?e:{...e,threadLastVisitedAtById:{...e.threadLastVisitedAtById,[t]:i}}}function Fy(e,t){let n=t in e.threadLastVisitedAtById,r=t in e.threadChangedFilesExpandedById,i=t in e.pinnedThreadById,a=t in e.threadLinkedPrById,o=t in e.pinOrderKeyById,s=t in e.activeOrderKeyById,c=t in e.threadSnoozeById;if(!n&&!r&&!i&&!a&&!o&&!s&&!c)return e;let l={...e.threadLastVisitedAtById},u={...e.threadChangedFilesExpandedById},d={...e.pinnedThreadById},f={...e.threadLinkedPrById},p={...e.pinOrderKeyById},m={...e.activeOrderKeyById},h={...e.threadSnoozeById};return delete l[t],delete u[t],delete d[t],delete f[t],delete p[t],delete m[t],delete h[t],{...e,threadLastVisitedAtById:l,threadChangedFilesExpandedById:u,pinnedThreadById:d,threadLinkedPrById:f,pinOrderKeyById:p,activeOrderKeyById:m,threadSnoozeById:h}}function Iy(e,t,n){if(e.pinnedThreadById[t]===!0===n)return e;if(n)return{...e,pinnedThreadById:{...e.pinnedThreadById,[t]:!0}};let r={...e.pinnedThreadById};return delete r[t],{...e,pinnedThreadById:r}}function Ly(e,t){return Iy(e,t,e.pinnedThreadById[t]!==!0)}function Ry(e,t,n){let r=e.pinOrderKeyById[t];if(n===null){if(r===void 0)return e;let n={...e.pinOrderKeyById};return delete n[t],{...e,pinOrderKeyById:n}}return r===n?e:{...e,pinOrderKeyById:{...e.pinOrderKeyById,[t]:n}}}function zy(e,t,n){let r=e.activeOrderKeyById[t];if(n===null){if(r===void 0)return e;let n={...e.activeOrderKeyById};return delete n[t],{...e,activeOrderKeyById:n}}return r===n?e:{...e,activeOrderKeyById:{...e.activeOrderKeyById,[t]:n}}}function By(e,t,n){if(n===null){if(!(t in e.threadSnoozeById))return e;let n={...e.threadSnoozeById};return delete n[t],{...e,threadSnoozeById:n}}let r=e.threadSnoozeById[t];return r&&r.snoozedAt===n.snoozedAt&&r.snoozedUntil===n.snoozedUntil?e:{...e,threadSnoozeById:{...e.threadSnoozeById,[t]:n}}}function Vy(e,t,n){return e.threadLinkedPrById[t]===n?e:{...e,threadLinkedPrById:{...e.threadLinkedPrById,[t]:n}}}function Hy(e,t){if(!(t in e.threadLinkedPrById))return e;let n={...e.threadLinkedPrById};return delete n[t],{...e,threadLinkedPrById:n}}function Uy(e,t,n,r){let i=e.threadChangedFilesExpandedById[t]??{};return i[n]===r?e:{...e,threadChangedFilesExpandedById:{...e.threadChangedFilesExpandedById,[t]:{...i,[n]:r}}}}var Wy=`forge:ui-state:v1`,Gy=[`t3code:ui-state:v1`,`t3code:renderer-state:v8`,`t3code:renderer-state:v7`,`t3code:renderer-state:v6`,`t3code:renderer-state:v5`,`t3code:renderer-state:v4`,`t3code:renderer-state:v3`,`codething:renderer-state:v4`,`codething:renderer-state:v3`,`codething:renderer-state:v2`,`codething:renderer-state:v1`],Ky=`months`,qy=new Set([`weeks`,`months`,`quarters`]);function Jy(e){return typeof e==`string`&&qy.has(e)?e:Ky}function Yy(e){return Number.isFinite(e)?Math.round(Math.min(560,Math.max(200,e))):360}var Xy={projectExpandedById:{},projectOrder:[],projectGroupOrder:[],lastActiveProject:null,threadLastVisitedAtById:{},threadChangedFilesExpandedById:{},pinnedThreadById:{},threadLinkedPrById:{},pinOrderKeyById:{},activeOrderKeyById:{},threadSnoozeById:{},workspaceDensityById:{},timelineWorkColumnWidth:360,timelineScale:Ky,projectLeadCompanion:Dy},Zy=new Set,Qy=[],$y=new Map,eb=!1;function tb(){if(typeof window>`u`)return Xy;try{let e=window.localStorage.getItem(Wy);if(!e){for(let e of Gy){let t=window.localStorage.getItem(e);if(t)return ub(JSON.parse(t)),Xy}return Xy}let t=JSON.parse(e);return ub(t),{...Xy,projectGroupOrder:nb(t.projectGroupOrderKeys),threadChangedFilesExpandedById:ob(t.threadChangedFilesExpandedById),pinnedThreadById:rb(t.pinnedThreadKeys),threadLinkedPrById:ib(t.threadLinkedPrById),pinOrderKeyById:ab(t.pinOrderKeyById),activeOrderKeyById:ab(t.activeOrderKeyById),threadSnoozeById:My(t.threadSnoozeById),timelineWorkColumnWidth:Yy(t.timelineWorkColumnWidth??360),timelineScale:Jy(t.timelineScale)}}catch{return Xy}}function nb(e){return Array.isArray(e)?[...new Set(e.filter(e=>typeof e==`string`&&e.length>0))]:[]}function rb(e){if(!Array.isArray(e))return{};let t={};for(let n of e)typeof n==`string`&&n.length>0&&(t[n]=!0);return t}function ib(e){if(!e||typeof e!=`object`)return{};let t={};for(let[n,r]of Object.entries(e))typeof n==`string`&&n.length!==0&&typeof r==`string`&&r.trim().length!==0&&(t[n]=r);return t}function ab(e){if(!e||typeof e!=`object`)return{};let t={};for(let[n,r]of Object.entries(e))typeof n==`string`&&n.length>0&&typeof r==`string`&&r.length>0&&(t[n]=r);return t}function ob(e){if(!e||typeof e!=`object`)return{};let t={};for(let[n,r]of Object.entries(e)){let e=sb(r);Object.keys(e).length>0&&(t[n]=e)}return t}function sb(e){let t={};if(!e||typeof e!=`object`)return t;for(let[n,r]of Object.entries(e))n&&typeof r==`boolean`&&r===!1&&(t[n]=!1);return t}function cb(e){for(let t of e)typeof t==`string`&&t.length>0&&Zy.add(t)}function lb(e){for(let t of e)typeof t==`string`&&t.length>0&&!Qy.includes(t)&&Qy.push(t)}function ub(e){Zy.clear(),Qy.length=0,cb(e.expandedProjectCwds??[]),lb(e.projectOrderCwds??[])}function db(e){if(!(typeof window>`u`))try{let t=Object.entries(e.projectExpandedById).filter(([,e])=>e).flatMap(([e])=>{let t=$y.get(e);return t?[t]:[]}),n=e.projectOrder.flatMap(e=>{let t=$y.get(e);return t?[t]:[]}),r=Object.fromEntries(Object.entries(e.threadChangedFilesExpandedById).flatMap(([e,t])=>{let n=Object.fromEntries(Object.entries(t).filter(([,e])=>e===!1));return Object.keys(n).length>0?[[e,n]]:[]}));if(window.localStorage.setItem(Wy,JSON.stringify({expandedProjectCwds:t,projectOrderCwds:n,projectGroupOrderKeys:e.projectGroupOrder,threadChangedFilesExpandedById:r,pinnedThreadKeys:Object.keys(e.pinnedThreadById).filter(t=>e.pinnedThreadById[t]),threadLinkedPrById:e.threadLinkedPrById,pinOrderKeyById:e.pinOrderKeyById,activeOrderKeyById:e.activeOrderKeyById,threadSnoozeById:e.threadSnoozeById,timelineWorkColumnWidth:e.timelineWorkColumnWidth,timelineScale:e.timelineScale})),!eb){eb=!0;for(let e of Gy)window.localStorage.removeItem(e)}}catch{}}var fb=new Aa(db,{wait:500});function pb(e,t){let n=Object.entries(e),r=Object.entries(t);if(n.length!==r.length)return!1;for(let[e,r]of n)if(t[e]!==r)return!1;return!0}function mb(e,t){return e.length===t.length&&e.every((e,n)=>e===t[n])}function hb(e,t){let n=Object.entries(e),r=Object.entries(t);if(n.length!==r.length)return!1;for(let[e,r]of n)if(!(e in t)||!pb(r,t[e]))return!1;return!0}function gb(e,t){let n=new Map($y),r=new Map([...n.entries()].map(([e,t])=>[t,e]));$y.clear();for(let e of t)$y.set(e.key,e.cwd);let i=n.size!==$y.size||t.some(e=>n.get(e.key)!==e.cwd),a={},o=e.projectExpandedById,s=new Map(Qy.map((e,t)=>[e,t])),c=t.map((e,t)=>{let n=r.get(e.cwd),i=o[e.key]??(n?o[n]:void 0)??(Zy.size>0?Zy.has(e.cwd):!0);return a[e.key]=i,{id:e.key,cwd:e.cwd,incomingIndex:t}}),l=e.projectOrder.length>0?(()=>{let t=new Map(c.map(e=>[e.cwd,e.id])),r=new Set,i=[];for(let o of e.projectOrder){let e=(o in a?o:void 0)??(()=>{let e=n.get(o);return e?t.get(e):void 0})();!e||r.has(e)||(r.add(e),i.push(e))}for(let e of c)r.has(e.id)||i.push(e.id);return i})():c.map(e=>({id:e.id,incomingIndex:e.incomingIndex,orderIndex:s.get(e.cwd)??Qy.length+e.incomingIndex})).toSorted((e,t)=>{let n=e.orderIndex-t.orderIndex;return n===0?e.incomingIndex-t.incomingIndex:n}).map(e=>e.id);return pb(e.projectExpandedById,a)&&mb(e.projectOrder,l)&&!i?e:{...e,projectExpandedById:a,projectOrder:l}}function _b(e,t){let n=new Set(t.map(e=>e.key)),r=Object.fromEntries(Object.entries(e.threadLastVisitedAtById).filter(([e])=>n.has(e)));for(let e of t)r[e.key]===void 0&&e.seedVisitedAt!==void 0&&e.seedVisitedAt.length>0&&(r[e.key]=e.seedVisitedAt);let i=Object.fromEntries(Object.entries(e.threadChangedFilesExpandedById).filter(([e])=>n.has(e))),a=Object.fromEntries(Object.entries(e.pinnedThreadById).filter(([e,t])=>n.has(e)&&t)),o=Object.fromEntries(Object.entries(e.threadLinkedPrById).filter(([e])=>n.has(e))),s=Object.fromEntries(Object.entries(e.pinOrderKeyById).filter(([e])=>n.has(e))),c=Object.fromEntries(Object.entries(e.activeOrderKeyById).filter(([e])=>n.has(e))),l=Object.fromEntries(Object.entries(e.threadSnoozeById).filter(([e])=>n.has(e)));return pb(e.threadLastVisitedAtById,r)&&hb(e.threadChangedFilesExpandedById,i)&&pb(e.pinnedThreadById,a)&&pb(e.threadLinkedPrById,o)&&pb(e.pinOrderKeyById,s)&&pb(e.activeOrderKeyById,c)&&pb(e.threadSnoozeById,l)?e:{...e,threadLastVisitedAtById:r,threadChangedFilesExpandedById:i,pinnedThreadById:a,threadLinkedPrById:o,pinOrderKeyById:s,activeOrderKeyById:c,threadSnoozeById:l}}function vb(e,t){return e.lastActiveProject?.environmentId===t?.environmentId&&e.lastActiveProject?.projectId===t?.projectId?e:{...e,lastActiveProject:t}}function yb(e,t,n){return e.workspaceDensityById[t]===n?e:{...e,workspaceDensityById:{...e.workspaceDensityById,[t]:n}}}function bb(e,t){let n=e.projectExpandedById[t]??!0;return{...e,projectExpandedById:{...e.projectExpandedById,[t]:!n}}}function xb(e,t,n){return(e.projectExpandedById[t]??!0)===n?e:{...e,projectExpandedById:{...e.projectExpandedById,[t]:n}}}function Sb(e,t,n){if(t.length===0)return e;let r=new Set(t),i=new Set(n);if(t.every(e=>i.has(e)))return e;let a=e.projectOrder.findIndex(e=>i.has(e));if(a<0)return e;let o=[...e.projectOrder],s=[],c=0;for(let e=o.length-1;e>=0;e--)r.has(o[e])&&(s.unshift(o.splice(e,1)[0]),e<a&&c++);if(s.length===0)return e;let l=a-Math.max(0,c-1);return o.splice(l,0,...s),{...e,projectOrder:o}}function Cb(e,t){let n=[...new Set(t)],r=new Set(n),i=e.projectGroupOrder.filter(e=>r.has(e)),a=new Set(i);for(let e of n)a.has(e)||i.push(e);return mb(e.projectGroupOrder,i)?e:{...e,projectGroupOrder:i}}function wb(e,t,n){if(t===n)return e;let r=e.projectGroupOrder.indexOf(t),i=e.projectGroupOrder.indexOf(n);if(r<0||i<0)return e;let a=[...e.projectGroupOrder],[o]=a.splice(r,1);return o===void 0?e:(a.splice(i,0,o),{...e,projectGroupOrder:a})}var Tb=wa(e=>({...tb(),syncProjects:t=>e(e=>gb(e,t)),syncProjectGroups:t=>e(e=>Cb(e,t)),syncThreads:t=>e(e=>_b(e,t)),markThreadVisited:(t,n)=>e(e=>Ny(e,t,n)),markThreadUnread:(t,n)=>e(e=>Py(e,t,n)),clearThreadUi:t=>e(e=>Fy(e,t)),setThreadPinned:(t,n)=>e(e=>Iy(e,t,n)),toggleThreadPinned:t=>e(e=>Ly(e,t)),setThreadPinOrderKey:(t,n)=>e(e=>Ry(e,t,n)),setThreadActiveOrderKey:(t,n)=>e(e=>zy(e,t,n)),setThreadSnooze:(t,n)=>e(e=>By(e,t,n)),setThreadLinkedPr:(t,n)=>e(e=>Vy(e,t,n)),clearThreadLinkedPr:t=>e(e=>Hy(e,t)),setThreadChangedFilesExpanded:(t,n,r)=>e(e=>Uy(e,t,n,r)),setWorkspaceDensity:(t,n)=>e(e=>yb(e,t,n)),toggleProject:t=>e(e=>bb(e,t)),setProjectExpanded:(t,n)=>e(e=>xb(e,t,n)),reorderProjects:(t,n)=>e(e=>Sb(e,t,n)),reorderProjectGroups:(t,n)=>e(e=>wb(e,t,n)),setLastActiveProject:t=>e(e=>vb(e,t)),setTimelineWorkColumnWidth:t=>e(e=>({...e,timelineWorkColumnWidth:Yy(t)})),setTimelineScale:t=>e(e=>({...e,timelineScale:t})),openProjectLeadCompanion:t=>e(e=>({...e,projectLeadCompanion:ky(e.projectLeadCompanion,t)})),closeProjectLeadCompanion:()=>e(e=>({...e,projectLeadCompanion:{...e.projectLeadCompanion,open:!1}})),setProjectLeadCompanionMinimized:t=>e(e=>({...e,projectLeadCompanion:{...e.projectLeadCompanion,minimized:t}})),setProjectLeadCompanionDock:t=>e(e=>({...e,projectLeadCompanion:{...e.projectLeadCompanion,dock:t}})),setProjectLeadCompanionPosition:t=>e(e=>({...e,projectLeadCompanion:{...e.projectLeadCompanion,position:t}}))}));function Eb(e){Tb.getState().openProjectLeadCompanion(e)}Tb.subscribe(e=>fb.maybeExecute(e)),typeof window<`u`&&typeof window.addEventListener==`function`&&window.addEventListener(`beforeunload`,()=>{fb.flush()});var F=new Map;function Db(e){return!e.isWorking||e.msSinceLastEvent<e.stallThresholdMs?`none`:e.recoveryAttempts<e.maxResubscribeAttempts?`resubscribe`:e.recoveryAttempts<e.maxTotalAttempts?`reconnect`:`none`}var Ob=3e4,kb=1e4,Ab=[/(?:^|\s)\/(?:Users|var|private|tmp|project|repo|home)\/[^\s'"<>)]*/i,/(?:^|\s)[A-Za-z]:\\[^\s'"<>)]*/];function jb(e){let t=e?.trim();return t&&t.length>0?t:null}function Mb(e){return jb(e)??`Project`}function Nb(e,t=`safe`){let n=jb(e);return n?t===`full`?n:n.replaceAll(`\\`,`/`).split(`/`).filter(Boolean).at(-1)??`Local checkout`:`Local checkout`}function Pb(e,t=`Something went wrong. Try again.`){let n=e instanceof Error?e.message:typeof e==`string`?e:String(e),r=dr(n,{fallback:t});return!r||Ab.some(e=>e.test(r))?t:r}var Fb=`Thread not found or you no longer have access.`;function Ib(e){if(e==null)return Fb;let t=Pb(qt(e)?ke(e):e,Fb);return/\bnot found\b/i.test(t)?Fb:t}function Lb(e,t,n){S.getState().setThreadSubscriptionError(e,t,Ib(n))}var Rb=null;function zb(e){Rb=e}function Bb(){if(Rb===null)throw Error(`Thread detail subscriptions were used before the service was configured.`);return Rb}var Vb=9e5,Hb=()=>void 0;function Ub(e,t){return Ln(C(e,t))}function Wb(e){return e.evictionTimeoutId!==null&&(clearTimeout(e.evictionTimeoutId),e.evictionTimeoutId=null),e}function Gb(e){let t=C(e.environmentId,e.threadId),n=S.getState(),r=Tn(n,t);if(r&&qb(r))return!0;let i=Sn(n,t);return i?Kb(i.session?.orchestrationStatus)||i.latestTurn?.state===`running`||i.pendingSourceProposedPlan!==void 0:!1}function Kb(e){return!!(e&&e!==`idle`&&e!==`stopped`)}function qb(e){return e.hasPendingApprovals||e.hasPendingUserInput||e.hasActionableProposedPlan||Kb(e.session?.orchestrationStatus)||e.latestTurn?.state===`running`}function Jb(e){return e.refCount===0&&!Gb(e)}function Yb(e){let t=Bb().readConnection(e.environmentId);return e.unsubscribe===Hb&&!t?!1:(e.unsubscribeConnectionListener!==null&&(e.unsubscribeConnectionListener(),e.unsubscribeConnectionListener=null),e.unsubscribe!==Hb||!t||(e.unsubscribe=t.client.orchestration.subscribeThread({threadId:e.threadId},t=>{e.lastEventAt=Date.now(),e.recoveryAttempts=0,t.kind===`event`?Bb().applyEvent(t.event,e.environmentId):t.kind===`snapshot`&&(S.getState().syncServerThreadDetail(t.snapshot.thread,e.environmentId),S.getState().clearThreadSubscriptionError(e.environmentId,e.threadId))},{onError:t=>Lb(e.environmentId,e.threadId,t)})),!0)}function Xb(e){e.unsubscribeConnectionListener===null&&(e.unsubscribeConnectionListener=Bb().subscribeConnections(()=>{Yb(e)&&(e.lastAccessedAt=Date.now())}),Yb(e))}var Zb=null;function Qb(e){let t=C(e.environmentId,e.threadId),n=S.getState(),r=Tn(n,t);if(r?.latestTurn?.state===`running`||r?.session?.orchestrationStatus===`running`)return!0;let i=Sn(n,t);return i?.latestTurn?.state===`running`||i?.session?.orchestrationStatus===`running`}function $b(e){e.unsubscribe!==Hb&&(e.unsubscribe(),e.unsubscribe=Hb),Yb(e)||Xb(e)}function ex(e,t,n){if(e.recoveryAttempts+=1,e.lastEventAt=Date.now(),console.warn(`[forge] thread-detail liveness watchdog recovering`,{action:t,threadId:String(e.threadId),environmentId:String(e.environmentId),msSinceLastEvent:Math.round(n),recoveryAttempts:e.recoveryAttempts}),t===`resubscribe`){$b(e);return}Bb().readConnection(e.environmentId)?.reconnect().catch(t=>{Vn(t,{route:`thread-detail-liveness-watchdog-reconnect-failed`,threadId:String(e.threadId),environmentId:String(e.environmentId),msSinceLastEvent:String(Math.round(n)),recoveryAttempts:String(e.recoveryAttempts)})})}function tx(){let e=Date.now();for(let t of F.values()){let n=Db({isWorking:Qb(t),msSinceLastEvent:e-t.lastEventAt,stallThresholdMs:Ob,recoveryAttempts:t.recoveryAttempts,maxResubscribeAttempts:2,maxTotalAttempts:4});n!==`none`&&ex(t,n,e-t.lastEventAt)}}function nx(){Zb===null&&(Zb=setInterval(tx,kb))}function rx(){F.size>0||Zb!==null&&(clearInterval(Zb),Zb=null)}function ix(e){let t=F.get(e);return t?(Wb(t),t.unsubscribeConnectionListener?.(),t.unsubscribeConnectionListener=null,F.delete(e),t.unsubscribe(),t.unsubscribe=Hb,rx(),!0):!1}function ax(e){ox(e,!0),j.getState().clear(e)}function ox(e,t=!1){for(let[n,r]of F)if(r.environmentId===e){if(r.refCount===0||t){ix(n);continue}r.unsubscribe(),r.unsubscribe=Hb,Xb(r)}}function sx(e){for(let t=e.messages.length-1;t>=0;--t){let n=e.messages[t];if(n?.role===`user`)return n.createdAt}return null}function cx(e){return e.session?{threadId:e.id,updatedAt:e.session.updatedAt,providerName:e.session.provider,runtimeMode:e.runtimeMode,activeTurnId:e.session.activeTurnId??null,lastError:e.session.lastError??null,status:e.session.orchestrationStatus}:null}function lx(e,t){return{updatedAt:e.updatedAt??e.createdAt,latestUserMessageAt:t?.latestUserMessageAt??sx(e),titleRegeneration:e.titleRegeneration??null}}function ux(e){return{hasPendingApprovals:e?.hasPendingApprovals??!1,hasPendingUserInput:e?.hasPendingUserInput??!1,hasActionableProposedPlan:e?.hasActionableProposedPlan??!1}}function dx(e){let t=C(e.environmentId,e.threadId),n=S.getState(),r=Sn(n,t);if(!r)return null;let i=Tn(n,t);return{id:r.id,projectId:r.projectId,title:r.title,modelSelection:r.modelSelection,runtimeMode:r.runtimeMode,interactionMode:r.interactionMode,branch:r.branch,worktreePath:r.worktreePath,latestTurn:r.latestTurn,createdAt:r.createdAt,...lx(r,i),...ux(i),archivedAt:r.archivedAt,session:cx(r),anchorKind:r.anchorKind,anchorCmmdId:r.anchorCmmdId,kind:r.kind,parentThreadId:r.parentThreadId,status:r.status,workerRole:r.workerRole,goal:r.goal}}function fx(e,t){if(F.size===0)return e;let n=new Set(e.threads.map(e=>e.id)),r=[];for(let e of F.values()){if(e.environmentId!==t||e.refCount<=0||n.has(e.threadId))continue;let i=dx(e);i&&(n.add(i.id),r.push(i))}return r.length===0?e:{...e,threads:[...e.threads,...r]}}function px(e,t){let n=new Set(t);for(let[t,r]of F)r.environmentId===e&&!n.has(r.threadId)&&Jb(r)&&ix(t)}function mx(e){Wb(e),Jb(e)&&(e.evictionTimeoutId=setTimeout(()=>{let t=F.get(Ub(e.environmentId,e.threadId));t&&(t.evictionTimeoutId=null,Jb(t)&&ix(Ub(e.environmentId,e.threadId)))},Vb))}function hx(){if(F.size<=32)return;let e=[...F.entries()].filter(([,e])=>Jb(e)).toSorted(([,e],[,t])=>e.lastAccessedAt-t.lastAccessedAt);for(let[t]of e){if(F.size<=32)return;ix(t)}}function gx(e){Wb(e),Jb(e)&&mx(e)}function _x(e,t){let n=F.get(Ub(e,t));n&&gx(n)}function vx(e){for(let t of F.values())t.environmentId===e&&gx(t);hx()}function yx(e){let t=!1;return()=>{t||(t=!0,e.refCount=Math.max(0,e.refCount-1),e.lastAccessedAt=Date.now(),e.refCount===0&&(gx(e),hx()))}}function bx(e,t){let n=Ub(e,t),r=F.get(n);if(r)return Wb(r),r.refCount+=1,r.lastAccessedAt=Date.now(),Yb(r)||Xb(r),yx(r);let i={environmentId:e,threadId:t,unsubscribe:Hb,unsubscribeConnectionListener:null,refCount:1,lastAccessedAt:Date.now(),evictionTimeoutId:null,lastEventAt:Date.now(),recoveryAttempts:0};return F.set(n,i),Yb(i)||Xb(i),nx(),hx(),yx(i)}function xx(e,t){return e.type!==`thread.message-sent`||t.type!==`thread.message-sent`||e.payload.threadId!==t.payload.threadId||e.payload.messageId!==t.payload.messageId?null:{...t,payload:{...t.payload,attachments:t.payload.attachments??e.payload.attachments,createdAt:e.payload.createdAt,text:!t.payload.streaming&&t.payload.text.length>0?t.payload.text:e.payload.text+t.payload.text}}}function Sx(e){if(e.length<2)return[...e];let t=[];for(let n of e){let e=t.at(-1),r=e?xx(e,n):null;if(r){t[t.length-1]=r;continue}t.push(n)}return t}function Cx(){let e=wn(S.getState());Tb.getState().syncProjects(e.map(e=>({key:Fn(In(e.environmentId,e.id)),cwd:e.cwd})))}function wx(){let e=mn(S.getState());Tb.getState().syncThreads(e.map(e=>({key:Ln(C(e.environmentId,e.id)),seedVisitedAt:e.updatedAt??e.createdAt}))),by(e.map(e=>C(e.environmentId,e.id)))}function Tx(){Cx(),wx();let e=Ty({snapshotThreads:mn(S.getState()).map(e=>({key:Ln(C(e.environmentId,e.id)),deletedAt:null,archivedAt:e.archivedAt})),draftThreadKeys:gy.getState().listDraftThreadKeys()});lm.getState().removeOrphanedTerminalStates(e)}function Ex(e){return e.serverThreadArchivedAt===void 0?e.hasDraftThread:e.serverThreadArchivedAt===null}function Dx(e,t){if(e.length===0)return;let n=Ey(e),r=Sx(e),i=e.some(e=>e.type===`project.created`||e.type===`project.meta-updated`||e.type===`project.deleted`);if(n.needsProviderInvalidation&&wy().notifyProviderInvalidation(),S.getState().applyOrchestrationEvents(r,t),i){let e=wn(S.getState());Tb.getState().syncProjects(e.map(e=>({key:Fn(In(e.environmentId,e.id)),cwd:e.cwd})))}if(e.some(e=>e.type===`thread.created`||e.type===`thread.deleted`)){let e=mn(S.getState());Tb.getState().syncThreads(e.map(e=>({key:Ln(C(e.environmentId,e.id)),seedVisitedAt:e.updatedAt??e.createdAt})))}let a=gy.getState();for(let e of n.promoteDraftThreadIds)yy(C(t,e));for(let e of n.clearDeletedThreadIds)a.clearDraftThread(C(t,e)),Tb.getState().clearThreadUi(Ln(C(t,e)));for(let e of n.removeTerminalStateThreadIds){let n=C(t,e);lm.getState().removeTerminalState(n),Pf.getState().clearBrowserState(n)}vx(t)}function Ox(e,t){Dx([e],t)}function kx(e,t){let n=e.kind===`thread-upserted`?e.thread.id:e.kind===`thread-removed`?e.threadId:null,r=n?C(t,n):null,i=r?Sn(S.getState(),r):void 0;switch(S.getState().applyShellEvent(e,t),e.kind){case`project-upserted`:case`project-removed`:Cx();return;case`thread-upserted`:wx(),!i&&r&&yy(r),i?.archivedAt===null&&e.thread.archivedAt!==null&&r&&(lm.getState().removeTerminalState(r),Pf.getState().clearBrowserState(r)),_x(t,e.thread.id),hx();return;case`thread-removed`:r&&(ix(Ln(r)),gy.getState().clearDraftThread(r),Tb.getState().clearThreadUi(Ln(r)),lm.getState().removeTerminalState(r),Pf.getState().clearBrowserState(r)),wx();return}}function Ax(e,t){return e.invalidateQueries({queryKey:Rf.all(t)})}function jx(e){return{onWelcome:(t,n)=>{e?.(t);let r=wy().readQueryClient();r&&Ax(r,n)},applyShellEvent:kx,syncShellSnapshot:(e,t)=>{let n=fx(e,t);S.getState().syncServerShellSnapshot(n,t),px(t,n.threads.map(e=>e.id)),vx(t),Tx()},applyTerminalEvent:(e,t)=>{let n=C(t,zr.make(e.threadId)),r=Sn(S.getState(),n),i=gy.getState().getDraftThreadByRef(n)!==null;Ex({serverThreadArchivedAt:r?.archivedAt,hasDraftThread:i})&&lm.getState().applyTerminalEvent(n,e)},applyBrowserEvent:(e,t)=>{let n=C(t,zr.make(e.threadId)),r=Sn(S.getState(),n),i=gy.getState().getDraftThreadByRef(n)!==null;Ex({serverThreadArchivedAt:r?.archivedAt,hasDraftThread:i})&&Pf.getState().applyBrowserEvent(n,e)},onShellSubscriptionError:(e,t)=>{wy().setRuntimeError(t,e)}}}function Mx(){return new Date().toISOString()}function Nx(e){j.getState().patch(e,{connectionState:`connecting`,lastError:null,lastErrorAt:null})}function Px(e){let t=Mx();j.getState().patch(e,{connectionState:`connected`,authState:`authenticated`,connectedAt:t,disconnectedAt:null,lastError:null,lastErrorAt:null}),ir.getState().markConnected(e,t)}function Fx(e,t){j.getState().patch(e,{descriptor:t.environment,serverConfig:t})}function Ix(e,t){j.getState().patch(e,{connectionState:`disconnected`,disconnectedAt:Mx(),...t&&t.trim().length>0?{lastError:t,lastErrorAt:Mx()}:{}})}function Lx(e,t){j.getState().patch(e,{connectionState:`error`,...vl(t)})}function Rx(){return new Date().toISOString()}function zx(e){let t=hr();if(!t?.environmentId)throw Error(`Unable to resolve the primary environment.`);let n=e.readConnection(t.environmentId);if(n)return n;let r=of(),i=t.source===`paired-bearer`||!0;return e.registerConnection(ql({kind:`primary`,knownEnvironment:t,client:cf(t),resolveEnvironmentId:()=>hr()?.environmentId??t.environmentId,...i?{readiness:r?{bearerToken:r.bearerToken}:{}}:{},...jx()}))}async function Bx(e){let t=sf();if(!t)throw Error(`Desktop Local runtime is not authenticated. Sign in with CMMD again before importing local projects.`);let n=await Il({httpBaseUrl:t.httpBaseUrl,bearerToken:t.bearerToken}),r=e.readConnection(n.environmentId);if(r)return r;let i=xn({id:n.environmentId,label:t.label,source:`desktop-managed`,target:{httpBaseUrl:t.httpBaseUrl,wsBaseUrl:t.wsBaseUrl}});return e.registerConnection(ql({kind:`desktop-local`,knownEnvironment:{...i,environmentId:n.environmentId,label:n.label},client:lf({environmentId:n.environmentId,httpBaseUrl:t.httpBaseUrl,wsBaseUrl:t.wsBaseUrl,bearerToken:t.bearerToken,onConnecting:Nx,onConnected:Px,onError:(e,t)=>{j.getState().patch(e,{connectionState:`error`,lastError:t,lastErrorAt:Rx()})},onDisconnected:Ix}),...jx()}))}var Vx=new Map;function Hx(e){for(let t of e){let e=Vx.get(t);e===void 0||e<=1?Vx.delete(t):Vx.set(t,e-1)}}async function Ux(e,t){let n=e.environmentId;Vx.set(n,(Vx.get(n)??0)+1);try{return t.readConnection(n)||await t.ensureCmmdRuntimeSavedEnvironmentConnection(e),!0}catch{return Hx([n]),!1}}async function Wx(e){await Qn();let t=(await Promise.all(ar().map(async t=>await Ux(t,e)?t.environmentId:null))).flatMap(e=>e===null?[]:[e]),n=!1;return()=>{n||(n=!0,Hx(t))}}function Gx(){return new Date().toISOString()}async function Kx(e,t){t.readConnection(e)?.kind===`saved`&&(j.getState().clear(e),await t.removeConnection(e).catch(()=>!1))}async function qx(e,t){let n=er(e);if(!n)throw Error(`Saved environment not found.`);let r=t.readConnection(e);if(!r){try{await t.ensureCmmdRuntimeSavedEnvironmentConnection(n)}catch(t){throw Lx(e,t),t}return}Nx(e);try{await r.reconnect()}catch(t){throw Lx(e,t),t}}async function Jx(e,t){t.invalidate(e),ir.getState().remove(e),await mr(e),await Kx(e,t)}async function Yx(e,t){let{existing:n,replacedRecord:r}=ml({environmentId:Hr.make(e.environment.environmentId),replacesEnvironmentId:e.environment.replacesEnvironmentId}),i=Xx(e.environment,n);al(e.signal);let a=await hl(n),o=t.readConnection(i.environmentId)!==null&&pl({existing:n,replacedRecord:r,record:i});return o||(t.invalidate(i.environmentId),await t.removeConnection(i.environmentId).catch(()=>!1)),r&&(t.invalidate(r.environmentId),await t.removeConnection(r.environmentId).catch(()=>!1)),await t.ensureCmmdRuntimeSavedEnvironmentConnection(i,{bearerToken:e.bearerToken,registryExpectation:n&&!r?{kind:`existing-record`,record:n}:{kind:`initial-add`},...e.signal?{signal:e.signal}:{},...e.onBootstrapRetry?{onBootstrapRetry:e.onBootstrapRetry}:{}}),Zx({record:i,replacedRecord:r,persistenceRollback:a,keepsLiveConnection:o,signal:e.signal,dependencies:t})}function Xx(e,t){let n=Hr.make(e.environmentId),{kind:r,cmmdOrganizationId:i,cmmdProjectId:a,runtimeId:o,runtimeTicketExpiresAt:s}=e;return{environmentId:n,label:e.label,wsBaseUrl:Jr(e.wsBaseUrl),httpBaseUrl:e.httpBaseUrl,createdAt:t?.createdAt??Gx(),lastConnectedAt:Gx(),...r===void 0?{}:{kind:r},...i===void 0?{}:{cmmdOrganizationId:i},...a===void 0?{}:{cmmdProjectId:a},...o===void 0?{}:{runtimeId:o},...s===void 0?{}:{runtimeTicketExpiresAt:s}}}async function Zx(e){let{record:t,replacedRecord:n,persistenceRollback:r,keepsLiveConnection:i,signal:a,dependencies:o}=e,s=!1;try{return al(a),await _l({record:t,replacedRecord:n,rollback:r,...a?{signal:a}:{}}),s=!0,al(a),ir.getState().upsert(ul(t)),n&&o.retireEnvironmentId(n.environmentId),t}catch(e){throw i||await o.removeConnection(t.environmentId).catch(()=>!1),s&&await gl({record:t,replacedRecord:n,rollback:r}),al(a),e}}var Qx=`forge.deviceRegistry.deviceKey`,$x=`forge.deviceRegistry.runtimeId`;function eS(e){let t=rS(Qx,e.desktopIdentity?.deviceKey,`device`),n=rS($x,e.desktopIdentity?.runtimeId,`runtime`),r=nS(e.desktopIdentity?.hostKey),i=cS(),a=e.desktopAvailable?`desktop`:lS(),o=e.desktopAvailable?sS(e.desktopIdentity)??uS(i):dS(i);return{device:{...r?{hostKey:r}:{},deviceKey:t,displayName:o,platform:i,deviceType:a,metadata:{clientKind:e.desktopAvailable?`forge-desktop`:`forge-web`,userAgent:window.navigator.userAgent,origin:window.location.origin,...e.desktopIdentity?{desktopIdentity:{hostName:e.desktopIdentity.hostName,computerName:e.desktopIdentity.computerName,platform:e.desktopIdentity.platform}}:{}}},...e.desktopAvailable&&e.includeExecutableRuntime!==!1?{runtime:{runtimeId:n,runtimeKind:`desktop-local`,displayName:`Local Forge Desktop`,endpointUrl:e.desktopEndpointUrl??null,status:`online`,metadata:{origin:window.location.origin}}}:{}}}async function tS(){let e=await window.desktopBridge?.getDeviceIdentity?.()??null;return eS({desktopAvailable:!!window.desktopBridge,desktopIdentity:e,includeExecutableRuntime:!1})}function nS(e){let t=e?.trim()??``;return t.length>0?t:null}function rS(e,t,n){let r=nS(t);return r?(En(e,r),r):oS(e,n)}function iS(){return Mn($x)}function aS(){return Mn(Qx)}function oS(e,t){let n=Mn(e);if(n)return n;let r=`${t}_${crypto.randomUUID()}`;return En(e,r),r}function sS(e){let t=e?.displayName?.trim()??``;return t.length>0?t:null}function cS(){let e=window.navigator.userAgent.toLowerCase();return e.includes(`iphone`)||e.includes(`ipad`)?`ios`:e.includes(`android`)?`android`:e.includes(`mac`)?`macos`:e.includes(`win`)?`windows`:e.includes(`linux`)?`linux`:`unknown`}function lS(){let e=window.navigator.userAgent.toLowerCase();return e.includes(`ipad`)||e.includes(`tablet`)?`tablet`:e.includes(`mobi`)||e.includes(`iphone`)||e.includes(`android`)?`mobile`:`browser`}function uS(e){return e===`macos`?`Mac`:e===`windows`?`Windows PC`:e===`linux`?`Linux Desktop`:`Desktop`}function dS(e){return e===`web`?`Browser`:e===`macos`?`Mac Browser`:e===`windows`?`Windows Browser`:e===`linux`?`Linux Browser`:`Browser`}var fS=`forge.relayControlJournal.v1`;function pS(){if(globalThis.localStorage===void 0)throw Error(`Forge relay control recovery requires durable browser storage.`);return globalThis.localStorage}var mS={read:()=>pS().getItem(fS),write:e=>pS().setItem(fS,e)},hS=null,gS=wa()(e=>({byRuntimeId:{},replace:t=>e({byRuntimeId:t})}));function _S(e){e.subscribe(e=>{let t=new Set(e.records.map(e=>e.runtimeId));gS.getState().replace(Object.fromEntries([...t].map(t=>[t,la(e.records,t)])))})}function vS(){return hS===null&&(hS=ua({storage:mS}),_S(hS)),hS}function yS(){let e=(0,A.c)(1),t=gS(xS),n;return e[0]===Symbol.for(`react.memo_cache_sentinel`)?(n=[],e[0]=n):n=e[0],(0,O.useEffect)(bS,n),t}function bS(){vS()}function xS(e){return e.byRuntimeId}function SS(e){let t=vS();for(let n of t.records())n.runtimeId===e&&(n.status===`failed`||n.status===`outcome-unknown`)&&t.acknowledge(n.runtimeId,n.actorSessionId,n.transportRequestId)}var CS=class extends Error{code;constructor(e,t){super(t),this.name=`RelayControlRouteError`,this.code=e}};function wS(e){let t=e&&typeof e==`object`?e.code:null;throw t===`PROTOCOL_INCOMPATIBLE`?new CS(`FORGE_RUNTIME_UPDATE_REQUIRED`,`Update Forge on the target runtime before connecting remotely.`):t===`PROTOCOL_ROLLOUT_DENIED`?new CS(`FORGE_REMOTE_CONTROL_NOT_ENABLED`,`Remote control is not enabled for this CMMD account. Synced runtime inventory remains available.`):e}async function TS(e){let t=e.getStoredDeviceKey(),n=t?await e.apiClient.getDeviceRegistry():await e.apiClient.registerDevice(await e.buildDeviceRegistration());return t&&!n.devices.some(e=>e.deviceKey===t)&&(n=await e.apiClient.registerDevice(await e.buildDeviceRegistration())),t??=e.getStoredDeviceKey(),{deviceKey:t,registry:n}}function ES(e){if(!e.deviceKey)throw new CS(`FORGE_CONTROL_DEVICE_UNAUTHORIZED`,`This Forge control surface could not establish CMMD identity.`);let t=e.registry.devices.find(t=>t.deviceKey===e.deviceKey);if(t?.trustState===`revoked`||t?.authorization?.revoked===!0)throw new CS(`FORGE_CONTROL_DEVICE_REVOKED`,`This Forge control surface was revoked by CMMD.`);if(!t||t.trustState!==`trusted`)throw new CS(`FORGE_CONTROL_DEVICE_UNAUTHORIZED`,`This Forge control surface is not trusted by CMMD.`);return t}function DS(e,t){let n=async()=>ES(await TS(t));return{acquireRoute:async()=>{let r=await n(),i=await ca();try{let n=await t.apiClient.issueRelayControlRoute(e,{controlDeviceId:r.id,controlSessionId:t.controlSessionId,scopes:[...Ci],protocolMinVersion:4,protocolMaxVersion:4,...Yi(i)});return $i({route:n,runtimeId:e,endpoint:i})}catch(e){if(e instanceof sa)throw new CS(`FORGE_RUNTIME_UPDATE_REQUIRED`,e.message);return wS(e)}},acquireActionGrant:async r=>{let i=await n();try{return(await t.apiClient.issueRelayActionGrant(e,{controlDeviceId:i.id,controlSessionId:t.controlSessionId,...r})).token}catch(e){return wS(e)}}}}var OS=new Map;async function kS(e,t){let n=Hr.make(e.runtimeId),r=t.readConnection(n);if(r)return r;Nx(n);let i=vS(),a=DS(e.runtimeId,{apiClient:cr,getStoredDeviceKey:aS,buildDeviceRegistration:tS,controlSessionId:i.controlSessionId}),o;try{o=await a.acquireRoute()}catch(e){throw Lx(n,e),e}let s=o,c=ga({acquireRoute:async()=>{let e=s;return s=null,e??a.acquireRoute()},acquireActionGrant:a.acquireActionGrant,journal:i,lifecycle:{onConnecting:()=>Nx(n),onAuthenticated:()=>Px(n),onDisconnected:e=>Ix(n,e.reason),onError:e=>Lx(n,Object.assign(Error(e.message),e))}}),l=af(new ld(o.relayWebSocketUrl,{trackGlobalConnection:!1},{layer:c,makeClient:Qi(Ci)})),u=ql({kind:`saved`,knownEnvironment:{...xn({id:n,label:e.label,source:`manual`,target:{httpBaseUrl:ra()?.target.httpBaseUrl??o.relayWebSocketUrl,wsBaseUrl:o.relayWebSocketUrl}}),environmentId:n},client:l,tolerateReportedEnvironmentIdentity:!0,onConfigSnapshot:e=>Fx(n,e),...jx(e=>{j.getState().patch(n,{descriptor:e.environment})})});try{let[,e]=await Promise.all([u.ensureBootstrapped(),l.server.getConfig()]);return Fx(n,e),Px(n),t.registerConnection(u)}catch(e){throw Lx(n,e),await u.dispose().catch(()=>void 0),e}}function AS(e,t){let n=Hr.make(e.runtimeId),r=t.readConnection(n);if(r)return Promise.resolve(r);let i=OS.get(n);if(i)return i;let a=kS(e,t).finally(()=>{OS.delete(n)});return OS.set(n,a),a}var jS=new Set([`CMMD_AUTH_REQUIRED`,`CMMD_AUTH_EXPIRED`,`INVALID_OR_NON_USER_TOKEN`,`NON_USER_BEARER`,`CMMD_REST_AUTH_ERROR`]);function MS(e){if(!e||typeof e!=`object`)return null;let t=e.code;return typeof t!=`string`||!jS.has(t)?null:t}function NS(e,t){return e===401||e===403||MS(t)!==null}function PS(e){if(!e||typeof e!=`object`)return!1;let t=e.status,n=e.code;return NS(typeof t==`number`?t:void 0,typeof n==`string`?{code:n}:void 0)}var FS=[1e3,2e3,4e3,8e3,12e3,16e3,2e4],IS=9e4,LS=[`all fibers interrupted without error`,`timed out while waiting for forge cloud runtime metadata`,`timed out while waiting for`,`to stream its shell snapshot`,`forge runtime route not found`,`fly-replay`,`could not find a good candidate`,`instance refused connection`],RS=[`Unknown socket error`,`Failed to fetch remote auth endpoint`,`Forge runtime replay target is unavailable`,`Remote auth request failed (502)`,`Remote auth request failed (503)`,`Remote auth request failed (504)`,`Unable to connect to the Forge server WebSocket`];function zS(e){if(typeof e!=`object`||!e)return null;let t=e.status;return typeof t==`number`&&Number.isInteger(t)?t:null}function BS(e){if(PS(e))return!1;let t=zS(e);if(t===502||t===503||t===504||e._tag===`OrchestrationGetSnapshotError`)return!0;let n=e instanceof Error?e.message:String(e),r=n.toLowerCase();return LS.some(e=>r.includes(e))||RS.some(e=>n.includes(e))}function VS(e){return FS[e]??FS[FS.length-1]}function HS(){return IS}function US(e,t){if(!dl(e))return t;let n=null,r=new Promise((t,r)=>{n=globalThis.setTimeout(()=>{r(Error(`Timed out while waiting for Forge Cloud runtime metadata for ${e.environmentId}. The VM may still be starting.`))},HS())});return Promise.race([t,r]).finally(()=>{n!==null&&globalThis.clearTimeout(n)})}function WS(e){let t=e.toLowerCase();return t.includes(`authentication`)||t.includes(`unauthorized`)||t.includes(`forbidden`)||t.includes(`credential`)||t.includes(`runtime ticket`)||t.includes(`status 401`)||t.includes(`status 403`)}var GS=`forge:cloud-runtime-handoffs:v2`,KS=3e5,qS=new Map,JS={clear:()=>qS.clear(),getItem:e=>qS.get(e)??null,key:e=>Array.from(qS.keys())[e]??null,get length(){return qS.size},removeItem:e=>qS.delete(e),setItem:(e,t)=>qS.set(e,t)};function YS(){return typeof window<`u`?window.localStorage:globalThis.localStorage??JS}var XS=wa()(Wf(e=>({byRuntimeId:{},record:t=>e(e=>({byRuntimeId:{...e.byRuntimeId,[t.runtimeId]:t}})),clearRuntime:t=>e(e=>t in e.byRuntimeId?{byRuntimeId:Object.fromEntries(Object.entries(e.byRuntimeId).filter(([e])=>e!==t))}:e),reconcileCatalog:(t,n=Date.now())=>e(e=>{let r=Object.entries(e.byRuntimeId).filter(([,e])=>{if(n-e.recordedAt>KS)return!1;let r=t.find(t=>t.cmmdOrganizationId===e.cmmdOrganizationId&&t.cmmdProjectId===e.cmmdProjectId);return r?.runtimeId===e.previousCatalogRuntimeId&&r.registeredAt===e.catalogRegisteredAt});return r.length===Object.keys(e.byRuntimeId).length?e:{byRuntimeId:Object.fromEntries(r)}}),reset:()=>e({byRuntimeId:{}})}),{name:GS,storage:Hf(YS),partialize:e=>({byRuntimeId:e.byRuntimeId}),version:2}));function ZS(e){XS.getState().record({...e,recordedAt:Date.now()})}function QS(e){XS.getState().clearRuntime(e)}var $S=new Set([`filesystem`,`terminal`,`git`,`project-write`]);function eC(e){return e===`desktop-local`}function tC(e){return e===`cloud`||e===`cloud-vm`||e===`cmmd`||e===`github`}function nC(e){return e.actionKind===`cloud-api`?{available:!0,route:`cloud`,requiresPermissionGate:!1,title:`Cloud API route`,description:`Cloud and Command work routes through authenticated Forge Cloud APIs.`}:$S.has(e.actionKind)?tC(e.workSource)?e.workSource===`cloud-vm`&&e.executionRuntime===`cloud`?{available:!0,route:`cloud-vm`,requiresPermissionGate:!1,title:`Cloud VM route`,description:`Filesystem, terminal, git, and project writes run inside the user's Forge Cloud VM.`}:e.executionRuntime===`cloud`?{available:!0,route:`cloud`,requiresPermissionGate:!1,title:`Cloud work route`,description:`Cloud-scoped filesystem, terminal, git, and project writes run in the Forge Cloud runtime.`}:{available:!1,route:`blocked`,requiresPermissionGate:!1,title:`Open in Forge Cloud`,description:`Cloud projects must execute inside the Forge Cloud runtime. Local Desktop cannot run cloud project filesystem, terminal, git, or project-write actions.`}:eC(e.workSource)?e.surface===`desktop-local`||e.executionRuntime===`desktop-local`?{available:!0,route:`desktop-local`,requiresPermissionGate:!1,title:`Desktop local route`,description:`Local filesystem, terminal, git, and project writes run through the Desktop local backend.`}:e.executionRuntime===`dev-local-web`?{available:!0,route:`dev-local-web`,requiresPermissionGate:!1,title:`Dev local route`,description:`Local Web is a development-only projection and routes local actions through the dev server.`}:{available:!1,route:`blocked`,requiresPermissionGate:!1,title:`Switch to Desktop Local`,description:`Local projects must execute in the Desktop Local runtime. Forge Cloud cannot run local filesystem, terminal, git, or project-write actions.`}:{available:!1,route:`blocked`,requiresPermissionGate:!1,title:`Unknown work source`,description:`Forge cannot safely route local actions for this work source yet.`}:{available:!1,route:`blocked`,requiresPermissionGate:!1,title:`Unsupported route`,description:`Forge does not have a runtime route for this action yet.`}}var rC=`Ready to use. Your cloud project starts when you open the first thread.`;function iC(e){let t=nC({actionKind:`project-write`,surface:`cloud-official`,workSource:`cloud-vm`,executionRuntime:`cloud`});return{actionAuthority:`runtime`,surface:`cloud-official`,hostKind:`user-cloud-vm`,workSource:`cloud-vm`,executionRuntime:`cloud`,modelRuntime:`cloud`,linkState:`cloud-only`,workspaceIdentity:null,hideLocalPath:!0,label:`Cloud project`,description:e?`This project runs in your Forge Cloud VM.`:rC,actionRouteLabel:t.title,actionRouteDescription:t.description,actionRouteAvailable:t.available,requiresPermissionGate:t.requiresPermissionGate}}var aC=3e5;function oC(e,t,n=Date.now()){let r=new Map,i=new Map;for(let t of e){let e={cmmdOrganizationId:t.cmmdOrganizationId,cmmdProjectId:t.cmmdProjectId};r.set(lC(e),e),t.runtimeId!==null&&i.set(t.runtimeId,e)}for(let a of t){if(n-a.recordedAt>aC)continue;let t=r.get(lC({cmmdOrganizationId:a.cmmdOrganizationId,cmmdProjectId:a.cmmdProjectId})),o=e.find(e=>e.cmmdOrganizationId===a.cmmdOrganizationId&&e.cmmdProjectId===a.cmmdProjectId);t&&o?.runtimeId===a.previousCatalogRuntimeId&&o.registeredAt===a.catalogRegisteredAt&&!i.has(a.runtimeId)&&i.set(a.runtimeId,t)}return i}function sC(e){return e.environmentId??`cmmd-cloud-project:${e.cmmdOrganizationId}:${e.cmmdProjectId}`}function cC(e){return{environmentId:sC(e),workspaceRoot:e.workspaceRoot,resolvedRef:e.resolvedRef}}function lC(e){return`cloud:${e.cmmdOrganizationId}:${e.cmmdProjectId}`}function uC(e){let t=/^cloud:(\d+):(\d+)$/.exec(e??``);return t?{cmmdOrganizationId:Number(t[1]),cmmdProjectId:Number(t[2])}:null}function dC(e){return`cloud-runtime:${e}`}var fC=`cloud-unconnected:`;function pC(e,t,n=[]){let r=lC(e);return mC({id:xi.make(`${fC}${r}`),environmentId:Hr.make(sC(e)),name:e.projectName,cwd:``,repositoryIdentity:null,availability:void 0,defaultModelSelection:null,createdAt:void 0,updatedAt:void 0,scripts:[],projectKey:r,environmentPresence:`remote-only`,source:iC(e.runtimeId!==null),memberProjectRefs:t?[t]:[],remoteEnvironmentLabels:[],worktreeMembers:[],activeWorktreeKey:null,preConnectCloud:{runtimeId:e.runtimeId,cmmdOrganizationId:e.cmmdOrganizationId,cmmdProjectId:e.cmmdProjectId,cmmdEnvironmentId:e.cmmdEnvironmentId,registeredAt:e.registeredAt,projectName:e.projectName,githubRepoFullName:e.githubRepoFullName,workspaceRoot:e.workspaceRoot,iconUrl:e.iconUrl,icon:e.icon,status:e.status,removal:e.removal},cloudRemoval:e.removal},n)}function mC(e,t){if(t.length===0)return e;let n=[...e.memberProjectRefs],r=new Set(n.map(e=>`${e.environmentId}:${e.projectId}`));for(let e of t){let t=`${e.environmentId}:${e.projectId}`;r.has(t)||(r.add(t),n.push(e))}return n.length===e.memberProjectRefs.length?e:{...e,memberProjectRefs:n}}function hC(e,t,n,r){if(!e)return null;let i=t.find(t=>t.cmmdEnvironmentId===String(e));if(i)return{row:i,runtimeId:i.runtimeId,matchedByHandoff:!1};let a=vr(e).legacyRuntimeId;if(a){let e=t.find(e=>e.runtimeId===a);if(e)return{row:e,runtimeId:a,matchedByHandoff:!1};let i=oC(t,n,r).get(a);if(!i)return null;let o=t.find(e=>e.cmmdOrganizationId===i.cmmdOrganizationId&&e.cmmdProjectId===i.cmmdProjectId);return o?{row:o,runtimeId:a,matchedByHandoff:!0}:null}let o=t.find(t=>t.runtimeId===null&&sC(t)===String(e));return o?{row:o,runtimeId:null,matchedByHandoff:!1}:null}function gC(e,t=e.runtimeId){return{runtimeId:t,cmmdOrganizationId:e.cmmdOrganizationId,cmmdProjectId:e.cmmdProjectId,cmmdEnvironmentId:e.cmmdEnvironmentId,registeredAt:e.registeredAt,projectName:e.projectName,githubRepoFullName:e.githubRepoFullName,workspaceRoot:e.workspaceRoot,iconUrl:e.iconUrl,icon:e.icon,status:e.status,desiredState:e.desiredState}}function _C(e){return e.desiredState===`stopped`}var vC=15e3;function yC(e){return e===401||e===403}function bC(e){return typeof e!=`object`||!e?!1:e.retryable===!0}function xC(e){return yC(e.status)||e.attempt>=e.maxAttempts||e.status>=200&&e.status<300?!1:e.status>=500||e.status===409&&bC(e.body)}function SC(e,t){let n=e?.trim();if(!n)return null;if(/^-?\d+$/.test(n))return Number(n)*1e3;let r=Date.parse(n);return Number.isNaN(r)?null:r-t}function CC(e){let t=e=>Math.min(vC,Math.max(0,e)),n=SC(e.retryAfter,e.nowMs??Date.now());return t(n===null?300*2**Math.max(0,e.attempt-1):n)}var wC=6e4;function TC(e,t){if(!e||typeof e!=`object`)return t;let n=e.error;return typeof n==`string`&&n.trim().length>0?n:t}var EC=`CMMD returned an invalid Cloud runtime connection descriptor.`;function DC(e,t){let n=e[t];if(typeof n!=`string`||n.length===0)throw Error(EC);return n}function OC(e){if(!e||typeof e!=`object`)throw Error(EC);let t=e;return{httpBaseUrl:DC(t,`httpBaseUrl`),wsBaseUrl:DC(t,`wsBaseUrl`),bearerToken:DC(t,`bearerToken`),expiresAt:DC(t,`expiresAt`)}}async function kC(e){let t=Ji(`/api/cmmd/forge-runtimes/${encodeURIComponent(e.runtimeId)}/connect`),n=ta({method:`POST`,...e.signal?{signal:e.signal}:{},headers:{"Content-Type":`application/json`},body:JSON.stringify(e.organizationId===void 0?{}:{organizationId:e.organizationId})});for(let r=1;r<=8;r+=1){let i=await fetch(t,n),a=await i.json().catch(()=>null);if(i.ok)return OC(a);if(!xC({status:i.status,body:a,attempt:r,maxAttempts:8})){let e=NS(i.status,a)?`CMMD authentication expired while renewing the Cloud runtime connection. Sign in again.`:`CMMD could not renew the Cloud runtime connection (${i.status}).`;throw Object.assign(Error(TC(a,e)),{status:i.status,...MS(a)?{code:MS(a)}:{}})}await sl(CC({attempt:r,retryAfter:i.headers.get(`retry-after`)}),e.signal)}throw Error(`Cloud runtime connection retry budget was exhausted.`)}function AC(e,t){if(!e?.expiresAt)return!0;let n=Date.parse(e.expiresAt);return!Number.isFinite(n)||n<=t+wC}function jC(e){let t=e.requestDescriptor??kC,n=e.now??Date.now,r=e.initialDescriptor??null,i=null,a=!1,o=new AbortController,s=e=>ol(e,o.signal),c=()=>i||(i=s(t({runtimeId:e.runtimeId,...e.organizationId===void 0?{}:{organizationId:e.organizationId},signal:o.signal})).then(async t=>(await s(Promise.resolve(e.validateDescriptor?.(t))),await s(Promise.resolve(e.persistDescriptor?.(t))),await s(Promise.resolve()),r=t,a=!1,t)).then(e=>(i=null,e),e=>{throw i=null,e}),i);return{acquire:e=>{if(o.signal.aborted)return s(Promise.resolve(r));let t=e?.forceRefresh||a||AC(r,n())?c():Promise.resolve(r);return ol(s(t),e?.signal)},invalidate:()=>{a=!0},dispose:()=>{o.abort()}}}function MC(e){let t=e.runtimeId?.trim();if(t)return t;let n=vr(e.environmentId).legacyRuntimeId;if(n)return n;let r=ur().rows,i=Object.values(XS.getState().byRuntimeId);return hC(e.environmentId,r,i)?.runtimeId??null}function NC(e,t,n,r){let i=e,a=jC({runtimeId:t,...e.cmmdOrganizationId===void 0?{}:{organizationId:e.cmmdOrganizationId},...n===void 0?{}:{initialDescriptor:{httpBaseUrl:e.httpBaseUrl,wsBaseUrl:e.wsBaseUrl,bearerToken:n,expiresAt:e.runtimeTicketExpiresAt??null}},validateDescriptor:async e=>{await Fl({httpBaseUrl:e.httpBaseUrl,bearerToken:e.bearerToken})},persistDescriptor:async e=>{if(r&&!r())throw Error(`Saved environment changed while its connection was being acquired.`);let t={...ul(i),httpBaseUrl:e.httpBaseUrl,wsBaseUrl:Jr(e.wsBaseUrl),...e.expiresAt===null?{}:{runtimeTicketExpiresAt:e.expiresAt},lastConnectedAt:new Date().toISOString()};await Gn(t),await mr(t.environmentId),ir.getState().upsert(t),i=t}});return xl(e.environmentId,a),a}function PC(e){let t={wsBaseUrl:e.record.wsBaseUrl,httpBaseUrl:e.record.httpBaseUrl,bearerToken:e.bearerToken,expiresAt:e.record.runtimeTicketExpiresAt??null};return{acquire:()=>Promise.resolve(t)}}var FC=12e4,IC=3e4,LC=3e4;function RC(e){let t=e.expiresAt?Date.parse(e.expiresAt):NaN;if(!Number.isFinite(t))throw Error(`Cloud runtime authority descriptor has no valid expiry.`);return t}function zC(e){if(!e||typeof e!=`object`)return!1;let t=e.status;return t===401||t===403}function BC(e){let t=e.now??Date.now,n=e.renewalSkewMs??FC,r=!1,i=null,a=null,o=RC(e.initialDescriptor),s=()=>{i!==null&&(globalThis.clearTimeout(i),i=null)},c=a=>{if(r)return;s();let c=RC(a);o=c;let l=Math.max(t(),c-n);e.onState?.({kind:`scheduled`,expiresAt:new Date(c).toISOString(),renewAt:new Date(l).toISOString()}),i=globalThis.setTimeout(()=>{i=null,u().catch(()=>void 0)},Math.max(0,l-t()))},l=()=>{if(r)return null;let e=t()+LC;return e>=o?null:(i=globalThis.setTimeout(()=>{i=null,u().catch(()=>void 0)},LC),new Date(e).toISOString())},u=()=>{if(r)return Promise.resolve();if(a)return a;s(),e.onState?.({kind:`renewing`,expiresAt:new Date(o).toISOString()});let n=e.renew().then(async n=>{let i=RC(n);if(i<=t())throw Error(`Cloud runtime authority descriptor is already expired.`);r||(e.onState?.({kind:`ready`,expiresAt:new Date(i).toISOString(),renewedAt:new Date(t()).toISOString()}),c(n))}).catch(t=>{if(r)return;let n=zC(t);throw e.onState?.({kind:`error`,code:n?`authority_auth_rejected`:`authority_renewal_failed`,retryAt:n?null:l()}),t}).finally(()=>{a=null});return a=n,n};return c(e.initialDescriptor),{ensureLive:()=>o>t()+IC?Promise.resolve():u(),renewNow:u,dispose:()=>{r=!0,s()}}}function VC(){return new Date().toISOString()}function HC(e,t,n,r,i){return n()&&j.getState().ensure(e.environmentId),af(new ld(async()=>{let e=e=>Rl({wsBaseUrl:e.wsBaseUrl,httpBaseUrl:e.httpBaseUrl,bearerToken:e.bearerToken,...r?{runtimeTicket:e.bearerToken}:{}}),n=await t.acquire();try{return await e(n)}catch(n){if(!r||!Rn(n))throw n;return e(await t.acquire({forceRefresh:!0}))}},{trackGlobalConnection:!1,onAttempt:()=>{n()&&i.setConnecting(e.environmentId)},onOpen:()=>{n()&&i.setConnected(e.environmentId)},onError:i=>{r&&WS(i)&&t.invalidate?.(),n()&&j.getState().patch(e.environmentId,{connectionState:`error`,lastError:i,lastErrorAt:VC()})},onClose:a=>{r&&(a.code===1008||WS(a.reason))&&t.invalidate?.(),n()&&i.setDisconnected(e.environmentId,a.reason)}}))}async function UC(e,t,n,r,i,a,o){let s=await bl(t,o),[c,l]=await Promise.all([a?Promise.resolve(a):n.server.getConfig(),Fl({httpBaseUrl:s.httpBaseUrl,bearerToken:s.bearerToken,...o?{signal:o}:{}})]);return r()?(j.getState().patch(e.environmentId,{authState:l.authenticated?`authenticated`:`requires-auth`,descriptor:c.environment,serverConfig:c,role:l.authenticated?l.role??i??null:null}),WC(e,c,l.authenticated,r),!0):!1}function WC(e,t,n,r){if(!n||!r())return;let i=er(e.environmentId);i&&ir.getState().upsert({...i,lastAuthenticatedPullRequestCapability:t.environment.capabilities?.pullRequests===!0})}async function GC(e,t,n,r){let i=n.findConnection(e.environmentId);if(i)return i;let a=r?.registryExpectation??{kind:`existing-record`,record:e},o=()=>n.canCommit({record:e,generation:t,registryExpectation:a}),{isCmmdRuntime:s,targetProvider:c,initialTarget:l}=await KC(e,r,o);if(!o())throw qC(e.environmentId,c,s),Error(`Saved environment changed while its connection was being acquired.`);let u=r?.client??HC(e,c,o,s,n),d=YC({record:e,initialTarget:l,targetProvider:c,isCmmdRuntime:s,client:u,canCommit:o,dependencies:n});try{if(!await n.withMetadataTimeout(e,UC(e,c,u,o,r?.role??null,r?.serverConfig??null,r?.signal))||!o())throw Error(`Saved environment changed while its connection was being acquired.`);return n.registerConnection(d)}catch(t){throw s&&Cl(e.environmentId,c),o()&&n.setError(e.environmentId,t),await d.dispose().catch(()=>void 0),t}}async function KC(e,t,n){let r=dl(e)?MC(e):null,i=r!==null,a=await JC(e,t,i,n),o=i?NC(e,r,a??void 0,n):PC({record:e,bearerToken:a});try{return{isCmmdRuntime:i,targetProvider:o,initialTarget:await bl(o,t?.signal)}}catch(t){throw qC(e.environmentId,o,i),t}}function qC(e,t,n){n&&Cl(e,t)}async function JC(e,t,n,r){if(n)return t?.bearerToken;let i=t?.bearerToken??await nr(e.environmentId);if(i)return i;throw r()&&j.getState().patch(e.environmentId,{authState:`requires-auth`,role:null,connectionState:`disconnected`,lastError:`Saved environment is missing its saved credential. Pair it again.`,lastErrorAt:VC()}),Error(`Saved environment is missing its saved credential.`)}function YC(e){let{record:t,initialTarget:n,targetProvider:r,isCmmdRuntime:i,client:a,canCommit:o,dependencies:s}=e,c=xn({id:t.environmentId,label:t.label,source:`manual`,target:{httpBaseUrl:n.httpBaseUrl,wsBaseUrl:n.wsBaseUrl}}),l=i&&n.expiresAt?BC({initialDescriptor:{...n,expiresAt:n.expiresAt},renew:async()=>{let e=await r.acquire({forceRefresh:!0});return{...e,expiresAt:e.expiresAt??null}},onState:e=>{o()&&j.getState().patch(t.environmentId,{providerAuthority:e})}}):null;return ql({kind:`saved`,knownEnvironment:{...c,environmentId:t.environmentId},client:a,readiness:{bearerToken:n.bearerToken},tolerateReportedEnvironmentIdentity:i,refreshMetadata:async()=>{await UC(t,r,a,o)},...l?{ensureProviderAuthority:l.ensureLive,onDispose:l.dispose}:{},onConfigSnapshot:e=>{o()&&j.getState().patch(t.environmentId,{descriptor:e.environment,serverConfig:e})},...s.createHandlers(e=>{o()&&j.getState().patch(t.environmentId,{descriptor:e.environment})})})}var XC=class{readRecord;hasSameTarget;generations=new Map;acquisitions=new Map;constructor(e,t){this.readRecord=e,this.hasSameTarget=t}invalidate(e){this.generations.set(e,this.readGeneration(e)+1)}generationFor(e){return this.readGeneration(e)}isCurrent(e){if(this.readGeneration(e.record.environmentId)!==e.generation)return!1;let t=this.readRecord(e.record.environmentId);return e.registryExpectation.kind===`initial-add`?t===null||this.hasSameTarget(t,e.record):t!==null&&this.hasSameTarget(t,e.registryExpectation.record)}ensure(e,t){let n=this.readGeneration(e.environmentId),r=this.acquisitions.get(e.environmentId);if(r&&r.generation===n&&this.hasSameTarget(r.record,e))return r.promise;let i=t(e,n).finally(()=>{this.acquisitions.get(e.environmentId)?.promise===i&&this.acquisitions.delete(e.environmentId)});return this.acquisitions.set(e.environmentId,{generation:n,record:e,promise:i}),i}async sync(e){await rr(e.records);let t=new Map(e.records.map(e=>[e.environmentId,e]));for(let[e,n]of this.acquisitions){let r=t.get(e);(!r||!this.hasSameTarget(r,n.record))&&this.invalidate(e)}let n=new Set(t.keys());await Promise.all(e.connectedSavedEnvironmentIds.filter(e=>!n.has(e)).map(async t=>{this.invalidate(t),await e.disconnect(t)}))}clear(){this.generations.clear(),this.acquisitions.clear()}readGeneration(e){return this.generations.get(e)??0}};async function ZC(e,t,n){if(!dl(e))return n.ensureSavedEnvironmentConnection(e,t);let r=n.getGeneration(e.environmentId),i=()=>n.registry.isCurrent({record:e,generation:r,registryExpectation:t?.registryExpectation??{kind:`existing-record`,record:e}}),a=null;for(let r=0;r<8;r+=1){al(t?.signal);try{let r=await n.ensureSavedEnvironmentConnection(e,t);return await ol(r.ensureBootstrapped(),t?.signal),r}catch(o){a=o,await QC({error:o,attemptIndex:r,record:e,options:t,dependencies:n,canCommit:i})}}let o=a instanceof Error?a:Error(String(a));throw i()&&n.setRuntimeError(e.environmentId,o),o}async function QC(e){let{error:t,attemptIndex:n,record:r,options:i,dependencies:a,canCommit:o}=e;if(!o())throw t;if(await a.removeConnection(r.environmentId).catch(()=>!1),al(i?.signal),n>=7||!BS(t))throw o()&&a.setRuntimeError(r.environmentId,t),t;let s=VS(n);i?.onBootstrapRetry?.({attempt:n+2,maxAttempts:8,retryDelayMs:s,error:t}),o()&&j.getState().patch(r.environmentId,{connectionState:`connecting`,lastError:null,lastErrorAt:null}),await sl(s,i?.signal)}var $C=new Map,ew=new XC(e=>er(e),fl),tw=new Set,nw=Al({createPrimaryEnvironmentConnection:sw,syncSavedEnvironmentConnections:lw});function rw(){nw.notifyProviderInvalidation()}function iw(){for(let e of tw)e()}function aw(e){let t=$C.get(e.environmentId);if(t&&t!==e)throw Error(`Environment ${e.environmentId} already has an active connection.`);return $C.set(e.environmentId,e),iw(),e}async function ow(e){let t=$C.get(e);return t?($C.delete(e),Cl(e),ox(e),iw(),await t.dispose(),!0):!1}function sw(){return zx({readConnection:dw,registerConnection:aw})}async function cw(e,t){return $C.get(e.environmentId)||ew.ensure(e,(e,n)=>GC(e,n,{findConnection:e=>$C.get(e),registerConnection:aw,canCommit:ew.isCurrent.bind(ew),createHandlers:jx,withMetadataTimeout:US,setConnecting:Nx,setConnected:Px,setDisconnected:Ix,setError:Lx},t))}async function lw(e){await ew.sync({records:e,connectedSavedEnvironmentIds:[...$C.values()].filter(e=>e.kind===`saved`).map(e=>e.environmentId),disconnect:_w})}function uw(e){return tw.add(e),()=>{tw.delete(e)}}function dw(e){return $C.get(e)??null}function fw(e){return AS(e,{readConnection:dw,registerConnection:aw})}function pw(e){let t=dw(e);if(!t)throw Error(`No websocket client registered for environment ${e}.`);return t}function mw(){return sw()}async function hw(){return Bx({readConnection:dw,registerConnection:aw})}function gw(){return{readConnection:dw,removeConnection:ow,ensureSavedEnvironmentConnection:cw,ensureCmmdRuntimeSavedEnvironmentConnection:Sw,invalidate:e=>ew.invalidate(e),retireEnvironmentId:ax}}async function _w(e){await Kx(e,gw())}async function vw(e){await qx(e,gw())}async function yw(){return Wx({readConnection:dw,ensureCmmdRuntimeSavedEnvironmentConnection:Sw})}async function bw(e){await Jx(e,gw())}async function xw(e){return Yx(e,gw())}async function Sw(e,t){return ZC(e,t,{ensureSavedEnvironmentConnection:cw,getGeneration:e=>ew.generationFor(e),registry:ew,removeConnection:ow,setRuntimeError:Lx})}async function Cw(e){await $C.get(e)?.ensureBootstrapped()}async function ww(e){let t=$C.get(e);if(t?.ensureProviderAuthority){await t.ensureProviderAuthority();return}if(Sl(e))throw Error(`Cloud runtime provider authority is not available.`)}function Tw(e){return nw.start(e)}zb({applyEvent:Ox,readConnection:dw,subscribeConnections:uw}),Cy({notifyProviderInvalidation:rw,readQueryClient:()=>nw.readActiveService()?.queryClient??null,setRuntimeError:Lx});function Ew(e){return{environmentId:e.environmentId,threadId:e.threadId}}function Dw(e){return{draftId:e}}function Ow(e){return!e.environmentId||!e.threadId?null:C(e.environmentId,e.threadId)}function kw(e){return e.environmentId&&e.threadId?{kind:`server`,threadRef:C(e.environmentId,e.threadId)}:e.draftId?{kind:`draft`,draftId:e.draftId}:null}function Aw(e){let t=(0,A.c)(8),n,r;t[0]===e?(n=t[1],r=t[2]):({className:n,...r}=e,t[0]=e,t[1]=n,t[2]=r);let i;t[3]===n?i=t[4]:(i=Ca(`relative overflow-hidden rounded-sm bg-muted [--skeleton-highlight:--alpha(var(--color-white)/64%)] after:absolute after:inset-0 after:animate-skeleton after:bg-[linear-gradient(120deg,transparent_40%,var(--skeleton-highlight),transparent_60%)] motion-reduce:after:content-none dark:[--skeleton-highlight:--alpha(var(--color-white)/4%)]`,n),t[3]=n,t[4]=i);let a;return t[5]!==r||t[6]!==i?(a=(0,k.jsx)(`div`,{className:i,"data-slot":`skeleton`,...r}),t[5]=r,t[6]=i,t[7]=a):a=t[7],a}function jw(e,t){if(!De(e)||!De(t))return t;let n={...e};for(let[e,r]of Object.entries(t)){if(r===void 0)continue;let t=n[e];n[e]=De(t)&&De(r)?jw(t,r):r}return n}function Mw(e,t){return un(t).pipe(ln,sn(e))}function Nw(e){return{issues:e.issues,providers:e.providers,settings:e.settings}}var Pw=[],Fw=[],Iw=[],Lw=e=>e?.availableEditors??Pw,Rw=e=>e?.keybindings??Fw,zw=e=>e?.keybindingsConfigPath??null,Bw=e=>e?.observability??null,Vw=e=>e?.providers??Iw,Hw=e=>e?.settings??Li,Uw=Mw(`server-welcome`,null),Ww=Mw(`server-config`,null),Gw=Mw(`server-config-updated`,null),Kw=Mw(`server-providers-updated`,null);function qw(){return cn.get(Ww)}function Jw(){return cn.get(Gw)}function Yw(e){iT(e),aT({providers:e.providers}),oT(Nw(e),`snapshot`)}function Xw(e){switch(e.type){case`snapshot`:Yw(e.config);return;case`keybindingsUpdated`:{let t=qw();if(!t)return;let n={...t,issues:e.payload.issues,keybindings:e.payload.keybindings};iT(n),oT(Nw(n),e.type);return}case`providerStatuses`:Zw(e.payload);return;case`settingsUpdated`:Qw(e.payload.settings);return;case`environmentUpdated`:$w(e.payload.environment);return}}function Zw(e){let t=qw();if(aT(e),!t)return;let n={...t,providers:e.providers};iT(n),oT(Nw(n),`providerStatuses`)}function Qw(e){let t=qw();if(!t)return;let n={...t,settings:e};iT(n),oT(Nw(n),`settingsUpdated`)}function $w(e){let t=qw();if(yr()?.environmentId===e.environmentId&&vn(e),!t)return;let n={...t,environment:e};iT(n),oT(Nw(n),`environmentUpdated`)}function eT(e){cn.set(Uw,e)}function tT(e){return sT(Gw,t=>{e(t.payload,t.source)})}function nT(e){let t=!1,n=[e.subscribeLifecycle(e=>{e.type===`welcome`&&eT(e.payload)}),e.subscribeConfig(e=>{Xw(e)})];return qw()===null&&e.getConfig().then(e=>{t||qw()!==null||Yw(e)}).catch(()=>void 0),()=>{t=!0;for(let e of n)e()}}var rT=1;function iT(e){cn.set(Ww,e)}function aT(e){cn.set(Kw,e)}function oT(e,t){cn.set(Gw,{id:rT++,payload:e,source:t})}function sT(e,t){return cn.subscribe(e,e=>{e!==null&&t(e)},{immediate:!0})}function cT(e,t){let n=(0,O.useRef)(t);n.current=t;let r=(0,O.useCallback)(e=>{e!==null&&n.current(e)},[]);_a(e,r,{immediate:!0})}function lT(){return ma(Ww)}function uT(){return ma(Ww,Hw)}function dT(){return ma(Ww,Vw)}function fT(){return ma(Ww,Rw)}function pT(){return ma(Ww,Lw)}function mT(){return ma(Ww,zw)}function hT(){return ma(Ww,Bw)}function gT(e){cT(Uw,e)}function _T(){return ma(Uw)}function vT(e){cT(Gw,e)}var yT=`[CLIENT_SETTINGS]`,bT=new Set,xT=li,ST=!1,CT=null,wT=`pending`;function TT(e){wT!==e&&(wT=e,ET())}function ET(){for(let e of bT)e()}function DT(){return xT}function OT(e){xT=e,ET()}function kT(e){return bT.add(e),AT(),()=>{bT.delete(e)}}async function AT(){if(ST)return;if(CT)return CT;let e=(async()=>{try{let e=await tr();e&&OT(e),ST=!0,TT(`ready`)}catch(e){console.error(`${yT} hydrate failed`,e),TT(`failed`)}})().finally(()=>{CT===e&&(CT=null)});return CT=e,CT}var jT=new Set(ei(Ii.fields));function MT(e){let t={},n={};for(let[r,i]of Object.entries(e))jT.has(r)?t[r]=i:n[r]=i;return{serverPatch:t,clientPatch:n}}function NT(){return AT()}var PT=Promise.resolve();function FT(e){let t=PT.then(async()=>{if(await NT(),RT()!==`ready`)throw Error(`${yT} hydration failed; refusing to persist settings.`);return e()});return PT=t.then(()=>void 0,()=>void 0),t}function IT(e){return FT(async()=>{let t=e(DT());await or(t),OT(t)})}function LT(){return(0,O.useSyncExternalStore)(kT,RT,RT)}function RT(){return wT}function zT(){return(0,O.useSyncExternalStore)(kT,VT,BT)}function BT(){return!1}function VT(){return ST}function HT(){let e=zT(),t=I(UT);return e&&t}function UT(e){return e.legacySidebarEnabled}function I(e){let t=uT(),n=(0,O.useSyncExternalStore)(kT,DT,()=>li),r=(0,O.useMemo)(()=>({...t,...n}),[n,t]);return(0,O.useMemo)(()=>e?e(r):r,[r,e])}function WT(){let e=(0,A.c)(2),t=GT,n;e[0]===Symbol.for(`react.memo_cache_sentinel`)?(n=()=>{t(Tr)},e[0]=n):n=e[0];let r=n,i;return e[1]===Symbol.for(`react.memo_cache_sentinel`)?(i={updateSettings:t,resetSettings:r},e[1]=i):i=e[1],i}function GT(e){let{serverPatch:t,clientPatch:n}=MT(e);if(Object.keys(t).length>0){let e=qw();e&&Qw(jw(e.settings,t)),mw().client.server.updateSettings(t)}Object.keys(n).length>0&&FT(async()=>{let e={...DT(),...n};OT(e),await or(e).catch(qT)}).catch(KT)}function KT(e){console.error(`${yT} persist failed`,e)}function qT(e){console.error(`${yT} persist failed`,e)}function JT(e){return t=>e?pn(t,e.environmentId).projectById[e.projectId]:void 0}function YT(e){let t,n,r;return i=>{let a=e(i);if(!a)return;let o=pn(i,a.environmentId);return r&&t===o&&n===a.threadId?r:(t=o,n=a.threadId,r=Pn(o,a.threadId),r)}}function XT(e){return YT(()=>e)}function ZT(e){return t=>{if(e)return pn(t,e.environmentId).threadSubscriptionErrorById[e.threadId]}}function QT(e){let t,n,r,i;return a=>{if(!e){i=void 0,t=void 0,n=void 0,r=void 0;return}let o=pn(a,e.environmentId).threadShellById,s=o[e.threadId];if(!s){i=void 0,t=void 0,n=void 0,r=void 0;return}let c=s.kind===`master`?s.id:s.parentThreadId,l=c==null?void 0:o[c];if(i&&t===o&&n===s&&r===l)return i;let u=[];if(c!=null){for(let e of Object.values(o))e.kind===`worker`&&e.parentThreadId===c&&u.push(e);u.sort((e,t)=>e.createdAt.localeCompare(t.createdAt))}return t=o,n=s,r=l,i={you:s,master:l,workers:u},i}}function $T(e,t){let n=new Set(e.filter(e=>e.bootstrapped).map(e=>String(e.ref.environmentId))),r=e.filter(e=>{let r=t?.(e.ref.environmentId)??null;return r===null||!n.has(r)}),i=r.filter(e=>e.bootstrapped);return(i.find(e=>e.active)??i.at(-1)??r.find(e=>e.active)??r[0])?.ref}function eE(e,t){return YT(n=>{if(e)return $T(Object.entries(n.environmentStateById).filter(([,t])=>t.threadShellById[e]).map(([t,r])=>({ref:{environmentId:t,threadId:e},active:n.activeEnvironmentId===t,bootstrapped:r.bootstrapComplete})),t)})}var tE,nE=[];function rE(e){return tE===e.environmentStateById&&nE!==void 0?nE:(tE=e.environmentStateById,nE=Object.values(e.environmentStateById).flatMap(e=>Object.values(e.sidebarThreadSummaryById)),nE)}function iE(e){let t=e.payload&&typeof e.payload==`object`?e.payload:null,n=t?.plan;if(!Array.isArray(n))return null;let r=[];for(let e of n){if(!e||typeof e!=`object`)continue;let t=e;if(typeof t.step!=`string`)continue;let n=t.status===`completed`||t.status===`inProgress`?t.status:`pending`;r.push({step:t.step,status:n})}return r.length===0?null:{createdAt:e.createdAt,turnId:e.turnId,...t&&`explanation`in t?{explanation:t.explanation}:{},steps:r}}function aE(e){let t=new Map;return e.map(e=>{let n=t.get(e.step)??0;return t.set(e.step,n+1),{key:`${e.step}:${n}`,step:e}})}function oE(e,t){let n=new Map,r;for(let e of t){let t=iE(e),i=Date.parse(e.createdAt);if(!(!t||Number.isNaN(i))){r??=i;for(let{key:e,step:r}of aE(t.steps)){let t=n.get(e)??{};r.status===`inProgress`&&t.startedAt===void 0&&(t.startedAt=i),r.status===`completed`&&t.completedAt===void 0&&(t.completedAt=i),n.set(e,t)}}}let i=new Map,a=r;for(let[e,t]of[...n.entries()].toSorted((e,t)=>(e[1].completedAt??1/0)-(t[1].completedAt??1/0))){let n=t.completedAt,r=t.startedAt??a;n!==void 0&&(r!==void 0&&n>r&&i.set(e,n-r),a=n)}return{...e,steps:aE(e.steps).map(({key:e,step:t})=>{if(t.status!==`completed`)return t;let n=i.get(e);return n===void 0?t:Object.assign({},t,{durationMs:n})})}}function sE(e){let t=lE(e?.data),n=lE(t?.item),r=lE(n?.result),i=lE(n?.input),a=uE(e?.itemType),o=uE(e?.detail),s=[e?.command,n?.command,i?.command,r?.command,t?.command,a===`command_execution`&&o?cE(o).output:null];for(let e of s){let t=bE(e);if(t)return{command:t,rawCommand:xE(e,t)}}return{command:null,rawCommand:null}}function cE(e){let t=e.trim(),n=/^(?<output>[\s\S]*?)(?:\s*<exited with exit code (?<code>\d+)>)\s*$/i.exec(t);if(!n?.groups)return{output:t.length>0?t:null};let r=Number.parseInt(n.groups.code??``,10),i=n.groups.output?.trim()??``;return{output:i.length>0?i:null,...Number.isInteger(r)?{exitCode:r}:{}}}function lE(e){return e&&typeof e==`object`?e:null}function uE(e){if(typeof e!=`string`)return null;let t=e.trim();return t.length>0?t:null}function dE(e){let t=e.trim();if(t.startsWith(`'`)&&t.endsWith(`'`)||t.startsWith(`"`)&&t.endsWith(`"`)){let e=t.slice(1,-1).trim();return e.length>0?e:t}return t}function fE(e){let t=dE(e);if(t.length===0)return null;let n=t.replace(/\\/g,`/`).split(`/`).at(-1)?.trim()??``;return n.length>0?n.toLowerCase():null}function pE(e){let t=e.trim();if(t.length===0)return null;if(t.startsWith(`"`)||t.startsWith(`'`)){let e=t.charAt(0),n=t.indexOf(e,1);return n<=0?null:{executable:t.slice(0,n+1),rest:t.slice(n+1).trim()}}let n=t.search(/\s/);return n<0?{executable:t,rest:``}:{executable:t.slice(0,n),rest:t.slice(n).trim()}}var mE=[{executables:[`pwsh`,`pwsh.exe`,`powershell`,`powershell.exe`],wrapperFlagPattern:/(?:^|\s)-command\s+/i},{executables:[`cmd`,`cmd.exe`],wrapperFlagPattern:/(?:^|\s)\/c\s+/i},{executables:[`bash`,`sh`,`zsh`],wrapperFlagPattern:/(?:^|\s)-(?:l)?c\s+/i}];function hE(e){return mE.find(t=>t.executables.includes(e))}function gE(e,t){let n=t.exec(e);if(!n)return null;let r=e.slice(n.index+n[0].length).trim();if(r.length===0)return null;let i=r[0];if((i===`'`||i===`"`)&&!r.endsWith(i))return null;let a=dE(r);return a.length>0?a:null}function _E(e){let t=pE(e);if(!t||t.rest.length===0)return e;let n=fE(t.executable);if(!n)return e;let r=hE(n);return r?gE(t.rest,r.wrapperFlagPattern)??e:e}function vE(e){return/[\s"'`]/.test(e)?`"${e.replace(/"/g,`\\"`)}"`:e}function yE(e){let t=uE(e);if(t)return t;if(!Array.isArray(e))return null;let n=[];for(let t of e){let e=uE(t);e!==null&&n.push(e)}return n.length===0?null:n.map(e=>vE(e)).join(` `)}function bE(e){let t=yE(e);return t?_E(t):null}function xE(e,t){let n=yE(e);return!n||t===null||n===t?null:n}function SE(e){return typeof e==`object`&&e&&!Array.isArray(e)?e:null}function CE(e){return typeof e==`string`&&e.trim().length>0?e:null}function wE(e){let t=CE(e);if(t)return t;let n=Array.isArray(e)?e:null,r=SE(e)?.content,i=CE(r);if(i)return i;let a=n??(Array.isArray(r)?r:null);if(!a)return null;let o=a.flatMap(e=>{let t=CE(e)??CE(SE(e)?.text);return t?[t]:[]});return o.length>0?o.join(`
|
|
17
|
-
`):null}function
|
|
14
|
+
`)){let e=/^- (.+):$/.exec(t);if(e){r(),n={header:e[1],bodyLines:[]};continue}if(n){if(t.startsWith(` `)){n.bodyLines.push(t.slice(2));continue}t.length===0&&n.bodyLines.push(``)}}return r(),t}function Wm(e){let t=0;for(let n of e)n===``&&(t+=1);return t}function Gm(e,t){let n=t-Wm(e);return n<=0?e:`${``.repeat(n)}${e}`}function Km(e){return e===void 0||e===` `||e===`
|
|
15
|
+
`||e===` `||e===`\r`}function qm(e,t){let n=Math.max(0,Math.min(e.length,Math.floor(t))),r=`${Km(e[n-1])?``:` `} `,i=e[n]===` `?n+1:n;return{prompt:`${e.slice(0,n)}${r}${e.slice(i)}`,cursor:n+r.length,contextIndex:Wm(e.slice(0,n))}}function Jm(e){return e.replaceAll(``,``)}function Ym(e,t){if(t<0)return{prompt:e,cursor:e.length};let n=0;for(let r=0;r<e.length;r+=1)if(e[r]===``){if(n===t)return{prompt:e.slice(0,r)+e.slice(r+1),cursor:r};n+=1}return{prompt:e,cursor:e.length}}var Xm=e=>Symbol.iterator in e,Zm=e=>`entries`in e,Qm=(e,t)=>{let n=e instanceof Map?e:new Map(e.entries()),r=t instanceof Map?t:new Map(t.entries());if(n.size!==r.size)return!1;for(let[e,t]of n)if(!r.has(e)||!Object.is(t,r.get(e)))return!1;return!0},$m=(e,t)=>{let n=e[Symbol.iterator](),r=t[Symbol.iterator](),i=n.next(),a=r.next();for(;!i.done&&!a.done;){if(!Object.is(i.value,a.value))return!1;i=n.next(),a=r.next()}return!!i.done&&!!a.done};function eh(e,t){return Object.is(e,t)?!0:typeof e!=`object`||!e||typeof t!=`object`||!t||Object.getPrototypeOf(e)!==Object.getPrototypeOf(t)?!1:Xm(e)&&Xm(t)?Zm(e)&&Zm(t)?Qm(e,t):$m(e,t):Qm({entries:()=>Object.entries(e)},{entries:()=>Object.entries(t)})}function th(e){let t=O.useRef(void 0);return n=>{let r=e(n);return eh(t.current,r)?t.current:t.current=r}}var nh=[`draftsByThreadKey`,`draftThreadsByThreadKey`,`logicalProjectDraftThreadKeyByLogicalProjectKey`],rh=[`stickyModelSelectionByProvider`,`stickyActiveProvider`];function ih(e){let t=oh(e.nextLocal,e.version,!1);if(!t)return e.currentStored??e.nextLocal;if(e.currentStored!==null&&e.canMigrate!==void 0&&!e.canMigrate(e.currentStored,e.version))return e.currentStored;if(e.previousLocal===e.currentStored&&(e.canMigrate??ah)(e.currentStored,e.version))return e.nextLocal;let n=oh(e.previousLocal,e.version,!0),r=oh(e.currentStored,e.version,!0);if(!r||!n)return e.currentStored??e.nextLocal;let i={...r.state};for(let e of nh)i[e]=uh(n.state[e],r.state[e],t.state[e]);for(let e of rh)dh(n.state[e],t.state[e])||(i[e]=t.state[e]);return JSON.stringify({...r,version:e.version,state:i})}function ah(e,t){if(e===null)return!0;try{let n=JSON.parse(e);return!fh(n)||!fh(n.state)||typeof n.version!=`number`||!Number.isInteger(n.version)?!1:n.version>=1&&n.version<t}catch{return!1}}function oh(e,t,n){if(e===null)return n?{version:t,state:lh()}:null;let r=sh(e);return r&&ch(r,t)?{version:t,state:r.state}:null}function sh(e){try{let t=JSON.parse(e);return fh(t)?t:null}catch{return null}}function ch(e,t){let n=e.state;return e.version!==t||!fh(n)?!1:nh.every(e=>fh(n[e]))}function lh(){return Object.fromEntries(nh.map(e=>[e,{}]))}function uh(e,t,n){let r={...t};for(let t of new Set([...Object.keys(e),...Object.keys(n)]))dh(e[t],n[t])||(t in n?r[t]=n[t]:delete r[t]);return r}function dh(e,t){return JSON.stringify(e)===JSON.stringify(t)}function fh(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function ph(e){let t;return{getItem:n=>{let r=e.storage.getItem(n);return t===void 0&&(t=r),r},setItem:(n,r)=>{let i=e.storage.getItem(n),a=ih({previousLocal:t??null,currentStored:i,nextLocal:r,version:e.version,...e.canMigrate===void 0?{}:{canMigrate:e.canMigrate}});(a!==i||i===r)&&(e.storage.setItem(n,a),t=r)},removeItem:n=>{e.storage.removeItem(n),t=null}}}function mh(e){let t=e.auth.status!==`unauthenticated`||e.auth.provenance?.credentialScope===`proxied`;return e.enabled&&e.installed&&e.status===`ready`&&t&&e.models.length>0}var hh={providers:{codex:!0,claude:!1,cmmd:!0},meteredEgressApproved:{codex:!1,claude:!1,cmmd:!1},allowedWallets:[`personal`],updatedAt:`1970-01-01T00:00:00.000Z`};function gh(e){if(e==null)return hh;let t=e.providers,n=e.meteredEgressApproved,r=e.allowedWallets;return{providers:{...hh.providers,...t},meteredEgressApproved:{...hh.meteredEgressApproved,...n},allowedWallets:Array.isArray(r)&&r.length>0?r:hh.allowedWallets,updatedAt:typeof e.updatedAt==`string`?e.updatedAt:hh.updatedAt}}function _h(e){switch(e){case`codex`:return`codex`;case`claudeAgent`:return`claude`;case`cmmd`:case`apex`:return`cmmd`;default:return null}}var vh=[`codex`,`claudeAgent`,`cmmd`];function yh(e,t){if(t==null)return null;let n=t.providers;if(typeof n!=`object`||!n)return null;let r=n[e];return typeof r==`boolean`?r:null}function bh(e,t){let n=_h(e);if(n===null)return{offered:!1,reason:`unknown-provider`};let r=yh(n,t);return r===!0?{offered:!0}:r===!1?{offered:!1,reason:`org-disabled`}:gh(t).providers[n]===!0?{offered:!0}:{offered:!1,reason:`policy-unavailable`}}function xh(e,t){return bh(e,t).offered}function Sh(e,t){return Ch(e,t).offered}function Ch(e,t){return t===null?{offered:!0}:bh(e,t)}function wh(e,t){return gh(t).allowedWallets.includes(e)}function Th(e){return wh(`personal`,e)}function Eh(e){return e===`claudeAgent`||e===`codex`}function Dh(e,t){return e!==`claudeAgent`||Th(t)||xh(`claudeAgent`,t)}function Oh(e){return e.isDebugDisclosureEnabled||Eh(e.provider)&&Th(e.policy)?!1:!xh(e.provider===`apex`?`apex`:e.provider,e.policy)}function kh(e){if(!Fh(e)||!Array.isArray(e.accounts))throw Error(`CMMD returned invalid provider accounts.`);return{accounts:e.accounts.filter(Ah)}}function Ah(e){return Fh(e)?Mh(e.provider)&&Nh(e.providerAccountId)&&jh(e)&&Ph(e.accountEmail)&&Ph(e.accountDisplayName)&&Ph(e.planType)&&typeof e.isDefault==`boolean`&&typeof e.needsReconnect==`boolean`:!1}function jh(e){return(e.credentialTarget===`primary`||e.credentialTarget===`linked`)&&Array.isArray(e.legacyProviderAccountIds)&&e.legacyProviderAccountIds.every(Nh)}function Mh(e){return e===`codex`||e===`claudeAgent`}function Nh(e){return typeof e==`string`&&e.trim().length>0}function Ph(e){return typeof e==`string`||e===null}function Fh(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Ih(e){let t=vr(e);return t.legacyRuntimeId===null?t.shape===`durable-environment`&&typeof e==`string`?e:null:t.legacyRuntimeId}var Lh=class extends Error{constructor(e){super(e===`auth`?`Your CMMD session expired. Sign in again to verify Claude runtime readiness.`:`CMMD denied access to verify Claude runtime readiness. Check your organization permissions.`),this.name=`ForgeProviderAccessAuthorityError`}};async function Rh(e){if(!e.enabled||e.readinessTargetId===null)return null;try{return Vh(await e.load(e.readinessTargetId),e.readinessTargetId)}catch(e){if(e instanceof Ta&&(e.kind===`auth`||e.kind===`permission`))throw new Lh(e.kind);return null}}var zh=new Set([`not_connected`,`pending`,`claimed`,`activating`,`applied`,`failed`,`stale`]),Bh=[`generationId`,`nativeVerifiedAt`,`reason`,`lastErrorCode`,`lastErrorMessage`];function Vh(e,t){if(!Yh(e)||!qh(e)||!Hh(e,t))throw Error(`CMMD returned invalid Claude runtime readiness.`);return e}function Hh(e,t){if(e.deliveryReceipt===null)return e.nativeExecutable!==!0;if(!Yh(e.deliveryReceipt))return!1;let n=e.deliveryReceipt,r=Yh(n.identity)?n.identity:null;return r!==null&&Uh(n,t)&&Kh(r,e.generationId)}function Uh(e,t){return Wh(e,t)&&Gh(e)}function Wh(e,t){return typeof e.receiptId==`string`&&e.receiptId.trim().length>0&&e.runtimeId===t&&typeof e.machineId==`string`&&e.machineId.trim().length>0&&typeof e.credentialEpoch==`number`&&Number.isSafeInteger(e.credentialEpoch)&&e.credentialEpoch>=0}function Gh(e){return typeof e.issuedAt==`string`&&Number.isFinite(Date.parse(e.issuedAt))&&e.expiresAt===null}function Kh(e,t){return e.kind===`credential_generation`&&e.provider===`claude`&&typeof e.credentialGenerationId==`string`&&e.credentialGenerationId===t}function qh(e){return typeof e.connected==`boolean`&&zh.has(String(e.deliveryStatus))&&typeof e.nativeExecutable==`boolean`&&Bh.every(t=>Jh(e[t]))}function Jh(e){return e===null||typeof e==`string`}function Yh(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var Xh={credential_expired_refreshing:`CREDENTIAL_EXPIRED_REFRESHING`,credential_reconnect_required:`CREDENTIAL_RECONNECT_REQUIRED`,credential_not_connected:`CREDENTIAL_RECONNECT_REQUIRED`,credential_generation_not_applied:`CREDENTIAL_GENERATION_NOT_APPLIED`,runtime_unavailable:`RUNTIME_UNAVAILABLE`};function Zh(e){return typeof e!=`string`||!Object.hasOwn(Xh,e)?null:Xh[e]??null}var Qh=new Set([`pending`,`claimed`,`activating`]),$h=2e3;function eg(e){return{readinessTargetId:e,dataUpdatedAt:0,consecutiveUnavailableResponses:0,consecutiveFailedResponses:0}}function tg(e){let t=e.current.readinessTargetId===e.readinessTargetId?e.current:eg(e.readinessTargetId);return e.dataUpdatedAt===0||e.dataUpdatedAt===t.dataUpdatedAt?t:{readinessTargetId:e.readinessTargetId,dataUpdatedAt:e.dataUpdatedAt,consecutiveUnavailableResponses:e.readinessUnavailable?t.consecutiveUnavailableResponses+1:0,consecutiveFailedResponses:e.deliveryStatus===`failed`?t.consecutiveFailedResponses+1:0}}function ng(e,t){if(!e.claudeOffered||!e.claudeConnected)return!1;let n=Zh(e.reason);return n===`CREDENTIAL_EXPIRED_REFRESHING`?!0:e.deliveryStatus===`failed`?n!==`CREDENTIAL_RECONNECT_REQUIRED`&&t.consecutiveFailedResponses<16:e.deliveryStatus===null?t.consecutiveUnavailableResponses>0&&t.consecutiveUnavailableResponses<3:Qh.has(e.deliveryStatus)}function rg(e){return e.credentialMode===`runtime`?e.provider&&mh(e.provider)?{eligible:!0}:{eligible:!1,reason:`runtime-unavailable`}:e.access.status===`loading`?{eligible:!1,reason:`access-loading`}:e.access.status===`error`?{eligible:!1,reason:`access-error`}:ig({provider:e.provider,providerKind:e.providerKind,policy:e.access.policy,personalConnections:e.access.personalConnections,personalReconnectRequired:e.access.personalReconnectRequired,claudeRuntimeReadiness:e.access.claudeRuntimeReadiness})}function ig(e){return!e.provider||!mh(e.provider)?{eligible:!1,reason:`runtime-unavailable`}:e.policy===null?{eligible:!1,reason:`access-error`}:xh(e.providerKind,e.policy)?og({providerKind:e.providerKind,policy:e.policy,personalConnections:e.personalConnections,personalReconnectRequired:e.personalReconnectRequired,claudeRuntimeReadiness:e.claudeRuntimeReadiness,stage:`live-runtime`}):{eligible:!1,reason:`not-offered`}}function ag(e){return e.access.status===`loading`?{eligible:!1,reason:`access-loading`}:e.access.status===`error`||e.access.policy===null?{eligible:!1,reason:`access-error`}:xh(e.providerKind,e.access.policy)?og({providerKind:e.providerKind,policy:e.access.policy,personalConnections:e.access.personalConnections,personalReconnectRequired:e.access.personalReconnectRequired,claudeRuntimeReadiness:e.access.claudeRuntimeReadiness,stage:`provisioning`}):{eligible:!1,reason:`not-offered`}}function og(e){return e.providerKind===`cmmd`||e.providerKind===`apex`?{eligible:!0}:e.providerKind!==`codex`&&e.providerKind!==`claudeAgent`?{eligible:!1,reason:`not-offered`}:sg({providerKind:e.providerKind,personalConnections:e.personalConnections,personalReconnectRequired:e.personalReconnectRequired,claudeRuntimeReadiness:e.claudeRuntimeReadiness,workspaceWalletAllowed:wh(`workspace`,e.policy),stage:e.stage})}function sg(e){return cg(e.workspaceWalletAllowed)?{eligible:!0}:lg(e.providerKind,e.personalReconnectRequired)?{eligible:!1,reason:`personal-credential-reconnect-required`}:ug(e.providerKind,e.personalConnections)?pg(e)?{eligible:!1,reason:`environment-not-running`}:dg(e)?{eligible:!0}:{eligible:!1,reason:`native-runtime-not-ready`}:{eligible:!1,reason:`personal-credential-required`}}function cg(e){return e&&!1}function lg(e,t){return e===`codex`&&t?.codex===!0}function ug(e,t){return t?.[e]===!0}function dg(e){return e.providerKind!==`claudeAgent`||e.stage===`provisioning`||mg(e.claudeRuntimeReadiness)}var fg=`runtime_unavailable`;function pg(e){return e.providerKind!==`claudeAgent`||e.stage===`provisioning`?!1:e.claudeRuntimeReadiness?.reason===fg}function mg(e){if(!hg(e))return!1;let t=e.deliveryReceipt?.identity;return t?.kind===`credential_generation`&&t.provider===`claude`&&t.credentialGenerationId===e.generationId}function hg(e){return e?.connected===!0&&e.nativeExecutable===!0&&typeof e.generationId==`string`&&e.generationId.trim().length>0}function gg(e){if(e.status!==`ready`)return!1;if(e.policy===null)return!0;let t=e.policy.providers,n=wh(`workspace`,e.policy);return t.cmmd?!0:wh(`personal`,e.policy)||n?t.codex&&e.personalConnections?.codex===!0||t.claude&&e.personalConnections?.claudeAgent===!0:!1}var _g={providers:{codex:!1,claude:!1,cmmd:!1},meteredEgressApproved:{codex:!1,claude:!1,cmmd:!1},allowedWallets:[`personal`],updatedAt:`1970-01-01T00:00:00.000Z`},vg=[`cmmd`,`forge-provider-access`],yg=$h;function bg(e,t){return!(t instanceof Lh)&&e<3}function xg(e,t=null){return[...vg,e,t]}async function Sg(e){e.queryClient.setQueriesData({queryKey:vg},t=>Cg(t,e.provider,e.connected)),await e.queryClient.invalidateQueries({queryKey:vg,refetchType:`all`})}function Cg(e,t,n){return e?.status!==`ready`||e.personalConnections===null?e:{...e,personalConnections:{...e.personalConnections,[t]:n},...t===`codex`?{personalReconnectRequired:{codex:!1}}:{},...t===`claudeAgent`?{claudeRuntimeReadiness:null}:{}}}async function wg(e,t=null){if(e===`runtime`)return{status:`ready`,policy:null,personalConnections:null,providerAccounts:[],claudeRuntimeReadiness:null};let n=$n(),r=jg(await n.getOrgProviderPolicy());wh(`workspace`,r);let[i,a,o,s]=await Promise.all([Dg(()=>n.getProviderAccounts()),Og({enabled:r.providers.codex,load:()=>n.getUserCodexCredential(),provider:`codex`}),Og({enabled:r.providers.claude,load:()=>n.getUserClaudeCredential(),provider:`claudeAgent`}),Rh({enabled:r.providers.claude,readinessTargetId:t,load:e=>n.getClaudeRuntimeReadiness(e)})]),c=i.accounts.filter(e=>e.provider===`codex`?r.providers.codex:r.providers.claude),l=Tg(c),u=l.codex||a.connected,d=l.claudeAgent||o.connected,f=c.some(e=>e.provider===`codex`&&e.needsReconnect)||a.reconnectRequired;return{status:`ready`,policy:r,personalConnections:{codex:u,claudeAgent:d},providerAccounts:c,...f?{personalReconnectRequired:{codex:!0}}:{},claudeRuntimeReadiness:s}}function Tg(e){return{codex:e.some(e=>e.provider===`codex`&&!e.needsReconnect),claudeAgent:e.some(e=>e.provider===`claudeAgent`&&!e.needsReconnect)}}function Eg(e,t){if(e.status!==`ready`)return;let n=e.providerAccounts??[];return(n.find(e=>e.provider===t&&e.isDefault&&!e.needsReconnect)??n.find(e=>e.provider===t&&!e.needsReconnect))?.providerAccountId}async function Dg(e){try{return kh(await e())}catch{return{accounts:[]}}}async function Og(e){if(!e.enabled)return{connected:!1,reconnectRequired:!1};try{return Fg(await e.load(),e.provider)}catch{return{connected:!1,reconnectRequired:!1}}}function kg(e){let t=e?.policy?.providers.claude===!0,n=e?.personalConnections?.claudeAgent===!0;return{claudeOffered:t,claudeConnected:n,deliveryStatus:e?.claudeRuntimeReadiness?.deliveryStatus??null,reason:e?.claudeRuntimeReadiness?.reason??null,readinessUnavailable:t&&n&&e?.claudeRuntimeReadiness===null}}function Ag(e){let t=(0,A.c)(21),n;t[0]!==e.environmentId||t[1]!==e.runtimeId?(n=e.environmentId==null?e.runtimeId??null:Ih(e.environmentId),t[0]=e.environmentId,t[1]=e.runtimeId,t[2]=n):n=t[2];let r=n,i;t[3]===r?i=t[4]:(i=eg(r),t[3]=r,t[4]=i);let a=(0,O.useRef)(i),o;t[5]!==e.credentialMode||t[6]!==r?(o=xg(e.credentialMode,r),t[5]=e.credentialMode,t[6]=r,t[7]=o):o=t[7];let s;t[8]===r?s=t[9]:(s=()=>wg(`cmmd-cloud`,r),t[8]=r,t[9]=s);let c=e.enabled&&e.credentialMode===`cmmd-cloud`,l;t[10]===r?l=t[11]:(l=e=>{if(e.state.error instanceof Lh)return!1;let t=kg(e.state.data);return a.current=tg({current:a.current,readinessTargetId:r,dataUpdatedAt:e.state.dataUpdatedAt,readinessUnavailable:r!==null&&t.readinessUnavailable,deliveryStatus:t.deliveryStatus}),r!==null&&ng(t,a.current)?yg:!1},t[10]=r,t[11]=l);let u;t[12]!==o||t[13]!==s||t[14]!==c||t[15]!==l?(u={queryKey:o,queryFn:s,enabled:c,retry:bg,staleTime:3e4,refetchInterval:l},t[12]=o,t[13]=s,t[14]=c,t[15]=l,t[16]=u):u=t[16];let d=Bs(u);if(!e.enabled){let e;return t[17]===Symbol.for(`react.memo_cache_sentinel`)?(e={status:`loading`},t[17]=e):e=t[17],e}if(e.credentialMode===`runtime`){let e;return t[18]===Symbol.for(`react.memo_cache_sentinel`)?(e={status:`ready`,policy:null,personalConnections:null,providerAccounts:[],claudeRuntimeReadiness:null},t[18]=e):e=t[18],e}if(d.isPending){let e;return t[19]===Symbol.for(`react.memo_cache_sentinel`)?(e={status:`loading`},t[19]=e):e=t[19],e}if(d.isError||!d.data){let e;return t[20]===Symbol.for(`react.memo_cache_sentinel`)?(e={status:`error`},t[20]=e):e=t[20],e}return d.data}function jg(e){if(!Lg(e)||!Lg(e.providers))throw Error(`CMMD returned an invalid organization provider policy.`);let{providers:t,meteredEgressApproved:n,allowedWallets:r,updatedAt:i}=e,a=Pg(r,i);if(!Ng(t)||a===null)throw Error(`CMMD returned an invalid organization provider policy.`);return{providers:{codex:t.codex,claude:t.claude,cmmd:t.cmmd},meteredEgressApproved:Mg(n),allowedWallets:[...new Set(a.allowedWallets)],updatedAt:a.updatedAt}}function Mg(e){return Lg(e)&&Ng(e)?{codex:e.codex,claude:e.claude,cmmd:e.cmmd}:{codex:!1,claude:!1,cmmd:!1}}function Ng(e){return typeof e.codex==`boolean`&&typeof e.claude==`boolean`&&typeof e.cmmd==`boolean`}function Pg(e,t){return Array.isArray(e)&&e.length>0&&e.every(Ig)&&typeof t==`string`&&t.trim().length>0?{allowedWallets:e,updatedAt:t}:null}function Fg(e,t){if(!Lg(e)||typeof e.connected!=`boolean`)throw Error(`CMMD returned an invalid ${t} connection state.`);if(!e.connected)return{connected:!1,reconnectRequired:!1};if(t===`codex`){if(typeof e.needsReconnect!=`boolean`)throw Error(`CMMD returned an invalid Codex connection state.`);return{connected:!e.needsReconnect,reconnectRequired:e.needsReconnect}}if(typeof e.generationId!=`string`||e.generationId.trim().length===0)throw Error(`CMMD returned an invalid Claude connection state.`);return{connected:!0,reconnectRequired:!1}}function Ig(e){return e===`personal`||e===`workspace`}function Lg(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Rg(e){return e.status===`ready`?e.policy:_g}var zg=[`cursor`,`opencode`,`gemini`],Bg={state:`usable`},Vg={state:`withheld`,reason:`unbuilt`},Hg={state:`withheld`,reason:`not-on-this-environment`};function Ug(e){return zg.includes(e)}function Wg(e){return e===`gemini`?null:e}function Gg(e,t){if(e===void 0)return t?Hg:Bg;if(e.availability===`unavailable`){let t=e.unavailableReason??`not-on-this-environment`,n=t===`not-on-this-environment`&&e.availabilityCheck===`could-not-check`?`could-not-check`:e.unavailableDetail;return n===void 0?{state:`withheld`,reason:t}:{state:`withheld`,reason:t,detail:n}}return e.availability===`available`||mh(e)||Kg(e)?Bg:Hg}function Kg(e){return e.installed&&e.auth.status===`unauthenticated`&&e.auth.provenance?.credentialScope!==`proxied`}function qg(e,t){let n=ag({providerKind:e,access:t});return n.eligible?null:Jg(n.reason)}function Jg(e){switch(e){case`access-loading`:return{state:`unresolved`,cause:`loading`};case`access-error`:return{state:`unresolved`,cause:`error`};case`not-offered`:return{state:`withheld`,reason:`not-offered`};case`personal-credential-required`:return{state:`withheld`,reason:`not-usable`,detail:`no-connection`};case`personal-credential-reconnect-required`:return{state:`withheld`,reason:`not-usable`,detail:`reconnect-required`};case`native-runtime-not-ready`:return{state:`withheld`,reason:`not-usable`,detail:`delivery-pending`};case`environment-not-running`:return{state:`withheld`,reason:`not-usable`,detail:`environment-not-running`};case`runtime-unavailable`:return null}}function Yg(e){if(Ug(e.provider))return{pick:Vg,run:Vg};let t=Wg(e.provider);return t===null?{pick:Vg,run:Vg}:Xg({...e,providerKind:t})}function Xg(e){return{pick:$g(e,`pick`),run:$g(e,`run`)}}function Zg(e){return $g(e,`pick`)}function Qg(e){return e.providers.filter(t=>$g({providerKind:t.provider,snapshot:t,access:e.access,credentialMode:e.credentialMode,hasLiveInventory:e.hasLiveInventory},`run`).state===`usable`)}function $g(e,t){let{providerKind:n}=e;if(e.snapshot?.unavailableReason===`unbuilt`)return Vg;if(e.credentialMode===`runtime`)return e_({...e,providerKind:n},t);if(e.access.status!==`ready`)return{state:`unresolved`,cause:e.access.status};if(!Ch(n,e.access.policy).offered)return{state:`withheld`,reason:`not-offered`};let r=qg(n,e.access);return r===null?e_({...e,providerKind:n},t):r}function e_(e,t){let n=rg({provider:e.snapshot,providerKind:e.providerKind,access:e.access,credentialMode:e.credentialMode});if(!n.eligible&&n.reason===`environment-not-running`)return{state:`withheld`,reason:`not-usable`,detail:`environment-not-running`};if(!n.eligible&&n.reason===`native-runtime-not-ready`)return{state:`withheld`,reason:`not-usable`,detail:`delivery-pending`};let r=Gg(e.snapshot,e.hasLiveInventory);return!n.eligible&&n.reason===`runtime-unavailable`&&t===`run`?t_(r,e.hasLiveInventory)?Bg:Hg:r}function t_(e,t){return e.state===`withheld`&&e.reason===`not-on-this-environment`&&(e.detail===`could-not-check`||!t)}var n_={reasoningEffortLevels:[],supportsFastMode:!1,supportsThinkingToggle:!1,contextWindowOptions:[],promptInjectedEffortLevels:[]},r_=[`codex`,`claudeAgent`,`apex`];function i_(e){for(let t of r_){let n=e.find(e=>e.provider===t);if(n&&o_(n))return t}return e.find(o_)?.provider??null}function a_(e,t){return e.find(e=>e.provider===t)?.models??[]}function o_(e){return mh(e)}function s_(e,t){let n=t??i_(e)??`codex`,r=e.find(e=>e.provider===n);if(r&&o_(r)||n===`codex`)return n;for(let t of r_){let n=e.find(e=>e.provider===t);if(n&&o_(n))return t}return`codex`}function c_(e){return e.providers.filter(t=>Zg({providerKind:t.provider,snapshot:t,access:e.access,credentialMode:e.credentialMode,hasLiveInventory:!0}).state===`usable`)}function l_(e,t,n,r){let i=c_({providers:e,access:n,credentialMode:r});return t&&i.some(e=>e.provider===t)?t:i_(i)}function u_(e,t,n,r){return t==null?l_(e,null,n,r):Qg({providers:e,access:n,credentialMode:r,hasLiveInventory:!0}).some(e=>e.provider===t)?t:null}function d_(e,t,n){let r=Dn(t,n);return e.find(e=>e.slug===r)?.capabilities??n_}function f_(e,t,n){let r=a_(e,t).filter(e=>!e.isLegacy);return r.find(e=>e.slug===n)?.slug??r.find(e=>e.isDefault)?.slug??r.find(e=>e.slug===Fi[t])?.slug??r.find(e=>!e.isCustom)?.slug??r[0]?.slug??Fi[t]}function p_(e){let{provider:t,model:n,models:r,prompt:i,modelOptions:a}=e,o=d_(r,n,t),s=a?.[t],c=s?`effort`in s?s.effort:`reasoningEffort`in s?s.reasoningEffort:null:null,l=fn(o,c)??null,u=t===`codex`?Hn(o,s):zn(o,s),d=o.promptInjectedEffortLevels.length>0&&Bn(i);return{provider:t,promptEffort:l,modelOptionsForDispatch:u,...d?{composerFrameClassName:`ultrathink-frame`}:{},...d?{composerSurfaceClassName:`shadow-[0_0_0_1px_rgba(255,255,255,0.04)_inset]`}:{},...d?{modelPickerIconClassName:`ultrathink-chroma`}:{}}}function m_(e,t,n,r){return a_(t,n).map(({slug:e,name:t,isCustom:n,isDefault:r,isLegacy:i})=>({slug:e,name:t,isCustom:n,isDefault:r,isLegacy:i}))}function h_(e,t,n,r,i){let a=fr(e,r,m_(t,n,e,r));if(a&&!yn(a,e))return a;let o=g_(n,e,i),s=m_(t,n,o,r),c=fr(o,r,s)??f_(n,o);return e&&yn(c,e)?f_(n,e):c}function g_(e,t,n){return!t||!xh(t,n)?s_(e,`codex`):s_(e,t)}function __(e,t,n,r){return{codex:m_(e,t,`codex`,n===`codex`?r:void 0),claudeAgent:m_(e,t,`claudeAgent`,n===`claudeAgent`?r:void 0),ollama:m_(e,t,`ollama`,n===`ollama`?r:void 0),cmmd:m_(e,t,`cmmd`,n===`cmmd`?r:void 0),apex:m_(e,t,`apex`,n===`apex`?r:void 0),cursor:m_(e,t,`cursor`,n===`cursor`?r:void 0),opencode:m_(e,t,`opencode`,n===`opencode`?r:void 0)}}function v_(e,t,n){let r=e.textGenerationModelSelection??{provider:`codex`,model:si.codex},i=g_(t,r.provider,n),a=h_(i,e,t,i===r.provider?r.model:null,n),{modelOptionsForDispatch:o}=p_({provider:i,model:a,models:a_(t,i),prompt:``,modelOptions:{[i]:i===r.provider?r.options:void 0}});return{provider:i,model:a,...o?{options:o}:{}}}function y_(e){return e?.options?{[e.provider]:e.options}:null}function b_(e){if(!e)return null;let t={};for(let[n,r]of Object.entries(e))r?.options&&(t[n]=r.options);return Object.keys(t).length>0?t:null}function x_(e){if(e.activeSelection&&`providerAccountId`in e.activeSelection)return e.activeSelection.providerAccountId;for(let t of e.candidates)if(t?.provider===e.selectedProvider&&`providerAccountId`in t)return t.providerAccountId}function S_(e){let t=t=>t!==void 0&&yn(t,e.selectedProvider)?void 0:t,n=t(e.threadModelSelection?.provider===e.selectedProvider?e.threadModelSelection.model:void 0),r=t(e.projectModelSelection?.provider===e.selectedProvider?e.projectModelSelection.model:void 0),i=Dn(n??r,e.selectedProvider)??f_(e.providers,e.selectedProvider),a=e.draft?.modelSelectionByProvider?.[e.selectedProvider],o=x_({activeSelection:a,selectedProvider:e.selectedProvider,candidates:[e.threadModelSelection,e.projectModelSelection]}),s=t(a?.model),c=s?h_(e.selectedProvider,e.settings,e.providers,s):i,l=b_(e.draft?.modelSelectionByProvider)??y_(e.threadModelSelection)??y_(e.projectModelSelection)??null;return{selectedModel:c,...o?{selectedProviderAccountId:o}:{},modelOptions:l}}var C_=zi({id:E,name:E,mimeType:E,sizeBytes:gi,dataUrl:E}),w_=zi({id:E,name:E,mimeType:E,sizeBytes:gi}),T_=zi({id:E,threadId:zr,createdAt:E,terminalId:E,terminalLabel:E,lineStart:gi,lineEnd:gi}),E_=zi({prompt:E,attachments:ji(C_),files:w(ji(w_)),terminalContexts:ji(T_),startedAt:E,commandId:w(Dr),messageId:w(Cr),modelSelection:w(Ei),runtimeMode:w(hi),interactionMode:w(Pi),executionIntent:w(zi({runtimeId:E,intentId:w(E)}))});function D_(e,t){return Array.isArray(e)?e.flatMap(e=>t(e)??[]):[]}function O_(e){if(!(!e||typeof e.runtimeId!=`string`))return{runtimeId:e.runtimeId,...typeof e.intentId==`string`?{intentId:e.intentId}:{}}}function k_(e){return{...typeof e.commandId==`string`?{commandId:Dr.make(e.commandId)}:{},...typeof e.messageId==`string`?{messageId:Cr.make(e.messageId)}:{}}}function A_(e,t){let n=t.modelSelection(e.modelSelection);return{...n?{modelSelection:n}:{},...t.runtimeMode(e.runtimeMode)?{runtimeMode:e.runtimeMode}:{},...e.interactionMode==="default"||e.interactionMode===`plan`?{interactionMode:e.interactionMode}:{}}}function j_(e,t){if(!e||typeof e!=`object`)return null;let n=e;if(typeof n.prompt!=`string`||typeof n.startedAt!=`string`)return null;let r=O_(n.executionIntent);return{prompt:n.prompt,attachments:D_(n.attachments,t.attachment),files:D_(n.files,t.file),terminalContexts:D_(n.terminalContexts,t.terminalContext),startedAt:n.startedAt,...k_(n),...A_(n,t),...r?{executionIntent:r}:{}}}function M_(e){return{id:e.id,threadId:e.threadId,createdAt:e.createdAt,terminalId:e.terminalId,terminalLabel:e.terminalLabel,lineStart:e.lineStart,lineEnd:e.lineEnd}}function N_(e){return{prompt:e.prompt,attachments:[...e.attachments],files:[...e.files],terminalContexts:e.terminalContexts.map(M_),startedAt:e.startedAt,...e.commandId?{commandId:e.commandId}:{},...e.messageId?{messageId:e.messageId}:{},...e.modelSelection?{modelSelection:e.modelSelection}:{},...e.runtimeMode?{runtimeMode:e.runtimeMode}:{},...e.interactionMode?{interactionMode:e.interactionMode}:{},...e.executionIntent?{executionIntent:e.executionIntent}:{}}}function P_(e){return e?{...e,attachments:[...e.attachments],files:[...e.files??[]],terminalContexts:e.terminalContexts.map(e=>({...e,text:``}))}:null}function F_(e,t,n,r){let i=e[t];if(i?.stagedSubmission)return null;let a=V_(i??I_(),r,n);return a?{previousDraft:i,restoredDraft:a,drafts:{...e,[t]:a}}:null}function I_(){return{prompt:``,images:[],files:[],nonPersistedImageIds:[],persistedAttachments:[],terminalContexts:[],modelSelectionByProvider:{},activeProvider:null,runtimeMode:null,interactionMode:null,stagedSubmission:null}}function L_(e){return`${e.mimeType}\u0000${e.sizeBytes}\u0000${e.name}`}function R_(e){return`${e.terminalId}\u0000${e.lineStart}\u0000${e.lineEnd}`}function z_(e,t){let n=t.terminalId.trim(),r=t.terminalLabel.trim(),i=Om(t.text);if(!n||!r)return null;let a=Math.max(1,Math.floor(t.lineStart));return{...t,threadId:e,terminalId:n,terminalLabel:r,lineStart:a,lineEnd:Math.max(a,Math.floor(t.lineEnd)),text:i}}function B_(e,t){let n=new Set,r=new Set,i=[];for(let a of t){let t=z_(e,a);if(!t)continue;let o=R_(t);n.has(t.id)||r.has(o)||(i.push(t),n.add(t.id),r.add(o))}return i}function V_(e,t,n){let r=U_(e,t);if(!r)return null;let i=H_(e.files??[],t.files);if(r.images.length+i.length>8)return null;let a=W_(e,t,n),o=[e.prompt,t.prompt].filter(e=>e.length>0).join(`
|
|
16
|
+
`);return{...e,prompt:Gm(o,a.contexts.length),images:r.images,files:i,persistedAttachments:r.attachments,terminalContexts:a.contexts,stashTerminalContexts:[...e.stashTerminalContexts??[],...a.restoredSnapshots]}}function H_(e,t){let n=new Set(e.map(e=>e.id));return[...e,...t.filter(e=>!n.has(e.id))]}function U_(e,t){let n=new Map(t.attachments.map(e=>[e.id,e])),r=[...e.images],i=e.persistedAttachments.filter(t=>e.images.some(e=>e.id===t.id)),a=new Set(r.map(e=>e.id)),o=new Set(r.map(L_));for(let e of t.images){let t=n.get(e.id);if(!t)return null;let s=L_(e);a.has(e.id)||o.has(s)||(r.push(e),i.push(t),a.add(e.id),o.add(s))}return r.length>8?null:{images:r,attachments:i}}function W_(e,t,n){let r=[...e.terminalContexts],i=new Set(r.map(e=>e.id)),a=new Set(r.map(R_)),o=[];for(let e of t.terminalContexts){let t=z_(n,e);!t||i.has(t.id)||a.has(R_(t))||(r.push(t),o.push(t),i.add(t.id),a.add(R_(t)))}return{contexts:r,restoredSnapshots:o}}function G_(e,t){return e.prompt===t.prompt&&JSON.stringify(e.attachments)===JSON.stringify(t.persistedAttachments)&&JSON.stringify(e.files??[])===JSON.stringify((t.files??[]).map(({file:e,type:t,...n})=>n))&&JSON.stringify(e.terminalContexts??[])===JSON.stringify(t.terminalContexts.map(({text:e,...t})=>t))&&JSON.stringify(e.stashTerminalContexts??[])===JSON.stringify(t.stashTerminalContexts??[])}function K_(e){typeof URL<`u`&&e.startsWith(`blob:`)&&URL.revokeObjectURL(e)}function q_(e){if(!e||typeof e!=`object`)return null;let{id:t,name:n,mimeType:r,sizeBytes:i,dataUrl:a}=e;return typeof t!=`string`||typeof n!=`string`||typeof r!=`string`||typeof i!=`number`||!Number.isFinite(i)||typeof a!=`string`||t.length===0||a.length===0?null:{id:t,name:n,mimeType:r,sizeBytes:i,dataUrl:a}}function J_(e){if(!e||typeof e!=`object`)return null;let{id:t,name:n,mimeType:r,sizeBytes:i}=e;return typeof t!=`string`||t.length===0||typeof n!=`string`||typeof r!=`string`||typeof i!=`number`||!Number.isSafeInteger(i)||i<0?null:{id:t,name:n,mimeType:r,sizeBytes:i}}async function Y_(e,t){let n=await Promise.all(e.map(async e=>{let n=await t.read(e);return{...e,type:`file`,file:n}}));return n.length===e.length?n:null}function X_(e){let t=Z_(e.dataUrl,e.mimeType);return t?new File([t.content],e.name,{type:t.mimeType}):null}function Z_(e,t){let n=e.indexOf(`,`),r=n===-1?e:e.slice(0,n),i=n===-1?``:e.slice(n+1);if(i.length===0)return null;try{return r.includes(`;base64`)?{content:ev(i),mimeType:t}:{content:$_(i),mimeType:Q_(r,t)}}catch{return null}}function Q_(e,t){return!e.startsWith(`data:`)||!e.includes(`;`)?t:e.slice(5,e.indexOf(`;`))||t}function $_(e){return decodeURIComponent(e)}function ev(e){let t=atob(e),n=new Uint8Array(new ArrayBuffer(t.length));for(let e=0;e<t.length;e+=1)n[e]=t.charCodeAt(e);return n}function tv(e){return e.flatMap(e=>{let t=X_(e);return t?[{type:`image`,id:e.id,name:e.name,mimeType:e.mimeType,sizeBytes:e.sizeBytes,previewUrl:e.dataUrl,file:t}]:[]})}function nv(e){return{prompt:e.prompt,images:[...e.images],files:[...e.files??[]],persistedAttachments:[...e.persistedAttachments],terminalContexts:[...e.terminalContexts]}}function rv({file:e,previewUrl:t,...n}){return n}function iv(e,t){return e.prompt===t.prompt&&JSON.stringify(e.images.map(rv))===JSON.stringify(t.images.map(rv))&&JSON.stringify((e.files??[]).map(({file:e,...t})=>t))===JSON.stringify(t.files.map(({file:e,...t})=>t))&&JSON.stringify(e.persistedAttachments)===JSON.stringify(t.persistedAttachments)&&JSON.stringify(e.terminalContexts)===JSON.stringify(t.terminalContexts)}function av(e){let{lastGeneratedPullRequestPrompt:t,...n}=e;return{...n,prompt:``,images:[],files:[],nonPersistedImageIds:[],persistedAttachments:[],terminalContexts:[],stashTerminalContexts:[]}}function N(e){return e.prompt.length===0&&e.lastGeneratedPullRequestPrompt===void 0&&e.images.length===0&&(e.files?.length??0)===0&&e.persistedAttachments.length===0&&e.terminalContexts.length===0&&Object.keys(e.modelSelectionByProvider).length===0&&e.activeProvider===null&&e.runtimeMode===null&&e.interactionMode===null&&e.stagedSubmission==null}function ov(e){switch(e){case`codex`:case`claudeAgent`:case`ollama`:case`cmmd`:case`apex`:case`cursor`:case`opencode`:return e;default:return null}}function sv(e){return _i.some(t=>t===e)}function cv(e){return wi.some(t=>t===e)}function lv(e,t,n){let r=e&&typeof e==`object`?e:null,i=r?.codex&&typeof r.codex==`object`?r.codex:null,a=r?.claudeAgent&&typeof r.claudeAgent==`object`?r.claudeAgent:null,o=sv(i?.reasoningEffort)?i.reasoningEffort:t===`codex`&&sv(n?.effort)?n.effort:void 0,s=i?.fastMode===!0?!0:i?.fastMode===!1?!1:t===`codex`&&n?.codexFastMode===!0||typeof n?.serviceTier==`string`&&n.serviceTier===`fast`||void 0,c=o!==void 0||s!==void 0?{...o===void 0?{}:{reasoningEffort:o},...s===void 0?{}:{fastMode:s}}:void 0,l=a?.thinking===!0||a?.thinking!==!1&&void 0,u=cv(a?.effort)?a.effort:void 0,d=a?.fastMode===!0||a?.fastMode!==!1&&void 0,f=typeof a?.contextWindow==`string`&&a.contextWindow.length>0?a.contextWindow:void 0,p=l!==void 0||u!==void 0||d!==void 0||f!==void 0?{...l===void 0?{}:{thinking:l},...u===void 0?{}:{effort:u},...d===void 0?{}:{fastMode:d},...f===void 0?{}:{contextWindow:f}}:void 0;return!c&&!p?null:{...c?{codex:c}:{},...p?{claudeAgent:p}:{}}}function uv(e,t){let n=e&&typeof e==`object`?e:null,r=ov(n?.provider??t?.provider);if(r===null)return null;let i=n?.model??t?.model;if(typeof i!=`string`)return null;let a=Dn(i,r);if(!a)return null;let o=lv(n?.options?{[r]:n.options}:t?.modelOptions,r,r===`codex`?t?.legacyCodex:void 0),s=r===`codex`?o?.codex:o?.claudeAgent,c=n?.providerAccountId,l=typeof c==`string`&&c.trim().length>0?c.trim():void 0;return{provider:r,model:a,...l?{providerAccountId:l}:{},...s?{options:s}:{}}}function dv(e,t){if(e===null)return null;let n=t?.[e.provider];return{provider:e.provider,model:e.model,...`providerAccountId`in e&&e.providerAccountId?{providerAccountId:e.providerAccountId}:{},...n?{options:n}:{}}}function fv(e,t){return e?.options===void 0?lv(t):pv(lv(t),e.provider,e.options)}function pv(e,t,n){let{[t]:r,...i}=e??{},a=lv({[t]:n},t);return lv({...i,...a||{}})}function mv(e,t){let n={};if(t)for(let r of[`codex`,`claudeAgent`]){let i=t[r];i&&Object.keys(i).length>0&&(n[r]={provider:r,model:e?.provider===r?e.model:Fi[r],options:i})}return e&&(n[e.provider]=e),n}var hv=`forge:composer-drafts:v1`,gv=5,_v=Oi([`local`,`worktree`]),vv=Br(hi),yv=300,bv=ph({storage:typeof localStorage<`u`?localStorage:gr(),version:gv,canMigrate:Dv}),xv=gn(bv,yv);typeof window<`u`&&typeof window.addEventListener==`function`&&window.addEventListener(`beforeunload`,()=>{xv.flush()});var Sv=zi({prompt:E,lastGeneratedPullRequestPrompt:w(E),attachments:ji(C_),files:w(ji(w_)),terminalContexts:w(ji(T_)),stashTerminalContexts:w(ji(zi({...T_.fields,text:E}))),modelSelectionByProvider:w(oi(fi,w(Ei))),activeProvider:w(vi(fi)),runtimeMode:w(hi),interactionMode:w(Pi),stagedSubmission:w(E_)});zi({effort:w(Oi(_i)),codexFastMode:w(di),serviceTier:w(E)}),zi({provider:w(fi),model:w(E),modelOptions:w(vi(Er))}),zi({stickyProvider:w(fi),stickyModel:w(E),stickyModelOptions:w(vi(Er))});var Cv=zi({threadId:zr,environmentId:E,projectId:xi,logicalProjectKey:w(E),createdAt:E,runtimeMode:hi,interactionMode:Pi,branch:vi(E),worktreePath:vi(E),envMode:_v,promotedTo:w(vi(zi({environmentId:E,threadId:E}))),anchorKind:w(Ur),anchorCmmdId:w(vi(E)),linkedPullRequest:w(vi(Ni))}),wv=zi({draftsByThreadKey:oi(E,Sv),draftThreadsByThreadKey:oi(E,Cv),logicalProjectDraftThreadKeyByLogicalProjectKey:oi(E,E),stickyModelSelectionByProvider:w(oi(fi,w(Ei))),stickyActiveProvider:w(vi(fi))}),Tv=zi({version:gi,state:wv}),Ev=Si(Tv);function Dv(e,t){if(e===null)return!0;try{let n=JSON.parse(e);if(!n||typeof n!=`object`)return!1;let r=n;return r.version===t?(Ev(n),!0):typeof r.version==`number`&&Number.isInteger(r.version)&&r.version>=1&&r.version<t&&r.state!==null&&typeof r.state==`object`}catch{return!1}}function Ov(e){if(e===null)return new Set;try{let t=Ev(JSON.parse(e));if(t.version!==gv)return null;let n=new Set;for(let e of Object.values(t.state.draftsByThreadKey)){for(let t of e.files??[])n.add(t.id);for(let t of e.stagedSubmission?.files??[])n.add(t.id)}return n}catch{return null}}function kv(){xv.flush()}var Av=Object.freeze({draftsByThreadKey:{},draftThreadsByThreadKey:{},logicalProjectDraftThreadKeyByLogicalProjectKey:{},stickyModelSelectionByProvider:{},stickyActiveProvider:null}),jv=[],Mv=[],Nv=[],Pv=[],Fv=[];Object.freeze(jv),Object.freeze(Nv),Object.freeze(Pv);var Iv=Object.freeze({}),Lv=Object.freeze({activeProvider:null,modelSelectionByProvider:Iv}),Rv=Object.freeze({prompt:``,images:jv,files:Mv,nonPersistedImageIds:Nv,persistedAttachments:Pv,terminalContexts:Fv,modelSelectionByProvider:Iv,activeProvider:null,runtimeMode:null,interactionMode:null,stagedSubmission:null});function P(){return{prompt:``,images:[],files:[],nonPersistedImageIds:[],persistedAttachments:[],terminalContexts:[],modelSelectionByProvider:{},activeProvider:null,runtimeMode:null,interactionMode:null,stagedSubmission:null}}function zv(e){if(!e||typeof e!=`object`)return null;let t=e,n=t.id,r=t.threadId,i=t.createdAt,a=t.lineStart,o=t.lineEnd;if(typeof n!=`string`||n.length===0||typeof r!=`string`||r.length===0||typeof i!=`string`||i.length===0||typeof a!=`number`||!Number.isFinite(a)||typeof o!=`number`||!Number.isFinite(o))return null;let s=typeof t.terminalId==`string`?t.terminalId.trim():``,c=typeof t.terminalLabel==`string`?t.terminalLabel.trim():``;if(s.length===0||c.length===0)return null;let l=Math.max(1,Math.floor(a));return{id:n,threadId:r,createdAt:i,terminalId:s,terminalLabel:c,lineStart:l,lineEnd:Math.max(l,Math.floor(o))}}function Bv(e,t){return e===`local`||e===`worktree`?e:t?`worktree`:`local`}function Vv(e){return Fn(e)}function Hv(e){return e.trim()}function Uv(e){return typeof e==`string`?e.trim():Ln(e)}function Wv(e,t){let n=hn(e);return n?Uv(n):t?.environmentId?Uv(C(t.environmentId,e)):e}function Gv(e){return hn(e)}function Kv(e,t){if(typeof t==`string`){let e=t.trim();return e.length>0?ba.make(e):null}return t}function F(e,t){let n=Kv(e,t);if(!n)return null;if(typeof n!=`string`){let t=Uv(n);if(e.draftsByThreadKey[t])return t;for(let[t,r]of Object.entries(e.draftThreadsByThreadKey))if(r.environmentId===n.environmentId&&r.threadId===n.threadId)return t;return t}let r=Uv(n);return r.length>0?r:null}function qv(e,t){let n=Kv(e,t);return n?typeof n==`string`?e.draftThreadsByThreadKey[n]?.threadId??zr.make(n):n.threadId:null}function Jv(e,t){let n=F(e,t);return n?e.draftsByThreadKey[n]??null:null}function Yv(e,t){return Object.values(e).includes(t)}function Xv(e,t){return{draftId:e,...t}}function Zv(e,t,n,r,i){let a=r!==void 0&&(r.environmentId!==e.environmentId||r.projectId!==e.projectId),o=i?.worktreePath===void 0?a?null:r?.worktreePath??null:i.worktreePath??null,s=i?.branch===void 0?a?null:r?.branch??null:i.branch??null,c=i?.anchorKind===void 0?r?.anchorKind:i.anchorKind??void 0;return{threadId:t,environmentId:e.environmentId,projectId:e.projectId,logicalProjectKey:n,createdAt:i?.createdAt??r?.createdAt??new Date().toISOString(),runtimeMode:i?.runtimeMode??r?.runtimeMode??`full-access`,interactionMode:i?.interactionMode??r?.interactionMode??`default`,branch:s,worktreePath:o,envMode:i?.envMode??(o?`worktree`:a?`local`:r?.envMode??`local`),promotedTo:null,cmmdTaskId:i?.cmmdTaskId===void 0?r?.cmmdTaskId??null:i.cmmdTaskId,anchorCmmdId:i?.anchorCmmdId===void 0?r?.anchorCmmdId??null:i.anchorCmmdId,linkedPullRequest:i?.linkedPullRequest===void 0?r?.linkedPullRequest??null:i.linkedPullRequest,...c===void 0?{}:{anchorKind:c}}}function Qv(e,t){return!e||!t?e===t:e.environmentId===t.environmentId&&e.threadId===t.threadId}function $v(e){return e?.promotedTo!==null&&e?.promotedTo!==void 0}function ey(e,t){return!!e&&e.threadId===t.threadId&&e.environmentId===t.environmentId&&e.projectId===t.projectId&&e.logicalProjectKey===t.logicalProjectKey&&e.createdAt===t.createdAt&&e.runtimeMode===t.runtimeMode&&e.interactionMode===t.interactionMode&&e.branch===t.branch&&e.worktreePath===t.worktreePath&&e.envMode===t.envMode&&(e.anchorKind??void 0)===(t.anchorKind??void 0)&&(e.anchorCmmdId??null)===(t.anchorCmmdId??null)&&ty(e.linkedPullRequest,t.linkedPullRequest)&&Qv(e.promotedTo,t.promotedTo)}function ty(e,t){return(e?.projectId??null)===(t?.projectId??null)&&(e?.projectRepositoryId??null)===(t?.projectRepositoryId??null)&&(e?.provider??null)===(t?.provider??null)&&(e?.host??null)===(t?.host??null)&&(e?.repository??null)===(t?.repository??null)&&(e?.number??null)===(t?.number??null)&&(e?.url??null)===(t?.url??null)}function ny(e,t){let n=Object.fromEntries(Object.entries(e.logicalProjectDraftThreadKeyByLogicalProjectKey).filter(([,e])=>e!==t)),{[t]:r,...i}=e.draftThreadsByThreadKey,{[t]:a,...o}=e.draftsByThreadKey;return{draftsByThreadKey:o,draftThreadsByThreadKey:i,logicalProjectDraftThreadKeyByLogicalProjectKey:n}}function ry(e,t){let n={},r=new Map;if(t&&typeof t==`object`)for(let[e,n]of Object.entries(t)){if(typeof n!=`string`||n.length===0)continue;let t=br(e);if(!t)continue;let i=hn(n);if(i){r.set(i.threadId,i.environmentId);continue}r.set(n,t.environmentId)}if(e&&typeof e==`object`)for(let[t,i]of Object.entries(e)){if(typeof t!=`string`||t.length===0||!i||typeof i!=`object`)continue;let e=i,a=hn(t),o=Wv(t),s=a?.threadId??(typeof e.threadId==`string`&&e.threadId.length>0?e.threadId:t),c=a?.environmentId??(typeof e.environmentId==`string`&&e.environmentId.length>0?e.environmentId:r.get(t)),l=e.projectId,u=e.createdAt,d=e.branch,f=e.worktreePath,p=typeof f==`string`?f:null,m=e.promotedTo,h=m&&typeof m==`object`?m:null,g=h&&typeof h.environmentId==`string`&&h.environmentId.length>0&&typeof h.threadId==`string`&&h.threadId.length>0?C(h.environmentId,h.threadId):null;if(typeof l!=`string`||l.length===0||c===void 0)continue;let _=c;n[o]={threadId:s,environmentId:_,projectId:l,logicalProjectKey:typeof e.logicalProjectKey==`string`&&e.logicalProjectKey.length>0?e.logicalProjectKey:a?Vv(In(_,l)):t,createdAt:typeof u==`string`&&u.length>0?u:new Date().toISOString(),runtimeMode:vv(e.runtimeMode)?e.runtimeMode:sp,interactionMode:e.interactionMode===`plan`||e.interactionMode==="default"?e.interactionMode:cp,branch:typeof d==`string`?d:null,worktreePath:p,envMode:Bv(e.envMode,p),promotedTo:g}}let i={};if(t&&typeof t==`object`)for(let[e,a]of Object.entries(t)){if(typeof a!=`string`||a.length===0)continue;let t=br(e),o=hn(a),s=Wv(a);if(i[e]=s,o&&r.set(o.threadId,o.environmentId),!t){let t=n[s];t&&!t.logicalProjectKey&&(n[s]={...t,logicalProjectKey:e});continue}n[s]?(n[s]?.projectId!==t.projectId||n[s]?.environmentId!==t.environmentId)&&(n[s]={...n[s],threadId:n[s].threadId,environmentId:t.environmentId,projectId:t.projectId,logicalProjectKey:e}):n[s]={threadId:o?.threadId??s,environmentId:t.environmentId,projectId:t.projectId,logicalProjectKey:e,createdAt:new Date().toISOString(),runtimeMode:sp,interactionMode:cp,branch:null,worktreePath:null,envMode:`local`,promotedTo:null}}return{draftThreadsByThreadKey:n,logicalProjectDraftThreadKeyByLogicalProjectKey:i}}function iy(e,t){if(!e||typeof e!=`object`)return{};let n=new Map;for(let[e,r]of Object.entries(t)){let t=Gv(e);t&&n.set(t.threadId,r.environmentId)}let r={};for(let[i,a]of Object.entries(e)){if(typeof i!=`string`||i.length===0||!a||typeof a!=`object`)continue;let e=a,o=typeof e.prompt==`string`?e.prompt:``,s=typeof e.lastGeneratedPullRequestPrompt==`string`?e.lastGeneratedPullRequestPrompt:void 0,c=Array.isArray(e.attachments)?e.attachments.flatMap(e=>{let t=q_(e);return t?[t]:[]}):[],l=Array.isArray(e.files)?e.files.flatMap(e=>{let t=J_(e);return t?[t]:[]}):[],u=Array.isArray(e.terminalContexts)?e.terminalContexts.flatMap(e=>{let t=zv(e);return t?[t]:[]}):[],d=Array.isArray(e.stashTerminalContexts)?e.stashTerminalContexts.flatMap(e=>{let t=zv(e),n=typeof e.text==`string`?e.text:``;return t&&n.length>0?[{...t,text:n}]:[]}):[],f=vv(e.runtimeMode)?e.runtimeMode:null,p=e.interactionMode===`plan`||e.interactionMode==="default"?e.interactionMode:null,m=j_(e.stagedSubmission,{attachment:q_,file:J_,terminalContext:zv,modelSelection:e=>uv(e)??null,runtimeMode:vv}),h=Gm(o,u.length),g=a,_={},v=null;if(e.modelSelectionByProvider&&typeof e.modelSelectionByProvider==`object`)_=e.modelSelectionByProvider,v=ov(e.activeProvider);else{let e=lv(g.modelOptions,void 0,g)??null,t=uv(g.modelSelection,{provider:g.provider,model:g.model,modelOptions:e??g.modelOptions,legacyCodex:g}),n=fv(t,e),r=dv(t,n);_=mv(r,n),v=r?.provider??null}let y=Object.keys(_).length>0||v!==null;if(o.length===0&&c.length===0&&l.length===0&&u.length===0&&d.length===0&&!y&&!f&&!p&&!m)continue;let b=hn(i)===null?t[i]===void 0?(()=>{let e=n.get(i);return e?Wv(i,{environmentId:e}):i})():i:Wv(i);r[b]={prompt:h,...s===void 0?{}:{lastGeneratedPullRequestPrompt:s},attachments:c,...l.length>0?{files:l}:{},...u.length>0?{terminalContexts:u}:{},...d.length>0?{stashTerminalContexts:d}:{},...y?{modelSelectionByProvider:_,activeProvider:v}:{},...f?{runtimeMode:f}:{},...p?{interactionMode:p}:{},...m?{stagedSubmission:m}:{}}}return r}function ay(e){if(!e||typeof e!=`object`)return Av;let t=e,n=t.draftsByThreadKey??t.draftsByThreadId,r=t.draftThreadsByThreadKey??t.draftThreadsByThreadId,i=t.logicalProjectDraftThreadKeyByLogicalProjectKey??t.projectDraftThreadKeyByProjectKey??t.projectDraftThreadIdByProjectKey??t.projectDraftThreadIdByProjectId,a=lv(t.stickyModelOptions)??{},o=uv(t.stickyModelSelection,{provider:t.stickyProvider??`codex`,model:t.stickyModel,modelOptions:a}),s=fv(o,a),c=mv(dv(o,s),s),l=ov(t.stickyProvider)??null,{draftThreadsByThreadKey:u,logicalProjectDraftThreadKeyByLogicalProjectKey:d}=ry(r,i);return{draftsByThreadKey:iy(n,u),draftThreadsByThreadKey:u,logicalProjectDraftThreadKeyByLogicalProjectKey:d,stickyModelSelectionByProvider:c,stickyActiveProvider:l}}function oy(e){let t={};for(let[n,r]of Object.entries(e.draftsByThreadKey)){if(typeof n!=`string`||n.length===0)continue;let e=Object.keys(r.modelSelectionByProvider).length>0||r.activeProvider!==null;r.prompt.length===0&&r.lastGeneratedPullRequestPrompt===void 0&&r.persistedAttachments.length===0&&(r.files?.length??0)===0&&r.terminalContexts.length===0&&!e&&r.runtimeMode===null&&r.interactionMode===null&&r.stagedSubmission==null||(t[n]={prompt:r.prompt,...r.lastGeneratedPullRequestPrompt===void 0?{}:{lastGeneratedPullRequestPrompt:r.lastGeneratedPullRequestPrompt},attachments:r.persistedAttachments,...(r.files?.length??0)>0?{files:r.files.map(({file:e,type:t,...n})=>n)}:{},...r.terminalContexts.length>0?{terminalContexts:r.terminalContexts.map(e=>({id:e.id,threadId:e.threadId,createdAt:e.createdAt,terminalId:e.terminalId,terminalLabel:e.terminalLabel,lineStart:e.lineStart,lineEnd:e.lineEnd}))}:{},...r.stashTerminalContexts&&r.stashTerminalContexts.length>0?{stashTerminalContexts:r.stashTerminalContexts.map(e=>({id:e.id,threadId:e.threadId,createdAt:e.createdAt,terminalId:e.terminalId,terminalLabel:e.terminalLabel,lineStart:e.lineStart,lineEnd:e.lineEnd,text:e.text}))}:{},...e?{modelSelectionByProvider:r.modelSelectionByProvider,activeProvider:r.activeProvider}:{},...r.runtimeMode?{runtimeMode:r.runtimeMode}:{},...r.interactionMode?{interactionMode:r.interactionMode}:{},...r.stagedSubmission?{stagedSubmission:N_(r.stagedSubmission)}:{}})}return{draftsByThreadKey:t,draftThreadsByThreadKey:e.draftThreadsByThreadKey,logicalProjectDraftThreadKeyByLogicalProjectKey:e.logicalProjectDraftThreadKeyByLogicalProjectKey,stickyModelSelectionByProvider:e.stickyModelSelectionByProvider,stickyActiveProvider:e.stickyActiveProvider}}function sy(e){if(!e||typeof e!=`object`)return Av;let t=e,{draftThreadsByThreadKey:n,logicalProjectDraftThreadKeyByLogicalProjectKey:r}=ry(t.draftThreadsByThreadKey??t.draftThreadsByThreadId,t.logicalProjectDraftThreadKeyByLogicalProjectKey??t.projectDraftThreadKeyByProjectKey??t.projectDraftThreadIdByProjectKey??t.projectDraftThreadIdByProjectId),i={},a=null;if(t.stickyModelSelectionByProvider&&typeof t.stickyModelSelectionByProvider==`object`)i=t.stickyModelSelectionByProvider,a=ov(t.stickyActiveProvider);else{let e=lv(t.stickyModelOptions)??{},n=uv(t.stickyModelSelection,{provider:t.stickyProvider,model:t.stickyModel,modelOptions:e}),r=fv(n,e);i=mv(dv(n,r),r),a=ov(t.stickyProvider)}return{draftsByThreadKey:iy(t.draftsByThreadKey??t.draftsByThreadId,n),draftThreadsByThreadKey:n,logicalProjectDraftThreadKeyByLogicalProjectKey:r,stickyModelSelectionByProvider:i,stickyActiveProvider:a}}function cy(e){if(e.length===0)return[];try{let t=jn(hv,Tv);return!t||t.version!==gv?[]:(t.state.draftsByThreadKey[e]?.attachments??[]).map(e=>e.id)}catch{return[]}}function ly(e){if(e.length===0)return null;try{let t=xv.getItem(hv);if(typeof t!=`string`)return null;let n=Ev(JSON.parse(t));return!n||n.version!==gv?null:n.state.draftsByThreadKey[e]??null}catch{return null}}function uy(e,t,n){let r=new Set;try{xv.flush(),r=new Set(cy(e))}catch{r=new Set}n(n=>{let i=n.draftsByThreadKey[e];if(!i)return n;let a=new Set(i.images.map(e=>e.id)),o=t.filter(e=>a.has(e.id)&&r.has(e.id)),s=i.images.map(e=>e.id).filter(e=>!r.has(e)),c={...i,persistedAttachments:o,nonPersistedImageIds:s},l={...n.draftsByThreadKey};return N(c)?delete l[e]:l[e]=c,{draftsByThreadKey:l}})}function dy(e,t){return e.length>0?e:t?.prompt??``}function fy(e,t){return e?.length?e:t??[]}function py(e){let t=e.stagedSubmission;return{prompt:dy(e.prompt,t),attachments:fy(e.attachments,t?.attachments),files:fy(e.files,t?.files),terminalContexts:fy(e.terminalContexts,t?.terminalContexts)}}function my(e){let t=e.modelSelectionByProvider??{},n=ov(e.activeProvider)??null,r=py(e);return{prompt:r.prompt,...e.lastGeneratedPullRequestPrompt===void 0?{}:{lastGeneratedPullRequestPrompt:e.lastGeneratedPullRequestPrompt},images:tv(r.attachments),files:r.files.map(e=>({...e,type:`file`,file:null})),nonPersistedImageIds:[],persistedAttachments:[...r.attachments],terminalContexts:r.terminalContexts.map(t=>{let n=e.stashTerminalContexts?.find(e=>e.id===t.id);return Object.assign({},t,{text:n?.text??``})}),...e.stashTerminalContexts&&e.stashTerminalContexts.length>0?{stashTerminalContexts:e.stashTerminalContexts.map(e=>({...e}))}:{},modelSelectionByProvider:t,activeProvider:n,runtimeMode:e.runtimeMode??null,interactionMode:e.interactionMode??null,stagedSubmission:P_(e.stagedSubmission)}}function hy(e){return{threadId:e.threadId,environmentId:e.environmentId,projectId:e.projectId,logicalProjectKey:e.logicalProjectKey??Vv(In(e.environmentId,e.projectId)),createdAt:e.createdAt,runtimeMode:e.runtimeMode,interactionMode:e.interactionMode,branch:e.branch,worktreePath:e.worktreePath,envMode:e.envMode,promotedTo:e.promotedTo?C(e.promotedTo.environmentId,e.promotedTo.threadId):null,linkedPullRequest:e.linkedPullRequest??null}}var gy=wa()(Gf((e,t)=>{let n=e;return{draftsByThreadKey:{},draftThreadsByThreadKey:{},logicalProjectDraftThreadKeyByLogicalProjectKey:{},stickyModelSelectionByProvider:{},stickyActiveProvider:null,getComposerDraft:e=>Jv(t(),e),getDraftThreadByLogicalProjectKey:e=>t().getDraftSessionByLogicalProjectKey(e),getDraftSessionByLogicalProjectKey:e=>{let n=Hv(e);if(n.length===0)return null;let r=t().logicalProjectDraftThreadKeyByLogicalProjectKey[n];if(!r)return null;let i=t().draftThreadsByThreadKey[r];return!i||$v(i)?null:Xv(ba.make(r),i)},getDraftThreadByProjectRef:e=>t().getDraftSessionByProjectRef(e),getDraftSessionByProjectRef:e=>{for(let[n,r]of Object.entries(t().draftThreadsByThreadKey))if(!$v(r)&&r.projectId===e.projectId&&r.environmentId===e.environmentId)return Xv(ba.make(n),r);return null},getDraftSession:e=>t().draftThreadsByThreadKey[e]??null,getDraftSessionByRef:e=>{for(let n of Object.values(t().draftThreadsByThreadKey))if(n.environmentId===e.environmentId&&n.threadId===e.threadId)return n;return null},getDraftThread:e=>typeof e==`string`?t().getDraftSession(ba.make(e)):t().getDraftSessionByRef(e),getDraftThreadByRef:e=>t().getDraftSessionByRef(e),listDraftThreadKeys:()=>Object.values(t().draftThreadsByThreadKey).map(e=>Ln(C(e.environmentId,e.threadId))),hasDraftThreadsInEnvironment:e=>Object.values(t().draftThreadsByThreadKey).some(t=>t.environmentId===e),setLogicalProjectDraftThreadId:(e,t,r,i)=>{let a=Hv(e);a.length!==0&&r.length!==0&&n(e=>{let n=e.draftThreadsByThreadKey[r],o=e.logicalProjectDraftThreadKeyByLogicalProjectKey[a],s=Zv(t,i?.threadId??n?.threadId??zr.make(r),a,n,i);if(o===r&&ey(n,s))return e;let c={...e.logicalProjectDraftThreadKeyByLogicalProjectKey,[a]:r},l={...e.draftThreadsByThreadKey,[r]:s},u=e.draftsByThreadKey,d=o===void 0?void 0:l[o];return o&&o!==r&&!Yv(c,o)&&!$v(d)&&(delete l[o],e.draftsByThreadKey[o]!==void 0&&(u={...e.draftsByThreadKey},delete u[o])),{draftsByThreadKey:u,draftThreadsByThreadKey:l,logicalProjectDraftThreadKeyByLogicalProjectKey:c}})},setProjectDraftThreadId:(e,n,r)=>{t().setLogicalProjectDraftThreadId(Vv(e),e,n,r)},setDraftThreadContext:(e,r)=>{let i=F(t(),e)??``;i.length!==0&&n(e=>{let t=e.draftThreadsByThreadKey[i];if(!t)return e;let n=r.projectRef??{environmentId:t.environmentId,projectId:t.projectId};if(n.projectId.length===0||n.environmentId.length===0)return e;let a=n.environmentId!==t.environmentId||n.projectId!==t.projectId,o=r.worktreePath===void 0?a?null:t.worktreePath:r.worktreePath??null,s=r.branch===void 0?a?null:t.branch:r.branch??null,c=r.anchorKind===void 0?t.anchorKind:r.anchorKind??void 0,l={threadId:t.threadId,environmentId:n.environmentId,projectId:n.projectId,logicalProjectKey:t.logicalProjectKey,createdAt:r.createdAt===void 0?t.createdAt:r.createdAt||t.createdAt,runtimeMode:r.runtimeMode??t.runtimeMode,interactionMode:r.interactionMode??t.interactionMode,branch:s,worktreePath:o,envMode:r.envMode??(o?`worktree`:a?`local`:t.envMode??`local`),promotedTo:t.promotedTo??null,cmmdTaskId:r.cmmdTaskId===void 0?t.cmmdTaskId??null:r.cmmdTaskId,anchorCmmdId:r.anchorCmmdId===void 0?t.anchorCmmdId??null:r.anchorCmmdId,linkedPullRequest:r.linkedPullRequest===void 0?t.linkedPullRequest??null:r.linkedPullRequest,...c===void 0?{}:{anchorKind:c}};return l.environmentId===t.environmentId&&l.projectId===t.projectId&&l.logicalProjectKey===t.logicalProjectKey&&l.createdAt===t.createdAt&&l.runtimeMode===t.runtimeMode&&l.interactionMode===t.interactionMode&&l.branch===t.branch&&l.worktreePath===t.worktreePath&&l.envMode===t.envMode&&(l.anchorKind??void 0)===(t.anchorKind??void 0)&&(l.anchorCmmdId??null)===(t.anchorCmmdId??null)&&ty(l.linkedPullRequest,t.linkedPullRequest)&&Qv(l.promotedTo,t.promotedTo)?e:{draftThreadsByThreadKey:{...e.draftThreadsByThreadKey,[i]:l}}})},clearProjectDraftThreadId:e=>{n(t=>{let n=Object.entries(t.draftThreadsByThreadKey).find(([,t])=>t.projectId===e.projectId&&t.environmentId===e.environmentId);return n?ny(t,n[0]):t})},clearProjectDraftThreadById:(e,r)=>{let i=F(t(),r)??``;i.length!==0&&n(t=>{let n=t.draftThreadsByThreadKey[i];return!n||n.projectId!==e.projectId||n.environmentId!==e.environmentId?t:ny(t,i)})},markDraftThreadPromoting:(e,r)=>{let i=F(t(),e);i&&n(e=>{let t=e.draftThreadsByThreadKey[i];if(!t)return e;let n=r??C(t.environmentId,t.threadId);return Qv(t.promotedTo,n)?e:{draftThreadsByThreadKey:{...e.draftThreadsByThreadKey,[i]:{...t,promotedTo:n}}}})},finalizePromotedDraftThread:e=>{let r=F(t(),e)??``;r.length!==0&&n(e=>{let t=e.draftThreadsByThreadKey[r];if(!$v(t))return e;let n=Uv(t.promotedTo),i=e.draftsByThreadKey[n],a=e.draftsByThreadKey[r];return ny(a?{...e,draftsByThreadKey:{...e.draftsByThreadKey,[n]:i?{...i,modelSelectionByProvider:{...i.modelSelectionByProvider,...a.modelSelectionByProvider},activeProvider:a.activeProvider,runtimeMode:a.runtimeMode,interactionMode:a.interactionMode}:a}}:e,r)})},clearDraftThread:e=>{let r=F(t(),e)??``;if(r.length===0)return;let i=t().draftsByThreadKey[r];if(i)for(let e of i.images)K_(e.previewUrl);n(e=>{let t=e.draftThreadsByThreadKey[r]!==void 0,n=Object.values(e.logicalProjectDraftThreadKeyByLogicalProjectKey).includes(r),i=e.draftsByThreadKey[r]!==void 0;return!t&&!n&&!i?e:ny(e,r)})},setStickyModelSelection:e=>{let t=uv(e);n(e=>{if(!t)return e;let n={...e.stickyModelSelectionByProvider,[t.provider]:t};return rt(e.stickyModelSelectionByProvider,n)?e.stickyActiveProvider===t.provider?e:{stickyActiveProvider:t.provider}:{stickyModelSelectionByProvider:n,stickyActiveProvider:t.provider}})},applyStickyState:e=>{let r=F(t(),e)??``;r.length!==0&&n(e=>{let t=e.stickyModelSelectionByProvider,n=e.stickyActiveProvider;if(Object.keys(t).length===0&&n===null)return e;let i=e.draftsByThreadKey[r]??P(),a={...i.modelSelectionByProvider};for(let[e,n]of Object.entries(t))if(n){let t=a[e];a[e]={...n,model:t?.model??n.model}}if(rt(i.modelSelectionByProvider,a)&&i.activeProvider===n)return e;let o={...i,modelSelectionByProvider:a,activeProvider:n},s={...e.draftsByThreadKey};return N(o)?delete s[r]:s[r]=o,{draftsByThreadKey:s}})},setPrompt:(e,r)=>{let i=F(t(),e)??``;i.length!==0&&n(e=>{let t=e.draftsByThreadKey[i]??P();if(t.prompt===r)return e;let n={...t,prompt:r},a={...e.draftsByThreadKey};return N(n)?delete a[i]:a[i]=n,{draftsByThreadKey:a}})},setGeneratedPullRequestPrompt:(e,r)=>{let i=F(t(),e)??``;i.length!==0&&n(e=>{let t=e.draftsByThreadKey[i]??P();return{draftsByThreadKey:{...e.draftsByThreadKey,[i]:{...t,lastGeneratedPullRequestPrompt:r}}}})},setPendingAutoSubmit:(e,r)=>{let i=F(t(),e)??``;i.length!==0&&n(e=>{let t=e.draftsByThreadKey[i]??P();if((t.pendingAutoSubmit??!1)===r)return e;let n=r?{...t,pendingAutoSubmit:!0}:(()=>{let{pendingAutoSubmit:e,...n}=t;return n})(),a={...e.draftsByThreadKey};return N(n)?delete a[i]:a[i]=n,{draftsByThreadKey:a}})},stageComposerSubmission:(e,r,i,a,o,s,c)=>{let l=F(t(),e)??``;l.length!==0&&(n(e=>{let t=e.draftsByThreadKey[l];if(!t)return e;let n={prompt:t.prompt,attachments:[...c??t.persistedAttachments],files:(t.files??[]).map(({file:e,type:t,...n})=>n),terminalContexts:[...t.terminalContexts],startedAt:r,commandId:i,messageId:a,...o?{executionIntent:o}:{},...s},u={...e.draftsByThreadKey};return u[l]={...t,stagedSubmission:n},{draftsByThreadKey:u}}),xv.flush())},setStagedComposerExecutionIntent:(e,r)=>{let i=F(t(),e)??``;i.length!==0&&(n(e=>{let t=e.draftsByThreadKey[i];return t?.stagedSubmission?{draftsByThreadKey:{...e.draftsByThreadKey,[i]:{...t,stagedSubmission:{...t.stagedSubmission,executionIntent:r}}}}:e}),xv.flush())},clearStagedComposerSubmission:e=>{let r=F(t(),e)??``;r.length!==0&&n(e=>{let t=e.draftsByThreadKey[r];if(!t?.stagedSubmission)return e;let n={...t,stagedSubmission:null},i={...e.draftsByThreadKey};return N(n)?delete i[r]:i[r]=n,{draftsByThreadKey:i}})},setTerminalContexts:(e,r,i)=>{let a=F(t(),e),o=qv(t(),e);if(!a||!o)return;let s=B_(o,r);n(e=>{let t=e.draftsByThreadKey[a]??P(),n={...t,prompt:Gm(t.prompt,s.length),terminalContexts:s,...i?.preserveTextForReload?{stashTerminalContexts:s}:{stashTerminalContexts:[]}},r={...e.draftsByThreadKey};return N(n)?delete r[a]:r[a]=n,{draftsByThreadKey:r}})},setModelSelection:(e,r)=>{let i=F(t(),e)??``;if(i.length===0)return;let a=uv(r);n(e=>{let t=e.draftsByThreadKey[i];if(!t&&a===null)return e;let n=t??P(),r={...n.modelSelectionByProvider};if(a){let e=r[a.provider];a.options===void 0?r[a.provider]={provider:a.provider,model:a.model,...`providerAccountId`in a&&a.providerAccountId?{providerAccountId:a.providerAccountId}:e&&`providerAccountId`in e&&e.providerAccountId?{providerAccountId:e.providerAccountId}:{},...e?.options?{options:e.options}:{}}:r[a.provider]=a}let o=a?.provider??n.activeProvider;if(rt(n.modelSelectionByProvider,r)&&n.activeProvider===o)return e;let s={...n,modelSelectionByProvider:r,activeProvider:o},c={...e.draftsByThreadKey};return N(s)?delete c[i]:c[i]=s,{draftsByThreadKey:c}})},setModelOptions:(e,r)=>{let i=F(t(),e)??``;if(i.length===0)return;let a=lv(r);n(e=>{let t=e.draftsByThreadKey[i];if(!t&&a===null)return e;let n=t??P(),r={...n.modelSelectionByProvider};for(let e of[`codex`,`claudeAgent`]){if(!a||!(e in a))continue;let t=a[e],n=r[e];if(t)r[e]={provider:e,model:n?.model??Fi[e],...n&&`providerAccountId`in n&&n.providerAccountId?{providerAccountId:n.providerAccountId}:{},options:t};else if(n?.options){let{options:t,...i}=n;r[e]=i}}if(rt(n.modelSelectionByProvider,r))return e;let o={...n,modelSelectionByProvider:r},s={...e.draftsByThreadKey};return N(o)?delete s[i]:s[i]=o,{draftsByThreadKey:s}})},setProviderModelOptions:(e,r,i,a)=>{let o=F(t(),e)??``;if(o.length===0)return;let s=ov(r);if(s===null)return;let c=lv({[s]:i},s)?.[s];n(e=>{let t=e.draftsByThreadKey[o]??P(),n={...t.modelSelectionByProvider},r=n[s];if(c)n[s]={provider:s,model:r?.model??Fi[s],...r&&`providerAccountId`in r&&r.providerAccountId?{providerAccountId:r.providerAccountId}:{},options:c};else if(r?.options){let{options:e,...t}=r;n[s]=t}let i=e.stickyModelSelectionByProvider,l=e.stickyActiveProvider;if(a?.persistSticky===!0){i={...e.stickyModelSelectionByProvider};let n=i[s]??t.modelSelectionByProvider[s]??{provider:s,model:Fi[s]};if(c)i[s]={...n,provider:s,options:c};else if(n.options){let{options:e,...t}=n;i[s]=t}l=t.activeProvider??s}if(rt(t.modelSelectionByProvider,n)&&rt(e.stickyModelSelectionByProvider,i)&&e.stickyActiveProvider===l)return e;let u={...t,modelSelectionByProvider:n},d={...e.draftsByThreadKey};return N(u)?delete d[o]:d[o]=u,{draftsByThreadKey:d,...a?.persistSticky===!0?{stickyModelSelectionByProvider:i,stickyActiveProvider:l}:{}}})},setRuntimeMode:(e,r)=>{let i=F(t(),e)??``;if(i.length===0)return;let a=vv(r)?r:null;n(e=>{let t=e.draftsByThreadKey[i];if(!t&&a===null)return e;let n=t??P();if(n.runtimeMode===a)return e;let r={...n,runtimeMode:a},o={...e.draftsByThreadKey};return N(r)?delete o[i]:o[i]=r,{draftsByThreadKey:o}})},setInteractionMode:(e,r)=>{let i=F(t(),e)??``;if(i.length===0)return;let a=r===`plan`||r==="default"?r:null;n(e=>{let t=e.draftsByThreadKey[i];if(!t&&a===null)return e;let n=t??P();if(n.interactionMode===a)return e;let r={...n,interactionMode:a},o={...e.draftsByThreadKey};return N(r)?delete o[i]:o[i]=r,{draftsByThreadKey:o}})},addImage:(e,n)=>{let r=F(t(),e),i=qv(t(),e);!r||!i||t().addImages(typeof e==`string`?ba.make(r):e,[n])},addImages:(e,r)=>{let i=F(t(),e)??``;i.length!==0&&r.length!==0&&n(e=>{let t=e.draftsByThreadKey[i]??P(),n=new Set(t.images.map(e=>e.id)),a=new Set(t.images.map(e=>L_(e))),o=new Set(t.images.map(e=>e.previewUrl)),s=[];for(let e of r){let t=L_(e);if(n.has(e.id)||a.has(t)){o.has(e.previewUrl)||K_(e.previewUrl);continue}s.push(e),n.add(e.id),a.add(t),o.add(e.previewUrl)}return s.length===0?e:{draftsByThreadKey:{...e.draftsByThreadKey,[i]:{...t,images:[...t.images,...s]}}}})},addFiles:(e,r)=>{let i=F(t(),e)??``;i.length!==0&&r.length!==0&&n(e=>{let t=e.draftsByThreadKey[i]??P(),n=new Set((t.files??[]).map(e=>e.id)),a=Math.max(0,8-t.images.length-(t.files?.length??0)),o=r.filter(e=>!n.has(e.id)).slice(0,a);return o.length===0?e:{draftsByThreadKey:{...e.draftsByThreadKey,[i]:{...t,files:[...t.files??[],...o]}}}})},setFiles:(e,r)=>{let i=F(t(),e)??``;i.length!==0&&n(e=>{let t=e.draftsByThreadKey[i]??P();return{draftsByThreadKey:{...e.draftsByThreadKey,[i]:{...t,files:[...r]}}}})},removeImage:(e,r)=>{let i=F(t(),e)??``;if(i.length===0)return;let a=t().draftsByThreadKey[i];if(!a)return;let o=a.images.find(e=>e.id===r);o&&K_(o.previewUrl),n(e=>{let t=e.draftsByThreadKey[i];if(!t)return e;let n={...t,images:t.images.filter(e=>e.id!==r),nonPersistedImageIds:t.nonPersistedImageIds.filter(e=>e!==r),persistedAttachments:t.persistedAttachments.filter(e=>e.id!==r)},a={...e.draftsByThreadKey};return N(n)?delete a[i]:a[i]=n,{draftsByThreadKey:a}})},insertTerminalContext:(e,r,i,a)=>{let o=F(t(),e),s=qv(t(),e);if(!o||!s)return!1;let c=!1;return n(e=>{let t=e.draftsByThreadKey[o]??P(),n=z_(s,i);if(!n)return e;let l=R_(n);if(t.terminalContexts.some(e=>e.id===n.id)||t.terminalContexts.some(e=>R_(e)===l))return e;c=!0;let u=Math.max(0,Math.min(t.terminalContexts.length,a)),d={...t,prompt:r,terminalContexts:[...t.terminalContexts.slice(0,u),n,...t.terminalContexts.slice(u)]};return{draftsByThreadKey:{...e.draftsByThreadKey,[o]:d}}}),c},addTerminalContext:(e,n)=>{let r=F(t(),e),i=qv(t(),e);!r||!i||t().addTerminalContexts(typeof e==`string`?ba.make(r):e,[n])},addTerminalContexts:(e,r)=>{let i=F(t(),e),a=qv(t(),e);!i||!a||r.length===0||n(e=>{let t=e.draftsByThreadKey[i]??P(),n=B_(a,[...t.terminalContexts,...r]).slice(t.terminalContexts.length);return n.length===0?e:{draftsByThreadKey:{...e.draftsByThreadKey,[i]:{...t,prompt:Gm(t.prompt,t.terminalContexts.length+n.length),terminalContexts:[...t.terminalContexts,...n]}}}})},removeTerminalContext:(e,r)=>{let i=F(t(),e)??``;i.length!==0&&r.length!==0&&n(e=>{let t=e.draftsByThreadKey[i];if(!t)return e;let n={...t,terminalContexts:t.terminalContexts.filter(e=>e.id!==r)},a={...e.draftsByThreadKey};return N(n)?delete a[i]:a[i]=n,{draftsByThreadKey:a}})},clearTerminalContexts:e=>{let r=F(t(),e)??``;r.length!==0&&n(e=>{let t=e.draftsByThreadKey[r];if(!t||t.terminalContexts.length===0)return e;let n={...t,terminalContexts:[]},i={...e.draftsByThreadKey};return N(n)?delete i[r]:i[r]=n,{draftsByThreadKey:i}})},clearPersistedAttachments:e=>{let r=F(t(),e)??``;r.length!==0&&n(e=>{let t=e.draftsByThreadKey[r];if(!t)return e;let n={...t,persistedAttachments:[],nonPersistedImageIds:[]},i={...e.draftsByThreadKey};return N(n)?delete i[r]:i[r]=n,{draftsByThreadKey:i}})},syncPersistedAttachments:(e,r)=>{let i=F(t(),e);if(!i)return;let a=new Set(r.map(e=>e.id));n(e=>{let t=e.draftsByThreadKey[i];if(!t)return e;let n={...t,persistedAttachments:r,nonPersistedImageIds:t.nonPersistedImageIds.filter(e=>!a.has(e))},o={...e.draftsByThreadKey};return N(n)?delete o[i]:o[i]=n,{draftsByThreadKey:o}}),Promise.resolve().then(()=>{uy(i,r,n)})},moveComposerDraft:(e,r)=>{let i=fm(t().draftsByThreadKey,e,r);return i!==null&&(n({draftsByThreadKey:i}),xv.flush(),!0)},clearComposerContent:e=>{let r=F(t(),e)??``;r.length!==0&&n(e=>{let t=e.draftsByThreadKey[r];if(!t)return e;let n=av(t),i={...e.draftsByThreadKey};return N(n)?delete i[r]:i[r]=n,{draftsByThreadKey:i}})},clearComposerContentIfUnchanged:(e,r)=>{let i=F(t(),e)??``;if(i.length===0)return!1;let a=!1;return n(e=>{let t=e.draftsByThreadKey[i];if(!t||!iv(t,r))return e;let n=av(t),o={...e.draftsByThreadKey};return N(n)?delete o[i]:o[i]=n,a=!0,{draftsByThreadKey:o}}),a},restoreComposerStash:(e,r)=>{let i=F(t(),e)??``,a=qv(t(),e);if(i.length===0||!a)return!1;let o,s;if(n(e=>{let t=F_(e.draftsByThreadKey,i,a,r);return t?(o=t.previousDraft,s=t.restoredDraft,{draftsByThreadKey:t.drafts}):e}),!s)return!1;let c=!1;try{xv.flush();let e=ly(i),n=t().draftsByThreadKey[i];e!==null&&n===s&&G_(e,n)&&(c=!0)}catch{}if(c&&(r.onPersisted?.()??!0))return!0;n(e=>{if(e.draftsByThreadKey[i]!==s)return e;let t={...e.draftsByThreadKey};return o?t[i]=o:delete t[i],{draftsByThreadKey:t}});try{xv.flush()}catch{}return!1}}},{name:hv,version:gv,storage:Uf(()=>xv),migrate:ay,partialize:oy,merge:(e,t)=>{let n=sy(e),r=Object.fromEntries(Object.entries(n.draftsByThreadKey).map(([e,t])=>[e,my(t)])),i=Object.fromEntries(Object.entries(n.draftThreadsByThreadKey).map(([e,t])=>[e,hy(t)]));return{...t,draftsByThreadKey:r,draftThreadsByThreadKey:i,logicalProjectDraftThreadKeyByLogicalProjectKey:n.logicalProjectDraftThreadKeyByLogicalProjectKey,stickyModelSelectionByProvider:n.stickyModelSelectionByProvider??{},stickyActiveProvider:n.stickyActiveProvider??null}}}));function _y(e){let t=(0,A.c)(2),n;return t[0]===e?n=t[1]:(n=t=>Jv(t,e)??Rv,t[0]=e,t[1]=n),gy(n)}function vy(e){let t=(0,A.c)(2),n;return t[0]===e?n=t[1]:(n=t=>{let n=Jv(t,e);return n?{activeProvider:n.activeProvider,modelSelectionByProvider:n.modelSelectionByProvider}:Lv},t[0]=e,t[1]=n),gy(th(n))}function yy(e){let t=gy.getState();for(let[n,r]of Object.entries(t.draftThreadsByThreadKey))r.environmentId===e.environmentId&&r.threadId===e.threadId&&t.markDraftThreadPromoting(ba.make(n),e)}function by(e){for(let t of e)yy(t)}function xy(e){let t=gy.getState();for(let[n,r]of Object.entries(t.draftThreadsByThreadKey))r.promotedTo&&r.promotedTo.environmentId===e.environmentId&&r.promotedTo.threadId===e.threadId&&t.finalizePromotedDraftThread(ba.make(n))}var Sy=null;function Cy(e){Sy=e}function wy(){if(Sy===null)throw Error(`Environment event handling was used before the service was configured.`);return Sy}function Ty(e){let t=new Set,n=new Map(e.snapshotThreads.map(e=>[e.key,e]));for(let n of e.snapshotThreads)n.deletedAt===null&&n.archivedAt===null&&t.add(n.key);for(let r of e.draftThreadKeys){let e=n.get(r);e&&(e.deletedAt!==null||e.archivedAt!==null)||t.add(r)}return t}function Ey(e){let t=new Map,n=!1;for(let r of e)switch(r.type){case`thread.turn-diff-completed`:case`thread.reverted`:n=!0;break;case`thread.created`:t.set(r.payload.threadId,{clearPromotedDraft:!0,clearDeletedThread:!1,removeTerminalState:!1});break;case`thread.deleted`:t.set(r.payload.threadId,{clearPromotedDraft:!1,clearDeletedThread:!0,removeTerminalState:!0});break;case`thread.archived`:t.set(r.payload.threadId,{clearPromotedDraft:!1,clearDeletedThread:!1,removeTerminalState:!0});break;case`thread.unarchived`:t.set(r.payload.threadId,{clearPromotedDraft:!1,clearDeletedThread:!1,removeTerminalState:!1})}let r=[],i=[],a=[];for(let[e,n]of t)n.clearPromotedDraft&&r.push(e),n.clearDeletedThread&&i.push(e),n.removeTerminalState&&a.push(e);return{promoteDraftThreadIds:r,clearDeletedThreadIds:i,removeTerminalStateThreadIds:a,needsProviderInvalidation:n}}var Dy={threadRef:null,open:!1,minimized:!1,dock:`floating`,position:null};function Oy(e){return{x:Math.max(12,Math.min(e.position.x,e.viewportWidth-e.width-12)),y:Math.max(12,Math.min(e.position.y,e.viewportHeight-e.height-12))}}function ky(e,t){return{...e,threadRef:t,open:!0,minimized:!1}}function Ay(e){let t=e.companion.threadRef;return!e.companion.open||t===null?!1:e.routeThreadRef?.environmentId!==t.environmentId||e.routeThreadRef.threadId!==t.threadId}function jy(e){if(!e||typeof e!=`object`)return null;let t=e;return typeof t.snoozedAt!=`string`||t.snoozedAt.length===0||typeof t.snoozedUntil!=`string`||t.snoozedUntil.length===0?null:{snoozedAt:t.snoozedAt,snoozedUntil:t.snoozedUntil}}function My(e){if(!e||typeof e!=`object`)return{};let t={};for(let[n,r]of Object.entries(e)){if(typeof n!=`string`||n.length===0)continue;let e=jy(r);e&&(t[n]=e)}return t}function Ny(e,t,n){let r=n??new Date().toISOString(),i=Date.parse(r),a=e.threadLastVisitedAtById[t],o=a?Date.parse(a):NaN;return Number.isFinite(o)&&Number.isFinite(i)&&o>=i?e:{...e,threadLastVisitedAtById:{...e.threadLastVisitedAtById,[t]:r}}}function Py(e,t,n){if(!n)return e;let r=Date.parse(n);if(Number.isNaN(r))return e;let i=new Date(r-1).toISOString();return e.threadLastVisitedAtById[t]===i?e:{...e,threadLastVisitedAtById:{...e.threadLastVisitedAtById,[t]:i}}}function Fy(e,t){let n=t in e.threadLastVisitedAtById,r=t in e.threadChangedFilesExpandedById,i=t in e.pinnedThreadById,a=t in e.threadLinkedPrById,o=t in e.pinOrderKeyById,s=t in e.activeOrderKeyById,c=t in e.threadSnoozeById;if(!n&&!r&&!i&&!a&&!o&&!s&&!c)return e;let l={...e.threadLastVisitedAtById},u={...e.threadChangedFilesExpandedById},d={...e.pinnedThreadById},f={...e.threadLinkedPrById},p={...e.pinOrderKeyById},m={...e.activeOrderKeyById},h={...e.threadSnoozeById};return delete l[t],delete u[t],delete d[t],delete f[t],delete p[t],delete m[t],delete h[t],{...e,threadLastVisitedAtById:l,threadChangedFilesExpandedById:u,pinnedThreadById:d,threadLinkedPrById:f,pinOrderKeyById:p,activeOrderKeyById:m,threadSnoozeById:h}}function Iy(e,t,n){if(e.pinnedThreadById[t]===!0===n)return e;if(n)return{...e,pinnedThreadById:{...e.pinnedThreadById,[t]:!0}};let r={...e.pinnedThreadById};return delete r[t],{...e,pinnedThreadById:r}}function Ly(e,t){return Iy(e,t,e.pinnedThreadById[t]!==!0)}function Ry(e,t,n){let r=e.pinOrderKeyById[t];if(n===null){if(r===void 0)return e;let n={...e.pinOrderKeyById};return delete n[t],{...e,pinOrderKeyById:n}}return r===n?e:{...e,pinOrderKeyById:{...e.pinOrderKeyById,[t]:n}}}function zy(e,t,n){let r=e.activeOrderKeyById[t];if(n===null){if(r===void 0)return e;let n={...e.activeOrderKeyById};return delete n[t],{...e,activeOrderKeyById:n}}return r===n?e:{...e,activeOrderKeyById:{...e.activeOrderKeyById,[t]:n}}}function By(e,t,n){if(n===null){if(!(t in e.threadSnoozeById))return e;let n={...e.threadSnoozeById};return delete n[t],{...e,threadSnoozeById:n}}let r=e.threadSnoozeById[t];return r&&r.snoozedAt===n.snoozedAt&&r.snoozedUntil===n.snoozedUntil?e:{...e,threadSnoozeById:{...e.threadSnoozeById,[t]:n}}}function Vy(e,t,n){return e.threadLinkedPrById[t]===n?e:{...e,threadLinkedPrById:{...e.threadLinkedPrById,[t]:n}}}function Hy(e,t){if(!(t in e.threadLinkedPrById))return e;let n={...e.threadLinkedPrById};return delete n[t],{...e,threadLinkedPrById:n}}function Uy(e,t,n,r){let i=e.threadChangedFilesExpandedById[t]??{};return i[n]===r?e:{...e,threadChangedFilesExpandedById:{...e.threadChangedFilesExpandedById,[t]:{...i,[n]:r}}}}var Wy=`forge:ui-state:v1`,Gy=[`t3code:ui-state:v1`,`t3code:renderer-state:v8`,`t3code:renderer-state:v7`,`t3code:renderer-state:v6`,`t3code:renderer-state:v5`,`t3code:renderer-state:v4`,`t3code:renderer-state:v3`,`codething:renderer-state:v4`,`codething:renderer-state:v3`,`codething:renderer-state:v2`,`codething:renderer-state:v1`],Ky=`months`,qy=new Set([`weeks`,`months`,`quarters`]);function Jy(e){return typeof e==`string`&&qy.has(e)?e:Ky}function Yy(e){return Number.isFinite(e)?Math.round(Math.min(560,Math.max(200,e))):360}var Xy={projectExpandedById:{},projectOrder:[],projectGroupOrder:[],lastActiveProject:null,threadLastVisitedAtById:{},threadChangedFilesExpandedById:{},pinnedThreadById:{},threadLinkedPrById:{},pinOrderKeyById:{},activeOrderKeyById:{},threadSnoozeById:{},workspaceDensityById:{},timelineWorkColumnWidth:360,timelineScale:Ky,projectLeadCompanion:Dy},Zy=new Set,Qy=[],$y=new Map,eb=!1;function tb(){if(typeof window>`u`)return Xy;try{let e=window.localStorage.getItem(Wy);if(!e){for(let e of Gy){let t=window.localStorage.getItem(e);if(t)return ub(JSON.parse(t)),Xy}return Xy}let t=JSON.parse(e);return ub(t),{...Xy,projectGroupOrder:nb(t.projectGroupOrderKeys),threadChangedFilesExpandedById:ob(t.threadChangedFilesExpandedById),pinnedThreadById:rb(t.pinnedThreadKeys),threadLinkedPrById:ib(t.threadLinkedPrById),pinOrderKeyById:ab(t.pinOrderKeyById),activeOrderKeyById:ab(t.activeOrderKeyById),threadSnoozeById:My(t.threadSnoozeById),timelineWorkColumnWidth:Yy(t.timelineWorkColumnWidth??360),timelineScale:Jy(t.timelineScale)}}catch{return Xy}}function nb(e){return Array.isArray(e)?[...new Set(e.filter(e=>typeof e==`string`&&e.length>0))]:[]}function rb(e){if(!Array.isArray(e))return{};let t={};for(let n of e)typeof n==`string`&&n.length>0&&(t[n]=!0);return t}function ib(e){if(!e||typeof e!=`object`)return{};let t={};for(let[n,r]of Object.entries(e))typeof n==`string`&&n.length!==0&&typeof r==`string`&&r.trim().length!==0&&(t[n]=r);return t}function ab(e){if(!e||typeof e!=`object`)return{};let t={};for(let[n,r]of Object.entries(e))typeof n==`string`&&n.length>0&&typeof r==`string`&&r.length>0&&(t[n]=r);return t}function ob(e){if(!e||typeof e!=`object`)return{};let t={};for(let[n,r]of Object.entries(e)){let e=sb(r);Object.keys(e).length>0&&(t[n]=e)}return t}function sb(e){let t={};if(!e||typeof e!=`object`)return t;for(let[n,r]of Object.entries(e))n&&typeof r==`boolean`&&r===!1&&(t[n]=!1);return t}function cb(e){for(let t of e)typeof t==`string`&&t.length>0&&Zy.add(t)}function lb(e){for(let t of e)typeof t==`string`&&t.length>0&&!Qy.includes(t)&&Qy.push(t)}function ub(e){Zy.clear(),Qy.length=0,cb(e.expandedProjectCwds??[]),lb(e.projectOrderCwds??[])}function db(e){if(!(typeof window>`u`))try{let t=Object.entries(e.projectExpandedById).filter(([,e])=>e).flatMap(([e])=>{let t=$y.get(e);return t?[t]:[]}),n=e.projectOrder.flatMap(e=>{let t=$y.get(e);return t?[t]:[]}),r=Object.fromEntries(Object.entries(e.threadChangedFilesExpandedById).flatMap(([e,t])=>{let n=Object.fromEntries(Object.entries(t).filter(([,e])=>e===!1));return Object.keys(n).length>0?[[e,n]]:[]}));if(window.localStorage.setItem(Wy,JSON.stringify({expandedProjectCwds:t,projectOrderCwds:n,projectGroupOrderKeys:e.projectGroupOrder,threadChangedFilesExpandedById:r,pinnedThreadKeys:Object.keys(e.pinnedThreadById).filter(t=>e.pinnedThreadById[t]),threadLinkedPrById:e.threadLinkedPrById,pinOrderKeyById:e.pinOrderKeyById,activeOrderKeyById:e.activeOrderKeyById,threadSnoozeById:e.threadSnoozeById,timelineWorkColumnWidth:e.timelineWorkColumnWidth,timelineScale:e.timelineScale})),!eb){eb=!0;for(let e of Gy)window.localStorage.removeItem(e)}}catch{}}var fb=new Aa(db,{wait:500});function pb(e,t){let n=Object.entries(e),r=Object.entries(t);if(n.length!==r.length)return!1;for(let[e,r]of n)if(t[e]!==r)return!1;return!0}function mb(e,t){return e.length===t.length&&e.every((e,n)=>e===t[n])}function hb(e,t){let n=Object.entries(e),r=Object.entries(t);if(n.length!==r.length)return!1;for(let[e,r]of n)if(!(e in t)||!pb(r,t[e]))return!1;return!0}function gb(e,t){let n=new Map($y),r=new Map([...n.entries()].map(([e,t])=>[t,e]));$y.clear();for(let e of t)$y.set(e.key,e.cwd);let i=n.size!==$y.size||t.some(e=>n.get(e.key)!==e.cwd),a={},o=e.projectExpandedById,s=new Map(Qy.map((e,t)=>[e,t])),c=t.map((e,t)=>{let n=r.get(e.cwd),i=o[e.key]??(n?o[n]:void 0)??(Zy.size>0?Zy.has(e.cwd):!0);return a[e.key]=i,{id:e.key,cwd:e.cwd,incomingIndex:t}}),l=e.projectOrder.length>0?(()=>{let t=new Map(c.map(e=>[e.cwd,e.id])),r=new Set,i=[];for(let o of e.projectOrder){let e=(o in a?o:void 0)??(()=>{let e=n.get(o);return e?t.get(e):void 0})();!e||r.has(e)||(r.add(e),i.push(e))}for(let e of c)r.has(e.id)||i.push(e.id);return i})():c.map(e=>({id:e.id,incomingIndex:e.incomingIndex,orderIndex:s.get(e.cwd)??Qy.length+e.incomingIndex})).toSorted((e,t)=>{let n=e.orderIndex-t.orderIndex;return n===0?e.incomingIndex-t.incomingIndex:n}).map(e=>e.id);return pb(e.projectExpandedById,a)&&mb(e.projectOrder,l)&&!i?e:{...e,projectExpandedById:a,projectOrder:l}}function _b(e,t){let n=new Set(t.map(e=>e.key)),r=Object.fromEntries(Object.entries(e.threadLastVisitedAtById).filter(([e])=>n.has(e)));for(let e of t)r[e.key]===void 0&&e.seedVisitedAt!==void 0&&e.seedVisitedAt.length>0&&(r[e.key]=e.seedVisitedAt);let i=Object.fromEntries(Object.entries(e.threadChangedFilesExpandedById).filter(([e])=>n.has(e))),a=Object.fromEntries(Object.entries(e.pinnedThreadById).filter(([e,t])=>n.has(e)&&t)),o=Object.fromEntries(Object.entries(e.threadLinkedPrById).filter(([e])=>n.has(e))),s=Object.fromEntries(Object.entries(e.pinOrderKeyById).filter(([e])=>n.has(e))),c=Object.fromEntries(Object.entries(e.activeOrderKeyById).filter(([e])=>n.has(e))),l=Object.fromEntries(Object.entries(e.threadSnoozeById).filter(([e])=>n.has(e)));return pb(e.threadLastVisitedAtById,r)&&hb(e.threadChangedFilesExpandedById,i)&&pb(e.pinnedThreadById,a)&&pb(e.threadLinkedPrById,o)&&pb(e.pinOrderKeyById,s)&&pb(e.activeOrderKeyById,c)&&pb(e.threadSnoozeById,l)?e:{...e,threadLastVisitedAtById:r,threadChangedFilesExpandedById:i,pinnedThreadById:a,threadLinkedPrById:o,pinOrderKeyById:s,activeOrderKeyById:c,threadSnoozeById:l}}function vb(e,t){return e.lastActiveProject?.environmentId===t?.environmentId&&e.lastActiveProject?.projectId===t?.projectId?e:{...e,lastActiveProject:t}}function yb(e,t,n){return e.workspaceDensityById[t]===n?e:{...e,workspaceDensityById:{...e.workspaceDensityById,[t]:n}}}function bb(e,t){let n=e.projectExpandedById[t]??!0;return{...e,projectExpandedById:{...e.projectExpandedById,[t]:!n}}}function xb(e,t,n){return(e.projectExpandedById[t]??!0)===n?e:{...e,projectExpandedById:{...e.projectExpandedById,[t]:n}}}function Sb(e,t,n){if(t.length===0)return e;let r=new Set(t),i=new Set(n);if(t.every(e=>i.has(e)))return e;let a=e.projectOrder.findIndex(e=>i.has(e));if(a<0)return e;let o=[...e.projectOrder],s=[],c=0;for(let e=o.length-1;e>=0;e--)r.has(o[e])&&(s.unshift(o.splice(e,1)[0]),e<a&&c++);if(s.length===0)return e;let l=a-Math.max(0,c-1);return o.splice(l,0,...s),{...e,projectOrder:o}}function Cb(e,t){let n=[...new Set(t)],r=new Set(n),i=e.projectGroupOrder.filter(e=>r.has(e)),a=new Set(i);for(let e of n)a.has(e)||i.push(e);return mb(e.projectGroupOrder,i)?e:{...e,projectGroupOrder:i}}function wb(e,t,n){if(t===n)return e;let r=e.projectGroupOrder.indexOf(t),i=e.projectGroupOrder.indexOf(n);if(r<0||i<0)return e;let a=[...e.projectGroupOrder],[o]=a.splice(r,1);return o===void 0?e:(a.splice(i,0,o),{...e,projectGroupOrder:a})}var Tb=wa(e=>({...tb(),syncProjects:t=>e(e=>gb(e,t)),syncProjectGroups:t=>e(e=>Cb(e,t)),syncThreads:t=>e(e=>_b(e,t)),markThreadVisited:(t,n)=>e(e=>Ny(e,t,n)),markThreadUnread:(t,n)=>e(e=>Py(e,t,n)),clearThreadUi:t=>e(e=>Fy(e,t)),setThreadPinned:(t,n)=>e(e=>Iy(e,t,n)),toggleThreadPinned:t=>e(e=>Ly(e,t)),setThreadPinOrderKey:(t,n)=>e(e=>Ry(e,t,n)),setThreadActiveOrderKey:(t,n)=>e(e=>zy(e,t,n)),setThreadSnooze:(t,n)=>e(e=>By(e,t,n)),setThreadLinkedPr:(t,n)=>e(e=>Vy(e,t,n)),clearThreadLinkedPr:t=>e(e=>Hy(e,t)),setThreadChangedFilesExpanded:(t,n,r)=>e(e=>Uy(e,t,n,r)),setWorkspaceDensity:(t,n)=>e(e=>yb(e,t,n)),toggleProject:t=>e(e=>bb(e,t)),setProjectExpanded:(t,n)=>e(e=>xb(e,t,n)),reorderProjects:(t,n)=>e(e=>Sb(e,t,n)),reorderProjectGroups:(t,n)=>e(e=>wb(e,t,n)),setLastActiveProject:t=>e(e=>vb(e,t)),setTimelineWorkColumnWidth:t=>e(e=>({...e,timelineWorkColumnWidth:Yy(t)})),setTimelineScale:t=>e(e=>({...e,timelineScale:t})),openProjectLeadCompanion:t=>e(e=>({...e,projectLeadCompanion:ky(e.projectLeadCompanion,t)})),closeProjectLeadCompanion:()=>e(e=>({...e,projectLeadCompanion:{...e.projectLeadCompanion,open:!1}})),setProjectLeadCompanionMinimized:t=>e(e=>({...e,projectLeadCompanion:{...e.projectLeadCompanion,minimized:t}})),setProjectLeadCompanionDock:t=>e(e=>({...e,projectLeadCompanion:{...e.projectLeadCompanion,dock:t}})),setProjectLeadCompanionPosition:t=>e(e=>({...e,projectLeadCompanion:{...e.projectLeadCompanion,position:t}}))}));function Eb(e){Tb.getState().openProjectLeadCompanion(e)}Tb.subscribe(e=>fb.maybeExecute(e)),typeof window<`u`&&typeof window.addEventListener==`function`&&window.addEventListener(`beforeunload`,()=>{fb.flush()});var I=new Map;function Db(e){return!e.isWorking||e.msSinceLastEvent<e.stallThresholdMs?`none`:e.recoveryAttempts<e.maxResubscribeAttempts?`resubscribe`:e.recoveryAttempts<e.maxTotalAttempts?`reconnect`:`none`}var Ob=3e4,kb=1e4,Ab=[/(?:^|\s)\/(?:Users|var|private|tmp|project|repo|home)\/[^\s'"<>)]*/i,/(?:^|\s)[A-Za-z]:\\[^\s'"<>)]*/];function jb(e){let t=e?.trim();return t&&t.length>0?t:null}function Mb(e){return jb(e)??`Project`}function Nb(e,t=`safe`){let n=jb(e);return n?t===`full`?n:n.replaceAll(`\\`,`/`).split(`/`).filter(Boolean).at(-1)??`Local checkout`:`Local checkout`}function Pb(e,t=`Something went wrong. Try again.`){let n=e instanceof Error?e.message:typeof e==`string`?e:String(e),r=dr(n,{fallback:t});return!r||Ab.some(e=>e.test(r))?t:r}var Fb=`Thread not found or you no longer have access.`;function Ib(e){if(e==null)return Fb;let t=Pb(qt(e)?ke(e):e,Fb);return/\bnot found\b/i.test(t)?Fb:t}function Lb(e,t,n){S.getState().setThreadSubscriptionError(e,t,Ib(n))}var Rb=null;function zb(e){Rb=e}function Bb(){if(Rb===null)throw Error(`Thread detail subscriptions were used before the service was configured.`);return Rb}var Vb=9e5,Hb=()=>void 0;function Ub(e,t){return Ln(C(e,t))}function Wb(e){return e.evictionTimeoutId!==null&&(clearTimeout(e.evictionTimeoutId),e.evictionTimeoutId=null),e}function Gb(e){let t=C(e.environmentId,e.threadId),n=S.getState(),r=Tn(n,t);if(r&&qb(r))return!0;let i=Sn(n,t);return i?Kb(i.session?.orchestrationStatus)||i.latestTurn?.state===`running`||i.pendingSourceProposedPlan!==void 0:!1}function Kb(e){return!!(e&&e!==`idle`&&e!==`stopped`)}function qb(e){return e.hasPendingApprovals||e.hasPendingUserInput||e.hasActionableProposedPlan||Kb(e.session?.orchestrationStatus)||e.latestTurn?.state===`running`}function Jb(e){return e.refCount===0&&!Gb(e)}function Yb(e){let t=Bb().readConnection(e.environmentId);return e.unsubscribe===Hb&&!t?!1:(e.unsubscribeConnectionListener!==null&&(e.unsubscribeConnectionListener(),e.unsubscribeConnectionListener=null),e.unsubscribe!==Hb||!t||(e.unsubscribe=t.client.orchestration.subscribeThread({threadId:e.threadId},t=>{e.lastEventAt=Date.now(),e.recoveryAttempts=0,t.kind===`event`?Bb().applyEvent(t.event,e.environmentId):t.kind===`snapshot`&&(S.getState().syncServerThreadDetail(t.snapshot.thread,e.environmentId),S.getState().clearThreadSubscriptionError(e.environmentId,e.threadId))},{onError:t=>Lb(e.environmentId,e.threadId,t)})),!0)}function Xb(e){e.unsubscribeConnectionListener===null&&(e.unsubscribeConnectionListener=Bb().subscribeConnections(()=>{Yb(e)&&(e.lastAccessedAt=Date.now())}),Yb(e))}var Zb=null;function Qb(e){let t=C(e.environmentId,e.threadId),n=S.getState(),r=Tn(n,t);if(r?.latestTurn?.state===`running`||r?.session?.orchestrationStatus===`running`)return!0;let i=Sn(n,t);return i?.latestTurn?.state===`running`||i?.session?.orchestrationStatus===`running`}function $b(e){e.unsubscribe!==Hb&&(e.unsubscribe(),e.unsubscribe=Hb),Yb(e)||Xb(e)}function ex(e,t,n){if(e.recoveryAttempts+=1,e.lastEventAt=Date.now(),console.warn(`[forge] thread-detail liveness watchdog recovering`,{action:t,threadId:String(e.threadId),environmentId:String(e.environmentId),msSinceLastEvent:Math.round(n),recoveryAttempts:e.recoveryAttempts}),t===`resubscribe`){$b(e);return}Bb().readConnection(e.environmentId)?.reconnect().catch(t=>{Vn(t,{route:`thread-detail-liveness-watchdog-reconnect-failed`,threadId:String(e.threadId),environmentId:String(e.environmentId),msSinceLastEvent:String(Math.round(n)),recoveryAttempts:String(e.recoveryAttempts)})})}function tx(){let e=Date.now();for(let t of I.values()){let n=Db({isWorking:Qb(t),msSinceLastEvent:e-t.lastEventAt,stallThresholdMs:Ob,recoveryAttempts:t.recoveryAttempts,maxResubscribeAttempts:2,maxTotalAttempts:4});n!==`none`&&ex(t,n,e-t.lastEventAt)}}function nx(){Zb===null&&(Zb=setInterval(tx,kb))}function rx(){I.size>0||Zb!==null&&(clearInterval(Zb),Zb=null)}function ix(e){let t=I.get(e);return t?(Wb(t),t.unsubscribeConnectionListener?.(),t.unsubscribeConnectionListener=null,I.delete(e),t.unsubscribe(),t.unsubscribe=Hb,rx(),!0):!1}function ax(e){ox(e,!0),j.getState().clear(e)}function ox(e,t=!1){for(let[n,r]of I)if(r.environmentId===e){if(r.refCount===0||t){ix(n);continue}r.unsubscribe(),r.unsubscribe=Hb,Xb(r)}}function sx(e){for(let t=e.messages.length-1;t>=0;--t){let n=e.messages[t];if(n?.role===`user`)return n.createdAt}return null}function cx(e){return e.session?{threadId:e.id,updatedAt:e.session.updatedAt,providerName:e.session.provider,runtimeMode:e.runtimeMode,activeTurnId:e.session.activeTurnId??null,lastError:e.session.lastError??null,status:e.session.orchestrationStatus}:null}function lx(e,t){return{updatedAt:e.updatedAt??e.createdAt,latestUserMessageAt:t?.latestUserMessageAt??sx(e),titleRegeneration:e.titleRegeneration??null}}function ux(e){return{hasPendingApprovals:e?.hasPendingApprovals??!1,hasPendingUserInput:e?.hasPendingUserInput??!1,hasActionableProposedPlan:e?.hasActionableProposedPlan??!1}}function dx(e){let t=C(e.environmentId,e.threadId),n=S.getState(),r=Sn(n,t);if(!r)return null;let i=Tn(n,t);return{id:r.id,projectId:r.projectId,title:r.title,modelSelection:r.modelSelection,runtimeMode:r.runtimeMode,interactionMode:r.interactionMode,branch:r.branch,worktreePath:r.worktreePath,latestTurn:r.latestTurn,createdAt:r.createdAt,...lx(r,i),...ux(i),archivedAt:r.archivedAt,session:cx(r),anchorKind:r.anchorKind,anchorCmmdId:r.anchorCmmdId,kind:r.kind,parentThreadId:r.parentThreadId,status:r.status,workerRole:r.workerRole,goal:r.goal}}function fx(e,t){if(I.size===0)return e;let n=new Set(e.threads.map(e=>e.id)),r=[];for(let e of I.values()){if(e.environmentId!==t||e.refCount<=0||n.has(e.threadId))continue;let i=dx(e);i&&(n.add(i.id),r.push(i))}return r.length===0?e:{...e,threads:[...e.threads,...r]}}function px(e,t){let n=new Set(t);for(let[t,r]of I)r.environmentId===e&&!n.has(r.threadId)&&Jb(r)&&ix(t)}function mx(e){Wb(e),Jb(e)&&(e.evictionTimeoutId=setTimeout(()=>{let t=I.get(Ub(e.environmentId,e.threadId));t&&(t.evictionTimeoutId=null,Jb(t)&&ix(Ub(e.environmentId,e.threadId)))},Vb))}function hx(){if(I.size<=32)return;let e=[...I.entries()].filter(([,e])=>Jb(e)).toSorted(([,e],[,t])=>e.lastAccessedAt-t.lastAccessedAt);for(let[t]of e){if(I.size<=32)return;ix(t)}}function gx(e){Wb(e),Jb(e)&&mx(e)}function _x(e,t){let n=I.get(Ub(e,t));n&&gx(n)}function vx(e){for(let t of I.values())t.environmentId===e&&gx(t);hx()}function yx(e){let t=!1;return()=>{t||(t=!0,e.refCount=Math.max(0,e.refCount-1),e.lastAccessedAt=Date.now(),e.refCount===0&&(gx(e),hx()))}}function bx(e,t){let n=Ub(e,t),r=I.get(n);if(r)return Wb(r),r.refCount+=1,r.lastAccessedAt=Date.now(),Yb(r)||Xb(r),yx(r);let i={environmentId:e,threadId:t,unsubscribe:Hb,unsubscribeConnectionListener:null,refCount:1,lastAccessedAt:Date.now(),evictionTimeoutId:null,lastEventAt:Date.now(),recoveryAttempts:0};return I.set(n,i),Yb(i)||Xb(i),nx(),hx(),yx(i)}function xx(e,t){return e.type!==`thread.message-sent`||t.type!==`thread.message-sent`||e.payload.threadId!==t.payload.threadId||e.payload.messageId!==t.payload.messageId?null:{...t,payload:{...t.payload,attachments:t.payload.attachments??e.payload.attachments,createdAt:e.payload.createdAt,text:!t.payload.streaming&&t.payload.text.length>0?t.payload.text:e.payload.text+t.payload.text}}}function Sx(e){if(e.length<2)return[...e];let t=[];for(let n of e){let e=t.at(-1),r=e?xx(e,n):null;if(r){t[t.length-1]=r;continue}t.push(n)}return t}function Cx(){let e=wn(S.getState());Tb.getState().syncProjects(e.map(e=>({key:Fn(In(e.environmentId,e.id)),cwd:e.cwd})))}function wx(){let e=mn(S.getState());Tb.getState().syncThreads(e.map(e=>({key:Ln(C(e.environmentId,e.id)),seedVisitedAt:e.updatedAt??e.createdAt}))),by(e.map(e=>C(e.environmentId,e.id)))}function Tx(){Cx(),wx();let e=Ty({snapshotThreads:mn(S.getState()).map(e=>({key:Ln(C(e.environmentId,e.id)),deletedAt:null,archivedAt:e.archivedAt})),draftThreadKeys:gy.getState().listDraftThreadKeys()});um.getState().removeOrphanedTerminalStates(e)}function Ex(e){return e.serverThreadArchivedAt===void 0?e.hasDraftThread:e.serverThreadArchivedAt===null}function Dx(e,t){if(e.length===0)return;let n=Ey(e),r=Sx(e),i=e.some(e=>e.type===`project.created`||e.type===`project.meta-updated`||e.type===`project.deleted`);if(n.needsProviderInvalidation&&wy().notifyProviderInvalidation(),S.getState().applyOrchestrationEvents(r,t),i){let e=wn(S.getState());Tb.getState().syncProjects(e.map(e=>({key:Fn(In(e.environmentId,e.id)),cwd:e.cwd})))}if(e.some(e=>e.type===`thread.created`||e.type===`thread.deleted`)){let e=mn(S.getState());Tb.getState().syncThreads(e.map(e=>({key:Ln(C(e.environmentId,e.id)),seedVisitedAt:e.updatedAt??e.createdAt})))}let a=gy.getState();for(let e of n.promoteDraftThreadIds)yy(C(t,e));for(let e of n.clearDeletedThreadIds)a.clearDraftThread(C(t,e)),Tb.getState().clearThreadUi(Ln(C(t,e)));for(let e of n.removeTerminalStateThreadIds){let n=C(t,e);um.getState().removeTerminalState(n),Ff.getState().clearBrowserState(n)}vx(t)}function Ox(e,t){Dx([e],t)}function kx(e,t){let n=e.kind===`thread-upserted`?e.thread.id:e.kind===`thread-removed`?e.threadId:null,r=n?C(t,n):null,i=r?Sn(S.getState(),r):void 0;switch(S.getState().applyShellEvent(e,t),e.kind){case`project-upserted`:case`project-removed`:Cx();return;case`thread-upserted`:wx(),!i&&r&&yy(r),i?.archivedAt===null&&e.thread.archivedAt!==null&&r&&(um.getState().removeTerminalState(r),Ff.getState().clearBrowserState(r)),_x(t,e.thread.id),hx();return;case`thread-removed`:r&&(ix(Ln(r)),gy.getState().clearDraftThread(r),Tb.getState().clearThreadUi(Ln(r)),um.getState().removeTerminalState(r),Ff.getState().clearBrowserState(r)),wx();return}}function Ax(e,t){return e.invalidateQueries({queryKey:zf.all(t)})}function jx(e){return{onWelcome:(t,n)=>{e?.(t);let r=wy().readQueryClient();r&&Ax(r,n)},applyShellEvent:kx,syncShellSnapshot:(e,t)=>{let n=fx(e,t);S.getState().syncServerShellSnapshot(n,t),px(t,n.threads.map(e=>e.id)),vx(t),Tx()},applyTerminalEvent:(e,t)=>{let n=C(t,zr.make(e.threadId)),r=Sn(S.getState(),n),i=gy.getState().getDraftThreadByRef(n)!==null;Ex({serverThreadArchivedAt:r?.archivedAt,hasDraftThread:i})&&um.getState().applyTerminalEvent(n,e)},applyBrowserEvent:(e,t)=>{let n=C(t,zr.make(e.threadId)),r=Sn(S.getState(),n),i=gy.getState().getDraftThreadByRef(n)!==null;Ex({serverThreadArchivedAt:r?.archivedAt,hasDraftThread:i})&&Ff.getState().applyBrowserEvent(n,e)},onShellSubscriptionError:(e,t)=>{wy().setRuntimeError(t,e)}}}function Mx(){return new Date().toISOString()}function Nx(e){j.getState().patch(e,{connectionState:`connecting`,lastError:null,lastErrorAt:null})}function Px(e){let t=Mx();j.getState().patch(e,{connectionState:`connected`,authState:`authenticated`,connectedAt:t,disconnectedAt:null,lastError:null,lastErrorAt:null}),ir.getState().markConnected(e,t)}function Fx(e,t){j.getState().patch(e,{descriptor:t.environment,serverConfig:t})}function Ix(e,t){j.getState().patch(e,{connectionState:`disconnected`,disconnectedAt:Mx(),...t&&t.trim().length>0?{lastError:t,lastErrorAt:Mx()}:{}})}function Lx(e,t){j.getState().patch(e,{connectionState:`error`,...vl(t)})}function Rx(){return new Date().toISOString()}function zx(e){let t=hr();if(!t?.environmentId)throw Error(`Unable to resolve the primary environment.`);let n=e.readConnection(t.environmentId);if(n)return n;let r=sf(),i=t.source===`paired-bearer`||!0;return e.registerConnection(ql({kind:`primary`,knownEnvironment:t,client:lf(t),resolveEnvironmentId:()=>hr()?.environmentId??t.environmentId,...i?{readiness:r?{bearerToken:r.bearerToken}:{}}:{},...jx()}))}async function Bx(e){let t=cf();if(!t)throw Error(`Desktop Local runtime is not authenticated. Sign in with CMMD again before importing local projects.`);let n=await Il({httpBaseUrl:t.httpBaseUrl,bearerToken:t.bearerToken}),r=e.readConnection(n.environmentId);if(r)return r;let i=xn({id:n.environmentId,label:t.label,source:`desktop-managed`,target:{httpBaseUrl:t.httpBaseUrl,wsBaseUrl:t.wsBaseUrl}});return e.registerConnection(ql({kind:`desktop-local`,knownEnvironment:{...i,environmentId:n.environmentId,label:n.label},client:uf({environmentId:n.environmentId,httpBaseUrl:t.httpBaseUrl,wsBaseUrl:t.wsBaseUrl,bearerToken:t.bearerToken,onConnecting:Nx,onConnected:Px,onError:(e,t)=>{j.getState().patch(e,{connectionState:`error`,lastError:t,lastErrorAt:Rx()})},onDisconnected:Ix}),...jx()}))}var Vx=new Map;function Hx(e){for(let t of e){let e=Vx.get(t);e===void 0||e<=1?Vx.delete(t):Vx.set(t,e-1)}}async function Ux(e,t){let n=e.environmentId;Vx.set(n,(Vx.get(n)??0)+1);try{return t.readConnection(n)||await t.ensureCmmdRuntimeSavedEnvironmentConnection(e),!0}catch{return Hx([n]),!1}}async function Wx(e){await Qn();let t=(await Promise.all(ar().map(async t=>await Ux(t,e)?t.environmentId:null))).flatMap(e=>e===null?[]:[e]),n=!1;return()=>{n||(n=!0,Hx(t))}}function Gx(){return new Date().toISOString()}async function Kx(e,t){t.readConnection(e)?.kind===`saved`&&(j.getState().clear(e),await t.removeConnection(e).catch(()=>!1))}async function qx(e,t){let n=er(e);if(!n)throw Error(`Saved environment not found.`);let r=t.readConnection(e);if(!r){try{await t.ensureCmmdRuntimeSavedEnvironmentConnection(n)}catch(t){throw Lx(e,t),t}return}Nx(e);try{await r.reconnect()}catch(t){throw Lx(e,t),t}}async function Jx(e,t){t.invalidate(e),ir.getState().remove(e),await mr(e),await Kx(e,t)}async function Yx(e,t){let{existing:n,replacedRecord:r}=ml({environmentId:Hr.make(e.environment.environmentId),replacesEnvironmentId:e.environment.replacesEnvironmentId}),i=Xx(e.environment,n);al(e.signal);let a=await hl(n),o=t.readConnection(i.environmentId)!==null&&pl({existing:n,replacedRecord:r,record:i});return o||(t.invalidate(i.environmentId),await t.removeConnection(i.environmentId).catch(()=>!1)),r&&(t.invalidate(r.environmentId),await t.removeConnection(r.environmentId).catch(()=>!1)),await t.ensureCmmdRuntimeSavedEnvironmentConnection(i,{bearerToken:e.bearerToken,registryExpectation:n&&!r?{kind:`existing-record`,record:n}:{kind:`initial-add`},...e.signal?{signal:e.signal}:{},...e.onBootstrapRetry?{onBootstrapRetry:e.onBootstrapRetry}:{}}),Zx({record:i,replacedRecord:r,persistenceRollback:a,keepsLiveConnection:o,signal:e.signal,dependencies:t})}function Xx(e,t){let n=Hr.make(e.environmentId),{kind:r,cmmdOrganizationId:i,cmmdProjectId:a,runtimeId:o,runtimeTicketExpiresAt:s}=e;return{environmentId:n,label:e.label,wsBaseUrl:Jr(e.wsBaseUrl),httpBaseUrl:e.httpBaseUrl,createdAt:t?.createdAt??Gx(),lastConnectedAt:Gx(),...r===void 0?{}:{kind:r},...i===void 0?{}:{cmmdOrganizationId:i},...a===void 0?{}:{cmmdProjectId:a},...o===void 0?{}:{runtimeId:o},...s===void 0?{}:{runtimeTicketExpiresAt:s}}}async function Zx(e){let{record:t,replacedRecord:n,persistenceRollback:r,keepsLiveConnection:i,signal:a,dependencies:o}=e,s=!1;try{return al(a),await _l({record:t,replacedRecord:n,rollback:r,...a?{signal:a}:{}}),s=!0,al(a),ir.getState().upsert(ul(t)),n&&o.retireEnvironmentId(n.environmentId),t}catch(e){throw i||await o.removeConnection(t.environmentId).catch(()=>!1),s&&await gl({record:t,replacedRecord:n,rollback:r}),al(a),e}}var Qx=`forge.deviceRegistry.deviceKey`,$x=`forge.deviceRegistry.runtimeId`;function eS(e){let t=rS(Qx,e.desktopIdentity?.deviceKey,`device`),n=rS($x,e.desktopIdentity?.runtimeId,`runtime`),r=nS(e.desktopIdentity?.hostKey),i=cS(),a=e.desktopAvailable?`desktop`:lS(),o=e.desktopAvailable?sS(e.desktopIdentity)??uS(i):dS(i);return{device:{...r?{hostKey:r}:{},deviceKey:t,displayName:o,platform:i,deviceType:a,metadata:{clientKind:e.desktopAvailable?`forge-desktop`:`forge-web`,userAgent:window.navigator.userAgent,origin:window.location.origin,...e.desktopIdentity?{desktopIdentity:{hostName:e.desktopIdentity.hostName,computerName:e.desktopIdentity.computerName,platform:e.desktopIdentity.platform}}:{}}},...e.desktopAvailable&&e.includeExecutableRuntime!==!1?{runtime:{runtimeId:n,runtimeKind:`desktop-local`,displayName:`Local Forge Desktop`,endpointUrl:e.desktopEndpointUrl??null,status:`online`,metadata:{origin:window.location.origin}}}:{}}}async function tS(){let e=await window.desktopBridge?.getDeviceIdentity?.()??null;return eS({desktopAvailable:!!window.desktopBridge,desktopIdentity:e,includeExecutableRuntime:!1})}function nS(e){let t=e?.trim()??``;return t.length>0?t:null}function rS(e,t,n){let r=nS(t);return r?(En(e,r),r):oS(e,n)}function iS(){return Mn($x)}function aS(){return Mn(Qx)}function oS(e,t){let n=Mn(e);if(n)return n;let r=`${t}_${crypto.randomUUID()}`;return En(e,r),r}function sS(e){let t=e?.displayName?.trim()??``;return t.length>0?t:null}function cS(){let e=window.navigator.userAgent.toLowerCase();return e.includes(`iphone`)||e.includes(`ipad`)?`ios`:e.includes(`android`)?`android`:e.includes(`mac`)?`macos`:e.includes(`win`)?`windows`:e.includes(`linux`)?`linux`:`unknown`}function lS(){let e=window.navigator.userAgent.toLowerCase();return e.includes(`ipad`)||e.includes(`tablet`)?`tablet`:e.includes(`mobi`)||e.includes(`iphone`)||e.includes(`android`)?`mobile`:`browser`}function uS(e){return e===`macos`?`Mac`:e===`windows`?`Windows PC`:e===`linux`?`Linux Desktop`:`Desktop`}function dS(e){return e===`web`?`Browser`:e===`macos`?`Mac Browser`:e===`windows`?`Windows Browser`:e===`linux`?`Linux Browser`:`Browser`}var fS=`forge.relayControlJournal.v1`;function pS(){if(globalThis.localStorage===void 0)throw Error(`Forge relay control recovery requires durable browser storage.`);return globalThis.localStorage}var mS={read:()=>pS().getItem(fS),write:e=>pS().setItem(fS,e)},hS=null,gS=wa()(e=>({byRuntimeId:{},replace:t=>e({byRuntimeId:t})}));function _S(e){e.subscribe(e=>{let t=new Set(e.records.map(e=>e.runtimeId));gS.getState().replace(Object.fromEntries([...t].map(t=>[t,la(e.records,t)])))})}function vS(){return hS===null&&(hS=ua({storage:mS}),_S(hS)),hS}function yS(){let e=(0,A.c)(1),t=gS(xS),n;return e[0]===Symbol.for(`react.memo_cache_sentinel`)?(n=[],e[0]=n):n=e[0],(0,O.useEffect)(bS,n),t}function bS(){vS()}function xS(e){return e.byRuntimeId}function SS(e){let t=vS();for(let n of t.records())n.runtimeId===e&&(n.status===`failed`||n.status===`outcome-unknown`)&&t.acknowledge(n.runtimeId,n.actorSessionId,n.transportRequestId)}var CS=class extends Error{code;constructor(e,t){super(t),this.name=`RelayControlRouteError`,this.code=e}};function wS(e){let t=e&&typeof e==`object`?e.code:null;throw t===`PROTOCOL_INCOMPATIBLE`?new CS(`FORGE_RUNTIME_UPDATE_REQUIRED`,`Update Forge on the target runtime before connecting remotely.`):t===`PROTOCOL_ROLLOUT_DENIED`?new CS(`FORGE_REMOTE_CONTROL_NOT_ENABLED`,`Remote control is not enabled for this CMMD account. Synced runtime inventory remains available.`):e}async function TS(e){let t=e.getStoredDeviceKey(),n=t?await e.apiClient.getDeviceRegistry():await e.apiClient.registerDevice(await e.buildDeviceRegistration());return t&&!n.devices.some(e=>e.deviceKey===t)&&(n=await e.apiClient.registerDevice(await e.buildDeviceRegistration())),t??=e.getStoredDeviceKey(),{deviceKey:t,registry:n}}function ES(e){if(!e.deviceKey)throw new CS(`FORGE_CONTROL_DEVICE_UNAUTHORIZED`,`This Forge control surface could not establish CMMD identity.`);let t=e.registry.devices.find(t=>t.deviceKey===e.deviceKey);if(t?.trustState===`revoked`||t?.authorization?.revoked===!0)throw new CS(`FORGE_CONTROL_DEVICE_REVOKED`,`This Forge control surface was revoked by CMMD.`);if(!t||t.trustState!==`trusted`)throw new CS(`FORGE_CONTROL_DEVICE_UNAUTHORIZED`,`This Forge control surface is not trusted by CMMD.`);return t}function DS(e,t){let n=async()=>ES(await TS(t));return{acquireRoute:async()=>{let r=await n(),i=await ca();try{let n=await t.apiClient.issueRelayControlRoute(e,{controlDeviceId:r.id,controlSessionId:t.controlSessionId,scopes:[...Ci],protocolMinVersion:4,protocolMaxVersion:4,...Yi(i)});return $i({route:n,runtimeId:e,endpoint:i})}catch(e){if(e instanceof sa)throw new CS(`FORGE_RUNTIME_UPDATE_REQUIRED`,e.message);return wS(e)}},acquireActionGrant:async r=>{let i=await n();try{return(await t.apiClient.issueRelayActionGrant(e,{controlDeviceId:i.id,controlSessionId:t.controlSessionId,...r})).token}catch(e){return wS(e)}}}}var OS=new Map;async function kS(e,t){let n=Hr.make(e.runtimeId),r=t.readConnection(n);if(r)return r;Nx(n);let i=vS(),a=DS(e.runtimeId,{apiClient:cr,getStoredDeviceKey:aS,buildDeviceRegistration:tS,controlSessionId:i.controlSessionId}),o;try{o=await a.acquireRoute()}catch(e){throw Lx(n,e),e}let s=o,c=ga({acquireRoute:async()=>{let e=s;return s=null,e??a.acquireRoute()},acquireActionGrant:a.acquireActionGrant,journal:i,lifecycle:{onConnecting:()=>Nx(n),onAuthenticated:()=>Px(n),onDisconnected:e=>Ix(n,e.reason),onError:e=>Lx(n,Object.assign(Error(e.message),e))}}),l=of(new ud(o.relayWebSocketUrl,{trackGlobalConnection:!1},{layer:c,makeClient:Qi(Ci)})),u=ql({kind:`saved`,knownEnvironment:{...xn({id:n,label:e.label,source:`manual`,target:{httpBaseUrl:ra()?.target.httpBaseUrl??o.relayWebSocketUrl,wsBaseUrl:o.relayWebSocketUrl}}),environmentId:n},client:l,tolerateReportedEnvironmentIdentity:!0,onConfigSnapshot:e=>Fx(n,e),...jx(e=>{j.getState().patch(n,{descriptor:e.environment})})});try{let[,e]=await Promise.all([u.ensureBootstrapped(),l.server.getConfig()]);return Fx(n,e),Px(n),t.registerConnection(u)}catch(e){throw Lx(n,e),await u.dispose().catch(()=>void 0),e}}function AS(e,t){let n=Hr.make(e.runtimeId),r=t.readConnection(n);if(r)return Promise.resolve(r);let i=OS.get(n);if(i)return i;let a=kS(e,t).finally(()=>{OS.delete(n)});return OS.set(n,a),a}var jS=new Set([`CMMD_AUTH_REQUIRED`,`CMMD_AUTH_EXPIRED`,`INVALID_OR_NON_USER_TOKEN`,`NON_USER_BEARER`,`CMMD_REST_AUTH_ERROR`]);function MS(e){if(!e||typeof e!=`object`)return null;let t=e.code;return typeof t!=`string`||!jS.has(t)?null:t}function NS(e,t){return e===401||e===403||MS(t)!==null}function PS(e){if(!e||typeof e!=`object`)return!1;let t=e.status,n=e.code;return NS(typeof t==`number`?t:void 0,typeof n==`string`?{code:n}:void 0)}var FS=[1e3,2e3,4e3,8e3,12e3,16e3,2e4],IS=9e4,LS=[`all fibers interrupted without error`,`timed out while waiting for forge cloud runtime metadata`,`timed out while waiting for`,`to stream its shell snapshot`,`forge runtime route not found`,`fly-replay`,`could not find a good candidate`,`instance refused connection`],RS=[`Unknown socket error`,`Failed to fetch remote auth endpoint`,`Forge runtime replay target is unavailable`,`Remote auth request failed (502)`,`Remote auth request failed (503)`,`Remote auth request failed (504)`,`Unable to connect to the Forge server WebSocket`];function zS(e){if(typeof e!=`object`||!e)return null;let t=e.status;return typeof t==`number`&&Number.isInteger(t)?t:null}function BS(e){if(PS(e))return!1;let t=zS(e);if(t===502||t===503||t===504||e._tag===`OrchestrationGetSnapshotError`)return!0;let n=e instanceof Error?e.message:String(e),r=n.toLowerCase();return LS.some(e=>r.includes(e))||RS.some(e=>n.includes(e))}function VS(e){return FS[e]??FS[FS.length-1]}function HS(){return IS}function US(e,t){if(!dl(e))return t;let n=null,r=new Promise((t,r)=>{n=globalThis.setTimeout(()=>{r(Error(`Timed out while waiting for Forge Cloud runtime metadata for ${e.environmentId}. The VM may still be starting.`))},HS())});return Promise.race([t,r]).finally(()=>{n!==null&&globalThis.clearTimeout(n)})}function WS(e){let t=e.toLowerCase();return t.includes(`authentication`)||t.includes(`unauthorized`)||t.includes(`forbidden`)||t.includes(`credential`)||t.includes(`runtime ticket`)||t.includes(`status 401`)||t.includes(`status 403`)}var GS=`forge:cloud-runtime-handoffs:v2`,KS=3e5,qS=new Map,JS={clear:()=>qS.clear(),getItem:e=>qS.get(e)??null,key:e=>Array.from(qS.keys())[e]??null,get length(){return qS.size},removeItem:e=>qS.delete(e),setItem:(e,t)=>qS.set(e,t)};function YS(){return typeof window<`u`?window.localStorage:globalThis.localStorage??JS}var XS=wa()(Gf(e=>({byRuntimeId:{},record:t=>e(e=>({byRuntimeId:{...e.byRuntimeId,[t.runtimeId]:t}})),clearRuntime:t=>e(e=>t in e.byRuntimeId?{byRuntimeId:Object.fromEntries(Object.entries(e.byRuntimeId).filter(([e])=>e!==t))}:e),reconcileCatalog:(t,n=Date.now())=>e(e=>{let r=Object.entries(e.byRuntimeId).filter(([,e])=>{if(n-e.recordedAt>KS)return!1;let r=t.find(t=>t.cmmdOrganizationId===e.cmmdOrganizationId&&t.cmmdProjectId===e.cmmdProjectId);return r?.runtimeId===e.previousCatalogRuntimeId&&r.registeredAt===e.catalogRegisteredAt});return r.length===Object.keys(e.byRuntimeId).length?e:{byRuntimeId:Object.fromEntries(r)}}),reset:()=>e({byRuntimeId:{}})}),{name:GS,storage:Uf(YS),partialize:e=>({byRuntimeId:e.byRuntimeId}),version:2}));function ZS(e){XS.getState().record({...e,recordedAt:Date.now()})}function QS(e){XS.getState().clearRuntime(e)}var $S=new Set([`filesystem`,`terminal`,`git`,`project-write`]);function eC(e){return e===`desktop-local`}function tC(e){return e===`cloud`||e===`cloud-vm`||e===`cmmd`||e===`github`}function nC(e){return e.actionKind===`cloud-api`?{available:!0,route:`cloud`,requiresPermissionGate:!1,title:`Cloud API route`,description:`Cloud and Command work routes through authenticated Forge Cloud APIs.`}:$S.has(e.actionKind)?tC(e.workSource)?e.workSource===`cloud-vm`&&e.executionRuntime===`cloud`?{available:!0,route:`cloud-vm`,requiresPermissionGate:!1,title:`Cloud VM route`,description:`Filesystem, terminal, git, and project writes run inside the user's Forge Cloud VM.`}:e.executionRuntime===`cloud`?{available:!0,route:`cloud`,requiresPermissionGate:!1,title:`Cloud work route`,description:`Cloud-scoped filesystem, terminal, git, and project writes run in the Forge Cloud runtime.`}:{available:!1,route:`blocked`,requiresPermissionGate:!1,title:`Open in Forge Cloud`,description:`Cloud projects must execute inside the Forge Cloud runtime. Local Desktop cannot run cloud project filesystem, terminal, git, or project-write actions.`}:eC(e.workSource)?e.surface===`desktop-local`||e.executionRuntime===`desktop-local`?{available:!0,route:`desktop-local`,requiresPermissionGate:!1,title:`Desktop local route`,description:`Local filesystem, terminal, git, and project writes run through the Desktop local backend.`}:e.executionRuntime===`dev-local-web`?{available:!0,route:`dev-local-web`,requiresPermissionGate:!1,title:`Dev local route`,description:`Local Web is a development-only projection and routes local actions through the dev server.`}:{available:!1,route:`blocked`,requiresPermissionGate:!1,title:`Switch to Desktop Local`,description:`Local projects must execute in the Desktop Local runtime. Forge Cloud cannot run local filesystem, terminal, git, or project-write actions.`}:{available:!1,route:`blocked`,requiresPermissionGate:!1,title:`Unknown work source`,description:`Forge cannot safely route local actions for this work source yet.`}:{available:!1,route:`blocked`,requiresPermissionGate:!1,title:`Unsupported route`,description:`Forge does not have a runtime route for this action yet.`}}var rC=`Ready to use. Your cloud project starts when you open the first thread.`;function iC(e){let t=nC({actionKind:`project-write`,surface:`cloud-official`,workSource:`cloud-vm`,executionRuntime:`cloud`});return{actionAuthority:`runtime`,surface:`cloud-official`,hostKind:`user-cloud-vm`,workSource:`cloud-vm`,executionRuntime:`cloud`,modelRuntime:`cloud`,linkState:`cloud-only`,workspaceIdentity:null,hideLocalPath:!0,label:`Cloud project`,description:e?`This project runs in your Forge Cloud VM.`:rC,actionRouteLabel:t.title,actionRouteDescription:t.description,actionRouteAvailable:t.available,requiresPermissionGate:t.requiresPermissionGate}}var aC=3e5;function oC(e,t,n=Date.now()){let r=new Map,i=new Map;for(let t of e){let e={cmmdOrganizationId:t.cmmdOrganizationId,cmmdProjectId:t.cmmdProjectId};r.set(lC(e),e),t.runtimeId!==null&&i.set(t.runtimeId,e)}for(let a of t){if(n-a.recordedAt>aC)continue;let t=r.get(lC({cmmdOrganizationId:a.cmmdOrganizationId,cmmdProjectId:a.cmmdProjectId})),o=e.find(e=>e.cmmdOrganizationId===a.cmmdOrganizationId&&e.cmmdProjectId===a.cmmdProjectId);t&&o?.runtimeId===a.previousCatalogRuntimeId&&o.registeredAt===a.catalogRegisteredAt&&!i.has(a.runtimeId)&&i.set(a.runtimeId,t)}return i}function sC(e){return e.environmentId??`cmmd-cloud-project:${e.cmmdOrganizationId}:${e.cmmdProjectId}`}function cC(e){return{environmentId:sC(e),workspaceRoot:e.workspaceRoot,resolvedRef:e.resolvedRef}}function lC(e){return`cloud:${e.cmmdOrganizationId}:${e.cmmdProjectId}`}function uC(e){let t=/^cloud:(\d+):(\d+)$/.exec(e??``);return t?{cmmdOrganizationId:Number(t[1]),cmmdProjectId:Number(t[2])}:null}function dC(e){return`cloud-runtime:${e}`}var fC=`cloud-unconnected:`;function pC(e,t,n=[]){let r=lC(e);return mC({id:xi.make(`${fC}${r}`),environmentId:Hr.make(sC(e)),name:e.projectName,cwd:``,repositoryIdentity:null,availability:void 0,defaultModelSelection:null,createdAt:void 0,updatedAt:void 0,scripts:[],projectKey:r,environmentPresence:`remote-only`,source:iC(e.runtimeId!==null),memberProjectRefs:t?[t]:[],remoteEnvironmentLabels:[],worktreeMembers:[],activeWorktreeKey:null,preConnectCloud:{runtimeId:e.runtimeId,cmmdOrganizationId:e.cmmdOrganizationId,cmmdProjectId:e.cmmdProjectId,cmmdEnvironmentId:e.cmmdEnvironmentId,registeredAt:e.registeredAt,projectName:e.projectName,githubRepoFullName:e.githubRepoFullName,workspaceRoot:e.workspaceRoot,iconUrl:e.iconUrl,icon:e.icon,status:e.status,removal:e.removal},cloudRemoval:e.removal},n)}function mC(e,t){if(t.length===0)return e;let n=[...e.memberProjectRefs],r=new Set(n.map(e=>`${e.environmentId}:${e.projectId}`));for(let e of t){let t=`${e.environmentId}:${e.projectId}`;r.has(t)||(r.add(t),n.push(e))}return n.length===e.memberProjectRefs.length?e:{...e,memberProjectRefs:n}}function hC(e,t,n,r){if(!e)return null;let i=t.find(t=>t.cmmdEnvironmentId===String(e));if(i)return{row:i,runtimeId:i.runtimeId,matchedByHandoff:!1};let a=vr(e).legacyRuntimeId;if(a){let e=t.find(e=>e.runtimeId===a);if(e)return{row:e,runtimeId:a,matchedByHandoff:!1};let i=oC(t,n,r).get(a);if(!i)return null;let o=t.find(e=>e.cmmdOrganizationId===i.cmmdOrganizationId&&e.cmmdProjectId===i.cmmdProjectId);return o?{row:o,runtimeId:a,matchedByHandoff:!0}:null}let o=t.find(t=>t.runtimeId===null&&sC(t)===String(e));return o?{row:o,runtimeId:null,matchedByHandoff:!1}:null}function gC(e,t=e.runtimeId){return{runtimeId:t,cmmdOrganizationId:e.cmmdOrganizationId,cmmdProjectId:e.cmmdProjectId,cmmdEnvironmentId:e.cmmdEnvironmentId,registeredAt:e.registeredAt,projectName:e.projectName,githubRepoFullName:e.githubRepoFullName,workspaceRoot:e.workspaceRoot,iconUrl:e.iconUrl,icon:e.icon,status:e.status,desiredState:e.desiredState}}function _C(e){return e.desiredState===`stopped`}var vC=15e3;function yC(e){return e===401||e===403}function bC(e){return typeof e!=`object`||!e?!1:e.retryable===!0}function xC(e){return yC(e.status)||e.attempt>=e.maxAttempts||e.status>=200&&e.status<300?!1:e.status>=500||e.status===409&&bC(e.body)}function SC(e,t){let n=e?.trim();if(!n)return null;if(/^-?\d+$/.test(n))return Number(n)*1e3;let r=Date.parse(n);return Number.isNaN(r)?null:r-t}function CC(e){let t=e=>Math.min(vC,Math.max(0,e)),n=SC(e.retryAfter,e.nowMs??Date.now());return t(n===null?300*2**Math.max(0,e.attempt-1):n)}var wC=6e4;function TC(e,t){if(!e||typeof e!=`object`)return t;let n=e.error;return typeof n==`string`&&n.trim().length>0?n:t}var EC=`CMMD returned an invalid Cloud runtime connection descriptor.`;function DC(e,t){let n=e[t];if(typeof n!=`string`||n.length===0)throw Error(EC);return n}function OC(e){if(!e||typeof e!=`object`)throw Error(EC);let t=e;return{httpBaseUrl:DC(t,`httpBaseUrl`),wsBaseUrl:DC(t,`wsBaseUrl`),bearerToken:DC(t,`bearerToken`),expiresAt:DC(t,`expiresAt`)}}async function kC(e){let t=Ji(`/api/cmmd/forge-runtimes/${encodeURIComponent(e.runtimeId)}/connect`),n=ta({method:`POST`,...e.signal?{signal:e.signal}:{},headers:{"Content-Type":`application/json`},body:JSON.stringify(e.organizationId===void 0?{}:{organizationId:e.organizationId})});for(let r=1;r<=8;r+=1){let i=await fetch(t,n),a=await i.json().catch(()=>null);if(i.ok)return OC(a);if(!xC({status:i.status,body:a,attempt:r,maxAttempts:8})){let e=NS(i.status,a)?`CMMD authentication expired while renewing the Cloud runtime connection. Sign in again.`:`CMMD could not renew the Cloud runtime connection (${i.status}).`;throw Object.assign(Error(TC(a,e)),{status:i.status,...MS(a)?{code:MS(a)}:{}})}await sl(CC({attempt:r,retryAfter:i.headers.get(`retry-after`)}),e.signal)}throw Error(`Cloud runtime connection retry budget was exhausted.`)}function AC(e,t){if(!e?.expiresAt)return!0;let n=Date.parse(e.expiresAt);return!Number.isFinite(n)||n<=t+wC}function jC(e){let t=e.requestDescriptor??kC,n=e.now??Date.now,r=e.initialDescriptor??null,i=null,a=!1,o=new AbortController,s=e=>ol(e,o.signal),c=()=>i||(i=s(t({runtimeId:e.runtimeId,...e.organizationId===void 0?{}:{organizationId:e.organizationId},signal:o.signal})).then(async t=>(await s(Promise.resolve(e.validateDescriptor?.(t))),await s(Promise.resolve(e.persistDescriptor?.(t))),await s(Promise.resolve()),r=t,a=!1,t)).then(e=>(i=null,e),e=>{throw i=null,e}),i);return{acquire:e=>{if(o.signal.aborted)return s(Promise.resolve(r));let t=e?.forceRefresh||a||AC(r,n())?c():Promise.resolve(r);return ol(s(t),e?.signal)},invalidate:()=>{a=!0},dispose:()=>{o.abort()}}}function MC(e){let t=e.runtimeId?.trim();if(t)return t;let n=vr(e.environmentId).legacyRuntimeId;if(n)return n;let r=ur().rows,i=Object.values(XS.getState().byRuntimeId);return hC(e.environmentId,r,i)?.runtimeId??null}function NC(e,t,n,r){let i=e,a=jC({runtimeId:t,...e.cmmdOrganizationId===void 0?{}:{organizationId:e.cmmdOrganizationId},...n===void 0?{}:{initialDescriptor:{httpBaseUrl:e.httpBaseUrl,wsBaseUrl:e.wsBaseUrl,bearerToken:n,expiresAt:e.runtimeTicketExpiresAt??null}},validateDescriptor:async e=>{await Fl({httpBaseUrl:e.httpBaseUrl,bearerToken:e.bearerToken})},persistDescriptor:async e=>{if(r&&!r())throw Error(`Saved environment changed while its connection was being acquired.`);let t={...ul(i),httpBaseUrl:e.httpBaseUrl,wsBaseUrl:Jr(e.wsBaseUrl),...e.expiresAt===null?{}:{runtimeTicketExpiresAt:e.expiresAt},lastConnectedAt:new Date().toISOString()};await Gn(t),await mr(t.environmentId),ir.getState().upsert(t),i=t}});return xl(e.environmentId,a),a}function PC(e){let t={wsBaseUrl:e.record.wsBaseUrl,httpBaseUrl:e.record.httpBaseUrl,bearerToken:e.bearerToken,expiresAt:e.record.runtimeTicketExpiresAt??null};return{acquire:()=>Promise.resolve(t)}}var FC=12e4,IC=3e4,LC=3e4;function RC(e){let t=e.expiresAt?Date.parse(e.expiresAt):NaN;if(!Number.isFinite(t))throw Error(`Cloud runtime authority descriptor has no valid expiry.`);return t}function zC(e){if(!e||typeof e!=`object`)return!1;let t=e.status;return t===401||t===403}function BC(e){let t=e.now??Date.now,n=e.renewalSkewMs??FC,r=!1,i=null,a=null,o=RC(e.initialDescriptor),s=()=>{i!==null&&(globalThis.clearTimeout(i),i=null)},c=a=>{if(r)return;s();let c=RC(a);o=c;let l=Math.max(t(),c-n);e.onState?.({kind:`scheduled`,expiresAt:new Date(c).toISOString(),renewAt:new Date(l).toISOString()}),i=globalThis.setTimeout(()=>{i=null,u().catch(()=>void 0)},Math.max(0,l-t()))},l=()=>{if(r)return null;let e=t()+LC;return e>=o?null:(i=globalThis.setTimeout(()=>{i=null,u().catch(()=>void 0)},LC),new Date(e).toISOString())},u=()=>{if(r)return Promise.resolve();if(a)return a;s(),e.onState?.({kind:`renewing`,expiresAt:new Date(o).toISOString()});let n=e.renew().then(async n=>{let i=RC(n);if(i<=t())throw Error(`Cloud runtime authority descriptor is already expired.`);r||(e.onState?.({kind:`ready`,expiresAt:new Date(i).toISOString(),renewedAt:new Date(t()).toISOString()}),c(n))}).catch(t=>{if(r)return;let n=zC(t);throw e.onState?.({kind:`error`,code:n?`authority_auth_rejected`:`authority_renewal_failed`,retryAt:n?null:l()}),t}).finally(()=>{a=null});return a=n,n};return c(e.initialDescriptor),{ensureLive:()=>o>t()+IC?Promise.resolve():u(),renewNow:u,dispose:()=>{r=!0,s()}}}function VC(){return new Date().toISOString()}function HC(e,t,n,r,i){return n()&&j.getState().ensure(e.environmentId),of(new ud(async()=>{let e=e=>Rl({wsBaseUrl:e.wsBaseUrl,httpBaseUrl:e.httpBaseUrl,bearerToken:e.bearerToken,...r?{runtimeTicket:e.bearerToken}:{}}),n=await t.acquire();try{return await e(n)}catch(n){if(!r||!Rn(n))throw n;return e(await t.acquire({forceRefresh:!0}))}},{trackGlobalConnection:!1,onAttempt:()=>{n()&&i.setConnecting(e.environmentId)},onOpen:()=>{n()&&i.setConnected(e.environmentId)},onError:i=>{r&&WS(i)&&t.invalidate?.(),n()&&j.getState().patch(e.environmentId,{connectionState:`error`,lastError:i,lastErrorAt:VC()})},onClose:a=>{r&&(a.code===1008||WS(a.reason))&&t.invalidate?.(),n()&&i.setDisconnected(e.environmentId,a.reason)}}))}async function UC(e,t,n,r,i,a,o){let s=await bl(t,o),[c,l]=await Promise.all([a?Promise.resolve(a):n.server.getConfig(),Fl({httpBaseUrl:s.httpBaseUrl,bearerToken:s.bearerToken,...o?{signal:o}:{}})]);return r()?(j.getState().patch(e.environmentId,{authState:l.authenticated?`authenticated`:`requires-auth`,descriptor:c.environment,serverConfig:c,role:l.authenticated?l.role??i??null:null}),WC(e,c,l.authenticated,r),!0):!1}function WC(e,t,n,r){if(!n||!r())return;let i=er(e.environmentId);i&&ir.getState().upsert({...i,lastAuthenticatedPullRequestCapability:t.environment.capabilities?.pullRequests===!0})}async function GC(e,t,n,r){let i=n.findConnection(e.environmentId);if(i)return i;let a=r?.registryExpectation??{kind:`existing-record`,record:e},o=()=>n.canCommit({record:e,generation:t,registryExpectation:a}),{isCmmdRuntime:s,targetProvider:c,initialTarget:l}=await KC(e,r,o);if(!o())throw qC(e.environmentId,c,s),Error(`Saved environment changed while its connection was being acquired.`);let u=r?.client??HC(e,c,o,s,n),d=YC({record:e,initialTarget:l,targetProvider:c,isCmmdRuntime:s,client:u,canCommit:o,dependencies:n});try{if(!await n.withMetadataTimeout(e,UC(e,c,u,o,r?.role??null,r?.serverConfig??null,r?.signal))||!o())throw Error(`Saved environment changed while its connection was being acquired.`);return n.registerConnection(d)}catch(t){throw s&&Cl(e.environmentId,c),o()&&n.setError(e.environmentId,t),await d.dispose().catch(()=>void 0),t}}async function KC(e,t,n){let r=dl(e)?MC(e):null,i=r!==null,a=await JC(e,t,i,n),o=i?NC(e,r,a??void 0,n):PC({record:e,bearerToken:a});try{return{isCmmdRuntime:i,targetProvider:o,initialTarget:await bl(o,t?.signal)}}catch(t){throw qC(e.environmentId,o,i),t}}function qC(e,t,n){n&&Cl(e,t)}async function JC(e,t,n,r){if(n)return t?.bearerToken;let i=t?.bearerToken??await nr(e.environmentId);if(i)return i;throw r()&&j.getState().patch(e.environmentId,{authState:`requires-auth`,role:null,connectionState:`disconnected`,lastError:`Saved environment is missing its saved credential. Pair it again.`,lastErrorAt:VC()}),Error(`Saved environment is missing its saved credential.`)}function YC(e){let{record:t,initialTarget:n,targetProvider:r,isCmmdRuntime:i,client:a,canCommit:o,dependencies:s}=e,c=xn({id:t.environmentId,label:t.label,source:`manual`,target:{httpBaseUrl:n.httpBaseUrl,wsBaseUrl:n.wsBaseUrl}}),l=i&&n.expiresAt?BC({initialDescriptor:{...n,expiresAt:n.expiresAt},renew:async()=>{let e=await r.acquire({forceRefresh:!0});return{...e,expiresAt:e.expiresAt??null}},onState:e=>{o()&&j.getState().patch(t.environmentId,{providerAuthority:e})}}):null;return ql({kind:`saved`,knownEnvironment:{...c,environmentId:t.environmentId},client:a,readiness:{bearerToken:n.bearerToken},tolerateReportedEnvironmentIdentity:i,refreshMetadata:async()=>{await UC(t,r,a,o)},...l?{ensureProviderAuthority:l.ensureLive,onDispose:l.dispose}:{},onConfigSnapshot:e=>{o()&&j.getState().patch(t.environmentId,{descriptor:e.environment,serverConfig:e})},...s.createHandlers(e=>{o()&&j.getState().patch(t.environmentId,{descriptor:e.environment})})})}var XC=class{readRecord;hasSameTarget;generations=new Map;acquisitions=new Map;constructor(e,t){this.readRecord=e,this.hasSameTarget=t}invalidate(e){this.generations.set(e,this.readGeneration(e)+1)}generationFor(e){return this.readGeneration(e)}isCurrent(e){if(this.readGeneration(e.record.environmentId)!==e.generation)return!1;let t=this.readRecord(e.record.environmentId);return e.registryExpectation.kind===`initial-add`?t===null||this.hasSameTarget(t,e.record):t!==null&&this.hasSameTarget(t,e.registryExpectation.record)}ensure(e,t){let n=this.readGeneration(e.environmentId),r=this.acquisitions.get(e.environmentId);if(r&&r.generation===n&&this.hasSameTarget(r.record,e))return r.promise;let i=t(e,n).finally(()=>{this.acquisitions.get(e.environmentId)?.promise===i&&this.acquisitions.delete(e.environmentId)});return this.acquisitions.set(e.environmentId,{generation:n,record:e,promise:i}),i}async sync(e){await rr(e.records);let t=new Map(e.records.map(e=>[e.environmentId,e]));for(let[e,n]of this.acquisitions){let r=t.get(e);(!r||!this.hasSameTarget(r,n.record))&&this.invalidate(e)}let n=new Set(t.keys());await Promise.all(e.connectedSavedEnvironmentIds.filter(e=>!n.has(e)).map(async t=>{this.invalidate(t),await e.disconnect(t)}))}clear(){this.generations.clear(),this.acquisitions.clear()}readGeneration(e){return this.generations.get(e)??0}};async function ZC(e,t,n){if(!dl(e))return n.ensureSavedEnvironmentConnection(e,t);let r=n.getGeneration(e.environmentId),i=()=>n.registry.isCurrent({record:e,generation:r,registryExpectation:t?.registryExpectation??{kind:`existing-record`,record:e}}),a=null;for(let r=0;r<8;r+=1){al(t?.signal);try{let r=await n.ensureSavedEnvironmentConnection(e,t);return await ol(r.ensureBootstrapped(),t?.signal),r}catch(o){a=o,await QC({error:o,attemptIndex:r,record:e,options:t,dependencies:n,canCommit:i})}}let o=a instanceof Error?a:Error(String(a));throw i()&&n.setRuntimeError(e.environmentId,o),o}async function QC(e){let{error:t,attemptIndex:n,record:r,options:i,dependencies:a,canCommit:o}=e;if(!o())throw t;if(await a.removeConnection(r.environmentId).catch(()=>!1),al(i?.signal),n>=7||!BS(t))throw o()&&a.setRuntimeError(r.environmentId,t),t;let s=VS(n);i?.onBootstrapRetry?.({attempt:n+2,maxAttempts:8,retryDelayMs:s,error:t}),o()&&j.getState().patch(r.environmentId,{connectionState:`connecting`,lastError:null,lastErrorAt:null}),await sl(s,i?.signal)}var $C=new Map,ew=new XC(e=>er(e),fl),tw=new Set,nw=Al({createPrimaryEnvironmentConnection:sw,syncSavedEnvironmentConnections:lw});function rw(){nw.notifyProviderInvalidation()}function iw(){for(let e of tw)e()}function aw(e){let t=$C.get(e.environmentId);if(t&&t!==e)throw Error(`Environment ${e.environmentId} already has an active connection.`);return $C.set(e.environmentId,e),iw(),e}async function ow(e){let t=$C.get(e);return t?($C.delete(e),Cl(e),ox(e),iw(),await t.dispose(),!0):!1}function sw(){return zx({readConnection:dw,registerConnection:aw})}async function cw(e,t){return $C.get(e.environmentId)||ew.ensure(e,(e,n)=>GC(e,n,{findConnection:e=>$C.get(e),registerConnection:aw,canCommit:ew.isCurrent.bind(ew),createHandlers:jx,withMetadataTimeout:US,setConnecting:Nx,setConnected:Px,setDisconnected:Ix,setError:Lx},t))}async function lw(e){await ew.sync({records:e,connectedSavedEnvironmentIds:[...$C.values()].filter(e=>e.kind===`saved`).map(e=>e.environmentId),disconnect:_w})}function uw(e){return tw.add(e),()=>{tw.delete(e)}}function dw(e){return $C.get(e)??null}function fw(e){return AS(e,{readConnection:dw,registerConnection:aw})}function pw(e){let t=dw(e);if(!t)throw Error(`No websocket client registered for environment ${e}.`);return t}function mw(){return sw()}async function hw(){return Bx({readConnection:dw,registerConnection:aw})}function gw(){return{readConnection:dw,removeConnection:ow,ensureSavedEnvironmentConnection:cw,ensureCmmdRuntimeSavedEnvironmentConnection:Sw,invalidate:e=>ew.invalidate(e),retireEnvironmentId:ax}}async function _w(e){await Kx(e,gw())}async function vw(e){await qx(e,gw())}async function yw(){return Wx({readConnection:dw,ensureCmmdRuntimeSavedEnvironmentConnection:Sw})}async function bw(e){await Jx(e,gw())}async function xw(e){return Yx(e,gw())}async function Sw(e,t){return ZC(e,t,{ensureSavedEnvironmentConnection:cw,getGeneration:e=>ew.generationFor(e),registry:ew,removeConnection:ow,setRuntimeError:Lx})}async function Cw(e){await $C.get(e)?.ensureBootstrapped()}async function ww(e){let t=$C.get(e);if(t?.ensureProviderAuthority){await t.ensureProviderAuthority();return}if(Sl(e))throw Error(`Cloud runtime provider authority is not available.`)}function Tw(e){return nw.start(e)}zb({applyEvent:Ox,readConnection:dw,subscribeConnections:uw}),Cy({notifyProviderInvalidation:rw,readQueryClient:()=>nw.readActiveService()?.queryClient??null,setRuntimeError:Lx});function Ew(e){return{environmentId:e.environmentId,threadId:e.threadId}}function Dw(e){return{draftId:e}}function Ow(e){return!e.environmentId||!e.threadId?null:C(e.environmentId,e.threadId)}function kw(e){return e.environmentId&&e.threadId?{kind:`server`,threadRef:C(e.environmentId,e.threadId)}:e.draftId?{kind:`draft`,draftId:e.draftId}:null}function Aw(e){let t=(0,A.c)(8),n,r;t[0]===e?(n=t[1],r=t[2]):({className:n,...r}=e,t[0]=e,t[1]=n,t[2]=r);let i;t[3]===n?i=t[4]:(i=Ca(`relative overflow-hidden rounded-sm bg-muted [--skeleton-highlight:--alpha(var(--color-white)/64%)] after:absolute after:inset-0 after:animate-skeleton after:bg-[linear-gradient(120deg,transparent_40%,var(--skeleton-highlight),transparent_60%)] motion-reduce:after:content-none dark:[--skeleton-highlight:--alpha(var(--color-white)/4%)]`,n),t[3]=n,t[4]=i);let a;return t[5]!==r||t[6]!==i?(a=(0,k.jsx)(`div`,{className:i,"data-slot":`skeleton`,...r}),t[5]=r,t[6]=i,t[7]=a):a=t[7],a}function jw(e,t){if(!De(e)||!De(t))return t;let n={...e};for(let[e,r]of Object.entries(t)){if(r===void 0)continue;let t=n[e];n[e]=De(t)&&De(r)?jw(t,r):r}return n}function Mw(e,t){return un(t).pipe(ln,sn(e))}function Nw(e){return{issues:e.issues,providers:e.providers,settings:e.settings}}var Pw=[],Fw=[],Iw=[],Lw=e=>e?.availableEditors??Pw,Rw=e=>e?.keybindings??Fw,zw=e=>e?.keybindingsConfigPath??null,Bw=e=>e?.observability??null,Vw=e=>e?.providers??Iw,Hw=e=>e?.settings??Li,Uw=Mw(`server-welcome`,null),Ww=Mw(`server-config`,null),Gw=Mw(`server-config-updated`,null),Kw=Mw(`server-providers-updated`,null);function qw(){return cn.get(Ww)}function Jw(){return cn.get(Gw)}function Yw(e){iT(e),aT({providers:e.providers}),oT(Nw(e),`snapshot`)}function Xw(e){switch(e.type){case`snapshot`:Yw(e.config);return;case`keybindingsUpdated`:{let t=qw();if(!t)return;let n={...t,issues:e.payload.issues,keybindings:e.payload.keybindings};iT(n),oT(Nw(n),e.type);return}case`providerStatuses`:Zw(e.payload);return;case`settingsUpdated`:Qw(e.payload.settings);return;case`environmentUpdated`:$w(e.payload.environment);return}}function Zw(e){let t=qw();if(aT(e),!t)return;let n={...t,providers:e.providers};iT(n),oT(Nw(n),`providerStatuses`)}function Qw(e){let t=qw();if(!t)return;let n={...t,settings:e};iT(n),oT(Nw(n),`settingsUpdated`)}function $w(e){let t=qw();if(yr()?.environmentId===e.environmentId&&vn(e),!t)return;let n={...t,environment:e};iT(n),oT(Nw(n),`environmentUpdated`)}function eT(e){cn.set(Uw,e)}function tT(e){return sT(Gw,t=>{e(t.payload,t.source)})}function nT(e){let t=!1,n=[e.subscribeLifecycle(e=>{e.type===`welcome`&&eT(e.payload)}),e.subscribeConfig(e=>{Xw(e)})];return qw()===null&&e.getConfig().then(e=>{t||qw()!==null||Yw(e)}).catch(()=>void 0),()=>{t=!0;for(let e of n)e()}}var rT=1;function iT(e){cn.set(Ww,e)}function aT(e){cn.set(Kw,e)}function oT(e,t){cn.set(Gw,{id:rT++,payload:e,source:t})}function sT(e,t){return cn.subscribe(e,e=>{e!==null&&t(e)},{immediate:!0})}function cT(e,t){let n=(0,O.useRef)(t);n.current=t;let r=(0,O.useCallback)(e=>{e!==null&&n.current(e)},[]);_a(e,r,{immediate:!0})}function lT(){return ma(Ww)}function uT(){return ma(Ww,Hw)}function dT(){return ma(Ww,Vw)}function fT(){return ma(Ww,Rw)}function pT(){return ma(Ww,Lw)}function mT(){return ma(Ww,zw)}function hT(){return ma(Ww,Bw)}function gT(e){cT(Uw,e)}function _T(){return ma(Uw)}function vT(e){cT(Gw,e)}var yT=`[CLIENT_SETTINGS]`,bT=new Set,xT=li,ST=!1,CT=null,wT=`pending`;function TT(e){wT!==e&&(wT=e,ET())}function ET(){for(let e of bT)e()}function DT(){return xT}function OT(e){xT=e,ET()}function kT(e){return bT.add(e),AT(),()=>{bT.delete(e)}}async function AT(){if(ST)return;if(CT)return CT;let e=(async()=>{try{let e=await tr();e&&OT(e),ST=!0,TT(`ready`)}catch(e){console.error(`${yT} hydrate failed`,e),TT(`failed`)}})().finally(()=>{CT===e&&(CT=null)});return CT=e,CT}var jT=new Set(ei(Ii.fields));function MT(e){let t={},n={};for(let[r,i]of Object.entries(e))jT.has(r)?t[r]=i:n[r]=i;return{serverPatch:t,clientPatch:n}}function NT(){return AT()}var PT=Promise.resolve();function FT(e){let t=PT.then(async()=>{if(await NT(),RT()!==`ready`)throw Error(`${yT} hydration failed; refusing to persist settings.`);return e()});return PT=t.then(()=>void 0,()=>void 0),t}function IT(e){return FT(async()=>{let t=e(DT());await or(t),OT(t)})}function LT(){return(0,O.useSyncExternalStore)(kT,RT,RT)}function RT(){return wT}function zT(){return(0,O.useSyncExternalStore)(kT,VT,BT)}function BT(){return!1}function VT(){return ST}function HT(){let e=zT(),t=WT(UT);return e&&t}function UT(e){return e.legacySidebarEnabled}function WT(e){let t=uT(),n=(0,O.useSyncExternalStore)(kT,DT,()=>li),r=(0,O.useMemo)(()=>({...t,...n}),[n,t]);return(0,O.useMemo)(()=>e?e(r):r,[r,e])}function GT(){let e=(0,A.c)(2),t=KT,n;e[0]===Symbol.for(`react.memo_cache_sentinel`)?(n=()=>{t(Tr)},e[0]=n):n=e[0];let r=n,i;return e[1]===Symbol.for(`react.memo_cache_sentinel`)?(i={updateSettings:t,resetSettings:r},e[1]=i):i=e[1],i}function KT(e){let{serverPatch:t,clientPatch:n}=MT(e);if(Object.keys(t).length>0){let e=qw();e&&Qw(jw(e.settings,t)),mw().client.server.updateSettings(t)}Object.keys(n).length>0&&FT(async()=>{let e={...DT(),...n};OT(e),await or(e).catch(JT)}).catch(qT)}function qT(e){console.error(`${yT} persist failed`,e)}function JT(e){console.error(`${yT} persist failed`,e)}function YT(e){return t=>e?pn(t,e.environmentId).projectById[e.projectId]:void 0}function XT(e){let t,n,r;return i=>{let a=e(i);if(!a)return;let o=pn(i,a.environmentId);return r&&t===o&&n===a.threadId?r:(t=o,n=a.threadId,r=Pn(o,a.threadId),r)}}function ZT(e){return XT(()=>e)}function QT(e){return t=>{if(e)return pn(t,e.environmentId).threadSubscriptionErrorById[e.threadId]}}function $T(e){let t,n,r,i;return a=>{if(!e){i=void 0,t=void 0,n=void 0,r=void 0;return}let o=pn(a,e.environmentId).threadShellById,s=o[e.threadId];if(!s){i=void 0,t=void 0,n=void 0,r=void 0;return}let c=s.kind===`master`?s.id:s.parentThreadId,l=c==null?void 0:o[c];if(i&&t===o&&n===s&&r===l)return i;let u=[];if(c!=null){for(let e of Object.values(o))e.kind===`worker`&&e.parentThreadId===c&&u.push(e);u.sort((e,t)=>e.createdAt.localeCompare(t.createdAt))}return t=o,n=s,r=l,i={you:s,master:l,workers:u},i}}function eE(e,t){let n=new Set(e.filter(e=>e.bootstrapped).map(e=>String(e.ref.environmentId))),r=e.filter(e=>{let r=t?.(e.ref.environmentId)??null;return r===null||!n.has(r)}),i=r.filter(e=>e.bootstrapped);return(i.find(e=>e.active)??i.at(-1)??r.find(e=>e.active)??r[0])?.ref}function tE(e,t){return XT(n=>{if(e)return eE(Object.entries(n.environmentStateById).filter(([,t])=>t.threadShellById[e]).map(([t,r])=>({ref:{environmentId:t,threadId:e},active:n.activeEnvironmentId===t,bootstrapped:r.bootstrapComplete})),t)})}var nE,rE=[];function iE(e){return nE===e.environmentStateById&&rE!==void 0?rE:(nE=e.environmentStateById,rE=Object.values(e.environmentStateById).flatMap(e=>Object.values(e.sidebarThreadSummaryById)),rE)}function aE(e){let t=e.payload&&typeof e.payload==`object`?e.payload:null,n=t?.plan;if(!Array.isArray(n))return null;let r=[];for(let e of n){if(!e||typeof e!=`object`)continue;let t=e;if(typeof t.step!=`string`)continue;let n=t.status===`completed`||t.status===`inProgress`?t.status:`pending`;r.push({step:t.step,status:n})}return r.length===0?null:{createdAt:e.createdAt,turnId:e.turnId,...t&&`explanation`in t?{explanation:t.explanation}:{},steps:r}}function oE(e){let t=new Map;return e.map(e=>{let n=t.get(e.step)??0;return t.set(e.step,n+1),{key:`${e.step}:${n}`,step:e}})}function sE(e,t){let n=new Map,r;for(let e of t){let t=aE(e),i=Date.parse(e.createdAt);if(!(!t||Number.isNaN(i))){r??=i;for(let{key:e,step:r}of oE(t.steps)){let t=n.get(e)??{};r.status===`inProgress`&&t.startedAt===void 0&&(t.startedAt=i),r.status===`completed`&&t.completedAt===void 0&&(t.completedAt=i),n.set(e,t)}}}let i=new Map,a=r;for(let[e,t]of[...n.entries()].toSorted((e,t)=>(e[1].completedAt??1/0)-(t[1].completedAt??1/0))){let n=t.completedAt,r=t.startedAt??a;n!==void 0&&(r!==void 0&&n>r&&i.set(e,n-r),a=n)}return{...e,steps:oE(e.steps).map(({key:e,step:t})=>{if(t.status!==`completed`)return t;let n=i.get(e);return n===void 0?t:Object.assign({},t,{durationMs:n})})}}function cE(e){let t=uE(e?.data),n=uE(t?.item),r=uE(n?.result),i=uE(n?.input),a=dE(e?.itemType),o=dE(e?.detail),s=[e?.command,n?.command,i?.command,r?.command,t?.command,a===`command_execution`&&o?lE(o).output:null];for(let e of s){let t=xE(e);if(t)return{command:t,rawCommand:SE(e,t)}}return{command:null,rawCommand:null}}function lE(e){let t=e.trim(),n=/^(?<output>[\s\S]*?)(?:\s*<exited with exit code (?<code>\d+)>)\s*$/i.exec(t);if(!n?.groups)return{output:t.length>0?t:null};let r=Number.parseInt(n.groups.code??``,10),i=n.groups.output?.trim()??``;return{output:i.length>0?i:null,...Number.isInteger(r)?{exitCode:r}:{}}}function uE(e){return e&&typeof e==`object`?e:null}function dE(e){if(typeof e!=`string`)return null;let t=e.trim();return t.length>0?t:null}function fE(e){let t=e.trim();if(t.startsWith(`'`)&&t.endsWith(`'`)||t.startsWith(`"`)&&t.endsWith(`"`)){let e=t.slice(1,-1).trim();return e.length>0?e:t}return t}function pE(e){let t=fE(e);if(t.length===0)return null;let n=t.replace(/\\/g,`/`).split(`/`).at(-1)?.trim()??``;return n.length>0?n.toLowerCase():null}function mE(e){let t=e.trim();if(t.length===0)return null;if(t.startsWith(`"`)||t.startsWith(`'`)){let e=t.charAt(0),n=t.indexOf(e,1);return n<=0?null:{executable:t.slice(0,n+1),rest:t.slice(n+1).trim()}}let n=t.search(/\s/);return n<0?{executable:t,rest:``}:{executable:t.slice(0,n),rest:t.slice(n).trim()}}var hE=[{executables:[`pwsh`,`pwsh.exe`,`powershell`,`powershell.exe`],wrapperFlagPattern:/(?:^|\s)-command\s+/i},{executables:[`cmd`,`cmd.exe`],wrapperFlagPattern:/(?:^|\s)\/c\s+/i},{executables:[`bash`,`sh`,`zsh`],wrapperFlagPattern:/(?:^|\s)-(?:l)?c\s+/i}];function gE(e){return hE.find(t=>t.executables.includes(e))}function _E(e,t){let n=t.exec(e);if(!n)return null;let r=e.slice(n.index+n[0].length).trim();if(r.length===0)return null;let i=r[0];if((i===`'`||i===`"`)&&!r.endsWith(i))return null;let a=fE(r);return a.length>0?a:null}function vE(e){let t=mE(e);if(!t||t.rest.length===0)return e;let n=pE(t.executable);if(!n)return e;let r=gE(n);return r?_E(t.rest,r.wrapperFlagPattern)??e:e}function yE(e){return/[\s"'`]/.test(e)?`"${e.replace(/"/g,`\\"`)}"`:e}function bE(e){let t=dE(e);if(t)return t;if(!Array.isArray(e))return null;let n=[];for(let t of e){let e=dE(t);e!==null&&n.push(e)}return n.length===0?null:n.map(e=>yE(e)).join(` `)}function xE(e){let t=bE(e);return t?vE(t):null}function SE(e,t){let n=bE(e);return!n||t===null||n===t?null:n}function CE(e){return typeof e==`object`&&e&&!Array.isArray(e)?e:null}function wE(e){return typeof e==`string`&&e.trim().length>0?e:null}function TE(e){let t=wE(e);if(t)return t;let n=Array.isArray(e)?e:null,r=CE(e)?.content,i=wE(r);if(i)return i;let a=n??(Array.isArray(r)?r:null);if(!a)return null;let o=a.flatMap(e=>{let t=wE(e)??wE(CE(e)?.text);return t?[t]:[]});return o.length>0?o.join(`
|
|
17
|
+
`):null}function EE(e){let t=CE(e),n=CE(t?.item),r=CE(n?.result),i=CE(t?.rawOutput),a=[wE(i?.stdout),wE(i?.stderr)].filter(e=>e!==null),o=Array.isArray(t?.content)?t.content.flatMap(e=>{let t=CE(e),n=CE(t?.content),r=t?.type===`content`?wE(n?.text):null;return r?[r]:[]}).join(`
|
|
18
18
|
`):null,s=[n?.aggregatedOutput,r?.content,t?.rawOutput,i?.content,a.length>0?a.join(`
|
|
19
|
-
`):null,i?.output,o,t?.result];for(let e of s){let t=
|
|
20
|
-
`)}function R(e){return typeof e==`object`&&e&&!Array.isArray(e)?e:void 0}var cD={};function lD(e){return typeof e==`string`&&e.trim().length>0}function uD(e){let t=R(e);if(!t||!lD(t.requestId)||!R(t.answers)||!R(t.attachmentsByQuestionId))return!1;let n=R(t.questionTextById);if(t.questionTextById!==void 0&&!n)return!1;if(n){for(let e of Object.values(n))if(typeof e!=`string`)return!1}for(let e of Object.values(t.attachmentsByQuestionId)){if(!Array.isArray(e))return!1;for(let t of e){let e=R(t);if(!e||!lD(e.id)||!lD(e.name))return!1}}return!0}function dD(e,t){if(typeof e==`string`)return t.get(e)??e;if(Array.isArray(e))return e.map(e=>dD(e,t));let n=R(e);return n&&`answers`in n?{...n,answers:dD(n.answers,t)}:e}function fD(e,t){let n=t.map(e=>typeof e==`string`?e.trim():``);return n.length>0&&n.every(Boolean)?JSON.stringify([e,n.sort()]):void 0}function pD(e){return e&&typeof e==`object`?e:null}function mD(e){if(typeof e!=`string`)return null;let t=e.trim();return t.length>0?t:null}function hD(e,t){let n=pD(e.item),r=e.toolName??e.tool??n?.tool??t;if(typeof r!=`string`)return{};let i=r.split(/__|[./]/).at(-1)?.replace(/[_\s]/g,``).toLowerCase();if(!i||!/^(askuserquestion|requestuserinput(?:async)?|askquestion|question)$/.test(i))return{};let a=pD(e.input??e.rawInput??pD(e.state)?.input??n?.arguments),o=a?.questions??pD(a?.params)?.questions;return Array.isArray(o)?{input:{questions:o.map(e=>{let t=pD(e);return{question:mD(t?.question??t?.question_text??t?.prompt??t?.title)}})}}:{}}function gD(e){let t=new Set;for(let n of e){if(n.kind!==`user-input.answer-submitted`||!n.turnId)continue;let e=R(n.payload),r=Object.values(R(e?.questionTextById)??cD),i=fD(n.turnId,r);i&&t.add(i)}if(t.size===0)return e;let n=new Set;for(let r of e){if(!r.kind.startsWith(`tool.`)||!r.turnId)continue;let e=R(r.payload);if(typeof e?.toolCallId!=`string`)continue;let i=hD(R(e.data)??{},e.title).input;if(!i)continue;let a=fD(r.turnId,i.questions.map(e=>e.question));a&&t.has(a)&&n.add(JSON.stringify([r.turnId,e.toolCallId]))}return e.filter(e=>{let t=R(e.payload),r=t?.toolCallId;return e.tone===`error`||/^(failed|declined|stopped|cancelled)$/.test(String(t?.status))||!e.kind.startsWith(`tool.`)||typeof r!=`string`||!n.has(JSON.stringify([e.turnId,r]))})}function _D(e){let t=new Map;for(let n of e){if(n.kind!==`user-input.requested`&&n.kind!==`user-input.resolved`&&n.kind!==`user-input.answer-submitted`)continue;let e=R(n.payload)?.requestId;if(typeof e!=`string`||!e)continue;let r=t.get(e)??[];r.push(n),t.set(e,r)}let n=new Map;for(let[e,r]of t){let t=r.map(e=>R(e.payload)),i=new Map,a=new Map;for(let e of t){for(let[t,n]of Object.entries(R(e.questionTextById)??cD))a.set(t,n);for(let t of Array.isArray(e.questions)?e.questions:[]){let e=R(t);typeof e?.id==`string`&&(i.set(e.id,e),typeof e.question==`string`&&a.set(e.id,e.question))}}let o=Object.fromEntries(a),s=R(R(r.findLast(e=>e.kind===`user-input.answer-submitted`&&R(R(e.payload)?.answers))?.payload)?.answers)??t.map(e=>R(e.answers)).findLast(Boolean)??{},c=Object.fromEntries(Object.entries(s).map(([e,t])=>{let n=i.get(e)?.options,r=new Map;for(let e of Array.isArray(n)?n:[]){let t=R(e);typeof t?.label==`string`&&(typeof t.value==`string`&&r.set(t.value,t.label),r.set(t.label,t.label))}return[e,dD(t,r)]})),l=Object.fromEntries(t.flatMap(e=>Object.entries(R(e.attachmentsByQuestionId)??cD))),u={requestId:e,questionTextById:o,answers:c,attachmentsByQuestionId:l};if(!uD(u))continue;let d=Object.keys(c).length>0||Object.keys(l).length>0;for(let e of r)n.set(e,null);n.set(r[0],{...r[0],kind:`user-input.answer-submitted`,tone:`tool`,summary:d?`User input submitted`:r.some(e=>e.kind===`user-input.resolved`)?`User input dismissed`:`User input requested`,payload:u})}return gD(e.flatMap(e=>{let t=n.get(e);return t===null?[]:[t??e]}))}function vD(e){if(typeof e==`string`)return e;if(Array.isArray(e))return e.map(vD).filter(Boolean).join(`, `);let t=R(e);return t?vD(t.answers):``}function yD(e){let t=Object.values(e.answers).map(vD).filter(Boolean),n=Object.values(e.attachmentsByQuestionId).flat().map(e=>e.name);return(t.length>0?t.join(` · `):n.length>0?n.join(`, `):Object.values(e.questionTextById??{}).join(` · `)).replace(/\s+/g,` `).trim()}function bD(e){return Object.values(e.answers).some(vD)||Object.values(e.attachmentsByQuestionId).some(e=>e.length>0)}function xD(e){return typeof e==`object`&&e&&!Array.isArray(e)?e:void 0}function SD(e,t){if(typeof e!=`string`)return;let n=e.trim();return n&&n.length<=t?n:void 0}function CD(e){let t=SD(e,4096);if(t)try{let e=new URL(t);return e.protocol===`http:`||e.protocol===`https:`||e.protocol===`data:`?e.href:void 0}catch{return}}function wD(e){let t=SD(e,4096);if(t)try{let e=new URL(t);return e.protocol===`http:`||e.protocol===`https:`?e.href:void 0}catch{return}}function TD(e){let t=xD(e),n=SD(t?.appId,512);if(t?._tag===`app-id`&&n&&/^[A-Za-z0-9._-]+$/u.test(n))return{_tag:`app-id`,appId:n};let r=SD(t?.displayName,160);if(t?._tag===`display-name`&&r)return{_tag:`display-name`,displayName:r}}function ED(e){let t=xD(e);if(t?._tag===`website`){let e=wD(t.pageUrl),n=CD(t.faviconUrl),r=CD(t.faviconUrlDark);if(e)return{_tag:`website`,pageUrl:e,...n?{faviconUrl:n}:{},...r?{faviconUrlDark:r}:{}}}if(t?._tag===`native-app`){let e=TD(t.app);if(e)return{_tag:`native-app`,app:e}}if(t?._tag===`themed-logo`){let e=CD(t.logoUrl),n=CD(t.logoUrlDark);if(e)return{_tag:`themed-logo`,logoUrl:e,...n?{logoUrlDark:n}:{}}}}function DD(e){let t=xD(e),n=SD(t?.key,512),r=SD(t?.name,160),i=t?.kind;if(!n||!r||i!==`browser`&&i!==`computer`&&i!==`integration`)return;let a=ED(t?.icon);return{key:n,name:r,kind:i,...a?{icon:a}:{}}}function OD(e){let t=xD(e),n=t?.toolSurface===`browser`||t?.toolSurface===`computer`?t.toolSurface:void 0,r=ED(t?.toolIcon),i=DD(t?.toolSource);return{...n?{toolSurface:n}:{},...r?{toolIcon:r}:{},...i?{toolSource:i}:{}}}function kD(e,t,n){return e===t||e.endsWith(`.${t}`)?!0:n!==void 0&&e.split(`.`).includes(n)}function AD(e){let t;try{t=new URL(e)}catch{return null}if(t.protocol!==`https:`&&t.protocol!==`http:`)return null;let n=t.hostname.toLowerCase();if(kD(n,`github.com`,`github`)){let e=/^\/([^/]+\/[^/]+)\/pull\/(\d+)(?:\/|$)/u.exec(t.pathname);if(e)return jD(n,e)}let r=/^\/([^/]+(?:\/[^/]+)+)\/pulls\/(\d+)(?:\/|$)/u.exec(t.pathname);if(r){let e=jD(n,r);return e===null?null:{...e,authority:t.host.toLowerCase()}}let i=/^\/([^/]+(?:\/[^/]+)+)\/-\/merge_requests\/(\d+)(?:\/|$)/u.exec(t.pathname);return i?jD(n,i):kD(n,`bitbucket.org`,`bitbucket`)?jD(n,/^\/([^/]+\/[^/]+)\/pull-requests\/(\d+)(?:\/|$)/u.exec(t.pathname)):kD(n,`dev.azure.com`)||n.endsWith(`.visualstudio.com`)?jD(n,/^\/((?:[^/]+\/)*_git\/[^/]+)\/pullrequest\/(\d+)(?:\/|$)/u.exec(t.pathname)):null}function jD(e,t){let n=t?.[1],r=Number(t?.[2]);return n&&Number.isSafeInteger(r)&&r>0?{host:e,repository:n.toLowerCase(),number:r}:null}function MD(e){return e.replace(/\s+(?:complete|completed)\s*$/i,``).trim()}var ND={link_pull_request:[`Link`,`Linking`,`Linked`,`a pull request`],unlink_pull_request:[`Unlink`,`Unlinking`,`Unlinked`,`a pull request`],list_thread_pull_requests:[`Check`,`Checking`,`Checked`,`linked pull requests`],orchestrator_capabilities:[`Get`,`Getting`,`Got`,`orchestration capabilities`],delegate_task:[`Delegate`,`Delegating`,`Delegated`,`a child task`],task_status:[`Get`,`Getting`,`Got`,`delegated task status`],task_cancel:[`Cancel`,`Canceling`,`Canceled`,`delegated task`],schedule_task:[`Schedule`,`Scheduling`,`Scheduled`,`a recurring task`],list_scheduled_tasks:[`List`,`Listing`,`Listed`,`scheduled tasks`],update_scheduled_task:[`Update`,`Updating`,`Updated`,`a scheduled task`],delete_scheduled_task:[`Delete`,`Deleting`,`Deleted`,`a scheduled task`],create_threads:[`Create`,`Creating`,`Created`,`T3 threads`],t3_thread_start:[`Start`,`Starting`,`Started`,`a T3 thread`],t3_thread_list:[`List`,`Listing`,`Listed`,`T3 threads`],t3_thread_read:[`Read`,`Reading`,`Read`,`a T3 thread`],t3_thread_send:[`Send`,`Sending`,`Sent`,`to a T3 thread`],t3_thread_wait:[`Wait`,`Waiting`,`Waited`,`for a T3 thread`],t3_thread_interrupt:[`Interrupt`,`Interrupting`,`Interrupted`,`a T3 thread`],t3_worktree_handoff:[`Hand off`,`Handing off`,`Handed off`,`thread to a git worktree`],t3_worktree_status:[`Get`,`Getting`,`Got`,`thread worktree status`],preview_status:[`Get`,`Getting`,`Got`,`preview browser status`],preview_open:[`Open`,`Opening`,`Opened`,`a page in the preview browser`],preview_navigate:[`Navigate`,`Navigating`,`Navigated`,`the preview browser`],preview_snapshot:[`Take a snapshot of`,`Taking a snapshot of`,`Took a snapshot of`,`the preview page`],preview_click:[`Click`,`Clicking`,`Clicked`,`in the preview browser`],preview_press:[`Press`,`Pressing`,`Pressed`,`a key in the preview browser`],preview_type:[`Type`,`Typing`,`Typed`,`in the preview browser`],preview_scroll:[`Scroll`,`Scrolling`,`Scrolled`,`the preview browser`],preview_resize:[`Resize`,`Resizing`,`Resized`,`the preview browser`],preview_evaluate:[`Evaluate`,`Evaluating`,`Evaluated`,`script in the preview browser`],preview_wait_for:[`Wait`,`Waiting`,`Waited`,`for the preview page`],preview_set_appearance:[`Set`,`Setting`,`Set`,`preview browser appearance`],preview_recording_start:[`Start`,`Starting`,`Started`,`recording the preview browser`],preview_recording_stop:[`Stop`,`Stopping`,`Stopped`,`recording the preview browser`],device_list:[`List`,`Listing`,`Listed`,`simulators and emulators`],device_open:[`Open`,`Opening`,`Opened`,`a device in the Device panel`],device_screenshot:[`Take a screenshot of`,`Taking a screenshot of`,`Took a screenshot of`,`the device`],device_close:[`Close`,`Closing`,`Closed`,`a device`]},PD={link_pull_request:`link-pr`,unlink_pull_request:`unlink-pr`,list_thread_pull_requests:`list-prs`};function FD(e,t,n){if(!e)return null;let r=MD(e).replace(/^(?:mcp__(?:t3-code|t3_code|t3code)__|(?:t3-code|t3_code|t3code)(?:[.:/]|\s*·\s*))/i,``);if(!Object.hasOwn(ND,r))return null;let[i,a,o,s]=ND[r],c=t===`inProgress`?a:t===`completed`?o:t===`failed`?`Failed to ${i.toLowerCase()}`:t===`declined`?`Declined to ${i.toLowerCase()}`:t===`stopped`?`Stopped ${a.toLowerCase()}`:a,l=Object.hasOwn(PD,r)?PD[r]:void 0,u=RD(n),d=RD(u?.arguments)??RD(u?.input)??RD(u?.rawInput),f=(typeof d?.url==`string`?AD(d.url):null)?.number??d?.number;return{displayName:`${c} ${l!==void 0&&l!==`list-prs`&&typeof f==`number`&&Number.isSafeInteger(f)&&f>0?`PR #${f}`:s}`,icon:l===void 0?r.startsWith(`preview_`)?`browser`:r.startsWith(`device_`)?`device`:`t3-code`:`pull-request`,...l===void 0?{}:{action:l}}}function ID(e,t){return e===`failed`||e===`declined`||e===`stopped`?e:t||e===`inProgress`?`inProgress`:`completed`}function LD(e,t){let n=e.toolLifecycleStatus??t,r=e.toolData;if(typeof r==`object`&&r){if(`server`in r&&typeof r.server==`string`&&`tool`in r&&typeof r.tool==`string`)return FD(`${r.server}.${r.tool}`,n,r);if(`toolName`in r&&typeof r.toolName==`string`)return FD(r.toolName,n,r)}return FD(e.toolTitle,n,r)??FD(e.label,n,r)}function RD(e){return typeof e==`object`&&e&&!Array.isArray(e)?e:null}function zD(e){let t=RD(e);switch(t?.status){case`pending`:case`running`:case`waiting`:return`inProgress`;case`cancelled`:case`interrupted`:return`stopped`;case`idle`:return t.taskType===`subagent_batch`?`stopped`:void 0;case`inProgress`:case`completed`:case`failed`:case`declined`:case`stopped`:return t.status;default:return}}function BD(e){return e.tone===`tool`||e.tone===`thinking`||e.tone===`error`||e.command!==void 0&&e.command.trim().length>0||e.requestKind!==void 0||e.itemType!==void 0&&Gr(e.itemType)}function VD(e){let t=e.toLowerCase();return t.includes(`file not found`)||t.includes(`no files found`)||t.includes(`enoent`)||t.includes(`no such file or directory`)||t.includes(`no such file`)||t.includes(`commandnotfoundexception`)||t.includes(`command not found`)||t.includes(`cannot find path`)&&t.includes(`because it does not exist`)||t.includes(`is not recognized`)&&t.includes(`the term '`)||t.includes(`is not recognized as the name of a cmdlet`)||t.includes(`a parameter cannot be found that matches parameter name`)||/<exited with exit code\s+[1-9]\d*\s*>/i.test(e)||/exit(?:ed)? with exit code\s+[1-9]\d*/i.test(e)||/exit code\s*[:\s]\s*[1-9]\d*\b/i.test(e)}function HD(e,t){if(e.tone===`error`||e.toolLifecycleStatus===`failed`||e.toolLifecycleStatus===`declined`)return!0;if(!BD(e))return!1;let n=t?[e.detail,e.command].filter(Boolean).join(`
|
|
21
|
-
`):e.detail??``;return n.length>0&&VD(n)}function UD(e){return HD(e,!0)}function WD(e){return HD(e,!1)}function GD(e){return BD(e)&&!UD(e)&&e.tone!==`thinking`&&e.toolLifecycleStatus!==`inProgress`&&e.toolLifecycleStatus!==`stopped`}function KD(e){let t=e.taskId??``,n=t.indexOf(`:wf:`);return n===-1?e.agentSpawn?.workflowId?`wf:${e.agentSpawn.workflowId}`:e.isWorkflowCoordinator?`wf:${t}`:e.turnId?`direct:${e.turnId}`:`direct:task:${t}`:`wf:${t.slice(0,n)}`}function qD(e){if(e.sourceActivityKind===`tool.updated`||e.sourceActivityKind===`tool.completed`)return e.toolCallId?`tool:${e.turnId??`no-turn`}:${e.toolCallId}`:void 0}function JD(e){let t=[],n=new Map,r=new Map,i=new Map;for(let a of e){if(a.taskId!==void 0&&!a.isBackgroundTask&&(a.sourceActivityKind===`task.started`||a.sourceActivityKind===`task.progress`||a.sourceActivityKind===`task.completed`)&&a.taskId!==void 0){let e=r.get(a.taskId),i=e??KD(a);e===void 0&&r.set(a.taskId,i);let o=i.startsWith(`wf:`)?i.slice(3):null,s=n.get(i);if(s!==void 0){let e=t[s],n=e.agentSpawn?.agentTaskIds.includes(a.taskId)?e.agentSpawn.agentTaskIds:[...e.agentSpawn?.agentTaskIds??[],a.taskId];t[s]={...XD(e,a),id:e.id,createdAt:e.createdAt,turnId:e.turnId??null,...e.taskId===void 0?{}:{taskId:e.taskId},label:e.label,agentSpawn:{workflowId:o,agentTaskIds:n}};continue}n.set(i,t.length),t.push({...a,agentSpawn:{workflowId:o,agentTaskIds:[a.taskId]}});continue}let e=qD(a);if(e!==void 0){let n=i.get(e),r=n===void 0?void 0:t[n];if(n!==void 0&&r&&YD(r,a)){t[n]=XD(r,a);continue}i.delete(e)}let o=t.at(-1);if(o&&YD(o,a)){let e=t.length-1,n=qD(o);n!==void 0&&i.delete(n);let r=XD(o,a);t[e]=r;let s=qD(r);s!==void 0&&i.set(s,e);continue}t.push(a),e!==void 0&&i.set(e,t.length-1)}return t}function YD(e,t){return e.sourceActivityKind!==`tool.updated`&&e.sourceActivityKind!==`tool.completed`||t.sourceActivityKind!==`tool.updated`&&t.sourceActivityKind!==`tool.completed`||e.turnId!==t.turnId||e.sourceActivityKind===`tool.completed`?!1:e.collapseKey!==void 0&&e.collapseKey===t.collapseKey||e.toolCallId!==void 0&&t.toolCallId===void 0&&e.itemType===t.itemType&&MD(e.toolTitle??e.label)===MD(t.toolTitle??t.label)}function XD(e,t){let n=ZD(e.changedFiles,t.changedFiles),r=t.detail??e.detail,i=t.viewedImagePath??e.viewedImagePath,a=t.command??e.command,o=t.rawCommand??e.rawCommand,s=t.toolTitle??e.toolTitle,c=t.toolSurface??e.toolSurface,l=t.toolIcon??e.toolIcon,u=t.toolSource??e.toolSource,d=t.itemType??e.itemType,f=t.requestKind??e.requestKind,p=t.collapseKey??e.collapseKey,m=t.toolCallId??e.toolCallId,h=t.toolLifecycleStatus??e.toolLifecycleStatus,g=t.toolData??e.toolData;return{...e,...t,...r?{detail:r}:{},...i?{viewedImagePath:i}:{},...a?{command:a}:{},...o?{rawCommand:o}:{},...n.length>0?{changedFiles:n}:{},...s?{toolTitle:s}:{},...c?{toolSurface:c}:{},...l?{toolIcon:l}:{},...u?{toolSource:u}:{},...d?{itemType:d}:{},...f?{requestKind:f}:{},...p?{collapseKey:p}:{},...m?{toolCallId:m}:{},...h===void 0?{}:{toolLifecycleStatus:h},...g===void 0?{}:{toolData:g}}}function ZD(e,t){let n=[...e??[],...t??[]];return n.length===0?[]:[...new Set(n)]}function QD(e){if(e.taskId&&(e.sourceActivityKind===`task.progress`||e.sourceActivityKind===`task.completed`))return`task${e.taskId}`;if(e.sourceActivityKind!==`tool.updated`&&e.sourceActivityKind!==`tool.completed`)return;if(e.toolCallId)return`tool:${e.turnId??`no-turn`}:${e.toolCallId}`;let t=MD(e.toolTitle??e.label),n=e.detail?.trim()??``,r=e.itemType??``;if(t.length!==0||n.length!==0||r.length!==0)return[r,t,n].join(``)}function $D(e){let t=aO(e?.data);return oO(e?.toolCallId)??oO(t?.toolCallId)}function eO(e){switch(e){case`command_execution_approval`:case`exec_command_approval`:return`command`;case`file_read_approval`:return`file-read`;case`file_change_approval`:case`apply_patch_approval`:return`file-change`;default:return null}}function tO(e){return e?.requestKind===`command`||e?.requestKind===`file-read`||e?.requestKind===`file-change`?e.requestKind:eO(e?.requestType)??void 0}function nO(e,t,n){let r=oO(n);!r||t.has(r)||(t.add(r),e.push(r))}function rO(e,t,n,r){if(r>4||t.length>=12)return;if(Array.isArray(e)){for(let i of e)if(rO(i,t,n,r+1),t.length>=12)return;return}let i=aO(e);if(i){nO(t,n,i.path),nO(t,n,i.filePath),nO(t,n,i.relativePath),nO(t,n,i.filename),nO(t,n,i.newPath),nO(t,n,i.oldPath);for(let e of[`item`,`result`,`input`,`data`,`changes`,`files`,`edits`,`patch`,`patches`,`operations`])if(e in i&&(rO(i[e],t,n,r+1),t.length>=12))return}}function iO(e){let t=[],n=new Set;return rO(aO(e?.data),t,n,0),t}function aO(e){return e&&typeof e==`object`?e:null}function oO(e){if(typeof e!=`string`)return null;let t=e.trim();return t.length>0?t:null}var sO=new WeakMap;function cO(e){return!(e.agentSpawn!==void 0||!BD(e)||UD(e)||GD(e))}function lO(e){let t=sO.get(e);if(t)return t;let n=e.payload&&typeof e.payload==`object`?e.payload:null,r=sE(n),i=iO(n),a=GE(n),o=OD(n),s=e.kind===`task.progress`||e.kind===`task.completed`,c=s&&typeof n?.summary==`string`&&n.summary.length>0?n.summary:null,l=s&&!c&&typeof n?.detail==`string`&&n.detail.length>0?n.detail:null,u=c||l,d=s?!l&&n&&typeof n.detail==`string`&&n.detail.length>0?cE(n.detail).output:null:zE(n,a??e.summary),f=s?null:$D(n),p={id:e.id,createdAt:e.createdAt,turnId:e.turnId,label:u||e.summary,tone:e.kind===`task.progress`?`thinking`:e.tone,sourceActivityKind:e.kind};if(e.kind===`user-input.answer-submitted`){let e=n&&uD(n)?n:null;e&&(p.questionAnswer={requestId:e.requestId,questionTextById:e.questionTextById,answers:e.answers,attachmentsByQuestionId:e.attachmentsByQuestionId})}let m=AE(n),h=tO(n),g=oO(aO(n?.data)?.imagePath);if(d)p.detail=d;else if(e.kind===`runtime.error`||e.kind===`runtime.warning`){let t=kE(n,e.summary);t&&(p.detail=t)}if(g&&(p.viewedImagePath=g),r.command&&(p.command=r.command),r.rawCommand&&(p.rawCommand=r.rawCommand),i.length>0&&(p.changedFiles=i),a&&(p.toolTitle=a),o.toolSurface&&(p.toolSurface=o.toolSurface),o.toolIcon&&(p.toolIcon=o.toolIcon),o.toolSource&&(p.toolSource=o.toolSource),m===`mcp_tool_call`){let e=aO(n?.data),t=typeof e?.toolName==`string`?e.item??e:e?.item;t!==void 0&&(p.toolData=t)}m&&(p.itemType=m),h&&(p.requestKind=h),f&&(p.toolCallId=f);let _=zD(n);!_&&e.kind===`tool.completed`&&(_=`completed`),_&&(p.toolLifecycleStatus=_);let v=e.kind===`task.started`||e.kind===`task.progress`||e.kind===`task.completed`;v&&typeof n?.taskId==`string`&&n.taskId.length>0&&(p.taskId=n.taskId),v&&typeof n?.role==`string`&&n.role.length>0&&(p.agentRole=n.role),v&&(n?.taskType===`local_workflow`||typeof n?.workflowName==`string`&&n.workflowName.length>0)&&(p.isWorkflowCoordinator=!0),v&&n&&n.agentKind!==`agent`&&(p.isBackgroundTask=!0);let y=XE(n);if(y)p.githubConfirmation=y,p.tone=`approval`,p.label=`GitHub action needs approval`,p.toolTitle=eD(y.operation),p.detail=tD(y);else{let e=ZE(n);e&&(p.githubActionRequired=e,p.tone=`approval`,p.label=nD(e.action),p.toolTitle=`GitHub setup required`,p.detail=iD(e))}let b=QD(p);return b&&(p.collapseKey=b),sO.set(e,p),p}var uO=new Set([`tool.started`,`task.started`,`context-window.updated`,`text-generation.usage`,`worktree.stage`,`launch.agent-starting`,`turn.terminal-status`]);function dO(e){return uO.has(e.kind)||e.summary===`Checkpoint captured`}function fO(e,t){return!t.latestTurnId||e.turnId===t.latestTurnId||pO(e)?!0:mO(e,t.latestTurnStartedAt)}function pO(e){return e.kind.startsWith(`worktree.`)||e.kind.startsWith(`setup-script.`)}function mO(e,t){return e.turnId!==null||e.tone!==`error`||t===null?!1:e.createdAt>=t}function hO(e){return e.agentKind===`agent`}function gO(e){let t=e.payload&&typeof e.payload==`object`?e.payload:null;return!t||typeof t.taskId!=`string`?!1:hO(t)}function _O(e){let t=e.payload&&typeof e.payload==`object`?e.payload:null;return t?e.kind===`task.started`||e.kind===`task.progress`||e.kind===`task.updated`||e.kind===`task.completed`?typeof t.agentId==`string`&&t.agentId.trim().length>0||t.timelineBypass===!0?!(e.kind!==`task.updated`&&typeof t.taskId==`string`&&hO(t)):!1:t.timelineBypass===!0||typeof t.agentId==`string`&&t.agentId.trim().length>0:!1}function vO(){if(typeof window>`u`)return!1;try{return window.localStorage.getItem(`forge:debug-mode`)===`true`}catch{return!1}}function yO(e){if(e.kind!==`tool.updated`&&e.kind!==`tool.completed`)return!1;let t=e.payload&&typeof e.payload==`object`?e.payload:null;return typeof t?.detail==`string`&&t.detail.startsWith(`ExitPlanMode:`)}function bO(e,t,n){let r=vO(),i={latestTurnId:t,latestTurnStartedAt:n??null},a=[...e].toSorted(xO),o=new Set;for(let e of a)if((e.kind===`task.started`||e.kind===`task.progress`||e.kind===`task.completed`)&&gO(e)){let t=oO(aO(e.payload)?.toolUseId);t&&o.add(t)}let s=[];for(let e of _D(a)){if(!fO(e,i)||!(e.kind===`task.started`&&gO(e))&&dO(e)||e.kind===`task.started`&&!gO(e)||e.kind===`task.updated`||e.kind===`tool.progress`||e.kind===`turn.plan.updated`||!r&&OE(e)||yO(e)||_O(e))continue;let t=lO(e);if(e.kind===`tool.updated`&&t.itemType===`collab_agent_tool_call`&&t.toolLifecycleStatus===`inProgress`&&t.tone!==`error`){let t=aO(aO(e.payload)?.data)?.toolName;if(t===`Agent`||t===`Task`)continue}(e.kind===`tool.updated`||e.kind===`tool.completed`)&&t.toolCallId&&o.has(t.toolCallId)&&t.tone!==`error`&&t.toolLifecycleStatus!==`failed`||s.push(t)}return JD(s).map(({sourceActivityKind:e,collapseKey:t,isWorkflowCoordinator:n,isBackgroundTask:r,...i})=>i)}function xO(e,t){if(e.sequence!==void 0&&t.sequence!==void 0){if(e.sequence!==t.sequence)return e.sequence-t.sequence}else if(e.sequence!==void 0)return 1;else if(t.sequence!==void 0)return-1;let n=e.createdAt.localeCompare(t.createdAt);if(n!==0)return n;let r=SO(e.kind)-SO(t.kind);return r===0?e.id.localeCompare(t.id):r}function SO(e){return e.endsWith(`.started`)||e===`tool.started`?0:e.endsWith(`.progress`)||e.endsWith(`.updated`)?1:e.endsWith(`.completed`)||e.endsWith(`.resolved`)?2:1}function CO(e){return{id:e.id,kind:`message`,createdAt:e.createdAt,message:e}}function wO(e){return{id:e.id,kind:`proposed-plan`,createdAt:e.createdAt,proposedPlan:e}}function TO(e){return{id:e.id,kind:`work`,createdAt:e.createdAt,entry:e}}function EO(e,t){return e.createdAt.localeCompare(t.createdAt)}function DO(e){switch(e.kind){case`message`:return 0;case`proposed-plan`:return 1;case`work`:return 2}}function OO(e,t){let n=EO(e,t);return n===0?DO(e)<=DO(t):n<0}function kO(e,t){if(e===t)return!0;if(t.length<e.length)return!1;for(let n=0;n<e.length;n+=1)if(e[n]!==t[n])return!1;return!0}function AO(e,t){if(t.length===0)return[...e];let n=e.at(-1),r=!0;for(let e=1;e<t.length;e+=1)if(EO(t[e-1],t[e])>0){r=!1;break}if(r&&(n===void 0||OO(n,t[0])))return[...e,...t];let i=[],a=0,o=0;for(;a<e.length||o<t.length;){let n=e[a],r=t[o];n!==void 0&&(r===void 0||OO(n,r))?(i.push(n),a+=1):r!==void 0&&(i.push(r),o+=1)}return i}var jO=e=>e===`assistant`||e===`reasoning`;function MO(e,t){if(!jO(e.role)||e.role!==t.role||!e.streaming||!t.streaming)return!1;let{text:n,updatedAt:r,...i}=e,{text:a,updatedAt:o,...s}=t;return $m(i,s)}function NO(e,t){if(e.length!==t.messages.length)return null;let n=new Map;for(let[r,i]of e.entries()){let e=t.messages[r];if(i!==e){if(!MO(e,i))return null;n.set(e,i)}}return n.size===0?t.entries:t.entries.map(e=>{let t=e.kind===`message`?n.get(e.message):void 0;return t?CO(t):e})}function PO(e,t,n,r=null){if(r!==null&&r.proposedPlans.length===t.length&&r.workEntries.length===n.length&&kO(r.proposedPlans,t)&&kO(r.workEntries,n)){let i=NO(e,r);if(i!==null)return{messages:e,proposedPlans:t,workEntries:n,entries:i}}let i=new Set(n.flatMap(e=>e.questionAnswer?[`async-answer:${e.questionAnswer.requestId}`]:[])),a=e=>e.role!==`user`||!i.has(e.id);if(r!==null&&!r.entries.some(e=>e.kind===`message`&&!a(e.message))&&kO(r.messages,e)&&kO(r.proposedPlans,t)&&kO(r.workEntries,n)){let i=e.slice(r.messages.length).filter(a).map(CO),o=t.slice(r.proposedPlans.length).map(wO),s=n.slice(r.workEntries.length).map(TO),c=[...i,...o,...s].toSorted(EO);return{messages:e,proposedPlans:t,workEntries:n,entries:AO(r.entries,c)}}let o=e.filter(a).map(CO),s=t.map(wO),c=n.map(TO);return{messages:e,proposedPlans:t,workEntries:n,entries:[...o,...s,...c].toSorted(EO)}}var FO=[{value:`codex`,label:`Codex`,available:!0},{value:`claudeAgent`,label:`Claude`,available:!0},{value:`cmmd`,label:`CMMD`,available:!0},{value:`ollama`,label:`Ollama`,available:!1},{value:`cursor`,label:`Cursor`,available:!1}];function IO(e){if(!Number.isFinite(e)||e<0)return`0ms`;if(e<1e3)return`${Math.max(1,Math.round(e))}ms`;if(e<1e4)return`${(e/1e3).toFixed(1)}s`;if(e<6e4)return`${Math.round(e/1e3)}s`;let t=Math.floor(e/6e4),n=Math.round(e%6e4/1e3);return n===0?`${t}m`:n===60?`${t+1}m`:`${t}m ${n}s`}function LO(e,t){if(!t)return null;let n=Date.parse(e),r=Date.parse(t);return Number.isNaN(n)||Number.isNaN(r)||r<n?null:IO(r-n)}function RO(e,t){return!e?.startedAt||!e.completedAt?!1:!t||t.orchestrationStatus!==`running`}function zO(e,t,n){let r=t?.orchestrationStatus===`running`?t.activeTurnId??null:null;return r===null?RO(e,t)?n:e?.startedAt??n:e?.turnId===r?e.startedAt??n:n}function BO(e){let t=e?.toLowerCase();return t?t.includes(`stale pending approval request`)||t.includes(`stale pending user-input request`)||t.includes(`unknown pending approval request`)||t.includes(`unknown pending permission request`)||t.includes(`unknown pending user-input request`):!1}function VO(e){let t=new Map,n=[...e].toSorted(xO);for(let e of n){let n=e.payload&&typeof e.payload==`object`?e.payload:null,r=n&&typeof n.requestId==`string`?kr.make(n.requestId):null,i=n&&(n.requestKind===`command`||n.requestKind===`file-read`||n.requestKind===`file-change`)?n.requestKind:n?eO(n.requestType):null,a=n&&typeof n.detail==`string`?n.detail:void 0;if(e.kind===`approval.requested`&&r&&i){t.set(r,{requestId:r,requestKind:i,createdAt:e.createdAt,...a?{detail:a}:{}});continue}if(e.kind===`approval.resolved`&&r){t.delete(r);continue}if(e.kind===`provider.approval.respond.failed`&&r&&BO(a)){t.delete(r);continue}}return[...t.values()].toSorted((e,t)=>e.createdAt.localeCompare(t.createdAt))}function HO(e){let t=e?.questions;if(!Array.isArray(t))return null;let n=t.map(e=>{if(!e||typeof e!=`object`)return null;let t=e;if(typeof t.id!=`string`||typeof t.header!=`string`||typeof t.question!=`string`||!Array.isArray(t.options))return null;let n=t.options.map(e=>{if(!e||typeof e!=`object`)return null;let t=e;return typeof t.label!=`string`||typeof t.description!=`string`?null:{label:t.label,description:t.description}}).filter(e=>e!==null);return n.length===0?null:{id:t.id,header:t.header,question:t.question,options:n,multiSelect:t.multiSelect===!0}}).filter(e=>e!==null);return n.length>0?n:null}function UO(e){let t=new Map,n=[...e].toSorted(xO);for(let e of n){let n=e.payload&&typeof e.payload==`object`?e.payload:null,r=n&&typeof n.requestId==`string`?kr.make(n.requestId):null,i=n&&typeof n.detail==`string`?n.detail:void 0;if(e.kind===`user-input.requested`&&r){let i=HO(n);if(!i)continue;t.set(r,{requestId:r,createdAt:e.createdAt,questions:i});continue}if(e.kind===`user-input.resolved`&&r){t.delete(r);continue}e.kind===`provider.user-input.respond.failed`&&r&&BO(i)&&t.delete(r)}return[...t.values()].toSorted((e,t)=>e.createdAt.localeCompare(t.createdAt))}function WO(e,t){if(!t)return null;let n=[...e].toSorted(xO),r=null;for(let e of n){let t=ZE(e.payload&&typeof e.payload==`object`?e.payload:null);t&&(r={request:t,turnId:e.turnId})}return!r||r.turnId!==t?null:r.request}function GO(e,t){let n=[...e].toSorted(xO),r=n.filter(e=>e.kind===`turn.plan.updated`),i=(t?r.findLast(e=>e.turnId===t):void 0)??r.at(-1)??null;if(!i)return null;let a=iE(i);if(!a)return null;let o=r.filter(e=>e.turnId===i.turnId),s=o.findLastIndex(e=>iE(e)===null),c=oE(a,o.slice(s+1)),l=i.turnId!==null&&n.some(e=>e.kind===`turn.completed`&&e.turnId===i.turnId&&xO(i,e)<0);return{...c,steps:l?c.steps.map(e=>e.status===`inProgress`?{...e,status:`completed`}:e):c.steps}}function KO(e,t){if(t){let n=[...e].filter(e=>e.turnId===t).toSorted((e,t)=>e.updatedAt.localeCompare(t.updatedAt)||e.id.localeCompare(t.id)).at(-1);if(n)return ck(n)}let n=[...e].toSorted((e,t)=>e.updatedAt.localeCompare(t.updatedAt)||e.id.localeCompare(t.id)).at(-1);return n?ck(n):null}function qO(e){let t=e.threads.find(t=>t.id===e.threadId)?.proposedPlans??[];if(!e.latestTurnSettled){let t=e.latestTurn?.sourceProposedPlan;if(t){let n=e.threads.find(e=>e.id===t.threadId)?.proposedPlans.find(e=>e.id===t.planId);if(n)return ck(n)}}return KO(t,e.latestTurn?.turnId??null)}function JO(e){return e!==null&&e.implementedAt===null}function YO(e,t){return t?e.some(e=>e.turnId===t&&e.tone===`tool`):!1}var XO=new WeakMap;function ZO(e,t){if(e.role!==`assistant`)return[];let n=$O(e.text,{workEntries:t,createdAt:e.createdAt});if(!n)return[];let r=XO.get(e),i=`${e.id}:github-confirmation:${n.confirmationId}`;if(r&&r[0]?.id===i)return r;let a=[{id:i,kind:`work`,createdAt:e.createdAt,entry:{id:i,createdAt:e.createdAt,label:`GitHub action needs approval`,detail:tD(n),tone:`approval`,toolTitle:eD(n.operation),githubConfirmation:n}}];return XO.set(e,a),a}function QO(e,t,n,r){let i=PO(e,t,n,r),a=e.flatMap(e=>ZO(e,n));if(a.length===0)return i;let o=new Set(i.entries.map(e=>e.id)),s=a.filter(e=>!o.has(e.id));return s.length===0?i:{...i,entries:[...i.entries,...s].toSorted((e,t)=>e.createdAt.localeCompare(t.createdAt))}}function $O(e,t){if(!e.includes(`confirm_github_tool`))return null;let n=ik(e,/\b(?:New confirmation id|Confirmation id):\s*`?([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})`?/i)??null,r=/\bRepo(?: to create)?:\s*(private|public|internal)\s+`?([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+)`?/i.exec(e);if(!n)return null;let i=ek(e,n,t);if(i)return i;if(!r)return null;let a=r[1]?.toLowerCase(),o=r[2],s=r[3];return!o||!s?null:{confirmationId:n,toolName:`forge_github_create_repository`,operation:`create_repository`,request:{owner:o,name:s,visibility:a}}}function ek(e,t,n){if(!tk(e))return null;let r=nk(n?.workEntries??[],n?.createdAt,`forge_github_refresh_credentials`)?.request,i=r?rk(r.cwd):null;return i?{confirmationId:t,toolName:`forge_github_refresh_credentials`,operation:`refresh_credentials`,request:{cwd:i}}:null}function tk(e){return/\bforge_github_refresh_credentials\b/i.test(e)||/\bcredential refresh\b/i.test(e)||/\brefresh(?:ing)? GitHub credentials\b/i.test(e)}function nk(e,t,n){for(let r of e.toReversed()){if(t!==void 0&&r.createdAt>t)continue;let e=r.githubConfirmation;if(e?.toolName===n)return e}return null}function rk(e){if(typeof e!=`string`)return null;let t=e.trim();return t.length>0?t:null}function ik(e,t){return t.exec(e)?.[1]??null}function ak(e){let t=[...e].toSorted((e,t)=>e.completedAt.localeCompare(t.completedAt)),n={};for(let e=0;e<t.length;e+=1){let r=t[e];r&&(n[r.turnId]=e+1)}return n}function ok(e){return!e||e.status===`closed`?`disconnected`:e.status===`connecting`?`connecting`:e.status===`running`?`running`:`ready`}function sk(e,t){if(t===`disconnected`||t===`connecting`)return null;for(let t of e.toReversed())if(t.kind===`work`&&t.entry.githubConfirmation)return t.entry.githubConfirmation;return null}function ck(e){return{id:e.id,createdAt:e.createdAt,updatedAt:e.updatedAt,turnId:e.turnId,planMarkdown:e.planMarkdown,implementedAt:e.implementedAt,implementationThreadId:e.implementationThreadId}}function lk(e){let t=e.browser,n=t?{openSession:t.openSession,listSessions:t.listSessions,closeSession:t.closeSession,getSession:t.getSession,command:t.command,clearBrowsingData:t.clearBrowsingData,attachDisplay:t.attachDisplay,addDisplayIceCandidate:async e=>{await t.addDisplayIceCandidate(e)},onEvent:(e,n)=>t.onEvent(e,n)}:void 0;return{...n?{browser:n}:{},attachments:{createUploadUrl:t=>e.attachments.createUploadUrl(t),delete:t=>e.attachments.delete(t)},computer:{input:t=>e.computer.input(t)},threadDevRuntime:{get:t=>e.threadDevRuntime.get(t),allocatePort:t=>e.threadDevRuntime.allocatePort(t),release:t=>e.threadDevRuntime.release(t)},devTunnel:{register:t=>e.devTunnel.register(t),unregister:t=>e.devTunnel.unregister(t),list:t=>e.devTunnel.list(t)},terminal:{open:t=>e.terminal.open(t),write:t=>e.terminal.write(t),resize:t=>e.terminal.resize(t),signal:t=>e.terminal.signal(t),clear:t=>e.terminal.clear(t),restart:t=>e.terminal.restart(t),close:t=>e.terminal.close(t),onEvent:t=>e.terminal.onEvent(t)},projects:{searchContents:e.projects.searchContents,searchEntries:e.projects.searchEntries,readFile:e.projects.readFile,writeFile:e.projects.writeFile},workspace:{environmentPreflight:e.workspace.environmentPreflight,listDirectory:e.workspace.listDirectory,ensureScratch:e.workspace.ensureScratch},shell:{openInEditor:t=>e.shell.openInEditor(t)},git:{pull:e.git.pull,refreshStatus:e.git.refreshStatus,onStatus:(t,n,r)=>e.git.onStatus(t,n,r),listBranches:e.git.listBranches,createWorktree:e.git.createWorktree,removeWorktree:e.git.removeWorktree,createBranch:e.git.createBranch,checkout:e.git.checkout,init:e.git.init,resolvePullRequest:e.git.resolvePullRequest,preparePullRequestThread:e.git.preparePullRequestThread},pullRequests:{list:t=>e.pullRequests.list(t),listStats:t=>e.pullRequests.listStats(t),detail:t=>e.pullRequests.detail(t),activity:t=>e.pullRequests.activity(t),threadComments:t=>e.pullRequests.threadComments(t),diffFileContents:t=>e.pullRequests.diffFileContents(t),runAction:t=>e.pullRequests.runAction(t),update:t=>e.pullRequests.update(t),comment:t=>e.pullRequests.comment(t),updateComment:t=>e.pullRequests.updateComment(t),submitReview:t=>e.pullRequests.submitReview(t),replyToThread:t=>e.pullRequests.replyToThread(t),setThreadResolution:t=>e.pullRequests.setThreadResolution(t),setReaction:t=>e.pullRequests.setReaction(t),invalidate:t=>e.pullRequests.invalidate(t),reviewerCandidates:t=>e.pullRequests.reviewerCandidates(t),requestReviewers:t=>e.pullRequests.requestReviewers(t)},orchestration:{dispatchCommand:e.orchestration.dispatchCommand,searchThreads:e.orchestration.searchThreads,getTurnDiff:e.orchestration.getTurnDiff,getFullThreadDiff:e.orchestration.getFullThreadDiff,subscribeShell:(t,n)=>e.orchestration.subscribeShell(t,n),subscribeThread:(t,n,r)=>e.orchestration.subscribeThread(t,n,r)}}}function uk(e){if(typeof window>`u`||!e)return;let t=dw(e);return t?lk(t.client):void 0}function dk(e){let t=(0,A.c)(4),n;t[0]===e?n=t[1]:(n=()=>dw(e),t[0]=e,t[1]=n);let r=(0,O.useSyncExternalStore)(uw,n,fk),i,a;return t[2]===r?a=t[3]:(a=r?lk(r.client):void 0,t[2]=r,t[3]=a),i=a,i}function fk(){return null}function pk(e){let t=uk(e);if(!t)throw Error(`Environment API not found for environment ${e}`);return t}var mk=[`preview`,`terminal`,`canvas`,`diff`,`plan`,`task`,`simulator`,`display`,`agents`,`file`,`files`,`pull-request`],hk={isOpen:!1,isMaximized:!1,activeSurfaceId:null,surfaces:[]};function gk(e){return e===null?{id:`browser:new`,kind:`preview`,resourceId:null}:{id:`browser:${e}`,kind:`preview`,resourceId:e}}function _k(e,t,n,r=`execution-intent`){return{id:`file:${e}`,kind:`file`,relativePath:e,revealLine:t,revealRequestId:n,readPolicy:r}}function vk(e){let t=[e.provider,e.environmentId,e.repositoryLinkId??``,e.projectId,e.host.toLowerCase(),e.repository,String(e.number)].map(e=>encodeURIComponent(e)).join(`:`);return{...e,id:`pull-request:${t}`,kind:`pull-request`}}function yk(e){return e===`diff`?{id:`diff`,kind:`diff`,turnId:null,filePath:null}:{id:e,kind:e}}var bk=`workspace:pull-requests`;function xk(e){return typeof e==`object`&&!!e}function Sk(e){return typeof e==`string`&&mk.includes(e)}function Ck(e){return typeof e==`number`&&Number.isFinite(e)?Math.max(1,Math.trunc(e)):null}function wk(e){return typeof e==`number`&&Number.isSafeInteger(e)&&e>=0?e:0}function Tk(e){let t=e.relativePath;return typeof t!=`string`||t.length===0?null:{id:`file:${t}`,kind:`file`,relativePath:t,revealLine:Ck(e.revealLine),revealRequestId:wk(e.revealRequestId),readPolicy:e.readPolicy===`connected-only`?`connected-only`:`execution-intent`}}function Ek(e){let t=e.resourceId;return t==null?{id:`browser:new`,kind:`preview`,resourceId:null}:typeof t!=`string`||t.length===0?null:{id:`browser:${t}`,kind:`preview`,resourceId:t}}function Dk(e){let t=e.turnId,n=e.filePath,r=typeof t==`string`&&t.length>0?Vr.make(t):null;return{id:`diff`,kind:`diff`,turnId:r,filePath:r&&typeof n==`string`&&n.length>0?n:null}}var Ok=new Set([`github`,`gitlab`,`azure-devops`,`bitbucket`,`unknown`]);function kk(e){return typeof e==`string`&&e.length>0}function Ak(e){return e===null||typeof e==`string`}function jk(e){return e===void 0||Ak(e)}function Mk(e){let t=e.provider,n=e.environmentId,r=e.repositoryLinkId,i=e.projectId,a=e.host,o=e.repository,s=Ck(e.number),c=e.title;return![kk(t)&&Ok.has(t),kk(n),Ak(r),kk(i),kk(a),kk(o),s!==null,jk(c)].every(Boolean)||!kk(t)||!kk(n)?null:vk({provider:t,environmentId:Hr.make(n),repositoryLinkId:r,projectId:xi.make(i),host:a,repository:o,number:s,...typeof c==`string`||c===null?{title:c}:{}})}function Nk(e){let t=e.label;if(typeof t!=`string`)return;let n=t.trim();return n.length>0?n:void 0}function Pk(e){if(!xk(e)||!Sk(e.kind))return null;let t=e.kind,n=t===`file`?Tk(e):t===`preview`?Ek(e):t===`diff`?Dk(e):t===`pull-request`?Mk(e):{id:t,kind:t};if(n===null)return null;let r=Nk(e);return r===void 0?n:{...n,label:r}}function Fk(e){let t=[],n=new Set;for(let r of Array.isArray(e)?e:[]){let e=Pk(r);!e||n.has(e.id)||(n.add(e.id),t.push(e))}return t}function Ik(e){if(!xk(e))return null;let t=Fk(e.surfaces);if(t.length===0)return null;let n=e.activeSurfaceId,r=t.some(e=>e.id===n),i=typeof n==`string`&&r?n:t[0]?.id??null;return{isOpen:e.isOpen===!0,activeSurfaceId:i,surfaces:t}}function Lk(e){if(!xk(e)||!xk(e.byThreadKey))return{byThreadKey:{}};let t={};for(let[n,r]of Object.entries(e.byThreadKey)){if(n===bk)continue;let e=Ik(r);e&&(t[n]=e)}return{byThreadKey:t}}var Rk=`forge:right-panel-state`,zk=3,Bk=e=>e===`workspace:pull-requests`;function Vk(e){return`draft:${e}`}function Hk(e){return e.startsWith(`draft:`)}function Uk(e){return e==null||!Number.isFinite(e)?null:Math.max(1,Math.trunc(e))}var Wk=(e,t,n=!0)=>({...e,isOpen:!0,surfaces:e.surfaces.some(e=>e.id===t.id)?e.surfaces:[...e.surfaces,t],activeSurfaceId:n?t.id:e.activeSurfaceId});function Gk(e,t){if(t.length===0){let{label:t,...n}=e;return n}return{...e,label:t}}var z=(e,t,n)=>{let r=e[t]??hk,i=n(r);if(!i.isOpen&&i.activeSurfaceId===null&&i.surfaces.length===0){if(!(t in e))return e;let{[t]:n,...r}=e;return r}return i===r?e:{...e,[t]:i}},Kk=wa()(Wf(e=>({byThreadKey:{},open:(t,n)=>e(e=>({byThreadKey:z(e.byThreadKey,t,e=>Wk(e,e.surfaces.find(e=>e.kind===n)??yk(n)))})),openBrowser:(t,n)=>e(e=>({byThreadKey:z(e.byThreadKey,t,e=>{let t=n?e.surfaces.filter(e=>e.id!==`browser:new`):e.surfaces;return Wk({...e,surfaces:t},gk(n))})})),revealBrowser:t=>e(e=>({byThreadKey:z(e.byThreadKey,t,e=>Wk(e,e.surfaces.find(e=>e.kind===`preview`)??gk(null)))})),openDiff:(t,n,r)=>e(e=>({byThreadKey:z(e.byThreadKey,t,e=>{let t={id:`diff`,kind:`diff`,turnId:n??null,filePath:n?r??null:null};return{...e,isOpen:!0,activeSurfaceId:t.id,surfaces:e.surfaces.some(e=>e.id===`diff`)?e.surfaces.map(e=>e.id===`diff`?t:e):[...e.surfaces,t]}})})),openFile:(t,n,r,i=`execution-intent`)=>e(e=>({byThreadKey:z(e.byThreadKey,t,e=>{let t=`file:${n}`,a=e.surfaces.find(e=>e.id===t&&e.kind===`file`),o=_k(n,Uk(r),(a?.revealRequestId??0)+1,i);return{...e,isOpen:!0,activeSurfaceId:o.id,surfaces:a?e.surfaces.map(e=>e.id===o.id?o:e):[...e.surfaces,o]}})})),openPullRequest:(t,n)=>e(e=>({byThreadKey:z(e.byThreadKey,t,e=>Wk(e,vk(n)))})),activateSurface:(t,n)=>e(e=>({byThreadKey:z(e.byThreadKey,t,e=>e.surfaces.some(e=>e.id===n)?{...e,isOpen:!0,activeSurfaceId:n}:e)})),closeSurface:(t,n)=>e(e=>({byThreadKey:z(e.byThreadKey,t,e=>{let t=e.surfaces.findIndex(e=>e.id===n);if(t<0)return e;let r=e.surfaces.filter(e=>e.id!==n);if(e.activeSurfaceId!==n)return{...e,isOpen:r.length>0&&e.isOpen,surfaces:r};let i=r[Math.min(t,r.length-1)]??null;return{...e,isOpen:r.length>0&&e.isOpen,surfaces:r,activeSurfaceId:i?.id??null}})})),closeOtherSurfaces:(t,n)=>e(e=>({byThreadKey:z(e.byThreadKey,t,e=>{let t=e.surfaces.find(e=>e.id===n);return!t||e.surfaces.length===1?e:{...e,isOpen:!0,surfaces:[t],activeSurfaceId:t.id}})})),closeSurfacesToRight:(t,n)=>e(e=>({byThreadKey:z(e.byThreadKey,t,e=>{let t=e.surfaces.findIndex(e=>e.id===n);if(t<0||t===e.surfaces.length-1)return e;let r=e.surfaces.slice(0,t+1),i=r.some(t=>t.id===e.activeSurfaceId);return{...e,surfaces:r,activeSurfaceId:i?e.activeSurfaceId:n}})})),closeAllSurfaces:t=>e(e=>({byThreadKey:z(e.byThreadKey,t,()=>hk)})),renameSurface:(t,n,r)=>e(e=>({byThreadKey:z(e.byThreadKey,t,e=>{let t=r.trim();return{...e,surfaces:e.surfaces.map(e=>e.id===n?Gk(e,t):e)}})})),show:t=>e(e=>({byThreadKey:z(e.byThreadKey,t,e=>({...e,isOpen:!0}))})),close:t=>e(e=>({byThreadKey:z(e.byThreadKey,t,e=>e.isOpen?{...e,isOpen:!1,isMaximized:!1}:e)})),toggleVisibility:t=>e(e=>({byThreadKey:z(e.byThreadKey,t,e=>({...e,isOpen:!e.isOpen}))})),toggleMaximized:t=>e(e=>({byThreadKey:z(e.byThreadKey,t,e=>e.isOpen?{...e,isMaximized:!(e.isMaximized??!1)}:e)})),removeThread:t=>e(e=>{if(!(t in e.byThreadKey))return e;let{[t]:n,...r}=e.byThreadKey;return{byThreadKey:r}})}),{name:Rk,version:zk,storage:Hf(()=>An),partialize:e=>({byThreadKey:Object.fromEntries(Object.entries(e.byThreadKey).filter(([e])=>!Hk(e)&&!Bk(e)))}),migrate:e=>Lk(e)}));function qk(e,t){let n={hour:`numeric`,minute:`2-digit`,...t?{second:`2-digit`}:{}};return e===`locale`?n:{...n,hour12:e===`12-hour`}}var Jk=new Map;function Yk(e,t){let n=`${e}:${t?`seconds`:`minutes`}`,r=Jk.get(n);if(r)return r;let i=new Intl.DateTimeFormat(void 0,qk(e,t));return Jk.set(n,i),i}function Xk(e,t){return Yk(t,!0).format(new Date(e))}function Zk(e,t){return Yk(t,!1).format(new Date(e))}function Qk(e){let t=Date.now()-new Date(e).getTime();if(t<0)return{value:`just now`,suffix:null};let n=Math.floor(t/1e3);if(n<60)return{value:`just now`,suffix:null};let r=Math.floor(n/60);if(r<60)return{value:`${r}m`,suffix:`ago`};let i=Math.floor(r/60);return i<24?{value:`${i}h`,suffix:`ago`}:{value:`${Math.floor(i/24)}d`,suffix:`ago`}}function $k(e){let t=Qk(e);return t.suffix?`${t.value} ${t.suffix}`:t.value}function eA(e){if(e===null)return null;let t=e.trim();return t.length>0?t:null}var tA=Object.freeze({data:null,error:null,cause:null,isPending:!1}),nA=Object.freeze({...tA,isPending:!0}),rA=un(tA).pipe(ln,sn(`git-status:null`)),iA=()=>void 0,aA=new Map,oA=new Set,sA=new Map,cA=new Map,lA=1e3,uA=on(e=>(oA.add(e),un(nA).pipe(ln,sn(`git-status:${e}`))));function dA(e){return e.environmentId===null||eA(e.cwd)===null?null:`${e.environmentId}:${e.cwd}`}function fA(e){if(e.environmentId===null)return null;let t=dw(e.environmentId);return t?{clientIdentity:t.environmentId,client:t.client.git}:null}function pA(e){let t=dA(e);return t===null?tA:cn.get(uA(t))}function mA(e,t){let n=dA(e);if(n===null)return iA;let r=aA.get(n);return r?(r.refCount+=1,()=>_A(n)):(aA.set(n,{refCount:1,unsubscribe:vA(n,e,t)}),()=>_A(n))}function hA(e,t){let n=dA(e),r=eA(e.cwd);if(n===null||r===null)return Promise.resolve(null);let i=t??fA(e)?.client;if(!i)return Promise.resolve(pA(e).data);let a=sA.get(n);if(a)return a;let o=cA.get(n)??0;if(Date.now()-o<lA)return Promise.resolve(pA(e).data);cA.set(n,Date.now());let s=i.refreshStatus({cwd:r}).finally(()=>{sA.delete(n)});return sA.set(n,s),s}function gA(e){let t=(0,A.c)(4),n=dA(e),r,i;t[0]!==e.cwd||t[1]!==e.environmentId?(r=()=>mA({environmentId:e.environmentId,cwd:e.cwd}),i=[e.environmentId,e.cwd],t[0]=e.cwd,t[1]=e.environmentId,t[2]=r,t[3]=i):(r=t[2],i=t[3]),(0,O.useEffect)(r,i);let a=ma(n===null?rA:uA(n));return n===null?tA:a}function _A(e){let t=aA.get(e);t&&(--t.refCount,!(t.refCount>0)&&(t.unsubscribe(),aA.delete(e)))}function vA(e,t,n){let r=eA(t.cwd);if(r===null)return iA;let i=null,a=iA,o=()=>{let o=n?{clientIdentity:`provided:${e}`,client:n}:fA(t);if(!o){i!==null&&(a(),a=iA,i=null),bA(e);return}i!==o.clientIdentity&&(a(),i=o.clientIdentity,a=yA(e,r,o.client))},s=n?iA:uw(o);return o(),()=>{s(),a()}}function yA(e,t,n){return bA(e),n.onStatus({cwd:t},t=>{cn.set(uA(e),{data:t,error:null,cause:null,isPending:!1})},{onResubscribe:()=>{bA(e)}})}function bA(e){let t=uA(e),n=cn.get(t),r=n.data===null?nA:{...n,error:null,cause:null,isPending:!0};(n.data!==r.data||n.error!==r.error||n.cause!==r.cause||n.isPending!==r.isPending)&&cn.set(t,r)}function xA(e){let t=[];for(let n of e){let e=n.children??[];if(e.length>0){t.push({item:n,isGroupLabel:!0});for(let n of e)t.push({item:n,isGroupLabel:!1});continue}Array.isArray(n.children)||t.push({item:n,isGroupLabel:!1})}return t}function SA(e){let t=document.createElement(`div`);return t.textContent=e,t.className=`px-2 pt-1.5 pb-0.5 text-[10px] font-medium uppercase tracking-wide text-muted-foreground/70`,t}function CA(e){let t=document.createElement(`button`);return t.type=`button`,t.textContent=e.label,t.disabled=e.disabled,t.className=e.disabled?`flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-[11px] text-muted-foreground/50 cursor-not-allowed`:e.destructive?`flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-[11px] text-destructive transition-colors hover:bg-accent`:`flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-[11px] text-popover-foreground transition-colors hover:bg-accent`,t}function wA(e,t){return new Promise(n=>{let r=document.createElement(`div`);r.style.cssText=`position:fixed;inset:0;z-index:9999`;let i=document.createElement(`div`);i.className=`fixed z-[10000] min-w-[160px] rounded-lg border bg-popover p-1 text-popover-foreground shadow-lg/5 outline-none before:pointer-events-none before:absolute before:inset-0 before:rounded-[calc(var(--radius-lg)-1px)] before:shadow-[0_1px_--theme(--color-black/4%)] dark:before:shadow-[0_-1px_--theme(--color-white/6%)]`;let a=t?.x??0,o=t?.y??0;i.style.top=`${o}px`,i.style.left=`${a}px`;function s(e){document.removeEventListener(`keydown`,c),r.remove(),i.remove(),n(e)}function c(e){e.key===`Escape`&&(e.preventDefault(),s(null))}r.addEventListener(`mousedown`,()=>s(null)),document.addEventListener(`keydown`,c);let l=!1;for(let{item:t,isGroupLabel:n}of xA(e)){if(n){i.appendChild(SA(t.label));continue}let e=t.destructive===!0||t.id===`delete`,r=t.disabled===!0;if(e&&!l){let e=document.createElement(`div`);e.className=`-mx-1 my-1 h-px bg-border`,i.appendChild(e),l=!0}let a=CA({label:t.label,disabled:r,destructive:e});r||a.addEventListener(`click`,()=>s(t.id)),i.appendChild(a)}document.body.appendChild(r),document.body.appendChild(i),requestAnimationFrame(()=>{let e=i.getBoundingClientRect();e.right>window.innerWidth&&(i.style.left=`${window.innerWidth-e.width-4}px`),e.bottom>window.innerHeight&&(i.style.top=`${window.innerHeight-e.height-4}px`)})})}var TA;function EA(){return DA(mw().client)}function DA(e){return{getConfig:e.server.getConfig,refreshProviders:e.server.refreshProviders,startProviderAuth:e.server.startProviderAuth,repairProviderAuthRuntime:e.server.repairProviderAuthRuntime,disconnectProviderAuth:e.server.disconnectProviderAuth,getProviderAuthSession:e.server.getProviderAuthSession,cancelProviderAuth:e.server.cancelProviderAuth,submitProviderAuthCode:e.server.submitProviderAuthCode,syncPersonalCodexToCloud:e.server.syncPersonalCodexToCloud,syncPersonalClaudeToCloud:e.server.syncPersonalClaudeToCloud,upsertKeybinding:e.server.upsertKeybinding,removeKeybinding:e.server.removeKeybinding,getSettings:e.server.getSettings,updateSettings:e.server.updateSettings,updateEnvironmentDisplayName:async t=>{let n=await e.server.updateEnvironmentDisplayName({displayName:t});return $w(n.environment),n}}}function OA(e,t){return{...e,...t,dialogs:{...e.dialogs,...t.dialogs},shell:{...e.shell,...t.shell},contextMenu:{...e.contextMenu,...t.contextMenu},persistence:{...e.persistence,...t.persistence},server:{...e.server,...t.server}}}function kA(e){return{dialogs:{pickFolder:async()=>window.desktopBridge?window.desktopBridge.pickFolder():null,confirm:async e=>window.desktopBridge?window.desktopBridge.confirm(e):window.confirm(e)},shell:{openInEditor:(t,n)=>e.shell.openInEditor({cwd:t,editor:n}),openExternal:async e=>{if(window.desktopBridge){if(!await window.desktopBridge.openExternal(e))throw Error(`Unable to open link.`);return}window.open(e,`_blank`,`noopener,noreferrer`)}},contextMenu:{show:async(e,t)=>window.desktopBridge?window.desktopBridge.showContextMenu(e,t):wA(e,t)},persistence:{getClientSettings:tr,setClientSettings:or,getSavedEnvironmentRegistry:pr,setSavedEnvironmentRegistry:rr,getSavedEnvironmentSecret:Kn,setSavedEnvironmentSecret:Zn,removeSavedEnvironmentSecret:Jn},server:DA(e)}}function AA(){if(typeof window>`u`)return;if(TA)return TA;let e=kA(mw().client);return window.nativeApi?(TA=OA(e,window.nativeApi),TA):(TA=e,TA)}function jA(){let e=AA();if(!e)throw Error(`Local API not found`);return e}function MA(){let e=(0,A.c)(2),[t,n]=(0,O.useState)(NA),r,i;return e[0]===Symbol.for(`react.memo_cache_sentinel`)?(r=()=>(n(Ia()),Pa(()=>{n(Ia())})),i=[],e[0]=r,e[1]=i):(r=e[0],i=e[1]),(0,O.useEffect)(r,i),t}function NA(){return Ia()}function PA(e,t){e.style.setProperty(`--appearance-contrast-base`,`${Math.min(t,100)}%`),e.style.setProperty(`--appearance-contrast-boost`,`${Math.max(t-100,0)}%`),e.style.setProperty(`--appearance-contrast-border-boost`,`${Math.max(t-100,0)/4}%`)}var FA=`-apple-system, BlinkMacSystemFont, "Segoe UI", system-ui, sans-serif`,IA=`ui-monospace, "SF Mono", "SFMono-Regular", Menlo, Consolas, "Liberation Mono", monospace`;function LA(e){let t=e.trim();return t.length===0?``:/^(['"]).*\1$/u.test(t)||/^[a-zA-Z][a-zA-Z0-9-]*$/u.test(t)?t:`"${t.replaceAll(`"`,``)}"`}function RA(e){let t=e.split(`,`).map(LA).filter(e=>e.length>0);return t.length>0?t.join(`, `):null}var zA={appearanceContrastBase:`--appearance-contrast-base`,appearanceContrastBoost:`--appearance-contrast-boost`,appearanceContrastBorderBoost:`--appearance-contrast-border-boost`,fontSans:`--font-sans`,fontMono:`--font-mono`,fontComposer:`--font-composer`,fontTerminal:`--font-terminal`,promptFontSize:`--forge-prompt-font-size`,terminalFontSize:`--forge-terminal-font-size`,glassOpacity:`--glass-opacity`};function BA(e,t){let n=[[zA.fontSans,t.fontFamilySans,FA],[zA.fontMono,t.fontFamilyCode,IA],[zA.fontComposer,t.fontFamilyComposer,`var(--font-sans)`],[zA.fontTerminal,t.fontFamilyTerminal,`var(--font-mono)`]];for(let[t,r,i]of n){let n=RA(r);if(n===null){e.style.removeProperty(t);continue}e.style.setProperty(t,`${n}, ${i}`)}e.style.setProperty(zA.promptFontSize,`${String(t.promptFontSize)}px`),e.style.setProperty(zA.terminalFontSize,`${String(t.terminalFontSize)}px`),e.style.setProperty(zA.glassOpacity,`${String(t.glassOpacity)}%`),PA(e,t.appearanceContrast),t.fontSmoothing?e.style.setProperty(`-webkit-font-smoothing`,`antialiased`):e.style.removeProperty(`-webkit-font-smoothing`)}function VA(){return typeof window<`u`&&typeof localStorage<`u`}function HA(){if(!VA())return{};try{let e=JSON.parse(window.localStorage.getItem(`forge:theme-halves:v1`)??`null`);if(typeof e!=`object`||!e||Array.isArray(e))return{};let t={};for(let n of[`light`,`dark`]){let r=e[n];typeof r==`string`&&(t[n]=r)}return t}catch{return{}}}function UA(){if(!VA())return null;try{return Na(window.localStorage.getItem(Ra))}catch{return null}}function WA(e){if(VA())try{e===null||e.light===void 0&&e.dark===void 0?window.localStorage.removeItem(Ra):window.localStorage.setItem(Ra,JSON.stringify(e))}catch{}}function GA(e,t,n){let r={...e};return n===null?delete r[t]:r[t]=n,r}function KA(e){return e!==null&&(e.light!==void 0||e.dark!==void 0)?e:null}function qA(e,t){let n=(0,A.c)(13),[r,i]=(0,O.useState)(JA),a=MA(),o;n[0]===Symbol.for(`react.memo_cache_sentinel`)?(o=(e,t)=>{let n=GA(HA(),e,t);return WA(n),i(KA(n)),!0},n[0]=o):o=n[0];let s=o,c;n[1]===Symbol.for(`react.memo_cache_sentinel`)?(c=()=>(WA(null),i(null),!0),n[1]=c):c=n[1];let l=c,u;n[2]!==t||n[3]!==r||n[4]!==e?(u=()=>{let n=t===`dark`?`dark`:`light`;Fa(La(e,r,n),n)},n[2]=t,n[3]=r,n[4]=e,n[5]=u):u=n[5];let d;n[6]!==a||n[7]!==t||n[8]!==r||n[9]!==e?(d=[e,t,r,a],n[6]=a,n[7]=t,n[8]=r,n[9]=e,n[10]=d):d=n[10],(0,O.useEffect)(u,d);let f;return n[11]===r?f=n[12]:(f={themeHalves:r,setThemeHalf:s,clearThemeHalves:l},n[11]=r,n[12]=f),f}function JA(){return UA()}var YA=`theme-color`,XA=`meta[name="${YA}"][data-dynamic-theme-color="true"]`,ZA={dark:`#0a0a0a`,light:`#ffffff`};function QA(){let e=document.querySelector(XA);return e||(e=document.createElement(`meta`),e.name=YA,e.setAttribute(`data-dynamic-theme-color`,`true`),document.head.append(e),e)}function $A(e){let t=e?.trim().toLowerCase();return!t||t===`transparent`||t===`rgba(0, 0, 0, 0)`||t===`rgba(0 0 0 / 0)`?null:e?.trim()??null}function ej(){return document.querySelector(`main[data-slot='sidebar-inset']`)??document.querySelector(`[data-slot='sidebar-inner']`)??document.body}function tj(){return document.documentElement.classList.contains(`dark`)?`dark`:`light`}function nj(e=tj()){if(typeof document>`u`||typeof getComputedStyle>`u`)return;document.documentElement.style.backgroundColor=``,document.body.style.backgroundColor=``;let t=$A(getComputedStyle(ej()).backgroundColor),n=$A(getComputedStyle(document.body).backgroundColor),r=t??n??ZA[e];document.documentElement.style.backgroundColor=r,document.body.style.backgroundColor=r,QA().setAttribute(`content`,r)}var rj=`forge:theme`,ij=`(prefers-color-scheme: dark)`;function aj(e){return e===`system`||e===`light`||e===`dark`}function oj(e,t){return typeof e!=`number`||!Number.isFinite(e)?t:Math.min(20,Math.max(11,Math.round(e)))}function sj(){if(!VA())return{theme:`system`,uiFontSize:16,codeFontSize:13};try{let e=window.localStorage.getItem(Yn);if(e){let t=Un(JSON.parse(e));return{theme:aj(t.theme)?t.theme:`system`,uiFontSize:oj(t.uiFontSize,16),codeFontSize:oj(t.codeFontSize,13)}}let t=window.localStorage.getItem(rj);return{theme:aj(t)?t:`system`,uiFontSize:16,codeFontSize:13}}catch{return{theme:`system`,uiFontSize:16,codeFontSize:13}}}function cj(){return typeof window>`u`||typeof window.matchMedia!=`function`||window.matchMedia(ij).matches?`dark`:`light`}function lj(e){return e===`system`?cj():e}function uj(e){if(typeof window>`u`)return;let t=window.desktopBridge;t&&t.setTheme(e).catch(()=>{})}function dj(e,t=!1){let n=lj(e);return typeof document>`u`||typeof window>`u`?n:(t&&document.documentElement.classList.add(`no-transitions`),document.documentElement.classList.toggle(`dark`,n===`dark`),document.documentElement.dataset.theme=e,document.documentElement.style.colorScheme=n,nj(n),uj(e),t&&(document.documentElement.offsetHeight,requestAnimationFrame(()=>{document.documentElement.classList.remove(`no-transitions`)})),n)}function fj(e){typeof document>`u`||document.documentElement.style.setProperty(`--forge-ui-font-size`,`${oj(e,16)}px`)}function pj(e){typeof document>`u`||document.documentElement.style.setProperty(`--forge-code-font-size`,`${oj(e,13)}px`)}function mj(e){fj(e.uiFontSize),pj(e.codeFontSize)}if(typeof document<`u`){let e=sj();dj(e.theme),mj(e)}function hj(){let e=(0,A.c)(33),t=I(yj),n=I(vj),r=I(_j),i=I(gj),{updateSettings:a}=WT(),o;e[0]===t?o=e[1]:(o=()=>lj(t),e[0]=t,e[1]=o);let[s,c]=(0,O.useState)(o),{themeHalves:l,setThemeHalf:u,clearThemeHalves:d}=qA(n,s),f;e[2]===a?f=e[3]:(f=e=>{a({theme:e}),c(dj(e,!0))},e[2]=a,e[3]=f);let p=f,m;e[4]===a?m=e[5]:(m=e=>{a({themeId:e})},e[4]=a,e[5]=m);let h=m,g;e[6]===a?g=e[7]:(g=e=>{let t=oj(e,16);a({uiFontSize:t}),fj(t)},e[6]=a,e[7]=g);let _=g,v;e[8]===a?v=e[9]:(v=e=>{let t=oj(e,13);a({codeFontSize:t}),pj(t)},e[8]=a,e[9]=v);let y=v,b,x;e[10]===t?(b=e[11],x=e[12]):(b=()=>{c(dj(t))},x=[t],e[10]=t,e[11]=b,e[12]=x),(0,O.useEffect)(b,x);let ee,te;e[13]!==i||e[14]!==r?(ee=()=>{mj({uiFontSize:r,codeFontSize:i})},te=[r,i],e[13]=i,e[14]=r,e[15]=ee,e[16]=te):(ee=e[15],te=e[16]),(0,O.useEffect)(ee,te);let ne,re;e[17]===t?(ne=e[18],re=e[19]):(re=()=>{if(t!==`system`||typeof window>`u`||typeof window.matchMedia!=`function`)return;let e=window.matchMedia(ij),n=()=>{c(dj(`system`,!0))};return e.addEventListener(`change`,n),()=>{e.removeEventListener(`change`,n)}},ne=[t],e[17]=t,e[18]=ne,e[19]=re),(0,O.useEffect)(re,ne);let ie;return e[20]!==d||e[21]!==i||e[22]!==s||e[23]!==y||e[24]!==p||e[25]!==u||e[26]!==h||e[27]!==_||e[28]!==t||e[29]!==l||e[30]!==n||e[31]!==r?(ie={theme:t,setTheme:p,themeId:n,setThemeId:h,resolvedTheme:s,themeHalves:l,setThemeHalf:u,clearThemeHalves:d,uiFontSize:r,codeFontSize:i,setUiFontSize:_,setCodeFontSize:y},e[20]=d,e[21]=i,e[22]=s,e[23]=y,e[24]=p,e[25]=u,e[26]=h,e[27]=_,e[28]=t,e[29]=l,e[30]=n,e[31]=r,e[32]=ie):ie=e[32],ie}function gj(e){return e.codeFontSize}function _j(e){return e.uiFontSize}function vj(e){return e.themeId}function yj(e){return e.theme}function bj(){let e=(0,A.c)(11),t=I(kj),n=I(Oj),r=I(Dj),i=I(Ej),a=I(Tj),o=I(wj),s=I(Cj),c=I(Sj),l=I(xj),u,d;e[0]!==t||e[1]!==r||e[2]!==i||e[3]!==n||e[4]!==a||e[5]!==c||e[6]!==l||e[7]!==o||e[8]!==s?(u=()=>{typeof document>`u`||BA(document.documentElement,{appearanceContrast:t,fontFamilyCode:r,fontFamilyComposer:i,fontFamilySans:n,fontFamilyTerminal:a,fontSmoothing:c,glassOpacity:l,promptFontSize:o,terminalFontSize:s})},d=[t,r,i,n,a,c,l,o,s],e[0]=t,e[1]=r,e[2]=i,e[3]=n,e[4]=a,e[5]=c,e[6]=l,e[7]=o,e[8]=s,e[9]=u,e[10]=d):(u=e[9],d=e[10]),(0,O.useEffect)(u,d)}function xj(e){return e.glassOpacity}function Sj(e){return e.fontSmoothing}function Cj(e){return e.terminalFontSize}function wj(e){return e.promptFontSize}function Tj(e){return e.fontFamilyTerminal}function Ej(e){return e.fontFamilyComposer}function Dj(e){return e.fontFamilyCode}function Oj(e){return e.fontFamilySans}function kj(e){return e.appearanceContrast}var Aj=`forge:last-editor`;function jj(e){let t=(0,A.c)(5),[n,r]=Nn(Aj,null,bi),i;bb0:{if(n&&e.includes(n)){i=n;break bb0}let r;t[0]===e?r=t[1]:(r=Sr.find(t=>e.includes(t.id))?.id??null,t[0]=e,t[1]=r),i=r}let a=i,o;return t[2]!==a||t[3]!==r?(o=[a,r],t[2]=a,t[3]=r,t[4]=o):o=t[4],o}function Mj(e){let t=new Set(e),n=jn(Aj,bi);if(n&&t.has(n))return n;let r=Sr.find(e=>t.has(e.id))?.id??null;return r&&_r(Aj,r,bi),r??null}async function Nj(e,t){let{availableEditors:n}=await e.server.getConfig(),r=Mj(n);if(!r)throw Error(`No available editors found.`);return await e.shell.openInEditor(t,r),r}var Pj=/https?:\/\/[^\s"'`<>]+/g,Fj=/(?:~\/|\.{1,2}\/|\/|[A-Za-z]:[\\/]|\\\\)[^\s"'`<>]+|[A-Za-z0-9._-]+(?:\/[A-Za-z0-9._-]+)+(?::\d+){0,2}/g,Ij=/[.,;!?]+$/;function Lj(e){let t=e.replace(Ij,``);if(t.length===0)return t;let n=(e,n)=>{for(;t.endsWith(n);){if(t.split(e).length-1>=t.split(n).length-1)return;t=t.slice(0,-1)}};return n(`(`,`)`),n(`[`,`]`),n(`{`,`}`),t}function Rj(e,t){return e.start<t.end&&t.start<e.end}function zj(e,t,n,r){let i=[];n.lastIndex=0;for(let a of e.matchAll(n)){let e=a[0],n=a.index??-1;if(n<0||e.length===0)continue;let o=Lj(e);if(o.length===0||t===`path`&&/^https?:\/\//i.test(o))continue;let s={kind:t,text:o,start:n,end:n+o.length};[...r,...i].some(e=>Rj(s,e))||i.push(s)}return i}function Bj(e){return/^[A-Za-z]:[\\/]/.test(e)||e.startsWith(`\\\\`)}function Vj(e){return e.startsWith(`/`)||Bj(e)}function Hj(e){return Bj(e)||/[A-Za-z]:\\/.test(e)}function Uj(e,t,n){let r=e.replace(/[\\/]+$/,``);return n===`\\`?`${r}\\${t.replaceAll(`/`,`\\`)}`:`${r}/${t.replace(/^\/+/,``)}`}function Wj(e){let t=e.match(/^\/Users\/([^/]+)/);if(t?.[1])return`/Users/${t[1]}`;let n=e.match(/^\/home\/([^/]+)/);if(n?.[1])return`/home/${n[1]}`;let r=e.match(/^([A-Za-z]:\\Users\\[^\\]+)/);if(r?.[1])return r[1]}function Gj(e){let t=e,n,r,i=t.match(/:(\d+)$/);if(!i?.[1])return{path:t,line:void 0,column:void 0};n=i[1],t=t.slice(0,-i[0].length);let a=t.match(/:(\d+)$/);return a?.[1]?(r=a[1],t=t.slice(0,-a[0].length)):(r=n,n=void 0),{path:t,line:r,column:n}}function Kj(e){let t=zj(e,`url`,Pj,[]),n=zj(e,`path`,Fj,t);return[...t,...n].toSorted((e,t)=>e.start-t.start)}function qj(e,t){let n=t(e-1);if(!n)return null;let r=e,i=n;for(;r>1&&i.isWrapped;){let e=t(r-2);if(!e)return null;--r,i=e}let a=[],o=0,s=r;for(;;){let e=t(s-1);if(!e)break;let n=t(s)?.isWrapped===!0,r=e.translateToString(!n);if(a.push({bufferLineNumber:s,text:r,startIndex:o,endIndex:o+r.length}),o+=r.length,!n)break;s+=1}return{text:a.map(e=>e.text).join(``),segments:a}}function Jj(e,t){for(let n of e)if(t<n.endIndex)return{x:t-n.startIndex+1,y:n.bufferLineNumber};let n=e[e.length-1];return{x:Math.max(n?.text.length??0,1),y:n?.bufferLineNumber??1}}function Yj(e,t){return{start:Jj(e.segments,t.start),end:Jj(e.segments,t.end-1)}}function Xj(e,t){return e.start.y<=t&&t<=e.end.y}function Zj(e,t=typeof navigator>`u`?``:navigator.platform){return t.length===0?!1:Sa(t)?e.metaKey&&!e.ctrlKey:e.ctrlKey&&!e.metaKey}function Qj(e,t){let{path:n,line:r,column:i}=Gj(e),a=n;if(n.startsWith(`~/`)){let e=Wj(t);if(e){let t=Hj(e)?`\\`:`/`;a=Uj(e,n.slice(2),t)}}else Vj(n)||(a=Uj(t,n,Hj(t)?`\\`:`/`));return r?`${a}:${r}${i?`:${i}`:``}`:a}var $j=`diffs-container`,eM=(()=>{try{return!1}catch{return!1}})(),tM=/(?=^From [a-f0-9]+ .+$)/m,nM=/(?=^diff --git)/gm,rM=/(?<=\n)/,iM=/^(---|\+\+\+)\s+([^\t\r\n]+)/,aM=/^(---|\+\+\+)\s+[ab]\/([^\t\r\n]+)/,oM=/^diff --git (?:"a\/(.+?)"|a\/(.+?)) (?:"b\/(.+?)"|b\/(.+?))$/,sM=/^index ([0-9a-f]+)\.\.([0-9a-f]+)(?: (\d+))?$/i,cM=`header-prefix`,lM=`header-filename-suffix`,uM=`header-metadata`,dM=`header-custom`,fM={dark:`pierre-dark`,light:`pierre-light`},pM=`data-theme-css`,mM=`data-unsafe-css`,hM=`data-diffs-scrollbar-measure`,gM=`data-diffs-code-view-header`,_M=`data-diffs-code-view-footer`,vM=`--diffs-scrollbar-gutter-measured`,yM=1e5,bM={hunkLineCount:50,lineHeight:20,diffHeaderHeight:44,spacing:8},xM={...bM,hunkLineCount:1},SM={paddingTop:8,paddingBottom:8,gap:8},CM={omega:.015,positionEpsilon:.5,velocityEpsilon:.05},wM=Object.freeze({fromStart:0,fromEnd:0}),TM={startingLine:0,totalLines:1/0,bufferBefore:0,bufferAfter:0},EM={startingLine:0,totalLines:0,bufferBefore:0,bufferAfter:0},DM=new Set,OM=null;function kM(e){DM.add(e),OM??=requestAnimationFrame(jM)}function AM(e){DM.delete(e)&&DM.size===0&&OM!=null&&(cancelAnimationFrame(OM),OM=null)}function jM(e){let t=new Set(DM);DM.clear();for(let n of t)try{n(e)}catch(e){console.error(e)}OM=DM.size>0?requestAnimationFrame(jM):null}function MM(e,t,n){if(e===t||e==null||t==null)return e===t;let r=new Set(n),i=Object.keys(e),a=new Set(Object.keys(t));for(let n of i)if(a.delete(n),!r.has(n)&&(!(n in t)||e[n]!==t[n]))return!1;for(let e of Array.from(a))if(!r.has(e))return!1;return!0}function NM(e,t){return e==null||t==null||typeof e==`string`||typeof t==`string`?e===t:e.dark===t.dark&&e.light===t.light}function PM(e,t){let n=e?.theme??fM,r=t?.theme??fM,i=FM(e),a=FM(t);return NM(n,r)&&MM(e,t,[`theme`,`parseDiffOptions`])&&MM(i,a)}function FM(e){if(e!=null&&`parseDiffOptions`in e)return e.parseDiffOptions}function IM(e,t){return e?.start===t?.start&&e?.end===t?.end&&e?.side===t?.side&&e?.endSide===t?.endSide}function LM({scrollTop:e,scrollHeight:t,height:n,fitPerfectly:r=!1,fitPerfectlyOverscroll:i=0,overscrollSize:a}){let o=n+a*2,s=r?n+i*2:o;if(t=Math.max(t,s),o>=t||r){let n=Math.max(e-i,0),r=Math.min(e+s,t);return{top:n,bottom:Math.max(r,n)}}let c=e+n/2-o/2,l=c+o;return c<0&&(c=0),l>t&&(l=t),c=Math.floor(Math.max(c,0)),{top:c,bottom:Math.ceil(Math.max(Math.min(l,t),c))}}function RM(e){let t=e.length;return e.charCodeAt(t-1)===10&&(t--,e.charCodeAt(t-1)===13&&t--),e.slice(0,t)}function zM(e,t){return e-(t===0?0:1)}function BM(e,t){return zM(e,t)+t}var VM=class{diff(e,t,n={}){let r;typeof n==`function`?(r=n,n={}):`callback`in n&&(r=n.callback);let i=this.castInput(e,n),a=this.castInput(t,n),o=this.removeEmpty(this.tokenize(i,n)),s=this.removeEmpty(this.tokenize(a,n));return this.diffWithOptionsObj(o,s,n,r)}diffWithOptionsObj(e,t,n,r){let i=e=>{if(e=this.postProcess(e,n),r){setTimeout(function(){r(e)},0);return}return e},a=t.length,o=e.length,s=1,c=a+o;n.maxEditLength!=null&&(c=Math.min(c,n.maxEditLength));let l=n.timeout??1/0,u=Date.now()+l,d=[{oldPos:-1,lastComponent:void 0}],f=this.extractCommon(d[0],t,e,0,n);if(d[0].oldPos+1>=o&&f+1>=a)return i(this.buildValues(d[0].lastComponent,t,e));let p=-1/0,m=1/0,h=()=>{for(let r=Math.max(p,-s);r<=Math.min(m,s);r+=2){let s,c=d[r-1],l=d[r+1];c&&(d[r-1]=void 0);let u=!1;if(l){let e=l.oldPos-r;u=l&&0<=e&&e<a}let h=c&&c.oldPos+1<o;if(!u&&!h){d[r]=void 0;continue}if(s=!h||u&&c.oldPos<l.oldPos?this.addToPath(l,!0,!1,0,n):this.addToPath(c,!1,!0,1,n),f=this.extractCommon(s,t,e,r,n),s.oldPos+1>=o&&f+1>=a)return i(this.buildValues(s.lastComponent,t,e))||!0;d[r]=s,s.oldPos+1>=o&&(m=Math.min(m,r-1)),f+1>=a&&(p=Math.max(p,r+1))}s++};if(r)(function e(){setTimeout(function(){if(s>c||Date.now()>u)return r(void 0);h()||e()},0)})();else for(;s<=c&&Date.now()<=u;){let e=h();if(e)return e}}addToPath(e,t,n,r,i){let a=e.lastComponent;return a&&!i.oneChangePerToken&&a.added===t&&a.removed===n?{oldPos:e.oldPos+r,lastComponent:{count:a.count+1,added:t,removed:n,previousComponent:a.previousComponent}}:{oldPos:e.oldPos+r,lastComponent:{count:1,added:t,removed:n,previousComponent:a}}}extractCommon(e,t,n,r,i){let a=t.length,o=n.length,s=e.oldPos,c=s-r,l=0;for(;c+1<a&&s+1<o&&this.equals(n[s+1],t[c+1],i);)c++,s++,l++,i.oneChangePerToken&&(e.lastComponent={count:1,previousComponent:e.lastComponent,added:!1,removed:!1});return l&&!i.oneChangePerToken&&(e.lastComponent={count:l,previousComponent:e.lastComponent,added:!1,removed:!1}),e.oldPos=s,c}equals(e,t,n){return n.comparator?n.comparator(e,t):e===t||!!n.ignoreCase&&e.toLowerCase()===t.toLowerCase()}removeEmpty(e){let t=[];for(let n=0;n<e.length;n++)e[n]&&t.push(e[n]);return t}castInput(e,t){return e}tokenize(e,t){return Array.from(e)}join(e){return e.join(``)}postProcess(e,t){return e}get useLongestToken(){return!1}buildValues(e,t,n){let r=[],i;for(;e;)r.push(e),i=e.previousComponent,delete e.previousComponent,e=i;r.reverse();let a=r.length,o=0,s=0,c=0;for(;o<a;o++){let e=r[o];if(e.removed)e.value=this.join(n.slice(c,c+e.count)),c+=e.count;else{if(!e.added&&this.useLongestToken){let r=t.slice(s,s+e.count);r=r.map(function(e,t){let r=n[c+t];return r.length>e.length?r:e}),e.value=this.join(r)}else e.value=this.join(t.slice(s,s+e.count));s+=e.count,e.added||(c+=e.count)}}return r}},HM=new class extends VM{};function UM(e,t,n){return HM.diff(e,t,n)}function WM(e,t){let n;for(n=0;n<e.length&&n<t.length;n++)if(e[n]!=t[n])return e.slice(0,n);return e.slice(0,n)}function GM(e,t){let n;if(!e||!t||e[e.length-1]!=t[t.length-1])return``;for(n=0;n<e.length&&n<t.length;n++)if(e[e.length-(n+1)]!=t[t.length-(n+1)])return e.slice(-n);return e.slice(-n)}function KM(e,t,n){if(e.slice(0,t.length)!=t)throw Error(`string ${JSON.stringify(e)} doesn't start with prefix ${JSON.stringify(t)}; this is a bug`);return n+e.slice(t.length)}function qM(e,t,n){if(!t)return e+n;if(e.slice(-t.length)!=t)throw Error(`string ${JSON.stringify(e)} doesn't end with suffix ${JSON.stringify(t)}; this is a bug`);return e.slice(0,-t.length)+n}function JM(e,t){return KM(e,t,``)}function YM(e,t){return qM(e,t,``)}function XM(e,t){return t.slice(0,ZM(e,t))}function ZM(e,t){let n=0;e.length>t.length&&(n=e.length-t.length);let r=t.length;e.length<t.length&&(r=e.length);let i=Array(r),a=0;i[0]=0;for(let e=1;e<r;e++){for(t[e]==t[a]?i[e]=i[a]:i[e]=a;a>0&&t[e]!=t[a];)a=i[a];t[e]==t[a]&&a++}a=0;for(let r=n;r<e.length;r++){for(;a>0&&e[r]!=t[a];)a=i[a];e[r]==t[a]&&a++}return a}function QM(e,t){let n=[];for(let r of Array.from(t.segment(e))){let e=r.segment;n.length&&/\s/.test(n[n.length-1])&&/\s/.test(e)?n[n.length-1]+=e:n.push(e)}return n}function $M(e,t){if(t)return tN(e,t)[1];let n;for(n=e.length-1;n>=0&&e[n].match(/\s/);n--);return e.substring(n+1)}function eN(e,t){if(t)return tN(e,t)[0];let n=e.match(/^\s*/);return n?n[0]:``}function tN(e,t){if(!t)return[eN(e),$M(e)];if(t.resolvedOptions().granularity!=`word`)throw Error(`The segmenter passed must have a granularity of "word"`);let n=QM(e,t),r=n[0],i=n[n.length-1];return[/\s/.test(r)?r:``,/\s/.test(i)?i:``]}var nN=`a-zA-Z0-9_\\u{AD}\\u{C0}-\\u{D6}\\u{D8}-\\u{F6}\\u{F8}-\\u{2C6}\\u{2C8}-\\u{2D7}\\u{2DE}-\\u{2FF}\\u{1E00}-\\u{1EFF}`,rN=RegExp(`[${nN}]+|\\s+|[^${nN}]`,`ug`);new class extends VM{equals(e,t,n){return n.ignoreCase&&(e=e.toLowerCase(),t=t.toLowerCase()),e.trim()===t.trim()}tokenize(e,t={}){let n;if(t.intlSegmenter){let r=t.intlSegmenter;if(r.resolvedOptions().granularity!=`word`)throw Error(`The segmenter passed must have a granularity of "word"`);n=QM(e,r)}else n=e.match(rN)||[];let r=[],i=null;return n.forEach(e=>{/\s/.test(e)?i==null?r.push(e):r.push(r.pop()+e):i!=null&&/\s/.test(i)?r[r.length-1]==i?r.push(r.pop()+e):r.push(i+e):r.push(e),i=e}),r}join(e){return e.map((e,t)=>t==0?e:e.replace(/^\s+/,``)).join(``)}postProcess(e,t){if(!e||t.oneChangePerToken)return e;let n=null,r=null,i=null;return e.forEach(e=>{e.added?r=e:e.removed?i=e:((r||i)&&iN(n,i,r,e,t.intlSegmenter),n=e,r=null,i=null)}),(r||i)&&iN(n,i,r,null,t.intlSegmenter),e}};function iN(e,t,n,r,i){if(t&&n){let[a,o]=tN(t.value,i),[s,c]=tN(n.value,i);if(e){let r=WM(a,s);e.value=qM(e.value,s,r),t.value=JM(t.value,r),n.value=JM(n.value,r)}if(r){let e=GM(o,c);r.value=KM(r.value,c,e),t.value=YM(t.value,e),n.value=YM(n.value,e)}}else if(n){if(e){let e=eN(n.value,i);n.value=n.value.substring(e.length)}if(r){let e=eN(r.value,i);r.value=r.value.substring(e.length)}}else if(e&&r){let n=eN(r.value,i),[a,o]=tN(t.value,i),s=WM(n,a);t.value=JM(t.value,s);let c=GM(JM(n,s),o);t.value=YM(t.value,c),r.value=KM(r.value,n,c),e.value=qM(e.value,n,n.slice(0,n.length-c.length))}else if(r){let e=eN(r.value,i),n=XM($M(t.value,i),e);t.value=YM(t.value,n)}else if(e){let n=XM($M(e.value,i),eN(t.value,i));t.value=JM(t.value,n)}}var aN=new class extends VM{tokenize(e){let t=RegExp(`(\\r?\\n)|[${nN}]+|[^\\S\\n\\r]+|[^${nN}]`,`ug`);return e.match(t)||[]}};function oN(e,t,n){return aN.diff(e,t,n)}var sN=new class extends VM{constructor(){super(...arguments),this.tokenize=lN}equals(e,t,n){return n.ignoreWhitespace?((!n.newlineIsToken||!e.includes(`
|
|
19
|
+
`):null,i?.output,o,t?.result];for(let e of s){let t=TE(e);if(t)return t}return null}function DE(e,t){let n=e.endsWith(`...`)?e.slice(0,-3):e.endsWith(`…`)?e.slice(0,-1):null;return t.some(t=>{let r=t?.trim();return r?r===e||n!==null&&n.length>0&&r.length>n.length&&r.startsWith(n):!1})}function OE(e){let t=wE(e.toolName)?.trim(),n=e.detail.trim(),r=[e.command,e.rawCommand];if(t){let e=`${t}:`;if(n.toLowerCase().startsWith(e.toLowerCase())&&DE(n.slice(e.length).trim(),r))return!0}if(!DE(n,r))return!1;let i=CE(e.data),a=CE(i?.item),o=CE(a?.input),s=CE(a?.result);return![a?.command,o?.command,s?.command,i?.command].some(e=>Array.isArray(e)?e.some(e=>wE(e)!==null):wE(e)!==null)||a!==null||i?.toolCallId!==void 0||wE(i?.kind)?.toLowerCase()===`execute`}function kE(e){return e.kind===`runtime.warning`&&e.summary.endsWith(`(no displayable text content)`)}function AE(e,t){let n=UE(e?.message);return n&&PE(n)!==PE(t)?n:null}function jE(e){if(typeof e?.itemType==`string`&&Gr(e.itemType))return e.itemType}function ME(e){return e.replace(/\s+/g,` `).trim()}function NE(e,t=84){return e.length<=t?e:`${e.slice(0,t-1).trimEnd()}…`}function PE(e){let t=UE(e);return t?VE(ME(t)).toLowerCase():null}function FE(e){let t=[];for(let n of e.split(/\r?\n/u)){let e=ME(n);e.length>0&&t.push(e)}let n=t.find(e=>e!=="```");return n?NE(n):t.length>1?`${t.length.toLocaleString()} lines`:null}function IE(e){return typeof e==`number`&&Number.isFinite(e)?e:null}function LE(e){let t=HE(HE(e?.data)?.rawOutput);if(!t)return null;let n=IE(t.totalFiles);if(n!==null){let e=t.truncated===!0?`+`:``;return`${n.toLocaleString()} file${n===1?``:`s`}${e}`}let r=UE(t.content);if(r)return FE(r);let i=UE(t.stdout);return i?FE(i):null}function RE(e){let t=EE(e?.data);return t?lE(t).output:null}function zE(e,t){let n=UE(HE(e?.data)?.kind)?.toLowerCase(),r=UE(e?.title??t)?.toLowerCase();return jE(e)===`command_execution`||n===`execute`||r===`terminal`||r===`ran command`}function BE(e,t){let n=UE(e?.detail),r=n?lE(n).output:null,i=PE(t),a=PE(r),o=zE(e,t),s=o?cE(e):{command:null,rawCommand:null},c=s.command;if(o&&c){let t=RE(e);if(t)return t}let l=HE(e?.data),u=r!==null&&OE({detail:r,command:c,rawCommand:s.rawCommand,toolName:l?.toolName,data:l});if(r&&i!==a&&(!o||!u))return r;if(o)return null;let d=LE(e);return d&&PE(d)!==i?d:null}function VE(e){return e.replace(/\s+(?:complete|completed)\s*$/i,``).trim()}function HE(e){return e&&typeof e==`object`?e:null}function UE(e){if(typeof e!=`string`)return null;let t=e.trim();return t.length>0?t:null}function WE(e){return e&&typeof e==`object`?e:null}function GE(e){if(typeof e!=`string`)return null;let t=e.trim();return t.length>0?t:null}function KE(e){return qE(e)??GE(e?.title)}function qE(e){if(!e)return null;let t=WE(e.data),n=WE(t?.item),r=WE(n?.input)??WE(t?.input),i=GE(e.title),a=GE(e.itemType),o=GE(n?.name)??GE(n?.toolName)??GE(t?.name)??GE(e.toolName)??i,s=GE(e.detail),c=[o,i,a,s].filter(Boolean).join(` `).toLowerCase();if(!c.includes(`browser`)&&!c.includes(`forge-browser`))return null;switch(JE(o,r,s)){case`open-session`:return`Opened browser session`;case`name-session`:return`Named browser session`;case`new-tab`:return YE(r)??`Opened browser tab`;case`navigate`:return YE(r)??`Navigated browser`;case`reload`:return`Reloaded page`;case`back`:return`Went back`;case`forward`:return`Went forward`;case`screenshot`:return`Captured screenshot`;case`snapshot`:return`Read DOM snapshot`;case`logs`:return`Read console logs`;case`click`:return`Clicked page`;case`type`:return`Typed text`;case`scroll`:return`Scrolled page`;case`viewport`:return`Updated viewport`;case`visibility`:return`Updated browser visibility`;default:return null}}function JE(e,t,n){let r=[GE(t?.type)??GE(t?.command),e,n].filter(Boolean).join(` `).toLowerCase();return/\b(open[-_.\s]?session|create[-_.\s]?session|session[-_.\s]?open)\b/.test(r)?`open-session`:/\b(name[-_.\s]?session|session[-_.\s]?name)\b/.test(r)?`name-session`:/\b(new[-_.\s]?tab|create[-_.\s]?tab|open[-_.\s]?tab)\b/.test(r)?`new-tab`:/\b(navigate|goto|go[-_.\s]?to)\b/.test(r)?`navigate`:/\breload\b/.test(r)?`reload`:/\b(go[-_.\s]?back|back)\b/.test(r)?`back`:/\b(go[-_.\s]?forward|forward)\b/.test(r)?`forward`:/\b(screenshot|capture)\b/.test(r)?`screenshot`:/\b(snapshot|dom[-_.\s]?snapshot|read[-_.\s]?dom)\b/.test(r)?`snapshot`:/\b(console[-_.\s]?logs?|logs?)\b/.test(r)?`logs`:/\bclick\b/.test(r)?`click`:/\btype|fill\b/.test(r)?`type`:/\bscroll\b/.test(r)?`scroll`:/\bviewport\b/.test(r)?`viewport`:/\bvisibility|visible|hidden\b/.test(r)?`visibility`:null}function YE(e){let t=GE(e?.url)??GE(e?.initialUrl);if(!t)return null;try{let e=new URL(t);return e.hostname.length===0?null:`Navigated to ${e.hostname}`}catch{return null}}function XE(e){return e&&typeof e==`object`?e:null}function L(e){if(typeof e!=`string`)return null;let t=e.trim();return t.length>0?t:null}function ZE(e){for(let t of $E(e)){if(t.userActionRequired!==`confirm_github_tool`)continue;let e=XE(t.confirmation),n=XE(e?.request),r=L(e?.confirmationId),i=L(e?.toolName),a=L(e?.operation);if(!(!r||!i||!a||!n))return{confirmationId:r,toolName:i,operation:a,request:n}}return null}function QE(e){let t=$E(e)[0];if(!t)return null;let n=L(t.userActionRequired);return!n||n===`confirm_github_tool`?null:{action:n,toolName:L(t.toolName),message:L(t.error)??L(t.message)}}function $E(e){if(!e)return[];let t=[],n=new Set,r=(e,i)=>{if(i>8||e==null)return;if(typeof e==`string`){let n=L(e);if(!n)return;let r=eD(n);r&&L(r.userActionRequired)&&t.push(r);return}if(typeof e!=`object`||n.has(e))return;if(n.add(e),Array.isArray(e)){for(let t of e)r(t,i+1);return}let a=e;if(L(a.userActionRequired)){t.push(a);return}for(let e of Object.values(a))r(e,i+1)};return r(e,0),t}function eD(e){try{return XE(JSON.parse(e))}catch{return null}}function tD(e){switch(e){case`create_repository`:return`Create GitHub repository`;case`link_project_repository`:return`Link project repository`;case`push_branch`:return`Push Git branch`;case`create_pull_request`:return`Create pull request`;case`rerun_workflow`:return`Rerun GitHub Actions workflow`;default:return e.split(`_`).filter(Boolean).map(e=>`${e.charAt(0).toUpperCase()}${e.slice(1)}`).join(` `)}}function nD(e){return[L(e.request.repoFullName)??(L(e.request.owner)&&L(e.request.name)?`${L(e.request.owner)}/${L(e.request.name)}`:null),L(e.request.cwd),L(e.request.branch),L(e.request.title)].filter(Boolean).join(` - `)}function rD(e){switch(e){case`connect_github`:return`Connect GitHub to continue`;case`connect_cmmd`:return`Forge couldn't authorize this action`;case`start_from_authenticated_forge_session`:return`Open this thread in Forge`;case`link_project_repository`:return`Link this project to GitHub`;case`create_branch`:return`Create a branch before pushing`;case`retry_in_user_vm`:return`Retry in the project VM`;default:return e.split(`_`).filter(Boolean).map(e=>`${e.charAt(0).toUpperCase()}${e.slice(1)}`).join(` `)}}function iD(e){switch(e){case`connect_github`:return`Connect GitHub so agents can create repos, push branches, and open PRs.`;case`connect_cmmd`:return`Reconnect Forge, then retry. Your conversation is preserved.`;case`start_from_authenticated_forge_session`:return`Open it in Forge so this action uses your signed-in account.`;case`link_project_repository`:return`Link a GitHub repo to this project before pushing or opening PRs.`;case`create_branch`:return`Forge needs a branch before it can push to GitHub.`;case`retry_in_user_vm`:return`This has to run from the project's cloud VM.`;default:return`Finish the required setup, then retry.`}}function aD(e){return e.action===`connect_cmmd`?iD(e.action):e.message??iD(e.action)}function oD(e,t){return e.action===t.action&&e.toolName===t.toolName&&e.message===t.message}function sD(e){switch(e){case`connect_cmmd`:return`Reconnect Forge`;case`connect_github`:return`Connect GitHub`;default:return`Open Git settings`}}function cD(e){return[`The required Forge GitHub setup has been completed by the user.`,e.toolName?`Retry the previous GitHub tool request for \`${e.toolName}\`.`:`Retry the previous GitHub tool request.`,`Continue the previous GitHub lifecycle request using Forge brokered GitHub tools only.`,"Do not use shell `gh` or direct GitHub CLI commands."].join(`
|
|
20
|
+
`)}function R(e){return typeof e==`object`&&e&&!Array.isArray(e)?e:void 0}var lD={};function uD(e){return typeof e==`string`&&e.trim().length>0}function dD(e){let t=R(e);if(!t||!uD(t.requestId)||!R(t.answers)||!R(t.attachmentsByQuestionId))return!1;let n=R(t.questionTextById);if(t.questionTextById!==void 0&&!n)return!1;if(n){for(let e of Object.values(n))if(typeof e!=`string`)return!1}for(let e of Object.values(t.attachmentsByQuestionId)){if(!Array.isArray(e))return!1;for(let t of e){let e=R(t);if(!e||!uD(e.id)||!uD(e.name))return!1}}return!0}function fD(e,t){if(typeof e==`string`)return t.get(e)??e;if(Array.isArray(e))return e.map(e=>fD(e,t));let n=R(e);return n&&`answers`in n?{...n,answers:fD(n.answers,t)}:e}function pD(e,t){let n=t.map(e=>typeof e==`string`?e.trim():``);return n.length>0&&n.every(Boolean)?JSON.stringify([e,n.sort()]):void 0}function mD(e){return e&&typeof e==`object`?e:null}function hD(e){if(typeof e!=`string`)return null;let t=e.trim();return t.length>0?t:null}function gD(e,t){let n=mD(e.item),r=e.toolName??e.tool??n?.tool??t;if(typeof r!=`string`)return{};let i=r.split(/__|[./]/).at(-1)?.replace(/[_\s]/g,``).toLowerCase();if(!i||!/^(askuserquestion|requestuserinput(?:async)?|askquestion|question)$/.test(i))return{};let a=mD(e.input??e.rawInput??mD(e.state)?.input??n?.arguments),o=a?.questions??mD(a?.params)?.questions;return Array.isArray(o)?{input:{questions:o.map(e=>{let t=mD(e);return{question:hD(t?.question??t?.question_text??t?.prompt??t?.title)}})}}:{}}function _D(e){let t=new Set;for(let n of e){if(n.kind!==`user-input.answer-submitted`||!n.turnId)continue;let e=R(n.payload),r=Object.values(R(e?.questionTextById)??lD),i=pD(n.turnId,r);i&&t.add(i)}if(t.size===0)return e;let n=new Set;for(let r of e){if(!r.kind.startsWith(`tool.`)||!r.turnId)continue;let e=R(r.payload);if(typeof e?.toolCallId!=`string`)continue;let i=gD(R(e.data)??{},e.title).input;if(!i)continue;let a=pD(r.turnId,i.questions.map(e=>e.question));a&&t.has(a)&&n.add(JSON.stringify([r.turnId,e.toolCallId]))}return e.filter(e=>{let t=R(e.payload),r=t?.toolCallId;return e.tone===`error`||/^(failed|declined|stopped|cancelled)$/.test(String(t?.status))||!e.kind.startsWith(`tool.`)||typeof r!=`string`||!n.has(JSON.stringify([e.turnId,r]))})}function vD(e){let t=new Map;for(let n of e){if(n.kind!==`user-input.requested`&&n.kind!==`user-input.resolved`&&n.kind!==`user-input.answer-submitted`)continue;let e=R(n.payload)?.requestId;if(typeof e!=`string`||!e)continue;let r=t.get(e)??[];r.push(n),t.set(e,r)}let n=new Map;for(let[e,r]of t){let t=r.map(e=>R(e.payload)),i=new Map,a=new Map;for(let e of t){for(let[t,n]of Object.entries(R(e.questionTextById)??lD))a.set(t,n);for(let t of Array.isArray(e.questions)?e.questions:[]){let e=R(t);typeof e?.id==`string`&&(i.set(e.id,e),typeof e.question==`string`&&a.set(e.id,e.question))}}let o=Object.fromEntries(a),s=R(R(r.findLast(e=>e.kind===`user-input.answer-submitted`&&R(R(e.payload)?.answers))?.payload)?.answers)??t.map(e=>R(e.answers)).findLast(Boolean)??{},c=Object.fromEntries(Object.entries(s).map(([e,t])=>{let n=i.get(e)?.options,r=new Map;for(let e of Array.isArray(n)?n:[]){let t=R(e);typeof t?.label==`string`&&(typeof t.value==`string`&&r.set(t.value,t.label),r.set(t.label,t.label))}return[e,fD(t,r)]})),l=Object.fromEntries(t.flatMap(e=>Object.entries(R(e.attachmentsByQuestionId)??lD))),u={requestId:e,questionTextById:o,answers:c,attachmentsByQuestionId:l};if(!dD(u))continue;let d=Object.keys(c).length>0||Object.keys(l).length>0;for(let e of r)n.set(e,null);n.set(r[0],{...r[0],kind:`user-input.answer-submitted`,tone:`tool`,summary:d?`User input submitted`:r.some(e=>e.kind===`user-input.resolved`)?`User input dismissed`:`User input requested`,payload:u})}return _D(e.flatMap(e=>{let t=n.get(e);return t===null?[]:[t??e]}))}function yD(e){if(typeof e==`string`)return e;if(Array.isArray(e))return e.map(yD).filter(Boolean).join(`, `);let t=R(e);return t?yD(t.answers):``}function bD(e){let t=Object.values(e.answers).map(yD).filter(Boolean),n=Object.values(e.attachmentsByQuestionId).flat().map(e=>e.name);return(t.length>0?t.join(` · `):n.length>0?n.join(`, `):Object.values(e.questionTextById??{}).join(` · `)).replace(/\s+/g,` `).trim()}function xD(e){return Object.values(e.answers).some(yD)||Object.values(e.attachmentsByQuestionId).some(e=>e.length>0)}function SD(e){return typeof e==`object`&&e&&!Array.isArray(e)?e:void 0}function CD(e,t){if(typeof e!=`string`)return;let n=e.trim();return n&&n.length<=t?n:void 0}function wD(e){let t=CD(e,4096);if(t)try{let e=new URL(t);return e.protocol===`http:`||e.protocol===`https:`||e.protocol===`data:`?e.href:void 0}catch{return}}function TD(e){let t=CD(e,4096);if(t)try{let e=new URL(t);return e.protocol===`http:`||e.protocol===`https:`?e.href:void 0}catch{return}}function ED(e){let t=SD(e),n=CD(t?.appId,512);if(t?._tag===`app-id`&&n&&/^[A-Za-z0-9._-]+$/u.test(n))return{_tag:`app-id`,appId:n};let r=CD(t?.displayName,160);if(t?._tag===`display-name`&&r)return{_tag:`display-name`,displayName:r}}function DD(e){let t=SD(e);if(t?._tag===`website`){let e=TD(t.pageUrl),n=wD(t.faviconUrl),r=wD(t.faviconUrlDark);if(e)return{_tag:`website`,pageUrl:e,...n?{faviconUrl:n}:{},...r?{faviconUrlDark:r}:{}}}if(t?._tag===`native-app`){let e=ED(t.app);if(e)return{_tag:`native-app`,app:e}}if(t?._tag===`themed-logo`){let e=wD(t.logoUrl),n=wD(t.logoUrlDark);if(e)return{_tag:`themed-logo`,logoUrl:e,...n?{logoUrlDark:n}:{}}}}function OD(e){let t=SD(e),n=CD(t?.key,512),r=CD(t?.name,160),i=t?.kind;if(!n||!r||i!==`browser`&&i!==`computer`&&i!==`integration`)return;let a=DD(t?.icon);return{key:n,name:r,kind:i,...a?{icon:a}:{}}}function kD(e){let t=SD(e),n=t?.toolSurface===`browser`||t?.toolSurface===`computer`?t.toolSurface:void 0,r=DD(t?.toolIcon),i=OD(t?.toolSource);return{...n?{toolSurface:n}:{},...r?{toolIcon:r}:{},...i?{toolSource:i}:{}}}function AD(e,t,n){return e===t||e.endsWith(`.${t}`)?!0:n!==void 0&&e.split(`.`).includes(n)}function jD(e){let t;try{t=new URL(e)}catch{return null}if(t.protocol!==`https:`&&t.protocol!==`http:`)return null;let n=t.hostname.toLowerCase();if(AD(n,`github.com`,`github`)){let e=/^\/([^/]+\/[^/]+)\/pull\/(\d+)(?:\/|$)/u.exec(t.pathname);if(e)return MD(n,e)}let r=/^\/([^/]+(?:\/[^/]+)+)\/pulls\/(\d+)(?:\/|$)/u.exec(t.pathname);if(r){let e=MD(n,r);return e===null?null:{...e,authority:t.host.toLowerCase()}}let i=/^\/([^/]+(?:\/[^/]+)+)\/-\/merge_requests\/(\d+)(?:\/|$)/u.exec(t.pathname);return i?MD(n,i):AD(n,`bitbucket.org`,`bitbucket`)?MD(n,/^\/([^/]+\/[^/]+)\/pull-requests\/(\d+)(?:\/|$)/u.exec(t.pathname)):AD(n,`dev.azure.com`)||n.endsWith(`.visualstudio.com`)?MD(n,/^\/((?:[^/]+\/)*_git\/[^/]+)\/pullrequest\/(\d+)(?:\/|$)/u.exec(t.pathname)):null}function MD(e,t){let n=t?.[1],r=Number(t?.[2]);return n&&Number.isSafeInteger(r)&&r>0?{host:e,repository:n.toLowerCase(),number:r}:null}function ND(e){return e.replace(/\s+(?:complete|completed)\s*$/i,``).trim()}var PD={link_pull_request:[`Link`,`Linking`,`Linked`,`a pull request`],unlink_pull_request:[`Unlink`,`Unlinking`,`Unlinked`,`a pull request`],list_thread_pull_requests:[`Check`,`Checking`,`Checked`,`linked pull requests`],orchestrator_capabilities:[`Get`,`Getting`,`Got`,`orchestration capabilities`],delegate_task:[`Delegate`,`Delegating`,`Delegated`,`a child task`],task_status:[`Get`,`Getting`,`Got`,`delegated task status`],task_cancel:[`Cancel`,`Canceling`,`Canceled`,`delegated task`],schedule_task:[`Schedule`,`Scheduling`,`Scheduled`,`a recurring task`],list_scheduled_tasks:[`List`,`Listing`,`Listed`,`scheduled tasks`],update_scheduled_task:[`Update`,`Updating`,`Updated`,`a scheduled task`],delete_scheduled_task:[`Delete`,`Deleting`,`Deleted`,`a scheduled task`],create_threads:[`Create`,`Creating`,`Created`,`T3 threads`],t3_thread_start:[`Start`,`Starting`,`Started`,`a T3 thread`],t3_thread_list:[`List`,`Listing`,`Listed`,`T3 threads`],t3_thread_read:[`Read`,`Reading`,`Read`,`a T3 thread`],t3_thread_send:[`Send`,`Sending`,`Sent`,`to a T3 thread`],t3_thread_wait:[`Wait`,`Waiting`,`Waited`,`for a T3 thread`],t3_thread_interrupt:[`Interrupt`,`Interrupting`,`Interrupted`,`a T3 thread`],t3_worktree_handoff:[`Hand off`,`Handing off`,`Handed off`,`thread to a git worktree`],t3_worktree_status:[`Get`,`Getting`,`Got`,`thread worktree status`],preview_status:[`Get`,`Getting`,`Got`,`preview browser status`],preview_open:[`Open`,`Opening`,`Opened`,`a page in the preview browser`],preview_navigate:[`Navigate`,`Navigating`,`Navigated`,`the preview browser`],preview_snapshot:[`Take a snapshot of`,`Taking a snapshot of`,`Took a snapshot of`,`the preview page`],preview_click:[`Click`,`Clicking`,`Clicked`,`in the preview browser`],preview_press:[`Press`,`Pressing`,`Pressed`,`a key in the preview browser`],preview_type:[`Type`,`Typing`,`Typed`,`in the preview browser`],preview_scroll:[`Scroll`,`Scrolling`,`Scrolled`,`the preview browser`],preview_resize:[`Resize`,`Resizing`,`Resized`,`the preview browser`],preview_evaluate:[`Evaluate`,`Evaluating`,`Evaluated`,`script in the preview browser`],preview_wait_for:[`Wait`,`Waiting`,`Waited`,`for the preview page`],preview_set_appearance:[`Set`,`Setting`,`Set`,`preview browser appearance`],preview_recording_start:[`Start`,`Starting`,`Started`,`recording the preview browser`],preview_recording_stop:[`Stop`,`Stopping`,`Stopped`,`recording the preview browser`],device_list:[`List`,`Listing`,`Listed`,`simulators and emulators`],device_open:[`Open`,`Opening`,`Opened`,`a device in the Device panel`],device_screenshot:[`Take a screenshot of`,`Taking a screenshot of`,`Took a screenshot of`,`the device`],device_close:[`Close`,`Closing`,`Closed`,`a device`]},FD={link_pull_request:`link-pr`,unlink_pull_request:`unlink-pr`,list_thread_pull_requests:`list-prs`};function ID(e,t,n){if(!e)return null;let r=ND(e).replace(/^(?:mcp__(?:t3-code|t3_code|t3code)__|(?:t3-code|t3_code|t3code)(?:[.:/]|\s*·\s*))/i,``);if(!Object.hasOwn(PD,r))return null;let[i,a,o,s]=PD[r],c=t===`inProgress`?a:t===`completed`?o:t===`failed`?`Failed to ${i.toLowerCase()}`:t===`declined`?`Declined to ${i.toLowerCase()}`:t===`stopped`?`Stopped ${a.toLowerCase()}`:a,l=Object.hasOwn(FD,r)?FD[r]:void 0,u=zD(n),d=zD(u?.arguments)??zD(u?.input)??zD(u?.rawInput),f=(typeof d?.url==`string`?jD(d.url):null)?.number??d?.number;return{displayName:`${c} ${l!==void 0&&l!==`list-prs`&&typeof f==`number`&&Number.isSafeInteger(f)&&f>0?`PR #${f}`:s}`,icon:l===void 0?r.startsWith(`preview_`)?`browser`:r.startsWith(`device_`)?`device`:`t3-code`:`pull-request`,...l===void 0?{}:{action:l}}}function LD(e,t){return e===`failed`||e===`declined`||e===`stopped`?e:t||e===`inProgress`?`inProgress`:`completed`}function RD(e,t){let n=e.toolLifecycleStatus??t,r=e.toolData;if(typeof r==`object`&&r){if(`server`in r&&typeof r.server==`string`&&`tool`in r&&typeof r.tool==`string`)return ID(`${r.server}.${r.tool}`,n,r);if(`toolName`in r&&typeof r.toolName==`string`)return ID(r.toolName,n,r)}return ID(e.toolTitle,n,r)??ID(e.label,n,r)}function zD(e){return typeof e==`object`&&e&&!Array.isArray(e)?e:null}function BD(e){let t=zD(e);switch(t?.status){case`pending`:case`running`:case`waiting`:return`inProgress`;case`cancelled`:case`interrupted`:return`stopped`;case`idle`:return t.taskType===`subagent_batch`?`stopped`:void 0;case`inProgress`:case`completed`:case`failed`:case`declined`:case`stopped`:return t.status;default:return}}function VD(e){return e.tone===`tool`||e.tone===`thinking`||e.tone===`error`||e.command!==void 0&&e.command.trim().length>0||e.requestKind!==void 0||e.itemType!==void 0&&Gr(e.itemType)}function HD(e){let t=e.toLowerCase();return t.includes(`file not found`)||t.includes(`no files found`)||t.includes(`enoent`)||t.includes(`no such file or directory`)||t.includes(`no such file`)||t.includes(`commandnotfoundexception`)||t.includes(`command not found`)||t.includes(`cannot find path`)&&t.includes(`because it does not exist`)||t.includes(`is not recognized`)&&t.includes(`the term '`)||t.includes(`is not recognized as the name of a cmdlet`)||t.includes(`a parameter cannot be found that matches parameter name`)||/<exited with exit code\s+[1-9]\d*\s*>/i.test(e)||/exit(?:ed)? with exit code\s+[1-9]\d*/i.test(e)||/exit code\s*[:\s]\s*[1-9]\d*\b/i.test(e)}function UD(e,t){if(e.tone===`error`||e.toolLifecycleStatus===`failed`||e.toolLifecycleStatus===`declined`)return!0;if(!VD(e))return!1;let n=t?[e.detail,e.command].filter(Boolean).join(`
|
|
21
|
+
`):e.detail??``;return n.length>0&&HD(n)}function WD(e){return UD(e,!0)}function GD(e){return UD(e,!1)}function KD(e){return VD(e)&&!WD(e)&&e.tone!==`thinking`&&e.toolLifecycleStatus!==`inProgress`&&e.toolLifecycleStatus!==`stopped`}function qD(e){let t=e.taskId??``,n=t.indexOf(`:wf:`);return n===-1?e.agentSpawn?.workflowId?`wf:${e.agentSpawn.workflowId}`:e.isWorkflowCoordinator?`wf:${t}`:e.turnId?`direct:${e.turnId}`:`direct:task:${t}`:`wf:${t.slice(0,n)}`}function JD(e){if(e.sourceActivityKind===`tool.updated`||e.sourceActivityKind===`tool.completed`)return e.toolCallId?`tool:${e.turnId??`no-turn`}:${e.toolCallId}`:void 0}function YD(e){let t=[],n=new Map,r=new Map,i=new Map;for(let a of e){if(a.taskId!==void 0&&!a.isBackgroundTask&&(a.sourceActivityKind===`task.started`||a.sourceActivityKind===`task.progress`||a.sourceActivityKind===`task.completed`)&&a.taskId!==void 0){let e=r.get(a.taskId),i=e??qD(a);e===void 0&&r.set(a.taskId,i);let o=i.startsWith(`wf:`)?i.slice(3):null,s=n.get(i);if(s!==void 0){let e=t[s],n=e.agentSpawn?.agentTaskIds.includes(a.taskId)?e.agentSpawn.agentTaskIds:[...e.agentSpawn?.agentTaskIds??[],a.taskId];t[s]={...ZD(e,a),id:e.id,createdAt:e.createdAt,turnId:e.turnId??null,...e.taskId===void 0?{}:{taskId:e.taskId},label:e.label,agentSpawn:{workflowId:o,agentTaskIds:n}};continue}n.set(i,t.length),t.push({...a,agentSpawn:{workflowId:o,agentTaskIds:[a.taskId]}});continue}let e=JD(a);if(e!==void 0){let n=i.get(e),r=n===void 0?void 0:t[n];if(n!==void 0&&r&&XD(r,a)){t[n]=ZD(r,a);continue}i.delete(e)}let o=t.at(-1);if(o&&XD(o,a)){let e=t.length-1,n=JD(o);n!==void 0&&i.delete(n);let r=ZD(o,a);t[e]=r;let s=JD(r);s!==void 0&&i.set(s,e);continue}t.push(a),e!==void 0&&i.set(e,t.length-1)}return t}function XD(e,t){return e.sourceActivityKind!==`tool.updated`&&e.sourceActivityKind!==`tool.completed`||t.sourceActivityKind!==`tool.updated`&&t.sourceActivityKind!==`tool.completed`||e.turnId!==t.turnId||e.sourceActivityKind===`tool.completed`?!1:e.collapseKey!==void 0&&e.collapseKey===t.collapseKey||e.toolCallId!==void 0&&t.toolCallId===void 0&&e.itemType===t.itemType&&ND(e.toolTitle??e.label)===ND(t.toolTitle??t.label)}function ZD(e,t){let n=QD(e.changedFiles,t.changedFiles),r=t.detail??e.detail,i=t.viewedImagePath??e.viewedImagePath,a=t.command??e.command,o=t.rawCommand??e.rawCommand,s=t.toolTitle??e.toolTitle,c=t.toolSurface??e.toolSurface,l=t.toolIcon??e.toolIcon,u=t.toolSource??e.toolSource,d=t.itemType??e.itemType,f=t.requestKind??e.requestKind,p=t.collapseKey??e.collapseKey,m=t.toolCallId??e.toolCallId,h=t.toolLifecycleStatus??e.toolLifecycleStatus,g=t.toolData??e.toolData;return{...e,...t,...r?{detail:r}:{},...i?{viewedImagePath:i}:{},...a?{command:a}:{},...o?{rawCommand:o}:{},...n.length>0?{changedFiles:n}:{},...s?{toolTitle:s}:{},...c?{toolSurface:c}:{},...l?{toolIcon:l}:{},...u?{toolSource:u}:{},...d?{itemType:d}:{},...f?{requestKind:f}:{},...p?{collapseKey:p}:{},...m?{toolCallId:m}:{},...h===void 0?{}:{toolLifecycleStatus:h},...g===void 0?{}:{toolData:g}}}function QD(e,t){let n=[...e??[],...t??[]];return n.length===0?[]:[...new Set(n)]}function $D(e){if(e.taskId&&(e.sourceActivityKind===`task.progress`||e.sourceActivityKind===`task.completed`))return`task${e.taskId}`;if(e.sourceActivityKind!==`tool.updated`&&e.sourceActivityKind!==`tool.completed`)return;if(e.toolCallId)return`tool:${e.turnId??`no-turn`}:${e.toolCallId}`;let t=ND(e.toolTitle??e.label),n=e.detail?.trim()??``,r=e.itemType??``;if(t.length!==0||n.length!==0||r.length!==0)return[r,t,n].join(``)}function eO(e){let t=oO(e?.data);return sO(e?.toolCallId)??sO(t?.toolCallId)}function tO(e){switch(e){case`command_execution_approval`:case`exec_command_approval`:return`command`;case`file_read_approval`:return`file-read`;case`file_change_approval`:case`apply_patch_approval`:return`file-change`;default:return null}}function nO(e){return e?.requestKind===`command`||e?.requestKind===`file-read`||e?.requestKind===`file-change`?e.requestKind:tO(e?.requestType)??void 0}function rO(e,t,n){let r=sO(n);!r||t.has(r)||(t.add(r),e.push(r))}function iO(e,t,n,r){if(r>4||t.length>=12)return;if(Array.isArray(e)){for(let i of e)if(iO(i,t,n,r+1),t.length>=12)return;return}let i=oO(e);if(i){rO(t,n,i.path),rO(t,n,i.filePath),rO(t,n,i.relativePath),rO(t,n,i.filename),rO(t,n,i.newPath),rO(t,n,i.oldPath);for(let e of[`item`,`result`,`input`,`data`,`changes`,`files`,`edits`,`patch`,`patches`,`operations`])if(e in i&&(iO(i[e],t,n,r+1),t.length>=12))return}}function aO(e){let t=[],n=new Set;return iO(oO(e?.data),t,n,0),t}function oO(e){return e&&typeof e==`object`?e:null}function sO(e){if(typeof e!=`string`)return null;let t=e.trim();return t.length>0?t:null}var cO=new WeakMap;function lO(e){return!(e.agentSpawn!==void 0||!VD(e)||WD(e)||KD(e))}function uO(e){let t=cO.get(e);if(t)return t;let n=e.payload&&typeof e.payload==`object`?e.payload:null,r=cE(n),i=aO(n),a=KE(n),o=kD(n),s=e.kind===`task.progress`||e.kind===`task.completed`,c=s&&typeof n?.summary==`string`&&n.summary.length>0?n.summary:null,l=s&&!c&&typeof n?.detail==`string`&&n.detail.length>0?n.detail:null,u=c||l,d=s?!l&&n&&typeof n.detail==`string`&&n.detail.length>0?lE(n.detail).output:null:BE(n,a??e.summary),f=s?null:eO(n),p={id:e.id,createdAt:e.createdAt,turnId:e.turnId,label:u||e.summary,tone:e.kind===`task.progress`?`thinking`:e.tone,sourceActivityKind:e.kind};if(e.kind===`user-input.answer-submitted`){let e=n&&dD(n)?n:null;e&&(p.questionAnswer={requestId:e.requestId,questionTextById:e.questionTextById,answers:e.answers,attachmentsByQuestionId:e.attachmentsByQuestionId})}let m=jE(n),h=nO(n),g=sO(oO(n?.data)?.imagePath);if(d)p.detail=d;else if(e.kind===`runtime.error`||e.kind===`runtime.warning`){let t=AE(n,e.summary);t&&(p.detail=t)}if(g&&(p.viewedImagePath=g),r.command&&(p.command=r.command),r.rawCommand&&(p.rawCommand=r.rawCommand),i.length>0&&(p.changedFiles=i),a&&(p.toolTitle=a),o.toolSurface&&(p.toolSurface=o.toolSurface),o.toolIcon&&(p.toolIcon=o.toolIcon),o.toolSource&&(p.toolSource=o.toolSource),m===`mcp_tool_call`){let e=oO(n?.data),t=typeof e?.toolName==`string`?e.item??e:e?.item;t!==void 0&&(p.toolData=t)}m&&(p.itemType=m),h&&(p.requestKind=h),f&&(p.toolCallId=f);let _=BD(n);!_&&e.kind===`tool.completed`&&(_=`completed`),_&&(p.toolLifecycleStatus=_);let v=e.kind===`task.started`||e.kind===`task.progress`||e.kind===`task.completed`;v&&typeof n?.taskId==`string`&&n.taskId.length>0&&(p.taskId=n.taskId),v&&typeof n?.role==`string`&&n.role.length>0&&(p.agentRole=n.role),v&&(n?.taskType===`local_workflow`||typeof n?.workflowName==`string`&&n.workflowName.length>0)&&(p.isWorkflowCoordinator=!0),v&&n&&n.agentKind!==`agent`&&(p.isBackgroundTask=!0);let y=ZE(n);if(y)p.githubConfirmation=y,p.tone=`approval`,p.label=`GitHub action needs approval`,p.toolTitle=tD(y.operation),p.detail=nD(y);else{let e=QE(n);e&&(p.githubActionRequired=e,p.tone=`approval`,p.label=rD(e.action),p.toolTitle=`GitHub setup required`,p.detail=aD(e))}let b=$D(p);return b&&(p.collapseKey=b),cO.set(e,p),p}var dO=new Set([`tool.started`,`task.started`,`context-window.updated`,`text-generation.usage`,`worktree.stage`,`launch.agent-starting`,`turn.terminal-status`]);function fO(e){return dO.has(e.kind)||e.summary===`Checkpoint captured`}function pO(e,t){return!t.latestTurnId||e.turnId===t.latestTurnId||mO(e)?!0:hO(e,t.latestTurnStartedAt)}function mO(e){return e.kind.startsWith(`worktree.`)||e.kind.startsWith(`setup-script.`)}function hO(e,t){return e.turnId!==null||e.tone!==`error`||t===null?!1:e.createdAt>=t}function gO(e){return e.agentKind===`agent`}function _O(e){let t=e.payload&&typeof e.payload==`object`?e.payload:null;return!t||typeof t.taskId!=`string`?!1:gO(t)}function vO(e){let t=e.payload&&typeof e.payload==`object`?e.payload:null;return t?e.kind===`task.started`||e.kind===`task.progress`||e.kind===`task.updated`||e.kind===`task.completed`?typeof t.agentId==`string`&&t.agentId.trim().length>0||t.timelineBypass===!0?!(e.kind!==`task.updated`&&typeof t.taskId==`string`&&gO(t)):!1:t.timelineBypass===!0||typeof t.agentId==`string`&&t.agentId.trim().length>0:!1}function yO(){if(typeof window>`u`)return!1;try{return window.localStorage.getItem(`forge:debug-mode`)===`true`}catch{return!1}}function bO(e){if(e.kind!==`tool.updated`&&e.kind!==`tool.completed`)return!1;let t=e.payload&&typeof e.payload==`object`?e.payload:null;return typeof t?.detail==`string`&&t.detail.startsWith(`ExitPlanMode:`)}function xO(e,t,n){let r=yO(),i={latestTurnId:t,latestTurnStartedAt:n??null},a=[...e].toSorted(SO),o=new Set;for(let e of a)if((e.kind===`task.started`||e.kind===`task.progress`||e.kind===`task.completed`)&&_O(e)){let t=sO(oO(e.payload)?.toolUseId);t&&o.add(t)}let s=[];for(let e of vD(a)){if(!pO(e,i)||!(e.kind===`task.started`&&_O(e))&&fO(e)||e.kind===`task.started`&&!_O(e)||e.kind===`task.updated`||e.kind===`tool.progress`||e.kind===`turn.plan.updated`||!r&&kE(e)||bO(e)||vO(e))continue;let t=uO(e);if(e.kind===`tool.updated`&&t.itemType===`collab_agent_tool_call`&&t.toolLifecycleStatus===`inProgress`&&t.tone!==`error`){let t=oO(oO(e.payload)?.data)?.toolName;if(t===`Agent`||t===`Task`)continue}(e.kind===`tool.updated`||e.kind===`tool.completed`)&&t.toolCallId&&o.has(t.toolCallId)&&t.tone!==`error`&&t.toolLifecycleStatus!==`failed`||s.push(t)}return YD(s).map(({sourceActivityKind:e,collapseKey:t,isWorkflowCoordinator:n,isBackgroundTask:r,...i})=>i)}function SO(e,t){if(e.sequence!==void 0&&t.sequence!==void 0){if(e.sequence!==t.sequence)return e.sequence-t.sequence}else if(e.sequence!==void 0)return 1;else if(t.sequence!==void 0)return-1;let n=e.createdAt.localeCompare(t.createdAt);if(n!==0)return n;let r=CO(e.kind)-CO(t.kind);return r===0?e.id.localeCompare(t.id):r}function CO(e){return e.endsWith(`.started`)||e===`tool.started`?0:e.endsWith(`.progress`)||e.endsWith(`.updated`)?1:e.endsWith(`.completed`)||e.endsWith(`.resolved`)?2:1}function wO(e){return{id:e.id,kind:`message`,createdAt:e.createdAt,message:e}}function TO(e){return{id:e.id,kind:`proposed-plan`,createdAt:e.createdAt,proposedPlan:e}}function EO(e){return{id:e.id,kind:`work`,createdAt:e.createdAt,entry:e}}function DO(e,t){return e.createdAt.localeCompare(t.createdAt)}function OO(e){switch(e.kind){case`message`:return 0;case`proposed-plan`:return 1;case`work`:return 2}}function kO(e,t){let n=DO(e,t);return n===0?OO(e)<=OO(t):n<0}function AO(e,t){if(e===t)return!0;if(t.length<e.length)return!1;for(let n=0;n<e.length;n+=1)if(e[n]!==t[n])return!1;return!0}function jO(e,t){if(t.length===0)return[...e];let n=e.at(-1),r=!0;for(let e=1;e<t.length;e+=1)if(DO(t[e-1],t[e])>0){r=!1;break}if(r&&(n===void 0||kO(n,t[0])))return[...e,...t];let i=[],a=0,o=0;for(;a<e.length||o<t.length;){let n=e[a],r=t[o];n!==void 0&&(r===void 0||kO(n,r))?(i.push(n),a+=1):r!==void 0&&(i.push(r),o+=1)}return i}var MO=e=>e===`assistant`||e===`reasoning`;function NO(e,t){if(!MO(e.role)||e.role!==t.role||!e.streaming||!t.streaming)return!1;let{text:n,updatedAt:r,...i}=e,{text:a,updatedAt:o,...s}=t;return eh(i,s)}function PO(e,t){if(e.length!==t.messages.length)return null;let n=new Map;for(let[r,i]of e.entries()){let e=t.messages[r];if(i!==e){if(!NO(e,i))return null;n.set(e,i)}}return n.size===0?t.entries:t.entries.map(e=>{let t=e.kind===`message`?n.get(e.message):void 0;return t?wO(t):e})}function FO(e,t,n,r=null){if(r!==null&&r.proposedPlans.length===t.length&&r.workEntries.length===n.length&&AO(r.proposedPlans,t)&&AO(r.workEntries,n)){let i=PO(e,r);if(i!==null)return{messages:e,proposedPlans:t,workEntries:n,entries:i}}let i=new Set(n.flatMap(e=>e.questionAnswer?[`async-answer:${e.questionAnswer.requestId}`]:[])),a=e=>e.role!==`user`||!i.has(e.id);if(r!==null&&!r.entries.some(e=>e.kind===`message`&&!a(e.message))&&AO(r.messages,e)&&AO(r.proposedPlans,t)&&AO(r.workEntries,n)){let i=e.slice(r.messages.length).filter(a).map(wO),o=t.slice(r.proposedPlans.length).map(TO),s=n.slice(r.workEntries.length).map(EO),c=[...i,...o,...s].toSorted(DO);return{messages:e,proposedPlans:t,workEntries:n,entries:jO(r.entries,c)}}let o=e.filter(a).map(wO),s=t.map(TO),c=n.map(EO);return{messages:e,proposedPlans:t,workEntries:n,entries:[...o,...s,...c].toSorted(DO)}}var IO=[{value:`codex`,label:`Codex`,available:!0},{value:`claudeAgent`,label:`Claude`,available:!0},{value:`cmmd`,label:`CMMD`,available:!0},{value:`ollama`,label:`Ollama`,available:!1},{value:`cursor`,label:`Cursor`,available:!1}];function LO(e){if(!Number.isFinite(e)||e<0)return`0ms`;if(e<1e3)return`${Math.max(1,Math.round(e))}ms`;if(e<1e4)return`${(e/1e3).toFixed(1)}s`;if(e<6e4)return`${Math.round(e/1e3)}s`;let t=Math.floor(e/6e4),n=Math.round(e%6e4/1e3);return n===0?`${t}m`:n===60?`${t+1}m`:`${t}m ${n}s`}function RO(e,t){if(!t)return null;let n=Date.parse(e),r=Date.parse(t);return Number.isNaN(n)||Number.isNaN(r)||r<n?null:LO(r-n)}function zO(e,t){return!e?.startedAt||!e.completedAt?!1:!t||t.orchestrationStatus!==`running`}function BO(e,t,n){let r=t?.orchestrationStatus===`running`?t.activeTurnId??null:null;return r===null?zO(e,t)?n:e?.startedAt??n:e?.turnId===r?e.startedAt??n:n}function VO(e){let t=e?.toLowerCase();return t?t.includes(`stale pending approval request`)||t.includes(`stale pending user-input request`)||t.includes(`unknown pending approval request`)||t.includes(`unknown pending permission request`)||t.includes(`unknown pending user-input request`):!1}function HO(e){let t=new Map,n=[...e].toSorted(SO);for(let e of n){let n=e.payload&&typeof e.payload==`object`?e.payload:null,r=n&&typeof n.requestId==`string`?kr.make(n.requestId):null,i=n&&(n.requestKind===`command`||n.requestKind===`file-read`||n.requestKind===`file-change`)?n.requestKind:n?tO(n.requestType):null,a=n&&typeof n.detail==`string`?n.detail:void 0;if(e.kind===`approval.requested`&&r&&i){t.set(r,{requestId:r,requestKind:i,createdAt:e.createdAt,...a?{detail:a}:{}});continue}if(e.kind===`approval.resolved`&&r){t.delete(r);continue}if(e.kind===`provider.approval.respond.failed`&&r&&VO(a)){t.delete(r);continue}}return[...t.values()].toSorted((e,t)=>e.createdAt.localeCompare(t.createdAt))}function UO(e){let t=e?.questions;if(!Array.isArray(t))return null;let n=t.map(e=>{if(!e||typeof e!=`object`)return null;let t=e;if(typeof t.id!=`string`||typeof t.header!=`string`||typeof t.question!=`string`||!Array.isArray(t.options))return null;let n=t.options.map(e=>{if(!e||typeof e!=`object`)return null;let t=e;return typeof t.label!=`string`||typeof t.description!=`string`?null:{label:t.label,description:t.description}}).filter(e=>e!==null);return n.length===0?null:{id:t.id,header:t.header,question:t.question,options:n,multiSelect:t.multiSelect===!0}}).filter(e=>e!==null);return n.length>0?n:null}function WO(e){let t=new Map,n=[...e].toSorted(SO);for(let e of n){let n=e.payload&&typeof e.payload==`object`?e.payload:null,r=n&&typeof n.requestId==`string`?kr.make(n.requestId):null,i=n&&typeof n.detail==`string`?n.detail:void 0;if(e.kind===`user-input.requested`&&r){let i=UO(n);if(!i)continue;t.set(r,{requestId:r,createdAt:e.createdAt,questions:i});continue}if(e.kind===`user-input.resolved`&&r){t.delete(r);continue}e.kind===`provider.user-input.respond.failed`&&r&&VO(i)&&t.delete(r)}return[...t.values()].toSorted((e,t)=>e.createdAt.localeCompare(t.createdAt))}function GO(e,t){if(!t)return null;let n=[...e].toSorted(SO),r=null;for(let e of n){let t=QE(e.payload&&typeof e.payload==`object`?e.payload:null);t&&(r={request:t,turnId:e.turnId})}return!r||r.turnId!==t?null:r.request}function KO(e,t){let n=[...e].toSorted(SO),r=n.filter(e=>e.kind===`turn.plan.updated`),i=(t?r.findLast(e=>e.turnId===t):void 0)??r.at(-1)??null;if(!i)return null;let a=aE(i);if(!a)return null;let o=r.filter(e=>e.turnId===i.turnId),s=o.findLastIndex(e=>aE(e)===null),c=sE(a,o.slice(s+1)),l=i.turnId!==null&&n.some(e=>e.kind===`turn.completed`&&e.turnId===i.turnId&&SO(i,e)<0);return{...c,steps:l?c.steps.map(e=>e.status===`inProgress`?{...e,status:`completed`}:e):c.steps}}function qO(e,t){if(t){let n=[...e].filter(e=>e.turnId===t).toSorted((e,t)=>e.updatedAt.localeCompare(t.updatedAt)||e.id.localeCompare(t.id)).at(-1);if(n)return lk(n)}let n=[...e].toSorted((e,t)=>e.updatedAt.localeCompare(t.updatedAt)||e.id.localeCompare(t.id)).at(-1);return n?lk(n):null}function JO(e){let t=e.threads.find(t=>t.id===e.threadId)?.proposedPlans??[];if(!e.latestTurnSettled){let t=e.latestTurn?.sourceProposedPlan;if(t){let n=e.threads.find(e=>e.id===t.threadId)?.proposedPlans.find(e=>e.id===t.planId);if(n)return lk(n)}}return qO(t,e.latestTurn?.turnId??null)}function YO(e){return e!==null&&e.implementedAt===null}function XO(e,t){return t?e.some(e=>e.turnId===t&&e.tone===`tool`):!1}var ZO=new WeakMap;function QO(e,t){if(e.role!==`assistant`)return[];let n=ek(e.text,{workEntries:t,createdAt:e.createdAt});if(!n)return[];let r=ZO.get(e),i=`${e.id}:github-confirmation:${n.confirmationId}`;if(r&&r[0]?.id===i)return r;let a=[{id:i,kind:`work`,createdAt:e.createdAt,entry:{id:i,createdAt:e.createdAt,label:`GitHub action needs approval`,detail:nD(n),tone:`approval`,toolTitle:tD(n.operation),githubConfirmation:n}}];return ZO.set(e,a),a}function $O(e,t,n,r){let i=FO(e,t,n,r),a=e.flatMap(e=>QO(e,n));if(a.length===0)return i;let o=new Set(i.entries.map(e=>e.id)),s=a.filter(e=>!o.has(e.id));return s.length===0?i:{...i,entries:[...i.entries,...s].toSorted((e,t)=>e.createdAt.localeCompare(t.createdAt))}}function ek(e,t){if(!e.includes(`confirm_github_tool`))return null;let n=ak(e,/\b(?:New confirmation id|Confirmation id):\s*`?([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})`?/i)??null,r=/\bRepo(?: to create)?:\s*(private|public|internal)\s+`?([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+)`?/i.exec(e);if(!n)return null;let i=tk(e,n,t);if(i)return i;if(!r)return null;let a=r[1]?.toLowerCase(),o=r[2],s=r[3];return!o||!s?null:{confirmationId:n,toolName:`forge_github_create_repository`,operation:`create_repository`,request:{owner:o,name:s,visibility:a}}}function tk(e,t,n){if(!nk(e))return null;let r=rk(n?.workEntries??[],n?.createdAt,`forge_github_refresh_credentials`)?.request,i=r?ik(r.cwd):null;return i?{confirmationId:t,toolName:`forge_github_refresh_credentials`,operation:`refresh_credentials`,request:{cwd:i}}:null}function nk(e){return/\bforge_github_refresh_credentials\b/i.test(e)||/\bcredential refresh\b/i.test(e)||/\brefresh(?:ing)? GitHub credentials\b/i.test(e)}function rk(e,t,n){for(let r of e.toReversed()){if(t!==void 0&&r.createdAt>t)continue;let e=r.githubConfirmation;if(e?.toolName===n)return e}return null}function ik(e){if(typeof e!=`string`)return null;let t=e.trim();return t.length>0?t:null}function ak(e,t){return t.exec(e)?.[1]??null}function ok(e){let t=[...e].toSorted((e,t)=>e.completedAt.localeCompare(t.completedAt)),n={};for(let e=0;e<t.length;e+=1){let r=t[e];r&&(n[r.turnId]=e+1)}return n}function sk(e){return!e||e.status===`closed`?`disconnected`:e.status===`connecting`?`connecting`:e.status===`running`?`running`:`ready`}function ck(e,t){if(t===`disconnected`||t===`connecting`)return null;for(let t of e.toReversed())if(t.kind===`work`&&t.entry.githubConfirmation)return t.entry.githubConfirmation;return null}function lk(e){return{id:e.id,createdAt:e.createdAt,updatedAt:e.updatedAt,turnId:e.turnId,planMarkdown:e.planMarkdown,implementedAt:e.implementedAt,implementationThreadId:e.implementationThreadId}}function uk(e){let t=e.browser,n=t?{openSession:t.openSession,listSessions:t.listSessions,closeSession:t.closeSession,getSession:t.getSession,command:t.command,clearBrowsingData:t.clearBrowsingData,attachDisplay:t.attachDisplay,addDisplayIceCandidate:async e=>{await t.addDisplayIceCandidate(e)},onEvent:(e,n)=>t.onEvent(e,n)}:void 0;return{...n?{browser:n}:{},attachments:{createUploadUrl:t=>e.attachments.createUploadUrl(t),delete:t=>e.attachments.delete(t)},computer:{input:t=>e.computer.input(t)},threadDevRuntime:{get:t=>e.threadDevRuntime.get(t),allocatePort:t=>e.threadDevRuntime.allocatePort(t),release:t=>e.threadDevRuntime.release(t)},devTunnel:{register:t=>e.devTunnel.register(t),unregister:t=>e.devTunnel.unregister(t),list:t=>e.devTunnel.list(t)},terminal:{open:t=>e.terminal.open(t),write:t=>e.terminal.write(t),resize:t=>e.terminal.resize(t),signal:t=>e.terminal.signal(t),clear:t=>e.terminal.clear(t),restart:t=>e.terminal.restart(t),close:t=>e.terminal.close(t),onEvent:t=>e.terminal.onEvent(t)},projects:{searchContents:e.projects.searchContents,searchEntries:e.projects.searchEntries,readFile:e.projects.readFile,writeFile:e.projects.writeFile},workspace:{environmentPreflight:e.workspace.environmentPreflight,listDirectory:e.workspace.listDirectory,ensureScratch:e.workspace.ensureScratch},shell:{openInEditor:t=>e.shell.openInEditor(t)},git:{pull:e.git.pull,refreshStatus:e.git.refreshStatus,onStatus:(t,n,r)=>e.git.onStatus(t,n,r),listBranches:e.git.listBranches,createWorktree:e.git.createWorktree,removeWorktree:e.git.removeWorktree,createBranch:e.git.createBranch,checkout:e.git.checkout,init:e.git.init,resolvePullRequest:e.git.resolvePullRequest,preparePullRequestThread:e.git.preparePullRequestThread},pullRequests:{list:t=>e.pullRequests.list(t),listStats:t=>e.pullRequests.listStats(t),detail:t=>e.pullRequests.detail(t),activity:t=>e.pullRequests.activity(t),threadComments:t=>e.pullRequests.threadComments(t),diffFileContents:t=>e.pullRequests.diffFileContents(t),runAction:t=>e.pullRequests.runAction(t),update:t=>e.pullRequests.update(t),comment:t=>e.pullRequests.comment(t),updateComment:t=>e.pullRequests.updateComment(t),submitReview:t=>e.pullRequests.submitReview(t),replyToThread:t=>e.pullRequests.replyToThread(t),setThreadResolution:t=>e.pullRequests.setThreadResolution(t),setReaction:t=>e.pullRequests.setReaction(t),invalidate:t=>e.pullRequests.invalidate(t),reviewerCandidates:t=>e.pullRequests.reviewerCandidates(t),requestReviewers:t=>e.pullRequests.requestReviewers(t)},orchestration:{dispatchCommand:e.orchestration.dispatchCommand,searchThreads:e.orchestration.searchThreads,getTurnDiff:e.orchestration.getTurnDiff,getFullThreadDiff:e.orchestration.getFullThreadDiff,subscribeShell:(t,n)=>e.orchestration.subscribeShell(t,n),subscribeThread:(t,n,r)=>e.orchestration.subscribeThread(t,n,r)}}}function dk(e){if(typeof window>`u`||!e)return;let t=dw(e);return t?uk(t.client):void 0}function fk(e){let t=(0,A.c)(4),n;t[0]===e?n=t[1]:(n=()=>dw(e),t[0]=e,t[1]=n);let r=(0,O.useSyncExternalStore)(uw,n,pk),i,a;return t[2]===r?a=t[3]:(a=r?uk(r.client):void 0,t[2]=r,t[3]=a),i=a,i}function pk(){return null}function mk(e){let t=dk(e);if(!t)throw Error(`Environment API not found for environment ${e}`);return t}var hk=[`preview`,`terminal`,`canvas`,`diff`,`plan`,`task`,`simulator`,`display`,`agents`,`file`,`files`,`pull-request`],gk={isOpen:!1,isMaximized:!1,activeSurfaceId:null,surfaces:[]};function _k(e){return e===null?{id:`browser:new`,kind:`preview`,resourceId:null}:{id:`browser:${e}`,kind:`preview`,resourceId:e}}function vk(e,t,n,r=`execution-intent`){return{id:`file:${e}`,kind:`file`,relativePath:e,revealLine:t,revealRequestId:n,readPolicy:r}}function yk(e){let t=[e.provider,e.environmentId,e.repositoryLinkId??``,e.projectId,e.host.toLowerCase(),e.repository,String(e.number)].map(e=>encodeURIComponent(e)).join(`:`);return{...e,id:`pull-request:${t}`,kind:`pull-request`}}function bk(e){return e===`diff`?{id:`diff`,kind:`diff`,turnId:null,filePath:null}:{id:e,kind:e}}var xk=`workspace:pull-requests`;function Sk(e){return typeof e==`object`&&!!e}function Ck(e){return typeof e==`string`&&hk.includes(e)}function wk(e){return typeof e==`number`&&Number.isFinite(e)?Math.max(1,Math.trunc(e)):null}function Tk(e){return typeof e==`number`&&Number.isSafeInteger(e)&&e>=0?e:0}function Ek(e){let t=e.relativePath;return typeof t!=`string`||t.length===0?null:{id:`file:${t}`,kind:`file`,relativePath:t,revealLine:wk(e.revealLine),revealRequestId:Tk(e.revealRequestId),readPolicy:e.readPolicy===`connected-only`?`connected-only`:`execution-intent`}}function Dk(e){let t=e.resourceId;return t==null?{id:`browser:new`,kind:`preview`,resourceId:null}:typeof t!=`string`||t.length===0?null:{id:`browser:${t}`,kind:`preview`,resourceId:t}}function Ok(e){let t=e.turnId,n=e.filePath,r=typeof t==`string`&&t.length>0?Vr.make(t):null;return{id:`diff`,kind:`diff`,turnId:r,filePath:r&&typeof n==`string`&&n.length>0?n:null}}var kk=new Set([`github`,`gitlab`,`azure-devops`,`bitbucket`,`unknown`]);function Ak(e){return typeof e==`string`&&e.length>0}function jk(e){return e===null||typeof e==`string`}function Mk(e){return e===void 0||jk(e)}function Nk(e){let t=e.provider,n=e.environmentId,r=e.repositoryLinkId,i=e.projectId,a=e.host,o=e.repository,s=wk(e.number),c=e.title;return![Ak(t)&&kk.has(t),Ak(n),jk(r),Ak(i),Ak(a),Ak(o),s!==null,Mk(c)].every(Boolean)||!Ak(t)||!Ak(n)?null:yk({provider:t,environmentId:Hr.make(n),repositoryLinkId:r,projectId:xi.make(i),host:a,repository:o,number:s,...typeof c==`string`||c===null?{title:c}:{}})}function Pk(e){let t=e.label;if(typeof t!=`string`)return;let n=t.trim();return n.length>0?n:void 0}function Fk(e){if(!Sk(e)||!Ck(e.kind))return null;let t=e.kind,n=t===`file`?Ek(e):t===`preview`?Dk(e):t===`diff`?Ok(e):t===`pull-request`?Nk(e):{id:t,kind:t};if(n===null)return null;let r=Pk(e);return r===void 0?n:{...n,label:r}}function Ik(e){let t=[],n=new Set;for(let r of Array.isArray(e)?e:[]){let e=Fk(r);!e||n.has(e.id)||(n.add(e.id),t.push(e))}return t}function Lk(e){if(!Sk(e))return null;let t=Ik(e.surfaces);if(t.length===0)return null;let n=e.activeSurfaceId,r=t.some(e=>e.id===n),i=typeof n==`string`&&r?n:t[0]?.id??null;return{isOpen:e.isOpen===!0,activeSurfaceId:i,surfaces:t}}function Rk(e){if(!Sk(e)||!Sk(e.byThreadKey))return{byThreadKey:{}};let t={};for(let[n,r]of Object.entries(e.byThreadKey)){if(n===xk)continue;let e=Lk(r);e&&(t[n]=e)}return{byThreadKey:t}}var zk=`forge:right-panel-state`,Bk=3,Vk=e=>e===`workspace:pull-requests`;function Hk(e){return`draft:${e}`}function Uk(e){return e.startsWith(`draft:`)}function Wk(e){return e==null||!Number.isFinite(e)?null:Math.max(1,Math.trunc(e))}var Gk=(e,t,n=!0)=>({...e,isOpen:!0,surfaces:e.surfaces.some(e=>e.id===t.id)?e.surfaces:[...e.surfaces,t],activeSurfaceId:n?t.id:e.activeSurfaceId});function Kk(e,t){if(t.length===0){let{label:t,...n}=e;return n}return{...e,label:t}}var z=(e,t,n)=>{let r=e[t]??gk,i=n(r);if(!i.isOpen&&i.activeSurfaceId===null&&i.surfaces.length===0){if(!(t in e))return e;let{[t]:n,...r}=e;return r}return i===r?e:{...e,[t]:i}},qk=wa()(Gf(e=>({byThreadKey:{},open:(t,n)=>e(e=>({byThreadKey:z(e.byThreadKey,t,e=>Gk(e,e.surfaces.find(e=>e.kind===n)??bk(n)))})),openBrowser:(t,n)=>e(e=>({byThreadKey:z(e.byThreadKey,t,e=>{let t=n?e.surfaces.filter(e=>e.id!==`browser:new`):e.surfaces;return Gk({...e,surfaces:t},_k(n))})})),revealBrowser:t=>e(e=>({byThreadKey:z(e.byThreadKey,t,e=>Gk(e,e.surfaces.find(e=>e.kind===`preview`)??_k(null)))})),openDiff:(t,n,r)=>e(e=>({byThreadKey:z(e.byThreadKey,t,e=>{let t={id:`diff`,kind:`diff`,turnId:n??null,filePath:n?r??null:null};return{...e,isOpen:!0,activeSurfaceId:t.id,surfaces:e.surfaces.some(e=>e.id===`diff`)?e.surfaces.map(e=>e.id===`diff`?t:e):[...e.surfaces,t]}})})),openFile:(t,n,r,i=`execution-intent`)=>e(e=>({byThreadKey:z(e.byThreadKey,t,e=>{let t=`file:${n}`,a=e.surfaces.find(e=>e.id===t&&e.kind===`file`),o=vk(n,Wk(r),(a?.revealRequestId??0)+1,i);return{...e,isOpen:!0,activeSurfaceId:o.id,surfaces:a?e.surfaces.map(e=>e.id===o.id?o:e):[...e.surfaces,o]}})})),openPullRequest:(t,n)=>e(e=>({byThreadKey:z(e.byThreadKey,t,e=>Gk(e,yk(n)))})),activateSurface:(t,n)=>e(e=>({byThreadKey:z(e.byThreadKey,t,e=>e.surfaces.some(e=>e.id===n)?{...e,isOpen:!0,activeSurfaceId:n}:e)})),closeSurface:(t,n)=>e(e=>({byThreadKey:z(e.byThreadKey,t,e=>{let t=e.surfaces.findIndex(e=>e.id===n);if(t<0)return e;let r=e.surfaces.filter(e=>e.id!==n);if(e.activeSurfaceId!==n)return{...e,isOpen:r.length>0&&e.isOpen,surfaces:r};let i=r[Math.min(t,r.length-1)]??null;return{...e,isOpen:r.length>0&&e.isOpen,surfaces:r,activeSurfaceId:i?.id??null}})})),closeOtherSurfaces:(t,n)=>e(e=>({byThreadKey:z(e.byThreadKey,t,e=>{let t=e.surfaces.find(e=>e.id===n);return!t||e.surfaces.length===1?e:{...e,isOpen:!0,surfaces:[t],activeSurfaceId:t.id}})})),closeSurfacesToRight:(t,n)=>e(e=>({byThreadKey:z(e.byThreadKey,t,e=>{let t=e.surfaces.findIndex(e=>e.id===n);if(t<0||t===e.surfaces.length-1)return e;let r=e.surfaces.slice(0,t+1),i=r.some(t=>t.id===e.activeSurfaceId);return{...e,surfaces:r,activeSurfaceId:i?e.activeSurfaceId:n}})})),closeAllSurfaces:t=>e(e=>({byThreadKey:z(e.byThreadKey,t,()=>gk)})),renameSurface:(t,n,r)=>e(e=>({byThreadKey:z(e.byThreadKey,t,e=>{let t=r.trim();return{...e,surfaces:e.surfaces.map(e=>e.id===n?Kk(e,t):e)}})})),show:t=>e(e=>({byThreadKey:z(e.byThreadKey,t,e=>({...e,isOpen:!0}))})),close:t=>e(e=>({byThreadKey:z(e.byThreadKey,t,e=>e.isOpen?{...e,isOpen:!1,isMaximized:!1}:e)})),toggleVisibility:t=>e(e=>({byThreadKey:z(e.byThreadKey,t,e=>({...e,isOpen:!e.isOpen}))})),toggleMaximized:t=>e(e=>({byThreadKey:z(e.byThreadKey,t,e=>e.isOpen?{...e,isMaximized:!(e.isMaximized??!1)}:e)})),removeThread:t=>e(e=>{if(!(t in e.byThreadKey))return e;let{[t]:n,...r}=e.byThreadKey;return{byThreadKey:r}})}),{name:zk,version:Bk,storage:Uf(()=>An),partialize:e=>({byThreadKey:Object.fromEntries(Object.entries(e.byThreadKey).filter(([e])=>!Uk(e)&&!Vk(e)))}),migrate:e=>Rk(e)}));function Jk(e,t){let n={hour:`numeric`,minute:`2-digit`,...t?{second:`2-digit`}:{}};return e===`locale`?n:{...n,hour12:e===`12-hour`}}var Yk=new Map;function Xk(e,t){let n=`${e}:${t?`seconds`:`minutes`}`,r=Yk.get(n);if(r)return r;let i=new Intl.DateTimeFormat(void 0,Jk(e,t));return Yk.set(n,i),i}function Zk(e,t){return Xk(t,!0).format(new Date(e))}function Qk(e,t){return Xk(t,!1).format(new Date(e))}function $k(e){let t=Date.now()-new Date(e).getTime();if(t<0)return{value:`just now`,suffix:null};let n=Math.floor(t/1e3);if(n<60)return{value:`just now`,suffix:null};let r=Math.floor(n/60);if(r<60)return{value:`${r}m`,suffix:`ago`};let i=Math.floor(r/60);return i<24?{value:`${i}h`,suffix:`ago`}:{value:`${Math.floor(i/24)}d`,suffix:`ago`}}function eA(e){let t=$k(e);return t.suffix?`${t.value} ${t.suffix}`:t.value}function tA(e){if(e===null)return null;let t=e.trim();return t.length>0?t:null}var nA=Object.freeze({data:null,error:null,cause:null,isPending:!1}),rA=Object.freeze({...nA,isPending:!0}),iA=un(nA).pipe(ln,sn(`git-status:null`)),aA=()=>void 0,oA=new Map,sA=new Set,cA=new Map,lA=new Map,uA=1e3,dA=on(e=>(sA.add(e),un(rA).pipe(ln,sn(`git-status:${e}`))));function fA(e){return e.environmentId===null||tA(e.cwd)===null?null:`${e.environmentId}:${e.cwd}`}function pA(e){if(e.environmentId===null)return null;let t=dw(e.environmentId);return t?{clientIdentity:t.environmentId,client:t.client.git}:null}function mA(e){let t=fA(e);return t===null?nA:cn.get(dA(t))}function hA(e,t){let n=fA(e);if(n===null)return aA;let r=oA.get(n);return r?(r.refCount+=1,()=>vA(n)):(oA.set(n,{refCount:1,unsubscribe:yA(n,e,t)}),()=>vA(n))}function gA(e,t){let n=fA(e),r=tA(e.cwd);if(n===null||r===null)return Promise.resolve(null);let i=t??pA(e)?.client;if(!i)return Promise.resolve(mA(e).data);let a=cA.get(n);if(a)return a;let o=lA.get(n)??0;if(Date.now()-o<uA)return Promise.resolve(mA(e).data);lA.set(n,Date.now());let s=i.refreshStatus({cwd:r}).finally(()=>{cA.delete(n)});return cA.set(n,s),s}function _A(e){let t=(0,A.c)(4),n=fA(e),r,i;t[0]!==e.cwd||t[1]!==e.environmentId?(r=()=>hA({environmentId:e.environmentId,cwd:e.cwd}),i=[e.environmentId,e.cwd],t[0]=e.cwd,t[1]=e.environmentId,t[2]=r,t[3]=i):(r=t[2],i=t[3]),(0,O.useEffect)(r,i);let a=ma(n===null?iA:dA(n));return n===null?nA:a}function vA(e){let t=oA.get(e);t&&(--t.refCount,!(t.refCount>0)&&(t.unsubscribe(),oA.delete(e)))}function yA(e,t,n){let r=tA(t.cwd);if(r===null)return aA;let i=null,a=aA,o=()=>{let o=n?{clientIdentity:`provided:${e}`,client:n}:pA(t);if(!o){i!==null&&(a(),a=aA,i=null),xA(e);return}i!==o.clientIdentity&&(a(),i=o.clientIdentity,a=bA(e,r,o.client))},s=n?aA:uw(o);return o(),()=>{s(),a()}}function bA(e,t,n){return xA(e),n.onStatus({cwd:t},t=>{cn.set(dA(e),{data:t,error:null,cause:null,isPending:!1})},{onResubscribe:()=>{xA(e)}})}function xA(e){let t=dA(e),n=cn.get(t),r=n.data===null?rA:{...n,error:null,cause:null,isPending:!0};(n.data!==r.data||n.error!==r.error||n.cause!==r.cause||n.isPending!==r.isPending)&&cn.set(t,r)}function SA(e){let t=[];for(let n of e){let e=n.children??[];if(e.length>0){t.push({item:n,isGroupLabel:!0});for(let n of e)t.push({item:n,isGroupLabel:!1});continue}Array.isArray(n.children)||t.push({item:n,isGroupLabel:!1})}return t}function CA(e){let t=document.createElement(`div`);return t.textContent=e,t.className=`px-2 pt-1.5 pb-0.5 text-[10px] font-medium uppercase tracking-wide text-muted-foreground/70`,t}function wA(e){let t=document.createElement(`button`);return t.type=`button`,t.textContent=e.label,t.disabled=e.disabled,t.className=e.disabled?`flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-[11px] text-muted-foreground/50 cursor-not-allowed`:e.destructive?`flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-[11px] text-destructive transition-colors hover:bg-accent`:`flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-[11px] text-popover-foreground transition-colors hover:bg-accent`,t}function TA(e,t){return new Promise(n=>{let r=document.createElement(`div`);r.style.cssText=`position:fixed;inset:0;z-index:9999`;let i=document.createElement(`div`);i.className=`fixed z-[10000] min-w-[160px] rounded-lg border bg-popover p-1 text-popover-foreground shadow-lg/5 outline-none before:pointer-events-none before:absolute before:inset-0 before:rounded-[calc(var(--radius-lg)-1px)] before:shadow-[0_1px_--theme(--color-black/4%)] dark:before:shadow-[0_-1px_--theme(--color-white/6%)]`;let a=t?.x??0,o=t?.y??0;i.style.top=`${o}px`,i.style.left=`${a}px`;function s(e){document.removeEventListener(`keydown`,c),r.remove(),i.remove(),n(e)}function c(e){e.key===`Escape`&&(e.preventDefault(),s(null))}r.addEventListener(`mousedown`,()=>s(null)),document.addEventListener(`keydown`,c);let l=!1;for(let{item:t,isGroupLabel:n}of SA(e)){if(n){i.appendChild(CA(t.label));continue}let e=t.destructive===!0||t.id===`delete`,r=t.disabled===!0;if(e&&!l){let e=document.createElement(`div`);e.className=`-mx-1 my-1 h-px bg-border`,i.appendChild(e),l=!0}let a=wA({label:t.label,disabled:r,destructive:e});r||a.addEventListener(`click`,()=>s(t.id)),i.appendChild(a)}document.body.appendChild(r),document.body.appendChild(i),requestAnimationFrame(()=>{let e=i.getBoundingClientRect();e.right>window.innerWidth&&(i.style.left=`${window.innerWidth-e.width-4}px`),e.bottom>window.innerHeight&&(i.style.top=`${window.innerHeight-e.height-4}px`)})})}var EA;function DA(){return OA(mw().client)}function OA(e){return{getConfig:e.server.getConfig,refreshProviders:e.server.refreshProviders,startProviderAuth:e.server.startProviderAuth,repairProviderAuthRuntime:e.server.repairProviderAuthRuntime,disconnectProviderAuth:e.server.disconnectProviderAuth,getProviderAuthSession:e.server.getProviderAuthSession,cancelProviderAuth:e.server.cancelProviderAuth,submitProviderAuthCode:e.server.submitProviderAuthCode,syncPersonalCodexToCloud:e.server.syncPersonalCodexToCloud,syncPersonalClaudeToCloud:e.server.syncPersonalClaudeToCloud,upsertKeybinding:e.server.upsertKeybinding,removeKeybinding:e.server.removeKeybinding,getSettings:e.server.getSettings,updateSettings:e.server.updateSettings,updateEnvironmentDisplayName:async t=>{let n=await e.server.updateEnvironmentDisplayName({displayName:t});return $w(n.environment),n}}}function kA(e,t){return{...e,...t,dialogs:{...e.dialogs,...t.dialogs},shell:{...e.shell,...t.shell},contextMenu:{...e.contextMenu,...t.contextMenu},persistence:{...e.persistence,...t.persistence},server:{...e.server,...t.server}}}function AA(e){return{dialogs:{pickFolder:async()=>window.desktopBridge?window.desktopBridge.pickFolder():null,confirm:async e=>window.desktopBridge?window.desktopBridge.confirm(e):window.confirm(e)},shell:{openInEditor:(t,n)=>e.shell.openInEditor({cwd:t,editor:n}),openExternal:async e=>{if(window.desktopBridge){if(!await window.desktopBridge.openExternal(e))throw Error(`Unable to open link.`);return}window.open(e,`_blank`,`noopener,noreferrer`)}},contextMenu:{show:async(e,t)=>window.desktopBridge?window.desktopBridge.showContextMenu(e,t):TA(e,t)},persistence:{getClientSettings:tr,setClientSettings:or,getSavedEnvironmentRegistry:pr,setSavedEnvironmentRegistry:rr,getSavedEnvironmentSecret:Kn,setSavedEnvironmentSecret:Zn,removeSavedEnvironmentSecret:Jn},server:OA(e)}}function jA(){if(typeof window>`u`)return;if(EA)return EA;let e=AA(mw().client);return window.nativeApi?(EA=kA(e,window.nativeApi),EA):(EA=e,EA)}function MA(){let e=jA();if(!e)throw Error(`Local API not found`);return e}function NA(){let e=(0,A.c)(2),[t,n]=(0,O.useState)(PA),r,i;return e[0]===Symbol.for(`react.memo_cache_sentinel`)?(r=()=>(n(Ia()),Pa(()=>{n(Ia())})),i=[],e[0]=r,e[1]=i):(r=e[0],i=e[1]),(0,O.useEffect)(r,i),t}function PA(){return Ia()}function FA(e,t){e.style.setProperty(`--appearance-contrast-base`,`${Math.min(t,100)}%`),e.style.setProperty(`--appearance-contrast-boost`,`${Math.max(t-100,0)}%`),e.style.setProperty(`--appearance-contrast-border-boost`,`${Math.max(t-100,0)/4}%`)}var IA=`-apple-system, BlinkMacSystemFont, "Segoe UI", system-ui, sans-serif`,LA=`ui-monospace, "SF Mono", "SFMono-Regular", Menlo, Consolas, "Liberation Mono", monospace`;function RA(e){let t=e.trim();return t.length===0?``:/^(['"]).*\1$/u.test(t)||/^[a-zA-Z][a-zA-Z0-9-]*$/u.test(t)?t:`"${t.replaceAll(`"`,``)}"`}function zA(e){let t=e.split(`,`).map(RA).filter(e=>e.length>0);return t.length>0?t.join(`, `):null}var BA={appearanceContrastBase:`--appearance-contrast-base`,appearanceContrastBoost:`--appearance-contrast-boost`,appearanceContrastBorderBoost:`--appearance-contrast-border-boost`,fontSans:`--font-sans`,fontMono:`--font-mono`,fontComposer:`--font-composer`,fontTerminal:`--font-terminal`,promptFontSize:`--forge-prompt-font-size`,terminalFontSize:`--forge-terminal-font-size`,glassOpacity:`--glass-opacity`};function VA(e,t){let n=[[BA.fontSans,t.fontFamilySans,IA],[BA.fontMono,t.fontFamilyCode,LA],[BA.fontComposer,t.fontFamilyComposer,`var(--font-sans)`],[BA.fontTerminal,t.fontFamilyTerminal,`var(--font-mono)`]];for(let[t,r,i]of n){let n=zA(r);if(n===null){e.style.removeProperty(t);continue}e.style.setProperty(t,`${n}, ${i}`)}e.style.setProperty(BA.promptFontSize,`${String(t.promptFontSize)}px`),e.style.setProperty(BA.terminalFontSize,`${String(t.terminalFontSize)}px`),e.style.setProperty(BA.glassOpacity,`${String(t.glassOpacity)}%`),FA(e,t.appearanceContrast),t.fontSmoothing?e.style.setProperty(`-webkit-font-smoothing`,`antialiased`):e.style.removeProperty(`-webkit-font-smoothing`)}function HA(){return typeof window<`u`&&typeof localStorage<`u`}function UA(){if(!HA())return{};try{let e=JSON.parse(window.localStorage.getItem(`forge:theme-halves:v1`)??`null`);if(typeof e!=`object`||!e||Array.isArray(e))return{};let t={};for(let n of[`light`,`dark`]){let r=e[n];typeof r==`string`&&(t[n]=r)}return t}catch{return{}}}function WA(){if(!HA())return null;try{return Na(window.localStorage.getItem(Ra))}catch{return null}}function GA(e){if(HA())try{e===null||e.light===void 0&&e.dark===void 0?window.localStorage.removeItem(Ra):window.localStorage.setItem(Ra,JSON.stringify(e))}catch{}}function KA(e,t,n){let r={...e};return n===null?delete r[t]:r[t]=n,r}function qA(e){return e!==null&&(e.light!==void 0||e.dark!==void 0)?e:null}function JA(e,t){let n=(0,A.c)(13),[r,i]=(0,O.useState)(YA),a=NA(),o;n[0]===Symbol.for(`react.memo_cache_sentinel`)?(o=(e,t)=>{let n=KA(UA(),e,t);return GA(n),i(qA(n)),!0},n[0]=o):o=n[0];let s=o,c;n[1]===Symbol.for(`react.memo_cache_sentinel`)?(c=()=>(GA(null),i(null),!0),n[1]=c):c=n[1];let l=c,u;n[2]!==t||n[3]!==r||n[4]!==e?(u=()=>{let n=t===`dark`?`dark`:`light`;Fa(La(e,r,n),n)},n[2]=t,n[3]=r,n[4]=e,n[5]=u):u=n[5];let d;n[6]!==a||n[7]!==t||n[8]!==r||n[9]!==e?(d=[e,t,r,a],n[6]=a,n[7]=t,n[8]=r,n[9]=e,n[10]=d):d=n[10],(0,O.useEffect)(u,d);let f;return n[11]===r?f=n[12]:(f={themeHalves:r,setThemeHalf:s,clearThemeHalves:l},n[11]=r,n[12]=f),f}function YA(){return WA()}var XA=`theme-color`,ZA=`meta[name="${XA}"][data-dynamic-theme-color="true"]`,QA={dark:`#0a0a0a`,light:`#ffffff`};function $A(){let e=document.querySelector(ZA);return e||(e=document.createElement(`meta`),e.name=XA,e.setAttribute(`data-dynamic-theme-color`,`true`),document.head.append(e),e)}function ej(e){let t=e?.trim().toLowerCase();return!t||t===`transparent`||t===`rgba(0, 0, 0, 0)`||t===`rgba(0 0 0 / 0)`?null:e?.trim()??null}function tj(){return document.querySelector(`main[data-slot='sidebar-inset']`)??document.querySelector(`[data-slot='sidebar-inner']`)??document.body}function nj(){return document.documentElement.classList.contains(`dark`)?`dark`:`light`}function rj(e=nj()){if(typeof document>`u`||typeof getComputedStyle>`u`)return;document.documentElement.style.backgroundColor=``,document.body.style.backgroundColor=``;let t=ej(getComputedStyle(tj()).backgroundColor),n=ej(getComputedStyle(document.body).backgroundColor),r=t??n??QA[e];document.documentElement.style.backgroundColor=r,document.body.style.backgroundColor=r,$A().setAttribute(`content`,r)}var ij=`forge:theme`,aj=`(prefers-color-scheme: dark)`;function oj(e){return e===`system`||e===`light`||e===`dark`}function sj(e,t){return typeof e!=`number`||!Number.isFinite(e)?t:Math.min(20,Math.max(11,Math.round(e)))}function cj(){if(!HA())return{theme:`system`,uiFontSize:16,codeFontSize:13};try{let e=window.localStorage.getItem(Yn);if(e){let t=Un(JSON.parse(e));return{theme:oj(t.theme)?t.theme:`system`,uiFontSize:sj(t.uiFontSize,16),codeFontSize:sj(t.codeFontSize,13)}}let t=window.localStorage.getItem(ij);return{theme:oj(t)?t:`system`,uiFontSize:16,codeFontSize:13}}catch{return{theme:`system`,uiFontSize:16,codeFontSize:13}}}function lj(){return typeof window>`u`||typeof window.matchMedia!=`function`||window.matchMedia(aj).matches?`dark`:`light`}function uj(e){return e===`system`?lj():e}function dj(e){if(typeof window>`u`)return;let t=window.desktopBridge;t&&t.setTheme(e).catch(()=>{})}function fj(e,t=!1){let n=uj(e);return typeof document>`u`||typeof window>`u`?n:(t&&document.documentElement.classList.add(`no-transitions`),document.documentElement.classList.toggle(`dark`,n===`dark`),document.documentElement.dataset.theme=e,document.documentElement.style.colorScheme=n,rj(n),dj(e),t&&(document.documentElement.offsetHeight,requestAnimationFrame(()=>{document.documentElement.classList.remove(`no-transitions`)})),n)}function pj(e){typeof document>`u`||document.documentElement.style.setProperty(`--forge-ui-font-size`,`${sj(e,16)}px`)}function mj(e){typeof document>`u`||document.documentElement.style.setProperty(`--forge-code-font-size`,`${sj(e,13)}px`)}function hj(e){pj(e.uiFontSize),mj(e.codeFontSize)}if(typeof document<`u`){let e=cj();fj(e.theme),hj(e)}function gj(){let e=(0,A.c)(33),t=WT(bj),n=WT(yj),r=WT(vj),i=WT(_j),{updateSettings:a}=GT(),o;e[0]===t?o=e[1]:(o=()=>uj(t),e[0]=t,e[1]=o);let[s,c]=(0,O.useState)(o),{themeHalves:l,setThemeHalf:u,clearThemeHalves:d}=JA(n,s),f;e[2]===a?f=e[3]:(f=e=>{a({theme:e}),c(fj(e,!0))},e[2]=a,e[3]=f);let p=f,m;e[4]===a?m=e[5]:(m=e=>{a({themeId:e})},e[4]=a,e[5]=m);let h=m,g;e[6]===a?g=e[7]:(g=e=>{let t=sj(e,16);a({uiFontSize:t}),pj(t)},e[6]=a,e[7]=g);let _=g,v;e[8]===a?v=e[9]:(v=e=>{let t=sj(e,13);a({codeFontSize:t}),mj(t)},e[8]=a,e[9]=v);let y=v,b,x;e[10]===t?(b=e[11],x=e[12]):(b=()=>{c(fj(t))},x=[t],e[10]=t,e[11]=b,e[12]=x),(0,O.useEffect)(b,x);let ee,te;e[13]!==i||e[14]!==r?(ee=()=>{hj({uiFontSize:r,codeFontSize:i})},te=[r,i],e[13]=i,e[14]=r,e[15]=ee,e[16]=te):(ee=e[15],te=e[16]),(0,O.useEffect)(ee,te);let ne,re;e[17]===t?(ne=e[18],re=e[19]):(re=()=>{if(t!==`system`||typeof window>`u`||typeof window.matchMedia!=`function`)return;let e=window.matchMedia(aj),n=()=>{c(fj(`system`,!0))};return e.addEventListener(`change`,n),()=>{e.removeEventListener(`change`,n)}},ne=[t],e[17]=t,e[18]=ne,e[19]=re),(0,O.useEffect)(re,ne);let ie;return e[20]!==d||e[21]!==i||e[22]!==s||e[23]!==y||e[24]!==p||e[25]!==u||e[26]!==h||e[27]!==_||e[28]!==t||e[29]!==l||e[30]!==n||e[31]!==r?(ie={theme:t,setTheme:p,themeId:n,setThemeId:h,resolvedTheme:s,themeHalves:l,setThemeHalf:u,clearThemeHalves:d,uiFontSize:r,codeFontSize:i,setUiFontSize:_,setCodeFontSize:y},e[20]=d,e[21]=i,e[22]=s,e[23]=y,e[24]=p,e[25]=u,e[26]=h,e[27]=_,e[28]=t,e[29]=l,e[30]=n,e[31]=r,e[32]=ie):ie=e[32],ie}function _j(e){return e.codeFontSize}function vj(e){return e.uiFontSize}function yj(e){return e.themeId}function bj(e){return e.theme}function xj(){let e=(0,A.c)(11),t=WT(Aj),n=WT(kj),r=WT(Oj),i=WT(Dj),a=WT(Ej),o=WT(Tj),s=WT(wj),c=WT(Cj),l=WT(Sj),u,d;e[0]!==t||e[1]!==r||e[2]!==i||e[3]!==n||e[4]!==a||e[5]!==c||e[6]!==l||e[7]!==o||e[8]!==s?(u=()=>{typeof document>`u`||VA(document.documentElement,{appearanceContrast:t,fontFamilyCode:r,fontFamilyComposer:i,fontFamilySans:n,fontFamilyTerminal:a,fontSmoothing:c,glassOpacity:l,promptFontSize:o,terminalFontSize:s})},d=[t,r,i,n,a,c,l,o,s],e[0]=t,e[1]=r,e[2]=i,e[3]=n,e[4]=a,e[5]=c,e[6]=l,e[7]=o,e[8]=s,e[9]=u,e[10]=d):(u=e[9],d=e[10]),(0,O.useEffect)(u,d)}function Sj(e){return e.glassOpacity}function Cj(e){return e.fontSmoothing}function wj(e){return e.terminalFontSize}function Tj(e){return e.promptFontSize}function Ej(e){return e.fontFamilyTerminal}function Dj(e){return e.fontFamilyComposer}function Oj(e){return e.fontFamilyCode}function kj(e){return e.fontFamilySans}function Aj(e){return e.appearanceContrast}var jj=`forge:last-editor`;function Mj(e){let t=(0,A.c)(5),[n,r]=Nn(jj,null,bi),i;bb0:{if(n&&e.includes(n)){i=n;break bb0}let r;t[0]===e?r=t[1]:(r=Sr.find(t=>e.includes(t.id))?.id??null,t[0]=e,t[1]=r),i=r}let a=i,o;return t[2]!==a||t[3]!==r?(o=[a,r],t[2]=a,t[3]=r,t[4]=o):o=t[4],o}function Nj(e){let t=new Set(e),n=jn(jj,bi);if(n&&t.has(n))return n;let r=Sr.find(e=>t.has(e.id))?.id??null;return r&&_r(jj,r,bi),r??null}async function Pj(e,t){let{availableEditors:n}=await e.server.getConfig(),r=Nj(n);if(!r)throw Error(`No available editors found.`);return await e.shell.openInEditor(t,r),r}var Fj=/https?:\/\/[^\s"'`<>]+/g,Ij=/(?:~\/|\.{1,2}\/|\/|[A-Za-z]:[\\/]|\\\\)[^\s"'`<>]+|[A-Za-z0-9._-]+(?:\/[A-Za-z0-9._-]+)+(?::\d+){0,2}/g,Lj=/[.,;!?]+$/;function Rj(e){let t=e.replace(Lj,``);if(t.length===0)return t;let n=(e,n)=>{for(;t.endsWith(n);){if(t.split(e).length-1>=t.split(n).length-1)return;t=t.slice(0,-1)}};return n(`(`,`)`),n(`[`,`]`),n(`{`,`}`),t}function zj(e,t){return e.start<t.end&&t.start<e.end}function Bj(e,t,n,r){let i=[];n.lastIndex=0;for(let a of e.matchAll(n)){let e=a[0],n=a.index??-1;if(n<0||e.length===0)continue;let o=Rj(e);if(o.length===0||t===`path`&&/^https?:\/\//i.test(o))continue;let s={kind:t,text:o,start:n,end:n+o.length};[...r,...i].some(e=>zj(s,e))||i.push(s)}return i}function Vj(e){return/^[A-Za-z]:[\\/]/.test(e)||e.startsWith(`\\\\`)}function Hj(e){return e.startsWith(`/`)||Vj(e)}function Uj(e){return Vj(e)||/[A-Za-z]:\\/.test(e)}function Wj(e,t,n){let r=e.replace(/[\\/]+$/,``);return n===`\\`?`${r}\\${t.replaceAll(`/`,`\\`)}`:`${r}/${t.replace(/^\/+/,``)}`}function Gj(e){let t=e.match(/^\/Users\/([^/]+)/);if(t?.[1])return`/Users/${t[1]}`;let n=e.match(/^\/home\/([^/]+)/);if(n?.[1])return`/home/${n[1]}`;let r=e.match(/^([A-Za-z]:\\Users\\[^\\]+)/);if(r?.[1])return r[1]}function Kj(e){let t=e,n,r,i=t.match(/:(\d+)$/);if(!i?.[1])return{path:t,line:void 0,column:void 0};n=i[1],t=t.slice(0,-i[0].length);let a=t.match(/:(\d+)$/);return a?.[1]?(r=a[1],t=t.slice(0,-a[0].length)):(r=n,n=void 0),{path:t,line:r,column:n}}function qj(e){let t=Bj(e,`url`,Fj,[]),n=Bj(e,`path`,Ij,t);return[...t,...n].toSorted((e,t)=>e.start-t.start)}function Jj(e,t){let n=t(e-1);if(!n)return null;let r=e,i=n;for(;r>1&&i.isWrapped;){let e=t(r-2);if(!e)return null;--r,i=e}let a=[],o=0,s=r;for(;;){let e=t(s-1);if(!e)break;let n=t(s)?.isWrapped===!0,r=e.translateToString(!n);if(a.push({bufferLineNumber:s,text:r,startIndex:o,endIndex:o+r.length}),o+=r.length,!n)break;s+=1}return{text:a.map(e=>e.text).join(``),segments:a}}function Yj(e,t){for(let n of e)if(t<n.endIndex)return{x:t-n.startIndex+1,y:n.bufferLineNumber};let n=e[e.length-1];return{x:Math.max(n?.text.length??0,1),y:n?.bufferLineNumber??1}}function Xj(e,t){return{start:Yj(e.segments,t.start),end:Yj(e.segments,t.end-1)}}function Zj(e,t){return e.start.y<=t&&t<=e.end.y}function Qj(e,t=typeof navigator>`u`?``:navigator.platform){return t.length===0?!1:Sa(t)?e.metaKey&&!e.ctrlKey:e.ctrlKey&&!e.metaKey}function $j(e,t){let{path:n,line:r,column:i}=Kj(e),a=n;if(n.startsWith(`~/`)){let e=Gj(t);if(e){let t=Uj(e)?`\\`:`/`;a=Wj(e,n.slice(2),t)}}else Hj(n)||(a=Wj(t,n,Uj(t)?`\\`:`/`));return r?`${a}:${r}${i?`:${i}`:``}`:a}var eM=`diffs-container`,tM=(()=>{try{return!1}catch{return!1}})(),nM=/(?=^From [a-f0-9]+ .+$)/m,rM=/(?=^diff --git)/gm,iM=/(?<=\n)/,aM=/^(---|\+\+\+)\s+([^\t\r\n]+)/,oM=/^(---|\+\+\+)\s+[ab]\/([^\t\r\n]+)/,sM=/^diff --git (?:"a\/(.+?)"|a\/(.+?)) (?:"b\/(.+?)"|b\/(.+?))$/,cM=/^index ([0-9a-f]+)\.\.([0-9a-f]+)(?: (\d+))?$/i,lM=`header-prefix`,uM=`header-filename-suffix`,dM=`header-metadata`,fM=`header-custom`,pM={dark:`pierre-dark`,light:`pierre-light`},mM=`data-theme-css`,hM=`data-unsafe-css`,gM=`data-diffs-scrollbar-measure`,_M=`data-diffs-code-view-header`,vM=`data-diffs-code-view-footer`,yM=`--diffs-scrollbar-gutter-measured`,bM=1e5,xM={hunkLineCount:50,lineHeight:20,diffHeaderHeight:44,spacing:8},SM={...xM,hunkLineCount:1},CM={paddingTop:8,paddingBottom:8,gap:8},wM={omega:.015,positionEpsilon:.5,velocityEpsilon:.05},TM=Object.freeze({fromStart:0,fromEnd:0}),EM={startingLine:0,totalLines:1/0,bufferBefore:0,bufferAfter:0},DM={startingLine:0,totalLines:0,bufferBefore:0,bufferAfter:0},OM=new Set,kM=null;function AM(e){OM.add(e),kM??=requestAnimationFrame(MM)}function jM(e){OM.delete(e)&&OM.size===0&&kM!=null&&(cancelAnimationFrame(kM),kM=null)}function MM(e){let t=new Set(OM);OM.clear();for(let n of t)try{n(e)}catch(e){console.error(e)}kM=OM.size>0?requestAnimationFrame(MM):null}function NM(e,t,n){if(e===t||e==null||t==null)return e===t;let r=new Set(n),i=Object.keys(e),a=new Set(Object.keys(t));for(let n of i)if(a.delete(n),!r.has(n)&&(!(n in t)||e[n]!==t[n]))return!1;for(let e of Array.from(a))if(!r.has(e))return!1;return!0}function PM(e,t){return e==null||t==null||typeof e==`string`||typeof t==`string`?e===t:e.dark===t.dark&&e.light===t.light}function FM(e,t){let n=e?.theme??pM,r=t?.theme??pM,i=IM(e),a=IM(t);return PM(n,r)&&NM(e,t,[`theme`,`parseDiffOptions`])&&NM(i,a)}function IM(e){if(e!=null&&`parseDiffOptions`in e)return e.parseDiffOptions}function LM(e,t){return e?.start===t?.start&&e?.end===t?.end&&e?.side===t?.side&&e?.endSide===t?.endSide}function RM({scrollTop:e,scrollHeight:t,height:n,fitPerfectly:r=!1,fitPerfectlyOverscroll:i=0,overscrollSize:a}){let o=n+a*2,s=r?n+i*2:o;if(t=Math.max(t,s),o>=t||r){let n=Math.max(e-i,0),r=Math.min(e+s,t);return{top:n,bottom:Math.max(r,n)}}let c=e+n/2-o/2,l=c+o;return c<0&&(c=0),l>t&&(l=t),c=Math.floor(Math.max(c,0)),{top:c,bottom:Math.ceil(Math.max(Math.min(l,t),c))}}function zM(e){let t=e.length;return e.charCodeAt(t-1)===10&&(t--,e.charCodeAt(t-1)===13&&t--),e.slice(0,t)}function BM(e,t){return e-(t===0?0:1)}function VM(e,t){return BM(e,t)+t}var HM=class{diff(e,t,n={}){let r;typeof n==`function`?(r=n,n={}):`callback`in n&&(r=n.callback);let i=this.castInput(e,n),a=this.castInput(t,n),o=this.removeEmpty(this.tokenize(i,n)),s=this.removeEmpty(this.tokenize(a,n));return this.diffWithOptionsObj(o,s,n,r)}diffWithOptionsObj(e,t,n,r){let i=e=>{if(e=this.postProcess(e,n),r){setTimeout(function(){r(e)},0);return}return e},a=t.length,o=e.length,s=1,c=a+o;n.maxEditLength!=null&&(c=Math.min(c,n.maxEditLength));let l=n.timeout??1/0,u=Date.now()+l,d=[{oldPos:-1,lastComponent:void 0}],f=this.extractCommon(d[0],t,e,0,n);if(d[0].oldPos+1>=o&&f+1>=a)return i(this.buildValues(d[0].lastComponent,t,e));let p=-1/0,m=1/0,h=()=>{for(let r=Math.max(p,-s);r<=Math.min(m,s);r+=2){let s,c=d[r-1],l=d[r+1];c&&(d[r-1]=void 0);let u=!1;if(l){let e=l.oldPos-r;u=l&&0<=e&&e<a}let h=c&&c.oldPos+1<o;if(!u&&!h){d[r]=void 0;continue}if(s=!h||u&&c.oldPos<l.oldPos?this.addToPath(l,!0,!1,0,n):this.addToPath(c,!1,!0,1,n),f=this.extractCommon(s,t,e,r,n),s.oldPos+1>=o&&f+1>=a)return i(this.buildValues(s.lastComponent,t,e))||!0;d[r]=s,s.oldPos+1>=o&&(m=Math.min(m,r-1)),f+1>=a&&(p=Math.max(p,r+1))}s++};if(r)(function e(){setTimeout(function(){if(s>c||Date.now()>u)return r(void 0);h()||e()},0)})();else for(;s<=c&&Date.now()<=u;){let e=h();if(e)return e}}addToPath(e,t,n,r,i){let a=e.lastComponent;return a&&!i.oneChangePerToken&&a.added===t&&a.removed===n?{oldPos:e.oldPos+r,lastComponent:{count:a.count+1,added:t,removed:n,previousComponent:a.previousComponent}}:{oldPos:e.oldPos+r,lastComponent:{count:1,added:t,removed:n,previousComponent:a}}}extractCommon(e,t,n,r,i){let a=t.length,o=n.length,s=e.oldPos,c=s-r,l=0;for(;c+1<a&&s+1<o&&this.equals(n[s+1],t[c+1],i);)c++,s++,l++,i.oneChangePerToken&&(e.lastComponent={count:1,previousComponent:e.lastComponent,added:!1,removed:!1});return l&&!i.oneChangePerToken&&(e.lastComponent={count:l,previousComponent:e.lastComponent,added:!1,removed:!1}),e.oldPos=s,c}equals(e,t,n){return n.comparator?n.comparator(e,t):e===t||!!n.ignoreCase&&e.toLowerCase()===t.toLowerCase()}removeEmpty(e){let t=[];for(let n=0;n<e.length;n++)e[n]&&t.push(e[n]);return t}castInput(e,t){return e}tokenize(e,t){return Array.from(e)}join(e){return e.join(``)}postProcess(e,t){return e}get useLongestToken(){return!1}buildValues(e,t,n){let r=[],i;for(;e;)r.push(e),i=e.previousComponent,delete e.previousComponent,e=i;r.reverse();let a=r.length,o=0,s=0,c=0;for(;o<a;o++){let e=r[o];if(e.removed)e.value=this.join(n.slice(c,c+e.count)),c+=e.count;else{if(!e.added&&this.useLongestToken){let r=t.slice(s,s+e.count);r=r.map(function(e,t){let r=n[c+t];return r.length>e.length?r:e}),e.value=this.join(r)}else e.value=this.join(t.slice(s,s+e.count));s+=e.count,e.added||(c+=e.count)}}return r}},UM=new class extends HM{};function WM(e,t,n){return UM.diff(e,t,n)}function GM(e,t){let n;for(n=0;n<e.length&&n<t.length;n++)if(e[n]!=t[n])return e.slice(0,n);return e.slice(0,n)}function KM(e,t){let n;if(!e||!t||e[e.length-1]!=t[t.length-1])return``;for(n=0;n<e.length&&n<t.length;n++)if(e[e.length-(n+1)]!=t[t.length-(n+1)])return e.slice(-n);return e.slice(-n)}function qM(e,t,n){if(e.slice(0,t.length)!=t)throw Error(`string ${JSON.stringify(e)} doesn't start with prefix ${JSON.stringify(t)}; this is a bug`);return n+e.slice(t.length)}function JM(e,t,n){if(!t)return e+n;if(e.slice(-t.length)!=t)throw Error(`string ${JSON.stringify(e)} doesn't end with suffix ${JSON.stringify(t)}; this is a bug`);return e.slice(0,-t.length)+n}function YM(e,t){return qM(e,t,``)}function XM(e,t){return JM(e,t,``)}function ZM(e,t){return t.slice(0,QM(e,t))}function QM(e,t){let n=0;e.length>t.length&&(n=e.length-t.length);let r=t.length;e.length<t.length&&(r=e.length);let i=Array(r),a=0;i[0]=0;for(let e=1;e<r;e++){for(t[e]==t[a]?i[e]=i[a]:i[e]=a;a>0&&t[e]!=t[a];)a=i[a];t[e]==t[a]&&a++}a=0;for(let r=n;r<e.length;r++){for(;a>0&&e[r]!=t[a];)a=i[a];e[r]==t[a]&&a++}return a}function $M(e,t){let n=[];for(let r of Array.from(t.segment(e))){let e=r.segment;n.length&&/\s/.test(n[n.length-1])&&/\s/.test(e)?n[n.length-1]+=e:n.push(e)}return n}function eN(e,t){if(t)return nN(e,t)[1];let n;for(n=e.length-1;n>=0&&e[n].match(/\s/);n--);return e.substring(n+1)}function tN(e,t){if(t)return nN(e,t)[0];let n=e.match(/^\s*/);return n?n[0]:``}function nN(e,t){if(!t)return[tN(e),eN(e)];if(t.resolvedOptions().granularity!=`word`)throw Error(`The segmenter passed must have a granularity of "word"`);let n=$M(e,t),r=n[0],i=n[n.length-1];return[/\s/.test(r)?r:``,/\s/.test(i)?i:``]}var rN=`a-zA-Z0-9_\\u{AD}\\u{C0}-\\u{D6}\\u{D8}-\\u{F6}\\u{F8}-\\u{2C6}\\u{2C8}-\\u{2D7}\\u{2DE}-\\u{2FF}\\u{1E00}-\\u{1EFF}`,iN=RegExp(`[${rN}]+|\\s+|[^${rN}]`,`ug`);new class extends HM{equals(e,t,n){return n.ignoreCase&&(e=e.toLowerCase(),t=t.toLowerCase()),e.trim()===t.trim()}tokenize(e,t={}){let n;if(t.intlSegmenter){let r=t.intlSegmenter;if(r.resolvedOptions().granularity!=`word`)throw Error(`The segmenter passed must have a granularity of "word"`);n=$M(e,r)}else n=e.match(iN)||[];let r=[],i=null;return n.forEach(e=>{/\s/.test(e)?i==null?r.push(e):r.push(r.pop()+e):i!=null&&/\s/.test(i)?r[r.length-1]==i?r.push(r.pop()+e):r.push(i+e):r.push(e),i=e}),r}join(e){return e.map((e,t)=>t==0?e:e.replace(/^\s+/,``)).join(``)}postProcess(e,t){if(!e||t.oneChangePerToken)return e;let n=null,r=null,i=null;return e.forEach(e=>{e.added?r=e:e.removed?i=e:((r||i)&&aN(n,i,r,e,t.intlSegmenter),n=e,r=null,i=null)}),(r||i)&&aN(n,i,r,null,t.intlSegmenter),e}};function aN(e,t,n,r,i){if(t&&n){let[a,o]=nN(t.value,i),[s,c]=nN(n.value,i);if(e){let r=GM(a,s);e.value=JM(e.value,s,r),t.value=YM(t.value,r),n.value=YM(n.value,r)}if(r){let e=KM(o,c);r.value=qM(r.value,c,e),t.value=XM(t.value,e),n.value=XM(n.value,e)}}else if(n){if(e){let e=tN(n.value,i);n.value=n.value.substring(e.length)}if(r){let e=tN(r.value,i);r.value=r.value.substring(e.length)}}else if(e&&r){let n=tN(r.value,i),[a,o]=nN(t.value,i),s=GM(n,a);t.value=YM(t.value,s);let c=KM(YM(n,s),o);t.value=XM(t.value,c),r.value=qM(r.value,n,c),e.value=JM(e.value,n,n.slice(0,n.length-c.length))}else if(r){let e=tN(r.value,i),n=ZM(eN(t.value,i),e);t.value=XM(t.value,n)}else if(e){let n=ZM(eN(e.value,i),tN(t.value,i));t.value=YM(t.value,n)}}var oN=new class extends HM{tokenize(e){let t=RegExp(`(\\r?\\n)|[${rN}]+|[^\\S\\n\\r]+|[^${rN}]`,`ug`);return e.match(t)||[]}};function sN(e,t,n){return oN.diff(e,t,n)}var cN=new class extends HM{constructor(){super(...arguments),this.tokenize=uN}equals(e,t,n){return n.ignoreWhitespace?((!n.newlineIsToken||!e.includes(`
|
|
22
22
|
`))&&(e=e.trim()),(!n.newlineIsToken||!t.includes(`
|
|
23
23
|
`))&&(t=t.trim())):n.ignoreNewlineAtEof&&!n.newlineIsToken&&(e.endsWith(`
|
|
24
24
|
`)&&(e=e.slice(0,-1)),t.endsWith(`
|
|
25
|
-
`)&&(t=t.slice(0,-1))),super.equals(e,t,n)}};function
|
|
26
|
-
`));let n=[],r=e.split(/(\n|\r\n)/);r[r.length-1]||r.pop();for(let e=0;e<r.length;e++){let i=r[e];e%2&&!t.newlineIsToken?n[n.length-1]+=i:n.push(i)}return n}function
|
|
27
|
-
`)?e.lines[t]=e.lines[t].slice(0,-1):(e.lines.splice(t+1,0,`\`),t++);return{oldFileName:e,newFileName:t,oldHeader:i,newHeader:a,hunks:o}}}function
|
|
28
|
-
`)}let n=[];if(e.isGit){if(t=
|
|
25
|
+
`)&&(t=t.slice(0,-1))),super.equals(e,t,n)}};function lN(e,t,n){return cN.diff(e,t,n)}function uN(e,t){t.stripTrailingCr&&(e=e.replace(/\r\n/g,`
|
|
26
|
+
`));let n=[],r=e.split(/(\n|\r\n)/);r[r.length-1]||r.pop();for(let e=0;e<r.length;e++){let i=r[e];e%2&&!t.newlineIsToken?n[n.length-1]+=i:n.push(i)}return n}function dN(e){return e==`.`||e==`!`||e==`?`}new class extends HM{tokenize(e){let t=[],n=0;for(let r=0;r<e.length;r++){if(r==e.length-1){t.push(e.slice(n));break}if(dN(e[r])&&e[r+1].match(/\s/)){for(t.push(e.slice(n,r+1)),r=n=r+1;e[r+1]?.match(/\s/);)r++;t.push(e.slice(n,r+1)),n=r+1}}return t}},new class extends HM{tokenize(e){return e.split(/([{}:;,]|\s+)/)}},new class extends HM{constructor(){super(...arguments),this.tokenize=uN}get useLongestToken(){return!0}castInput(e,t){let{undefinedReplacement:n,stringifyReplacer:r=(e,t)=>t===void 0?n:t}=t;return typeof e==`string`?e:JSON.stringify(fN(e,null,null,r),null,` `)}equals(e,t,n){return super.equals(e.replace(/,([\r\n])/g,`$1`),t.replace(/,([\r\n])/g,`$1`),n)}};function fN(e,t,n,r,i){t||=[],n||=[],r&&(e=r(i===void 0?``:i,e));let a;for(a=0;a<t.length;a+=1)if(t[a]===e)return n[a];let o;if(Object.prototype.toString.call(e)===`[object Array]`){for(t.push(e),o=Array(e.length),n.push(o),a=0;a<e.length;a+=1)o[a]=fN(e[a],t,n,r,String(a));return t.pop(),n.pop(),o}if(e&&e.toJSON&&(e=e.toJSON()),typeof e==`object`&&e){t.push(e),o={},n.push(o);let i=[],s;for(s in e)Object.prototype.hasOwnProperty.call(e,s)&&i.push(s);for(i.sort(),a=0;a<i.length;a+=1)s=i[a],o[s]=fN(e[s],t,n,r,s);t.pop(),n.pop()}else o=e;return o}new class extends HM{tokenize(e){return e.slice()}join(e){return e}removeEmpty(e){return e}};function pN(e){for(let t=0;t<e.length;t++)if(e[t]<` `||e[t]>`~`||e[t]===`"`||e[t]===`\\`)return!0;return!1}function mN(e){if(!pN(e))return e;let t=`"`,n=new TextEncoder().encode(e),r=0;for(;r<n.length;){let e=n[r];t+=e===7?`\\a`:e===8?`\\b`:e===9?`\\t`:e===10?`\\n`:e===11?`\\v`:e===12?`\\f`:e===13?`\\r`:e===34?`\\"`:e===92?`\\\\`:e>=32&&e<=126?String.fromCharCode(e):`\\`+e.toString(8).padStart(3,`0`),r++}return t+=`"`,t}var hN={includeIndex:!0,includeUnderline:!0,includeFileHeaders:!0};function gN(e,t,n,r,i,a,o){let s;s=o?typeof o==`function`?{callback:o}:o:{},s.context===void 0&&(s.context=4);let c=s.context;if(s.newlineIsToken)throw Error(`newlineIsToken may not be used with patch-generation functions, only with diffing functions`);if(s.callback){let{callback:e}=s;lN(n,r,Object.assign(Object.assign({},s),{callback:t=>{let n=l(t);e(n)}}))}else return l(lN(n,r,s));function l(n){if(!n)return;n.push({value:``,lines:[]});function r(e){return e.map(function(e){return` `+e})}let o=[],s=0,l=0,u=[],d=1,f=1;for(let e=0;e<n.length;e++){let t=n[e],i=t.lines||yN(t.value);if(t.lines=i,t.added||t.removed){if(!s){let t=n[e-1];s=d,l=f,t&&(u=c>0?r(t.lines.slice(-c)):[],s-=u.length,l-=u.length)}for(let e of i)u.push((t.added?`+`:`-`)+e);t.added?f+=i.length:d+=i.length}else{if(s)if(i.length<=c*2&&e<n.length-2)for(let e of r(i))u.push(e);else{let e=Math.min(i.length,c);for(let t of r(i.slice(0,e)))u.push(t);let t={oldStart:s,oldLines:d-s+e,newStart:l,newLines:f-l+e,lines:u};o.push(t),s=0,l=0,u=[]}d+=i.length,f+=i.length}}for(let e of o)for(let t=0;t<e.lines.length;t++)e.lines[t].endsWith(`
|
|
27
|
+
`)?e.lines[t]=e.lines[t].slice(0,-1):(e.lines.splice(t+1,0,`\`),t++);return{oldFileName:e,newFileName:t,oldHeader:i,newHeader:a,hunks:o}}}function _N(e,t){if(t||=hN,Array.isArray(e)){if(e.length>1&&!t.includeFileHeaders&&!e.every(e=>e.isGit))throw Error(`Cannot omit file headers on a multi-file patch. (The result would be unparseable; how would a tool trying to apply the patch know which changes are to which file?)`);return e.map(e=>_N(e,t)).join(`
|
|
28
|
+
`)}let n=[];if(e.isGit){if(t=hN,!e.oldFileName)throw Error(`oldFileName must be specified for Git patches`);if(!e.newFileName)throw Error(`newFileName must be specified for Git patches`);let r=e.oldFileName,i=e.newFileName;e.isCreate&&r===`/dev/null`?r=i.replace(/^b\//,`a/`):e.isDelete&&i===`/dev/null`&&(i=r.replace(/^a\//,`b/`)),n.push(`diff --git `+mN(r)+` `+mN(i)),e.isDelete&&n.push(`deleted file mode `+(e.oldMode??`100644`)),e.isCreate&&n.push(`new file mode `+(e.newMode??`100644`)),e.oldMode&&e.newMode&&!e.isDelete&&!e.isCreate&&(n.push(`old mode `+e.oldMode),n.push(`new mode `+e.newMode)),e.isRename&&(n.push(`rename from `+mN((e.oldFileName??``).replace(/^a\//,``))),n.push(`rename to `+mN((e.newFileName??``).replace(/^b\//,``)))),e.isCopy&&(n.push(`copy from `+mN((e.oldFileName??``).replace(/^a\//,``))),n.push(`copy to `+mN((e.newFileName??``).replace(/^b\//,``))))}else t.includeIndex&&e.oldFileName==e.newFileName&&e.oldFileName!==void 0&&n.push(`Index: `+e.oldFileName),t.includeUnderline&&n.push(`===================================================================`);let r=e.hunks.length>0;t.includeFileHeaders&&e.oldFileName!==void 0&&e.newFileName!==void 0&&(!e.isGit||r)&&(n.push(`--- `+mN(e.oldFileName)+(e.oldHeader?` `+e.oldHeader:``)),n.push(`+++ `+mN(e.newFileName)+(e.newHeader?` `+e.newHeader:``)));for(let t=0;t<e.hunks.length;t++){let r=e.hunks[t],i=r.oldLines===0?r.oldStart-1:r.oldStart,a=r.newLines===0?r.newStart-1:r.newStart;n.push(`@@ -`+i+`,`+r.oldLines+` +`+a+`,`+r.newLines+` @@`);for(let e of r.lines)n.push(e)}return n.join(`
|
|
29
29
|
`)+`
|
|
30
|
-
`}function
|
|
30
|
+
`}function vN(e,t,n,r,i,a,o){if(typeof o==`function`&&(o={callback:o}),o?.callback){let{callback:s}=o;gN(e,t,n,r,i,a,Object.assign(Object.assign({},o),{callback:e=>{s(e?_N(e,o.headerOptions):void 0)}}))}else{let s=gN(e,t,n,r,i,a,o);return s?_N(s,o?.headerOptions):void 0}}function yN(e){let t=e.endsWith(`
|
|
31
31
|
`),n=e.split(`
|
|
32
32
|
`).map(e=>e+`
|
|
33
|
-
`);return t?n.pop():n.push(n.pop().slice(0,-1)),n}function yN(e,t){return e?.cacheKey===t?.cacheKey&&e?.contents===t?.contents&&e?.name===t?.name&&e?.lang===t?.lang}function bN(e){return{type:`text`,value:e}}function B({tagName:e,children:t=[],properties:n={}}){return{type:`element`,tagName:e,properties:n,children:t}}function xN({name:e,width:t=16,height:n=16,properties:r}){return B({tagName:`svg`,properties:{width:t,height:n,viewBox:`0 0 16 16`,...r},children:[B({tagName:`use`,properties:{href:`#${e.replace(/^#/,``)}`}})]})}function SN(e){let t=e.children[0];for(;t!=null;){if(t.type===`element`&&t.tagName===`code`)return t;t=`children`in t?t.children[0]:null}}function CN(e){return B({tagName:`div`,properties:{"data-gutter":``},children:e})}function wN(e,t,n,r={}){return B({tagName:`div`,properties:{"data-line-type":e,"data-column-number":t,"data-line-index":n,...r},children:t==null?void 0:[B({tagName:`span`,properties:{"data-line-number-content":``},children:[bN(`${t}`)]})]})}function TN(e,t,n){return B({tagName:`div`,properties:{"data-gutter-buffer":t,"data-buffer-size":n,"data-line-type":t===`annotation`?void 0:e,style:t===`annotation`?`grid-row: span ${n};`:`grid-row: span ${n};min-height:calc(${n} * 1lh);`}})}function EN(){return B({tagName:`button`,properties:{"data-utility-button":``,type:`button`},children:[xN({name:`diffs-icon-plus`,properties:{"data-icon":``}})]})}function DN(e,t){return e.lineNumber===t.lineNumber&&e.side===t.side}function ON(e){for(let t of e)if(t instanceof HTMLElement&&(t.hasAttribute(`data-utility-button`)||t.hasAttribute(`data-gutter-utility-slot`)||t.getAttribute(`slot`)===`gutter-utility-slot`||t.getAttribute(`name`)===`gutter-utility-slot`))return!0;return!1}var kN=[`area`,`base`,`basefont`,`bgsound`,`br`,`col`,`command`,`embed`,`frame`,`hr`,`image`,`img`,`input`,`keygen`,`link`,`meta`,`param`,`source`,`track`,`wbr`],AN=class{constructor(e,t,n){this.normal=t,this.property=e,n&&(this.space=n)}};AN.prototype.normal={},AN.prototype.property={},AN.prototype.space=void 0;function jN(e,t){let n={},r={};for(let t of e)Object.assign(n,t.property),Object.assign(r,t.normal);return new AN(n,r,t)}function MN(e){return e.toLowerCase()}var NN=class{constructor(e,t){this.attribute=t,this.property=e}};NN.prototype.attribute=``,NN.prototype.booleanish=!1,NN.prototype.boolean=!1,NN.prototype.commaOrSpaceSeparated=!1,NN.prototype.commaSeparated=!1,NN.prototype.defined=!1,NN.prototype.mustUseProperty=!1,NN.prototype.number=!1,NN.prototype.overloadedBoolean=!1,NN.prototype.property=``,NN.prototype.spaceSeparated=!1,NN.prototype.space=void 0;var PN=e({boolean:()=>V,booleanish:()=>H,commaOrSpaceSeparated:()=>RN,commaSeparated:()=>LN,number:()=>U,overloadedBoolean:()=>IN,spaceSeparated:()=>W}),FN=0,V=zN(),H=zN(),IN=zN(),U=zN(),W=zN(),LN=zN(),RN=zN();function zN(){return 2**++FN}var BN=Object.keys(PN),VN=class extends NN{constructor(e,t,n,r){let i=-1;if(super(e,t),HN(this,`space`,r),typeof n==`number`)for(;++i<BN.length;){let e=BN[i];HN(this,BN[i],(n&PN[e])===PN[e])}}};VN.prototype.defined=!0;function HN(e,t,n){n&&(e[t]=n)}function UN(e){let t={},n={};for(let[r,i]of Object.entries(e.properties)){let a=new VN(r,e.transform(e.attributes||{},r),i,e.space);e.mustUseProperty&&e.mustUseProperty.includes(r)&&(a.mustUseProperty=!0),t[r]=a,n[MN(r)]=r,n[MN(a.attribute)]=r}return new AN(t,n,e.space)}var WN=UN({properties:{ariaActiveDescendant:null,ariaAtomic:H,ariaAutoComplete:null,ariaBusy:H,ariaChecked:H,ariaColCount:U,ariaColIndex:U,ariaColSpan:U,ariaControls:W,ariaCurrent:null,ariaDescribedBy:W,ariaDetails:null,ariaDisabled:H,ariaDropEffect:W,ariaErrorMessage:null,ariaExpanded:H,ariaFlowTo:W,ariaGrabbed:H,ariaHasPopup:null,ariaHidden:H,ariaInvalid:null,ariaKeyShortcuts:null,ariaLabel:null,ariaLabelledBy:W,ariaLevel:U,ariaLive:null,ariaModal:H,ariaMultiLine:H,ariaMultiSelectable:H,ariaOrientation:null,ariaOwns:W,ariaPlaceholder:null,ariaPosInSet:U,ariaPressed:H,ariaReadOnly:H,ariaRelevant:null,ariaRequired:H,ariaRoleDescription:W,ariaRowCount:U,ariaRowIndex:U,ariaRowSpan:U,ariaSelected:H,ariaSetSize:U,ariaSort:null,ariaValueMax:U,ariaValueMin:U,ariaValueNow:U,ariaValueText:null,role:null},transform(e,t){return t===`role`?t:`aria-`+t.slice(4).toLowerCase()}});function GN(e,t){return t in e?e[t]:t}function KN(e,t){return GN(e,t.toLowerCase())}var qN=UN({attributes:{acceptcharset:`accept-charset`,classname:`class`,htmlfor:`for`,httpequiv:`http-equiv`},mustUseProperty:[`checked`,`multiple`,`muted`,`selected`],properties:{abbr:null,accept:LN,acceptCharset:W,accessKey:W,action:null,allow:null,allowFullScreen:V,allowPaymentRequest:V,allowUserMedia:V,alt:null,as:null,async:V,autoCapitalize:null,autoComplete:W,autoFocus:V,autoPlay:V,blocking:W,capture:null,charSet:null,checked:V,cite:null,className:W,cols:U,colSpan:null,content:null,contentEditable:H,controls:V,controlsList:W,coords:U|LN,crossOrigin:null,data:null,dateTime:null,decoding:null,default:V,defer:V,dir:null,dirName:null,disabled:V,download:IN,draggable:H,encType:null,enterKeyHint:null,fetchPriority:null,form:null,formAction:null,formEncType:null,formMethod:null,formNoValidate:V,formTarget:null,headers:W,height:U,hidden:IN,high:U,href:null,hrefLang:null,htmlFor:W,httpEquiv:W,id:null,imageSizes:null,imageSrcSet:null,inert:V,inputMode:null,integrity:null,is:null,isMap:V,itemId:null,itemProp:W,itemRef:W,itemScope:V,itemType:W,kind:null,label:null,lang:null,language:null,list:null,loading:null,loop:V,low:U,manifest:null,max:null,maxLength:U,media:null,method:null,min:null,minLength:U,multiple:V,muted:V,name:null,nonce:null,noModule:V,noValidate:V,onAbort:null,onAfterPrint:null,onAuxClick:null,onBeforeMatch:null,onBeforePrint:null,onBeforeToggle:null,onBeforeUnload:null,onBlur:null,onCancel:null,onCanPlay:null,onCanPlayThrough:null,onChange:null,onClick:null,onClose:null,onContextLost:null,onContextMenu:null,onContextRestored:null,onCopy:null,onCueChange:null,onCut:null,onDblClick:null,onDrag:null,onDragEnd:null,onDragEnter:null,onDragExit:null,onDragLeave:null,onDragOver:null,onDragStart:null,onDrop:null,onDurationChange:null,onEmptied:null,onEnded:null,onError:null,onFocus:null,onFormData:null,onHashChange:null,onInput:null,onInvalid:null,onKeyDown:null,onKeyPress:null,onKeyUp:null,onLanguageChange:null,onLoad:null,onLoadedData:null,onLoadedMetadata:null,onLoadEnd:null,onLoadStart:null,onMessage:null,onMessageError:null,onMouseDown:null,onMouseEnter:null,onMouseLeave:null,onMouseMove:null,onMouseOut:null,onMouseOver:null,onMouseUp:null,onOffline:null,onOnline:null,onPageHide:null,onPageShow:null,onPaste:null,onPause:null,onPlay:null,onPlaying:null,onPopState:null,onProgress:null,onRateChange:null,onRejectionHandled:null,onReset:null,onResize:null,onScroll:null,onScrollEnd:null,onSecurityPolicyViolation:null,onSeeked:null,onSeeking:null,onSelect:null,onSlotChange:null,onStalled:null,onStorage:null,onSubmit:null,onSuspend:null,onTimeUpdate:null,onToggle:null,onUnhandledRejection:null,onUnload:null,onVolumeChange:null,onWaiting:null,onWheel:null,open:V,optimum:U,pattern:null,ping:W,placeholder:null,playsInline:V,popover:null,popoverTarget:null,popoverTargetAction:null,poster:null,preload:null,readOnly:V,referrerPolicy:null,rel:W,required:V,reversed:V,rows:U,rowSpan:U,sandbox:W,scope:null,scoped:V,seamless:V,selected:V,shadowRootClonable:V,shadowRootDelegatesFocus:V,shadowRootMode:null,shape:null,size:U,sizes:null,slot:null,span:U,spellCheck:H,src:null,srcDoc:null,srcLang:null,srcSet:null,start:U,step:null,style:null,tabIndex:U,target:null,title:null,translate:null,type:null,typeMustMatch:V,useMap:null,value:H,width:U,wrap:null,writingSuggestions:null,align:null,aLink:null,archive:W,axis:null,background:null,bgColor:null,border:U,borderColor:null,bottomMargin:U,cellPadding:null,cellSpacing:null,char:null,charOff:null,classId:null,clear:null,code:null,codeBase:null,codeType:null,color:null,compact:V,declare:V,event:null,face:null,frame:null,frameBorder:null,hSpace:U,leftMargin:U,link:null,longDesc:null,lowSrc:null,marginHeight:U,marginWidth:U,noResize:V,noHref:V,noShade:V,noWrap:V,object:null,profile:null,prompt:null,rev:null,rightMargin:U,rules:null,scheme:null,scrolling:H,standby:null,summary:null,text:null,topMargin:U,valueType:null,version:null,vAlign:null,vLink:null,vSpace:U,allowTransparency:null,autoCorrect:null,autoSave:null,disablePictureInPicture:V,disableRemotePlayback:V,prefix:null,property:null,results:U,security:null,unselectable:null},space:`html`,transform:KN}),JN=UN({attributes:{accentHeight:`accent-height`,alignmentBaseline:`alignment-baseline`,arabicForm:`arabic-form`,baselineShift:`baseline-shift`,capHeight:`cap-height`,className:`class`,clipPath:`clip-path`,clipRule:`clip-rule`,colorInterpolation:`color-interpolation`,colorInterpolationFilters:`color-interpolation-filters`,colorProfile:`color-profile`,colorRendering:`color-rendering`,crossOrigin:`crossorigin`,dataType:`datatype`,dominantBaseline:`dominant-baseline`,enableBackground:`enable-background`,fillOpacity:`fill-opacity`,fillRule:`fill-rule`,floodColor:`flood-color`,floodOpacity:`flood-opacity`,fontFamily:`font-family`,fontSize:`font-size`,fontSizeAdjust:`font-size-adjust`,fontStretch:`font-stretch`,fontStyle:`font-style`,fontVariant:`font-variant`,fontWeight:`font-weight`,glyphName:`glyph-name`,glyphOrientationHorizontal:`glyph-orientation-horizontal`,glyphOrientationVertical:`glyph-orientation-vertical`,hrefLang:`hreflang`,horizAdvX:`horiz-adv-x`,horizOriginX:`horiz-origin-x`,horizOriginY:`horiz-origin-y`,imageRendering:`image-rendering`,letterSpacing:`letter-spacing`,lightingColor:`lighting-color`,markerEnd:`marker-end`,markerMid:`marker-mid`,markerStart:`marker-start`,navDown:`nav-down`,navDownLeft:`nav-down-left`,navDownRight:`nav-down-right`,navLeft:`nav-left`,navNext:`nav-next`,navPrev:`nav-prev`,navRight:`nav-right`,navUp:`nav-up`,navUpLeft:`nav-up-left`,navUpRight:`nav-up-right`,onAbort:`onabort`,onActivate:`onactivate`,onAfterPrint:`onafterprint`,onBeforePrint:`onbeforeprint`,onBegin:`onbegin`,onCancel:`oncancel`,onCanPlay:`oncanplay`,onCanPlayThrough:`oncanplaythrough`,onChange:`onchange`,onClick:`onclick`,onClose:`onclose`,onCopy:`oncopy`,onCueChange:`oncuechange`,onCut:`oncut`,onDblClick:`ondblclick`,onDrag:`ondrag`,onDragEnd:`ondragend`,onDragEnter:`ondragenter`,onDragExit:`ondragexit`,onDragLeave:`ondragleave`,onDragOver:`ondragover`,onDragStart:`ondragstart`,onDrop:`ondrop`,onDurationChange:`ondurationchange`,onEmptied:`onemptied`,onEnd:`onend`,onEnded:`onended`,onError:`onerror`,onFocus:`onfocus`,onFocusIn:`onfocusin`,onFocusOut:`onfocusout`,onHashChange:`onhashchange`,onInput:`oninput`,onInvalid:`oninvalid`,onKeyDown:`onkeydown`,onKeyPress:`onkeypress`,onKeyUp:`onkeyup`,onLoad:`onload`,onLoadedData:`onloadeddata`,onLoadedMetadata:`onloadedmetadata`,onLoadStart:`onloadstart`,onMessage:`onmessage`,onMouseDown:`onmousedown`,onMouseEnter:`onmouseenter`,onMouseLeave:`onmouseleave`,onMouseMove:`onmousemove`,onMouseOut:`onmouseout`,onMouseOver:`onmouseover`,onMouseUp:`onmouseup`,onMouseWheel:`onmousewheel`,onOffline:`onoffline`,onOnline:`ononline`,onPageHide:`onpagehide`,onPageShow:`onpageshow`,onPaste:`onpaste`,onPause:`onpause`,onPlay:`onplay`,onPlaying:`onplaying`,onPopState:`onpopstate`,onProgress:`onprogress`,onRateChange:`onratechange`,onRepeat:`onrepeat`,onReset:`onreset`,onResize:`onresize`,onScroll:`onscroll`,onSeeked:`onseeked`,onSeeking:`onseeking`,onSelect:`onselect`,onShow:`onshow`,onStalled:`onstalled`,onStorage:`onstorage`,onSubmit:`onsubmit`,onSuspend:`onsuspend`,onTimeUpdate:`ontimeupdate`,onToggle:`ontoggle`,onUnload:`onunload`,onVolumeChange:`onvolumechange`,onWaiting:`onwaiting`,onZoom:`onzoom`,overlinePosition:`overline-position`,overlineThickness:`overline-thickness`,paintOrder:`paint-order`,panose1:`panose-1`,pointerEvents:`pointer-events`,referrerPolicy:`referrerpolicy`,renderingIntent:`rendering-intent`,shapeRendering:`shape-rendering`,stopColor:`stop-color`,stopOpacity:`stop-opacity`,strikethroughPosition:`strikethrough-position`,strikethroughThickness:`strikethrough-thickness`,strokeDashArray:`stroke-dasharray`,strokeDashOffset:`stroke-dashoffset`,strokeLineCap:`stroke-linecap`,strokeLineJoin:`stroke-linejoin`,strokeMiterLimit:`stroke-miterlimit`,strokeOpacity:`stroke-opacity`,strokeWidth:`stroke-width`,tabIndex:`tabindex`,textAnchor:`text-anchor`,textDecoration:`text-decoration`,textRendering:`text-rendering`,transformOrigin:`transform-origin`,typeOf:`typeof`,underlinePosition:`underline-position`,underlineThickness:`underline-thickness`,unicodeBidi:`unicode-bidi`,unicodeRange:`unicode-range`,unitsPerEm:`units-per-em`,vAlphabetic:`v-alphabetic`,vHanging:`v-hanging`,vIdeographic:`v-ideographic`,vMathematical:`v-mathematical`,vectorEffect:`vector-effect`,vertAdvY:`vert-adv-y`,vertOriginX:`vert-origin-x`,vertOriginY:`vert-origin-y`,wordSpacing:`word-spacing`,writingMode:`writing-mode`,xHeight:`x-height`,playbackOrder:`playbackorder`,timelineBegin:`timelinebegin`},properties:{about:RN,accentHeight:U,accumulate:null,additive:null,alignmentBaseline:null,alphabetic:U,amplitude:U,arabicForm:null,ascent:U,attributeName:null,attributeType:null,azimuth:U,bandwidth:null,baselineShift:null,baseFrequency:null,baseProfile:null,bbox:null,begin:null,bias:U,by:null,calcMode:null,capHeight:U,className:W,clip:null,clipPath:null,clipPathUnits:null,clipRule:null,color:null,colorInterpolation:null,colorInterpolationFilters:null,colorProfile:null,colorRendering:null,content:null,contentScriptType:null,contentStyleType:null,crossOrigin:null,cursor:null,cx:null,cy:null,d:null,dataType:null,defaultAction:null,descent:U,diffuseConstant:U,direction:null,display:null,dur:null,divisor:U,dominantBaseline:null,download:V,dx:null,dy:null,edgeMode:null,editable:null,elevation:U,enableBackground:null,end:null,event:null,exponent:U,externalResourcesRequired:null,fill:null,fillOpacity:U,fillRule:null,filter:null,filterRes:null,filterUnits:null,floodColor:null,floodOpacity:null,focusable:null,focusHighlight:null,fontFamily:null,fontSize:null,fontSizeAdjust:null,fontStretch:null,fontStyle:null,fontVariant:null,fontWeight:null,format:null,fr:null,from:null,fx:null,fy:null,g1:LN,g2:LN,glyphName:LN,glyphOrientationHorizontal:null,glyphOrientationVertical:null,glyphRef:null,gradientTransform:null,gradientUnits:null,handler:null,hanging:U,hatchContentUnits:null,hatchUnits:null,height:null,href:null,hrefLang:null,horizAdvX:U,horizOriginX:U,horizOriginY:U,id:null,ideographic:U,imageRendering:null,initialVisibility:null,in:null,in2:null,intercept:U,k:U,k1:U,k2:U,k3:U,k4:U,kernelMatrix:RN,kernelUnitLength:null,keyPoints:null,keySplines:null,keyTimes:null,kerning:null,lang:null,lengthAdjust:null,letterSpacing:null,lightingColor:null,limitingConeAngle:U,local:null,markerEnd:null,markerMid:null,markerStart:null,markerHeight:null,markerUnits:null,markerWidth:null,mask:null,maskContentUnits:null,maskUnits:null,mathematical:null,max:null,media:null,mediaCharacterEncoding:null,mediaContentEncodings:null,mediaSize:U,mediaTime:null,method:null,min:null,mode:null,name:null,navDown:null,navDownLeft:null,navDownRight:null,navLeft:null,navNext:null,navPrev:null,navRight:null,navUp:null,navUpLeft:null,navUpRight:null,numOctaves:null,observer:null,offset:null,onAbort:null,onActivate:null,onAfterPrint:null,onBeforePrint:null,onBegin:null,onCancel:null,onCanPlay:null,onCanPlayThrough:null,onChange:null,onClick:null,onClose:null,onCopy:null,onCueChange:null,onCut:null,onDblClick:null,onDrag:null,onDragEnd:null,onDragEnter:null,onDragExit:null,onDragLeave:null,onDragOver:null,onDragStart:null,onDrop:null,onDurationChange:null,onEmptied:null,onEnd:null,onEnded:null,onError:null,onFocus:null,onFocusIn:null,onFocusOut:null,onHashChange:null,onInput:null,onInvalid:null,onKeyDown:null,onKeyPress:null,onKeyUp:null,onLoad:null,onLoadedData:null,onLoadedMetadata:null,onLoadStart:null,onMessage:null,onMouseDown:null,onMouseEnter:null,onMouseLeave:null,onMouseMove:null,onMouseOut:null,onMouseOver:null,onMouseUp:null,onMouseWheel:null,onOffline:null,onOnline:null,onPageHide:null,onPageShow:null,onPaste:null,onPause:null,onPlay:null,onPlaying:null,onPopState:null,onProgress:null,onRateChange:null,onRepeat:null,onReset:null,onResize:null,onScroll:null,onSeeked:null,onSeeking:null,onSelect:null,onShow:null,onStalled:null,onStorage:null,onSubmit:null,onSuspend:null,onTimeUpdate:null,onToggle:null,onUnload:null,onVolumeChange:null,onWaiting:null,onZoom:null,opacity:null,operator:null,order:null,orient:null,orientation:null,origin:null,overflow:null,overlay:null,overlinePosition:U,overlineThickness:U,paintOrder:null,panose1:null,path:null,pathLength:U,patternContentUnits:null,patternTransform:null,patternUnits:null,phase:null,ping:W,pitch:null,playbackOrder:null,pointerEvents:null,points:null,pointsAtX:U,pointsAtY:U,pointsAtZ:U,preserveAlpha:null,preserveAspectRatio:null,primitiveUnits:null,propagate:null,property:RN,r:null,radius:null,referrerPolicy:null,refX:null,refY:null,rel:RN,rev:RN,renderingIntent:null,repeatCount:null,repeatDur:null,requiredExtensions:RN,requiredFeatures:RN,requiredFonts:RN,requiredFormats:RN,resource:null,restart:null,result:null,rotate:null,rx:null,ry:null,scale:null,seed:null,shapeRendering:null,side:null,slope:null,snapshotTime:null,specularConstant:U,specularExponent:U,spreadMethod:null,spacing:null,startOffset:null,stdDeviation:null,stemh:null,stemv:null,stitchTiles:null,stopColor:null,stopOpacity:null,strikethroughPosition:U,strikethroughThickness:U,string:null,stroke:null,strokeDashArray:RN,strokeDashOffset:null,strokeLineCap:null,strokeLineJoin:null,strokeMiterLimit:U,strokeOpacity:U,strokeWidth:null,style:null,surfaceScale:U,syncBehavior:null,syncBehaviorDefault:null,syncMaster:null,syncTolerance:null,syncToleranceDefault:null,systemLanguage:RN,tabIndex:U,tableValues:null,target:null,targetX:U,targetY:U,textAnchor:null,textDecoration:null,textRendering:null,textLength:null,timelineBegin:null,title:null,transformBehavior:null,type:null,typeOf:RN,to:null,transform:null,transformOrigin:null,u1:null,u2:null,underlinePosition:U,underlineThickness:U,unicode:null,unicodeBidi:null,unicodeRange:null,unitsPerEm:U,values:null,vAlphabetic:U,vMathematical:U,vectorEffect:null,vHanging:U,vIdeographic:U,version:null,vertAdvY:U,vertOriginX:U,vertOriginY:U,viewBox:null,viewTarget:null,visibility:null,width:null,widths:null,wordSpacing:null,writingMode:null,x:null,x1:null,x2:null,xChannelSelector:null,xHeight:U,y:null,y1:null,y2:null,yChannelSelector:null,z:null,zoomAndPan:null},space:`svg`,transform:GN}),YN=UN({properties:{xLinkActuate:null,xLinkArcRole:null,xLinkHref:null,xLinkRole:null,xLinkShow:null,xLinkTitle:null,xLinkType:null},space:`xlink`,transform(e,t){return`xlink:`+t.slice(5).toLowerCase()}}),XN=UN({attributes:{xmlnsxlink:`xmlns:xlink`},properties:{xmlnsXLink:null,xmlns:null},space:`xmlns`,transform:KN}),ZN=UN({properties:{xmlBase:null,xmlLang:null,xmlSpace:null},space:`xml`,transform(e,t){return`xml:`+t.slice(3).toLowerCase()}}),QN=/[A-Z]/g,$N=/-[a-z]/g,eP=/^data[-\w.:]+$/i;function tP(e,t){let n=MN(t),r=t,i=NN;if(n in e.normal)return e.property[e.normal[n]];if(n.length>4&&n.slice(0,4)===`data`&&eP.test(t)){if(t.charAt(4)===`-`){let e=t.slice(5).replace($N,rP);r=`data`+e.charAt(0).toUpperCase()+e.slice(1)}else{let e=t.slice(4);if(!$N.test(e)){let n=e.replace(QN,nP);n.charAt(0)!==`-`&&(n=`-`+n),t=`data`+n}}i=VN}return new i(r,t)}function nP(e){return`-`+e.toLowerCase()}function rP(e){return e.charAt(1).toUpperCase()}var iP=jN([WN,qN,YN,XN,ZN],`html`),aP=jN([WN,JN,YN,XN,ZN],`svg`),oP={}.hasOwnProperty;function sP(e,t){let n=t||{};function r(t,...n){let i=r.invalid,a=r.handlers;if(t&&oP.call(t,e)){let n=String(t[e]);i=oP.call(a,n)?a[n]:r.unknown}if(i)return i.call(this,t,...n)}return r.handlers=n.handlers||{},r.invalid=n.invalid,r.unknown=n.unknown,r}var cP=/["&'<>`]/g,lP=/[\uD800-\uDBFF][\uDC00-\uDFFF]/g,uP=/[\x01-\t\v\f\x0E-\x1F\x7F\x81\x8D\x8F\x90\x9D\xA0-\uFFFF]/g,dP=/[|\\{}()[\]^$+*?.]/g,fP=new WeakMap;function pP(e,t){if(e=e.replace(t.subset?mP(t.subset):cP,r),t.subset||t.escapeOnly)return e;return e.replace(lP,n).replace(uP,r);function n(e,n,r){return t.format((e.charCodeAt(0)-55296)*1024+e.charCodeAt(1)-56320+65536,r.charCodeAt(n+2),t)}function r(e,n,r){return t.format(e.charCodeAt(0),r.charCodeAt(n+1),t)}}function mP(e){let t=fP.get(e);return t||(t=hP(e),fP.set(e,t)),t}function hP(e){let t=[],n=-1;for(;++n<e.length;)t.push(e[n].replace(dP,`\\$&`));return RegExp(`(?:`+t.join(`|`)+`)`,`g`)}var gP=/[\dA-Fa-f]/;function _P(e,t,n){let r=`&#x`+e.toString(16).toUpperCase();return n&&t&&!gP.test(String.fromCharCode(t))?r:r+`;`}var vP=/\d/;function yP(e,t,n){let r=`&#`+String(e);return n&&t&&!vP.test(String.fromCharCode(t))?r:r+`;`}var bP=`AElig.AMP.Aacute.Acirc.Agrave.Aring.Atilde.Auml.COPY.Ccedil.ETH.Eacute.Ecirc.Egrave.Euml.GT.Iacute.Icirc.Igrave.Iuml.LT.Ntilde.Oacute.Ocirc.Ograve.Oslash.Otilde.Ouml.QUOT.REG.THORN.Uacute.Ucirc.Ugrave.Uuml.Yacute.aacute.acirc.acute.aelig.agrave.amp.aring.atilde.auml.brvbar.ccedil.cedil.cent.copy.curren.deg.divide.eacute.ecirc.egrave.eth.euml.frac12.frac14.frac34.gt.iacute.icirc.iexcl.igrave.iquest.iuml.laquo.lt.macr.micro.middot.nbsp.not.ntilde.oacute.ocirc.ograve.ordf.ordm.oslash.otilde.ouml.para.plusmn.pound.quot.raquo.reg.sect.shy.sup1.sup2.sup3.szlig.thorn.times.uacute.ucirc.ugrave.uml.uuml.yacute.yen.yuml`.split(`.`),xP={nbsp:`\xA0`,iexcl:`¡`,cent:`¢`,pound:`£`,curren:`¤`,yen:`¥`,brvbar:`¦`,sect:`§`,uml:`¨`,copy:`©`,ordf:`ª`,laquo:`«`,not:`¬`,shy:``,reg:`®`,macr:`¯`,deg:`°`,plusmn:`±`,sup2:`²`,sup3:`³`,acute:`´`,micro:`µ`,para:`¶`,middot:`·`,cedil:`¸`,sup1:`¹`,ordm:`º`,raquo:`»`,frac14:`¼`,frac12:`½`,frac34:`¾`,iquest:`¿`,Agrave:`À`,Aacute:`Á`,Acirc:`Â`,Atilde:`Ã`,Auml:`Ä`,Aring:`Å`,AElig:`Æ`,Ccedil:`Ç`,Egrave:`È`,Eacute:`É`,Ecirc:`Ê`,Euml:`Ë`,Igrave:`Ì`,Iacute:`Í`,Icirc:`Î`,Iuml:`Ï`,ETH:`Ð`,Ntilde:`Ñ`,Ograve:`Ò`,Oacute:`Ó`,Ocirc:`Ô`,Otilde:`Õ`,Ouml:`Ö`,times:`×`,Oslash:`Ø`,Ugrave:`Ù`,Uacute:`Ú`,Ucirc:`Û`,Uuml:`Ü`,Yacute:`Ý`,THORN:`Þ`,szlig:`ß`,agrave:`à`,aacute:`á`,acirc:`â`,atilde:`ã`,auml:`ä`,aring:`å`,aelig:`æ`,ccedil:`ç`,egrave:`è`,eacute:`é`,ecirc:`ê`,euml:`ë`,igrave:`ì`,iacute:`í`,icirc:`î`,iuml:`ï`,eth:`ð`,ntilde:`ñ`,ograve:`ò`,oacute:`ó`,ocirc:`ô`,otilde:`õ`,ouml:`ö`,divide:`÷`,oslash:`ø`,ugrave:`ù`,uacute:`ú`,ucirc:`û`,uuml:`ü`,yacute:`ý`,thorn:`þ`,yuml:`ÿ`,fnof:`ƒ`,Alpha:`Α`,Beta:`Β`,Gamma:`Γ`,Delta:`Δ`,Epsilon:`Ε`,Zeta:`Ζ`,Eta:`Η`,Theta:`Θ`,Iota:`Ι`,Kappa:`Κ`,Lambda:`Λ`,Mu:`Μ`,Nu:`Ν`,Xi:`Ξ`,Omicron:`Ο`,Pi:`Π`,Rho:`Ρ`,Sigma:`Σ`,Tau:`Τ`,Upsilon:`Υ`,Phi:`Φ`,Chi:`Χ`,Psi:`Ψ`,Omega:`Ω`,alpha:`α`,beta:`β`,gamma:`γ`,delta:`δ`,epsilon:`ε`,zeta:`ζ`,eta:`η`,theta:`θ`,iota:`ι`,kappa:`κ`,lambda:`λ`,mu:`μ`,nu:`ν`,xi:`ξ`,omicron:`ο`,pi:`π`,rho:`ρ`,sigmaf:`ς`,sigma:`σ`,tau:`τ`,upsilon:`υ`,phi:`φ`,chi:`χ`,psi:`ψ`,omega:`ω`,thetasym:`ϑ`,upsih:`ϒ`,piv:`ϖ`,bull:`•`,hellip:`…`,prime:`′`,Prime:`″`,oline:`‾`,frasl:`⁄`,weierp:`℘`,image:`ℑ`,real:`ℜ`,trade:`™`,alefsym:`ℵ`,larr:`←`,uarr:`↑`,rarr:`→`,darr:`↓`,harr:`↔`,crarr:`↵`,lArr:`⇐`,uArr:`⇑`,rArr:`⇒`,dArr:`⇓`,hArr:`⇔`,forall:`∀`,part:`∂`,exist:`∃`,empty:`∅`,nabla:`∇`,isin:`∈`,notin:`∉`,ni:`∋`,prod:`∏`,sum:`∑`,minus:`−`,lowast:`∗`,radic:`√`,prop:`∝`,infin:`∞`,ang:`∠`,and:`∧`,or:`∨`,cap:`∩`,cup:`∪`,int:`∫`,there4:`∴`,sim:`∼`,cong:`≅`,asymp:`≈`,ne:`≠`,equiv:`≡`,le:`≤`,ge:`≥`,sub:`⊂`,sup:`⊃`,nsub:`⊄`,sube:`⊆`,supe:`⊇`,oplus:`⊕`,otimes:`⊗`,perp:`⊥`,sdot:`⋅`,lceil:`⌈`,rceil:`⌉`,lfloor:`⌊`,rfloor:`⌋`,lang:`〈`,rang:`〉`,loz:`◊`,spades:`♠`,clubs:`♣`,hearts:`♥`,diams:`♦`,quot:`"`,amp:`&`,lt:`<`,gt:`>`,OElig:`Œ`,oelig:`œ`,Scaron:`Š`,scaron:`š`,Yuml:`Ÿ`,circ:`ˆ`,tilde:`˜`,ensp:` `,emsp:` `,thinsp:` `,zwnj:``,zwj:``,lrm:``,rlm:``,ndash:`–`,mdash:`—`,lsquo:`‘`,rsquo:`’`,sbquo:`‚`,ldquo:`“`,rdquo:`”`,bdquo:`„`,dagger:`†`,Dagger:`‡`,permil:`‰`,lsaquo:`‹`,rsaquo:`›`,euro:`€`},SP=[`cent`,`copy`,`divide`,`gt`,`lt`,`not`,`para`,`times`],CP={}.hasOwnProperty,wP={},TP;for(TP in xP)CP.call(xP,TP)&&(wP[xP[TP]]=TP);var EP=/[^\dA-Za-z]/;function DP(e,t,n,r){let i=String.fromCharCode(e);if(CP.call(wP,i)){let e=wP[i],a=`&`+e;return n&&bP.includes(e)&&!SP.includes(e)&&(!r||t&&t!==61&&EP.test(String.fromCharCode(t)))?a:a+`;`}return``}function OP(e,t,n){let r=_P(e,t,n.omitOptionalSemicolons),i;if((n.useNamedReferences||n.useShortestReferences)&&(i=DP(e,t,n.omitOptionalSemicolons,n.attribute)),(n.useShortestReferences||!i)&&n.useShortestReferences){let i=yP(e,t,n.omitOptionalSemicolons);i.length<r.length&&(r=i)}return i&&(!n.useShortestReferences||i.length<r.length)?i:r}function kP(e,t){return pP(e,Object.assign({format:OP},t))}var AP=/^>|^->|<!--|-->|--!>|<!-$/g,jP=[`>`],MP=[`<`,`>`];function NP(e,t,n,r){return r.settings.bogusComments?`<?`+kP(e.value,Object.assign({},r.settings.characterReferences,{subset:jP}))+`>`:`<!--`+e.value.replace(AP,i)+`-->`;function i(e){return kP(e,Object.assign({},r.settings.characterReferences,{subset:MP}))}}function PP(e,t,n,r){return`<!`+(r.settings.upperDoctype?`DOCTYPE`:`doctype`)+(r.settings.tightDoctype?``:` `)+`html>`}function FP(e,t){let n=String(e);if(typeof t!=`string`)throw TypeError(`Expected character`);let r=0,i=n.indexOf(t);for(;i!==-1;)r++,i=n.indexOf(t,i+t.length);return r}function IP(e){let t=[],n=String(e||``),r=n.indexOf(`,`),i=0,a=!1;for(;!a;){r===-1&&(r=n.length,a=!0);let e=n.slice(i,r).trim();(e||!a)&&t.push(e),i=r+1,r=n.indexOf(`,`,i)}return t}function LP(e,t){let n=t||{};return(e[e.length-1]===``?[...e,``]:e).join((n.padRight?` `:``)+`,`+(n.padLeft===!1?``:` `)).trim()}function RP(e){let t=String(e||``).trim();return t?t.split(/[ \t\n\r\f]+/g):[]}function zP(e){return e.join(` `).trim()}var BP=/[ \t\n\f\r]/g;function VP(e){return typeof e==`object`?e.type===`text`&&HP(e.value):HP(e)}function HP(e){return e.replace(BP,``)===``}var G=GP(1),UP=GP(-1),WP=[];function GP(e){return t;function t(t,n,r){let i=t?t.children:WP,a=(n||0)+e,o=i[a];if(!r)for(;o&&VP(o);)a+=e,o=i[a];return o}}var KP={}.hasOwnProperty;function qP(e){return t;function t(t,n,r){return KP.call(e,t.tagName)&&e[t.tagName](t,n,r)}}var JP=qP({body:ZP,caption:YP,colgroup:YP,dd:tF,dt:eF,head:YP,html:XP,li:$P,optgroup:rF,option:iF,p:QP,rp:nF,rt:nF,tbody:oF,td:lF,tfoot:sF,th:lF,thead:aF,tr:cF});function YP(e,t,n){let r=G(n,t,!0);return!r||r.type!==`comment`&&!(r.type===`text`&&VP(r.value.charAt(0)))}function XP(e,t,n){let r=G(n,t);return!r||r.type!==`comment`}function ZP(e,t,n){let r=G(n,t);return!r||r.type!==`comment`}function QP(e,t,n){let r=G(n,t);return r?r.type===`element`&&(r.tagName===`address`||r.tagName===`article`||r.tagName===`aside`||r.tagName===`blockquote`||r.tagName===`details`||r.tagName===`div`||r.tagName===`dl`||r.tagName===`fieldset`||r.tagName===`figcaption`||r.tagName===`figure`||r.tagName===`footer`||r.tagName===`form`||r.tagName===`h1`||r.tagName===`h2`||r.tagName===`h3`||r.tagName===`h4`||r.tagName===`h5`||r.tagName===`h6`||r.tagName===`header`||r.tagName===`hgroup`||r.tagName===`hr`||r.tagName===`main`||r.tagName===`menu`||r.tagName===`nav`||r.tagName===`ol`||r.tagName===`p`||r.tagName===`pre`||r.tagName===`section`||r.tagName===`table`||r.tagName===`ul`):!n||n.type!==`element`||n.tagName!==`a`&&n.tagName!==`audio`&&n.tagName!==`del`&&n.tagName!==`ins`&&n.tagName!==`map`&&n.tagName!==`noscript`&&n.tagName!==`video`}function $P(e,t,n){let r=G(n,t);return!r||r.type===`element`&&r.tagName===`li`}function eF(e,t,n){let r=G(n,t);return!!(r&&r.type===`element`&&(r.tagName===`dt`||r.tagName===`dd`))}function tF(e,t,n){let r=G(n,t);return!r||r.type===`element`&&(r.tagName===`dt`||r.tagName===`dd`)}function nF(e,t,n){let r=G(n,t);return!r||r.type===`element`&&(r.tagName===`rp`||r.tagName===`rt`)}function rF(e,t,n){let r=G(n,t);return!r||r.type===`element`&&r.tagName===`optgroup`}function iF(e,t,n){let r=G(n,t);return!r||r.type===`element`&&(r.tagName===`option`||r.tagName===`optgroup`)}function aF(e,t,n){let r=G(n,t);return!!(r&&r.type===`element`&&(r.tagName===`tbody`||r.tagName===`tfoot`))}function oF(e,t,n){let r=G(n,t);return!r||r.type===`element`&&(r.tagName===`tbody`||r.tagName===`tfoot`)}function sF(e,t,n){return!G(n,t)}function cF(e,t,n){let r=G(n,t);return!r||r.type===`element`&&r.tagName===`tr`}function lF(e,t,n){let r=G(n,t);return!r||r.type===`element`&&(r.tagName===`td`||r.tagName===`th`)}var uF=qP({body:pF,colgroup:mF,head:fF,html:dF,tbody:hF});function dF(e){let t=G(e,-1);return!t||t.type!==`comment`}function fF(e){let t=new Set;for(let n of e.children)if(n.type===`element`&&(n.tagName===`base`||n.tagName===`title`)){if(t.has(n.tagName))return!1;t.add(n.tagName)}let n=e.children[0];return!n||n.type===`element`}function pF(e){let t=G(e,-1,!0);return!t||t.type!==`comment`&&!(t.type===`text`&&VP(t.value.charAt(0)))&&(t.type!==`element`||t.tagName!==`meta`&&t.tagName!==`link`&&t.tagName!==`script`&&t.tagName!==`style`&&t.tagName!==`template`)}function mF(e,t,n){let r=UP(n,t),i=G(e,-1,!0);return n&&r&&r.type===`element`&&r.tagName===`colgroup`&&JP(r,n.children.indexOf(r),n)?!1:!!(i&&i.type===`element`&&i.tagName===`col`)}function hF(e,t,n){let r=UP(n,t),i=G(e,-1);return n&&r&&r.type===`element`&&(r.tagName===`thead`||r.tagName===`tbody`)&&JP(r,n.children.indexOf(r),n)?!1:!!(i&&i.type===`element`&&i.tagName===`tr`)}var gF={name:[[`
|
|
33
|
+
`);return t?n.pop():n.push(n.pop().slice(0,-1)),n}function bN(e,t){return e?.cacheKey===t?.cacheKey&&e?.contents===t?.contents&&e?.name===t?.name&&e?.lang===t?.lang}function xN(e){return{type:`text`,value:e}}function B({tagName:e,children:t=[],properties:n={}}){return{type:`element`,tagName:e,properties:n,children:t}}function SN({name:e,width:t=16,height:n=16,properties:r}){return B({tagName:`svg`,properties:{width:t,height:n,viewBox:`0 0 16 16`,...r},children:[B({tagName:`use`,properties:{href:`#${e.replace(/^#/,``)}`}})]})}function CN(e){let t=e.children[0];for(;t!=null;){if(t.type===`element`&&t.tagName===`code`)return t;t=`children`in t?t.children[0]:null}}function wN(e){return B({tagName:`div`,properties:{"data-gutter":``},children:e})}function TN(e,t,n,r={}){return B({tagName:`div`,properties:{"data-line-type":e,"data-column-number":t,"data-line-index":n,...r},children:t==null?void 0:[B({tagName:`span`,properties:{"data-line-number-content":``},children:[xN(`${t}`)]})]})}function EN(e,t,n){return B({tagName:`div`,properties:{"data-gutter-buffer":t,"data-buffer-size":n,"data-line-type":t===`annotation`?void 0:e,style:t===`annotation`?`grid-row: span ${n};`:`grid-row: span ${n};min-height:calc(${n} * 1lh);`}})}function DN(){return B({tagName:`button`,properties:{"data-utility-button":``,type:`button`},children:[SN({name:`diffs-icon-plus`,properties:{"data-icon":``}})]})}function ON(e,t){return e.lineNumber===t.lineNumber&&e.side===t.side}function kN(e){for(let t of e)if(t instanceof HTMLElement&&(t.hasAttribute(`data-utility-button`)||t.hasAttribute(`data-gutter-utility-slot`)||t.getAttribute(`slot`)===`gutter-utility-slot`||t.getAttribute(`name`)===`gutter-utility-slot`))return!0;return!1}var AN=[`area`,`base`,`basefont`,`bgsound`,`br`,`col`,`command`,`embed`,`frame`,`hr`,`image`,`img`,`input`,`keygen`,`link`,`meta`,`param`,`source`,`track`,`wbr`],jN=class{constructor(e,t,n){this.normal=t,this.property=e,n&&(this.space=n)}};jN.prototype.normal={},jN.prototype.property={},jN.prototype.space=void 0;function MN(e,t){let n={},r={};for(let t of e)Object.assign(n,t.property),Object.assign(r,t.normal);return new jN(n,r,t)}function NN(e){return e.toLowerCase()}var PN=class{constructor(e,t){this.attribute=t,this.property=e}};PN.prototype.attribute=``,PN.prototype.booleanish=!1,PN.prototype.boolean=!1,PN.prototype.commaOrSpaceSeparated=!1,PN.prototype.commaSeparated=!1,PN.prototype.defined=!1,PN.prototype.mustUseProperty=!1,PN.prototype.number=!1,PN.prototype.overloadedBoolean=!1,PN.prototype.property=``,PN.prototype.spaceSeparated=!1,PN.prototype.space=void 0;var FN=e({boolean:()=>V,booleanish:()=>H,commaOrSpaceSeparated:()=>zN,commaSeparated:()=>RN,number:()=>U,overloadedBoolean:()=>LN,spaceSeparated:()=>W}),IN=0,V=BN(),H=BN(),LN=BN(),U=BN(),W=BN(),RN=BN(),zN=BN();function BN(){return 2**++IN}var VN=Object.keys(FN),HN=class extends PN{constructor(e,t,n,r){let i=-1;if(super(e,t),UN(this,`space`,r),typeof n==`number`)for(;++i<VN.length;){let e=VN[i];UN(this,VN[i],(n&FN[e])===FN[e])}}};HN.prototype.defined=!0;function UN(e,t,n){n&&(e[t]=n)}function WN(e){let t={},n={};for(let[r,i]of Object.entries(e.properties)){let a=new HN(r,e.transform(e.attributes||{},r),i,e.space);e.mustUseProperty&&e.mustUseProperty.includes(r)&&(a.mustUseProperty=!0),t[r]=a,n[NN(r)]=r,n[NN(a.attribute)]=r}return new jN(t,n,e.space)}var GN=WN({properties:{ariaActiveDescendant:null,ariaAtomic:H,ariaAutoComplete:null,ariaBusy:H,ariaChecked:H,ariaColCount:U,ariaColIndex:U,ariaColSpan:U,ariaControls:W,ariaCurrent:null,ariaDescribedBy:W,ariaDetails:null,ariaDisabled:H,ariaDropEffect:W,ariaErrorMessage:null,ariaExpanded:H,ariaFlowTo:W,ariaGrabbed:H,ariaHasPopup:null,ariaHidden:H,ariaInvalid:null,ariaKeyShortcuts:null,ariaLabel:null,ariaLabelledBy:W,ariaLevel:U,ariaLive:null,ariaModal:H,ariaMultiLine:H,ariaMultiSelectable:H,ariaOrientation:null,ariaOwns:W,ariaPlaceholder:null,ariaPosInSet:U,ariaPressed:H,ariaReadOnly:H,ariaRelevant:null,ariaRequired:H,ariaRoleDescription:W,ariaRowCount:U,ariaRowIndex:U,ariaRowSpan:U,ariaSelected:H,ariaSetSize:U,ariaSort:null,ariaValueMax:U,ariaValueMin:U,ariaValueNow:U,ariaValueText:null,role:null},transform(e,t){return t===`role`?t:`aria-`+t.slice(4).toLowerCase()}});function KN(e,t){return t in e?e[t]:t}function qN(e,t){return KN(e,t.toLowerCase())}var JN=WN({attributes:{acceptcharset:`accept-charset`,classname:`class`,htmlfor:`for`,httpequiv:`http-equiv`},mustUseProperty:[`checked`,`multiple`,`muted`,`selected`],properties:{abbr:null,accept:RN,acceptCharset:W,accessKey:W,action:null,allow:null,allowFullScreen:V,allowPaymentRequest:V,allowUserMedia:V,alt:null,as:null,async:V,autoCapitalize:null,autoComplete:W,autoFocus:V,autoPlay:V,blocking:W,capture:null,charSet:null,checked:V,cite:null,className:W,cols:U,colSpan:null,content:null,contentEditable:H,controls:V,controlsList:W,coords:U|RN,crossOrigin:null,data:null,dateTime:null,decoding:null,default:V,defer:V,dir:null,dirName:null,disabled:V,download:LN,draggable:H,encType:null,enterKeyHint:null,fetchPriority:null,form:null,formAction:null,formEncType:null,formMethod:null,formNoValidate:V,formTarget:null,headers:W,height:U,hidden:LN,high:U,href:null,hrefLang:null,htmlFor:W,httpEquiv:W,id:null,imageSizes:null,imageSrcSet:null,inert:V,inputMode:null,integrity:null,is:null,isMap:V,itemId:null,itemProp:W,itemRef:W,itemScope:V,itemType:W,kind:null,label:null,lang:null,language:null,list:null,loading:null,loop:V,low:U,manifest:null,max:null,maxLength:U,media:null,method:null,min:null,minLength:U,multiple:V,muted:V,name:null,nonce:null,noModule:V,noValidate:V,onAbort:null,onAfterPrint:null,onAuxClick:null,onBeforeMatch:null,onBeforePrint:null,onBeforeToggle:null,onBeforeUnload:null,onBlur:null,onCancel:null,onCanPlay:null,onCanPlayThrough:null,onChange:null,onClick:null,onClose:null,onContextLost:null,onContextMenu:null,onContextRestored:null,onCopy:null,onCueChange:null,onCut:null,onDblClick:null,onDrag:null,onDragEnd:null,onDragEnter:null,onDragExit:null,onDragLeave:null,onDragOver:null,onDragStart:null,onDrop:null,onDurationChange:null,onEmptied:null,onEnded:null,onError:null,onFocus:null,onFormData:null,onHashChange:null,onInput:null,onInvalid:null,onKeyDown:null,onKeyPress:null,onKeyUp:null,onLanguageChange:null,onLoad:null,onLoadedData:null,onLoadedMetadata:null,onLoadEnd:null,onLoadStart:null,onMessage:null,onMessageError:null,onMouseDown:null,onMouseEnter:null,onMouseLeave:null,onMouseMove:null,onMouseOut:null,onMouseOver:null,onMouseUp:null,onOffline:null,onOnline:null,onPageHide:null,onPageShow:null,onPaste:null,onPause:null,onPlay:null,onPlaying:null,onPopState:null,onProgress:null,onRateChange:null,onRejectionHandled:null,onReset:null,onResize:null,onScroll:null,onScrollEnd:null,onSecurityPolicyViolation:null,onSeeked:null,onSeeking:null,onSelect:null,onSlotChange:null,onStalled:null,onStorage:null,onSubmit:null,onSuspend:null,onTimeUpdate:null,onToggle:null,onUnhandledRejection:null,onUnload:null,onVolumeChange:null,onWaiting:null,onWheel:null,open:V,optimum:U,pattern:null,ping:W,placeholder:null,playsInline:V,popover:null,popoverTarget:null,popoverTargetAction:null,poster:null,preload:null,readOnly:V,referrerPolicy:null,rel:W,required:V,reversed:V,rows:U,rowSpan:U,sandbox:W,scope:null,scoped:V,seamless:V,selected:V,shadowRootClonable:V,shadowRootDelegatesFocus:V,shadowRootMode:null,shape:null,size:U,sizes:null,slot:null,span:U,spellCheck:H,src:null,srcDoc:null,srcLang:null,srcSet:null,start:U,step:null,style:null,tabIndex:U,target:null,title:null,translate:null,type:null,typeMustMatch:V,useMap:null,value:H,width:U,wrap:null,writingSuggestions:null,align:null,aLink:null,archive:W,axis:null,background:null,bgColor:null,border:U,borderColor:null,bottomMargin:U,cellPadding:null,cellSpacing:null,char:null,charOff:null,classId:null,clear:null,code:null,codeBase:null,codeType:null,color:null,compact:V,declare:V,event:null,face:null,frame:null,frameBorder:null,hSpace:U,leftMargin:U,link:null,longDesc:null,lowSrc:null,marginHeight:U,marginWidth:U,noResize:V,noHref:V,noShade:V,noWrap:V,object:null,profile:null,prompt:null,rev:null,rightMargin:U,rules:null,scheme:null,scrolling:H,standby:null,summary:null,text:null,topMargin:U,valueType:null,version:null,vAlign:null,vLink:null,vSpace:U,allowTransparency:null,autoCorrect:null,autoSave:null,disablePictureInPicture:V,disableRemotePlayback:V,prefix:null,property:null,results:U,security:null,unselectable:null},space:`html`,transform:qN}),YN=WN({attributes:{accentHeight:`accent-height`,alignmentBaseline:`alignment-baseline`,arabicForm:`arabic-form`,baselineShift:`baseline-shift`,capHeight:`cap-height`,className:`class`,clipPath:`clip-path`,clipRule:`clip-rule`,colorInterpolation:`color-interpolation`,colorInterpolationFilters:`color-interpolation-filters`,colorProfile:`color-profile`,colorRendering:`color-rendering`,crossOrigin:`crossorigin`,dataType:`datatype`,dominantBaseline:`dominant-baseline`,enableBackground:`enable-background`,fillOpacity:`fill-opacity`,fillRule:`fill-rule`,floodColor:`flood-color`,floodOpacity:`flood-opacity`,fontFamily:`font-family`,fontSize:`font-size`,fontSizeAdjust:`font-size-adjust`,fontStretch:`font-stretch`,fontStyle:`font-style`,fontVariant:`font-variant`,fontWeight:`font-weight`,glyphName:`glyph-name`,glyphOrientationHorizontal:`glyph-orientation-horizontal`,glyphOrientationVertical:`glyph-orientation-vertical`,hrefLang:`hreflang`,horizAdvX:`horiz-adv-x`,horizOriginX:`horiz-origin-x`,horizOriginY:`horiz-origin-y`,imageRendering:`image-rendering`,letterSpacing:`letter-spacing`,lightingColor:`lighting-color`,markerEnd:`marker-end`,markerMid:`marker-mid`,markerStart:`marker-start`,navDown:`nav-down`,navDownLeft:`nav-down-left`,navDownRight:`nav-down-right`,navLeft:`nav-left`,navNext:`nav-next`,navPrev:`nav-prev`,navRight:`nav-right`,navUp:`nav-up`,navUpLeft:`nav-up-left`,navUpRight:`nav-up-right`,onAbort:`onabort`,onActivate:`onactivate`,onAfterPrint:`onafterprint`,onBeforePrint:`onbeforeprint`,onBegin:`onbegin`,onCancel:`oncancel`,onCanPlay:`oncanplay`,onCanPlayThrough:`oncanplaythrough`,onChange:`onchange`,onClick:`onclick`,onClose:`onclose`,onCopy:`oncopy`,onCueChange:`oncuechange`,onCut:`oncut`,onDblClick:`ondblclick`,onDrag:`ondrag`,onDragEnd:`ondragend`,onDragEnter:`ondragenter`,onDragExit:`ondragexit`,onDragLeave:`ondragleave`,onDragOver:`ondragover`,onDragStart:`ondragstart`,onDrop:`ondrop`,onDurationChange:`ondurationchange`,onEmptied:`onemptied`,onEnd:`onend`,onEnded:`onended`,onError:`onerror`,onFocus:`onfocus`,onFocusIn:`onfocusin`,onFocusOut:`onfocusout`,onHashChange:`onhashchange`,onInput:`oninput`,onInvalid:`oninvalid`,onKeyDown:`onkeydown`,onKeyPress:`onkeypress`,onKeyUp:`onkeyup`,onLoad:`onload`,onLoadedData:`onloadeddata`,onLoadedMetadata:`onloadedmetadata`,onLoadStart:`onloadstart`,onMessage:`onmessage`,onMouseDown:`onmousedown`,onMouseEnter:`onmouseenter`,onMouseLeave:`onmouseleave`,onMouseMove:`onmousemove`,onMouseOut:`onmouseout`,onMouseOver:`onmouseover`,onMouseUp:`onmouseup`,onMouseWheel:`onmousewheel`,onOffline:`onoffline`,onOnline:`ononline`,onPageHide:`onpagehide`,onPageShow:`onpageshow`,onPaste:`onpaste`,onPause:`onpause`,onPlay:`onplay`,onPlaying:`onplaying`,onPopState:`onpopstate`,onProgress:`onprogress`,onRateChange:`onratechange`,onRepeat:`onrepeat`,onReset:`onreset`,onResize:`onresize`,onScroll:`onscroll`,onSeeked:`onseeked`,onSeeking:`onseeking`,onSelect:`onselect`,onShow:`onshow`,onStalled:`onstalled`,onStorage:`onstorage`,onSubmit:`onsubmit`,onSuspend:`onsuspend`,onTimeUpdate:`ontimeupdate`,onToggle:`ontoggle`,onUnload:`onunload`,onVolumeChange:`onvolumechange`,onWaiting:`onwaiting`,onZoom:`onzoom`,overlinePosition:`overline-position`,overlineThickness:`overline-thickness`,paintOrder:`paint-order`,panose1:`panose-1`,pointerEvents:`pointer-events`,referrerPolicy:`referrerpolicy`,renderingIntent:`rendering-intent`,shapeRendering:`shape-rendering`,stopColor:`stop-color`,stopOpacity:`stop-opacity`,strikethroughPosition:`strikethrough-position`,strikethroughThickness:`strikethrough-thickness`,strokeDashArray:`stroke-dasharray`,strokeDashOffset:`stroke-dashoffset`,strokeLineCap:`stroke-linecap`,strokeLineJoin:`stroke-linejoin`,strokeMiterLimit:`stroke-miterlimit`,strokeOpacity:`stroke-opacity`,strokeWidth:`stroke-width`,tabIndex:`tabindex`,textAnchor:`text-anchor`,textDecoration:`text-decoration`,textRendering:`text-rendering`,transformOrigin:`transform-origin`,typeOf:`typeof`,underlinePosition:`underline-position`,underlineThickness:`underline-thickness`,unicodeBidi:`unicode-bidi`,unicodeRange:`unicode-range`,unitsPerEm:`units-per-em`,vAlphabetic:`v-alphabetic`,vHanging:`v-hanging`,vIdeographic:`v-ideographic`,vMathematical:`v-mathematical`,vectorEffect:`vector-effect`,vertAdvY:`vert-adv-y`,vertOriginX:`vert-origin-x`,vertOriginY:`vert-origin-y`,wordSpacing:`word-spacing`,writingMode:`writing-mode`,xHeight:`x-height`,playbackOrder:`playbackorder`,timelineBegin:`timelinebegin`},properties:{about:zN,accentHeight:U,accumulate:null,additive:null,alignmentBaseline:null,alphabetic:U,amplitude:U,arabicForm:null,ascent:U,attributeName:null,attributeType:null,azimuth:U,bandwidth:null,baselineShift:null,baseFrequency:null,baseProfile:null,bbox:null,begin:null,bias:U,by:null,calcMode:null,capHeight:U,className:W,clip:null,clipPath:null,clipPathUnits:null,clipRule:null,color:null,colorInterpolation:null,colorInterpolationFilters:null,colorProfile:null,colorRendering:null,content:null,contentScriptType:null,contentStyleType:null,crossOrigin:null,cursor:null,cx:null,cy:null,d:null,dataType:null,defaultAction:null,descent:U,diffuseConstant:U,direction:null,display:null,dur:null,divisor:U,dominantBaseline:null,download:V,dx:null,dy:null,edgeMode:null,editable:null,elevation:U,enableBackground:null,end:null,event:null,exponent:U,externalResourcesRequired:null,fill:null,fillOpacity:U,fillRule:null,filter:null,filterRes:null,filterUnits:null,floodColor:null,floodOpacity:null,focusable:null,focusHighlight:null,fontFamily:null,fontSize:null,fontSizeAdjust:null,fontStretch:null,fontStyle:null,fontVariant:null,fontWeight:null,format:null,fr:null,from:null,fx:null,fy:null,g1:RN,g2:RN,glyphName:RN,glyphOrientationHorizontal:null,glyphOrientationVertical:null,glyphRef:null,gradientTransform:null,gradientUnits:null,handler:null,hanging:U,hatchContentUnits:null,hatchUnits:null,height:null,href:null,hrefLang:null,horizAdvX:U,horizOriginX:U,horizOriginY:U,id:null,ideographic:U,imageRendering:null,initialVisibility:null,in:null,in2:null,intercept:U,k:U,k1:U,k2:U,k3:U,k4:U,kernelMatrix:zN,kernelUnitLength:null,keyPoints:null,keySplines:null,keyTimes:null,kerning:null,lang:null,lengthAdjust:null,letterSpacing:null,lightingColor:null,limitingConeAngle:U,local:null,markerEnd:null,markerMid:null,markerStart:null,markerHeight:null,markerUnits:null,markerWidth:null,mask:null,maskContentUnits:null,maskUnits:null,mathematical:null,max:null,media:null,mediaCharacterEncoding:null,mediaContentEncodings:null,mediaSize:U,mediaTime:null,method:null,min:null,mode:null,name:null,navDown:null,navDownLeft:null,navDownRight:null,navLeft:null,navNext:null,navPrev:null,navRight:null,navUp:null,navUpLeft:null,navUpRight:null,numOctaves:null,observer:null,offset:null,onAbort:null,onActivate:null,onAfterPrint:null,onBeforePrint:null,onBegin:null,onCancel:null,onCanPlay:null,onCanPlayThrough:null,onChange:null,onClick:null,onClose:null,onCopy:null,onCueChange:null,onCut:null,onDblClick:null,onDrag:null,onDragEnd:null,onDragEnter:null,onDragExit:null,onDragLeave:null,onDragOver:null,onDragStart:null,onDrop:null,onDurationChange:null,onEmptied:null,onEnd:null,onEnded:null,onError:null,onFocus:null,onFocusIn:null,onFocusOut:null,onHashChange:null,onInput:null,onInvalid:null,onKeyDown:null,onKeyPress:null,onKeyUp:null,onLoad:null,onLoadedData:null,onLoadedMetadata:null,onLoadStart:null,onMessage:null,onMouseDown:null,onMouseEnter:null,onMouseLeave:null,onMouseMove:null,onMouseOut:null,onMouseOver:null,onMouseUp:null,onMouseWheel:null,onOffline:null,onOnline:null,onPageHide:null,onPageShow:null,onPaste:null,onPause:null,onPlay:null,onPlaying:null,onPopState:null,onProgress:null,onRateChange:null,onRepeat:null,onReset:null,onResize:null,onScroll:null,onSeeked:null,onSeeking:null,onSelect:null,onShow:null,onStalled:null,onStorage:null,onSubmit:null,onSuspend:null,onTimeUpdate:null,onToggle:null,onUnload:null,onVolumeChange:null,onWaiting:null,onZoom:null,opacity:null,operator:null,order:null,orient:null,orientation:null,origin:null,overflow:null,overlay:null,overlinePosition:U,overlineThickness:U,paintOrder:null,panose1:null,path:null,pathLength:U,patternContentUnits:null,patternTransform:null,patternUnits:null,phase:null,ping:W,pitch:null,playbackOrder:null,pointerEvents:null,points:null,pointsAtX:U,pointsAtY:U,pointsAtZ:U,preserveAlpha:null,preserveAspectRatio:null,primitiveUnits:null,propagate:null,property:zN,r:null,radius:null,referrerPolicy:null,refX:null,refY:null,rel:zN,rev:zN,renderingIntent:null,repeatCount:null,repeatDur:null,requiredExtensions:zN,requiredFeatures:zN,requiredFonts:zN,requiredFormats:zN,resource:null,restart:null,result:null,rotate:null,rx:null,ry:null,scale:null,seed:null,shapeRendering:null,side:null,slope:null,snapshotTime:null,specularConstant:U,specularExponent:U,spreadMethod:null,spacing:null,startOffset:null,stdDeviation:null,stemh:null,stemv:null,stitchTiles:null,stopColor:null,stopOpacity:null,strikethroughPosition:U,strikethroughThickness:U,string:null,stroke:null,strokeDashArray:zN,strokeDashOffset:null,strokeLineCap:null,strokeLineJoin:null,strokeMiterLimit:U,strokeOpacity:U,strokeWidth:null,style:null,surfaceScale:U,syncBehavior:null,syncBehaviorDefault:null,syncMaster:null,syncTolerance:null,syncToleranceDefault:null,systemLanguage:zN,tabIndex:U,tableValues:null,target:null,targetX:U,targetY:U,textAnchor:null,textDecoration:null,textRendering:null,textLength:null,timelineBegin:null,title:null,transformBehavior:null,type:null,typeOf:zN,to:null,transform:null,transformOrigin:null,u1:null,u2:null,underlinePosition:U,underlineThickness:U,unicode:null,unicodeBidi:null,unicodeRange:null,unitsPerEm:U,values:null,vAlphabetic:U,vMathematical:U,vectorEffect:null,vHanging:U,vIdeographic:U,version:null,vertAdvY:U,vertOriginX:U,vertOriginY:U,viewBox:null,viewTarget:null,visibility:null,width:null,widths:null,wordSpacing:null,writingMode:null,x:null,x1:null,x2:null,xChannelSelector:null,xHeight:U,y:null,y1:null,y2:null,yChannelSelector:null,z:null,zoomAndPan:null},space:`svg`,transform:KN}),XN=WN({properties:{xLinkActuate:null,xLinkArcRole:null,xLinkHref:null,xLinkRole:null,xLinkShow:null,xLinkTitle:null,xLinkType:null},space:`xlink`,transform(e,t){return`xlink:`+t.slice(5).toLowerCase()}}),ZN=WN({attributes:{xmlnsxlink:`xmlns:xlink`},properties:{xmlnsXLink:null,xmlns:null},space:`xmlns`,transform:qN}),QN=WN({properties:{xmlBase:null,xmlLang:null,xmlSpace:null},space:`xml`,transform(e,t){return`xml:`+t.slice(3).toLowerCase()}}),$N=/[A-Z]/g,eP=/-[a-z]/g,tP=/^data[-\w.:]+$/i;function nP(e,t){let n=NN(t),r=t,i=PN;if(n in e.normal)return e.property[e.normal[n]];if(n.length>4&&n.slice(0,4)===`data`&&tP.test(t)){if(t.charAt(4)===`-`){let e=t.slice(5).replace(eP,iP);r=`data`+e.charAt(0).toUpperCase()+e.slice(1)}else{let e=t.slice(4);if(!eP.test(e)){let n=e.replace($N,rP);n.charAt(0)!==`-`&&(n=`-`+n),t=`data`+n}}i=HN}return new i(r,t)}function rP(e){return`-`+e.toLowerCase()}function iP(e){return e.charAt(1).toUpperCase()}var aP=MN([GN,JN,XN,ZN,QN],`html`),oP=MN([GN,YN,XN,ZN,QN],`svg`),sP={}.hasOwnProperty;function cP(e,t){let n=t||{};function r(t,...n){let i=r.invalid,a=r.handlers;if(t&&sP.call(t,e)){let n=String(t[e]);i=sP.call(a,n)?a[n]:r.unknown}if(i)return i.call(this,t,...n)}return r.handlers=n.handlers||{},r.invalid=n.invalid,r.unknown=n.unknown,r}var lP=/["&'<>`]/g,uP=/[\uD800-\uDBFF][\uDC00-\uDFFF]/g,dP=/[\x01-\t\v\f\x0E-\x1F\x7F\x81\x8D\x8F\x90\x9D\xA0-\uFFFF]/g,fP=/[|\\{}()[\]^$+*?.]/g,pP=new WeakMap;function mP(e,t){if(e=e.replace(t.subset?hP(t.subset):lP,r),t.subset||t.escapeOnly)return e;return e.replace(uP,n).replace(dP,r);function n(e,n,r){return t.format((e.charCodeAt(0)-55296)*1024+e.charCodeAt(1)-56320+65536,r.charCodeAt(n+2),t)}function r(e,n,r){return t.format(e.charCodeAt(0),r.charCodeAt(n+1),t)}}function hP(e){let t=pP.get(e);return t||(t=gP(e),pP.set(e,t)),t}function gP(e){let t=[],n=-1;for(;++n<e.length;)t.push(e[n].replace(fP,`\\$&`));return RegExp(`(?:`+t.join(`|`)+`)`,`g`)}var _P=/[\dA-Fa-f]/;function vP(e,t,n){let r=`&#x`+e.toString(16).toUpperCase();return n&&t&&!_P.test(String.fromCharCode(t))?r:r+`;`}var yP=/\d/;function bP(e,t,n){let r=`&#`+String(e);return n&&t&&!yP.test(String.fromCharCode(t))?r:r+`;`}var xP=`AElig.AMP.Aacute.Acirc.Agrave.Aring.Atilde.Auml.COPY.Ccedil.ETH.Eacute.Ecirc.Egrave.Euml.GT.Iacute.Icirc.Igrave.Iuml.LT.Ntilde.Oacute.Ocirc.Ograve.Oslash.Otilde.Ouml.QUOT.REG.THORN.Uacute.Ucirc.Ugrave.Uuml.Yacute.aacute.acirc.acute.aelig.agrave.amp.aring.atilde.auml.brvbar.ccedil.cedil.cent.copy.curren.deg.divide.eacute.ecirc.egrave.eth.euml.frac12.frac14.frac34.gt.iacute.icirc.iexcl.igrave.iquest.iuml.laquo.lt.macr.micro.middot.nbsp.not.ntilde.oacute.ocirc.ograve.ordf.ordm.oslash.otilde.ouml.para.plusmn.pound.quot.raquo.reg.sect.shy.sup1.sup2.sup3.szlig.thorn.times.uacute.ucirc.ugrave.uml.uuml.yacute.yen.yuml`.split(`.`),SP={nbsp:`\xA0`,iexcl:`¡`,cent:`¢`,pound:`£`,curren:`¤`,yen:`¥`,brvbar:`¦`,sect:`§`,uml:`¨`,copy:`©`,ordf:`ª`,laquo:`«`,not:`¬`,shy:``,reg:`®`,macr:`¯`,deg:`°`,plusmn:`±`,sup2:`²`,sup3:`³`,acute:`´`,micro:`µ`,para:`¶`,middot:`·`,cedil:`¸`,sup1:`¹`,ordm:`º`,raquo:`»`,frac14:`¼`,frac12:`½`,frac34:`¾`,iquest:`¿`,Agrave:`À`,Aacute:`Á`,Acirc:`Â`,Atilde:`Ã`,Auml:`Ä`,Aring:`Å`,AElig:`Æ`,Ccedil:`Ç`,Egrave:`È`,Eacute:`É`,Ecirc:`Ê`,Euml:`Ë`,Igrave:`Ì`,Iacute:`Í`,Icirc:`Î`,Iuml:`Ï`,ETH:`Ð`,Ntilde:`Ñ`,Ograve:`Ò`,Oacute:`Ó`,Ocirc:`Ô`,Otilde:`Õ`,Ouml:`Ö`,times:`×`,Oslash:`Ø`,Ugrave:`Ù`,Uacute:`Ú`,Ucirc:`Û`,Uuml:`Ü`,Yacute:`Ý`,THORN:`Þ`,szlig:`ß`,agrave:`à`,aacute:`á`,acirc:`â`,atilde:`ã`,auml:`ä`,aring:`å`,aelig:`æ`,ccedil:`ç`,egrave:`è`,eacute:`é`,ecirc:`ê`,euml:`ë`,igrave:`ì`,iacute:`í`,icirc:`î`,iuml:`ï`,eth:`ð`,ntilde:`ñ`,ograve:`ò`,oacute:`ó`,ocirc:`ô`,otilde:`õ`,ouml:`ö`,divide:`÷`,oslash:`ø`,ugrave:`ù`,uacute:`ú`,ucirc:`û`,uuml:`ü`,yacute:`ý`,thorn:`þ`,yuml:`ÿ`,fnof:`ƒ`,Alpha:`Α`,Beta:`Β`,Gamma:`Γ`,Delta:`Δ`,Epsilon:`Ε`,Zeta:`Ζ`,Eta:`Η`,Theta:`Θ`,Iota:`Ι`,Kappa:`Κ`,Lambda:`Λ`,Mu:`Μ`,Nu:`Ν`,Xi:`Ξ`,Omicron:`Ο`,Pi:`Π`,Rho:`Ρ`,Sigma:`Σ`,Tau:`Τ`,Upsilon:`Υ`,Phi:`Φ`,Chi:`Χ`,Psi:`Ψ`,Omega:`Ω`,alpha:`α`,beta:`β`,gamma:`γ`,delta:`δ`,epsilon:`ε`,zeta:`ζ`,eta:`η`,theta:`θ`,iota:`ι`,kappa:`κ`,lambda:`λ`,mu:`μ`,nu:`ν`,xi:`ξ`,omicron:`ο`,pi:`π`,rho:`ρ`,sigmaf:`ς`,sigma:`σ`,tau:`τ`,upsilon:`υ`,phi:`φ`,chi:`χ`,psi:`ψ`,omega:`ω`,thetasym:`ϑ`,upsih:`ϒ`,piv:`ϖ`,bull:`•`,hellip:`…`,prime:`′`,Prime:`″`,oline:`‾`,frasl:`⁄`,weierp:`℘`,image:`ℑ`,real:`ℜ`,trade:`™`,alefsym:`ℵ`,larr:`←`,uarr:`↑`,rarr:`→`,darr:`↓`,harr:`↔`,crarr:`↵`,lArr:`⇐`,uArr:`⇑`,rArr:`⇒`,dArr:`⇓`,hArr:`⇔`,forall:`∀`,part:`∂`,exist:`∃`,empty:`∅`,nabla:`∇`,isin:`∈`,notin:`∉`,ni:`∋`,prod:`∏`,sum:`∑`,minus:`−`,lowast:`∗`,radic:`√`,prop:`∝`,infin:`∞`,ang:`∠`,and:`∧`,or:`∨`,cap:`∩`,cup:`∪`,int:`∫`,there4:`∴`,sim:`∼`,cong:`≅`,asymp:`≈`,ne:`≠`,equiv:`≡`,le:`≤`,ge:`≥`,sub:`⊂`,sup:`⊃`,nsub:`⊄`,sube:`⊆`,supe:`⊇`,oplus:`⊕`,otimes:`⊗`,perp:`⊥`,sdot:`⋅`,lceil:`⌈`,rceil:`⌉`,lfloor:`⌊`,rfloor:`⌋`,lang:`〈`,rang:`〉`,loz:`◊`,spades:`♠`,clubs:`♣`,hearts:`♥`,diams:`♦`,quot:`"`,amp:`&`,lt:`<`,gt:`>`,OElig:`Œ`,oelig:`œ`,Scaron:`Š`,scaron:`š`,Yuml:`Ÿ`,circ:`ˆ`,tilde:`˜`,ensp:` `,emsp:` `,thinsp:` `,zwnj:``,zwj:``,lrm:``,rlm:``,ndash:`–`,mdash:`—`,lsquo:`‘`,rsquo:`’`,sbquo:`‚`,ldquo:`“`,rdquo:`”`,bdquo:`„`,dagger:`†`,Dagger:`‡`,permil:`‰`,lsaquo:`‹`,rsaquo:`›`,euro:`€`},CP=[`cent`,`copy`,`divide`,`gt`,`lt`,`not`,`para`,`times`],wP={}.hasOwnProperty,TP={},EP;for(EP in SP)wP.call(SP,EP)&&(TP[SP[EP]]=EP);var DP=/[^\dA-Za-z]/;function OP(e,t,n,r){let i=String.fromCharCode(e);if(wP.call(TP,i)){let e=TP[i],a=`&`+e;return n&&xP.includes(e)&&!CP.includes(e)&&(!r||t&&t!==61&&DP.test(String.fromCharCode(t)))?a:a+`;`}return``}function kP(e,t,n){let r=vP(e,t,n.omitOptionalSemicolons),i;if((n.useNamedReferences||n.useShortestReferences)&&(i=OP(e,t,n.omitOptionalSemicolons,n.attribute)),(n.useShortestReferences||!i)&&n.useShortestReferences){let i=bP(e,t,n.omitOptionalSemicolons);i.length<r.length&&(r=i)}return i&&(!n.useShortestReferences||i.length<r.length)?i:r}function AP(e,t){return mP(e,Object.assign({format:kP},t))}var jP=/^>|^->|<!--|-->|--!>|<!-$/g,MP=[`>`],NP=[`<`,`>`];function PP(e,t,n,r){return r.settings.bogusComments?`<?`+AP(e.value,Object.assign({},r.settings.characterReferences,{subset:MP}))+`>`:`<!--`+e.value.replace(jP,i)+`-->`;function i(e){return AP(e,Object.assign({},r.settings.characterReferences,{subset:NP}))}}function FP(e,t,n,r){return`<!`+(r.settings.upperDoctype?`DOCTYPE`:`doctype`)+(r.settings.tightDoctype?``:` `)+`html>`}function IP(e,t){let n=String(e);if(typeof t!=`string`)throw TypeError(`Expected character`);let r=0,i=n.indexOf(t);for(;i!==-1;)r++,i=n.indexOf(t,i+t.length);return r}function LP(e){let t=[],n=String(e||``),r=n.indexOf(`,`),i=0,a=!1;for(;!a;){r===-1&&(r=n.length,a=!0);let e=n.slice(i,r).trim();(e||!a)&&t.push(e),i=r+1,r=n.indexOf(`,`,i)}return t}function RP(e,t){let n=t||{};return(e[e.length-1]===``?[...e,``]:e).join((n.padRight?` `:``)+`,`+(n.padLeft===!1?``:` `)).trim()}function zP(e){let t=String(e||``).trim();return t?t.split(/[ \t\n\r\f]+/g):[]}function BP(e){return e.join(` `).trim()}var VP=/[ \t\n\f\r]/g;function HP(e){return typeof e==`object`?e.type===`text`&&UP(e.value):UP(e)}function UP(e){return e.replace(VP,``)===``}var G=KP(1),WP=KP(-1),GP=[];function KP(e){return t;function t(t,n,r){let i=t?t.children:GP,a=(n||0)+e,o=i[a];if(!r)for(;o&&HP(o);)a+=e,o=i[a];return o}}var qP={}.hasOwnProperty;function JP(e){return t;function t(t,n,r){return qP.call(e,t.tagName)&&e[t.tagName](t,n,r)}}var YP=JP({body:QP,caption:XP,colgroup:XP,dd:nF,dt:tF,head:XP,html:ZP,li:eF,optgroup:iF,option:aF,p:$P,rp:rF,rt:rF,tbody:sF,td:uF,tfoot:cF,th:uF,thead:oF,tr:lF});function XP(e,t,n){let r=G(n,t,!0);return!r||r.type!==`comment`&&!(r.type===`text`&&HP(r.value.charAt(0)))}function ZP(e,t,n){let r=G(n,t);return!r||r.type!==`comment`}function QP(e,t,n){let r=G(n,t);return!r||r.type!==`comment`}function $P(e,t,n){let r=G(n,t);return r?r.type===`element`&&(r.tagName===`address`||r.tagName===`article`||r.tagName===`aside`||r.tagName===`blockquote`||r.tagName===`details`||r.tagName===`div`||r.tagName===`dl`||r.tagName===`fieldset`||r.tagName===`figcaption`||r.tagName===`figure`||r.tagName===`footer`||r.tagName===`form`||r.tagName===`h1`||r.tagName===`h2`||r.tagName===`h3`||r.tagName===`h4`||r.tagName===`h5`||r.tagName===`h6`||r.tagName===`header`||r.tagName===`hgroup`||r.tagName===`hr`||r.tagName===`main`||r.tagName===`menu`||r.tagName===`nav`||r.tagName===`ol`||r.tagName===`p`||r.tagName===`pre`||r.tagName===`section`||r.tagName===`table`||r.tagName===`ul`):!n||n.type!==`element`||n.tagName!==`a`&&n.tagName!==`audio`&&n.tagName!==`del`&&n.tagName!==`ins`&&n.tagName!==`map`&&n.tagName!==`noscript`&&n.tagName!==`video`}function eF(e,t,n){let r=G(n,t);return!r||r.type===`element`&&r.tagName===`li`}function tF(e,t,n){let r=G(n,t);return!!(r&&r.type===`element`&&(r.tagName===`dt`||r.tagName===`dd`))}function nF(e,t,n){let r=G(n,t);return!r||r.type===`element`&&(r.tagName===`dt`||r.tagName===`dd`)}function rF(e,t,n){let r=G(n,t);return!r||r.type===`element`&&(r.tagName===`rp`||r.tagName===`rt`)}function iF(e,t,n){let r=G(n,t);return!r||r.type===`element`&&r.tagName===`optgroup`}function aF(e,t,n){let r=G(n,t);return!r||r.type===`element`&&(r.tagName===`option`||r.tagName===`optgroup`)}function oF(e,t,n){let r=G(n,t);return!!(r&&r.type===`element`&&(r.tagName===`tbody`||r.tagName===`tfoot`))}function sF(e,t,n){let r=G(n,t);return!r||r.type===`element`&&(r.tagName===`tbody`||r.tagName===`tfoot`)}function cF(e,t,n){return!G(n,t)}function lF(e,t,n){let r=G(n,t);return!r||r.type===`element`&&r.tagName===`tr`}function uF(e,t,n){let r=G(n,t);return!r||r.type===`element`&&(r.tagName===`td`||r.tagName===`th`)}var dF=JP({body:mF,colgroup:hF,head:pF,html:fF,tbody:gF});function fF(e){let t=G(e,-1);return!t||t.type!==`comment`}function pF(e){let t=new Set;for(let n of e.children)if(n.type===`element`&&(n.tagName===`base`||n.tagName===`title`)){if(t.has(n.tagName))return!1;t.add(n.tagName)}let n=e.children[0];return!n||n.type===`element`}function mF(e){let t=G(e,-1,!0);return!t||t.type!==`comment`&&!(t.type===`text`&&HP(t.value.charAt(0)))&&(t.type!==`element`||t.tagName!==`meta`&&t.tagName!==`link`&&t.tagName!==`script`&&t.tagName!==`style`&&t.tagName!==`template`)}function hF(e,t,n){let r=WP(n,t),i=G(e,-1,!0);return n&&r&&r.type===`element`&&r.tagName===`colgroup`&&YP(r,n.children.indexOf(r),n)?!1:!!(i&&i.type===`element`&&i.tagName===`col`)}function gF(e,t,n){let r=WP(n,t),i=G(e,-1);return n&&r&&r.type===`element`&&(r.tagName===`thead`||r.tagName===`tbody`)&&YP(r,n.children.indexOf(r),n)?!1:!!(i&&i.type===`element`&&i.tagName===`tr`)}var _F={name:[[`
|
|
34
34
|
\f\r &/=>`.split(``),`
|
|
35
35
|
\f\r "&'/=>\``.split(``)],[`\0
|
|
36
36
|
\f\r "&'/<=>`.split(``),`\0
|
|
@@ -38,12 +38,12 @@ import{n as e,r as t,t as n}from"./rolldown-runtime-hePW80VL.js";import{$ as r,$
|
|
|
38
38
|
\f\r &>`.split(``),`\0
|
|
39
39
|
\f\r "&'<=>\``.split(``)],[`\0
|
|
40
40
|
\f\r "&'<=>\``.split(``),`\0
|
|
41
|
-
\f\r "&'<=>\``.split(``)]],single:[[`&'`.split(``),`"&'\``.split(``)],[`\0&'`.split(``),`\0"&'\``.split(``)]],double:[[`"&`.split(``),`"&'\``.split(``)],[`\0"&`.split(``),`\0"&'\``.split(``)]]};function _F(e,t,n,r){let i=r.schema,a=i.space!==`svg`&&r.settings.omitOptionalTags,o=i.space===`svg`?r.settings.closeEmptyElements:r.settings.voids.includes(e.tagName.toLowerCase()),s=[],c;i.space===`html`&&e.tagName===`svg`&&(r.schema=aP);let l=vF(r,e.properties),u=r.all(i.space===`html`&&e.tagName===`template`?e.content:e);return r.schema=i,u&&(o=!1),(l||!a||!uF(e,t,n))&&(s.push(`<`,e.tagName,l?` `+l:``),o&&(i.space===`svg`||r.settings.closeSelfClosing)&&(c=l.charAt(l.length-1),(!r.settings.tightSelfClosing||c===`/`||c&&c!==`"`&&c!==`'`)&&s.push(` `),s.push(`/`)),s.push(`>`)),s.push(u),!o&&(!a||!JP(e,t,n))&&s.push(`</`+e.tagName+`>`),s.join(``)}function vF(e,t){let n=[],r=-1,i;if(t){for(i in t)if(t[i]!==null&&t[i]!==void 0){let r=yF(e,i,t[i]);r&&n.push(r)}}for(;++r<n.length;){let t=e.settings.tightAttributes?n[r].charAt(n[r].length-1):void 0;r!==n.length-1&&t!==`"`&&t!==`'`&&(n[r]+=` `)}return n.join(``)}function yF(e,t,n){let r=tP(e.schema,t),i=e.settings.allowParseErrors&&e.schema.space===`html`?0:1,a=+!e.settings.allowDangerousCharacters,o=e.quote,s;if(r.overloadedBoolean&&(n===r.attribute||n===``)?n=!0:(r.boolean||r.overloadedBoolean)&&(typeof n!=`string`||n===r.attribute||n===``)&&(n=!!n),n==null||n===!1||typeof n==`number`&&Number.isNaN(n))return``;let c=kP(r.attribute,Object.assign({},e.settings.characterReferences,{subset:gF.name[i][a]}));return n===!0||(n=Array.isArray(n)?(r.commaSeparated?LP:zP)(n,{padLeft:!e.settings.tightCommaSeparatedLists}):String(n),e.settings.collapseEmptyAttributes&&!n)?c:(e.settings.preferUnquoted&&(s=kP(n,Object.assign({},e.settings.characterReferences,{attribute:!0,subset:gF.unquoted[i][a]}))),s!==n&&(e.settings.quoteSmart&&FP(n,o)>FP(n,e.alternative)&&(o=e.alternative),s=o+kP(n,Object.assign({},e.settings.characterReferences,{subset:(o===`'`?gF.single:gF.double)[i][a],attribute:!0}))+o),c+(s&&`=`+s))}var bF=[`<`,`&`];function xF(e,t,n,r){return n&&n.type===`element`&&(n.tagName===`script`||n.tagName===`style`)?e.value:kP(e.value,Object.assign({},r.settings.characterReferences,{subset:bF}))}function SF(e,t,n,r){return r.settings.allowDangerousHtml?e.value:xF(e,t,n,r)}function CF(e,t,n,r){return r.all(e)}var wF=sP(`type`,{invalid:TF,unknown:EF,handlers:{comment:NP,doctype:PP,element:_F,raw:SF,root:CF,text:xF}});function TF(e){throw Error("Expected node, not `"+e+"`")}function EF(e){throw Error("Cannot compile unknown node `"+e.type+"`")}var DF={},OF={},kF=[];function AF(e,t){let n=t||DF,r=n.quote||`"`,i=r===`"`?`'`:`"`;if(r!==`"`&&r!==`'`)throw Error("Invalid quote `"+r+"`, expected `'` or `\"`");return{one:jF,all:MF,settings:{omitOptionalTags:n.omitOptionalTags||!1,allowParseErrors:n.allowParseErrors||!1,allowDangerousCharacters:n.allowDangerousCharacters||!1,quoteSmart:n.quoteSmart||!1,preferUnquoted:n.preferUnquoted||!1,tightAttributes:n.tightAttributes||!1,upperDoctype:n.upperDoctype||!1,tightDoctype:n.tightDoctype||!1,bogusComments:n.bogusComments||!1,tightCommaSeparatedLists:n.tightCommaSeparatedLists||!1,tightSelfClosing:n.tightSelfClosing||!1,collapseEmptyAttributes:n.collapseEmptyAttributes||!1,allowDangerousHtml:n.allowDangerousHtml||!1,voids:n.voids||kN,characterReferences:n.characterReferences||OF,closeSelfClosing:n.closeSelfClosing||!1,closeEmptyElements:n.closeEmptyElements||!1},schema:n.space===`svg`?aP:iP,quote:r,alternative:i}.one(Array.isArray(e)?{type:`root`,children:e}:e,void 0,void 0)}function jF(e,t,n){return wF(e,t,n,this)}function MF(e){let t=[],n=e&&e.children||kF,r=-1;for(;++r<n.length;)t[r]=this.one(n[r],r,e);return t.join(``)}var NF=class{mode;options;hoveredLine;hoveredToken;pre;gutterUtilityLine;gutterUtilityContainer;gutterUtilityButton;gutterUtilitySlot;interactiveLinesAttr=!1;interactiveLineNumbersAttr=!1;hasPointerListeners=!1;hasDocumentPointerListeners=!1;selectedRange=null;selectedRangeHighlightSide;selectedRangeLineNumberOnly=!1;editorActiveLine=null;editorActiveLineSide;editorLineNumberOnly=!1;proposedSelectedRange;renderedSelectedLinesState;renderedEditorActiveLineState;selectionAnchor;pointerSession={mode:`idle`};constructor(e,t){this.mode=e,this.options=t}setOptions(e){this.options=e}cleanUp(){this.pre?.removeEventListener(`click`,this.handlePointerClick),this.pre?.removeEventListener(`pointerdown`,this.handlePointerDown),this.pre?.removeEventListener(`pointermove`,this.handlePointerMove),this.pre?.removeEventListener(`pointerleave`,this.handlePointerLeave),this.pre?.removeAttribute(`data-interactive-lines`),this.pre?.removeAttribute(`data-interactive-line-numbers`),this.pre=void 0,this.gutterUtilityContainer?.remove(),this.gutterUtilityLine=void 0,this.gutterUtilityContainer=void 0,this.gutterUtilityButton=void 0,this.gutterUtilitySlot=void 0,this.clearHoveredLine(),this.clearHoveredToken(),this.detachDocumentPointerListeners(),this.clearPointerSession(),AM(this.renderSelection),this.interactiveLinesAttr=!1,this.interactiveLineNumbersAttr=!1,this.hasPointerListeners=!1,this.setSelectionDirty()}setup(e){this.setSelectionDirty();let{usesCustomGutterUtility:t=!1,enableGutterUtility:n=!1}=this.options;this.pre!==e&&(this.cleanUp(),this.pre=e),n?this.ensureGutterUtilityNode(t):this.gutterUtilityContainer!=null&&(this.gutterUtilityContainer.remove(),this.gutterUtilityLine=void 0,this.gutterUtilityContainer=void 0,this.gutterUtilityButton=void 0,this.gutterUtilitySlot=void 0,this.pointerSession.mode===`gutterSelecting`&&(this.clearPointerSession(),this.detachDocumentPointerListeners())),this.syncPointerListeners(e),this.updateInteractiveLineAttributes(),this.renderSelection(),this.placeUtility()}setSelectionDirty(){this.renderedSelectedLinesState=void 0,this.renderedEditorActiveLineState=void 0}isSelectionDirty(){return this.renderedSelectedLinesState===void 0||this.renderedEditorActiveLineState===void 0}setSelection(e,t){let n=!(e===this.selectedRange||IM(e??void 0,this.selectedRange??void 0)),r=t?.lineNumberOnly??!1,i=t?.activeLineSide!==this.selectedRangeHighlightSide||r!==this.selectedRangeLineNumberOnly;!this.isSelectionDirty()&&!n&&!i||(this.proposedSelectedRange=void 0,this.selectedRange=e,this.selectedRangeHighlightSide=t?.activeLineSide,this.selectedRangeLineNumberOnly=r,this.renderSelection(),this.placeUtility(),n&&t?.notify!==!1&&this.notifySelectionCommitted(e))}setEditorActiveLine(e,{lineNumberOnly:t=!1,side:n}={}){let r=e!==this.editorActiveLine,i=n!==this.editorActiveLineSide||t!==this.editorLineNumberOnly;!this.isSelectionDirty()&&!r&&!i||(this.editorActiveLine=e,this.editorActiveLineSide=n,this.editorLineNumberOnly=t,this.renderSelection())}getSelection(){return this.selectedRange}getHoveredLine=()=>{let e=this.gutterUtilityLine??this.hoveredLine;if(e!=null){if(this.mode===`diff`&&e.type===`diff-line`)return{lineNumber:e.lineNumber,side:e.annotationSide};if(this.mode===`file`&&e.type===`line`)return{lineNumber:e.lineNumber}}};handlePointerClick=e=>{let{onHunkExpand:t,onLineClick:n,onLineNumberClick:r,onTokenClick:i,onMergeConflictActionClick:a}=this.options;(t!=null||n!=null||r!=null||a!=null||i!=null)&&(this.options.onGutterUtilityClick!=null&&ON(e.composedPath())||(QF(this.options.__debugPointerEvents,`click`,`FileDiff.DEBUG.handlePointerClick:`,e),this.handlePointerEvent({eventType:`click`,event:e})))};handlePointerMove=e=>{if(e.pointerType!==`mouse`)return;let{lineHoverHighlight:t=`disabled`,onLineEnter:n,onLineLeave:r,onTokenEnter:i,onTokenLeave:a,enableGutterUtility:o=!1}=this.options;t===`disabled`&&!o&&n==null&&r==null&&i==null&&a==null||(QF(this.options.__debugPointerEvents,`move`,`FileDiff.DEBUG.handlePointerMove:`,e),this.handlePointerEvent({eventType:`move`,event:e}))};handlePointerLeave=e=>{let{__debugPointerEvents:t}=this.options;if(QF(t,`move`,`FileDiff.DEBUG.handlePointerLeave: no event`),this.hoveredLine==null&&this.hoveredToken==null){QF(t,`move`,`FileDiff.DEBUG.handlePointerLeave: returned early, no hovered line or token`);return}this.hoveredToken!=null&&(this.options.onTokenLeave?.(this.hoveredToken,e),this.clearHoveredToken()),this.hoveredLine!=null&&(this.options.onLineLeave?.({...this.hoveredLine,event:e}),this.clearHoveredLine()),this.placeUtility()};handlePointerEvent({eventType:e,event:t}){let{__debugPointerEvents:n}=this.options,r=t.composedPath();QF(n,e,`FileDiff.DEBUG.handlePointerEvent:`,{eventType:e,composedPath:r});let i=this.resolvePointerTarget(r);QF(n,e,`FileDiff.DEBUG.handlePointerEvent: resolvePointerTarget result:`,i);let{onLineClick:a,onLineNumberClick:o,onLineEnter:s,onLineLeave:c,onTokenClick:l,onTokenEnter:u,onTokenLeave:d,onHunkExpand:f,onMergeConflictActionClick:p}=this.options;switch(e){case`move`:{let e=RF(i)&&this.hoveredLine?.lineElement===i.lineElement;LF(i)&&this.hoveredToken?.tokenElement===i.tokenElement||(this.hoveredToken!=null&&(d?.(this.hoveredToken,t),this.clearHoveredToken()),LF(i)&&(this.setHoveredToken(this.toTokenEventBaseProps(i)),u?.(this.hoveredToken,t))),e||(this.hoveredLine!=null&&(c?.({...this.hoveredLine,event:t}),this.clearHoveredLine()),RF(i)?(this.setHoveredLine(this.toEventBaseProps(i)),this.placeUtility(),s?.({...this.hoveredLine,event:t})):this.placeUtility());break}case`click`:{if(i==null)break;if(BF(i)&&p!=null){p(i);break}if(zF(i)&&f!=null){f(i.hunkIndex,i.all||t.shiftKey?`both`:i.direction,i.all||t.shiftKey?1/0:void 0);break}if(!RF(i))break;LF(i)&&l!=null&&l(this.toTokenEventBaseProps(i),t);let e=this.toEventBaseProps(i);o!=null&&i.numberColumn?o({...e,event:t}):a?.({...e,event:t});break}}}syncPointerListeners(e){let{__debugPointerEvents:t,lineHoverHighlight:n=`disabled`,onLineClick:r,onLineNumberClick:i,onLineEnter:a,onLineLeave:o,onTokenClick:s,onTokenEnter:c,onTokenLeave:l,onHunkExpand:u,onMergeConflictActionClick:d,enableGutterUtility:f=!1,enableLineSelection:p=!1,onGutterUtilityClick:m}=this.options,h=m!=null,g=n!==`disabled`||r!=null||i!=null||a!=null||o!=null||s!=null||c!=null||l!=null||u!=null||d!=null||f||p||h;g&&!this.hasPointerListeners?(e.addEventListener(`click`,this.handlePointerClick),e.addEventListener(`pointerdown`,this.handlePointerDown),e.addEventListener(`pointermove`,this.handlePointerMove),e.addEventListener(`pointerleave`,this.handlePointerLeave),this.hasPointerListeners=!0,QF(t,`click`,`FileDiff.DEBUG.attachEventListeners: Attaching click events for:`,(()=>{let e=[];return(t===`both`||t===`click`)&&(r!=null&&e.push(`onLineClick`),i!=null&&e.push(`onLineNumberClick`),u!=null&&e.push(`expandable hunk separators`),d!=null&&e.push(`merge conflict actions`)),e})()),QF(t,`move`,`FileDiff.DEBUG.attachEventListeners: Attaching pointer move event`),QF(t,`move`,`FileDiff.DEBUG.attachEventListeners: Attaching pointer leave event`)):!g&&this.hasPointerListeners&&(e.removeEventListener(`click`,this.handlePointerClick),e.removeEventListener(`pointerdown`,this.handlePointerDown),e.removeEventListener(`pointermove`,this.handlePointerMove),e.removeEventListener(`pointerleave`,this.handlePointerLeave),this.hasPointerListeners=!1);let _=this.pointerSession.mode===`selecting`||this.pointerSession.mode===`pendingSingleLineUnselect`,v=this.pointerSession.mode===`gutterSelecting`;(!p&&_||!h&&v)&&(this.clearPointerSession(),this.detachDocumentPointerListeners(),this.selectionAnchor=void 0,this.clearPendingSingleLineState())}updateInteractiveLineAttributes(){if(this.pre==null)return;let{onLineClick:e,onLineNumberClick:t,enableLineSelection:n=!1}=this.options,r=e!=null,i=t!=null||n;r&&!this.interactiveLinesAttr?(this.pre.setAttribute(`data-interactive-lines`,``),this.interactiveLinesAttr=!0):!r&&this.interactiveLinesAttr&&(this.pre.removeAttribute(`data-interactive-lines`),this.interactiveLinesAttr=!1),i&&!this.interactiveLineNumbersAttr?(this.pre.setAttribute(`data-interactive-line-numbers`,``),this.interactiveLineNumbersAttr=!0):!i&&this.interactiveLineNumbersAttr&&(this.pre.removeAttribute(`data-interactive-line-numbers`),this.interactiveLineNumbersAttr=!1)}handlePointerDown=e=>{if(e.pointerType===`mouse`&&e.button!==0||this.pre==null||this.pointerSession.mode!==`idle`)return;let t=e.composedPath();ON(t)&&this.options.onGutterUtilityClick!=null?this.startGutterSelectionFromPointerDown(e):(e.pointerType!==`mouse`&&this.revealUtilityFromGutterPath(t),this.startLineSelectionFromPointerDown(e))};startLineSelectionFromPointerDown(e){let{enableLineSelection:t=!1}=this.options;if(!t)return;let n=this.resolveSelectionInfo(e,{source:`event-path`,requireNumberColumn:!0});if(n==null)return;let{pre:r}=this;if(r==null)return;let{lineNumber:i,eventSide:a,lineIndex:o}=n;if(e.shiftKey&&this.selectedRange!=null){let t=this.getIndexesFromSelection(this.selectedRange,r.getAttribute(`data-diff-type`)===`split`);if(t==null)return;let n=t.start<=t.end?o>=t.start:o<=t.end;this.selectionAnchor={lineNumber:n?this.selectedRange.start:this.selectedRange.end,side:n?this.selectedRange.side:this.selectedRange.endSide??this.selectedRange.side},this.updateSelection(i,a,!1),this.notifySelectionStart(this.getCurrentSelectionRange()),this.pointerSession={mode:`selecting`,pointerId:e.pointerId},this.attachDocumentPointerListeners();return}if(this.selectedRange?.start===i&&this.selectedRange?.end===i){let t={lineNumber:i,side:a};this.selectionAnchor=t,this.pointerSession={mode:`pendingSingleLineUnselect`,pointerId:e.pointerId,anchor:t,pending:t},this.attachDocumentPointerListeners();return}this.options.controlledSelection===!0?this.proposedSelectedRange=null:this.selectedRange=null,this.placeUtility(),this.selectionAnchor={lineNumber:i,side:a},this.updateSelection(i,a,!1),this.notifySelectionStart(this.getCurrentSelectionRange()),this.pointerSession={mode:`selecting`,pointerId:e.pointerId},this.attachDocumentPointerListeners()}startGutterSelectionFromPointerDown(e){let{onGutterUtilityClick:t}=this.options;if(t==null)return;let n=this.currentSelectionEnds(),r=n?.bottom??this.resolveSelectionPoint(e,{source:`event-path`,excludeUtility:!1}),i=n?.top??r;r!=null&&i!=null&&(e.preventDefault(),e.stopPropagation(),this.pointerSession={mode:`gutterSelecting`,pointerId:e.pointerId,anchor:i,current:r},this.selectionAnchor={lineNumber:i.lineNumber,side:i.side},this.updateSelection(r.lineNumber,r.side,!1),this.notifySelectionStart(this.getCurrentSelectionRange()),this.attachDocumentPointerListeners())}handleDocumentPointerMove=e=>{switch(this.pointerSession.mode){case`idle`:return;case`gutterSelecting`:{if(e.pointerId!==this.pointerSession.pointerId)return;e.preventDefault();let t=this.resolveSelectionPoint(e,{source:`coordinates-first`});if(t==null)return;this.pointerSession.current=t,this.updateSelection(t.lineNumber,t.side);return}case`selecting`:{if(e.pointerId!==this.pointerSession.pointerId)return;e.preventDefault();let t=this.resolveSelectionInfo(e,{source:`coordinates-first`,requireNumberColumn:!1});if(t==null||this.selectionAnchor==null)return;this.updateSelection(t.lineNumber,t.eventSide);return}case`pendingSingleLineUnselect`:{if(e.pointerId!==this.pointerSession.pointerId)return;e.preventDefault();let t=this.resolveSelectionInfo(e,{source:`coordinates-first`,requireNumberColumn:!1});if(t==null||this.selectionAnchor==null)return;let n={lineNumber:t.lineNumber,side:t.eventSide};if(DN(this.pointerSession.pending,n))return;this.updateSelection(t.lineNumber,t.eventSide,!1),this.notifySelectionStart(this.getCurrentSelectionRange()),this.notifySelectionChangeDelta(),this.pointerSession={mode:`selecting`,pointerId:e.pointerId};return}}};handleDocumentPointerUp=e=>{let{onGutterUtilityClick:t}=this.options;switch(this.pointerSession.mode){case`idle`:return;case`gutterSelecting`:{let{pointerSession:n}=this;if(e.pointerId!==n.pointerId)return;e.preventDefault();let r=this.resolveSelectionPoint(e,{source:`coordinates-first`});r!=null&&(n.current=r,this.updateSelection(r.lineNumber,r.side));let i=this.buildSelectedLineRange(n.anchor,n.current);t?.({...i}),this.selectionAnchor=void 0,this.notifySelectionEnd(i),this.notifySelectionCommitted(i),this.clearProposedSelection(),this.clearPointerSession(),this.detachDocumentPointerListeners();return}case`pendingSingleLineUnselect`:if(e.pointerId!==this.pointerSession.pointerId)return;e.preventDefault(),this.updateSelection(null,void 0,!1),this.selectionAnchor=void 0,this.clearPendingSingleLineState(),this.detachDocumentPointerListeners(),this.notifySelectionEnd(this.getCurrentSelectionRange()),this.notifySelectionCommitted(this.getCurrentSelectionRange()),this.clearProposedSelection();return;case`selecting`:if(e.pointerId!==this.pointerSession.pointerId)return;e.preventDefault(),this.selectionAnchor=void 0,this.detachDocumentPointerListeners(),this.clearPointerSession(),this.notifySelectionEnd(this.getCurrentSelectionRange()),this.notifySelectionCommitted(this.getCurrentSelectionRange()),this.clearProposedSelection()}};handleDocumentPointerCancel=e=>{switch(this.pointerSession.mode){case`idle`:return;case`gutterSelecting`:case`selecting`:case`pendingSingleLineUnselect`:if(`pointerId`in this.pointerSession&&e.pointerId!==this.pointerSession.pointerId)return;this.selectionAnchor=void 0,this.clearProposedSelection(),this.clearPendingSingleLineState(),this.clearPointerSession(),this.detachDocumentPointerListeners()}};clearHoveredLine(){this.hoveredLine!=null&&(this.hoveredLine.lineElement.removeAttribute(`data-hovered`),this.hoveredLine.numberElement.removeAttribute(`data-hovered`),this.hoveredLine=void 0)}setHoveredLine(e){let{lineHoverHighlight:t=`disabled`}=this.options;this.hoveredLine!=null&&this.clearHoveredLine(),this.hoveredLine=e,t!==`disabled`&&((t===`both`||t===`line`)&&this.hoveredLine.lineElement.setAttribute(`data-hovered`,``),(t===`both`||t===`number`)&&this.hoveredLine.numberElement.setAttribute(`data-hovered`,``))}clearHoveredToken(){this.hoveredToken!=null&&(this.hoveredToken=void 0)}setHoveredToken(e){this.hoveredToken!=null&&this.clearHoveredToken(),this.hoveredToken=e}ensureGutterUtilityNode(e){if(this.gutterUtilityContainer??(this.gutterUtilityContainer=document.createElement(`div`),this.gutterUtilityContainer.setAttribute(`data-gutter-utility-slot`,``)),e)this.gutterUtilityButton!=null&&(this.gutterUtilityButton.remove(),this.gutterUtilityButton=void 0),this.gutterUtilitySlot??(this.gutterUtilitySlot=document.createElement(`slot`),this.gutterUtilitySlot.name=`gutter-utility-slot`),this.gutterUtilitySlot.parentNode!==this.gutterUtilityContainer&&this.gutterUtilityContainer.replaceChildren(this.gutterUtilitySlot);else{if(this.gutterUtilitySlot?.remove(),this.gutterUtilitySlot=void 0,this.gutterUtilityButton==null){let e=document.createElement(`div`);e.innerHTML=AF(EN());let t=e.firstElementChild;if(!(t instanceof HTMLButtonElement))throw Error(`InteractionManager.ensureGutterUtilityNode: Node element should be a button`);t.remove(),this.gutterUtilityButton=t}this.gutterUtilityButton.parentNode!==this.gutterUtilityContainer&&this.gutterUtilityContainer.replaceChildren(this.gutterUtilityButton)}}revealUtilityFromGutterPath(e){if(this.placeUtilityFromSelection())return;let t=this.resolvePointerTarget(e);IF(t)&&t.numberColumn&&this.showUtilityOnLine(this.toEventBaseProps(t))}placeUtility(){if(!this.placeUtilityFromSelection()){if(this.hoveredLine!=null){this.showUtilityOnLine(this.hoveredLine);return}this.hideUtility()}}placeUtilityFromSelection(){let e=this.currentSelectionEnds();if(e==null)return!1;let t=this.targetForSelectionPoint(e.bottom);return t==null?this.hideUtility():this.showUtilityOnLine(this.toEventBaseProps(t)),!0}showUtilityOnLine(e){this.gutterUtilityContainer!=null&&(this.gutterUtilityLine=e,e.numberElement.appendChild(this.gutterUtilityContainer))}hideUtility(){this.gutterUtilityContainer?.remove(),this.gutterUtilityLine=void 0}currentSelectionEnds(){let e=this.getCurrentSelectionRange();return e==null?void 0:this.selectionEnds(e)}selectionEnds(e){let t={lineNumber:e.start,side:e.side},n={lineNumber:e.end,side:e.endSide??e.side},r=this.selectionPointRowIndex(t),i=this.selectionPointRowIndex(n);if(r!=null&&i!=null)return r>i?{top:n,bottom:t}:{top:t,bottom:n}}selectionPointRowIndex(e){let t=this.getLineIndex(e.lineNumber,e.side);if(t!=null)return this.isSplitDiff()?t[1]:t[0]}targetForSelectionPoint(e){if(this.pre==null)return;let t=this.getLineIndex(e.lineNumber,e.side);if(t==null)return;let n=this.mode===`diff`?`${t[0]},${t[1]}`:`${t[0]}`,r=this.pre.querySelectorAll(`[data-column-number="${e.lineNumber}"][data-line-index="${n}"]`);for(let t of r){if(!(t instanceof HTMLElement))continue;let n=this.resolvePointerTarget(UF(t));if(IF(n)&&(this.mode!==`diff`||e.side==null||n.side===e.side))return n}}attachDocumentPointerListeners(){this.hasDocumentPointerListeners||=(document.addEventListener(`pointermove`,this.handleDocumentPointerMove),document.addEventListener(`pointerup`,this.handleDocumentPointerUp),document.addEventListener(`pointercancel`,this.handleDocumentPointerCancel),!0)}detachDocumentPointerListeners(){this.hasDocumentPointerListeners&&=(document.removeEventListener(`pointermove`,this.handleDocumentPointerMove),document.removeEventListener(`pointerup`,this.handleDocumentPointerUp),document.removeEventListener(`pointercancel`,this.handleDocumentPointerCancel),!1)}clearPointerSession(){this.pointerSession={mode:`idle`}}clearPendingSingleLineState(){this.pointerSession.mode===`pendingSingleLineUnselect`&&(this.pointerSession={mode:`idle`})}selectionInfoFromPath(e,t){let n=this.resolvePointerTarget(e);if(IF(n)&&!(t&&!n.numberColumn)&&n.splitLineIndex!=null)return{lineIndex:n.splitLineIndex,lineNumber:n.lineNumber,eventSide:this.mode===`diff`?n.side:void 0}}resolveSelectionInfo(e,t){let n=this.resolveSelectionPath(e,t);return n==null?void 0:this.selectionInfoFromPath(n,t.requireNumberColumn)}selectionPointFromPath(e){let t=this.resolvePointerTarget(e);if(IF(t))return{lineNumber:t.lineNumber,side:this.mode===`diff`?t.side:void 0}}resolveSelectionPoint(e,t){let n=this.resolveSelectionPath(e,t);return n==null?void 0:this.selectionPointFromPath(n)}resolveSelectionPath(e,t){let n=t.excludeUtility!==!1;switch(t.source){case`event-path`:return this.pathFromEventPath(e.composedPath(),n);case`coordinates-first`:{let t=this.pathFromCoordinates(e,n);return t===void 0?this.pathFromEventPath(e.composedPath(),n):t??void 0}}}pathFromCoordinates(e,t){let n=this.hitTest(e);if(n!==void 0)return n===null?null:this.pathFromElement(n,t)??null}pathFromEventPath(e,t){if(!(t&&ON(e))){for(let n of e)if(n instanceof Element)return this.pathFromElement(n,t)}}pathFromElement(e,t){let n=UF(e);if(t&&ON(n))return;let r=WF(e);return r==null?this.pathFromAnnotationSlot(e):UF(r)}pathFromAnnotationSlot(e){let t=KF(GF(e));if(t==null)return;let n=this.targetForSelectionPoint(t);return n==null?void 0:UF(n.lineElement)}hitTest(e){if(!Number.isFinite(e.clientX)||!Number.isFinite(e.clientY))return;let t=this.pre?.getRootNode(),n=qF(t)?t:qF(document)?document:void 0;if(n!=null)return n.elementFromPoint(e.clientX,e.clientY)}getLineIndex(e,t){let{getLineIndex:n}=this.options;return n==null?[e-1,e-1]:n(e,t)}getCurrentSelectionRange(){return this.proposedSelectedRange===void 0?this.selectedRange:this.proposedSelectedRange}clearProposedSelection(){this.proposedSelectedRange=void 0}updateSelection(e,t,n=!0){let r=this.getCurrentSelectionRange(),i;if(e==null)i=null;else{let n=this.selectionAnchor?.side??t,r=this.selectionAnchor?.lineNumber??e;i=this.buildSelectionRange(r,e,n,t)}IM(r??void 0,i??void 0)||(this.selectedRangeHighlightSide=void 0,this.selectedRangeLineNumberOnly=!1,this.options.controlledSelection===!0?this.proposedSelectedRange=i:(this.selectedRange=i,kM(this.renderSelection)),this.placeUtility(),n&&this.notifySelectionChangeDelta())}getIndexesFromSelection(e,t){if(this.pre==null)return;let n=this.getLineIndex(e.start,e.side),r=this.getLineIndex(e.end,e.endSide??e.side);return n!=null&&r!=null?{start:t?n[1]:n[0],end:t?r[1]:r[0]}:void 0}getSelectionRenderState(){return{selectedLines:{range:this.selectedRange,highlightSide:this.selectedRangeHighlightSide,lineNumberOnly:this.selectedRangeLineNumberOnly},editorActiveLine:{range:this.editorActiveLine==null?null:{start:this.editorActiveLine,end:this.editorActiveLine,side:this.editorActiveLineSide},highlightSide:this.editorActiveLineSide,lineNumberOnly:this.editorLineNumberOnly}}}resolveLineRenderRange(e,t,n){if(e.range==null)return;let r=this.getIndexesFromSelection(e.range,t);if(r==null)throw console.error({rowRange:r,range:e.range}),Error(`InteractionManager.renderSelection: No valid ${n} rowRange`);return r}getLineRenderColumns(e,t,n,r){if(this.pre==null||t==null&&r==null)return[];let{children:i}=this.pre;if(i.length>2)throw console.error(i),Error(`InteractionManager.renderSelection: Somehow there are more than 2 code elements...`);let a=[];for(let o of i){let i=o.hasAttribute(`data-deletions`)?`deletions`:o.hasAttribute(`data-additions`)?`additions`:void 0,s=e!=null&&t!=null&&(e.highlightSide==null||i==null||e.highlightSide===i),c=n!=null&&r!=null&&(n.highlightSide==null||i==null||n.highlightSide===i);if(!s&&!c)continue;let[l,u]=o.children;if(!(l instanceof HTMLElement)||!(u instanceof HTMLElement))throw Error(`InteractionManager.renderSelection: missing gutter or content element`);if(u.children.length!==l.children.length)throw Error(`InteractionManager.renderSelection: gutter and content children dont match, something is wrong`);a.push({content:u,gutter:l,renderEditorActiveLine:c,renderSelectedLines:s})}return a}renderSelection=()=>{AM(this.renderSelection);let e=this.getSelectionRenderState();if(this.pre==null)return;let{editorActiveLine:t,selectedLines:n}=e,r=!YF(this.renderedSelectedLinesState,n),i=!YF(this.renderedEditorActiveLineState,t);if(!r&&!i)return;r&&(this.renderedSelectedLinesState=void 0),i&&(this.renderedEditorActiveLineState=void 0);let a=this.pre.getAttribute(`data-diff-type`)===`split`,o=r?this.resolveLineRenderRange(n,a,`selected-lines`):void 0,s=i?this.resolveLineRenderRange(t,a,`editor-active-line`):void 0,c=this.getLineRenderColumns(r?n:void 0,o,i?t:void 0,s),l=n.range==null||c.some(e=>e.renderSelectedLines),u=t.range==null||c.some(e=>e.renderEditorActiveLine);if(r)for(let e of this.pre.querySelectorAll(`[data-selected-line]`))e.removeAttribute(`data-selected-line`);if(i)for(let e of this.pre.querySelectorAll(`[data-editor-active-line]`))e.removeAttribute(`data-editor-active-line`);let d=o==null?void 0:Math.min(o.start,o.end),f=o==null?void 0:Math.max(o.start,o.end),p=d===f,m=s?.start;for(let e of c){let{content:r,gutter:i,renderEditorActiveLine:o,renderSelectedLines:s}=e,c=Math.max(s?f??-1/0:-1/0,o?m??-1/0:-1/0),l=r.children.length;for(let e=0;e<l;e++){let l=r.children[e],u=i.children[e];if(!(l instanceof HTMLElement)||!(u instanceof HTMLElement))continue;let h=this.parseLineIndex(l,a);if((h??0)>c)break;if(h!=null){if(s&&d!=null&&f!=null&&h>=d&&h<=f){let e=p?`single`:h===d?`first`:h===f?`last`:``;u.setAttribute(`data-selected-line`,e),n.lineNumberOnly||(l.setAttribute(`data-selected-line`,e),u.nextSibling instanceof HTMLElement&&l.nextSibling instanceof HTMLElement&&(l.nextSibling.hasAttribute(`data-line-annotation`)||l.nextSibling.hasAttribute(`data-merge-conflict-actions`))&&(p?(e=`last`,l.setAttribute(`data-selected-line`,`first`)):h===d?e=``:h===f&&l.setAttribute(`data-selected-line`,``),l.nextSibling.setAttribute(`data-selected-line`,e),u.nextSibling.setAttribute(`data-selected-line`,e)))}o&&h===m&&(u.setAttribute(`data-editor-active-line`,``),t.lineNumberOnly||l.setAttribute(`data-editor-active-line`,``))}}}r&&l&&(this.renderedSelectedLinesState=n),i&&u&&(this.renderedEditorActiveLineState=t)};notifySelectionCommitted(e){this.options.onLineSelected?.(e)}notifySelectionChangeDelta(){this.options.onLineSelectionChange?.(this.getCurrentSelectionRange()??null)}notifySelectionStart(e){this.options.onLineSelectionStart?.(e)}notifySelectionEnd(e){this.options.onLineSelectionEnd?.(e)}toEventBaseProps(e){return this.mode===`file`?{type:`line`,lineElement:e.lineElement,lineNumber:e.lineNumber,numberColumn:e.numberColumn,numberElement:e.numberElement}:{type:`diff-line`,annotationSide:e.side,lineType:e.lineType,lineElement:e.lineElement,numberElement:e.numberElement,lineNumber:e.lineNumber,numberColumn:e.numberColumn}}toTokenEventBaseProps({lineCharEnd:e,lineCharStart:t,lineNumber:n,side:r,tokenElement:i,tokenText:a}){return this.mode===`file`?{type:`token`,lineCharEnd:e,lineCharStart:t,lineNumber:n,tokenElement:i,tokenText:a}:{type:`token`,lineCharEnd:e,lineCharStart:t,lineNumber:n,side:r,tokenElement:i,tokenText:a}}buildSelectedLineRange(e,t){return this.buildSelectionRange(e.lineNumber,t.lineNumber,e.side,t.side)}buildSelectionRange(e,t,n,r){return{start:e,end:t,...n==null?{}:{side:n},...n!==r&&r!=null?{endSide:r}:{}}}resolvePointerTarget(e){let t=!1,n,r,i,a,o,s,c,l,u,d;for(let f of e){if(!(f instanceof HTMLElement))continue;if(d==null&&f.hasAttribute(`data-merge-conflict-action`)){let e=f.getAttribute(`data-merge-conflict-action`)??void 0,t=f.getAttribute(`data-merge-conflict-conflict-index`)??void 0,n=t==null?NaN:Number.parseInt(t,10);VF(e)&&Number.isFinite(n)&&(d={kind:`merge-conflict-action`,resolution:e,conflictIndex:n})}if(s==null&&f.hasAttribute(`data-char`)){s=f;let e=f.getAttribute(`data-char`);if(e!=null){let t=Number.parseInt(e,10);if(!Number.isNaN(t)){let e=f.textContent??``,n=t+e.length;(e.trim()!==``||this.options.enableTokenInteractionsOnWhitespace===!0)&&(c={tokenElement:s,lineCharStart:t,lineCharEnd:n,tokenText:e});continue}}}let e=o==null?f.getAttribute(`data-column-number`)??void 0:void 0;if(e!=null){o=f,u=Number.parseInt(e,10),t=!0,n=ZF(f),a=f.getAttribute(`data-line-index`)??void 0;continue}let p=i==null?f.getAttribute(`data-line`)??void 0:void 0;if(p!=null){i=f,u=Number.parseInt(p,10),n=ZF(f),a=f.getAttribute(`data-line-index`)??void 0;continue}if(l==null&&(f.hasAttribute(`data-expand-button`)||f.hasAttribute(`data-unmodified-lines`))){l={hunkIndex:void 0,direction:f.hasAttribute(`data-expand-up`)?`up`:f.hasAttribute(`data-expand-down`)?`down`:`both`,all:f.hasAttribute(`data-expand-all-button`)};continue}let m=l==null?void 0:f.getAttribute(`data-expand-index`)??void 0;if(l!=null&&m!=null){let e=Number.parseInt(m,10);Number.isNaN(e)||(l.hunkIndex=e);continue}if(r==null&&f.hasAttribute(`data-code`)){r=f;break}}if(d!=null)return d;if(l?.hunkIndex!=null)return{type:`line-info`,hunkIndex:l.hunkIndex,direction:l.direction,all:l.all};if(i??=a==null?void 0:HF(r,`[data-line][data-line-index="${a}"]`),o??=a==null?void 0:HF(r,`[data-column-number][data-line-index="${a}"]`),r==null||i==null||o==null||n==null||u==null||Number.isNaN(u))return;let f=this.parseLineIndex(i,this.isSplitDiff());return c==null?this.mode===`file`?{kind:`line`,lineType:n,lineElement:i,lineNumber:u,numberColumn:t,numberElement:o,side:void 0,splitLineIndex:f}:{kind:`line`,lineType:n,lineElement:i,lineNumber:u,numberColumn:t,numberElement:o,side:XF(n,r),splitLineIndex:f}:this.mode===`file`?{kind:`token`,lineType:n,lineElement:i,lineNumber:u,numberColumn:t,numberElement:o,side:void 0,splitLineIndex:f,...c}:{kind:`token`,lineType:n,lineElement:i,lineNumber:u,numberColumn:t,numberElement:o,side:XF(n,r),splitLineIndex:f,...c}}isSplitDiff(){return this.pre?.getAttribute(`data-diff-type`)===`split`}parseLineIndex(e,t){let n=(e.getAttribute(`data-line-index`)??``).split(`,`).map(e=>Number.parseInt(e,10)).filter(e=>!Number.isNaN(e));if(t&&n.length===2)return n[1];if(!t)return n[0]}};function PF({enableTokenInteractionsOnWhitespace:e,enableGutterUtility:t,lineHoverHighlight:n,onGutterUtilityClick:r,onLineClick:i,onLineEnter:a,onLineLeave:o,onLineNumberClick:s,onTokenClick:c,onTokenEnter:l,onTokenLeave:u,renderGutterUtility:d,__debugPointerEvents:f,enableLineSelection:p,controlledSelection:m,onLineSelected:h,onLineSelectionStart:g,onLineSelectionChange:_,onLineSelectionEnd:v},y,b,x){return{enableTokenInteractionsOnWhitespace:e,enableGutterUtility:FF({enableGutterUtility:t,renderGutterUtility:d,onGutterUtilityClick:r}),usesCustomGutterUtility:d!=null,lineHoverHighlight:n,onGutterUtilityClick:r,onHunkExpand:y,onMergeConflictActionClick:x,onLineClick:i,onLineEnter:a,onLineLeave:o,onLineNumberClick:s,onTokenClick:c,onTokenEnter:l,onTokenLeave:u,__debugPointerEvents:f,enableLineSelection:p,controlledSelection:m,onLineSelected:h,onLineSelectionStart:g,onLineSelectionChange:_,onLineSelectionEnd:v,getLineIndex:b}}function FF({enableGutterUtility:e,renderGutterUtility:t,onGutterUtilityClick:n}){if(n!=null&&t!=null)throw Error(`Cannot use both 'onGutterUtilityClick' and 'renderGutterUtility'. Use only one gutter utility API.`);return e??!1}function IF(e){return e!=null&&`kind`in e&&e.kind===`line`}function LF(e){return e!=null&&`kind`in e&&e.kind===`token`}function RF(e){return IF(e)||LF(e)}function zF(e){return`type`in e&&e.type===`line-info`}function BF(e){return`kind`in e&&e.kind===`merge-conflict-action`}function VF(e){return e===`current`||e===`incoming`||e===`both`}function HF(e,t){let n=e?.querySelector(t);return n instanceof HTMLElement?n:void 0}function UF(e){let t=[],n=e;for(;n!=null;)t.push(n),n=n.parentNode;return t}function WF(e){let t=e.closest(`[data-line], [data-column-number]`);if(t instanceof HTMLElement)return t;let n=e.closest(`[data-line-annotation], [data-gutter-buffer="annotation"]`);if(!(n instanceof HTMLElement))return;let r=n.previousElementSibling;return r instanceof HTMLElement&&(r.hasAttribute(`data-line`)||r.hasAttribute(`data-column-number`))?r:void 0}function GF(e){let t=e.closest(`[slot^="annotation-"]`);if(t instanceof HTMLElement)return t.getAttribute(`slot`)??void 0;if(e instanceof HTMLElement){let t=e.getAttribute(`name`)??void 0;return t!=null&&t.startsWith(`annotation-`)?t:void 0}}function KF(e){if(e==null)return;let t=/^annotation-(?:(additions|deletions)-)?(\d+)$/.exec(e);if(t==null)return;let n=Number.parseInt(t[2],10);if(!(!Number.isFinite(n)||n<=0))return{lineNumber:n,side:t[1]}}function qF(e){return e!=null&&typeof e.elementFromPoint==`function`}function JF(e,t){return e===t||IM(e??void 0,t??void 0)}function YF(e,t){return e?.highlightSide===t.highlightSide&&e?.lineNumberOnly===t.lineNumberOnly&&JF(e?.range??null,t.range)}function XF(e,t){switch(e){case`change-deletion`:return`deletions`;case`change-addition`:return`additions`;default:return t.hasAttribute(`data-deletions`)?`deletions`:`additions`}}function ZF(e){let t=e.getAttribute(`data-line-type`);if(t!=null)switch(t){case`change-deletion`:case`change-addition`:case`context`:case`context-expanded`:return t;default:return}}function QF(e=`none`,t,...n){switch(e){case`none`:return;case`both`:break;case`click`:if(t!==`click`)return;break;case`move`:if(t!==`move`)return}console.log(...n)}var $F=class e{static resizeObserver;static managersByElement=new Map;static getResizeObserver(){let t=e.resizeObserver??new ResizeObserver(e.handleSharedResizeEntries);return e.resizeObserver=t,t}static handleSharedResizeEntries(t){let n=new Map;for(let r of t){let t=e.managersByElement.get(r.target);if(t==null)continue;let i=n.get(t);i==null?n.set(t,[r]):i.push(r)}for(let[e,t]of n)e.handleResizeEntries(t)}observedNodes=new Map;setup(e,{disableAnnotations:t,columnVariables:n=`apply`}){let r=new Set,i=n===`apply`,a=0,o=new Map(this.observedNodes);this.observedNodes.clear();for(let t of e.children){if(a===2)break;let e=(()=>{if(t instanceof HTMLElement&&t.tagName===`CODE`)return t})();if(e==null)continue;a++;let n=o.get(e);if(n!=null&&n.type!==`code`)throw Error(`ResizeManager.setup: somehow a code node is being used for an annotation, should be impossible`);let r=e.firstElementChild;r instanceof HTMLElement||(r=null),n==null?(n={type:`code`,codeElement:e,numberElement:r,codeWidth:`auto`,numberWidth:0,applyColumnVariables:i},this.observedNodes.set(e,n),this.observe(e),r!=null&&(this.observedNodes.set(r,n),this.observe(r))):(this.observedNodes.set(e,n),o.delete(e),n.numberElement===r?n.numberElement==null?n.numberWidth=0:(o.delete(n.numberElement),this.observedNodes.set(n.numberElement,n)):(n.numberElement!=null&&(this.unobserve(n.numberElement),o.delete(n.numberElement)),r!=null&&(this.observe(r),o.delete(r),this.observedNodes.set(r,n)),n.numberElement=r,n.numberWidth=0),nI(n,i))}if(a>1&&!t){let t=e.querySelectorAll(`[data-line-annotation*=","]`),n=new Map;for(let e of t){if(!(e instanceof HTMLElement))continue;let t=e.getAttribute(`data-line-annotation`)??``;if(!/^-?\d+,-?\d+$/.test(t)){console.error(`DiffFileRenderer.setupResizeObserver: Invalid element or annotation`,{lineAnnotation:t,element:e});continue}let r=n.get(t);r??(r=[],n.set(t,r)),r.push(e)}for(let[e,t]of n){if(t.length!==2){console.error(`DiffFileRenderer.setupResizeObserver: Bad Pair`,e,t);continue}let[n,i]=t,a=n.firstElementChild,s=i.firstElementChild;if(!(n instanceof HTMLElement)||!(i instanceof HTMLElement)||!(a instanceof HTMLElement)||!(s instanceof HTMLElement))continue;let c=o.get(a);if(c!=null){this.observedNodes.set(a,c),this.observedNodes.set(s,c),o.delete(a),o.delete(s);continue}let l=a.getBoundingClientRect().height,u=s.getBoundingClientRect().height;c={type:`annotations`,column1:{container:n,child:a,childHeight:l},column2:{container:i,child:s,childHeight:u},currentHeight:`auto`},r.add({child1:a,child2:s,item:c,newHeight:Math.max(l,u)})}for(let e of r)this.applyNewHeight(e.item,e.newHeight),this.observedNodes.set(e.child1,e.item),this.observedNodes.set(e.child2,e.item),this.observe(e.child1),this.observe(e.child2);r.clear()}for(let[e,t]of o)this.unobserve(e),t.type===`code`?aI(t):oI(t);o.clear()}cleanUp(){for(let e of this.observedNodes.keys())this.unobserve(e);this.observedNodes.clear()}observe(t){let{managersByElement:n}=e,r=n.get(t);if(r!==this){if(r!=null&&r!==this)throw Error(`ResizeManager.observe: element is already owned by another ResizeManager`);n.set(t,this),e.getResizeObserver().observe(t)}}unobserve(t){let{managersByElement:n,resizeObserver:r}=e,i=n.get(t);if(i!=null){if(i!==this)throw Error(`ResizeManager.unobserve: element is owned by another ResizeManager`);n.delete(t),r?.unobserve(t),r!=null&&n.size===0&&(r.disconnect(),e.resizeObserver=void 0)}}handleResizeEntries(e){let t=new Map,n=new Set;for(let r of e){let{target:e,borderBoxSize:i,contentBoxSize:a}=r;if(!(e instanceof HTMLElement)){console.error(`ResizeManager.handleResizeEntries: Invalid element for ResizeObserver`,r);continue}let o=this.observedNodes.get(e);if(o==null){console.error(`ResizeManager.handleResizeEntries: Not a valid observed node`,r);continue}if(o.type===`annotations`){let t=(()=>{if(e===o.column1.child)return o.column1;if(e===o.column2.child)return o.column2})();if(t==null){console.error(`ResizeManager.handleResizeEntries: Couldn't find a column for`,{item:o,target:e});continue}t.childHeight=i[0].blockSize,n.add(o)}else if(o.type===`code`){let n=t.get(o)??{},r=a[0].inlineSize;e===o.codeElement?n.codeInlineSize=r:e===o.numberElement&&(n.numberInlineSize=r),t.set(o,n)}}this.applyAnnotationUpdates(n),n.clear(),this.applyColumnUpdates(t),t.clear()}applyAnnotationUpdates(e){for(let t of e)this.applyNewHeight(t,Math.max(t.column1.childHeight,t.column2.childHeight))}applyColumnUpdates=e=>{for(let[t,n]of e){let e=n.codeInlineSize==null?t.codeWidth:eI(n.codeInlineSize),r=n.numberInlineSize==null?t.numberWidth:tI(n.numberInlineSize),i=e!==t.codeWidth,a=r!==t.numberWidth;!i&&!a||(t.codeWidth=e,t.numberWidth=r,t.applyColumnVariables&&rI(t,{codeWidthChanged:i,numberWidthChanged:a}))}};applyNewHeight(e,t){t!==e.currentHeight&&(e.currentHeight=Math.max(t,0),e.column1.container.style.setProperty(`--diffs-annotation-min-height`,`${e.currentHeight}px`),e.column2.container.style.setProperty(`--diffs-annotation-min-height`,`${e.currentHeight}px`))}};function eI(e){let t=Math.max(Math.floor(e),0);return t===0?`auto`:t}function tI(e){return Math.max(Math.ceil(e),0)}function nI(e,t){e.applyColumnVariables!==t&&(e.applyColumnVariables=t,t?rI(e,{codeWidthChanged:!0,numberWidthChanged:!0}):iI(e))}function rI(e,{codeWidthChanged:t,numberWidthChanged:n}){let{codeElement:r,codeWidth:i,numberWidth:a}=e;if(t&&r.style.setProperty(`--diffs-column-width`,`${typeof i==`number`?`${i}px`:`auto`}`),n&&r.style.setProperty(`--diffs-column-number-width`,`${a===0?`auto`:`${a}px`}`),t||n&&i!==`auto`){let e=typeof i==`number`?Math.max(i-a,0):0;r.style.setProperty(`--diffs-column-content-width`,`${e>0?`${e}px`:`auto`}`)}}function iI(e){e.codeElement.style.removeProperty(`--diffs-column-content-width`),e.codeElement.style.removeProperty(`--diffs-column-number-width`),e.codeElement.style.removeProperty(`--diffs-column-width`)}function aI(e){e.codeElement.isConnected&&iI(e)}function oI(e){e.column1.container.isConnected&&e.column1.container.style.removeProperty(`--diffs-annotation-min-height`),e.column2.container.isConnected&&e.column2.container.style.removeProperty(`--diffs-annotation-min-height`)}var sI=new Map,cI=new Map,lI=new Map,uI=new Set;function dI(e){for(let t of Array.isArray(e)?e:[e])if(t!==`text`&&t!==`ansi`&&!uI.has(t))return!1;return!0}function fI(e,t){e=Array.isArray(e)?e:[e];for(let n of e){if(uI.has(n.name))continue;let e=sI.get(n.name);e??(e=n,sI.set(n.name,e)),uI.add(e.name),t.loadLanguageSync(e.data)}}function pI(){return typeof WorkerGlobalScope<`u`&&typeof self<`u`&&self instanceof WorkerGlobalScope}var mI=Object.defineProperty,hI=Object.getOwnPropertyDescriptor,gI=Object.getOwnPropertyNames,_I=Object.prototype.hasOwnProperty,vI=(e,t)=>{let n={};for(var r in e)mI(n,r,{get:e[r],enumerable:!0});return t||mI(n,Symbol.toStringTag,{value:`Module`}),n},yI=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=gI(t),a=0,o=i.length,s;a<o;a++)s=i[a],!_I.call(e,s)&&s!==n&&mI(e,s,{get:(e=>t[e]).bind(null,s),enumerable:!(r=hI(t,s))||r.enumerable});return e},bI=(e,t,n)=>(yI(e,t,`default`),n&&yI(n,t,`default`)),xI=[{id:`abap`,name:`ABAP`,import:(()=>D(()=>import(`./abap-CLvhMVsD.js`),[]))},{id:`actionscript-3`,name:`ActionScript`,import:(()=>D(()=>import(`./actionscript-3--17pq3dv.js`),[]))},{id:`ada`,name:`Ada`,import:(()=>D(()=>import(`./ada-C5qYipkI.js`),[]))},{id:`angular-html`,name:`Angular HTML`,import:(()=>D(()=>import(`./angular-html-B8mrqUL5.js`).then(e=>e.n),__vite__mapDeps([4,1,5,6,7])))},{id:`angular-ts`,name:`Angular TypeScript`,import:(()=>D(()=>import(`./angular-ts-Bzix210W.js`),__vite__mapDeps([8,4,1,5,6,7,9])))},{id:`apache`,name:`Apache Conf`,import:(()=>D(()=>import(`./apache-U0d_L8uA.js`),[]))},{id:`apex`,name:`Apex`,import:(()=>D(()=>import(`./apex-CGTLDQj6.js`),[]))},{id:`apl`,name:`APL`,import:(()=>D(()=>import(`./apl-Dhin1L29.js`),__vite__mapDeps([10,6,1,7,5,11,12,13])))},{id:`applescript`,name:`AppleScript`,import:(()=>D(()=>import(`./applescript-CCn79oCD.js`),[]))},{id:`ara`,name:`Ara`,import:(()=>D(()=>import(`./ara-4CJ0cIlV.js`),[]))},{id:`asciidoc`,name:`AsciiDoc`,aliases:[`adoc`],import:(()=>D(()=>import(`./asciidoc-DE70LPWp.js`),[]))},{id:`asm`,name:`Assembly`,import:(()=>D(()=>import(`./asm-Cmm7eHzH.js`),[]))},{id:`astro`,name:`Astro`,import:(()=>D(()=>import(`./astro-B-4NNgOP.js`),__vite__mapDeps([14,6,1,7,13,15,16,17])))},{id:`awk`,name:`AWK`,import:(()=>D(()=>import(`./awk-BWXHIvNe.js`),[]))},{id:`ballerina`,name:`Ballerina`,import:(()=>D(()=>import(`./ballerina-B7ZEbQpA.js`),[]))},{id:`bat`,name:`Batch File`,aliases:[`batch`],import:(()=>D(()=>import(`./bat-Bo4NYOV-.js`),[]))},{id:`beancount`,name:`Beancount`,import:(()=>D(()=>import(`./beancount-D-usSTwE.js`),[]))},{id:`berry`,name:`Berry`,aliases:[`be`],import:(()=>D(()=>import(`./berry-DKpUyyne.js`),[]))},{id:`bibtex`,name:`BibTeX`,import:(()=>D(()=>import(`./bibtex-Ci_nEsc7.js`),[]))},{id:`bicep`,name:`Bicep`,import:(()=>D(()=>import(`./bicep-CUHmPFLl.js`),[]))},{id:`bird2`,name:`BIRD2 Configuration`,aliases:[`bird`],import:(()=>D(()=>import(`./bird2-C6vDhewU.js`),[]))},{id:`blade`,name:`Blade`,import:(()=>D(()=>import(`./blade-Wr94ul2N.js`),__vite__mapDeps([18,6,1,7,5,11,12,13,19,20])))},{id:`bsl`,name:`1C (Enterprise)`,aliases:[`1c`],import:(()=>D(()=>import(`./bsl-BkkzgIyY.js`),__vite__mapDeps([21,22])))},{id:`c`,name:`C`,import:(()=>D(()=>import(`./c-iCihek07.js`).then(e=>e.n),__vite__mapDeps([23,1])))},{id:`c3`,name:`C3`,import:(()=>D(()=>import(`./c3-CnJL0r0V.js`),[]))},{id:`cadence`,name:`Cadence`,aliases:[`cdc`],import:(()=>D(()=>import(`./cadence-CQ2zXKGN.js`),[]))},{id:`cairo`,name:`Cairo`,import:(()=>D(()=>import(`./cairo-DLTphjLi.js`),__vite__mapDeps([24,25])))},{id:`clarity`,name:`Clarity`,import:(()=>D(()=>import(`./clarity-SemFz856.js`),[]))},{id:`clojure`,name:`Clojure`,aliases:[`clj`],import:(()=>D(()=>import(`./clojure-DqKBuwfJ.js`),[]))},{id:`cmake`,name:`CMake`,import:(()=>D(()=>import(`./cmake-Bj61d0ZC.js`),[]))},{id:`cobol`,name:`COBOL`,import:(()=>D(()=>import(`./cobol-Cw2-KvLW.js`),__vite__mapDeps([26,5,1,6,7,12])))},{id:`codeowners`,name:`CODEOWNERS`,import:(()=>D(()=>import(`./codeowners-C8r90Shi.js`),[]))},{id:`codeql`,name:`CodeQL`,aliases:[`ql`],import:(()=>D(()=>import(`./codeql-oeQT6MSM.js`),[]))},{id:`coffee`,name:`CoffeeScript`,aliases:[`coffeescript`],import:(()=>D(()=>import(`./coffee-CiiSLhB6.js`),__vite__mapDeps([27,6,1])))},{id:`common-lisp`,name:`Common Lisp`,aliases:[`lisp`],import:(()=>D(()=>import(`./common-lisp-Cv5bFMCO.js`),[]))},{id:`coq`,name:`Coq`,import:(()=>D(()=>import(`./coq-BrsZFFmf.js`),[]))},{id:`cpp`,name:`C++`,aliases:[`c++`],import:(()=>D(()=>import(`./cpp-DjoE5qBx.js`).then(e=>e.n),__vite__mapDeps([28,1,20,29,30,23])))},{id:`crystal`,name:`Crystal`,import:(()=>D(()=>import(`./crystal-wCJpIkgB.js`),__vite__mapDeps([31,6,1,7,5,20,23,32])))},{id:`csharp`,name:`C#`,aliases:[`c#`,`cs`],import:(()=>D(()=>import(`./csharp-Ct8U2NOr.js`),[]))},{id:`css`,name:`CSS`,import:(()=>D(()=>import(`./css-CNuuLpMC.js`).then(e=>e.n),__vite__mapDeps([7,1])))},{id:`csv`,name:`CSV`,import:(()=>D(()=>import(`./csv-Dx-8-gkx.js`),[]))},{id:`cue`,name:`CUE`,import:(()=>D(()=>import(`./cue-CE9AQfxI.js`),[]))},{id:`cypher`,name:`Cypher`,aliases:[`cql`],import:(()=>D(()=>import(`./cypher-ClKdZ_lG.js`),[]))},{id:`d`,name:`D`,import:(()=>D(()=>import(`./d-qD-0Kul2.js`),[]))},{id:`dart`,name:`Dart`,import:(()=>D(()=>import(`./dart-CnvKMtbv.js`),[]))},{id:`dax`,name:`DAX`,import:(()=>D(()=>import(`./dax-BkyTk9wS.js`),[]))},{id:`desktop`,name:`Desktop`,import:(()=>D(()=>import(`./desktop-Dlh5hvp9.js`),[]))},{id:`diff`,name:`Diff`,import:(()=>D(()=>import(`./diff-woXpYk--.js`),[]))},{id:`docker`,name:`Dockerfile`,aliases:[`dockerfile`],import:(()=>D(()=>import(`./docker-IyjqRm3v.js`),[]))},{id:`dotenv`,name:`dotEnv`,import:(()=>D(()=>import(`./dotenv-_5a1GRtc.js`),[]))},{id:`dream-maker`,name:`Dream Maker`,import:(()=>D(()=>import(`./dream-maker-DW3nJb8Q.js`),[]))},{id:`edge`,name:`Edge`,import:(()=>D(()=>import(`./edge-DCY0a-ow.js`),__vite__mapDeps([33,5,1,6,7,15,19])))},{id:`elixir`,name:`Elixir`,import:(()=>D(()=>import(`./elixir-DP304Xio.js`),__vite__mapDeps([34,5,1,6,7])))},{id:`elm`,name:`Elm`,import:(()=>D(()=>import(`./elm-o4NJxfws.js`),__vite__mapDeps([35,30,1,23])))},{id:`emacs-lisp`,name:`Emacs Lisp`,aliases:[`elisp`],import:(()=>D(()=>import(`./emacs-lisp-B4R74twV.js`),[]))},{id:`erb`,name:`ERB`,import:(()=>D(()=>import(`./erb-BcNYoZVd.js`),__vite__mapDeps([36,5,1,6,7,37,11,12,20,23,28,29,30,32,38,39,15,17,40,41,42])))},{id:`erlang`,name:`Erlang`,aliases:[`erl`],import:(()=>D(()=>import(`./erlang-Cphh6RMH.js`),__vite__mapDeps([43,44])))},{id:`fennel`,name:`Fennel`,import:(()=>D(()=>import(`./fennel-DQxkIbk2.js`),[]))},{id:`fish`,name:`Fish`,import:(()=>D(()=>import(`./fish-BJitypiv.js`),[]))},{id:`fluent`,name:`Fluent`,aliases:[`ftl`],import:(()=>D(()=>import(`./fluent-C03EYrpw.js`),[]))},{id:`fortran-fixed-form`,name:`Fortran (Fixed Form)`,aliases:[`f`,`for`,`f77`],import:(()=>D(()=>import(`./fortran-fixed-form-DEKoE2YW.js`),__vite__mapDeps([45,46])))},{id:`fortran-free-form`,name:`Fortran (Free Form)`,aliases:[`f90`,`f95`,`f03`,`f08`,`f18`],import:(()=>D(()=>import(`./fortran-free-form-CYNrtFtB.js`),[]))},{id:`fsharp`,name:`F#`,aliases:[`f#`,`fs`],import:(()=>D(()=>import(`./fsharp-D13ZGOAj.js`),__vite__mapDeps([47,44])))},{id:`gdresource`,name:`GDResource`,aliases:[`tscn`,`tres`],import:(()=>D(()=>import(`./gdresource-C0sCabJj.js`),__vite__mapDeps([48,49,50])))},{id:`gdscript`,name:`GDScript`,aliases:[`gd`],import:(()=>D(()=>import(`./gdscript-Cp2uCuqX.js`),[]))},{id:`gdshader`,name:`GDShader`,import:(()=>D(()=>import(`./gdshader-CBce3t8t.js`),[]))},{id:`genie`,name:`Genie`,import:(()=>D(()=>import(`./genie-CV2tkWYe.js`),[]))},{id:`gherkin`,name:`Gherkin`,import:(()=>D(()=>import(`./gherkin-DExj1W_8.js`),[]))},{id:`git-commit`,name:`Git Commit Message`,import:(()=>D(()=>import(`./git-commit-BSykSTBG.js`),__vite__mapDeps([51,52])))},{id:`git-rebase`,name:`Git Rebase Message`,import:(()=>D(()=>import(`./git-rebase-BDPpS8w6.js`),__vite__mapDeps([53,32,1])))},{id:`gleam`,name:`Gleam`,import:(()=>D(()=>import(`./gleam-CSRkHgEL.js`),[]))},{id:`glimmer-js`,name:`Glimmer JS`,aliases:[`gjs`],import:(()=>D(()=>import(`./glimmer-js-BONyzAsu.js`),__vite__mapDeps([54,6,1,7,5,15])))},{id:`glimmer-ts`,name:`Glimmer TS`,aliases:[`gts`],import:(()=>D(()=>import(`./glimmer-ts-f9c0GCOe.js`),__vite__mapDeps([55,6,1,7,5,15])))},{id:`glsl`,name:`GLSL`,import:(()=>D(()=>import(`./glsl-D5MA2a_X.js`).then(e=>e.n),__vite__mapDeps([30,1,23])))},{id:`gn`,name:`GN`,import:(()=>D(()=>import(`./gn-ilITqXS6.js`),[]))},{id:`gnuplot`,name:`Gnuplot`,import:(()=>D(()=>import(`./gnuplot-7GGW24-e.js`),[]))},{id:`go`,name:`Go`,import:(()=>D(()=>import(`./go-rLFTqkRN.js`),[]))},{id:`graphql`,name:`GraphQL`,aliases:[`gql`],import:(()=>D(()=>import(`./graphql-Ctjuxyvl.js`).then(e=>e.n),__vite__mapDeps([39,1,6,15,17,40])))},{id:`groovy`,name:`Groovy`,import:(()=>D(()=>import(`./groovy-CacY0gHj.js`),[]))},{id:`hack`,name:`Hack`,import:(()=>D(()=>import(`./hack-7ztQ7Up-.js`),__vite__mapDeps([56,5,1,6,7,20])))},{id:`haml`,name:`Ruby Haml`,import:(()=>D(()=>import(`./haml-CwEpbK1d.js`).then(e=>e.n),__vite__mapDeps([38,1,6,7])))},{id:`handlebars`,name:`Handlebars`,aliases:[`hbs`],import:(()=>D(()=>import(`./handlebars-ryMP1rBR.js`),__vite__mapDeps([57,6,1,7,5,42])))},{id:`haskell`,name:`Haskell`,aliases:[`hs`],import:(()=>D(()=>import(`./haskell-D8IpX4py.js`),[]))},{id:`haxe`,name:`Haxe`,import:(()=>D(()=>import(`./haxe-OTjmBuCE.js`),[]))},{id:`hcl`,name:`HashiCorp HCL`,import:(()=>D(()=>import(`./hcl-Dh228itO.js`),[]))},{id:`hjson`,name:`Hjson`,import:(()=>D(()=>import(`./hjson-CxZEssPk.js`),[]))},{id:`hlsl`,name:`HLSL`,import:(()=>D(()=>import(`./hlsl-Cvrh5tZx.js`),[]))},{id:`html`,name:`HTML`,import:(()=>D(()=>import(`./html-XwrE-1r6.js`).then(e=>e.n),__vite__mapDeps([5,1,6,7])))},{id:`html-derivative`,name:`HTML (Derivative)`,import:(()=>D(()=>import(`./html-derivative-i4STDFnl.js`),__vite__mapDeps([19,5,1,6,7])))},{id:`http`,name:`HTTP`,import:(()=>D(()=>import(`./http-kmH8AyfE.js`),__vite__mapDeps([58,11,1,12,13,32,39,6,15,17,40])))},{id:`hurl`,name:`Hurl`,import:(()=>D(()=>import(`./hurl-DCZHXKU4.js`),__vite__mapDeps([59,11,1,12,60,39,6,15,17,40])))},{id:`hxml`,name:`HXML`,import:(()=>D(()=>import(`./hxml-B0Qn7Nwc.js`),__vite__mapDeps([61,62])))},{id:`hy`,name:`Hy`,import:(()=>D(()=>import(`./hy-CZbG8q4J.js`),[]))},{id:`imba`,name:`Imba`,import:(()=>D(()=>import(`./imba-DsUTQ-LC.js`),[]))},{id:`ini`,name:`INI`,aliases:[`properties`],import:(()=>D(()=>import(`./ini-B5eOa1yu.js`),[]))},{id:`java`,name:`Java`,import:(()=>D(()=>import(`./java-DdHNQ9hk.js`).then(e=>e.n),__vite__mapDeps([12,1])))},{id:`javascript`,name:`JavaScript`,aliases:[`js`,`cjs`,`mjs`],import:(()=>D(()=>import(`./javascript-obGGvMPs.js`).then(e=>e.n),__vite__mapDeps([6,1])))},{id:`jinja`,name:`Jinja`,import:(()=>D(()=>import(`./jinja-B-tLrNsM.js`),__vite__mapDeps([63,5,1,6,7])))},{id:`jison`,name:`Jison`,import:(()=>D(()=>import(`./jison-CBjhYtSs.js`),__vite__mapDeps([64,6,1])))},{id:`json`,name:`JSON`,import:(()=>D(()=>import(`./json-DAgxKhMr.js`).then(e=>e.n),__vite__mapDeps([13,1])))},{id:`json5`,name:`JSON5`,import:(()=>D(()=>import(`./json5-BR5RXkoi.js`),[]))},{id:`jsonc`,name:`JSON with Comments`,import:(()=>D(()=>import(`./jsonc-CYpm1nAK.js`),[]))},{id:`jsonl`,name:`JSON Lines`,import:(()=>D(()=>import(`./jsonl-CmCQp5Yx.js`),[]))},{id:`jsonnet`,name:`Jsonnet`,import:(()=>D(()=>import(`./jsonnet-CJTPZ8u_.js`),[]))},{id:`jssm`,name:`JSSM`,aliases:[`fsl`],import:(()=>D(()=>import(`./jssm-DXw9l8Rf.js`),[]))},{id:`jsx`,name:`JSX`,import:(()=>D(()=>import(`./jsx-gTgmArGx.js`).then(e=>e.n),__vite__mapDeps([40,1])))},{id:`julia`,name:`Julia`,aliases:[`jl`],import:(()=>D(()=>import(`./julia-CjHxn3vf.js`),__vite__mapDeps([65,6,1,20,25,28,29,30,23,66])))},{id:`just`,name:`Just`,import:(()=>D(()=>import(`./just-CZ9bduw9.js`),__vite__mapDeps([67,6,1,15,25,32,37,7,5,11,12,20,23,28,29,30,38,39,17,40,41,42,68])))},{id:`kdl`,name:`KDL`,import:(()=>D(()=>import(`./kdl-CsD5j6eV.js`),[]))},{id:`kotlin`,name:`Kotlin`,aliases:[`kt`,`kts`],import:(()=>D(()=>import(`./kotlin-DhhofPvG.js`),[]))},{id:`kusto`,name:`Kusto`,aliases:[`kql`],import:(()=>D(()=>import(`./kusto-C7mF5XQf.js`),[]))},{id:`latex`,name:`LaTeX`,import:(()=>D(()=>import(`./latex-D9bvcAJr.js`),__vite__mapDeps([69,70,66,1])))},{id:`lean`,name:`Lean 4`,aliases:[`lean4`],import:(()=>D(()=>import(`./lean-CewbzKMR.js`),[]))},{id:`less`,name:`Less`,import:(()=>D(()=>import(`./less-DVTAwKKz.js`),[]))},{id:`liquid`,name:`Liquid`,import:(()=>D(()=>import(`./liquid-G0MH4h_m.js`),__vite__mapDeps([71,6,1,7,5,13])))},{id:`llvm`,name:`LLVM IR`,import:(()=>D(()=>import(`./llvm-Cm23YOpf.js`),[]))},{id:`log`,name:`Log file`,import:(()=>D(()=>import(`./log-BNLmms1o.js`),[]))},{id:`logo`,name:`Logo`,import:(()=>D(()=>import(`./logo-Cluzi2Zq.js`),[]))},{id:`lua`,name:`Lua`,import:(()=>D(()=>import(`./lua-FONpmTUP.js`).then(e=>e.n),__vite__mapDeps([41,1,23])))},{id:`luau`,name:`Luau`,import:(()=>D(()=>import(`./luau-CNKltnaQ.js`),[]))},{id:`make`,name:`Makefile`,aliases:[`makefile`],import:(()=>D(()=>import(`./make-Dixweg8N.js`),[]))},{id:`markdown`,name:`Markdown`,aliases:[`md`],import:(()=>D(()=>import(`./markdown-BYOwaDjH.js`),[]))},{id:`marko`,name:`Marko`,import:(()=>D(()=>import(`./marko-DV5GrDmo.js`),__vite__mapDeps([72,7,1,9,15,73])))},{id:`matlab`,name:`MATLAB`,import:(()=>D(()=>import(`./matlab-D7qyCx1q.js`),[]))},{id:`mdc`,name:`MDC`,import:(()=>D(()=>import(`./mdc-cg1lnqpW.js`),__vite__mapDeps([74,19,5,1,6,7,42,44])))},{id:`mdx`,name:`MDX`,import:(()=>D(()=>import(`./mdx-DQZ5AkYe.js`),[]))},{id:`mermaid`,name:`Mermaid`,aliases:[`mmd`],import:(()=>D(()=>import(`./mermaid-Bk4SNUv9.js`),[]))},{id:`mipsasm`,name:`MIPS Assembly`,aliases:[`mips`],import:(()=>D(()=>import(`./mipsasm-BMqwQI7S.js`),[]))},{id:`mojo`,name:`Mojo`,import:(()=>D(()=>import(`./mojo-BgCJLMeH.js`),[]))},{id:`moonbit`,name:`MoonBit`,aliases:[`mbt`,`mbti`],import:(()=>D(()=>import(`./moonbit-CaWjb8XO.js`),[]))},{id:`move`,name:`Move`,import:(()=>D(()=>import(`./move-B1IS1UjX.js`),[]))},{id:`narrat`,name:`Narrat Language`,aliases:[`nar`],import:(()=>D(()=>import(`./narrat-_X_XdTYD.js`),[]))},{id:`nextflow`,name:`Nextflow`,aliases:[`nf`],import:(()=>D(()=>import(`./nextflow-BJtWHP5T.js`),__vite__mapDeps([75,76])))},{id:`nextflow-groovy`,name:`Nextflow Groovy`,import:(()=>D(()=>import(`./nextflow-groovy-DJMQeKeT.js`),[]))},{id:`nginx`,name:`Nginx`,import:(()=>D(()=>import(`./nginx-BTMw9COX.js`),__vite__mapDeps([77,41,1,23])))},{id:`nim`,name:`Nim`,import:(()=>D(()=>import(`./nim-B6yJ_yaC.js`),__vite__mapDeps([78,6,1,7,5,11,12,23,30,44])))},{id:`nix`,name:`Nix`,import:(()=>D(()=>import(`./nix-IvuFDN5E.js`),[]))},{id:`nushell`,name:`nushell`,aliases:[`nu`],import:(()=>D(()=>import(`./nushell-DcLAeLz5.js`),[]))},{id:`objective-c`,name:`Objective-C`,aliases:[`objc`],import:(()=>D(()=>import(`./objective-c-D1A_Heim.js`),[]))},{id:`objective-cpp`,name:`Objective-C++`,import:(()=>D(()=>import(`./objective-cpp-BsSzOQcm.js`),[]))},{id:`ocaml`,name:`OCaml`,import:(()=>D(()=>import(`./ocaml-O90oeIOV.js`),[]))},{id:`odin`,name:`Odin`,import:(()=>D(()=>import(`./odin-B1RWQWA5.js`),[]))},{id:`openscad`,name:`OpenSCAD`,aliases:[`scad`],import:(()=>D(()=>import(`./openscad-BUDT5pXO.js`),[]))},{id:`pascal`,name:`Pascal`,import:(()=>D(()=>import(`./pascal-4ZHwLPI5.js`),[]))},{id:`perl`,name:`Perl`,import:(()=>D(()=>import(`./perl-BAov3eih.js`),__vite__mapDeps([68,6,1,7,5,11,12,20])))},{id:`php`,name:`PHP`,import:(()=>D(()=>import(`./php-Cg76ANFt.js`),__vite__mapDeps([79,6,1,7,5,11,12,13,20])))},{id:`pkl`,name:`Pkl`,import:(()=>D(()=>import(`./pkl-ot-7Btpt.js`),[]))},{id:`plsql`,name:`PL/SQL`,import:(()=>D(()=>import(`./plsql-DGHpHOYJ.js`),[]))},{id:`po`,name:`Gettext PO`,aliases:[`pot`,`potx`],import:(()=>D(()=>import(`./po-BiJDBrnU.js`),[]))},{id:`polar`,name:`Polar`,import:(()=>D(()=>import(`./polar-C7UOKdEL.js`),[]))},{id:`postcss`,name:`PostCSS`,import:(()=>D(()=>import(`./postcss-BXeXVLqQ.js`),[]))},{id:`powerquery`,name:`PowerQuery`,import:(()=>D(()=>import(`./powerquery-DNMTfnFr.js`),[]))},{id:`powershell`,name:`PowerShell`,aliases:[`ps`,`ps1`],import:(()=>D(()=>import(`./powershell-DshXNtvi.js`),[]))},{id:`prisma`,name:`Prisma`,import:(()=>D(()=>import(`./prisma-BsRQq5mF.js`),[]))},{id:`prolog`,name:`Prolog`,import:(()=>D(()=>import(`./prolog-iXnhIJG7.js`),[]))},{id:`proto`,name:`Protocol Buffer 3`,aliases:[`protobuf`],import:(()=>D(()=>import(`./proto-DB4EqR-F.js`),[]))},{id:`pug`,name:`Pug`,aliases:[`jade`],import:(()=>D(()=>import(`./pug-DkgDHZci.js`),__vite__mapDeps([80,6,1,7,5])))},{id:`puppet`,name:`Puppet`,import:(()=>D(()=>import(`./puppet-CDv2pdJW.js`),[]))},{id:`purescript`,name:`PureScript`,import:(()=>D(()=>import(`./purescript-9MfHhQsQ.js`),[]))},{id:`python`,name:`Python`,aliases:[`py`],import:(()=>D(()=>import(`./python-gzcpVVnB.js`),[]))},{id:`qml`,name:`QML`,import:(()=>D(()=>import(`./qml-_a-QhfPD.js`),__vite__mapDeps([81,6,1])))},{id:`qmldir`,name:`QML Directory`,import:(()=>D(()=>import(`./qmldir-DCQb3MpD.js`),[]))},{id:`qss`,name:`Qt Style Sheets`,import:(()=>D(()=>import(`./qss-Fe1Jh2GI.js`),[]))},{id:`r`,name:`R`,import:(()=>D(()=>import(`./r-D6UWEOL2.js`).then(e=>e.n),__vite__mapDeps([66,1])))},{id:`racket`,name:`Racket`,import:(()=>D(()=>import(`./racket-DcIDlBhZ.js`),[]))},{id:`raku`,name:`Raku`,aliases:[`perl6`],import:(()=>D(()=>import(`./raku-B3gFvitq.js`),[]))},{id:`razor`,name:`ASP.NET Razor`,import:(()=>D(()=>import(`./razor-D3EoCAik.js`),__vite__mapDeps([82,5,1,6,7,83])))},{id:`reg`,name:`Windows Registry Script`,import:(()=>D(()=>import(`./reg-CRGYupPL.js`),[]))},{id:`regexp`,name:`RegExp`,aliases:[`regex`],import:(()=>D(()=>import(`./regexp-DR20uMnK.js`).then(e=>e.n),__vite__mapDeps([29,1])))},{id:`rel`,name:`Rel`,import:(()=>D(()=>import(`./rel-BtDbiS_P.js`),[]))},{id:`riscv`,name:`RISC-V`,import:(()=>D(()=>import(`./riscv-Ckw8ddFX.js`),[]))},{id:`ron`,name:`RON`,import:(()=>D(()=>import(`./ron-VUp2lXgN.js`),[]))},{id:`rosmsg`,name:`ROS Interface`,import:(()=>D(()=>import(`./rosmsg-CAekHB0j.js`),[]))},{id:`rst`,name:`reStructuredText`,import:(()=>D(()=>import(`./rst-YTmaoyaq.js`),__vite__mapDeps([84,6,1,19,5,7,25,85,28,20,29,30,23,32,42,37,11,12,38,39,15,17,40,41])))},{id:`ruby`,name:`Ruby`,aliases:[`rb`],import:(()=>D(()=>import(`./ruby-2bd251b9.js`),__vite__mapDeps([37,6,1,7,5,11,12,20,23,28,29,30,32,38,39,15,17,40,41,42])))},{id:`rust`,name:`Rust`,aliases:[`rs`],import:(()=>D(()=>import(`./rust-Cfkwpbl8.js`),[]))},{id:`sas`,name:`SAS`,import:(()=>D(()=>import(`./sas-B6p8-ynO.js`),__vite__mapDeps([86,20,1])))},{id:`sass`,name:`Sass`,import:(()=>D(()=>import(`./sass-DXrisJhu.js`),[]))},{id:`scala`,name:`Scala`,import:(()=>D(()=>import(`./scala-DKOlJaKm.js`),[]))},{id:`scheme`,name:`Scheme`,import:(()=>D(()=>import(`./scheme-DQCgrYNe.js`),[]))},{id:`scss`,name:`SCSS`,import:(()=>D(()=>import(`./scss-YesllqfO.js`).then(e=>e.n),__vite__mapDeps([9,1,7])))},{id:`sdbl`,name:`1C (Query)`,aliases:[`1c-query`],import:(()=>D(()=>import(`./sdbl-bTVj8UrX.js`),[]))},{id:`shaderlab`,name:`ShaderLab`,aliases:[`shader`],import:(()=>D(()=>import(`./shaderlab-TOUzSsQk.js`),__vite__mapDeps([87,88])))},{id:`shellscript`,name:`Shell`,aliases:[`bash`,`sh`,`shell`,`zsh`],import:(()=>D(()=>import(`./shellscript-Da78Ox-3.js`).then(e=>e.n),__vite__mapDeps([32,1])))},{id:`shellsession`,name:`Shell Session`,aliases:[`console`],import:(()=>D(()=>import(`./shellsession-CVsQGYfZ.js`),__vite__mapDeps([89,32,1])))},{id:`smalltalk`,name:`Smalltalk`,import:(()=>D(()=>import(`./smalltalk-B16xEiuN.js`),[]))},{id:`solidity`,name:`Solidity`,import:(()=>D(()=>import(`./solidity-CKzVLygQ.js`),[]))},{id:`soy`,name:`Closure Templates`,aliases:[`closure-templates`],import:(()=>D(()=>import(`./soy-DEd-qcad.js`),__vite__mapDeps([90,5,1,6,7])))},{id:`sparql`,name:`SPARQL`,import:(()=>D(()=>import(`./sparql-D_iOobhT.js`),__vite__mapDeps([91,92])))},{id:`splunk`,name:`Splunk Query Language`,aliases:[`spl`],import:(()=>D(()=>import(`./splunk-BC2Px7Mm.js`),[]))},{id:`sql`,name:`SQL`,import:(()=>D(()=>import(`./sql-ClgswhA6.js`).then(e=>e.n),__vite__mapDeps([20,1])))},{id:`ssh-config`,name:`SSH Config`,import:(()=>D(()=>import(`./ssh-config-BgfXC-Er.js`),[]))},{id:`stata`,name:`Stata`,import:(()=>D(()=>import(`./stata-RoaAgbqU.js`),__vite__mapDeps([93,20,1])))},{id:`stylus`,name:`Stylus`,aliases:[`styl`],import:(()=>D(()=>import(`./stylus-B6D30XZt.js`),[]))},{id:`surrealql`,name:`SurrealQL`,aliases:[`surql`],import:(()=>D(()=>import(`./surrealql-DIn4NJsS.js`),__vite__mapDeps([94,6,1])))},{id:`svelte`,name:`Svelte`,import:(()=>D(()=>import(`./svelte-Bj3Hmc9F.js`),__vite__mapDeps([95,6,1,7,15,16])))},{id:`swift`,name:`Swift`,import:(()=>D(()=>import(`./swift-DonLKvLd.js`),[]))},{id:`system-verilog`,name:`SystemVerilog`,import:(()=>D(()=>import(`./system-verilog-DJ5XKQeo.js`),[]))},{id:`systemd`,name:`Systemd Units`,import:(()=>D(()=>import(`./systemd-BxMlprV5.js`),[]))},{id:`talonscript`,name:`TalonScript`,aliases:[`talon`],import:(()=>D(()=>import(`./talonscript-CohzipZa.js`),[]))},{id:`tasl`,name:`Tasl`,import:(()=>D(()=>import(`./tasl-DMoTqEGO.js`),[]))},{id:`tcl`,name:`Tcl`,import:(()=>D(()=>import(`./tcl-CZd0xW_V.js`),[]))},{id:`templ`,name:`Templ`,import:(()=>D(()=>import(`./templ-TjxbArHn.js`),__vite__mapDeps([96,6,1,7,97])))},{id:`terraform`,name:`Terraform`,aliases:[`tf`,`tfvars`],import:(()=>D(()=>import(`./terraform-DswuEJGm.js`),[]))},{id:`tex`,name:`TeX`,import:(()=>D(()=>import(`./tex-0w6-Dtgt.js`),__vite__mapDeps([70,66,1])))},{id:`toml`,name:`TOML`,import:(()=>D(()=>import(`./toml-CcmNWLt0.js`),[]))},{id:`ts-tags`,name:`TypeScript with Tags`,aliases:[`lit`],import:(()=>D(()=>import(`./ts-tags-DFwAVxhO.js`),__vite__mapDeps([98,6,1,7,5,11,12,15,20,30,23])))},{id:`tsv`,name:`TSV`,import:(()=>D(()=>import(`./tsv-sltzmVWM.js`),[]))},{id:`tsx`,name:`TSX`,import:(()=>D(()=>import(`./tsx-CUOciP0b.js`).then(e=>e.n),__vite__mapDeps([17,1])))},{id:`turtle`,name:`Turtle`,import:(()=>D(()=>import(`./turtle-ByJddavk.js`),[]))},{id:`twig`,name:`Twig`,import:(()=>D(()=>import(`./twig-BbcH-NR0.js`),__vite__mapDeps([99,6,1,7,9,25,37,5,11,12,20,23,28,29,30,32,38,39,15,17,40,41,42,79,13])))},{id:`typescript`,name:`TypeScript`,aliases:[`ts`,`cts`,`mts`],import:(()=>D(()=>import(`./typescript-BydbNFcO.js`).then(e=>e.n),__vite__mapDeps([15,1])))},{id:`typespec`,name:`TypeSpec`,aliases:[`tsp`],import:(()=>D(()=>import(`./typespec-BRdr0IET.js`),[]))},{id:`typst`,name:`Typst`,aliases:[`typ`],import:(()=>D(()=>import(`./typst-DI99ib-x.js`),[]))},{id:`v`,name:`V`,import:(()=>D(()=>import(`./v-DETTlOr0.js`),[]))},{id:`vala`,name:`Vala`,import:(()=>D(()=>import(`./vala-zf12oZj6.js`),[]))},{id:`vb`,name:`Visual Basic`,aliases:[`cmd`],import:(()=>D(()=>import(`./vb-Djn5o6TS.js`),[]))},{id:`verilog`,name:`Verilog`,import:(()=>D(()=>import(`./verilog-CiiDBU1e.js`),[]))},{id:`vhdl`,name:`VHDL`,import:(()=>D(()=>import(`./vhdl-BroJfC0k.js`),[]))},{id:`viml`,name:`Vim Script`,aliases:[`vim`,`vimscript`],import:(()=>D(()=>import(`./viml-DvXPmvsu.js`),[]))},{id:`vue`,name:`Vue`,import:(()=>D(()=>import(`./vue-BNi0qJZP.js`),__vite__mapDeps([100,6,1,7,5,13,15,19])))},{id:`vue-html`,name:`Vue HTML`,import:(()=>D(()=>import(`./vue-html-DkKkQnZL.js`),__vite__mapDeps([101,6,1])))},{id:`vue-vine`,name:`Vue Vine`,import:(()=>D(()=>import(`./vue-vine-DFaKYU4X.js`),__vite__mapDeps([102,6,1,7,9,16,73,103])))},{id:`vyper`,name:`Vyper`,aliases:[`vy`],import:(()=>D(()=>import(`./vyper-CgoNMtux.js`),[]))},{id:`wasm`,name:`WebAssembly`,import:(()=>D(()=>import(`./wasm-ByWQv1Qj.js`),[]))},{id:`wenyan`,name:`Wenyan`,aliases:[`文言`],import:(()=>D(()=>import(`./wenyan-C8pVoKbM.js`),[]))},{id:`wgsl`,name:`WGSL`,import:(()=>D(()=>import(`./wgsl-BsKzXJz4.js`),[]))},{id:`wikitext`,name:`Wikitext`,aliases:[`mediawiki`,`wiki`],import:(()=>D(()=>import(`./wikitext-ClFFjSW2.js`),[]))},{id:`wit`,name:`WebAssembly Interface Types`,import:(()=>D(()=>import(`./wit-DdvCle-K.js`),[]))},{id:`wolfram`,name:`Wolfram`,aliases:[`wl`],import:(()=>D(()=>import(`./wolfram-DLL8P-h_.js`),[]))},{id:`xml`,name:`XML`,import:(()=>D(()=>import(`./xml-BlnrEAEy.js`).then(e=>e.n),__vite__mapDeps([11,1,12])))},{id:`xsl`,name:`XSL`,import:(()=>D(()=>import(`./xsl-BOPS8gLt.js`),__vite__mapDeps([104,11,1,12])))},{id:`yaml`,name:`YAML`,aliases:[`yml`],import:(()=>D(()=>import(`./yaml-Du_6cdrH.js`).then(e=>e.n),__vite__mapDeps([42,1])))},{id:`zenscript`,name:`ZenScript`,import:(()=>D(()=>import(`./zenscript-BnlCZFoB.js`),[]))},{id:`zig`,name:`Zig`,import:(()=>D(()=>import(`./zig-CMLA9XwU.js`),[]))}],SI=Object.fromEntries(xI.map(e=>[e.id,e.import])),CI=Object.fromEntries(xI.flatMap(e=>e.aliases?.map(t=>[t,e.import])||[])),wI={...SI,...CI},TI=Object.fromEntries([{id:`andromeeda`,displayName:`Andromeeda`,type:`dark`,import:(()=>D(()=>import(`./andromeeda-WkhI09AS.js`),[]))},{id:`aurora-x`,displayName:`Aurora X`,type:`dark`,import:(()=>D(()=>import(`./aurora-x-C7CFqhAd.js`),[]))},{id:`ayu-dark`,displayName:`Ayu Dark`,type:`dark`,import:(()=>D(()=>import(`./ayu-dark-CRu61w6_.js`),[]))},{id:`ayu-light`,displayName:`Ayu Light`,type:`light`,import:(()=>D(()=>import(`./ayu-light-Dn6O_aYR.js`),[]))},{id:`ayu-mirage`,displayName:`Ayu Mirage`,type:`dark`,import:(()=>D(()=>import(`./ayu-mirage-CTjYAbs-.js`),[]))},{id:`catppuccin-frappe`,displayName:`Catppuccin Frappé`,type:`dark`,import:(()=>D(()=>import(`./catppuccin-frappe-DFlFW5gh.js`),[]))},{id:`catppuccin-latte`,displayName:`Catppuccin Latte`,type:`light`,import:(()=>D(()=>import(`./catppuccin-latte-CpxdcXpJ.js`),[]))},{id:`catppuccin-macchiato`,displayName:`Catppuccin Macchiato`,type:`dark`,import:(()=>D(()=>import(`./catppuccin-macchiato-DIdIQ04K.js`),[]))},{id:`catppuccin-mocha`,displayName:`Catppuccin Mocha`,type:`dark`,import:(()=>D(()=>import(`./catppuccin-mocha-Co3Xjl64.js`),[]))},{id:`dark-plus`,displayName:`Dark Plus`,type:`dark`,import:(()=>D(()=>import(`./dark-plus-GAt2ZgX8.js`),[]))},{id:`dracula`,displayName:`Dracula Theme`,type:`dark`,import:(()=>D(()=>import(`./dracula-C2uKkzgK.js`),[]))},{id:`dracula-soft`,displayName:`Dracula Theme Soft`,type:`dark`,import:(()=>D(()=>import(`./dracula-soft-D1bVjxWZ.js`),[]))},{id:`everforest-dark`,displayName:`Everforest Dark`,type:`dark`,import:(()=>D(()=>import(`./everforest-dark-D-DlICQR.js`),[]))},{id:`everforest-light`,displayName:`Everforest Light`,type:`light`,import:(()=>D(()=>import(`./everforest-light-CeVdGHYG.js`),[]))},{id:`github-dark`,displayName:`GitHub Dark`,type:`dark`,import:(()=>D(()=>import(`./github-dark-DwbbXv51.js`),[]))},{id:`github-dark-default`,displayName:`GitHub Dark Default`,type:`dark`,import:(()=>D(()=>import(`./github-dark-default-CxjRwzl6.js`),[]))},{id:`github-dark-dimmed`,displayName:`GitHub Dark Dimmed`,type:`dark`,import:(()=>D(()=>import(`./github-dark-dimmed-Cr1oaoul.js`),[]))},{id:`github-dark-high-contrast`,displayName:`GitHub Dark High Contrast`,type:`dark`,import:(()=>D(()=>import(`./github-dark-high-contrast-B4qJZLZa.js`),[]))},{id:`github-light`,displayName:`GitHub Light`,type:`light`,import:(()=>D(()=>import(`./github-light-CsVXhIlR.js`),[]))},{id:`github-light-default`,displayName:`GitHub Light Default`,type:`light`,import:(()=>D(()=>import(`./github-light-default-DB_IwZa6.js`),[]))},{id:`github-light-high-contrast`,displayName:`GitHub Light High Contrast`,type:`light`,import:(()=>D(()=>import(`./github-light-high-contrast-DLgVeSB-.js`),[]))},{id:`gruvbox-dark-hard`,displayName:`Gruvbox Dark Hard`,type:`dark`,import:(()=>D(()=>import(`./gruvbox-dark-hard-DXm60lX3.js`),[]))},{id:`gruvbox-dark-medium`,displayName:`Gruvbox Dark Medium`,type:`dark`,import:(()=>D(()=>import(`./gruvbox-dark-medium-GE2thSmD.js`),[]))},{id:`gruvbox-dark-soft`,displayName:`Gruvbox Dark Soft`,type:`dark`,import:(()=>D(()=>import(`./gruvbox-dark-soft-04Cj-4VZ.js`),[]))},{id:`gruvbox-light-hard`,displayName:`Gruvbox Light Hard`,type:`light`,import:(()=>D(()=>import(`./gruvbox-light-hard-K6wSn29D.js`),[]))},{id:`gruvbox-light-medium`,displayName:`Gruvbox Light Medium`,type:`light`,import:(()=>D(()=>import(`./gruvbox-light-medium-CVy3aSlc.js`),[]))},{id:`gruvbox-light-soft`,displayName:`Gruvbox Light Soft`,type:`light`,import:(()=>D(()=>import(`./gruvbox-light-soft-DNgJjaY0.js`),[]))},{id:`horizon`,displayName:`Horizon`,type:`dark`,import:(()=>D(()=>import(`./horizon-0-RkHfro.js`),[]))},{id:`horizon-bright`,displayName:`Horizon Bright`,type:`light`,import:(()=>D(()=>import(`./horizon-bright-BgL2X9oq.js`),[]))},{id:`houston`,displayName:`Houston`,type:`dark`,import:(()=>D(()=>import(`./houston-KyjWKfuY.js`),[]))},{id:`kanagawa-dragon`,displayName:`Kanagawa Dragon`,type:`dark`,import:(()=>D(()=>import(`./kanagawa-dragon-7TqgsUPC.js`),[]))},{id:`kanagawa-lotus`,displayName:`Kanagawa Lotus`,type:`light`,import:(()=>D(()=>import(`./kanagawa-lotus-CqxMQulh.js`),[]))},{id:`kanagawa-wave`,displayName:`Kanagawa Wave`,type:`dark`,import:(()=>D(()=>import(`./kanagawa-wave-D8CNn6T_.js`),[]))},{id:`laserwave`,displayName:`LaserWave`,type:`dark`,import:(()=>D(()=>import(`./laserwave-CQkdhozh.js`),[]))},{id:`light-plus`,displayName:`Light Plus`,type:`light`,import:(()=>D(()=>import(`./light-plus-CNQ8_7Y0.js`),[]))},{id:`material-theme`,displayName:`Material Theme`,type:`dark`,import:(()=>D(()=>import(`./material-theme-CAtLaHa3.js`),[]))},{id:`material-theme-darker`,displayName:`Material Theme Darker`,type:`dark`,import:(()=>D(()=>import(`./material-theme-darker-k-s5Bc6K.js`),[]))},{id:`material-theme-lighter`,displayName:`Material Theme Lighter`,type:`light`,import:(()=>D(()=>import(`./material-theme-lighter-CD6a-c4d.js`),[]))},{id:`material-theme-ocean`,displayName:`Material Theme Ocean`,type:`dark`,import:(()=>D(()=>import(`./material-theme-ocean-B3mraInd.js`),[]))},{id:`material-theme-palenight`,displayName:`Material Theme Palenight`,type:`dark`,import:(()=>D(()=>import(`./material-theme-palenight-DEhAARHw.js`),[]))},{id:`min-dark`,displayName:`Min Dark`,type:`dark`,import:(()=>D(()=>import(`./min-dark-BFqTAwCr.js`),[]))},{id:`min-light`,displayName:`Min Light`,type:`light`,import:(()=>D(()=>import(`./min-light-O7UdaaxX.js`),[]))},{id:`monokai`,displayName:`Monokai`,type:`dark`,import:(()=>D(()=>import(`./monokai-C0p7Qecz.js`),[]))},{id:`night-owl`,displayName:`Night Owl`,type:`dark`,import:(()=>D(()=>import(`./night-owl-BsnCLAKc.js`),[]))},{id:`night-owl-light`,displayName:`Night Owl Light`,type:`light`,import:(()=>D(()=>import(`./night-owl-light-BODRhcTU.js`),[]))},{id:`nord`,displayName:`Nord`,type:`dark`,import:(()=>D(()=>import(`./nord-Cd-F4txO.js`),[]))},{id:`one-dark-pro`,displayName:`One Dark Pro`,type:`dark`,import:(()=>D(()=>import(`./one-dark-pro-DUS_IGRK.js`),[]))},{id:`one-light`,displayName:`One Light`,type:`light`,import:(()=>D(()=>import(`./one-light-CVUd7yD5.js`),[]))},{id:`plastic`,displayName:`Plastic`,type:`dark`,import:(()=>D(()=>import(`./plastic-CF8VZTnn.js`),[]))},{id:`poimandres`,displayName:`Poimandres`,type:`dark`,import:(()=>D(()=>import(`./poimandres-BX2TyY6j.js`),[]))},{id:`red`,displayName:`Red`,type:`dark`,import:(()=>D(()=>import(`./red-7ga_dcKu.js`),[]))},{id:`rose-pine`,displayName:`Rosé Pine`,type:`dark`,import:(()=>D(()=>import(`./rose-pine-rh6ipraJ.js`),[]))},{id:`rose-pine-dawn`,displayName:`Rosé Pine Dawn`,type:`light`,import:(()=>D(()=>import(`./rose-pine-dawn-DSuRaP6u.js`),[]))},{id:`rose-pine-moon`,displayName:`Rosé Pine Moon`,type:`dark`,import:(()=>D(()=>import(`./rose-pine-moon-DdHjCvFQ.js`),[]))},{id:`slack-dark`,displayName:`Slack Dark`,type:`dark`,import:(()=>D(()=>import(`./slack-dark-DYvUXyrP.js`),[]))},{id:`slack-ochin`,displayName:`Slack Ochin`,type:`light`,import:(()=>D(()=>import(`./slack-ochin-bqtMVDfH.js`),[]))},{id:`snazzy-light`,displayName:`Snazzy Light`,type:`light`,import:(()=>D(()=>import(`./snazzy-light-D8dzFmq5.js`),[]))},{id:`solarized-dark`,displayName:`Solarized Dark`,type:`dark`,import:(()=>D(()=>import(`./solarized-dark-BQwPDzxK.js`),[]))},{id:`solarized-light`,displayName:`Solarized Light`,type:`light`,import:(()=>D(()=>import(`./solarized-light-BLaijb3X.js`),[]))},{id:`synthwave-84`,displayName:`Synthwave '84`,type:`dark`,import:(()=>D(()=>import(`./synthwave-84-CIknw8y7.js`),[]))},{id:`tokyo-night`,displayName:`Tokyo Night`,type:`dark`,import:(()=>D(()=>import(`./tokyo-night-iIspnLcq.js`),[]))},{id:`vesper`,displayName:`Vesper`,type:`dark`,import:(()=>D(()=>import(`./vesper-D5bVUKB1.js`),[]))},{id:`vitesse-black`,displayName:`Vitesse Black`,type:`dark`,import:(()=>D(()=>import(`./vitesse-black-D082JcaE.js`),[]))},{id:`vitesse-dark`,displayName:`Vitesse Dark`,type:`dark`,import:(()=>D(()=>import(`./vitesse-dark-z-nr_5O8.js`),[]))},{id:`vitesse-light`,displayName:`Vitesse Light`,type:`light`,import:(()=>D(()=>import(`./vitesse-light-ojz42ZLy.js`),[]))}].map(e=>[e.id,e.import])),EI=e({createOnigurumaEngine:()=>QI,getDefaultWasmLoader:()=>ZI,loadWasm:()=>GI,setDefaultWasmLoader:()=>XI}),DI=class extends Error{constructor(e){super(e),this.name=`ShikiError`}};function OI(){return 2147483648}function kI(){return typeof performance<`u`?performance.now():Date.now()}var AI=(e,t)=>e+(t-e%t)%t;async function jI(e){let t,n,r={};function i(e){n=e,r.HEAPU8=new Uint8Array(e),r.HEAPU32=new Uint32Array(e)}function a(e,t,n){r.HEAPU8.copyWithin(e,t,t+n)}function o(e){try{return t.grow(e-n.byteLength+65535>>>16),i(t.buffer),1}catch{}}function s(e){let t=r.HEAPU8.length;e>>>=0;let n=OI();if(e>n)return!1;for(let r=1;r<=4;r*=2){let i=t*(1+.2/r);if(i=Math.min(i,e+100663296),o(Math.min(n,AI(Math.max(e,i),65536))))return!0}return!1}let c=typeof TextDecoder<`u`?new TextDecoder(`utf8`):void 0;function l(e,t,n=1024){let r=t+n,i=t;for(;e[i]&&!(i>=r);)++i;if(i-t>16&&e.buffer&&c)return c.decode(e.subarray(t,i));let a=``;for(;t<i;){let n=e[t++];if(!(n&128)){a+=String.fromCharCode(n);continue}let r=e[t++]&63;if((n&224)==192){a+=String.fromCharCode((n&31)<<6|r);continue}let i=e[t++]&63;if(n=(n&240)==224?(n&15)<<12|r<<6|i:(n&7)<<18|r<<12|i<<6|e[t++]&63,n<65536)a+=String.fromCharCode(n);else{let e=n-65536;a+=String.fromCharCode(55296|e>>10,56320|e&1023)}}return a}function u(e,t){return e?l(r.HEAPU8,e,t):``}let d={emscripten_get_now:kI,emscripten_memcpy_big:a,emscripten_resize_heap:s,fd_write:()=>0};async function f(){let n=await e({env:d,wasi_snapshot_preview1:d});t=n.memory,i(t.buffer),Object.assign(r,n),r.UTF8ToString=u}return await f(),r}var MI=Object.defineProperty,NI=(e,t,n)=>t in e?MI(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,K=(e,t,n)=>NI(e,typeof t==`symbol`?t:t+``,n),q=null;function PI(e){throw new DI(e.UTF8ToString(e.getLastOnigError()))}var FI=class e{constructor(t){K(this,`utf16Length`),K(this,`utf8Length`),K(this,`utf16Value`),K(this,`utf8Value`),K(this,`utf16OffsetToUtf8`),K(this,`utf8OffsetToUtf16`);let n=t.length,r=e._utf8ByteLength(t),i=r!==n,a=i?new Uint32Array(n+1):null;i&&(a[n]=r);let o=i?new Uint32Array(r+1):null;i&&(o[r]=n);let s=new Uint8Array(r),c=0;for(let e=0;e<n;e++){let r=t.charCodeAt(e),l=r,u=!1;if(r>=55296&&r<=56319&&e+1<n){let n=t.charCodeAt(e+1);n>=56320&&n<=57343&&(l=(r-55296<<10)+65536|n-56320,u=!0)}i&&(a[e]=c,u&&(a[e+1]=c),l<=127?o[c+0]=e:l<=2047?(o[c+0]=e,o[c+1]=e):l<=65535?(o[c+0]=e,o[c+1]=e,o[c+2]=e):(o[c+0]=e,o[c+1]=e,o[c+2]=e,o[c+3]=e)),l<=127?s[c++]=l:l<=2047?(s[c++]=192|(l&1984)>>>6,s[c++]=128|(l&63)>>>0):l<=65535?(s[c++]=224|(l&61440)>>>12,s[c++]=128|(l&4032)>>>6,s[c++]=128|(l&63)>>>0):(s[c++]=240|(l&1835008)>>>18,s[c++]=128|(l&258048)>>>12,s[c++]=128|(l&4032)>>>6,s[c++]=128|(l&63)>>>0),u&&e++}this.utf16Length=n,this.utf8Length=r,this.utf16Value=t,this.utf8Value=s,this.utf16OffsetToUtf8=a,this.utf8OffsetToUtf16=o}static _utf8ByteLength(e){let t=0;for(let n=0,r=e.length;n<r;n++){let i=e.charCodeAt(n),a=i,o=!1;if(i>=55296&&i<=56319&&n+1<r){let t=e.charCodeAt(n+1);t>=56320&&t<=57343&&(a=(i-55296<<10)+65536|t-56320,o=!0)}t+=a<=127?1:a<=2047?2:a<=65535?3:4,o&&n++}return t}createString(e){let t=e.omalloc(this.utf8Length);return e.HEAPU8.set(this.utf8Value,t),t}},II=class e{constructor(t){if(K(this,`id`,++e.LAST_ID),K(this,`_onigBinding`),K(this,`content`),K(this,`utf16Length`),K(this,`utf8Length`),K(this,`utf16OffsetToUtf8`),K(this,`utf8OffsetToUtf16`),K(this,`ptr`),!q)throw new DI(`Must invoke loadWasm first.`);this._onigBinding=q,this.content=t;let n=new FI(t);this.utf16Length=n.utf16Length,this.utf8Length=n.utf8Length,this.utf16OffsetToUtf8=n.utf16OffsetToUtf8,this.utf8OffsetToUtf16=n.utf8OffsetToUtf16,this.utf8Length<1e4&&!e._sharedPtrInUse?(e._sharedPtr||=q.omalloc(1e4),e._sharedPtrInUse=!0,q.HEAPU8.set(n.utf8Value,e._sharedPtr),this.ptr=e._sharedPtr):this.ptr=n.createString(q)}convertUtf8OffsetToUtf16(e){return this.utf8OffsetToUtf16?e<0?0:e>this.utf8Length?this.utf16Length:this.utf8OffsetToUtf16[e]:e}convertUtf16OffsetToUtf8(e){return this.utf16OffsetToUtf8?e<0?0:e>this.utf16Length?this.utf8Length:this.utf16OffsetToUtf8[e]:e}dispose(){this.ptr===e._sharedPtr?e._sharedPtrInUse=!1:this._onigBinding.ofree(this.ptr)}};K(II,`LAST_ID`,0),K(II,`_sharedPtr`,0),K(II,`_sharedPtrInUse`,!1);var LI=II,RI=class{constructor(e){if(K(this,`_onigBinding`),K(this,`_ptr`),!q)throw new DI(`Must invoke loadWasm first.`);let t=[],n=[];for(let r=0,i=e.length;r<i;r++){let i=new FI(e[r]);t[r]=i.createString(q),n[r]=i.utf8Length}let r=q.omalloc(4*e.length);q.HEAPU32.set(t,r/4);let i=q.omalloc(4*e.length);q.HEAPU32.set(n,i/4);let a=q.createOnigScanner(r,i,e.length);for(let n=0,r=e.length;n<r;n++)q.ofree(t[n]);q.ofree(i),q.ofree(r),a===0&&PI(q),this._onigBinding=q,this._ptr=a}dispose(){this._onigBinding.freeOnigScanner(this._ptr)}findNextMatchSync(e,t,n){let r=0;if(typeof n==`number`&&(r=n),typeof e==`string`){e=new LI(e);let n=this._findNextMatchSync(e,t,!1,r);return e.dispose(),n}return this._findNextMatchSync(e,t,!1,r)}_findNextMatchSync(e,t,n,r){let i=this._onigBinding,a=i.findNextOnigScannerMatch(this._ptr,e.id,e.ptr,e.utf8Length,e.convertUtf16OffsetToUtf8(t),r);if(a===0)return null;let o=i.HEAPU32,s=a/4,c=o[s++],l=o[s++],u=[];for(let t=0;t<l;t++){let n=e.convertUtf8OffsetToUtf16(o[s++]),r=e.convertUtf8OffsetToUtf16(o[s++]);u[t]={start:n,end:r,length:r-n}}return{index:c,captureIndices:u}}};function zI(e){return typeof e.instantiator==`function`}function BI(e){return typeof e.default==`function`}function VI(e){return e.data!==void 0}function HI(e){return typeof Response<`u`&&e instanceof Response}function UI(e){return typeof ArrayBuffer<`u`&&(e instanceof ArrayBuffer||ArrayBuffer.isView(e))||typeof Buffer<`u`&&Buffer.isBuffer?.(e)||typeof SharedArrayBuffer<`u`&&e instanceof SharedArrayBuffer||typeof Uint32Array<`u`&&e instanceof Uint32Array}var WI;function GI(e){if(WI)return WI;async function t(){q=await jI(async t=>{let n=e;return n=await n,typeof n==`function`&&(n=await n(t)),typeof n==`function`&&(n=await n(t)),zI(n)?n=await n.instantiator(t):BI(n)?n=await n.default(t):(VI(n)&&(n=n.data),HI(n)?n=typeof WebAssembly.instantiateStreaming==`function`?await qI(n)(t):await JI(n)(t):UI(n)||n instanceof WebAssembly.Module?n=await KI(n)(t):`default`in n&&n.default instanceof WebAssembly.Module&&(n=await KI(n.default)(t))),`instance`in n&&(n=n.instance),`exports`in n&&(n=n.exports),n})}return WI=t(),WI}function KI(e){return t=>WebAssembly.instantiate(e,t)}function qI(e){return t=>WebAssembly.instantiateStreaming(e,t)}function JI(e){return async t=>{let n=await e.arrayBuffer();return WebAssembly.instantiate(n,t)}}var YI;function XI(e){YI=e}function ZI(){return YI}async function QI(e){return e&&await GI(e),{createScanner(e){return new RI(e.map(e=>typeof e==`string`?e:e.source))},createString(e){return new LI(e)}}}var $I=vI({});bI($I,EI);var J=class extends Error{constructor(e){super(e),this.name=`ShikiError`}};function eL(e){return tL(e)}function tL(e){return Array.isArray(e)?nL(e):e instanceof RegExp?e:typeof e==`object`?rL(e):e}function nL(e){let t=[];for(let n=0,r=e.length;n<r;n++)t[n]=tL(e[n]);return t}function rL(e){let t={};for(let n in e)t[n]=tL(e[n]);return t}function iL(e,...t){return t.forEach(t=>{for(let n in t)e[n]=t[n]}),e}function aL(e){let t=~e.lastIndexOf(`/`)||~e.lastIndexOf(`\\`);return t===0?e:~t===e.length-1?aL(e.substring(0,e.length-1)):e.substr(~t+1)}var oL=/\$(\d+)|\${(\d+):\/(downcase|upcase)}/g,sL=class{static hasCaptures(e){return e!==null&&(oL.lastIndex=0,oL.test(e))}static replaceCaptures(e,t,n){return e.replace(oL,(e,r,i,a)=>{let o=n[parseInt(r||i,10)];if(o){let e=t.substring(o.start,o.end);for(;e[0]===`.`;)e=e.substring(1);switch(a){case`downcase`:return e.toLowerCase();case`upcase`:return e.toUpperCase();default:return e}}else return e})}};function cL(e,t){return e<t?-1:+(e>t)}function lL(e,t){if(e===null&&t===null)return 0;if(!e)return-1;if(!t)return 1;let n=e.length,r=t.length;if(n===r){for(let r=0;r<n;r++){let n=cL(e[r],t[r]);if(n!==0)return n}return 0}return n-r}function uL(e){return!!(/^#[0-9a-f]{6}$/i.test(e)||/^#[0-9a-f]{8}$/i.test(e)||/^#[0-9a-f]{3}$/i.test(e)||/^#[0-9a-f]{4}$/i.test(e))}function dL(e){return e.replace(/[\-\\\{\}\*\+\?\|\^\$\.\,\[\]\(\)\#\s]/g,`\\$&`)}var fL=class{constructor(e){this.fn=e}cache=new Map;get(e){if(this.cache.has(e))return this.cache.get(e);let t=this.fn(e);return this.cache.set(e,t),t}},pL=class{constructor(e,t,n){this._colorMap=e,this._defaults=t,this._root=n}static createFromRawTheme(e,t){return this.createFromParsedTheme(vL(e),t)}static createFromParsedTheme(e,t){return bL(e,t)}_cachedMatchRoot=new fL(e=>this._root.match(e));getColorMap(){return this._colorMap.getColorMap()}getDefaults(){return this._defaults}match(e){if(e===null)return this._defaults;let t=e.scopeName,n=this._cachedMatchRoot.get(t).find(t=>hL(e.parent,t.parentScopes));return n?new _L(n.fontStyle,n.foreground,n.background):null}},mL=class e{constructor(e,t){this.parent=e,this.scopeName=t}static push(t,n){for(let r of n)t=new e(t,r);return t}static from(...t){let n=null;for(let r=0;r<t.length;r++)n=new e(n,t[r]);return n}push(t){return new e(this,t)}getSegments(){let e=this,t=[];for(;e;)t.push(e.scopeName),e=e.parent;return t.reverse(),t}toString(){return this.getSegments().join(` `)}extends(e){return this===e||this.parent!==null&&this.parent.extends(e)}getExtensionIfDefined(e){let t=[],n=this;for(;n&&n!==e;)t.push(n.scopeName),n=n.parent;return n===e?t.reverse():void 0}};function hL(e,t){if(t.length===0)return!0;for(let n=0;n<t.length;n++){let r=t[n],i=!1;if(r===`>`){if(n===t.length-1)return!1;r=t[++n],i=!0}for(;e&&!gL(e.scopeName,r);){if(i)return!1;e=e.parent}if(!e)return!1;e=e.parent}return!0}function gL(e,t){return t===e||e.startsWith(t)&&e[t.length]===`.`}var _L=class{constructor(e,t,n){this.fontStyle=e,this.foregroundId=t,this.backgroundId=n}};function vL(e){if(!e||!e.settings||!Array.isArray(e.settings))return[];let t=e.settings,n=[],r=0;for(let e=0,i=t.length;e<i;e++){let i=t[e];if(!i.settings)continue;let a;if(typeof i.scope==`string`){let e=i.scope;e=e.replace(/^[,]+/,``),e=e.replace(/[,]+$/,``),a=e.split(`,`)}else a=Array.isArray(i.scope)?i.scope:[``];let o=-1;if(typeof i.settings.fontStyle==`string`){o=0;let e=i.settings.fontStyle.split(` `);for(let t=0,n=e.length;t<n;t++)switch(e[t]){case`italic`:o|=1;break;case`bold`:o|=2;break;case`underline`:o|=4;break;case`strikethrough`:o|=8}}let s=null;typeof i.settings.foreground==`string`&&uL(i.settings.foreground)&&(s=i.settings.foreground);let c=null;typeof i.settings.background==`string`&&uL(i.settings.background)&&(c=i.settings.background);for(let t=0,i=a.length;t<i;t++){let i=a[t].trim().split(` `),l=i[i.length-1],u=null;i.length>1&&(u=i.slice(0,i.length-1),u.reverse()),n[r++]=new yL(l,u,e,o,s,c)}}return n}var yL=class{constructor(e,t,n,r,i,a){this.scope=e,this.parentScopes=t,this.index=n,this.fontStyle=r,this.foreground=i,this.background=a}},Y=(e=>(e[e.NotSet=-1]=`NotSet`,e[e.None=0]=`None`,e[e.Italic=1]=`Italic`,e[e.Bold=2]=`Bold`,e[e.Underline=4]=`Underline`,e[e.Strikethrough=8]=`Strikethrough`,e))(Y||{});function bL(e,t){e.sort((e,t)=>{let n=cL(e.scope,t.scope);return n!==0||(n=lL(e.parentScopes,t.parentScopes),n!==0)?n:e.index-t.index});let n=0,r=`#000000`,i=`#ffffff`;for(;e.length>=1&&e[0].scope===``;){let t=e.shift();t.fontStyle!==-1&&(n=t.fontStyle),t.foreground!==null&&(r=t.foreground),t.background!==null&&(i=t.background)}let a=new xL(t),o=new _L(n,a.getId(r),a.getId(i)),s=new wL(new CL(0,null,-1,0,0),[]);for(let t=0,n=e.length;t<n;t++){let n=e[t];s.insert(0,n.scope,n.parentScopes,n.fontStyle,a.getId(n.foreground),a.getId(n.background))}return new pL(a,o,s)}var xL=class{_isFrozen;_lastColorId;_id2color;_color2id;constructor(e){if(this._lastColorId=0,this._id2color=[],this._color2id=Object.create(null),Array.isArray(e)){this._isFrozen=!0;for(let t=0,n=e.length;t<n;t++)this._color2id[e[t]]=t,this._id2color[t]=e[t]}else this._isFrozen=!1}getId(e){if(e===null)return 0;e=e.toUpperCase();let t=this._color2id[e];if(t)return t;if(this._isFrozen)throw Error(`Missing color in color map - ${e}`);return t=++this._lastColorId,this._color2id[e]=t,this._id2color[t]=e,t}getColorMap(){return this._id2color.slice(0)}},SL=Object.freeze([]),CL=class e{scopeDepth;parentScopes;fontStyle;foreground;background;constructor(e,t,n,r,i){this.scopeDepth=e,this.parentScopes=t||SL,this.fontStyle=n,this.foreground=r,this.background=i}clone(){return new e(this.scopeDepth,this.parentScopes,this.fontStyle,this.foreground,this.background)}static cloneArr(e){let t=[];for(let n=0,r=e.length;n<r;n++)t[n]=e[n].clone();return t}acceptOverwrite(e,t,n,r){this.scopeDepth>e?console.log(`how did this happen?`):this.scopeDepth=e,t!==-1&&(this.fontStyle=t),n!==0&&(this.foreground=n),r!==0&&(this.background=r)}},wL=class e{constructor(e,t=[],n={}){this._mainRule=e,this._children=n,this._rulesWithParentScopes=t}_rulesWithParentScopes;static _cmpBySpecificity(e,t){if(e.scopeDepth!==t.scopeDepth)return t.scopeDepth-e.scopeDepth;let n=0,r=0;for(;e.parentScopes[n]===`>`&&n++,t.parentScopes[r]===`>`&&r++,!(n>=e.parentScopes.length||r>=t.parentScopes.length);){let i=t.parentScopes[r].length-e.parentScopes[n].length;if(i!==0)return i;n++,r++}return t.parentScopes.length-e.parentScopes.length}match(t){if(t!==``){let e=t.indexOf(`.`),n,r;if(e===-1?(n=t,r=``):(n=t.substring(0,e),r=t.substring(e+1)),this._children.hasOwnProperty(n))return this._children[n].match(r)}let n=this._rulesWithParentScopes.concat(this._mainRule);return n.sort(e._cmpBySpecificity),n}insert(t,n,r,i,a,o){if(n===``){this._doInsertHere(t,r,i,a,o);return}let s=n.indexOf(`.`),c,l;s===-1?(c=n,l=``):(c=n.substring(0,s),l=n.substring(s+1));let u;this._children.hasOwnProperty(c)?u=this._children[c]:(u=new e(this._mainRule.clone(),CL.cloneArr(this._rulesWithParentScopes)),this._children[c]=u),u.insert(t+1,l,r,i,a,o)}_doInsertHere(e,t,n,r,i){if(t===null){this._mainRule.acceptOverwrite(e,n,r,i);return}for(let a=0,o=this._rulesWithParentScopes.length;a<o;a++){let o=this._rulesWithParentScopes[a];if(lL(o.parentScopes,t)===0){o.acceptOverwrite(e,n,r,i);return}}n===-1&&(n=this._mainRule.fontStyle),r===0&&(r=this._mainRule.foreground),i===0&&(i=this._mainRule.background),this._rulesWithParentScopes.push(new CL(e,t,n,r,i))}},TL=class e{static toBinaryStr(e){return e.toString(2).padStart(32,`0`)}static print(t){let n=e.getLanguageId(t),r=e.getTokenType(t),i=e.getFontStyle(t),a=e.getForeground(t),o=e.getBackground(t);console.log({languageId:n,tokenType:r,fontStyle:i,foreground:a,background:o})}static getLanguageId(e){return(e&255)>>>0}static getTokenType(e){return(e&768)>>>8}static containsBalancedBrackets(e){return!!(e&1024)}static getFontStyle(e){return(e&30720)>>>11}static getForeground(e){return(e&16744448)>>>15}static getBackground(e){return(e&4278190080)>>>24}static set(t,n,r,i,a,o,s){let c=e.getLanguageId(t),l=e.getTokenType(t),u=+!!e.containsBalancedBrackets(t),d=e.getFontStyle(t),f=e.getForeground(t),p=e.getBackground(t);return n!==0&&(c=n),r!==8&&(l=DL(r)),i!==null&&(u=+!!i),a!==-1&&(d=a),o!==0&&(f=o),s!==0&&(p=s),(c<<0|l<<8|u<<10|d<<11|f<<15|p<<24)>>>0}};function EL(e){return e}function DL(e){return e}function OL(e,t){let n=[],r=AL(e),i=r.next();for(;i!==null;){let e=0;if(i.length===2&&i.charAt(1)===`:`){switch(i.charAt(0)){case`R`:e=1;break;case`L`:e=-1;break;default:console.log(`Unknown priority ${i} in scope selector`)}i=r.next()}let t=o();if(n.push({matcher:t,priority:e}),i!==`,`)break;i=r.next()}return n;function a(){if(i===`-`){i=r.next();let e=a();return t=>!!e&&!e(t)}if(i===`(`){i=r.next();let e=s();return i===`)`&&(i=r.next()),e}if(kL(i)){let e=[];do e.push(i),i=r.next();while(kL(i));return n=>t(e,n)}return null}function o(){let e=[],t=a();for(;t;)e.push(t),t=a();return t=>e.every(e=>e(t))}function s(){let e=[],t=o();for(;t&&(e.push(t),i===`|`||i===`,`);){do i=r.next();while(i===`|`||i===`,`);t=o()}return t=>e.some(e=>e(t))}}function kL(e){return!!e&&!!e.match(/[\w\.:]+/)}function AL(e){let t=/([LR]:|[\w\.:][\w\.:\-]*|[\,\|\-\(\)])/g,n=t.exec(e);return{next:()=>{if(!n)return null;let r=n[0];return n=t.exec(e),r}}}function jL(e){typeof e.dispose==`function`&&e.dispose()}var ML=class{constructor(e){this.scopeName=e}toKey(){return this.scopeName}},NL=class{constructor(e,t){this.scopeName=e,this.ruleName=t}toKey(){return`${this.scopeName}#${this.ruleName}`}},PL=class{_references=[];_seenReferenceKeys=new Set;get references(){return this._references}visitedRule=new Set;add(e){let t=e.toKey();this._seenReferenceKeys.has(t)||(this._seenReferenceKeys.add(t),this._references.push(e))}},FL=class{constructor(e,t){this.repo=e,this.initialScopeName=t,this.seenFullScopeRequests.add(this.initialScopeName),this.Q=[new ML(this.initialScopeName)]}seenFullScopeRequests=new Set;seenPartialScopeRequests=new Set;Q;processQueue(){let e=this.Q;this.Q=[];let t=new PL;for(let n of e)IL(n,this.initialScopeName,this.repo,t);for(let e of t.references)if(e instanceof ML){if(this.seenFullScopeRequests.has(e.scopeName))continue;this.seenFullScopeRequests.add(e.scopeName),this.Q.push(e)}else{if(this.seenFullScopeRequests.has(e.scopeName)||this.seenPartialScopeRequests.has(e.toKey()))continue;this.seenPartialScopeRequests.add(e.toKey()),this.Q.push(e)}}};function IL(e,t,n,r){let i=n.lookup(e.scopeName);if(!i){if(e.scopeName===t)throw Error(`No grammar provided for <${t}>`);return}let a=n.lookup(t);e instanceof ML?RL({baseGrammar:a,selfGrammar:i},r):LL(e.ruleName,{baseGrammar:a,selfGrammar:i,repository:i.repository},r);let o=n.injections(e.scopeName);if(o)for(let e of o)r.add(new ML(e))}function LL(e,t,n){if(t.repository&&t.repository[e]){let r=t.repository[e];zL([r],t,n)}}function RL(e,t){e.selfGrammar.patterns&&Array.isArray(e.selfGrammar.patterns)&&zL(e.selfGrammar.patterns,{...e,repository:e.selfGrammar.repository},t),e.selfGrammar.injections&&zL(Object.values(e.selfGrammar.injections),{...e,repository:e.selfGrammar.repository},t)}function zL(e,t,n){for(let r of e){if(n.visitedRule.has(r))continue;n.visitedRule.add(r);let e=r.repository?iL({},t.repository,r.repository):t.repository;Array.isArray(r.patterns)&&zL(r.patterns,{...t,repository:e},n);let i=r.include;if(!i)continue;let a=GL(i);switch(a.kind){case 0:RL({...t,selfGrammar:t.baseGrammar},n);break;case 1:RL(t,n);break;case 2:LL(a.ruleName,{...t,repository:e},n);break;case 3:case 4:let r=a.scopeName===t.selfGrammar.scopeName?t.selfGrammar:a.scopeName===t.baseGrammar.scopeName?t.baseGrammar:void 0;if(r){let i={baseGrammar:t.baseGrammar,selfGrammar:r,repository:e};a.kind===4?LL(a.ruleName,i,n):RL(i,n)}else a.kind===4?n.add(new NL(a.scopeName,a.ruleName)):n.add(new ML(a.scopeName))}}}var BL=class{kind=0},VL=class{kind=1},HL=class{constructor(e){this.ruleName=e}kind=2},UL=class{constructor(e){this.scopeName=e}kind=3},WL=class{constructor(e,t){this.scopeName=e,this.ruleName=t}kind=4};function GL(e){if(e===`$base`)return new BL;if(e===`$self`)return new VL;let t=e.indexOf(`#`);return t===-1?new UL(e):t===0?new HL(e.substring(1)):new WL(e.substring(0,t),e.substring(t+1))}var KL=/\\(\d+)/,qL=/\\(\d+)/g,JL=-1,YL=-2;function XL(e){return e}function ZL(e){return e}var QL=class{$location;id;_nameIsCapturing;_name;_contentNameIsCapturing;_contentName;constructor(e,t,n,r){this.$location=e,this.id=t,this._name=n||null,this._nameIsCapturing=sL.hasCaptures(this._name),this._contentName=r||null,this._contentNameIsCapturing=sL.hasCaptures(this._contentName)}get debugName(){let e=this.$location?`${aL(this.$location.filename)}:${this.$location.line}`:`unknown`;return`${this.constructor.name}#${this.id} @ ${e}`}getName(e,t){return!this._nameIsCapturing||this._name===null||e===null||t===null?this._name:sL.replaceCaptures(this._name,e,t)}getContentName(e,t){return!this._contentNameIsCapturing||this._contentName===null?this._contentName:sL.replaceCaptures(this._contentName,e,t)}},$L=class extends QL{retokenizeCapturedWithRuleId;constructor(e,t,n,r,i){super(e,t,n,r),this.retokenizeCapturedWithRuleId=i}dispose(){}collectPatterns(e,t){throw Error(`Not supported!`)}compile(e,t){throw Error(`Not supported!`)}compileAG(e,t,n,r){throw Error(`Not supported!`)}},eR=class extends QL{_match;captures;_cachedCompiledPatterns;constructor(e,t,n,r,i){super(e,t,n,null),this._match=new aR(r,this.id),this.captures=i,this._cachedCompiledPatterns=null}dispose(){this._cachedCompiledPatterns&&=(this._cachedCompiledPatterns.dispose(),null)}get debugMatchRegExp(){return`${this._match.source}`}collectPatterns(e,t){t.push(this._match)}compile(e,t){return this._getCachedCompiledPatterns(e).compile(e)}compileAG(e,t,n,r){return this._getCachedCompiledPatterns(e).compileAG(e,n,r)}_getCachedCompiledPatterns(e){return this._cachedCompiledPatterns||(this._cachedCompiledPatterns=new oR,this.collectPatterns(e,this._cachedCompiledPatterns)),this._cachedCompiledPatterns}},tR=class extends QL{hasMissingPatterns;patterns;_cachedCompiledPatterns;constructor(e,t,n,r,i){super(e,t,n,r),this.patterns=i.patterns,this.hasMissingPatterns=i.hasMissingPatterns,this._cachedCompiledPatterns=null}dispose(){this._cachedCompiledPatterns&&=(this._cachedCompiledPatterns.dispose(),null)}collectPatterns(e,t){for(let n of this.patterns)e.getRule(n).collectPatterns(e,t)}compile(e,t){return this._getCachedCompiledPatterns(e).compile(e)}compileAG(e,t,n,r){return this._getCachedCompiledPatterns(e).compileAG(e,n,r)}_getCachedCompiledPatterns(e){return this._cachedCompiledPatterns||(this._cachedCompiledPatterns=new oR,this.collectPatterns(e,this._cachedCompiledPatterns)),this._cachedCompiledPatterns}},nR=class extends QL{_begin;beginCaptures;_end;endHasBackReferences;endCaptures;applyEndPatternLast;hasMissingPatterns;patterns;_cachedCompiledPatterns;constructor(e,t,n,r,i,a,o,s,c,l){super(e,t,n,r),this._begin=new aR(i,this.id),this.beginCaptures=a,this._end=new aR(o||``,-1),this.endHasBackReferences=this._end.hasBackReferences,this.endCaptures=s,this.applyEndPatternLast=c||!1,this.patterns=l.patterns,this.hasMissingPatterns=l.hasMissingPatterns,this._cachedCompiledPatterns=null}dispose(){this._cachedCompiledPatterns&&=(this._cachedCompiledPatterns.dispose(),null)}get debugBeginRegExp(){return`${this._begin.source}`}get debugEndRegExp(){return`${this._end.source}`}getEndWithResolvedBackReferences(e,t){return this._end.resolveBackReferences(e,t)}collectPatterns(e,t){t.push(this._begin)}compile(e,t){return this._getCachedCompiledPatterns(e,t).compile(e)}compileAG(e,t,n,r){return this._getCachedCompiledPatterns(e,t).compileAG(e,n,r)}_getCachedCompiledPatterns(e,t){if(!this._cachedCompiledPatterns){this._cachedCompiledPatterns=new oR;for(let t of this.patterns)e.getRule(t).collectPatterns(e,this._cachedCompiledPatterns);this.applyEndPatternLast?this._cachedCompiledPatterns.push(this._end.hasBackReferences?this._end.clone():this._end):this._cachedCompiledPatterns.unshift(this._end.hasBackReferences?this._end.clone():this._end)}return this._end.hasBackReferences&&(this.applyEndPatternLast?this._cachedCompiledPatterns.setSource(this._cachedCompiledPatterns.length()-1,t):this._cachedCompiledPatterns.setSource(0,t)),this._cachedCompiledPatterns}},rR=class extends QL{_begin;beginCaptures;whileCaptures;_while;whileHasBackReferences;hasMissingPatterns;patterns;_cachedCompiledPatterns;_cachedCompiledWhilePatterns;constructor(e,t,n,r,i,a,o,s,c){super(e,t,n,r),this._begin=new aR(i,this.id),this.beginCaptures=a,this.whileCaptures=s,this._while=new aR(o,YL),this.whileHasBackReferences=this._while.hasBackReferences,this.patterns=c.patterns,this.hasMissingPatterns=c.hasMissingPatterns,this._cachedCompiledPatterns=null,this._cachedCompiledWhilePatterns=null}dispose(){this._cachedCompiledPatterns&&=(this._cachedCompiledPatterns.dispose(),null),this._cachedCompiledWhilePatterns&&=(this._cachedCompiledWhilePatterns.dispose(),null)}get debugBeginRegExp(){return`${this._begin.source}`}get debugWhileRegExp(){return`${this._while.source}`}getWhileWithResolvedBackReferences(e,t){return this._while.resolveBackReferences(e,t)}collectPatterns(e,t){t.push(this._begin)}compile(e,t){return this._getCachedCompiledPatterns(e).compile(e)}compileAG(e,t,n,r){return this._getCachedCompiledPatterns(e).compileAG(e,n,r)}_getCachedCompiledPatterns(e){if(!this._cachedCompiledPatterns){this._cachedCompiledPatterns=new oR;for(let t of this.patterns)e.getRule(t).collectPatterns(e,this._cachedCompiledPatterns)}return this._cachedCompiledPatterns}compileWhile(e,t){return this._getCachedCompiledWhilePatterns(e,t).compile(e)}compileWhileAG(e,t,n,r){return this._getCachedCompiledWhilePatterns(e,t).compileAG(e,n,r)}_getCachedCompiledWhilePatterns(e,t){return this._cachedCompiledWhilePatterns||(this._cachedCompiledWhilePatterns=new oR,this._cachedCompiledWhilePatterns.push(this._while.hasBackReferences?this._while.clone():this._while)),this._while.hasBackReferences&&this._cachedCompiledWhilePatterns.setSource(0,t||``),this._cachedCompiledWhilePatterns}},iR=class e{static createCaptureRule(e,t,n,r,i){return e.registerRule(e=>new $L(t,e,n,r,i))}static getCompiledRuleId(t,n,r){return t.id||n.registerRule(i=>{if(t.id=i,t.match)return new eR(t.$vscodeTextmateLocation,t.id,t.name,t.match,e._compileCaptures(t.captures,n,r));if(t.begin===void 0){t.repository&&(r=iL({},r,t.repository));let i=t.patterns;return i===void 0&&t.include&&(i=[{include:t.include}]),new tR(t.$vscodeTextmateLocation,t.id,t.name,t.contentName,e._compilePatterns(i,n,r))}return t.while?new rR(t.$vscodeTextmateLocation,t.id,t.name,t.contentName,t.begin,e._compileCaptures(t.beginCaptures||t.captures,n,r),t.while,e._compileCaptures(t.whileCaptures||t.captures,n,r),e._compilePatterns(t.patterns,n,r)):new nR(t.$vscodeTextmateLocation,t.id,t.name,t.contentName,t.begin,e._compileCaptures(t.beginCaptures||t.captures,n,r),t.end,e._compileCaptures(t.endCaptures||t.captures,n,r),t.applyEndPatternLast,e._compilePatterns(t.patterns,n,r))}),t.id}static _compileCaptures(t,n,r){let i=[];if(t){let a=0;for(let e in t){if(e===`$vscodeTextmateLocation`)continue;let t=parseInt(e,10);t>a&&(a=t)}for(let e=0;e<=a;e++)i[e]=null;for(let a in t){if(a===`$vscodeTextmateLocation`)continue;let o=parseInt(a,10),s=0;t[a].patterns&&(s=e.getCompiledRuleId(t[a],n,r)),i[o]=e.createCaptureRule(n,t[a].$vscodeTextmateLocation,t[a].name,t[a].contentName,s)}}return i}static _compilePatterns(t,n,r){let i=[];if(t)for(let a=0,o=t.length;a<o;a++){let o=t[a],s=-1;if(o.include){let t=GL(o.include);switch(t.kind){case 0:case 1:s=e.getCompiledRuleId(r[o.include],n,r);break;case 2:let i=r[t.ruleName];i&&(s=e.getCompiledRuleId(i,n,r));break;case 3:case 4:let a=t.scopeName,c=t.kind===4?t.ruleName:null,l=n.getExternalGrammar(a,r);if(l)if(c){let t=l.repository[c];t&&(s=e.getCompiledRuleId(t,n,l.repository))}else s=e.getCompiledRuleId(l.repository.$self,n,l.repository)}}else s=e.getCompiledRuleId(o,n,r);if(s!==-1){let e=n.getRule(s),t=!1;if((e instanceof tR||e instanceof nR||e instanceof rR)&&e.hasMissingPatterns&&e.patterns.length===0&&(t=!0),t)continue;i.push(s)}}return{patterns:i,hasMissingPatterns:(t?t.length:0)!==i.length}}},aR=class e{source;ruleId;hasAnchor;hasBackReferences;_anchorCache;constructor(e,t){if(e&&typeof e==`string`){let t=e.length,n=0,r=[],i=!1;for(let a=0;a<t;a++)if(e.charAt(a)===`\\`&&a+1<t){let t=e.charAt(a+1);t===`z`?(r.push(e.substring(n,a)),r.push(`$(?!\\n)(?<!\\n)`),n=a+2):(t===`A`||t===`G`)&&(i=!0),a++}this.hasAnchor=i,n===0?this.source=e:(r.push(e.substring(n,t)),this.source=r.join(``))}else this.hasAnchor=!1,this.source=e;this._anchorCache=this.hasAnchor?this._buildAnchorCache():null,this.ruleId=t,this.hasBackReferences=typeof this.source==`string`&&KL.test(this.source)}clone(){return new e(this.source,this.ruleId)}setSource(e){this.source!==e&&(this.source=e,this.hasAnchor&&(this._anchorCache=this._buildAnchorCache()))}resolveBackReferences(e,t){if(typeof this.source!=`string`)throw Error(`This method should only be called if the source is a string`);let n=t.map(t=>e.substring(t.start,t.end));return qL.lastIndex=0,this.source.replace(qL,(e,t)=>dL(n[parseInt(t,10)]||``))}_buildAnchorCache(){if(typeof this.source!=`string`)throw Error(`This method should only be called if the source is a string`);let e=[],t=[],n=[],r=[],i,a,o,s;for(i=0,a=this.source.length;i<a;i++)o=this.source.charAt(i),e[i]=o,t[i]=o,n[i]=o,r[i]=o,o===`\\`&&i+1<a&&(s=this.source.charAt(i+1),s===`A`?(e[i+1]=``,t[i+1]=``,n[i+1]=`A`,r[i+1]=`A`):s===`G`?(e[i+1]=``,t[i+1]=`G`,n[i+1]=``,r[i+1]=`G`):(e[i+1]=s,t[i+1]=s,n[i+1]=s,r[i+1]=s),i++);return{A0_G0:e.join(``),A0_G1:t.join(``),A1_G0:n.join(``),A1_G1:r.join(``)}}resolveAnchors(e,t){return!this.hasAnchor||!this._anchorCache||typeof this.source!=`string`?this.source:e?t?this._anchorCache.A1_G1:this._anchorCache.A1_G0:t?this._anchorCache.A0_G1:this._anchorCache.A0_G0}},oR=class{_items;_hasAnchors;_cached;_anchorCache;constructor(){this._items=[],this._hasAnchors=!1,this._cached=null,this._anchorCache={A0_G0:null,A0_G1:null,A1_G0:null,A1_G1:null}}dispose(){this._disposeCaches()}_disposeCaches(){this._cached&&=(this._cached.dispose(),null),this._anchorCache.A0_G0&&(this._anchorCache.A0_G0.dispose(),this._anchorCache.A0_G0=null),this._anchorCache.A0_G1&&(this._anchorCache.A0_G1.dispose(),this._anchorCache.A0_G1=null),this._anchorCache.A1_G0&&(this._anchorCache.A1_G0.dispose(),this._anchorCache.A1_G0=null),this._anchorCache.A1_G1&&(this._anchorCache.A1_G1.dispose(),this._anchorCache.A1_G1=null)}push(e){this._items.push(e),this._hasAnchors=this._hasAnchors||e.hasAnchor}unshift(e){this._items.unshift(e),this._hasAnchors=this._hasAnchors||e.hasAnchor}length(){return this._items.length}setSource(e,t){this._items[e].source!==t&&(this._disposeCaches(),this._items[e].setSource(t))}compile(e){if(!this._cached){let t=this._items.map(e=>e.source);this._cached=new sR(e,t,this._items.map(e=>e.ruleId))}return this._cached}compileAG(e,t,n){return this._hasAnchors?t?n?(this._anchorCache.A1_G1||(this._anchorCache.A1_G1=this._resolveAnchors(e,t,n)),this._anchorCache.A1_G1):(this._anchorCache.A1_G0||(this._anchorCache.A1_G0=this._resolveAnchors(e,t,n)),this._anchorCache.A1_G0):n?(this._anchorCache.A0_G1||(this._anchorCache.A0_G1=this._resolveAnchors(e,t,n)),this._anchorCache.A0_G1):(this._anchorCache.A0_G0||(this._anchorCache.A0_G0=this._resolveAnchors(e,t,n)),this._anchorCache.A0_G0):this.compile(e)}_resolveAnchors(e,t,n){return new sR(e,this._items.map(e=>e.resolveAnchors(t,n)),this._items.map(e=>e.ruleId))}},sR=class{constructor(e,t,n){this.regExps=t,this.rules=n,this.scanner=e.createOnigScanner(t)}scanner;dispose(){typeof this.scanner.dispose==`function`&&this.scanner.dispose()}toString(){let e=[];for(let t=0,n=this.rules.length;t<n;t++)e.push(` - `+this.rules[t]+`: `+this.regExps[t]);return e.join(`
|
|
42
|
-
`)}findNextMatchSync(e,t,n){let r=this.scanner.findNextMatchSync(e,t,n);return r?{ruleId:this.rules[r.index],captureIndices:r.captureIndices}:null}},
|
|
43
|
-
`;let a=this.createOnigString(e),o=a.content.length,s=new AR(n,e,this._tokenTypeMatchers,this.balancedBracketSelectors),c=fR(this,a,i,0,t,s,!0,r);return jL(a),{lineLength:o,lineTokens:s,ruleStack:c.stack,stoppedEarly:c.stoppedEarly}}};function ER(e,t){return e=eL(e),e.repository=e.repository||{},e.repository.$self={$vscodeTextmateLocation:e.$vscodeTextmateLocation,patterns:e.patterns,name:e.scopeName},e.repository.$base=t||e.repository.$self,e}var DR=class e{constructor(e,t,n){this.parent=e,this.scopePath=t,this.tokenAttributes=n}static fromExtension(t,n){let r=t,i=t?.scopePath??null;for(let t of n)i=mL.push(i,t.scopeNames),r=new e(r,i,t.encodedTokenAttributes);return r}static createRoot(t,n){return new e(null,new mL(null,t),n)}static createRootAndLookUpScopeName(t,n,r){let i=r.getMetadataForScope(t),a=new mL(null,t),o=r.themeProvider.themeMatch(a),s=e.mergeAttributes(n,i,o);return new e(null,a,s)}get scopeName(){return this.scopePath.scopeName}toString(){return this.getScopeNames().join(` `)}equals(t){return e.equals(this,t)}static equals(e,t){do{if(e===t||!e&&!t)return!0;if(!e||!t||e.scopeName!==t.scopeName||e.tokenAttributes!==t.tokenAttributes)return!1;e=e.parent,t=t.parent}while(!0)}static mergeAttributes(e,t,n){let r=-1,i=0,a=0;return n!==null&&(r=n.fontStyle,i=n.foregroundId,a=n.backgroundId),TL.set(e,t.languageId,t.tokenType,null,r,i,a)}pushAttributed(t,n){if(t===null)return this;if(t.indexOf(` `)===-1)return e._pushAttributed(this,t,n);let r=t.split(/ /g),i=this;for(let t of r)i=e._pushAttributed(i,t,n);return i}static _pushAttributed(t,n,r){let i=r.getMetadataForScope(n),a=t.scopePath.push(n),o=r.themeProvider.themeMatch(a),s=e.mergeAttributes(t.tokenAttributes,i,o);return new e(t,a,s)}getScopeNames(){return this.scopePath.getSegments()}getExtensionIfDefined(e){let t=[],n=this;for(;n&&n!==e;)t.push({encodedTokenAttributes:n.tokenAttributes,scopeNames:n.scopePath.getExtensionIfDefined(n.parent?.scopePath??null)}),n=n.parent;return n===e?t.reverse():void 0}},OR=class e{constructor(e,t,n,r,i,a,o,s){this.parent=e,this.ruleId=t,this.beginRuleCapturedEOL=i,this.endRule=a,this.nameScopesList=o,this.contentNameScopesList=s,this.depth=this.parent?this.parent.depth+1:1,this._enterPos=n,this._anchorPos=r}_stackElementBrand=void 0;static NULL=new e(null,0,0,0,!1,null,null,null);_enterPos;_anchorPos;depth;equals(t){return t!==null&&e._equals(this,t)}static _equals(e,t){return e===t?!0:this._structuralEquals(e,t)?DR.equals(e.contentNameScopesList,t.contentNameScopesList):!1}static _structuralEquals(e,t){do{if(e===t||!e&&!t)return!0;if(!e||!t||e.depth!==t.depth||e.ruleId!==t.ruleId||e.endRule!==t.endRule)return!1;e=e.parent,t=t.parent}while(!0)}clone(){return this}static _reset(e){for(;e;)e._enterPos=-1,e._anchorPos=-1,e=e.parent}reset(){e._reset(this)}pop(){return this.parent}safePop(){return this.parent?this.parent:this}push(t,n,r,i,a,o,s){return new e(this,t,n,r,i,a,o,s)}getEnterPos(){return this._enterPos}getAnchorPos(){return this._anchorPos}getRule(e){return e.getRule(this.ruleId)}toString(){let e=[];return this._writeString(e,0),`[`+e.join(`,`)+`]`}_writeString(e,t){return this.parent&&(t=this.parent._writeString(e,t)),e[t++]=`(${this.ruleId}, ${this.nameScopesList?.toString()}, ${this.contentNameScopesList?.toString()})`,t}withContentNameScopesList(e){return this.contentNameScopesList===e?this:this.parent.push(this.ruleId,this._enterPos,this._anchorPos,this.beginRuleCapturedEOL,this.endRule,this.nameScopesList,e)}withEndRule(t){return this.endRule===t?this:new e(this.parent,this.ruleId,this._enterPos,this._anchorPos,this.beginRuleCapturedEOL,t,this.nameScopesList,this.contentNameScopesList)}hasSameRuleAs(e){let t=this;for(;t&&t._enterPos===e._enterPos;){if(t.ruleId===e.ruleId)return!0;t=t.parent}return!1}toStateStackFrame(){return{ruleId:ZL(this.ruleId),beginRuleCapturedEOL:this.beginRuleCapturedEOL,endRule:this.endRule,nameScopesList:this.nameScopesList?.getExtensionIfDefined(this.parent?.nameScopesList??null)??[],contentNameScopesList:this.contentNameScopesList?.getExtensionIfDefined(this.nameScopesList)??[]}}static pushFrame(t,n){let r=DR.fromExtension(t?.nameScopesList??null,n.nameScopesList);return new e(t,XL(n.ruleId),n.enterPos??-1,n.anchorPos??-1,n.beginRuleCapturedEOL,n.endRule,r,DR.fromExtension(r,n.contentNameScopesList))}},kR=class{balancedBracketScopes;unbalancedBracketScopes;allowAny=!1;constructor(e,t){this.balancedBracketScopes=e.flatMap(e=>e===`*`?(this.allowAny=!0,[]):OL(e,CR).map(e=>e.matcher)),this.unbalancedBracketScopes=t.flatMap(e=>OL(e,CR).map(e=>e.matcher))}get matchesAlways(){return this.allowAny&&this.unbalancedBracketScopes.length===0}get matchesNever(){return this.balancedBracketScopes.length===0&&!this.allowAny}match(e){for(let t of this.unbalancedBracketScopes)if(t(e))return!1;for(let t of this.balancedBracketScopes)if(t(e))return!0;return this.allowAny}},AR=class{constructor(e,t,n,r){this.balancedBracketSelectors=r,this._emitBinaryTokens=e,this._tokenTypeOverrides=n,this._lineText=null,this._tokens=[],this._binaryTokens=[],this._lastTokenEndIndex=0}_emitBinaryTokens;_lineText;_tokens;_binaryTokens;_lastTokenEndIndex;_tokenTypeOverrides;produce(e,t){this.produceFromScopes(e.contentNameScopesList,t)}produceFromScopes(e,t){if(this._lastTokenEndIndex>=t)return;if(this._emitBinaryTokens){let n=e?.tokenAttributes??0,r=!1;if(this.balancedBracketSelectors?.matchesAlways&&(r=!0),this._tokenTypeOverrides.length>0||this.balancedBracketSelectors&&!this.balancedBracketSelectors.matchesAlways&&!this.balancedBracketSelectors.matchesNever){let t=e?.getScopeNames()??[];for(let e of this._tokenTypeOverrides)e.matcher(t)&&(n=TL.set(n,0,EL(e.type),null,-1,0,0));this.balancedBracketSelectors&&(r=this.balancedBracketSelectors.match(t))}if(r&&(n=TL.set(n,0,8,r,-1,0,0)),this._binaryTokens.length>0&&this._binaryTokens[this._binaryTokens.length-1]===n){this._lastTokenEndIndex=t;return}this._binaryTokens.push(this._lastTokenEndIndex),this._binaryTokens.push(n),this._lastTokenEndIndex=t;return}let n=e?.getScopeNames()??[];this._tokens.push({startIndex:this._lastTokenEndIndex,endIndex:t,scopes:n}),this._lastTokenEndIndex=t}getResult(e,t){return this._tokens.length>0&&this._tokens[this._tokens.length-1].startIndex===t-1&&this._tokens.pop(),this._tokens.length===0&&(this._lastTokenEndIndex=-1,this.produce(e,t),this._tokens[this._tokens.length-1].startIndex=0),this._tokens}getBinaryResult(e,t){this._binaryTokens.length>0&&this._binaryTokens[this._binaryTokens.length-2]===t-1&&(this._binaryTokens.pop(),this._binaryTokens.pop()),this._binaryTokens.length===0&&(this._lastTokenEndIndex=-1,this.produce(e,t),this._binaryTokens[this._binaryTokens.length-2]=0);let n=new Uint32Array(this._binaryTokens.length);for(let e=0,t=this._binaryTokens.length;e<t;e++)n[e]=this._binaryTokens[e];return n}},jR=class{constructor(e,t){this._onigLib=t,this._theme=e}_grammars=new Map;_rawGrammars=new Map;_injectionGrammars=new Map;_theme;dispose(){for(let e of this._grammars.values())e.dispose()}setTheme(e){this._theme=e}getColorMap(){return this._theme.getColorMap()}addGrammar(e,t){this._rawGrammars.set(e.scopeName,e),t&&this._injectionGrammars.set(e.scopeName,t)}lookup(e){return this._rawGrammars.get(e)}injections(e){return this._injectionGrammars.get(e)}getDefaults(){return this._theme.getDefaults()}themeMatch(e){return this._theme.match(e)}grammarForScopeName(e,t,n,r,i){if(!this._grammars.has(e)){let a=this._rawGrammars.get(e);if(!a)return null;this._grammars.set(e,xR(e,a,t,n,r,i,this,this._onigLib))}return this._grammars.get(e)}},MR=class{_options;_syncRegistry;_ensureGrammarCache;constructor(e){this._options=e,this._syncRegistry=new jR(pL.createFromRawTheme(e.theme,e.colorMap),e.onigLib),this._ensureGrammarCache=new Map}dispose(){this._syncRegistry.dispose()}setTheme(e,t){this._syncRegistry.setTheme(pL.createFromRawTheme(e,t))}getColorMap(){return this._syncRegistry.getColorMap()}loadGrammarWithEmbeddedLanguages(e,t,n){return this.loadGrammarWithConfiguration(e,t,{embeddedLanguages:n})}loadGrammarWithConfiguration(e,t,n){return this._loadGrammar(e,t,n.embeddedLanguages,n.tokenTypes,new kR(n.balancedBracketSelectors||[],n.unbalancedBracketSelectors||[]))}loadGrammar(e){return this._loadGrammar(e,0,null,null,null)}_loadGrammar(e,t,n,r,i){let a=new FL(this._syncRegistry,e);for(;a.Q.length>0;)a.Q.map(e=>this._loadSingleGrammar(e.scopeName)),a.processQueue();return this._grammarForScopeName(e,t,n,r,i)}_loadSingleGrammar(e){this._ensureGrammarCache.has(e)||(this._doLoadSingleGrammar(e),this._ensureGrammarCache.set(e,!0))}_doLoadSingleGrammar(e){let t=this._options.loadGrammar(e);if(t){let n=typeof this._options.getInjections==`function`?this._options.getInjections(e):void 0;this._syncRegistry.addGrammar(t,n)}}addGrammar(e,t=[],n=0,r=null){return this._syncRegistry.addGrammar(e,t),this._grammarForScopeName(e.scopeName,n,r)}_grammarForScopeName(e,t=0,n=null,r=null,i=null){return this._syncRegistry.grammarForScopeName(e,t,n,r,i)}},NR=OR.NULL;function PR(e,t){let n=typeof e==`string`?{}:{...e.colorReplacements},r=typeof e==`string`?e:e.name;for(let[e,i]of Object.entries(t?.colorReplacements||{}))typeof i==`string`?n[e]=i:e===r&&Object.assign(n,i);return n}function FR(e,t){return e&&(t?.[e?.toLowerCase()]||e)}function IR(e){return Array.isArray(e)?e:[e]}async function LR(e){return Promise.resolve(typeof e==`function`?e():e).then(e=>e.default||e)}function RR(e){return!e||[`plaintext`,`txt`,`text`,`plain`].includes(e)}function zR(e){return e===`ansi`||RR(e)}function BR(e){return e===`none`}function VR(e){return BR(e)}function HR(e,t=!1){if(e.length===0)return[[``,0]];let n=e.split(/(\r?\n)/g),r=0,i=[];for(let e=0;e<n.length;e+=2){let a=t?n[e]+(n[e+1]||``):n[e];i.push([a,r]),r+=n[e].length,r+=n[e+1]?.length||0}return i}var UR={light:`#333333`,dark:`#bbbbbb`},WR={light:`#fffffe`,dark:`#1e1e1e`},GR=`__shiki_resolved`;function KR(e){if(e?.[GR])return e;let t={...e};t.tokenColors&&!t.settings&&(t.settings=t.tokenColors,delete t.tokenColors),t.type||=`dark`,t.colorReplacements={...t.colorReplacements},t.settings||=[];let{bg:n,fg:r}=t;if(!n||!r){let e=t.settings?t.settings.find(e=>!e.name&&!e.scope):void 0;e?.settings?.foreground&&(r=e.settings.foreground),e?.settings?.background&&(n=e.settings.background),!r&&t?.colors?.[`editor.foreground`]&&(r=t.colors[`editor.foreground`]),!n&&t?.colors?.[`editor.background`]&&(n=t.colors[`editor.background`]),r||=t.type===`light`?UR.light:UR.dark,n||=t.type===`light`?WR.light:WR.dark,t.fg=r,t.bg=n}t.settings[0]&&t.settings[0].settings&&!t.settings[0].scope||t.settings.unshift({settings:{foreground:t.fg,background:t.bg}});let i=0,a=new Map;function o(e){if(a.has(e))return a.get(e);i+=1;let n=`#${i.toString(16).padStart(8,`0`).toLowerCase()}`;return t.colorReplacements?.[`#${n}`]?o(e):(a.set(e,n),n)}t.settings=t.settings.map(e=>{let n=e.settings?.foreground&&!e.settings.foreground.startsWith(`#`),r=e.settings?.background&&!e.settings.background.startsWith(`#`);if(!n&&!r)return e;let i={...e,settings:{...e.settings}};if(n){let n=o(e.settings.foreground);t.colorReplacements[n]=e.settings.foreground,i.settings.foreground=n}if(r){let n=o(e.settings.background);t.colorReplacements[n]=e.settings.background,i.settings.background=n}return i});for(let e of Object.keys(t.colors||{}))if((e===`editor.foreground`||e===`editor.background`||e.startsWith(`terminal.ansi`))&&!t.colors[e]?.startsWith(`#`)){let n=o(t.colors[e]);t.colorReplacements[n]=t.colors[e],t.colors[e]=n}return Object.defineProperty(t,GR,{enumerable:!1,writable:!1,value:!0}),t}async function qR(e){return Array.from(new Set((await Promise.all(e.filter(e=>!zR(e)).map(async e=>await LR(e).then(e=>Array.isArray(e)?e:[e])))).flat()))}async function JR(e){return(await Promise.all(e.map(async e=>VR(e)?null:KR(await LR(e))))).filter(e=>!!e)}function YR(e,t){if(!t)return e;if(t[e]){let n=new Set([e]);for(;t[e];){if(e=t[e],n.has(e))throw new J(`Circular alias \`${Array.from(n).join(` -> `)} -> ${e}\``);n.add(e)}}return e}var XR=class extends MR{_resolvedThemes=new Map;_resolvedGrammars=new Map;_langMap=new Map;_langGraph=new Map;_textmateThemeCache=new WeakMap;_loadedThemesCache=null;_loadedLanguagesCache=null;constructor(e,t,n,r={}){super(e),this._resolver=e,this._themes=t,this._langs=n,this._alias=r,this._themes.map(e=>this.loadTheme(e)),this.loadLanguages(this._langs)}getTheme(e){return typeof e==`string`?this._resolvedThemes.get(e):this.loadTheme(e)}loadTheme(e){let t=KR(e);return t.name&&(this._resolvedThemes.set(t.name,t),this._loadedThemesCache=null),t}getLoadedThemes(){return this._loadedThemesCache||=[...this._resolvedThemes.keys()],this._loadedThemesCache}setTheme(e){let t=this._textmateThemeCache.get(e);t||(t=pL.createFromRawTheme(e),this._textmateThemeCache.set(e,t)),this._syncRegistry.setTheme(t)}getGrammar(e){return e=YR(e,this._alias),this._resolvedGrammars.get(e)}loadLanguage(e){if(this.getGrammar(e.name))return;let t=new Set([...this._langMap.values()].filter(t=>t.embeddedLangsLazy?.includes(e.name)));this._resolver.addLanguage(e);let n={balancedBracketSelectors:e.balancedBracketSelectors||[`*`],unbalancedBracketSelectors:e.unbalancedBracketSelectors||[]};this._syncRegistry._rawGrammars.set(e.scopeName,e);let r=this.loadGrammarWithConfiguration(e.scopeName,1,n);if(r.name=e.name,this._resolvedGrammars.set(e.name,r),e.aliases&&e.aliases.forEach(t=>{this._alias[t]=e.name}),this._loadedLanguagesCache=null,t.size)for(let e of t)this._resolvedGrammars.delete(e.name),this._loadedLanguagesCache=null,this._syncRegistry?._injectionGrammars?.delete(e.scopeName),this._syncRegistry?._grammars?.delete(e.scopeName),this.loadLanguage(this._langMap.get(e.name))}dispose(){super.dispose(),this._resolvedThemes.clear(),this._resolvedGrammars.clear(),this._langMap.clear(),this._langGraph.clear(),this._loadedThemesCache=null}loadLanguages(e){for(let t of e)this.resolveEmbeddedLanguages(t);let t=Array.from(this._langGraph.entries()),n=t.filter(([e,t])=>!t);if(n.length){let e=t.filter(([e,t])=>t?(t.embeddedLanguages||t.embeddedLangs)?.some(e=>n.map(([e])=>e).includes(e)):!1).filter(e=>!n.includes(e));throw new J(`Missing languages ${n.map(([e])=>`\`${e}\``).join(`, `)}, required by ${e.map(([e])=>`\`${e}\``).join(`, `)}`)}for(let[e,n]of t)this._resolver.addLanguage(n);for(let[e,n]of t)this.loadLanguage(n)}getLoadedLanguages(){return this._loadedLanguagesCache||=[...new Set([...this._resolvedGrammars.keys(),...Object.keys(this._alias)])],this._loadedLanguagesCache}resolveEmbeddedLanguages(e){this._langMap.set(e.name,e),this._langGraph.set(e.name,e);let t=e.embeddedLanguages??e.embeddedLangs;if(t)for(let e of t)this._langGraph.set(e,this._langMap.get(e))}},ZR=class{_langs=new Map;_scopeToLang=new Map;_injections=new Map;_onigLib;constructor(e,t){this._onigLib={createOnigScanner:t=>e.createScanner(t),createOnigString:t=>e.createString(t)},t.forEach(e=>this.addLanguage(e))}get onigLib(){return this._onigLib}getLangRegistration(e){return this._langs.get(e)}loadGrammar(e){return this._scopeToLang.get(e)}addLanguage(e){this._langs.set(e.name,e),e.aliases&&e.aliases.forEach(t=>{this._langs.set(t,e)}),this._scopeToLang.set(e.scopeName,e),e.injectTo&&e.injectTo.forEach(t=>{this._injections.get(t)||this._injections.set(t,[]),this._injections.get(t).push(e.scopeName)})}getInjections(e){let t=e.split(`.`),n=[];for(let e=1;e<=t.length;e++){let r=t.slice(0,e).join(`.`);n=[...n,...this._injections.get(r)||[]]}return n}},QR=0;function $R(e){QR+=1,e.warnings!==!1&&QR>=10&&QR%10==0&&console.warn(`[Shiki] ${QR} instances have been created. Shiki is supposed to be used as a singleton, consider refactoring your code to cache your highlighter instance; Or call \`highlighter.dispose()\` to release unused instances.`);let t=!1;if(!e.engine)throw new J("`engine` option is required for synchronous mode");let n=(e.langs||[]).flat(1),r=(e.themes||[]).flat(1).map(KR),i=new XR(new ZR(e.engine,n),r,n,e.langAlias),a;function o(t){return YR(t,e.langAlias)}function s(e){g();let t=i.getGrammar(typeof e==`string`?e:e.name);if(!t)throw new J(`Language \`${e}\` not found, you may need to load it first`);return t}function c(e){if(e===`none`)return{bg:``,fg:``,name:`none`,settings:[],type:`dark`};g();let t=i.getTheme(e);if(!t)throw new J(`Theme \`${e}\` not found, you may need to load it first`);return t}function l(e){g();let t=c(e);return a!==e&&(i.setTheme(t),a=e),{theme:t,colorMap:i.getColorMap()}}function u(){return g(),i.getLoadedThemes()}function d(){return g(),i.getLoadedLanguages()}function f(...e){g(),i.loadLanguages(e.flat(1))}async function p(...e){return f(await qR(e))}function m(...e){g();for(let t of e.flat(1))i.loadTheme(t)}async function h(...e){return g(),m(await JR(e))}function g(){if(t)throw new J(`Shiki instance has been disposed`)}function _(){t||(t=!0,i.dispose(),--QR)}return{setTheme:l,getTheme:c,getLanguage:s,getLoadedThemes:u,getLoadedLanguages:d,resolveLangAlias:o,loadLanguage:p,loadLanguageSync:f,loadTheme:h,loadThemeSync:m,dispose:_,[Symbol.dispose]:_}}async function ez(e){e.engine||console.warn("`engine` option is required. Use `createOnigurumaEngine` or `createJavaScriptRegexEngine` to create an engine.");let[t,n,r]=await Promise.all([JR(e.themes||[]),qR(e.langs||[]),e.engine]);return $R({...e,themes:t,langs:n,engine:r})}var tz=new WeakMap;function nz(e,t){tz.set(e,t)}function rz(e){return tz.get(e)}var iz=class e{_stacks={};lang;get themes(){return Object.keys(this._stacks)}get theme(){return this.themes[0]}get _stack(){return this._stacks[this.theme]}static initial(t,n){return new e(Object.fromEntries(IR(n).map(e=>[e,NR])),t)}constructor(...e){if(e.length===2){let[t,n]=e;this.lang=n,this._stacks=t}else{let[t,n,r]=e;this.lang=n,this._stacks={[r]:t}}}getInternalStack(e=this.theme){return this._stacks[e]}getScopes(e=this.theme){return az(this._stacks[e])}toJSON(){return{lang:this.lang,theme:this.theme,themes:this.themes,scopes:this.getScopes()}}};function az(e){let t=[],n=new Set;function r(e){if(n.has(e))return;n.add(e);let i=e?.nameScopesList?.scopeName;i&&t.push(i),e.parent&&r(e.parent)}return r(e),t}function oz(e,t){if(!(e instanceof iz))throw new J(`Invalid grammar state`);return e.getInternalStack(t)}function sz(e,t,n={}){let{theme:r=e.getLoadedThemes()[0]}=n;if(RR(e.resolveLangAlias(n.lang||`text`))||BR(r))return HR(t).map(e=>[{content:e[0],offset:e[1]}]);let{theme:i,colorMap:a}=e.setTheme(r),o=e.getLanguage(n.lang||`text`);if(n.grammarState){if(n.grammarState.lang!==o.name)throw new J(`Grammar state language "${n.grammarState.lang}" does not match highlight language "${o.name}"`);if(!n.grammarState.themes.includes(i.name))throw new J(`Grammar state themes "${n.grammarState.themes}" do not contain highlight theme "${i.name}"`)}return lz(t,o,i,a,n)}function cz(...e){if(e.length===2)return rz(e[1]);let[t,n,r={}]=e,{lang:i=`text`,theme:a=t.getLoadedThemes()[0]}=r;if(RR(i)||BR(a))throw new J(`Plain language does not have grammar state`);if(i===`ansi`)throw new J(`ANSI language does not have grammar state`);let{theme:o,colorMap:s}=t.setTheme(a),c=t.getLanguage(i);return new iz(uz(n,c,o,s,r).stateStack,c.name,o.name)}function lz(e,t,n,r,i){let a=uz(e,t,n,r,i),o=new iz(a.stateStack,t.name,n.name);return nz(a.tokens,o),a.tokens}function uz(e,t,n,r,i){let a=PR(n,i),{tokenizeMaxLineLength:o=0,tokenizeTimeLimit:s=500}=i,c=HR(e),l=i.grammarState?oz(i.grammarState,n.name)??NR:i.grammarContextCode==null?NR:uz(i.grammarContextCode,t,n,r,{...i,grammarState:void 0,grammarContextCode:void 0}).stateStack,u=[],d=[];for(let e=0,f=c.length;e<f;e++){let[f,p]=c[e];if(f===``){u=[],d.push([]);continue}if(o>0&&f.length>=o){u=[],d.push([{content:f,offset:p,color:``,fontStyle:0}]);continue}let m,h,g;i.includeExplanation&&(m=t.tokenizeLine(f,l,s),h=m.tokens,g=0);let _=t.tokenizeLine2(f,l,s),v=_.tokens.length/2;for(let e=0;e<v;e++){let t=_.tokens[2*e],o=e+1<v?_.tokens[2*e+2]:f.length;if(t===o)continue;let s=_.tokens[2*e+1],c=FR(r[TL.getForeground(s)],a),l=TL.getFontStyle(s),d={content:f.substring(t,o),offset:p+t,color:c,fontStyle:l};if(i.includeExplanation){let e=[];if(i.includeExplanation!==`scopeName`)for(let t of n.settings){let n;switch(typeof t.scope){case`string`:n=t.scope.split(/,/).map(e=>e.trim());break;case`object`:n=t.scope;break;default:continue}e.push({settings:t,selectors:n.map(e=>e.split(/ /))})}d.explanation=[];let r=0;for(;t+r<o;){let t=h[g],n=f.substring(t.startIndex,t.endIndex);r+=n.length,d.explanation.push({content:n,scopes:i.includeExplanation===`scopeName`?dz(t.scopes):fz(e,t.scopes)}),g+=1}}u.push(d)}d.push(u),u=[],l=_.ruleStack}return{tokens:d,stateStack:l}}function dz(e){return e.map(e=>({scopeName:e}))}function fz(e,t){let n=[];for(let r=0,i=t.length;r<i;r++){let i=t[r];n[r]={scopeName:i,themeMatches:hz(e,i,t.slice(0,r))}}return n}function pz(e,t){return e===t||t.substring(0,e.length)===e&&t[e.length]===`.`}function mz(e,t,n){if(!pz(e[e.length-1],t))return!1;let r=e.length-2,i=n.length-1;for(;r>=0&&i>=0;)pz(e[r],n[i])&&--r,--i;return r===-1}function hz(e,t,n){let r=[];for(let{selectors:i,settings:a}of e)for(let e of i)if(mz(e,t,n)){r.push(a);break}return r}function gz(e,t,n,r=sz){let i=Object.entries(n.themes).filter(e=>e[1]).map(e=>({color:e[0],theme:e[1]})),a=i.map(i=>{let a=r(e,t,{...n,theme:i.theme});return{tokens:a,state:rz(a),theme:typeof i.theme==`string`?i.theme:i.theme.name}}),o=_z(...a.map(e=>e.tokens)),s=o[0].map((e,t)=>e.map((e,r)=>{let a={content:e.content,variants:{},offset:e.offset};return`includeExplanation`in n&&n.includeExplanation&&(a.explanation=e.explanation),o.forEach((e,n)=>{let{content:o,explanation:s,offset:c,...l}=e[t][r];a.variants[i[n].color]=l}),a})),c=a[0].state?new iz(Object.fromEntries(a.map(e=>[e.theme,e.state?.getInternalStack(e.theme)])),a[0].state.lang):void 0;return c&&nz(s,c),s}function _z(...e){let t=e.map(()=>[]),n=e.length;for(let r=0;r<e[0].length;r++){let i=e.map(e=>e[r]),a=t.map(()=>[]);t.forEach((e,t)=>e.push(a[t]));let o=i.map(()=>0),s=i.map(e=>e[0]);for(;s.every(e=>e);){let e=Math.min(...s.map(e=>e.content.length));for(let t=0;t<n;t++){let n=s[t];n.content.length===e?(a[t].push(n),o[t]+=1,s[t]=i[t][o[t]]):(a[t].push({...n,content:n.content.slice(0,e)}),s[t]={...n,content:n.content.slice(e),offset:n.offset+e})}}}return t}function vz(e,t){if(!t)return e;e.properties||={},e.properties.class||=[],typeof e.properties.class==`string`&&(e.properties.class=e.properties.class.split(/\s+/g)),Array.isArray(e.properties.class)||(e.properties.class=[]);let n=Array.isArray(t)?t:t.split(/\s+/g);for(let t of n)t&&!e.properties.class.includes(t)&&e.properties.class.push(t);return e}function yz(e){let t=HR(e,!0).map(([e])=>e);function n(n){if(n===e.length)return{line:t.length-1,character:t[t.length-1].length};let r=n,i=0;for(let e of t){if(r<e.length)break;r-=e.length,i++}return{line:i,character:r}}function r(e,n){let r=0;for(let n=0;n<e;n++)r+=t[n].length;return r+=n,r}return{lines:t,indexToPos:n,posToIndex:r}}function bz(e,t,n){let r=new Set;for(let t of e.matchAll(/:?lang=["']([^"']+)["']/g)){let e=t[1].toLowerCase().trim();e&&r.add(e)}for(let t of e.matchAll(/(?:```|~~~)([\w-]+)/g)){let e=t[1].toLowerCase().trim();e&&r.add(e)}for(let t of e.matchAll(/\\begin\{([\w-]+)\}/g)){let e=t[1].toLowerCase().trim();e&&r.add(e)}for(let t of e.matchAll(/<script\s+(?:type|lang)=["']([^"']+)["']/gi)){let e=t[1].toLowerCase().trim(),n=e.includes(`/`)?e.split(`/`).pop():e;n&&r.add(n)}if(!n)return Array.from(r);let i=n.getBundledLanguages();return Array.from(r).filter(e=>e&&i[e])}var xz=`light-dark()`,Sz=[`color`,`background-color`];function Cz(e,t){let n=0,r=[];for(let i of t)i>n&&r.push({...e,content:e.content.slice(n,i),offset:e.offset+n}),n=i;return n<e.content.length&&r.push({...e,content:e.content.slice(n),offset:e.offset+n}),r}function wz(e,t){let n=Array.from(t instanceof Set?t:new Set(t)).sort((e,t)=>e-t);return n.length?e.map(e=>e.flatMap(e=>{let t=n.filter(t=>e.offset<t&&t<e.offset+e.content.length).map(t=>t-e.offset).sort((e,t)=>e-t);return t.length?Cz(e,t):e})):e}function Tz(e,t,n,r,i=`css-vars`){let a={content:e.content,explanation:e.explanation,offset:e.offset},o=t.map(t=>Ez(e.variants[t])),s=new Set(o.flatMap(e=>Object.keys(e))),c={},l=(e,r)=>{let i=r===`color`?``:r===`background-color`?`-bg`:`-${r}`;return n+t[e]+(r===`color`?``:i)};return o.forEach((e,n)=>{for(let a of s){let s=e[a]||`inherit`;if(n===0&&r&&Sz.includes(a))if(r===xz&&o.length>1){let e=t.findIndex(e=>e===`light`),r=t.findIndex(e=>e===`dark`);if(e===-1||r===-1)throw new J('When using `defaultColor: "light-dark()"`, you must provide both `light` and `dark` themes');c[a]=`light-dark(${o[e][a]||`inherit`}, ${o[r][a]||`inherit`})`,i===`css-vars`&&(c[l(n,a)]=s)}else c[a]=s;else i===`css-vars`&&(c[l(n,a)]=s)}}),a.htmlStyle=c,a}function Ez(e){let t={};if(e.color&&(t.color=e.color),e.bgColor&&(t[`background-color`]=e.bgColor),e.fontStyle){e.fontStyle&Y.Italic&&(t[`font-style`]=`italic`),e.fontStyle&Y.Bold&&(t[`font-weight`]=`bold`);let n=[];e.fontStyle&Y.Underline&&n.push(`underline`),e.fontStyle&Y.Strikethrough&&n.push(`line-through`),n.length&&(t[`text-decoration`]=n.join(` `))}return t}function Dz(e){return typeof e==`string`?e:Object.entries(e).map(([e,t])=>`${e}:${t}`).join(`;`)}function Oz(){let e=new WeakMap;function t(t){if(!e.has(t.meta)){let n=yz(t.source);function r(e){if(typeof e==`number`){if(e<0||e>t.source.length)throw new J(`Invalid decoration offset: ${e}. Code length: ${t.source.length}`);return{...n.indexToPos(e),offset:e}}{let t=n.lines[e.line];if(t===void 0)throw new J(`Invalid decoration position ${JSON.stringify(e)}. Lines length: ${n.lines.length}`);let r=e.character;if(r<0&&(r=t.length+r),r<0||r>t.length)throw new J(`Invalid decoration position ${JSON.stringify(e)}. Line ${e.line} length: ${t.length}`);return{...e,character:r,offset:n.posToIndex(e.line,r)}}}let i=(t.options.decorations||[]).map(e=>({...e,start:r(e.start),end:r(e.end)}));kz(i),e.set(t.meta,{decorations:i,converter:n,source:t.source})}return e.get(t.meta)}return{name:`shiki:decorations`,tokens(e){if(this.options.decorations?.length)return wz(e,t(this).decorations.flatMap(e=>[e.start.offset,e.end.offset]))},code(e){if(!this.options.decorations?.length)return;let n=t(this),r=Array.from(e.children).filter(e=>e.type===`element`&&e.tagName===`span`);if(r.length!==n.converter.lines.length)throw new J(`Number of lines in code element (${r.length}) does not match the number of lines in the source (${n.converter.lines.length}). Failed to apply decorations.`);function i(e,t,n,i){let a=r[e],s=``,c=-1,l=-1;if(t===0&&(c=0),n===0&&(l=0),n===1/0&&(l=a.children.length),c===-1||l===-1)for(let e=0;e<a.children.length;e++)s+=Az(a.children[e]),c===-1&&s.length===t&&(c=e+1),l===-1&&s.length===n&&(l=e+1);if(c===-1)throw new J(`Failed to find start index for decoration ${JSON.stringify(i.start)}`);if(l===-1)throw new J(`Failed to find end index for decoration ${JSON.stringify(i.end)}`);let u=a.children.slice(c,l);if(!i.alwaysWrap&&u.length===a.children.length)o(a,i,`line`);else if(!i.alwaysWrap&&u.length===1&&u[0].type===`element`)o(u[0],i,`token`);else{let e={type:`element`,tagName:`span`,properties:{},children:u};o(e,i,`wrapper`),a.children.splice(c,u.length,e)}}function a(e,t){r[e]=o(r[e],t,`line`)}function o(e,t,n){let r=t.properties||{},i=t.transform||(e=>e);return e.tagName=t.tagName||`span`,e.properties={...e.properties,...r,class:e.properties.class},t.properties?.class&&vz(e,t.properties.class),e=i(e,n)||e,e}let s=[],c=n.decorations.sort((e,t)=>t.start.offset-e.start.offset||e.end.offset-t.end.offset);for(let e of c){let{start:t,end:n}=e;if(t.line===n.line)i(t.line,t.character,n.character,e);else if(t.line<n.line){i(t.line,t.character,1/0,e);for(let r=t.line+1;r<n.line;r++)s.unshift(()=>a(r,e));i(n.line,0,n.character,e)}}s.forEach(e=>e())}}}function kz(e){for(let t=0;t<e.length;t++){let n=e[t];if(n.start.offset>n.end.offset)throw new J(`Invalid decoration range: ${JSON.stringify(n.start)} - ${JSON.stringify(n.end)}`);for(let r=t+1;r<e.length;r++){let t=e[r],i=n.start.offset<=t.start.offset&&t.start.offset<n.end.offset,a=n.start.offset<t.end.offset&&t.end.offset<=n.end.offset,o=t.start.offset<=n.start.offset&&n.start.offset<t.end.offset,s=t.start.offset<n.end.offset&&n.end.offset<=t.end.offset;if(i||a||o||s){if(i&&a||o&&s||o&&n.start.offset===n.end.offset||a&&t.start.offset===t.end.offset)continue;throw new J(`Decorations ${JSON.stringify(n.start)} and ${JSON.stringify(t.start)} intersect.`)}}}}function Az(e){return e.type===`text`?e.value:e.type===`element`?e.children.map(Az).join(``):``}var jz=[Oz()];function Mz(e){let t=Nz(e.transformers||[]);return[...t.pre,...t.normal,...t.post,...jz]}function Nz(e){let t=[],n=[],r=[];for(let i of e)switch(i.enforce){case`pre`:t.push(i);break;case`post`:n.push(i);break;default:r.push(i)}return{pre:t,post:n,normal:r}}var Pz=[`black`,`red`,`green`,`yellow`,`blue`,`magenta`,`cyan`,`white`,`brightBlack`,`brightRed`,`brightGreen`,`brightYellow`,`brightBlue`,`brightMagenta`,`brightCyan`,`brightWhite`],Fz={1:`bold`,2:`dim`,3:`italic`,4:`underline`,7:`reverse`,8:`hidden`,9:`strikethrough`};function Iz(e,t){let n=e.indexOf(`\x1B`,t);if(n!==-1&&e[n+1]===`[`){let t=e.indexOf(`m`,n);if(t!==-1)return{sequence:e.substring(n+2,t).split(`;`),startPosition:n,position:t+1}}return{position:e.length}}function Lz(e){let t=e.shift();if(t===`2`){let t=e.splice(0,3).map(e=>Number.parseInt(e));return t.length!==3||t.some(e=>Number.isNaN(e))?void 0:{type:`rgb`,rgb:t}}if(t===`5`){let t=e.shift();if(t)return{type:`table`,index:Number(t)}}}function Rz(e){let t=[];for(;e.length>0;){let n=e.shift();if(!n)continue;let r=Number.parseInt(n);if(!Number.isNaN(r))if(r===0)t.push({type:`resetAll`});else if(r<=9)Fz[r]&&t.push({type:`setDecoration`,value:Fz[r]});else if(r<=29){let e=Fz[r-20];e&&(t.push({type:`resetDecoration`,value:e}),e===`dim`&&t.push({type:`resetDecoration`,value:`bold`}))}else if(r<=37)t.push({type:`setForegroundColor`,value:{type:`named`,name:Pz[r-30]}});else if(r===38){let n=Lz(e);n&&t.push({type:`setForegroundColor`,value:n})}else if(r===39)t.push({type:`resetForegroundColor`});else if(r<=47)t.push({type:`setBackgroundColor`,value:{type:`named`,name:Pz[r-40]}});else if(r===48){let n=Lz(e);n&&t.push({type:`setBackgroundColor`,value:n})}else r===49?t.push({type:`resetBackgroundColor`}):r===53?t.push({type:`setDecoration`,value:`overline`}):r===55?t.push({type:`resetDecoration`,value:`overline`}):r>=90&&r<=97?t.push({type:`setForegroundColor`,value:{type:`named`,name:Pz[r-90+8]}}):r>=100&&r<=107&&t.push({type:`setBackgroundColor`,value:{type:`named`,name:Pz[r-100+8]}})}return t}function zz(){let e=null,t=null,n=new Set;return{parse(r){let i=[],a=0;do{let o=Iz(r,a),s=o.sequence?r.substring(a,o.startPosition):r.substring(a);if(s.length>0&&i.push({value:s,foreground:e,background:t,decorations:new Set(n)}),o.sequence){let r=Rz(o.sequence);for(let i of r)i.type===`resetAll`?(e=null,t=null,n.clear()):i.type===`resetForegroundColor`?e=null:i.type===`resetBackgroundColor`?t=null:i.type===`resetDecoration`&&n.delete(i.value);for(let i of r)i.type===`setForegroundColor`?e=i.value:i.type===`setBackgroundColor`?t=i.value:i.type===`setDecoration`&&n.add(i.value)}a=o.position}while(a<r.length);return i}}}var Bz={black:`#000000`,red:`#bb0000`,green:`#00bb00`,yellow:`#bbbb00`,blue:`#0000bb`,magenta:`#ff00ff`,cyan:`#00bbbb`,white:`#eeeeee`,brightBlack:`#555555`,brightRed:`#ff5555`,brightGreen:`#00ff00`,brightYellow:`#ffff55`,brightBlue:`#5555ff`,brightMagenta:`#ff55ff`,brightCyan:`#55ffff`,brightWhite:`#ffffff`};function Vz(e=Bz){function t(t){return e[t]}function n(e){return`#${e.map(e=>Math.max(0,Math.min(e,255)).toString(16).padStart(2,`0`)).join(``)}`}let r;function i(){if(r)return r;r=[];for(let e=0;e<Pz.length;e++)r.push(t(Pz[e]));let e=[0,95,135,175,215,255];for(let t=0;t<6;t++)for(let i=0;i<6;i++)for(let a=0;a<6;a++)r.push(n([e[t],e[i],e[a]]));let i=8;for(let e=0;e<24;e++,i+=10)r.push(n([i,i,i]));return r}function a(e){return i()[e]}function o(e){switch(e.type){case`named`:return t(e.name);case`rgb`:return n(e.rgb);case`table`:return a(e.index)}}return{value:o}}var Hz={black:`#000000`,red:`#cd3131`,green:`#0DBC79`,yellow:`#E5E510`,blue:`#2472C8`,magenta:`#BC3FBC`,cyan:`#11A8CD`,white:`#E5E5E5`,brightBlack:`#666666`,brightRed:`#F14C4C`,brightGreen:`#23D18B`,brightYellow:`#F5F543`,brightBlue:`#3B8EEA`,brightMagenta:`#D670D6`,brightCyan:`#29B8DB`,brightWhite:`#FFFFFF`};function Uz(e,t,n){let r=PR(e,n),i=HR(t),a=Vz(Object.fromEntries(Pz.map(t=>{let n=`terminal.ansi${t[0].toUpperCase()}${t.substring(1)}`;return[t,e.colors?.[n]||Hz[t]]}))),o=zz();return i.map(t=>o.parse(t[0]).map(n=>{let i,o;n.decorations.has(`reverse`)?(i=n.background?a.value(n.background):e.bg,o=n.foreground?a.value(n.foreground):e.fg):(i=n.foreground?a.value(n.foreground):e.fg,o=n.background?a.value(n.background):void 0),i=FR(i,r),o=FR(o,r),n.decorations.has(`dim`)&&(i=Wz(i));let s=Y.None;return n.decorations.has(`bold`)&&(s|=Y.Bold),n.decorations.has(`italic`)&&(s|=Y.Italic),n.decorations.has(`underline`)&&(s|=Y.Underline),n.decorations.has(`strikethrough`)&&(s|=Y.Strikethrough),{content:n.value,offset:t[1],color:i,bgColor:o,fontStyle:s}}))}function Wz(e){let t=e.match(/#([0-9a-f]{3,8})/i);if(t){let e=t[1];if(e.length===8){let t=Math.round(Number.parseInt(e.slice(6,8),16)/2).toString(16).padStart(2,`0`);return`#${e.slice(0,6)}${t}`}if(e.length===6)return`#${e}80`;if(e.length===4){let t=e[0],n=e[1],r=e[2],i=e[3];return`#${t}${t}${n}${n}${r}${r}${Math.round(Number.parseInt(`${i}${i}`,16)/2).toString(16).padStart(2,`0`)}`}if(e.length===3){let t=e[0],n=e[1],r=e[2];return`#${t}${t}${n}${n}${r}${r}80`}}let n=e.match(/var\((--[\w-]+-ansi-[\w-]+)\)/);return n?`var(${n[1]}-dim)`:e}function Gz(e,t,n={}){let r=e.resolveLangAlias(n.lang||`text`),{theme:i=e.getLoadedThemes()[0]}=n;if(!RR(r)&&!BR(i)&&r===`ansi`){let{theme:r}=e.setTheme(i);return Uz(r,t,n)}return sz(e,t,n)}function Kz(e,t,n){let r,i,a,o,s,c;if(`themes`in n){let{defaultColor:l=`light`,cssVariablePrefix:u=`--shiki-`,colorsRendering:d=`css-vars`}=n,f=Object.entries(n.themes).filter(e=>e[1]).map(e=>({color:e[0],theme:e[1]})).sort((e,t)=>e.color===l?-1:+(t.color===l));if(f.length===0)throw new J("`themes` option must not be empty");let p=gz(e,t,n,Gz);if(c=rz(p),l&&xz!==l&&!f.find(e=>e.color===l))throw new J(`\`themes\` option must contain the defaultColor key \`${l}\``);let m=f.map(t=>e.getTheme(t.theme)),h=f.map(e=>e.color);a=p.map(e=>e.map(e=>Tz(e,h,u,l,d))),c&&nz(a,c);let g=f.map(e=>PR(e.theme,n));i=qz(f,m,g,u,l,`fg`,d),r=qz(f,m,g,u,l,`bg`,d),o=`shiki-themes ${m.map(e=>e.name).join(` `)}`,s=l?void 0:[i,r].join(`;`)}else if(`theme`in n){let s=PR(n.theme,n);a=Gz(e,t,n);let l=e.getTheme(n.theme);r=FR(l.bg,s),i=FR(l.fg,s),o=l.name,c=rz(a)}else throw new J("Invalid options, either `theme` or `themes` must be provided");return{tokens:a,fg:i,bg:r,themeName:o,rootStyle:s,grammarState:c}}function qz(e,t,n,r,i,a,o){return e.map((s,c)=>{let l=FR(t[c][a],n[c])||`inherit`,u=`${r+s.color}${a===`bg`?`-bg`:``}:${l}`;if(c===0&&i){if(i===xz&&e.length>1){let r=e.findIndex(e=>e.color===`light`),i=e.findIndex(e=>e.color===`dark`);if(r===-1||i===-1)throw new J('When using `defaultColor: "light-dark()"`, you must provide both `light` and `dark` themes');return`light-dark(${FR(t[r][a],n[r])||`inherit`}, ${FR(t[i][a],n[i])||`inherit`});${u}`}return l}return o===`css-vars`?u:null}).filter(e=>!!e).join(`;`)}function Jz(e,t,n,r={meta:{},options:n,codeToHast:(t,n)=>Jz(e,t,n),codeToTokens:(t,n)=>Kz(e,t,n)}){let i=t;for(let e of Mz(n))i=e.preprocess?.call(r,i,n)||i;let{tokens:a,fg:o,bg:s,themeName:c,rootStyle:l,grammarState:u}=Kz(e,i,n),{mergeWhitespaces:d=!0,mergeSameStyleTokens:f=!1}=n;d===!0?a=Xz(a):d===`never`&&(a=Zz(a)),f&&(a=Qz(a));let p={...r,get source(){return i}};for(let e of Mz(n))a=e.tokens?.call(p,a)||a;return Yz(a,{...n,fg:o,bg:s,themeName:c,rootStyle:n.rootStyle===!1?!1:n.rootStyle??l},p,u)}function Yz(e,t,n,r=rz(e)){let i=Mz(t),a=[],o={type:`root`,children:[]},{structure:s=`classic`,tabindex:c=`0`}=t,l={class:`shiki ${t.themeName||``}`};t.rootStyle!==!1&&(l.style=t.rootStyle==null?`background-color:${t.bg};color:${t.fg}`:t.rootStyle),c!==!1&&c!=null&&(l.tabindex=c.toString());for(let[e,n]of Object.entries(t.meta||{}))e.startsWith(`_`)||(l[e]=n);let u={type:`element`,tagName:`pre`,properties:l,children:[],data:t.data},d={type:`element`,tagName:`code`,properties:{},children:a},f=[],p={...n,structure:s,addClassToHast:vz,get source(){return n.source},get tokens(){return e},get options(){return t},get root(){return o},get pre(){return u},get code(){return d},get lines(){return f}};if(e.forEach((e,t)=>{t&&(s===`inline`?o.children.push({type:`element`,tagName:`br`,properties:{},children:[]}):s===`classic`&&a.push({type:`text`,value:`
|
|
44
|
-
`}));let n={type:`element`,tagName:`span`,properties:{class:`line`},children:[]},r=0;for(let a of e){let e={type:`element`,tagName:`span`,properties:{...a.htmlAttrs},children:[{type:`text`,value:a.content}]},c=
|
|
41
|
+
\f\r "&'<=>\``.split(``)]],single:[[`&'`.split(``),`"&'\``.split(``)],[`\0&'`.split(``),`\0"&'\``.split(``)]],double:[[`"&`.split(``),`"&'\``.split(``)],[`\0"&`.split(``),`\0"&'\``.split(``)]]};function vF(e,t,n,r){let i=r.schema,a=i.space!==`svg`&&r.settings.omitOptionalTags,o=i.space===`svg`?r.settings.closeEmptyElements:r.settings.voids.includes(e.tagName.toLowerCase()),s=[],c;i.space===`html`&&e.tagName===`svg`&&(r.schema=oP);let l=yF(r,e.properties),u=r.all(i.space===`html`&&e.tagName===`template`?e.content:e);return r.schema=i,u&&(o=!1),(l||!a||!dF(e,t,n))&&(s.push(`<`,e.tagName,l?` `+l:``),o&&(i.space===`svg`||r.settings.closeSelfClosing)&&(c=l.charAt(l.length-1),(!r.settings.tightSelfClosing||c===`/`||c&&c!==`"`&&c!==`'`)&&s.push(` `),s.push(`/`)),s.push(`>`)),s.push(u),!o&&(!a||!YP(e,t,n))&&s.push(`</`+e.tagName+`>`),s.join(``)}function yF(e,t){let n=[],r=-1,i;if(t){for(i in t)if(t[i]!==null&&t[i]!==void 0){let r=bF(e,i,t[i]);r&&n.push(r)}}for(;++r<n.length;){let t=e.settings.tightAttributes?n[r].charAt(n[r].length-1):void 0;r!==n.length-1&&t!==`"`&&t!==`'`&&(n[r]+=` `)}return n.join(``)}function bF(e,t,n){let r=nP(e.schema,t),i=e.settings.allowParseErrors&&e.schema.space===`html`?0:1,a=+!e.settings.allowDangerousCharacters,o=e.quote,s;if(r.overloadedBoolean&&(n===r.attribute||n===``)?n=!0:(r.boolean||r.overloadedBoolean)&&(typeof n!=`string`||n===r.attribute||n===``)&&(n=!!n),n==null||n===!1||typeof n==`number`&&Number.isNaN(n))return``;let c=AP(r.attribute,Object.assign({},e.settings.characterReferences,{subset:_F.name[i][a]}));return n===!0||(n=Array.isArray(n)?(r.commaSeparated?RP:BP)(n,{padLeft:!e.settings.tightCommaSeparatedLists}):String(n),e.settings.collapseEmptyAttributes&&!n)?c:(e.settings.preferUnquoted&&(s=AP(n,Object.assign({},e.settings.characterReferences,{attribute:!0,subset:_F.unquoted[i][a]}))),s!==n&&(e.settings.quoteSmart&&IP(n,o)>IP(n,e.alternative)&&(o=e.alternative),s=o+AP(n,Object.assign({},e.settings.characterReferences,{subset:(o===`'`?_F.single:_F.double)[i][a],attribute:!0}))+o),c+(s&&`=`+s))}var xF=[`<`,`&`];function SF(e,t,n,r){return n&&n.type===`element`&&(n.tagName===`script`||n.tagName===`style`)?e.value:AP(e.value,Object.assign({},r.settings.characterReferences,{subset:xF}))}function CF(e,t,n,r){return r.settings.allowDangerousHtml?e.value:SF(e,t,n,r)}function wF(e,t,n,r){return r.all(e)}var TF=cP(`type`,{invalid:EF,unknown:DF,handlers:{comment:PP,doctype:FP,element:vF,raw:CF,root:wF,text:SF}});function EF(e){throw Error("Expected node, not `"+e+"`")}function DF(e){throw Error("Cannot compile unknown node `"+e.type+"`")}var OF={},kF={},AF=[];function jF(e,t){let n=t||OF,r=n.quote||`"`,i=r===`"`?`'`:`"`;if(r!==`"`&&r!==`'`)throw Error("Invalid quote `"+r+"`, expected `'` or `\"`");return{one:MF,all:NF,settings:{omitOptionalTags:n.omitOptionalTags||!1,allowParseErrors:n.allowParseErrors||!1,allowDangerousCharacters:n.allowDangerousCharacters||!1,quoteSmart:n.quoteSmart||!1,preferUnquoted:n.preferUnquoted||!1,tightAttributes:n.tightAttributes||!1,upperDoctype:n.upperDoctype||!1,tightDoctype:n.tightDoctype||!1,bogusComments:n.bogusComments||!1,tightCommaSeparatedLists:n.tightCommaSeparatedLists||!1,tightSelfClosing:n.tightSelfClosing||!1,collapseEmptyAttributes:n.collapseEmptyAttributes||!1,allowDangerousHtml:n.allowDangerousHtml||!1,voids:n.voids||AN,characterReferences:n.characterReferences||kF,closeSelfClosing:n.closeSelfClosing||!1,closeEmptyElements:n.closeEmptyElements||!1},schema:n.space===`svg`?oP:aP,quote:r,alternative:i}.one(Array.isArray(e)?{type:`root`,children:e}:e,void 0,void 0)}function MF(e,t,n){return TF(e,t,n,this)}function NF(e){let t=[],n=e&&e.children||AF,r=-1;for(;++r<n.length;)t[r]=this.one(n[r],r,e);return t.join(``)}var PF=class{mode;options;hoveredLine;hoveredToken;pre;gutterUtilityLine;gutterUtilityContainer;gutterUtilityButton;gutterUtilitySlot;interactiveLinesAttr=!1;interactiveLineNumbersAttr=!1;hasPointerListeners=!1;hasDocumentPointerListeners=!1;selectedRange=null;selectedRangeHighlightSide;selectedRangeLineNumberOnly=!1;editorActiveLine=null;editorActiveLineSide;editorLineNumberOnly=!1;proposedSelectedRange;renderedSelectedLinesState;renderedEditorActiveLineState;selectionAnchor;pointerSession={mode:`idle`};constructor(e,t){this.mode=e,this.options=t}setOptions(e){this.options=e}cleanUp(){this.pre?.removeEventListener(`click`,this.handlePointerClick),this.pre?.removeEventListener(`pointerdown`,this.handlePointerDown),this.pre?.removeEventListener(`pointermove`,this.handlePointerMove),this.pre?.removeEventListener(`pointerleave`,this.handlePointerLeave),this.pre?.removeAttribute(`data-interactive-lines`),this.pre?.removeAttribute(`data-interactive-line-numbers`),this.pre=void 0,this.gutterUtilityContainer?.remove(),this.gutterUtilityLine=void 0,this.gutterUtilityContainer=void 0,this.gutterUtilityButton=void 0,this.gutterUtilitySlot=void 0,this.clearHoveredLine(),this.clearHoveredToken(),this.detachDocumentPointerListeners(),this.clearPointerSession(),jM(this.renderSelection),this.interactiveLinesAttr=!1,this.interactiveLineNumbersAttr=!1,this.hasPointerListeners=!1,this.setSelectionDirty()}setup(e){this.setSelectionDirty();let{usesCustomGutterUtility:t=!1,enableGutterUtility:n=!1}=this.options;this.pre!==e&&(this.cleanUp(),this.pre=e),n?this.ensureGutterUtilityNode(t):this.gutterUtilityContainer!=null&&(this.gutterUtilityContainer.remove(),this.gutterUtilityLine=void 0,this.gutterUtilityContainer=void 0,this.gutterUtilityButton=void 0,this.gutterUtilitySlot=void 0,this.pointerSession.mode===`gutterSelecting`&&(this.clearPointerSession(),this.detachDocumentPointerListeners())),this.syncPointerListeners(e),this.updateInteractiveLineAttributes(),this.renderSelection(),this.placeUtility()}setSelectionDirty(){this.renderedSelectedLinesState=void 0,this.renderedEditorActiveLineState=void 0}isSelectionDirty(){return this.renderedSelectedLinesState===void 0||this.renderedEditorActiveLineState===void 0}setSelection(e,t){let n=!(e===this.selectedRange||LM(e??void 0,this.selectedRange??void 0)),r=t?.lineNumberOnly??!1,i=t?.activeLineSide!==this.selectedRangeHighlightSide||r!==this.selectedRangeLineNumberOnly;!this.isSelectionDirty()&&!n&&!i||(this.proposedSelectedRange=void 0,this.selectedRange=e,this.selectedRangeHighlightSide=t?.activeLineSide,this.selectedRangeLineNumberOnly=r,this.renderSelection(),this.placeUtility(),n&&t?.notify!==!1&&this.notifySelectionCommitted(e))}setEditorActiveLine(e,{lineNumberOnly:t=!1,side:n}={}){let r=e!==this.editorActiveLine,i=n!==this.editorActiveLineSide||t!==this.editorLineNumberOnly;!this.isSelectionDirty()&&!r&&!i||(this.editorActiveLine=e,this.editorActiveLineSide=n,this.editorLineNumberOnly=t,this.renderSelection())}getSelection(){return this.selectedRange}getHoveredLine=()=>{let e=this.gutterUtilityLine??this.hoveredLine;if(e!=null){if(this.mode===`diff`&&e.type===`diff-line`)return{lineNumber:e.lineNumber,side:e.annotationSide};if(this.mode===`file`&&e.type===`line`)return{lineNumber:e.lineNumber}}};handlePointerClick=e=>{let{onHunkExpand:t,onLineClick:n,onLineNumberClick:r,onTokenClick:i,onMergeConflictActionClick:a}=this.options;(t!=null||n!=null||r!=null||a!=null||i!=null)&&(this.options.onGutterUtilityClick!=null&&kN(e.composedPath())||($F(this.options.__debugPointerEvents,`click`,`FileDiff.DEBUG.handlePointerClick:`,e),this.handlePointerEvent({eventType:`click`,event:e})))};handlePointerMove=e=>{if(e.pointerType!==`mouse`)return;let{lineHoverHighlight:t=`disabled`,onLineEnter:n,onLineLeave:r,onTokenEnter:i,onTokenLeave:a,enableGutterUtility:o=!1}=this.options;t===`disabled`&&!o&&n==null&&r==null&&i==null&&a==null||($F(this.options.__debugPointerEvents,`move`,`FileDiff.DEBUG.handlePointerMove:`,e),this.handlePointerEvent({eventType:`move`,event:e}))};handlePointerLeave=e=>{let{__debugPointerEvents:t}=this.options;if($F(t,`move`,`FileDiff.DEBUG.handlePointerLeave: no event`),this.hoveredLine==null&&this.hoveredToken==null){$F(t,`move`,`FileDiff.DEBUG.handlePointerLeave: returned early, no hovered line or token`);return}this.hoveredToken!=null&&(this.options.onTokenLeave?.(this.hoveredToken,e),this.clearHoveredToken()),this.hoveredLine!=null&&(this.options.onLineLeave?.({...this.hoveredLine,event:e}),this.clearHoveredLine()),this.placeUtility()};handlePointerEvent({eventType:e,event:t}){let{__debugPointerEvents:n}=this.options,r=t.composedPath();$F(n,e,`FileDiff.DEBUG.handlePointerEvent:`,{eventType:e,composedPath:r});let i=this.resolvePointerTarget(r);$F(n,e,`FileDiff.DEBUG.handlePointerEvent: resolvePointerTarget result:`,i);let{onLineClick:a,onLineNumberClick:o,onLineEnter:s,onLineLeave:c,onTokenClick:l,onTokenEnter:u,onTokenLeave:d,onHunkExpand:f,onMergeConflictActionClick:p}=this.options;switch(e){case`move`:{let e=zF(i)&&this.hoveredLine?.lineElement===i.lineElement;RF(i)&&this.hoveredToken?.tokenElement===i.tokenElement||(this.hoveredToken!=null&&(d?.(this.hoveredToken,t),this.clearHoveredToken()),RF(i)&&(this.setHoveredToken(this.toTokenEventBaseProps(i)),u?.(this.hoveredToken,t))),e||(this.hoveredLine!=null&&(c?.({...this.hoveredLine,event:t}),this.clearHoveredLine()),zF(i)?(this.setHoveredLine(this.toEventBaseProps(i)),this.placeUtility(),s?.({...this.hoveredLine,event:t})):this.placeUtility());break}case`click`:{if(i==null)break;if(VF(i)&&p!=null){p(i);break}if(BF(i)&&f!=null){f(i.hunkIndex,i.all||t.shiftKey?`both`:i.direction,i.all||t.shiftKey?1/0:void 0);break}if(!zF(i))break;RF(i)&&l!=null&&l(this.toTokenEventBaseProps(i),t);let e=this.toEventBaseProps(i);o!=null&&i.numberColumn?o({...e,event:t}):a?.({...e,event:t});break}}}syncPointerListeners(e){let{__debugPointerEvents:t,lineHoverHighlight:n=`disabled`,onLineClick:r,onLineNumberClick:i,onLineEnter:a,onLineLeave:o,onTokenClick:s,onTokenEnter:c,onTokenLeave:l,onHunkExpand:u,onMergeConflictActionClick:d,enableGutterUtility:f=!1,enableLineSelection:p=!1,onGutterUtilityClick:m}=this.options,h=m!=null,g=n!==`disabled`||r!=null||i!=null||a!=null||o!=null||s!=null||c!=null||l!=null||u!=null||d!=null||f||p||h;g&&!this.hasPointerListeners?(e.addEventListener(`click`,this.handlePointerClick),e.addEventListener(`pointerdown`,this.handlePointerDown),e.addEventListener(`pointermove`,this.handlePointerMove),e.addEventListener(`pointerleave`,this.handlePointerLeave),this.hasPointerListeners=!0,$F(t,`click`,`FileDiff.DEBUG.attachEventListeners: Attaching click events for:`,(()=>{let e=[];return(t===`both`||t===`click`)&&(r!=null&&e.push(`onLineClick`),i!=null&&e.push(`onLineNumberClick`),u!=null&&e.push(`expandable hunk separators`),d!=null&&e.push(`merge conflict actions`)),e})()),$F(t,`move`,`FileDiff.DEBUG.attachEventListeners: Attaching pointer move event`),$F(t,`move`,`FileDiff.DEBUG.attachEventListeners: Attaching pointer leave event`)):!g&&this.hasPointerListeners&&(e.removeEventListener(`click`,this.handlePointerClick),e.removeEventListener(`pointerdown`,this.handlePointerDown),e.removeEventListener(`pointermove`,this.handlePointerMove),e.removeEventListener(`pointerleave`,this.handlePointerLeave),this.hasPointerListeners=!1);let _=this.pointerSession.mode===`selecting`||this.pointerSession.mode===`pendingSingleLineUnselect`,v=this.pointerSession.mode===`gutterSelecting`;(!p&&_||!h&&v)&&(this.clearPointerSession(),this.detachDocumentPointerListeners(),this.selectionAnchor=void 0,this.clearPendingSingleLineState())}updateInteractiveLineAttributes(){if(this.pre==null)return;let{onLineClick:e,onLineNumberClick:t,enableLineSelection:n=!1}=this.options,r=e!=null,i=t!=null||n;r&&!this.interactiveLinesAttr?(this.pre.setAttribute(`data-interactive-lines`,``),this.interactiveLinesAttr=!0):!r&&this.interactiveLinesAttr&&(this.pre.removeAttribute(`data-interactive-lines`),this.interactiveLinesAttr=!1),i&&!this.interactiveLineNumbersAttr?(this.pre.setAttribute(`data-interactive-line-numbers`,``),this.interactiveLineNumbersAttr=!0):!i&&this.interactiveLineNumbersAttr&&(this.pre.removeAttribute(`data-interactive-line-numbers`),this.interactiveLineNumbersAttr=!1)}handlePointerDown=e=>{if(e.pointerType===`mouse`&&e.button!==0||this.pre==null||this.pointerSession.mode!==`idle`)return;let t=e.composedPath();kN(t)&&this.options.onGutterUtilityClick!=null?this.startGutterSelectionFromPointerDown(e):(e.pointerType!==`mouse`&&this.revealUtilityFromGutterPath(t),this.startLineSelectionFromPointerDown(e))};startLineSelectionFromPointerDown(e){let{enableLineSelection:t=!1}=this.options;if(!t)return;let n=this.resolveSelectionInfo(e,{source:`event-path`,requireNumberColumn:!0});if(n==null)return;let{pre:r}=this;if(r==null)return;let{lineNumber:i,eventSide:a,lineIndex:o}=n;if(e.shiftKey&&this.selectedRange!=null){let t=this.getIndexesFromSelection(this.selectedRange,r.getAttribute(`data-diff-type`)===`split`);if(t==null)return;let n=t.start<=t.end?o>=t.start:o<=t.end;this.selectionAnchor={lineNumber:n?this.selectedRange.start:this.selectedRange.end,side:n?this.selectedRange.side:this.selectedRange.endSide??this.selectedRange.side},this.updateSelection(i,a,!1),this.notifySelectionStart(this.getCurrentSelectionRange()),this.pointerSession={mode:`selecting`,pointerId:e.pointerId},this.attachDocumentPointerListeners();return}if(this.selectedRange?.start===i&&this.selectedRange?.end===i){let t={lineNumber:i,side:a};this.selectionAnchor=t,this.pointerSession={mode:`pendingSingleLineUnselect`,pointerId:e.pointerId,anchor:t,pending:t},this.attachDocumentPointerListeners();return}this.options.controlledSelection===!0?this.proposedSelectedRange=null:this.selectedRange=null,this.placeUtility(),this.selectionAnchor={lineNumber:i,side:a},this.updateSelection(i,a,!1),this.notifySelectionStart(this.getCurrentSelectionRange()),this.pointerSession={mode:`selecting`,pointerId:e.pointerId},this.attachDocumentPointerListeners()}startGutterSelectionFromPointerDown(e){let{onGutterUtilityClick:t}=this.options;if(t==null)return;let n=this.currentSelectionEnds(),r=n?.bottom??this.resolveSelectionPoint(e,{source:`event-path`,excludeUtility:!1}),i=n?.top??r;r!=null&&i!=null&&(e.preventDefault(),e.stopPropagation(),this.pointerSession={mode:`gutterSelecting`,pointerId:e.pointerId,anchor:i,current:r},this.selectionAnchor={lineNumber:i.lineNumber,side:i.side},this.updateSelection(r.lineNumber,r.side,!1),this.notifySelectionStart(this.getCurrentSelectionRange()),this.attachDocumentPointerListeners())}handleDocumentPointerMove=e=>{switch(this.pointerSession.mode){case`idle`:return;case`gutterSelecting`:{if(e.pointerId!==this.pointerSession.pointerId)return;e.preventDefault();let t=this.resolveSelectionPoint(e,{source:`coordinates-first`});if(t==null)return;this.pointerSession.current=t,this.updateSelection(t.lineNumber,t.side);return}case`selecting`:{if(e.pointerId!==this.pointerSession.pointerId)return;e.preventDefault();let t=this.resolveSelectionInfo(e,{source:`coordinates-first`,requireNumberColumn:!1});if(t==null||this.selectionAnchor==null)return;this.updateSelection(t.lineNumber,t.eventSide);return}case`pendingSingleLineUnselect`:{if(e.pointerId!==this.pointerSession.pointerId)return;e.preventDefault();let t=this.resolveSelectionInfo(e,{source:`coordinates-first`,requireNumberColumn:!1});if(t==null||this.selectionAnchor==null)return;let n={lineNumber:t.lineNumber,side:t.eventSide};if(ON(this.pointerSession.pending,n))return;this.updateSelection(t.lineNumber,t.eventSide,!1),this.notifySelectionStart(this.getCurrentSelectionRange()),this.notifySelectionChangeDelta(),this.pointerSession={mode:`selecting`,pointerId:e.pointerId};return}}};handleDocumentPointerUp=e=>{let{onGutterUtilityClick:t}=this.options;switch(this.pointerSession.mode){case`idle`:return;case`gutterSelecting`:{let{pointerSession:n}=this;if(e.pointerId!==n.pointerId)return;e.preventDefault();let r=this.resolveSelectionPoint(e,{source:`coordinates-first`});r!=null&&(n.current=r,this.updateSelection(r.lineNumber,r.side));let i=this.buildSelectedLineRange(n.anchor,n.current);t?.({...i}),this.selectionAnchor=void 0,this.notifySelectionEnd(i),this.notifySelectionCommitted(i),this.clearProposedSelection(),this.clearPointerSession(),this.detachDocumentPointerListeners();return}case`pendingSingleLineUnselect`:if(e.pointerId!==this.pointerSession.pointerId)return;e.preventDefault(),this.updateSelection(null,void 0,!1),this.selectionAnchor=void 0,this.clearPendingSingleLineState(),this.detachDocumentPointerListeners(),this.notifySelectionEnd(this.getCurrentSelectionRange()),this.notifySelectionCommitted(this.getCurrentSelectionRange()),this.clearProposedSelection();return;case`selecting`:if(e.pointerId!==this.pointerSession.pointerId)return;e.preventDefault(),this.selectionAnchor=void 0,this.detachDocumentPointerListeners(),this.clearPointerSession(),this.notifySelectionEnd(this.getCurrentSelectionRange()),this.notifySelectionCommitted(this.getCurrentSelectionRange()),this.clearProposedSelection()}};handleDocumentPointerCancel=e=>{switch(this.pointerSession.mode){case`idle`:return;case`gutterSelecting`:case`selecting`:case`pendingSingleLineUnselect`:if(`pointerId`in this.pointerSession&&e.pointerId!==this.pointerSession.pointerId)return;this.selectionAnchor=void 0,this.clearProposedSelection(),this.clearPendingSingleLineState(),this.clearPointerSession(),this.detachDocumentPointerListeners()}};clearHoveredLine(){this.hoveredLine!=null&&(this.hoveredLine.lineElement.removeAttribute(`data-hovered`),this.hoveredLine.numberElement.removeAttribute(`data-hovered`),this.hoveredLine=void 0)}setHoveredLine(e){let{lineHoverHighlight:t=`disabled`}=this.options;this.hoveredLine!=null&&this.clearHoveredLine(),this.hoveredLine=e,t!==`disabled`&&((t===`both`||t===`line`)&&this.hoveredLine.lineElement.setAttribute(`data-hovered`,``),(t===`both`||t===`number`)&&this.hoveredLine.numberElement.setAttribute(`data-hovered`,``))}clearHoveredToken(){this.hoveredToken!=null&&(this.hoveredToken=void 0)}setHoveredToken(e){this.hoveredToken!=null&&this.clearHoveredToken(),this.hoveredToken=e}ensureGutterUtilityNode(e){if(this.gutterUtilityContainer??(this.gutterUtilityContainer=document.createElement(`div`),this.gutterUtilityContainer.setAttribute(`data-gutter-utility-slot`,``)),e)this.gutterUtilityButton!=null&&(this.gutterUtilityButton.remove(),this.gutterUtilityButton=void 0),this.gutterUtilitySlot??(this.gutterUtilitySlot=document.createElement(`slot`),this.gutterUtilitySlot.name=`gutter-utility-slot`),this.gutterUtilitySlot.parentNode!==this.gutterUtilityContainer&&this.gutterUtilityContainer.replaceChildren(this.gutterUtilitySlot);else{if(this.gutterUtilitySlot?.remove(),this.gutterUtilitySlot=void 0,this.gutterUtilityButton==null){let e=document.createElement(`div`);e.innerHTML=jF(DN());let t=e.firstElementChild;if(!(t instanceof HTMLButtonElement))throw Error(`InteractionManager.ensureGutterUtilityNode: Node element should be a button`);t.remove(),this.gutterUtilityButton=t}this.gutterUtilityButton.parentNode!==this.gutterUtilityContainer&&this.gutterUtilityContainer.replaceChildren(this.gutterUtilityButton)}}revealUtilityFromGutterPath(e){if(this.placeUtilityFromSelection())return;let t=this.resolvePointerTarget(e);LF(t)&&t.numberColumn&&this.showUtilityOnLine(this.toEventBaseProps(t))}placeUtility(){if(!this.placeUtilityFromSelection()){if(this.hoveredLine!=null){this.showUtilityOnLine(this.hoveredLine);return}this.hideUtility()}}placeUtilityFromSelection(){let e=this.currentSelectionEnds();if(e==null)return!1;let t=this.targetForSelectionPoint(e.bottom);return t==null?this.hideUtility():this.showUtilityOnLine(this.toEventBaseProps(t)),!0}showUtilityOnLine(e){this.gutterUtilityContainer!=null&&(this.gutterUtilityLine=e,e.numberElement.appendChild(this.gutterUtilityContainer))}hideUtility(){this.gutterUtilityContainer?.remove(),this.gutterUtilityLine=void 0}currentSelectionEnds(){let e=this.getCurrentSelectionRange();return e==null?void 0:this.selectionEnds(e)}selectionEnds(e){let t={lineNumber:e.start,side:e.side},n={lineNumber:e.end,side:e.endSide??e.side},r=this.selectionPointRowIndex(t),i=this.selectionPointRowIndex(n);if(r!=null&&i!=null)return r>i?{top:n,bottom:t}:{top:t,bottom:n}}selectionPointRowIndex(e){let t=this.getLineIndex(e.lineNumber,e.side);if(t!=null)return this.isSplitDiff()?t[1]:t[0]}targetForSelectionPoint(e){if(this.pre==null)return;let t=this.getLineIndex(e.lineNumber,e.side);if(t==null)return;let n=this.mode===`diff`?`${t[0]},${t[1]}`:`${t[0]}`,r=this.pre.querySelectorAll(`[data-column-number="${e.lineNumber}"][data-line-index="${n}"]`);for(let t of r){if(!(t instanceof HTMLElement))continue;let n=this.resolvePointerTarget(WF(t));if(LF(n)&&(this.mode!==`diff`||e.side==null||n.side===e.side))return n}}attachDocumentPointerListeners(){this.hasDocumentPointerListeners||=(document.addEventListener(`pointermove`,this.handleDocumentPointerMove),document.addEventListener(`pointerup`,this.handleDocumentPointerUp),document.addEventListener(`pointercancel`,this.handleDocumentPointerCancel),!0)}detachDocumentPointerListeners(){this.hasDocumentPointerListeners&&=(document.removeEventListener(`pointermove`,this.handleDocumentPointerMove),document.removeEventListener(`pointerup`,this.handleDocumentPointerUp),document.removeEventListener(`pointercancel`,this.handleDocumentPointerCancel),!1)}clearPointerSession(){this.pointerSession={mode:`idle`}}clearPendingSingleLineState(){this.pointerSession.mode===`pendingSingleLineUnselect`&&(this.pointerSession={mode:`idle`})}selectionInfoFromPath(e,t){let n=this.resolvePointerTarget(e);if(LF(n)&&!(t&&!n.numberColumn)&&n.splitLineIndex!=null)return{lineIndex:n.splitLineIndex,lineNumber:n.lineNumber,eventSide:this.mode===`diff`?n.side:void 0}}resolveSelectionInfo(e,t){let n=this.resolveSelectionPath(e,t);return n==null?void 0:this.selectionInfoFromPath(n,t.requireNumberColumn)}selectionPointFromPath(e){let t=this.resolvePointerTarget(e);if(LF(t))return{lineNumber:t.lineNumber,side:this.mode===`diff`?t.side:void 0}}resolveSelectionPoint(e,t){let n=this.resolveSelectionPath(e,t);return n==null?void 0:this.selectionPointFromPath(n)}resolveSelectionPath(e,t){let n=t.excludeUtility!==!1;switch(t.source){case`event-path`:return this.pathFromEventPath(e.composedPath(),n);case`coordinates-first`:{let t=this.pathFromCoordinates(e,n);return t===void 0?this.pathFromEventPath(e.composedPath(),n):t??void 0}}}pathFromCoordinates(e,t){let n=this.hitTest(e);if(n!==void 0)return n===null?null:this.pathFromElement(n,t)??null}pathFromEventPath(e,t){if(!(t&&kN(e))){for(let n of e)if(n instanceof Element)return this.pathFromElement(n,t)}}pathFromElement(e,t){let n=WF(e);if(t&&kN(n))return;let r=GF(e);return r==null?this.pathFromAnnotationSlot(e):WF(r)}pathFromAnnotationSlot(e){let t=qF(KF(e));if(t==null)return;let n=this.targetForSelectionPoint(t);return n==null?void 0:WF(n.lineElement)}hitTest(e){if(!Number.isFinite(e.clientX)||!Number.isFinite(e.clientY))return;let t=this.pre?.getRootNode(),n=JF(t)?t:JF(document)?document:void 0;if(n!=null)return n.elementFromPoint(e.clientX,e.clientY)}getLineIndex(e,t){let{getLineIndex:n}=this.options;return n==null?[e-1,e-1]:n(e,t)}getCurrentSelectionRange(){return this.proposedSelectedRange===void 0?this.selectedRange:this.proposedSelectedRange}clearProposedSelection(){this.proposedSelectedRange=void 0}updateSelection(e,t,n=!0){let r=this.getCurrentSelectionRange(),i;if(e==null)i=null;else{let n=this.selectionAnchor?.side??t,r=this.selectionAnchor?.lineNumber??e;i=this.buildSelectionRange(r,e,n,t)}LM(r??void 0,i??void 0)||(this.selectedRangeHighlightSide=void 0,this.selectedRangeLineNumberOnly=!1,this.options.controlledSelection===!0?this.proposedSelectedRange=i:(this.selectedRange=i,AM(this.renderSelection)),this.placeUtility(),n&&this.notifySelectionChangeDelta())}getIndexesFromSelection(e,t){if(this.pre==null)return;let n=this.getLineIndex(e.start,e.side),r=this.getLineIndex(e.end,e.endSide??e.side);return n!=null&&r!=null?{start:t?n[1]:n[0],end:t?r[1]:r[0]}:void 0}getSelectionRenderState(){return{selectedLines:{range:this.selectedRange,highlightSide:this.selectedRangeHighlightSide,lineNumberOnly:this.selectedRangeLineNumberOnly},editorActiveLine:{range:this.editorActiveLine==null?null:{start:this.editorActiveLine,end:this.editorActiveLine,side:this.editorActiveLineSide},highlightSide:this.editorActiveLineSide,lineNumberOnly:this.editorLineNumberOnly}}}resolveLineRenderRange(e,t,n){if(e.range==null)return;let r=this.getIndexesFromSelection(e.range,t);if(r==null)throw console.error({rowRange:r,range:e.range}),Error(`InteractionManager.renderSelection: No valid ${n} rowRange`);return r}getLineRenderColumns(e,t,n,r){if(this.pre==null||t==null&&r==null)return[];let{children:i}=this.pre;if(i.length>2)throw console.error(i),Error(`InteractionManager.renderSelection: Somehow there are more than 2 code elements...`);let a=[];for(let o of i){let i=o.hasAttribute(`data-deletions`)?`deletions`:o.hasAttribute(`data-additions`)?`additions`:void 0,s=e!=null&&t!=null&&(e.highlightSide==null||i==null||e.highlightSide===i),c=n!=null&&r!=null&&(n.highlightSide==null||i==null||n.highlightSide===i);if(!s&&!c)continue;let[l,u]=o.children;if(!(l instanceof HTMLElement)||!(u instanceof HTMLElement))throw Error(`InteractionManager.renderSelection: missing gutter or content element`);if(u.children.length!==l.children.length)throw Error(`InteractionManager.renderSelection: gutter and content children dont match, something is wrong`);a.push({content:u,gutter:l,renderEditorActiveLine:c,renderSelectedLines:s})}return a}renderSelection=()=>{jM(this.renderSelection);let e=this.getSelectionRenderState();if(this.pre==null)return;let{editorActiveLine:t,selectedLines:n}=e,r=!XF(this.renderedSelectedLinesState,n),i=!XF(this.renderedEditorActiveLineState,t);if(!r&&!i)return;r&&(this.renderedSelectedLinesState=void 0),i&&(this.renderedEditorActiveLineState=void 0);let a=this.pre.getAttribute(`data-diff-type`)===`split`,o=r?this.resolveLineRenderRange(n,a,`selected-lines`):void 0,s=i?this.resolveLineRenderRange(t,a,`editor-active-line`):void 0,c=this.getLineRenderColumns(r?n:void 0,o,i?t:void 0,s),l=n.range==null||c.some(e=>e.renderSelectedLines),u=t.range==null||c.some(e=>e.renderEditorActiveLine);if(r)for(let e of this.pre.querySelectorAll(`[data-selected-line]`))e.removeAttribute(`data-selected-line`);if(i)for(let e of this.pre.querySelectorAll(`[data-editor-active-line]`))e.removeAttribute(`data-editor-active-line`);let d=o==null?void 0:Math.min(o.start,o.end),f=o==null?void 0:Math.max(o.start,o.end),p=d===f,m=s?.start;for(let e of c){let{content:r,gutter:i,renderEditorActiveLine:o,renderSelectedLines:s}=e,c=Math.max(s?f??-1/0:-1/0,o?m??-1/0:-1/0),l=r.children.length;for(let e=0;e<l;e++){let l=r.children[e],u=i.children[e];if(!(l instanceof HTMLElement)||!(u instanceof HTMLElement))continue;let h=this.parseLineIndex(l,a);if((h??0)>c)break;if(h!=null){if(s&&d!=null&&f!=null&&h>=d&&h<=f){let e=p?`single`:h===d?`first`:h===f?`last`:``;u.setAttribute(`data-selected-line`,e),n.lineNumberOnly||(l.setAttribute(`data-selected-line`,e),u.nextSibling instanceof HTMLElement&&l.nextSibling instanceof HTMLElement&&(l.nextSibling.hasAttribute(`data-line-annotation`)||l.nextSibling.hasAttribute(`data-merge-conflict-actions`))&&(p?(e=`last`,l.setAttribute(`data-selected-line`,`first`)):h===d?e=``:h===f&&l.setAttribute(`data-selected-line`,``),l.nextSibling.setAttribute(`data-selected-line`,e),u.nextSibling.setAttribute(`data-selected-line`,e)))}o&&h===m&&(u.setAttribute(`data-editor-active-line`,``),t.lineNumberOnly||l.setAttribute(`data-editor-active-line`,``))}}}r&&l&&(this.renderedSelectedLinesState=n),i&&u&&(this.renderedEditorActiveLineState=t)};notifySelectionCommitted(e){this.options.onLineSelected?.(e)}notifySelectionChangeDelta(){this.options.onLineSelectionChange?.(this.getCurrentSelectionRange()??null)}notifySelectionStart(e){this.options.onLineSelectionStart?.(e)}notifySelectionEnd(e){this.options.onLineSelectionEnd?.(e)}toEventBaseProps(e){return this.mode===`file`?{type:`line`,lineElement:e.lineElement,lineNumber:e.lineNumber,numberColumn:e.numberColumn,numberElement:e.numberElement}:{type:`diff-line`,annotationSide:e.side,lineType:e.lineType,lineElement:e.lineElement,numberElement:e.numberElement,lineNumber:e.lineNumber,numberColumn:e.numberColumn}}toTokenEventBaseProps({lineCharEnd:e,lineCharStart:t,lineNumber:n,side:r,tokenElement:i,tokenText:a}){return this.mode===`file`?{type:`token`,lineCharEnd:e,lineCharStart:t,lineNumber:n,tokenElement:i,tokenText:a}:{type:`token`,lineCharEnd:e,lineCharStart:t,lineNumber:n,side:r,tokenElement:i,tokenText:a}}buildSelectedLineRange(e,t){return this.buildSelectionRange(e.lineNumber,t.lineNumber,e.side,t.side)}buildSelectionRange(e,t,n,r){return{start:e,end:t,...n==null?{}:{side:n},...n!==r&&r!=null?{endSide:r}:{}}}resolvePointerTarget(e){let t=!1,n,r,i,a,o,s,c,l,u,d;for(let f of e){if(!(f instanceof HTMLElement))continue;if(d==null&&f.hasAttribute(`data-merge-conflict-action`)){let e=f.getAttribute(`data-merge-conflict-action`)??void 0,t=f.getAttribute(`data-merge-conflict-conflict-index`)??void 0,n=t==null?NaN:Number.parseInt(t,10);HF(e)&&Number.isFinite(n)&&(d={kind:`merge-conflict-action`,resolution:e,conflictIndex:n})}if(s==null&&f.hasAttribute(`data-char`)){s=f;let e=f.getAttribute(`data-char`);if(e!=null){let t=Number.parseInt(e,10);if(!Number.isNaN(t)){let e=f.textContent??``,n=t+e.length;(e.trim()!==``||this.options.enableTokenInteractionsOnWhitespace===!0)&&(c={tokenElement:s,lineCharStart:t,lineCharEnd:n,tokenText:e});continue}}}let e=o==null?f.getAttribute(`data-column-number`)??void 0:void 0;if(e!=null){o=f,u=Number.parseInt(e,10),t=!0,n=QF(f),a=f.getAttribute(`data-line-index`)??void 0;continue}let p=i==null?f.getAttribute(`data-line`)??void 0:void 0;if(p!=null){i=f,u=Number.parseInt(p,10),n=QF(f),a=f.getAttribute(`data-line-index`)??void 0;continue}if(l==null&&(f.hasAttribute(`data-expand-button`)||f.hasAttribute(`data-unmodified-lines`))){l={hunkIndex:void 0,direction:f.hasAttribute(`data-expand-up`)?`up`:f.hasAttribute(`data-expand-down`)?`down`:`both`,all:f.hasAttribute(`data-expand-all-button`)};continue}let m=l==null?void 0:f.getAttribute(`data-expand-index`)??void 0;if(l!=null&&m!=null){let e=Number.parseInt(m,10);Number.isNaN(e)||(l.hunkIndex=e);continue}if(r==null&&f.hasAttribute(`data-code`)){r=f;break}}if(d!=null)return d;if(l?.hunkIndex!=null)return{type:`line-info`,hunkIndex:l.hunkIndex,direction:l.direction,all:l.all};if(i??=a==null?void 0:UF(r,`[data-line][data-line-index="${a}"]`),o??=a==null?void 0:UF(r,`[data-column-number][data-line-index="${a}"]`),r==null||i==null||o==null||n==null||u==null||Number.isNaN(u))return;let f=this.parseLineIndex(i,this.isSplitDiff());return c==null?this.mode===`file`?{kind:`line`,lineType:n,lineElement:i,lineNumber:u,numberColumn:t,numberElement:o,side:void 0,splitLineIndex:f}:{kind:`line`,lineType:n,lineElement:i,lineNumber:u,numberColumn:t,numberElement:o,side:ZF(n,r),splitLineIndex:f}:this.mode===`file`?{kind:`token`,lineType:n,lineElement:i,lineNumber:u,numberColumn:t,numberElement:o,side:void 0,splitLineIndex:f,...c}:{kind:`token`,lineType:n,lineElement:i,lineNumber:u,numberColumn:t,numberElement:o,side:ZF(n,r),splitLineIndex:f,...c}}isSplitDiff(){return this.pre?.getAttribute(`data-diff-type`)===`split`}parseLineIndex(e,t){let n=(e.getAttribute(`data-line-index`)??``).split(`,`).map(e=>Number.parseInt(e,10)).filter(e=>!Number.isNaN(e));if(t&&n.length===2)return n[1];if(!t)return n[0]}};function FF({enableTokenInteractionsOnWhitespace:e,enableGutterUtility:t,lineHoverHighlight:n,onGutterUtilityClick:r,onLineClick:i,onLineEnter:a,onLineLeave:o,onLineNumberClick:s,onTokenClick:c,onTokenEnter:l,onTokenLeave:u,renderGutterUtility:d,__debugPointerEvents:f,enableLineSelection:p,controlledSelection:m,onLineSelected:h,onLineSelectionStart:g,onLineSelectionChange:_,onLineSelectionEnd:v},y,b,x){return{enableTokenInteractionsOnWhitespace:e,enableGutterUtility:IF({enableGutterUtility:t,renderGutterUtility:d,onGutterUtilityClick:r}),usesCustomGutterUtility:d!=null,lineHoverHighlight:n,onGutterUtilityClick:r,onHunkExpand:y,onMergeConflictActionClick:x,onLineClick:i,onLineEnter:a,onLineLeave:o,onLineNumberClick:s,onTokenClick:c,onTokenEnter:l,onTokenLeave:u,__debugPointerEvents:f,enableLineSelection:p,controlledSelection:m,onLineSelected:h,onLineSelectionStart:g,onLineSelectionChange:_,onLineSelectionEnd:v,getLineIndex:b}}function IF({enableGutterUtility:e,renderGutterUtility:t,onGutterUtilityClick:n}){if(n!=null&&t!=null)throw Error(`Cannot use both 'onGutterUtilityClick' and 'renderGutterUtility'. Use only one gutter utility API.`);return e??!1}function LF(e){return e!=null&&`kind`in e&&e.kind===`line`}function RF(e){return e!=null&&`kind`in e&&e.kind===`token`}function zF(e){return LF(e)||RF(e)}function BF(e){return`type`in e&&e.type===`line-info`}function VF(e){return`kind`in e&&e.kind===`merge-conflict-action`}function HF(e){return e===`current`||e===`incoming`||e===`both`}function UF(e,t){let n=e?.querySelector(t);return n instanceof HTMLElement?n:void 0}function WF(e){let t=[],n=e;for(;n!=null;)t.push(n),n=n.parentNode;return t}function GF(e){let t=e.closest(`[data-line], [data-column-number]`);if(t instanceof HTMLElement)return t;let n=e.closest(`[data-line-annotation], [data-gutter-buffer="annotation"]`);if(!(n instanceof HTMLElement))return;let r=n.previousElementSibling;return r instanceof HTMLElement&&(r.hasAttribute(`data-line`)||r.hasAttribute(`data-column-number`))?r:void 0}function KF(e){let t=e.closest(`[slot^="annotation-"]`);if(t instanceof HTMLElement)return t.getAttribute(`slot`)??void 0;if(e instanceof HTMLElement){let t=e.getAttribute(`name`)??void 0;return t!=null&&t.startsWith(`annotation-`)?t:void 0}}function qF(e){if(e==null)return;let t=/^annotation-(?:(additions|deletions)-)?(\d+)$/.exec(e);if(t==null)return;let n=Number.parseInt(t[2],10);if(!(!Number.isFinite(n)||n<=0))return{lineNumber:n,side:t[1]}}function JF(e){return e!=null&&typeof e.elementFromPoint==`function`}function YF(e,t){return e===t||LM(e??void 0,t??void 0)}function XF(e,t){return e?.highlightSide===t.highlightSide&&e?.lineNumberOnly===t.lineNumberOnly&&YF(e?.range??null,t.range)}function ZF(e,t){switch(e){case`change-deletion`:return`deletions`;case`change-addition`:return`additions`;default:return t.hasAttribute(`data-deletions`)?`deletions`:`additions`}}function QF(e){let t=e.getAttribute(`data-line-type`);if(t!=null)switch(t){case`change-deletion`:case`change-addition`:case`context`:case`context-expanded`:return t;default:return}}function $F(e=`none`,t,...n){switch(e){case`none`:return;case`both`:break;case`click`:if(t!==`click`)return;break;case`move`:if(t!==`move`)return}console.log(...n)}var eI=class e{static resizeObserver;static managersByElement=new Map;static getResizeObserver(){let t=e.resizeObserver??new ResizeObserver(e.handleSharedResizeEntries);return e.resizeObserver=t,t}static handleSharedResizeEntries(t){let n=new Map;for(let r of t){let t=e.managersByElement.get(r.target);if(t==null)continue;let i=n.get(t);i==null?n.set(t,[r]):i.push(r)}for(let[e,t]of n)e.handleResizeEntries(t)}observedNodes=new Map;setup(e,{disableAnnotations:t,columnVariables:n=`apply`}){let r=new Set,i=n===`apply`,a=0,o=new Map(this.observedNodes);this.observedNodes.clear();for(let t of e.children){if(a===2)break;let e=(()=>{if(t instanceof HTMLElement&&t.tagName===`CODE`)return t})();if(e==null)continue;a++;let n=o.get(e);if(n!=null&&n.type!==`code`)throw Error(`ResizeManager.setup: somehow a code node is being used for an annotation, should be impossible`);let r=e.firstElementChild;r instanceof HTMLElement||(r=null),n==null?(n={type:`code`,codeElement:e,numberElement:r,codeWidth:`auto`,numberWidth:0,applyColumnVariables:i},this.observedNodes.set(e,n),this.observe(e),r!=null&&(this.observedNodes.set(r,n),this.observe(r))):(this.observedNodes.set(e,n),o.delete(e),n.numberElement===r?n.numberElement==null?n.numberWidth=0:(o.delete(n.numberElement),this.observedNodes.set(n.numberElement,n)):(n.numberElement!=null&&(this.unobserve(n.numberElement),o.delete(n.numberElement)),r!=null&&(this.observe(r),o.delete(r),this.observedNodes.set(r,n)),n.numberElement=r,n.numberWidth=0),rI(n,i))}if(a>1&&!t){let t=e.querySelectorAll(`[data-line-annotation*=","]`),n=new Map;for(let e of t){if(!(e instanceof HTMLElement))continue;let t=e.getAttribute(`data-line-annotation`)??``;if(!/^-?\d+,-?\d+$/.test(t)){console.error(`DiffFileRenderer.setupResizeObserver: Invalid element or annotation`,{lineAnnotation:t,element:e});continue}let r=n.get(t);r??(r=[],n.set(t,r)),r.push(e)}for(let[e,t]of n){if(t.length!==2){console.error(`DiffFileRenderer.setupResizeObserver: Bad Pair`,e,t);continue}let[n,i]=t,a=n.firstElementChild,s=i.firstElementChild;if(!(n instanceof HTMLElement)||!(i instanceof HTMLElement)||!(a instanceof HTMLElement)||!(s instanceof HTMLElement))continue;let c=o.get(a);if(c!=null){this.observedNodes.set(a,c),this.observedNodes.set(s,c),o.delete(a),o.delete(s);continue}let l=a.getBoundingClientRect().height,u=s.getBoundingClientRect().height;c={type:`annotations`,column1:{container:n,child:a,childHeight:l},column2:{container:i,child:s,childHeight:u},currentHeight:`auto`},r.add({child1:a,child2:s,item:c,newHeight:Math.max(l,u)})}for(let e of r)this.applyNewHeight(e.item,e.newHeight),this.observedNodes.set(e.child1,e.item),this.observedNodes.set(e.child2,e.item),this.observe(e.child1),this.observe(e.child2);r.clear()}for(let[e,t]of o)this.unobserve(e),t.type===`code`?oI(t):sI(t);o.clear()}cleanUp(){for(let e of this.observedNodes.keys())this.unobserve(e);this.observedNodes.clear()}observe(t){let{managersByElement:n}=e,r=n.get(t);if(r!==this){if(r!=null&&r!==this)throw Error(`ResizeManager.observe: element is already owned by another ResizeManager`);n.set(t,this),e.getResizeObserver().observe(t)}}unobserve(t){let{managersByElement:n,resizeObserver:r}=e,i=n.get(t);if(i!=null){if(i!==this)throw Error(`ResizeManager.unobserve: element is owned by another ResizeManager`);n.delete(t),r?.unobserve(t),r!=null&&n.size===0&&(r.disconnect(),e.resizeObserver=void 0)}}handleResizeEntries(e){let t=new Map,n=new Set;for(let r of e){let{target:e,borderBoxSize:i,contentBoxSize:a}=r;if(!(e instanceof HTMLElement)){console.error(`ResizeManager.handleResizeEntries: Invalid element for ResizeObserver`,r);continue}let o=this.observedNodes.get(e);if(o==null){console.error(`ResizeManager.handleResizeEntries: Not a valid observed node`,r);continue}if(o.type===`annotations`){let t=(()=>{if(e===o.column1.child)return o.column1;if(e===o.column2.child)return o.column2})();if(t==null){console.error(`ResizeManager.handleResizeEntries: Couldn't find a column for`,{item:o,target:e});continue}t.childHeight=i[0].blockSize,n.add(o)}else if(o.type===`code`){let n=t.get(o)??{},r=a[0].inlineSize;e===o.codeElement?n.codeInlineSize=r:e===o.numberElement&&(n.numberInlineSize=r),t.set(o,n)}}this.applyAnnotationUpdates(n),n.clear(),this.applyColumnUpdates(t),t.clear()}applyAnnotationUpdates(e){for(let t of e)this.applyNewHeight(t,Math.max(t.column1.childHeight,t.column2.childHeight))}applyColumnUpdates=e=>{for(let[t,n]of e){let e=n.codeInlineSize==null?t.codeWidth:tI(n.codeInlineSize),r=n.numberInlineSize==null?t.numberWidth:nI(n.numberInlineSize),i=e!==t.codeWidth,a=r!==t.numberWidth;!i&&!a||(t.codeWidth=e,t.numberWidth=r,t.applyColumnVariables&&iI(t,{codeWidthChanged:i,numberWidthChanged:a}))}};applyNewHeight(e,t){t!==e.currentHeight&&(e.currentHeight=Math.max(t,0),e.column1.container.style.setProperty(`--diffs-annotation-min-height`,`${e.currentHeight}px`),e.column2.container.style.setProperty(`--diffs-annotation-min-height`,`${e.currentHeight}px`))}};function tI(e){let t=Math.max(Math.floor(e),0);return t===0?`auto`:t}function nI(e){return Math.max(Math.ceil(e),0)}function rI(e,t){e.applyColumnVariables!==t&&(e.applyColumnVariables=t,t?iI(e,{codeWidthChanged:!0,numberWidthChanged:!0}):aI(e))}function iI(e,{codeWidthChanged:t,numberWidthChanged:n}){let{codeElement:r,codeWidth:i,numberWidth:a}=e;if(t&&r.style.setProperty(`--diffs-column-width`,`${typeof i==`number`?`${i}px`:`auto`}`),n&&r.style.setProperty(`--diffs-column-number-width`,`${a===0?`auto`:`${a}px`}`),t||n&&i!==`auto`){let e=typeof i==`number`?Math.max(i-a,0):0;r.style.setProperty(`--diffs-column-content-width`,`${e>0?`${e}px`:`auto`}`)}}function aI(e){e.codeElement.style.removeProperty(`--diffs-column-content-width`),e.codeElement.style.removeProperty(`--diffs-column-number-width`),e.codeElement.style.removeProperty(`--diffs-column-width`)}function oI(e){e.codeElement.isConnected&&aI(e)}function sI(e){e.column1.container.isConnected&&e.column1.container.style.removeProperty(`--diffs-annotation-min-height`),e.column2.container.isConnected&&e.column2.container.style.removeProperty(`--diffs-annotation-min-height`)}var cI=new Map,lI=new Map,uI=new Map,dI=new Set;function fI(e){for(let t of Array.isArray(e)?e:[e])if(t!==`text`&&t!==`ansi`&&!dI.has(t))return!1;return!0}function pI(e,t){e=Array.isArray(e)?e:[e];for(let n of e){if(dI.has(n.name))continue;let e=cI.get(n.name);e??(e=n,cI.set(n.name,e)),dI.add(e.name),t.loadLanguageSync(e.data)}}function mI(){return typeof WorkerGlobalScope<`u`&&typeof self<`u`&&self instanceof WorkerGlobalScope}var hI=Object.defineProperty,gI=Object.getOwnPropertyDescriptor,_I=Object.getOwnPropertyNames,vI=Object.prototype.hasOwnProperty,yI=(e,t)=>{let n={};for(var r in e)hI(n,r,{get:e[r],enumerable:!0});return t||hI(n,Symbol.toStringTag,{value:`Module`}),n},bI=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=_I(t),a=0,o=i.length,s;a<o;a++)s=i[a],!vI.call(e,s)&&s!==n&&hI(e,s,{get:(e=>t[e]).bind(null,s),enumerable:!(r=gI(t,s))||r.enumerable});return e},xI=(e,t,n)=>(bI(e,t,`default`),n&&bI(n,t,`default`)),SI=[{id:`abap`,name:`ABAP`,import:(()=>D(()=>import(`./abap-CLvhMVsD.js`),[]))},{id:`actionscript-3`,name:`ActionScript`,import:(()=>D(()=>import(`./actionscript-3--17pq3dv.js`),[]))},{id:`ada`,name:`Ada`,import:(()=>D(()=>import(`./ada-C5qYipkI.js`),[]))},{id:`angular-html`,name:`Angular HTML`,import:(()=>D(()=>import(`./angular-html-B8mrqUL5.js`).then(e=>e.n),__vite__mapDeps([4,1,5,6,7])))},{id:`angular-ts`,name:`Angular TypeScript`,import:(()=>D(()=>import(`./angular-ts-Bzix210W.js`),__vite__mapDeps([8,4,1,5,6,7,9])))},{id:`apache`,name:`Apache Conf`,import:(()=>D(()=>import(`./apache-U0d_L8uA.js`),[]))},{id:`apex`,name:`Apex`,import:(()=>D(()=>import(`./apex-CGTLDQj6.js`),[]))},{id:`apl`,name:`APL`,import:(()=>D(()=>import(`./apl-Dhin1L29.js`),__vite__mapDeps([10,6,1,7,5,11,12,13])))},{id:`applescript`,name:`AppleScript`,import:(()=>D(()=>import(`./applescript-CCn79oCD.js`),[]))},{id:`ara`,name:`Ara`,import:(()=>D(()=>import(`./ara-4CJ0cIlV.js`),[]))},{id:`asciidoc`,name:`AsciiDoc`,aliases:[`adoc`],import:(()=>D(()=>import(`./asciidoc-DE70LPWp.js`),[]))},{id:`asm`,name:`Assembly`,import:(()=>D(()=>import(`./asm-Cmm7eHzH.js`),[]))},{id:`astro`,name:`Astro`,import:(()=>D(()=>import(`./astro-B-4NNgOP.js`),__vite__mapDeps([14,6,1,7,13,15,16,17])))},{id:`awk`,name:`AWK`,import:(()=>D(()=>import(`./awk-BWXHIvNe.js`),[]))},{id:`ballerina`,name:`Ballerina`,import:(()=>D(()=>import(`./ballerina-B7ZEbQpA.js`),[]))},{id:`bat`,name:`Batch File`,aliases:[`batch`],import:(()=>D(()=>import(`./bat-Bo4NYOV-.js`),[]))},{id:`beancount`,name:`Beancount`,import:(()=>D(()=>import(`./beancount-D-usSTwE.js`),[]))},{id:`berry`,name:`Berry`,aliases:[`be`],import:(()=>D(()=>import(`./berry-DKpUyyne.js`),[]))},{id:`bibtex`,name:`BibTeX`,import:(()=>D(()=>import(`./bibtex-Ci_nEsc7.js`),[]))},{id:`bicep`,name:`Bicep`,import:(()=>D(()=>import(`./bicep-CUHmPFLl.js`),[]))},{id:`bird2`,name:`BIRD2 Configuration`,aliases:[`bird`],import:(()=>D(()=>import(`./bird2-C6vDhewU.js`),[]))},{id:`blade`,name:`Blade`,import:(()=>D(()=>import(`./blade-Wr94ul2N.js`),__vite__mapDeps([18,6,1,7,5,11,12,13,19,20])))},{id:`bsl`,name:`1C (Enterprise)`,aliases:[`1c`],import:(()=>D(()=>import(`./bsl-BkkzgIyY.js`),__vite__mapDeps([21,22])))},{id:`c`,name:`C`,import:(()=>D(()=>import(`./c-iCihek07.js`).then(e=>e.n),__vite__mapDeps([23,1])))},{id:`c3`,name:`C3`,import:(()=>D(()=>import(`./c3-CnJL0r0V.js`),[]))},{id:`cadence`,name:`Cadence`,aliases:[`cdc`],import:(()=>D(()=>import(`./cadence-CQ2zXKGN.js`),[]))},{id:`cairo`,name:`Cairo`,import:(()=>D(()=>import(`./cairo-DLTphjLi.js`),__vite__mapDeps([24,25])))},{id:`clarity`,name:`Clarity`,import:(()=>D(()=>import(`./clarity-SemFz856.js`),[]))},{id:`clojure`,name:`Clojure`,aliases:[`clj`],import:(()=>D(()=>import(`./clojure-DqKBuwfJ.js`),[]))},{id:`cmake`,name:`CMake`,import:(()=>D(()=>import(`./cmake-Bj61d0ZC.js`),[]))},{id:`cobol`,name:`COBOL`,import:(()=>D(()=>import(`./cobol-Cw2-KvLW.js`),__vite__mapDeps([26,5,1,6,7,12])))},{id:`codeowners`,name:`CODEOWNERS`,import:(()=>D(()=>import(`./codeowners-C8r90Shi.js`),[]))},{id:`codeql`,name:`CodeQL`,aliases:[`ql`],import:(()=>D(()=>import(`./codeql-oeQT6MSM.js`),[]))},{id:`coffee`,name:`CoffeeScript`,aliases:[`coffeescript`],import:(()=>D(()=>import(`./coffee-CiiSLhB6.js`),__vite__mapDeps([27,6,1])))},{id:`common-lisp`,name:`Common Lisp`,aliases:[`lisp`],import:(()=>D(()=>import(`./common-lisp-Cv5bFMCO.js`),[]))},{id:`coq`,name:`Coq`,import:(()=>D(()=>import(`./coq-BrsZFFmf.js`),[]))},{id:`cpp`,name:`C++`,aliases:[`c++`],import:(()=>D(()=>import(`./cpp-DjoE5qBx.js`).then(e=>e.n),__vite__mapDeps([28,1,20,29,30,23])))},{id:`crystal`,name:`Crystal`,import:(()=>D(()=>import(`./crystal-wCJpIkgB.js`),__vite__mapDeps([31,6,1,7,5,20,23,32])))},{id:`csharp`,name:`C#`,aliases:[`c#`,`cs`],import:(()=>D(()=>import(`./csharp-Ct8U2NOr.js`),[]))},{id:`css`,name:`CSS`,import:(()=>D(()=>import(`./css-CNuuLpMC.js`).then(e=>e.n),__vite__mapDeps([7,1])))},{id:`csv`,name:`CSV`,import:(()=>D(()=>import(`./csv-Dx-8-gkx.js`),[]))},{id:`cue`,name:`CUE`,import:(()=>D(()=>import(`./cue-CE9AQfxI.js`),[]))},{id:`cypher`,name:`Cypher`,aliases:[`cql`],import:(()=>D(()=>import(`./cypher-ClKdZ_lG.js`),[]))},{id:`d`,name:`D`,import:(()=>D(()=>import(`./d-qD-0Kul2.js`),[]))},{id:`dart`,name:`Dart`,import:(()=>D(()=>import(`./dart-CnvKMtbv.js`),[]))},{id:`dax`,name:`DAX`,import:(()=>D(()=>import(`./dax-BkyTk9wS.js`),[]))},{id:`desktop`,name:`Desktop`,import:(()=>D(()=>import(`./desktop-Dlh5hvp9.js`),[]))},{id:`diff`,name:`Diff`,import:(()=>D(()=>import(`./diff-woXpYk--.js`),[]))},{id:`docker`,name:`Dockerfile`,aliases:[`dockerfile`],import:(()=>D(()=>import(`./docker-IyjqRm3v.js`),[]))},{id:`dotenv`,name:`dotEnv`,import:(()=>D(()=>import(`./dotenv-_5a1GRtc.js`),[]))},{id:`dream-maker`,name:`Dream Maker`,import:(()=>D(()=>import(`./dream-maker-DW3nJb8Q.js`),[]))},{id:`edge`,name:`Edge`,import:(()=>D(()=>import(`./edge-DCY0a-ow.js`),__vite__mapDeps([33,5,1,6,7,15,19])))},{id:`elixir`,name:`Elixir`,import:(()=>D(()=>import(`./elixir-DP304Xio.js`),__vite__mapDeps([34,5,1,6,7])))},{id:`elm`,name:`Elm`,import:(()=>D(()=>import(`./elm-o4NJxfws.js`),__vite__mapDeps([35,30,1,23])))},{id:`emacs-lisp`,name:`Emacs Lisp`,aliases:[`elisp`],import:(()=>D(()=>import(`./emacs-lisp-B4R74twV.js`),[]))},{id:`erb`,name:`ERB`,import:(()=>D(()=>import(`./erb-BcNYoZVd.js`),__vite__mapDeps([36,5,1,6,7,37,11,12,20,23,28,29,30,32,38,39,15,17,40,41,42])))},{id:`erlang`,name:`Erlang`,aliases:[`erl`],import:(()=>D(()=>import(`./erlang-Cphh6RMH.js`),__vite__mapDeps([43,44])))},{id:`fennel`,name:`Fennel`,import:(()=>D(()=>import(`./fennel-DQxkIbk2.js`),[]))},{id:`fish`,name:`Fish`,import:(()=>D(()=>import(`./fish-BJitypiv.js`),[]))},{id:`fluent`,name:`Fluent`,aliases:[`ftl`],import:(()=>D(()=>import(`./fluent-C03EYrpw.js`),[]))},{id:`fortran-fixed-form`,name:`Fortran (Fixed Form)`,aliases:[`f`,`for`,`f77`],import:(()=>D(()=>import(`./fortran-fixed-form-DEKoE2YW.js`),__vite__mapDeps([45,46])))},{id:`fortran-free-form`,name:`Fortran (Free Form)`,aliases:[`f90`,`f95`,`f03`,`f08`,`f18`],import:(()=>D(()=>import(`./fortran-free-form-CYNrtFtB.js`),[]))},{id:`fsharp`,name:`F#`,aliases:[`f#`,`fs`],import:(()=>D(()=>import(`./fsharp-D13ZGOAj.js`),__vite__mapDeps([47,44])))},{id:`gdresource`,name:`GDResource`,aliases:[`tscn`,`tres`],import:(()=>D(()=>import(`./gdresource-C0sCabJj.js`),__vite__mapDeps([48,49,50])))},{id:`gdscript`,name:`GDScript`,aliases:[`gd`],import:(()=>D(()=>import(`./gdscript-Cp2uCuqX.js`),[]))},{id:`gdshader`,name:`GDShader`,import:(()=>D(()=>import(`./gdshader-CBce3t8t.js`),[]))},{id:`genie`,name:`Genie`,import:(()=>D(()=>import(`./genie-CV2tkWYe.js`),[]))},{id:`gherkin`,name:`Gherkin`,import:(()=>D(()=>import(`./gherkin-DExj1W_8.js`),[]))},{id:`git-commit`,name:`Git Commit Message`,import:(()=>D(()=>import(`./git-commit-BSykSTBG.js`),__vite__mapDeps([51,52])))},{id:`git-rebase`,name:`Git Rebase Message`,import:(()=>D(()=>import(`./git-rebase-BDPpS8w6.js`),__vite__mapDeps([53,32,1])))},{id:`gleam`,name:`Gleam`,import:(()=>D(()=>import(`./gleam-CSRkHgEL.js`),[]))},{id:`glimmer-js`,name:`Glimmer JS`,aliases:[`gjs`],import:(()=>D(()=>import(`./glimmer-js-BONyzAsu.js`),__vite__mapDeps([54,6,1,7,5,15])))},{id:`glimmer-ts`,name:`Glimmer TS`,aliases:[`gts`],import:(()=>D(()=>import(`./glimmer-ts-f9c0GCOe.js`),__vite__mapDeps([55,6,1,7,5,15])))},{id:`glsl`,name:`GLSL`,import:(()=>D(()=>import(`./glsl-D5MA2a_X.js`).then(e=>e.n),__vite__mapDeps([30,1,23])))},{id:`gn`,name:`GN`,import:(()=>D(()=>import(`./gn-ilITqXS6.js`),[]))},{id:`gnuplot`,name:`Gnuplot`,import:(()=>D(()=>import(`./gnuplot-7GGW24-e.js`),[]))},{id:`go`,name:`Go`,import:(()=>D(()=>import(`./go-rLFTqkRN.js`),[]))},{id:`graphql`,name:`GraphQL`,aliases:[`gql`],import:(()=>D(()=>import(`./graphql-Ctjuxyvl.js`).then(e=>e.n),__vite__mapDeps([39,1,6,15,17,40])))},{id:`groovy`,name:`Groovy`,import:(()=>D(()=>import(`./groovy-CacY0gHj.js`),[]))},{id:`hack`,name:`Hack`,import:(()=>D(()=>import(`./hack-7ztQ7Up-.js`),__vite__mapDeps([56,5,1,6,7,20])))},{id:`haml`,name:`Ruby Haml`,import:(()=>D(()=>import(`./haml-CwEpbK1d.js`).then(e=>e.n),__vite__mapDeps([38,1,6,7])))},{id:`handlebars`,name:`Handlebars`,aliases:[`hbs`],import:(()=>D(()=>import(`./handlebars-ryMP1rBR.js`),__vite__mapDeps([57,6,1,7,5,42])))},{id:`haskell`,name:`Haskell`,aliases:[`hs`],import:(()=>D(()=>import(`./haskell-D8IpX4py.js`),[]))},{id:`haxe`,name:`Haxe`,import:(()=>D(()=>import(`./haxe-OTjmBuCE.js`),[]))},{id:`hcl`,name:`HashiCorp HCL`,import:(()=>D(()=>import(`./hcl-Dh228itO.js`),[]))},{id:`hjson`,name:`Hjson`,import:(()=>D(()=>import(`./hjson-CxZEssPk.js`),[]))},{id:`hlsl`,name:`HLSL`,import:(()=>D(()=>import(`./hlsl-Cvrh5tZx.js`),[]))},{id:`html`,name:`HTML`,import:(()=>D(()=>import(`./html-XwrE-1r6.js`).then(e=>e.n),__vite__mapDeps([5,1,6,7])))},{id:`html-derivative`,name:`HTML (Derivative)`,import:(()=>D(()=>import(`./html-derivative-i4STDFnl.js`),__vite__mapDeps([19,5,1,6,7])))},{id:`http`,name:`HTTP`,import:(()=>D(()=>import(`./http-kmH8AyfE.js`),__vite__mapDeps([58,11,1,12,13,32,39,6,15,17,40])))},{id:`hurl`,name:`Hurl`,import:(()=>D(()=>import(`./hurl-DCZHXKU4.js`),__vite__mapDeps([59,11,1,12,60,39,6,15,17,40])))},{id:`hxml`,name:`HXML`,import:(()=>D(()=>import(`./hxml-B0Qn7Nwc.js`),__vite__mapDeps([61,62])))},{id:`hy`,name:`Hy`,import:(()=>D(()=>import(`./hy-CZbG8q4J.js`),[]))},{id:`imba`,name:`Imba`,import:(()=>D(()=>import(`./imba-DsUTQ-LC.js`),[]))},{id:`ini`,name:`INI`,aliases:[`properties`],import:(()=>D(()=>import(`./ini-B5eOa1yu.js`),[]))},{id:`java`,name:`Java`,import:(()=>D(()=>import(`./java-DdHNQ9hk.js`).then(e=>e.n),__vite__mapDeps([12,1])))},{id:`javascript`,name:`JavaScript`,aliases:[`js`,`cjs`,`mjs`],import:(()=>D(()=>import(`./javascript-obGGvMPs.js`).then(e=>e.n),__vite__mapDeps([6,1])))},{id:`jinja`,name:`Jinja`,import:(()=>D(()=>import(`./jinja-B-tLrNsM.js`),__vite__mapDeps([63,5,1,6,7])))},{id:`jison`,name:`Jison`,import:(()=>D(()=>import(`./jison-CBjhYtSs.js`),__vite__mapDeps([64,6,1])))},{id:`json`,name:`JSON`,import:(()=>D(()=>import(`./json-DAgxKhMr.js`).then(e=>e.n),__vite__mapDeps([13,1])))},{id:`json5`,name:`JSON5`,import:(()=>D(()=>import(`./json5-BR5RXkoi.js`),[]))},{id:`jsonc`,name:`JSON with Comments`,import:(()=>D(()=>import(`./jsonc-CYpm1nAK.js`),[]))},{id:`jsonl`,name:`JSON Lines`,import:(()=>D(()=>import(`./jsonl-CmCQp5Yx.js`),[]))},{id:`jsonnet`,name:`Jsonnet`,import:(()=>D(()=>import(`./jsonnet-CJTPZ8u_.js`),[]))},{id:`jssm`,name:`JSSM`,aliases:[`fsl`],import:(()=>D(()=>import(`./jssm-DXw9l8Rf.js`),[]))},{id:`jsx`,name:`JSX`,import:(()=>D(()=>import(`./jsx-gTgmArGx.js`).then(e=>e.n),__vite__mapDeps([40,1])))},{id:`julia`,name:`Julia`,aliases:[`jl`],import:(()=>D(()=>import(`./julia-CjHxn3vf.js`),__vite__mapDeps([65,6,1,20,25,28,29,30,23,66])))},{id:`just`,name:`Just`,import:(()=>D(()=>import(`./just-CZ9bduw9.js`),__vite__mapDeps([67,6,1,15,25,32,37,7,5,11,12,20,23,28,29,30,38,39,17,40,41,42,68])))},{id:`kdl`,name:`KDL`,import:(()=>D(()=>import(`./kdl-CsD5j6eV.js`),[]))},{id:`kotlin`,name:`Kotlin`,aliases:[`kt`,`kts`],import:(()=>D(()=>import(`./kotlin-DhhofPvG.js`),[]))},{id:`kusto`,name:`Kusto`,aliases:[`kql`],import:(()=>D(()=>import(`./kusto-C7mF5XQf.js`),[]))},{id:`latex`,name:`LaTeX`,import:(()=>D(()=>import(`./latex-D9bvcAJr.js`),__vite__mapDeps([69,70,66,1])))},{id:`lean`,name:`Lean 4`,aliases:[`lean4`],import:(()=>D(()=>import(`./lean-CewbzKMR.js`),[]))},{id:`less`,name:`Less`,import:(()=>D(()=>import(`./less-DVTAwKKz.js`),[]))},{id:`liquid`,name:`Liquid`,import:(()=>D(()=>import(`./liquid-G0MH4h_m.js`),__vite__mapDeps([71,6,1,7,5,13])))},{id:`llvm`,name:`LLVM IR`,import:(()=>D(()=>import(`./llvm-Cm23YOpf.js`),[]))},{id:`log`,name:`Log file`,import:(()=>D(()=>import(`./log-BNLmms1o.js`),[]))},{id:`logo`,name:`Logo`,import:(()=>D(()=>import(`./logo-Cluzi2Zq.js`),[]))},{id:`lua`,name:`Lua`,import:(()=>D(()=>import(`./lua-FONpmTUP.js`).then(e=>e.n),__vite__mapDeps([41,1,23])))},{id:`luau`,name:`Luau`,import:(()=>D(()=>import(`./luau-CNKltnaQ.js`),[]))},{id:`make`,name:`Makefile`,aliases:[`makefile`],import:(()=>D(()=>import(`./make-Dixweg8N.js`),[]))},{id:`markdown`,name:`Markdown`,aliases:[`md`],import:(()=>D(()=>import(`./markdown-BYOwaDjH.js`),[]))},{id:`marko`,name:`Marko`,import:(()=>D(()=>import(`./marko-DV5GrDmo.js`),__vite__mapDeps([72,7,1,9,15,73])))},{id:`matlab`,name:`MATLAB`,import:(()=>D(()=>import(`./matlab-D7qyCx1q.js`),[]))},{id:`mdc`,name:`MDC`,import:(()=>D(()=>import(`./mdc-cg1lnqpW.js`),__vite__mapDeps([74,19,5,1,6,7,42,44])))},{id:`mdx`,name:`MDX`,import:(()=>D(()=>import(`./mdx-DQZ5AkYe.js`),[]))},{id:`mermaid`,name:`Mermaid`,aliases:[`mmd`],import:(()=>D(()=>import(`./mermaid-Bk4SNUv9.js`),[]))},{id:`mipsasm`,name:`MIPS Assembly`,aliases:[`mips`],import:(()=>D(()=>import(`./mipsasm-BMqwQI7S.js`),[]))},{id:`mojo`,name:`Mojo`,import:(()=>D(()=>import(`./mojo-BgCJLMeH.js`),[]))},{id:`moonbit`,name:`MoonBit`,aliases:[`mbt`,`mbti`],import:(()=>D(()=>import(`./moonbit-CaWjb8XO.js`),[]))},{id:`move`,name:`Move`,import:(()=>D(()=>import(`./move-B1IS1UjX.js`),[]))},{id:`narrat`,name:`Narrat Language`,aliases:[`nar`],import:(()=>D(()=>import(`./narrat-_X_XdTYD.js`),[]))},{id:`nextflow`,name:`Nextflow`,aliases:[`nf`],import:(()=>D(()=>import(`./nextflow-BJtWHP5T.js`),__vite__mapDeps([75,76])))},{id:`nextflow-groovy`,name:`Nextflow Groovy`,import:(()=>D(()=>import(`./nextflow-groovy-DJMQeKeT.js`),[]))},{id:`nginx`,name:`Nginx`,import:(()=>D(()=>import(`./nginx-BTMw9COX.js`),__vite__mapDeps([77,41,1,23])))},{id:`nim`,name:`Nim`,import:(()=>D(()=>import(`./nim-B6yJ_yaC.js`),__vite__mapDeps([78,6,1,7,5,11,12,23,30,44])))},{id:`nix`,name:`Nix`,import:(()=>D(()=>import(`./nix-IvuFDN5E.js`),[]))},{id:`nushell`,name:`nushell`,aliases:[`nu`],import:(()=>D(()=>import(`./nushell-DcLAeLz5.js`),[]))},{id:`objective-c`,name:`Objective-C`,aliases:[`objc`],import:(()=>D(()=>import(`./objective-c-D1A_Heim.js`),[]))},{id:`objective-cpp`,name:`Objective-C++`,import:(()=>D(()=>import(`./objective-cpp-BsSzOQcm.js`),[]))},{id:`ocaml`,name:`OCaml`,import:(()=>D(()=>import(`./ocaml-O90oeIOV.js`),[]))},{id:`odin`,name:`Odin`,import:(()=>D(()=>import(`./odin-B1RWQWA5.js`),[]))},{id:`openscad`,name:`OpenSCAD`,aliases:[`scad`],import:(()=>D(()=>import(`./openscad-BUDT5pXO.js`),[]))},{id:`pascal`,name:`Pascal`,import:(()=>D(()=>import(`./pascal-4ZHwLPI5.js`),[]))},{id:`perl`,name:`Perl`,import:(()=>D(()=>import(`./perl-BAov3eih.js`),__vite__mapDeps([68,6,1,7,5,11,12,20])))},{id:`php`,name:`PHP`,import:(()=>D(()=>import(`./php-Cg76ANFt.js`),__vite__mapDeps([79,6,1,7,5,11,12,13,20])))},{id:`pkl`,name:`Pkl`,import:(()=>D(()=>import(`./pkl-ot-7Btpt.js`),[]))},{id:`plsql`,name:`PL/SQL`,import:(()=>D(()=>import(`./plsql-DGHpHOYJ.js`),[]))},{id:`po`,name:`Gettext PO`,aliases:[`pot`,`potx`],import:(()=>D(()=>import(`./po-BiJDBrnU.js`),[]))},{id:`polar`,name:`Polar`,import:(()=>D(()=>import(`./polar-C7UOKdEL.js`),[]))},{id:`postcss`,name:`PostCSS`,import:(()=>D(()=>import(`./postcss-BXeXVLqQ.js`),[]))},{id:`powerquery`,name:`PowerQuery`,import:(()=>D(()=>import(`./powerquery-DNMTfnFr.js`),[]))},{id:`powershell`,name:`PowerShell`,aliases:[`ps`,`ps1`],import:(()=>D(()=>import(`./powershell-DshXNtvi.js`),[]))},{id:`prisma`,name:`Prisma`,import:(()=>D(()=>import(`./prisma-BsRQq5mF.js`),[]))},{id:`prolog`,name:`Prolog`,import:(()=>D(()=>import(`./prolog-iXnhIJG7.js`),[]))},{id:`proto`,name:`Protocol Buffer 3`,aliases:[`protobuf`],import:(()=>D(()=>import(`./proto-DB4EqR-F.js`),[]))},{id:`pug`,name:`Pug`,aliases:[`jade`],import:(()=>D(()=>import(`./pug-DkgDHZci.js`),__vite__mapDeps([80,6,1,7,5])))},{id:`puppet`,name:`Puppet`,import:(()=>D(()=>import(`./puppet-CDv2pdJW.js`),[]))},{id:`purescript`,name:`PureScript`,import:(()=>D(()=>import(`./purescript-9MfHhQsQ.js`),[]))},{id:`python`,name:`Python`,aliases:[`py`],import:(()=>D(()=>import(`./python-gzcpVVnB.js`),[]))},{id:`qml`,name:`QML`,import:(()=>D(()=>import(`./qml-_a-QhfPD.js`),__vite__mapDeps([81,6,1])))},{id:`qmldir`,name:`QML Directory`,import:(()=>D(()=>import(`./qmldir-DCQb3MpD.js`),[]))},{id:`qss`,name:`Qt Style Sheets`,import:(()=>D(()=>import(`./qss-Fe1Jh2GI.js`),[]))},{id:`r`,name:`R`,import:(()=>D(()=>import(`./r-D6UWEOL2.js`).then(e=>e.n),__vite__mapDeps([66,1])))},{id:`racket`,name:`Racket`,import:(()=>D(()=>import(`./racket-DcIDlBhZ.js`),[]))},{id:`raku`,name:`Raku`,aliases:[`perl6`],import:(()=>D(()=>import(`./raku-B3gFvitq.js`),[]))},{id:`razor`,name:`ASP.NET Razor`,import:(()=>D(()=>import(`./razor-D3EoCAik.js`),__vite__mapDeps([82,5,1,6,7,83])))},{id:`reg`,name:`Windows Registry Script`,import:(()=>D(()=>import(`./reg-CRGYupPL.js`),[]))},{id:`regexp`,name:`RegExp`,aliases:[`regex`],import:(()=>D(()=>import(`./regexp-DR20uMnK.js`).then(e=>e.n),__vite__mapDeps([29,1])))},{id:`rel`,name:`Rel`,import:(()=>D(()=>import(`./rel-BtDbiS_P.js`),[]))},{id:`riscv`,name:`RISC-V`,import:(()=>D(()=>import(`./riscv-Ckw8ddFX.js`),[]))},{id:`ron`,name:`RON`,import:(()=>D(()=>import(`./ron-VUp2lXgN.js`),[]))},{id:`rosmsg`,name:`ROS Interface`,import:(()=>D(()=>import(`./rosmsg-CAekHB0j.js`),[]))},{id:`rst`,name:`reStructuredText`,import:(()=>D(()=>import(`./rst-YTmaoyaq.js`),__vite__mapDeps([84,6,1,19,5,7,25,85,28,20,29,30,23,32,42,37,11,12,38,39,15,17,40,41])))},{id:`ruby`,name:`Ruby`,aliases:[`rb`],import:(()=>D(()=>import(`./ruby-2bd251b9.js`),__vite__mapDeps([37,6,1,7,5,11,12,20,23,28,29,30,32,38,39,15,17,40,41,42])))},{id:`rust`,name:`Rust`,aliases:[`rs`],import:(()=>D(()=>import(`./rust-Cfkwpbl8.js`),[]))},{id:`sas`,name:`SAS`,import:(()=>D(()=>import(`./sas-B6p8-ynO.js`),__vite__mapDeps([86,20,1])))},{id:`sass`,name:`Sass`,import:(()=>D(()=>import(`./sass-DXrisJhu.js`),[]))},{id:`scala`,name:`Scala`,import:(()=>D(()=>import(`./scala-DKOlJaKm.js`),[]))},{id:`scheme`,name:`Scheme`,import:(()=>D(()=>import(`./scheme-DQCgrYNe.js`),[]))},{id:`scss`,name:`SCSS`,import:(()=>D(()=>import(`./scss-YesllqfO.js`).then(e=>e.n),__vite__mapDeps([9,1,7])))},{id:`sdbl`,name:`1C (Query)`,aliases:[`1c-query`],import:(()=>D(()=>import(`./sdbl-bTVj8UrX.js`),[]))},{id:`shaderlab`,name:`ShaderLab`,aliases:[`shader`],import:(()=>D(()=>import(`./shaderlab-TOUzSsQk.js`),__vite__mapDeps([87,88])))},{id:`shellscript`,name:`Shell`,aliases:[`bash`,`sh`,`shell`,`zsh`],import:(()=>D(()=>import(`./shellscript-Da78Ox-3.js`).then(e=>e.n),__vite__mapDeps([32,1])))},{id:`shellsession`,name:`Shell Session`,aliases:[`console`],import:(()=>D(()=>import(`./shellsession-CVsQGYfZ.js`),__vite__mapDeps([89,32,1])))},{id:`smalltalk`,name:`Smalltalk`,import:(()=>D(()=>import(`./smalltalk-B16xEiuN.js`),[]))},{id:`solidity`,name:`Solidity`,import:(()=>D(()=>import(`./solidity-CKzVLygQ.js`),[]))},{id:`soy`,name:`Closure Templates`,aliases:[`closure-templates`],import:(()=>D(()=>import(`./soy-DEd-qcad.js`),__vite__mapDeps([90,5,1,6,7])))},{id:`sparql`,name:`SPARQL`,import:(()=>D(()=>import(`./sparql-D_iOobhT.js`),__vite__mapDeps([91,92])))},{id:`splunk`,name:`Splunk Query Language`,aliases:[`spl`],import:(()=>D(()=>import(`./splunk-BC2Px7Mm.js`),[]))},{id:`sql`,name:`SQL`,import:(()=>D(()=>import(`./sql-ClgswhA6.js`).then(e=>e.n),__vite__mapDeps([20,1])))},{id:`ssh-config`,name:`SSH Config`,import:(()=>D(()=>import(`./ssh-config-BgfXC-Er.js`),[]))},{id:`stata`,name:`Stata`,import:(()=>D(()=>import(`./stata-RoaAgbqU.js`),__vite__mapDeps([93,20,1])))},{id:`stylus`,name:`Stylus`,aliases:[`styl`],import:(()=>D(()=>import(`./stylus-B6D30XZt.js`),[]))},{id:`surrealql`,name:`SurrealQL`,aliases:[`surql`],import:(()=>D(()=>import(`./surrealql-DIn4NJsS.js`),__vite__mapDeps([94,6,1])))},{id:`svelte`,name:`Svelte`,import:(()=>D(()=>import(`./svelte-Bj3Hmc9F.js`),__vite__mapDeps([95,6,1,7,15,16])))},{id:`swift`,name:`Swift`,import:(()=>D(()=>import(`./swift-DonLKvLd.js`),[]))},{id:`system-verilog`,name:`SystemVerilog`,import:(()=>D(()=>import(`./system-verilog-DJ5XKQeo.js`),[]))},{id:`systemd`,name:`Systemd Units`,import:(()=>D(()=>import(`./systemd-BxMlprV5.js`),[]))},{id:`talonscript`,name:`TalonScript`,aliases:[`talon`],import:(()=>D(()=>import(`./talonscript-CohzipZa.js`),[]))},{id:`tasl`,name:`Tasl`,import:(()=>D(()=>import(`./tasl-DMoTqEGO.js`),[]))},{id:`tcl`,name:`Tcl`,import:(()=>D(()=>import(`./tcl-CZd0xW_V.js`),[]))},{id:`templ`,name:`Templ`,import:(()=>D(()=>import(`./templ-TjxbArHn.js`),__vite__mapDeps([96,6,1,7,97])))},{id:`terraform`,name:`Terraform`,aliases:[`tf`,`tfvars`],import:(()=>D(()=>import(`./terraform-DswuEJGm.js`),[]))},{id:`tex`,name:`TeX`,import:(()=>D(()=>import(`./tex-0w6-Dtgt.js`),__vite__mapDeps([70,66,1])))},{id:`toml`,name:`TOML`,import:(()=>D(()=>import(`./toml-CcmNWLt0.js`),[]))},{id:`ts-tags`,name:`TypeScript with Tags`,aliases:[`lit`],import:(()=>D(()=>import(`./ts-tags-DFwAVxhO.js`),__vite__mapDeps([98,6,1,7,5,11,12,15,20,30,23])))},{id:`tsv`,name:`TSV`,import:(()=>D(()=>import(`./tsv-sltzmVWM.js`),[]))},{id:`tsx`,name:`TSX`,import:(()=>D(()=>import(`./tsx-CUOciP0b.js`).then(e=>e.n),__vite__mapDeps([17,1])))},{id:`turtle`,name:`Turtle`,import:(()=>D(()=>import(`./turtle-ByJddavk.js`),[]))},{id:`twig`,name:`Twig`,import:(()=>D(()=>import(`./twig-BbcH-NR0.js`),__vite__mapDeps([99,6,1,7,9,25,37,5,11,12,20,23,28,29,30,32,38,39,15,17,40,41,42,79,13])))},{id:`typescript`,name:`TypeScript`,aliases:[`ts`,`cts`,`mts`],import:(()=>D(()=>import(`./typescript-BydbNFcO.js`).then(e=>e.n),__vite__mapDeps([15,1])))},{id:`typespec`,name:`TypeSpec`,aliases:[`tsp`],import:(()=>D(()=>import(`./typespec-BRdr0IET.js`),[]))},{id:`typst`,name:`Typst`,aliases:[`typ`],import:(()=>D(()=>import(`./typst-DI99ib-x.js`),[]))},{id:`v`,name:`V`,import:(()=>D(()=>import(`./v-DETTlOr0.js`),[]))},{id:`vala`,name:`Vala`,import:(()=>D(()=>import(`./vala-zf12oZj6.js`),[]))},{id:`vb`,name:`Visual Basic`,aliases:[`cmd`],import:(()=>D(()=>import(`./vb-Djn5o6TS.js`),[]))},{id:`verilog`,name:`Verilog`,import:(()=>D(()=>import(`./verilog-CiiDBU1e.js`),[]))},{id:`vhdl`,name:`VHDL`,import:(()=>D(()=>import(`./vhdl-BroJfC0k.js`),[]))},{id:`viml`,name:`Vim Script`,aliases:[`vim`,`vimscript`],import:(()=>D(()=>import(`./viml-DvXPmvsu.js`),[]))},{id:`vue`,name:`Vue`,import:(()=>D(()=>import(`./vue-BNi0qJZP.js`),__vite__mapDeps([100,6,1,7,5,13,15,19])))},{id:`vue-html`,name:`Vue HTML`,import:(()=>D(()=>import(`./vue-html-DkKkQnZL.js`),__vite__mapDeps([101,6,1])))},{id:`vue-vine`,name:`Vue Vine`,import:(()=>D(()=>import(`./vue-vine-DFaKYU4X.js`),__vite__mapDeps([102,6,1,7,9,16,73,103])))},{id:`vyper`,name:`Vyper`,aliases:[`vy`],import:(()=>D(()=>import(`./vyper-CgoNMtux.js`),[]))},{id:`wasm`,name:`WebAssembly`,import:(()=>D(()=>import(`./wasm-ByWQv1Qj.js`),[]))},{id:`wenyan`,name:`Wenyan`,aliases:[`文言`],import:(()=>D(()=>import(`./wenyan-C8pVoKbM.js`),[]))},{id:`wgsl`,name:`WGSL`,import:(()=>D(()=>import(`./wgsl-BsKzXJz4.js`),[]))},{id:`wikitext`,name:`Wikitext`,aliases:[`mediawiki`,`wiki`],import:(()=>D(()=>import(`./wikitext-ClFFjSW2.js`),[]))},{id:`wit`,name:`WebAssembly Interface Types`,import:(()=>D(()=>import(`./wit-DdvCle-K.js`),[]))},{id:`wolfram`,name:`Wolfram`,aliases:[`wl`],import:(()=>D(()=>import(`./wolfram-DLL8P-h_.js`),[]))},{id:`xml`,name:`XML`,import:(()=>D(()=>import(`./xml-BlnrEAEy.js`).then(e=>e.n),__vite__mapDeps([11,1,12])))},{id:`xsl`,name:`XSL`,import:(()=>D(()=>import(`./xsl-BOPS8gLt.js`),__vite__mapDeps([104,11,1,12])))},{id:`yaml`,name:`YAML`,aliases:[`yml`],import:(()=>D(()=>import(`./yaml-Du_6cdrH.js`).then(e=>e.n),__vite__mapDeps([42,1])))},{id:`zenscript`,name:`ZenScript`,import:(()=>D(()=>import(`./zenscript-BnlCZFoB.js`),[]))},{id:`zig`,name:`Zig`,import:(()=>D(()=>import(`./zig-CMLA9XwU.js`),[]))}],CI=Object.fromEntries(SI.map(e=>[e.id,e.import])),wI=Object.fromEntries(SI.flatMap(e=>e.aliases?.map(t=>[t,e.import])||[])),TI={...CI,...wI},EI=Object.fromEntries([{id:`andromeeda`,displayName:`Andromeeda`,type:`dark`,import:(()=>D(()=>import(`./andromeeda-WkhI09AS.js`),[]))},{id:`aurora-x`,displayName:`Aurora X`,type:`dark`,import:(()=>D(()=>import(`./aurora-x-C7CFqhAd.js`),[]))},{id:`ayu-dark`,displayName:`Ayu Dark`,type:`dark`,import:(()=>D(()=>import(`./ayu-dark-CRu61w6_.js`),[]))},{id:`ayu-light`,displayName:`Ayu Light`,type:`light`,import:(()=>D(()=>import(`./ayu-light-Dn6O_aYR.js`),[]))},{id:`ayu-mirage`,displayName:`Ayu Mirage`,type:`dark`,import:(()=>D(()=>import(`./ayu-mirage-CTjYAbs-.js`),[]))},{id:`catppuccin-frappe`,displayName:`Catppuccin Frappé`,type:`dark`,import:(()=>D(()=>import(`./catppuccin-frappe-DFlFW5gh.js`),[]))},{id:`catppuccin-latte`,displayName:`Catppuccin Latte`,type:`light`,import:(()=>D(()=>import(`./catppuccin-latte-CpxdcXpJ.js`),[]))},{id:`catppuccin-macchiato`,displayName:`Catppuccin Macchiato`,type:`dark`,import:(()=>D(()=>import(`./catppuccin-macchiato-DIdIQ04K.js`),[]))},{id:`catppuccin-mocha`,displayName:`Catppuccin Mocha`,type:`dark`,import:(()=>D(()=>import(`./catppuccin-mocha-Co3Xjl64.js`),[]))},{id:`dark-plus`,displayName:`Dark Plus`,type:`dark`,import:(()=>D(()=>import(`./dark-plus-GAt2ZgX8.js`),[]))},{id:`dracula`,displayName:`Dracula Theme`,type:`dark`,import:(()=>D(()=>import(`./dracula-C2uKkzgK.js`),[]))},{id:`dracula-soft`,displayName:`Dracula Theme Soft`,type:`dark`,import:(()=>D(()=>import(`./dracula-soft-D1bVjxWZ.js`),[]))},{id:`everforest-dark`,displayName:`Everforest Dark`,type:`dark`,import:(()=>D(()=>import(`./everforest-dark-D-DlICQR.js`),[]))},{id:`everforest-light`,displayName:`Everforest Light`,type:`light`,import:(()=>D(()=>import(`./everforest-light-CeVdGHYG.js`),[]))},{id:`github-dark`,displayName:`GitHub Dark`,type:`dark`,import:(()=>D(()=>import(`./github-dark-DwbbXv51.js`),[]))},{id:`github-dark-default`,displayName:`GitHub Dark Default`,type:`dark`,import:(()=>D(()=>import(`./github-dark-default-CxjRwzl6.js`),[]))},{id:`github-dark-dimmed`,displayName:`GitHub Dark Dimmed`,type:`dark`,import:(()=>D(()=>import(`./github-dark-dimmed-Cr1oaoul.js`),[]))},{id:`github-dark-high-contrast`,displayName:`GitHub Dark High Contrast`,type:`dark`,import:(()=>D(()=>import(`./github-dark-high-contrast-B4qJZLZa.js`),[]))},{id:`github-light`,displayName:`GitHub Light`,type:`light`,import:(()=>D(()=>import(`./github-light-CsVXhIlR.js`),[]))},{id:`github-light-default`,displayName:`GitHub Light Default`,type:`light`,import:(()=>D(()=>import(`./github-light-default-DB_IwZa6.js`),[]))},{id:`github-light-high-contrast`,displayName:`GitHub Light High Contrast`,type:`light`,import:(()=>D(()=>import(`./github-light-high-contrast-DLgVeSB-.js`),[]))},{id:`gruvbox-dark-hard`,displayName:`Gruvbox Dark Hard`,type:`dark`,import:(()=>D(()=>import(`./gruvbox-dark-hard-DXm60lX3.js`),[]))},{id:`gruvbox-dark-medium`,displayName:`Gruvbox Dark Medium`,type:`dark`,import:(()=>D(()=>import(`./gruvbox-dark-medium-GE2thSmD.js`),[]))},{id:`gruvbox-dark-soft`,displayName:`Gruvbox Dark Soft`,type:`dark`,import:(()=>D(()=>import(`./gruvbox-dark-soft-04Cj-4VZ.js`),[]))},{id:`gruvbox-light-hard`,displayName:`Gruvbox Light Hard`,type:`light`,import:(()=>D(()=>import(`./gruvbox-light-hard-K6wSn29D.js`),[]))},{id:`gruvbox-light-medium`,displayName:`Gruvbox Light Medium`,type:`light`,import:(()=>D(()=>import(`./gruvbox-light-medium-CVy3aSlc.js`),[]))},{id:`gruvbox-light-soft`,displayName:`Gruvbox Light Soft`,type:`light`,import:(()=>D(()=>import(`./gruvbox-light-soft-DNgJjaY0.js`),[]))},{id:`horizon`,displayName:`Horizon`,type:`dark`,import:(()=>D(()=>import(`./horizon-0-RkHfro.js`),[]))},{id:`horizon-bright`,displayName:`Horizon Bright`,type:`light`,import:(()=>D(()=>import(`./horizon-bright-BgL2X9oq.js`),[]))},{id:`houston`,displayName:`Houston`,type:`dark`,import:(()=>D(()=>import(`./houston-KyjWKfuY.js`),[]))},{id:`kanagawa-dragon`,displayName:`Kanagawa Dragon`,type:`dark`,import:(()=>D(()=>import(`./kanagawa-dragon-7TqgsUPC.js`),[]))},{id:`kanagawa-lotus`,displayName:`Kanagawa Lotus`,type:`light`,import:(()=>D(()=>import(`./kanagawa-lotus-CqxMQulh.js`),[]))},{id:`kanagawa-wave`,displayName:`Kanagawa Wave`,type:`dark`,import:(()=>D(()=>import(`./kanagawa-wave-D8CNn6T_.js`),[]))},{id:`laserwave`,displayName:`LaserWave`,type:`dark`,import:(()=>D(()=>import(`./laserwave-CQkdhozh.js`),[]))},{id:`light-plus`,displayName:`Light Plus`,type:`light`,import:(()=>D(()=>import(`./light-plus-CNQ8_7Y0.js`),[]))},{id:`material-theme`,displayName:`Material Theme`,type:`dark`,import:(()=>D(()=>import(`./material-theme-CAtLaHa3.js`),[]))},{id:`material-theme-darker`,displayName:`Material Theme Darker`,type:`dark`,import:(()=>D(()=>import(`./material-theme-darker-k-s5Bc6K.js`),[]))},{id:`material-theme-lighter`,displayName:`Material Theme Lighter`,type:`light`,import:(()=>D(()=>import(`./material-theme-lighter-CD6a-c4d.js`),[]))},{id:`material-theme-ocean`,displayName:`Material Theme Ocean`,type:`dark`,import:(()=>D(()=>import(`./material-theme-ocean-B3mraInd.js`),[]))},{id:`material-theme-palenight`,displayName:`Material Theme Palenight`,type:`dark`,import:(()=>D(()=>import(`./material-theme-palenight-DEhAARHw.js`),[]))},{id:`min-dark`,displayName:`Min Dark`,type:`dark`,import:(()=>D(()=>import(`./min-dark-BFqTAwCr.js`),[]))},{id:`min-light`,displayName:`Min Light`,type:`light`,import:(()=>D(()=>import(`./min-light-O7UdaaxX.js`),[]))},{id:`monokai`,displayName:`Monokai`,type:`dark`,import:(()=>D(()=>import(`./monokai-C0p7Qecz.js`),[]))},{id:`night-owl`,displayName:`Night Owl`,type:`dark`,import:(()=>D(()=>import(`./night-owl-BsnCLAKc.js`),[]))},{id:`night-owl-light`,displayName:`Night Owl Light`,type:`light`,import:(()=>D(()=>import(`./night-owl-light-BODRhcTU.js`),[]))},{id:`nord`,displayName:`Nord`,type:`dark`,import:(()=>D(()=>import(`./nord-Cd-F4txO.js`),[]))},{id:`one-dark-pro`,displayName:`One Dark Pro`,type:`dark`,import:(()=>D(()=>import(`./one-dark-pro-DUS_IGRK.js`),[]))},{id:`one-light`,displayName:`One Light`,type:`light`,import:(()=>D(()=>import(`./one-light-CVUd7yD5.js`),[]))},{id:`plastic`,displayName:`Plastic`,type:`dark`,import:(()=>D(()=>import(`./plastic-CF8VZTnn.js`),[]))},{id:`poimandres`,displayName:`Poimandres`,type:`dark`,import:(()=>D(()=>import(`./poimandres-BX2TyY6j.js`),[]))},{id:`red`,displayName:`Red`,type:`dark`,import:(()=>D(()=>import(`./red-7ga_dcKu.js`),[]))},{id:`rose-pine`,displayName:`Rosé Pine`,type:`dark`,import:(()=>D(()=>import(`./rose-pine-rh6ipraJ.js`),[]))},{id:`rose-pine-dawn`,displayName:`Rosé Pine Dawn`,type:`light`,import:(()=>D(()=>import(`./rose-pine-dawn-DSuRaP6u.js`),[]))},{id:`rose-pine-moon`,displayName:`Rosé Pine Moon`,type:`dark`,import:(()=>D(()=>import(`./rose-pine-moon-DdHjCvFQ.js`),[]))},{id:`slack-dark`,displayName:`Slack Dark`,type:`dark`,import:(()=>D(()=>import(`./slack-dark-DYvUXyrP.js`),[]))},{id:`slack-ochin`,displayName:`Slack Ochin`,type:`light`,import:(()=>D(()=>import(`./slack-ochin-bqtMVDfH.js`),[]))},{id:`snazzy-light`,displayName:`Snazzy Light`,type:`light`,import:(()=>D(()=>import(`./snazzy-light-D8dzFmq5.js`),[]))},{id:`solarized-dark`,displayName:`Solarized Dark`,type:`dark`,import:(()=>D(()=>import(`./solarized-dark-BQwPDzxK.js`),[]))},{id:`solarized-light`,displayName:`Solarized Light`,type:`light`,import:(()=>D(()=>import(`./solarized-light-BLaijb3X.js`),[]))},{id:`synthwave-84`,displayName:`Synthwave '84`,type:`dark`,import:(()=>D(()=>import(`./synthwave-84-CIknw8y7.js`),[]))},{id:`tokyo-night`,displayName:`Tokyo Night`,type:`dark`,import:(()=>D(()=>import(`./tokyo-night-iIspnLcq.js`),[]))},{id:`vesper`,displayName:`Vesper`,type:`dark`,import:(()=>D(()=>import(`./vesper-D5bVUKB1.js`),[]))},{id:`vitesse-black`,displayName:`Vitesse Black`,type:`dark`,import:(()=>D(()=>import(`./vitesse-black-D082JcaE.js`),[]))},{id:`vitesse-dark`,displayName:`Vitesse Dark`,type:`dark`,import:(()=>D(()=>import(`./vitesse-dark-z-nr_5O8.js`),[]))},{id:`vitesse-light`,displayName:`Vitesse Light`,type:`light`,import:(()=>D(()=>import(`./vitesse-light-ojz42ZLy.js`),[]))}].map(e=>[e.id,e.import])),DI=e({createOnigurumaEngine:()=>$I,getDefaultWasmLoader:()=>QI,loadWasm:()=>KI,setDefaultWasmLoader:()=>ZI}),OI=class extends Error{constructor(e){super(e),this.name=`ShikiError`}};function kI(){return 2147483648}function AI(){return typeof performance<`u`?performance.now():Date.now()}var jI=(e,t)=>e+(t-e%t)%t;async function MI(e){let t,n,r={};function i(e){n=e,r.HEAPU8=new Uint8Array(e),r.HEAPU32=new Uint32Array(e)}function a(e,t,n){r.HEAPU8.copyWithin(e,t,t+n)}function o(e){try{return t.grow(e-n.byteLength+65535>>>16),i(t.buffer),1}catch{}}function s(e){let t=r.HEAPU8.length;e>>>=0;let n=kI();if(e>n)return!1;for(let r=1;r<=4;r*=2){let i=t*(1+.2/r);if(i=Math.min(i,e+100663296),o(Math.min(n,jI(Math.max(e,i),65536))))return!0}return!1}let c=typeof TextDecoder<`u`?new TextDecoder(`utf8`):void 0;function l(e,t,n=1024){let r=t+n,i=t;for(;e[i]&&!(i>=r);)++i;if(i-t>16&&e.buffer&&c)return c.decode(e.subarray(t,i));let a=``;for(;t<i;){let n=e[t++];if(!(n&128)){a+=String.fromCharCode(n);continue}let r=e[t++]&63;if((n&224)==192){a+=String.fromCharCode((n&31)<<6|r);continue}let i=e[t++]&63;if(n=(n&240)==224?(n&15)<<12|r<<6|i:(n&7)<<18|r<<12|i<<6|e[t++]&63,n<65536)a+=String.fromCharCode(n);else{let e=n-65536;a+=String.fromCharCode(55296|e>>10,56320|e&1023)}}return a}function u(e,t){return e?l(r.HEAPU8,e,t):``}let d={emscripten_get_now:AI,emscripten_memcpy_big:a,emscripten_resize_heap:s,fd_write:()=>0};async function f(){let n=await e({env:d,wasi_snapshot_preview1:d});t=n.memory,i(t.buffer),Object.assign(r,n),r.UTF8ToString=u}return await f(),r}var NI=Object.defineProperty,PI=(e,t,n)=>t in e?NI(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,K=(e,t,n)=>PI(e,typeof t==`symbol`?t:t+``,n),q=null;function FI(e){throw new OI(e.UTF8ToString(e.getLastOnigError()))}var II=class e{constructor(t){K(this,`utf16Length`),K(this,`utf8Length`),K(this,`utf16Value`),K(this,`utf8Value`),K(this,`utf16OffsetToUtf8`),K(this,`utf8OffsetToUtf16`);let n=t.length,r=e._utf8ByteLength(t),i=r!==n,a=i?new Uint32Array(n+1):null;i&&(a[n]=r);let o=i?new Uint32Array(r+1):null;i&&(o[r]=n);let s=new Uint8Array(r),c=0;for(let e=0;e<n;e++){let r=t.charCodeAt(e),l=r,u=!1;if(r>=55296&&r<=56319&&e+1<n){let n=t.charCodeAt(e+1);n>=56320&&n<=57343&&(l=(r-55296<<10)+65536|n-56320,u=!0)}i&&(a[e]=c,u&&(a[e+1]=c),l<=127?o[c+0]=e:l<=2047?(o[c+0]=e,o[c+1]=e):l<=65535?(o[c+0]=e,o[c+1]=e,o[c+2]=e):(o[c+0]=e,o[c+1]=e,o[c+2]=e,o[c+3]=e)),l<=127?s[c++]=l:l<=2047?(s[c++]=192|(l&1984)>>>6,s[c++]=128|(l&63)>>>0):l<=65535?(s[c++]=224|(l&61440)>>>12,s[c++]=128|(l&4032)>>>6,s[c++]=128|(l&63)>>>0):(s[c++]=240|(l&1835008)>>>18,s[c++]=128|(l&258048)>>>12,s[c++]=128|(l&4032)>>>6,s[c++]=128|(l&63)>>>0),u&&e++}this.utf16Length=n,this.utf8Length=r,this.utf16Value=t,this.utf8Value=s,this.utf16OffsetToUtf8=a,this.utf8OffsetToUtf16=o}static _utf8ByteLength(e){let t=0;for(let n=0,r=e.length;n<r;n++){let i=e.charCodeAt(n),a=i,o=!1;if(i>=55296&&i<=56319&&n+1<r){let t=e.charCodeAt(n+1);t>=56320&&t<=57343&&(a=(i-55296<<10)+65536|t-56320,o=!0)}t+=a<=127?1:a<=2047?2:a<=65535?3:4,o&&n++}return t}createString(e){let t=e.omalloc(this.utf8Length);return e.HEAPU8.set(this.utf8Value,t),t}},LI=class e{constructor(t){if(K(this,`id`,++e.LAST_ID),K(this,`_onigBinding`),K(this,`content`),K(this,`utf16Length`),K(this,`utf8Length`),K(this,`utf16OffsetToUtf8`),K(this,`utf8OffsetToUtf16`),K(this,`ptr`),!q)throw new OI(`Must invoke loadWasm first.`);this._onigBinding=q,this.content=t;let n=new II(t);this.utf16Length=n.utf16Length,this.utf8Length=n.utf8Length,this.utf16OffsetToUtf8=n.utf16OffsetToUtf8,this.utf8OffsetToUtf16=n.utf8OffsetToUtf16,this.utf8Length<1e4&&!e._sharedPtrInUse?(e._sharedPtr||=q.omalloc(1e4),e._sharedPtrInUse=!0,q.HEAPU8.set(n.utf8Value,e._sharedPtr),this.ptr=e._sharedPtr):this.ptr=n.createString(q)}convertUtf8OffsetToUtf16(e){return this.utf8OffsetToUtf16?e<0?0:e>this.utf8Length?this.utf16Length:this.utf8OffsetToUtf16[e]:e}convertUtf16OffsetToUtf8(e){return this.utf16OffsetToUtf8?e<0?0:e>this.utf16Length?this.utf8Length:this.utf16OffsetToUtf8[e]:e}dispose(){this.ptr===e._sharedPtr?e._sharedPtrInUse=!1:this._onigBinding.ofree(this.ptr)}};K(LI,`LAST_ID`,0),K(LI,`_sharedPtr`,0),K(LI,`_sharedPtrInUse`,!1);var RI=LI,zI=class{constructor(e){if(K(this,`_onigBinding`),K(this,`_ptr`),!q)throw new OI(`Must invoke loadWasm first.`);let t=[],n=[];for(let r=0,i=e.length;r<i;r++){let i=new II(e[r]);t[r]=i.createString(q),n[r]=i.utf8Length}let r=q.omalloc(4*e.length);q.HEAPU32.set(t,r/4);let i=q.omalloc(4*e.length);q.HEAPU32.set(n,i/4);let a=q.createOnigScanner(r,i,e.length);for(let n=0,r=e.length;n<r;n++)q.ofree(t[n]);q.ofree(i),q.ofree(r),a===0&&FI(q),this._onigBinding=q,this._ptr=a}dispose(){this._onigBinding.freeOnigScanner(this._ptr)}findNextMatchSync(e,t,n){let r=0;if(typeof n==`number`&&(r=n),typeof e==`string`){e=new RI(e);let n=this._findNextMatchSync(e,t,!1,r);return e.dispose(),n}return this._findNextMatchSync(e,t,!1,r)}_findNextMatchSync(e,t,n,r){let i=this._onigBinding,a=i.findNextOnigScannerMatch(this._ptr,e.id,e.ptr,e.utf8Length,e.convertUtf16OffsetToUtf8(t),r);if(a===0)return null;let o=i.HEAPU32,s=a/4,c=o[s++],l=o[s++],u=[];for(let t=0;t<l;t++){let n=e.convertUtf8OffsetToUtf16(o[s++]),r=e.convertUtf8OffsetToUtf16(o[s++]);u[t]={start:n,end:r,length:r-n}}return{index:c,captureIndices:u}}};function BI(e){return typeof e.instantiator==`function`}function VI(e){return typeof e.default==`function`}function HI(e){return e.data!==void 0}function UI(e){return typeof Response<`u`&&e instanceof Response}function WI(e){return typeof ArrayBuffer<`u`&&(e instanceof ArrayBuffer||ArrayBuffer.isView(e))||typeof Buffer<`u`&&Buffer.isBuffer?.(e)||typeof SharedArrayBuffer<`u`&&e instanceof SharedArrayBuffer||typeof Uint32Array<`u`&&e instanceof Uint32Array}var GI;function KI(e){if(GI)return GI;async function t(){q=await MI(async t=>{let n=e;return n=await n,typeof n==`function`&&(n=await n(t)),typeof n==`function`&&(n=await n(t)),BI(n)?n=await n.instantiator(t):VI(n)?n=await n.default(t):(HI(n)&&(n=n.data),UI(n)?n=typeof WebAssembly.instantiateStreaming==`function`?await JI(n)(t):await YI(n)(t):WI(n)||n instanceof WebAssembly.Module?n=await qI(n)(t):`default`in n&&n.default instanceof WebAssembly.Module&&(n=await qI(n.default)(t))),`instance`in n&&(n=n.instance),`exports`in n&&(n=n.exports),n})}return GI=t(),GI}function qI(e){return t=>WebAssembly.instantiate(e,t)}function JI(e){return t=>WebAssembly.instantiateStreaming(e,t)}function YI(e){return async t=>{let n=await e.arrayBuffer();return WebAssembly.instantiate(n,t)}}var XI;function ZI(e){XI=e}function QI(){return XI}async function $I(e){return e&&await KI(e),{createScanner(e){return new zI(e.map(e=>typeof e==`string`?e:e.source))},createString(e){return new RI(e)}}}var eL=yI({});xI(eL,DI);var J=class extends Error{constructor(e){super(e),this.name=`ShikiError`}};function tL(e){return nL(e)}function nL(e){return Array.isArray(e)?rL(e):e instanceof RegExp?e:typeof e==`object`?iL(e):e}function rL(e){let t=[];for(let n=0,r=e.length;n<r;n++)t[n]=nL(e[n]);return t}function iL(e){let t={};for(let n in e)t[n]=nL(e[n]);return t}function aL(e,...t){return t.forEach(t=>{for(let n in t)e[n]=t[n]}),e}function oL(e){let t=~e.lastIndexOf(`/`)||~e.lastIndexOf(`\\`);return t===0?e:~t===e.length-1?oL(e.substring(0,e.length-1)):e.substr(~t+1)}var sL=/\$(\d+)|\${(\d+):\/(downcase|upcase)}/g,cL=class{static hasCaptures(e){return e!==null&&(sL.lastIndex=0,sL.test(e))}static replaceCaptures(e,t,n){return e.replace(sL,(e,r,i,a)=>{let o=n[parseInt(r||i,10)];if(o){let e=t.substring(o.start,o.end);for(;e[0]===`.`;)e=e.substring(1);switch(a){case`downcase`:return e.toLowerCase();case`upcase`:return e.toUpperCase();default:return e}}else return e})}};function lL(e,t){return e<t?-1:+(e>t)}function uL(e,t){if(e===null&&t===null)return 0;if(!e)return-1;if(!t)return 1;let n=e.length,r=t.length;if(n===r){for(let r=0;r<n;r++){let n=lL(e[r],t[r]);if(n!==0)return n}return 0}return n-r}function dL(e){return!!(/^#[0-9a-f]{6}$/i.test(e)||/^#[0-9a-f]{8}$/i.test(e)||/^#[0-9a-f]{3}$/i.test(e)||/^#[0-9a-f]{4}$/i.test(e))}function fL(e){return e.replace(/[\-\\\{\}\*\+\?\|\^\$\.\,\[\]\(\)\#\s]/g,`\\$&`)}var pL=class{constructor(e){this.fn=e}cache=new Map;get(e){if(this.cache.has(e))return this.cache.get(e);let t=this.fn(e);return this.cache.set(e,t),t}},mL=class{constructor(e,t,n){this._colorMap=e,this._defaults=t,this._root=n}static createFromRawTheme(e,t){return this.createFromParsedTheme(yL(e),t)}static createFromParsedTheme(e,t){return xL(e,t)}_cachedMatchRoot=new pL(e=>this._root.match(e));getColorMap(){return this._colorMap.getColorMap()}getDefaults(){return this._defaults}match(e){if(e===null)return this._defaults;let t=e.scopeName,n=this._cachedMatchRoot.get(t).find(t=>gL(e.parent,t.parentScopes));return n?new vL(n.fontStyle,n.foreground,n.background):null}},hL=class e{constructor(e,t){this.parent=e,this.scopeName=t}static push(t,n){for(let r of n)t=new e(t,r);return t}static from(...t){let n=null;for(let r=0;r<t.length;r++)n=new e(n,t[r]);return n}push(t){return new e(this,t)}getSegments(){let e=this,t=[];for(;e;)t.push(e.scopeName),e=e.parent;return t.reverse(),t}toString(){return this.getSegments().join(` `)}extends(e){return this===e||this.parent!==null&&this.parent.extends(e)}getExtensionIfDefined(e){let t=[],n=this;for(;n&&n!==e;)t.push(n.scopeName),n=n.parent;return n===e?t.reverse():void 0}};function gL(e,t){if(t.length===0)return!0;for(let n=0;n<t.length;n++){let r=t[n],i=!1;if(r===`>`){if(n===t.length-1)return!1;r=t[++n],i=!0}for(;e&&!_L(e.scopeName,r);){if(i)return!1;e=e.parent}if(!e)return!1;e=e.parent}return!0}function _L(e,t){return t===e||e.startsWith(t)&&e[t.length]===`.`}var vL=class{constructor(e,t,n){this.fontStyle=e,this.foregroundId=t,this.backgroundId=n}};function yL(e){if(!e||!e.settings||!Array.isArray(e.settings))return[];let t=e.settings,n=[],r=0;for(let e=0,i=t.length;e<i;e++){let i=t[e];if(!i.settings)continue;let a;if(typeof i.scope==`string`){let e=i.scope;e=e.replace(/^[,]+/,``),e=e.replace(/[,]+$/,``),a=e.split(`,`)}else a=Array.isArray(i.scope)?i.scope:[``];let o=-1;if(typeof i.settings.fontStyle==`string`){o=0;let e=i.settings.fontStyle.split(` `);for(let t=0,n=e.length;t<n;t++)switch(e[t]){case`italic`:o|=1;break;case`bold`:o|=2;break;case`underline`:o|=4;break;case`strikethrough`:o|=8}}let s=null;typeof i.settings.foreground==`string`&&dL(i.settings.foreground)&&(s=i.settings.foreground);let c=null;typeof i.settings.background==`string`&&dL(i.settings.background)&&(c=i.settings.background);for(let t=0,i=a.length;t<i;t++){let i=a[t].trim().split(` `),l=i[i.length-1],u=null;i.length>1&&(u=i.slice(0,i.length-1),u.reverse()),n[r++]=new bL(l,u,e,o,s,c)}}return n}var bL=class{constructor(e,t,n,r,i,a){this.scope=e,this.parentScopes=t,this.index=n,this.fontStyle=r,this.foreground=i,this.background=a}},Y=(e=>(e[e.NotSet=-1]=`NotSet`,e[e.None=0]=`None`,e[e.Italic=1]=`Italic`,e[e.Bold=2]=`Bold`,e[e.Underline=4]=`Underline`,e[e.Strikethrough=8]=`Strikethrough`,e))(Y||{});function xL(e,t){e.sort((e,t)=>{let n=lL(e.scope,t.scope);return n!==0||(n=uL(e.parentScopes,t.parentScopes),n!==0)?n:e.index-t.index});let n=0,r=`#000000`,i=`#ffffff`;for(;e.length>=1&&e[0].scope===``;){let t=e.shift();t.fontStyle!==-1&&(n=t.fontStyle),t.foreground!==null&&(r=t.foreground),t.background!==null&&(i=t.background)}let a=new SL(t),o=new vL(n,a.getId(r),a.getId(i)),s=new TL(new wL(0,null,-1,0,0),[]);for(let t=0,n=e.length;t<n;t++){let n=e[t];s.insert(0,n.scope,n.parentScopes,n.fontStyle,a.getId(n.foreground),a.getId(n.background))}return new mL(a,o,s)}var SL=class{_isFrozen;_lastColorId;_id2color;_color2id;constructor(e){if(this._lastColorId=0,this._id2color=[],this._color2id=Object.create(null),Array.isArray(e)){this._isFrozen=!0;for(let t=0,n=e.length;t<n;t++)this._color2id[e[t]]=t,this._id2color[t]=e[t]}else this._isFrozen=!1}getId(e){if(e===null)return 0;e=e.toUpperCase();let t=this._color2id[e];if(t)return t;if(this._isFrozen)throw Error(`Missing color in color map - ${e}`);return t=++this._lastColorId,this._color2id[e]=t,this._id2color[t]=e,t}getColorMap(){return this._id2color.slice(0)}},CL=Object.freeze([]),wL=class e{scopeDepth;parentScopes;fontStyle;foreground;background;constructor(e,t,n,r,i){this.scopeDepth=e,this.parentScopes=t||CL,this.fontStyle=n,this.foreground=r,this.background=i}clone(){return new e(this.scopeDepth,this.parentScopes,this.fontStyle,this.foreground,this.background)}static cloneArr(e){let t=[];for(let n=0,r=e.length;n<r;n++)t[n]=e[n].clone();return t}acceptOverwrite(e,t,n,r){this.scopeDepth>e?console.log(`how did this happen?`):this.scopeDepth=e,t!==-1&&(this.fontStyle=t),n!==0&&(this.foreground=n),r!==0&&(this.background=r)}},TL=class e{constructor(e,t=[],n={}){this._mainRule=e,this._children=n,this._rulesWithParentScopes=t}_rulesWithParentScopes;static _cmpBySpecificity(e,t){if(e.scopeDepth!==t.scopeDepth)return t.scopeDepth-e.scopeDepth;let n=0,r=0;for(;e.parentScopes[n]===`>`&&n++,t.parentScopes[r]===`>`&&r++,!(n>=e.parentScopes.length||r>=t.parentScopes.length);){let i=t.parentScopes[r].length-e.parentScopes[n].length;if(i!==0)return i;n++,r++}return t.parentScopes.length-e.parentScopes.length}match(t){if(t!==``){let e=t.indexOf(`.`),n,r;if(e===-1?(n=t,r=``):(n=t.substring(0,e),r=t.substring(e+1)),this._children.hasOwnProperty(n))return this._children[n].match(r)}let n=this._rulesWithParentScopes.concat(this._mainRule);return n.sort(e._cmpBySpecificity),n}insert(t,n,r,i,a,o){if(n===``){this._doInsertHere(t,r,i,a,o);return}let s=n.indexOf(`.`),c,l;s===-1?(c=n,l=``):(c=n.substring(0,s),l=n.substring(s+1));let u;this._children.hasOwnProperty(c)?u=this._children[c]:(u=new e(this._mainRule.clone(),wL.cloneArr(this._rulesWithParentScopes)),this._children[c]=u),u.insert(t+1,l,r,i,a,o)}_doInsertHere(e,t,n,r,i){if(t===null){this._mainRule.acceptOverwrite(e,n,r,i);return}for(let a=0,o=this._rulesWithParentScopes.length;a<o;a++){let o=this._rulesWithParentScopes[a];if(uL(o.parentScopes,t)===0){o.acceptOverwrite(e,n,r,i);return}}n===-1&&(n=this._mainRule.fontStyle),r===0&&(r=this._mainRule.foreground),i===0&&(i=this._mainRule.background),this._rulesWithParentScopes.push(new wL(e,t,n,r,i))}},EL=class e{static toBinaryStr(e){return e.toString(2).padStart(32,`0`)}static print(t){let n=e.getLanguageId(t),r=e.getTokenType(t),i=e.getFontStyle(t),a=e.getForeground(t),o=e.getBackground(t);console.log({languageId:n,tokenType:r,fontStyle:i,foreground:a,background:o})}static getLanguageId(e){return(e&255)>>>0}static getTokenType(e){return(e&768)>>>8}static containsBalancedBrackets(e){return!!(e&1024)}static getFontStyle(e){return(e&30720)>>>11}static getForeground(e){return(e&16744448)>>>15}static getBackground(e){return(e&4278190080)>>>24}static set(t,n,r,i,a,o,s){let c=e.getLanguageId(t),l=e.getTokenType(t),u=+!!e.containsBalancedBrackets(t),d=e.getFontStyle(t),f=e.getForeground(t),p=e.getBackground(t);return n!==0&&(c=n),r!==8&&(l=OL(r)),i!==null&&(u=+!!i),a!==-1&&(d=a),o!==0&&(f=o),s!==0&&(p=s),(c<<0|l<<8|u<<10|d<<11|f<<15|p<<24)>>>0}};function DL(e){return e}function OL(e){return e}function kL(e,t){let n=[],r=jL(e),i=r.next();for(;i!==null;){let e=0;if(i.length===2&&i.charAt(1)===`:`){switch(i.charAt(0)){case`R`:e=1;break;case`L`:e=-1;break;default:console.log(`Unknown priority ${i} in scope selector`)}i=r.next()}let t=o();if(n.push({matcher:t,priority:e}),i!==`,`)break;i=r.next()}return n;function a(){if(i===`-`){i=r.next();let e=a();return t=>!!e&&!e(t)}if(i===`(`){i=r.next();let e=s();return i===`)`&&(i=r.next()),e}if(AL(i)){let e=[];do e.push(i),i=r.next();while(AL(i));return n=>t(e,n)}return null}function o(){let e=[],t=a();for(;t;)e.push(t),t=a();return t=>e.every(e=>e(t))}function s(){let e=[],t=o();for(;t&&(e.push(t),i===`|`||i===`,`);){do i=r.next();while(i===`|`||i===`,`);t=o()}return t=>e.some(e=>e(t))}}function AL(e){return!!e&&!!e.match(/[\w\.:]+/)}function jL(e){let t=/([LR]:|[\w\.:][\w\.:\-]*|[\,\|\-\(\)])/g,n=t.exec(e);return{next:()=>{if(!n)return null;let r=n[0];return n=t.exec(e),r}}}function ML(e){typeof e.dispose==`function`&&e.dispose()}var NL=class{constructor(e){this.scopeName=e}toKey(){return this.scopeName}},PL=class{constructor(e,t){this.scopeName=e,this.ruleName=t}toKey(){return`${this.scopeName}#${this.ruleName}`}},FL=class{_references=[];_seenReferenceKeys=new Set;get references(){return this._references}visitedRule=new Set;add(e){let t=e.toKey();this._seenReferenceKeys.has(t)||(this._seenReferenceKeys.add(t),this._references.push(e))}},IL=class{constructor(e,t){this.repo=e,this.initialScopeName=t,this.seenFullScopeRequests.add(this.initialScopeName),this.Q=[new NL(this.initialScopeName)]}seenFullScopeRequests=new Set;seenPartialScopeRequests=new Set;Q;processQueue(){let e=this.Q;this.Q=[];let t=new FL;for(let n of e)LL(n,this.initialScopeName,this.repo,t);for(let e of t.references)if(e instanceof NL){if(this.seenFullScopeRequests.has(e.scopeName))continue;this.seenFullScopeRequests.add(e.scopeName),this.Q.push(e)}else{if(this.seenFullScopeRequests.has(e.scopeName)||this.seenPartialScopeRequests.has(e.toKey()))continue;this.seenPartialScopeRequests.add(e.toKey()),this.Q.push(e)}}};function LL(e,t,n,r){let i=n.lookup(e.scopeName);if(!i){if(e.scopeName===t)throw Error(`No grammar provided for <${t}>`);return}let a=n.lookup(t);e instanceof NL?zL({baseGrammar:a,selfGrammar:i},r):RL(e.ruleName,{baseGrammar:a,selfGrammar:i,repository:i.repository},r);let o=n.injections(e.scopeName);if(o)for(let e of o)r.add(new NL(e))}function RL(e,t,n){if(t.repository&&t.repository[e]){let r=t.repository[e];BL([r],t,n)}}function zL(e,t){e.selfGrammar.patterns&&Array.isArray(e.selfGrammar.patterns)&&BL(e.selfGrammar.patterns,{...e,repository:e.selfGrammar.repository},t),e.selfGrammar.injections&&BL(Object.values(e.selfGrammar.injections),{...e,repository:e.selfGrammar.repository},t)}function BL(e,t,n){for(let r of e){if(n.visitedRule.has(r))continue;n.visitedRule.add(r);let e=r.repository?aL({},t.repository,r.repository):t.repository;Array.isArray(r.patterns)&&BL(r.patterns,{...t,repository:e},n);let i=r.include;if(!i)continue;let a=KL(i);switch(a.kind){case 0:zL({...t,selfGrammar:t.baseGrammar},n);break;case 1:zL(t,n);break;case 2:RL(a.ruleName,{...t,repository:e},n);break;case 3:case 4:let r=a.scopeName===t.selfGrammar.scopeName?t.selfGrammar:a.scopeName===t.baseGrammar.scopeName?t.baseGrammar:void 0;if(r){let i={baseGrammar:t.baseGrammar,selfGrammar:r,repository:e};a.kind===4?RL(a.ruleName,i,n):zL(i,n)}else a.kind===4?n.add(new PL(a.scopeName,a.ruleName)):n.add(new NL(a.scopeName))}}}var VL=class{kind=0},HL=class{kind=1},UL=class{constructor(e){this.ruleName=e}kind=2},WL=class{constructor(e){this.scopeName=e}kind=3},GL=class{constructor(e,t){this.scopeName=e,this.ruleName=t}kind=4};function KL(e){if(e===`$base`)return new VL;if(e===`$self`)return new HL;let t=e.indexOf(`#`);return t===-1?new WL(e):t===0?new UL(e.substring(1)):new GL(e.substring(0,t),e.substring(t+1))}var qL=/\\(\d+)/,JL=/\\(\d+)/g,YL=-1,XL=-2;function ZL(e){return e}function QL(e){return e}var $L=class{$location;id;_nameIsCapturing;_name;_contentNameIsCapturing;_contentName;constructor(e,t,n,r){this.$location=e,this.id=t,this._name=n||null,this._nameIsCapturing=cL.hasCaptures(this._name),this._contentName=r||null,this._contentNameIsCapturing=cL.hasCaptures(this._contentName)}get debugName(){let e=this.$location?`${oL(this.$location.filename)}:${this.$location.line}`:`unknown`;return`${this.constructor.name}#${this.id} @ ${e}`}getName(e,t){return!this._nameIsCapturing||this._name===null||e===null||t===null?this._name:cL.replaceCaptures(this._name,e,t)}getContentName(e,t){return!this._contentNameIsCapturing||this._contentName===null?this._contentName:cL.replaceCaptures(this._contentName,e,t)}},eR=class extends $L{retokenizeCapturedWithRuleId;constructor(e,t,n,r,i){super(e,t,n,r),this.retokenizeCapturedWithRuleId=i}dispose(){}collectPatterns(e,t){throw Error(`Not supported!`)}compile(e,t){throw Error(`Not supported!`)}compileAG(e,t,n,r){throw Error(`Not supported!`)}},tR=class extends $L{_match;captures;_cachedCompiledPatterns;constructor(e,t,n,r,i){super(e,t,n,null),this._match=new oR(r,this.id),this.captures=i,this._cachedCompiledPatterns=null}dispose(){this._cachedCompiledPatterns&&=(this._cachedCompiledPatterns.dispose(),null)}get debugMatchRegExp(){return`${this._match.source}`}collectPatterns(e,t){t.push(this._match)}compile(e,t){return this._getCachedCompiledPatterns(e).compile(e)}compileAG(e,t,n,r){return this._getCachedCompiledPatterns(e).compileAG(e,n,r)}_getCachedCompiledPatterns(e){return this._cachedCompiledPatterns||(this._cachedCompiledPatterns=new sR,this.collectPatterns(e,this._cachedCompiledPatterns)),this._cachedCompiledPatterns}},nR=class extends $L{hasMissingPatterns;patterns;_cachedCompiledPatterns;constructor(e,t,n,r,i){super(e,t,n,r),this.patterns=i.patterns,this.hasMissingPatterns=i.hasMissingPatterns,this._cachedCompiledPatterns=null}dispose(){this._cachedCompiledPatterns&&=(this._cachedCompiledPatterns.dispose(),null)}collectPatterns(e,t){for(let n of this.patterns)e.getRule(n).collectPatterns(e,t)}compile(e,t){return this._getCachedCompiledPatterns(e).compile(e)}compileAG(e,t,n,r){return this._getCachedCompiledPatterns(e).compileAG(e,n,r)}_getCachedCompiledPatterns(e){return this._cachedCompiledPatterns||(this._cachedCompiledPatterns=new sR,this.collectPatterns(e,this._cachedCompiledPatterns)),this._cachedCompiledPatterns}},rR=class extends $L{_begin;beginCaptures;_end;endHasBackReferences;endCaptures;applyEndPatternLast;hasMissingPatterns;patterns;_cachedCompiledPatterns;constructor(e,t,n,r,i,a,o,s,c,l){super(e,t,n,r),this._begin=new oR(i,this.id),this.beginCaptures=a,this._end=new oR(o||``,-1),this.endHasBackReferences=this._end.hasBackReferences,this.endCaptures=s,this.applyEndPatternLast=c||!1,this.patterns=l.patterns,this.hasMissingPatterns=l.hasMissingPatterns,this._cachedCompiledPatterns=null}dispose(){this._cachedCompiledPatterns&&=(this._cachedCompiledPatterns.dispose(),null)}get debugBeginRegExp(){return`${this._begin.source}`}get debugEndRegExp(){return`${this._end.source}`}getEndWithResolvedBackReferences(e,t){return this._end.resolveBackReferences(e,t)}collectPatterns(e,t){t.push(this._begin)}compile(e,t){return this._getCachedCompiledPatterns(e,t).compile(e)}compileAG(e,t,n,r){return this._getCachedCompiledPatterns(e,t).compileAG(e,n,r)}_getCachedCompiledPatterns(e,t){if(!this._cachedCompiledPatterns){this._cachedCompiledPatterns=new sR;for(let t of this.patterns)e.getRule(t).collectPatterns(e,this._cachedCompiledPatterns);this.applyEndPatternLast?this._cachedCompiledPatterns.push(this._end.hasBackReferences?this._end.clone():this._end):this._cachedCompiledPatterns.unshift(this._end.hasBackReferences?this._end.clone():this._end)}return this._end.hasBackReferences&&(this.applyEndPatternLast?this._cachedCompiledPatterns.setSource(this._cachedCompiledPatterns.length()-1,t):this._cachedCompiledPatterns.setSource(0,t)),this._cachedCompiledPatterns}},iR=class extends $L{_begin;beginCaptures;whileCaptures;_while;whileHasBackReferences;hasMissingPatterns;patterns;_cachedCompiledPatterns;_cachedCompiledWhilePatterns;constructor(e,t,n,r,i,a,o,s,c){super(e,t,n,r),this._begin=new oR(i,this.id),this.beginCaptures=a,this.whileCaptures=s,this._while=new oR(o,XL),this.whileHasBackReferences=this._while.hasBackReferences,this.patterns=c.patterns,this.hasMissingPatterns=c.hasMissingPatterns,this._cachedCompiledPatterns=null,this._cachedCompiledWhilePatterns=null}dispose(){this._cachedCompiledPatterns&&=(this._cachedCompiledPatterns.dispose(),null),this._cachedCompiledWhilePatterns&&=(this._cachedCompiledWhilePatterns.dispose(),null)}get debugBeginRegExp(){return`${this._begin.source}`}get debugWhileRegExp(){return`${this._while.source}`}getWhileWithResolvedBackReferences(e,t){return this._while.resolveBackReferences(e,t)}collectPatterns(e,t){t.push(this._begin)}compile(e,t){return this._getCachedCompiledPatterns(e).compile(e)}compileAG(e,t,n,r){return this._getCachedCompiledPatterns(e).compileAG(e,n,r)}_getCachedCompiledPatterns(e){if(!this._cachedCompiledPatterns){this._cachedCompiledPatterns=new sR;for(let t of this.patterns)e.getRule(t).collectPatterns(e,this._cachedCompiledPatterns)}return this._cachedCompiledPatterns}compileWhile(e,t){return this._getCachedCompiledWhilePatterns(e,t).compile(e)}compileWhileAG(e,t,n,r){return this._getCachedCompiledWhilePatterns(e,t).compileAG(e,n,r)}_getCachedCompiledWhilePatterns(e,t){return this._cachedCompiledWhilePatterns||(this._cachedCompiledWhilePatterns=new sR,this._cachedCompiledWhilePatterns.push(this._while.hasBackReferences?this._while.clone():this._while)),this._while.hasBackReferences&&this._cachedCompiledWhilePatterns.setSource(0,t||``),this._cachedCompiledWhilePatterns}},aR=class e{static createCaptureRule(e,t,n,r,i){return e.registerRule(e=>new eR(t,e,n,r,i))}static getCompiledRuleId(t,n,r){return t.id||n.registerRule(i=>{if(t.id=i,t.match)return new tR(t.$vscodeTextmateLocation,t.id,t.name,t.match,e._compileCaptures(t.captures,n,r));if(t.begin===void 0){t.repository&&(r=aL({},r,t.repository));let i=t.patterns;return i===void 0&&t.include&&(i=[{include:t.include}]),new nR(t.$vscodeTextmateLocation,t.id,t.name,t.contentName,e._compilePatterns(i,n,r))}return t.while?new iR(t.$vscodeTextmateLocation,t.id,t.name,t.contentName,t.begin,e._compileCaptures(t.beginCaptures||t.captures,n,r),t.while,e._compileCaptures(t.whileCaptures||t.captures,n,r),e._compilePatterns(t.patterns,n,r)):new rR(t.$vscodeTextmateLocation,t.id,t.name,t.contentName,t.begin,e._compileCaptures(t.beginCaptures||t.captures,n,r),t.end,e._compileCaptures(t.endCaptures||t.captures,n,r),t.applyEndPatternLast,e._compilePatterns(t.patterns,n,r))}),t.id}static _compileCaptures(t,n,r){let i=[];if(t){let a=0;for(let e in t){if(e===`$vscodeTextmateLocation`)continue;let t=parseInt(e,10);t>a&&(a=t)}for(let e=0;e<=a;e++)i[e]=null;for(let a in t){if(a===`$vscodeTextmateLocation`)continue;let o=parseInt(a,10),s=0;t[a].patterns&&(s=e.getCompiledRuleId(t[a],n,r)),i[o]=e.createCaptureRule(n,t[a].$vscodeTextmateLocation,t[a].name,t[a].contentName,s)}}return i}static _compilePatterns(t,n,r){let i=[];if(t)for(let a=0,o=t.length;a<o;a++){let o=t[a],s=-1;if(o.include){let t=KL(o.include);switch(t.kind){case 0:case 1:s=e.getCompiledRuleId(r[o.include],n,r);break;case 2:let i=r[t.ruleName];i&&(s=e.getCompiledRuleId(i,n,r));break;case 3:case 4:let a=t.scopeName,c=t.kind===4?t.ruleName:null,l=n.getExternalGrammar(a,r);if(l)if(c){let t=l.repository[c];t&&(s=e.getCompiledRuleId(t,n,l.repository))}else s=e.getCompiledRuleId(l.repository.$self,n,l.repository)}}else s=e.getCompiledRuleId(o,n,r);if(s!==-1){let e=n.getRule(s),t=!1;if((e instanceof nR||e instanceof rR||e instanceof iR)&&e.hasMissingPatterns&&e.patterns.length===0&&(t=!0),t)continue;i.push(s)}}return{patterns:i,hasMissingPatterns:(t?t.length:0)!==i.length}}},oR=class e{source;ruleId;hasAnchor;hasBackReferences;_anchorCache;constructor(e,t){if(e&&typeof e==`string`){let t=e.length,n=0,r=[],i=!1;for(let a=0;a<t;a++)if(e.charAt(a)===`\\`&&a+1<t){let t=e.charAt(a+1);t===`z`?(r.push(e.substring(n,a)),r.push(`$(?!\\n)(?<!\\n)`),n=a+2):(t===`A`||t===`G`)&&(i=!0),a++}this.hasAnchor=i,n===0?this.source=e:(r.push(e.substring(n,t)),this.source=r.join(``))}else this.hasAnchor=!1,this.source=e;this._anchorCache=this.hasAnchor?this._buildAnchorCache():null,this.ruleId=t,this.hasBackReferences=typeof this.source==`string`&&qL.test(this.source)}clone(){return new e(this.source,this.ruleId)}setSource(e){this.source!==e&&(this.source=e,this.hasAnchor&&(this._anchorCache=this._buildAnchorCache()))}resolveBackReferences(e,t){if(typeof this.source!=`string`)throw Error(`This method should only be called if the source is a string`);let n=t.map(t=>e.substring(t.start,t.end));return JL.lastIndex=0,this.source.replace(JL,(e,t)=>fL(n[parseInt(t,10)]||``))}_buildAnchorCache(){if(typeof this.source!=`string`)throw Error(`This method should only be called if the source is a string`);let e=[],t=[],n=[],r=[],i,a,o,s;for(i=0,a=this.source.length;i<a;i++)o=this.source.charAt(i),e[i]=o,t[i]=o,n[i]=o,r[i]=o,o===`\\`&&i+1<a&&(s=this.source.charAt(i+1),s===`A`?(e[i+1]=``,t[i+1]=``,n[i+1]=`A`,r[i+1]=`A`):s===`G`?(e[i+1]=``,t[i+1]=`G`,n[i+1]=``,r[i+1]=`G`):(e[i+1]=s,t[i+1]=s,n[i+1]=s,r[i+1]=s),i++);return{A0_G0:e.join(``),A0_G1:t.join(``),A1_G0:n.join(``),A1_G1:r.join(``)}}resolveAnchors(e,t){return!this.hasAnchor||!this._anchorCache||typeof this.source!=`string`?this.source:e?t?this._anchorCache.A1_G1:this._anchorCache.A1_G0:t?this._anchorCache.A0_G1:this._anchorCache.A0_G0}},sR=class{_items;_hasAnchors;_cached;_anchorCache;constructor(){this._items=[],this._hasAnchors=!1,this._cached=null,this._anchorCache={A0_G0:null,A0_G1:null,A1_G0:null,A1_G1:null}}dispose(){this._disposeCaches()}_disposeCaches(){this._cached&&=(this._cached.dispose(),null),this._anchorCache.A0_G0&&(this._anchorCache.A0_G0.dispose(),this._anchorCache.A0_G0=null),this._anchorCache.A0_G1&&(this._anchorCache.A0_G1.dispose(),this._anchorCache.A0_G1=null),this._anchorCache.A1_G0&&(this._anchorCache.A1_G0.dispose(),this._anchorCache.A1_G0=null),this._anchorCache.A1_G1&&(this._anchorCache.A1_G1.dispose(),this._anchorCache.A1_G1=null)}push(e){this._items.push(e),this._hasAnchors=this._hasAnchors||e.hasAnchor}unshift(e){this._items.unshift(e),this._hasAnchors=this._hasAnchors||e.hasAnchor}length(){return this._items.length}setSource(e,t){this._items[e].source!==t&&(this._disposeCaches(),this._items[e].setSource(t))}compile(e){if(!this._cached){let t=this._items.map(e=>e.source);this._cached=new cR(e,t,this._items.map(e=>e.ruleId))}return this._cached}compileAG(e,t,n){return this._hasAnchors?t?n?(this._anchorCache.A1_G1||(this._anchorCache.A1_G1=this._resolveAnchors(e,t,n)),this._anchorCache.A1_G1):(this._anchorCache.A1_G0||(this._anchorCache.A1_G0=this._resolveAnchors(e,t,n)),this._anchorCache.A1_G0):n?(this._anchorCache.A0_G1||(this._anchorCache.A0_G1=this._resolveAnchors(e,t,n)),this._anchorCache.A0_G1):(this._anchorCache.A0_G0||(this._anchorCache.A0_G0=this._resolveAnchors(e,t,n)),this._anchorCache.A0_G0):this.compile(e)}_resolveAnchors(e,t,n){return new cR(e,this._items.map(e=>e.resolveAnchors(t,n)),this._items.map(e=>e.ruleId))}},cR=class{constructor(e,t,n){this.regExps=t,this.rules=n,this.scanner=e.createOnigScanner(t)}scanner;dispose(){typeof this.scanner.dispose==`function`&&this.scanner.dispose()}toString(){let e=[];for(let t=0,n=this.rules.length;t<n;t++)e.push(` - `+this.rules[t]+`: `+this.regExps[t]);return e.join(`
|
|
42
|
+
`)}findNextMatchSync(e,t,n){let r=this.scanner.findNextMatchSync(e,t,n);return r?{ruleId:this.rules[r.index],captureIndices:r.captureIndices}:null}},lR=class{constructor(e,t){this.languageId=e,this.tokenType=t}},uR=class e{_defaultAttributes;_embeddedLanguagesMatcher;constructor(e,t){this._defaultAttributes=new lR(e,8),this._embeddedLanguagesMatcher=new dR(Object.entries(t||{}))}getDefaultAttributes(){return this._defaultAttributes}getBasicScopeAttributes(t){return t===null?e._NULL_SCOPE_METADATA:this._getBasicScopeAttributes.get(t)}static _NULL_SCOPE_METADATA=new lR(0,0);_getBasicScopeAttributes=new pL(e=>new lR(this._scopeToLanguage(e),this._toStandardTokenType(e)));_scopeToLanguage(e){return this._embeddedLanguagesMatcher.match(e)||0}_toStandardTokenType(t){let n=t.match(e.STANDARD_TOKEN_TYPE_REGEXP);if(!n)return 8;switch(n[1]){case`comment`:return 1;case`string`:return 2;case`regex`:return 3;case`meta.embedded`:return 0}throw Error(`Unexpected match for standard token type!`)}static STANDARD_TOKEN_TYPE_REGEXP=/\b(comment|string|regex|meta\.embedded)\b/},dR=class{values;scopesRegExp;constructor(e){if(e.length===0)this.values=null,this.scopesRegExp=null;else{this.values=new Map(e);let t=e.map(([e,t])=>fL(e));t.sort(),t.reverse(),this.scopesRegExp=RegExp(`^((${t.join(`)|(`)}))($|\\.)`,``)}}match(e){if(!this.scopesRegExp)return;let t=e.match(this.scopesRegExp);if(t)return this.values.get(t[1])}};typeof process<`u`&&{}.VSCODE_TEXTMATE_DEBUG;var fR=class{constructor(e,t){this.stack=e,this.stoppedEarly=t}};function pR(e,t,n,r,i,a,o,s){let c=t.content.length,l=!1,u=-1;if(o){let o=mR(e,t,n,r,i,a);i=o.stack,r=o.linePos,n=o.isFirstLine,u=o.anchorPosition}let d=Date.now();for(;!l;){if(s!==0&&Date.now()-d>s)return new fR(i,!0);f()}return new fR(i,!1);function f(){let o=hR(e,t,n,r,i,u);if(!o){a.produce(i,c),l=!0;return}let s=o.captureIndices,d=o.matchedRuleId,f=s&&s.length>0?s[0].end>r:!1;if(d===YL){let o=i.getRule(e);a.produce(i,s[0].start),i=i.withContentNameScopesList(i.nameScopesList),bR(e,t,n,i,a,o.endCaptures,s),a.produce(i,s[0].end);let d=i;if(i=i.parent,u=d.getAnchorPos(),!f&&d.getEnterPos()===r){i=d,a.produce(i,c),l=!0;return}}else{let o=e.getRule(d);a.produce(i,s[0].start);let p=i,m=o.getName(t.content,s),h=i.contentNameScopesList.pushAttributed(m,e);if(i=i.push(d,r,u,s[0].end===c,null,h,h),o instanceof rR){let r=o;bR(e,t,n,i,a,r.beginCaptures,s),a.produce(i,s[0].end),u=s[0].end;let d=r.getContentName(t.content,s),m=h.pushAttributed(d,e);if(i=i.withContentNameScopesList(m),r.endHasBackReferences&&(i=i.withEndRule(r.getEndWithResolvedBackReferences(t.content,s))),!f&&p.hasSameRuleAs(i)){i=i.pop(),a.produce(i,c),l=!0;return}}else if(o instanceof iR){let r=o;bR(e,t,n,i,a,r.beginCaptures,s),a.produce(i,s[0].end),u=s[0].end;let d=r.getContentName(t.content,s),m=h.pushAttributed(d,e);if(i=i.withContentNameScopesList(m),r.whileHasBackReferences&&(i=i.withEndRule(r.getWhileWithResolvedBackReferences(t.content,s))),!f&&p.hasSameRuleAs(i)){i=i.pop(),a.produce(i,c),l=!0;return}}else if(bR(e,t,n,i,a,o.captures,s),a.produce(i,s[0].end),i=i.pop(),!f){i=i.safePop(),a.produce(i,c),l=!0;return}}s[0].end>r&&(r=s[0].end,n=!1)}}function mR(e,t,n,r,i,a){let o=i.beginRuleCapturedEOL?0:-1,s=[];for(let t=i;t;t=t.pop()){let n=t.getRule(e);n instanceof iR&&s.push({rule:n,stack:t})}for(let c=s.pop();c;c=s.pop()){let{ruleScanner:s,findOptions:l}=yR(c.rule,e,c.stack.endRule,n,r===o),u=s.findNextMatchSync(t,r,l);if(u){if(u.ruleId!==XL){i=c.stack.pop();break}u.captureIndices&&u.captureIndices.length&&(a.produce(c.stack,u.captureIndices[0].start),bR(e,t,n,c.stack,a,c.rule.whileCaptures,u.captureIndices),a.produce(c.stack,u.captureIndices[0].end),o=u.captureIndices[0].end,u.captureIndices[0].end>r&&(r=u.captureIndices[0].end,n=!1))}else{i=c.stack.pop();break}}return{stack:i,linePos:r,anchorPosition:o,isFirstLine:n}}function hR(e,t,n,r,i,a){let o=gR(e,t,n,r,i,a),s=e.getInjections();if(s.length===0)return o;let c=_R(s,e,t,n,r,i,a);if(!c)return o;if(!o)return c;let l=o.captureIndices[0].start,u=c.captureIndices[0].start;return u<l||c.priorityMatch&&u===l?c:o}function gR(e,t,n,r,i,a){let{ruleScanner:o,findOptions:s}=vR(i.getRule(e),e,i.endRule,n,r===a),c=o.findNextMatchSync(t,r,s);return c?{captureIndices:c.captureIndices,matchedRuleId:c.ruleId}:null}function _R(e,t,n,r,i,a,o){let s=Number.MAX_VALUE,c=null,l,u=0,d=a.contentNameScopesList.getScopeNames();for(let a=0,f=e.length;a<f;a++){let f=e[a];if(!f.matcher(d))continue;let{ruleScanner:p,findOptions:m}=vR(t.getRule(f.ruleId),t,null,r,i===o),h=p.findNextMatchSync(n,i,m);if(!h)continue;let g=h.captureIndices[0].start;if(!(g>=s)&&(s=g,c=h.captureIndices,l=h.ruleId,u=f.priority,s===i))break}return c?{priorityMatch:u===-1,captureIndices:c,matchedRuleId:l}:null}function vR(e,t,n,r,i){return{ruleScanner:e.compileAG(t,n,r,i),findOptions:0}}function yR(e,t,n,r,i){return{ruleScanner:e.compileWhileAG(t,n,r,i),findOptions:0}}function bR(e,t,n,r,i,a,o){if(a.length===0)return;let s=t.content,c=Math.min(a.length,o.length),l=[],u=o[0].end;for(let t=0;t<c;t++){let c=a[t];if(c===null)continue;let d=o[t];if(d.length===0)continue;if(d.start>u)break;for(;l.length>0&&l[l.length-1].endPos<=d.start;)i.produceFromScopes(l[l.length-1].scopes,l[l.length-1].endPos),l.pop();if(l.length>0?i.produceFromScopes(l[l.length-1].scopes,d.start):i.produce(r,d.start),c.retokenizeCapturedWithRuleId){let t=c.getName(s,o),a=r.contentNameScopesList.pushAttributed(t,e),l=c.getContentName(s,o),u=a.pushAttributed(l,e),f=r.push(c.retokenizeCapturedWithRuleId,d.start,-1,!1,null,a,u),p=e.createOnigString(s.substring(0,d.end));pR(e,p,n&&d.start===0,d.start,f,i,!1,0),ML(p);continue}let f=c.getName(s,o);if(f!==null){let t=(l.length>0?l[l.length-1].scopes:r.contentNameScopesList).pushAttributed(f,e);l.push(new xR(t,d.end))}}for(;l.length>0;)i.produceFromScopes(l[l.length-1].scopes,l[l.length-1].endPos),l.pop()}var xR=class{scopes;endPos;constructor(e,t){this.scopes=e,this.endPos=t}};function SR(e,t,n,r,i,a,o,s){return new ER(e,t,n,r,i,a,o,s)}function CR(e,t,n,r,i){let a=kL(t,wR),o=aR.getCompiledRuleId(n,r,i.repository);for(let n of a)e.push({debugSelector:t,matcher:n.matcher,ruleId:o,grammar:i,priority:n.priority})}function wR(e,t){if(t.length<e.length)return!1;let n=0;return e.every(e=>{for(let r=n;r<t.length;r++)if(TR(t[r],e))return n=r+1,!0;return!1})}function TR(e,t){if(!e)return!1;if(e===t)return!0;let n=t.length;return e.length>n&&e.substr(0,n)===t&&e[n]===`.`}var ER=class{constructor(e,t,n,r,i,a,o,s){if(this._rootScopeName=e,this.balancedBracketSelectors=a,this._onigLib=s,this._basicScopeAttributesProvider=new uR(n,r),this._rootId=-1,this._lastRuleId=0,this._ruleId2desc=[null],this._includedGrammars={},this._grammarRepository=o,this._grammar=DR(t,null),this._injections=null,this._tokenTypeMatchers=[],i)for(let e of Object.keys(i)){let t=kL(e,wR);for(let n of t)this._tokenTypeMatchers.push({matcher:n.matcher,type:i[e]})}}_rootId;_lastRuleId;_ruleId2desc;_includedGrammars;_grammarRepository;_grammar;_injections;_basicScopeAttributesProvider;_tokenTypeMatchers;get themeProvider(){return this._grammarRepository}dispose(){for(let e of this._ruleId2desc)e&&e.dispose()}createOnigScanner(e){return this._onigLib.createOnigScanner(e)}createOnigString(e){return this._onigLib.createOnigString(e)}getMetadataForScope(e){return this._basicScopeAttributesProvider.getBasicScopeAttributes(e)}_collectInjections(){let e={lookup:e=>e===this._rootScopeName?this._grammar:this.getExternalGrammar(e),injections:e=>this._grammarRepository.injections(e)},t=[],n=this._rootScopeName,r=e.lookup(n);if(r){let e=r.injections;if(e)for(let n in e)CR(t,n,e[n],this,r);let i=this._grammarRepository.injections(n);i&&i.forEach(e=>{let n=this.getExternalGrammar(e);if(n){let e=n.injectionSelector;e&&CR(t,e,n,this,n)}})}return t.sort((e,t)=>e.priority-t.priority),t}getInjections(){return this._injections===null&&(this._injections=this._collectInjections()),this._injections}registerRule(e){let t=++this._lastRuleId,n=e(ZL(t));return this._ruleId2desc[t]=n,n}getRule(e){return this._ruleId2desc[QL(e)]}getExternalGrammar(e,t){if(this._includedGrammars[e])return this._includedGrammars[e];if(this._grammarRepository){let n=this._grammarRepository.lookup(e);if(n)return this._includedGrammars[e]=DR(n,t&&t.$base),this._includedGrammars[e]}}tokenizeLine(e,t,n=0){let r=this._tokenize(e,t,!1,n);return{tokens:r.lineTokens.getResult(r.ruleStack,r.lineLength),ruleStack:r.ruleStack,stoppedEarly:r.stoppedEarly}}tokenizeLine2(e,t,n=0){let r=this._tokenize(e,t,!0,n);return{tokens:r.lineTokens.getBinaryResult(r.ruleStack,r.lineLength),ruleStack:r.ruleStack,stoppedEarly:r.stoppedEarly}}_tokenize(e,t,n,r){this._rootId===-1&&(this._rootId=aR.getCompiledRuleId(this._grammar.repository.$self,this,this._grammar.repository),this.getInjections());let i;if(!t||t===kR.NULL){i=!0;let e=this._basicScopeAttributesProvider.getDefaultAttributes(),n=this.themeProvider.getDefaults(),r=EL.set(0,e.languageId,e.tokenType,null,n.fontStyle,n.foregroundId,n.backgroundId),a=this.getRule(this._rootId).getName(null,null),o;o=a?OR.createRootAndLookUpScopeName(a,r,this):OR.createRoot(`unknown`,r),t=new kR(null,this._rootId,-1,-1,!1,null,o,o)}else i=!1,t.reset();e+=`
|
|
43
|
+
`;let a=this.createOnigString(e),o=a.content.length,s=new jR(n,e,this._tokenTypeMatchers,this.balancedBracketSelectors),c=pR(this,a,i,0,t,s,!0,r);return ML(a),{lineLength:o,lineTokens:s,ruleStack:c.stack,stoppedEarly:c.stoppedEarly}}};function DR(e,t){return e=tL(e),e.repository=e.repository||{},e.repository.$self={$vscodeTextmateLocation:e.$vscodeTextmateLocation,patterns:e.patterns,name:e.scopeName},e.repository.$base=t||e.repository.$self,e}var OR=class e{constructor(e,t,n){this.parent=e,this.scopePath=t,this.tokenAttributes=n}static fromExtension(t,n){let r=t,i=t?.scopePath??null;for(let t of n)i=hL.push(i,t.scopeNames),r=new e(r,i,t.encodedTokenAttributes);return r}static createRoot(t,n){return new e(null,new hL(null,t),n)}static createRootAndLookUpScopeName(t,n,r){let i=r.getMetadataForScope(t),a=new hL(null,t),o=r.themeProvider.themeMatch(a),s=e.mergeAttributes(n,i,o);return new e(null,a,s)}get scopeName(){return this.scopePath.scopeName}toString(){return this.getScopeNames().join(` `)}equals(t){return e.equals(this,t)}static equals(e,t){do{if(e===t||!e&&!t)return!0;if(!e||!t||e.scopeName!==t.scopeName||e.tokenAttributes!==t.tokenAttributes)return!1;e=e.parent,t=t.parent}while(!0)}static mergeAttributes(e,t,n){let r=-1,i=0,a=0;return n!==null&&(r=n.fontStyle,i=n.foregroundId,a=n.backgroundId),EL.set(e,t.languageId,t.tokenType,null,r,i,a)}pushAttributed(t,n){if(t===null)return this;if(t.indexOf(` `)===-1)return e._pushAttributed(this,t,n);let r=t.split(/ /g),i=this;for(let t of r)i=e._pushAttributed(i,t,n);return i}static _pushAttributed(t,n,r){let i=r.getMetadataForScope(n),a=t.scopePath.push(n),o=r.themeProvider.themeMatch(a),s=e.mergeAttributes(t.tokenAttributes,i,o);return new e(t,a,s)}getScopeNames(){return this.scopePath.getSegments()}getExtensionIfDefined(e){let t=[],n=this;for(;n&&n!==e;)t.push({encodedTokenAttributes:n.tokenAttributes,scopeNames:n.scopePath.getExtensionIfDefined(n.parent?.scopePath??null)}),n=n.parent;return n===e?t.reverse():void 0}},kR=class e{constructor(e,t,n,r,i,a,o,s){this.parent=e,this.ruleId=t,this.beginRuleCapturedEOL=i,this.endRule=a,this.nameScopesList=o,this.contentNameScopesList=s,this.depth=this.parent?this.parent.depth+1:1,this._enterPos=n,this._anchorPos=r}_stackElementBrand=void 0;static NULL=new e(null,0,0,0,!1,null,null,null);_enterPos;_anchorPos;depth;equals(t){return t!==null&&e._equals(this,t)}static _equals(e,t){return e===t?!0:this._structuralEquals(e,t)?OR.equals(e.contentNameScopesList,t.contentNameScopesList):!1}static _structuralEquals(e,t){do{if(e===t||!e&&!t)return!0;if(!e||!t||e.depth!==t.depth||e.ruleId!==t.ruleId||e.endRule!==t.endRule)return!1;e=e.parent,t=t.parent}while(!0)}clone(){return this}static _reset(e){for(;e;)e._enterPos=-1,e._anchorPos=-1,e=e.parent}reset(){e._reset(this)}pop(){return this.parent}safePop(){return this.parent?this.parent:this}push(t,n,r,i,a,o,s){return new e(this,t,n,r,i,a,o,s)}getEnterPos(){return this._enterPos}getAnchorPos(){return this._anchorPos}getRule(e){return e.getRule(this.ruleId)}toString(){let e=[];return this._writeString(e,0),`[`+e.join(`,`)+`]`}_writeString(e,t){return this.parent&&(t=this.parent._writeString(e,t)),e[t++]=`(${this.ruleId}, ${this.nameScopesList?.toString()}, ${this.contentNameScopesList?.toString()})`,t}withContentNameScopesList(e){return this.contentNameScopesList===e?this:this.parent.push(this.ruleId,this._enterPos,this._anchorPos,this.beginRuleCapturedEOL,this.endRule,this.nameScopesList,e)}withEndRule(t){return this.endRule===t?this:new e(this.parent,this.ruleId,this._enterPos,this._anchorPos,this.beginRuleCapturedEOL,t,this.nameScopesList,this.contentNameScopesList)}hasSameRuleAs(e){let t=this;for(;t&&t._enterPos===e._enterPos;){if(t.ruleId===e.ruleId)return!0;t=t.parent}return!1}toStateStackFrame(){return{ruleId:QL(this.ruleId),beginRuleCapturedEOL:this.beginRuleCapturedEOL,endRule:this.endRule,nameScopesList:this.nameScopesList?.getExtensionIfDefined(this.parent?.nameScopesList??null)??[],contentNameScopesList:this.contentNameScopesList?.getExtensionIfDefined(this.nameScopesList)??[]}}static pushFrame(t,n){let r=OR.fromExtension(t?.nameScopesList??null,n.nameScopesList);return new e(t,ZL(n.ruleId),n.enterPos??-1,n.anchorPos??-1,n.beginRuleCapturedEOL,n.endRule,r,OR.fromExtension(r,n.contentNameScopesList))}},AR=class{balancedBracketScopes;unbalancedBracketScopes;allowAny=!1;constructor(e,t){this.balancedBracketScopes=e.flatMap(e=>e===`*`?(this.allowAny=!0,[]):kL(e,wR).map(e=>e.matcher)),this.unbalancedBracketScopes=t.flatMap(e=>kL(e,wR).map(e=>e.matcher))}get matchesAlways(){return this.allowAny&&this.unbalancedBracketScopes.length===0}get matchesNever(){return this.balancedBracketScopes.length===0&&!this.allowAny}match(e){for(let t of this.unbalancedBracketScopes)if(t(e))return!1;for(let t of this.balancedBracketScopes)if(t(e))return!0;return this.allowAny}},jR=class{constructor(e,t,n,r){this.balancedBracketSelectors=r,this._emitBinaryTokens=e,this._tokenTypeOverrides=n,this._lineText=null,this._tokens=[],this._binaryTokens=[],this._lastTokenEndIndex=0}_emitBinaryTokens;_lineText;_tokens;_binaryTokens;_lastTokenEndIndex;_tokenTypeOverrides;produce(e,t){this.produceFromScopes(e.contentNameScopesList,t)}produceFromScopes(e,t){if(this._lastTokenEndIndex>=t)return;if(this._emitBinaryTokens){let n=e?.tokenAttributes??0,r=!1;if(this.balancedBracketSelectors?.matchesAlways&&(r=!0),this._tokenTypeOverrides.length>0||this.balancedBracketSelectors&&!this.balancedBracketSelectors.matchesAlways&&!this.balancedBracketSelectors.matchesNever){let t=e?.getScopeNames()??[];for(let e of this._tokenTypeOverrides)e.matcher(t)&&(n=EL.set(n,0,DL(e.type),null,-1,0,0));this.balancedBracketSelectors&&(r=this.balancedBracketSelectors.match(t))}if(r&&(n=EL.set(n,0,8,r,-1,0,0)),this._binaryTokens.length>0&&this._binaryTokens[this._binaryTokens.length-1]===n){this._lastTokenEndIndex=t;return}this._binaryTokens.push(this._lastTokenEndIndex),this._binaryTokens.push(n),this._lastTokenEndIndex=t;return}let n=e?.getScopeNames()??[];this._tokens.push({startIndex:this._lastTokenEndIndex,endIndex:t,scopes:n}),this._lastTokenEndIndex=t}getResult(e,t){return this._tokens.length>0&&this._tokens[this._tokens.length-1].startIndex===t-1&&this._tokens.pop(),this._tokens.length===0&&(this._lastTokenEndIndex=-1,this.produce(e,t),this._tokens[this._tokens.length-1].startIndex=0),this._tokens}getBinaryResult(e,t){this._binaryTokens.length>0&&this._binaryTokens[this._binaryTokens.length-2]===t-1&&(this._binaryTokens.pop(),this._binaryTokens.pop()),this._binaryTokens.length===0&&(this._lastTokenEndIndex=-1,this.produce(e,t),this._binaryTokens[this._binaryTokens.length-2]=0);let n=new Uint32Array(this._binaryTokens.length);for(let e=0,t=this._binaryTokens.length;e<t;e++)n[e]=this._binaryTokens[e];return n}},MR=class{constructor(e,t){this._onigLib=t,this._theme=e}_grammars=new Map;_rawGrammars=new Map;_injectionGrammars=new Map;_theme;dispose(){for(let e of this._grammars.values())e.dispose()}setTheme(e){this._theme=e}getColorMap(){return this._theme.getColorMap()}addGrammar(e,t){this._rawGrammars.set(e.scopeName,e),t&&this._injectionGrammars.set(e.scopeName,t)}lookup(e){return this._rawGrammars.get(e)}injections(e){return this._injectionGrammars.get(e)}getDefaults(){return this._theme.getDefaults()}themeMatch(e){return this._theme.match(e)}grammarForScopeName(e,t,n,r,i){if(!this._grammars.has(e)){let a=this._rawGrammars.get(e);if(!a)return null;this._grammars.set(e,SR(e,a,t,n,r,i,this,this._onigLib))}return this._grammars.get(e)}},NR=class{_options;_syncRegistry;_ensureGrammarCache;constructor(e){this._options=e,this._syncRegistry=new MR(mL.createFromRawTheme(e.theme,e.colorMap),e.onigLib),this._ensureGrammarCache=new Map}dispose(){this._syncRegistry.dispose()}setTheme(e,t){this._syncRegistry.setTheme(mL.createFromRawTheme(e,t))}getColorMap(){return this._syncRegistry.getColorMap()}loadGrammarWithEmbeddedLanguages(e,t,n){return this.loadGrammarWithConfiguration(e,t,{embeddedLanguages:n})}loadGrammarWithConfiguration(e,t,n){return this._loadGrammar(e,t,n.embeddedLanguages,n.tokenTypes,new AR(n.balancedBracketSelectors||[],n.unbalancedBracketSelectors||[]))}loadGrammar(e){return this._loadGrammar(e,0,null,null,null)}_loadGrammar(e,t,n,r,i){let a=new IL(this._syncRegistry,e);for(;a.Q.length>0;)a.Q.map(e=>this._loadSingleGrammar(e.scopeName)),a.processQueue();return this._grammarForScopeName(e,t,n,r,i)}_loadSingleGrammar(e){this._ensureGrammarCache.has(e)||(this._doLoadSingleGrammar(e),this._ensureGrammarCache.set(e,!0))}_doLoadSingleGrammar(e){let t=this._options.loadGrammar(e);if(t){let n=typeof this._options.getInjections==`function`?this._options.getInjections(e):void 0;this._syncRegistry.addGrammar(t,n)}}addGrammar(e,t=[],n=0,r=null){return this._syncRegistry.addGrammar(e,t),this._grammarForScopeName(e.scopeName,n,r)}_grammarForScopeName(e,t=0,n=null,r=null,i=null){return this._syncRegistry.grammarForScopeName(e,t,n,r,i)}},PR=kR.NULL;function FR(e,t){let n=typeof e==`string`?{}:{...e.colorReplacements},r=typeof e==`string`?e:e.name;for(let[e,i]of Object.entries(t?.colorReplacements||{}))typeof i==`string`?n[e]=i:e===r&&Object.assign(n,i);return n}function IR(e,t){return e&&(t?.[e?.toLowerCase()]||e)}function LR(e){return Array.isArray(e)?e:[e]}async function RR(e){return Promise.resolve(typeof e==`function`?e():e).then(e=>e.default||e)}function zR(e){return!e||[`plaintext`,`txt`,`text`,`plain`].includes(e)}function BR(e){return e===`ansi`||zR(e)}function VR(e){return e===`none`}function HR(e){return VR(e)}function UR(e,t=!1){if(e.length===0)return[[``,0]];let n=e.split(/(\r?\n)/g),r=0,i=[];for(let e=0;e<n.length;e+=2){let a=t?n[e]+(n[e+1]||``):n[e];i.push([a,r]),r+=n[e].length,r+=n[e+1]?.length||0}return i}var WR={light:`#333333`,dark:`#bbbbbb`},GR={light:`#fffffe`,dark:`#1e1e1e`},KR=`__shiki_resolved`;function qR(e){if(e?.[KR])return e;let t={...e};t.tokenColors&&!t.settings&&(t.settings=t.tokenColors,delete t.tokenColors),t.type||=`dark`,t.colorReplacements={...t.colorReplacements},t.settings||=[];let{bg:n,fg:r}=t;if(!n||!r){let e=t.settings?t.settings.find(e=>!e.name&&!e.scope):void 0;e?.settings?.foreground&&(r=e.settings.foreground),e?.settings?.background&&(n=e.settings.background),!r&&t?.colors?.[`editor.foreground`]&&(r=t.colors[`editor.foreground`]),!n&&t?.colors?.[`editor.background`]&&(n=t.colors[`editor.background`]),r||=t.type===`light`?WR.light:WR.dark,n||=t.type===`light`?GR.light:GR.dark,t.fg=r,t.bg=n}t.settings[0]&&t.settings[0].settings&&!t.settings[0].scope||t.settings.unshift({settings:{foreground:t.fg,background:t.bg}});let i=0,a=new Map;function o(e){if(a.has(e))return a.get(e);i+=1;let n=`#${i.toString(16).padStart(8,`0`).toLowerCase()}`;return t.colorReplacements?.[`#${n}`]?o(e):(a.set(e,n),n)}t.settings=t.settings.map(e=>{let n=e.settings?.foreground&&!e.settings.foreground.startsWith(`#`),r=e.settings?.background&&!e.settings.background.startsWith(`#`);if(!n&&!r)return e;let i={...e,settings:{...e.settings}};if(n){let n=o(e.settings.foreground);t.colorReplacements[n]=e.settings.foreground,i.settings.foreground=n}if(r){let n=o(e.settings.background);t.colorReplacements[n]=e.settings.background,i.settings.background=n}return i});for(let e of Object.keys(t.colors||{}))if((e===`editor.foreground`||e===`editor.background`||e.startsWith(`terminal.ansi`))&&!t.colors[e]?.startsWith(`#`)){let n=o(t.colors[e]);t.colorReplacements[n]=t.colors[e],t.colors[e]=n}return Object.defineProperty(t,KR,{enumerable:!1,writable:!1,value:!0}),t}async function JR(e){return Array.from(new Set((await Promise.all(e.filter(e=>!BR(e)).map(async e=>await RR(e).then(e=>Array.isArray(e)?e:[e])))).flat()))}async function YR(e){return(await Promise.all(e.map(async e=>HR(e)?null:qR(await RR(e))))).filter(e=>!!e)}function XR(e,t){if(!t)return e;if(t[e]){let n=new Set([e]);for(;t[e];){if(e=t[e],n.has(e))throw new J(`Circular alias \`${Array.from(n).join(` -> `)} -> ${e}\``);n.add(e)}}return e}var ZR=class extends NR{_resolvedThemes=new Map;_resolvedGrammars=new Map;_langMap=new Map;_langGraph=new Map;_textmateThemeCache=new WeakMap;_loadedThemesCache=null;_loadedLanguagesCache=null;constructor(e,t,n,r={}){super(e),this._resolver=e,this._themes=t,this._langs=n,this._alias=r,this._themes.map(e=>this.loadTheme(e)),this.loadLanguages(this._langs)}getTheme(e){return typeof e==`string`?this._resolvedThemes.get(e):this.loadTheme(e)}loadTheme(e){let t=qR(e);return t.name&&(this._resolvedThemes.set(t.name,t),this._loadedThemesCache=null),t}getLoadedThemes(){return this._loadedThemesCache||=[...this._resolvedThemes.keys()],this._loadedThemesCache}setTheme(e){let t=this._textmateThemeCache.get(e);t||(t=mL.createFromRawTheme(e),this._textmateThemeCache.set(e,t)),this._syncRegistry.setTheme(t)}getGrammar(e){return e=XR(e,this._alias),this._resolvedGrammars.get(e)}loadLanguage(e){if(this.getGrammar(e.name))return;let t=new Set([...this._langMap.values()].filter(t=>t.embeddedLangsLazy?.includes(e.name)));this._resolver.addLanguage(e);let n={balancedBracketSelectors:e.balancedBracketSelectors||[`*`],unbalancedBracketSelectors:e.unbalancedBracketSelectors||[]};this._syncRegistry._rawGrammars.set(e.scopeName,e);let r=this.loadGrammarWithConfiguration(e.scopeName,1,n);if(r.name=e.name,this._resolvedGrammars.set(e.name,r),e.aliases&&e.aliases.forEach(t=>{this._alias[t]=e.name}),this._loadedLanguagesCache=null,t.size)for(let e of t)this._resolvedGrammars.delete(e.name),this._loadedLanguagesCache=null,this._syncRegistry?._injectionGrammars?.delete(e.scopeName),this._syncRegistry?._grammars?.delete(e.scopeName),this.loadLanguage(this._langMap.get(e.name))}dispose(){super.dispose(),this._resolvedThemes.clear(),this._resolvedGrammars.clear(),this._langMap.clear(),this._langGraph.clear(),this._loadedThemesCache=null}loadLanguages(e){for(let t of e)this.resolveEmbeddedLanguages(t);let t=Array.from(this._langGraph.entries()),n=t.filter(([e,t])=>!t);if(n.length){let e=t.filter(([e,t])=>t?(t.embeddedLanguages||t.embeddedLangs)?.some(e=>n.map(([e])=>e).includes(e)):!1).filter(e=>!n.includes(e));throw new J(`Missing languages ${n.map(([e])=>`\`${e}\``).join(`, `)}, required by ${e.map(([e])=>`\`${e}\``).join(`, `)}`)}for(let[e,n]of t)this._resolver.addLanguage(n);for(let[e,n]of t)this.loadLanguage(n)}getLoadedLanguages(){return this._loadedLanguagesCache||=[...new Set([...this._resolvedGrammars.keys(),...Object.keys(this._alias)])],this._loadedLanguagesCache}resolveEmbeddedLanguages(e){this._langMap.set(e.name,e),this._langGraph.set(e.name,e);let t=e.embeddedLanguages??e.embeddedLangs;if(t)for(let e of t)this._langGraph.set(e,this._langMap.get(e))}},QR=class{_langs=new Map;_scopeToLang=new Map;_injections=new Map;_onigLib;constructor(e,t){this._onigLib={createOnigScanner:t=>e.createScanner(t),createOnigString:t=>e.createString(t)},t.forEach(e=>this.addLanguage(e))}get onigLib(){return this._onigLib}getLangRegistration(e){return this._langs.get(e)}loadGrammar(e){return this._scopeToLang.get(e)}addLanguage(e){this._langs.set(e.name,e),e.aliases&&e.aliases.forEach(t=>{this._langs.set(t,e)}),this._scopeToLang.set(e.scopeName,e),e.injectTo&&e.injectTo.forEach(t=>{this._injections.get(t)||this._injections.set(t,[]),this._injections.get(t).push(e.scopeName)})}getInjections(e){let t=e.split(`.`),n=[];for(let e=1;e<=t.length;e++){let r=t.slice(0,e).join(`.`);n=[...n,...this._injections.get(r)||[]]}return n}},$R=0;function ez(e){$R+=1,e.warnings!==!1&&$R>=10&&$R%10==0&&console.warn(`[Shiki] ${$R} instances have been created. Shiki is supposed to be used as a singleton, consider refactoring your code to cache your highlighter instance; Or call \`highlighter.dispose()\` to release unused instances.`);let t=!1;if(!e.engine)throw new J("`engine` option is required for synchronous mode");let n=(e.langs||[]).flat(1),r=(e.themes||[]).flat(1).map(qR),i=new ZR(new QR(e.engine,n),r,n,e.langAlias),a;function o(t){return XR(t,e.langAlias)}function s(e){g();let t=i.getGrammar(typeof e==`string`?e:e.name);if(!t)throw new J(`Language \`${e}\` not found, you may need to load it first`);return t}function c(e){if(e===`none`)return{bg:``,fg:``,name:`none`,settings:[],type:`dark`};g();let t=i.getTheme(e);if(!t)throw new J(`Theme \`${e}\` not found, you may need to load it first`);return t}function l(e){g();let t=c(e);return a!==e&&(i.setTheme(t),a=e),{theme:t,colorMap:i.getColorMap()}}function u(){return g(),i.getLoadedThemes()}function d(){return g(),i.getLoadedLanguages()}function f(...e){g(),i.loadLanguages(e.flat(1))}async function p(...e){return f(await JR(e))}function m(...e){g();for(let t of e.flat(1))i.loadTheme(t)}async function h(...e){return g(),m(await YR(e))}function g(){if(t)throw new J(`Shiki instance has been disposed`)}function _(){t||(t=!0,i.dispose(),--$R)}return{setTheme:l,getTheme:c,getLanguage:s,getLoadedThemes:u,getLoadedLanguages:d,resolveLangAlias:o,loadLanguage:p,loadLanguageSync:f,loadTheme:h,loadThemeSync:m,dispose:_,[Symbol.dispose]:_}}async function tz(e){e.engine||console.warn("`engine` option is required. Use `createOnigurumaEngine` or `createJavaScriptRegexEngine` to create an engine.");let[t,n,r]=await Promise.all([YR(e.themes||[]),JR(e.langs||[]),e.engine]);return ez({...e,themes:t,langs:n,engine:r})}var nz=new WeakMap;function rz(e,t){nz.set(e,t)}function iz(e){return nz.get(e)}var az=class e{_stacks={};lang;get themes(){return Object.keys(this._stacks)}get theme(){return this.themes[0]}get _stack(){return this._stacks[this.theme]}static initial(t,n){return new e(Object.fromEntries(LR(n).map(e=>[e,PR])),t)}constructor(...e){if(e.length===2){let[t,n]=e;this.lang=n,this._stacks=t}else{let[t,n,r]=e;this.lang=n,this._stacks={[r]:t}}}getInternalStack(e=this.theme){return this._stacks[e]}getScopes(e=this.theme){return oz(this._stacks[e])}toJSON(){return{lang:this.lang,theme:this.theme,themes:this.themes,scopes:this.getScopes()}}};function oz(e){let t=[],n=new Set;function r(e){if(n.has(e))return;n.add(e);let i=e?.nameScopesList?.scopeName;i&&t.push(i),e.parent&&r(e.parent)}return r(e),t}function sz(e,t){if(!(e instanceof az))throw new J(`Invalid grammar state`);return e.getInternalStack(t)}function cz(e,t,n={}){let{theme:r=e.getLoadedThemes()[0]}=n;if(zR(e.resolveLangAlias(n.lang||`text`))||VR(r))return UR(t).map(e=>[{content:e[0],offset:e[1]}]);let{theme:i,colorMap:a}=e.setTheme(r),o=e.getLanguage(n.lang||`text`);if(n.grammarState){if(n.grammarState.lang!==o.name)throw new J(`Grammar state language "${n.grammarState.lang}" does not match highlight language "${o.name}"`);if(!n.grammarState.themes.includes(i.name))throw new J(`Grammar state themes "${n.grammarState.themes}" do not contain highlight theme "${i.name}"`)}return uz(t,o,i,a,n)}function lz(...e){if(e.length===2)return iz(e[1]);let[t,n,r={}]=e,{lang:i=`text`,theme:a=t.getLoadedThemes()[0]}=r;if(zR(i)||VR(a))throw new J(`Plain language does not have grammar state`);if(i===`ansi`)throw new J(`ANSI language does not have grammar state`);let{theme:o,colorMap:s}=t.setTheme(a),c=t.getLanguage(i);return new az(dz(n,c,o,s,r).stateStack,c.name,o.name)}function uz(e,t,n,r,i){let a=dz(e,t,n,r,i),o=new az(a.stateStack,t.name,n.name);return rz(a.tokens,o),a.tokens}function dz(e,t,n,r,i){let a=FR(n,i),{tokenizeMaxLineLength:o=0,tokenizeTimeLimit:s=500}=i,c=UR(e),l=i.grammarState?sz(i.grammarState,n.name)??PR:i.grammarContextCode==null?PR:dz(i.grammarContextCode,t,n,r,{...i,grammarState:void 0,grammarContextCode:void 0}).stateStack,u=[],d=[];for(let e=0,f=c.length;e<f;e++){let[f,p]=c[e];if(f===``){u=[],d.push([]);continue}if(o>0&&f.length>=o){u=[],d.push([{content:f,offset:p,color:``,fontStyle:0}]);continue}let m,h,g;i.includeExplanation&&(m=t.tokenizeLine(f,l,s),h=m.tokens,g=0);let _=t.tokenizeLine2(f,l,s),v=_.tokens.length/2;for(let e=0;e<v;e++){let t=_.tokens[2*e],o=e+1<v?_.tokens[2*e+2]:f.length;if(t===o)continue;let s=_.tokens[2*e+1],c=IR(r[EL.getForeground(s)],a),l=EL.getFontStyle(s),d={content:f.substring(t,o),offset:p+t,color:c,fontStyle:l};if(i.includeExplanation){let e=[];if(i.includeExplanation!==`scopeName`)for(let t of n.settings){let n;switch(typeof t.scope){case`string`:n=t.scope.split(/,/).map(e=>e.trim());break;case`object`:n=t.scope;break;default:continue}e.push({settings:t,selectors:n.map(e=>e.split(/ /))})}d.explanation=[];let r=0;for(;t+r<o;){let t=h[g],n=f.substring(t.startIndex,t.endIndex);r+=n.length,d.explanation.push({content:n,scopes:i.includeExplanation===`scopeName`?fz(t.scopes):pz(e,t.scopes)}),g+=1}}u.push(d)}d.push(u),u=[],l=_.ruleStack}return{tokens:d,stateStack:l}}function fz(e){return e.map(e=>({scopeName:e}))}function pz(e,t){let n=[];for(let r=0,i=t.length;r<i;r++){let i=t[r];n[r]={scopeName:i,themeMatches:gz(e,i,t.slice(0,r))}}return n}function mz(e,t){return e===t||t.substring(0,e.length)===e&&t[e.length]===`.`}function hz(e,t,n){if(!mz(e[e.length-1],t))return!1;let r=e.length-2,i=n.length-1;for(;r>=0&&i>=0;)mz(e[r],n[i])&&--r,--i;return r===-1}function gz(e,t,n){let r=[];for(let{selectors:i,settings:a}of e)for(let e of i)if(hz(e,t,n)){r.push(a);break}return r}function _z(e,t,n,r=cz){let i=Object.entries(n.themes).filter(e=>e[1]).map(e=>({color:e[0],theme:e[1]})),a=i.map(i=>{let a=r(e,t,{...n,theme:i.theme});return{tokens:a,state:iz(a),theme:typeof i.theme==`string`?i.theme:i.theme.name}}),o=vz(...a.map(e=>e.tokens)),s=o[0].map((e,t)=>e.map((e,r)=>{let a={content:e.content,variants:{},offset:e.offset};return`includeExplanation`in n&&n.includeExplanation&&(a.explanation=e.explanation),o.forEach((e,n)=>{let{content:o,explanation:s,offset:c,...l}=e[t][r];a.variants[i[n].color]=l}),a})),c=a[0].state?new az(Object.fromEntries(a.map(e=>[e.theme,e.state?.getInternalStack(e.theme)])),a[0].state.lang):void 0;return c&&rz(s,c),s}function vz(...e){let t=e.map(()=>[]),n=e.length;for(let r=0;r<e[0].length;r++){let i=e.map(e=>e[r]),a=t.map(()=>[]);t.forEach((e,t)=>e.push(a[t]));let o=i.map(()=>0),s=i.map(e=>e[0]);for(;s.every(e=>e);){let e=Math.min(...s.map(e=>e.content.length));for(let t=0;t<n;t++){let n=s[t];n.content.length===e?(a[t].push(n),o[t]+=1,s[t]=i[t][o[t]]):(a[t].push({...n,content:n.content.slice(0,e)}),s[t]={...n,content:n.content.slice(e),offset:n.offset+e})}}}return t}function yz(e,t){if(!t)return e;e.properties||={},e.properties.class||=[],typeof e.properties.class==`string`&&(e.properties.class=e.properties.class.split(/\s+/g)),Array.isArray(e.properties.class)||(e.properties.class=[]);let n=Array.isArray(t)?t:t.split(/\s+/g);for(let t of n)t&&!e.properties.class.includes(t)&&e.properties.class.push(t);return e}function bz(e){let t=UR(e,!0).map(([e])=>e);function n(n){if(n===e.length)return{line:t.length-1,character:t[t.length-1].length};let r=n,i=0;for(let e of t){if(r<e.length)break;r-=e.length,i++}return{line:i,character:r}}function r(e,n){let r=0;for(let n=0;n<e;n++)r+=t[n].length;return r+=n,r}return{lines:t,indexToPos:n,posToIndex:r}}function xz(e,t,n){let r=new Set;for(let t of e.matchAll(/:?lang=["']([^"']+)["']/g)){let e=t[1].toLowerCase().trim();e&&r.add(e)}for(let t of e.matchAll(/(?:```|~~~)([\w-]+)/g)){let e=t[1].toLowerCase().trim();e&&r.add(e)}for(let t of e.matchAll(/\\begin\{([\w-]+)\}/g)){let e=t[1].toLowerCase().trim();e&&r.add(e)}for(let t of e.matchAll(/<script\s+(?:type|lang)=["']([^"']+)["']/gi)){let e=t[1].toLowerCase().trim(),n=e.includes(`/`)?e.split(`/`).pop():e;n&&r.add(n)}if(!n)return Array.from(r);let i=n.getBundledLanguages();return Array.from(r).filter(e=>e&&i[e])}var Sz=`light-dark()`,Cz=[`color`,`background-color`];function wz(e,t){let n=0,r=[];for(let i of t)i>n&&r.push({...e,content:e.content.slice(n,i),offset:e.offset+n}),n=i;return n<e.content.length&&r.push({...e,content:e.content.slice(n),offset:e.offset+n}),r}function Tz(e,t){let n=Array.from(t instanceof Set?t:new Set(t)).sort((e,t)=>e-t);return n.length?e.map(e=>e.flatMap(e=>{let t=n.filter(t=>e.offset<t&&t<e.offset+e.content.length).map(t=>t-e.offset).sort((e,t)=>e-t);return t.length?wz(e,t):e})):e}function Ez(e,t,n,r,i=`css-vars`){let a={content:e.content,explanation:e.explanation,offset:e.offset},o=t.map(t=>Dz(e.variants[t])),s=new Set(o.flatMap(e=>Object.keys(e))),c={},l=(e,r)=>{let i=r===`color`?``:r===`background-color`?`-bg`:`-${r}`;return n+t[e]+(r===`color`?``:i)};return o.forEach((e,n)=>{for(let a of s){let s=e[a]||`inherit`;if(n===0&&r&&Cz.includes(a))if(r===Sz&&o.length>1){let e=t.findIndex(e=>e===`light`),r=t.findIndex(e=>e===`dark`);if(e===-1||r===-1)throw new J('When using `defaultColor: "light-dark()"`, you must provide both `light` and `dark` themes');c[a]=`light-dark(${o[e][a]||`inherit`}, ${o[r][a]||`inherit`})`,i===`css-vars`&&(c[l(n,a)]=s)}else c[a]=s;else i===`css-vars`&&(c[l(n,a)]=s)}}),a.htmlStyle=c,a}function Dz(e){let t={};if(e.color&&(t.color=e.color),e.bgColor&&(t[`background-color`]=e.bgColor),e.fontStyle){e.fontStyle&Y.Italic&&(t[`font-style`]=`italic`),e.fontStyle&Y.Bold&&(t[`font-weight`]=`bold`);let n=[];e.fontStyle&Y.Underline&&n.push(`underline`),e.fontStyle&Y.Strikethrough&&n.push(`line-through`),n.length&&(t[`text-decoration`]=n.join(` `))}return t}function Oz(e){return typeof e==`string`?e:Object.entries(e).map(([e,t])=>`${e}:${t}`).join(`;`)}function kz(){let e=new WeakMap;function t(t){if(!e.has(t.meta)){let n=bz(t.source);function r(e){if(typeof e==`number`){if(e<0||e>t.source.length)throw new J(`Invalid decoration offset: ${e}. Code length: ${t.source.length}`);return{...n.indexToPos(e),offset:e}}{let t=n.lines[e.line];if(t===void 0)throw new J(`Invalid decoration position ${JSON.stringify(e)}. Lines length: ${n.lines.length}`);let r=e.character;if(r<0&&(r=t.length+r),r<0||r>t.length)throw new J(`Invalid decoration position ${JSON.stringify(e)}. Line ${e.line} length: ${t.length}`);return{...e,character:r,offset:n.posToIndex(e.line,r)}}}let i=(t.options.decorations||[]).map(e=>({...e,start:r(e.start),end:r(e.end)}));Az(i),e.set(t.meta,{decorations:i,converter:n,source:t.source})}return e.get(t.meta)}return{name:`shiki:decorations`,tokens(e){if(this.options.decorations?.length)return Tz(e,t(this).decorations.flatMap(e=>[e.start.offset,e.end.offset]))},code(e){if(!this.options.decorations?.length)return;let n=t(this),r=Array.from(e.children).filter(e=>e.type===`element`&&e.tagName===`span`);if(r.length!==n.converter.lines.length)throw new J(`Number of lines in code element (${r.length}) does not match the number of lines in the source (${n.converter.lines.length}). Failed to apply decorations.`);function i(e,t,n,i){let a=r[e],s=``,c=-1,l=-1;if(t===0&&(c=0),n===0&&(l=0),n===1/0&&(l=a.children.length),c===-1||l===-1)for(let e=0;e<a.children.length;e++)s+=jz(a.children[e]),c===-1&&s.length===t&&(c=e+1),l===-1&&s.length===n&&(l=e+1);if(c===-1)throw new J(`Failed to find start index for decoration ${JSON.stringify(i.start)}`);if(l===-1)throw new J(`Failed to find end index for decoration ${JSON.stringify(i.end)}`);let u=a.children.slice(c,l);if(!i.alwaysWrap&&u.length===a.children.length)o(a,i,`line`);else if(!i.alwaysWrap&&u.length===1&&u[0].type===`element`)o(u[0],i,`token`);else{let e={type:`element`,tagName:`span`,properties:{},children:u};o(e,i,`wrapper`),a.children.splice(c,u.length,e)}}function a(e,t){r[e]=o(r[e],t,`line`)}function o(e,t,n){let r=t.properties||{},i=t.transform||(e=>e);return e.tagName=t.tagName||`span`,e.properties={...e.properties,...r,class:e.properties.class},t.properties?.class&&yz(e,t.properties.class),e=i(e,n)||e,e}let s=[],c=n.decorations.sort((e,t)=>t.start.offset-e.start.offset||e.end.offset-t.end.offset);for(let e of c){let{start:t,end:n}=e;if(t.line===n.line)i(t.line,t.character,n.character,e);else if(t.line<n.line){i(t.line,t.character,1/0,e);for(let r=t.line+1;r<n.line;r++)s.unshift(()=>a(r,e));i(n.line,0,n.character,e)}}s.forEach(e=>e())}}}function Az(e){for(let t=0;t<e.length;t++){let n=e[t];if(n.start.offset>n.end.offset)throw new J(`Invalid decoration range: ${JSON.stringify(n.start)} - ${JSON.stringify(n.end)}`);for(let r=t+1;r<e.length;r++){let t=e[r],i=n.start.offset<=t.start.offset&&t.start.offset<n.end.offset,a=n.start.offset<t.end.offset&&t.end.offset<=n.end.offset,o=t.start.offset<=n.start.offset&&n.start.offset<t.end.offset,s=t.start.offset<n.end.offset&&n.end.offset<=t.end.offset;if(i||a||o||s){if(i&&a||o&&s||o&&n.start.offset===n.end.offset||a&&t.start.offset===t.end.offset)continue;throw new J(`Decorations ${JSON.stringify(n.start)} and ${JSON.stringify(t.start)} intersect.`)}}}}function jz(e){return e.type===`text`?e.value:e.type===`element`?e.children.map(jz).join(``):``}var Mz=[kz()];function Nz(e){let t=Pz(e.transformers||[]);return[...t.pre,...t.normal,...t.post,...Mz]}function Pz(e){let t=[],n=[],r=[];for(let i of e)switch(i.enforce){case`pre`:t.push(i);break;case`post`:n.push(i);break;default:r.push(i)}return{pre:t,post:n,normal:r}}var Fz=[`black`,`red`,`green`,`yellow`,`blue`,`magenta`,`cyan`,`white`,`brightBlack`,`brightRed`,`brightGreen`,`brightYellow`,`brightBlue`,`brightMagenta`,`brightCyan`,`brightWhite`],Iz={1:`bold`,2:`dim`,3:`italic`,4:`underline`,7:`reverse`,8:`hidden`,9:`strikethrough`};function Lz(e,t){let n=e.indexOf(`\x1B`,t);if(n!==-1&&e[n+1]===`[`){let t=e.indexOf(`m`,n);if(t!==-1)return{sequence:e.substring(n+2,t).split(`;`),startPosition:n,position:t+1}}return{position:e.length}}function Rz(e){let t=e.shift();if(t===`2`){let t=e.splice(0,3).map(e=>Number.parseInt(e));return t.length!==3||t.some(e=>Number.isNaN(e))?void 0:{type:`rgb`,rgb:t}}if(t===`5`){let t=e.shift();if(t)return{type:`table`,index:Number(t)}}}function zz(e){let t=[];for(;e.length>0;){let n=e.shift();if(!n)continue;let r=Number.parseInt(n);if(!Number.isNaN(r))if(r===0)t.push({type:`resetAll`});else if(r<=9)Iz[r]&&t.push({type:`setDecoration`,value:Iz[r]});else if(r<=29){let e=Iz[r-20];e&&(t.push({type:`resetDecoration`,value:e}),e===`dim`&&t.push({type:`resetDecoration`,value:`bold`}))}else if(r<=37)t.push({type:`setForegroundColor`,value:{type:`named`,name:Fz[r-30]}});else if(r===38){let n=Rz(e);n&&t.push({type:`setForegroundColor`,value:n})}else if(r===39)t.push({type:`resetForegroundColor`});else if(r<=47)t.push({type:`setBackgroundColor`,value:{type:`named`,name:Fz[r-40]}});else if(r===48){let n=Rz(e);n&&t.push({type:`setBackgroundColor`,value:n})}else r===49?t.push({type:`resetBackgroundColor`}):r===53?t.push({type:`setDecoration`,value:`overline`}):r===55?t.push({type:`resetDecoration`,value:`overline`}):r>=90&&r<=97?t.push({type:`setForegroundColor`,value:{type:`named`,name:Fz[r-90+8]}}):r>=100&&r<=107&&t.push({type:`setBackgroundColor`,value:{type:`named`,name:Fz[r-100+8]}})}return t}function Bz(){let e=null,t=null,n=new Set;return{parse(r){let i=[],a=0;do{let o=Lz(r,a),s=o.sequence?r.substring(a,o.startPosition):r.substring(a);if(s.length>0&&i.push({value:s,foreground:e,background:t,decorations:new Set(n)}),o.sequence){let r=zz(o.sequence);for(let i of r)i.type===`resetAll`?(e=null,t=null,n.clear()):i.type===`resetForegroundColor`?e=null:i.type===`resetBackgroundColor`?t=null:i.type===`resetDecoration`&&n.delete(i.value);for(let i of r)i.type===`setForegroundColor`?e=i.value:i.type===`setBackgroundColor`?t=i.value:i.type===`setDecoration`&&n.add(i.value)}a=o.position}while(a<r.length);return i}}}var Vz={black:`#000000`,red:`#bb0000`,green:`#00bb00`,yellow:`#bbbb00`,blue:`#0000bb`,magenta:`#ff00ff`,cyan:`#00bbbb`,white:`#eeeeee`,brightBlack:`#555555`,brightRed:`#ff5555`,brightGreen:`#00ff00`,brightYellow:`#ffff55`,brightBlue:`#5555ff`,brightMagenta:`#ff55ff`,brightCyan:`#55ffff`,brightWhite:`#ffffff`};function Hz(e=Vz){function t(t){return e[t]}function n(e){return`#${e.map(e=>Math.max(0,Math.min(e,255)).toString(16).padStart(2,`0`)).join(``)}`}let r;function i(){if(r)return r;r=[];for(let e=0;e<Fz.length;e++)r.push(t(Fz[e]));let e=[0,95,135,175,215,255];for(let t=0;t<6;t++)for(let i=0;i<6;i++)for(let a=0;a<6;a++)r.push(n([e[t],e[i],e[a]]));let i=8;for(let e=0;e<24;e++,i+=10)r.push(n([i,i,i]));return r}function a(e){return i()[e]}function o(e){switch(e.type){case`named`:return t(e.name);case`rgb`:return n(e.rgb);case`table`:return a(e.index)}}return{value:o}}var Uz={black:`#000000`,red:`#cd3131`,green:`#0DBC79`,yellow:`#E5E510`,blue:`#2472C8`,magenta:`#BC3FBC`,cyan:`#11A8CD`,white:`#E5E5E5`,brightBlack:`#666666`,brightRed:`#F14C4C`,brightGreen:`#23D18B`,brightYellow:`#F5F543`,brightBlue:`#3B8EEA`,brightMagenta:`#D670D6`,brightCyan:`#29B8DB`,brightWhite:`#FFFFFF`};function Wz(e,t,n){let r=FR(e,n),i=UR(t),a=Hz(Object.fromEntries(Fz.map(t=>{let n=`terminal.ansi${t[0].toUpperCase()}${t.substring(1)}`;return[t,e.colors?.[n]||Uz[t]]}))),o=Bz();return i.map(t=>o.parse(t[0]).map(n=>{let i,o;n.decorations.has(`reverse`)?(i=n.background?a.value(n.background):e.bg,o=n.foreground?a.value(n.foreground):e.fg):(i=n.foreground?a.value(n.foreground):e.fg,o=n.background?a.value(n.background):void 0),i=IR(i,r),o=IR(o,r),n.decorations.has(`dim`)&&(i=Gz(i));let s=Y.None;return n.decorations.has(`bold`)&&(s|=Y.Bold),n.decorations.has(`italic`)&&(s|=Y.Italic),n.decorations.has(`underline`)&&(s|=Y.Underline),n.decorations.has(`strikethrough`)&&(s|=Y.Strikethrough),{content:n.value,offset:t[1],color:i,bgColor:o,fontStyle:s}}))}function Gz(e){let t=e.match(/#([0-9a-f]{3,8})/i);if(t){let e=t[1];if(e.length===8){let t=Math.round(Number.parseInt(e.slice(6,8),16)/2).toString(16).padStart(2,`0`);return`#${e.slice(0,6)}${t}`}if(e.length===6)return`#${e}80`;if(e.length===4){let t=e[0],n=e[1],r=e[2],i=e[3];return`#${t}${t}${n}${n}${r}${r}${Math.round(Number.parseInt(`${i}${i}`,16)/2).toString(16).padStart(2,`0`)}`}if(e.length===3){let t=e[0],n=e[1],r=e[2];return`#${t}${t}${n}${n}${r}${r}80`}}let n=e.match(/var\((--[\w-]+-ansi-[\w-]+)\)/);return n?`var(${n[1]}-dim)`:e}function Kz(e,t,n={}){let r=e.resolveLangAlias(n.lang||`text`),{theme:i=e.getLoadedThemes()[0]}=n;if(!zR(r)&&!VR(i)&&r===`ansi`){let{theme:r}=e.setTheme(i);return Wz(r,t,n)}return cz(e,t,n)}function qz(e,t,n){let r,i,a,o,s,c;if(`themes`in n){let{defaultColor:l=`light`,cssVariablePrefix:u=`--shiki-`,colorsRendering:d=`css-vars`}=n,f=Object.entries(n.themes).filter(e=>e[1]).map(e=>({color:e[0],theme:e[1]})).sort((e,t)=>e.color===l?-1:+(t.color===l));if(f.length===0)throw new J("`themes` option must not be empty");let p=_z(e,t,n,Kz);if(c=iz(p),l&&Sz!==l&&!f.find(e=>e.color===l))throw new J(`\`themes\` option must contain the defaultColor key \`${l}\``);let m=f.map(t=>e.getTheme(t.theme)),h=f.map(e=>e.color);a=p.map(e=>e.map(e=>Ez(e,h,u,l,d))),c&&rz(a,c);let g=f.map(e=>FR(e.theme,n));i=Jz(f,m,g,u,l,`fg`,d),r=Jz(f,m,g,u,l,`bg`,d),o=`shiki-themes ${m.map(e=>e.name).join(` `)}`,s=l?void 0:[i,r].join(`;`)}else if(`theme`in n){let s=FR(n.theme,n);a=Kz(e,t,n);let l=e.getTheme(n.theme);r=IR(l.bg,s),i=IR(l.fg,s),o=l.name,c=iz(a)}else throw new J("Invalid options, either `theme` or `themes` must be provided");return{tokens:a,fg:i,bg:r,themeName:o,rootStyle:s,grammarState:c}}function Jz(e,t,n,r,i,a,o){return e.map((s,c)=>{let l=IR(t[c][a],n[c])||`inherit`,u=`${r+s.color}${a===`bg`?`-bg`:``}:${l}`;if(c===0&&i){if(i===Sz&&e.length>1){let r=e.findIndex(e=>e.color===`light`),i=e.findIndex(e=>e.color===`dark`);if(r===-1||i===-1)throw new J('When using `defaultColor: "light-dark()"`, you must provide both `light` and `dark` themes');return`light-dark(${IR(t[r][a],n[r])||`inherit`}, ${IR(t[i][a],n[i])||`inherit`});${u}`}return l}return o===`css-vars`?u:null}).filter(e=>!!e).join(`;`)}function Yz(e,t,n,r={meta:{},options:n,codeToHast:(t,n)=>Yz(e,t,n),codeToTokens:(t,n)=>qz(e,t,n)}){let i=t;for(let e of Nz(n))i=e.preprocess?.call(r,i,n)||i;let{tokens:a,fg:o,bg:s,themeName:c,rootStyle:l,grammarState:u}=qz(e,i,n),{mergeWhitespaces:d=!0,mergeSameStyleTokens:f=!1}=n;d===!0?a=Zz(a):d===`never`&&(a=Qz(a)),f&&(a=$z(a));let p={...r,get source(){return i}};for(let e of Nz(n))a=e.tokens?.call(p,a)||a;return Xz(a,{...n,fg:o,bg:s,themeName:c,rootStyle:n.rootStyle===!1?!1:n.rootStyle??l},p,u)}function Xz(e,t,n,r=iz(e)){let i=Nz(t),a=[],o={type:`root`,children:[]},{structure:s=`classic`,tabindex:c=`0`}=t,l={class:`shiki ${t.themeName||``}`};t.rootStyle!==!1&&(l.style=t.rootStyle==null?`background-color:${t.bg};color:${t.fg}`:t.rootStyle),c!==!1&&c!=null&&(l.tabindex=c.toString());for(let[e,n]of Object.entries(t.meta||{}))e.startsWith(`_`)||(l[e]=n);let u={type:`element`,tagName:`pre`,properties:l,children:[],data:t.data},d={type:`element`,tagName:`code`,properties:{},children:a},f=[],p={...n,structure:s,addClassToHast:yz,get source(){return n.source},get tokens(){return e},get options(){return t},get root(){return o},get pre(){return u},get code(){return d},get lines(){return f}};if(e.forEach((e,t)=>{t&&(s===`inline`?o.children.push({type:`element`,tagName:`br`,properties:{},children:[]}):s===`classic`&&a.push({type:`text`,value:`
|
|
44
|
+
`}));let n={type:`element`,tagName:`span`,properties:{class:`line`},children:[]},r=0;for(let a of e){let e={type:`element`,tagName:`span`,properties:{...a.htmlAttrs},children:[{type:`text`,value:a.content}]},c=Oz(a.htmlStyle||Dz(a));c&&(e.properties.style=c);for(let o of i)e=o?.span?.call(p,e,t+1,r,n,a)||e;s===`inline`?o.children.push(e):s===`classic`&&n.children.push(e),r+=a.content.length}if(s===`classic`){for(let e of i)n=e?.line?.call(p,n,t+1)||n;f.push(n),a.push(n)}else s===`inline`&&f.push(n)}),s===`classic`){for(let e of i)d=e?.code?.call(p,d)||d;u.children.push(d);for(let e of i)u=e?.pre?.call(p,u)||u;o.children.push(u)}else if(s===`inline`){let e=[],t={type:`element`,tagName:`span`,properties:{class:`line`},children:[]};for(let n of o.children)n.type===`element`&&n.tagName===`br`?(e.push(t),t={type:`element`,tagName:`span`,properties:{class:`line`},children:[]}):(n.type===`element`||n.type===`text`)&&t.children.push(n);e.push(t);let n={type:`element`,tagName:`code`,properties:{},children:e};for(let e of i)n=e?.code?.call(p,n)||n;o.children=[];for(let e=0;e<n.children.length;e++){e>0&&o.children.push({type:`element`,tagName:`br`,properties:{},children:[]});let t=n.children[e];t.type===`element`&&o.children.push(...t.children)}}let m=o;for(let e of i)m=e?.root?.call(p,m)||m;return r&&rz(m,r),m}function Zz(e){return e.map(e=>{let t=[],n=``,r;return e.forEach((i,a)=>{let o=!(i.fontStyle&&(i.fontStyle&Y.Underline||i.fontStyle&Y.Strikethrough));o&&i.content.match(/^\s+$/)&&e[a+1]?(r===void 0&&(r=i.offset),n+=i.content):n?(o?t.push({...i,offset:r,content:n+i.content}):t.push({content:n,offset:r},i),r=void 0,n=``):t.push(i)}),t})}function Qz(e){return e.map(e=>e.flatMap(e=>{if(e.content.match(/^\s+$/))return e;let t=e.content.match(/^(\s*)(.*?)(\s*)$/);if(!t)return e;let[,n,r,i]=t;if(!n&&!i)return e;let a=[{...e,offset:e.offset+n.length,content:r}];return n&&a.unshift({content:n,offset:e.offset}),i&&a.push({content:i,offset:e.offset+n.length+r.length}),a}))}function $z(e){return e.map(e=>{let t=[];for(let n of e){if(t.length===0){t.push({...n});continue}let e=t[t.length-1],r=Oz(e.htmlStyle||Dz(e)),i=Oz(n.htmlStyle||Dz(n)),a=e.fontStyle&&(e.fontStyle&Y.Underline||e.fontStyle&Y.Strikethrough),o=n.fontStyle&&(n.fontStyle&Y.Underline||n.fontStyle&Y.Strikethrough);!a&&!o&&r===i?e.content+=n.content:t.push({...n})}return t})}var eB=jF;function tB(e,t,n){let r={meta:{},options:n,codeToHast:(t,n)=>Yz(e,t,n),codeToTokens:(t,n)=>qz(e,t,n)},i=eB(Yz(e,t,n,r));for(let e of Nz(n))i=e.postprocess?.call(r,i,n)||i;return i}async function nB(e){let t=await tz(e);return{getLastGrammarState:(...e)=>lz(t,...e),codeToTokensBase:(e,n)=>Kz(t,e,n),codeToTokensWithThemes:(e,n)=>_z(t,e,n),codeToTokens:(e,n)=>qz(t,e,n),codeToHast:(e,n)=>Yz(t,e,n),codeToHtml:(e,n)=>tB(t,e,n),getBundledLanguages:()=>({}),getBundledThemes:()=>({}),...t,getInternalContext:()=>t}}function rB(e){let t=e.langs,n=e.themes,r=e.engine;async function i(e){function i(n){if(typeof n==`string`){if(n=e.langAlias?.[n]||n,BR(n))return[];let r=t[n];if(!r)throw new J(`Language \`${n}\` is not included in this bundle. You may want to load it from external source.`);return r}return n}function a(e){if(HR(e))return`none`;if(typeof e==`string`){let t=n[e];if(!t)throw new J(`Theme \`${e}\` is not included in this bundle. You may want to load it from external source.`);return t}return e}let o=(e.themes??[]).map(e=>a(e)),s=(e.langs??[]).map(e=>i(e)),c=await nB({engine:e.engine??r(),...e,themes:o,langs:s});return{...c,loadLanguage(...e){return c.loadLanguage(...e.map(i))},loadTheme(...e){return c.loadTheme(...e.map(a))},getBundledLanguages(){return t},getBundledThemes(){return n}}}return i}function iB(e){let t;async function n(n={}){if(t){let e=await t;return await Promise.all([e.loadTheme(...n.themes||[]),e.loadLanguage(...n.langs||[])]),e}{t=e({...n,themes:[],langs:[]});let r=await t;return await Promise.all([r.loadTheme(...n.themes||[]),r.loadLanguage(...n.langs||[])]),r}}return n}function aB(e,t){let n=iB(e);async function r(e,r){let i=await n({langs:[r.lang],themes:`theme`in r?[r.theme]:Object.values(r.themes)}),a=await t?.guessEmbeddedLanguages?.(e,r.lang,i);return a&&await i.loadLanguage(...a),i}return{getSingletonHighlighter(e){return n(e)},async codeToHtml(e,t){return(await r(e,t)).codeToHtml(e,t)},async codeToHast(e,t){return(await r(e,t)).codeToHast(e,t)},async codeToTokens(e,t){return(await r(e,t)).codeToTokens(e,t)},async codeToTokensBase(e,t){return(await r(e,t)).codeToTokensBase(e,t)},async codeToTokensWithThemes(e,t){return(await r(e,t)).codeToTokensWithThemes(e,t)},async getLastGrammarState(e,t){return(await n({langs:[t.lang],themes:[t.theme]})).getLastGrammarState(e,t)}}}var oB=rB({langs:TI,themes:EI,engine:()=>(0,eL.createOnigurumaEngine)(D(()=>import(`./wasm-BnjxR4X6.js`),[]))}),{codeToHtml:sB,codeToHast:cB,codeToTokens:lB,codeToTokensBase:uB,codeToTokensWithThemes:dB,getSingletonHighlighter:fB,getLastGrammarState:pB}=aB(oB,{guessEmbeddedLanguages:xz}),mB=4294967295,hB=class{regexps;constructor(e,t={}){this.patterns=e,this.options=t;let{forgiving:n=!1,cache:r,regexConstructor:i}=t;if(!i)throw Error("Option `regexConstructor` is not provided");this.regexps=e.map(e=>{if(typeof e!=`string`)return e;let t=r?.get(e);if(t){if(t instanceof RegExp)return t;if(n)return null;throw t}try{let t=i(e);return r?.set(e,t),t}catch(t){if(r?.set(e,t),n)return null;throw t}})}findNextMatchSync(e,t,n){let r=typeof e==`string`?e:e.content,i=[];function a(e,t,n=0){return{index:e,captureIndices:t.indices.map(e=>e==null?{start:mB,end:mB,length:0}:{start:e[0]+n,end:e[1]+n,length:e[1]-e[0]})}}for(let e=0;e<this.regexps.length;e++){let n=this.regexps[e];if(n)try{n.lastIndex=t;let o=n.exec(r);if(!o)continue;if(o.index===t)return a(e,o,0);i.push([e,o,0])}catch(e){if(this.options.forgiving)continue;throw e}}if(i.length){let e=Math.min(...i.map(e=>e[1].index));for(let[t,n,r]of i)if(n.index===e)return a(t,n,r)}return null}};function gB(e){if([...e].length!==1)throw Error(`Expected "${e}" to be a single code point`);return e.codePointAt(0)}function _B(e,t,n){return e.has(t)||e.set(t,n),e.get(t)}var vB=new Set([`alnum`,`alpha`,`ascii`,`blank`,`cntrl`,`digit`,`graph`,`lower`,`print`,`punct`,`space`,`upper`,`word`,`xdigit`]),X=String.raw;function yB(e,t){if(e==null)throw Error(t??`Value expected`);return e}var bB=X`\[\^?`,xB=`c.? | C(?:-.?)?|${X`[pP]\{(?:\^?[-\x20_]*[A-Za-z][-\x20\w]*\})?`}|${X`x[89A-Fa-f]\p{AHex}(?:\\x[89A-Fa-f]\p{AHex})*`}|${X`u(?:\p{AHex}{4})? | x\{[^\}]*\}? | x\p{AHex}{0,2}`}|${X`o\{[^\}]*\}?`}|${X`\d{1,3}`}`,SB=/[?*+][?+]?|\{(?:\d+(?:,\d*)?|,\d+)\}\??/,CB=new RegExp(X`
|
|
45
45
|
\\ (?:
|
|
46
|
-
${
|
|
46
|
+
${xB}
|
|
47
47
|
| [gk]<[^>]*>?
|
|
48
48
|
| [gk]'[^']*'?
|
|
49
49
|
| .
|
|
@@ -60,20 +60,20 @@ import{n as e,r as t,t as n}from"./rolldown-runtime-hePW80VL.js";import{$ as r,$
|
|
|
60
60
|
)?
|
|
61
61
|
| \*[^\)]*\)?
|
|
62
62
|
)?
|
|
63
|
-
| (?:${
|
|
64
|
-
| ${
|
|
63
|
+
| (?:${SB.source})+
|
|
64
|
+
| ${bB}
|
|
65
65
|
| .
|
|
66
|
-
`.replace(/\s+/g,``),`gsu`),
|
|
66
|
+
`.replace(/\s+/g,``),`gsu`),wB=new RegExp(X`
|
|
67
67
|
\\ (?:
|
|
68
|
-
${
|
|
68
|
+
${xB}
|
|
69
69
|
| .
|
|
70
70
|
)
|
|
71
71
|
| \[:(?:\^?\p{Alpha}+|\^):\]
|
|
72
|
-
| ${
|
|
72
|
+
| ${bB}
|
|
73
73
|
| &&
|
|
74
74
|
| .
|
|
75
|
-
`.replace(/\s+/g,``),`gsu`);function
|
|
76
|
-
`,r);return{lastIndex:e===-1?t.length:e}}if(/^\s$/.test(n)){let e=/\s+/y;return e.lastIndex=r,{lastIndex:e.exec(t)?e.lastIndex:r}}}return n===`.`?{token:LB(`dot`,n)}:n===`^`||n===`$`?{token:AB(e.singleline?{"^":X`\A`,$:X`\Z`}[n]:n,n)}:n===`|`?{token:kB(n)}:xB.test(n)?{tokens:rV(n)}:{token:MB(hB(n),n)}}function EB(e,t,n){let r=[IB(t[1]===`^`,t)],i=1,a;for(CB.lastIndex=n;a=CB.exec(e);){let e=a[0];if(e[0]===`[`&&e[1]!==`:`)i++,r.push(IB(e[1]===`^`,e));else if(e===`]`){if(r.at(-1).type===`CharacterClassOpen`)r.push(MB(93,e));else if(i--,r.push(NB(e)),!i)break}else{let t=DB(e);Array.isArray(t)?r.push(...t):r.push(t)}}return{tokens:r,lastIndex:CB.lastIndex||e.length}}function DB(e){if(e[0]===`\\`)return OB(e,{inCharClass:!0});if(e[0]===`[`){let t=/\[:(?<negate>\^?)(?<name>[a-z]+):\]/.exec(e);if(!t||!_B.has(t.groups.name))throw Error(`Invalid POSIX class "${e}"`);return LB(`posix`,e,{value:t.groups.name,negate:!!t.groups.negate})}return e===`-`?PB(e):e===`&&`?FB(e):MB(hB(e),e)}function OB(e,{inCharClass:t}){let n=e[1];if(n===`c`||n===`C`)return qB(e);if(`dDhHsSwW`.includes(n))return ZB(e);if(e.startsWith(X`\o{`))throw Error(`Incomplete, invalid, or unsupported octal code point "${e}"`);if(/^\\[pP]\{/.test(e)){if(e.length===3)throw Error(`Incomplete or invalid Unicode property "${e}"`);return QB(e)}if(/^\\x[89A-Fa-f]\p{AHex}/u.test(e))try{let t=e.split(/\\x/).slice(1).map(e=>parseInt(e,16)),n=new TextDecoder(`utf-8`,{ignoreBOM:!0,fatal:!0}).decode(new Uint8Array(t)),r=new TextEncoder;return[...n].map(e=>{let t=[...r.encode(e)].map(e=>`\\x${e.toString(16)}`).join(``);return MB(hB(e),t)})}catch{throw Error(`Multibyte code "${e}" incomplete or invalid in Oniguruma`)}if(n===`u`||n===`x`)return MB(tV(e),e);if(KB.has(n))return MB(KB.get(n),e);if(/\d/.test(n))return zB(t,e);if(e===`\\`)throw Error(X`Incomplete escape "\"`);if(n===`M`)throw Error(`Unsupported meta "${e}"`);if([...e].length===2)return MB(e.codePointAt(1),e);throw Error(`Unexpected escape "${e}"`)}function kB(e){return{type:`Alternator`,raw:e}}function AB(e,t){return{type:`Assertion`,kind:e,raw:t}}function jB(e){return{type:`Backreference`,raw:e}}function MB(e,t){return{type:`Character`,value:e,raw:t}}function NB(e){return{type:`CharacterClassClose`,raw:e}}function PB(e){return{type:`CharacterClassHyphen`,raw:e}}function FB(e){return{type:`CharacterClassIntersector`,raw:e}}function IB(e,t){return{type:`CharacterClassOpen`,negate:e,raw:t}}function LB(e,t,n={}){return{type:`CharacterSet`,kind:e,...n,raw:t}}function RB(e,t,n={}){return e===`keep`?{type:`Directive`,kind:e,raw:t}:{type:`Directive`,kind:e,flags:vB(n.flags),raw:t}}function zB(e,t){return{type:`EscapedNumber`,inCharClass:e,raw:t}}function BB(e){return{type:`GroupClose`,raw:e}}function VB(e,t,n={}){return{type:`GroupOpen`,kind:e,...n,raw:t}}function HB(e,t,n,r){return{type:`NamedCallout`,kind:e,tag:t,arguments:n,raw:r}}function UB(e,t,n,r){return{type:`Quantifier`,kind:e,min:t,max:n,raw:r}}function WB(e){return{type:`Subroutine`,raw:e}}var GB=new Set([`COUNT`,`CMP`,`ERROR`,`FAIL`,`MAX`,`MISMATCH`,`SKIP`,`TOTAL_COUNT`]),KB=new Map([[`a`,7],[`b`,8],[`e`,27],[`f`,12],[`n`,10],[`r`,13],[`t`,9],[`v`,11]]);function qB(e){let t=e[1]===`c`?e[2]:e[3];if(!t||!/[A-Za-z]/.test(t))throw Error(`Unsupported control character "${e}"`);return MB(hB(t.toUpperCase())-64,e)}function JB(e,t){let{on:n,off:r}=/^\(\?(?<on>[imx]*)(?:-(?<off>[-imx]*))?/.exec(e).groups;r??=``;let i=(t.getCurrentModX()||n.includes(`x`))&&!r.includes(`x`),a=$B(n),o=$B(r),s={};if(a&&(s.enable=a),o&&(s.disable=o),e.endsWith(`)`))return t.replaceCurrentModX(i),RB(`flags`,e,{flags:s});if(e.endsWith(`:`))return t.pushModX(i),t.numOpenGroups++,VB(`group`,e,{...(a||o)&&{flags:s}});throw Error(`Unexpected flag modifier "${e}"`)}function YB(e){let t=/\(\*(?<name>[A-Za-z_]\w*)?(?:\[(?<tag>(?:[A-Za-z_]\w*)?)\])?(?:\{(?<args>[^}]*)\})?\)/.exec(e);if(!t)throw Error(`Incomplete or invalid named callout "${e}"`);let{name:n,tag:r,args:i}=t.groups;if(!n)throw Error(`Invalid named callout "${e}"`);if(r===``)throw Error(`Named callout tag with empty value not allowed "${e}"`);let a=i?i.split(`,`).filter(e=>e!==``).map(e=>/^[+-]?\d+$/.test(e)?+e:e):[],[o,s,c]=a,l=GB.has(n)?n.toLowerCase():`custom`;switch(l){case`fail`:case`mismatch`:case`skip`:if(a.length>0)throw Error(`Named callout arguments not allowed "${a}"`);break;case`error`:if(a.length>1)throw Error(`Named callout allows only one argument "${a}"`);if(typeof o==`string`)throw Error(`Named callout argument must be a number "${o}"`);break;case`max`:if(!a.length||a.length>2)throw Error(`Named callout must have one or two arguments "${a}"`);if(typeof o==`string`&&!/^[A-Za-z_]\w*$/.test(o))throw Error(`Named callout argument one must be a tag or number "${o}"`);if(a.length===2&&(typeof s==`number`||!/^[<>X]$/.test(s)))throw Error(`Named callout optional argument two must be '<', '>', or 'X' "${s}"`);break;case`count`:case`total_count`:if(a.length>1)throw Error(`Named callout allows only one argument "${a}"`);if(a.length===1&&(typeof o==`number`||!/^[<>X]$/.test(o)))throw Error(`Named callout optional argument must be '<', '>', or 'X' "${o}"`);break;case`cmp`:if(a.length!==3)throw Error(`Named callout must have three arguments "${a}"`);if(typeof o==`string`&&!/^[A-Za-z_]\w*$/.test(o))throw Error(`Named callout argument one must be a tag or number "${o}"`);if(typeof s==`number`||!/^(?:[<>!=]=|[<>])$/.test(s))throw Error(`Named callout argument two must be '==', '!=', '>', '<', '>=', or '<=' "${s}"`);if(typeof c==`string`&&!/^[A-Za-z_]\w*$/.test(c))throw Error(`Named callout argument three must be a tag or number "${c}"`);break;case`custom`:throw Error(`Undefined callout name "${n}"`);default:throw Error(`Unexpected named callout kind "${l}"`)}return HB(l,r??null,i?.split(`,`)??null,e)}function XB(e){let t=null,n,r;if(e[0]===`{`){let{minStr:i,maxStr:a}=/^\{(?<minStr>\d*)(?:,(?<maxStr>\d*))?/.exec(e).groups,o=1e5;if(+i>o||a&&+a>o)throw Error(`Quantifier value unsupported in Oniguruma`);if(n=+i,r=a===void 0?+i:a===``?1/0:+a,n>r&&(t=`possessive`,[n,r]=[r,n]),e.endsWith(`?`)){if(t===`possessive`)throw Error(`Unsupported possessive interval quantifier chain with "?"`);t=`lazy`}else t||=`greedy`}else n=+(e[0]===`+`),r=e[0]===`?`?1:1/0,t=e[1]===`+`?`possessive`:e[1]===`?`?`lazy`:`greedy`;return UB(t,n,r,e)}function ZB(e){let t=e[1].toLowerCase();return LB({d:`digit`,h:`hex`,s:`space`,w:`word`}[t],e,{negate:e[1]!==t})}function QB(e){let{p:t,neg:n,value:r}=/^\\(?<p>[pP])\{(?<neg>\^?)(?<value>[^}]+)/.exec(e).groups;return LB(`property`,e,{value:r,negate:t===`P`&&!n||t===`p`&&!!n})}function $B(e){let t={};return e.includes(`i`)&&(t.ignoreCase=!0),e.includes(`m`)&&(t.dotAll=!0),e.includes(`x`)&&(t.extended=!0),Object.keys(t).length?t:null}function eV(e){let t={ignoreCase:!1,dotAll:!1,extended:!1,digitIsAscii:!1,posixIsAscii:!1,spaceIsAscii:!1,wordIsAscii:!1,textSegmentMode:null};for(let n=0;n<e.length;n++){let r=e[n];if(!`imxDPSWy`.includes(r))throw Error(`Invalid flag "${r}"`);if(r===`y`){if(!/^y{[gw]}/.test(e.slice(n)))throw Error(`Invalid or unspecified flag "y" mode`);t.textSegmentMode=e[n+2]===`g`?`grapheme`:`word`,n+=3;continue}t[{i:`ignoreCase`,m:`dotAll`,x:`extended`,D:`digitIsAscii`,P:`posixIsAscii`,S:`spaceIsAscii`,W:`wordIsAscii`}[r]]=!0}return t}function tV(e){if(/^(?:\\u(?!\p{AHex}{4})|\\x(?!\p{AHex}{1,2}|\{\p{AHex}{1,8}\}))/u.test(e))throw Error(`Incomplete or invalid escape "${e}"`);let t=e[2]===`{`?/^\\x\{\s*(?<hex>\p{AHex}+)/u.exec(e).groups.hex:e.slice(2);return parseInt(t,16)}function nV(e,t){let{raw:n,inCharClass:r}=e,i=n.slice(1);if(!r&&(i!==`0`&&i.length===1||i[0]!==`0`&&+i<=t))return[jB(n)];let a=[],o=i.match(/^[0-7]+|\d/g);for(let e=0;e<o.length;e++){let t=o[e],r;if(e===0&&t!==`8`&&t!==`9`){if(r=parseInt(t,8),r>127)throw Error(X`Octal encoded byte above 177 unsupported "${n}"`)}else r=hB(t);a.push(MB(r,(e===0?`\\`:``)+t))}return a}function rV(e){let t=[],n=new RegExp(xB,`gy`),r;for(;r=n.exec(e);){let e=r[0];if(e[0]===`{`){let r=/^\{(?<min>\d+),(?<max>\d+)\}\??$/.exec(e);if(r){let{min:i,max:a}=r.groups;if(+i>+a&&e.endsWith(`?`)){n.lastIndex--,t.push(XB(e.slice(0,-1)));continue}}}t.push(XB(e))}return t}function iV(e,t){if(!Array.isArray(e.body))throw Error(`Expected node with body array`);if(e.body.length!==1)return!1;let n=e.body[0];return!t||Object.keys(t).every(e=>t[e]===n[e])}function aV(e){return oV.has(e.type)}var oV=new Set([`AbsenceFunction`,`Backreference`,`CapturingGroup`,`Character`,`CharacterClass`,`CharacterSet`,`Group`,`Quantifier`,`Subroutine`]);function sV(e,t={}){let n={flags:``,normalizeUnknownPropertyNames:!1,skipBackrefValidation:!1,skipLookbehindValidation:!1,skipPropertyNameValidation:!1,unicodePropertyMap:null,...t,rules:{captureGroup:!1,singleline:!1,...t.rules}},r=wB(e,{flags:n.flags,rules:{captureGroup:n.rules.captureGroup,singleline:n.rules.singleline}}),i=(e,t)=>{let n=r.tokens[a.nextIndex];switch(a.parent=e,a.nextIndex++,n.type){case`Alternator`:return _V();case`Assertion`:return cV(n);case`Backreference`:return lV(n,a);case`Character`:return xV(n.value,{useLastValid:!!t.isCheckingRangeEnd});case`CharacterClassHyphen`:return uV(n,a,t);case`CharacterClassOpen`:return dV(n,a,t);case`CharacterSet`:return fV(n,a);case`Directive`:return TV(n.kind,{flags:n.flags});case`GroupOpen`:return pV(n,a,t);case`NamedCallout`:return kV(n.kind,n.tag,n.arguments);case`Quantifier`:return mV(n,a);case`Subroutine`:return hV(n,a);default:throw Error(`Unexpected token type "${n.type}"`)}},a={capturingGroups:[],hasNumberedRef:!1,namedGroupsByName:new Map,nextIndex:0,normalizeUnknownPropertyNames:n.normalizeUnknownPropertyNames,parent:null,skipBackrefValidation:n.skipBackrefValidation,skipLookbehindValidation:n.skipLookbehindValidation,skipPropertyNameValidation:n.skipPropertyNameValidation,subroutines:[],tokens:r.tokens,unicodePropertyMap:n.unicodePropertyMap,walk:i},o=MV(EV(r.flags)),s=o.body[0];for(;a.nextIndex<r.tokens.length;){let e=i(s,{});e.type===`Alternative`?(o.body.push(e),s=e):s.body.push(e)}let{capturingGroups:c,hasNumberedRef:l,namedGroupsByName:u,subroutines:d}=a;if(l&&u.size&&!n.rules.captureGroup)throw Error(`Numbered backref/subroutine not allowed when using named capture`);for(let{ref:e}of d)if(typeof e==`number`){if(e>c.length)throw Error(`Subroutine uses a group number that's not defined`);e&&(c[e-1].isSubroutined=!0)}else if(u.has(e)){if(u.get(e).length>1)throw Error(X`Subroutine uses a duplicate group name "\g<${e}>"`);u.get(e)[0].isSubroutined=!0}else throw Error(X`Subroutine uses a group name that's not defined "\g<${e}>"`);return o}function cV({kind:e}){return vV(vB({"^":`line_start`,$:`line_end`,"\\A":`string_start`,"\\b":`word_boundary`,"\\B":`word_boundary`,"\\G":`search_start`,"\\y":`text_segment_boundary`,"\\Y":`text_segment_boundary`,"\\z":`string_end`,"\\Z":`string_end_newline`}[e],`Unexpected assertion kind "${e}"`),{negate:e===X`\B`||e===X`\Y`})}function lV({raw:e},t){let n=/^\\k[<']/.test(e),r=n?e.slice(3,-1):e.slice(1),i=(n,r=!1)=>{let i=t.capturingGroups.length,a=!1;if(n>i)if(t.skipBackrefValidation)a=!0;else throw Error(`Not enough capturing groups defined to the left "${e}"`);return t.hasNumberedRef=!0,yV(r?i+1-n:n,{orphan:a})};if(n){let n=/^(?<sign>-?)0*(?<num>[1-9]\d*)$/.exec(r);if(n)return i(+n.groups.num,!!n.groups.sign);if(/[-+]/.test(r))throw Error(`Invalid backref name "${e}"`);if(!t.namedGroupsByName.has(r))throw Error(`Group name not defined to the left "${e}"`);return yV(r)}return i(+r)}function uV(e,t,n){let{tokens:r,walk:i}=t,a=t.parent,o=a.body.at(-1),s=r[t.nextIndex];if(!n.isCheckingRangeEnd&&o&&o.type!==`CharacterClass`&&o.type!==`CharacterClassRange`&&s&&s.type!==`CharacterClassOpen`&&s.type!==`CharacterClassClose`&&s.type!==`CharacterClassIntersector`){let e=i(a,{...n,isCheckingRangeEnd:!0});if(o.type===`Character`&&e.type===`Character`)return a.body.pop(),CV(o,e);throw Error(`Invalid character class range`)}return xV(hB(`-`))}function dV({negate:e},t,n){let{tokens:r,walk:i}=t,a=r[t.nextIndex],o=[SV()],s=UV(a);for(;s.type!==`CharacterClassClose`;){if(s.type===`CharacterClassIntersector`)o.push(SV()),t.nextIndex++;else{let e=o.at(-1);e.body.push(i(e,n))}s=UV(r[t.nextIndex],a)}let c=SV({negate:e});return o.length===1?c.body=o[0].body:(c.kind=`intersection`,c.body=o.map(e=>e.body.length===1?e.body[0]:e)),t.nextIndex++,c}function fV({kind:e,negate:t,value:n},r){let{normalizeUnknownPropertyNames:i,skipPropertyNameValidation:a,unicodePropertyMap:o}=r;if(e===`property`){let r=HV(n);if(_B.has(r)&&!o?.has(r))e=`posix`,n=r;else return PV(n,{negate:t,normalizeUnknownPropertyNames:i,skipPropertyNameValidation:a,unicodePropertyMap:o})}return e===`posix`?AV(n,{negate:t}):wV(e,{negate:t})}function pV(e,t,n){let{tokens:r,capturingGroups:i,namedGroupsByName:a,skipLookbehindValidation:o,walk:s}=t,c=FV(e),l=c.type===`AbsenceFunction`,u=zV(c),d=u&&c.negate;if(c.type===`CapturingGroup`&&(i.push(c),c.name&&gB(a,c.name,[]).push(c)),l&&n.isInAbsenceFunction)throw Error(`Nested absence function not supported by Oniguruma`);let f=WV(r[t.nextIndex]);for(;f.type!==`GroupClose`;){if(f.type===`Alternator`)c.body.push(_V()),t.nextIndex++;else{let e=c.body.at(-1),t=s(e,{...n,isInAbsenceFunction:n.isInAbsenceFunction||l,isInLookbehind:n.isInLookbehind||u,isInNegLookbehind:n.isInNegLookbehind||d});if(e.body.push(t),(u||n.isInLookbehind)&&!o){let e=`Lookbehind includes a pattern not allowed by Oniguruma`;if(d||n.isInNegLookbehind){if(RV(t)||t.type===`CapturingGroup`)throw Error(e)}else if(RV(t)||zV(t)&&t.negate)throw Error(e)}}f=WV(r[t.nextIndex])}return t.nextIndex++,c}function mV({kind:e,min:t,max:n},r){let i=r.parent,a=i.body.at(-1);if(!a||!aV(a))throw Error(`Quantifier requires a repeatable token`);let o=jV(e,t,n,a);return i.body.pop(),o}function hV({raw:e},t){let{capturingGroups:n,subroutines:r}=t,i=e.slice(3,-1),a=/^(?<sign>[-+]?)0*(?<num>[1-9]\d*)$/.exec(i);if(a){let e=+a.groups.num,r=n.length;if(t.hasNumberedRef=!0,i={"":e,"+":r+e,"-":r+1-e}[a.groups.sign],i<1)throw Error(`Invalid subroutine number`)}else i===`0`&&(i=0);let o=NV(i);return r.push(o),o}function gV(e,t){if(e!==`repeater`)throw Error(`Unexpected absence function kind "${e}"`);return{type:`AbsenceFunction`,kind:e,body:IV(t?.body)}}function _V(e){return{type:`Alternative`,body:LV(e?.body)}}function vV(e,t){let n={type:`Assertion`,kind:e};return(e===`word_boundary`||e===`text_segment_boundary`)&&(n.negate=!!t?.negate),n}function yV(e,t){let n=!!t?.orphan;return{type:`Backreference`,ref:e,...n&&{orphan:n}}}function bV(e,t){let n={name:void 0,isSubroutined:!1,...t};if(n.name!==void 0&&!BV(n.name))throw Error(`Group name "${n.name}" invalid in Oniguruma`);return{type:`CapturingGroup`,number:e,...n.name&&{name:n.name},...n.isSubroutined&&{isSubroutined:n.isSubroutined},body:IV(t?.body)}}function xV(e,t){let n={useLastValid:!1,...t};if(e>1114111){let t=e.toString(16);if(n.useLastValid)e=1114111;else throw Error(e>1310719?`Invalid code point out of range "\\x{${t}}"`:`Invalid code point out of range in JS "\\x{${t}}"`)}return{type:`Character`,value:e}}function SV(e){let t={kind:`union`,negate:!1,...e};return{type:`CharacterClass`,kind:t.kind,negate:t.negate,body:LV(e?.body)}}function CV(e,t){if(t.value<e.value)throw Error(`Character class range out of order`);return{type:`CharacterClassRange`,min:e,max:t}}function wV(e,t){let n=!!t?.negate,r={type:`CharacterSet`,kind:e};return(e===`digit`||e===`hex`||e===`newline`||e===`space`||e===`word`)&&(r.negate=n),(e===`text_segment`||e===`newline`&&!n)&&(r.variableLength=!0),r}function TV(e,t={}){if(e===`keep`)return{type:`Directive`,kind:e};if(e===`flags`)return{type:`Directive`,kind:e,flags:vB(t.flags)};throw Error(`Unexpected directive kind "${e}"`)}function EV(e){return{type:`Flags`,...e}}function DV(e){let t=e?.atomic,n=e?.flags;if(t&&n)throw Error(`Atomic group cannot have flags`);return{type:`Group`,...t&&{atomic:t},...n&&{flags:n},body:IV(e?.body)}}function OV(e){let t={behind:!1,negate:!1,...e};return{type:`LookaroundAssertion`,kind:t.behind?`lookbehind`:`lookahead`,negate:t.negate,body:IV(e?.body)}}function kV(e,t,n){return{type:`NamedCallout`,kind:e,tag:t,arguments:n}}function AV(e,t){let n=!!t?.negate;if(!_B.has(e))throw Error(`Invalid POSIX class "${e}"`);return{type:`CharacterSet`,kind:`posix`,value:e,negate:n}}function jV(e,t,n,r){if(t>n)throw Error(`Invalid reversed quantifier range`);return{type:`Quantifier`,kind:e,min:t,max:n,body:r}}function MV(e,t){return{type:`Regex`,body:IV(t?.body),flags:e}}function NV(e){return{type:`Subroutine`,ref:e}}function PV(e,t){let n={negate:!1,normalizeUnknownPropertyNames:!1,skipPropertyNameValidation:!1,unicodePropertyMap:null,...t},r=n.unicodePropertyMap?.get(HV(e));if(!r){if(n.normalizeUnknownPropertyNames)r=VV(e);else if(n.unicodePropertyMap&&!n.skipPropertyNameValidation)throw Error(X`Invalid Unicode property "\p{${e}}"`)}return{type:`CharacterSet`,kind:`property`,value:r??e,negate:n.negate}}function FV({flags:e,kind:t,name:n,negate:r,number:i}){switch(t){case`absence_repeater`:return gV(`repeater`);case`atomic`:return DV({atomic:!0});case`capturing`:return bV(i,{name:n});case`group`:return DV({flags:e});case`lookahead`:case`lookbehind`:return OV({behind:t===`lookbehind`,negate:r});default:throw Error(`Unexpected group kind "${t}"`)}}function IV(e){if(e===void 0)e=[_V()];else if(!Array.isArray(e)||!e.length||!e.every(e=>e.type===`Alternative`))throw Error(`Invalid body; expected array of one or more Alternative nodes`);return e}function LV(e){if(e===void 0)e=[];else if(!Array.isArray(e)||!e.every(e=>!!e.type))throw Error(`Invalid body; expected array of nodes`);return e}function RV(e){return e.type===`LookaroundAssertion`&&e.kind===`lookahead`}function zV(e){return e.type===`LookaroundAssertion`&&e.kind===`lookbehind`}function BV(e){return/^[\p{Alpha}\p{Pc}][^)]*$/u.test(e)}function VV(e){return e.trim().replace(/[- _]+/g,`_`).replace(/[A-Z][a-z]+(?=[A-Z])/g,`$&_`).replace(/[A-Za-z]+/g,e=>e[0].toUpperCase()+e.slice(1).toLowerCase())}function HV(e){return e.replace(/[- _]+/g,``).toLowerCase()}function UV(e,t){return vB(e,`${t?.type===`Character`&&t.value===93?`Empty`:`Unclosed`} character class`)}function WV(e){return vB(e,`Unclosed group`)}function GV(e,t,n=null){function r(e,t){for(let n=0;n<e.length;n++){let r=i(e[n],t,n,e);n=Math.max(-1,n+r)}}function i(a,o=null,s=null,c=null){let l=0,u=!1,d={node:a,parent:o,key:s,container:c,root:e,remove(){KV(c).splice(Math.max(0,qV(s)+l),1),l--,u=!0},removeAllNextSiblings(){return KV(c).splice(qV(s)+1)},removeAllPrevSiblings(){let e=qV(s)+l;return l-=e,KV(c).splice(0,Math.max(0,e))},replaceWith(e,t={}){let n=!!t.traverse;c?c[Math.max(0,qV(s)+l)]=e:vB(o,`Can't replace root node`)[s]=e,n&&i(e,o,s,c),u=!0},replaceWithMultiple(e,t={}){let n=!!t.traverse;if(KV(c).splice(Math.max(0,qV(s)+l),1,...e),l+=e.length-1,n){let t=0;for(let n=0;n<e.length;n++)t+=i(e[n],o,qV(s)+n+t,c)}u=!0},skip(){u=!0}},{type:f}=a,p=t[`*`],m=t[f],h=typeof p==`function`?p:p?.enter,g=typeof m==`function`?m:m?.enter;if(h?.(d,n),g?.(d,n),!u)switch(f){case`AbsenceFunction`:case`CapturingGroup`:case`Group`:r(a.body,a);break;case`Alternative`:case`CharacterClass`:r(a.body,a);break;case`Assertion`:case`Backreference`:case`Character`:case`CharacterSet`:case`Directive`:case`Flags`:case`NamedCallout`:case`Subroutine`:break;case`CharacterClassRange`:i(a.min,a,`min`),i(a.max,a,`max`);break;case`LookaroundAssertion`:r(a.body,a);break;case`Quantifier`:i(a.body,a,`body`);break;case`Regex`:r(a.body,a),i(a.flags,a,`flags`);break;default:throw Error(`Unexpected node type "${f}"`)}return m?.exit?.(d,n),p?.exit?.(d,n),l}return i(e),e}function KV(e){if(!Array.isArray(e))throw Error(`Container expected`);return e}function qV(e){if(typeof e!=`number`)throw Error(`Numeric key expected`);return e}var JV=String.raw`\(\?(?:[:=!>A-Za-z\-]|<[=!]|\(DEFINE\))`;function YV(e,t){for(let n=0;n<e.length;n++)e[n]>=t&&e[n]++}function XV(e,t,n,r){return e.slice(0,t)+r+e.slice(t+n.length)}var ZV=Object.freeze({DEFAULT:`DEFAULT`,CHAR_CLASS:`CHAR_CLASS`});function QV(e,t,n,r){let i=new RegExp(String.raw`${t}|(?<$skip>\[\^?|\\?.)`,`gsu`),a=[!1],o=0,s=``;for(let t of e.matchAll(i)){let{0:e,groups:{$skip:i}}=t;if(!i&&(!r||r===ZV.DEFAULT==!o)){n instanceof Function?s+=n(t,{context:o?ZV.CHAR_CLASS:ZV.DEFAULT,negated:a[a.length-1]}):s+=n;continue}e[0]===`[`?(o++,a.push(e[1]===`^`)):e===`]`&&o&&(o--,a.pop()),s+=e}return s}function $V(e,t,n,r){QV(e,t,n,r)}function eH(e,t,n=0,r){if(!new RegExp(t,`su`).test(e))return null;let i=RegExp(`${t}|(?<$skip>\\\\?.)`,`gsu`);i.lastIndex=n;let a=0,o;for(;o=i.exec(e);){let{0:e,groups:{$skip:t}}=o;if(!t&&(!r||r===ZV.DEFAULT==!a))return o;e===`[`?a++:e===`]`&&a&&a--,i.lastIndex==o.index&&i.lastIndex++}return null}function tH(e,t,n){return!!eH(e,t,0,n)}function nH(e,t){let n=/\\?./gsu;n.lastIndex=t;let r=e.length,i=0,a=1,o;for(;o=n.exec(e);){let[e]=o;if(e===`[`)i++;else if(i)e===`]`&&i--;else if(e===`(`)a++;else if(e===`)`&&(a--,!a)){r=o.index;break}}return e.slice(t,r)}var rH=new RegExp(String.raw`(?<noncapturingStart>${JV})|(?<capturingStart>\((?:\?<[^>]+>)?)|\\?.`,`gsu`);function iH(e,t){let n=t?.hiddenCaptures??[],r=t?.captureTransfers??new Map;if(!/\(\?>/.test(e))return{pattern:e,captureTransfers:r,hiddenCaptures:n};let i=[0],a=[],o=0,s=0,c=NaN,l;do{l=!1;let t=0,u=0,d=!1,f;for(rH.lastIndex=Number.isNaN(c)?0:c+7;f=rH.exec(e);){let{0:p,index:m,groups:{capturingStart:h,noncapturingStart:g}}=f;if(p===`[`)t++;else if(t)p===`]`&&t--;else if(p===`(?>`&&!d)c=m,d=!0;else if(d&&g)u++;else if(h)d?u++:(o++,i.push(o+s));else if(p===`)`&&d){if(!u){s++;let t=o+s;if(e=`${e.slice(0,c)}(?:(?=(${e.slice(c+3,m)}))<$$${t}>)${e.slice(m+1)}`,l=!0,a.push(t),YV(n,t),r.size){let e=new Map;r.forEach((n,r)=>{e.set(r>=t?r+1:r,n.map(e=>e>=t?e+1:e))}),r=e}break}u--}}}while(l);return n.push(...a),e=QV(e,String.raw`\\(?<backrefNum>[1-9]\d*)|<\$\$(?<wrappedBackrefNum>\d+)>`,({0:e,groups:{backrefNum:t,wrappedBackrefNum:n}})=>{if(t){let n=+t;if(n>i.length-1)throw Error(`Backref "${e}" greater than number of captures`);return`\\${i[n]}`}return`\\${n}`},ZV.DEFAULT),{pattern:e,captureTransfers:r,hiddenCaptures:n}}var aH=String.raw`(?:[?*+]|\{\d+(?:,\d*)?\})`,oH=new RegExp(String.raw`
|
|
75
|
+
`.replace(/\s+/g,``),`gsu`);function TB(e,t={}){let n={flags:``,...t,rules:{captureGroup:!1,singleline:!1,...t.rules}};if(typeof e!=`string`)throw Error(`String expected as pattern`);let r=tV(n.flags),i=[r.extended],a={captureGroup:n.rules.captureGroup,getCurrentModX(){return i.at(-1)},numOpenGroups:0,popModX(){i.pop()},pushModX(e){i.push(e)},replaceCurrentModX(e){i[i.length-1]=e},singleline:n.rules.singleline},o=[],s;for(CB.lastIndex=0;s=CB.exec(e);){let t=EB(a,e,s[0],CB.lastIndex);t.tokens?o.push(...t.tokens):t.token&&o.push(t.token),t.lastIndex!==void 0&&(CB.lastIndex=t.lastIndex)}let c=[],l=0;o.filter(e=>e.type===`GroupOpen`).forEach(e=>{e.kind===`capturing`?e.number=++l:e.raw===`(`&&c.push(e)}),l||c.forEach((e,t)=>{e.kind=`capturing`,e.number=t+1});let u=l||c.length;return{tokens:o.map(e=>e.type===`EscapedNumber`?rV(e,u):e).flat(),flags:r}}function EB(e,t,n,r){let[i,a]=n;if(n===`[`||n===`[^`){let e=DB(t,n,r);return{tokens:e.tokens,lastIndex:e.lastIndex}}if(i===`\\`){if(`AbBGyYzZ`.includes(a))return{token:jB(n,n)};if(/^\\g[<']/.test(n)){if(!/^\\g(?:<[^>]+>|'[^']+')$/.test(n))throw Error(`Invalid group name "${n}"`);return{token:GB(n)}}if(/^\\k[<']/.test(n)){if(!/^\\k(?:<[^>]+>|'[^']+')$/.test(n))throw Error(`Invalid group name "${n}"`);return{token:MB(n)}}if(a===`K`)return{token:zB(`keep`,n)};if(a===`N`||a===`R`)return{token:RB(`newline`,n,{negate:a===`N`})};if(a===`O`)return{token:RB(`any`,n)};if(a===`X`)return{token:RB(`text_segment`,n)};let e=kB(n,{inCharClass:!1});return Array.isArray(e)?{tokens:e}:{token:e}}if(i===`(`){if(a===`*`)return{token:XB(n)};if(n===`(?{`)throw Error(`Unsupported callout "${n}"`);if(n.startsWith(`(?#`)){if(t[r]!==`)`)throw Error(`Unclosed comment group "(?#"`);return{lastIndex:r+1}}if(/^\(\?[-imx]+[:)]$/.test(n))return{token:YB(n,e)};if(e.pushModX(e.getCurrentModX()),e.numOpenGroups++,n===`(`&&!e.captureGroup||n===`(?:`)return{token:HB(`group`,n)};if(n===`(?>`)return{token:HB(`atomic`,n)};if(n===`(?=`||n===`(?!`||n===`(?<=`||n===`(?<!`)return{token:HB(n[2]===`<`?`lookbehind`:`lookahead`,n,{negate:n.endsWith(`!`)})};if(n===`(`&&e.captureGroup||n.startsWith(`(?<`)&&n.endsWith(`>`)||n.startsWith(`(?'`)&&n.endsWith(`'`))return{token:HB(`capturing`,n,{...n!==`(`&&{name:n.slice(3,-1)}})};if(n.startsWith(`(?~`)){if(n===`(?~|`)throw Error(`Unsupported absence function kind "${n}"`);return{token:HB(`absence_repeater`,n)}}throw Error(n===`(?(`?`Unsupported conditional "${n}"`:`Invalid or unsupported group option "${n}"`)}if(n===`)`){if(e.popModX(),e.numOpenGroups--,e.numOpenGroups<0)throw Error(`Unmatched ")"`);return{token:VB(n)}}if(e.getCurrentModX()){if(n===`#`){let e=t.indexOf(`
|
|
76
|
+
`,r);return{lastIndex:e===-1?t.length:e}}if(/^\s$/.test(n)){let e=/\s+/y;return e.lastIndex=r,{lastIndex:e.exec(t)?e.lastIndex:r}}}return n===`.`?{token:RB(`dot`,n)}:n===`^`||n===`$`?{token:jB(e.singleline?{"^":X`\A`,$:X`\Z`}[n]:n,n)}:n===`|`?{token:AB(n)}:SB.test(n)?{tokens:iV(n)}:{token:NB(gB(n),n)}}function DB(e,t,n){let r=[LB(t[1]===`^`,t)],i=1,a;for(wB.lastIndex=n;a=wB.exec(e);){let e=a[0];if(e[0]===`[`&&e[1]!==`:`)i++,r.push(LB(e[1]===`^`,e));else if(e===`]`){if(r.at(-1).type===`CharacterClassOpen`)r.push(NB(93,e));else if(i--,r.push(PB(e)),!i)break}else{let t=OB(e);Array.isArray(t)?r.push(...t):r.push(t)}}return{tokens:r,lastIndex:wB.lastIndex||e.length}}function OB(e){if(e[0]===`\\`)return kB(e,{inCharClass:!0});if(e[0]===`[`){let t=/\[:(?<negate>\^?)(?<name>[a-z]+):\]/.exec(e);if(!t||!vB.has(t.groups.name))throw Error(`Invalid POSIX class "${e}"`);return RB(`posix`,e,{value:t.groups.name,negate:!!t.groups.negate})}return e===`-`?FB(e):e===`&&`?IB(e):NB(gB(e),e)}function kB(e,{inCharClass:t}){let n=e[1];if(n===`c`||n===`C`)return JB(e);if(`dDhHsSwW`.includes(n))return QB(e);if(e.startsWith(X`\o{`))throw Error(`Incomplete, invalid, or unsupported octal code point "${e}"`);if(/^\\[pP]\{/.test(e)){if(e.length===3)throw Error(`Incomplete or invalid Unicode property "${e}"`);return $B(e)}if(/^\\x[89A-Fa-f]\p{AHex}/u.test(e))try{let t=e.split(/\\x/).slice(1).map(e=>parseInt(e,16)),n=new TextDecoder(`utf-8`,{ignoreBOM:!0,fatal:!0}).decode(new Uint8Array(t)),r=new TextEncoder;return[...n].map(e=>{let t=[...r.encode(e)].map(e=>`\\x${e.toString(16)}`).join(``);return NB(gB(e),t)})}catch{throw Error(`Multibyte code "${e}" incomplete or invalid in Oniguruma`)}if(n===`u`||n===`x`)return NB(nV(e),e);if(qB.has(n))return NB(qB.get(n),e);if(/\d/.test(n))return BB(t,e);if(e===`\\`)throw Error(X`Incomplete escape "\"`);if(n===`M`)throw Error(`Unsupported meta "${e}"`);if([...e].length===2)return NB(e.codePointAt(1),e);throw Error(`Unexpected escape "${e}"`)}function AB(e){return{type:`Alternator`,raw:e}}function jB(e,t){return{type:`Assertion`,kind:e,raw:t}}function MB(e){return{type:`Backreference`,raw:e}}function NB(e,t){return{type:`Character`,value:e,raw:t}}function PB(e){return{type:`CharacterClassClose`,raw:e}}function FB(e){return{type:`CharacterClassHyphen`,raw:e}}function IB(e){return{type:`CharacterClassIntersector`,raw:e}}function LB(e,t){return{type:`CharacterClassOpen`,negate:e,raw:t}}function RB(e,t,n={}){return{type:`CharacterSet`,kind:e,...n,raw:t}}function zB(e,t,n={}){return e===`keep`?{type:`Directive`,kind:e,raw:t}:{type:`Directive`,kind:e,flags:yB(n.flags),raw:t}}function BB(e,t){return{type:`EscapedNumber`,inCharClass:e,raw:t}}function VB(e){return{type:`GroupClose`,raw:e}}function HB(e,t,n={}){return{type:`GroupOpen`,kind:e,...n,raw:t}}function UB(e,t,n,r){return{type:`NamedCallout`,kind:e,tag:t,arguments:n,raw:r}}function WB(e,t,n,r){return{type:`Quantifier`,kind:e,min:t,max:n,raw:r}}function GB(e){return{type:`Subroutine`,raw:e}}var KB=new Set([`COUNT`,`CMP`,`ERROR`,`FAIL`,`MAX`,`MISMATCH`,`SKIP`,`TOTAL_COUNT`]),qB=new Map([[`a`,7],[`b`,8],[`e`,27],[`f`,12],[`n`,10],[`r`,13],[`t`,9],[`v`,11]]);function JB(e){let t=e[1]===`c`?e[2]:e[3];if(!t||!/[A-Za-z]/.test(t))throw Error(`Unsupported control character "${e}"`);return NB(gB(t.toUpperCase())-64,e)}function YB(e,t){let{on:n,off:r}=/^\(\?(?<on>[imx]*)(?:-(?<off>[-imx]*))?/.exec(e).groups;r??=``;let i=(t.getCurrentModX()||n.includes(`x`))&&!r.includes(`x`),a=eV(n),o=eV(r),s={};if(a&&(s.enable=a),o&&(s.disable=o),e.endsWith(`)`))return t.replaceCurrentModX(i),zB(`flags`,e,{flags:s});if(e.endsWith(`:`))return t.pushModX(i),t.numOpenGroups++,HB(`group`,e,{...(a||o)&&{flags:s}});throw Error(`Unexpected flag modifier "${e}"`)}function XB(e){let t=/\(\*(?<name>[A-Za-z_]\w*)?(?:\[(?<tag>(?:[A-Za-z_]\w*)?)\])?(?:\{(?<args>[^}]*)\})?\)/.exec(e);if(!t)throw Error(`Incomplete or invalid named callout "${e}"`);let{name:n,tag:r,args:i}=t.groups;if(!n)throw Error(`Invalid named callout "${e}"`);if(r===``)throw Error(`Named callout tag with empty value not allowed "${e}"`);let a=i?i.split(`,`).filter(e=>e!==``).map(e=>/^[+-]?\d+$/.test(e)?+e:e):[],[o,s,c]=a,l=KB.has(n)?n.toLowerCase():`custom`;switch(l){case`fail`:case`mismatch`:case`skip`:if(a.length>0)throw Error(`Named callout arguments not allowed "${a}"`);break;case`error`:if(a.length>1)throw Error(`Named callout allows only one argument "${a}"`);if(typeof o==`string`)throw Error(`Named callout argument must be a number "${o}"`);break;case`max`:if(!a.length||a.length>2)throw Error(`Named callout must have one or two arguments "${a}"`);if(typeof o==`string`&&!/^[A-Za-z_]\w*$/.test(o))throw Error(`Named callout argument one must be a tag or number "${o}"`);if(a.length===2&&(typeof s==`number`||!/^[<>X]$/.test(s)))throw Error(`Named callout optional argument two must be '<', '>', or 'X' "${s}"`);break;case`count`:case`total_count`:if(a.length>1)throw Error(`Named callout allows only one argument "${a}"`);if(a.length===1&&(typeof o==`number`||!/^[<>X]$/.test(o)))throw Error(`Named callout optional argument must be '<', '>', or 'X' "${o}"`);break;case`cmp`:if(a.length!==3)throw Error(`Named callout must have three arguments "${a}"`);if(typeof o==`string`&&!/^[A-Za-z_]\w*$/.test(o))throw Error(`Named callout argument one must be a tag or number "${o}"`);if(typeof s==`number`||!/^(?:[<>!=]=|[<>])$/.test(s))throw Error(`Named callout argument two must be '==', '!=', '>', '<', '>=', or '<=' "${s}"`);if(typeof c==`string`&&!/^[A-Za-z_]\w*$/.test(c))throw Error(`Named callout argument three must be a tag or number "${c}"`);break;case`custom`:throw Error(`Undefined callout name "${n}"`);default:throw Error(`Unexpected named callout kind "${l}"`)}return UB(l,r??null,i?.split(`,`)??null,e)}function ZB(e){let t=null,n,r;if(e[0]===`{`){let{minStr:i,maxStr:a}=/^\{(?<minStr>\d*)(?:,(?<maxStr>\d*))?/.exec(e).groups,o=1e5;if(+i>o||a&&+a>o)throw Error(`Quantifier value unsupported in Oniguruma`);if(n=+i,r=a===void 0?+i:a===``?1/0:+a,n>r&&(t=`possessive`,[n,r]=[r,n]),e.endsWith(`?`)){if(t===`possessive`)throw Error(`Unsupported possessive interval quantifier chain with "?"`);t=`lazy`}else t||=`greedy`}else n=+(e[0]===`+`),r=e[0]===`?`?1:1/0,t=e[1]===`+`?`possessive`:e[1]===`?`?`lazy`:`greedy`;return WB(t,n,r,e)}function QB(e){let t=e[1].toLowerCase();return RB({d:`digit`,h:`hex`,s:`space`,w:`word`}[t],e,{negate:e[1]!==t})}function $B(e){let{p:t,neg:n,value:r}=/^\\(?<p>[pP])\{(?<neg>\^?)(?<value>[^}]+)/.exec(e).groups;return RB(`property`,e,{value:r,negate:t===`P`&&!n||t===`p`&&!!n})}function eV(e){let t={};return e.includes(`i`)&&(t.ignoreCase=!0),e.includes(`m`)&&(t.dotAll=!0),e.includes(`x`)&&(t.extended=!0),Object.keys(t).length?t:null}function tV(e){let t={ignoreCase:!1,dotAll:!1,extended:!1,digitIsAscii:!1,posixIsAscii:!1,spaceIsAscii:!1,wordIsAscii:!1,textSegmentMode:null};for(let n=0;n<e.length;n++){let r=e[n];if(!`imxDPSWy`.includes(r))throw Error(`Invalid flag "${r}"`);if(r===`y`){if(!/^y{[gw]}/.test(e.slice(n)))throw Error(`Invalid or unspecified flag "y" mode`);t.textSegmentMode=e[n+2]===`g`?`grapheme`:`word`,n+=3;continue}t[{i:`ignoreCase`,m:`dotAll`,x:`extended`,D:`digitIsAscii`,P:`posixIsAscii`,S:`spaceIsAscii`,W:`wordIsAscii`}[r]]=!0}return t}function nV(e){if(/^(?:\\u(?!\p{AHex}{4})|\\x(?!\p{AHex}{1,2}|\{\p{AHex}{1,8}\}))/u.test(e))throw Error(`Incomplete or invalid escape "${e}"`);let t=e[2]===`{`?/^\\x\{\s*(?<hex>\p{AHex}+)/u.exec(e).groups.hex:e.slice(2);return parseInt(t,16)}function rV(e,t){let{raw:n,inCharClass:r}=e,i=n.slice(1);if(!r&&(i!==`0`&&i.length===1||i[0]!==`0`&&+i<=t))return[MB(n)];let a=[],o=i.match(/^[0-7]+|\d/g);for(let e=0;e<o.length;e++){let t=o[e],r;if(e===0&&t!==`8`&&t!==`9`){if(r=parseInt(t,8),r>127)throw Error(X`Octal encoded byte above 177 unsupported "${n}"`)}else r=gB(t);a.push(NB(r,(e===0?`\\`:``)+t))}return a}function iV(e){let t=[],n=new RegExp(SB,`gy`),r;for(;r=n.exec(e);){let e=r[0];if(e[0]===`{`){let r=/^\{(?<min>\d+),(?<max>\d+)\}\??$/.exec(e);if(r){let{min:i,max:a}=r.groups;if(+i>+a&&e.endsWith(`?`)){n.lastIndex--,t.push(ZB(e.slice(0,-1)));continue}}}t.push(ZB(e))}return t}function aV(e,t){if(!Array.isArray(e.body))throw Error(`Expected node with body array`);if(e.body.length!==1)return!1;let n=e.body[0];return!t||Object.keys(t).every(e=>t[e]===n[e])}function oV(e){return sV.has(e.type)}var sV=new Set([`AbsenceFunction`,`Backreference`,`CapturingGroup`,`Character`,`CharacterClass`,`CharacterSet`,`Group`,`Quantifier`,`Subroutine`]);function cV(e,t={}){let n={flags:``,normalizeUnknownPropertyNames:!1,skipBackrefValidation:!1,skipLookbehindValidation:!1,skipPropertyNameValidation:!1,unicodePropertyMap:null,...t,rules:{captureGroup:!1,singleline:!1,...t.rules}},r=TB(e,{flags:n.flags,rules:{captureGroup:n.rules.captureGroup,singleline:n.rules.singleline}}),i=(e,t)=>{let n=r.tokens[a.nextIndex];switch(a.parent=e,a.nextIndex++,n.type){case`Alternator`:return vV();case`Assertion`:return lV(n);case`Backreference`:return uV(n,a);case`Character`:return SV(n.value,{useLastValid:!!t.isCheckingRangeEnd});case`CharacterClassHyphen`:return dV(n,a,t);case`CharacterClassOpen`:return fV(n,a,t);case`CharacterSet`:return pV(n,a);case`Directive`:return EV(n.kind,{flags:n.flags});case`GroupOpen`:return mV(n,a,t);case`NamedCallout`:return AV(n.kind,n.tag,n.arguments);case`Quantifier`:return hV(n,a);case`Subroutine`:return gV(n,a);default:throw Error(`Unexpected token type "${n.type}"`)}},a={capturingGroups:[],hasNumberedRef:!1,namedGroupsByName:new Map,nextIndex:0,normalizeUnknownPropertyNames:n.normalizeUnknownPropertyNames,parent:null,skipBackrefValidation:n.skipBackrefValidation,skipLookbehindValidation:n.skipLookbehindValidation,skipPropertyNameValidation:n.skipPropertyNameValidation,subroutines:[],tokens:r.tokens,unicodePropertyMap:n.unicodePropertyMap,walk:i},o=NV(DV(r.flags)),s=o.body[0];for(;a.nextIndex<r.tokens.length;){let e=i(s,{});e.type===`Alternative`?(o.body.push(e),s=e):s.body.push(e)}let{capturingGroups:c,hasNumberedRef:l,namedGroupsByName:u,subroutines:d}=a;if(l&&u.size&&!n.rules.captureGroup)throw Error(`Numbered backref/subroutine not allowed when using named capture`);for(let{ref:e}of d)if(typeof e==`number`){if(e>c.length)throw Error(`Subroutine uses a group number that's not defined`);e&&(c[e-1].isSubroutined=!0)}else if(u.has(e)){if(u.get(e).length>1)throw Error(X`Subroutine uses a duplicate group name "\g<${e}>"`);u.get(e)[0].isSubroutined=!0}else throw Error(X`Subroutine uses a group name that's not defined "\g<${e}>"`);return o}function lV({kind:e}){return yV(yB({"^":`line_start`,$:`line_end`,"\\A":`string_start`,"\\b":`word_boundary`,"\\B":`word_boundary`,"\\G":`search_start`,"\\y":`text_segment_boundary`,"\\Y":`text_segment_boundary`,"\\z":`string_end`,"\\Z":`string_end_newline`}[e],`Unexpected assertion kind "${e}"`),{negate:e===X`\B`||e===X`\Y`})}function uV({raw:e},t){let n=/^\\k[<']/.test(e),r=n?e.slice(3,-1):e.slice(1),i=(n,r=!1)=>{let i=t.capturingGroups.length,a=!1;if(n>i)if(t.skipBackrefValidation)a=!0;else throw Error(`Not enough capturing groups defined to the left "${e}"`);return t.hasNumberedRef=!0,bV(r?i+1-n:n,{orphan:a})};if(n){let n=/^(?<sign>-?)0*(?<num>[1-9]\d*)$/.exec(r);if(n)return i(+n.groups.num,!!n.groups.sign);if(/[-+]/.test(r))throw Error(`Invalid backref name "${e}"`);if(!t.namedGroupsByName.has(r))throw Error(`Group name not defined to the left "${e}"`);return bV(r)}return i(+r)}function dV(e,t,n){let{tokens:r,walk:i}=t,a=t.parent,o=a.body.at(-1),s=r[t.nextIndex];if(!n.isCheckingRangeEnd&&o&&o.type!==`CharacterClass`&&o.type!==`CharacterClassRange`&&s&&s.type!==`CharacterClassOpen`&&s.type!==`CharacterClassClose`&&s.type!==`CharacterClassIntersector`){let e=i(a,{...n,isCheckingRangeEnd:!0});if(o.type===`Character`&&e.type===`Character`)return a.body.pop(),wV(o,e);throw Error(`Invalid character class range`)}return SV(gB(`-`))}function fV({negate:e},t,n){let{tokens:r,walk:i}=t,a=r[t.nextIndex],o=[CV()],s=WV(a);for(;s.type!==`CharacterClassClose`;){if(s.type===`CharacterClassIntersector`)o.push(CV()),t.nextIndex++;else{let e=o.at(-1);e.body.push(i(e,n))}s=WV(r[t.nextIndex],a)}let c=CV({negate:e});return o.length===1?c.body=o[0].body:(c.kind=`intersection`,c.body=o.map(e=>e.body.length===1?e.body[0]:e)),t.nextIndex++,c}function pV({kind:e,negate:t,value:n},r){let{normalizeUnknownPropertyNames:i,skipPropertyNameValidation:a,unicodePropertyMap:o}=r;if(e===`property`){let r=UV(n);if(vB.has(r)&&!o?.has(r))e=`posix`,n=r;else return FV(n,{negate:t,normalizeUnknownPropertyNames:i,skipPropertyNameValidation:a,unicodePropertyMap:o})}return e===`posix`?jV(n,{negate:t}):TV(e,{negate:t})}function mV(e,t,n){let{tokens:r,capturingGroups:i,namedGroupsByName:a,skipLookbehindValidation:o,walk:s}=t,c=IV(e),l=c.type===`AbsenceFunction`,u=BV(c),d=u&&c.negate;if(c.type===`CapturingGroup`&&(i.push(c),c.name&&_B(a,c.name,[]).push(c)),l&&n.isInAbsenceFunction)throw Error(`Nested absence function not supported by Oniguruma`);let f=GV(r[t.nextIndex]);for(;f.type!==`GroupClose`;){if(f.type===`Alternator`)c.body.push(vV()),t.nextIndex++;else{let e=c.body.at(-1),t=s(e,{...n,isInAbsenceFunction:n.isInAbsenceFunction||l,isInLookbehind:n.isInLookbehind||u,isInNegLookbehind:n.isInNegLookbehind||d});if(e.body.push(t),(u||n.isInLookbehind)&&!o){let e=`Lookbehind includes a pattern not allowed by Oniguruma`;if(d||n.isInNegLookbehind){if(zV(t)||t.type===`CapturingGroup`)throw Error(e)}else if(zV(t)||BV(t)&&t.negate)throw Error(e)}}f=GV(r[t.nextIndex])}return t.nextIndex++,c}function hV({kind:e,min:t,max:n},r){let i=r.parent,a=i.body.at(-1);if(!a||!oV(a))throw Error(`Quantifier requires a repeatable token`);let o=MV(e,t,n,a);return i.body.pop(),o}function gV({raw:e},t){let{capturingGroups:n,subroutines:r}=t,i=e.slice(3,-1),a=/^(?<sign>[-+]?)0*(?<num>[1-9]\d*)$/.exec(i);if(a){let e=+a.groups.num,r=n.length;if(t.hasNumberedRef=!0,i={"":e,"+":r+e,"-":r+1-e}[a.groups.sign],i<1)throw Error(`Invalid subroutine number`)}else i===`0`&&(i=0);let o=PV(i);return r.push(o),o}function _V(e,t){if(e!==`repeater`)throw Error(`Unexpected absence function kind "${e}"`);return{type:`AbsenceFunction`,kind:e,body:LV(t?.body)}}function vV(e){return{type:`Alternative`,body:RV(e?.body)}}function yV(e,t){let n={type:`Assertion`,kind:e};return(e===`word_boundary`||e===`text_segment_boundary`)&&(n.negate=!!t?.negate),n}function bV(e,t){let n=!!t?.orphan;return{type:`Backreference`,ref:e,...n&&{orphan:n}}}function xV(e,t){let n={name:void 0,isSubroutined:!1,...t};if(n.name!==void 0&&!VV(n.name))throw Error(`Group name "${n.name}" invalid in Oniguruma`);return{type:`CapturingGroup`,number:e,...n.name&&{name:n.name},...n.isSubroutined&&{isSubroutined:n.isSubroutined},body:LV(t?.body)}}function SV(e,t){let n={useLastValid:!1,...t};if(e>1114111){let t=e.toString(16);if(n.useLastValid)e=1114111;else throw Error(e>1310719?`Invalid code point out of range "\\x{${t}}"`:`Invalid code point out of range in JS "\\x{${t}}"`)}return{type:`Character`,value:e}}function CV(e){let t={kind:`union`,negate:!1,...e};return{type:`CharacterClass`,kind:t.kind,negate:t.negate,body:RV(e?.body)}}function wV(e,t){if(t.value<e.value)throw Error(`Character class range out of order`);return{type:`CharacterClassRange`,min:e,max:t}}function TV(e,t){let n=!!t?.negate,r={type:`CharacterSet`,kind:e};return(e===`digit`||e===`hex`||e===`newline`||e===`space`||e===`word`)&&(r.negate=n),(e===`text_segment`||e===`newline`&&!n)&&(r.variableLength=!0),r}function EV(e,t={}){if(e===`keep`)return{type:`Directive`,kind:e};if(e===`flags`)return{type:`Directive`,kind:e,flags:yB(t.flags)};throw Error(`Unexpected directive kind "${e}"`)}function DV(e){return{type:`Flags`,...e}}function OV(e){let t=e?.atomic,n=e?.flags;if(t&&n)throw Error(`Atomic group cannot have flags`);return{type:`Group`,...t&&{atomic:t},...n&&{flags:n},body:LV(e?.body)}}function kV(e){let t={behind:!1,negate:!1,...e};return{type:`LookaroundAssertion`,kind:t.behind?`lookbehind`:`lookahead`,negate:t.negate,body:LV(e?.body)}}function AV(e,t,n){return{type:`NamedCallout`,kind:e,tag:t,arguments:n}}function jV(e,t){let n=!!t?.negate;if(!vB.has(e))throw Error(`Invalid POSIX class "${e}"`);return{type:`CharacterSet`,kind:`posix`,value:e,negate:n}}function MV(e,t,n,r){if(t>n)throw Error(`Invalid reversed quantifier range`);return{type:`Quantifier`,kind:e,min:t,max:n,body:r}}function NV(e,t){return{type:`Regex`,body:LV(t?.body),flags:e}}function PV(e){return{type:`Subroutine`,ref:e}}function FV(e,t){let n={negate:!1,normalizeUnknownPropertyNames:!1,skipPropertyNameValidation:!1,unicodePropertyMap:null,...t},r=n.unicodePropertyMap?.get(UV(e));if(!r){if(n.normalizeUnknownPropertyNames)r=HV(e);else if(n.unicodePropertyMap&&!n.skipPropertyNameValidation)throw Error(X`Invalid Unicode property "\p{${e}}"`)}return{type:`CharacterSet`,kind:`property`,value:r??e,negate:n.negate}}function IV({flags:e,kind:t,name:n,negate:r,number:i}){switch(t){case`absence_repeater`:return _V(`repeater`);case`atomic`:return OV({atomic:!0});case`capturing`:return xV(i,{name:n});case`group`:return OV({flags:e});case`lookahead`:case`lookbehind`:return kV({behind:t===`lookbehind`,negate:r});default:throw Error(`Unexpected group kind "${t}"`)}}function LV(e){if(e===void 0)e=[vV()];else if(!Array.isArray(e)||!e.length||!e.every(e=>e.type===`Alternative`))throw Error(`Invalid body; expected array of one or more Alternative nodes`);return e}function RV(e){if(e===void 0)e=[];else if(!Array.isArray(e)||!e.every(e=>!!e.type))throw Error(`Invalid body; expected array of nodes`);return e}function zV(e){return e.type===`LookaroundAssertion`&&e.kind===`lookahead`}function BV(e){return e.type===`LookaroundAssertion`&&e.kind===`lookbehind`}function VV(e){return/^[\p{Alpha}\p{Pc}][^)]*$/u.test(e)}function HV(e){return e.trim().replace(/[- _]+/g,`_`).replace(/[A-Z][a-z]+(?=[A-Z])/g,`$&_`).replace(/[A-Za-z]+/g,e=>e[0].toUpperCase()+e.slice(1).toLowerCase())}function UV(e){return e.replace(/[- _]+/g,``).toLowerCase()}function WV(e,t){return yB(e,`${t?.type===`Character`&&t.value===93?`Empty`:`Unclosed`} character class`)}function GV(e){return yB(e,`Unclosed group`)}function KV(e,t,n=null){function r(e,t){for(let n=0;n<e.length;n++){let r=i(e[n],t,n,e);n=Math.max(-1,n+r)}}function i(a,o=null,s=null,c=null){let l=0,u=!1,d={node:a,parent:o,key:s,container:c,root:e,remove(){qV(c).splice(Math.max(0,JV(s)+l),1),l--,u=!0},removeAllNextSiblings(){return qV(c).splice(JV(s)+1)},removeAllPrevSiblings(){let e=JV(s)+l;return l-=e,qV(c).splice(0,Math.max(0,e))},replaceWith(e,t={}){let n=!!t.traverse;c?c[Math.max(0,JV(s)+l)]=e:yB(o,`Can't replace root node`)[s]=e,n&&i(e,o,s,c),u=!0},replaceWithMultiple(e,t={}){let n=!!t.traverse;if(qV(c).splice(Math.max(0,JV(s)+l),1,...e),l+=e.length-1,n){let t=0;for(let n=0;n<e.length;n++)t+=i(e[n],o,JV(s)+n+t,c)}u=!0},skip(){u=!0}},{type:f}=a,p=t[`*`],m=t[f],h=typeof p==`function`?p:p?.enter,g=typeof m==`function`?m:m?.enter;if(h?.(d,n),g?.(d,n),!u)switch(f){case`AbsenceFunction`:case`CapturingGroup`:case`Group`:r(a.body,a);break;case`Alternative`:case`CharacterClass`:r(a.body,a);break;case`Assertion`:case`Backreference`:case`Character`:case`CharacterSet`:case`Directive`:case`Flags`:case`NamedCallout`:case`Subroutine`:break;case`CharacterClassRange`:i(a.min,a,`min`),i(a.max,a,`max`);break;case`LookaroundAssertion`:r(a.body,a);break;case`Quantifier`:i(a.body,a,`body`);break;case`Regex`:r(a.body,a),i(a.flags,a,`flags`);break;default:throw Error(`Unexpected node type "${f}"`)}return m?.exit?.(d,n),p?.exit?.(d,n),l}return i(e),e}function qV(e){if(!Array.isArray(e))throw Error(`Container expected`);return e}function JV(e){if(typeof e!=`number`)throw Error(`Numeric key expected`);return e}var YV=String.raw`\(\?(?:[:=!>A-Za-z\-]|<[=!]|\(DEFINE\))`;function XV(e,t){for(let n=0;n<e.length;n++)e[n]>=t&&e[n]++}function ZV(e,t,n,r){return e.slice(0,t)+r+e.slice(t+n.length)}var QV=Object.freeze({DEFAULT:`DEFAULT`,CHAR_CLASS:`CHAR_CLASS`});function $V(e,t,n,r){let i=new RegExp(String.raw`${t}|(?<$skip>\[\^?|\\?.)`,`gsu`),a=[!1],o=0,s=``;for(let t of e.matchAll(i)){let{0:e,groups:{$skip:i}}=t;if(!i&&(!r||r===QV.DEFAULT==!o)){n instanceof Function?s+=n(t,{context:o?QV.CHAR_CLASS:QV.DEFAULT,negated:a[a.length-1]}):s+=n;continue}e[0]===`[`?(o++,a.push(e[1]===`^`)):e===`]`&&o&&(o--,a.pop()),s+=e}return s}function eH(e,t,n,r){$V(e,t,n,r)}function tH(e,t,n=0,r){if(!new RegExp(t,`su`).test(e))return null;let i=RegExp(`${t}|(?<$skip>\\\\?.)`,`gsu`);i.lastIndex=n;let a=0,o;for(;o=i.exec(e);){let{0:e,groups:{$skip:t}}=o;if(!t&&(!r||r===QV.DEFAULT==!a))return o;e===`[`?a++:e===`]`&&a&&a--,i.lastIndex==o.index&&i.lastIndex++}return null}function nH(e,t,n){return!!tH(e,t,0,n)}function rH(e,t){let n=/\\?./gsu;n.lastIndex=t;let r=e.length,i=0,a=1,o;for(;o=n.exec(e);){let[e]=o;if(e===`[`)i++;else if(i)e===`]`&&i--;else if(e===`(`)a++;else if(e===`)`&&(a--,!a)){r=o.index;break}}return e.slice(t,r)}var iH=new RegExp(String.raw`(?<noncapturingStart>${YV})|(?<capturingStart>\((?:\?<[^>]+>)?)|\\?.`,`gsu`);function aH(e,t){let n=t?.hiddenCaptures??[],r=t?.captureTransfers??new Map;if(!/\(\?>/.test(e))return{pattern:e,captureTransfers:r,hiddenCaptures:n};let i=[0],a=[],o=0,s=0,c=NaN,l;do{l=!1;let t=0,u=0,d=!1,f;for(iH.lastIndex=Number.isNaN(c)?0:c+7;f=iH.exec(e);){let{0:p,index:m,groups:{capturingStart:h,noncapturingStart:g}}=f;if(p===`[`)t++;else if(t)p===`]`&&t--;else if(p===`(?>`&&!d)c=m,d=!0;else if(d&&g)u++;else if(h)d?u++:(o++,i.push(o+s));else if(p===`)`&&d){if(!u){s++;let t=o+s;if(e=`${e.slice(0,c)}(?:(?=(${e.slice(c+3,m)}))<$$${t}>)${e.slice(m+1)}`,l=!0,a.push(t),XV(n,t),r.size){let e=new Map;r.forEach((n,r)=>{e.set(r>=t?r+1:r,n.map(e=>e>=t?e+1:e))}),r=e}break}u--}}}while(l);return n.push(...a),e=$V(e,String.raw`\\(?<backrefNum>[1-9]\d*)|<\$\$(?<wrappedBackrefNum>\d+)>`,({0:e,groups:{backrefNum:t,wrappedBackrefNum:n}})=>{if(t){let n=+t;if(n>i.length-1)throw Error(`Backref "${e}" greater than number of captures`);return`\\${i[n]}`}return`\\${n}`},QV.DEFAULT),{pattern:e,captureTransfers:r,hiddenCaptures:n}}var oH=String.raw`(?:[?*+]|\{\d+(?:,\d*)?\})`,sH=new RegExp(String.raw`
|
|
77
77
|
\\(?: \d+
|
|
78
78
|
| c[A-Za-z]
|
|
79
79
|
| [gk]<[^>]+>
|
|
@@ -86,9 +86,9 @@ import{n as e,r as t,t as n}from"./rolldown-runtime-hePW80VL.js";import{$ as r,$
|
|
|
86
86
|
| [A-Za-z\-]+:
|
|
87
87
|
| \(DEFINE\)
|
|
88
88
|
))?
|
|
89
|
-
| (?<qBase>${
|
|
89
|
+
| (?<qBase>${oH})(?<qMod>[?+]?)(?<invalidQ>[?*+\{]?)
|
|
90
90
|
| \\?.
|
|
91
|
-
`.replace(/\s+/g,``),`gsu`);function
|
|
91
|
+
`.replace(/\s+/g,``),`gsu`);function cH(e){if(!RegExp(`${oH}\\+`).test(e))return{pattern:e};let t=[],n=null,r=null,i=``,a=0,o;for(sH.lastIndex=0;o=sH.exec(e);){let{0:s,index:c,groups:{qBase:l,qMod:u,invalidQ:d}}=o;if(s===`[`)a||(r=c),a++;else if(s===`]`)a?a--:r=null;else if(!a)if(u===`+`&&i&&!i.startsWith(`(`)){if(d)throw Error(`Invalid quantifier "${s}"`);let t=-1;if(/^\{\d+\}$/.test(l))e=ZV(e,c+l.length,u,``);else{if(i===`)`||i===`]`){let t=i===`)`?n:r;if(t===null)throw Error(`Invalid unmatched "${i}"`);e=`${e.slice(0,t)}(?>${e.slice(t,c)}${l})${e.slice(c+s.length)}`}else e=`${e.slice(0,c-i.length)}(?>${i}${l})${e.slice(c+s.length)}`;t+=4}sH.lastIndex+=t}else s[0]===`(`?t.push(c):s===`)`&&(n=t.length?t.pop():null);i=s}return{pattern:e}}var lH=String.raw,uH=lH`\(\?R=(?<rDepth>[^\)]+)\)|${lH`\\g<(?<gRNameOrNum>[^>&]+)&R=(?<gRDepth>[^>]+)>`}`,dH=lH`\(\?<(?![=!])(?<captureName>[^>]+)>`,fH=lH`${dH}|(?<unnamed>\()(?!\?)`,pH=new RegExp(lH`${dH}|${uH}|\(\?|\\?.`,`gsu`),mH=`Cannot use multiple overlapping recursions`;function hH(e,t){let{hiddenCaptures:n,mode:r}={hiddenCaptures:[],mode:`plugin`,...t},i=t?.captureTransfers??new Map;if(!new RegExp(uH,`su`).test(e))return{pattern:e,captureTransfers:i,hiddenCaptures:n};if(r===`plugin`&&nH(e,lH`\(\?\(DEFINE\)`,QV.DEFAULT))throw Error(`DEFINE groups cannot be used with recursion`);let a=[],o=nH(e,lH`\\[1-9]`,QV.DEFAULT),s=new Map,c=[],l=!1,u=0,d=0,f;for(pH.lastIndex=0;f=pH.exec(e);){let{0:t,groups:{captureName:p,rDepth:m,gRNameOrNum:h,gRDepth:g}}=f;if(t===`[`)u++;else if(u)t===`]`&&u--;else{if(m){if(gH(m),l)throw Error(mH);if(o)throw Error(`${r===`external`?`Backrefs`:`Numbered backrefs`} cannot be used with global recursion`);let t=e.slice(0,f.index),s=e.slice(pH.lastIndex);if(nH(s,uH,QV.DEFAULT))throw Error(mH);let c=m-1;e=_H(t,s,c,!1,n,a,d),i=bH(i,t,c,a.length,0,d);break}if(h){gH(g);let u=!1;for(let e of c)if(e.name===h||e.num===+h){if(u=!0,e.hasRecursedWithin)throw Error(mH);break}if(!u)throw Error(lH`Recursive \g cannot be used outside the referenced group "${r===`external`?h:lH`\g<${h}&R=${g}>`}"`);let p=s.get(h),m=rH(e,p);if(o&&nH(m,lH`${dH}|\((?!\?)`,QV.DEFAULT))throw Error(`${r===`external`?`Backrefs`:`Numbered backrefs`} cannot be used with recursion of capturing groups`);let _=e.slice(p,f.index),v=m.slice(_.length+t.length),y=a.length,b=g-1,x=_H(_,v,b,!0,n,a,d);i=bH(i,_,b,a.length-y,y,d),e=`${e.slice(0,p)}${x}${e.slice(p+m.length)}`,pH.lastIndex+=x.length-t.length-_.length-v.length,c.forEach(e=>e.hasRecursedWithin=!0),l=!0}else if(p)d++,s.set(String(d),pH.lastIndex),s.set(p,pH.lastIndex),c.push({num:d,name:p});else if(t[0]===`(`){let e=t===`(`;e&&(d++,s.set(String(d),pH.lastIndex)),c.push(e?{num:d}:{})}else t===`)`&&c.pop()}}return n.push(...a),{pattern:e,captureTransfers:i,hiddenCaptures:n}}function gH(e){let t=`Max depth must be integer between 2 and 100; used ${e}`;if(!/^[1-9]\d*$/.test(e)||(e=+e,e<2||e>100))throw Error(t)}function _H(e,t,n,r,i,a,o){let s=new Set;r&&eH(e+t,dH,({groups:{captureName:e}})=>{s.add(e)},QV.DEFAULT);let c=[n,r?s:null,i,a,o];return`${e}${vH(`(?:${e}`,`forward`,...c)}(?:)${vH(`${t})`,`backward`,...c)}${t}`}function vH(e,t,n,r,i,a,o){let s=e=>t===`forward`?e+2:n-e+2-1,c=``;for(let t=0;t<n;t++){let n=s(t);c+=$V(e,lH`${fH}|\\k<(?<backref>[^>]+)>`,({0:e,groups:{captureName:t,unnamed:s,backref:c}})=>{if(c&&r&&!r.has(c))return e;let l=`_$${n}`;if(s||t){let n=o+a.length+1;return a.push(n),yH(i,n),s?e:`(?<${t}${l}>`}return lH`\k<${c}${l}>`},QV.DEFAULT)}return c}function yH(e,t){for(let n=0;n<e.length;n++)e[n]>=t&&e[n]++}function bH(e,t,n,r,i,a){if(e.size&&r){let o=0;eH(t,fH,()=>o++,QV.DEFAULT);let s=a-o+i,c=new Map;return e.forEach((e,t)=>{let i=(r-o*n)/n,a=o*n,l=t>s+o?t+r:t,u=[];for(let t of e)if(t<=s)u.push(t);else if(t>s+o+i)u.push(t+r);else if(t<=s+o)for(let e=0;e<=n;e++)u.push(t+o*e);else for(let e=0;e<=n;e++)u.push(t+a+i*e);c.set(l,u)}),c}return e}var Z=String.fromCodePoint,Q=String.raw,xH={},SH=globalThis.RegExp;xH.flagGroups=(()=>{try{new SH(`(?i:)`)}catch{return!1}return!0})(),xH.unicodeSets=(()=>{try{new SH(`[[]]`,`v`)}catch{return!1}return!0})(),xH.bugFlagVLiteralHyphenIsRange=xH.unicodeSets?(()=>{try{new SH(Q`[\d\-a]`,`v`)}catch{return!0}return!1})():!1,xH.bugNestedClassIgnoresNegation=xH.unicodeSets&&new SH(`[[^a]]`,`v`).test(`a`);function CH(e,{enable:t,disable:n}){return{dotAll:!n?.dotAll&&!!(t?.dotAll||e.dotAll),ignoreCase:!n?.ignoreCase&&!!(t?.ignoreCase||e.ignoreCase)}}function wH(e,t,n){return e.has(t)||e.set(t,n),e.get(t)}function TH(e,t){return DH[e]>=DH[t]}function EH(e,t){if(e==null)throw Error(t??`Value expected`);return e}var DH={ES2025:2025,ES2024:2024,ES2018:2018},OH={auto:`auto`,ES2025:`ES2025`,ES2024:`ES2024`,ES2018:`ES2018`};function kH(e={}){if({}.toString.call(e)!==`[object Object]`)throw Error(`Unexpected options`);if(e.target!==void 0&&!OH[e.target])throw Error(`Unexpected target "${e.target}"`);let t={accuracy:`default`,avoidSubclass:!1,flags:``,global:!1,hasIndices:!1,lazyCompileLength:1/0,target:`auto`,verbose:!1,...e,rules:{allowOrphanBackrefs:!1,asciiWordBoundaries:!1,captureGroup:!1,recursionLimit:20,singleline:!1,...e.rules}};return t.target===`auto`&&(t.target=xH.flagGroups?`ES2025`:xH.unicodeSets?`ES2024`:`ES2018`),t}var AH=`[ -\r ]`,jH=new Set([Z(304),Z(305)]),MH=Q`[\p{L}\p{M}\p{N}\p{Pc}]`;function NH(e){if(jH.has(e))return[e];let t=new Set,n=e.toLowerCase(),r=n.toUpperCase(),i=LH.get(n),a=FH.get(n),o=IH.get(n);return[...r].length===1&&t.add(r),o&&t.add(o),i&&t.add(i),t.add(n),a&&t.add(a),[...t]}var PH=new Map(`C Other
|
|
92
92
|
Cc Control cntrl
|
|
93
93
|
Cf Format
|
|
94
94
|
Cn Unassigned
|
|
@@ -178,18 +178,18 @@ Uppercase Upper
|
|
|
178
178
|
Variation_Selector VS
|
|
179
179
|
White_Space space
|
|
180
180
|
XID_Continue XIDC
|
|
181
|
-
XID_Start XIDS`.split(/\s/).map(e=>[
|
|
181
|
+
XID_Start XIDS`.split(/\s/).map(e=>[UV(e),e])),FH=new Map([[`s`,Z(383)],[Z(383),`s`]]),IH=new Map([[Z(223),Z(7838)],[Z(107),Z(8490)],[Z(229),Z(8491)],[Z(969),Z(8486)]]),LH=new Map([BH(453),BH(456),BH(459),BH(498),...VH(8072,8079),...VH(8088,8095),...VH(8104,8111),BH(8124),BH(8140),BH(8188)]),RH=new Map([[`alnum`,Q`[\p{Alpha}\p{Nd}]`],[`alpha`,Q`\p{Alpha}`],[`ascii`,Q`\p{ASCII}`],[`blank`,Q`[\p{Zs}\t]`],[`cntrl`,Q`\p{Cc}`],[`digit`,Q`\p{Nd}`],[`graph`,Q`[\P{space}&&\P{Cc}&&\P{Cn}&&\P{Cs}]`],[`lower`,Q`\p{Lower}`],[`print`,Q`[[\P{space}&&\P{Cc}&&\P{Cn}&&\P{Cs}]\p{Zs}]`],[`punct`,Q`[\p{P}\p{S}]`],[`space`,Q`\p{space}`],[`upper`,Q`\p{Upper}`],[`word`,Q`[\p{Alpha}\p{M}\p{Nd}\p{Pc}]`],[`xdigit`,Q`\p{AHex}`]]);function zH(e,t){let n=[];for(let r=e;r<=t;r++)n.push(r);return n}function BH(e){let t=Z(e);return[t.toLowerCase(),t]}function VH(e,t){return zH(e,t).map(e=>BH(e))}var HH=new Set([`Lower`,`Lowercase`,`Upper`,`Uppercase`,`Ll`,`Lowercase_Letter`,`Lt`,`Titlecase_Letter`,`Lu`,`Uppercase_Letter`]);function UH(e,t){let n={accuracy:`default`,asciiWordBoundaries:!1,avoidSubclass:!1,bestEffortTarget:`ES2025`,...t};qH(e);let r={accuracy:n.accuracy,asciiWordBoundaries:n.asciiWordBoundaries,avoidSubclass:n.avoidSubclass,flagDirectivesByAlt:new Map,jsGroupNameMap:new Map,minTargetEs2024:TH(n.bestEffortTarget,`ES2024`),passedLookbehind:!1,strategy:null,subroutineRefMap:new Map,supportedGNodes:new Set,digitIsAscii:e.flags.digitIsAscii,spaceIsAscii:e.flags.spaceIsAscii,wordIsAscii:e.flags.wordIsAscii};KV(e,WH,r);let i={dotAll:e.flags.dotAll,ignoreCase:e.flags.ignoreCase},a={currentFlags:i,prevFlags:null,globalFlags:i,groupOriginByCopy:new Map,groupsByName:new Map,multiplexCapturesToLeftByRef:new Map,openRefs:new Map,reffedNodesByReferencer:new Map,subroutineRefMap:r.subroutineRefMap};return KV(e,GH,a),KV(e,KH,{groupsByName:a.groupsByName,highestOrphanBackref:0,numCapturesToLeft:0,reffedNodesByReferencer:a.reffedNodesByReferencer}),e._originMap=a.groupOriginByCopy,e._strategy=r.strategy,e}var WH={AbsenceFunction({node:e,parent:t,replaceWith:n}){let{body:r,kind:i}=e;if(i===`repeater`){let e=OV();e.body[0].body.push(kV({negate:!0,body:r}),FV(`Any`));let i=OV();i.body[0].body.push(MV(`greedy`,0,1/0,e)),n($(i,t),{traverse:!0})}else throw Error(`Unsupported absence function "(?~|"`)},Alternative:{enter({node:e,parent:t,key:n},{flagDirectivesByAlt:r}){let i=e.body.filter(e=>e.kind===`flags`);for(let e=n+1;e<t.body.length;e++){let n=t.body[e];wH(r,n,[]).push(...i)}},exit({node:e},{flagDirectivesByAlt:t}){if(t.get(e)?.length){let n=eU(t.get(e));if(n){let t=OV({flags:n});t.body[0].body=e.body,e.body=[$(t,e)]}}}},Assertion({node:e,parent:t,key:n,container:r,root:i,remove:a,replaceWith:o},s){let{kind:c,negate:l}=e,{asciiWordBoundaries:u,avoidSubclass:d,supportedGNodes:f,wordIsAscii:p}=s;if(c===`text_segment_boundary`)throw Error(`Unsupported text segment boundary "\\${l?`Y`:`y`}"`);if(c===`line_end`)o($(kV({body:[vV({body:[yV(`string_end`)]}),vV({body:[SV(10)]})]}),t));else if(c===`line_start`)o($(lU(Q`(?<=\A|\n(?!\z))`,{skipLookbehindValidation:!0}),t));else if(c===`search_start`)if(f.has(e))i.flags.sticky=!0,a();else{let e=r[n-1];if(e&&oU(e))o($(kV({negate:!0}),t));else if(d)throw Error(Q`Uses "\G" in a way that requires a subclass`);else o(dU(yV(`string_start`),t)),s.strategy=`clip_search`}else if(c!==`string_end`&&c!==`string_start`)if(c===`string_end_newline`)o($(lU(Q`(?=\n?\z)`),t));else if(c===`word_boundary`){if(!p&&!u){let e=`(?:(?<=${MH})(?!${MH})|(?<!${MH})(?=${MH}))`,n=`(?:(?<=${MH})(?=${MH})|(?<!${MH})(?!${MH}))`;o($(lU(l?n:e),t))}}else throw Error(`Unexpected assertion kind "${c}"`)},Backreference({node:e},{jsGroupNameMap:t}){let{ref:n}=e;typeof n==`string`&&!cU(n)&&(n=$H(n,t),e.ref=n)},CapturingGroup({node:e},{jsGroupNameMap:t,subroutineRefMap:n}){let{name:r}=e;r&&!cU(r)&&(r=$H(r,t),e.name=r),n.set(e.number,e),r&&n.set(r,e)},CharacterClassRange({node:e,parent:t,replaceWith:n}){t.kind===`intersection`&&n($(CV({body:[e]}),t),{traverse:!0})},CharacterSet({node:e,parent:t,replaceWith:n},{accuracy:r,minTargetEs2024:i,digitIsAscii:a,spaceIsAscii:o,wordIsAscii:s}){let{kind:c,negate:l,value:u}=e;if(a&&(c===`digit`||u===`digit`)){n(dU(TV(`digit`,{negate:l}),t));return}if(o&&(c===`space`||u===`space`)){n($(uU(lU(AH),l),t));return}if(s&&(c===`word`||u===`word`)){n(dU(TV(`word`,{negate:l}),t));return}if(c===`any`)n(dU(FV(`Any`),t));else if(c===`digit`)n(dU(FV(`Nd`,{negate:l}),t));else if(c!==`dot`)if(c===`text_segment`){if(r===`strict`)throw Error(Q`Use of "\X" requires non-strict accuracy`);let e=`\\p{Emoji}(?:\\p{EMod}|\\uFE0F\\u20E3?|[\\x{E0020}-\\x{E007E}]+\\x{E007F})?`,a=Q`\p{RI}{2}|${e}(?:\u200D${e})*`;n($(lU(Q`(?>\r\n|${i?Q`\p{RGI_Emoji}`:a}|\P{M}\p{M}*)`,{skipPropertyNameValidation:!0}),t))}else if(c===`hex`)n(dU(FV(`AHex`,{negate:l}),t));else if(c===`newline`)n($(lU(l?`[^
|
|
182
182
|
]`:`(?>\r
|
|
183
183
|
?|[
|
|
184
|
-
\v\f
\u2028\u2029])`),t));else if(c===`posix`)if(!i&&(u===`graph`||u===`print`)){if(r===`strict`)throw Error(`POSIX class "${u}" requires min target ES2024 or non-strict accuracy`);let e={graph:`!-~`,print:` -~`}[u];l&&(e=`\0-${Z(e.codePointAt(0)-1)}${Z(e.codePointAt(2)+1)}-\u{10FFFF}`),n($(cU(`[${e}]`),t))}else n($(lU(cU(LH.get(u)),l),t));else if(c===`property`)NH.has(HV(u))||(e.key=`sc`);else if(c===`space`)n(uU(PV(`space`,{negate:l}),t));else if(c===`word`)n($(lU(cU(jH),l),t));else throw Error(`Unexpected character set kind "${c}"`)},Directive({node:e,parent:t,root:n,remove:r,replaceWith:i,removeAllPrevSiblings:a,removeAllNextSiblings:o}){let{kind:s,flags:c}=e;if(s===`flags`)if(!c.enable&&!c.disable)r();else{let e=DV({flags:c});e.body[0].body=o(),i($(e,t),{traverse:!0})}else if(s===`keep`){let e=n.body[0],r=n.body.length===1&&iV(e,{type:`Group`})&&e.body[0].body.length===1?e.body[0]:n;if(t.parent!==r||r.body.length>1)throw Error(Q`Uses "\K" in a way that's unsupported`);let o=OV({behind:!0});o.body[0].body=a(),i($(o,t))}else throw Error(`Unexpected directive kind "${s}"`)},Flags({node:e,parent:t}){if(e.posixIsAscii)throw Error(`Unsupported flag "P"`);if(e.textSegmentMode===`word`)throw Error(`Unsupported flag "y{w}"`);[`digitIsAscii`,`extended`,`posixIsAscii`,`spaceIsAscii`,`wordIsAscii`,`textSegmentMode`].forEach(t=>delete e[t]),Object.assign(e,{global:!1,hasIndices:!1,multiline:!1,sticky:e.sticky??!1}),t.options={disable:{x:!0,n:!0},force:{v:!0}}},Group({node:e}){if(!e.flags)return;let{enable:t,disable:n}=e.flags;t?.extended&&delete t.extended,n?.extended&&delete n.extended,t?.dotAll&&n?.dotAll&&delete t.dotAll,t?.ignoreCase&&n?.ignoreCase&&delete t.ignoreCase,t&&!Object.keys(t).length&&delete e.flags.enable,n&&!Object.keys(n).length&&delete e.flags.disable,!e.flags.enable&&!e.flags.disable&&delete e.flags},LookaroundAssertion({node:e},t){let{kind:n}=e;n===`lookbehind`&&(t.passedLookbehind=!0)},NamedCallout({node:e,parent:t,replaceWith:n}){let{kind:r}=e;if(r===`fail`)n($(OV({negate:!0}),t));else throw Error(`Unsupported named callout "(*${r.toUpperCase()}"`)},Quantifier({node:e}){if(e.body.type===`Quantifier`){let t=DV();t.body[0].body.push(e.body),e.body=$(t,e)}},Regex:{enter({node:e},{supportedGNodes:t}){let n=[],r=!1,i=!1;for(let t of e.body)if(t.body.length===1&&t.body[0].kind===`search_start`)t.body.pop();else{let e=nU(t.body);e?(r=!0,Array.isArray(e)?n.push(...e):n.push(e)):i=!0}r&&!i&&n.forEach(e=>t.add(e))},exit(e,{accuracy:t,passedLookbehind:n,strategy:r}){if(t===`strict`&&n&&r)throw Error(Q`Uses "\G" in a way that requires non-strict accuracy`)}},Subroutine({node:e},{jsGroupNameMap:t}){let{ref:n}=e;typeof n==`string`&&!sU(n)&&(n=QH(n,t),e.ref=n)}},WH={Backreference({node:e},{multiplexCapturesToLeftByRef:t,reffedNodesByReferencer:n}){let{orphan:r,ref:i}=e;r||n.set(e,[...t.get(i).map(({node:e})=>e)])},CapturingGroup:{enter({node:e,parent:t,replaceWith:n,skip:r},{groupOriginByCopy:i,groupsByName:a,multiplexCapturesToLeftByRef:o,openRefs:s,reffedNodesByReferencer:c}){let l=i.get(e);if(l&&s.has(e.number)){let r=uU(XH(e.number),t);c.set(r,s.get(e.number)),n(r);return}s.set(e.number,e),o.set(e.number,[]),e.name&&CH(o,e.name,[]);let u=o.get(e.name??e.number);for(let t=0;t<u.length;t++){let n=u[t];if(l===n.node||l&&l===n.origin||e===n.origin){u.splice(t,1);break}}if(o.get(e.number).push({node:e,origin:l}),e.name&&o.get(e.name).push({node:e,origin:l}),e.name){let t=CH(a,e.name,new Map),n=!1;if(l)n=!0;else for(let e of t.values())if(!e.hasDuplicateNameToRemove){n=!0;break}a.get(e.name).set(e,{node:e,hasDuplicateNameToRemove:n})}},exit({node:e},{openRefs:t}){t.delete(e.number)}},Group:{enter({node:e},t){t.prevFlags=t.currentFlags,e.flags&&(t.currentFlags=SH(t.currentFlags,e.flags))},exit(e,t){t.currentFlags=t.prevFlags}},Subroutine({node:e,parent:t,replaceWith:n},r){let{isRecursive:i,ref:a}=e;if(i){let n=t;for(;(n=n.parent)&&(n.type!==`CapturingGroup`||n.name!==a&&n.number!==a););r.reffedNodesByReferencer.set(e,n);return}let o=r.subroutineRefMap.get(a),s=a===0,c=s?XH(0):YH(o,r.groupOriginByCopy,null),l=c;if(!s){let e=$H(ZH(o,e=>e.type===`Group`&&!!e.flags)),t=e?SH(r.globalFlags,e):r.globalFlags;qH(t,r.currentFlags)||(l=DV({flags:eU(t)}),l.body[0].body.push(c))}n($(l,t),{traverse:!s})}},GH={Backreference({node:e,parent:t,replaceWith:n},r){if(e.orphan){r.highestOrphanBackref=Math.max(r.highestOrphanBackref,e.ref);return}let i=r.reffedNodesByReferencer.get(e).filter(t=>JH(t,e));i.length?i.length>1?n($(DV({atomic:!0,body:i.reverse().map(e=>_V({body:[yV(e.number)]}))}),t)):e.ref=i[0].number:n($(OV({negate:!0}),t))},CapturingGroup({node:e},t){e.number=++t.numCapturesToLeft,e.name&&t.groupsByName.get(e.name).get(e).hasDuplicateNameToRemove&&delete e.name},Regex:{exit({node:e},t){let n=Math.max(t.highestOrphanBackref-t.numCapturesToLeft,0);for(let t=0;t<n;t++){let t=bV();e.body.at(-1).body.push(t)}}},Subroutine({node:e},t){!e.isRecursive||e.ref===0||(e.ref=t.reffedNodesByReferencer.get(e).number)}};function KH(e){GV(e,{"*"({node:e,parent:t}){e.parent=t}})}function qH(e,t){return e.dotAll===t.dotAll&&e.ignoreCase===t.ignoreCase}function JH(e,t){let n=t;do{if(n.type===`Regex`)return!1;if(n.type===`Alternative`)continue;if(n===e)return!1;let t=tU(n.parent);for(let r of t){if(r===n)break;if(r===e||rU(r,e))return!0}}while(n=n.parent);throw Error(`Unexpected path`)}function YH(e,t,n,r){let i=Array.isArray(e)?[]:{};for(let[a,o]of Object.entries(e))a===`parent`?i.parent=Array.isArray(n)?r:n:o&&typeof o==`object`?i[a]=YH(o,t,i,n):(a===`type`&&o===`CapturingGroup`&&t.set(i,t.get(e)??e),i[a]=o);return i}function XH(e){let t=NV(e);return t.isRecursive=!0,t}function ZH(e,t){let n=[];for(;e=e.parent;)(!t||t(e))&&n.push(e);return n}function QH(e,t){if(t.has(e))return t.get(e);let n=`$${t.size}_${e.replace(/^[^$_\p{IDS}]|[^$\u200C\u200D\p{IDC}]/gu,`_`)}`;return t.set(e,n),n}function $H(e){let t=[`dotAll`,`ignoreCase`],n={enable:{},disable:{}};return e.forEach(({flags:e})=>{t.forEach(t=>{e.enable?.[t]&&(delete n.disable[t],n.enable[t]=!0),e.disable?.[t]&&(n.disable[t]=!0)})}),Object.keys(n.enable).length||delete n.enable,Object.keys(n.disable).length||delete n.disable,n.enable||n.disable?n:null}function eU({dotAll:e,ignoreCase:t}){let n={};return(e||t)&&(n.enable={},e&&(n.enable.dotAll=!0),t&&(n.enable.ignoreCase=!0)),(!e||!t)&&(n.disable={},!e&&(n.disable.dotAll=!0),!t&&(n.disable.ignoreCase=!0)),n}function tU(e){if(!e)throw Error(`Node expected`);let{body:t}=e;return Array.isArray(t)?t:t?[t]:null}function nU(e){let t=e.find(e=>e.kind===`search_start`||oU(e,{negate:!1})||!iU(e));if(!t)return null;if(t.kind===`search_start`)return t;if(t.type===`LookaroundAssertion`)return t.body[0].body[0];if(t.type===`CapturingGroup`||t.type===`Group`){let e=[];for(let n of t.body){let t=nU(n.body);if(!t)return null;Array.isArray(t)?e.push(...t):e.push(t)}return e}return null}function rU(e,t){let n=tU(e)??[];for(let e of n)if(e===t||rU(e,t))return!0;return!1}function iU({type:e}){return e===`Assertion`||e===`Directive`||e===`LookaroundAssertion`}function aU(e){let t=[`Character`,`CharacterClass`,`CharacterSet`];return t.includes(e.type)||e.type===`Quantifier`&&e.min&&t.includes(e.body.type)}function oU(e,t){let n={negate:null,...t};return e.type===`LookaroundAssertion`&&(n.negate===null||e.negate===n.negate)&&e.body.length===1&&iV(e.body[0],{type:`Assertion`,kind:`search_start`})}function sU(e){return/^[$_\p{IDS}][$\u200C\u200D\p{IDC}]*$/u.test(e)}function cU(e,t){let n=sV(e,{...t,unicodePropertyMap:NH}).body;return n.length>1||n[0].body.length>1?DV({body:n}):n[0].body[0]}function lU(e,t){return e.negate=t,e}function uU(e,t){return e.parent=t,e}function $(e,t){return KH(e),e.parent=t,e}function dU(e,t){let n=OH(t),r=wH(n.target,`ES2024`),i=wH(n.target,`ES2025`),a=n.rules.recursionLimit;if(!Number.isInteger(a)||a<2||a>20)throw Error(`Invalid recursionLimit; use 2-20`);let o=null,s=null;if(!i){let t=[e.flags.ignoreCase];GV(e,fU,{getCurrentModI:()=>t.at(-1),popModI(){t.pop()},pushModI(e){t.push(e)},setHasCasedChar(){t.at(-1)?o=!0:s=!0}})}let c={dotAll:e.flags.dotAll,ignoreCase:!!((e.flags.ignoreCase||o)&&!s)},l=e,u={accuracy:n.accuracy,appliedGlobalFlags:c,captureMap:new Map,currentFlags:{dotAll:e.flags.dotAll,ignoreCase:e.flags.ignoreCase},inCharClass:!1,lastNode:l,originMap:e._originMap,recursionLimit:a,useAppliedIgnoreCase:!!(!i&&o&&s),useFlagMods:i,useFlagV:r,verbose:n.verbose};function d(e){return u.lastNode=l,l=e,TH(pU[e.type],`Unexpected node type "${e.type}"`)(e,u,d)}let f={pattern:e.body.map(d).join(`|`),flags:d(e.flags),options:{...e.options}};return r||(delete f.options.force.v,f.options.disable.v=!0,f.options.unicodeSetsPlugin=null),f._captureTransfers=new Map,f._hiddenCaptures=[],u.captureMap.forEach((e,t)=>{e.hidden&&f._hiddenCaptures.push(t),e.transferTo&&CH(f._captureTransfers,e.transferTo,[]).push(t)}),f}var fU={"*":{enter({node:e},t){if(TU(e)){let n=t.getCurrentModI();t.pushModI(e.flags?SH({ignoreCase:n},e.flags).ignoreCase:n)}},exit({node:e},t){TU(e)&&t.popModI()}},Backreference(e,t){t.setHasCasedChar()},Character({node:e},t){yU(Z(e.value))&&t.setHasCasedChar()},CharacterClassRange({node:e,skip:t},n){t(),bU(e,{firstOnly:!0}).length&&n.setHasCasedChar()},CharacterSet({node:e},t){e.kind===`property`&&VH.has(e.value)&&t.setHasCasedChar()}},pU={Alternative({body:e},t,n){return e.map(n).join(``)},Assertion({kind:e,negate:t}){if(e===`string_end`)return`$`;if(e===`string_start`)return`^`;if(e===`word_boundary`)return t?Q`\B`:Q`\b`;throw Error(`Unexpected assertion kind "${e}"`)},Backreference({ref:e},t){if(typeof e!=`number`)throw Error(`Unexpected named backref in transformed AST`);if(!t.useFlagMods&&t.accuracy===`strict`&&t.currentFlags.ignoreCase&&!t.captureMap.get(e).ignoreCase)throw Error(`Use of case-insensitive backref to case-sensitive group requires target ES2025 or non-strict accuracy`);return`\\`+e},CapturingGroup(e,t,n){let{body:r,name:i,number:a}=e,o={ignoreCase:t.currentFlags.ignoreCase},s=t.originMap.get(e);return s&&(o.hidden=!0,a>s.number&&(o.transferTo=s.number)),t.captureMap.set(a,o),`(${i?`?<${i}>`:``}${r.map(n).join(`|`)})`},Character({value:e},t){let n=Z(e),r=xU(e,{escDigit:t.lastNode.type===`Backreference`,inCharClass:t.inCharClass,useFlagV:t.useFlagV});if(r!==n)return r;if(t.useAppliedIgnoreCase&&t.currentFlags.ignoreCase&&yU(n)){let e=MH(n);return t.inCharClass?e.join(``):e.length>1?`[${e.join(``)}]`:e[0]}return n},CharacterClass(e,t,n){let{kind:r,negate:i,parent:a}=e,{body:o}=e;if(r===`intersection`&&!t.useFlagV)throw Error(`Use of character class intersection requires min target ES2024`);bH.bugFlagVLiteralHyphenIsRange&&t.useFlagV&&o.some(DU)&&(o=[xV(45),...o.filter(e=>!DU(e))]);let s=()=>`[${i?`^`:``}${o.map(n).join(r===`intersection`?`&&`:``)}]`;if(!t.inCharClass){if((!t.useFlagV||bH.bugNestedClassIgnoresNegation)&&!i){let t=o.filter(e=>e.type===`CharacterClass`&&e.kind===`union`&&e.negate);if(t.length){let r=DV(),i=r.body[0];return r.parent=a,i.parent=r,o=o.filter(e=>!t.includes(e)),e.body=o,o.length?(e.parent=i,i.body.push(e)):r.body.pop(),t.forEach(e=>{let t=_V({body:[e]});e.parent=t,t.parent=r,r.body.push(t)}),n(r)}}t.inCharClass=!0;let r=s();return t.inCharClass=!1,r}let c=o[0];if(r===`union`&&!i&&c&&((!t.useFlagV||!t.verbose)&&a.kind===`union`&&!(bH.bugFlagVLiteralHyphenIsRange&&t.useFlagV)||!t.verbose&&a.kind===`intersection`&&o.length===1&&c.type!==`CharacterClassRange`))return o.map(n).join(``);if(!t.useFlagV&&a.type===`CharacterClass`)throw Error(`Uses nested character class in a way that requires min target ES2024`);return s()},CharacterClassRange(e,t){let n=e.min.value,r=e.max.value,i={escDigit:!1,inCharClass:!0,useFlagV:t.useFlagV},a=xU(n,i),o=xU(r,i),s=new Set;return t.useAppliedIgnoreCase&&t.currentFlags.ignoreCase&&SU(bU(e)).forEach(e=>{s.add(Array.isArray(e)?`${xU(e[0],i)}-${xU(e[1],i)}`:xU(e,i))}),`${a}-${o}${[...s].join(``)}`},CharacterSet({kind:e,negate:t,value:n,key:r},i){if(e===`dot`)return i.currentFlags.dotAll?i.appliedGlobalFlags.dotAll||i.useFlagMods?`.`:`[^]`:Q`[^\n]`;if(e===`digit`)return t?Q`\D`:Q`\d`;if(e===`property`){if(i.useAppliedIgnoreCase&&i.currentFlags.ignoreCase&&VH.has(n))throw Error(`Unicode property "${n}" can't be case-insensitive when other chars have specific case`);return`${t?Q`\P`:Q`\p`}{${r?`${r}=`:``}${n}}`}if(e===`word`)return t?Q`\W`:Q`\w`;throw Error(`Unexpected character set kind "${e}"`)},Flags(e,t){return(t.appliedGlobalFlags.ignoreCase?`i`:``)+(e.dotAll?`s`:``)+(e.sticky?`y`:``)},Group({atomic:e,body:t,flags:n,parent:r},i,a){let o=i.currentFlags;n&&(i.currentFlags=SH(o,n));let s=t.map(a).join(`|`),c=!i.verbose&&t.length===1&&r.type!==`Quantifier`&&!e&&(!i.useFlagMods||!n)?s:`(?${CU(e,n,i.useFlagMods)}${s})`;return i.currentFlags=o,c},LookaroundAssertion({body:e,kind:t,negate:n},r,i){return`(?${`${t===`lookahead`?``:`<`}${n?`!`:`=`}`}${e.map(i).join(`|`)})`},Quantifier(e,t,n){return n(e.body)+wU(e)},Subroutine({isRecursive:e,ref:t},n){if(!e)throw Error(`Unexpected non-recursive subroutine in transformed AST`);let r=n.recursionLimit;return t===0?`(?R=${r})`:Q`\g<${t}&R=${r}>`}},mU=new Set([`$`,`(`,`)`,`*`,`+`,`.`,`?`,`[`,`\\`,`]`,`^`,`{`,`|`,`}`]),hU=new Set([`-`,`\\`,`]`,`^`,`[`]),gU=new Set("()-/[\\]^{|}!#$%&*+,.:;<=>?@`~".split(``)),_U=new Map([[9,Q`\t`],[10,Q`\n`],[11,Q`\v`],[12,Q`\f`],[13,Q`\r`],[8232,Q`\u2028`],[8233,Q`\u2029`],[65279,Q`\uFEFF`]]),vU=/^\p{Cased}$/u;function yU(e){return vU.test(e)}function bU(e,t){let n=!!t?.firstOnly,r=e.min.value,i=e.max.value,a=[];if(r<65&&(i===65535||i>=131071)||r===65536&&i>=131071)return a;for(let e=r;e<=i;e++){let t=Z(e);if(!yU(t))continue;let o=MH(t).filter(e=>{let t=e.codePointAt(0);return t<r||t>i});if(o.length&&(a.push(...o),n))break}return a}function xU(e,{escDigit:t,inCharClass:n,useFlagV:r}){if(_U.has(e))return _U.get(e);if(e<32||e>126&&e<160||e>262143||t&&EU(e))return e>255?`\\u{${e.toString(16).toUpperCase()}}`:`\\x${e.toString(16).toUpperCase().padStart(2,`0`)}`;let i=n?r?gU:hU:mU,a=Z(e);return(i.has(a)?`\\`:``)+a}function SU(e){let t=e.map(e=>e.codePointAt(0)).sort((e,t)=>e-t),n=[],r=null;for(let e=0;e<t.length;e++)t[e+1]===t[e]+1?r??=t[e]:r===null?n.push(t[e]):(n.push([r,t[e]]),r=null);return n}function CU(e,t,n){if(e)return`>`;let r=``;if(t&&n){let{enable:e,disable:n}=t;r=(e?.ignoreCase?`i`:``)+(e?.dotAll?`s`:``)+(n?`-`:``)+(n?.ignoreCase?`i`:``)+(n?.dotAll?`s`:``)}return`${r}:`}function wU({kind:e,max:t,min:n}){let r;return r=!n&&t===1?`?`:!n&&t===1/0?`*`:n===1&&t===1/0?`+`:n===t?`{${n}}`:`{${n},${t===1/0?``:t}}`,r+{greedy:``,lazy:`?`,possessive:`+`}[e]}function TU({type:e}){return e===`CapturingGroup`||e===`Group`||e===`LookaroundAssertion`}function EU(e){return e>47&&e<58}function DU({type:e,value:t}){return e===`Character`&&t===45}var OU=class e extends RegExp{#e=new Map;#t=null;#n;#r=null;#i=null;rawOptions={};get source(){return this.#n||`(?:)`}constructor(t,n,r){let i=!!r?.lazyCompile;if(t instanceof RegExp){if(r)throw Error(`Cannot provide options when copying a regexp`);let i=t;super(i,n),this.#n=i.source,i instanceof e&&(this.#e=i.#e,this.#r=i.#r,this.#i=i.#i,this.rawOptions=i.rawOptions)}else{let e={hiddenCaptures:[],strategy:null,transfers:[],...r};super(i?``:t,n),this.#n=t,this.#e=AU(e.hiddenCaptures,e.transfers),this.#i=e.strategy,this.rawOptions=r??{}}i||(this.#t=this)}exec(t){if(!this.#t){let{lazyCompile:t,...n}=this.rawOptions;this.#t=new e(this.#n,this.flags,n)}let n=this.global||this.sticky,r=this.lastIndex;if(this.#i===`clip_search`&&n&&r){this.lastIndex=0;let e=this.#a(t.slice(r));return e&&(kU(e,r,t,this.hasIndices),this.lastIndex+=r),e}return this.#a(t)}#a(e){this.#t.lastIndex=this.lastIndex;let t=super.exec.call(this.#t,e);if(this.lastIndex=this.#t.lastIndex,!t||!this.#e.size)return t;let n=[...t];t.length=1;let r;this.hasIndices&&(r=[...t.indices],t.indices.length=1);let i=[0];for(let e=1;e<n.length;e++){let{hidden:a,transferTo:o}=this.#e.get(e)??{};if(a?i.push(null):(i.push(t.length),t.push(n[e]),this.hasIndices&&t.indices.push(r[e])),o&&n[e]!==void 0){let a=i[o];if(!a)throw Error(`Invalid capture transfer to "${a}"`);if(t[a]=n[e],this.hasIndices&&(t.indices[a]=r[e]),t.groups){this.#r||=jU(this.source);let i=this.#r.get(o);i&&(t.groups[i]=n[e],this.hasIndices&&(t.indices.groups[i]=r[e]))}}}return t}};function kU(e,t,n,r){if(e.index+=t,e.input=n,r){let n=e.indices;for(let e=0;e<n.length;e++){let r=n[e];r&&(n[e]=[r[0]+t,r[1]+t])}let r=n.groups;r&&Object.keys(r).forEach(e=>{let n=r[e];n&&(r[e]=[n[0]+t,n[1]+t])})}}function AU(e,t){let n=new Map;for(let t of e)n.set(t,{hidden:!0});for(let[e,r]of t)for(let t of r)CH(n,t,{}).transferTo=e;return n}function jU(e){let t=/(?<capture>\((?:\?<(?![=!])(?<name>[^>]+)>|(?!\?)))|\\?./gsu,n=new Map,r=0,i=0,a;for(;a=t.exec(e);){let{0:e,groups:{capture:t,name:o}}=a;e===`[`?r++:r?e===`]`&&r--:t&&(i++,o&&n.set(i,o))}return n}function MU(e,t){let n=NU(e,t);return n.options?new OU(n.pattern,n.flags,n.options):new RegExp(n.pattern,n.flags)}function NU(e,t){let n=OH(t),r=HH(sV(e,{flags:n.flags,normalizeUnknownPropertyNames:!0,rules:{captureGroup:n.rules.captureGroup,singleline:n.rules.singleline},skipBackrefValidation:n.rules.allowOrphanBackrefs,unicodePropertyMap:NH}),{accuracy:n.accuracy,asciiWordBoundaries:n.rules.asciiWordBoundaries,avoidSubclass:n.avoidSubclass,bestEffortTarget:n.target}),i=dU(r,n),a=mH(i.pattern,{captureTransfers:i._captureTransfers,hiddenCaptures:i._hiddenCaptures,mode:`external`}),o=iH(sH(a.pattern).pattern,{captureTransfers:a.captureTransfers,hiddenCaptures:a.hiddenCaptures}),s={pattern:o.pattern,flags:`${n.hasIndices?`d`:``}${n.global?`g`:``}${i.flags}${i.options.disable.v?`u`:`v`}`};if(n.avoidSubclass){if(n.lazyCompileLength!==1/0)throw Error(`Lazy compilation requires subclass`)}else{let e=o.hiddenCaptures.sort((e,t)=>e-t),t=Array.from(o.captureTransfers),i=r._strategy,a=s.pattern.length>=n.lazyCompileLength;(e.length||t.length||i||a)&&(s.options={...e.length&&{hiddenCaptures:e},...t.length&&{transfers:t},...i&&{strategy:i},...a&&{lazyCompile:a}})}return s}function PU(e,t){return MU(e,{global:!0,hasIndices:!0,lazyCompileLength:3e3,rules:{allowOrphanBackrefs:!0,asciiWordBoundaries:!0,captureGroup:!0,recursionLimit:5,singleline:!0},...t})}function FU(e={}){let t=Object.assign({target:`auto`,cache:new Map},e);return t.regexConstructor||=e=>PU(e,{target:t.target}),{createScanner(e){return new mB(e,t)},createString(e){return{content:e}}}}async function IU(e){if(pI())throw Error(`resolveLanguage("${e}") cannot be called from a worker context. Languages must be pre-resolved on the main thread and passed to the worker via the resolvedLanguages parameter.`);let t=cI.get(e);if(t!=null)return t;try{let t=lI.get(e);if(t==null&&Object.prototype.hasOwnProperty.call(wI,e)&&(t=wI[e]),t==null)throw Error(`resolveLanguage: "${e}" not found in bundled or custom languages`);let n=t().then(({default:t})=>{let n={name:e,data:t};return sI.has(e)||sI.set(e,n),n});return cI.set(e,n),await n}finally{cI.delete(e)}}function LU(e){return sI.get(e)??IU(e)}var RU=new Set;function zU(e){let t=[],n=new Set;for(let r of BU(e.themes)){let e=UU(r)?r.getThemes():[r];for(let r of e){if(n.has(r.name))throw Error(`Theme collection already contains theme "${r.name}"`);n.add(r.name),t.push(r)}}let r=Object.freeze([...t]),i=Object.freeze(r.filter(e=>e.colorScheme===`light`)),a=Object.freeze(r.filter(e=>e.colorScheme===`dark`)),o=new Map(r.map(e=>[e.name,e])),s=Object.freeze(r.map(e=>e.name)),c=Object.freeze(i.map(e=>e.name)),l=Object.freeze(a.map(e=>e.name));function u(e){if(e==null)return r;let{colorScheme:t,collection:n}=e;return n==null?t===`light`?i:t===`dark`?a:r:r.filter(e=>e.collection===n?t==null||e.colorScheme===t:!1)}return{getTheme(e){return o.get(e)},getThemes(e){return u(e)},getThemeNames(e){return e?.collection==null?e?.colorScheme===`light`?c:e?.colorScheme===`dark`?l:s:u(e).map(e=>e.name)},hasTheme(e){return o.has(e)},orderBy(e){return zU({themes:r.map((e,t)=>({descriptor:e,index:t})).sort((t,n)=>{let r=e(t.descriptor,n.descriptor);return r===0?t.index-n.index:r}).map(e=>e.descriptor)})},pick(e){let t=[],n=new Set;for(let r of e){if(n.has(r))throw Error(`Theme collection pick already includes theme "${r}"`);n.add(r);let e=o.get(r);if(e==null)throw Error(`Theme collection does not contain theme "${r}"`);t.push(e)}return zU({themes:t})},registerInto(e){for(let t of r)e.registerThemeIfAbsent(t.name,t.load)}}}function BU(e){return VU(e)?[e]:e}function VU(e){return UU(e)||HU(e)}function HU(e){return typeof e.name==`string`&&typeof e.load==`function`}function UU(e){return typeof e.getThemes==`function`}function WU(e){return typeof e==`object`&&e&&`default`in e?e.default:e}var GU=class extends Error{constructor(e){super(`Theme "${e}" is already registered`),this.name=`DuplicateThemeError`}},KU=class extends Error{constructor(e){super(`No loader registered for theme "${e}"`),this.name=`UnregisteredThemeError`}},qU=class extends Error{constructor(e){super(`Theme "${e}" has not been resolved`),this.name=`UnresolvedThemeError`}};function JU(){let e=new Map,t=new Map,n=new Map,r=0;function i(t,n){if(e.has(t))throw new GU(t);e.set(t,n)}function a(t,n){return!e.has(t)&&(e.set(t,n),!0)}function o(t){return e.has(t)}function s(i){let a=t.get(i);if(a!==void 0)return Promise.resolve(a);let o=n.get(i);if(o!==void 0)return o;let s=e.get(i);if(s===void 0)return Promise.reject(new KU(i));let c=r,l=s().then(e=>{let a=WU(e);return c===r&&t.set(i,a),n.get(i)===l&&n.delete(i),a}).catch(e=>{throw n.get(i)===l&&n.delete(i),e});return n.set(i,l),l}function c(e){return Promise.all(e.map(e=>s(e)))}function l(e,n){t.set(e,n)}function u(e){for(let[t,n]of e)l(t,n)}function d(e){return t.get(e)}function f(e){let n=[];for(let r of e){let e=t.get(r);if(e===void 0)throw new qU(r);n.push(e)}return n}function p(e){return t.has(e)}function m(e){for(let n of e)if(!t.has(n))return!1;return!0}function h(e){let n=t.get(e);return n===void 0?s(e):n}function g(){r++,t.clear(),n.clear()}return{clearResolvedThemes:g,getResolvedOrResolveTheme:h,getResolvedTheme:d,getResolvedThemes:f,hasRegisteredTheme:o,hasResolvedTheme:p,hasResolvedThemes:m,registerTheme:i,registerThemeIfAbsent:a,resolveTheme:s,resolveThemes:c,seedResolvedTheme:l,seedResolvedThemes:u}}var YU=JU();function XU(e,t){e=Array.isArray(e)?e:[e];for(let n of e){let e;if(typeof n==`string`){if(e=YU.getResolvedTheme(n),e==null)throw Error(`loadResolvedThemes: ${n} is not resolved, you must resolve it before calling loadResolvedThemes`)}else e=n,n=n.name,YU.getResolvedTheme(n)??YU.seedResolvedTheme(n,e);RU.has(n)||(RU.add(n),t.loadThemeSync(e))}}function ZU({name:e,load:t,colorScheme:n,collection:r,displayName:i}){return{name:e,colorScheme:n,collection:r,displayName:i,load:QU(t)}}function QU(e){return async()=>KR(WU(await e()))}var $U=`pierre`,eW=[`pierre-dark`,`pierre-dark-soft`,`pierre-dark-vibrant`,`pierre-dark-protanopia-deuteranopia`,`pierre-dark-tritanopia`],tW=[`pierre-light`,`pierre-light-soft`,`pierre-light-vibrant`,`pierre-light-protanopia-deuteranopia`,`pierre-light-tritanopia`],nW=[...tW,...eW],rW=new Set(tW);function iW(e){return rW.has(e)?`light`:`dark`}var aW={"pierre-dark":`Pierre Dark`,"pierre-dark-soft":`Pierre Dark Soft`,"pierre-dark-vibrant":`Pierre Dark Vibrant`,"pierre-dark-protanopia-deuteranopia":`Pierre Dark Protanopia & Deuteranopia`,"pierre-dark-tritanopia":`Pierre Dark Tritanopia`,"pierre-light":`Pierre Light`,"pierre-light-soft":`Pierre Light Soft`,"pierre-light-vibrant":`Pierre Light Vibrant`,"pierre-light-protanopia-deuteranopia":`Pierre Light Protanopia & Deuteranopia`,"pierre-light-tritanopia":`Pierre Light Tritanopia`},oW={"pierre-dark":()=>D(()=>import(`./pierre-dark-CpLgRqie.js`),[]),"pierre-dark-soft":()=>D(()=>import(`./pierre-dark-soft-kZQmAZld.js`),[]),"pierre-dark-vibrant":()=>D(()=>import(`./pierre-dark-vibrant-CpQYzh95.js`),[]),"pierre-dark-protanopia-deuteranopia":()=>D(()=>import(`./pierre-dark-protanopia-deuteranopia-B35FxJx-.js`),[]),"pierre-dark-tritanopia":()=>D(()=>import(`./pierre-dark-tritanopia-CpjhbsIL.js`),[]),"pierre-light":()=>D(()=>import(`./pierre-light-CoaEpmwp.js`),[]),"pierre-light-soft":()=>D(()=>import(`./pierre-light-soft-lWLdNTOI.js`),[]),"pierre-light-vibrant":()=>D(()=>import(`./pierre-light-vibrant-D80Fkn33.js`),[]),"pierre-light-protanopia-deuteranopia":()=>D(()=>import(`./pierre-light-protanopia-deuteranopia-0fSaH845.js`),[]),"pierre-light-tritanopia":()=>D(()=>import(`./pierre-light-tritanopia-CEbqgOJL.js`),[])};function sW(e){return ZU({name:e,collection:$U,colorScheme:iW(e),displayName:aW[e],load:oW[e]})}var cW=zU({themes:nW.map(e=>sW(e))}),lW=`shiki`,uW=[`ayu-light`,`catppuccin-latte`,`everforest-light`,`github-light`,`github-light-default`,`github-light-high-contrast`,`gruvbox-light-hard`,`gruvbox-light-medium`,`gruvbox-light-soft`,`horizon-bright`,`kanagawa-lotus`,`light-plus`,`material-theme-lighter`,`min-light`,`night-owl-light`,`one-light`,`rose-pine-dawn`,`slack-ochin`,`snazzy-light`,`solarized-light`,`vitesse-light`],dW=`andromeeda.aurora-x.ayu-dark.ayu-mirage.catppuccin-frappe.catppuccin-macchiato.catppuccin-mocha.dark-plus.dracula.dracula-soft.everforest-dark.github-dark.github-dark-default.github-dark-dimmed.github-dark-high-contrast.gruvbox-dark-hard.gruvbox-dark-medium.gruvbox-dark-soft.horizon.houston.kanagawa-dragon.kanagawa-wave.laserwave.material-theme.material-theme-darker.material-theme-ocean.material-theme-palenight.min-dark.monokai.night-owl.nord.one-dark-pro.plastic.poimandres.red.rose-pine.rose-pine-moon.slack-dark.solarized-dark.synthwave-84.tokyo-night.vesper.vitesse-black.vitesse-dark`.split(`.`),fW=new Set(uW);function pW(e){return fW.has(e)?`light`:`dark`}var mW={andromeeda:()=>D(()=>import(`./andromeeda-vGVdxbeo.js`),[]),"aurora-x":()=>D(()=>import(`./aurora-x-CDeNXAV0.js`),[]),"ayu-dark":()=>D(()=>import(`./ayu-dark-DluEY0Gj.js`),[]),"ayu-light":()=>D(()=>import(`./ayu-light-C3h-C4tm.js`),[]),"ayu-mirage":()=>D(()=>import(`./ayu-mirage-Bqwy1Gya.js`),[]),"catppuccin-frappe":()=>D(()=>import(`./catppuccin-frappe-3VR1Za6u.js`),[]),"catppuccin-latte":()=>D(()=>import(`./catppuccin-latte-DwIHMF0Q.js`),[]),"catppuccin-macchiato":()=>D(()=>import(`./catppuccin-macchiato-DYnBP6_5.js`),[]),"catppuccin-mocha":()=>D(()=>import(`./catppuccin-mocha-DYhrFGRu.js`),[]),"dark-plus":()=>D(()=>import(`./dark-plus-Cs2F2srj.js`),[]),dracula:()=>D(()=>import(`./dracula-BHWKrbxM.js`),[]),"dracula-soft":()=>D(()=>import(`./dracula-soft-5eyTD99u.js`),[]),"everforest-dark":()=>D(()=>import(`./everforest-dark-sB-x3p7T.js`),[]),"everforest-light":()=>D(()=>import(`./everforest-light-Df2xbC6M.js`),[]),"github-dark":()=>D(()=>import(`./github-dark-C-LZuMrd.js`),[]),"github-dark-default":()=>D(()=>import(`./github-dark-default-DXG-b-1a.js`),[]),"github-dark-dimmed":()=>D(()=>import(`./github-dark-dimmed-Bx1FflLF.js`),[]),"github-dark-high-contrast":()=>D(()=>import(`./github-dark-high-contrast-B_tTalzw.js`),[]),"github-light":()=>D(()=>import(`./github-light-EUqPIrTm.js`),[]),"github-light-default":()=>D(()=>import(`./github-light-default-BXViO-2h.js`),[]),"github-light-high-contrast":()=>D(()=>import(`./github-light-high-contrast-B68TUdTA.js`),[]),"gruvbox-dark-hard":()=>D(()=>import(`./gruvbox-dark-hard-C820rvS2.js`),[]),"gruvbox-dark-medium":()=>D(()=>import(`./gruvbox-dark-medium-BPjhmG05.js`),[]),"gruvbox-dark-soft":()=>D(()=>import(`./gruvbox-dark-soft-MrdJrrXF.js`),[]),"gruvbox-light-hard":()=>D(()=>import(`./gruvbox-light-hard-BC_s9l72.js`),[]),"gruvbox-light-medium":()=>D(()=>import(`./gruvbox-light-medium-BAWPOn9u.js`),[]),"gruvbox-light-soft":()=>D(()=>import(`./gruvbox-light-soft-BSMLrYjP.js`),[]),horizon:()=>D(()=>import(`./horizon-CE9ld1lL.js`),[]),"horizon-bright":()=>D(()=>import(`./horizon-bright-DSNQnXHK.js`),[]),houston:()=>D(()=>import(`./houston-CsvMBhTu.js`),[]),"kanagawa-dragon":()=>D(()=>import(`./kanagawa-dragon-CXtmUGW6.js`),[]),"kanagawa-lotus":()=>D(()=>import(`./kanagawa-lotus-BN08jTvb.js`),[]),"kanagawa-wave":()=>D(()=>import(`./kanagawa-wave-CTweb8Dz.js`),[]),laserwave:()=>D(()=>import(`./laserwave-C_8bwKvT.js`),[]),"light-plus":()=>D(()=>import(`./light-plus-DVQuIRkW.js`),[]),"material-theme":()=>D(()=>import(`./material-theme-Bm3Qr25_.js`),[]),"material-theme-darker":()=>D(()=>import(`./material-theme-darker-2IIEA8gg.js`),[]),"material-theme-lighter":()=>D(()=>import(`./material-theme-lighter-uhdI0v04.js`),[]),"material-theme-ocean":()=>D(()=>import(`./material-theme-ocean-CHQ94UKr.js`),[]),"material-theme-palenight":()=>D(()=>import(`./material-theme-palenight-B5W6OYN7.js`),[]),"min-dark":()=>D(()=>import(`./min-dark-BSWPekZh.js`),[]),"min-light":()=>D(()=>import(`./min-light-DDpmG2fV.js`),[]),monokai:()=>D(()=>import(`./monokai-CdkpiU2Y.js`),[]),"night-owl":()=>D(()=>import(`./night-owl-DhmEMT88.js`),[]),"night-owl-light":()=>D(()=>import(`./night-owl-light-eJ-hLW7d.js`),[]),nord:()=>D(()=>import(`./nord-Cb4Vim4T.js`),[]),"one-dark-pro":()=>D(()=>import(`./one-dark-pro-CLwyXe_n.js`),[]),"one-light":()=>D(()=>import(`./one-light-D7Lr4KcI.js`),[]),plastic:()=>D(()=>import(`./plastic-DQwYfKfQ.js`),[]),poimandres:()=>D(()=>import(`./poimandres-DRFjx7u4.js`),[]),red:()=>D(()=>import(`./red-CJ3rzSJv.js`),[]),"rose-pine":()=>D(()=>import(`./rose-pine-BthvhNj6.js`),[]),"rose-pine-dawn":()=>D(()=>import(`./rose-pine-dawn-Dg85fqjY.js`),[]),"rose-pine-moon":()=>D(()=>import(`./rose-pine-moon-hon4tzzS.js`),[]),"slack-dark":()=>D(()=>import(`./slack-dark-DnToyrRv.js`),[]),"slack-ochin":()=>D(()=>import(`./slack-ochin-B2OO5cIa.js`),[]),"snazzy-light":()=>D(()=>import(`./snazzy-light-4G7pJPwS.js`),[]),"solarized-dark":()=>D(()=>import(`./solarized-dark-DV17i1UV.js`),[]),"solarized-light":()=>D(()=>import(`./solarized-light-DSh2HLQt.js`),[]),"synthwave-84":()=>D(()=>import(`./synthwave-84-nFMaYfgc.js`),[]),"tokyo-night":()=>D(()=>import(`./tokyo-night-oM2G3aXe.js`),[]),vesper:()=>D(()=>import(`./vesper-DdrHHSXu.js`),[]),"vitesse-black":()=>D(()=>import(`./vitesse-black-fwtXNY1n.js`),[]),"vitesse-dark":()=>D(()=>import(`./vitesse-dark-BZCL-v6S.js`),[]),"vitesse-light":()=>D(()=>import(`./vitesse-light-VbXTXTou.js`),[])};function hW(e){return ZU({name:e,collection:lW,colorScheme:pW(e),load:mW[e]})}var gW=zU({themes:Object.freeze([...uW.map(e=>hW(e)),...dW.map(e=>hW(e))])});function _W(e){if(pI())throw Error(`Theme "${e}" cannot be resolved from a worker context. Themes must be pre-resolved on the main thread and passed to the worker via the resolvedLanguages parameter.`);if(YU.hasRegisteredTheme(e))return;let t=gW.getTheme(e);if(t!=null){YU.registerThemeIfAbsent(t.name,t.load);return}throw Error(`No valid theme loader registered for "${e}"`)}function vW(e,t){if(t.name!==e)throw Error(`resolvedTheme: themeName: ${e} does not match theme.name: ${t.name}`)}async function yW(e){_W(e);let t=await YU.resolveTheme(e);return vW(e,t),t}function bW(e){return YU.getResolvedTheme(e)??yW(e)}var xW;async function SW({themes:e,langs:t,preferredHighlighter:n=`shiki-js`}){xW??=aB({themes:[],langs:[`text`],engine:n===`shiki-wasm`?QI(D(()=>import(`./wasm-BnjxR4X6.js`),[])):FU()});let r=wW(xW)?await xW:xW;xW=r;let i=[];for(let e of t){if(e===`text`||e===`ansi`)continue;let t=LU(e);`then`in t?i.push(t):fI(t,r)}let a=[];for(let t of e){let e=bW(t);`then`in e?a.push(e):XU(e,xW)}return(i.length>0||a.length>0)&&await Promise.all([Promise.all(i).then(e=>{fI(e,r)}),Promise.all(a).then(e=>{XU(e,r)})]),r}function CW(){if(xW!=null&&!(`then`in xW))return xW}function wW(e=xW){return e!=null&&`then`in e}for(let e of cW.getThemes())YU.registerThemeIfAbsent(e.name,e.load);function TW(e=fM){let t=[];return typeof e==`string`?t.push(e):(t.push(e.dark),t.push(e.light)),t}function EW(e){for(let t of TW(e))if(!RU.has(t))return!1;return!0}function DW(e){return YU.hasResolvedThemes(e)}function OW(e,t){return NM(e.theme,t.theme)&&e.useTokenTransformer===t.useTokenTransformer&&e.tokenizeMaxLineLength===t.tokenizeMaxLineLength}function kW(e,t){return e==null||t==null?e===t:e.startingLine===t.startingLine&&e.totalLines===t.totalLines&&e.bufferBefore===t.bufferBefore&&e.bufferAfter===t.bufferAfter}function AW(e){return B({tagName:`div`,children:[B({tagName:`div`,children:e.annotations?.map(e=>B({tagName:`slot`,properties:{name:e}})),properties:{"data-annotation-content":``}})],properties:{"data-line-annotation":`${e.hunkIndex},${e.lineIndex}`}})}function jW(e){switch(e){case`file`:return`diffs-icon-file-code`;case`change`:return`diffs-icon-symbol-modified`;case`new`:return`diffs-icon-symbol-added`;case`deleted`:return`diffs-icon-symbol-deleted`;case`rename-pure`:case`rename-changed`:return`diffs-icon-symbol-moved`}}function MW({fileOrDiff:e,mode:t,stickyHeader:n}){let r=`type`in e?e:void 0,i={"data-diffs-header":t,"data-change-type":r?.type,"data-sticky":n?``:void 0};return B({tagName:`div`,children:[t===`custom`?B({tagName:`slot`,properties:{name:dM}}):NW({name:e.name,prevName:`prevName`in e?e.prevName:void 0,iconType:r?.type??`file`}),...t===`custom`?[]:[PW(r)]],properties:i})}function NW({name:e,prevName:t,iconType:n}){let r=[B({tagName:`slot`,properties:{name:cM}}),xN({name:jW(n),properties:{"data-change-icon":n}})];return t!=null&&(r.push(B({tagName:`div`,children:[B({tagName:`bdi`,children:[bN(t)]})],properties:{"data-prev-name":``}})),r.push(xN({name:`diffs-icon-arrow-right-short`,properties:{"data-rename-icon":``}}))),r.push(B({tagName:`div`,children:[B({tagName:`bdi`,children:[bN(e)]})],properties:{"data-title":``}})),r.push(B({tagName:`slot`,properties:{name:lM}})),B({tagName:`div`,children:r,properties:{"data-header-content":``}})}function PW(e){let t=[];if(e!=null){let n=0,r=0;for(let t of e.hunks)n+=t.additionLines,r+=t.deletionLines;(r>0||n===0)&&t.push(B({tagName:`span`,children:[bN(`-${r}`)],properties:{"data-deletions-count":``}})),(n>0||r===0)&&t.push(B({tagName:`span`,children:[bN(`+${n}`)],properties:{"data-additions-count":``}}))}return t.push(B({tagName:`slot`,properties:{name:uM}})),B({tagName:`div`,children:t,properties:{"data-metadata":``}})}function FW(e){return B({tagName:`pre`,properties:IW(e)})}function IW({diffIndicators:e,disableBackground:t,disableLineNumbers:n,overflow:r,split:i,totalLines:a,type:o,customProperties:s}){return{...s,"data-diff":o===`diff`?``:void 0,"data-file":o===`file`?``:void 0,"data-diff-type":o===`diff`?i?`split`:`single`:void 0,"data-overflow":r,"data-disable-line-numbers":n?``:void 0,"data-background":t?void 0:``,"data-indicators":e===`bars`||e===`classic`?e:void 0,style:`--diffs-min-number-column-width-default:${`${a}`.length}ch;`}}var LW=new Map,RW=0,zW={"1c":`1c`,abap:`abap`,as:`actionscript-3`,ada:`ada`,adb:`ada`,ads:`ada`,adoc:`asciidoc`,asciidoc:`asciidoc`,"component.html":`angular-html`,"component.ts":`angular-ts`,conf:`nginx`,htaccess:`apache`,cls:`tex`,trigger:`apex`,apl:`apl`,applescript:`applescript`,scpt:`applescript`,ara:`ara`,asm:`asm`,s:`riscv`,astro:`astro`,awk:`awk`,bal:`ballerina`,sh:`zsh`,bash:`zsh`,bat:`cmd`,cmd:`cmd`,be:`berry`,beancount:`beancount`,bib:`bibtex`,bicep:`bicep`,"blade.php":`blade`,bsl:`bsl`,c:`c`,h:`objective-cpp`,cs:`csharp`,cpp:`cpp`,hpp:`cpp`,cc:`cpp`,cxx:`cpp`,hh:`cpp`,cdc:`cdc`,cairo:`cairo`,clar:`clarity`,clj:`clojure`,cljs:`clojure`,cljc:`clojure`,soy:`soy`,cmake:`cmake`,"CMakeLists.txt":`cmake`,cob:`cobol`,cbl:`cobol`,cobol:`cobol`,CODEOWNERS:`codeowners`,ql:`ql`,coffee:`coffeescript`,lisp:`lisp`,cl:`lisp`,lsp:`lisp`,log:`log`,v:`verilog`,cql:`cql`,cr:`crystal`,css:`css`,csv:`csv`,cue:`cue`,cypher:`cypher`,cyp:`cypher`,d:`d`,dart:`dart`,dax:`dax`,desktop:`desktop`,diff:`diff`,patch:`diff`,Dockerfile:`dockerfile`,dockerfile:`dockerfile`,env:`dotenv`,dm:`dream-maker`,edge:`edge`,el:`emacs-lisp`,ex:`elixir`,exs:`elixir`,elm:`elm`,erb:`erb`,erl:`erlang`,hrl:`erlang`,f:`fortran-fixed-form`,for:`fortran-fixed-form`,fs:`fsharp`,fsi:`fsharp`,fsx:`fsharp`,f03:`f03`,f08:`f08`,f18:`f18`,f77:`f77`,f90:`fortran-free-form`,f95:`fortran-free-form`,fnl:`fennel`,fish:`fish`,ftl:`ftl`,tres:`gdresource`,res:`gdresource`,gd:`gdscript`,gdshader:`gdshader`,gs:`genie`,feature:`gherkin`,COMMIT_EDITMSG:`git-commit`,"git-rebase-todo":`git-rebase`,gjs:`glimmer-js`,gleam:`gleam`,gts:`glimmer-ts`,glsl:`glsl`,vert:`glsl`,frag:`glsl`,shader:`shaderlab`,gp:`gnuplot`,plt:`gnuplot`,gnuplot:`gnuplot`,go:`go`,graphql:`graphql`,gql:`graphql`,groovy:`groovy`,gvy:`groovy`,hack:`hack`,haml:`haml`,hbs:`handlebars`,handlebars:`handlebars`,hs:`haskell`,lhs:`haskell`,hx:`haxe`,hcl:`hcl`,hjson:`hjson`,hlsl:`hlsl`,fx:`hlsl`,html:`html`,htm:`html`,http:`http`,rest:`http`,hxml:`hxml`,hy:`hy`,imba:`imba`,ini:`ini`,cfg:`ini`,jade:`pug`,pug:`pug`,java:`java`,js:`javascript`,mjs:`javascript`,cjs:`javascript`,jinja:`jinja`,jinja2:`jinja`,j2:`jinja`,jison:`jison`,jl:`julia`,json:`json`,json5:`json5`,jsonc:`jsonc`,jsonl:`jsonl`,jsonnet:`jsonnet`,libsonnet:`jsonnet`,jssm:`jssm`,jsx:`jsx`,kt:`kotlin`,kts:`kts`,kql:`kusto`,tex:`tex`,ltx:`tex`,lean:`lean4`,less:`less`,liquid:`liquid`,lit:`lit`,ll:`llvm`,logo:`logo`,lua:`lua`,luau:`luau`,Makefile:`makefile`,mk:`makefile`,makefile:`makefile`,md:`markdown`,markdown:`markdown`,marko:`marko`,m:`wolfram`,mat:`matlab`,mdc:`mdc`,mdx:`mdx`,wiki:`wikitext`,mediawiki:`wikitext`,mmd:`mermaid`,mermaid:`mermaid`,mips:`mipsasm`,mojo:`mojo`,"🔥":`mojo`,move:`move`,nar:`narrat`,nf:`nextflow`,nim:`nim`,nims:`nim`,nimble:`nim`,nix:`nix`,nu:`nushell`,mm:`objective-cpp`,ml:`ocaml`,mli:`ocaml`,mll:`ocaml`,mly:`ocaml`,pas:`pascal`,p:`pascal`,pl:`prolog`,pm:`perl`,t:`perl`,raku:`raku`,p6:`raku`,pl6:`raku`,php:`php`,phtml:`php`,pls:`plsql`,sql:`sql`,po:`po`,polar:`polar`,pcss:`postcss`,pot:`pot`,potx:`potx`,pq:`powerquery`,pqm:`powerquery`,ps1:`powershell`,psm1:`powershell`,psd1:`powershell`,prisma:`prisma`,pro:`prolog`,P:`prolog`,properties:`properties`,proto:`protobuf`,pp:`puppet`,purs:`purescript`,py:`python`,pyw:`python`,pyi:`python`,qml:`qml`,qmldir:`qmldir`,qss:`qss`,r:`r`,R:`r`,rkt:`racket`,rktl:`racket`,razor:`razor`,cshtml:`razor`,rb:`ruby`,rbw:`ruby`,reg:`reg`,regex:`regexp`,rel:`rel`,rs:`rust`,rst:`rst`,rake:`ruby`,gemspec:`ruby`,jbuilder:`ruby`,builder:`ruby`,rabl:`ruby`,arb:`ruby`,ru:`ruby`,podspec:`ruby`,Gemfile:`ruby`,Rakefile:`ruby`,Guardfile:`ruby`,Capfile:`ruby`,Berksfile:`ruby`,Brewfile:`ruby`,Vagrantfile:`ruby`,Thorfile:`ruby`,Appraisals:`ruby`,Dangerfile:`ruby`,sas:`sas`,sass:`sass`,scala:`scala`,sc:`scala`,scm:`scheme`,ss:`scheme`,sld:`scheme`,scss:`scss`,sdbl:`sdbl`,shadergraph:`shader`,st:`smalltalk`,sol:`solidity`,sparql:`sparql`,rq:`sparql`,spl:`splunk`,config:`ssh-config`,do:`stata`,ado:`stata`,dta:`stata`,styl:`stylus`,stylus:`stylus`,svelte:`svelte`,swift:`swift`,sv:`system-verilog`,svh:`system-verilog`,service:`systemd`,socket:`systemd`,device:`systemd`,timer:`systemd`,talon:`talonscript`,tasl:`tasl`,tcl:`tcl`,templ:`templ`,tf:`tf`,tfvars:`tfvars`,toml:`toml`,ts:`typescript`,mts:`typescript`,cts:`typescript`,tsp:`typespec`,tsv:`tsv`,tsx:`tsx`,ttl:`turtle`,twig:`twig`,typ:`typst`,vv:`v`,vala:`vala`,vapi:`vala`,vb:`vb`,vbs:`vb`,bas:`vb`,vh:`verilog`,vhd:`vhdl`,vhdl:`vhdl`,vim:`vimscript`,vue:`vue`,"vine.ts":`vue-vine`,vy:`vyper`,wasm:`wasm`,wat:`wasm`,wy:`文言`,wgsl:`wgsl`,wit:`wit`,wl:`wolfram`,nb:`wolfram`,xml:`xml`,xsl:`xsl`,xslt:`xsl`,yaml:`yaml`,yml:`yml`,zs:`zenscript`,zig:`zig`,zsh:`zsh`,sty:`tex`};function BW(e){if(LW.has(e))return LW.get(e)??`text`;if(zW[e]!=null)return zW[e];let t=e.match(/\.([^/\\]+\.[^/\\]+)$/);if(t!=null){if(LW.has(t[1]))return LW.get(t[1])??`text`;if(zW[t[1]]!=null)return zW[t[1]]??`text`}let n=e.match(/\.([^.]+)$/)?.[1]??``;return LW.has(n)?LW.get(n)??`text`:zW[n]??`text`}function VW(){return RW}function HW(){return Object.fromEntries(LW)}function UW(e,{theme:t,preferredHighlighter:n=`shiki-js`}){return{langs:[e??`text`],themes:TW(t),preferredHighlighter:n}}function WW(e){return`annotation-${`side`in e?`${e.side}-`:``}${e.lineNumber}`}function GW(e,t,n){let r=typeof n.lineInfo==`function`?n.lineInfo(t):n.lineInfo[t-1];if(r==null){let r=`processLine: line ${t}, contains no state.lineInfo`;throw console.error(r,{node:e,line:t,state:n}),Error(r)}return e.tagName=`div`,e.properties[`data-line`]=r.lineNumber,e.properties[`data-alt-line`]=r.altLineNumber,e.properties[`data-line-type`]=r.type,e.properties[`data-line-index`]=r.lineIndex,e.children.length===0&&e.children.push(bN(`
|
|
185
|
-
`)),e}var
|
|
184
|
+
\v\f
\u2028\u2029])`),t));else if(c===`posix`)if(!i&&(u===`graph`||u===`print`)){if(r===`strict`)throw Error(`POSIX class "${u}" requires min target ES2024 or non-strict accuracy`);let e={graph:`!-~`,print:` -~`}[u];l&&(e=`\0-${Z(e.codePointAt(0)-1)}${Z(e.codePointAt(2)+1)}-\u{10FFFF}`),n($(lU(`[${e}]`),t))}else n($(uU(lU(RH.get(u)),l),t));else if(c===`property`)PH.has(UV(u))||(e.key=`sc`);else if(c===`space`)n(dU(FV(`space`,{negate:l}),t));else if(c===`word`)n($(uU(lU(MH),l),t));else throw Error(`Unexpected character set kind "${c}"`)},Directive({node:e,parent:t,root:n,remove:r,replaceWith:i,removeAllPrevSiblings:a,removeAllNextSiblings:o}){let{kind:s,flags:c}=e;if(s===`flags`)if(!c.enable&&!c.disable)r();else{let e=OV({flags:c});e.body[0].body=o(),i($(e,t),{traverse:!0})}else if(s===`keep`){let e=n.body[0],r=n.body.length===1&&aV(e,{type:`Group`})&&e.body[0].body.length===1?e.body[0]:n;if(t.parent!==r||r.body.length>1)throw Error(Q`Uses "\K" in a way that's unsupported`);let o=kV({behind:!0});o.body[0].body=a(),i($(o,t))}else throw Error(`Unexpected directive kind "${s}"`)},Flags({node:e,parent:t}){if(e.posixIsAscii)throw Error(`Unsupported flag "P"`);if(e.textSegmentMode===`word`)throw Error(`Unsupported flag "y{w}"`);[`digitIsAscii`,`extended`,`posixIsAscii`,`spaceIsAscii`,`wordIsAscii`,`textSegmentMode`].forEach(t=>delete e[t]),Object.assign(e,{global:!1,hasIndices:!1,multiline:!1,sticky:e.sticky??!1}),t.options={disable:{x:!0,n:!0},force:{v:!0}}},Group({node:e}){if(!e.flags)return;let{enable:t,disable:n}=e.flags;t?.extended&&delete t.extended,n?.extended&&delete n.extended,t?.dotAll&&n?.dotAll&&delete t.dotAll,t?.ignoreCase&&n?.ignoreCase&&delete t.ignoreCase,t&&!Object.keys(t).length&&delete e.flags.enable,n&&!Object.keys(n).length&&delete e.flags.disable,!e.flags.enable&&!e.flags.disable&&delete e.flags},LookaroundAssertion({node:e},t){let{kind:n}=e;n===`lookbehind`&&(t.passedLookbehind=!0)},NamedCallout({node:e,parent:t,replaceWith:n}){let{kind:r}=e;if(r===`fail`)n($(kV({negate:!0}),t));else throw Error(`Unsupported named callout "(*${r.toUpperCase()}"`)},Quantifier({node:e}){if(e.body.type===`Quantifier`){let t=OV();t.body[0].body.push(e.body),e.body=$(t,e)}},Regex:{enter({node:e},{supportedGNodes:t}){let n=[],r=!1,i=!1;for(let t of e.body)if(t.body.length===1&&t.body[0].kind===`search_start`)t.body.pop();else{let e=rU(t.body);e?(r=!0,Array.isArray(e)?n.push(...e):n.push(e)):i=!0}r&&!i&&n.forEach(e=>t.add(e))},exit(e,{accuracy:t,passedLookbehind:n,strategy:r}){if(t===`strict`&&n&&r)throw Error(Q`Uses "\G" in a way that requires non-strict accuracy`)}},Subroutine({node:e},{jsGroupNameMap:t}){let{ref:n}=e;typeof n==`string`&&!cU(n)&&(n=$H(n,t),e.ref=n)}},GH={Backreference({node:e},{multiplexCapturesToLeftByRef:t,reffedNodesByReferencer:n}){let{orphan:r,ref:i}=e;r||n.set(e,[...t.get(i).map(({node:e})=>e)])},CapturingGroup:{enter({node:e,parent:t,replaceWith:n,skip:r},{groupOriginByCopy:i,groupsByName:a,multiplexCapturesToLeftByRef:o,openRefs:s,reffedNodesByReferencer:c}){let l=i.get(e);if(l&&s.has(e.number)){let r=dU(ZH(e.number),t);c.set(r,s.get(e.number)),n(r);return}s.set(e.number,e),o.set(e.number,[]),e.name&&wH(o,e.name,[]);let u=o.get(e.name??e.number);for(let t=0;t<u.length;t++){let n=u[t];if(l===n.node||l&&l===n.origin||e===n.origin){u.splice(t,1);break}}if(o.get(e.number).push({node:e,origin:l}),e.name&&o.get(e.name).push({node:e,origin:l}),e.name){let t=wH(a,e.name,new Map),n=!1;if(l)n=!0;else for(let e of t.values())if(!e.hasDuplicateNameToRemove){n=!0;break}a.get(e.name).set(e,{node:e,hasDuplicateNameToRemove:n})}},exit({node:e},{openRefs:t}){t.delete(e.number)}},Group:{enter({node:e},t){t.prevFlags=t.currentFlags,e.flags&&(t.currentFlags=CH(t.currentFlags,e.flags))},exit(e,t){t.currentFlags=t.prevFlags}},Subroutine({node:e,parent:t,replaceWith:n},r){let{isRecursive:i,ref:a}=e;if(i){let n=t;for(;(n=n.parent)&&(n.type!==`CapturingGroup`||n.name!==a&&n.number!==a););r.reffedNodesByReferencer.set(e,n);return}let o=r.subroutineRefMap.get(a),s=a===0,c=s?ZH(0):XH(o,r.groupOriginByCopy,null),l=c;if(!s){let e=eU(QH(o,e=>e.type===`Group`&&!!e.flags)),t=e?CH(r.globalFlags,e):r.globalFlags;JH(t,r.currentFlags)||(l=OV({flags:tU(t)}),l.body[0].body.push(c))}n($(l,t),{traverse:!s})}},KH={Backreference({node:e,parent:t,replaceWith:n},r){if(e.orphan){r.highestOrphanBackref=Math.max(r.highestOrphanBackref,e.ref);return}let i=r.reffedNodesByReferencer.get(e).filter(t=>YH(t,e));i.length?i.length>1?n($(OV({atomic:!0,body:i.reverse().map(e=>vV({body:[bV(e.number)]}))}),t)):e.ref=i[0].number:n($(kV({negate:!0}),t))},CapturingGroup({node:e},t){e.number=++t.numCapturesToLeft,e.name&&t.groupsByName.get(e.name).get(e).hasDuplicateNameToRemove&&delete e.name},Regex:{exit({node:e},t){let n=Math.max(t.highestOrphanBackref-t.numCapturesToLeft,0);for(let t=0;t<n;t++){let t=xV();e.body.at(-1).body.push(t)}}},Subroutine({node:e},t){!e.isRecursive||e.ref===0||(e.ref=t.reffedNodesByReferencer.get(e).number)}};function qH(e){KV(e,{"*"({node:e,parent:t}){e.parent=t}})}function JH(e,t){return e.dotAll===t.dotAll&&e.ignoreCase===t.ignoreCase}function YH(e,t){let n=t;do{if(n.type===`Regex`)return!1;if(n.type===`Alternative`)continue;if(n===e)return!1;let t=nU(n.parent);for(let r of t){if(r===n)break;if(r===e||iU(r,e))return!0}}while(n=n.parent);throw Error(`Unexpected path`)}function XH(e,t,n,r){let i=Array.isArray(e)?[]:{};for(let[a,o]of Object.entries(e))a===`parent`?i.parent=Array.isArray(n)?r:n:o&&typeof o==`object`?i[a]=XH(o,t,i,n):(a===`type`&&o===`CapturingGroup`&&t.set(i,t.get(e)??e),i[a]=o);return i}function ZH(e){let t=PV(e);return t.isRecursive=!0,t}function QH(e,t){let n=[];for(;e=e.parent;)(!t||t(e))&&n.push(e);return n}function $H(e,t){if(t.has(e))return t.get(e);let n=`$${t.size}_${e.replace(/^[^$_\p{IDS}]|[^$\u200C\u200D\p{IDC}]/gu,`_`)}`;return t.set(e,n),n}function eU(e){let t=[`dotAll`,`ignoreCase`],n={enable:{},disable:{}};return e.forEach(({flags:e})=>{t.forEach(t=>{e.enable?.[t]&&(delete n.disable[t],n.enable[t]=!0),e.disable?.[t]&&(n.disable[t]=!0)})}),Object.keys(n.enable).length||delete n.enable,Object.keys(n.disable).length||delete n.disable,n.enable||n.disable?n:null}function tU({dotAll:e,ignoreCase:t}){let n={};return(e||t)&&(n.enable={},e&&(n.enable.dotAll=!0),t&&(n.enable.ignoreCase=!0)),(!e||!t)&&(n.disable={},!e&&(n.disable.dotAll=!0),!t&&(n.disable.ignoreCase=!0)),n}function nU(e){if(!e)throw Error(`Node expected`);let{body:t}=e;return Array.isArray(t)?t:t?[t]:null}function rU(e){let t=e.find(e=>e.kind===`search_start`||sU(e,{negate:!1})||!aU(e));if(!t)return null;if(t.kind===`search_start`)return t;if(t.type===`LookaroundAssertion`)return t.body[0].body[0];if(t.type===`CapturingGroup`||t.type===`Group`){let e=[];for(let n of t.body){let t=rU(n.body);if(!t)return null;Array.isArray(t)?e.push(...t):e.push(t)}return e}return null}function iU(e,t){let n=nU(e)??[];for(let e of n)if(e===t||iU(e,t))return!0;return!1}function aU({type:e}){return e===`Assertion`||e===`Directive`||e===`LookaroundAssertion`}function oU(e){let t=[`Character`,`CharacterClass`,`CharacterSet`];return t.includes(e.type)||e.type===`Quantifier`&&e.min&&t.includes(e.body.type)}function sU(e,t){let n={negate:null,...t};return e.type===`LookaroundAssertion`&&(n.negate===null||e.negate===n.negate)&&e.body.length===1&&aV(e.body[0],{type:`Assertion`,kind:`search_start`})}function cU(e){return/^[$_\p{IDS}][$\u200C\u200D\p{IDC}]*$/u.test(e)}function lU(e,t){let n=cV(e,{...t,unicodePropertyMap:PH}).body;return n.length>1||n[0].body.length>1?OV({body:n}):n[0].body[0]}function uU(e,t){return e.negate=t,e}function dU(e,t){return e.parent=t,e}function $(e,t){return qH(e),e.parent=t,e}function fU(e,t){let n=kH(t),r=TH(n.target,`ES2024`),i=TH(n.target,`ES2025`),a=n.rules.recursionLimit;if(!Number.isInteger(a)||a<2||a>20)throw Error(`Invalid recursionLimit; use 2-20`);let o=null,s=null;if(!i){let t=[e.flags.ignoreCase];KV(e,pU,{getCurrentModI:()=>t.at(-1),popModI(){t.pop()},pushModI(e){t.push(e)},setHasCasedChar(){t.at(-1)?o=!0:s=!0}})}let c={dotAll:e.flags.dotAll,ignoreCase:!!((e.flags.ignoreCase||o)&&!s)},l=e,u={accuracy:n.accuracy,appliedGlobalFlags:c,captureMap:new Map,currentFlags:{dotAll:e.flags.dotAll,ignoreCase:e.flags.ignoreCase},inCharClass:!1,lastNode:l,originMap:e._originMap,recursionLimit:a,useAppliedIgnoreCase:!!(!i&&o&&s),useFlagMods:i,useFlagV:r,verbose:n.verbose};function d(e){return u.lastNode=l,l=e,EH(mU[e.type],`Unexpected node type "${e.type}"`)(e,u,d)}let f={pattern:e.body.map(d).join(`|`),flags:d(e.flags),options:{...e.options}};return r||(delete f.options.force.v,f.options.disable.v=!0,f.options.unicodeSetsPlugin=null),f._captureTransfers=new Map,f._hiddenCaptures=[],u.captureMap.forEach((e,t)=>{e.hidden&&f._hiddenCaptures.push(t),e.transferTo&&wH(f._captureTransfers,e.transferTo,[]).push(t)}),f}var pU={"*":{enter({node:e},t){if(EU(e)){let n=t.getCurrentModI();t.pushModI(e.flags?CH({ignoreCase:n},e.flags).ignoreCase:n)}},exit({node:e},t){EU(e)&&t.popModI()}},Backreference(e,t){t.setHasCasedChar()},Character({node:e},t){bU(Z(e.value))&&t.setHasCasedChar()},CharacterClassRange({node:e,skip:t},n){t(),xU(e,{firstOnly:!0}).length&&n.setHasCasedChar()},CharacterSet({node:e},t){e.kind===`property`&&HH.has(e.value)&&t.setHasCasedChar()}},mU={Alternative({body:e},t,n){return e.map(n).join(``)},Assertion({kind:e,negate:t}){if(e===`string_end`)return`$`;if(e===`string_start`)return`^`;if(e===`word_boundary`)return t?Q`\B`:Q`\b`;throw Error(`Unexpected assertion kind "${e}"`)},Backreference({ref:e},t){if(typeof e!=`number`)throw Error(`Unexpected named backref in transformed AST`);if(!t.useFlagMods&&t.accuracy===`strict`&&t.currentFlags.ignoreCase&&!t.captureMap.get(e).ignoreCase)throw Error(`Use of case-insensitive backref to case-sensitive group requires target ES2025 or non-strict accuracy`);return`\\`+e},CapturingGroup(e,t,n){let{body:r,name:i,number:a}=e,o={ignoreCase:t.currentFlags.ignoreCase},s=t.originMap.get(e);return s&&(o.hidden=!0,a>s.number&&(o.transferTo=s.number)),t.captureMap.set(a,o),`(${i?`?<${i}>`:``}${r.map(n).join(`|`)})`},Character({value:e},t){let n=Z(e),r=SU(e,{escDigit:t.lastNode.type===`Backreference`,inCharClass:t.inCharClass,useFlagV:t.useFlagV});if(r!==n)return r;if(t.useAppliedIgnoreCase&&t.currentFlags.ignoreCase&&bU(n)){let e=NH(n);return t.inCharClass?e.join(``):e.length>1?`[${e.join(``)}]`:e[0]}return n},CharacterClass(e,t,n){let{kind:r,negate:i,parent:a}=e,{body:o}=e;if(r===`intersection`&&!t.useFlagV)throw Error(`Use of character class intersection requires min target ES2024`);xH.bugFlagVLiteralHyphenIsRange&&t.useFlagV&&o.some(OU)&&(o=[SV(45),...o.filter(e=>!OU(e))]);let s=()=>`[${i?`^`:``}${o.map(n).join(r===`intersection`?`&&`:``)}]`;if(!t.inCharClass){if((!t.useFlagV||xH.bugNestedClassIgnoresNegation)&&!i){let t=o.filter(e=>e.type===`CharacterClass`&&e.kind===`union`&&e.negate);if(t.length){let r=OV(),i=r.body[0];return r.parent=a,i.parent=r,o=o.filter(e=>!t.includes(e)),e.body=o,o.length?(e.parent=i,i.body.push(e)):r.body.pop(),t.forEach(e=>{let t=vV({body:[e]});e.parent=t,t.parent=r,r.body.push(t)}),n(r)}}t.inCharClass=!0;let r=s();return t.inCharClass=!1,r}let c=o[0];if(r===`union`&&!i&&c&&((!t.useFlagV||!t.verbose)&&a.kind===`union`&&!(xH.bugFlagVLiteralHyphenIsRange&&t.useFlagV)||!t.verbose&&a.kind===`intersection`&&o.length===1&&c.type!==`CharacterClassRange`))return o.map(n).join(``);if(!t.useFlagV&&a.type===`CharacterClass`)throw Error(`Uses nested character class in a way that requires min target ES2024`);return s()},CharacterClassRange(e,t){let n=e.min.value,r=e.max.value,i={escDigit:!1,inCharClass:!0,useFlagV:t.useFlagV},a=SU(n,i),o=SU(r,i),s=new Set;return t.useAppliedIgnoreCase&&t.currentFlags.ignoreCase&&CU(xU(e)).forEach(e=>{s.add(Array.isArray(e)?`${SU(e[0],i)}-${SU(e[1],i)}`:SU(e,i))}),`${a}-${o}${[...s].join(``)}`},CharacterSet({kind:e,negate:t,value:n,key:r},i){if(e===`dot`)return i.currentFlags.dotAll?i.appliedGlobalFlags.dotAll||i.useFlagMods?`.`:`[^]`:Q`[^\n]`;if(e===`digit`)return t?Q`\D`:Q`\d`;if(e===`property`){if(i.useAppliedIgnoreCase&&i.currentFlags.ignoreCase&&HH.has(n))throw Error(`Unicode property "${n}" can't be case-insensitive when other chars have specific case`);return`${t?Q`\P`:Q`\p`}{${r?`${r}=`:``}${n}}`}if(e===`word`)return t?Q`\W`:Q`\w`;throw Error(`Unexpected character set kind "${e}"`)},Flags(e,t){return(t.appliedGlobalFlags.ignoreCase?`i`:``)+(e.dotAll?`s`:``)+(e.sticky?`y`:``)},Group({atomic:e,body:t,flags:n,parent:r},i,a){let o=i.currentFlags;n&&(i.currentFlags=CH(o,n));let s=t.map(a).join(`|`),c=!i.verbose&&t.length===1&&r.type!==`Quantifier`&&!e&&(!i.useFlagMods||!n)?s:`(?${wU(e,n,i.useFlagMods)}${s})`;return i.currentFlags=o,c},LookaroundAssertion({body:e,kind:t,negate:n},r,i){return`(?${`${t===`lookahead`?``:`<`}${n?`!`:`=`}`}${e.map(i).join(`|`)})`},Quantifier(e,t,n){return n(e.body)+TU(e)},Subroutine({isRecursive:e,ref:t},n){if(!e)throw Error(`Unexpected non-recursive subroutine in transformed AST`);let r=n.recursionLimit;return t===0?`(?R=${r})`:Q`\g<${t}&R=${r}>`}},hU=new Set([`$`,`(`,`)`,`*`,`+`,`.`,`?`,`[`,`\\`,`]`,`^`,`{`,`|`,`}`]),gU=new Set([`-`,`\\`,`]`,`^`,`[`]),_U=new Set("()-/[\\]^{|}!#$%&*+,.:;<=>?@`~".split(``)),vU=new Map([[9,Q`\t`],[10,Q`\n`],[11,Q`\v`],[12,Q`\f`],[13,Q`\r`],[8232,Q`\u2028`],[8233,Q`\u2029`],[65279,Q`\uFEFF`]]),yU=/^\p{Cased}$/u;function bU(e){return yU.test(e)}function xU(e,t){let n=!!t?.firstOnly,r=e.min.value,i=e.max.value,a=[];if(r<65&&(i===65535||i>=131071)||r===65536&&i>=131071)return a;for(let e=r;e<=i;e++){let t=Z(e);if(!bU(t))continue;let o=NH(t).filter(e=>{let t=e.codePointAt(0);return t<r||t>i});if(o.length&&(a.push(...o),n))break}return a}function SU(e,{escDigit:t,inCharClass:n,useFlagV:r}){if(vU.has(e))return vU.get(e);if(e<32||e>126&&e<160||e>262143||t&&DU(e))return e>255?`\\u{${e.toString(16).toUpperCase()}}`:`\\x${e.toString(16).toUpperCase().padStart(2,`0`)}`;let i=n?r?_U:gU:hU,a=Z(e);return(i.has(a)?`\\`:``)+a}function CU(e){let t=e.map(e=>e.codePointAt(0)).sort((e,t)=>e-t),n=[],r=null;for(let e=0;e<t.length;e++)t[e+1]===t[e]+1?r??=t[e]:r===null?n.push(t[e]):(n.push([r,t[e]]),r=null);return n}function wU(e,t,n){if(e)return`>`;let r=``;if(t&&n){let{enable:e,disable:n}=t;r=(e?.ignoreCase?`i`:``)+(e?.dotAll?`s`:``)+(n?`-`:``)+(n?.ignoreCase?`i`:``)+(n?.dotAll?`s`:``)}return`${r}:`}function TU({kind:e,max:t,min:n}){let r;return r=!n&&t===1?`?`:!n&&t===1/0?`*`:n===1&&t===1/0?`+`:n===t?`{${n}}`:`{${n},${t===1/0?``:t}}`,r+{greedy:``,lazy:`?`,possessive:`+`}[e]}function EU({type:e}){return e===`CapturingGroup`||e===`Group`||e===`LookaroundAssertion`}function DU(e){return e>47&&e<58}function OU({type:e,value:t}){return e===`Character`&&t===45}var kU=class e extends RegExp{#e=new Map;#t=null;#n;#r=null;#i=null;rawOptions={};get source(){return this.#n||`(?:)`}constructor(t,n,r){let i=!!r?.lazyCompile;if(t instanceof RegExp){if(r)throw Error(`Cannot provide options when copying a regexp`);let i=t;super(i,n),this.#n=i.source,i instanceof e&&(this.#e=i.#e,this.#r=i.#r,this.#i=i.#i,this.rawOptions=i.rawOptions)}else{let e={hiddenCaptures:[],strategy:null,transfers:[],...r};super(i?``:t,n),this.#n=t,this.#e=jU(e.hiddenCaptures,e.transfers),this.#i=e.strategy,this.rawOptions=r??{}}i||(this.#t=this)}exec(t){if(!this.#t){let{lazyCompile:t,...n}=this.rawOptions;this.#t=new e(this.#n,this.flags,n)}let n=this.global||this.sticky,r=this.lastIndex;if(this.#i===`clip_search`&&n&&r){this.lastIndex=0;let e=this.#a(t.slice(r));return e&&(AU(e,r,t,this.hasIndices),this.lastIndex+=r),e}return this.#a(t)}#a(e){this.#t.lastIndex=this.lastIndex;let t=super.exec.call(this.#t,e);if(this.lastIndex=this.#t.lastIndex,!t||!this.#e.size)return t;let n=[...t];t.length=1;let r;this.hasIndices&&(r=[...t.indices],t.indices.length=1);let i=[0];for(let e=1;e<n.length;e++){let{hidden:a,transferTo:o}=this.#e.get(e)??{};if(a?i.push(null):(i.push(t.length),t.push(n[e]),this.hasIndices&&t.indices.push(r[e])),o&&n[e]!==void 0){let a=i[o];if(!a)throw Error(`Invalid capture transfer to "${a}"`);if(t[a]=n[e],this.hasIndices&&(t.indices[a]=r[e]),t.groups){this.#r||=MU(this.source);let i=this.#r.get(o);i&&(t.groups[i]=n[e],this.hasIndices&&(t.indices.groups[i]=r[e]))}}}return t}};function AU(e,t,n,r){if(e.index+=t,e.input=n,r){let n=e.indices;for(let e=0;e<n.length;e++){let r=n[e];r&&(n[e]=[r[0]+t,r[1]+t])}let r=n.groups;r&&Object.keys(r).forEach(e=>{let n=r[e];n&&(r[e]=[n[0]+t,n[1]+t])})}}function jU(e,t){let n=new Map;for(let t of e)n.set(t,{hidden:!0});for(let[e,r]of t)for(let t of r)wH(n,t,{}).transferTo=e;return n}function MU(e){let t=/(?<capture>\((?:\?<(?![=!])(?<name>[^>]+)>|(?!\?)))|\\?./gsu,n=new Map,r=0,i=0,a;for(;a=t.exec(e);){let{0:e,groups:{capture:t,name:o}}=a;e===`[`?r++:r?e===`]`&&r--:t&&(i++,o&&n.set(i,o))}return n}function NU(e,t){let n=PU(e,t);return n.options?new kU(n.pattern,n.flags,n.options):new RegExp(n.pattern,n.flags)}function PU(e,t){let n=kH(t),r=UH(cV(e,{flags:n.flags,normalizeUnknownPropertyNames:!0,rules:{captureGroup:n.rules.captureGroup,singleline:n.rules.singleline},skipBackrefValidation:n.rules.allowOrphanBackrefs,unicodePropertyMap:PH}),{accuracy:n.accuracy,asciiWordBoundaries:n.rules.asciiWordBoundaries,avoidSubclass:n.avoidSubclass,bestEffortTarget:n.target}),i=fU(r,n),a=hH(i.pattern,{captureTransfers:i._captureTransfers,hiddenCaptures:i._hiddenCaptures,mode:`external`}),o=aH(cH(a.pattern).pattern,{captureTransfers:a.captureTransfers,hiddenCaptures:a.hiddenCaptures}),s={pattern:o.pattern,flags:`${n.hasIndices?`d`:``}${n.global?`g`:``}${i.flags}${i.options.disable.v?`u`:`v`}`};if(n.avoidSubclass){if(n.lazyCompileLength!==1/0)throw Error(`Lazy compilation requires subclass`)}else{let e=o.hiddenCaptures.sort((e,t)=>e-t),t=Array.from(o.captureTransfers),i=r._strategy,a=s.pattern.length>=n.lazyCompileLength;(e.length||t.length||i||a)&&(s.options={...e.length&&{hiddenCaptures:e},...t.length&&{transfers:t},...i&&{strategy:i},...a&&{lazyCompile:a}})}return s}function FU(e,t){return NU(e,{global:!0,hasIndices:!0,lazyCompileLength:3e3,rules:{allowOrphanBackrefs:!0,asciiWordBoundaries:!0,captureGroup:!0,recursionLimit:5,singleline:!0},...t})}function IU(e={}){let t=Object.assign({target:`auto`,cache:new Map},e);return t.regexConstructor||=e=>FU(e,{target:t.target}),{createScanner(e){return new hB(e,t)},createString(e){return{content:e}}}}async function LU(e){if(mI())throw Error(`resolveLanguage("${e}") cannot be called from a worker context. Languages must be pre-resolved on the main thread and passed to the worker via the resolvedLanguages parameter.`);let t=lI.get(e);if(t!=null)return t;try{let t=uI.get(e);if(t==null&&Object.prototype.hasOwnProperty.call(TI,e)&&(t=TI[e]),t==null)throw Error(`resolveLanguage: "${e}" not found in bundled or custom languages`);let n=t().then(({default:t})=>{let n={name:e,data:t};return cI.has(e)||cI.set(e,n),n});return lI.set(e,n),await n}finally{lI.delete(e)}}function RU(e){return cI.get(e)??LU(e)}var zU=new Set;function BU(e){let t=[],n=new Set;for(let r of VU(e.themes)){let e=WU(r)?r.getThemes():[r];for(let r of e){if(n.has(r.name))throw Error(`Theme collection already contains theme "${r.name}"`);n.add(r.name),t.push(r)}}let r=Object.freeze([...t]),i=Object.freeze(r.filter(e=>e.colorScheme===`light`)),a=Object.freeze(r.filter(e=>e.colorScheme===`dark`)),o=new Map(r.map(e=>[e.name,e])),s=Object.freeze(r.map(e=>e.name)),c=Object.freeze(i.map(e=>e.name)),l=Object.freeze(a.map(e=>e.name));function u(e){if(e==null)return r;let{colorScheme:t,collection:n}=e;return n==null?t===`light`?i:t===`dark`?a:r:r.filter(e=>e.collection===n?t==null||e.colorScheme===t:!1)}return{getTheme(e){return o.get(e)},getThemes(e){return u(e)},getThemeNames(e){return e?.collection==null?e?.colorScheme===`light`?c:e?.colorScheme===`dark`?l:s:u(e).map(e=>e.name)},hasTheme(e){return o.has(e)},orderBy(e){return BU({themes:r.map((e,t)=>({descriptor:e,index:t})).sort((t,n)=>{let r=e(t.descriptor,n.descriptor);return r===0?t.index-n.index:r}).map(e=>e.descriptor)})},pick(e){let t=[],n=new Set;for(let r of e){if(n.has(r))throw Error(`Theme collection pick already includes theme "${r}"`);n.add(r);let e=o.get(r);if(e==null)throw Error(`Theme collection does not contain theme "${r}"`);t.push(e)}return BU({themes:t})},registerInto(e){for(let t of r)e.registerThemeIfAbsent(t.name,t.load)}}}function VU(e){return HU(e)?[e]:e}function HU(e){return WU(e)||UU(e)}function UU(e){return typeof e.name==`string`&&typeof e.load==`function`}function WU(e){return typeof e.getThemes==`function`}function GU(e){return typeof e==`object`&&e&&`default`in e?e.default:e}var KU=class extends Error{constructor(e){super(`Theme "${e}" is already registered`),this.name=`DuplicateThemeError`}},qU=class extends Error{constructor(e){super(`No loader registered for theme "${e}"`),this.name=`UnregisteredThemeError`}},JU=class extends Error{constructor(e){super(`Theme "${e}" has not been resolved`),this.name=`UnresolvedThemeError`}};function YU(){let e=new Map,t=new Map,n=new Map,r=0;function i(t,n){if(e.has(t))throw new KU(t);e.set(t,n)}function a(t,n){return!e.has(t)&&(e.set(t,n),!0)}function o(t){return e.has(t)}function s(i){let a=t.get(i);if(a!==void 0)return Promise.resolve(a);let o=n.get(i);if(o!==void 0)return o;let s=e.get(i);if(s===void 0)return Promise.reject(new qU(i));let c=r,l=s().then(e=>{let a=GU(e);return c===r&&t.set(i,a),n.get(i)===l&&n.delete(i),a}).catch(e=>{throw n.get(i)===l&&n.delete(i),e});return n.set(i,l),l}function c(e){return Promise.all(e.map(e=>s(e)))}function l(e,n){t.set(e,n)}function u(e){for(let[t,n]of e)l(t,n)}function d(e){return t.get(e)}function f(e){let n=[];for(let r of e){let e=t.get(r);if(e===void 0)throw new JU(r);n.push(e)}return n}function p(e){return t.has(e)}function m(e){for(let n of e)if(!t.has(n))return!1;return!0}function h(e){let n=t.get(e);return n===void 0?s(e):n}function g(){r++,t.clear(),n.clear()}return{clearResolvedThemes:g,getResolvedOrResolveTheme:h,getResolvedTheme:d,getResolvedThemes:f,hasRegisteredTheme:o,hasResolvedTheme:p,hasResolvedThemes:m,registerTheme:i,registerThemeIfAbsent:a,resolveTheme:s,resolveThemes:c,seedResolvedTheme:l,seedResolvedThemes:u}}var XU=YU();function ZU(e,t){e=Array.isArray(e)?e:[e];for(let n of e){let e;if(typeof n==`string`){if(e=XU.getResolvedTheme(n),e==null)throw Error(`loadResolvedThemes: ${n} is not resolved, you must resolve it before calling loadResolvedThemes`)}else e=n,n=n.name,XU.getResolvedTheme(n)??XU.seedResolvedTheme(n,e);zU.has(n)||(zU.add(n),t.loadThemeSync(e))}}function QU({name:e,load:t,colorScheme:n,collection:r,displayName:i}){return{name:e,colorScheme:n,collection:r,displayName:i,load:$U(t)}}function $U(e){return async()=>qR(GU(await e()))}var eW=`pierre`,tW=[`pierre-dark`,`pierre-dark-soft`,`pierre-dark-vibrant`,`pierre-dark-protanopia-deuteranopia`,`pierre-dark-tritanopia`],nW=[`pierre-light`,`pierre-light-soft`,`pierre-light-vibrant`,`pierre-light-protanopia-deuteranopia`,`pierre-light-tritanopia`],rW=[...nW,...tW],iW=new Set(nW);function aW(e){return iW.has(e)?`light`:`dark`}var oW={"pierre-dark":`Pierre Dark`,"pierre-dark-soft":`Pierre Dark Soft`,"pierre-dark-vibrant":`Pierre Dark Vibrant`,"pierre-dark-protanopia-deuteranopia":`Pierre Dark Protanopia & Deuteranopia`,"pierre-dark-tritanopia":`Pierre Dark Tritanopia`,"pierre-light":`Pierre Light`,"pierre-light-soft":`Pierre Light Soft`,"pierre-light-vibrant":`Pierre Light Vibrant`,"pierre-light-protanopia-deuteranopia":`Pierre Light Protanopia & Deuteranopia`,"pierre-light-tritanopia":`Pierre Light Tritanopia`},sW={"pierre-dark":()=>D(()=>import(`./pierre-dark-CpLgRqie.js`),[]),"pierre-dark-soft":()=>D(()=>import(`./pierre-dark-soft-kZQmAZld.js`),[]),"pierre-dark-vibrant":()=>D(()=>import(`./pierre-dark-vibrant-CpQYzh95.js`),[]),"pierre-dark-protanopia-deuteranopia":()=>D(()=>import(`./pierre-dark-protanopia-deuteranopia-B35FxJx-.js`),[]),"pierre-dark-tritanopia":()=>D(()=>import(`./pierre-dark-tritanopia-CpjhbsIL.js`),[]),"pierre-light":()=>D(()=>import(`./pierre-light-CoaEpmwp.js`),[]),"pierre-light-soft":()=>D(()=>import(`./pierre-light-soft-lWLdNTOI.js`),[]),"pierre-light-vibrant":()=>D(()=>import(`./pierre-light-vibrant-D80Fkn33.js`),[]),"pierre-light-protanopia-deuteranopia":()=>D(()=>import(`./pierre-light-protanopia-deuteranopia-0fSaH845.js`),[]),"pierre-light-tritanopia":()=>D(()=>import(`./pierre-light-tritanopia-CEbqgOJL.js`),[])};function cW(e){return QU({name:e,collection:eW,colorScheme:aW(e),displayName:oW[e],load:sW[e]})}var lW=BU({themes:rW.map(e=>cW(e))}),uW=`shiki`,dW=[`ayu-light`,`catppuccin-latte`,`everforest-light`,`github-light`,`github-light-default`,`github-light-high-contrast`,`gruvbox-light-hard`,`gruvbox-light-medium`,`gruvbox-light-soft`,`horizon-bright`,`kanagawa-lotus`,`light-plus`,`material-theme-lighter`,`min-light`,`night-owl-light`,`one-light`,`rose-pine-dawn`,`slack-ochin`,`snazzy-light`,`solarized-light`,`vitesse-light`],fW=`andromeeda.aurora-x.ayu-dark.ayu-mirage.catppuccin-frappe.catppuccin-macchiato.catppuccin-mocha.dark-plus.dracula.dracula-soft.everforest-dark.github-dark.github-dark-default.github-dark-dimmed.github-dark-high-contrast.gruvbox-dark-hard.gruvbox-dark-medium.gruvbox-dark-soft.horizon.houston.kanagawa-dragon.kanagawa-wave.laserwave.material-theme.material-theme-darker.material-theme-ocean.material-theme-palenight.min-dark.monokai.night-owl.nord.one-dark-pro.plastic.poimandres.red.rose-pine.rose-pine-moon.slack-dark.solarized-dark.synthwave-84.tokyo-night.vesper.vitesse-black.vitesse-dark`.split(`.`),pW=new Set(dW);function mW(e){return pW.has(e)?`light`:`dark`}var hW={andromeeda:()=>D(()=>import(`./andromeeda-vGVdxbeo.js`),[]),"aurora-x":()=>D(()=>import(`./aurora-x-CDeNXAV0.js`),[]),"ayu-dark":()=>D(()=>import(`./ayu-dark-DluEY0Gj.js`),[]),"ayu-light":()=>D(()=>import(`./ayu-light-C3h-C4tm.js`),[]),"ayu-mirage":()=>D(()=>import(`./ayu-mirage-Bqwy1Gya.js`),[]),"catppuccin-frappe":()=>D(()=>import(`./catppuccin-frappe-3VR1Za6u.js`),[]),"catppuccin-latte":()=>D(()=>import(`./catppuccin-latte-DwIHMF0Q.js`),[]),"catppuccin-macchiato":()=>D(()=>import(`./catppuccin-macchiato-DYnBP6_5.js`),[]),"catppuccin-mocha":()=>D(()=>import(`./catppuccin-mocha-DYhrFGRu.js`),[]),"dark-plus":()=>D(()=>import(`./dark-plus-Cs2F2srj.js`),[]),dracula:()=>D(()=>import(`./dracula-BHWKrbxM.js`),[]),"dracula-soft":()=>D(()=>import(`./dracula-soft-5eyTD99u.js`),[]),"everforest-dark":()=>D(()=>import(`./everforest-dark-sB-x3p7T.js`),[]),"everforest-light":()=>D(()=>import(`./everforest-light-Df2xbC6M.js`),[]),"github-dark":()=>D(()=>import(`./github-dark-C-LZuMrd.js`),[]),"github-dark-default":()=>D(()=>import(`./github-dark-default-DXG-b-1a.js`),[]),"github-dark-dimmed":()=>D(()=>import(`./github-dark-dimmed-Bx1FflLF.js`),[]),"github-dark-high-contrast":()=>D(()=>import(`./github-dark-high-contrast-B_tTalzw.js`),[]),"github-light":()=>D(()=>import(`./github-light-EUqPIrTm.js`),[]),"github-light-default":()=>D(()=>import(`./github-light-default-BXViO-2h.js`),[]),"github-light-high-contrast":()=>D(()=>import(`./github-light-high-contrast-B68TUdTA.js`),[]),"gruvbox-dark-hard":()=>D(()=>import(`./gruvbox-dark-hard-C820rvS2.js`),[]),"gruvbox-dark-medium":()=>D(()=>import(`./gruvbox-dark-medium-BPjhmG05.js`),[]),"gruvbox-dark-soft":()=>D(()=>import(`./gruvbox-dark-soft-MrdJrrXF.js`),[]),"gruvbox-light-hard":()=>D(()=>import(`./gruvbox-light-hard-BC_s9l72.js`),[]),"gruvbox-light-medium":()=>D(()=>import(`./gruvbox-light-medium-BAWPOn9u.js`),[]),"gruvbox-light-soft":()=>D(()=>import(`./gruvbox-light-soft-BSMLrYjP.js`),[]),horizon:()=>D(()=>import(`./horizon-CE9ld1lL.js`),[]),"horizon-bright":()=>D(()=>import(`./horizon-bright-DSNQnXHK.js`),[]),houston:()=>D(()=>import(`./houston-CsvMBhTu.js`),[]),"kanagawa-dragon":()=>D(()=>import(`./kanagawa-dragon-CXtmUGW6.js`),[]),"kanagawa-lotus":()=>D(()=>import(`./kanagawa-lotus-BN08jTvb.js`),[]),"kanagawa-wave":()=>D(()=>import(`./kanagawa-wave-CTweb8Dz.js`),[]),laserwave:()=>D(()=>import(`./laserwave-C_8bwKvT.js`),[]),"light-plus":()=>D(()=>import(`./light-plus-DVQuIRkW.js`),[]),"material-theme":()=>D(()=>import(`./material-theme-Bm3Qr25_.js`),[]),"material-theme-darker":()=>D(()=>import(`./material-theme-darker-2IIEA8gg.js`),[]),"material-theme-lighter":()=>D(()=>import(`./material-theme-lighter-uhdI0v04.js`),[]),"material-theme-ocean":()=>D(()=>import(`./material-theme-ocean-CHQ94UKr.js`),[]),"material-theme-palenight":()=>D(()=>import(`./material-theme-palenight-B5W6OYN7.js`),[]),"min-dark":()=>D(()=>import(`./min-dark-BSWPekZh.js`),[]),"min-light":()=>D(()=>import(`./min-light-DDpmG2fV.js`),[]),monokai:()=>D(()=>import(`./monokai-CdkpiU2Y.js`),[]),"night-owl":()=>D(()=>import(`./night-owl-DhmEMT88.js`),[]),"night-owl-light":()=>D(()=>import(`./night-owl-light-eJ-hLW7d.js`),[]),nord:()=>D(()=>import(`./nord-Cb4Vim4T.js`),[]),"one-dark-pro":()=>D(()=>import(`./one-dark-pro-CLwyXe_n.js`),[]),"one-light":()=>D(()=>import(`./one-light-D7Lr4KcI.js`),[]),plastic:()=>D(()=>import(`./plastic-DQwYfKfQ.js`),[]),poimandres:()=>D(()=>import(`./poimandres-DRFjx7u4.js`),[]),red:()=>D(()=>import(`./red-CJ3rzSJv.js`),[]),"rose-pine":()=>D(()=>import(`./rose-pine-BthvhNj6.js`),[]),"rose-pine-dawn":()=>D(()=>import(`./rose-pine-dawn-Dg85fqjY.js`),[]),"rose-pine-moon":()=>D(()=>import(`./rose-pine-moon-hon4tzzS.js`),[]),"slack-dark":()=>D(()=>import(`./slack-dark-DnToyrRv.js`),[]),"slack-ochin":()=>D(()=>import(`./slack-ochin-B2OO5cIa.js`),[]),"snazzy-light":()=>D(()=>import(`./snazzy-light-4G7pJPwS.js`),[]),"solarized-dark":()=>D(()=>import(`./solarized-dark-DV17i1UV.js`),[]),"solarized-light":()=>D(()=>import(`./solarized-light-DSh2HLQt.js`),[]),"synthwave-84":()=>D(()=>import(`./synthwave-84-nFMaYfgc.js`),[]),"tokyo-night":()=>D(()=>import(`./tokyo-night-oM2G3aXe.js`),[]),vesper:()=>D(()=>import(`./vesper-DdrHHSXu.js`),[]),"vitesse-black":()=>D(()=>import(`./vitesse-black-fwtXNY1n.js`),[]),"vitesse-dark":()=>D(()=>import(`./vitesse-dark-BZCL-v6S.js`),[]),"vitesse-light":()=>D(()=>import(`./vitesse-light-VbXTXTou.js`),[])};function gW(e){return QU({name:e,collection:uW,colorScheme:mW(e),load:hW[e]})}var _W=BU({themes:Object.freeze([...dW.map(e=>gW(e)),...fW.map(e=>gW(e))])});function vW(e){if(mI())throw Error(`Theme "${e}" cannot be resolved from a worker context. Themes must be pre-resolved on the main thread and passed to the worker via the resolvedLanguages parameter.`);if(XU.hasRegisteredTheme(e))return;let t=_W.getTheme(e);if(t!=null){XU.registerThemeIfAbsent(t.name,t.load);return}throw Error(`No valid theme loader registered for "${e}"`)}function yW(e,t){if(t.name!==e)throw Error(`resolvedTheme: themeName: ${e} does not match theme.name: ${t.name}`)}async function bW(e){vW(e);let t=await XU.resolveTheme(e);return yW(e,t),t}function xW(e){return XU.getResolvedTheme(e)??bW(e)}var SW;async function CW({themes:e,langs:t,preferredHighlighter:n=`shiki-js`}){SW??=oB({themes:[],langs:[`text`],engine:n===`shiki-wasm`?$I(D(()=>import(`./wasm-BnjxR4X6.js`),[])):IU()});let r=TW(SW)?await SW:SW;SW=r;let i=[];for(let e of t){if(e===`text`||e===`ansi`)continue;let t=RU(e);`then`in t?i.push(t):pI(t,r)}let a=[];for(let t of e){let e=xW(t);`then`in e?a.push(e):ZU(e,SW)}return(i.length>0||a.length>0)&&await Promise.all([Promise.all(i).then(e=>{pI(e,r)}),Promise.all(a).then(e=>{ZU(e,r)})]),r}function wW(){if(SW!=null&&!(`then`in SW))return SW}function TW(e=SW){return e!=null&&`then`in e}for(let e of lW.getThemes())XU.registerThemeIfAbsent(e.name,e.load);function EW(e=pM){let t=[];return typeof e==`string`?t.push(e):(t.push(e.dark),t.push(e.light)),t}function DW(e){for(let t of EW(e))if(!zU.has(t))return!1;return!0}function OW(e){return XU.hasResolvedThemes(e)}function kW(e,t){return PM(e.theme,t.theme)&&e.useTokenTransformer===t.useTokenTransformer&&e.tokenizeMaxLineLength===t.tokenizeMaxLineLength}function AW(e,t){return e==null||t==null?e===t:e.startingLine===t.startingLine&&e.totalLines===t.totalLines&&e.bufferBefore===t.bufferBefore&&e.bufferAfter===t.bufferAfter}function jW(e){return B({tagName:`div`,children:[B({tagName:`div`,children:e.annotations?.map(e=>B({tagName:`slot`,properties:{name:e}})),properties:{"data-annotation-content":``}})],properties:{"data-line-annotation":`${e.hunkIndex},${e.lineIndex}`}})}function MW(e){switch(e){case`file`:return`diffs-icon-file-code`;case`change`:return`diffs-icon-symbol-modified`;case`new`:return`diffs-icon-symbol-added`;case`deleted`:return`diffs-icon-symbol-deleted`;case`rename-pure`:case`rename-changed`:return`diffs-icon-symbol-moved`}}function NW({fileOrDiff:e,mode:t,stickyHeader:n}){let r=`type`in e?e:void 0,i={"data-diffs-header":t,"data-change-type":r?.type,"data-sticky":n?``:void 0};return B({tagName:`div`,children:[t===`custom`?B({tagName:`slot`,properties:{name:fM}}):PW({name:e.name,prevName:`prevName`in e?e.prevName:void 0,iconType:r?.type??`file`}),...t===`custom`?[]:[FW(r)]],properties:i})}function PW({name:e,prevName:t,iconType:n}){let r=[B({tagName:`slot`,properties:{name:lM}}),SN({name:MW(n),properties:{"data-change-icon":n}})];return t!=null&&(r.push(B({tagName:`div`,children:[B({tagName:`bdi`,children:[xN(t)]})],properties:{"data-prev-name":``}})),r.push(SN({name:`diffs-icon-arrow-right-short`,properties:{"data-rename-icon":``}}))),r.push(B({tagName:`div`,children:[B({tagName:`bdi`,children:[xN(e)]})],properties:{"data-title":``}})),r.push(B({tagName:`slot`,properties:{name:uM}})),B({tagName:`div`,children:r,properties:{"data-header-content":``}})}function FW(e){let t=[];if(e!=null){let n=0,r=0;for(let t of e.hunks)n+=t.additionLines,r+=t.deletionLines;(r>0||n===0)&&t.push(B({tagName:`span`,children:[xN(`-${r}`)],properties:{"data-deletions-count":``}})),(n>0||r===0)&&t.push(B({tagName:`span`,children:[xN(`+${n}`)],properties:{"data-additions-count":``}}))}return t.push(B({tagName:`slot`,properties:{name:dM}})),B({tagName:`div`,children:t,properties:{"data-metadata":``}})}function IW(e){return B({tagName:`pre`,properties:LW(e)})}function LW({diffIndicators:e,disableBackground:t,disableLineNumbers:n,overflow:r,split:i,totalLines:a,type:o,customProperties:s}){return{...s,"data-diff":o===`diff`?``:void 0,"data-file":o===`file`?``:void 0,"data-diff-type":o===`diff`?i?`split`:`single`:void 0,"data-overflow":r,"data-disable-line-numbers":n?``:void 0,"data-background":t?void 0:``,"data-indicators":e===`bars`||e===`classic`?e:void 0,style:`--diffs-min-number-column-width-default:${`${a}`.length}ch;`}}var RW=new Map,zW=0,BW={"1c":`1c`,abap:`abap`,as:`actionscript-3`,ada:`ada`,adb:`ada`,ads:`ada`,adoc:`asciidoc`,asciidoc:`asciidoc`,"component.html":`angular-html`,"component.ts":`angular-ts`,conf:`nginx`,htaccess:`apache`,cls:`tex`,trigger:`apex`,apl:`apl`,applescript:`applescript`,scpt:`applescript`,ara:`ara`,asm:`asm`,s:`riscv`,astro:`astro`,awk:`awk`,bal:`ballerina`,sh:`zsh`,bash:`zsh`,bat:`cmd`,cmd:`cmd`,be:`berry`,beancount:`beancount`,bib:`bibtex`,bicep:`bicep`,"blade.php":`blade`,bsl:`bsl`,c:`c`,h:`objective-cpp`,cs:`csharp`,cpp:`cpp`,hpp:`cpp`,cc:`cpp`,cxx:`cpp`,hh:`cpp`,cdc:`cdc`,cairo:`cairo`,clar:`clarity`,clj:`clojure`,cljs:`clojure`,cljc:`clojure`,soy:`soy`,cmake:`cmake`,"CMakeLists.txt":`cmake`,cob:`cobol`,cbl:`cobol`,cobol:`cobol`,CODEOWNERS:`codeowners`,ql:`ql`,coffee:`coffeescript`,lisp:`lisp`,cl:`lisp`,lsp:`lisp`,log:`log`,v:`verilog`,cql:`cql`,cr:`crystal`,css:`css`,csv:`csv`,cue:`cue`,cypher:`cypher`,cyp:`cypher`,d:`d`,dart:`dart`,dax:`dax`,desktop:`desktop`,diff:`diff`,patch:`diff`,Dockerfile:`dockerfile`,dockerfile:`dockerfile`,env:`dotenv`,dm:`dream-maker`,edge:`edge`,el:`emacs-lisp`,ex:`elixir`,exs:`elixir`,elm:`elm`,erb:`erb`,erl:`erlang`,hrl:`erlang`,f:`fortran-fixed-form`,for:`fortran-fixed-form`,fs:`fsharp`,fsi:`fsharp`,fsx:`fsharp`,f03:`f03`,f08:`f08`,f18:`f18`,f77:`f77`,f90:`fortran-free-form`,f95:`fortran-free-form`,fnl:`fennel`,fish:`fish`,ftl:`ftl`,tres:`gdresource`,res:`gdresource`,gd:`gdscript`,gdshader:`gdshader`,gs:`genie`,feature:`gherkin`,COMMIT_EDITMSG:`git-commit`,"git-rebase-todo":`git-rebase`,gjs:`glimmer-js`,gleam:`gleam`,gts:`glimmer-ts`,glsl:`glsl`,vert:`glsl`,frag:`glsl`,shader:`shaderlab`,gp:`gnuplot`,plt:`gnuplot`,gnuplot:`gnuplot`,go:`go`,graphql:`graphql`,gql:`graphql`,groovy:`groovy`,gvy:`groovy`,hack:`hack`,haml:`haml`,hbs:`handlebars`,handlebars:`handlebars`,hs:`haskell`,lhs:`haskell`,hx:`haxe`,hcl:`hcl`,hjson:`hjson`,hlsl:`hlsl`,fx:`hlsl`,html:`html`,htm:`html`,http:`http`,rest:`http`,hxml:`hxml`,hy:`hy`,imba:`imba`,ini:`ini`,cfg:`ini`,jade:`pug`,pug:`pug`,java:`java`,js:`javascript`,mjs:`javascript`,cjs:`javascript`,jinja:`jinja`,jinja2:`jinja`,j2:`jinja`,jison:`jison`,jl:`julia`,json:`json`,json5:`json5`,jsonc:`jsonc`,jsonl:`jsonl`,jsonnet:`jsonnet`,libsonnet:`jsonnet`,jssm:`jssm`,jsx:`jsx`,kt:`kotlin`,kts:`kts`,kql:`kusto`,tex:`tex`,ltx:`tex`,lean:`lean4`,less:`less`,liquid:`liquid`,lit:`lit`,ll:`llvm`,logo:`logo`,lua:`lua`,luau:`luau`,Makefile:`makefile`,mk:`makefile`,makefile:`makefile`,md:`markdown`,markdown:`markdown`,marko:`marko`,m:`wolfram`,mat:`matlab`,mdc:`mdc`,mdx:`mdx`,wiki:`wikitext`,mediawiki:`wikitext`,mmd:`mermaid`,mermaid:`mermaid`,mips:`mipsasm`,mojo:`mojo`,"🔥":`mojo`,move:`move`,nar:`narrat`,nf:`nextflow`,nim:`nim`,nims:`nim`,nimble:`nim`,nix:`nix`,nu:`nushell`,mm:`objective-cpp`,ml:`ocaml`,mli:`ocaml`,mll:`ocaml`,mly:`ocaml`,pas:`pascal`,p:`pascal`,pl:`prolog`,pm:`perl`,t:`perl`,raku:`raku`,p6:`raku`,pl6:`raku`,php:`php`,phtml:`php`,pls:`plsql`,sql:`sql`,po:`po`,polar:`polar`,pcss:`postcss`,pot:`pot`,potx:`potx`,pq:`powerquery`,pqm:`powerquery`,ps1:`powershell`,psm1:`powershell`,psd1:`powershell`,prisma:`prisma`,pro:`prolog`,P:`prolog`,properties:`properties`,proto:`protobuf`,pp:`puppet`,purs:`purescript`,py:`python`,pyw:`python`,pyi:`python`,qml:`qml`,qmldir:`qmldir`,qss:`qss`,r:`r`,R:`r`,rkt:`racket`,rktl:`racket`,razor:`razor`,cshtml:`razor`,rb:`ruby`,rbw:`ruby`,reg:`reg`,regex:`regexp`,rel:`rel`,rs:`rust`,rst:`rst`,rake:`ruby`,gemspec:`ruby`,jbuilder:`ruby`,builder:`ruby`,rabl:`ruby`,arb:`ruby`,ru:`ruby`,podspec:`ruby`,Gemfile:`ruby`,Rakefile:`ruby`,Guardfile:`ruby`,Capfile:`ruby`,Berksfile:`ruby`,Brewfile:`ruby`,Vagrantfile:`ruby`,Thorfile:`ruby`,Appraisals:`ruby`,Dangerfile:`ruby`,sas:`sas`,sass:`sass`,scala:`scala`,sc:`scala`,scm:`scheme`,ss:`scheme`,sld:`scheme`,scss:`scss`,sdbl:`sdbl`,shadergraph:`shader`,st:`smalltalk`,sol:`solidity`,sparql:`sparql`,rq:`sparql`,spl:`splunk`,config:`ssh-config`,do:`stata`,ado:`stata`,dta:`stata`,styl:`stylus`,stylus:`stylus`,svelte:`svelte`,swift:`swift`,sv:`system-verilog`,svh:`system-verilog`,service:`systemd`,socket:`systemd`,device:`systemd`,timer:`systemd`,talon:`talonscript`,tasl:`tasl`,tcl:`tcl`,templ:`templ`,tf:`tf`,tfvars:`tfvars`,toml:`toml`,ts:`typescript`,mts:`typescript`,cts:`typescript`,tsp:`typespec`,tsv:`tsv`,tsx:`tsx`,ttl:`turtle`,twig:`twig`,typ:`typst`,vv:`v`,vala:`vala`,vapi:`vala`,vb:`vb`,vbs:`vb`,bas:`vb`,vh:`verilog`,vhd:`vhdl`,vhdl:`vhdl`,vim:`vimscript`,vue:`vue`,"vine.ts":`vue-vine`,vy:`vyper`,wasm:`wasm`,wat:`wasm`,wy:`文言`,wgsl:`wgsl`,wit:`wit`,wl:`wolfram`,nb:`wolfram`,xml:`xml`,xsl:`xsl`,xslt:`xsl`,yaml:`yaml`,yml:`yml`,zs:`zenscript`,zig:`zig`,zsh:`zsh`,sty:`tex`};function VW(e){if(RW.has(e))return RW.get(e)??`text`;if(BW[e]!=null)return BW[e];let t=e.match(/\.([^/\\]+\.[^/\\]+)$/);if(t!=null){if(RW.has(t[1]))return RW.get(t[1])??`text`;if(BW[t[1]]!=null)return BW[t[1]]??`text`}let n=e.match(/\.([^.]+)$/)?.[1]??``;return RW.has(n)?RW.get(n)??`text`:BW[n]??`text`}function HW(){return zW}function UW(){return Object.fromEntries(RW)}function WW(e,{theme:t,preferredHighlighter:n=`shiki-js`}){return{langs:[e??`text`],themes:EW(t),preferredHighlighter:n}}function GW(e){return`annotation-${`side`in e?`${e.side}-`:``}${e.lineNumber}`}function KW(e,t,n){let r=typeof n.lineInfo==`function`?n.lineInfo(t):n.lineInfo[t-1];if(r==null){let r=`processLine: line ${t}, contains no state.lineInfo`;throw console.error(r,{node:e,line:t,state:n}),Error(r)}return e.tagName=`div`,e.properties[`data-line`]=r.lineNumber,e.properties[`data-alt-line`]=r.altLineNumber,e.properties[`data-line-type`]=r.type,e.properties[`data-line-index`]=r.lineIndex,e.children.length===0&&e.children.push(xN(`
|
|
185
|
+
`)),e}var qW=Symbol(`no-token`),JW=Symbol(`multiple-tokens`);function YW(e){let t=XW(e);if(t!=null)return t;let n=qW,r=[],i=[],a,o=()=>{if(i.length===0||a==null){i=[],a=void 0;return}if(i.length===1){let e=i[0];if(e?.type===`element`){QW(e,a);for(let t of e.children)ZW(t)}else ZW(e);r.push(e),i=[],a=void 0;return}for(let e of i)ZW(e);r.push(B({tagName:`span`,properties:{"data-char":a},children:i})),i=[],a=void 0},s=e=>{if(e!==qW){if(e===JW){n=JW;return}if(n===qW){n=e;return}n!==e&&(n=JW)}};for(let t of e.children){let e=t.type===`element`?YW(t):qW;if(s(e),typeof e!=`number`){o(),r.push(t);continue}a!=null&&a!==e&&o(),a??=e,i.push(t)}return o(),e.children=r,n}function XW(e){let t=e.properties[`data-char`];if(typeof t==`number`)return t}function ZW(e){if(e.type===`element`){e.properties[`data-char`]=void 0;for(let t of e.children)ZW(t)}}function QW(e,t){e.properties[`data-char`]=t}function $W(e={}){let{classPrefix:t=`__shiki_`,classSuffix:n=``,classReplacer:r=e=>e}=e,i=new Map;function a(e){return Object.entries(e).map(([e,t])=>`${e}:${t}`).join(`;`)}function o(e){let o=typeof e==`string`?e:a(e),s=t+eG(o)+n;return s=r(s),i.has(s)||i.set(s,typeof e==`string`?e:{...e}),s}return{name:`@shikijs/transformers:style-to-class`,pre(e){if(!e.properties.style)return;let t=o(e.properties.style);delete e.properties.style,this.addClassToHast(e,t)},tokens(e){for(let t of e)for(let e of t){if(!e.htmlStyle)continue;let t=o(e.htmlStyle);e.htmlStyle={},e.htmlAttrs||={},e.htmlAttrs.class?e.htmlAttrs.class+=` ${t}`:e.htmlAttrs.class=t}},getClassRegistry(){return i},getCSS(){let e=``;for(let[t,n]of i.entries())e+=`.${t}{${typeof n==`string`?n:a(n)}}`;return e},clearRegistry(){i.clear()}}}function eG(e,t=0){let n=3735928559^t,r=1103547991^t;for(let t=0,i;t<e.length;t++)i=e.charCodeAt(t),n=Math.imul(n^i,2654435761),r=Math.imul(r^i,1597334677);return n=Math.imul(n^n>>>16,2246822507),n^=Math.imul(r^r>>>13,3266489909),r=Math.imul(r^r>>>16,2246822507),r^=Math.imul(n^n>>>13,3266489909),(4294967296*(2097151&r)+(n>>>0)).toString(36).slice(0,6)}function tG(e=!1,t=!1){let n={lineInfo:[]},r=[{line(e){return delete e.properties.class,e},pre(t){let r=CN(t),i=[];if(r!=null){let t=1;for(let a of r.children)a.type===`element`&&(e&&YW(a),i.push(KW(a,t,n)),t++);r.children=i}return t},...e?{tokens(e){for(let t of e){let e=0;for(let n of t){let t=n;t.__lineChar??=e,e+=n.content.length}}},preprocess(e,t){t.mergeWhitespaces=`never`},span(e,t,n,r,i){if(i?.offset!=null&&i.content!=null){let t=i.__lineChar;return t!=null&&(e.properties[`data-char`]=t),e}return e}}:null}];return t&&r.push(rG,nG),e&&r.push({line:e=>(e.type===`element`&&e.children.length===0&&e.children.push({type:`element`,tagName:`br`,properties:{},children:[]}),e)}),{state:n,transformers:r,toClass:nG}}var nG=$W({classPrefix:`hl-`}),rG={name:`token-style-normalizer`,tokens(e){for(let t of e)for(let e of t){if(e.htmlStyle!=null)continue;let t={};e.color!=null&&(t.color=e.color),e.bgColor!=null&&(t[`background-color`]=e.bgColor),e.fontStyle!=null&&e.fontStyle!==0&&(e.fontStyle&1&&(t[`font-style`]=`italic`),e.fontStyle&2&&(t[`font-weight`]=`bold`),e.fontStyle&4&&(t[`text-decoration`]=`underline`)),Object.keys(t).length>0&&(e.htmlStyle=t)}}};function iG(e){return`--${e===`token`?`diffs-token`:`diffs`}-`}var aG=/^#(?:[0-9a-f]{3}0|[0-9a-f]{6}00)$/i,oG=/^0(?:\.0+)?%?$/;function sG(e){let t=e.indexOf(`(`);if(t<=0||!e.endsWith(`)`))return;let n=e.slice(0,t).trim();if(!/^(?:rgb|rgba|hsl|hsla|hwb|lab|lch|oklab|oklch|color)$/i.test(n))return;let r=e.slice(t+1,-1).trim();if(r.length===0)return;let i=r.lastIndexOf(`/`);if(i!==-1)return r.slice(i+1).trim();if(/^(?:rgba|hsla)$/i.test(n)){let e=r.split(`,`);if(e.length===4)return e[3]?.trim()}}function cG(e){let t=/^#([0-9a-f]{3}|[0-9a-f]{6}|[0-9a-f]{8})\b/i.exec(e.trim());if(t==null)return null;let n=t[1],r,i=1;return n.length===3?r=n.split(``).map(e=>e+e).join(``):n.length===6?r=n:(r=n.slice(0,6),i=parseInt(n.slice(6,8),16)/255),[parseInt(r.slice(0,2),16),parseInt(r.slice(2,4),16),parseInt(r.slice(4,6),16),i]}function lG(e){if(e==null)return null;let t=cG(e);if(t==null)return null;let n=t[0]/255,r=t[1]/255,i=t[2]/255,a=e=>e<=.03928?e/12.92:((e+.055)/1.055)**2.4;return .2126*a(n)+.7152*a(r)+.0722*a(i)}function uG(e){if(e==null)return!1;let t=e.trim().toLowerCase();if(t===`transparent`||aG.test(t))return!0;let n=sG(t);return n!=null&&oG.test(n)}function dG(e,t,n){if(t==null||n==null)return!1;let r=lG(e),i=lG(t),a=lG(n);return r==null||i==null||a==null?!1:Math.abs(r-a)<Math.abs(r-i)}var fG=new WeakMap;function pG(e){let t=fG.get(e);if(t!=null)return t;let n=e.colors??{},r={...n},i=n[`editor.background`]??e.bg,a=n[`editor.foreground`]??e.fg,o=n[`sideBar.background`]??i,s=n[`sideBar.foreground`]??a;mG(r,`editor.background`,i),mG(r,`editor.foreground`,a),mG(r,`sideBar.background`,o),mG(r,`sideBar.foreground`,s),mG(r,`input.background`,n[`input.background`]??o),mG(r,`sideBarSectionHeader.foreground`,n[`sideBarSectionHeader.foreground`]??s),mG(r,`list.activeSelectionForeground`,n[`list.activeSelectionForeground`]??s),mG(r,`gitDecoration.addedResourceForeground`,hG(n[`gitDecoration.addedResourceForeground`],n[`terminal.ansiGreen`],n[`editorGutter.addedBackground`])),mG(r,`gitDecoration.modifiedResourceForeground`,hG(n[`gitDecoration.modifiedResourceForeground`],n[`terminal.ansiBlue`],n[`editorGutter.modifiedBackground`])),mG(r,`gitDecoration.deletedResourceForeground`,hG(n[`gitDecoration.deletedResourceForeground`],n[`terminal.ansiRed`],n[`editorGutter.deletedBackground`]));let c=(uG(n[`list.focusOutline`])?void 0:n[`list.focusOutline`])??(uG(n.focusBorder)?void 0:n.focusBorder);c==null?delete r[`list.focusOutline`]:r[`list.focusOutline`]=c;let l=n[`list.hoverBackground`];l!=null&&(gG(l,o)||dG(l,o,s))&&delete r[`list.hoverBackground`];let u=Object.freeze({...e,colors:Object.freeze(r)});return fG.set(e,u),u}function mG(e,t,n){n!=null&&n!==``&&(e[t]=n)}function hG(...e){for(let t of e)if(t!=null&&t!==``)return t}function gG(e,t){return t!=null&&e.toLowerCase()===t.toLowerCase()}function _G({theme:e=pM,highlighter:t,prefix:n}){let r=``;if(typeof e==`string`){let i=t.getTheme(e),a=pG(i);r+=`color:${a.fg};`,r+=`background-color:${a.bg};`,r+=`${iG(`global`)}fg:${a.fg};`,r+=`${iG(`global`)}bg:${a.bg};`,r+=vG(i,n)}else{let n=t.getTheme(e.dark),i=pG(n);r+=`${iG(`global`)}dark:${i.fg};`,r+=`${iG(`global`)}dark-bg:${i.bg};`,r+=vG(n,`dark`),n=t.getTheme(e.light),i=pG(n),r+=`${iG(`global`)}light:${i.fg};`,r+=`${iG(`global`)}light-bg:${i.bg};`,r+=vG(n,`light`)}return r}function vG(e,t){t=t==null?``:`${t}-`;let n=``,r=e.colors?.[`gitDecoration.addedResourceForeground`]??e.colors?.[`terminal.ansiGreen`];r!=null&&(n+=`${iG(`global`)}${t}addition-color:${r};`);let i=e.colors?.[`gitDecoration.deletedResourceForeground`]??e.colors?.[`terminal.ansiRed`];i!=null&&(n+=`${iG(`global`)}${t}deletion-color:${i};`);let a=e.colors?.[`gitDecoration.modifiedResourceForeground`]??e.colors?.[`terminal.ansiBlue`];return a!=null&&(n+=`${iG(`global`)}${t}modified-color:${a};`),n}function yG(e){let t=e.children[0];for(;t!=null;){if(t.type===`element`&&t.tagName===`code`)return t.children;t=`children`in t?t.children[0]:null}throw console.error(e),Error(`getLineNodes: Unable to find children`)}var bG=10,xG=13,SG=4,CG=40;function wG(e){let t=[0],n=e.indexOf(`\r`),r=e.indexOf(`
|
|
186
186
|
`),i=0,a=0;for(;n!==-1||r!==-1;){let o;if(n!==-1&&(r===-1||n<r)?r===n+1?(o=r+1,n=e.indexOf(`\r`,o),r=e.indexOf(`
|
|
187
187
|
`,o)):(o=n+1,n=e.indexOf(`\r`,o)):(o=r+1,r=e.indexOf(`
|
|
188
|
-
`,o)),t.push(o),++a===
|
|
188
|
+
`,o)),t.push(o),++a===SG){if(o-i<=CG){for(let n=o;n<e.length;n++){let r=e.charCodeAt(n);(r===bG||r===xG)&&(r===xG&&n+1<e.length&&e.charCodeAt(n+1)===bG&&n++,t.push(n+1))}return t}i=o,a=0}}return t}function TG(e){let t=wG(e);return Array.from({length:t.length},(n,r)=>{let i=t[r],a=t[r+1]??e.length;return e.slice(i,a)})}var EG={forcePlainText:!1};function DG(e,t,{theme:n=pM,tokenizeMaxLineLength:r,useTokenTransformer:i},{forcePlainText:a,startingLine:o,totalLines:s,lines:c}=EG){a?(o??=0,s??=1/0):(o=0,s=1/0);let l=o>0||s<1/0,{state:u,transformers:d}=tG(i),f=a?`text`:e.lang??VW(e.name),p=typeof n==`string`?t.getTheme(n).type:void 0,m=_G({theme:n,highlighter:t});u.lineInfo=e=>({type:`context`,lineIndex:e-1+o,lineNumber:e+o});let h=typeof n==`string`?{lang:f,theme:n,transformers:d,defaultColor:!1,cssVariablePrefix:iG(`token`),tokenizeMaxLineLength:r,tokenizeTimeLimit:0}:{lang:f,themes:n,transformers:d,defaultColor:!1,cssVariablePrefix:iG(`token`),tokenizeMaxLineLength:r,tokenizeTimeLimit:0},g=yG(t.codeToHast(l?OG(c??TG(e.contents),o,s):e.contents,h)),_=l?Array(o):g;return l&&_.push(...g),{code:_,themeStyles:m,baseThemeType:p}}function OG(e,t,n){if(e.length===0)return``;let r=Math.min(t+n,e.length);return e.slice(t,r).join(``)}var kG=`-1,-1`;function AG(e){return e?.some(e=>e.lineNumber===0)??!1}function jG(e){let t=e[0];return t!=null&&t.length>0?t:void 0}function MG(e){return e.startingLine===0&&e.totalLines>0}function NG(e,t){return e.endsWith(`\r
|
|
189
189
|
`)?t+`\r
|
|
190
190
|
`:e.endsWith(`\r`)?t+`\r`:e.endsWith(`
|
|
191
191
|
`)?t+`
|
|
192
|
-
`:t}function
|
|
192
|
+
`:t}function PG(e,t){return B({tagName:`div`,children:e,properties:{"data-content":``,style:`grid-row: span ${t}`}})}function FG(e){return(e.lang??VW(e.name))===`text`}var IG=`<svg data-icon-sprite aria-hidden="true" width="0" height="0">
|
|
193
193
|
<symbol id="diffs-icon-arrow-right-short" viewBox="0 0 16 16">
|
|
194
194
|
<path d="M8.47 4.22a.75.75 0 0 0 0 1.06l1.97 1.97H3.75a.75.75 0 0 0 0 1.5h6.69l-1.97 1.97a.75.75 0 1 0 1.06 1.06l3.25-3.25a.75.75 0 0 0 0-1.06L9.53 4.22a.75.75 0 0 0-1.06 0"/>
|
|
195
195
|
</symbol>
|
|
@@ -241,7 +241,7 @@ XID_Start XIDS`.split(/\s/).map(e=>[HV(e),e])),PH=new Map([[`s`,Z(383)],[Z(383),
|
|
|
241
241
|
<symbol id="diffs-icon-symbol-ref" viewBox="0 0 16 16">
|
|
242
242
|
<path d="M1.5 8c0 1.613.088 2.806.288 3.704.196.88.478 1.381.802 1.706.286.286.71.54 1.41.73V1.86c-.7.19-1.124.444-1.41.73-.324.325-.606.826-.802 1.706C1.588 5.194 1.5 6.387 1.5 8m4 6.397c.697.07 1.522.103 2.5.103 1.613 0 2.806-.088 3.704-.288.88-.195 1.381-.478 1.706-.802s.607-.826.802-1.706c.2-.898.288-2.091.288-3.704s-.088-2.806-.288-3.704c-.195-.88-.478-1.381-.802-1.706s-.826-.606-1.706-.802C10.806 1.588 9.613 1.5 8 1.5c-.978 0-1.803.033-2.5.103zM0 8c0-6.588 1.412-8 8-8s8 1.412 8 8-1.412 8-8 8-8-1.412-8-8m7-2a1 1 0 0 1 1-1h3a1 1 0 0 1 1 1v1a1 1 0 0 1-1 1H8a1 1 0 0 1-1-1z"/>
|
|
243
243
|
</symbol>
|
|
244
|
-
</svg>`;function
|
|
244
|
+
</svg>`;function LG(e,t){return e==null||t==null?e===t:zG(e.customProperties,t.customProperties)&&e.type===t.type&&e.diffIndicators===t.diffIndicators&&e.disableBackground===t.disableBackground&&e.disableLineNumbers===t.disableLineNumbers&&e.overflow===t.overflow&&e.split===t.split&&e.totalLines===t.totalLines}var RG={};function zG(e=RG,t=RG){if(e===t)return!0;let n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length)return!1;for(let r of n)if(e[r]!==t[r])return!1;return!0}function BG(e){let t=document.createElement(`div`);return t.dataset.annotationSlot=``,t.slot=e,t.style.whiteSpace=`normal`,t}function VG(){let e=document.createElement(`div`);return e.slot=`gutter-utility-slot`,e.style.position=`absolute`,e.style.top=`0`,e.style.bottom=`0`,e.style.textAlign=`center`,e.style.whiteSpace=`normal`,e.style.touchAction=`none`,e}function HG(){let e=document.createElement(`style`);return e.setAttribute(hM,``),e}var UG=`@layer base {
|
|
245
245
|
:host {
|
|
246
246
|
--diffs-font-fallback: "SF Mono", Monaco, Consolas, "Ubuntu Mono", "Liberation Mono",
|
|
247
247
|
"Courier New", monospace;
|
|
@@ -1519,15 +1519,15 @@ XID_Start XIDS`.split(/\s/).map(e=>[HV(e),e])),PH=new Map([[`s`,Z(383)],[Z(383),
|
|
|
1519
1519
|
}
|
|
1520
1520
|
|
|
1521
1521
|
@layer theme, rendered, unsafe;
|
|
1522
|
-
`,
|
|
1522
|
+
`,WG;function GG(e){if(WG!=null)return WG;let t=e.host;if(typeof HTMLElement<`u`&&t instanceof HTMLElement&&!t.isConnected)return;let n=document.createElement(`div`);n.setAttribute(`data-code`,``),n.setAttribute(gM,`true`);let r=document.createElement(`div`);return r.style.position=`relative`,r.style.width=`200%`,r.style.height=`200%`,n.appendChild(r),e.appendChild(n),WG=Math.max(n.offsetHeight-n.clientHeight,0),n.remove(),WG}function KG(e){return`${yM}: ${e==null?`var(--diffs-scrollbar-gutter-fallback)`:`${e}px`};`}var qG=`@layer base, theme, rendered, unsafe;`,JG=RegExp(`${QG(yM)}\\s*:\\s*[^;]+;`);function YG(e){return`${qG}
|
|
1523
1523
|
@layer unsafe {
|
|
1524
1524
|
${e}
|
|
1525
|
-
}`}function
|
|
1525
|
+
}`}function XG(e,t=`system`,n){return`${qG}
|
|
1526
1526
|
@layer rendered {
|
|
1527
1527
|
:host {${t===`system`?``:`
|
|
1528
1528
|
color-scheme: ${t};`}
|
|
1529
|
-
${
|
|
1529
|
+
${KG(n)}
|
|
1530
1530
|
${e}
|
|
1531
1531
|
}
|
|
1532
|
-
}`}function XG(e,t){let n=GG(t);return e.replace(qG,n)}function ZG(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function QG({code:e,pre:t,columnType:n,rowSpan:r,containerSize:i=!1}={}){return e??(e=document.createElement(`code`),e.setAttribute(`data-code`,``),n!=null&&e.setAttribute(`data-${n}`,``),t?.appendChild(e)),r==null?e.style.removeProperty(`grid-row`):e.style.setProperty(`grid-row`,`span ${r}`),i?e.setAttribute(`data-container-size`,``):e.removeAttribute(`data-container-size`),e}function $G(e,t){if(t==null)return;let n=e.shadowRoot??e.attachShadow({mode:`open`});n.innerHTML===``&&(n.innerHTML=t)}function eK(e,{type:t,diffIndicators:n,disableBackground:r,disableLineNumbers:i,overflow:a,split:o,totalLines:s,customProperties:c}){if(c!=null)for(let t in c){let n=c[t];n!=null&&e.setAttribute(t,`${n}`)}switch(t===`diff`?(e.setAttribute(`data-diff`,``),e.removeAttribute(`data-file`)):(e.setAttribute(`data-file`,``),e.removeAttribute(`data-diff`)),n){case`bars`:case`classic`:e.setAttribute(`data-indicators`,n);break;case`none`:e.removeAttribute(`data-indicators`)}return i?e.setAttribute(`data-disable-line-numbers`,``):e.removeAttribute(`data-disable-line-numbers`),r?e.removeAttribute(`data-background`):e.setAttribute(`data-background`,``),t===`diff`?e.setAttribute(`data-diff-type`,o?`split`:`single`):e.removeAttribute(`data-diff-type`),e.setAttribute(`data-overflow`,a),e.style.setProperty(`--diffs-min-number-column-width-default`,`${`${s}`.length}ch`),e}function tK(e){if(typeof HTMLStyleElement<`u`&&e instanceof HTMLStyleElement)return!0;let t=e.tagName??e.nodeName;return typeof t==`string`&&t.toLowerCase()===`style`}function nK(e){return e?.useTokenTransformer===!0||e?.onTokenClick!=null||e?.onTokenEnter!=null||e?.onTokenLeave!=null}function rK(e,t){let n=e?.offsetHeight??0;if(e==null||n===0){t();return}e.style.minHeight=`${n}px`;try{t(),e.offsetHeight}finally{e.style.minHeight=``}}function iK({shadowRoot:e,currentNode:t,themeCSS:n}){if(n.trim()===``){t?.remove();return}return t??=aK(),t.textContent=n,t.parentNode!==e&&e.appendChild(t),t}function aK(){let e=document.createElement(`style`);return e.setAttribute(pM,``),e}var oK=void 0;function sK(){return oK??=`safari`in window&&`pushNotification`in window.safari||/^((?!chrome|android).)*safari/i.test(navigator.userAgent)}if(typeof HTMLElement<`u`&&customElements.get(`diffs-container`)==null){let e;class t extends HTMLElement{constructor(){if(super(),this.shadowRoot!=null)return;let t=this.attachShadow({mode:`open`});e??(e=new CSSStyleSheet,e.replaceSync(HG)),t.adoptedStyleSheets=[e]}connectedCallback(){WG(this.shadowRoot??this.attachShadow({mode:`open`}))}}customElements.define($j,t)}function cK(e){return{...bM,...e}}function lK(e,t){let n=uK(e,t);return t?n:e.diffHeaderHeight+n}function uK(e,t){return e.paddingTop??(t?e.spacing:0)}function dK(e){return e.paddingBottom??e.spacing}function fK(e){switch(e){case`simple`:return 4;case`metadata`:case`line-info`:case`line-info-basic`:case`custom`:return 32}}function pK(e,t){return e===t||e?.cacheKey!=null&&e.cacheKey===t?.cacheKey}function mK(e,t){return NM(e.theme,t.theme)&&e.useTokenTransformer===t.useTokenTransformer&&e.tokenizeMaxLineLength===t.tokenizeMaxLineLength&&e.lineDiffType===t.lineDiffType&&e.maxLineDiffLength===t.maxLineDiffLength}function hK({line:e,spanStart:t,spanLength:n}){return{start:{line:e,character:t},end:{line:e,character:t+n},properties:{"data-diff-span":``},alwaysWrap:!0}}function gK({item:e,arr:t,enableJoin:n,isNeutral:r=!1,isLastItem:i=!1}){let a=t[t.length-1];if(a==null||i||!n){t.push([+!r,e.value]);return}let o=a[0]===0;if(r===o||r&&e.value.length===1&&!o){a[1]+=e.value;return}t.push([+!r,e.value])}function _K(e){return[zM(e.additionStart,e.additionCount)+1,BM(e.additionStart,e.additionCount)+1]}function vK({isPartial:e,rangeSize:t,expandedHunks:n,hunkIndex:r,collapsedContextThreshold:i}){let a=Math.max(t,0);if(a===0||e)return{fromStart:0,fromEnd:0,rangeSize:a,collapsedLines:a,renderAll:!1};if(n===!0||a<=i)return{fromStart:a,fromEnd:0,rangeSize:a,collapsedLines:0,renderAll:!0};let o=n?.get(r),s=Math.min(Math.max(o?.fromStart??0,0),a),c=Math.min(Math.max(o?.fromEnd??0,0),a),l=s+c,u=l>=a;return{fromStart:u?a:s,fromEnd:u?0:c,rangeSize:a,collapsedLines:Math.max(a-l,0),renderAll:u}}function yK(e){let t=e.hunks[e.hunks.length-1];if(t==null||e.isPartial||e.additionLines.length===0||e.deletionLines.length===0)return!1;let n=e.additionLines.length-BM(t.additionStart,t.additionCount),r=e.deletionLines.length-BM(t.deletionStart,t.deletionCount);return n<=0&&r<=0?!1:n!==r}function bK({fileDiff:e,errorPrefix:t}){let n=e.hunks[e.hunks.length-1];if(n==null||e.isPartial||e.additionLines.length===0||e.deletionLines.length===0)return 0;let r=e.additionLines.length-BM(n.additionStart,n.additionCount),i=e.deletionLines.length-BM(n.deletionStart,n.deletionCount);if(r<=0&&i<=0)return 0;if(r!==i)throw Error(`${t}: trailing context mismatch (additions=${r}, deletions=${i}) for ${e.name}`);return Math.min(r,i)}function xK({fileDiff:e,hunkIndex:t,expandedHunks:n,collapsedContextThreshold:r,errorPrefix:i}){if(t!==e.hunks.length-1)return;let a=bK({fileDiff:e,errorPrefix:i});if(a<=0)return;if(n===!0||a<=r)return{fromStart:a,fromEnd:0,rangeSize:a,collapsedLines:0,renderAll:!0};let o=n?.get(e.hunks.length),s=Math.min(Math.max(o?.fromStart??0,0),a);return{fromStart:s,fromEnd:0,rangeSize:a,collapsedLines:a-s,renderAll:s>=a}}function SK({fileDiff:e,lineNumber:t,expandedHunks:n,collapsedContextThreshold:r}){if(n===!0||e.isPartial)return!0;for(let[i,a]of e.hunks.entries()){let[o,s]=_K(a);if(t<o){let s=vK({isPartial:e.isPartial,rangeSize:a.collapsedBefore,expandedHunks:n,hunkIndex:i,collapsedContextThreshold:r}),c=o-s.rangeSize;return s.renderAll||t<c+s.fromStart||t>=o-s.fromEnd}if(t<s)return!0}let i=xK({fileDiff:e,hunkIndex:e.hunks.length-1,expandedHunks:n,collapsedContextThreshold:r,errorPrefix:`isAdditionLineRenderable`});if(i==null||i.renderAll)return!0;let a=e.hunks[e.hunks.length-1],[,o]=_K(a);return t<o+i.fromStart||t>=o+i.rangeSize}function CK({fileDiff:e,lineNumber:t,direction:n,expandedHunks:r,collapsedContextThreshold:i}){if(r===!0||e.isPartial)return t;let a=[],o=1;for(let[t,n]of e.hunks.entries()){let[s,c]=_K(n),l=vK({isPartial:e.isPartial,rangeSize:n.collapsedBefore,expandedHunks:r,hunkIndex:t,collapsedContextThreshold:i}),u=s-l.rangeSize;l.renderAll?a.push([u,s]):(l.fromStart>0&&a.push([u,u+l.fromStart]),l.fromEnd>0&&a.push([s-l.fromEnd,s])),a.push([s,c]),o=c}let s=xK({fileDiff:e,hunkIndex:e.hunks.length-1,expandedHunks:r,collapsedContextThreshold:i,errorPrefix:`getNearestRenderableAdditionLine`});if(s!=null){let e=o;o=e+s.rangeSize,s.renderAll?a.push([e,o]):s.fromStart>0&&a.push([e,e+s.fromStart])}if(t>=o)return t;if(n===`down`){for(let[e,n]of a)if(n>t)return Math.max(e,t);return}for(let e=a.length-1;e>=0;e--){let[n,r]=a[e];if(n<=t)return Math.min(r-1,t)}}function wK({type:e,metrics:t}){return t.hunkSeparatorHeight??fK(e)}function TK({type:e,metrics:t}){return e===`simple`||e===`metadata`||e===`line-info-basic`?0:t.spacing}function EK({type:e,hunkIndex:t,hunkSpecs:n}){switch(e){case`simple`:return t>0;case`metadata`:return n!=null;case`line-info`:case`line-info-basic`:case`custom`:return!0}}function DK(e){return e!==`simple`&&e!==`metadata`}function OK({type:e,metrics:t,hunkIndex:n,hunkSpecs:r}){if(!EK({type:e,hunkIndex:n,hunkSpecs:r}))return;let i=wK({type:e,metrics:t}),a=TK({type:e,metrics:t}),o=n>0?a:0,s=a;return{height:i,gapBefore:o,gapAfter:s,totalHeight:o+i+s}}function kK({type:e,metrics:t}){if(!DK(e))return;let n=wK({type:e,metrics:t}),r=TK({type:e,metrics:t});return{height:n,gapBefore:r,gapAfter:0,totalHeight:r+n}}function AK({diff:e,diffStyle:t,startingLine:n=0,totalLines:r=1/0,expandedHunks:i,collapsedContextThreshold:a=1,callback:o}){let s=jK({diff:e,diffStyle:t,startingLine:n,expandedHunks:i,collapsedContextThreshold:a}),c={viewportStart:n,viewportEnd:n+r,isWindowedHighlight:n>0||r<1/0,splitCount:s.splitCount,unifiedCount:s.unifiedCount,finalHunkIndex:e.hunks.length-1,shouldBreak(){if(!c.isWindowedHighlight)return!1;let e=c.unifiedCount>=n+r,i=c.splitCount>=n+r;return t===`unified`?e:(t===`split`||e)&&i},shouldSkip(e,r){if(!c.isWindowedHighlight)return!1;let i=e>0&&c.unifiedCount+e<=n,a=r>0&&c.splitCount+r<=n;return t===`unified`?i:(t===`split`||i)&&a},incrementCounts(e,n){(t===`unified`||t===`both`)&&(c.unifiedCount+=e),(t===`split`||t===`both`)&&(c.splitCount+=n)},isInWindow(e,n){if(!c.isWindowedHighlight)return!0;let r=c.isInUnifiedWindow(e),i=c.isInSplitWindow(n);return t===`unified`?r:t===`split`?i:r||i},isInUnifiedWindow(e){return!c.isWindowedHighlight||c.unifiedCount>=n-e&&c.unifiedCount<n+r},isInSplitWindow(e){return!c.isWindowedHighlight||c.splitCount>=n-e&&c.splitCount<n+r},emit(e,n=!1){return n||(t===`unified`?c.incrementCounts(1,0):t===`split`?c.incrementCounts(0,1):c.incrementCounts(1,1)),o(e)??!1}};hunkIterator:for(let n=s.hunkIndex;n<e.hunks.length;n++){let r=e.hunks[n];if(r==null)throw Error(`iterateOverDiff: invalid hunk index`);if(c.shouldBreak())break;let o=zM(r.deletionStart,r.deletionCount),s=zM(r.additionStart,r.additionCount),l=!e.isPartial&&r.deletionCount===0?o:r.deletionLineIndex,u=!e.isPartial&&r.additionCount===0?s:r.additionLineIndex,d=vK({isPartial:e.isPartial,rangeSize:r.collapsedBefore,expandedHunks:i,hunkIndex:n,collapsedContextThreshold:a}),f=n===c.finalHunkIndex?xK({fileDiff:e,hunkIndex:n,expandedHunks:i,collapsedContextThreshold:a,errorPrefix:`iterateOverDiff`}):void 0,p=d.fromStart+d.fromEnd;function m(e,n){return f==null||f.collapsedLines<=0||f.fromStart+f.fromEnd>0?0:t===`unified`?e===r.unifiedLineStart+r.unifiedLineCount-1?f.collapsedLines:0:n===r.splitLineStart+r.splitLineCount-1?f.collapsedLines:0}let h=d.collapsedLines===0;function g(){return h?0:(h=!0,d.collapsedLines)}if(c.shouldSkip(p,p))c.incrementCounts(p,p),g();else{let e=r.unifiedLineStart-d.rangeSize,i=r.splitLineStart-d.rangeSize,a=l-d.rangeSize,f=u-d.rangeSize,p=o+1-d.rangeSize,m=s+1-d.rangeSize;if(PK(c,d.fromStart,t,t=>c.emit({hunkIndex:n,hunk:r,collapsedBefore:0,collapsedAfter:0,type:`context-expanded`,deletionLine:{lineNumber:p+t,lineIndex:a+t,noEOFCR:!1,unifiedLineIndex:e+t,splitLineIndex:i+t},additionLine:{unifiedLineIndex:e+t,splitLineIndex:i+t,lineIndex:f+t,lineNumber:m+t,noEOFCR:!1}}))||(e=r.unifiedLineStart-d.fromEnd,i=r.splitLineStart-d.fromEnd,a=l-d.fromEnd,f=u-d.fromEnd,p=o+1-d.fromEnd,m=s+1-d.fromEnd,PK(c,d.fromEnd,t,t=>c.emit({hunkIndex:n,hunk:r,collapsedBefore:g(),collapsedAfter:0,type:`context-expanded`,deletionLine:{lineNumber:p+t,lineIndex:a+t,noEOFCR:!1,unifiedLineIndex:e+t,splitLineIndex:i+t},additionLine:{unifiedLineIndex:e+t,splitLineIndex:i+t,lineIndex:f+t,lineNumber:m+t,noEOFCR:!1}}),()=>{g()})))break hunkIterator}let _=r.unifiedLineStart,v=r.splitLineStart,y=l,b=u,x=o+1,ee=s+1,te=r.hunkContent.at(-1);for(let e of r.hunkContent){if(c.shouldBreak())break hunkIterator;let i=e===te;if(e.type===`context`){if(c.shouldSkip(e.lines,e.lines))c.incrementCounts(e.lines,e.lines),g();else if(PK(c,e.lines,t,t=>{let a=i&&t===e.lines-1,o=_+t,s=v+t;return c.emit({hunkIndex:n,hunk:r,collapsedBefore:g(),collapsedAfter:m(o,s),type:`context`,deletionLine:{lineNumber:x+t,lineIndex:y+t,noEOFCR:a&&r.noEOFCRDeletions,unifiedLineIndex:o,splitLineIndex:s},additionLine:{unifiedLineIndex:o,splitLineIndex:s,lineIndex:b+t,lineNumber:ee+t,noEOFCR:a&&r.noEOFCRAdditions}})},()=>{g()}))break hunkIterator;_+=e.lines,v+=e.lines,y+=e.lines,b+=e.lines,x+=e.lines,ee+=e.lines}else{let a=Math.max(e.deletions,e.additions),o=e.deletions+e.additions;if(!c.shouldSkip(o,a)){let s=FK(c,e,t);(s[0]?.[0]??0)>0&&g();for(let[l,u]of s)for(let s=l;s<u;s++){let l=m(_+s,t===`unified`?v+(s<e.deletions?s:s-e.deletions):v+s);if(c.emit(IK({hunkIndex:n,hunk:r,collapsedBefore:g(),collapsedAfter:l,diffStyle:t,index:s,unifiedLineIndex:_,splitLineIndex:v,additionLineIndex:b,deletionLineIndex:y,additionLineNumber:ee,deletionLineNumber:x,content:e,isLastContent:i,unifiedCount:o,splitCount:a}),!0))break hunkIterator}}g(),c.incrementCounts(o,a),_+=o,v+=a,y+=e.deletions,b+=e.additions,x+=e.deletions,ee+=e.additions}}if(f!=null){let{collapsedLines:n,fromStart:r,fromEnd:i}=f,a=r+i;if(PK(c,a,t,t=>{let r=t===a-1;return c.emit({hunkIndex:e.hunks.length,hunk:void 0,collapsedBefore:0,collapsedAfter:r?n:0,type:`context-expanded`,deletionLine:{lineNumber:x+t,lineIndex:y+t,noEOFCR:!1,unifiedLineIndex:_+t,splitLineIndex:v+t},additionLine:{unifiedLineIndex:_+t,splitLineIndex:v+t,lineIndex:b+t,lineNumber:ee+t,noEOFCR:!1}})},void 0,()=>c.shouldBreak()))break hunkIterator}}}function jK({diff:e,diffStyle:t,startingLine:n,expandedHunks:r,collapsedContextThreshold:i}){if(n<=0||t===`both`)return{hunkIndex:0,splitCount:0,unifiedCount:0};let a=MK({diff:e,expandedHunks:r,collapsedContextThreshold:i}),o=0,s=e.hunks.length-1,c=e.hunks.length;for(;o<=s;){let e=o+s>>1,r=a[e+1];if(r==null)throw Error(`iterateOverDiff: invalid hunk prefix index`);(t===`unified`?r.unifiedCount:r.splitCount)>n?(c=e,s=e-1):o=e+1}if(c>=e.hunks.length){let t=a[e.hunks.length];if(t==null)throw Error(`iterateOverDiff: invalid terminal hunk prefix index`);return{hunkIndex:e.hunks.length,splitCount:t.splitCount,unifiedCount:t.unifiedCount}}let l=a[c];if(l==null)throw Error(`iterateOverDiff: invalid selected hunk prefix index`);return{hunkIndex:c,splitCount:l.splitCount,unifiedCount:l.unifiedCount}}function MK({diff:e,expandedHunks:t,collapsedContextThreshold:n}){let r=0,i=0,a=e.hunks.length-1,o=[{splitCount:0,unifiedCount:0}];for(let s=0;s<e.hunks.length;s++){let c=e.hunks[s];if(c==null)throw Error(`iterateOverDiff: invalid hunk summary index`);let l=vK({isPartial:e.isPartial,rangeSize:c.collapsedBefore,expandedHunks:t,hunkIndex:s,collapsedContextThreshold:n}),u=l.fromStart+l.fromEnd;r+=u+c.splitLineCount,i+=u+c.unifiedLineCount;let d=s===a?xK({fileDiff:e,hunkIndex:s,expandedHunks:t,collapsedContextThreshold:n,errorPrefix:`iterateOverDiff`}):void 0;if(d!=null){let e=d.fromStart+d.fromEnd;r+=e,i+=e}o.push({splitCount:r,unifiedCount:i})}return o}function NK(e,t,n){if(!e.isWindowedHighlight||t<=0)return[0,t];let r=[];function i(n){let i=Math.max(0,e.viewportStart-n),a=Math.min(t,e.viewportEnd-n);a>i&&r.push([i,a])}if(n!==`split`&&i(e.unifiedCount),n!==`unified`&&i(e.splitCount),r.length===0)return[0,0];let a=r[0][0],o=r[0][1];for(let e=1;e<r.length;e++){let t=r[e];a=Math.min(a,t[0]),o=Math.max(o,t[1])}return[a,o]}function PK(e,t,n,r,i,a){let[o,s]=NK(e,t,n);o>0&&(e.incrementCounts(o,o),i?.());let c=o;for(;c<t;){if(a?.()===!0)return!0;if(c>=s){e.incrementCounts(t-c,t-c);break}if(e.isInWindow(0,0)){if(r(c)===!0)return!0}else e.incrementCounts(1,1);c++}return!1}function FK(e,t,n){if(!e.isWindowedHighlight)return[[0,n===`unified`?t.deletions+t.additions:Math.max(t.deletions,t.additions)]];let r=n!==`split`,i=n!==`unified`,a=n===`unified`?`unified`:`split`,o=[];function s(t,n){if(t+n<=e.viewportStart||t>=e.viewportEnd)return;let r=Math.max(0,e.viewportStart-t),i=Math.min(n,e.viewportEnd-t);return i>r?[r,i]:void 0}function c(e,n){return a===`split`?e:n===`additions`?[e[0]+t.deletions,e[1]+t.deletions]:e}function l(e,t){if(e==null)return;let[n,r]=c(e,t);r>n&&o.push([n,r])}if(r&&(l(s(e.unifiedCount,t.deletions),`deletions`),l(s(e.unifiedCount+t.deletions,t.additions),`additions`)),i&&(l(s(e.splitCount,t.deletions),`deletions`),l(s(e.splitCount,t.additions),`additions`)),o.length===0)return o;o.sort((e,t)=>e[0]-t[0]);let u=[o[0]];for(let[e,t]of o.slice(1)){let n=u[u.length-1];e<=n[1]?n[1]=Math.max(n[1],t):u.push([e,t])}return u}function IK({hunkIndex:e,hunk:t,collapsedAfter:n,collapsedBefore:r,diffStyle:i,index:a,unifiedLineIndex:o,splitLineIndex:s,additionLineIndex:c,deletionLineIndex:l,additionLineNumber:u,deletionLineNumber:d,content:f,isLastContent:p,unifiedCount:m,splitCount:h}){let g=a<f.deletions?o+a:void 0,_=i===`unified`?a>=f.deletions?o+a:void 0:a<f.additions?o+f.deletions+a:void 0,v=i===`unified`?s+(a<f.deletions?a:a-f.deletions):s+a,y=a<f.deletions?l+a:void 0,b=a<f.deletions?d+a:void 0,x=i===`unified`?a>=f.deletions?c+(a-f.deletions):void 0:a<f.additions?c+a:void 0,ee=i===`unified`?a>=f.deletions?u+(a-f.deletions):void 0:a<f.additions?u+a:void 0,te=i===`unified`?p&&a===f.deletions-1&&t.noEOFCRDeletions:p&&a===h-1&&t.noEOFCRDeletions,ne=i===`unified`?p&&a===m-1&&t.noEOFCRAdditions:p&&a===h-1&&t.noEOFCRAdditions,re=y!=null&&b!=null&&g!=null?{lineNumber:b,lineIndex:y,noEOFCR:te,unifiedLineIndex:g,splitLineIndex:v}:void 0,ie=x!=null&&ee!=null&&_!=null?{unifiedLineIndex:_,splitLineIndex:v,lineIndex:x,lineNumber:ee,noEOFCR:ne}:void 0;if(re==null&&ie!=null)return{type:`change`,hunkIndex:e,hunk:t,collapsedAfter:n,collapsedBefore:r,deletionLine:void 0,additionLine:ie};if(re!=null&&ie==null)return{type:`change`,hunkIndex:e,hunk:t,collapsedAfter:n,collapsedBefore:r,deletionLine:re,additionLine:void 0};if(re==null||ie==null)throw Error(`iterateOverDiff: missing change line data`);return{type:`change`,hunkIndex:e,hunk:t,collapsedAfter:n,collapsedBefore:r,deletionLine:re,additionLine:ie}}var LK={forcePlainText:!1};function RK(e,t,n,{forcePlainText:r,startingLine:i,totalLines:a,expandedHunks:o,collapsedContextThreshold:s=1}=LK){r?(i??=0,a??=1/0):(i=0,a=1/0);let c=i>0||a<1/0,l=typeof n.theme==`string`?t.getTheme(n.theme).type:void 0,u=gG({theme:n.theme,highlighter:t}),d=r&&!c&&(e.unifiedLineCount>1e3||e.splitLineCount>1e3)?`none`:n.lineDiffType,f={deletionLines:[],additionLines:[]},{maxLineDiffLength:p}=n,m=!r&&!e.isPartial,h=r?o:void 0,g=new Map;function _(e){let t=m?0:e,n=g.get(t)??BK();return g.set(t,n),n}function v(e,t,n,r){if(c){let e=n.at(-1);(e==null||e.targetIndex+e.count!==t)&&(e={targetIndex:t,originalOffset:r.length,count:0},n.push(e)),e.count++}r.push(e)}AK({diff:e,diffStyle:`both`,startingLine:i,totalLines:a,expandedHunks:!c||h,collapsedContextThreshold:s,callback:({hunkIndex:t,additionLine:n,deletionLine:r,type:i})=>{let a=_(t),o=n==null?r.splitLineIndex:n.splitLineIndex;i===`change`&&n!=null&&r!=null&&zK({additionLine:e.additionLines[n.lineIndex],deletionLine:e.deletionLines[r.lineIndex],deletionLineIndex:a.deletionContent.length,additionLineIndex:a.additionContent.length,deletionDecorations:a.deletionDecorations,additionDecorations:a.additionDecorations,lineDiffType:d,maxLineDiffLength:p}),r!=null&&(v(e.deletionLines[r.lineIndex],r.lineIndex,a.deletionSegments,a.deletionContent),a.deletionInfo.push({type:i===`change`?`change-deletion`:i,lineNumber:r.lineNumber,altLineNumber:i===`change`?void 0:n.lineNumber??void 0,lineIndex:`${r.unifiedLineIndex},${o}`})),n!=null&&(v(e.additionLines[n.lineIndex],n.lineIndex,a.additionSegments,a.additionContent),a.additionInfo.push({type:i===`change`?`change-addition`:i,lineNumber:n.lineNumber,altLineNumber:i===`change`?void 0:r.lineNumber??void 0,lineIndex:`${n.unifiedLineIndex},${o}`}))}});for(let i of g.values()){if(i.deletionContent.length===0&&i.additionContent.length===0)continue;let a={name:e.prevName??e.name,contents:i.deletionContent.value},o={name:e.name,contents:i.additionContent.value},{deletionLines:s,additionLines:c}=VK({deletionFile:a,deletionInfo:i.deletionInfo,deletionDecorations:i.deletionDecorations,additionFile:o,additionInfo:i.additionInfo,additionDecorations:i.additionDecorations,highlighter:t,options:n,languageOverride:r?`text`:e.lang});if(m){f.deletionLines=s,f.additionLines=c;continue}if(i.deletionSegments.length>0)for(let e of i.deletionSegments)for(let t=0;t<e.count;t++)f.deletionLines[e.targetIndex+t]=s[e.originalOffset+t];else f.deletionLines.push(...s);if(i.additionSegments.length>0)for(let e of i.additionSegments)for(let t=0;t<e.count;t++)f.additionLines[e.targetIndex+t]=c[e.originalOffset+t];else f.additionLines.push(...c)}return{code:f,themeStyles:u,baseThemeType:l}}function zK({deletionLine:e,additionLine:t,deletionLineIndex:n,additionLineIndex:r,deletionDecorations:i,additionDecorations:a,lineDiffType:o,maxLineDiffLength:s}){if(e==null||t==null||o===`none`||(e=RM(e),t=RM(t),e.length>s||t.length>s))return;let c=o===`char`?UM(e,t):oN(e,t),l=[],u=[],d=o===`word-alt`,f=c.at(-1);for(let e of c){let t=e===f;!e.added&&!e.removed?(gK({item:e,arr:l,enableJoin:d,isNeutral:!0,isLastItem:t}),gK({item:e,arr:u,enableJoin:d,isNeutral:!0,isLastItem:t})):e.removed?gK({item:e,arr:l,enableJoin:d,isLastItem:t}):gK({item:e,arr:u,enableJoin:d,isLastItem:t})}let p=0;for(let e of l)e[0]===1&&i.push(hK({line:n,spanStart:p,spanLength:e[1].length})),p+=e[1].length;p=0;for(let e of u)e[0]===1&&a.push(hK({line:r,spanStart:p,spanLength:e[1].length})),p+=e[1].length}function BK(){return{deletionContent:{push(e){this.value+=e,this.length++},value:``,length:0},additionContent:{push(e){this.value+=e,this.length++},value:``,length:0},deletionInfo:[],additionInfo:[],deletionDecorations:[],additionDecorations:[],deletionSegments:[],additionSegments:[]}}function VK({deletionFile:e,additionFile:t,deletionInfo:n,additionInfo:r,highlighter:i,deletionDecorations:a,additionDecorations:o,languageOverride:s,options:{theme:c=fM,...l}}){let u=s??BW(e.name),d=s??BW(t.name),{state:f,transformers:p}=eG(l.useTokenTransformer),m=typeof c==`string`?{...l,lang:`text`,theme:c,transformers:p,decorations:void 0,defaultColor:!1,cssVariablePrefix:rG(`token`),tokenizeTimeLimit:0}:{...l,lang:`text`,themes:c,transformers:p,decorations:void 0,defaultColor:!1,cssVariablePrefix:rG(`token`),tokenizeTimeLimit:0};return{deletionLines:e.contents===``?[]:(m.lang=u,f.lineInfo=n,m.decorations=a,vG(i.codeToHast(RM(e.contents),m))),additionLines:t.contents===``?[]:(m.lang=d,m.decorations=o,f.lineInfo=r,vG(i.codeToHast(RM(t.contents),m)))}}function HK(e){let t=e.lang??BW(e.name),n=e.lang??(e.prevName==null?`text`:BW(e.prevName));return t===`text`&&n===`text`}function UK(e){let t=[];for(let n of e){let e=sI.get(n);if(e==null)throw Error(`getResolvedLanguages: ${n} is not resolved. Please resolve languages before calling getResolvedLanguages`);t.push(e)}return t}function WK(e){for(let t of Array.isArray(e)?e:[e])if(!sI.has(t))return!1;return!0}async function GK(e){let t=[],n=[];for(let r of e){if(r===`text`||r===`ansi`)continue;let e=LU(r)??IU(r);`then`in e?n.push(e):t.push(e)}return n.length>0&&await Promise.all(n).then(e=>{for(let n of e){if(n==null)throw Error(`resolvedLanguages: unable to resolve language`);t.push(n)}}),t}function KK(e){return YU.getResolvedThemes(e)}async function qK(e){for(let t of e)_W(t);let t=await YU.resolveThemes(e);for(let n=0;n<e.length;n++)vW(e[n],t[n]);return t}var JK={light:`pierre-light`,dark:`pierre-dark`};function YK(e){return e===`dark`?JK.dark:JK.light}var XK=2166136261,ZK=16777619,QK=2654435769,$K=2246822507;function eq(e,t=XK,n=ZK){let r=t>>>0;for(let t=0;t<e.length;t+=1)r^=e.charCodeAt(t),r=Math.imul(r,n)>>>0;return r>>>0}function tq(e,t=`diff-panel`){let n=e.trim(),r=eq(n,XK,ZK).toString(36),i=eq(n,QK,$K).toString(36);return`${t}:${n.length}:${r}:${i}`}function nq(e){return Ca(`flex items-center justify-between gap-2 px-4 wco:pr-[calc(100vw-env(titlebar-area-width)-env(titlebar-area-x)+1em)]`,bn&&e!==`sheet`?`h-[52px] border-b border-border wco:h-[env(titlebar-area-height)]`:`h-12 wco:max-h-[env(titlebar-area-height)]`)}function rq(e){let t=(0,A.c)(10),n=bn&&e.mode!==`sheet`,r=e.mode===`inline`?`w-[42vw] min-w-[360px] max-w-[560px] shrink-0 border-l border-border`:`w-full`,i;t[0]===r?i=t[1]:(i=Ca(`flex h-full min-w-0 flex-col bg-background`,r),t[0]=r,t[1]=i);let a;t[2]!==e.header||t[3]!==e.mode||t[4]!==n?(a=n?(0,k.jsx)(`div`,{className:nq(e.mode),children:e.header}):(0,k.jsx)(`div`,{className:`border-b border-border`,children:(0,k.jsx)(`div`,{className:nq(e.mode),children:e.header})}),t[2]=e.header,t[3]=e.mode,t[4]=n,t[5]=a):a=t[5];let o;return t[6]!==e.children||t[7]!==i||t[8]!==a?(o=(0,k.jsxs)(`div`,{className:i,children:[a,e.children]}),t[6]=e.children,t[7]=i,t[8]=a,t[9]=o):o=t[9],o}function iq(){let e=(0,A.c)(4),t,n;e[0]===Symbol.for(`react.memo_cache_sentinel`)?(t=(0,k.jsx)(Aw,{className:`absolute left-0 top-1/2 size-6 -translate-y-1/2 rounded-md border border-border/50`}),n=(0,k.jsx)(Aw,{className:`absolute right-0 top-1/2 size-6 -translate-y-1/2 rounded-md border border-border/50`}),e[0]=t,e[1]=n):(t=e[0],n=e[1]);let r;e[2]===Symbol.for(`react.memo_cache_sentinel`)?(r=(0,k.jsxs)(`div`,{className:`relative min-w-0 flex-1`,children:[t,n,(0,k.jsxs)(`div`,{className:`flex gap-1 overflow-hidden px-8 py-0.5`,children:[(0,k.jsx)(Aw,{className:`h-6 w-16 shrink-0 rounded-md`}),(0,k.jsx)(Aw,{className:`h-6 w-24 shrink-0 rounded-md`}),(0,k.jsx)(Aw,{className:`h-6 w-24 shrink-0 rounded-md max-sm:hidden`})]})]}),e[2]=r):r=e[2];let i;return e[3]===Symbol.for(`react.memo_cache_sentinel`)?(i=(0,k.jsxs)(k.Fragment,{children:[r,(0,k.jsxs)(`div`,{className:`flex shrink-0 gap-1`,children:[(0,k.jsx)(Aw,{className:`size-7 rounded-md`}),(0,k.jsx)(Aw,{className:`size-7 rounded-md`})]})]}),e[3]=i):i=e[3],i}function aq(e){let t=(0,A.c)(7),n;t[0]===Symbol.for(`react.memo_cache_sentinel`)?(n=(0,k.jsxs)(`div`,{className:`flex items-center gap-2 border-b border-border/50 px-3 py-2`,children:[(0,k.jsx)(Aw,{className:`h-4 w-32 rounded-full`}),(0,k.jsx)(Aw,{className:`ml-auto h-4 w-20 rounded-full`})]}),t[0]=n):n=t[0];let r;t[1]===Symbol.for(`react.memo_cache_sentinel`)?(r=(0,k.jsxs)(`div`,{className:`space-y-2`,children:[(0,k.jsx)(Aw,{className:`h-3 w-full rounded-full`}),(0,k.jsx)(Aw,{className:`h-3 w-full rounded-full`}),(0,k.jsx)(Aw,{className:`h-3 w-10/12 rounded-full`}),(0,k.jsx)(Aw,{className:`h-3 w-11/12 rounded-full`}),(0,k.jsx)(Aw,{className:`h-3 w-9/12 rounded-full`})]}),t[1]=r):r=t[1];let i;t[2]===e.label?i=t[3]:(i=(0,k.jsxs)(`div`,{className:`flex min-h-0 flex-1 flex-col gap-4 px-3 py-4`,children:[r,(0,k.jsx)(`span`,{className:`sr-only`,children:e.label})]}),t[2]=e.label,t[3]=i);let a;return t[4]!==e.label||t[5]!==i?(a=(0,k.jsx)(`div`,{className:`flex min-h-0 flex-1 flex-col p-2`,children:(0,k.jsxs)(`div`,{className:`flex min-h-0 flex-1 flex-col overflow-hidden rounded-md border border-border/60 bg-card/25`,role:`status`,"aria-live":`polite`,"aria-label":e.label,children:[n,i]})}),t[4]=e.label,t[5]=i,t[6]=a):a=t[6],a}function oq(e){let t=(0,O.useRef)(e);return(0,O.useInsertionEffect)(()=>void(t.current=e)),(0,O.useCallback)((...e)=>t.current(...e),[])}var sq=(0,O.createContext)(void 0);function cq(){return(0,O.useContext)(sq)}var lq={position:`absolute`,top:0,bottom:0,textAlign:`center`,whiteSpace:`normal`,touchAction:`none`},uq={display:`contents`};function dq(){return null}var fq=t(n(((e,t)=>{(function(n,r){typeof e==`object`&&t!==void 0?r(e):typeof define==`function`&&define.amd?define([`exports`],r):r((n||=self).lru_map=n.lru_map||{})})(e,function(e){let t=Symbol(`newer`),n=Symbol(`older`);class r{constructor(e,t){typeof e!=`number`&&(t=e,e=0),this.size=0,this.limit=e,this.oldest=this.newest=void 0,this._keymap=new Map,t&&(this.assign(t),e<1&&(this.limit=this.size))}_markEntryAsUsed(e){e!==this.newest&&(e[t]&&(e===this.oldest&&(this.oldest=e[t]),e[t][n]=e[n]),e[n]&&(e[n][t]=e[t]),e[t]=void 0,e[n]=this.newest,this.newest&&(this.newest[t]=e),this.newest=e)}assign(e){let r,a=this.limit||Number.MAX_VALUE;this._keymap.clear();let o=e[Symbol.iterator]();for(let e=o.next();!e.done;e=o.next()){let o=new i(e.value[0],e.value[1]);if(this._keymap.set(o.key,o),r?(r[t]=o,o[n]=r):this.oldest=o,r=o,a--==0)throw Error(`overflow`)}this.newest=r,this.size=this._keymap.size}get(e){var t=this._keymap.get(e);return t?(this._markEntryAsUsed(t),t.value):void 0}set(e,r){var a=this._keymap.get(e);return a?(a.value=r,this._markEntryAsUsed(a),this):(this._keymap.set(e,a=new i(e,r)),this.newest?(this.newest[t]=a,a[n]=this.newest):this.oldest=a,this.newest=a,++this.size,this.size>this.limit&&this.shift(),this)}shift(){var e=this.oldest;if(e)return this.oldest[t]?(this.oldest=this.oldest[t],this.oldest[n]=void 0):(this.oldest=void 0,this.newest=void 0),e[t]=e[n]=void 0,this._keymap.delete(e.key),--this.size,[e.key,e.value]}find(e){let t=this._keymap.get(e);return t?t.value:void 0}has(e){return this._keymap.has(e)}delete(e){var r=this._keymap.get(e);return r?(this._keymap.delete(r.key),r[t]&&r[n]?(r[n][t]=r[t],r[t][n]=r[n]):r[t]?(r[t][n]=void 0,this.oldest=r[t]):r[n]?(r[n][t]=void 0,this.newest=r[n]):this.oldest=this.newest=void 0,this.size--,r.value):void 0}clear(){this.oldest=this.newest=void 0,this.size=0,this._keymap.clear()}keys(){return new o(this.oldest)}values(){return new s(this.oldest)}entries(){return this}[Symbol.iterator](){return new a(this.oldest)}forEach(e,n){typeof n!=`object`&&(n=this);let r=this.oldest;for(;r;)e.call(n,r.value,r.key,this),r=r[t]}toJSON(){for(var e=Array(this.size),n=0,r=this.oldest;r;)e[n++]={key:r.key,value:r.value},r=r[t];return e}toString(){for(var e=``,n=this.oldest;n;)e+=String(n.key)+`:`+n.value,n=n[t],n&&(e+=` < `);return e}}e.LRUMap=r;function i(e,r){this.key=e,this.value=r,this[t]=void 0,this[n]=void 0}function a(e){this.entry=e}a.prototype[Symbol.iterator]=function(){return this},a.prototype.next=function(){let e=this.entry;return e?(this.entry=e[t],{done:!1,value:[e.key,e.value]}):{done:!0,value:void 0}};function o(e){this.entry=e}o.prototype[Symbol.iterator]=function(){return this},o.prototype.next=function(){let e=this.entry;return e?(this.entry=e[t],{done:!1,value:e.key}):{done:!0,value:void 0}};function s(e){this.entry=e}s.prototype[Symbol.iterator]=function(){return this},s.prototype.next=function(){let e=this.entry;return e?(this.entry=e[t],{done:!1,value:e.value}):{done:!0,value:void 0}}})}))(),1),pq=Symbol(`IGNORE_RESPONSE`),mq=class extends Error{constructor(){super(`WorkerPoolManager: operation canceled because the pool terminated`)}},hq=class extends Error{constructor(){super(`WorkerPoolManager: operation canceled before the task completed`)}},gq=class{options;highlighter;preferredHighlighter;renderOptions;renderOptionsRequestVersion=0;renderOptionsVersion=0;initialized=!1;workers=[];queuedTasks=[];queuedTaskByInstance=new Map;taskByHighlightKey=new Map;activeTaskById=new Map;activeRequestByInstance=new Map;nextRequestId=0;themeSubscribers=new Set;workersFailed=!1;statSubscribers=new Set;fileCache;diffCache;_queuedBroadcast;lifecycleGeneration=0;constructor(e,{langs:t,theme:n=fM,useTokenTransformer:r=!1,lineDiffType:i=`word-alt`,maxLineDiffLength:a=1e3,tokenizeMaxLineLength:o=1e3,preferredHighlighter:s=`shiki-js`}){this.options=e,this.preferredHighlighter=s,this.renderOptions={theme:n,useTokenTransformer:r,lineDiffType:i,maxLineDiffLength:a,tokenizeMaxLineLength:o},this.fileCache=new fq.default.LRUMap(e.totalASTLRUCacheSize??100),this.diffCache=new fq.default.LRUMap(e.totalASTLRUCacheSize??100),this.queueInitialization(t)}isWorkingPool(){return!this.workersFailed}getFileResultCache(e){return e.cacheKey==null?void 0:this.fileCache.get(e.cacheKey)}getDiffResultCache(e){return e.cacheKey==null?void 0:this.diffCache.get(e.cacheKey)}inspectCaches(){let{fileCache:e,diffCache:t}=this;return{fileCache:e,diffCache:t}}evictFileFromCache(e){try{return this.fileCache.delete(e)!==void 0}finally{this.queueBroadcastStateChanges()}}evictDiffFromCache(e){try{return this.diffCache.delete(e)!==void 0}finally{this.queueBroadcastStateChanges()}}async setRenderOptions({theme:e=this.renderOptions.theme??fM,useTokenTransformer:t=this.renderOptions.useTokenTransformer??!1,lineDiffType:n=this.renderOptions.lineDiffType??`word-alt`,maxLineDiffLength:r=this.renderOptions.maxLineDiffLength??1e3,tokenizeMaxLineLength:i=this.renderOptions.tokenizeMaxLineLength??1e3}){let{lifecycleGeneration:a}=this,o=++this.renderOptionsRequestVersion,s=()=>this.isCurrentLifecycle(a)&&this.renderOptionsRequestVersion===o;try{let a={theme:e,useTokenTransformer:t,lineDiffType:n,maxLineDiffLength:r,tokenizeMaxLineLength:i};if(this.isInitialized()||await this.initialize(),!s()||mK(a,this.renderOptions))return;let o=TW(e),c=[];if(NM(a.theme,this.renderOptions.theme)||(c=DW(o)?KK(o):await qK(o)),!s())return;if(this.highlighter!=null)XU(c,this.highlighter);else{let e=await SW({themes:o,langs:[`text`],preferredHighlighter:this.preferredHighlighter});if(!s())return;this.highlighter=e}let l=this.setRenderOptionsOnWorkers(a,c);this.renderOptions=a,this.renderOptionsVersion++,this.diffCache.clear(),this.fileCache.clear(),this.invalidateRenderTasks();for(let e of this.themeSubscribers)e.onThemeChange();await l}catch(e){if(e instanceof mq||!s())return;throw e}}getPreferredHighlighter(){return this.preferredHighlighter}getFileRenderOptions(){let{tokenizeMaxLineLength:e,theme:t,useTokenTransformer:n}=this.renderOptions;return{theme:t,useTokenTransformer:n,tokenizeMaxLineLength:e}}getDiffRenderOptions(){return{...this.renderOptions}}async setRenderOptionsOnWorkers(e,t){if(this.workersFailed)return;this.isInitialized()||await this.initialize();let n=[];for(let r of this.workers){if(!r.initialized)throw console.log({managedWorker:r}),Error(`setRenderOptionsOnWorkers: Somehow we have an uninitialized worker`);n.push(new Promise((n,i)=>{let a=this.generateRequestId(),o={type:`set-render-options`,id:a,request:{type:`set-render-options`,id:a,renderOptions:e,resolvedThemes:t},resolve:n,reject:i,requestStart:Date.now()};this.activeTaskById.set(a,o),r.pendingSetupRequestId=a,r.worker.postMessage(o.request)}))}await Promise.all(n)}subscribeToThemeChanges(e){return this.themeSubscribers.add(e),this.queueBroadcastStateChanges(),()=>{this.unsubscribeToThemeChanges(e),this.queueBroadcastStateChanges()}}unsubscribeToThemeChanges(e){this.themeSubscribers.delete(e),this.queueBroadcastStateChanges()}subscribeToStatChanges(e){return this.statSubscribers.add(e),e(this.getStats()),()=>{this.statSubscribers.delete(e)}}queueBroadcastStateChanges(){this._queuedBroadcast??=requestAnimationFrame(this._broadcastStateChanges)}_broadcastStateChanges=()=>{this._queuedBroadcast!=null&&(cancelAnimationFrame(this._queuedBroadcast),this._queuedBroadcast=void 0);let e=this.getStats();for(let t of this.statSubscribers)t(e)};cleanUpTasks(e){this.detachInstanceFromQueuedTasks(e);let t=this.activeRequestByInstance.get(e);if(t!=null){let n=this.activeTaskById.get(t);yq(n)?(this.detachInstanceFromRenderTask(n,e),!n.primeCache&&n.instances.size===0&&this.removeActiveTask(n)):this.activeTaskById.delete(t)}this.activeRequestByInstance.delete(e),this.queueBroadcastStateChanges()}isInitialized(){return this.initialized===!0}async initialize(e=[]){if(this.initialized!==!0)if(this.initialized===!1){let{lifecycleGeneration:t}=this;this.initialized=new Promise((n,r)=>{(async()=>{try{let r=TW(this.renderOptions.theme),i=[];if(i=DW(r)?KK(r):await qK(r),!this.isCurrentLifecycle(t)){n();return}let a=[];if(a=WK(e)?UK(e):await GK(e),!this.isCurrentLifecycle(t)){n();return}let[o]=await Promise.all([SW({themes:r,langs:[`text`,...e],preferredHighlighter:this.preferredHighlighter}),this.initializeWorkers(i,a)]);if(!this.isCurrentLifecycle(t)){this.terminateWorkers(),n();return}this.highlighter=o,this.initialized=!0,this.diffCache.clear(),this.fileCache.clear(),this.drainQueue(),this.queueBroadcastStateChanges(),n()}catch(e){if(e instanceof mq||!this.isCurrentLifecycle(t)){n();return}this.initialized=!1,this.workersFailed=!0;for(let t of this.queuedTasks)this.rejectRenderTaskCallbacks(t,xq(e));this.queueBroadcastStateChanges(),r(e)}})()}),this.queueBroadcastStateChanges()}else return this.initialized}async initializeWorkers(e,t){this.workersFailed=!1;let n=[],r=VW(),i=r>0?HW():void 0;this.workers.length>0&&this.terminateWorkers();for(let a=0;a<(this.options.poolSize??8);a++){let a=this.options.workerFactory(),o={worker:a,requestId:void 0,pendingSetupRequestId:void 0,initialized:!1,langs:new Set([`text`,...t.map(({name:e})=>e)]),customExtensionsVersion:0};a.addEventListener(`message`,e=>{this.handleWorkerMessage(o,e.data)}),a.addEventListener(`error`,e=>console.error(`Worker error:`,e,o)),this.workers.push(o),n.push(new Promise((n,a)=>{let s=this.generateRequestId(),c={type:`initialize`,id:s,request:{type:`initialize`,id:s,renderOptions:this.renderOptions,preferredHighlighter:this.preferredHighlighter,resolvedThemes:e,resolvedLanguages:t,customExtensionsVersion:i==null?void 0:r,customExtensionMap:i},resolve(){o.initialized=!0,n()},reject:a,requestStart:Date.now()};this.activeTaskById.set(s,c),this.executeTask(o,c)}))}await Promise.all(n)}drainQueue=()=>{if(this._queuedDrain=void 0,this.initialized===!0&&this.queuedTasks.length!==0){for(let e=0;e<this.queuedTasks.length;){let t=this.queuedTasks[e];if(this.hasActiveRequest(t)){e++;continue}let n=vq(t),r=this.getAvailableWorker(n);if(r==null)break;this.queuedTasks.splice(e,1),this.assignWorkerToTask(t,r),this.resolveLanguagesAndExecuteTask(r,t,n)}this.queueBroadcastStateChanges()}};highlightFileAST(e,t){let n=this.getFileResultCache(t);PG(t)||n!=null&&OW(n.options,this.getFileRenderOptions())||this.hasMatchingFileInstanceTask(e,t)||this.submitTask(e,{type:`file`,file:t})}primeFileHighlightCache(e){if(!this.isWorkingPool())return Promise.reject(Error(`WorkerPoolManager.primeFileHighlightCache: worker pool is not working`));let t=this.getOrCreateFileHighlightCacheTask(e);return t==null?Promise.resolve():this.createRenderTaskCallbacks(t)}getOrCreateFileHighlightCacheTask(e){if(e.cacheKey==null){console.warn(`WorkerPoolManager.primeFileHighlightCache: priming highlight cache requires file.cacheKey; skipping "${e.name}".`);return}let t=this.getFileResultCache(e),n=this.getFileHighlightKey(e);if(n==null||PG(e)||t!=null&&OW(t.options,this.getFileRenderOptions()))return;let r=this.getTaskByHighlightKey(n);if(r!=null)return r.primeCache=!0,r.type===`file`?r:void 0;{let t=this.submitCacheTask({type:`file`,file:e},n);return t.type===`file`?t:void 0}}getPlainFileAST(e,t,n,r){if(this.highlighter==null){this.queueInitialization();return}return EG(e,this.highlighter,this.renderOptions,{forcePlainText:!0,startingLine:t,totalLines:n,lines:r})}highlightDiffAST(e,t){let n=this.getDiffResultCache(t);HK(t)||n!=null&&mK(n.options,this.getDiffRenderOptions())||this.hasMatchingDiffInstanceTask(e,t)||this.submitTask(e,{type:`diff`,diff:t})}primeDiffHighlightCache(e){if(!this.isWorkingPool())return Promise.reject(Error(`WorkerPoolManager.primeDiffHighlightCache: worker pool is not working`));let t=this.getOrCreateDiffHighlightCacheTask(e);return t==null?Promise.resolve():this.createRenderTaskCallbacks(t)}getOrCreateDiffHighlightCacheTask(e){if(e.cacheKey==null){console.warn(`WorkerPoolManager.primeDiffHighlightCache: priming highlight cache requires diff.cacheKey; skipping "${e.prevName??e.name}" -> "${e.name}".`);return}let t=this.getDiffResultCache(e),n=this.getDiffHighlightKey(e);if(n==null||HK(e)||t!=null&&mK(t.options,this.getDiffRenderOptions()))return;let r=this.getTaskByHighlightKey(n);if(r!=null)return r.primeCache=!0,r.type===`diff`?r:void 0;{let t=this.submitCacheTask({type:`diff`,diff:e},n);return t.type===`diff`?t:void 0}}getPlainDiffAST(e,t,n,r,i){return this.highlighter==null?void 0:RK(e,this.highlighter,this.renderOptions,{forcePlainText:!0,startingLine:t,totalLines:n,expandedHunks:r,collapsedContextThreshold:i})}terminate(){this.lifecycleGeneration++,this.cancelActiveWorkerTasks(),this.terminateWorkers();let e=new mq;for(let t of this.queuedTasks)this.rejectRenderTaskCallbacks(t,e);this.fileCache.clear(),this.diffCache.clear(),this.activeRequestByInstance.clear(),this.queuedTasks.length=0,this.queuedTaskByInstance.clear(),this.taskByHighlightKey.clear(),this.activeTaskById.clear(),this.highlighter=void 0,this.initialized=!1,this.workersFailed=!1,this.queueBroadcastStateChanges()}isCurrentLifecycle(e){return this.lifecycleGeneration===e}queueInitialization(e){this.initialize(e).catch(e=>{console.error(e)})}cancelActiveWorkerTasks(){let e=new mq;for(let t of this.activeTaskById.values())`reject`in t?t.reject(e):yq(t)&&this.rejectRenderTaskCallbacks(t,e)}terminateWorkers(){for(let e of this.workers)e.worker.terminate();this.workers.length=0}getStats(){return{managerState:this.initialized===!1?`waiting`:this.initialized===!0?`initialized`:`initializing`,totalWorkers:this.workers.length,workersFailed:this.workersFailed,busyWorkers:this.workers.filter(e=>e.requestId!=null||e.pendingSetupRequestId!=null).length,queuedTasks:this.queuedTasks.length,activeTasks:this.activeTaskById.size,themeSubscribers:this.themeSubscribers.size,fileCacheSize:this.fileCache.size,diffCacheSize:this.diffCache.size}}submitTask(e,t){this.initialized===!1&&this.queueInitialization();let n=this.getHighlightKeyForRequest(t),r=n==null?void 0:this.getTaskByHighlightKey(n);if(r!=null){this.detachInstanceFromQueuedTasks(e,r),this.addInstanceToTask(r,e),this.queueBroadcastStateChanges();return}this.detachInstanceFromQueuedTasks(e);let i=this.generateRequestId(),a=Date.now(),{renderOptionsVersion:o}=this,s=(()=>{switch(t.type){case`file`:return{type:`file`,id:i,request:{...t,id:i},instances:new Set([e]),primeCache:!1,highlightKey:n,callbacks:new Set,renderOptionsVersion:o,requestStart:a};case`diff`:return{type:`diff`,id:i,request:{...t,id:i},instances:new Set([e]),primeCache:!1,highlightKey:n,callbacks:new Set,renderOptionsVersion:o,requestStart:a}}})();this.enqueueRenderTask(s,e)}submitCacheTask(e,t){this.initialized===!1&&this.queueInitialization();let n=this.generateRequestId(),r=Date.now(),{renderOptionsVersion:i}=this,a=(()=>{switch(e.type){case`file`:return{type:`file`,id:n,request:{...e,id:n},instances:new Set,primeCache:!0,highlightKey:t,callbacks:new Set,renderOptionsVersion:i,requestStart:r};case`diff`:return{type:`diff`,id:n,request:{...e,id:n},instances:new Set,primeCache:!0,highlightKey:t,callbacks:new Set,renderOptionsVersion:i,requestStart:r}}})();return this.enqueueRenderTask(a),a}enqueueRenderTask(e,t){this.queuedTasks.push(e),t!=null&&this.queuedTaskByInstance.set(t,e),e.highlightKey!=null&&this.taskByHighlightKey.set(e.highlightKey,e),this.queueDrain()}async resolveLanguagesAndExecuteTask(e,t,n){try{let r=n.filter(t=>!e.langs.has(t));if(r.length>0&&(WK(r)?t.request.resolvedLanguages=UK(r):t.request.resolvedLanguages=await GK(r)),!this.activeTaskById.has(t.id)){e.requestId===t.id&&(this.cleanWorkerAndTask(e,t),this.queueBroadcastStateChanges(),this.queuedTasks.length>0&&this.queueDrain());return}this.executeTask(e,t)}catch(n){this.rejectRenderTaskCallbacks(t,xq(n)),this.cleanWorkerAndTask(e,t),this.queueBroadcastStateChanges(),this.queuedTasks.length>0&&this.queueDrain()}}handleWorkerMessage(e,t){let n=this.activeTaskById.get(t.id);try{if(n==null)throw pq;if(t.type===`error`){let e=Error(t.error);if(t.stack&&(e.stack=t.stack),`reject`in n)n.reject(e);else if(yq(n))this.notifyHighlightError(n,e),this.rejectRenderTaskCallbacks(n,e);else throw Error(`handleWorkerMessage: unknown task type`);throw e}switch(t.requestType){case`initialize`:if(n.type!==`initialize`)throw Error(`handleWorkerMessage: task/response dont match`);this.syncCustomExtensionVersion(e,n.request),n.resolve();break;case`set-render-options`:if(n.type!==`set-render-options`)throw Error(`handleWorkerMessage: task/response dont match`);n.resolve();break;case`file`:{if(n.type!==`file`)throw Error(`handleWorkerMessage: task/response dont match`);let{result:r,options:i}=t;if(!this.isCurrentRenderTask(n)||!OW(i,this.getFileRenderOptions()))throw pq;let{request:a}=n;this.syncCustomExtensionVersion(e,a),n.cacheKeyAtDispatch!=null&&this.fileCache.set(n.cacheKeyAtDispatch,{result:r,options:i}),this.resolveRenderTaskCallbacks(n),this.notifyFileInstances(n,r,i);break}case`diff`:{if(n.type!==`diff`)throw Error(`handleWorkerMessage: task/response dont match`);let{result:r,options:i}=t;if(!this.isCurrentRenderTask(n)||!mK(i,this.getDiffRenderOptions()))throw pq;let{request:a}=n;this.syncCustomExtensionVersion(e,a),n.cacheKeyAtDispatch!=null&&this.diffCache.set(n.cacheKeyAtDispatch,{result:r,options:i}),this.resolveRenderTaskCallbacks(n),this.notifyDiffInstances(n,r,i);break}}}catch(e){e!==pq&&console.error(e,n,t)}this.cleanWorkerAndTask(e,n,t.id),this.queueBroadcastStateChanges(),this.queuedTasks.length>0&&this.queueDrain()}_queuedDrain;queueDrain(){this._queuedDrain??(this._queuedDrain=Promise.resolve().then(this.drainQueue),this.queueBroadcastStateChanges())}assignWorkerToTask(e,t){t.requestId=e.id,yq(e)&&(this.clearQueuedInstanceRequests(e),this.trackInstanceRequests(e)),this.activeTaskById.set(e.id,e)}cleanWorkerAndTask(e,t,n=t?.id){e.requestId===n&&(e.requestId=void 0),e.pendingSetupRequestId===n&&(e.pendingSetupRequestId=void 0),t!=null&&(yq(t)&&(this.rejectRenderTaskCallbacks(t,new hq),this.clearInstanceRequests(t),this.clearHighlightKey(t)),this.activeTaskById.delete(t.id))}executeTask(e,t){_q(t.request)&&this.maybeAttachCustomExtensions(e,t.request),this.activeTaskById.has(t.id)||this.assignWorkerToTask(t,e);for(let n of vq(t))e.langs.add(n);try{t.type===`file`?t.cacheKeyAtDispatch=t.request.file.cacheKey:t.type===`diff`&&(t.cacheKeyAtDispatch=t.request.diff.cacheKey),e.worker.postMessage(t.request)}catch(n){console.error(`Failed to post message to worker:`,n),yq(t)?(this.notifyHighlightError(t,n),this.rejectRenderTaskCallbacks(t,xq(n))):`reject`in t&&t.reject(n),this.cleanWorkerAndTask(e,t),this.queuedTasks.length>0&&this.queueDrain()}this.queueBroadcastStateChanges()}maybeAttachCustomExtensions(e,t){if(t.customExtensionsVersion!=null)return;let n=VW();e.customExtensionsVersion>=n||(t.customExtensionsVersion=n,t.customExtensionMap=HW())}syncCustomExtensionVersion(e,t){t.customExtensionsVersion!=null&&(e.customExtensionsVersion=t.customExtensionsVersion)}getAvailableWorker(e){let t;for(let n of this.workers){if(n.requestId!=null||n.pendingSetupRequestId!=null||!n.initialized)continue;if(t=n,e.length===0)break;let r=!0;for(let t of e)if(!n.langs.has(t)){r=!1;break}if(r)break}return t}getFileHighlightKey(e){if(e.cacheKey!=null)return`file:${e.cacheKey}:${this.renderOptionsVersion}`}getDiffHighlightKey(e){if(e.cacheKey!=null)return`diff:${e.cacheKey}:${this.renderOptionsVersion}`}getHighlightKeyForRequest(e){switch(e.type){case`file`:return this.getFileHighlightKey(e.file);case`diff`:return this.getDiffHighlightKey(e.diff)}}hasActiveRequest(e){for(let t of bq(e))if(this.activeRequestByInstance.has(t))return!0;return!1}addInstanceToTask(e,t){e.type,e.instances.add(t),this.activeTaskById.has(e.id)?this.activeRequestByInstance.set(t,e.id):this.queuedTaskByInstance.set(t,e)}detachInstanceFromQueuedTasks(e,t){let n=this.queuedTaskByInstance.get(e);n!=null&&n!==t&&(this.queuedTaskByInstance.delete(e),this.detachInstanceFromRenderTask(n,e),!n.primeCache&&n.instances.size===0&&this.removeQueuedTask(n))}detachInstanceFromRenderTask(e,t){e.type,e.instances.delete(t)}removeQueuedTask(e){let t=this.queuedTasks.indexOf(e);t!==-1&&this.queuedTasks.splice(t,1),this.rejectRenderTaskCallbacks(e,new hq),this.clearQueuedInstanceRequests(e),this.clearHighlightKey(e)}removeActiveTask(e){this.rejectRenderTaskCallbacks(e,new hq),this.clearInstanceRequests(e),this.clearHighlightKey(e),this.activeTaskById.delete(e.id)}createRenderTaskCallbacks(e){return new Promise((t,n)=>{e.callbacks.add({resolve:t,reject:n})})}resolveRenderTaskCallbacks(e){for(let t of e.callbacks)t.resolve();e.callbacks.clear()}rejectRenderTaskCallbacks(e,t){for(let n of e.callbacks)n.reject(t);e.callbacks.clear()}invalidateRenderTasks(){for(let e=this.queuedTasks.length-1;e>=0;e--){let t=this.queuedTasks[e];t.renderOptionsVersion!==this.renderOptionsVersion&&this.removeQueuedTask(t)}for(let e of Array.from(this.activeTaskById.values()))yq(e)&&e.renderOptionsVersion!==this.renderOptionsVersion&&this.removeActiveTask(e)}clearQueuedInstanceRequests(e){for(let t of bq(e))this.queuedTaskByInstance.get(t)===e&&this.queuedTaskByInstance.delete(t)}clearHighlightKey(e){e.highlightKey!=null&&this.taskByHighlightKey.get(e.highlightKey)===e&&this.taskByHighlightKey.delete(e.highlightKey)}trackInstanceRequests(e){for(let t of bq(e))this.activeRequestByInstance.set(t,e.id)}clearInstanceRequests(e){for(let t of bq(e))this.activeRequestByInstance.get(t)===e.id&&this.activeRequestByInstance.delete(t)}notifyFileInstances(e,t,n){for(let r of e.instances)this.activeRequestByInstance.get(r)===e.id&&r.onHighlightSuccess(e.request.file,t,n)}notifyDiffInstances(e,t,n){for(let r of e.instances)this.activeRequestByInstance.get(r)===e.id&&r.onHighlightSuccess(e.request.diff,t,n)}notifyHighlightError(e,t){for(let n of bq(e))this.activeRequestByInstance.get(n)===e.id&&n.onHighlightError(t)}hasMatchingFileInstanceTask(e,t){for(let n of this.iterateRenderTasks())if(n.type===`file`&&this.isCurrentRenderTask(n)&&n.instances.has(e)&&yN(t,n.request.file))return!0;return!1}hasMatchingDiffInstanceTask(e,t){for(let n of this.iterateRenderTasks())if(n.type===`diff`&&this.isCurrentRenderTask(n)&&n.instances.has(e)&&pK(n.request.diff,t))return!0;return!1}getTaskByHighlightKey(e){let t=this.taskByHighlightKey.get(e);return t!=null&&this.isCurrentRenderTask(t)?t:void 0}isCurrentRenderTask(e){return e.renderOptionsVersion===this.renderOptionsVersion}*iterateRenderTasks(){for(let e of this.queuedTasks)yield e;for(let e of this.activeTaskById.values())yq(e)&&(yield e)}generateRequestId(){return`req_${++this.nextRequestId}`}};function _q(e){return e.type===`initialize`||e.type===`file`||e.type===`diff`}function vq(e){let t=new Set;if(e.type===`initialize`||e.type===`set-render-options`)return[];switch(e.type){case`file`:t.add(e.request.file.lang??BW(e.request.file.name));break;case`diff`:t.add(e.request.diff.lang??BW(e.request.diff.name)),t.add(e.request.diff.lang??BW(e.request.diff.prevName??`-`))}return t.delete(`text`),Array.from(t)}function yq(e){return e?.type===`file`||e?.type===`diff`}function bq(e){return e.instances}function xq(e){return e instanceof Error?e:Error(String(e))}var Sq;function Cq({poolOptions:e,highlighterOptions:t}){return Sq??=new gq(e,t),Sq}function wq(){Sq!=null&&(Sq.terminate(),Sq=void 0)}var Tq=(0,O.createContext)(void 0),Eq=0;function Dq({children:e,poolOptions:t,highlighterOptions:n}){let[r]=(0,O.useState)(()=>{if(!(typeof window>`u`))return Cq({poolOptions:t,highlighterOptions:n})});return(0,O.useInsertionEffect)(()=>{if(r!=null)return Eq++,()=>{Eq--}},[r]),(0,O.useEffect)(()=>()=>{Eq===0&&wq()},[]),(0,k.jsx)(Tq.Provider,{value:r,children:e})}function Oq(){return(0,O.useContext)(Tq)}export{AG as $,Ch as $a,bx as $i,uk as $n,j as $o,nT as $r,no as $s,_M as $t,lK as A,l_ as Aa,xC as Ai,Mj as An,Wf as Ao,oD as Ar,Lo as As,aP as At,XG as B,Ug as Ba,pC as Bi,hA as Bn,jd as Bo,QT as Br,mo as Bs,yN as Bt,xK as C,m_ as Ca,vw as Ci,Kj as Cn,rp as Co,MD as Cr,Po as Cs,RP as Ct,mK as D,u_ as Da,uw as Di,Gj as Dn,$f as Do,BD as Dr,jo as Ds,FP as Dt,SK as E,d_ as Ea,Tw as Ei,Yj as En,ip as Eo,GD as Er,Mo as Es,LP as Et,nK as F,Jg as Fa,lC as Fi,MA as Fn,Pf as Fo,JT as Fr,bo as Fs,wN as Ft,BG as G,kg as Ga,XS as Gi,Xk as Gn,Ru as Go,HT as Gr,to as Gs,LM as Gt,JG as H,Lg as Ha,nC as Hi,Qk as Hn,wd as Ho,RT as Hr,co as Hs,BM as Ht,tK as I,Wg as Ia,dC as Ii,DA as In,pf as Io,eE as Ir,yo as Is,CN as It,FG as J,ig as Ja,SS as Ji,hk as Jn,Rl as Jo,Zw as Jr,Za as Js,NM as Jt,zG as K,hg as Ka,NS as Ki,Vk as Kn,Uu as Ko,I as Kr,ao as Ks,IM as Kt,eK as L,Zg as La,mC as Li,jA as Ln,ff as Lo,XT as Lr,vo as Ls,B as Lt,sK as M,s_ as Ma,hC as Mi,bj as Mn,Vf as Mo,nD as Mr,Ro as Ms,MN as Mt,iK as N,o_ as Na,_C as Ni,hj as Nn,Rf as No,iD as Nr,Yo as Ns,kN as Nt,pK as O,i_ as Oa,jC as Oi,Xj as On,Yf as Oo,yD as Or,To as Os,sP as Ot,rK as P,Yg as Pa,oC as Pi,nj as Pn,Ff as Po,aD as Pr,qo as Ps,TN as Pt,OG as Q,Dh as Qa,iS as Qi,pk as Qn,dl as Qo,tT as Qr,Va as Qs,oM as Qt,$G as R,Rg as Ra,uC as Ri,EA as Rn,af as Ro,ZT as Rr,_o as Rs,xN as Rt,bK as S,g_ as Sa,dw as Si,qj as Sn,cp as So,ID as Sr,Eo as Ss,VP as St,yK as T,f_ as Ta,pw as Ti,Qj as Tn,Zf as To,WD as Tr,Wo as Ts,IP as Tt,WG as U,Tg as Ua,QS as Ui,$k as Un,td as Uo,IT as Ur,so as Us,zM as Ut,YG as V,Cg as Va,cC as Vi,gA as Vn,Sd as Vo,NT as Vr,lo as Vs,_N as Vt,VG as W,xg as Wa,ZS as Wi,Zk as Wn,ld as Wo,LT as Wr,oo as Ws,RM as Wt,NG as X,xh as Xa,tS as Xi,gk as Xn,Ol as Xo,qw as Xr,Ba as Xs,AM as Xt,PG as Y,_h as Ya,yS as Yi,mk as Yn,kl as Yo,Qw as Yr,io as Ys,MM as Yt,MG as Z,Eh as Za,aS as Zi,yk as Zn,wl as Zo,Jw as Zr,Ua as Zs,kM as Zt,AK as _,q_ as _a,hw as _i,lM as _n,sm as _o,RO as _r,fs as _s,dI as _t,uq as a,Oy as aa,hT as ai,wM as an,Rm as ao,zO as ar,Rs as as,UW as at,OK as b,w_ as ba,fw as bi,sM as bn,sp as bo,dO as br,ns as bs,PF as bt,oq as c,xy as ca,_T as ci,fM as cn,Pm as co,ok as cr,Ps as cs,MW as ct,rq as d,vy as da,Dw as di,eM as dn,km as do,qO as dr,Os as ds,OW as dt,Mb as ea,za as ec,pT as ei,gM as en,Sh as eo,dk as er,ol as es,kG as et,tq as f,gy as fa,Ew as fi,$j as fn,Jm as fo,IO as fr,Es as fs,DW as ft,RK as g,ev as ga,xw as gi,nM as gn,cm as go,ak as gr,ds as gs,SW as gt,HK as h,J_ as ha,yw as hi,aM as hn,om as ho,YO as hr,ps as hs,CW as ht,lq as i,Tb as ia,mT as ii,SM as in,$m as io,GO as ir,Fs as is,WW as it,dK as j,c_ as ja,gC as ji,jj as jn,Bf as jo,sD as jr,ko as js,tP as jt,cK as k,r_ as ka,CC as ki,Nj as kn,Hf as ko,bD as kr,Fo as ks,iP as kt,iq as l,Ov as la,gT as li,yM as ln,Nm as lo,QO as lr,Ns as ls,AW as lt,YK as m,tv as ma,kw as mi,iM as mn,am as mo,JO as mr,_s as ms,TW as mt,Dq as n,Pb as na,Ka as nc,vT as ni,dM as nn,ph as no,WO as nr,Bs as ns,EG as nt,dq as o,Ay as oa,dT as oi,TM as on,Vm as oo,VO as or,Ls as os,BW as ot,eq as p,_y as pa,Ow as pi,EM as pn,qm as po,LO as pr,Ts as ps,EW as pt,IG as q,ng as qa,MS as qi,Kk as qn,wu as qo,WT as qr,ro as qs,PM as qt,Oq as r,Eb as ra,fT as ri,xM as rn,eh as ro,sk as rr,zs as rs,wG as rt,cq as s,mv as sa,uT as si,CM as sn,Am as so,UO as sr,Ms as ss,FW as st,Tq as t,Nb as ta,Ga as tc,lT as ti,tM as tn,hh as to,FO as tr,Vs as ts,jG as tt,aq as u,Dv as ua,Aw as ui,bM as un,Km as uo,KO as ur,js as us,kW as ut,vK as v,C_ as va,Cw as vi,uM as vn,rm as vo,MO as vr,ss as vs,$F as vt,kK as w,__ as wa,bw as wi,Zj as wn,Xf as wo,LD as wr,No as ws,zP as wt,CK as x,x_ as xa,mw as xi,rM as xn,op as xo,cO as xr,ts as xs,AF as xt,_K as y,S_ as ya,ww as yi,cM as yn,lm as yo,bO as yr,os as ys,NF as yt,QG as z,Hg as za,sC as zi,AA as zn,xd as zo,rE as zr,go as zs,bN as zt};
|
|
1533
|
-
//# sourceMappingURL=WorkerPoolContext-
|
|
1532
|
+
}`}function ZG(e,t){let n=KG(t);return e.replace(JG,n)}function QG(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function $G({code:e,pre:t,columnType:n,rowSpan:r,containerSize:i=!1}={}){return e??(e=document.createElement(`code`),e.setAttribute(`data-code`,``),n!=null&&e.setAttribute(`data-${n}`,``),t?.appendChild(e)),r==null?e.style.removeProperty(`grid-row`):e.style.setProperty(`grid-row`,`span ${r}`),i?e.setAttribute(`data-container-size`,``):e.removeAttribute(`data-container-size`),e}function eK(e,t){if(t==null)return;let n=e.shadowRoot??e.attachShadow({mode:`open`});n.innerHTML===``&&(n.innerHTML=t)}function tK(e,{type:t,diffIndicators:n,disableBackground:r,disableLineNumbers:i,overflow:a,split:o,totalLines:s,customProperties:c}){if(c!=null)for(let t in c){let n=c[t];n!=null&&e.setAttribute(t,`${n}`)}switch(t===`diff`?(e.setAttribute(`data-diff`,``),e.removeAttribute(`data-file`)):(e.setAttribute(`data-file`,``),e.removeAttribute(`data-diff`)),n){case`bars`:case`classic`:e.setAttribute(`data-indicators`,n);break;case`none`:e.removeAttribute(`data-indicators`)}return i?e.setAttribute(`data-disable-line-numbers`,``):e.removeAttribute(`data-disable-line-numbers`),r?e.removeAttribute(`data-background`):e.setAttribute(`data-background`,``),t===`diff`?e.setAttribute(`data-diff-type`,o?`split`:`single`):e.removeAttribute(`data-diff-type`),e.setAttribute(`data-overflow`,a),e.style.setProperty(`--diffs-min-number-column-width-default`,`${`${s}`.length}ch`),e}function nK(e){if(typeof HTMLStyleElement<`u`&&e instanceof HTMLStyleElement)return!0;let t=e.tagName??e.nodeName;return typeof t==`string`&&t.toLowerCase()===`style`}function rK(e){return e?.useTokenTransformer===!0||e?.onTokenClick!=null||e?.onTokenEnter!=null||e?.onTokenLeave!=null}function iK(e,t){let n=e?.offsetHeight??0;if(e==null||n===0){t();return}e.style.minHeight=`${n}px`;try{t(),e.offsetHeight}finally{e.style.minHeight=``}}function aK({shadowRoot:e,currentNode:t,themeCSS:n}){if(n.trim()===``){t?.remove();return}return t??=oK(),t.textContent=n,t.parentNode!==e&&e.appendChild(t),t}function oK(){let e=document.createElement(`style`);return e.setAttribute(mM,``),e}var sK=void 0;function cK(){return sK??=`safari`in window&&`pushNotification`in window.safari||/^((?!chrome|android).)*safari/i.test(navigator.userAgent)}if(typeof HTMLElement<`u`&&customElements.get(`diffs-container`)==null){let e;class t extends HTMLElement{constructor(){if(super(),this.shadowRoot!=null)return;let t=this.attachShadow({mode:`open`});e??(e=new CSSStyleSheet,e.replaceSync(UG)),t.adoptedStyleSheets=[e]}connectedCallback(){GG(this.shadowRoot??this.attachShadow({mode:`open`}))}}customElements.define(eM,t)}function lK(e){return{...xM,...e}}function uK(e,t){let n=dK(e,t);return t?n:e.diffHeaderHeight+n}function dK(e,t){return e.paddingTop??(t?e.spacing:0)}function fK(e){return e.paddingBottom??e.spacing}function pK(e){switch(e){case`simple`:return 4;case`metadata`:case`line-info`:case`line-info-basic`:case`custom`:return 32}}function mK(e,t){return e===t||e?.cacheKey!=null&&e.cacheKey===t?.cacheKey}function hK(e,t){return PM(e.theme,t.theme)&&e.useTokenTransformer===t.useTokenTransformer&&e.tokenizeMaxLineLength===t.tokenizeMaxLineLength&&e.lineDiffType===t.lineDiffType&&e.maxLineDiffLength===t.maxLineDiffLength}function gK({line:e,spanStart:t,spanLength:n}){return{start:{line:e,character:t},end:{line:e,character:t+n},properties:{"data-diff-span":``},alwaysWrap:!0}}function _K({item:e,arr:t,enableJoin:n,isNeutral:r=!1,isLastItem:i=!1}){let a=t[t.length-1];if(a==null||i||!n){t.push([+!r,e.value]);return}let o=a[0]===0;if(r===o||r&&e.value.length===1&&!o){a[1]+=e.value;return}t.push([+!r,e.value])}function vK(e){return[BM(e.additionStart,e.additionCount)+1,VM(e.additionStart,e.additionCount)+1]}function yK({isPartial:e,rangeSize:t,expandedHunks:n,hunkIndex:r,collapsedContextThreshold:i}){let a=Math.max(t,0);if(a===0||e)return{fromStart:0,fromEnd:0,rangeSize:a,collapsedLines:a,renderAll:!1};if(n===!0||a<=i)return{fromStart:a,fromEnd:0,rangeSize:a,collapsedLines:0,renderAll:!0};let o=n?.get(r),s=Math.min(Math.max(o?.fromStart??0,0),a),c=Math.min(Math.max(o?.fromEnd??0,0),a),l=s+c,u=l>=a;return{fromStart:u?a:s,fromEnd:u?0:c,rangeSize:a,collapsedLines:Math.max(a-l,0),renderAll:u}}function bK(e){let t=e.hunks[e.hunks.length-1];if(t==null||e.isPartial||e.additionLines.length===0||e.deletionLines.length===0)return!1;let n=e.additionLines.length-VM(t.additionStart,t.additionCount),r=e.deletionLines.length-VM(t.deletionStart,t.deletionCount);return n<=0&&r<=0?!1:n!==r}function xK({fileDiff:e,errorPrefix:t}){let n=e.hunks[e.hunks.length-1];if(n==null||e.isPartial||e.additionLines.length===0||e.deletionLines.length===0)return 0;let r=e.additionLines.length-VM(n.additionStart,n.additionCount),i=e.deletionLines.length-VM(n.deletionStart,n.deletionCount);if(r<=0&&i<=0)return 0;if(r!==i)throw Error(`${t}: trailing context mismatch (additions=${r}, deletions=${i}) for ${e.name}`);return Math.min(r,i)}function SK({fileDiff:e,hunkIndex:t,expandedHunks:n,collapsedContextThreshold:r,errorPrefix:i}){if(t!==e.hunks.length-1)return;let a=xK({fileDiff:e,errorPrefix:i});if(a<=0)return;if(n===!0||a<=r)return{fromStart:a,fromEnd:0,rangeSize:a,collapsedLines:0,renderAll:!0};let o=n?.get(e.hunks.length),s=Math.min(Math.max(o?.fromStart??0,0),a);return{fromStart:s,fromEnd:0,rangeSize:a,collapsedLines:a-s,renderAll:s>=a}}function CK({fileDiff:e,lineNumber:t,expandedHunks:n,collapsedContextThreshold:r}){if(n===!0||e.isPartial)return!0;for(let[i,a]of e.hunks.entries()){let[o,s]=vK(a);if(t<o){let s=yK({isPartial:e.isPartial,rangeSize:a.collapsedBefore,expandedHunks:n,hunkIndex:i,collapsedContextThreshold:r}),c=o-s.rangeSize;return s.renderAll||t<c+s.fromStart||t>=o-s.fromEnd}if(t<s)return!0}let i=SK({fileDiff:e,hunkIndex:e.hunks.length-1,expandedHunks:n,collapsedContextThreshold:r,errorPrefix:`isAdditionLineRenderable`});if(i==null||i.renderAll)return!0;let a=e.hunks[e.hunks.length-1],[,o]=vK(a);return t<o+i.fromStart||t>=o+i.rangeSize}function wK({fileDiff:e,lineNumber:t,direction:n,expandedHunks:r,collapsedContextThreshold:i}){if(r===!0||e.isPartial)return t;let a=[],o=1;for(let[t,n]of e.hunks.entries()){let[s,c]=vK(n),l=yK({isPartial:e.isPartial,rangeSize:n.collapsedBefore,expandedHunks:r,hunkIndex:t,collapsedContextThreshold:i}),u=s-l.rangeSize;l.renderAll?a.push([u,s]):(l.fromStart>0&&a.push([u,u+l.fromStart]),l.fromEnd>0&&a.push([s-l.fromEnd,s])),a.push([s,c]),o=c}let s=SK({fileDiff:e,hunkIndex:e.hunks.length-1,expandedHunks:r,collapsedContextThreshold:i,errorPrefix:`getNearestRenderableAdditionLine`});if(s!=null){let e=o;o=e+s.rangeSize,s.renderAll?a.push([e,o]):s.fromStart>0&&a.push([e,e+s.fromStart])}if(t>=o)return t;if(n===`down`){for(let[e,n]of a)if(n>t)return Math.max(e,t);return}for(let e=a.length-1;e>=0;e--){let[n,r]=a[e];if(n<=t)return Math.min(r-1,t)}}function TK({type:e,metrics:t}){return t.hunkSeparatorHeight??pK(e)}function EK({type:e,metrics:t}){return e===`simple`||e===`metadata`||e===`line-info-basic`?0:t.spacing}function DK({type:e,hunkIndex:t,hunkSpecs:n}){switch(e){case`simple`:return t>0;case`metadata`:return n!=null;case`line-info`:case`line-info-basic`:case`custom`:return!0}}function OK(e){return e!==`simple`&&e!==`metadata`}function kK({type:e,metrics:t,hunkIndex:n,hunkSpecs:r}){if(!DK({type:e,hunkIndex:n,hunkSpecs:r}))return;let i=TK({type:e,metrics:t}),a=EK({type:e,metrics:t}),o=n>0?a:0,s=a;return{height:i,gapBefore:o,gapAfter:s,totalHeight:o+i+s}}function AK({type:e,metrics:t}){if(!OK(e))return;let n=TK({type:e,metrics:t}),r=EK({type:e,metrics:t});return{height:n,gapBefore:r,gapAfter:0,totalHeight:r+n}}function jK({diff:e,diffStyle:t,startingLine:n=0,totalLines:r=1/0,expandedHunks:i,collapsedContextThreshold:a=1,callback:o}){let s=MK({diff:e,diffStyle:t,startingLine:n,expandedHunks:i,collapsedContextThreshold:a}),c={viewportStart:n,viewportEnd:n+r,isWindowedHighlight:n>0||r<1/0,splitCount:s.splitCount,unifiedCount:s.unifiedCount,finalHunkIndex:e.hunks.length-1,shouldBreak(){if(!c.isWindowedHighlight)return!1;let e=c.unifiedCount>=n+r,i=c.splitCount>=n+r;return t===`unified`?e:(t===`split`||e)&&i},shouldSkip(e,r){if(!c.isWindowedHighlight)return!1;let i=e>0&&c.unifiedCount+e<=n,a=r>0&&c.splitCount+r<=n;return t===`unified`?i:(t===`split`||i)&&a},incrementCounts(e,n){(t===`unified`||t===`both`)&&(c.unifiedCount+=e),(t===`split`||t===`both`)&&(c.splitCount+=n)},isInWindow(e,n){if(!c.isWindowedHighlight)return!0;let r=c.isInUnifiedWindow(e),i=c.isInSplitWindow(n);return t===`unified`?r:t===`split`?i:r||i},isInUnifiedWindow(e){return!c.isWindowedHighlight||c.unifiedCount>=n-e&&c.unifiedCount<n+r},isInSplitWindow(e){return!c.isWindowedHighlight||c.splitCount>=n-e&&c.splitCount<n+r},emit(e,n=!1){return n||(t===`unified`?c.incrementCounts(1,0):t===`split`?c.incrementCounts(0,1):c.incrementCounts(1,1)),o(e)??!1}};hunkIterator:for(let n=s.hunkIndex;n<e.hunks.length;n++){let r=e.hunks[n];if(r==null)throw Error(`iterateOverDiff: invalid hunk index`);if(c.shouldBreak())break;let o=BM(r.deletionStart,r.deletionCount),s=BM(r.additionStart,r.additionCount),l=!e.isPartial&&r.deletionCount===0?o:r.deletionLineIndex,u=!e.isPartial&&r.additionCount===0?s:r.additionLineIndex,d=yK({isPartial:e.isPartial,rangeSize:r.collapsedBefore,expandedHunks:i,hunkIndex:n,collapsedContextThreshold:a}),f=n===c.finalHunkIndex?SK({fileDiff:e,hunkIndex:n,expandedHunks:i,collapsedContextThreshold:a,errorPrefix:`iterateOverDiff`}):void 0,p=d.fromStart+d.fromEnd;function m(e,n){return f==null||f.collapsedLines<=0||f.fromStart+f.fromEnd>0?0:t===`unified`?e===r.unifiedLineStart+r.unifiedLineCount-1?f.collapsedLines:0:n===r.splitLineStart+r.splitLineCount-1?f.collapsedLines:0}let h=d.collapsedLines===0;function g(){return h?0:(h=!0,d.collapsedLines)}if(c.shouldSkip(p,p))c.incrementCounts(p,p),g();else{let e=r.unifiedLineStart-d.rangeSize,i=r.splitLineStart-d.rangeSize,a=l-d.rangeSize,f=u-d.rangeSize,p=o+1-d.rangeSize,m=s+1-d.rangeSize;if(FK(c,d.fromStart,t,t=>c.emit({hunkIndex:n,hunk:r,collapsedBefore:0,collapsedAfter:0,type:`context-expanded`,deletionLine:{lineNumber:p+t,lineIndex:a+t,noEOFCR:!1,unifiedLineIndex:e+t,splitLineIndex:i+t},additionLine:{unifiedLineIndex:e+t,splitLineIndex:i+t,lineIndex:f+t,lineNumber:m+t,noEOFCR:!1}}))||(e=r.unifiedLineStart-d.fromEnd,i=r.splitLineStart-d.fromEnd,a=l-d.fromEnd,f=u-d.fromEnd,p=o+1-d.fromEnd,m=s+1-d.fromEnd,FK(c,d.fromEnd,t,t=>c.emit({hunkIndex:n,hunk:r,collapsedBefore:g(),collapsedAfter:0,type:`context-expanded`,deletionLine:{lineNumber:p+t,lineIndex:a+t,noEOFCR:!1,unifiedLineIndex:e+t,splitLineIndex:i+t},additionLine:{unifiedLineIndex:e+t,splitLineIndex:i+t,lineIndex:f+t,lineNumber:m+t,noEOFCR:!1}}),()=>{g()})))break hunkIterator}let _=r.unifiedLineStart,v=r.splitLineStart,y=l,b=u,x=o+1,ee=s+1,te=r.hunkContent.at(-1);for(let e of r.hunkContent){if(c.shouldBreak())break hunkIterator;let i=e===te;if(e.type===`context`){if(c.shouldSkip(e.lines,e.lines))c.incrementCounts(e.lines,e.lines),g();else if(FK(c,e.lines,t,t=>{let a=i&&t===e.lines-1,o=_+t,s=v+t;return c.emit({hunkIndex:n,hunk:r,collapsedBefore:g(),collapsedAfter:m(o,s),type:`context`,deletionLine:{lineNumber:x+t,lineIndex:y+t,noEOFCR:a&&r.noEOFCRDeletions,unifiedLineIndex:o,splitLineIndex:s},additionLine:{unifiedLineIndex:o,splitLineIndex:s,lineIndex:b+t,lineNumber:ee+t,noEOFCR:a&&r.noEOFCRAdditions}})},()=>{g()}))break hunkIterator;_+=e.lines,v+=e.lines,y+=e.lines,b+=e.lines,x+=e.lines,ee+=e.lines}else{let a=Math.max(e.deletions,e.additions),o=e.deletions+e.additions;if(!c.shouldSkip(o,a)){let s=IK(c,e,t);(s[0]?.[0]??0)>0&&g();for(let[l,u]of s)for(let s=l;s<u;s++){let l=m(_+s,t===`unified`?v+(s<e.deletions?s:s-e.deletions):v+s);if(c.emit(LK({hunkIndex:n,hunk:r,collapsedBefore:g(),collapsedAfter:l,diffStyle:t,index:s,unifiedLineIndex:_,splitLineIndex:v,additionLineIndex:b,deletionLineIndex:y,additionLineNumber:ee,deletionLineNumber:x,content:e,isLastContent:i,unifiedCount:o,splitCount:a}),!0))break hunkIterator}}g(),c.incrementCounts(o,a),_+=o,v+=a,y+=e.deletions,b+=e.additions,x+=e.deletions,ee+=e.additions}}if(f!=null){let{collapsedLines:n,fromStart:r,fromEnd:i}=f,a=r+i;if(FK(c,a,t,t=>{let r=t===a-1;return c.emit({hunkIndex:e.hunks.length,hunk:void 0,collapsedBefore:0,collapsedAfter:r?n:0,type:`context-expanded`,deletionLine:{lineNumber:x+t,lineIndex:y+t,noEOFCR:!1,unifiedLineIndex:_+t,splitLineIndex:v+t},additionLine:{unifiedLineIndex:_+t,splitLineIndex:v+t,lineIndex:b+t,lineNumber:ee+t,noEOFCR:!1}})},void 0,()=>c.shouldBreak()))break hunkIterator}}}function MK({diff:e,diffStyle:t,startingLine:n,expandedHunks:r,collapsedContextThreshold:i}){if(n<=0||t===`both`)return{hunkIndex:0,splitCount:0,unifiedCount:0};let a=NK({diff:e,expandedHunks:r,collapsedContextThreshold:i}),o=0,s=e.hunks.length-1,c=e.hunks.length;for(;o<=s;){let e=o+s>>1,r=a[e+1];if(r==null)throw Error(`iterateOverDiff: invalid hunk prefix index`);(t===`unified`?r.unifiedCount:r.splitCount)>n?(c=e,s=e-1):o=e+1}if(c>=e.hunks.length){let t=a[e.hunks.length];if(t==null)throw Error(`iterateOverDiff: invalid terminal hunk prefix index`);return{hunkIndex:e.hunks.length,splitCount:t.splitCount,unifiedCount:t.unifiedCount}}let l=a[c];if(l==null)throw Error(`iterateOverDiff: invalid selected hunk prefix index`);return{hunkIndex:c,splitCount:l.splitCount,unifiedCount:l.unifiedCount}}function NK({diff:e,expandedHunks:t,collapsedContextThreshold:n}){let r=0,i=0,a=e.hunks.length-1,o=[{splitCount:0,unifiedCount:0}];for(let s=0;s<e.hunks.length;s++){let c=e.hunks[s];if(c==null)throw Error(`iterateOverDiff: invalid hunk summary index`);let l=yK({isPartial:e.isPartial,rangeSize:c.collapsedBefore,expandedHunks:t,hunkIndex:s,collapsedContextThreshold:n}),u=l.fromStart+l.fromEnd;r+=u+c.splitLineCount,i+=u+c.unifiedLineCount;let d=s===a?SK({fileDiff:e,hunkIndex:s,expandedHunks:t,collapsedContextThreshold:n,errorPrefix:`iterateOverDiff`}):void 0;if(d!=null){let e=d.fromStart+d.fromEnd;r+=e,i+=e}o.push({splitCount:r,unifiedCount:i})}return o}function PK(e,t,n){if(!e.isWindowedHighlight||t<=0)return[0,t];let r=[];function i(n){let i=Math.max(0,e.viewportStart-n),a=Math.min(t,e.viewportEnd-n);a>i&&r.push([i,a])}if(n!==`split`&&i(e.unifiedCount),n!==`unified`&&i(e.splitCount),r.length===0)return[0,0];let a=r[0][0],o=r[0][1];for(let e=1;e<r.length;e++){let t=r[e];a=Math.min(a,t[0]),o=Math.max(o,t[1])}return[a,o]}function FK(e,t,n,r,i,a){let[o,s]=PK(e,t,n);o>0&&(e.incrementCounts(o,o),i?.());let c=o;for(;c<t;){if(a?.()===!0)return!0;if(c>=s){e.incrementCounts(t-c,t-c);break}if(e.isInWindow(0,0)){if(r(c)===!0)return!0}else e.incrementCounts(1,1);c++}return!1}function IK(e,t,n){if(!e.isWindowedHighlight)return[[0,n===`unified`?t.deletions+t.additions:Math.max(t.deletions,t.additions)]];let r=n!==`split`,i=n!==`unified`,a=n===`unified`?`unified`:`split`,o=[];function s(t,n){if(t+n<=e.viewportStart||t>=e.viewportEnd)return;let r=Math.max(0,e.viewportStart-t),i=Math.min(n,e.viewportEnd-t);return i>r?[r,i]:void 0}function c(e,n){return a===`split`?e:n===`additions`?[e[0]+t.deletions,e[1]+t.deletions]:e}function l(e,t){if(e==null)return;let[n,r]=c(e,t);r>n&&o.push([n,r])}if(r&&(l(s(e.unifiedCount,t.deletions),`deletions`),l(s(e.unifiedCount+t.deletions,t.additions),`additions`)),i&&(l(s(e.splitCount,t.deletions),`deletions`),l(s(e.splitCount,t.additions),`additions`)),o.length===0)return o;o.sort((e,t)=>e[0]-t[0]);let u=[o[0]];for(let[e,t]of o.slice(1)){let n=u[u.length-1];e<=n[1]?n[1]=Math.max(n[1],t):u.push([e,t])}return u}function LK({hunkIndex:e,hunk:t,collapsedAfter:n,collapsedBefore:r,diffStyle:i,index:a,unifiedLineIndex:o,splitLineIndex:s,additionLineIndex:c,deletionLineIndex:l,additionLineNumber:u,deletionLineNumber:d,content:f,isLastContent:p,unifiedCount:m,splitCount:h}){let g=a<f.deletions?o+a:void 0,_=i===`unified`?a>=f.deletions?o+a:void 0:a<f.additions?o+f.deletions+a:void 0,v=i===`unified`?s+(a<f.deletions?a:a-f.deletions):s+a,y=a<f.deletions?l+a:void 0,b=a<f.deletions?d+a:void 0,x=i===`unified`?a>=f.deletions?c+(a-f.deletions):void 0:a<f.additions?c+a:void 0,ee=i===`unified`?a>=f.deletions?u+(a-f.deletions):void 0:a<f.additions?u+a:void 0,te=i===`unified`?p&&a===f.deletions-1&&t.noEOFCRDeletions:p&&a===h-1&&t.noEOFCRDeletions,ne=i===`unified`?p&&a===m-1&&t.noEOFCRAdditions:p&&a===h-1&&t.noEOFCRAdditions,re=y!=null&&b!=null&&g!=null?{lineNumber:b,lineIndex:y,noEOFCR:te,unifiedLineIndex:g,splitLineIndex:v}:void 0,ie=x!=null&&ee!=null&&_!=null?{unifiedLineIndex:_,splitLineIndex:v,lineIndex:x,lineNumber:ee,noEOFCR:ne}:void 0;if(re==null&&ie!=null)return{type:`change`,hunkIndex:e,hunk:t,collapsedAfter:n,collapsedBefore:r,deletionLine:void 0,additionLine:ie};if(re!=null&&ie==null)return{type:`change`,hunkIndex:e,hunk:t,collapsedAfter:n,collapsedBefore:r,deletionLine:re,additionLine:void 0};if(re==null||ie==null)throw Error(`iterateOverDiff: missing change line data`);return{type:`change`,hunkIndex:e,hunk:t,collapsedAfter:n,collapsedBefore:r,deletionLine:re,additionLine:ie}}var RK={forcePlainText:!1};function zK(e,t,n,{forcePlainText:r,startingLine:i,totalLines:a,expandedHunks:o,collapsedContextThreshold:s=1}=RK){r?(i??=0,a??=1/0):(i=0,a=1/0);let c=i>0||a<1/0,l=typeof n.theme==`string`?t.getTheme(n.theme).type:void 0,u=_G({theme:n.theme,highlighter:t}),d=r&&!c&&(e.unifiedLineCount>1e3||e.splitLineCount>1e3)?`none`:n.lineDiffType,f={deletionLines:[],additionLines:[]},{maxLineDiffLength:p}=n,m=!r&&!e.isPartial,h=r?o:void 0,g=new Map;function _(e){let t=m?0:e,n=g.get(t)??VK();return g.set(t,n),n}function v(e,t,n,r){if(c){let e=n.at(-1);(e==null||e.targetIndex+e.count!==t)&&(e={targetIndex:t,originalOffset:r.length,count:0},n.push(e)),e.count++}r.push(e)}jK({diff:e,diffStyle:`both`,startingLine:i,totalLines:a,expandedHunks:!c||h,collapsedContextThreshold:s,callback:({hunkIndex:t,additionLine:n,deletionLine:r,type:i})=>{let a=_(t),o=n==null?r.splitLineIndex:n.splitLineIndex;i===`change`&&n!=null&&r!=null&&BK({additionLine:e.additionLines[n.lineIndex],deletionLine:e.deletionLines[r.lineIndex],deletionLineIndex:a.deletionContent.length,additionLineIndex:a.additionContent.length,deletionDecorations:a.deletionDecorations,additionDecorations:a.additionDecorations,lineDiffType:d,maxLineDiffLength:p}),r!=null&&(v(e.deletionLines[r.lineIndex],r.lineIndex,a.deletionSegments,a.deletionContent),a.deletionInfo.push({type:i===`change`?`change-deletion`:i,lineNumber:r.lineNumber,altLineNumber:i===`change`?void 0:n.lineNumber??void 0,lineIndex:`${r.unifiedLineIndex},${o}`})),n!=null&&(v(e.additionLines[n.lineIndex],n.lineIndex,a.additionSegments,a.additionContent),a.additionInfo.push({type:i===`change`?`change-addition`:i,lineNumber:n.lineNumber,altLineNumber:i===`change`?void 0:r.lineNumber??void 0,lineIndex:`${n.unifiedLineIndex},${o}`}))}});for(let i of g.values()){if(i.deletionContent.length===0&&i.additionContent.length===0)continue;let a={name:e.prevName??e.name,contents:i.deletionContent.value},o={name:e.name,contents:i.additionContent.value},{deletionLines:s,additionLines:c}=HK({deletionFile:a,deletionInfo:i.deletionInfo,deletionDecorations:i.deletionDecorations,additionFile:o,additionInfo:i.additionInfo,additionDecorations:i.additionDecorations,highlighter:t,options:n,languageOverride:r?`text`:e.lang});if(m){f.deletionLines=s,f.additionLines=c;continue}if(i.deletionSegments.length>0)for(let e of i.deletionSegments)for(let t=0;t<e.count;t++)f.deletionLines[e.targetIndex+t]=s[e.originalOffset+t];else f.deletionLines.push(...s);if(i.additionSegments.length>0)for(let e of i.additionSegments)for(let t=0;t<e.count;t++)f.additionLines[e.targetIndex+t]=c[e.originalOffset+t];else f.additionLines.push(...c)}return{code:f,themeStyles:u,baseThemeType:l}}function BK({deletionLine:e,additionLine:t,deletionLineIndex:n,additionLineIndex:r,deletionDecorations:i,additionDecorations:a,lineDiffType:o,maxLineDiffLength:s}){if(e==null||t==null||o===`none`||(e=zM(e),t=zM(t),e.length>s||t.length>s))return;let c=o===`char`?WM(e,t):sN(e,t),l=[],u=[],d=o===`word-alt`,f=c.at(-1);for(let e of c){let t=e===f;!e.added&&!e.removed?(_K({item:e,arr:l,enableJoin:d,isNeutral:!0,isLastItem:t}),_K({item:e,arr:u,enableJoin:d,isNeutral:!0,isLastItem:t})):e.removed?_K({item:e,arr:l,enableJoin:d,isLastItem:t}):_K({item:e,arr:u,enableJoin:d,isLastItem:t})}let p=0;for(let e of l)e[0]===1&&i.push(gK({line:n,spanStart:p,spanLength:e[1].length})),p+=e[1].length;p=0;for(let e of u)e[0]===1&&a.push(gK({line:r,spanStart:p,spanLength:e[1].length})),p+=e[1].length}function VK(){return{deletionContent:{push(e){this.value+=e,this.length++},value:``,length:0},additionContent:{push(e){this.value+=e,this.length++},value:``,length:0},deletionInfo:[],additionInfo:[],deletionDecorations:[],additionDecorations:[],deletionSegments:[],additionSegments:[]}}function HK({deletionFile:e,additionFile:t,deletionInfo:n,additionInfo:r,highlighter:i,deletionDecorations:a,additionDecorations:o,languageOverride:s,options:{theme:c=pM,...l}}){let u=s??VW(e.name),d=s??VW(t.name),{state:f,transformers:p}=tG(l.useTokenTransformer),m=typeof c==`string`?{...l,lang:`text`,theme:c,transformers:p,decorations:void 0,defaultColor:!1,cssVariablePrefix:iG(`token`),tokenizeTimeLimit:0}:{...l,lang:`text`,themes:c,transformers:p,decorations:void 0,defaultColor:!1,cssVariablePrefix:iG(`token`),tokenizeTimeLimit:0};return{deletionLines:e.contents===``?[]:(m.lang=u,f.lineInfo=n,m.decorations=a,yG(i.codeToHast(zM(e.contents),m))),additionLines:t.contents===``?[]:(m.lang=d,m.decorations=o,f.lineInfo=r,yG(i.codeToHast(zM(t.contents),m)))}}function UK(e){let t=e.lang??VW(e.name),n=e.lang??(e.prevName==null?`text`:VW(e.prevName));return t===`text`&&n===`text`}function WK(e){let t=[];for(let n of e){let e=cI.get(n);if(e==null)throw Error(`getResolvedLanguages: ${n} is not resolved. Please resolve languages before calling getResolvedLanguages`);t.push(e)}return t}function GK(e){for(let t of Array.isArray(e)?e:[e])if(!cI.has(t))return!1;return!0}async function KK(e){let t=[],n=[];for(let r of e){if(r===`text`||r===`ansi`)continue;let e=RU(r)??LU(r);`then`in e?n.push(e):t.push(e)}return n.length>0&&await Promise.all(n).then(e=>{for(let n of e){if(n==null)throw Error(`resolvedLanguages: unable to resolve language`);t.push(n)}}),t}function qK(e){return XU.getResolvedThemes(e)}async function JK(e){for(let t of e)vW(t);let t=await XU.resolveThemes(e);for(let n=0;n<e.length;n++)yW(e[n],t[n]);return t}var YK={light:`pierre-light`,dark:`pierre-dark`};function XK(e){return e===`dark`?YK.dark:YK.light}var ZK=2166136261,QK=16777619,$K=2654435769,eq=2246822507;function tq(e,t=ZK,n=QK){let r=t>>>0;for(let t=0;t<e.length;t+=1)r^=e.charCodeAt(t),r=Math.imul(r,n)>>>0;return r>>>0}function nq(e,t=`diff-panel`){let n=e.trim(),r=tq(n,ZK,QK).toString(36),i=tq(n,$K,eq).toString(36);return`${t}:${n.length}:${r}:${i}`}function rq(e){return Ca(`flex items-center justify-between gap-2 px-4 wco:pr-[calc(100vw-env(titlebar-area-width)-env(titlebar-area-x)+1em)]`,bn&&e!==`sheet`?`h-[52px] border-b border-border wco:h-[env(titlebar-area-height)]`:`h-12 wco:max-h-[env(titlebar-area-height)]`)}function iq(e){let t=(0,A.c)(10),n=bn&&e.mode!==`sheet`,r=e.mode===`inline`?`w-[42vw] min-w-[360px] max-w-[560px] shrink-0 border-l border-border`:`w-full`,i;t[0]===r?i=t[1]:(i=Ca(`flex h-full min-w-0 flex-col bg-background`,r),t[0]=r,t[1]=i);let a;t[2]!==e.header||t[3]!==e.mode||t[4]!==n?(a=n?(0,k.jsx)(`div`,{className:rq(e.mode),children:e.header}):(0,k.jsx)(`div`,{className:`border-b border-border`,children:(0,k.jsx)(`div`,{className:rq(e.mode),children:e.header})}),t[2]=e.header,t[3]=e.mode,t[4]=n,t[5]=a):a=t[5];let o;return t[6]!==e.children||t[7]!==i||t[8]!==a?(o=(0,k.jsxs)(`div`,{className:i,children:[a,e.children]}),t[6]=e.children,t[7]=i,t[8]=a,t[9]=o):o=t[9],o}function aq(){let e=(0,A.c)(4),t,n;e[0]===Symbol.for(`react.memo_cache_sentinel`)?(t=(0,k.jsx)(Aw,{className:`absolute left-0 top-1/2 size-6 -translate-y-1/2 rounded-md border border-border/50`}),n=(0,k.jsx)(Aw,{className:`absolute right-0 top-1/2 size-6 -translate-y-1/2 rounded-md border border-border/50`}),e[0]=t,e[1]=n):(t=e[0],n=e[1]);let r;e[2]===Symbol.for(`react.memo_cache_sentinel`)?(r=(0,k.jsxs)(`div`,{className:`relative min-w-0 flex-1`,children:[t,n,(0,k.jsxs)(`div`,{className:`flex gap-1 overflow-hidden px-8 py-0.5`,children:[(0,k.jsx)(Aw,{className:`h-6 w-16 shrink-0 rounded-md`}),(0,k.jsx)(Aw,{className:`h-6 w-24 shrink-0 rounded-md`}),(0,k.jsx)(Aw,{className:`h-6 w-24 shrink-0 rounded-md max-sm:hidden`})]})]}),e[2]=r):r=e[2];let i;return e[3]===Symbol.for(`react.memo_cache_sentinel`)?(i=(0,k.jsxs)(k.Fragment,{children:[r,(0,k.jsxs)(`div`,{className:`flex shrink-0 gap-1`,children:[(0,k.jsx)(Aw,{className:`size-7 rounded-md`}),(0,k.jsx)(Aw,{className:`size-7 rounded-md`})]})]}),e[3]=i):i=e[3],i}function oq(e){let t=(0,A.c)(7),n;t[0]===Symbol.for(`react.memo_cache_sentinel`)?(n=(0,k.jsxs)(`div`,{className:`flex items-center gap-2 border-b border-border/50 px-3 py-2`,children:[(0,k.jsx)(Aw,{className:`h-4 w-32 rounded-full`}),(0,k.jsx)(Aw,{className:`ml-auto h-4 w-20 rounded-full`})]}),t[0]=n):n=t[0];let r;t[1]===Symbol.for(`react.memo_cache_sentinel`)?(r=(0,k.jsxs)(`div`,{className:`space-y-2`,children:[(0,k.jsx)(Aw,{className:`h-3 w-full rounded-full`}),(0,k.jsx)(Aw,{className:`h-3 w-full rounded-full`}),(0,k.jsx)(Aw,{className:`h-3 w-10/12 rounded-full`}),(0,k.jsx)(Aw,{className:`h-3 w-11/12 rounded-full`}),(0,k.jsx)(Aw,{className:`h-3 w-9/12 rounded-full`})]}),t[1]=r):r=t[1];let i;t[2]===e.label?i=t[3]:(i=(0,k.jsxs)(`div`,{className:`flex min-h-0 flex-1 flex-col gap-4 px-3 py-4`,children:[r,(0,k.jsx)(`span`,{className:`sr-only`,children:e.label})]}),t[2]=e.label,t[3]=i);let a;return t[4]!==e.label||t[5]!==i?(a=(0,k.jsx)(`div`,{className:`flex min-h-0 flex-1 flex-col p-2`,children:(0,k.jsxs)(`div`,{className:`flex min-h-0 flex-1 flex-col overflow-hidden rounded-md border border-border/60 bg-card/25`,role:`status`,"aria-live":`polite`,"aria-label":e.label,children:[n,i]})}),t[4]=e.label,t[5]=i,t[6]=a):a=t[6],a}function sq(e){let t=(0,O.useRef)(e);return(0,O.useInsertionEffect)(()=>void(t.current=e)),(0,O.useCallback)((...e)=>t.current(...e),[])}var cq=(0,O.createContext)(void 0);function lq(){return(0,O.useContext)(cq)}var uq={position:`absolute`,top:0,bottom:0,textAlign:`center`,whiteSpace:`normal`,touchAction:`none`},dq={display:`contents`};function fq(){return null}var pq=t(n(((e,t)=>{(function(n,r){typeof e==`object`&&t!==void 0?r(e):typeof define==`function`&&define.amd?define([`exports`],r):r((n||=self).lru_map=n.lru_map||{})})(e,function(e){let t=Symbol(`newer`),n=Symbol(`older`);class r{constructor(e,t){typeof e!=`number`&&(t=e,e=0),this.size=0,this.limit=e,this.oldest=this.newest=void 0,this._keymap=new Map,t&&(this.assign(t),e<1&&(this.limit=this.size))}_markEntryAsUsed(e){e!==this.newest&&(e[t]&&(e===this.oldest&&(this.oldest=e[t]),e[t][n]=e[n]),e[n]&&(e[n][t]=e[t]),e[t]=void 0,e[n]=this.newest,this.newest&&(this.newest[t]=e),this.newest=e)}assign(e){let r,a=this.limit||Number.MAX_VALUE;this._keymap.clear();let o=e[Symbol.iterator]();for(let e=o.next();!e.done;e=o.next()){let o=new i(e.value[0],e.value[1]);if(this._keymap.set(o.key,o),r?(r[t]=o,o[n]=r):this.oldest=o,r=o,a--==0)throw Error(`overflow`)}this.newest=r,this.size=this._keymap.size}get(e){var t=this._keymap.get(e);return t?(this._markEntryAsUsed(t),t.value):void 0}set(e,r){var a=this._keymap.get(e);return a?(a.value=r,this._markEntryAsUsed(a),this):(this._keymap.set(e,a=new i(e,r)),this.newest?(this.newest[t]=a,a[n]=this.newest):this.oldest=a,this.newest=a,++this.size,this.size>this.limit&&this.shift(),this)}shift(){var e=this.oldest;if(e)return this.oldest[t]?(this.oldest=this.oldest[t],this.oldest[n]=void 0):(this.oldest=void 0,this.newest=void 0),e[t]=e[n]=void 0,this._keymap.delete(e.key),--this.size,[e.key,e.value]}find(e){let t=this._keymap.get(e);return t?t.value:void 0}has(e){return this._keymap.has(e)}delete(e){var r=this._keymap.get(e);return r?(this._keymap.delete(r.key),r[t]&&r[n]?(r[n][t]=r[t],r[t][n]=r[n]):r[t]?(r[t][n]=void 0,this.oldest=r[t]):r[n]?(r[n][t]=void 0,this.newest=r[n]):this.oldest=this.newest=void 0,this.size--,r.value):void 0}clear(){this.oldest=this.newest=void 0,this.size=0,this._keymap.clear()}keys(){return new o(this.oldest)}values(){return new s(this.oldest)}entries(){return this}[Symbol.iterator](){return new a(this.oldest)}forEach(e,n){typeof n!=`object`&&(n=this);let r=this.oldest;for(;r;)e.call(n,r.value,r.key,this),r=r[t]}toJSON(){for(var e=Array(this.size),n=0,r=this.oldest;r;)e[n++]={key:r.key,value:r.value},r=r[t];return e}toString(){for(var e=``,n=this.oldest;n;)e+=String(n.key)+`:`+n.value,n=n[t],n&&(e+=` < `);return e}}e.LRUMap=r;function i(e,r){this.key=e,this.value=r,this[t]=void 0,this[n]=void 0}function a(e){this.entry=e}a.prototype[Symbol.iterator]=function(){return this},a.prototype.next=function(){let e=this.entry;return e?(this.entry=e[t],{done:!1,value:[e.key,e.value]}):{done:!0,value:void 0}};function o(e){this.entry=e}o.prototype[Symbol.iterator]=function(){return this},o.prototype.next=function(){let e=this.entry;return e?(this.entry=e[t],{done:!1,value:e.key}):{done:!0,value:void 0}};function s(e){this.entry=e}s.prototype[Symbol.iterator]=function(){return this},s.prototype.next=function(){let e=this.entry;return e?(this.entry=e[t],{done:!1,value:e.value}):{done:!0,value:void 0}}})}))(),1),mq=Symbol(`IGNORE_RESPONSE`),hq=class extends Error{constructor(){super(`WorkerPoolManager: operation canceled because the pool terminated`)}},gq=class extends Error{constructor(){super(`WorkerPoolManager: operation canceled before the task completed`)}},_q=class{options;highlighter;preferredHighlighter;renderOptions;renderOptionsRequestVersion=0;renderOptionsVersion=0;initialized=!1;workers=[];queuedTasks=[];queuedTaskByInstance=new Map;taskByHighlightKey=new Map;activeTaskById=new Map;activeRequestByInstance=new Map;nextRequestId=0;themeSubscribers=new Set;workersFailed=!1;statSubscribers=new Set;fileCache;diffCache;_queuedBroadcast;lifecycleGeneration=0;constructor(e,{langs:t,theme:n=pM,useTokenTransformer:r=!1,lineDiffType:i=`word-alt`,maxLineDiffLength:a=1e3,tokenizeMaxLineLength:o=1e3,preferredHighlighter:s=`shiki-js`}){this.options=e,this.preferredHighlighter=s,this.renderOptions={theme:n,useTokenTransformer:r,lineDiffType:i,maxLineDiffLength:a,tokenizeMaxLineLength:o},this.fileCache=new pq.default.LRUMap(e.totalASTLRUCacheSize??100),this.diffCache=new pq.default.LRUMap(e.totalASTLRUCacheSize??100),this.queueInitialization(t)}isWorkingPool(){return!this.workersFailed}getFileResultCache(e){return e.cacheKey==null?void 0:this.fileCache.get(e.cacheKey)}getDiffResultCache(e){return e.cacheKey==null?void 0:this.diffCache.get(e.cacheKey)}inspectCaches(){let{fileCache:e,diffCache:t}=this;return{fileCache:e,diffCache:t}}evictFileFromCache(e){try{return this.fileCache.delete(e)!==void 0}finally{this.queueBroadcastStateChanges()}}evictDiffFromCache(e){try{return this.diffCache.delete(e)!==void 0}finally{this.queueBroadcastStateChanges()}}async setRenderOptions({theme:e=this.renderOptions.theme??pM,useTokenTransformer:t=this.renderOptions.useTokenTransformer??!1,lineDiffType:n=this.renderOptions.lineDiffType??`word-alt`,maxLineDiffLength:r=this.renderOptions.maxLineDiffLength??1e3,tokenizeMaxLineLength:i=this.renderOptions.tokenizeMaxLineLength??1e3}){let{lifecycleGeneration:a}=this,o=++this.renderOptionsRequestVersion,s=()=>this.isCurrentLifecycle(a)&&this.renderOptionsRequestVersion===o;try{let a={theme:e,useTokenTransformer:t,lineDiffType:n,maxLineDiffLength:r,tokenizeMaxLineLength:i};if(this.isInitialized()||await this.initialize(),!s()||hK(a,this.renderOptions))return;let o=EW(e),c=[];if(PM(a.theme,this.renderOptions.theme)||(c=OW(o)?qK(o):await JK(o)),!s())return;if(this.highlighter!=null)ZU(c,this.highlighter);else{let e=await CW({themes:o,langs:[`text`],preferredHighlighter:this.preferredHighlighter});if(!s())return;this.highlighter=e}let l=this.setRenderOptionsOnWorkers(a,c);this.renderOptions=a,this.renderOptionsVersion++,this.diffCache.clear(),this.fileCache.clear(),this.invalidateRenderTasks();for(let e of this.themeSubscribers)e.onThemeChange();await l}catch(e){if(e instanceof hq||!s())return;throw e}}getPreferredHighlighter(){return this.preferredHighlighter}getFileRenderOptions(){let{tokenizeMaxLineLength:e,theme:t,useTokenTransformer:n}=this.renderOptions;return{theme:t,useTokenTransformer:n,tokenizeMaxLineLength:e}}getDiffRenderOptions(){return{...this.renderOptions}}async setRenderOptionsOnWorkers(e,t){if(this.workersFailed)return;this.isInitialized()||await this.initialize();let n=[];for(let r of this.workers){if(!r.initialized)throw console.log({managedWorker:r}),Error(`setRenderOptionsOnWorkers: Somehow we have an uninitialized worker`);n.push(new Promise((n,i)=>{let a=this.generateRequestId(),o={type:`set-render-options`,id:a,request:{type:`set-render-options`,id:a,renderOptions:e,resolvedThemes:t},resolve:n,reject:i,requestStart:Date.now()};this.activeTaskById.set(a,o),r.pendingSetupRequestId=a,r.worker.postMessage(o.request)}))}await Promise.all(n)}subscribeToThemeChanges(e){return this.themeSubscribers.add(e),this.queueBroadcastStateChanges(),()=>{this.unsubscribeToThemeChanges(e),this.queueBroadcastStateChanges()}}unsubscribeToThemeChanges(e){this.themeSubscribers.delete(e),this.queueBroadcastStateChanges()}subscribeToStatChanges(e){return this.statSubscribers.add(e),e(this.getStats()),()=>{this.statSubscribers.delete(e)}}queueBroadcastStateChanges(){this._queuedBroadcast??=requestAnimationFrame(this._broadcastStateChanges)}_broadcastStateChanges=()=>{this._queuedBroadcast!=null&&(cancelAnimationFrame(this._queuedBroadcast),this._queuedBroadcast=void 0);let e=this.getStats();for(let t of this.statSubscribers)t(e)};cleanUpTasks(e){this.detachInstanceFromQueuedTasks(e);let t=this.activeRequestByInstance.get(e);if(t!=null){let n=this.activeTaskById.get(t);bq(n)?(this.detachInstanceFromRenderTask(n,e),!n.primeCache&&n.instances.size===0&&this.removeActiveTask(n)):this.activeTaskById.delete(t)}this.activeRequestByInstance.delete(e),this.queueBroadcastStateChanges()}isInitialized(){return this.initialized===!0}async initialize(e=[]){if(this.initialized!==!0)if(this.initialized===!1){let{lifecycleGeneration:t}=this;this.initialized=new Promise((n,r)=>{(async()=>{try{let r=EW(this.renderOptions.theme),i=[];if(i=OW(r)?qK(r):await JK(r),!this.isCurrentLifecycle(t)){n();return}let a=[];if(a=GK(e)?WK(e):await KK(e),!this.isCurrentLifecycle(t)){n();return}let[o]=await Promise.all([CW({themes:r,langs:[`text`,...e],preferredHighlighter:this.preferredHighlighter}),this.initializeWorkers(i,a)]);if(!this.isCurrentLifecycle(t)){this.terminateWorkers(),n();return}this.highlighter=o,this.initialized=!0,this.diffCache.clear(),this.fileCache.clear(),this.drainQueue(),this.queueBroadcastStateChanges(),n()}catch(e){if(e instanceof hq||!this.isCurrentLifecycle(t)){n();return}this.initialized=!1,this.workersFailed=!0;for(let t of this.queuedTasks)this.rejectRenderTaskCallbacks(t,Sq(e));this.queueBroadcastStateChanges(),r(e)}})()}),this.queueBroadcastStateChanges()}else return this.initialized}async initializeWorkers(e,t){this.workersFailed=!1;let n=[],r=HW(),i=r>0?UW():void 0;this.workers.length>0&&this.terminateWorkers();for(let a=0;a<(this.options.poolSize??8);a++){let a=this.options.workerFactory(),o={worker:a,requestId:void 0,pendingSetupRequestId:void 0,initialized:!1,langs:new Set([`text`,...t.map(({name:e})=>e)]),customExtensionsVersion:0};a.addEventListener(`message`,e=>{this.handleWorkerMessage(o,e.data)}),a.addEventListener(`error`,e=>console.error(`Worker error:`,e,o)),this.workers.push(o),n.push(new Promise((n,a)=>{let s=this.generateRequestId(),c={type:`initialize`,id:s,request:{type:`initialize`,id:s,renderOptions:this.renderOptions,preferredHighlighter:this.preferredHighlighter,resolvedThemes:e,resolvedLanguages:t,customExtensionsVersion:i==null?void 0:r,customExtensionMap:i},resolve(){o.initialized=!0,n()},reject:a,requestStart:Date.now()};this.activeTaskById.set(s,c),this.executeTask(o,c)}))}await Promise.all(n)}drainQueue=()=>{if(this._queuedDrain=void 0,this.initialized===!0&&this.queuedTasks.length!==0){for(let e=0;e<this.queuedTasks.length;){let t=this.queuedTasks[e];if(this.hasActiveRequest(t)){e++;continue}let n=yq(t),r=this.getAvailableWorker(n);if(r==null)break;this.queuedTasks.splice(e,1),this.assignWorkerToTask(t,r),this.resolveLanguagesAndExecuteTask(r,t,n)}this.queueBroadcastStateChanges()}};highlightFileAST(e,t){let n=this.getFileResultCache(t);FG(t)||n!=null&&kW(n.options,this.getFileRenderOptions())||this.hasMatchingFileInstanceTask(e,t)||this.submitTask(e,{type:`file`,file:t})}primeFileHighlightCache(e){if(!this.isWorkingPool())return Promise.reject(Error(`WorkerPoolManager.primeFileHighlightCache: worker pool is not working`));let t=this.getOrCreateFileHighlightCacheTask(e);return t==null?Promise.resolve():this.createRenderTaskCallbacks(t)}getOrCreateFileHighlightCacheTask(e){if(e.cacheKey==null){console.warn(`WorkerPoolManager.primeFileHighlightCache: priming highlight cache requires file.cacheKey; skipping "${e.name}".`);return}let t=this.getFileResultCache(e),n=this.getFileHighlightKey(e);if(n==null||FG(e)||t!=null&&kW(t.options,this.getFileRenderOptions()))return;let r=this.getTaskByHighlightKey(n);if(r!=null)return r.primeCache=!0,r.type===`file`?r:void 0;{let t=this.submitCacheTask({type:`file`,file:e},n);return t.type===`file`?t:void 0}}getPlainFileAST(e,t,n,r){if(this.highlighter==null){this.queueInitialization();return}return DG(e,this.highlighter,this.renderOptions,{forcePlainText:!0,startingLine:t,totalLines:n,lines:r})}highlightDiffAST(e,t){let n=this.getDiffResultCache(t);UK(t)||n!=null&&hK(n.options,this.getDiffRenderOptions())||this.hasMatchingDiffInstanceTask(e,t)||this.submitTask(e,{type:`diff`,diff:t})}primeDiffHighlightCache(e){if(!this.isWorkingPool())return Promise.reject(Error(`WorkerPoolManager.primeDiffHighlightCache: worker pool is not working`));let t=this.getOrCreateDiffHighlightCacheTask(e);return t==null?Promise.resolve():this.createRenderTaskCallbacks(t)}getOrCreateDiffHighlightCacheTask(e){if(e.cacheKey==null){console.warn(`WorkerPoolManager.primeDiffHighlightCache: priming highlight cache requires diff.cacheKey; skipping "${e.prevName??e.name}" -> "${e.name}".`);return}let t=this.getDiffResultCache(e),n=this.getDiffHighlightKey(e);if(n==null||UK(e)||t!=null&&hK(t.options,this.getDiffRenderOptions()))return;let r=this.getTaskByHighlightKey(n);if(r!=null)return r.primeCache=!0,r.type===`diff`?r:void 0;{let t=this.submitCacheTask({type:`diff`,diff:e},n);return t.type===`diff`?t:void 0}}getPlainDiffAST(e,t,n,r,i){return this.highlighter==null?void 0:zK(e,this.highlighter,this.renderOptions,{forcePlainText:!0,startingLine:t,totalLines:n,expandedHunks:r,collapsedContextThreshold:i})}terminate(){this.lifecycleGeneration++,this.cancelActiveWorkerTasks(),this.terminateWorkers();let e=new hq;for(let t of this.queuedTasks)this.rejectRenderTaskCallbacks(t,e);this.fileCache.clear(),this.diffCache.clear(),this.activeRequestByInstance.clear(),this.queuedTasks.length=0,this.queuedTaskByInstance.clear(),this.taskByHighlightKey.clear(),this.activeTaskById.clear(),this.highlighter=void 0,this.initialized=!1,this.workersFailed=!1,this.queueBroadcastStateChanges()}isCurrentLifecycle(e){return this.lifecycleGeneration===e}queueInitialization(e){this.initialize(e).catch(e=>{console.error(e)})}cancelActiveWorkerTasks(){let e=new hq;for(let t of this.activeTaskById.values())`reject`in t?t.reject(e):bq(t)&&this.rejectRenderTaskCallbacks(t,e)}terminateWorkers(){for(let e of this.workers)e.worker.terminate();this.workers.length=0}getStats(){return{managerState:this.initialized===!1?`waiting`:this.initialized===!0?`initialized`:`initializing`,totalWorkers:this.workers.length,workersFailed:this.workersFailed,busyWorkers:this.workers.filter(e=>e.requestId!=null||e.pendingSetupRequestId!=null).length,queuedTasks:this.queuedTasks.length,activeTasks:this.activeTaskById.size,themeSubscribers:this.themeSubscribers.size,fileCacheSize:this.fileCache.size,diffCacheSize:this.diffCache.size}}submitTask(e,t){this.initialized===!1&&this.queueInitialization();let n=this.getHighlightKeyForRequest(t),r=n==null?void 0:this.getTaskByHighlightKey(n);if(r!=null){this.detachInstanceFromQueuedTasks(e,r),this.addInstanceToTask(r,e),this.queueBroadcastStateChanges();return}this.detachInstanceFromQueuedTasks(e);let i=this.generateRequestId(),a=Date.now(),{renderOptionsVersion:o}=this,s=(()=>{switch(t.type){case`file`:return{type:`file`,id:i,request:{...t,id:i},instances:new Set([e]),primeCache:!1,highlightKey:n,callbacks:new Set,renderOptionsVersion:o,requestStart:a};case`diff`:return{type:`diff`,id:i,request:{...t,id:i},instances:new Set([e]),primeCache:!1,highlightKey:n,callbacks:new Set,renderOptionsVersion:o,requestStart:a}}})();this.enqueueRenderTask(s,e)}submitCacheTask(e,t){this.initialized===!1&&this.queueInitialization();let n=this.generateRequestId(),r=Date.now(),{renderOptionsVersion:i}=this,a=(()=>{switch(e.type){case`file`:return{type:`file`,id:n,request:{...e,id:n},instances:new Set,primeCache:!0,highlightKey:t,callbacks:new Set,renderOptionsVersion:i,requestStart:r};case`diff`:return{type:`diff`,id:n,request:{...e,id:n},instances:new Set,primeCache:!0,highlightKey:t,callbacks:new Set,renderOptionsVersion:i,requestStart:r}}})();return this.enqueueRenderTask(a),a}enqueueRenderTask(e,t){this.queuedTasks.push(e),t!=null&&this.queuedTaskByInstance.set(t,e),e.highlightKey!=null&&this.taskByHighlightKey.set(e.highlightKey,e),this.queueDrain()}async resolveLanguagesAndExecuteTask(e,t,n){try{let r=n.filter(t=>!e.langs.has(t));if(r.length>0&&(GK(r)?t.request.resolvedLanguages=WK(r):t.request.resolvedLanguages=await KK(r)),!this.activeTaskById.has(t.id)){e.requestId===t.id&&(this.cleanWorkerAndTask(e,t),this.queueBroadcastStateChanges(),this.queuedTasks.length>0&&this.queueDrain());return}this.executeTask(e,t)}catch(n){this.rejectRenderTaskCallbacks(t,Sq(n)),this.cleanWorkerAndTask(e,t),this.queueBroadcastStateChanges(),this.queuedTasks.length>0&&this.queueDrain()}}handleWorkerMessage(e,t){let n=this.activeTaskById.get(t.id);try{if(n==null)throw mq;if(t.type===`error`){let e=Error(t.error);if(t.stack&&(e.stack=t.stack),`reject`in n)n.reject(e);else if(bq(n))this.notifyHighlightError(n,e),this.rejectRenderTaskCallbacks(n,e);else throw Error(`handleWorkerMessage: unknown task type`);throw e}switch(t.requestType){case`initialize`:if(n.type!==`initialize`)throw Error(`handleWorkerMessage: task/response dont match`);this.syncCustomExtensionVersion(e,n.request),n.resolve();break;case`set-render-options`:if(n.type!==`set-render-options`)throw Error(`handleWorkerMessage: task/response dont match`);n.resolve();break;case`file`:{if(n.type!==`file`)throw Error(`handleWorkerMessage: task/response dont match`);let{result:r,options:i}=t;if(!this.isCurrentRenderTask(n)||!kW(i,this.getFileRenderOptions()))throw mq;let{request:a}=n;this.syncCustomExtensionVersion(e,a),n.cacheKeyAtDispatch!=null&&this.fileCache.set(n.cacheKeyAtDispatch,{result:r,options:i}),this.resolveRenderTaskCallbacks(n),this.notifyFileInstances(n,r,i);break}case`diff`:{if(n.type!==`diff`)throw Error(`handleWorkerMessage: task/response dont match`);let{result:r,options:i}=t;if(!this.isCurrentRenderTask(n)||!hK(i,this.getDiffRenderOptions()))throw mq;let{request:a}=n;this.syncCustomExtensionVersion(e,a),n.cacheKeyAtDispatch!=null&&this.diffCache.set(n.cacheKeyAtDispatch,{result:r,options:i}),this.resolveRenderTaskCallbacks(n),this.notifyDiffInstances(n,r,i);break}}}catch(e){e!==mq&&console.error(e,n,t)}this.cleanWorkerAndTask(e,n,t.id),this.queueBroadcastStateChanges(),this.queuedTasks.length>0&&this.queueDrain()}_queuedDrain;queueDrain(){this._queuedDrain??(this._queuedDrain=Promise.resolve().then(this.drainQueue),this.queueBroadcastStateChanges())}assignWorkerToTask(e,t){t.requestId=e.id,bq(e)&&(this.clearQueuedInstanceRequests(e),this.trackInstanceRequests(e)),this.activeTaskById.set(e.id,e)}cleanWorkerAndTask(e,t,n=t?.id){e.requestId===n&&(e.requestId=void 0),e.pendingSetupRequestId===n&&(e.pendingSetupRequestId=void 0),t!=null&&(bq(t)&&(this.rejectRenderTaskCallbacks(t,new gq),this.clearInstanceRequests(t),this.clearHighlightKey(t)),this.activeTaskById.delete(t.id))}executeTask(e,t){vq(t.request)&&this.maybeAttachCustomExtensions(e,t.request),this.activeTaskById.has(t.id)||this.assignWorkerToTask(t,e);for(let n of yq(t))e.langs.add(n);try{t.type===`file`?t.cacheKeyAtDispatch=t.request.file.cacheKey:t.type===`diff`&&(t.cacheKeyAtDispatch=t.request.diff.cacheKey),e.worker.postMessage(t.request)}catch(n){console.error(`Failed to post message to worker:`,n),bq(t)?(this.notifyHighlightError(t,n),this.rejectRenderTaskCallbacks(t,Sq(n))):`reject`in t&&t.reject(n),this.cleanWorkerAndTask(e,t),this.queuedTasks.length>0&&this.queueDrain()}this.queueBroadcastStateChanges()}maybeAttachCustomExtensions(e,t){if(t.customExtensionsVersion!=null)return;let n=HW();e.customExtensionsVersion>=n||(t.customExtensionsVersion=n,t.customExtensionMap=UW())}syncCustomExtensionVersion(e,t){t.customExtensionsVersion!=null&&(e.customExtensionsVersion=t.customExtensionsVersion)}getAvailableWorker(e){let t;for(let n of this.workers){if(n.requestId!=null||n.pendingSetupRequestId!=null||!n.initialized)continue;if(t=n,e.length===0)break;let r=!0;for(let t of e)if(!n.langs.has(t)){r=!1;break}if(r)break}return t}getFileHighlightKey(e){if(e.cacheKey!=null)return`file:${e.cacheKey}:${this.renderOptionsVersion}`}getDiffHighlightKey(e){if(e.cacheKey!=null)return`diff:${e.cacheKey}:${this.renderOptionsVersion}`}getHighlightKeyForRequest(e){switch(e.type){case`file`:return this.getFileHighlightKey(e.file);case`diff`:return this.getDiffHighlightKey(e.diff)}}hasActiveRequest(e){for(let t of xq(e))if(this.activeRequestByInstance.has(t))return!0;return!1}addInstanceToTask(e,t){e.type,e.instances.add(t),this.activeTaskById.has(e.id)?this.activeRequestByInstance.set(t,e.id):this.queuedTaskByInstance.set(t,e)}detachInstanceFromQueuedTasks(e,t){let n=this.queuedTaskByInstance.get(e);n!=null&&n!==t&&(this.queuedTaskByInstance.delete(e),this.detachInstanceFromRenderTask(n,e),!n.primeCache&&n.instances.size===0&&this.removeQueuedTask(n))}detachInstanceFromRenderTask(e,t){e.type,e.instances.delete(t)}removeQueuedTask(e){let t=this.queuedTasks.indexOf(e);t!==-1&&this.queuedTasks.splice(t,1),this.rejectRenderTaskCallbacks(e,new gq),this.clearQueuedInstanceRequests(e),this.clearHighlightKey(e)}removeActiveTask(e){this.rejectRenderTaskCallbacks(e,new gq),this.clearInstanceRequests(e),this.clearHighlightKey(e),this.activeTaskById.delete(e.id)}createRenderTaskCallbacks(e){return new Promise((t,n)=>{e.callbacks.add({resolve:t,reject:n})})}resolveRenderTaskCallbacks(e){for(let t of e.callbacks)t.resolve();e.callbacks.clear()}rejectRenderTaskCallbacks(e,t){for(let n of e.callbacks)n.reject(t);e.callbacks.clear()}invalidateRenderTasks(){for(let e=this.queuedTasks.length-1;e>=0;e--){let t=this.queuedTasks[e];t.renderOptionsVersion!==this.renderOptionsVersion&&this.removeQueuedTask(t)}for(let e of Array.from(this.activeTaskById.values()))bq(e)&&e.renderOptionsVersion!==this.renderOptionsVersion&&this.removeActiveTask(e)}clearQueuedInstanceRequests(e){for(let t of xq(e))this.queuedTaskByInstance.get(t)===e&&this.queuedTaskByInstance.delete(t)}clearHighlightKey(e){e.highlightKey!=null&&this.taskByHighlightKey.get(e.highlightKey)===e&&this.taskByHighlightKey.delete(e.highlightKey)}trackInstanceRequests(e){for(let t of xq(e))this.activeRequestByInstance.set(t,e.id)}clearInstanceRequests(e){for(let t of xq(e))this.activeRequestByInstance.get(t)===e.id&&this.activeRequestByInstance.delete(t)}notifyFileInstances(e,t,n){for(let r of e.instances)this.activeRequestByInstance.get(r)===e.id&&r.onHighlightSuccess(e.request.file,t,n)}notifyDiffInstances(e,t,n){for(let r of e.instances)this.activeRequestByInstance.get(r)===e.id&&r.onHighlightSuccess(e.request.diff,t,n)}notifyHighlightError(e,t){for(let n of xq(e))this.activeRequestByInstance.get(n)===e.id&&n.onHighlightError(t)}hasMatchingFileInstanceTask(e,t){for(let n of this.iterateRenderTasks())if(n.type===`file`&&this.isCurrentRenderTask(n)&&n.instances.has(e)&&bN(t,n.request.file))return!0;return!1}hasMatchingDiffInstanceTask(e,t){for(let n of this.iterateRenderTasks())if(n.type===`diff`&&this.isCurrentRenderTask(n)&&n.instances.has(e)&&mK(n.request.diff,t))return!0;return!1}getTaskByHighlightKey(e){let t=this.taskByHighlightKey.get(e);return t!=null&&this.isCurrentRenderTask(t)?t:void 0}isCurrentRenderTask(e){return e.renderOptionsVersion===this.renderOptionsVersion}*iterateRenderTasks(){for(let e of this.queuedTasks)yield e;for(let e of this.activeTaskById.values())bq(e)&&(yield e)}generateRequestId(){return`req_${++this.nextRequestId}`}};function vq(e){return e.type===`initialize`||e.type===`file`||e.type===`diff`}function yq(e){let t=new Set;if(e.type===`initialize`||e.type===`set-render-options`)return[];switch(e.type){case`file`:t.add(e.request.file.lang??VW(e.request.file.name));break;case`diff`:t.add(e.request.diff.lang??VW(e.request.diff.name)),t.add(e.request.diff.lang??VW(e.request.diff.prevName??`-`))}return t.delete(`text`),Array.from(t)}function bq(e){return e?.type===`file`||e?.type===`diff`}function xq(e){return e.instances}function Sq(e){return e instanceof Error?e:Error(String(e))}var Cq;function wq({poolOptions:e,highlighterOptions:t}){return Cq??=new _q(e,t),Cq}function Tq(){Cq!=null&&(Cq.terminate(),Cq=void 0)}var Eq=(0,O.createContext)(void 0),Dq=0;function Oq({children:e,poolOptions:t,highlighterOptions:n}){let[r]=(0,O.useState)(()=>{if(!(typeof window>`u`))return wq({poolOptions:t,highlighterOptions:n})});return(0,O.useInsertionEffect)(()=>{if(r!=null)return Dq++,()=>{Dq--}},[r]),(0,O.useEffect)(()=>()=>{Dq===0&&Tq()},[]),(0,k.jsx)(Eq.Provider,{value:r,children:e})}function kq(){return(0,O.useContext)(Eq)}export{jG as $,wh as $a,bx as $i,dk as $n,j as $o,nT as $r,no as $s,vM as $t,uK as A,u_ as Aa,xC as Ai,Nj as An,Gf as Ao,sD as Ar,Lo as As,oP as At,ZG as B,Wg as Ba,pC as Bi,gA as Bn,Md as Bo,$T as Br,mo as Bs,bN as Bt,SK as C,h_ as Ca,vw as Ci,qj as Cn,ip as Co,ND as Cr,Po as Cs,zP as Ct,hK as D,d_ as Da,uw as Di,Kj as Dn,ep as Do,VD as Dr,jo as Ds,IP as Dt,CK as E,f_ as Ea,Tw as Ei,Xj as En,ap as Eo,KD as Er,Mo as Es,RP as Et,rK as F,Yg as Fa,lC as Fi,NA as Fn,Ff as Fo,YT as Fr,bo as Fs,TN as Ft,VG as G,Ag as Ga,XS as Gi,Zk as Gn,zu as Go,HT as Gr,to as Gs,RM as Gt,YG as H,Rg as Ha,nC as Hi,$k as Hn,Td as Ho,RT as Hr,co as Hs,VM as Ht,nK as I,Gg as Ia,dC as Ii,OA as In,mf as Io,tE as Ir,yo as Is,wN as It,IG as J,ag as Ja,SS as Ji,gk as Jn,Rl as Jo,Zw as Jr,Za as Js,PM as Jt,BG as K,gg as Ka,NS as Ki,Hk as Kn,Wu as Ko,WT as Kr,ao as Ks,LM as Kt,tK as L,Qg as La,mC as Li,MA as Ln,pf as Lo,ZT as Lr,vo as Ls,B as Lt,cK as M,c_ as Ma,hC as Mi,xj as Mn,Hf as Mo,rD as Mr,Ro as Ms,NN as Mt,aK as N,s_ as Na,_C as Ni,gj as Nn,zf as No,aD as Nr,Yo as Ns,AN as Nt,mK as O,a_ as Oa,jC as Oi,Zj as On,Xf as Oo,bD as Or,To as Os,cP as Ot,iK as P,Xg as Pa,oC as Pi,rj as Pn,If as Po,oD as Pr,qo as Ps,EN as Pt,kG as Q,Oh as Qa,iS as Qi,mk as Qn,dl as Qo,tT as Qr,Va as Qs,sM as Qt,eK as R,zg as Ra,uC as Ri,DA as Rn,of as Ro,QT as Rr,_o as Rs,SN as Rt,xK as S,__ as Sa,dw as Si,Jj as Sn,lp as So,LD as Sr,Eo as Ss,HP as St,bK as T,p_ as Ta,pw as Ti,$j as Tn,Qf as To,GD as Tr,Wo as Ts,LP as Tt,GG as U,Eg as Ua,QS as Ui,eA as Un,nd as Uo,IT as Ur,so as Us,BM as Ut,XG as V,wg as Va,cC as Vi,_A as Vn,Cd as Vo,NT as Vr,lo as Vs,vN as Vt,HG as W,Sg as Wa,ZS as Wi,Qk as Wn,ud as Wo,LT as Wr,oo as Ws,zM as Wt,PG as X,Sh as Xa,tS as Xi,_k as Xn,Ol as Xo,qw as Xr,Ba as Xs,jM as Xt,FG as Y,vh as Ya,yS as Yi,hk as Yn,kl as Yo,Qw as Yr,io as Ys,NM as Yt,NG as Z,Dh as Za,aS as Zi,bk as Zn,wl as Zo,Jw as Zr,Ua as Zs,AM as Zt,jK as _,J_ as _a,hw as _i,uM as _n,cm as _o,zO as _r,fs as _s,fI as _t,dq as a,Oy as aa,hT as ai,TM as an,zm as ao,BO as ar,Rs as as,WW as at,kK as b,T_ as ba,fw as bi,cM as bn,cp as bo,fO as br,ns as bs,FF as bt,sq as c,xy as ca,_T as ci,pM as cn,Fm as co,sk as cr,Ps as cs,NW as ct,iq as d,vy as da,Dw as di,tM as dn,Am as do,JO as dr,Os as ds,kW as dt,Mb as ea,za as ec,pT as ei,_M as en,Ch as eo,fk as er,ol as es,AG as et,nq as f,gy as fa,Ew as fi,eM as fn,Ym as fo,LO as fr,Es as fs,OW as ft,zK as g,tv as ga,xw as gi,rM as gn,lm as go,ok as gr,ds as gs,CW as gt,UK as h,Y_ as ha,yw as hi,oM as hn,sm as ho,XO as hr,ps as hs,wW as ht,uq as i,Tb as ia,mT as ii,CM as in,eh as io,KO as ir,Fs as is,GW as it,fK as j,l_ as ja,gC as ji,Mj as jn,Vf as jo,cD as jr,ko as js,nP as jt,lK as k,i_ as ka,CC as ki,Pj as kn,Uf as ko,xD as kr,Fo as ks,aP as kt,aq as l,kv as la,gT as li,bM as ln,Pm as lo,$O as lr,Ns as ls,jW as lt,XK as m,nv as ma,kw as mi,aM as mn,om as mo,YO as mr,_s as ms,EW as mt,Oq as n,Pb as na,Ka as nc,vT as ni,fM as nn,mh as no,GO as nr,Bs as ns,DG as nt,fq as o,Ay as oa,dT as oi,EM as on,Hm as oo,HO as or,Ls as os,VW as ot,tq as p,_y as pa,Ow as pi,DM as pn,Jm as po,RO as pr,Ts as ps,DW as pt,LG as q,rg as qa,MS as qi,qk as qn,wu as qo,GT as qr,ro as qs,FM as qt,kq as r,Eb as ra,fT as ri,SM as rn,th as ro,ck as rr,zs as rs,TG as rt,lq as s,hv as sa,uT as si,wM as sn,jm as so,WO as sr,Ms as ss,IW as st,Eq as t,Nb as ta,Ga as tc,lT as ti,nM as tn,gh as to,IO as tr,Vs as ts,MG as tt,oq as u,Ov as ua,Aw as ui,xM as un,qm as uo,qO as ur,js as us,AW as ut,yK as v,w_ as va,Cw as vi,dM as vn,im as vo,NO as vr,ss as vs,eI as vt,AK as w,v_ as wa,bw as wi,Qj as wn,Zf as wo,RD as wr,No as ws,BP as wt,wK as x,S_ as xa,mw as xi,iM as xn,sp as xo,lO as xr,ts as xs,jF as xt,vK as y,C_ as ya,ww as yi,lM as yn,um as yo,xO as yr,os as ys,PF as yt,$G as z,Ug as za,sC as zi,jA as zn,Sd as zo,iE as zr,go as zs,xN as zt};
|
|
1533
|
+
//# sourceMappingURL=WorkerPoolContext-Dx0gHk2i.js.map
|