moi-computer 0.14.0 → 0.14.1
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/package.json +1 -1
- package/runtime/build-worker-entry.js +1 -1
- package/runtime/chunk-1drt3wyp.js +127 -0
- package/runtime/{chunk-00rk365r.js → chunk-1ttazyr4.js} +13 -13
- package/runtime/{chunk-w1fx9tsc.js → chunk-3xv43vzy.js} +2 -2
- package/runtime/chunk-8ktr8n5m.js +2 -0
- package/runtime/{chunk-kjp60rqs.js → chunk-bf4je23j.js} +2 -2
- package/runtime/{chunk-ewc55jga.js → chunk-f5vvtga3.js} +40 -40
- package/runtime/{chunk-4wj1jzhr.js → chunk-jcjcz9ae.js} +2 -2
- package/runtime/{chunk-k049dtaq.js → chunk-jrkbyrmq.js} +1 -1
- package/runtime/{chunk-r5s8rm8n.js → chunk-m4zx92xc.js} +2 -2
- package/runtime/{chunk-ggphq7nk.js → chunk-n5c20498.js} +4 -4
- package/runtime/{chunk-sdyqhxe1.js → chunk-p24qxcr3.js} +5 -5
- package/runtime/chunk-pdzpsbmy.js +3 -0
- package/runtime/{chunk-h2bwhk81.js → chunk-q7xvhh2t.js} +1 -1
- package/runtime/{chunk-j0nd7kw0.js → chunk-qghmmzct.js} +12 -12
- package/runtime/{chunk-8fvgvm56.js → chunk-sxs483zn.js} +1 -1
- package/runtime/chunk-tbwma23z.js +2 -0
- package/runtime/{chunk-zwvtkb81.js → chunk-vtxbnqhj.js} +4 -4
- package/runtime/{chunk-5egvk1rz.js → chunk-wbzwwpct.js} +1 -1
- package/runtime/{chunk-wvarpvem.js → chunk-wgjqjgj9.js} +17 -17
- package/runtime/{chunk-hjzfk1cr.js → chunk-yd4jjshe.js} +1 -1
- package/runtime/{chunk-gbkjshyt.js → chunk-yr67rvnq.js} +1 -1
- package/runtime/cli.js +46 -46
- package/runtime/functions-worker.js +1 -1
- package/runtime/gateway-client.js +1 -1
- package/runtime/chunk-c3qyet60.js +0 -128
- package/runtime/chunk-jb63ns1z.js +0 -2
- package/runtime/chunk-w6ksnv8y.js +0 -2
- package/runtime/chunk-zm7k0v1c.js +0 -3
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{w,W,ue,qi,je,K,re,We,xn,Q,vr,Sr,Tr,Ji,Xi,Yi,Zi,O,Ft,ze,Qi,es,In,Ve,Cn,d,f,pe,dt,Bt,ft,jt,wn,xr,Dn,Nn,Ar,On,kn,Rn,Ln,Mn,X,ns,Ir,Cr,Ut,zt,is,wr,Ze,Fn,ss,Bn,as,os,ls,cs,Dr,l,us,ps,Le,Vt,Nr,Kt,ds,jn,h,ne,Ae,S,fs,Or,ms,mt,Wn,Pe,kr,Rr,de,G,Un,L,A,Y,Lr,Gt,zn,Vn,Kn,Mr,Fr,Gn,hs,ys,Br,gs,jr,Wr,Ur,zr,ht,yt,Vr,$t,Kr,_s,be,Gr,fe,$n,qt,qn,Hn,ee,qr,xs,As,Yn,Ge,Ps,Zn,Hr,U,_t,Ht,Jt,Qe,Is,Jr,Qn,Cs,ws,Xt,Ds,B,ve,Ie,y,ie,Yt,Yr,z,q,ri,D,ni,Me,ii}from"./chunk-c3qyet60.js";import{x,p,Ce,Ms,C,Se,j,v,he}from"./chunk-kjp60rqs.js";import"./chunk-zwvtkb81.js";import{Ri,pr,ye,J,wt,Dt}from"./chunk-r5s8rm8n.js";import{it,gi,st,_i,St,ir,Tt,pn,at,sr,bi,Et,xt,Ai,Ii,Ci,wi,Di,Ni,Oi,Pt,le,Ee,xe,ce,Xe}from"./chunk-wvarpvem.js";import{ae,nr,ln}from"./chunk-5egvk1rz.js";import{Li,Mi,Fi}from"./chunk-j0nd7kw0.js";import{Nt}from"./chunk-k049dtaq.js";import{Ui,Ki,br,Gi}from"./chunk-q06m17nb.js";import{Fs,r,en,k,u,s,Rs,b,F,nn}from"./chunk-ggphq7nk.js";import{g,e}from"./chunk-7c0zbz74.js";var Hm=e(function(Bc,Fo){var WA=200,Td="__lodash_hash_undefined__",Yc=1,vm=2,Em=9007199254740991,Wc="[object Arguments]",bd="[object Array]",HA="[object AsyncFunction]",Am="[object Boolean]",xm="[object Date]",_m="[object Error]",Im="[object Function]",VA="[object GeneratorFunction]",Hc="[object Map]",Tm="[object Number]",zA="[object Null]",Uo="[object Object]",um="[object Promise]",GA="[object Proxy]",Rm="[object RegExp]",Vc="[object Set]",Pm="[object String]",KA="[object Symbol]",JA="[object Undefined]",vd="[object WeakMap]",Cm="[object ArrayBuffer]",zc="[object DataView]",YA="[object Float32Array]",XA="[object Float64Array]",ZA="[object Int8Array]",QA="[object Int16Array]",ex="[object Int32Array]",tx="[object Uint8Array]",rx="[object Uint8ClampedArray]",nx="[object Uint16Array]",sx="[object Uint32Array]",ix=/[\\^$.*+?()[\]{}|]/g,ox=/^\[object .+?Constructor\]$/,ax=/^(?:0|[1-9]\d*)$/,ot={};ot[YA]=ot[XA]=ot[ZA]=ot[QA]=ot[ex]=ot[tx]=ot[rx]=ot[nx]=ot[sx]=!0;ot[Wc]=ot[bd]=ot[Cm]=ot[Am]=ot[zc]=ot[xm]=ot[_m]=ot[Im]=ot[Hc]=ot[Tm]=ot[Uo]=ot[Rm]=ot[Vc]=ot[Pm]=ot[vd]=!1;var Om=typeof global=="object"&&global&&global.Object===Object&&global,cx=typeof self=="object"&&self&&self.Object===Object&&self,Js=Om||cx||Function("return this")(),km=typeof Bc=="object"&&Bc&&!Bc.nodeType&&Bc,dm=km&&typeof Fo=="object"&&Fo&&!Fo.nodeType&&Fo,Mm=dm&&dm.exports===km,yd=Mm&&Om.process,fm=function(){try{return yd&&yd.binding&&yd.binding("util")}catch(t){}}(),pm=fm&&fm.isTypedArray;function lx(t,n){var i=-1,o=t==null?0:t.length,a=0,c=[];while(++i<o){var m=t[i];if(n(m,i,t))c[a++]=m}return c}function ux(t,n){var i=-1,o=n.length,a=t.length;while(++i<o)t[a+i]=n[i];return t}function dx(t,n){var i=-1,o=t==null?0:t.length;while(++i<o)if(n(t[i],i,t))return!0;return!1}function fx(t,n){var i=-1,o=Array(t);while(++i<t)o[i]=n(i);return o}function px(t){return function(n){return t(n)}}function hx(t,n){return t.has(n)}function mx(t,n){return t==null?void 0:t[n]}function gx(t){var n=-1,i=Array(t.size);return t.forEach(function(o,a){i[++n]=[a,o]}),i}function yx(t,n){return function(i){return t(n(i))}}function wx(t){var n=-1,i=Array(t.size);return t.forEach(function(o){i[++n]=o}),i}var Sx=Array.prototype,bx=Function.prototype,Xc=Object.prototype,wd=Js["__core-js_shared__"],Nm=bx.toString,Ns=Xc.hasOwnProperty,hm=function(){var t=/[^.]+$/.exec(wd&&wd.keys&&wd.keys.IE_PROTO||"");return t?"Symbol(src)_1."+t:""}(),$m=Xc.toString,vx=RegExp("^"+Nm.call(Ns).replace(ix,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),mm=Mm?Js.Buffer:void 0,{Symbol:Gc,Uint8Array:gm}=Js,Dm=Xc.propertyIsEnumerable,Ex=Sx.splice,lo=Gc?Gc.toStringTag:void 0,ym=Object.getOwnPropertySymbols,Ax=mm?mm.isBuffer:void 0,xx=yx(Object.keys,Object),Ed=qo(Js,"DataView"),Ca=qo(Js,"Map"),Ad=qo(Js,"Promise"),xd=qo(Js,"Set"),_d=qo(Js,"WeakMap"),Oa=qo(Object,"create"),_x=po(Ed),Ix=po(Ca),Tx=po(Ad),Rx=po(xd),Px=po(_d),wm=Gc?Gc.prototype:void 0,Sd=wm?wm.valueOf:void 0;function uo(t){var n=-1,i=t==null?0:t.length;this.clear();while(++n<i){var o=t[n];this.set(o[0],o[1])}}function Cx(){this.__data__=Oa?Oa(null):{},this.size=0}function Ox(t){var n=this.has(t)&&delete this.__data__[t];return this.size-=n?1:0,n}function kx(t){var n=this.__data__;if(Oa){var i=n[t];return i===Td?void 0:i}return Ns.call(n,t)?n[t]:void 0}function Mx(t){var n=this.__data__;return Oa?n[t]!==void 0:Ns.call(n,t)}function Nx(t,n){var i=this.__data__;return this.size+=this.has(t)?0:1,i[t]=Oa&&n===void 0?Td:n,this}uo.prototype.clear=Cx;uo.prototype.delete=Ox;uo.prototype.get=kx;uo.prototype.has=Mx;uo.prototype.set=Nx;function Ys(t){var n=-1,i=t==null?0:t.length;this.clear();while(++n<i){var o=t[n];this.set(o[0],o[1])}}function $x(){this.__data__=[],this.size=0}function Dx(t){var n=this.__data__,i=Zc(n,t);if(i<0)return!1;var o=n.length-1;if(i==o)n.pop();else Ex.call(n,i,1);return--this.size,!0}function Lx(t){var n=this.__data__,i=Zc(n,t);return i<0?void 0:n[i][1]}function jx(t){return Zc(this.__data__,t)>-1}function Ux(t,n){var i=this.__data__,o=Zc(i,t);if(o<0)++this.size,i.push([t,n]);else i[o][1]=n;return this}Ys.prototype.clear=$x;Ys.prototype.delete=Dx;Ys.prototype.get=Lx;Ys.prototype.has=jx;Ys.prototype.set=Ux;function fo(t){var n=-1,i=t==null?0:t.length;this.clear();while(++n<i){var o=t[n];this.set(o[0],o[1])}}function Fx(){this.size=0,this.__data__={hash:new uo,map:new(Ca||Ys),string:new uo}}function qx(t){var n=Qc(this,t).delete(t);return this.size-=n?1:0,n}function Bx(t){return Qc(this,t).get(t)}function Wx(t){return Qc(this,t).has(t)}function Hx(t,n){var i=Qc(this,t),o=i.size;return i.set(t,n),this.size+=i.size==o?0:1,this}fo.prototype.clear=Fx;fo.prototype.delete=qx;fo.prototype.get=Bx;fo.prototype.has=Wx;fo.prototype.set=Hx;function Kc(t){var n=-1,i=t==null?0:t.length;this.__data__=new fo;while(++n<i)this.add(t[n])}function Vx(t){return this.__data__.set(t,Td),this}function zx(t){return this.__data__.has(t)}Kc.prototype.add=Kc.prototype.push=Vx;Kc.prototype.has=zx;function vi(t){var n=this.__data__=new Ys(t);this.size=n.size}function Gx(){this.__data__=new Ys,this.size=0}function Kx(t){var n=this.__data__,i=n.delete(t);return this.size=n.size,i}function Jx(t){return this.__data__.get(t)}function Yx(t){return this.__data__.has(t)}function Xx(t,n){var i=this.__data__;if(i instanceof Ys){var o=i.__data__;if(!Ca||o.length<WA-1)return o.push([t,n]),this.size=++i.size,this;i=this.__data__=new fo(o)}return i.set(t,n),this.size=i.size,this}vi.prototype.clear=Gx;vi.prototype.delete=Kx;vi.prototype.get=Jx;vi.prototype.has=Yx;vi.prototype.set=Xx;function Zx(t,n){var i=Jc(t),o=!i&&p_(t),a=!i&&!o&&Id(t),c=!i&&!o&&!a&&Wm(t),m=i||o||a||c,E=m?fx(t.length,String):[],_=E.length;for(var I in t)if((n||Ns.call(t,I))&&!(m&&(I=="length"||a&&(I=="offset"||I=="parent")||c&&(I=="buffer"||I=="byteLength"||I=="byteOffset")||c_(I,_))))E.push(I);return E}function Zc(t,n){var i=t.length;while(i--)if(Um(t[i][0],n))return i;return-1}function Qx(t,n,i){var o=n(t);return Jc(t)?o:ux(o,i(t))}function Ma(t){if(t==null)return t===void 0?JA:zA;return lo&&lo in Object(t)?o_(t):f_(t)}function Sm(t){return ka(t)&&Ma(t)==Wc}function Lm(t,n,i,o,a){if(t===n)return!0;if(t==null||n==null||!ka(t)&&!ka(n))return t!==t&&n!==n;return e_(t,n,i,o,Lm,a)}function e_(t,n,i,o,a,c){var m=Jc(t),E=Jc(n),_=m?bd:Si(t),I=E?bd:Si(n);_=_==Wc?Uo:_,I=I==Wc?Uo:I;var T=_==Uo,R=I==Uo,P=_==I;if(P&&Id(t)){if(!Id(n))return!1;m=!0,T=!1}if(P&&!T)return c||(c=new vi),m||Wm(t)?jm(t,n,i,o,a,c):s_(t,n,_,i,o,a,c);if(!(i&Yc)){var M=T&&Ns.call(t,"__wrapped__"),N=R&&Ns.call(n,"__wrapped__");if(M||N){var H=M?t.value():t,Z=N?n.value():n;return c||(c=new vi),a(H,Z,i,o,c)}}if(!P)return!1;return c||(c=new vi),i_(t,n,i,o,a,c)}function t_(t){if(!Bm(t)||u_(t))return!1;var n=Fm(t)?vx:ox;return n.test(po(t))}function r_(t){return ka(t)&&qm(t.length)&&!!ot[Ma(t)]}function n_(t){if(!d_(t))return xx(t);var n=[];for(var i in Object(t))if(Ns.call(t,i)&&i!="constructor")n.push(i);return n}function jm(t,n,i,o,a,c){var m=i&Yc,E=t.length,_=n.length;if(E!=_&&!(m&&_>E))return!1;var I=c.get(t);if(I&&c.get(n))return I==n;var T=-1,R=!0,P=i&vm?new Kc:void 0;c.set(t,n),c.set(n,t);while(++T<E){var M=t[T],N=n[T];if(o)var H=m?o(N,M,T,n,t,c):o(M,N,T,t,n,c);if(H!==void 0){if(H)continue;R=!1;break}if(P){if(!dx(n,function(Z,V){if(!hx(P,V)&&(M===Z||a(M,Z,i,o,c)))return P.push(V)})){R=!1;break}}else if(!(M===N||a(M,N,i,o,c))){R=!1;break}}return c.delete(t),c.delete(n),R}function s_(t,n,i,o,a,c,m){switch(i){case zc:if(t.byteLength!=n.byteLength||t.byteOffset!=n.byteOffset)return!1;t=t.buffer,n=n.buffer;case Cm:if(t.byteLength!=n.byteLength||!c(new gm(t),new gm(n)))return!1;return!0;case Am:case xm:case Tm:return Um(+t,+n);case _m:return t.name==n.name&&t.message==n.message;case Rm:case Pm:return t==n+"";case Hc:var E=gx;case Vc:var _=o&Yc;if(E||(E=wx),t.size!=n.size&&!_)return!1;var I=m.get(t);if(I)return I==n;o|=vm,m.set(t,n);var T=jm(E(t),E(n),o,a,c,m);return m.delete(t),T;case KA:if(Sd)return Sd.call(t)==Sd.call(n)}return!1}function i_(t,n,i,o,a,c){var m=i&Yc,E=bm(t),_=E.length,I=bm(n),T=I.length;if(_!=T&&!m)return!1;var R=_;while(R--){var P=E[R];if(!(m?P in n:Ns.call(n,P)))return!1}var M=c.get(t);if(M&&c.get(n))return M==n;var N=!0;c.set(t,n),c.set(n,t);var H=m;while(++R<_){P=E[R];var Z=t[P],V=n[P];if(o)var me=m?o(V,Z,P,n,t,c):o(Z,V,P,t,n,c);if(!(me===void 0?Z===V||a(Z,V,i,o,c):me)){N=!1;break}H||(H=P=="constructor")}if(N&&!H){var te=t.constructor,we=n.constructor;if(te!=we&&(("constructor"in t)&&("constructor"in n))&&!(typeof te=="function"&&te instanceof te&&typeof we=="function"&&we instanceof we))N=!1}return c.delete(t),c.delete(n),N}function bm(t){return Qx(t,g_,a_)}function Qc(t,n){var i=t.__data__;return l_(n)?i[typeof n=="string"?"string":"hash"]:i.map}function qo(t,n){var i=mx(t,n);return t_(i)?i:void 0}function o_(t){var n=Ns.call(t,lo),i=t[lo];try{t[lo]=void 0;var o=!0}catch(c){}var a=$m.call(t);if(o)if(n)t[lo]=i;else delete t[lo];return a}var a_=!ym?y_:function(t){if(t==null)return[];return t=Object(t),lx(ym(t),function(n){return Dm.call(t,n)})},Si=Ma;if(Ed&&Si(new Ed(new ArrayBuffer(1)))!=zc||Ca&&Si(new Ca)!=Hc||Ad&&Si(Ad.resolve())!=um||xd&&Si(new xd)!=Vc||_d&&Si(new _d)!=vd)Si=function(t){var n=Ma(t),i=n==Uo?t.constructor:void 0,o=i?po(i):"";if(o)switch(o){case _x:return zc;case Ix:return Hc;case Tx:return um;case Rx:return Vc;case Px:return vd}return n};function c_(t,n){return n=n==null?Em:n,!!n&&(typeof t=="number"||ax.test(t))&&(t>-1&&t%1==0&&t<n)}function l_(t){var n=typeof t;return n=="string"||n=="number"||n=="symbol"||n=="boolean"?t!=="__proto__":t===null}function u_(t){return!!hm&&hm in t}function d_(t){var n=t&&t.constructor,i=typeof n=="function"&&n.prototype||Xc;return t===i}function f_(t){return $m.call(t)}function po(t){if(t!=null){try{return Nm.call(t)}catch(n){}try{return t+""}catch(n){}}return""}function Um(t,n){return t===n||t!==t&&n!==n}var p_=Sm(function(){return arguments}())?Sm:function(t){return ka(t)&&Ns.call(t,"callee")&&!Dm.call(t,"callee")},Jc=Array.isArray;function h_(t){return t!=null&&qm(t.length)&&!Fm(t)}var Id=Ax||w_;function m_(t,n){return Lm(t,n)}function Fm(t){if(!Bm(t))return!1;var n=Ma(t);return n==Im||n==VA||n==HA||n==GA}function qm(t){return typeof t=="number"&&t>-1&&t%1==0&&t<=Em}function Bm(t){var n=typeof t;return t!=null&&(n=="object"||n=="function")}function ka(t){return t!=null&&typeof t=="object"}var Wm=pm?px(pm):r_;function g_(t){return h_(t)?Zx(t):n_(t)}function y_(){return[]}function w_(){return!1}Fo.exports=m_});var qd=e(function(el,Wo){var S_=200,jd="__lodash_hash_undefined__",tg=1,ol=2,rg=9007199254740991,tl="[object Arguments]",Cd="[object Array]",ng="[object Boolean]",sg="[object Date]",ig="[object Error]",og="[object Function]",b_="[object GeneratorFunction]",rl="[object Map]",ag="[object Number]",Bo="[object Object]",Vm="[object Promise]",cg="[object RegExp]",nl="[object Set]",lg="[object String]",v_="[object Symbol]",Od="[object WeakMap]",ug="[object ArrayBuffer]",sl="[object DataView]",E_="[object Float32Array]",A_="[object Float64Array]",x_="[object Int8Array]",__="[object Int16Array]",I_="[object Int32Array]",T_="[object Uint8Array]",R_="[object Uint8ClampedArray]",P_="[object Uint16Array]",C_="[object Uint32Array]",O_=/[\\^$.*+?()[\]{}|]/g,k_=/^\[object .+?Constructor\]$/,M_=/^(?:0|[1-9]\d*)$/,ct={};ct[E_]=ct[A_]=ct[x_]=ct[__]=ct[I_]=ct[T_]=ct[R_]=ct[P_]=ct[C_]=!0;ct[tl]=ct[Cd]=ct[ug]=ct[ng]=ct[sl]=ct[sg]=ct[ig]=ct[og]=ct[rl]=ct[ag]=ct[Bo]=ct[cg]=ct[nl]=ct[lg]=ct[Od]=!1;var dg=typeof global=="object"&&global&&global.Object===Object&&global,N_=typeof self=="object"&&self&&self.Object===Object&&self,Ti=dg||N_||Function("return this")(),fg=typeof el=="object"&&el&&!el.nodeType&&el,zm=fg&&typeof Wo=="object"&&Wo&&!Wo.nodeType&&Wo,$_=zm&&zm.exports===fg,Gm=$_&&dg.process,Km=function(){try{return Gm&&Gm.binding("util")}catch(t){}}(),Jm=Km&&Km.isTypedArray;function D_(t,n){var i=-1,o=t?t.length:0;while(++i<o)if(n(t[i],i,t))return!0;return!1}function L_(t,n){var i=-1,o=Array(t);while(++i<t)o[i]=n(i);return o}function j_(t){return function(n){return t(n)}}function U_(t,n){return t==null?void 0:t[n]}function kd(t){var n=!1;if(t!=null&&typeof t.toString!="function")try{n=!!(t+"")}catch(i){}return n}function F_(t){var n=-1,i=Array(t.size);return t.forEach(function(o,a){i[++n]=[a,o]}),i}function q_(t,n){return function(i){return t(n(i))}}function B_(t){var n=-1,i=Array(t.size);return t.forEach(function(o){i[++n]=o}),i}var W_=Array.prototype,H_=Function.prototype,al=Object.prototype,Rd=Ti["__core-js_shared__"],Ym=function(){var t=/[^.]+$/.exec(Rd&&Rd.keys&&Rd.keys.IE_PROTO||"");return t?"Symbol(src)_1."+t:""}(),pg=H_.toString,{hasOwnProperty:Xs,toString:Da}=al,V_=RegExp("^"+pg.call(Xs).replace(O_,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),{Symbol:Xm,Uint8Array:Zm}=Ti,z_=al.propertyIsEnumerable,G_=W_.splice,K_=q_(Object.keys,Object),Md=Ho(Ti,"DataView"),Na=Ho(Ti,"Map"),Nd=Ho(Ti,"Promise"),$d=Ho(Ti,"Set"),Dd=Ho(Ti,"WeakMap"),$a=Ho(Object,"create"),J_=go(Md),Y_=go(Na),X_=go(Nd),Z_=go($d),Q_=go(Dd),Qm=Xm?Xm.prototype:void 0,Pd=Qm?Qm.valueOf:void 0;function ho(t){var n=-1,i=t?t.length:0;this.clear();while(++n<i){var o=t[n];this.set(o[0],o[1])}}function eI(){this.__data__=$a?$a(null):{}}function tI(t){return this.has(t)&&delete this.__data__[t]}function rI(t){var n=this.__data__;if($a){var i=n[t];return i===jd?void 0:i}return Xs.call(n,t)?n[t]:void 0}function nI(t){var n=this.__data__;return $a?n[t]!==void 0:Xs.call(n,t)}function sI(t,n){var i=this.__data__;return i[t]=$a&&n===void 0?jd:n,this}ho.prototype.clear=eI;ho.prototype.delete=tI;ho.prototype.get=rI;ho.prototype.has=nI;ho.prototype.set=sI;function Zs(t){var n=-1,i=t?t.length:0;this.clear();while(++n<i){var o=t[n];this.set(o[0],o[1])}}function iI(){this.__data__=[]}function oI(t){var n=this.__data__,i=cl(n,t);if(i<0)return!1;var o=n.length-1;if(i==o)n.pop();else G_.call(n,i,1);return!0}function aI(t){var n=this.__data__,i=cl(n,t);return i<0?void 0:n[i][1]}function cI(t){return cl(this.__data__,t)>-1}function lI(t,n){var i=this.__data__,o=cl(i,t);if(o<0)i.push([t,n]);else i[o][1]=n;return this}Zs.prototype.clear=iI;Zs.prototype.delete=oI;Zs.prototype.get=aI;Zs.prototype.has=cI;Zs.prototype.set=lI;function mo(t){var n=-1,i=t?t.length:0;this.clear();while(++n<i){var o=t[n];this.set(o[0],o[1])}}function uI(){this.__data__={hash:new ho,map:new(Na||Zs),string:new ho}}function dI(t){return ll(this,t).delete(t)}function fI(t){return ll(this,t).get(t)}function pI(t){return ll(this,t).has(t)}function hI(t,n){return ll(this,t).set(t,n),this}mo.prototype.clear=uI;mo.prototype.delete=dI;mo.prototype.get=fI;mo.prototype.has=pI;mo.prototype.set=hI;function il(t){var n=-1,i=t?t.length:0;this.__data__=new mo;while(++n<i)this.add(t[n])}function mI(t){return this.__data__.set(t,jd),this}function gI(t){return this.__data__.has(t)}il.prototype.add=il.prototype.push=mI;il.prototype.has=gI;function xi(t){this.__data__=new Zs(t)}function yI(){this.__data__=new Zs}function wI(t){return this.__data__.delete(t)}function SI(t){return this.__data__.get(t)}function bI(t){return this.__data__.has(t)}function vI(t,n){var i=this.__data__;if(i instanceof Zs){var o=i.__data__;if(!Na||o.length<S_-1)return o.push([t,n]),this;i=this.__data__=new mo(o)}return i.set(t,n),this}xi.prototype.clear=yI;xi.prototype.delete=wI;xi.prototype.get=SI;xi.prototype.has=bI;xi.prototype.set=vI;function EI(t,n){var i=Ld(t)||NI(t)?L_(t.length,String):[],o=i.length,a=!!o;for(var c in t)if((n||Xs.call(t,c))&&!(a&&(c=="length"||CI(c,o))))i.push(c);return i}function cl(t,n){var i=t.length;while(i--)if(gg(t[i][0],n))return i;return-1}function AI(t){return Da.call(t)}function hg(t,n,i,o,a){if(t===n)return!0;if(t==null||n==null||!Ud(t)&&!Fd(n))return t!==t&&n!==n;return xI(t,n,hg,i,o,a)}function xI(t,n,i,o,a,c){var m=Ld(t),E=Ld(n),_=Cd,I=Cd;if(!m)_=Ei(t),_=_==tl?Bo:_;if(!E)I=Ei(n),I=I==tl?Bo:I;var T=_==Bo&&!kd(t),R=I==Bo&&!kd(n),P=_==I;if(P&&!T)return c||(c=new xi),m||LI(t)?mg(t,n,i,o,a,c):RI(t,n,_,i,o,a,c);if(!(a&ol)){var M=T&&Xs.call(t,"__wrapped__"),N=R&&Xs.call(n,"__wrapped__");if(M||N){var H=M?t.value():t,Z=N?n.value():n;return c||(c=new xi),i(H,Z,o,a,c)}}if(!P)return!1;return c||(c=new xi),PI(t,n,i,o,a,c)}function _I(t){if(!Ud(t)||kI(t))return!1;var n=wg(t)||kd(t)?V_:k_;return n.test(go(t))}function II(t){return Fd(t)&&Sg(t.length)&&!!ct[Da.call(t)]}function TI(t){if(!MI(t))return K_(t);var n=[];for(var i in Object(t))if(Xs.call(t,i)&&i!="constructor")n.push(i);return n}function mg(t,n,i,o,a,c){var m=a&ol,E=t.length,_=n.length;if(E!=_&&!(m&&_>E))return!1;var I=c.get(t);if(I&&c.get(n))return I==n;var T=-1,R=!0,P=a&tg?new il:void 0;c.set(t,n),c.set(n,t);while(++T<E){var M=t[T],N=n[T];if(o)var H=m?o(N,M,T,n,t,c):o(M,N,T,t,n,c);if(H!==void 0){if(H)continue;R=!1;break}if(P){if(!D_(n,function(Z,V){if(!P.has(V)&&(M===Z||i(M,Z,o,a,c)))return P.add(V)})){R=!1;break}}else if(!(M===N||i(M,N,o,a,c))){R=!1;break}}return c.delete(t),c.delete(n),R}function RI(t,n,i,o,a,c,m){switch(i){case sl:if(t.byteLength!=n.byteLength||t.byteOffset!=n.byteOffset)return!1;t=t.buffer,n=n.buffer;case ug:if(t.byteLength!=n.byteLength||!o(new Zm(t),new Zm(n)))return!1;return!0;case ng:case sg:case ag:return gg(+t,+n);case ig:return t.name==n.name&&t.message==n.message;case cg:case lg:return t==n+"";case rl:var E=F_;case nl:var _=c&ol;if(E||(E=B_),t.size!=n.size&&!_)return!1;var I=m.get(t);if(I)return I==n;c|=tg,m.set(t,n);var T=mg(E(t),E(n),o,a,c,m);return m.delete(t),T;case v_:if(Pd)return Pd.call(t)==Pd.call(n)}return!1}function PI(t,n,i,o,a,c){var m=a&ol,E=eg(t),_=E.length,I=eg(n),T=I.length;if(_!=T&&!m)return!1;var R=_;while(R--){var P=E[R];if(!(m?P in n:Xs.call(n,P)))return!1}var M=c.get(t);if(M&&c.get(n))return M==n;var N=!0;c.set(t,n),c.set(n,t);var H=m;while(++R<_){P=E[R];var Z=t[P],V=n[P];if(o)var me=m?o(V,Z,P,n,t,c):o(Z,V,P,t,n,c);if(!(me===void 0?Z===V||i(Z,V,o,a,c):me)){N=!1;break}H||(H=P=="constructor")}if(N&&!H){var te=t.constructor,we=n.constructor;if(te!=we&&(("constructor"in t)&&("constructor"in n))&&!(typeof te=="function"&&te instanceof te&&typeof we=="function"&&we instanceof we))N=!1}return c.delete(t),c.delete(n),N}function ll(t,n){var i=t.__data__;return OI(n)?i[typeof n=="string"?"string":"hash"]:i.map}function Ho(t,n){var i=U_(t,n);return _I(i)?i:void 0}var Ei=AI;if(Md&&Ei(new Md(new ArrayBuffer(1)))!=sl||Na&&Ei(new Na)!=rl||Nd&&Ei(Nd.resolve())!=Vm||$d&&Ei(new $d)!=nl||Dd&&Ei(new Dd)!=Od)Ei=function(t){var n=Da.call(t),i=n==Bo?t.constructor:void 0,o=i?go(i):void 0;if(o)switch(o){case J_:return sl;case Y_:return rl;case X_:return Vm;case Z_:return nl;case Q_:return Od}return n};function CI(t,n){return n=n==null?rg:n,!!n&&(typeof t=="number"||M_.test(t))&&(t>-1&&t%1==0&&t<n)}function OI(t){var n=typeof t;return n=="string"||n=="number"||n=="symbol"||n=="boolean"?t!=="__proto__":t===null}function kI(t){return!!Ym&&Ym in t}function MI(t){var n=t&&t.constructor,i=typeof n=="function"&&n.prototype||al;return t===i}function go(t){if(t!=null){try{return pg.call(t)}catch(n){}try{return t+""}catch(n){}}return""}function gg(t,n){return t===n||t!==t&&n!==n}function NI(t){return $I(t)&&Xs.call(t,"callee")&&(!z_.call(t,"callee")||Da.call(t)==tl)}var Ld=Array.isArray;function yg(t){return t!=null&&Sg(t.length)&&!wg(t)}function $I(t){return Fd(t)&&yg(t)}function DI(t,n,i){i=typeof i=="function"?i:void 0;var o=i?i(t,n):void 0;return o===void 0?hg(t,n,i):!!o}function wg(t){var n=Ud(t)?Da.call(t):"";return n==og||n==b_}function Sg(t){return typeof t=="number"&&t>-1&&t%1==0&&t<=rg}function Ud(t){var n=typeof t;return!!t&&(n=="object"||n=="function")}function Fd(t){return!!t&&typeof t=="object"}var LI=Jm?j_(Jm):II;function eg(t){return yg(t)?EI(t):TI(t)}Wo.exports=DI});var xg=e(function(HD,Ag){var Eg="Expected a function",bg=NaN,jI="[object Symbol]",UI=/^\s+|\s+$/g,FI=/^[-+]0x[0-9a-f]+$/i,qI=/^0b[01]+$/i,BI=/^0o[0-7]+$/i,WI=parseInt,HI=typeof global=="object"&&global&&global.Object===Object&&global,VI=typeof self=="object"&&self&&self.Object===Object&&self,zI=HI||VI||Function("return this")(),GI=Object.prototype,KI=GI.toString,{max:JI,min:YI}=Math,Bd=function(){return zI.Date.now()};function XI(t,n,i){var o,a,c,m,E,_,I=0,T=!1,R=!1,P=!0;if(typeof t!="function")throw TypeError(Eg);if(n=vg(n)||0,ul(i))T=!!i.leading,R="maxWait"in i,c=R?JI(vg(i.maxWait)||0,n):c,P="trailing"in i?!!i.trailing:P;function M($e){var Ue=o,Ct=a;return o=a=void 0,I=$e,m=t.apply(Ct,Ue),m}function N($e){return I=$e,E=setTimeout(V,n),T?M($e):m}function H($e){var Ue=$e-_,Ct=$e-I,Ot=n-Ue;return R?YI(Ot,c-Ct):Ot}function Z($e){var Ue=$e-_,Ct=$e-I;return _===void 0||Ue>=n||Ue<0||R&&Ct>=c}function V(){var $e=Bd();if(Z($e))return me($e);E=setTimeout(V,H($e))}function me($e){if(E=void 0,P&&o)return M($e);return o=a=void 0,m}function te(){if(E!==void 0)clearTimeout(E);I=0,o=_=a=E=void 0}function we(){return E===void 0?m:me(Bd())}function Te(){var $e=Bd(),Ue=Z($e);if(o=arguments,a=this,_=$e,Ue){if(E===void 0)return N(_);if(R)return E=setTimeout(V,n),M(_)}if(E===void 0)E=setTimeout(V,n);return m}return Te.cancel=te,Te.flush=we,Te}function ZI(t,n,i){var o=!0,a=!0;if(typeof t!="function")throw TypeError(Eg);if(ul(i))o="leading"in i?!!i.leading:o,a="trailing"in i?!!i.trailing:a;return XI(t,n,{leading:o,maxWait:n,trailing:a})}function ul(t){var n=typeof t;return!!t&&(n=="object"||n=="function")}function QI(t){return!!t&&typeof t=="object"}function eT(t){return typeof t=="symbol"||QI(t)&&KI.call(t)==jI}function vg(t){if(typeof t=="number")return t;if(eT(t))return bg;if(ul(t)){var n=typeof t.valueOf=="function"?t.valueOf():t;t=ul(n)?n+"":n}if(typeof t!="string")return t===0?t:+t;t=t.replace(UI,"");var i=qI.test(t);return i||BI.test(t)?WI(t.slice(2),i?2:8):FI.test(t)?bg:+t}Ag.exports=ZI});var Og=e(function(VD,Cg){var tT=200,Vd="__lodash_hash_undefined__",rT=1/0,nT="[object Function]",sT="[object GeneratorFunction]",iT=/[\\^$.*+?()[\]{}|]/g,oT=/^\[object .+?Constructor\]$/,aT=typeof global=="object"&&global&&global.Object===Object&&global,cT=typeof self=="object"&&self&&self.Object===Object&&self,zd=aT||cT||Function("return this")();function lT(t,n){var i=t?t.length:0;return!!i&&fT(t,n,0)>-1}function uT(t,n,i){var o=-1,a=t?t.length:0;while(++o<a)if(i(n,t[o]))return!0;return!1}function dT(t,n,i,o){var a=t.length,c=i+(o?1:-1);while(o?c--:++c<a)if(n(t[c],c,t))return c;return-1}function fT(t,n,i){if(n!==n)return dT(t,pT,i);var o=i-1,a=t.length;while(++o<a)if(t[o]===n)return o;return-1}function pT(t){return t!==t}function hT(t,n){return t.has(n)}function mT(t,n){return t==null?void 0:t[n]}function gT(t){var n=!1;if(t!=null&&typeof t.toString!="function")try{n=!!(t+"")}catch(i){}return n}function Ig(t){var n=-1,i=Array(t.size);return t.forEach(function(o){i[++n]=o}),i}var yT=Array.prototype,wT=Function.prototype,Tg=Object.prototype,Wd=zd["__core-js_shared__"],_g=function(){var t=/[^.]+$/.exec(Wd&&Wd.keys&&Wd.keys.IE_PROTO||"");return t?"Symbol(src)_1."+t:""}(),Rg=wT.toString,{hasOwnProperty:Gd,toString:ST}=Tg,bT=RegExp("^"+Rg.call(Gd).replace(iT,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),vT=yT.splice,ET=Kd(zd,"Map"),Hd=Kd(zd,"Set"),La=Kd(Object,"create");function yo(t){var n=-1,i=t?t.length:0;this.clear();while(++n<i){var o=t[n];this.set(o[0],o[1])}}function AT(){this.__data__=La?La(null):{}}function xT(t){return this.has(t)&&delete this.__data__[t]}function _T(t){var n=this.__data__;if(La){var i=n[t];return i===Vd?void 0:i}return Gd.call(n,t)?n[t]:void 0}function IT(t){var n=this.__data__;return La?n[t]!==void 0:Gd.call(n,t)}function TT(t,n){var i=this.__data__;return i[t]=La&&n===void 0?Vd:n,this}yo.prototype.clear=AT;yo.prototype.delete=xT;yo.prototype.get=_T;yo.prototype.has=IT;yo.prototype.set=TT;function Vo(t){var n=-1,i=t?t.length:0;this.clear();while(++n<i){var o=t[n];this.set(o[0],o[1])}}function RT(){this.__data__=[]}function PT(t){var n=this.__data__,i=fl(n,t);if(i<0)return!1;var o=n.length-1;if(i==o)n.pop();else vT.call(n,i,1);return!0}function CT(t){var n=this.__data__,i=fl(n,t);return i<0?void 0:n[i][1]}function OT(t){return fl(this.__data__,t)>-1}function kT(t,n){var i=this.__data__,o=fl(i,t);if(o<0)i.push([t,n]);else i[o][1]=n;return this}Vo.prototype.clear=RT;Vo.prototype.delete=PT;Vo.prototype.get=CT;Vo.prototype.has=OT;Vo.prototype.set=kT;function zo(t){var n=-1,i=t?t.length:0;this.clear();while(++n<i){var o=t[n];this.set(o[0],o[1])}}function MT(){this.__data__={hash:new yo,map:new(ET||Vo),string:new yo}}function NT(t){return pl(this,t).delete(t)}function $T(t){return pl(this,t).get(t)}function DT(t){return pl(this,t).has(t)}function LT(t,n){return pl(this,t).set(t,n),this}zo.prototype.clear=MT;zo.prototype.delete=NT;zo.prototype.get=$T;zo.prototype.has=DT;zo.prototype.set=LT;function dl(t){var n=-1,i=t?t.length:0;this.__data__=new zo;while(++n<i)this.add(t[n])}function jT(t){return this.__data__.set(t,Vd),this}function UT(t){return this.__data__.has(t)}dl.prototype.add=dl.prototype.push=jT;dl.prototype.has=UT;function fl(t,n){var i=t.length;while(i--)if(GT(t[i][0],n))return i;return-1}function FT(t){if(!Pg(t)||HT(t))return!1;var n=KT(t)||gT(t)?bT:oT;return n.test(VT(t))}function qT(t,n,i){var o=-1,a=lT,c=t.length,m=!0,E=[],_=E;if(i)m=!1,a=uT;else if(c>=tT){var I=n?null:BT(t);if(I)return Ig(I);m=!1,a=hT,_=new dl}else _=n?[]:E;e:while(++o<c){var T=t[o],R=n?n(T):T;if(T=i||T!==0?T:0,m&&R===R){var P=_.length;while(P--)if(_[P]===R)continue e;if(n)_.push(R);E.push(T)}else if(!a(_,R,i)){if(_!==E)_.push(R);E.push(T)}}return E}var BT=!(Hd&&1/Ig(new Hd([,-0]))[1]==rT)?JT:function(t){return new Hd(t)};function pl(t,n){var i=t.__data__;return WT(n)?i[typeof n=="string"?"string":"hash"]:i.map}function Kd(t,n){var i=mT(t,n);return FT(i)?i:void 0}function WT(t){var n=typeof t;return n=="string"||n=="number"||n=="symbol"||n=="boolean"?t!=="__proto__":t===null}function HT(t){return!!_g&&_g in t}function VT(t){if(t!=null){try{return Rg.call(t)}catch(n){}try{return t+""}catch(n){}}return""}function zT(t){return t&&t.length?qT(t):[]}function GT(t,n){return t===n||t!==t&&n!==n}function KT(t){var n=Pg(t)?ST.call(t):"";return n==nT||n==sT}function Pg(t){var n=typeof t;return!!t&&(n=="object"||n=="function")}function JT(){}Cg.exports=zT});var Zp=e(function(NS){Object.defineProperty(NS,"__esModule",{value:!0});NS.dynamicAnchor=void 0;var ga=d(),SP=pe(),uu=jt(),kS=xr(),bP={keyword:"$dynamicAnchor",schemaType:"string",code:(t)=>MS(t,t.schema)};function MS(t,n){let{gen:i,it:o}=t;o.schemaEnv.root.dynamicAnchors[n]=!0;let a=ga._`${SP.default.dynamicAnchors}${ga.getProperty(n)}`,c=o.errSchemaPath==="#"?o.validateName:vP(t);i.if(ga._`!${a}`,()=>i.assign(a,c))}NS.dynamicAnchor=MS;function vP(t){let{schemaEnv:n,schema:i,self:o}=t.it,{root:a,baseId:c,localRefs:m,meta:E}=n.root,{schemaId:_}=o.opts,I=new uu.SchemaEnv({schema:i,schemaId:_,root:a,baseId:c,localRefs:m,meta:E});return uu.compileSchema.call(o,I),kS.getValidate(t,I)}NS.default=bP});var Qp=e(function(LS){Object.defineProperty(LS,"__esModule",{value:!0});LS.dynamicRef=void 0;var du=d(),AP=pe(),fu=xr(),xP={keyword:"$dynamicRef",schemaType:"string",code:(t)=>DS(t,t.schema)};function DS(t,n){let{gen:i,keyword:o,it:a}=t;if(n[0]!=="#")throw Error(`"${o}" only supports hash fragment reference`);let c=n.slice(1);if(a.allErrors)m();else{let _=i.let("valid",!1);m(_),t.ok(_)}function m(_){if(a.schemaEnv.root.dynamicAnchors[c]){let I=i.let("_v",du._`${AP.default.dynamicAnchors}${du.getProperty(c)}`);i.if(I,E(I,_),E(a.validateName,_))}else E(a.validateName,_)()}function E(_,I){return I?()=>i.block(()=>{fu.callRef(t,_),i.let(I,!0)}):()=>fu.callRef(t,_)}}LS.dynamicRef=DS;LS.default=xP});var BS=e(function(qS){Object.defineProperty(qS,"__esModule",{value:!0});var US=Zp(),FS=f(),IP={keyword:"$recursiveAnchor",schemaType:"boolean",code(t){if(t.schema)US.dynamicAnchor(t,"");else FS.checkStrictMode(t.it,"$recursiveAnchor: false is ignored")}};qS.default=IP});var VS=e(function(HS){Object.defineProperty(HS,"__esModule",{value:!0});var WS=Qp(),RP={keyword:"$recursiveRef",schemaType:"string",code:(t)=>WS.dynamicRef(t,t.schema)};HS.default=RP});var GS=e(function(zS){Object.defineProperty(zS,"__esModule",{value:!0});var CP=Zp(),OP=Qp(),kP=BS(),MP=VS(),NP=[CP.default,OP.default,kP.default,MP.default];zS.default=NP});var JS=e(function(KS){Object.defineProperty(KS,"__esModule",{value:!0});var pu=Ar(),DP={keyword:"dependentRequired",type:"object",schemaType:"object",error:pu.error,code:(t)=>pu.validatePropertyDeps(t)};KS.default=DP});var ZS=e(function(XS){Object.defineProperty(XS,"__esModule",{value:!0});var YS=Ar(),jP={keyword:"dependentSchemas",type:"object",schemaType:"object",code:(t)=>YS.validateSchemaDeps(t)};XS.default=jP});var tb=e(function(eb){Object.defineProperty(eb,"__esModule",{value:!0});var QS=f(),FP={keyword:["maxContains","minContains"],type:"array",schemaType:"number",code({keyword:t,parentSchema:n,it:i}){if(n.contains===void 0)QS.checkStrictMode(i,`"${t}" without "contains" is ignored`)}};eb.default=FP});var nb=e(function(rb){Object.defineProperty(rb,"__esModule",{value:!0});var BP=JS(),WP=ZS(),HP=tb(),VP=[BP.default,WP.default,HP.default];rb.default=VP});var ib=e(function(sb){Object.defineProperty(sb,"__esModule",{value:!0});var _r=d(),hu=f(),GP=pe(),KP={message:"must NOT have unevaluated properties",params:({params:t})=>_r._`{unevaluatedProperty: ${t.unevaluatedProperty}}`},JP={keyword:"unevaluatedProperties",type:"object",schemaType:["boolean","object"],trackErrors:!0,error:KP,code(t){let{gen:n,schema:i,data:o,errsCount:a,it:c}=t;if(!a)throw Error("ajv implementation error");let{allErrors:m,props:E}=c;if(E instanceof _r.Name)n.if(_r._`${E} !== true`,()=>n.forIn("key",o,(R)=>n.if(I(E,R),()=>_(R))));else if(E!==!0)n.forIn("key",o,(R)=>E===void 0?_(R):n.if(T(E,R),()=>_(R)));c.props=!0,t.ok(_r._`${a} === ${GP.default.errors}`);function _(R){if(i===!1){if(t.setParams({unevaluatedProperty:R}),t.error(),!m)n.break();return}if(!hu.alwaysValidSchema(c,i)){let P=n.name("valid");if(t.subschema({keyword:"unevaluatedProperties",dataProp:R,dataPropType:hu.Type.Str},P),!m)n.if(_r.not(P),()=>n.break())}}function I(R,P){return _r._`!${R} || !${R}[${P}]`}function T(R,P){let M=[];for(let N in R)if(R[N]===!0)M.push(_r._`${P} !== ${N}`);return _r.and(...M)}}};sb.default=JP});var ab=e(function(ob){Object.defineProperty(ob,"__esModule",{value:!0});var an=d(),mu=f(),XP={message:({params:{len:t}})=>an.str`must NOT have more than ${t} items`,params:({params:{len:t}})=>an._`{limit: ${t}}`},ZP={keyword:"unevaluatedItems",type:"array",schemaType:["boolean","object"],error:XP,code(t){let{gen:n,schema:i,data:o,it:a}=t,c=a.items||0;if(c===!0)return;let m=n.const("len",an._`${o}.length`);if(i===!1)t.setParams({len:c}),t.fail(an._`${m} > ${c}`);else if(typeof i=="object"&&!mu.alwaysValidSchema(a,i)){let _=n.var("valid",an._`${m} <= ${c}`);n.if(an.not(_),()=>E(_,c)),t.ok(_)}a.items=!0;function E(_,I){n.forRange("i",I,m,(T)=>{if(t.subschema({keyword:"unevaluatedItems",dataProp:T,dataPropType:mu.Type.Num},_),!a.allErrors)n.if(an.not(_),()=>n.break())})}}};ob.default=ZP});var lb=e(function(cb){Object.defineProperty(cb,"__esModule",{value:!0});var eC=ib(),tC=ab(),rC=[eC.default,tC.default];cb.default=rC});var db=e(function(ub){Object.defineProperty(ub,"__esModule",{value:!0});var sC=Dn(),iC=Nn(),oC=On(),aC=GS(),cC=nb(),lC=lb(),uC=kn(),gu=Rn(),dC=[aC.default,sC.default,iC.default,(0,oC.default)(!0),uC.default,gu.metadataVocabulary,gu.contentVocabulary,cC.default,lC.default];ub.default=dC});var fb=e(function(GV,pC){pC.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/schema",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/core":!0,"https://json-schema.org/draft/2020-12/vocab/applicator":!0,"https://json-schema.org/draft/2020-12/vocab/unevaluated":!0,"https://json-schema.org/draft/2020-12/vocab/validation":!0,"https://json-schema.org/draft/2020-12/vocab/meta-data":!0,"https://json-schema.org/draft/2020-12/vocab/format-annotation":!0,"https://json-schema.org/draft/2020-12/vocab/content":!0},$dynamicAnchor:"meta",title:"Core and Validation specifications meta-schema",allOf:[{$ref:"meta/core"},{$ref:"meta/applicator"},{$ref:"meta/unevaluated"},{$ref:"meta/validation"},{$ref:"meta/meta-data"},{$ref:"meta/format-annotation"},{$ref:"meta/content"}],type:["object","boolean"],$comment:"This meta-schema also defines keywords that have appeared in previous drafts in order to prevent incompatible extensions as they remain in common use.",properties:{definitions:{$comment:'"definitions" has been replaced by "$defs".',type:"object",additionalProperties:{$dynamicRef:"#meta"},deprecated:!0,default:{}},dependencies:{$comment:'"dependencies" has been split and replaced by "dependentSchemas" and "dependentRequired" in order to serve their differing semantics.',type:"object",additionalProperties:{anyOf:[{$dynamicRef:"#meta"},{$ref:"meta/validation#/$defs/stringArray"}]},deprecated:!0,default:{}},$recursiveAnchor:{$comment:'"$recursiveAnchor" has been replaced by "$dynamicAnchor".',$ref:"meta/core#/$defs/anchorString",deprecated:!0},$recursiveRef:{$comment:'"$recursiveRef" has been replaced by "$dynamicRef".',$ref:"meta/core#/$defs/uriReferenceString",deprecated:!0}}}});var pb=e(function(KV,hC){hC.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/applicator",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/applicator":!0},$dynamicAnchor:"meta",title:"Applicator vocabulary meta-schema",type:["object","boolean"],properties:{prefixItems:{$ref:"#/$defs/schemaArray"},items:{$dynamicRef:"#meta"},contains:{$dynamicRef:"#meta"},additionalProperties:{$dynamicRef:"#meta"},properties:{type:"object",additionalProperties:{$dynamicRef:"#meta"},default:{}},patternProperties:{type:"object",additionalProperties:{$dynamicRef:"#meta"},propertyNames:{format:"regex"},default:{}},dependentSchemas:{type:"object",additionalProperties:{$dynamicRef:"#meta"},default:{}},propertyNames:{$dynamicRef:"#meta"},if:{$dynamicRef:"#meta"},then:{$dynamicRef:"#meta"},else:{$dynamicRef:"#meta"},allOf:{$ref:"#/$defs/schemaArray"},anyOf:{$ref:"#/$defs/schemaArray"},oneOf:{$ref:"#/$defs/schemaArray"},not:{$dynamicRef:"#meta"}},$defs:{schemaArray:{type:"array",minItems:1,items:{$dynamicRef:"#meta"}}}}});var hb=e(function(JV,mC){mC.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/unevaluated",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/unevaluated":!0},$dynamicAnchor:"meta",title:"Unevaluated applicator vocabulary meta-schema",type:["object","boolean"],properties:{unevaluatedItems:{$dynamicRef:"#meta"},unevaluatedProperties:{$dynamicRef:"#meta"}}}});var mb=e(function(YV,gC){gC.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/content",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/content":!0},$dynamicAnchor:"meta",title:"Content vocabulary meta-schema",type:["object","boolean"],properties:{contentEncoding:{type:"string"},contentMediaType:{type:"string"},contentSchema:{$dynamicRef:"#meta"}}}});var gb=e(function(XV,yC){yC.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/core",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/core":!0},$dynamicAnchor:"meta",title:"Core vocabulary meta-schema",type:["object","boolean"],properties:{$id:{$ref:"#/$defs/uriReferenceString",$comment:"Non-empty fragments not allowed.",pattern:"^[^#]*#?$"},$schema:{$ref:"#/$defs/uriString"},$ref:{$ref:"#/$defs/uriReferenceString"},$anchor:{$ref:"#/$defs/anchorString"},$dynamicRef:{$ref:"#/$defs/uriReferenceString"},$dynamicAnchor:{$ref:"#/$defs/anchorString"},$vocabulary:{type:"object",propertyNames:{$ref:"#/$defs/uriString"},additionalProperties:{type:"boolean"}},$comment:{type:"string"},$defs:{type:"object",additionalProperties:{$dynamicRef:"#meta"}}},$defs:{anchorString:{type:"string",pattern:"^[A-Za-z_][-A-Za-z0-9._]*$"},uriString:{type:"string",format:"uri"},uriReferenceString:{type:"string",format:"uri-reference"}}}});var yb=e(function(ZV,wC){wC.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/format-annotation",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/format-annotation":!0},$dynamicAnchor:"meta",title:"Format vocabulary meta-schema for annotation results",type:["object","boolean"],properties:{format:{type:"string"}}}});var wb=e(function(QV,SC){SC.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/meta-data",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/meta-data":!0},$dynamicAnchor:"meta",title:"Meta-data vocabulary meta-schema",type:["object","boolean"],properties:{title:{type:"string"},description:{type:"string"},default:!0,deprecated:{type:"boolean",default:!1},readOnly:{type:"boolean",default:!1},writeOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0}}}});var Sb=e(function(ez,bC){bC.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/validation",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/validation":!0},$dynamicAnchor:"meta",title:"Validation vocabulary meta-schema",type:["object","boolean"],properties:{type:{anyOf:[{$ref:"#/$defs/simpleTypes"},{type:"array",items:{$ref:"#/$defs/simpleTypes"},minItems:1,uniqueItems:!0}]},const:!0,enum:{type:"array",items:!0},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/$defs/nonNegativeInteger"},minLength:{$ref:"#/$defs/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},maxItems:{$ref:"#/$defs/nonNegativeInteger"},minItems:{$ref:"#/$defs/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},maxContains:{$ref:"#/$defs/nonNegativeInteger"},minContains:{$ref:"#/$defs/nonNegativeInteger",default:1},maxProperties:{$ref:"#/$defs/nonNegativeInteger"},minProperties:{$ref:"#/$defs/nonNegativeIntegerDefault0"},required:{$ref:"#/$defs/stringArray"},dependentRequired:{type:"object",additionalProperties:{$ref:"#/$defs/stringArray"}}},$defs:{nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{$ref:"#/$defs/nonNegativeInteger",default:0},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:!0,default:[]}}}});var vb=e(function(bb){Object.defineProperty(bb,"__esModule",{value:!0});var vC=fb(),EC=pb(),AC=hb(),xC=mb(),_C=gb(),IC=yb(),TC=wb(),RC=Sb(),PC=["/properties"];function CC(t){return[vC,EC,AC,xC,_C,n(this,IC),TC,n(this,RC)].forEach((i)=>this.addMetaSchema(i,void 0,!1)),this;function n(i,o){return t?i.$dataMetaSchema(o,PC):o}}bb.default=CC});var Eb=e(function(cn,th){Object.defineProperty(cn,"__esModule",{value:!0});cn.MissingRefError=cn.ValidationError=cn.CodeGen=cn.Name=cn.nil=cn.stringify=cn.str=cn._=cn.KeywordCxt=cn.Ajv2020=void 0;var kC=wn(),MC=db(),NC=Ln(),$C=vb(),eh="https://json-schema.org/draft/2020-12/schema";class yc extends kC.default{constructor(t={}){super({...t,dynamicRef:!0,next:!0,unevaluated:!0})}_addVocabularies(){if(super._addVocabularies(),MC.default.forEach((t)=>this.addVocabulary(t)),this.opts.discriminator)this.addKeyword(NC.default)}_addDefaultMetaSchema(){super._addDefaultMetaSchema();let{$data:t,meta:n}=this.opts;if(!n)return;$C.default.call(this,t),this.refs["http://json-schema.org/schema"]=eh}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(eh)?eh:void 0)}}cn.Ajv2020=yc;th.exports=cn=yc;th.exports.Ajv2020=yc;Object.defineProperty(cn,"__esModule",{value:!0});cn.default=yc;var DC=dt();Object.defineProperty(cn,"KeywordCxt",{enumerable:!0,get:function(){return DC.KeywordCxt}});var ya=d();Object.defineProperty(cn,"_",{enumerable:!0,get:function(){return ya._}});Object.defineProperty(cn,"str",{enumerable:!0,get:function(){return ya.str}});Object.defineProperty(cn,"stringify",{enumerable:!0,get:function(){return ya.stringify}});Object.defineProperty(cn,"nil",{enumerable:!0,get:function(){return ya.nil}});Object.defineProperty(cn,"Name",{enumerable:!0,get:function(){return ya.Name}});Object.defineProperty(cn,"CodeGen",{enumerable:!0,get:function(){return ya.CodeGen}});var LC=Bt();Object.defineProperty(cn,"ValidationError",{enumerable:!0,get:function(){return LC.default}});var jC=ft();Object.defineProperty(cn,"MissingRefError",{enumerable:!0,get:function(){return jC.default}})});var wa=e(function(pz,Ab){var JC=Number.MAX_SAFE_INTEGER||9007199254740991,YC=["major","premajor","minor","preminor","patch","prepatch","prerelease"];Ab.exports={MAX_LENGTH:256,MAX_SAFE_COMPONENT_LENGTH:16,MAX_SAFE_BUILD_LENGTH:250,MAX_SAFE_INTEGER:JC,RELEASE_TYPES:YC,SEMVER_SPEC_VERSION:"2.0.0",FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2}});var wc=e(function(hz,xb){var XC=typeof process==="object"&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...t)=>console.error("SEMVER",...t):()=>{};xb.exports=XC});var Sa=e(function(zs,_b){var{MAX_SAFE_COMPONENT_LENGTH:sh,MAX_SAFE_BUILD_LENGTH:ZC,MAX_LENGTH:QC}=wa(),eO=wc();zs=_b.exports={};var tO=zs.re=[],rO=zs.safeRe=[],se=zs.src=[],nO=zs.safeSrc=[],oe=zs.t={},sO=0,ih="[a-zA-Z0-9-]",iO=[["\\s",1],["\\d",QC],[ih,ZC]],oO=(t)=>{for(let[n,i]of iO)t=t.split(`${n}*`).join(`${n}{0,${i}}`).split(`${n}+`).join(`${n}{1,${i}}`);return t},Re=(t,n,i)=>{let o=oO(n),a=sO++;eO(t,a,n),oe[t]=a,se[a]=n,nO[a]=o,tO[a]=new RegExp(n,i?"g":void 0),rO[a]=new RegExp(o,i?"g":void 0)};Re("NUMERICIDENTIFIER","0|[1-9]\\d*");Re("NUMERICIDENTIFIERLOOSE","\\d+");Re("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${ih}*`);Re("MAINVERSION",`(${se[oe.NUMERICIDENTIFIER]})\\.(${se[oe.NUMERICIDENTIFIER]})\\.(${se[oe.NUMERICIDENTIFIER]})`);Re("MAINVERSIONLOOSE",`(${se[oe.NUMERICIDENTIFIERLOOSE]})\\.(${se[oe.NUMERICIDENTIFIERLOOSE]})\\.(${se[oe.NUMERICIDENTIFIERLOOSE]})`);Re("PRERELEASEIDENTIFIER",`(?:${se[oe.NONNUMERICIDENTIFIER]}|${se[oe.NUMERICIDENTIFIER]})`);Re("PRERELEASEIDENTIFIERLOOSE",`(?:${se[oe.NONNUMERICIDENTIFIER]}|${se[oe.NUMERICIDENTIFIERLOOSE]})`);Re("PRERELEASE",`(?:-(${se[oe.PRERELEASEIDENTIFIER]}(?:\\.${se[oe.PRERELEASEIDENTIFIER]})*))`);Re("PRERELEASELOOSE",`(?:-?(${se[oe.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${se[oe.PRERELEASEIDENTIFIERLOOSE]})*))`);Re("BUILDIDENTIFIER",`${ih}+`);Re("BUILD",`(?:\\+(${se[oe.BUILDIDENTIFIER]}(?:\\.${se[oe.BUILDIDENTIFIER]})*))`);Re("FULLPLAIN",`v?${se[oe.MAINVERSION]}${se[oe.PRERELEASE]}?${se[oe.BUILD]}?`);Re("FULL",`^${se[oe.FULLPLAIN]}$`);Re("LOOSEPLAIN",`[v=\\s]*${se[oe.MAINVERSIONLOOSE]}${se[oe.PRERELEASELOOSE]}?${se[oe.BUILD]}?`);Re("LOOSE",`^${se[oe.LOOSEPLAIN]}$`);Re("GTLT","((?:<|>)?=?)");Re("XRANGEIDENTIFIERLOOSE",`${se[oe.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`);Re("XRANGEIDENTIFIER",`${se[oe.NUMERICIDENTIFIER]}|x|X|\\*`);Re("XRANGEPLAIN",`[v=\\s]*(${se[oe.XRANGEIDENTIFIER]})(?:\\.(${se[oe.XRANGEIDENTIFIER]})(?:\\.(${se[oe.XRANGEIDENTIFIER]})(?:${se[oe.PRERELEASE]})?${se[oe.BUILD]}?)?)?`);Re("XRANGEPLAINLOOSE",`[v=\\s]*(${se[oe.XRANGEIDENTIFIERLOOSE]})(?:\\.(${se[oe.XRANGEIDENTIFIERLOOSE]})(?:\\.(${se[oe.XRANGEIDENTIFIERLOOSE]})(?:${se[oe.PRERELEASELOOSE]})?${se[oe.BUILD]}?)?)?`);Re("XRANGE",`^${se[oe.GTLT]}\\s*${se[oe.XRANGEPLAIN]}$`);Re("XRANGELOOSE",`^${se[oe.GTLT]}\\s*${se[oe.XRANGEPLAINLOOSE]}$`);Re("COERCEPLAIN",`(^|[^\\d])(\\d{1,${sh}})(?:\\.(\\d{1,${sh}}))?(?:\\.(\\d{1,${sh}}))?`);Re("COERCE",`${se[oe.COERCEPLAIN]}(?:$|[^\\d])`);Re("COERCEFULL",se[oe.COERCEPLAIN]+`(?:${se[oe.PRERELEASE]})?(?:${se[oe.BUILD]})?(?:$|[^\\d])`);Re("COERCERTL",se[oe.COERCE],!0);Re("COERCERTLFULL",se[oe.COERCEFULL],!0);Re("LONETILDE","(?:~>?)");Re("TILDETRIM",`(\\s*)${se[oe.LONETILDE]}\\s+`,!0);zs.tildeTrimReplace="$1~";Re("TILDE",`^${se[oe.LONETILDE]}${se[oe.XRANGEPLAIN]}$`);Re("TILDELOOSE",`^${se[oe.LONETILDE]}${se[oe.XRANGEPLAINLOOSE]}$`);Re("LONECARET","(?:\\^)");Re("CARETTRIM",`(\\s*)${se[oe.LONECARET]}\\s+`,!0);zs.caretTrimReplace="$1^";Re("CARET",`^${se[oe.LONECARET]}${se[oe.XRANGEPLAIN]}$`);Re("CARETLOOSE",`^${se[oe.LONECARET]}${se[oe.XRANGEPLAINLOOSE]}$`);Re("COMPARATORLOOSE",`^${se[oe.GTLT]}\\s*(${se[oe.LOOSEPLAIN]})$|^$`);Re("COMPARATOR",`^${se[oe.GTLT]}\\s*(${se[oe.FULLPLAIN]})$|^$`);Re("COMPARATORTRIM",`(\\s*)${se[oe.GTLT]}\\s*(${se[oe.LOOSEPLAIN]}|${se[oe.XRANGEPLAIN]})`,!0);zs.comparatorTrimReplace="$1$2$3";Re("HYPHENRANGE",`^\\s*(${se[oe.XRANGEPLAIN]})\\s+-\\s+(${se[oe.XRANGEPLAIN]})\\s*$`);Re("HYPHENRANGELOOSE",`^\\s*(${se[oe.XRANGEPLAINLOOSE]})\\s+-\\s+(${se[oe.XRANGEPLAINLOOSE]})\\s*$`);Re("STAR","(<|>)?=?\\s*\\*");Re("GTE0","^\\s*>=\\s*0\\.0\\.0\\s*$");Re("GTE0PRE","^\\s*>=\\s*0\\.0\\.0-0\\s*$")});var yu=e(function(mz,Ib){var aO=Object.freeze({loose:!0}),cO=Object.freeze({}),lO=(t)=>{if(!t)return cO;if(typeof t!=="object")return aO;return t};Ib.exports=lO});var oh=e(function(gz,Pb){var Tb=/^[0-9]+$/,Rb=(t,n)=>{if(typeof t==="number"&&typeof n==="number")return t===n?0:t<n?-1:1;let i=Tb.test(t),o=Tb.test(n);if(i&&o)t=+t,n=+n;return t===n?0:i&&!o?-1:o&&!i?1:t<n?-1:1},uO=(t,n)=>Rb(n,t);Pb.exports={compareIdentifiers:Rb,rcompareIdentifiers:uO}});var fr=e(function(yz,Ob){var wu=wc(),{MAX_LENGTH:Cb,MAX_SAFE_INTEGER:Su}=wa(),{safeRe:bu,t:vu}=Sa(),dO=yu(),{compareIdentifiers:ah}=oh(),fO=(t,n)=>{let i=n.split(".");if(i.length>t.length)return!1;for(let o=0;o<i.length;o++)if(ah(t[o],i[o])!==0)return!1;return!0};class Es{constructor(t,n){if(n=dO(n),t instanceof Es)if(t.loose===!!n.loose&&t.includePrerelease===!!n.includePrerelease)return t;else t=t.version;else if(typeof t!=="string")throw TypeError(`Invalid version. Must be a string. Got type "${typeof t}".`);if(t.length>Cb)throw TypeError(`version is longer than ${Cb} characters`);wu("SemVer",t,n),this.options=n,this.loose=!!n.loose,this.includePrerelease=!!n.includePrerelease;let i=t.trim().match(n.loose?bu[vu.LOOSE]:bu[vu.FULL]);if(!i)throw TypeError(`Invalid Version: ${t}`);if(this.raw=t,this.major=+i[1],this.minor=+i[2],this.patch=+i[3],this.major>Su||this.major<0)throw TypeError("Invalid major version");if(this.minor>Su||this.minor<0)throw TypeError("Invalid minor version");if(this.patch>Su||this.patch<0)throw TypeError("Invalid patch version");if(!i[4])this.prerelease=[];else this.prerelease=i[4].split(".").map((o)=>{if(/^[0-9]+$/.test(o)){let a=+o;if(a>=0&&a<Su)return a}return o});this.build=i[5]?i[5].split("."):[],this.format()}format(){if(this.version=`${this.major}.${this.minor}.${this.patch}`,this.prerelease.length)this.version+=`-${this.prerelease.join(".")}`;return this.version}toString(){return this.version}compare(t){if(wu("SemVer.compare",this.version,this.options,t),!(t instanceof Es)){if(typeof t==="string"&&t===this.version)return 0;t=new Es(t,this.options)}if(t.version===this.version)return 0;return this.compareMain(t)||this.comparePre(t)}compareMain(t){if(!(t instanceof Es))t=new Es(t,this.options);if(this.major<t.major)return-1;if(this.major>t.major)return 1;if(this.minor<t.minor)return-1;if(this.minor>t.minor)return 1;if(this.patch<t.patch)return-1;if(this.patch>t.patch)return 1;return 0}comparePre(t){if(!(t instanceof Es))t=new Es(t,this.options);if(this.prerelease.length&&!t.prerelease.length)return-1;else if(!this.prerelease.length&&t.prerelease.length)return 1;else if(!this.prerelease.length&&!t.prerelease.length)return 0;let n=0;do{let i=this.prerelease[n],o=t.prerelease[n];if(wu("prerelease compare",n,i,o),i===void 0&&o===void 0)return 0;else if(o===void 0)return 1;else if(i===void 0)return-1;else if(i===o)continue;else return ah(i,o)}while(++n)}compareBuild(t){if(!(t instanceof Es))t=new Es(t,this.options);let n=0;do{let i=this.build[n],o=t.build[n];if(wu("build compare",n,i,o),i===void 0&&o===void 0)return 0;else if(o===void 0)return 1;else if(i===void 0)return-1;else if(i===o)continue;else return ah(i,o)}while(++n)}inc(t,n,i){if(t.startsWith("pre")){if(!n&&i===!1)throw Error("invalid increment argument: identifier is empty");if(n){let o=`-${n}`.match(this.options.loose?bu[vu.PRERELEASELOOSE]:bu[vu.PRERELEASE]);if(!o||o[1]!==n)throw Error(`invalid identifier: ${n}`)}}switch(t){case"premajor":this.prerelease.length=0,this.patch=0,this.minor=0,this.major++,this.inc("pre",n,i);break;case"preminor":this.prerelease.length=0,this.patch=0,this.minor++,this.inc("pre",n,i);break;case"prepatch":this.prerelease.length=0,this.inc("patch",n,i),this.inc("pre",n,i);break;case"prerelease":if(this.prerelease.length===0)this.inc("patch",n,i);this.inc("pre",n,i);break;case"release":if(this.prerelease.length===0)throw Error(`version ${this.raw} is not a prerelease`);this.prerelease.length=0;break;case"major":if(this.minor!==0||this.patch!==0||this.prerelease.length===0)this.major++;this.minor=0,this.patch=0,this.prerelease=[];break;case"minor":if(this.patch!==0||this.prerelease.length===0)this.minor++;this.patch=0,this.prerelease=[];break;case"patch":if(this.prerelease.length===0)this.patch++;this.prerelease=[];break;case"pre":{let o=Number(i)?1:0;if(this.prerelease.length===0)this.prerelease=[o];else{let a=this.prerelease.length;while(--a>=0)if(typeof this.prerelease[a]==="number")this.prerelease[a]++,a=-2;if(a===-1){if(n===this.prerelease.join(".")&&i===!1)throw Error("invalid increment argument: identifier already exists");this.prerelease.push(o)}}if(n){let a=[n,o];if(i===!1)a=[n];if(fO(this.prerelease,n)){let c=this.prerelease[n.split(".").length];if(isNaN(c))this.prerelease=a}else this.prerelease=a}break}default:throw Error(`invalid increment argument: ${t}`)}if(this.raw=this.format(),this.build.length)this.raw+=`+${this.build.join(".")}`;return this}}Ob.exports=Es});var so=e(function(wz,Mb){var kb=fr(),pO=(t,n,i=!1)=>{if(t instanceof kb)return t;try{return new kb(t,n)}catch(o){if(!i)return null;throw o}};Mb.exports=pO});var $b=e(function(Sz,Nb){var hO=so(),mO=(t,n)=>{let i=hO(t,n);return i?i.version:null};Nb.exports=mO});var Lb=e(function(bz,Db){var gO=so(),yO=(t,n)=>{let i=gO(t.trim().replace(/^[=v]+/,""),n);return i?i.version:null};Db.exports=yO});var Fb=e(function(vz,Ub){var jb=fr(),wO=(t,n,i,o,a)=>{if(typeof i==="string")a=o,o=i,i=void 0;try{return new jb(t instanceof jb?t.version:t,i).inc(n,o,a).version}catch(c){return null}};Ub.exports=wO});var Wb=e(function(Ez,Bb){var qb=so(),SO=(t,n)=>{let i=qb(t,null,!0),o=qb(n,null,!0),a=i.compare(o);if(a===0)return null;let c=a>0,m=c?i:o,E=c?o:i,_=!!m.prerelease.length;if(!!E.prerelease.length&&!_){if(!E.patch&&!E.minor)return"major";if(E.compareMain(m)===0){if(E.minor&&!E.patch)return"minor";return"patch"}}let T=_?"pre":"";if(i.major!==o.major)return T+"major";if(i.minor!==o.minor)return T+"minor";if(i.patch!==o.patch)return T+"patch";return"prerelease"};Bb.exports=SO});var Vb=e(function(Az,Hb){var bO=fr(),vO=(t,n)=>new bO(t,n).major;Hb.exports=vO});var Gb=e(function(xz,zb){var EO=fr(),AO=(t,n)=>new EO(t,n).minor;zb.exports=AO});var Jb=e(function(_z,Kb){var xO=fr(),_O=(t,n)=>new xO(t,n).patch;Kb.exports=_O});var Xb=e(function(Iz,Yb){var IO=so(),TO=(t,n)=>{let i=IO(t,n);return i&&i.prerelease.length?i.prerelease:null};Yb.exports=TO});var An=e(function(Tz,Qb){var Zb=fr(),RO=(t,n,i)=>new Zb(t,i).compare(new Zb(n,i));Qb.exports=RO});var t0=e(function(Rz,e0){var PO=An(),CO=(t,n,i)=>PO(n,t,i);e0.exports=CO});var n0=e(function(Pz,r0){var OO=An(),kO=(t,n)=>OO(t,n,!0);r0.exports=kO});var Eu=e(function(Cz,i0){var s0=fr(),MO=(t,n,i)=>{let o=new s0(t,i),a=new s0(n,i);return o.compare(a)||o.compareBuild(a)};i0.exports=MO});var a0=e(function(Oz,o0){var NO=Eu(),$O=(t,n)=>t.sort((i,o)=>NO(i,o,n));o0.exports=$O});var l0=e(function(kz,c0){var DO=Eu(),LO=(t,n)=>t.sort((i,o)=>DO(o,i,n));c0.exports=LO});var Sc=e(function(Mz,u0){var jO=An(),UO=(t,n,i)=>jO(t,n,i)>0;u0.exports=UO});var Au=e(function(Nz,d0){var FO=An(),qO=(t,n,i)=>FO(t,n,i)<0;d0.exports=qO});var ch=e(function($z,f0){var BO=An(),WO=(t,n,i)=>BO(t,n,i)===0;f0.exports=WO});var lh=e(function(Dz,p0){var HO=An(),VO=(t,n,i)=>HO(t,n,i)!==0;p0.exports=VO});var xu=e(function(Lz,h0){var zO=An(),GO=(t,n,i)=>zO(t,n,i)>=0;h0.exports=GO});var _u=e(function(jz,m0){var KO=An(),JO=(t,n,i)=>KO(t,n,i)<=0;m0.exports=JO});var uh=e(function(Uz,g0){var YO=ch(),XO=lh(),ZO=Sc(),QO=xu(),ek=Au(),tk=_u(),rk=(t,n,i,o)=>{switch(n){case"===":if(typeof t==="object")t=t.version;if(typeof i==="object")i=i.version;return t===i;case"!==":if(typeof t==="object")t=t.version;if(typeof i==="object")i=i.version;return t!==i;case"":case"=":case"==":return YO(t,i,o);case"!=":return XO(t,i,o);case">":return ZO(t,i,o);case">=":return QO(t,i,o);case"<":return ek(t,i,o);case"<=":return tk(t,i,o);default:throw TypeError(`Invalid operator: ${n}`)}};g0.exports=rk});var w0=e(function(Fz,y0){var nk=fr(),sk=so(),{safeRe:Iu,t:Tu}=Sa(),ik=(t,n)=>{if(t instanceof nk)return t;if(typeof t==="number")t=String(t);if(typeof t!=="string")return null;n=n||{};let i=null;if(!n.rtl)i=t.match(n.includePrerelease?Iu[Tu.COERCEFULL]:Iu[Tu.COERCE]);else{let _=n.includePrerelease?Iu[Tu.COERCERTLFULL]:Iu[Tu.COERCERTL],I;while((I=_.exec(t))&&(!i||i.index+i[0].length!==t.length)){if(!i||I.index+I[0].length!==i.index+i[0].length)i=I;_.lastIndex=I.index+I[1].length+I[2].length}_.lastIndex=-1}if(i===null)return null;let o=i[2],a=i[3]||"0",c=i[4]||"0",m=n.includePrerelease&&i[5]?`-${i[5]}`:"",E=n.includePrerelease&&i[6]?`+${i[6]}`:"";return sk(`${o}.${a}.${c}${m}${E}`,n)};y0.exports=ik});var v0=e(function(qz,b0){var ok=so(),S0=wa(),ak=fr(),ck=(t,n,i)=>{if(!S0.RELEASE_TYPES.includes(n))return null;let o=lk(t,i);return o&&uk(o,n)},lk=(t,n)=>{let i=t instanceof ak?t.version:t;return ok(i,n)},uk=(t,n)=>{if(dk(n))return t.version;switch(t.prerelease=[],n){case"major":t.minor=0,t.patch=0;break;case"minor":t.patch=0;break}return t.format()},dk=(t)=>t.startsWith("pre");b0.exports=ck});var x0=e(function(Bz,A0){class E0{constructor(){this.max=1000,this.map=new Map}get(t){let n=this.map.get(t);if(n===void 0)return;else return this.map.delete(t),this.map.set(t,n),n}delete(t){return this.map.delete(t)}set(t,n){if(!this.delete(t)&&n!==void 0){if(this.map.size>=this.max){let o=this.map.keys().next().value;this.delete(o)}this.map.set(t,n)}return this}}A0.exports=E0});var _n=e(function(Wz,R0){var fk=/\s+/g;class bc{constructor(t,n){if(n=hk(n),t instanceof bc)if(t.loose===!!n.loose&&t.includePrerelease===!!n.includePrerelease)return t;else return new bc(t.raw,n);if(t instanceof Ru)return this.raw=t.value,this.set=[[t]],this.formatted=void 0,this;if(this.options=n,this.loose=!!n.loose,this.includePrerelease=!!n.includePrerelease,this.raw=t.trim().replace(fk," "),this.set=this.raw.split("||").map((i)=>this.parseRange(i.trim())).filter((i)=>i.length),!this.set.length)throw TypeError(`Invalid SemVer Range: ${this.raw}`);if(this.set.length>1){let i=this.set[0];if(this.set=this.set.filter((o)=>!I0(o[0])),this.set.length===0)this.set=[i];else if(this.set.length>1){for(let o of this.set)if(o.length===1&&Ak(o[0])){this.set=[o];break}}}this.formatted=void 0}get range(){if(this.formatted===void 0){this.formatted="";for(let t=0;t<this.set.length;t++){if(t>0)this.formatted+="||";let n=this.set[t];for(let i=0;i<n.length;i++){if(i>0)this.formatted+=" ";this.formatted+=n[i].toString().trim()}}}return this.formatted}format(){return this.range}toString(){return this.range}parseRange(t){t=t.replace(Ek,"");let i=((this.options.includePrerelease&&bk)|(this.options.loose&&vk))+":"+t,o=_0.get(i);if(o)return o;let a=this.options.loose,c=a?Xr[hr.HYPHENRANGELOOSE]:Xr[hr.HYPHENRANGE];t=t.replace(c,Nk(this.options.includePrerelease)),gt("hyphen replace",t),t=t.replace(Xr[hr.COMPARATORTRIM],yk),gt("comparator trim",t),t=t.replace(Xr[hr.TILDETRIM],wk),gt("tilde trim",t),t=t.replace(Xr[hr.CARETTRIM],Sk),gt("caret trim",t);let m=t.split(" ").map((T)=>xk(T,this.options)).join(" ").split(/\s+/).map((T)=>Mk(T,this.options));if(a)m=m.filter((T)=>(gt("loose invalid filter",T,this.options),!!T.match(Xr[hr.COMPARATORLOOSE])));gt("range list",m);let E=new Map,_=m.map((T)=>new Ru(T,this.options));for(let T of _){if(I0(T))return[T];E.set(T.value,T)}if(E.size>1&&E.has(""))E.delete("");let I=[...E.values()];return _0.set(i,I),I}intersects(t,n){if(!(t instanceof bc))throw TypeError("a Range is required");return this.set.some((i)=>T0(i,n)&&t.set.some((o)=>T0(o,n)&&i.every((a)=>o.every((c)=>a.intersects(c,n)))))}test(t){if(!t)return!1;if(typeof t==="string")try{t=new mk(t,this.options)}catch(n){return!1}for(let n=0;n<this.set.length;n++)if($k(this.set[n],t,this.options))return!0;return!1}}R0.exports=bc;var pk=x0(),_0=new pk,hk=yu(),Ru=vc(),gt=wc(),mk=fr(),{safeRe:Xr,src:gk,t:hr,comparatorTrimReplace:yk,tildeTrimReplace:wk,caretTrimReplace:Sk}=Sa(),{FLAG_INCLUDE_PRERELEASE:bk,FLAG_LOOSE:vk}=wa(),Ek=new RegExp(gk[hr.BUILD],"g"),I0=(t)=>t.value==="<0.0.0-0",Ak=(t)=>t.value==="",T0=(t,n)=>{let i=!0,o=t.slice(),a=o.pop();while(i&&o.length)i=o.every((c)=>a.intersects(c,n)),a=o.pop();return i},xk=(t,n)=>(t=t.replace(Xr[hr.BUILD],""),gt("comp",t,n),t=Rk(t,n),gt("caret",t),t=Ik(t,n),gt("tildes",t),t=Ck(t,n),gt("xrange",t),t=kk(t,n),gt("stars",t),t),Zt=(t)=>!t||t.toLowerCase()==="x"||t==="*",_k=(t,n,i)=>Zt(t)&&!Zt(n)||Zt(n)&&i&&!Zt(i),Ik=(t,n)=>t.trim().split(/\s+/).map((i)=>Tk(i,n)).join(" "),Tk=(t,n)=>{let i=n.loose?Xr[hr.TILDELOOSE]:Xr[hr.TILDE];return t.replace(i,(o,a,c,m,E)=>{gt("tilde",t,o,a,c,m,E);let _;if(Zt(a))_="";else if(Zt(c))_=`>=${a}.0.0 <${+a+1}.0.0-0`;else if(Zt(m))_=`>=${a}.${c}.0 <${a}.${+c+1}.0-0`;else if(E)gt("replaceTilde pr",E),_=`>=${a}.${c}.${m}-${E} <${a}.${+c+1}.0-0`;else _=`>=${a}.${c}.${m} <${a}.${+c+1}.0-0`;return gt("tilde return",_),_})},Rk=(t,n)=>t.trim().split(/\s+/).map((i)=>Pk(i,n)).join(" "),Pk=(t,n)=>{gt("caret",t,n);let i=n.loose?Xr[hr.CARETLOOSE]:Xr[hr.CARET],o=n.includePrerelease?"-0":"";return t.replace(i,(a,c,m,E,_)=>{gt("caret",t,a,c,m,E,_);let I;if(Zt(c))I="";else if(Zt(m))I=`>=${c}.0.0${o} <${+c+1}.0.0-0`;else if(Zt(E))if(c==="0")I=`>=${c}.${m}.0${o} <${c}.${+m+1}.0-0`;else I=`>=${c}.${m}.0${o} <${+c+1}.0.0-0`;else if(_)if(gt("replaceCaret pr",_),c==="0")if(m==="0")I=`>=${c}.${m}.${E}-${_} <${c}.${m}.${+E+1}-0`;else I=`>=${c}.${m}.${E}-${_} <${c}.${+m+1}.0-0`;else I=`>=${c}.${m}.${E}-${_} <${+c+1}.0.0-0`;else if(gt("no pr"),c==="0")if(m==="0")I=`>=${c}.${m}.${E} <${c}.${m}.${+E+1}-0`;else I=`>=${c}.${m}.${E} <${c}.${+m+1}.0-0`;else I=`>=${c}.${m}.${E} <${+c+1}.0.0-0`;return gt("caret return",I),I})},Ck=(t,n)=>(gt("replaceXRanges",t,n),t.split(/\s+/).map((i)=>Ok(i,n)).join(" ")),Ok=(t,n)=>{t=t.trim();let i=n.loose?Xr[hr.XRANGELOOSE]:Xr[hr.XRANGE];return t.replace(i,(o,a,c,m,E,_)=>{if(gt("xRange",t,o,a,c,m,E,_),_k(c,m,E))return t;let I=Zt(c),T=I||Zt(m),R=T||Zt(E),P=R;if(a==="="&&P)a="";if(_=n.includePrerelease?"-0":"",I)if(a===">"||a==="<")o="<0.0.0-0";else o="*";else if(a&&P){if(T)m=0;if(E=0,a===">")if(a=">=",T)c=+c+1,m=0,E=0;else m=+m+1,E=0;else if(a==="<=")if(a="<",T)c=+c+1;else m=+m+1;if(a==="<")_="-0";o=`${a+c}.${m}.${E}${_}`}else if(T)o=`>=${c}.0.0${_} <${+c+1}.0.0-0`;else if(R)o=`>=${c}.${m}.0${_} <${c}.${+m+1}.0-0`;return gt("xRange return",o),o})},kk=(t,n)=>(gt("replaceStars",t,n),t.trim().replace(Xr[hr.STAR],"")),Mk=(t,n)=>(gt("replaceGTE0",t,n),t.trim().replace(Xr[n.includePrerelease?hr.GTE0PRE:hr.GTE0],"")),Nk=(t)=>(n,i,o,a,c,m,E,_,I,T,R,P)=>{if(Zt(o))i="";else if(Zt(a))i=`>=${o}.0.0${t?"-0":""}`;else if(Zt(c))i=`>=${o}.${a}.0${t?"-0":""}`;else if(m)i=`>=${i}`;else i=`>=${i}${t?"-0":""}`;if(Zt(I))_="";else if(Zt(T))_=`<${+I+1}.0.0-0`;else if(Zt(R))_=`<${I}.${+T+1}.0-0`;else if(P)_=`<=${I}.${T}.${R}-${P}`;else if(t)_=`<${I}.${T}.${+R+1}-0`;else _=`<=${_}`;return`${i} ${_}`.trim()},$k=(t,n,i)=>{for(let o=0;o<t.length;o++)if(!t[o].test(n))return!1;if(n.prerelease.length&&!i.includePrerelease){for(let o=0;o<t.length;o++){if(gt(t[o].semver),t[o].semver===Ru.ANY)continue;if(t[o].semver.prerelease.length>0){let a=t[o].semver;if(a.major===n.major&&a.minor===n.minor&&a.patch===n.patch)return!0}}return!1}return!0}});var vc=e(function(Hz,N0){var Ec=Symbol("SemVer ANY");class Pu{static get ANY(){return Ec}constructor(t,n){if(n=P0(n),t instanceof Pu)if(t.loose===!!n.loose)return t;else t=t.value;if(t=t.trim().split(/\s+/).join(" "),fh("comparator",t,n),this.options=n,this.loose=!!n.loose,this.parse(t),this.semver===Ec)this.value="";else this.value=this.operator+this.semver.version;fh("comp",this)}parse(t){let n=this.options.loose?C0[O0.COMPARATORLOOSE]:C0[O0.COMPARATOR],i=t.match(n);if(!i)throw TypeError(`Invalid comparator: ${t}`);if(this.operator=i[1]!==void 0?i[1]:"",this.operator==="=")this.operator="";if(!i[2])this.semver=Ec;else this.semver=new k0(i[2],this.options.loose)}toString(){return this.value}test(t){if(fh("Comparator.test",t,this.options.loose),this.semver===Ec||t===Ec)return!0;if(typeof t==="string")try{t=new k0(t,this.options)}catch(n){return!1}return dh(t,this.operator,this.semver,this.options)}intersects(t,n){if(!(t instanceof Pu))throw TypeError("a Comparator is required");if(this.operator===""){if(this.value==="")return!0;return new M0(t.value,n).test(this.value)}else if(t.operator===""){if(t.value==="")return!0;return new M0(this.value,n).test(t.semver)}if(n=P0(n),n.includePrerelease&&(this.value==="<0.0.0-0"||t.value==="<0.0.0-0"))return!1;if(!n.includePrerelease&&(this.value.startsWith("<0.0.0")||t.value.startsWith("<0.0.0")))return!1;if(this.operator.startsWith(">")&&t.operator.startsWith(">"))return!0;if(this.operator.startsWith("<")&&t.operator.startsWith("<"))return!0;if(this.semver.version===t.semver.version&&this.operator.includes("=")&&t.operator.includes("="))return!0;if(dh(this.semver,"<",t.semver,n)&&this.operator.startsWith(">")&&t.operator.startsWith("<"))return!0;if(dh(this.semver,">",t.semver,n)&&this.operator.startsWith("<")&&t.operator.startsWith(">"))return!0;return!1}}N0.exports=Pu;var P0=yu(),{safeRe:C0,t:O0}=Sa(),dh=uh(),fh=wc(),k0=fr(),M0=_n()});var Ac=e(function(Vz,$0){var Dk=_n(),Lk=(t,n,i)=>{try{n=new Dk(n,i)}catch(o){return!1}return n.test(t)};$0.exports=Lk});var L0=e(function(zz,D0){var jk=_n(),Uk=(t,n)=>new jk(t,n).set.map((i)=>i.map((o)=>o.value).join(" ").trim().split(" "));D0.exports=Uk});var U0=e(function(Gz,j0){var Fk=fr(),qk=_n(),Bk=(t,n,i)=>{let o=null,a=null,c=null;try{c=new qk(n,i)}catch(m){return null}return t.forEach((m)=>{if(c.test(m)){if(!o||a.compare(m)===-1)o=m,a=new Fk(o,i)}}),o};j0.exports=Bk});var q0=e(function(Kz,F0){var Wk=fr(),Hk=_n(),Vk=(t,n,i)=>{let o=null,a=null,c=null;try{c=new Hk(n,i)}catch(m){return null}return t.forEach((m)=>{if(c.test(m)){if(!o||a.compare(m)===1)o=m,a=new Wk(o,i)}}),o};F0.exports=Vk});var H0=e(function(Jz,W0){var ph=fr(),zk=_n(),B0=Sc(),Gk=(t,n)=>{t=new zk(t,n);let i=new ph("0.0.0");if(t.test(i))return i;if(i=new ph("0.0.0-0"),t.test(i))return i;i=null;for(let o=0;o<t.set.length;++o){let a=t.set[o],c=null;if(a.forEach((m)=>{let E=new ph(m.semver.version);switch(m.operator){case">":if(E.prerelease.length===0)E.patch++;else E.prerelease.push(0);E.raw=E.format();case"":case">=":if(!c||B0(E,c))c=E;break;case"<":case"<=":break;default:throw Error(`Unexpected operation: ${m.operator}`)}}),c&&(!i||B0(i,c)))i=c}if(i&&t.test(i))return i;return null};W0.exports=Gk});var z0=e(function(Yz,V0){var Kk=_n(),Jk=(t,n)=>{try{return new Kk(t,n).range||"*"}catch(i){return null}};V0.exports=Jk});var Cu=e(function(Xz,Y0){var Yk=fr(),J0=vc(),{ANY:Xk}=J0,Zk=_n(),Qk=Ac(),G0=Sc(),K0=Au(),eM=_u(),tM=xu(),rM=(t,n,i,o)=>{t=new Yk(t,o),n=new Zk(n,o);let a,c,m,E,_;switch(i){case">":a=G0,c=eM,m=K0,E=">",_=">=";break;case"<":a=K0,c=tM,m=G0,E="<",_="<=";break;default:throw TypeError('Must provide a hilo val of "<" or ">"')}if(Qk(t,n,o))return!1;for(let I=0;I<n.set.length;++I){let T=n.set[I],R=null,P=null;if(T.forEach((M)=>{if(M.semver===Xk)M=new J0(">=0.0.0");if(R=R||M,P=P||M,a(M.semver,R.semver,o))R=M;else if(m(M.semver,P.semver,o))P=M}),R.operator===E||R.operator===_)return!1;if((!P.operator||P.operator===E)&&c(t,P.semver))return!1;else if(P.operator===_&&m(t,P.semver))return!1}return!0};Y0.exports=rM});var Z0=e(function(Zz,X0){var nM=Cu(),sM=(t,n,i)=>nM(t,n,">",i);X0.exports=sM});var ev=e(function(Qz,Q0){var iM=Cu(),oM=(t,n,i)=>iM(t,n,"<",i);Q0.exports=oM});var nv=e(function(e9,rv){var tv=_n(),aM=(t,n,i)=>(t=new tv(t,i),n=new tv(n,i),t.intersects(n,i));rv.exports=aM});var iv=e(function(t9,sv){var cM=Ac(),lM=An();sv.exports=(t,n,i)=>{let o=[],a=null,c=null,m=t.sort((T,R)=>lM(T,R,i));for(let T of m)if(cM(T,n,i)){if(c=T,!a)a=T}else{if(c)o.push([a,c]);c=null,a=null}if(a)o.push([a,null]);let E=[];for(let[T,R]of o)if(T===R)E.push(T);else if(!R&&T===m[0])E.push("*");else if(!R)E.push(`>=${T}`);else if(T===m[0])E.push(`<=${R}`);else E.push(`${T} - ${R}`);let _=E.join(" || "),I=typeof n.raw==="string"?n.raw:String(n);return _.length<I.length?_:n}});var dv=e(function(r9,uv){var ov=_n(),gh=vc(),{ANY:hh}=gh,mh=Ac(),yh=An(),uM=(t,n,i={})=>{if(t===n)return!0;t=new ov(t,i),n=new ov(n,i);let o=!1;e:for(let a of t.set){for(let c of n.set){let m=fM(a,c,i);if(o=o||m!==null,m)continue e}if(o)return!1}return!0},dM=[new gh(">=0.0.0-0")],av=[new gh(">=0.0.0")],fM=(t,n,i)=>{if(t===n)return!0;if(t.length===1&&t[0].semver===hh)if(n.length===1&&n[0].semver===hh)return!0;else if(i.includePrerelease)t=dM;else t=av;if(n.length===1&&n[0].semver===hh)if(i.includePrerelease)return!0;else n=av;let o=new Set,a,c;for(let M of t)if(M.operator===">"||M.operator===">=")a=cv(a,M,i);else if(M.operator==="<"||M.operator==="<=")c=lv(c,M,i);else o.add(M.semver);if(o.size>1)return null;let m;if(a&&c){if(m=yh(a.semver,c.semver,i),m>0)return null;else if(m===0&&(a.operator!==">="||c.operator!=="<="))return null}for(let M of o){if(a&&!mh(M,String(a),i))return null;if(c&&!mh(M,String(c),i))return null;for(let N of n)if(!mh(M,String(N),i))return!1;return!0}let E,_,I,T,R=c&&!i.includePrerelease&&c.semver.prerelease.length?c.semver:!1,P=a&&!i.includePrerelease&&a.semver.prerelease.length?a.semver:!1;if(R&&R.prerelease.length===1&&c.operator==="<"&&R.prerelease[0]===0)R=!1;for(let M of n){if(T=T||M.operator===">"||M.operator===">=",I=I||M.operator==="<"||M.operator==="<=",a){if(P){if(M.semver.prerelease&&M.semver.prerelease.length&&M.semver.major===P.major&&M.semver.minor===P.minor&&M.semver.patch===P.patch)P=!1}if(M.operator===">"||M.operator===">="){if(E=cv(a,M,i),E===M&&E!==a)return!1}else if(a.operator===">="&&!M.test(a.semver))return!1}if(c){if(R){if(M.semver.prerelease&&M.semver.prerelease.length&&M.semver.major===R.major&&M.semver.minor===R.minor&&M.semver.patch===R.patch)R=!1}if(M.operator==="<"||M.operator==="<="){if(_=lv(c,M,i),_===M&&_!==c)return!1}else if(c.operator==="<="&&!M.test(c.semver))return!1}if(!M.operator&&(c||a)&&m!==0)return!1}if(a&&I&&!c&&m!==0)return!1;if(c&&T&&!a&&m!==0)return!1;if(P||R)return!1;return!0},cv=(t,n,i)=>{if(!t)return n;let o=yh(t.semver,n.semver,i);return o>0?t:o<0?n:n.operator===">"&&t.operator===">="?n:t},lv=(t,n,i)=>{if(!t)return n;let o=yh(t.semver,n.semver,i);return o<0?t:o>0?n:n.operator==="<"&&t.operator==="<="?n:t};uv.exports=uM});var pv=e(function(n9,fv){var ba=Sa(),Ou=wa(),pM=fr(),ku=oh(),hM=so(),mM=$b(),gM=Lb(),yM=Fb(),wM=Wb(),SM=Vb(),bM=Gb(),vM=Jb(),EM=Xb(),AM=An(),xM=t0(),_M=n0(),IM=Eu(),TM=a0(),RM=l0(),PM=Sc(),CM=Au(),OM=ch(),kM=lh(),MM=xu(),NM=_u(),$M=uh(),DM=w0(),LM=v0(),jM=vc(),UM=_n(),FM=Ac(),qM=L0(),BM=U0(),WM=q0(),HM=H0(),VM=z0(),zM=Cu(),GM=Z0(),KM=ev(),JM=nv(),YM=iv(),XM=dv();fv.exports={parse:hM,valid:mM,clean:gM,inc:yM,diff:wM,major:SM,minor:bM,patch:vM,prerelease:EM,compare:AM,rcompare:xM,compareLoose:_M,compareBuild:IM,sort:TM,rsort:RM,gt:PM,lt:CM,eq:OM,neq:kM,gte:MM,lte:NM,cmp:$M,coerce:DM,truncate:LM,Comparator:jM,Range:UM,satisfies:FM,toComparators:qM,maxSatisfying:BM,minSatisfying:WM,minVersion:HM,validRange:VM,outside:zM,gtr:GM,ltr:KM,intersects:JM,simplifyRange:YM,subset:XM,SemVer:pM,re:ba.re,src:ba.src,tokens:ba.t,SEMVER_SPEC_VERSION:Ou.SEMVER_SPEC_VERSION,RELEASE_TYPES:Ou.RELEASE_TYPES,compareIdentifiers:ku.compareIdentifiers,rcompareIdentifiers:ku.rcompareIdentifiers}});import{rm as K$}from"fs/promises";import{dirname as J$,join as Y$}from"path";var $c=new Map;function Dc(t){return{type:"agent-activity:changed",agentIds:Array.from($c.get(t)?.keys()??[],qi)}}function gA(t,n){let i=$c.get(t)??new Map,o=i.get(n);clearTimeout(o);let a=setTimeout(()=>{if(i.delete(n),!i.size)$c.delete(t);jn(t,Dc(t))},60000).unref();if(i.set(n,a),$c.set(t,i),!o)jn(t,Dc(t))}function Lc(t,n){let i=n.headers.get("x-moi-user-id");if(i&&/^a_[A-Za-z0-9_-]{43}$/.test(i))gA(t,i)}import{chmod as NA,rm as $A}from"fs/promises";function zh(t){return[t&&gs("algorithms",t.algorithms),t?.crit]}function yA(t){return t===void 0?{}:ys(t,A,"JWS Protected Header is invalid")}function wA(t){try{return de(t)}catch{throw new A("JWS Compact Serialization payload must use only ASCII characters")}}async function SA(t,n,i,o,a){let{protected:c,header:m,payload:E}=t,_=a??yA(c);if(!Fr(_,m))throw new A("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let I={..._,...m},T=Wr(_,jr(A,Br,n[1],_,I)),{alg:R}=I;if(typeof R!="string"||!R)throw new A('JWS "alg" (Algorithm) Header Parameter missing or invalid');if(n[0]&&!n[0].has(R))throw new Un('"alg" (Algorithm) Header Parameter value not allowed');if(T){if(typeof E!="string")throw new A("JWS Payload must be a string")}else if(typeof E!="string"&&!(E instanceof Uint8Array))throw new A("JWS Payload must be a string or an Uint8Array instance");let P=T||typeof E!="string"?E:o(E),M=!1;typeof i=="function"&&(i=await i(_,t),M=!0);let N=Kr(R),H=Rr(c!==void 0?de(c):new Uint8Array,de("."),typeof P=="string"?n[2]??=hs(P,"payload",A):P),Z=Gn(t.signature,"signature",A),V=await Ur(N,i,"verify"),me=await Vr(V,N.subtle,"verify");N.minRsaBits&&zr(N.alg,me);let te=!1;try{te=await crypto.subtle.verify(N.signing,me,Z,H)}catch{}if(!te)throw new Kn;let we={payload:typeof P=="string"?Gn(P,"payload",A):P};return c!==void 0&&(we.protectedHeader=_),m!==void 0&&(we.unprotectedHeader=m),M?[{...we,key:V},T]:[we,T]}async function Gh(t,n,i){if(t instanceof Uint8Array&&(t=kr.decode(t)),typeof t!="string")throw new A("Compact JWS must be a string or Uint8Array");let{0:o,1:a,2:c,length:m}=t.split(".");if(m!==3)throw new A("Invalid Compact JWS");return SA({payload:a,protected:o,signature:c},n,i,wA)}async function Kh(t,n,i){let[o,a]=await Gh(t,zh(i),n);if(!a)throw new Y("JWTs MUST NOT use unencoded payload");let c=_s(o.protectedHeader,o.payload,i);return{...o,payload:c}}function bA(t,n,i,o){let{kty:a,key_ops:c,ext:m,kid:E,alg:_,use:I,crv:T}=t;return(m===void 0||typeof m=="boolean")&&(c===void 0||Array.isArray(c)&&c.every((R,P)=>typeof R=="string"&&c.indexOf(R)===P)&&c.includes("verify"))&&n.kty.includes(a)&&(o===void 0||typeof o=="string"&&o===E)&&(_===void 0?a!=="AKP":i===_)&&(I===void 0||I==="sig")&&(!n.crv||T===n.crv)}async function Jh(t,n,i){let o=t.get(n)||t.set(n,{}).get(n),{alg:a}=i;if(o[a]===void 0){let c=yt(i,n,!0).then((m)=>{if(m.type!=="public")throw new Lr("JSON Web Key Set members must be public keys");return o[a]=m,m}).catch((m)=>{throw o[a]===c&&delete o[a],m});o[a]=c}return o[a]}function ld(t){let n;try{n=structuredClone(t)}catch{}if(!Mr(n))throw new Lr("JSON Web Key Set malformed");let i=n.keys.map((a)=>{let c=ht(a);return Array.isArray(c.key_ops)&&(c.key_ops=[...c.key_ops]),c}),o=new WeakMap;return Object.defineProperty(async(a,c)=>{let{alg:m,kid:E}={...a,...c?.header},_=typeof m=="string"?$t[m]:void 0;if(!_||_.secret)throw new L('Unsupported "alg" value for a JSON Web Key Set');let I=n.keys.filter((P,M)=>bA(i[M],_,m,E)),{0:T,length:R}=I;if(!R)throw new Gt;if(R!==1){let P=new zn;throw P[Symbol.asyncIterator]=async function*(){for(let M of I)try{yield await Jh(o,M,_)}catch{}},P}return Jh(o,T,_)},"jwks",{value:()=>structuredClone(n)})}function vA(){return typeof WebSocketPair<"u"||typeof navigator<"u"&&navigator.userAgent==="Cloudflare-Workers"||typeof EdgeRuntime<"u"&&EdgeRuntime==="vercel"}var ud;(typeof navigator>"u"||!navigator.userAgent?.startsWith?.("Mozilla/5.0 "))&&(ud="jose/v6.2.12");var dd=Symbol();async function EA(t,n,i,o=fetch){let a=await o(t,{method:"GET",signal:i,redirect:"manual",headers:n}).catch((c)=>{throw c.name==="TimeoutError"?new Vn:c});if(a.status!==200)throw new G("Expected 200 OK from the JSON Web Key Set HTTP response");try{return await a.json()}catch{throw new G("Failed to parse the JSON Web Key Set HTTP response as JSON")}}var AA=Symbol();function Pa(t,n){return Number.isFinite(t)&&Date.now()<t+n}function Yh(t,n,i){if(Number.isNaN(t))throw TypeError(`"${i}" option must not be NaN`);return typeof t=="number"?t:n}function Xh(t,n){if(!(t instanceof URL))throw TypeError("url must be an instance of URL");let i=new URL(t.href).href,o=n??{},a=o.timeoutDuration;if(typeof a=="number"&&(!Number.isInteger(a)||a<0))throw TypeError('"timeoutDuration" option must be a non-negative integer');let c=typeof a=="number"?a:5000,m=Yh(o.cooldownDuration,30000,"cooldownDuration"),E=Yh(o.cacheMaxAge,600000,"cacheMaxAge"),_=new Headers(o.headers);ud&&!_.has("User-Agent")&&_.set("User-Agent",ud),_.has("accept")||_.set("accept","application/json, application/jwk-set+json");let I=o[dd],T=o[AA],R,P,M=0,N=0,H;if(T&&typeof T=="object"){let{uat:V,jwks:me}=T;Pa(V,E)&&Mr(me)&&(R=V,H=ld(me))}let Z=async()=>{if(P&&vA()&&(P=void 0),!P){let V=++M,me=P=EA(i,_,AbortSignal.timeout(c),I).then((te)=>{let we=ld(te);if(V<=N)return;H=we;let Te=Date.now();T&&(T.uat=Te,T.jwks=te),R=Te,N=V}).finally(()=>{P===me&&(P=void 0)})}await P};return Object.defineProperties(async(V,me)=>{(!H||!Pa(R,E))&&await Z();try{return await H(V,me)}catch(te){if(te instanceof Gt&&!Pa(R,m))return await Z(),H(V,me);throw te}},{coolingDown:{get:()=>Pa(R,m),enumerable:!0},fresh:{get:()=>Pa(R,E),enumerable:!0},reload:{value:Z,enumerable:!0},reloading:{get:()=>!!P,enumerable:!0},jwks:{value:()=>H?.jwks(),enumerable:!0}})}import{constants as jc}from"fs";import{lstat as fd,mkdir as xA,open as _A,realpath as IA,rename as TA,rm as RA}from"fs/promises";import{dirname as PA,isAbsolute as Zh,relative as Qh,resolve as pd,sep as em}from"path";class bt extends Error{status;constructor(t,n=400){super(t);this.status=n}}var CA=new be;function OA(t,n){let i=Qh(t,n);return i!==""&&i!==".."&&!i.startsWith(`..${em}`)&&!Zh(i)}async function Uc(t,n,i=!1){if(!n||Zh(n)||n.includes("\\")||n.includes("\x00")||n.split("/").some((m)=>m===".."||m==="."))throw new bt("Use a file path relative to the workspace");t=await IA(t);let o=pd(t,n);if(!OA(t,o))throw new bt("File is outside the workspace");let a=t,c=Qh(t,o).split(em);for(let[m,E]of c.entries()){a=pd(a,E);try{let _=await fd(a);if(_.isSymbolicLink())throw new bt("Symbolic links are not supported");if(m<c.length-1&&!_.isDirectory())throw new bt("Parent is not a directory");if(m===c.length-1&&!_.isFile())throw new bt("Path is not a file")}catch(_){if(_.code!=="ENOENT")throw _;if(!i)throw new bt("File not found",404);if(m<c.length-1)await xA(a)}}return o}async function hd(t,n,i,o){return CA.runExclusive(async()=>{let a=await Uc(t,n,!o),c=pd(PA(a),`.moi-write-${crypto.randomUUID()}`),m=436;try{m=(await fd(a)).mode&511}catch{}let E=await _A(c,jc.O_WRONLY|jc.O_CREAT|jc.O_EXCL|jc.O_NOFOLLOW,m);try{if(o){let _=new TextDecoder("utf-8",{fatal:!0}).decode(await Bun.file(a).arrayBuffer());await E.writeFile(o(_))}else for await(let _ of i)await E.writeFile(_);if(await E.close(),await Uc(t,n,!0)!==a)throw new bt("File changed during upload",409);await TA(c,a)}finally{await E.close().catch(()=>{}),await RA(c,{force:!0})}return{ok:!0,bytes:(await fd(a)).size}})}function tm(t,n){let i=t?t.split(`
|
|
2
|
+
import{w,W,ue,qi,We,K,re,Ue,xn,Q,vr,Sr,Tr,Ji,Xi,Yi,Zi,O,Ft,Ve,Qi,es,In,Ke,Cn,d,f,pe,dt,Bt,ft,jt,wn,xr,Dn,Nn,Ar,On,kn,Rn,Ln,Mn,X,ns,Ir,Cr,Ut,zt,is,wr,Qe,Fn,ss,Bn,as,os,ls,cs,Dr,l,us,ps,Me,Vt,Nr,Kt,ds,jn,h,ne,Ae,S,fs,Or,ms,mt,Wn,Pe,kr,Rr,de,G,Un,L,A,Y,Lr,Gt,zn,Vn,Kn,Mr,Fr,Gn,hs,ys,Br,gs,jr,Wr,Ur,zr,ht,yt,Vr,$t,Kr,_s,be,Gr,fe,$n,qt,qn,Hn,ee,qr,xs,As,Yn,$e,Ps,Zn,Hr,U,_t,Ht,Jt,et,Is,Jr,Qn,Cs,ws,Xt,Ds,B,ve,Ie,y,ie,Yt,Yr,z,q,ri,D,ni,Fe,ii}from"./chunk-1drt3wyp.js";import{x,p,Ce,Ms,C,Se,j,v,he}from"./chunk-bf4je23j.js";import"./chunk-vtxbnqhj.js";import{Ri,pr,ye,J,wt,Dt}from"./chunk-m4zx92xc.js";import{it,gi,st,_i,St,ir,Tt,pn,at,sr,bi,Et,xt,Ai,Ii,Ci,wi,Di,Ni,Oi,Pt,le,Ee,xe,ce,Ye}from"./chunk-wgjqjgj9.js";import{ae,nr,ln}from"./chunk-wbzwwpct.js";import{Li,Mi,Fi}from"./chunk-qghmmzct.js";import{Nt}from"./chunk-jrkbyrmq.js";import{Ui,Ki,br,Gi}from"./chunk-q06m17nb.js";import{Fs,r,en,k,u,s,Rs,b,F,nn}from"./chunk-n5c20498.js";import{g,e}from"./chunk-7c0zbz74.js";var Hm=e(function(Bc,Fo){var WA=200,Td="__lodash_hash_undefined__",Yc=1,vm=2,Em=9007199254740991,Wc="[object Arguments]",bd="[object Array]",HA="[object AsyncFunction]",Am="[object Boolean]",xm="[object Date]",_m="[object Error]",Im="[object Function]",VA="[object GeneratorFunction]",Hc="[object Map]",Tm="[object Number]",zA="[object Null]",Uo="[object Object]",um="[object Promise]",GA="[object Proxy]",Rm="[object RegExp]",Vc="[object Set]",Pm="[object String]",KA="[object Symbol]",JA="[object Undefined]",vd="[object WeakMap]",Cm="[object ArrayBuffer]",zc="[object DataView]",YA="[object Float32Array]",XA="[object Float64Array]",ZA="[object Int8Array]",QA="[object Int16Array]",ex="[object Int32Array]",tx="[object Uint8Array]",rx="[object Uint8ClampedArray]",nx="[object Uint16Array]",sx="[object Uint32Array]",ix=/[\\^$.*+?()[\]{}|]/g,ox=/^\[object .+?Constructor\]$/,ax=/^(?:0|[1-9]\d*)$/,ot={};ot[YA]=ot[XA]=ot[ZA]=ot[QA]=ot[ex]=ot[tx]=ot[rx]=ot[nx]=ot[sx]=!0;ot[Wc]=ot[bd]=ot[Cm]=ot[Am]=ot[zc]=ot[xm]=ot[_m]=ot[Im]=ot[Hc]=ot[Tm]=ot[Uo]=ot[Rm]=ot[Vc]=ot[Pm]=ot[vd]=!1;var Om=typeof global=="object"&&global&&global.Object===Object&&global,cx=typeof self=="object"&&self&&self.Object===Object&&self,Js=Om||cx||Function("return this")(),km=typeof Bc=="object"&&Bc&&!Bc.nodeType&&Bc,dm=km&&typeof Fo=="object"&&Fo&&!Fo.nodeType&&Fo,Mm=dm&&dm.exports===km,yd=Mm&&Om.process,fm=function(){try{return yd&&yd.binding&&yd.binding("util")}catch(t){}}(),pm=fm&&fm.isTypedArray;function lx(t,n){var i=-1,o=t==null?0:t.length,a=0,c=[];while(++i<o){var m=t[i];if(n(m,i,t))c[a++]=m}return c}function ux(t,n){var i=-1,o=n.length,a=t.length;while(++i<o)t[a+i]=n[i];return t}function dx(t,n){var i=-1,o=t==null?0:t.length;while(++i<o)if(n(t[i],i,t))return!0;return!1}function fx(t,n){var i=-1,o=Array(t);while(++i<t)o[i]=n(i);return o}function px(t){return function(n){return t(n)}}function hx(t,n){return t.has(n)}function mx(t,n){return t==null?void 0:t[n]}function gx(t){var n=-1,i=Array(t.size);return t.forEach(function(o,a){i[++n]=[a,o]}),i}function yx(t,n){return function(i){return t(n(i))}}function wx(t){var n=-1,i=Array(t.size);return t.forEach(function(o){i[++n]=o}),i}var Sx=Array.prototype,bx=Function.prototype,Xc=Object.prototype,wd=Js["__core-js_shared__"],Nm=bx.toString,Ns=Xc.hasOwnProperty,hm=function(){var t=/[^.]+$/.exec(wd&&wd.keys&&wd.keys.IE_PROTO||"");return t?"Symbol(src)_1."+t:""}(),$m=Xc.toString,vx=RegExp("^"+Nm.call(Ns).replace(ix,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),mm=Mm?Js.Buffer:void 0,{Symbol:Gc,Uint8Array:gm}=Js,Dm=Xc.propertyIsEnumerable,Ex=Sx.splice,lo=Gc?Gc.toStringTag:void 0,ym=Object.getOwnPropertySymbols,Ax=mm?mm.isBuffer:void 0,xx=yx(Object.keys,Object),Ed=qo(Js,"DataView"),Ca=qo(Js,"Map"),Ad=qo(Js,"Promise"),xd=qo(Js,"Set"),_d=qo(Js,"WeakMap"),Oa=qo(Object,"create"),_x=po(Ed),Ix=po(Ca),Tx=po(Ad),Rx=po(xd),Px=po(_d),wm=Gc?Gc.prototype:void 0,Sd=wm?wm.valueOf:void 0;function uo(t){var n=-1,i=t==null?0:t.length;this.clear();while(++n<i){var o=t[n];this.set(o[0],o[1])}}function Cx(){this.__data__=Oa?Oa(null):{},this.size=0}function Ox(t){var n=this.has(t)&&delete this.__data__[t];return this.size-=n?1:0,n}function kx(t){var n=this.__data__;if(Oa){var i=n[t];return i===Td?void 0:i}return Ns.call(n,t)?n[t]:void 0}function Mx(t){var n=this.__data__;return Oa?n[t]!==void 0:Ns.call(n,t)}function Nx(t,n){var i=this.__data__;return this.size+=this.has(t)?0:1,i[t]=Oa&&n===void 0?Td:n,this}uo.prototype.clear=Cx;uo.prototype.delete=Ox;uo.prototype.get=kx;uo.prototype.has=Mx;uo.prototype.set=Nx;function Ys(t){var n=-1,i=t==null?0:t.length;this.clear();while(++n<i){var o=t[n];this.set(o[0],o[1])}}function $x(){this.__data__=[],this.size=0}function Dx(t){var n=this.__data__,i=Zc(n,t);if(i<0)return!1;var o=n.length-1;if(i==o)n.pop();else Ex.call(n,i,1);return--this.size,!0}function Lx(t){var n=this.__data__,i=Zc(n,t);return i<0?void 0:n[i][1]}function jx(t){return Zc(this.__data__,t)>-1}function Ux(t,n){var i=this.__data__,o=Zc(i,t);if(o<0)++this.size,i.push([t,n]);else i[o][1]=n;return this}Ys.prototype.clear=$x;Ys.prototype.delete=Dx;Ys.prototype.get=Lx;Ys.prototype.has=jx;Ys.prototype.set=Ux;function fo(t){var n=-1,i=t==null?0:t.length;this.clear();while(++n<i){var o=t[n];this.set(o[0],o[1])}}function Fx(){this.size=0,this.__data__={hash:new uo,map:new(Ca||Ys),string:new uo}}function qx(t){var n=Qc(this,t).delete(t);return this.size-=n?1:0,n}function Bx(t){return Qc(this,t).get(t)}function Wx(t){return Qc(this,t).has(t)}function Hx(t,n){var i=Qc(this,t),o=i.size;return i.set(t,n),this.size+=i.size==o?0:1,this}fo.prototype.clear=Fx;fo.prototype.delete=qx;fo.prototype.get=Bx;fo.prototype.has=Wx;fo.prototype.set=Hx;function Kc(t){var n=-1,i=t==null?0:t.length;this.__data__=new fo;while(++n<i)this.add(t[n])}function Vx(t){return this.__data__.set(t,Td),this}function zx(t){return this.__data__.has(t)}Kc.prototype.add=Kc.prototype.push=Vx;Kc.prototype.has=zx;function vi(t){var n=this.__data__=new Ys(t);this.size=n.size}function Gx(){this.__data__=new Ys,this.size=0}function Kx(t){var n=this.__data__,i=n.delete(t);return this.size=n.size,i}function Jx(t){return this.__data__.get(t)}function Yx(t){return this.__data__.has(t)}function Xx(t,n){var i=this.__data__;if(i instanceof Ys){var o=i.__data__;if(!Ca||o.length<WA-1)return o.push([t,n]),this.size=++i.size,this;i=this.__data__=new fo(o)}return i.set(t,n),this.size=i.size,this}vi.prototype.clear=Gx;vi.prototype.delete=Kx;vi.prototype.get=Jx;vi.prototype.has=Yx;vi.prototype.set=Xx;function Zx(t,n){var i=Jc(t),o=!i&&p_(t),a=!i&&!o&&Id(t),c=!i&&!o&&!a&&Wm(t),m=i||o||a||c,E=m?fx(t.length,String):[],_=E.length;for(var I in t)if((n||Ns.call(t,I))&&!(m&&(I=="length"||a&&(I=="offset"||I=="parent")||c&&(I=="buffer"||I=="byteLength"||I=="byteOffset")||c_(I,_))))E.push(I);return E}function Zc(t,n){var i=t.length;while(i--)if(Um(t[i][0],n))return i;return-1}function Qx(t,n,i){var o=n(t);return Jc(t)?o:ux(o,i(t))}function Ma(t){if(t==null)return t===void 0?JA:zA;return lo&&lo in Object(t)?o_(t):f_(t)}function Sm(t){return ka(t)&&Ma(t)==Wc}function Lm(t,n,i,o,a){if(t===n)return!0;if(t==null||n==null||!ka(t)&&!ka(n))return t!==t&&n!==n;return e_(t,n,i,o,Lm,a)}function e_(t,n,i,o,a,c){var m=Jc(t),E=Jc(n),_=m?bd:Si(t),I=E?bd:Si(n);_=_==Wc?Uo:_,I=I==Wc?Uo:I;var T=_==Uo,R=I==Uo,P=_==I;if(P&&Id(t)){if(!Id(n))return!1;m=!0,T=!1}if(P&&!T)return c||(c=new vi),m||Wm(t)?jm(t,n,i,o,a,c):s_(t,n,_,i,o,a,c);if(!(i&Yc)){var M=T&&Ns.call(t,"__wrapped__"),N=R&&Ns.call(n,"__wrapped__");if(M||N){var H=M?t.value():t,Z=N?n.value():n;return c||(c=new vi),a(H,Z,i,o,c)}}if(!P)return!1;return c||(c=new vi),i_(t,n,i,o,a,c)}function t_(t){if(!Bm(t)||u_(t))return!1;var n=Fm(t)?vx:ox;return n.test(po(t))}function r_(t){return ka(t)&&qm(t.length)&&!!ot[Ma(t)]}function n_(t){if(!d_(t))return xx(t);var n=[];for(var i in Object(t))if(Ns.call(t,i)&&i!="constructor")n.push(i);return n}function jm(t,n,i,o,a,c){var m=i&Yc,E=t.length,_=n.length;if(E!=_&&!(m&&_>E))return!1;var I=c.get(t);if(I&&c.get(n))return I==n;var T=-1,R=!0,P=i&vm?new Kc:void 0;c.set(t,n),c.set(n,t);while(++T<E){var M=t[T],N=n[T];if(o)var H=m?o(N,M,T,n,t,c):o(M,N,T,t,n,c);if(H!==void 0){if(H)continue;R=!1;break}if(P){if(!dx(n,function(Z,V){if(!hx(P,V)&&(M===Z||a(M,Z,i,o,c)))return P.push(V)})){R=!1;break}}else if(!(M===N||a(M,N,i,o,c))){R=!1;break}}return c.delete(t),c.delete(n),R}function s_(t,n,i,o,a,c,m){switch(i){case zc:if(t.byteLength!=n.byteLength||t.byteOffset!=n.byteOffset)return!1;t=t.buffer,n=n.buffer;case Cm:if(t.byteLength!=n.byteLength||!c(new gm(t),new gm(n)))return!1;return!0;case Am:case xm:case Tm:return Um(+t,+n);case _m:return t.name==n.name&&t.message==n.message;case Rm:case Pm:return t==n+"";case Hc:var E=gx;case Vc:var _=o&Yc;if(E||(E=wx),t.size!=n.size&&!_)return!1;var I=m.get(t);if(I)return I==n;o|=vm,m.set(t,n);var T=jm(E(t),E(n),o,a,c,m);return m.delete(t),T;case KA:if(Sd)return Sd.call(t)==Sd.call(n)}return!1}function i_(t,n,i,o,a,c){var m=i&Yc,E=bm(t),_=E.length,I=bm(n),T=I.length;if(_!=T&&!m)return!1;var R=_;while(R--){var P=E[R];if(!(m?P in n:Ns.call(n,P)))return!1}var M=c.get(t);if(M&&c.get(n))return M==n;var N=!0;c.set(t,n),c.set(n,t);var H=m;while(++R<_){P=E[R];var Z=t[P],V=n[P];if(o)var me=m?o(V,Z,P,n,t,c):o(Z,V,P,t,n,c);if(!(me===void 0?Z===V||a(Z,V,i,o,c):me)){N=!1;break}H||(H=P=="constructor")}if(N&&!H){var te=t.constructor,we=n.constructor;if(te!=we&&(("constructor"in t)&&("constructor"in n))&&!(typeof te=="function"&&te instanceof te&&typeof we=="function"&&we instanceof we))N=!1}return c.delete(t),c.delete(n),N}function bm(t){return Qx(t,g_,a_)}function Qc(t,n){var i=t.__data__;return l_(n)?i[typeof n=="string"?"string":"hash"]:i.map}function qo(t,n){var i=mx(t,n);return t_(i)?i:void 0}function o_(t){var n=Ns.call(t,lo),i=t[lo];try{t[lo]=void 0;var o=!0}catch(c){}var a=$m.call(t);if(o)if(n)t[lo]=i;else delete t[lo];return a}var a_=!ym?y_:function(t){if(t==null)return[];return t=Object(t),lx(ym(t),function(n){return Dm.call(t,n)})},Si=Ma;if(Ed&&Si(new Ed(new ArrayBuffer(1)))!=zc||Ca&&Si(new Ca)!=Hc||Ad&&Si(Ad.resolve())!=um||xd&&Si(new xd)!=Vc||_d&&Si(new _d)!=vd)Si=function(t){var n=Ma(t),i=n==Uo?t.constructor:void 0,o=i?po(i):"";if(o)switch(o){case _x:return zc;case Ix:return Hc;case Tx:return um;case Rx:return Vc;case Px:return vd}return n};function c_(t,n){return n=n==null?Em:n,!!n&&(typeof t=="number"||ax.test(t))&&(t>-1&&t%1==0&&t<n)}function l_(t){var n=typeof t;return n=="string"||n=="number"||n=="symbol"||n=="boolean"?t!=="__proto__":t===null}function u_(t){return!!hm&&hm in t}function d_(t){var n=t&&t.constructor,i=typeof n=="function"&&n.prototype||Xc;return t===i}function f_(t){return $m.call(t)}function po(t){if(t!=null){try{return Nm.call(t)}catch(n){}try{return t+""}catch(n){}}return""}function Um(t,n){return t===n||t!==t&&n!==n}var p_=Sm(function(){return arguments}())?Sm:function(t){return ka(t)&&Ns.call(t,"callee")&&!Dm.call(t,"callee")},Jc=Array.isArray;function h_(t){return t!=null&&qm(t.length)&&!Fm(t)}var Id=Ax||w_;function m_(t,n){return Lm(t,n)}function Fm(t){if(!Bm(t))return!1;var n=Ma(t);return n==Im||n==VA||n==HA||n==GA}function qm(t){return typeof t=="number"&&t>-1&&t%1==0&&t<=Em}function Bm(t){var n=typeof t;return t!=null&&(n=="object"||n=="function")}function ka(t){return t!=null&&typeof t=="object"}var Wm=pm?px(pm):r_;function g_(t){return h_(t)?Zx(t):n_(t)}function y_(){return[]}function w_(){return!1}Fo.exports=m_});var qd=e(function(el,Wo){var S_=200,jd="__lodash_hash_undefined__",tg=1,ol=2,rg=9007199254740991,tl="[object Arguments]",Cd="[object Array]",ng="[object Boolean]",sg="[object Date]",ig="[object Error]",og="[object Function]",b_="[object GeneratorFunction]",rl="[object Map]",ag="[object Number]",Bo="[object Object]",Vm="[object Promise]",cg="[object RegExp]",nl="[object Set]",lg="[object String]",v_="[object Symbol]",Od="[object WeakMap]",ug="[object ArrayBuffer]",sl="[object DataView]",E_="[object Float32Array]",A_="[object Float64Array]",x_="[object Int8Array]",__="[object Int16Array]",I_="[object Int32Array]",T_="[object Uint8Array]",R_="[object Uint8ClampedArray]",P_="[object Uint16Array]",C_="[object Uint32Array]",O_=/[\\^$.*+?()[\]{}|]/g,k_=/^\[object .+?Constructor\]$/,M_=/^(?:0|[1-9]\d*)$/,ct={};ct[E_]=ct[A_]=ct[x_]=ct[__]=ct[I_]=ct[T_]=ct[R_]=ct[P_]=ct[C_]=!0;ct[tl]=ct[Cd]=ct[ug]=ct[ng]=ct[sl]=ct[sg]=ct[ig]=ct[og]=ct[rl]=ct[ag]=ct[Bo]=ct[cg]=ct[nl]=ct[lg]=ct[Od]=!1;var dg=typeof global=="object"&&global&&global.Object===Object&&global,N_=typeof self=="object"&&self&&self.Object===Object&&self,Ti=dg||N_||Function("return this")(),fg=typeof el=="object"&&el&&!el.nodeType&&el,zm=fg&&typeof Wo=="object"&&Wo&&!Wo.nodeType&&Wo,$_=zm&&zm.exports===fg,Gm=$_&&dg.process,Km=function(){try{return Gm&&Gm.binding("util")}catch(t){}}(),Jm=Km&&Km.isTypedArray;function D_(t,n){var i=-1,o=t?t.length:0;while(++i<o)if(n(t[i],i,t))return!0;return!1}function L_(t,n){var i=-1,o=Array(t);while(++i<t)o[i]=n(i);return o}function j_(t){return function(n){return t(n)}}function U_(t,n){return t==null?void 0:t[n]}function kd(t){var n=!1;if(t!=null&&typeof t.toString!="function")try{n=!!(t+"")}catch(i){}return n}function F_(t){var n=-1,i=Array(t.size);return t.forEach(function(o,a){i[++n]=[a,o]}),i}function q_(t,n){return function(i){return t(n(i))}}function B_(t){var n=-1,i=Array(t.size);return t.forEach(function(o){i[++n]=o}),i}var W_=Array.prototype,H_=Function.prototype,al=Object.prototype,Rd=Ti["__core-js_shared__"],Ym=function(){var t=/[^.]+$/.exec(Rd&&Rd.keys&&Rd.keys.IE_PROTO||"");return t?"Symbol(src)_1."+t:""}(),pg=H_.toString,{hasOwnProperty:Xs,toString:Da}=al,V_=RegExp("^"+pg.call(Xs).replace(O_,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),{Symbol:Xm,Uint8Array:Zm}=Ti,z_=al.propertyIsEnumerable,G_=W_.splice,K_=q_(Object.keys,Object),Md=Ho(Ti,"DataView"),Na=Ho(Ti,"Map"),Nd=Ho(Ti,"Promise"),$d=Ho(Ti,"Set"),Dd=Ho(Ti,"WeakMap"),$a=Ho(Object,"create"),J_=go(Md),Y_=go(Na),X_=go(Nd),Z_=go($d),Q_=go(Dd),Qm=Xm?Xm.prototype:void 0,Pd=Qm?Qm.valueOf:void 0;function ho(t){var n=-1,i=t?t.length:0;this.clear();while(++n<i){var o=t[n];this.set(o[0],o[1])}}function eI(){this.__data__=$a?$a(null):{}}function tI(t){return this.has(t)&&delete this.__data__[t]}function rI(t){var n=this.__data__;if($a){var i=n[t];return i===jd?void 0:i}return Xs.call(n,t)?n[t]:void 0}function nI(t){var n=this.__data__;return $a?n[t]!==void 0:Xs.call(n,t)}function sI(t,n){var i=this.__data__;return i[t]=$a&&n===void 0?jd:n,this}ho.prototype.clear=eI;ho.prototype.delete=tI;ho.prototype.get=rI;ho.prototype.has=nI;ho.prototype.set=sI;function Zs(t){var n=-1,i=t?t.length:0;this.clear();while(++n<i){var o=t[n];this.set(o[0],o[1])}}function iI(){this.__data__=[]}function oI(t){var n=this.__data__,i=cl(n,t);if(i<0)return!1;var o=n.length-1;if(i==o)n.pop();else G_.call(n,i,1);return!0}function aI(t){var n=this.__data__,i=cl(n,t);return i<0?void 0:n[i][1]}function cI(t){return cl(this.__data__,t)>-1}function lI(t,n){var i=this.__data__,o=cl(i,t);if(o<0)i.push([t,n]);else i[o][1]=n;return this}Zs.prototype.clear=iI;Zs.prototype.delete=oI;Zs.prototype.get=aI;Zs.prototype.has=cI;Zs.prototype.set=lI;function mo(t){var n=-1,i=t?t.length:0;this.clear();while(++n<i){var o=t[n];this.set(o[0],o[1])}}function uI(){this.__data__={hash:new ho,map:new(Na||Zs),string:new ho}}function dI(t){return ll(this,t).delete(t)}function fI(t){return ll(this,t).get(t)}function pI(t){return ll(this,t).has(t)}function hI(t,n){return ll(this,t).set(t,n),this}mo.prototype.clear=uI;mo.prototype.delete=dI;mo.prototype.get=fI;mo.prototype.has=pI;mo.prototype.set=hI;function il(t){var n=-1,i=t?t.length:0;this.__data__=new mo;while(++n<i)this.add(t[n])}function mI(t){return this.__data__.set(t,jd),this}function gI(t){return this.__data__.has(t)}il.prototype.add=il.prototype.push=mI;il.prototype.has=gI;function xi(t){this.__data__=new Zs(t)}function yI(){this.__data__=new Zs}function wI(t){return this.__data__.delete(t)}function SI(t){return this.__data__.get(t)}function bI(t){return this.__data__.has(t)}function vI(t,n){var i=this.__data__;if(i instanceof Zs){var o=i.__data__;if(!Na||o.length<S_-1)return o.push([t,n]),this;i=this.__data__=new mo(o)}return i.set(t,n),this}xi.prototype.clear=yI;xi.prototype.delete=wI;xi.prototype.get=SI;xi.prototype.has=bI;xi.prototype.set=vI;function EI(t,n){var i=Ld(t)||NI(t)?L_(t.length,String):[],o=i.length,a=!!o;for(var c in t)if((n||Xs.call(t,c))&&!(a&&(c=="length"||CI(c,o))))i.push(c);return i}function cl(t,n){var i=t.length;while(i--)if(gg(t[i][0],n))return i;return-1}function AI(t){return Da.call(t)}function hg(t,n,i,o,a){if(t===n)return!0;if(t==null||n==null||!Ud(t)&&!Fd(n))return t!==t&&n!==n;return xI(t,n,hg,i,o,a)}function xI(t,n,i,o,a,c){var m=Ld(t),E=Ld(n),_=Cd,I=Cd;if(!m)_=Ei(t),_=_==tl?Bo:_;if(!E)I=Ei(n),I=I==tl?Bo:I;var T=_==Bo&&!kd(t),R=I==Bo&&!kd(n),P=_==I;if(P&&!T)return c||(c=new xi),m||LI(t)?mg(t,n,i,o,a,c):RI(t,n,_,i,o,a,c);if(!(a&ol)){var M=T&&Xs.call(t,"__wrapped__"),N=R&&Xs.call(n,"__wrapped__");if(M||N){var H=M?t.value():t,Z=N?n.value():n;return c||(c=new xi),i(H,Z,o,a,c)}}if(!P)return!1;return c||(c=new xi),PI(t,n,i,o,a,c)}function _I(t){if(!Ud(t)||kI(t))return!1;var n=wg(t)||kd(t)?V_:k_;return n.test(go(t))}function II(t){return Fd(t)&&Sg(t.length)&&!!ct[Da.call(t)]}function TI(t){if(!MI(t))return K_(t);var n=[];for(var i in Object(t))if(Xs.call(t,i)&&i!="constructor")n.push(i);return n}function mg(t,n,i,o,a,c){var m=a&ol,E=t.length,_=n.length;if(E!=_&&!(m&&_>E))return!1;var I=c.get(t);if(I&&c.get(n))return I==n;var T=-1,R=!0,P=a&tg?new il:void 0;c.set(t,n),c.set(n,t);while(++T<E){var M=t[T],N=n[T];if(o)var H=m?o(N,M,T,n,t,c):o(M,N,T,t,n,c);if(H!==void 0){if(H)continue;R=!1;break}if(P){if(!D_(n,function(Z,V){if(!P.has(V)&&(M===Z||i(M,Z,o,a,c)))return P.add(V)})){R=!1;break}}else if(!(M===N||i(M,N,o,a,c))){R=!1;break}}return c.delete(t),c.delete(n),R}function RI(t,n,i,o,a,c,m){switch(i){case sl:if(t.byteLength!=n.byteLength||t.byteOffset!=n.byteOffset)return!1;t=t.buffer,n=n.buffer;case ug:if(t.byteLength!=n.byteLength||!o(new Zm(t),new Zm(n)))return!1;return!0;case ng:case sg:case ag:return gg(+t,+n);case ig:return t.name==n.name&&t.message==n.message;case cg:case lg:return t==n+"";case rl:var E=F_;case nl:var _=c&ol;if(E||(E=B_),t.size!=n.size&&!_)return!1;var I=m.get(t);if(I)return I==n;c|=tg,m.set(t,n);var T=mg(E(t),E(n),o,a,c,m);return m.delete(t),T;case v_:if(Pd)return Pd.call(t)==Pd.call(n)}return!1}function PI(t,n,i,o,a,c){var m=a&ol,E=eg(t),_=E.length,I=eg(n),T=I.length;if(_!=T&&!m)return!1;var R=_;while(R--){var P=E[R];if(!(m?P in n:Xs.call(n,P)))return!1}var M=c.get(t);if(M&&c.get(n))return M==n;var N=!0;c.set(t,n),c.set(n,t);var H=m;while(++R<_){P=E[R];var Z=t[P],V=n[P];if(o)var me=m?o(V,Z,P,n,t,c):o(Z,V,P,t,n,c);if(!(me===void 0?Z===V||i(Z,V,o,a,c):me)){N=!1;break}H||(H=P=="constructor")}if(N&&!H){var te=t.constructor,we=n.constructor;if(te!=we&&(("constructor"in t)&&("constructor"in n))&&!(typeof te=="function"&&te instanceof te&&typeof we=="function"&&we instanceof we))N=!1}return c.delete(t),c.delete(n),N}function ll(t,n){var i=t.__data__;return OI(n)?i[typeof n=="string"?"string":"hash"]:i.map}function Ho(t,n){var i=U_(t,n);return _I(i)?i:void 0}var Ei=AI;if(Md&&Ei(new Md(new ArrayBuffer(1)))!=sl||Na&&Ei(new Na)!=rl||Nd&&Ei(Nd.resolve())!=Vm||$d&&Ei(new $d)!=nl||Dd&&Ei(new Dd)!=Od)Ei=function(t){var n=Da.call(t),i=n==Bo?t.constructor:void 0,o=i?go(i):void 0;if(o)switch(o){case J_:return sl;case Y_:return rl;case X_:return Vm;case Z_:return nl;case Q_:return Od}return n};function CI(t,n){return n=n==null?rg:n,!!n&&(typeof t=="number"||M_.test(t))&&(t>-1&&t%1==0&&t<n)}function OI(t){var n=typeof t;return n=="string"||n=="number"||n=="symbol"||n=="boolean"?t!=="__proto__":t===null}function kI(t){return!!Ym&&Ym in t}function MI(t){var n=t&&t.constructor,i=typeof n=="function"&&n.prototype||al;return t===i}function go(t){if(t!=null){try{return pg.call(t)}catch(n){}try{return t+""}catch(n){}}return""}function gg(t,n){return t===n||t!==t&&n!==n}function NI(t){return $I(t)&&Xs.call(t,"callee")&&(!z_.call(t,"callee")||Da.call(t)==tl)}var Ld=Array.isArray;function yg(t){return t!=null&&Sg(t.length)&&!wg(t)}function $I(t){return Fd(t)&&yg(t)}function DI(t,n,i){i=typeof i=="function"?i:void 0;var o=i?i(t,n):void 0;return o===void 0?hg(t,n,i):!!o}function wg(t){var n=Ud(t)?Da.call(t):"";return n==og||n==b_}function Sg(t){return typeof t=="number"&&t>-1&&t%1==0&&t<=rg}function Ud(t){var n=typeof t;return!!t&&(n=="object"||n=="function")}function Fd(t){return!!t&&typeof t=="object"}var LI=Jm?j_(Jm):II;function eg(t){return yg(t)?EI(t):TI(t)}Wo.exports=DI});var xg=e(function(HD,Ag){var Eg="Expected a function",bg=NaN,jI="[object Symbol]",UI=/^\s+|\s+$/g,FI=/^[-+]0x[0-9a-f]+$/i,qI=/^0b[01]+$/i,BI=/^0o[0-7]+$/i,WI=parseInt,HI=typeof global=="object"&&global&&global.Object===Object&&global,VI=typeof self=="object"&&self&&self.Object===Object&&self,zI=HI||VI||Function("return this")(),GI=Object.prototype,KI=GI.toString,{max:JI,min:YI}=Math,Bd=function(){return zI.Date.now()};function XI(t,n,i){var o,a,c,m,E,_,I=0,T=!1,R=!1,P=!0;if(typeof t!="function")throw TypeError(Eg);if(n=vg(n)||0,ul(i))T=!!i.leading,R="maxWait"in i,c=R?JI(vg(i.maxWait)||0,n):c,P="trailing"in i?!!i.trailing:P;function M(De){var je=o,Ct=a;return o=a=void 0,I=De,m=t.apply(Ct,je),m}function N(De){return I=De,E=setTimeout(V,n),T?M(De):m}function H(De){var je=De-_,Ct=De-I,Ot=n-je;return R?YI(Ot,c-Ct):Ot}function Z(De){var je=De-_,Ct=De-I;return _===void 0||je>=n||je<0||R&&Ct>=c}function V(){var De=Bd();if(Z(De))return me(De);E=setTimeout(V,H(De))}function me(De){if(E=void 0,P&&o)return M(De);return o=a=void 0,m}function te(){if(E!==void 0)clearTimeout(E);I=0,o=_=a=E=void 0}function we(){return E===void 0?m:me(Bd())}function Te(){var De=Bd(),je=Z(De);if(o=arguments,a=this,_=De,je){if(E===void 0)return N(_);if(R)return E=setTimeout(V,n),M(_)}if(E===void 0)E=setTimeout(V,n);return m}return Te.cancel=te,Te.flush=we,Te}function ZI(t,n,i){var o=!0,a=!0;if(typeof t!="function")throw TypeError(Eg);if(ul(i))o="leading"in i?!!i.leading:o,a="trailing"in i?!!i.trailing:a;return XI(t,n,{leading:o,maxWait:n,trailing:a})}function ul(t){var n=typeof t;return!!t&&(n=="object"||n=="function")}function QI(t){return!!t&&typeof t=="object"}function eT(t){return typeof t=="symbol"||QI(t)&&KI.call(t)==jI}function vg(t){if(typeof t=="number")return t;if(eT(t))return bg;if(ul(t)){var n=typeof t.valueOf=="function"?t.valueOf():t;t=ul(n)?n+"":n}if(typeof t!="string")return t===0?t:+t;t=t.replace(UI,"");var i=qI.test(t);return i||BI.test(t)?WI(t.slice(2),i?2:8):FI.test(t)?bg:+t}Ag.exports=ZI});var Og=e(function(VD,Cg){var tT=200,Vd="__lodash_hash_undefined__",rT=1/0,nT="[object Function]",sT="[object GeneratorFunction]",iT=/[\\^$.*+?()[\]{}|]/g,oT=/^\[object .+?Constructor\]$/,aT=typeof global=="object"&&global&&global.Object===Object&&global,cT=typeof self=="object"&&self&&self.Object===Object&&self,zd=aT||cT||Function("return this")();function lT(t,n){var i=t?t.length:0;return!!i&&fT(t,n,0)>-1}function uT(t,n,i){var o=-1,a=t?t.length:0;while(++o<a)if(i(n,t[o]))return!0;return!1}function dT(t,n,i,o){var a=t.length,c=i+(o?1:-1);while(o?c--:++c<a)if(n(t[c],c,t))return c;return-1}function fT(t,n,i){if(n!==n)return dT(t,pT,i);var o=i-1,a=t.length;while(++o<a)if(t[o]===n)return o;return-1}function pT(t){return t!==t}function hT(t,n){return t.has(n)}function mT(t,n){return t==null?void 0:t[n]}function gT(t){var n=!1;if(t!=null&&typeof t.toString!="function")try{n=!!(t+"")}catch(i){}return n}function Ig(t){var n=-1,i=Array(t.size);return t.forEach(function(o){i[++n]=o}),i}var yT=Array.prototype,wT=Function.prototype,Tg=Object.prototype,Wd=zd["__core-js_shared__"],_g=function(){var t=/[^.]+$/.exec(Wd&&Wd.keys&&Wd.keys.IE_PROTO||"");return t?"Symbol(src)_1."+t:""}(),Rg=wT.toString,{hasOwnProperty:Gd,toString:ST}=Tg,bT=RegExp("^"+Rg.call(Gd).replace(iT,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),vT=yT.splice,ET=Kd(zd,"Map"),Hd=Kd(zd,"Set"),La=Kd(Object,"create");function yo(t){var n=-1,i=t?t.length:0;this.clear();while(++n<i){var o=t[n];this.set(o[0],o[1])}}function AT(){this.__data__=La?La(null):{}}function xT(t){return this.has(t)&&delete this.__data__[t]}function _T(t){var n=this.__data__;if(La){var i=n[t];return i===Vd?void 0:i}return Gd.call(n,t)?n[t]:void 0}function IT(t){var n=this.__data__;return La?n[t]!==void 0:Gd.call(n,t)}function TT(t,n){var i=this.__data__;return i[t]=La&&n===void 0?Vd:n,this}yo.prototype.clear=AT;yo.prototype.delete=xT;yo.prototype.get=_T;yo.prototype.has=IT;yo.prototype.set=TT;function Vo(t){var n=-1,i=t?t.length:0;this.clear();while(++n<i){var o=t[n];this.set(o[0],o[1])}}function RT(){this.__data__=[]}function PT(t){var n=this.__data__,i=fl(n,t);if(i<0)return!1;var o=n.length-1;if(i==o)n.pop();else vT.call(n,i,1);return!0}function CT(t){var n=this.__data__,i=fl(n,t);return i<0?void 0:n[i][1]}function OT(t){return fl(this.__data__,t)>-1}function kT(t,n){var i=this.__data__,o=fl(i,t);if(o<0)i.push([t,n]);else i[o][1]=n;return this}Vo.prototype.clear=RT;Vo.prototype.delete=PT;Vo.prototype.get=CT;Vo.prototype.has=OT;Vo.prototype.set=kT;function zo(t){var n=-1,i=t?t.length:0;this.clear();while(++n<i){var o=t[n];this.set(o[0],o[1])}}function MT(){this.__data__={hash:new yo,map:new(ET||Vo),string:new yo}}function NT(t){return pl(this,t).delete(t)}function $T(t){return pl(this,t).get(t)}function DT(t){return pl(this,t).has(t)}function LT(t,n){return pl(this,t).set(t,n),this}zo.prototype.clear=MT;zo.prototype.delete=NT;zo.prototype.get=$T;zo.prototype.has=DT;zo.prototype.set=LT;function dl(t){var n=-1,i=t?t.length:0;this.__data__=new zo;while(++n<i)this.add(t[n])}function jT(t){return this.__data__.set(t,Vd),this}function UT(t){return this.__data__.has(t)}dl.prototype.add=dl.prototype.push=jT;dl.prototype.has=UT;function fl(t,n){var i=t.length;while(i--)if(GT(t[i][0],n))return i;return-1}function FT(t){if(!Pg(t)||HT(t))return!1;var n=KT(t)||gT(t)?bT:oT;return n.test(VT(t))}function qT(t,n,i){var o=-1,a=lT,c=t.length,m=!0,E=[],_=E;if(i)m=!1,a=uT;else if(c>=tT){var I=n?null:BT(t);if(I)return Ig(I);m=!1,a=hT,_=new dl}else _=n?[]:E;e:while(++o<c){var T=t[o],R=n?n(T):T;if(T=i||T!==0?T:0,m&&R===R){var P=_.length;while(P--)if(_[P]===R)continue e;if(n)_.push(R);E.push(T)}else if(!a(_,R,i)){if(_!==E)_.push(R);E.push(T)}}return E}var BT=!(Hd&&1/Ig(new Hd([,-0]))[1]==rT)?JT:function(t){return new Hd(t)};function pl(t,n){var i=t.__data__;return WT(n)?i[typeof n=="string"?"string":"hash"]:i.map}function Kd(t,n){var i=mT(t,n);return FT(i)?i:void 0}function WT(t){var n=typeof t;return n=="string"||n=="number"||n=="symbol"||n=="boolean"?t!=="__proto__":t===null}function HT(t){return!!_g&&_g in t}function VT(t){if(t!=null){try{return Rg.call(t)}catch(n){}try{return t+""}catch(n){}}return""}function zT(t){return t&&t.length?qT(t):[]}function GT(t,n){return t===n||t!==t&&n!==n}function KT(t){var n=Pg(t)?ST.call(t):"";return n==nT||n==sT}function Pg(t){var n=typeof t;return!!t&&(n=="object"||n=="function")}function JT(){}Cg.exports=zT});var Zp=e(function(NS){Object.defineProperty(NS,"__esModule",{value:!0});NS.dynamicAnchor=void 0;var ga=d(),SP=pe(),uu=jt(),kS=xr(),bP={keyword:"$dynamicAnchor",schemaType:"string",code:(t)=>MS(t,t.schema)};function MS(t,n){let{gen:i,it:o}=t;o.schemaEnv.root.dynamicAnchors[n]=!0;let a=ga._`${SP.default.dynamicAnchors}${ga.getProperty(n)}`,c=o.errSchemaPath==="#"?o.validateName:vP(t);i.if(ga._`!${a}`,()=>i.assign(a,c))}NS.dynamicAnchor=MS;function vP(t){let{schemaEnv:n,schema:i,self:o}=t.it,{root:a,baseId:c,localRefs:m,meta:E}=n.root,{schemaId:_}=o.opts,I=new uu.SchemaEnv({schema:i,schemaId:_,root:a,baseId:c,localRefs:m,meta:E});return uu.compileSchema.call(o,I),kS.getValidate(t,I)}NS.default=bP});var Qp=e(function(LS){Object.defineProperty(LS,"__esModule",{value:!0});LS.dynamicRef=void 0;var du=d(),AP=pe(),fu=xr(),xP={keyword:"$dynamicRef",schemaType:"string",code:(t)=>DS(t,t.schema)};function DS(t,n){let{gen:i,keyword:o,it:a}=t;if(n[0]!=="#")throw Error(`"${o}" only supports hash fragment reference`);let c=n.slice(1);if(a.allErrors)m();else{let _=i.let("valid",!1);m(_),t.ok(_)}function m(_){if(a.schemaEnv.root.dynamicAnchors[c]){let I=i.let("_v",du._`${AP.default.dynamicAnchors}${du.getProperty(c)}`);i.if(I,E(I,_),E(a.validateName,_))}else E(a.validateName,_)()}function E(_,I){return I?()=>i.block(()=>{fu.callRef(t,_),i.let(I,!0)}):()=>fu.callRef(t,_)}}LS.dynamicRef=DS;LS.default=xP});var BS=e(function(qS){Object.defineProperty(qS,"__esModule",{value:!0});var US=Zp(),FS=f(),IP={keyword:"$recursiveAnchor",schemaType:"boolean",code(t){if(t.schema)US.dynamicAnchor(t,"");else FS.checkStrictMode(t.it,"$recursiveAnchor: false is ignored")}};qS.default=IP});var VS=e(function(HS){Object.defineProperty(HS,"__esModule",{value:!0});var WS=Qp(),RP={keyword:"$recursiveRef",schemaType:"string",code:(t)=>WS.dynamicRef(t,t.schema)};HS.default=RP});var GS=e(function(zS){Object.defineProperty(zS,"__esModule",{value:!0});var CP=Zp(),OP=Qp(),kP=BS(),MP=VS(),NP=[CP.default,OP.default,kP.default,MP.default];zS.default=NP});var JS=e(function(KS){Object.defineProperty(KS,"__esModule",{value:!0});var pu=Ar(),DP={keyword:"dependentRequired",type:"object",schemaType:"object",error:pu.error,code:(t)=>pu.validatePropertyDeps(t)};KS.default=DP});var ZS=e(function(XS){Object.defineProperty(XS,"__esModule",{value:!0});var YS=Ar(),jP={keyword:"dependentSchemas",type:"object",schemaType:"object",code:(t)=>YS.validateSchemaDeps(t)};XS.default=jP});var tb=e(function(eb){Object.defineProperty(eb,"__esModule",{value:!0});var QS=f(),FP={keyword:["maxContains","minContains"],type:"array",schemaType:"number",code({keyword:t,parentSchema:n,it:i}){if(n.contains===void 0)QS.checkStrictMode(i,`"${t}" without "contains" is ignored`)}};eb.default=FP});var nb=e(function(rb){Object.defineProperty(rb,"__esModule",{value:!0});var BP=JS(),WP=ZS(),HP=tb(),VP=[BP.default,WP.default,HP.default];rb.default=VP});var ib=e(function(sb){Object.defineProperty(sb,"__esModule",{value:!0});var _r=d(),hu=f(),GP=pe(),KP={message:"must NOT have unevaluated properties",params:({params:t})=>_r._`{unevaluatedProperty: ${t.unevaluatedProperty}}`},JP={keyword:"unevaluatedProperties",type:"object",schemaType:["boolean","object"],trackErrors:!0,error:KP,code(t){let{gen:n,schema:i,data:o,errsCount:a,it:c}=t;if(!a)throw Error("ajv implementation error");let{allErrors:m,props:E}=c;if(E instanceof _r.Name)n.if(_r._`${E} !== true`,()=>n.forIn("key",o,(R)=>n.if(I(E,R),()=>_(R))));else if(E!==!0)n.forIn("key",o,(R)=>E===void 0?_(R):n.if(T(E,R),()=>_(R)));c.props=!0,t.ok(_r._`${a} === ${GP.default.errors}`);function _(R){if(i===!1){if(t.setParams({unevaluatedProperty:R}),t.error(),!m)n.break();return}if(!hu.alwaysValidSchema(c,i)){let P=n.name("valid");if(t.subschema({keyword:"unevaluatedProperties",dataProp:R,dataPropType:hu.Type.Str},P),!m)n.if(_r.not(P),()=>n.break())}}function I(R,P){return _r._`!${R} || !${R}[${P}]`}function T(R,P){let M=[];for(let N in R)if(R[N]===!0)M.push(_r._`${P} !== ${N}`);return _r.and(...M)}}};sb.default=JP});var ab=e(function(ob){Object.defineProperty(ob,"__esModule",{value:!0});var an=d(),mu=f(),XP={message:({params:{len:t}})=>an.str`must NOT have more than ${t} items`,params:({params:{len:t}})=>an._`{limit: ${t}}`},ZP={keyword:"unevaluatedItems",type:"array",schemaType:["boolean","object"],error:XP,code(t){let{gen:n,schema:i,data:o,it:a}=t,c=a.items||0;if(c===!0)return;let m=n.const("len",an._`${o}.length`);if(i===!1)t.setParams({len:c}),t.fail(an._`${m} > ${c}`);else if(typeof i=="object"&&!mu.alwaysValidSchema(a,i)){let _=n.var("valid",an._`${m} <= ${c}`);n.if(an.not(_),()=>E(_,c)),t.ok(_)}a.items=!0;function E(_,I){n.forRange("i",I,m,(T)=>{if(t.subschema({keyword:"unevaluatedItems",dataProp:T,dataPropType:mu.Type.Num},_),!a.allErrors)n.if(an.not(_),()=>n.break())})}}};ob.default=ZP});var lb=e(function(cb){Object.defineProperty(cb,"__esModule",{value:!0});var eC=ib(),tC=ab(),rC=[eC.default,tC.default];cb.default=rC});var db=e(function(ub){Object.defineProperty(ub,"__esModule",{value:!0});var sC=Dn(),iC=Nn(),oC=On(),aC=GS(),cC=nb(),lC=lb(),uC=kn(),gu=Rn(),dC=[aC.default,sC.default,iC.default,(0,oC.default)(!0),uC.default,gu.metadataVocabulary,gu.contentVocabulary,cC.default,lC.default];ub.default=dC});var fb=e(function(GV,pC){pC.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/schema",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/core":!0,"https://json-schema.org/draft/2020-12/vocab/applicator":!0,"https://json-schema.org/draft/2020-12/vocab/unevaluated":!0,"https://json-schema.org/draft/2020-12/vocab/validation":!0,"https://json-schema.org/draft/2020-12/vocab/meta-data":!0,"https://json-schema.org/draft/2020-12/vocab/format-annotation":!0,"https://json-schema.org/draft/2020-12/vocab/content":!0},$dynamicAnchor:"meta",title:"Core and Validation specifications meta-schema",allOf:[{$ref:"meta/core"},{$ref:"meta/applicator"},{$ref:"meta/unevaluated"},{$ref:"meta/validation"},{$ref:"meta/meta-data"},{$ref:"meta/format-annotation"},{$ref:"meta/content"}],type:["object","boolean"],$comment:"This meta-schema also defines keywords that have appeared in previous drafts in order to prevent incompatible extensions as they remain in common use.",properties:{definitions:{$comment:'"definitions" has been replaced by "$defs".',type:"object",additionalProperties:{$dynamicRef:"#meta"},deprecated:!0,default:{}},dependencies:{$comment:'"dependencies" has been split and replaced by "dependentSchemas" and "dependentRequired" in order to serve their differing semantics.',type:"object",additionalProperties:{anyOf:[{$dynamicRef:"#meta"},{$ref:"meta/validation#/$defs/stringArray"}]},deprecated:!0,default:{}},$recursiveAnchor:{$comment:'"$recursiveAnchor" has been replaced by "$dynamicAnchor".',$ref:"meta/core#/$defs/anchorString",deprecated:!0},$recursiveRef:{$comment:'"$recursiveRef" has been replaced by "$dynamicRef".',$ref:"meta/core#/$defs/uriReferenceString",deprecated:!0}}}});var pb=e(function(KV,hC){hC.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/applicator",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/applicator":!0},$dynamicAnchor:"meta",title:"Applicator vocabulary meta-schema",type:["object","boolean"],properties:{prefixItems:{$ref:"#/$defs/schemaArray"},items:{$dynamicRef:"#meta"},contains:{$dynamicRef:"#meta"},additionalProperties:{$dynamicRef:"#meta"},properties:{type:"object",additionalProperties:{$dynamicRef:"#meta"},default:{}},patternProperties:{type:"object",additionalProperties:{$dynamicRef:"#meta"},propertyNames:{format:"regex"},default:{}},dependentSchemas:{type:"object",additionalProperties:{$dynamicRef:"#meta"},default:{}},propertyNames:{$dynamicRef:"#meta"},if:{$dynamicRef:"#meta"},then:{$dynamicRef:"#meta"},else:{$dynamicRef:"#meta"},allOf:{$ref:"#/$defs/schemaArray"},anyOf:{$ref:"#/$defs/schemaArray"},oneOf:{$ref:"#/$defs/schemaArray"},not:{$dynamicRef:"#meta"}},$defs:{schemaArray:{type:"array",minItems:1,items:{$dynamicRef:"#meta"}}}}});var hb=e(function(JV,mC){mC.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/unevaluated",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/unevaluated":!0},$dynamicAnchor:"meta",title:"Unevaluated applicator vocabulary meta-schema",type:["object","boolean"],properties:{unevaluatedItems:{$dynamicRef:"#meta"},unevaluatedProperties:{$dynamicRef:"#meta"}}}});var mb=e(function(YV,gC){gC.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/content",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/content":!0},$dynamicAnchor:"meta",title:"Content vocabulary meta-schema",type:["object","boolean"],properties:{contentEncoding:{type:"string"},contentMediaType:{type:"string"},contentSchema:{$dynamicRef:"#meta"}}}});var gb=e(function(XV,yC){yC.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/core",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/core":!0},$dynamicAnchor:"meta",title:"Core vocabulary meta-schema",type:["object","boolean"],properties:{$id:{$ref:"#/$defs/uriReferenceString",$comment:"Non-empty fragments not allowed.",pattern:"^[^#]*#?$"},$schema:{$ref:"#/$defs/uriString"},$ref:{$ref:"#/$defs/uriReferenceString"},$anchor:{$ref:"#/$defs/anchorString"},$dynamicRef:{$ref:"#/$defs/uriReferenceString"},$dynamicAnchor:{$ref:"#/$defs/anchorString"},$vocabulary:{type:"object",propertyNames:{$ref:"#/$defs/uriString"},additionalProperties:{type:"boolean"}},$comment:{type:"string"},$defs:{type:"object",additionalProperties:{$dynamicRef:"#meta"}}},$defs:{anchorString:{type:"string",pattern:"^[A-Za-z_][-A-Za-z0-9._]*$"},uriString:{type:"string",format:"uri"},uriReferenceString:{type:"string",format:"uri-reference"}}}});var yb=e(function(ZV,wC){wC.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/format-annotation",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/format-annotation":!0},$dynamicAnchor:"meta",title:"Format vocabulary meta-schema for annotation results",type:["object","boolean"],properties:{format:{type:"string"}}}});var wb=e(function(QV,SC){SC.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/meta-data",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/meta-data":!0},$dynamicAnchor:"meta",title:"Meta-data vocabulary meta-schema",type:["object","boolean"],properties:{title:{type:"string"},description:{type:"string"},default:!0,deprecated:{type:"boolean",default:!1},readOnly:{type:"boolean",default:!1},writeOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0}}}});var Sb=e(function(ez,bC){bC.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/validation",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/validation":!0},$dynamicAnchor:"meta",title:"Validation vocabulary meta-schema",type:["object","boolean"],properties:{type:{anyOf:[{$ref:"#/$defs/simpleTypes"},{type:"array",items:{$ref:"#/$defs/simpleTypes"},minItems:1,uniqueItems:!0}]},const:!0,enum:{type:"array",items:!0},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/$defs/nonNegativeInteger"},minLength:{$ref:"#/$defs/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},maxItems:{$ref:"#/$defs/nonNegativeInteger"},minItems:{$ref:"#/$defs/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},maxContains:{$ref:"#/$defs/nonNegativeInteger"},minContains:{$ref:"#/$defs/nonNegativeInteger",default:1},maxProperties:{$ref:"#/$defs/nonNegativeInteger"},minProperties:{$ref:"#/$defs/nonNegativeIntegerDefault0"},required:{$ref:"#/$defs/stringArray"},dependentRequired:{type:"object",additionalProperties:{$ref:"#/$defs/stringArray"}}},$defs:{nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{$ref:"#/$defs/nonNegativeInteger",default:0},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:!0,default:[]}}}});var vb=e(function(bb){Object.defineProperty(bb,"__esModule",{value:!0});var vC=fb(),EC=pb(),AC=hb(),xC=mb(),_C=gb(),IC=yb(),TC=wb(),RC=Sb(),PC=["/properties"];function CC(t){return[vC,EC,AC,xC,_C,n(this,IC),TC,n(this,RC)].forEach((i)=>this.addMetaSchema(i,void 0,!1)),this;function n(i,o){return t?i.$dataMetaSchema(o,PC):o}}bb.default=CC});var Eb=e(function(cn,th){Object.defineProperty(cn,"__esModule",{value:!0});cn.MissingRefError=cn.ValidationError=cn.CodeGen=cn.Name=cn.nil=cn.stringify=cn.str=cn._=cn.KeywordCxt=cn.Ajv2020=void 0;var kC=wn(),MC=db(),NC=Ln(),$C=vb(),eh="https://json-schema.org/draft/2020-12/schema";class yc extends kC.default{constructor(t={}){super({...t,dynamicRef:!0,next:!0,unevaluated:!0})}_addVocabularies(){if(super._addVocabularies(),MC.default.forEach((t)=>this.addVocabulary(t)),this.opts.discriminator)this.addKeyword(NC.default)}_addDefaultMetaSchema(){super._addDefaultMetaSchema();let{$data:t,meta:n}=this.opts;if(!n)return;$C.default.call(this,t),this.refs["http://json-schema.org/schema"]=eh}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(eh)?eh:void 0)}}cn.Ajv2020=yc;th.exports=cn=yc;th.exports.Ajv2020=yc;Object.defineProperty(cn,"__esModule",{value:!0});cn.default=yc;var DC=dt();Object.defineProperty(cn,"KeywordCxt",{enumerable:!0,get:function(){return DC.KeywordCxt}});var ya=d();Object.defineProperty(cn,"_",{enumerable:!0,get:function(){return ya._}});Object.defineProperty(cn,"str",{enumerable:!0,get:function(){return ya.str}});Object.defineProperty(cn,"stringify",{enumerable:!0,get:function(){return ya.stringify}});Object.defineProperty(cn,"nil",{enumerable:!0,get:function(){return ya.nil}});Object.defineProperty(cn,"Name",{enumerable:!0,get:function(){return ya.Name}});Object.defineProperty(cn,"CodeGen",{enumerable:!0,get:function(){return ya.CodeGen}});var LC=Bt();Object.defineProperty(cn,"ValidationError",{enumerable:!0,get:function(){return LC.default}});var jC=ft();Object.defineProperty(cn,"MissingRefError",{enumerable:!0,get:function(){return jC.default}})});var wa=e(function(pz,Ab){var JC=Number.MAX_SAFE_INTEGER||9007199254740991,YC=["major","premajor","minor","preminor","patch","prepatch","prerelease"];Ab.exports={MAX_LENGTH:256,MAX_SAFE_COMPONENT_LENGTH:16,MAX_SAFE_BUILD_LENGTH:250,MAX_SAFE_INTEGER:JC,RELEASE_TYPES:YC,SEMVER_SPEC_VERSION:"2.0.0",FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2}});var wc=e(function(hz,xb){var XC=typeof process==="object"&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...t)=>console.error("SEMVER",...t):()=>{};xb.exports=XC});var Sa=e(function(zs,_b){var{MAX_SAFE_COMPONENT_LENGTH:sh,MAX_SAFE_BUILD_LENGTH:ZC,MAX_LENGTH:QC}=wa(),eO=wc();zs=_b.exports={};var tO=zs.re=[],rO=zs.safeRe=[],se=zs.src=[],nO=zs.safeSrc=[],oe=zs.t={},sO=0,ih="[a-zA-Z0-9-]",iO=[["\\s",1],["\\d",QC],[ih,ZC]],oO=(t)=>{for(let[n,i]of iO)t=t.split(`${n}*`).join(`${n}{0,${i}}`).split(`${n}+`).join(`${n}{1,${i}}`);return t},Re=(t,n,i)=>{let o=oO(n),a=sO++;eO(t,a,n),oe[t]=a,se[a]=n,nO[a]=o,tO[a]=new RegExp(n,i?"g":void 0),rO[a]=new RegExp(o,i?"g":void 0)};Re("NUMERICIDENTIFIER","0|[1-9]\\d*");Re("NUMERICIDENTIFIERLOOSE","\\d+");Re("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${ih}*`);Re("MAINVERSION",`(${se[oe.NUMERICIDENTIFIER]})\\.(${se[oe.NUMERICIDENTIFIER]})\\.(${se[oe.NUMERICIDENTIFIER]})`);Re("MAINVERSIONLOOSE",`(${se[oe.NUMERICIDENTIFIERLOOSE]})\\.(${se[oe.NUMERICIDENTIFIERLOOSE]})\\.(${se[oe.NUMERICIDENTIFIERLOOSE]})`);Re("PRERELEASEIDENTIFIER",`(?:${se[oe.NONNUMERICIDENTIFIER]}|${se[oe.NUMERICIDENTIFIER]})`);Re("PRERELEASEIDENTIFIERLOOSE",`(?:${se[oe.NONNUMERICIDENTIFIER]}|${se[oe.NUMERICIDENTIFIERLOOSE]})`);Re("PRERELEASE",`(?:-(${se[oe.PRERELEASEIDENTIFIER]}(?:\\.${se[oe.PRERELEASEIDENTIFIER]})*))`);Re("PRERELEASELOOSE",`(?:-?(${se[oe.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${se[oe.PRERELEASEIDENTIFIERLOOSE]})*))`);Re("BUILDIDENTIFIER",`${ih}+`);Re("BUILD",`(?:\\+(${se[oe.BUILDIDENTIFIER]}(?:\\.${se[oe.BUILDIDENTIFIER]})*))`);Re("FULLPLAIN",`v?${se[oe.MAINVERSION]}${se[oe.PRERELEASE]}?${se[oe.BUILD]}?`);Re("FULL",`^${se[oe.FULLPLAIN]}$`);Re("LOOSEPLAIN",`[v=\\s]*${se[oe.MAINVERSIONLOOSE]}${se[oe.PRERELEASELOOSE]}?${se[oe.BUILD]}?`);Re("LOOSE",`^${se[oe.LOOSEPLAIN]}$`);Re("GTLT","((?:<|>)?=?)");Re("XRANGEIDENTIFIERLOOSE",`${se[oe.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`);Re("XRANGEIDENTIFIER",`${se[oe.NUMERICIDENTIFIER]}|x|X|\\*`);Re("XRANGEPLAIN",`[v=\\s]*(${se[oe.XRANGEIDENTIFIER]})(?:\\.(${se[oe.XRANGEIDENTIFIER]})(?:\\.(${se[oe.XRANGEIDENTIFIER]})(?:${se[oe.PRERELEASE]})?${se[oe.BUILD]}?)?)?`);Re("XRANGEPLAINLOOSE",`[v=\\s]*(${se[oe.XRANGEIDENTIFIERLOOSE]})(?:\\.(${se[oe.XRANGEIDENTIFIERLOOSE]})(?:\\.(${se[oe.XRANGEIDENTIFIERLOOSE]})(?:${se[oe.PRERELEASELOOSE]})?${se[oe.BUILD]}?)?)?`);Re("XRANGE",`^${se[oe.GTLT]}\\s*${se[oe.XRANGEPLAIN]}$`);Re("XRANGELOOSE",`^${se[oe.GTLT]}\\s*${se[oe.XRANGEPLAINLOOSE]}$`);Re("COERCEPLAIN",`(^|[^\\d])(\\d{1,${sh}})(?:\\.(\\d{1,${sh}}))?(?:\\.(\\d{1,${sh}}))?`);Re("COERCE",`${se[oe.COERCEPLAIN]}(?:$|[^\\d])`);Re("COERCEFULL",se[oe.COERCEPLAIN]+`(?:${se[oe.PRERELEASE]})?(?:${se[oe.BUILD]})?(?:$|[^\\d])`);Re("COERCERTL",se[oe.COERCE],!0);Re("COERCERTLFULL",se[oe.COERCEFULL],!0);Re("LONETILDE","(?:~>?)");Re("TILDETRIM",`(\\s*)${se[oe.LONETILDE]}\\s+`,!0);zs.tildeTrimReplace="$1~";Re("TILDE",`^${se[oe.LONETILDE]}${se[oe.XRANGEPLAIN]}$`);Re("TILDELOOSE",`^${se[oe.LONETILDE]}${se[oe.XRANGEPLAINLOOSE]}$`);Re("LONECARET","(?:\\^)");Re("CARETTRIM",`(\\s*)${se[oe.LONECARET]}\\s+`,!0);zs.caretTrimReplace="$1^";Re("CARET",`^${se[oe.LONECARET]}${se[oe.XRANGEPLAIN]}$`);Re("CARETLOOSE",`^${se[oe.LONECARET]}${se[oe.XRANGEPLAINLOOSE]}$`);Re("COMPARATORLOOSE",`^${se[oe.GTLT]}\\s*(${se[oe.LOOSEPLAIN]})$|^$`);Re("COMPARATOR",`^${se[oe.GTLT]}\\s*(${se[oe.FULLPLAIN]})$|^$`);Re("COMPARATORTRIM",`(\\s*)${se[oe.GTLT]}\\s*(${se[oe.LOOSEPLAIN]}|${se[oe.XRANGEPLAIN]})`,!0);zs.comparatorTrimReplace="$1$2$3";Re("HYPHENRANGE",`^\\s*(${se[oe.XRANGEPLAIN]})\\s+-\\s+(${se[oe.XRANGEPLAIN]})\\s*$`);Re("HYPHENRANGELOOSE",`^\\s*(${se[oe.XRANGEPLAINLOOSE]})\\s+-\\s+(${se[oe.XRANGEPLAINLOOSE]})\\s*$`);Re("STAR","(<|>)?=?\\s*\\*");Re("GTE0","^\\s*>=\\s*0\\.0\\.0\\s*$");Re("GTE0PRE","^\\s*>=\\s*0\\.0\\.0-0\\s*$")});var yu=e(function(mz,Ib){var aO=Object.freeze({loose:!0}),cO=Object.freeze({}),lO=(t)=>{if(!t)return cO;if(typeof t!=="object")return aO;return t};Ib.exports=lO});var oh=e(function(gz,Pb){var Tb=/^[0-9]+$/,Rb=(t,n)=>{if(typeof t==="number"&&typeof n==="number")return t===n?0:t<n?-1:1;let i=Tb.test(t),o=Tb.test(n);if(i&&o)t=+t,n=+n;return t===n?0:i&&!o?-1:o&&!i?1:t<n?-1:1},uO=(t,n)=>Rb(n,t);Pb.exports={compareIdentifiers:Rb,rcompareIdentifiers:uO}});var fr=e(function(yz,Ob){var wu=wc(),{MAX_LENGTH:Cb,MAX_SAFE_INTEGER:Su}=wa(),{safeRe:bu,t:vu}=Sa(),dO=yu(),{compareIdentifiers:ah}=oh(),fO=(t,n)=>{let i=n.split(".");if(i.length>t.length)return!1;for(let o=0;o<i.length;o++)if(ah(t[o],i[o])!==0)return!1;return!0};class Es{constructor(t,n){if(n=dO(n),t instanceof Es)if(t.loose===!!n.loose&&t.includePrerelease===!!n.includePrerelease)return t;else t=t.version;else if(typeof t!=="string")throw TypeError(`Invalid version. Must be a string. Got type "${typeof t}".`);if(t.length>Cb)throw TypeError(`version is longer than ${Cb} characters`);wu("SemVer",t,n),this.options=n,this.loose=!!n.loose,this.includePrerelease=!!n.includePrerelease;let i=t.trim().match(n.loose?bu[vu.LOOSE]:bu[vu.FULL]);if(!i)throw TypeError(`Invalid Version: ${t}`);if(this.raw=t,this.major=+i[1],this.minor=+i[2],this.patch=+i[3],this.major>Su||this.major<0)throw TypeError("Invalid major version");if(this.minor>Su||this.minor<0)throw TypeError("Invalid minor version");if(this.patch>Su||this.patch<0)throw TypeError("Invalid patch version");if(!i[4])this.prerelease=[];else this.prerelease=i[4].split(".").map((o)=>{if(/^[0-9]+$/.test(o)){let a=+o;if(a>=0&&a<Su)return a}return o});this.build=i[5]?i[5].split("."):[],this.format()}format(){if(this.version=`${this.major}.${this.minor}.${this.patch}`,this.prerelease.length)this.version+=`-${this.prerelease.join(".")}`;return this.version}toString(){return this.version}compare(t){if(wu("SemVer.compare",this.version,this.options,t),!(t instanceof Es)){if(typeof t==="string"&&t===this.version)return 0;t=new Es(t,this.options)}if(t.version===this.version)return 0;return this.compareMain(t)||this.comparePre(t)}compareMain(t){if(!(t instanceof Es))t=new Es(t,this.options);if(this.major<t.major)return-1;if(this.major>t.major)return 1;if(this.minor<t.minor)return-1;if(this.minor>t.minor)return 1;if(this.patch<t.patch)return-1;if(this.patch>t.patch)return 1;return 0}comparePre(t){if(!(t instanceof Es))t=new Es(t,this.options);if(this.prerelease.length&&!t.prerelease.length)return-1;else if(!this.prerelease.length&&t.prerelease.length)return 1;else if(!this.prerelease.length&&!t.prerelease.length)return 0;let n=0;do{let i=this.prerelease[n],o=t.prerelease[n];if(wu("prerelease compare",n,i,o),i===void 0&&o===void 0)return 0;else if(o===void 0)return 1;else if(i===void 0)return-1;else if(i===o)continue;else return ah(i,o)}while(++n)}compareBuild(t){if(!(t instanceof Es))t=new Es(t,this.options);let n=0;do{let i=this.build[n],o=t.build[n];if(wu("build compare",n,i,o),i===void 0&&o===void 0)return 0;else if(o===void 0)return 1;else if(i===void 0)return-1;else if(i===o)continue;else return ah(i,o)}while(++n)}inc(t,n,i){if(t.startsWith("pre")){if(!n&&i===!1)throw Error("invalid increment argument: identifier is empty");if(n){let o=`-${n}`.match(this.options.loose?bu[vu.PRERELEASELOOSE]:bu[vu.PRERELEASE]);if(!o||o[1]!==n)throw Error(`invalid identifier: ${n}`)}}switch(t){case"premajor":this.prerelease.length=0,this.patch=0,this.minor=0,this.major++,this.inc("pre",n,i);break;case"preminor":this.prerelease.length=0,this.patch=0,this.minor++,this.inc("pre",n,i);break;case"prepatch":this.prerelease.length=0,this.inc("patch",n,i),this.inc("pre",n,i);break;case"prerelease":if(this.prerelease.length===0)this.inc("patch",n,i);this.inc("pre",n,i);break;case"release":if(this.prerelease.length===0)throw Error(`version ${this.raw} is not a prerelease`);this.prerelease.length=0;break;case"major":if(this.minor!==0||this.patch!==0||this.prerelease.length===0)this.major++;this.minor=0,this.patch=0,this.prerelease=[];break;case"minor":if(this.patch!==0||this.prerelease.length===0)this.minor++;this.patch=0,this.prerelease=[];break;case"patch":if(this.prerelease.length===0)this.patch++;this.prerelease=[];break;case"pre":{let o=Number(i)?1:0;if(this.prerelease.length===0)this.prerelease=[o];else{let a=this.prerelease.length;while(--a>=0)if(typeof this.prerelease[a]==="number")this.prerelease[a]++,a=-2;if(a===-1){if(n===this.prerelease.join(".")&&i===!1)throw Error("invalid increment argument: identifier already exists");this.prerelease.push(o)}}if(n){let a=[n,o];if(i===!1)a=[n];if(fO(this.prerelease,n)){let c=this.prerelease[n.split(".").length];if(isNaN(c))this.prerelease=a}else this.prerelease=a}break}default:throw Error(`invalid increment argument: ${t}`)}if(this.raw=this.format(),this.build.length)this.raw+=`+${this.build.join(".")}`;return this}}Ob.exports=Es});var so=e(function(wz,Mb){var kb=fr(),pO=(t,n,i=!1)=>{if(t instanceof kb)return t;try{return new kb(t,n)}catch(o){if(!i)return null;throw o}};Mb.exports=pO});var $b=e(function(Sz,Nb){var hO=so(),mO=(t,n)=>{let i=hO(t,n);return i?i.version:null};Nb.exports=mO});var Lb=e(function(bz,Db){var gO=so(),yO=(t,n)=>{let i=gO(t.trim().replace(/^[=v]+/,""),n);return i?i.version:null};Db.exports=yO});var Fb=e(function(vz,Ub){var jb=fr(),wO=(t,n,i,o,a)=>{if(typeof i==="string")a=o,o=i,i=void 0;try{return new jb(t instanceof jb?t.version:t,i).inc(n,o,a).version}catch(c){return null}};Ub.exports=wO});var Wb=e(function(Ez,Bb){var qb=so(),SO=(t,n)=>{let i=qb(t,null,!0),o=qb(n,null,!0),a=i.compare(o);if(a===0)return null;let c=a>0,m=c?i:o,E=c?o:i,_=!!m.prerelease.length;if(!!E.prerelease.length&&!_){if(!E.patch&&!E.minor)return"major";if(E.compareMain(m)===0){if(E.minor&&!E.patch)return"minor";return"patch"}}let T=_?"pre":"";if(i.major!==o.major)return T+"major";if(i.minor!==o.minor)return T+"minor";if(i.patch!==o.patch)return T+"patch";return"prerelease"};Bb.exports=SO});var Vb=e(function(Az,Hb){var bO=fr(),vO=(t,n)=>new bO(t,n).major;Hb.exports=vO});var Gb=e(function(xz,zb){var EO=fr(),AO=(t,n)=>new EO(t,n).minor;zb.exports=AO});var Jb=e(function(_z,Kb){var xO=fr(),_O=(t,n)=>new xO(t,n).patch;Kb.exports=_O});var Xb=e(function(Iz,Yb){var IO=so(),TO=(t,n)=>{let i=IO(t,n);return i&&i.prerelease.length?i.prerelease:null};Yb.exports=TO});var An=e(function(Tz,Qb){var Zb=fr(),RO=(t,n,i)=>new Zb(t,i).compare(new Zb(n,i));Qb.exports=RO});var t0=e(function(Rz,e0){var PO=An(),CO=(t,n,i)=>PO(n,t,i);e0.exports=CO});var n0=e(function(Pz,r0){var OO=An(),kO=(t,n)=>OO(t,n,!0);r0.exports=kO});var Eu=e(function(Cz,i0){var s0=fr(),MO=(t,n,i)=>{let o=new s0(t,i),a=new s0(n,i);return o.compare(a)||o.compareBuild(a)};i0.exports=MO});var a0=e(function(Oz,o0){var NO=Eu(),$O=(t,n)=>t.sort((i,o)=>NO(i,o,n));o0.exports=$O});var l0=e(function(kz,c0){var DO=Eu(),LO=(t,n)=>t.sort((i,o)=>DO(o,i,n));c0.exports=LO});var Sc=e(function(Mz,u0){var jO=An(),UO=(t,n,i)=>jO(t,n,i)>0;u0.exports=UO});var Au=e(function(Nz,d0){var FO=An(),qO=(t,n,i)=>FO(t,n,i)<0;d0.exports=qO});var ch=e(function($z,f0){var BO=An(),WO=(t,n,i)=>BO(t,n,i)===0;f0.exports=WO});var lh=e(function(Dz,p0){var HO=An(),VO=(t,n,i)=>HO(t,n,i)!==0;p0.exports=VO});var xu=e(function(Lz,h0){var zO=An(),GO=(t,n,i)=>zO(t,n,i)>=0;h0.exports=GO});var _u=e(function(jz,m0){var KO=An(),JO=(t,n,i)=>KO(t,n,i)<=0;m0.exports=JO});var uh=e(function(Uz,g0){var YO=ch(),XO=lh(),ZO=Sc(),QO=xu(),ek=Au(),tk=_u(),rk=(t,n,i,o)=>{switch(n){case"===":if(typeof t==="object")t=t.version;if(typeof i==="object")i=i.version;return t===i;case"!==":if(typeof t==="object")t=t.version;if(typeof i==="object")i=i.version;return t!==i;case"":case"=":case"==":return YO(t,i,o);case"!=":return XO(t,i,o);case">":return ZO(t,i,o);case">=":return QO(t,i,o);case"<":return ek(t,i,o);case"<=":return tk(t,i,o);default:throw TypeError(`Invalid operator: ${n}`)}};g0.exports=rk});var w0=e(function(Fz,y0){var nk=fr(),sk=so(),{safeRe:Iu,t:Tu}=Sa(),ik=(t,n)=>{if(t instanceof nk)return t;if(typeof t==="number")t=String(t);if(typeof t!=="string")return null;n=n||{};let i=null;if(!n.rtl)i=t.match(n.includePrerelease?Iu[Tu.COERCEFULL]:Iu[Tu.COERCE]);else{let _=n.includePrerelease?Iu[Tu.COERCERTLFULL]:Iu[Tu.COERCERTL],I;while((I=_.exec(t))&&(!i||i.index+i[0].length!==t.length)){if(!i||I.index+I[0].length!==i.index+i[0].length)i=I;_.lastIndex=I.index+I[1].length+I[2].length}_.lastIndex=-1}if(i===null)return null;let o=i[2],a=i[3]||"0",c=i[4]||"0",m=n.includePrerelease&&i[5]?`-${i[5]}`:"",E=n.includePrerelease&&i[6]?`+${i[6]}`:"";return sk(`${o}.${a}.${c}${m}${E}`,n)};y0.exports=ik});var v0=e(function(qz,b0){var ok=so(),S0=wa(),ak=fr(),ck=(t,n,i)=>{if(!S0.RELEASE_TYPES.includes(n))return null;let o=lk(t,i);return o&&uk(o,n)},lk=(t,n)=>{let i=t instanceof ak?t.version:t;return ok(i,n)},uk=(t,n)=>{if(dk(n))return t.version;switch(t.prerelease=[],n){case"major":t.minor=0,t.patch=0;break;case"minor":t.patch=0;break}return t.format()},dk=(t)=>t.startsWith("pre");b0.exports=ck});var x0=e(function(Bz,A0){class E0{constructor(){this.max=1000,this.map=new Map}get(t){let n=this.map.get(t);if(n===void 0)return;else return this.map.delete(t),this.map.set(t,n),n}delete(t){return this.map.delete(t)}set(t,n){if(!this.delete(t)&&n!==void 0){if(this.map.size>=this.max){let o=this.map.keys().next().value;this.delete(o)}this.map.set(t,n)}return this}}A0.exports=E0});var _n=e(function(Wz,R0){var fk=/\s+/g;class bc{constructor(t,n){if(n=hk(n),t instanceof bc)if(t.loose===!!n.loose&&t.includePrerelease===!!n.includePrerelease)return t;else return new bc(t.raw,n);if(t instanceof Ru)return this.raw=t.value,this.set=[[t]],this.formatted=void 0,this;if(this.options=n,this.loose=!!n.loose,this.includePrerelease=!!n.includePrerelease,this.raw=t.trim().replace(fk," "),this.set=this.raw.split("||").map((i)=>this.parseRange(i.trim())).filter((i)=>i.length),!this.set.length)throw TypeError(`Invalid SemVer Range: ${this.raw}`);if(this.set.length>1){let i=this.set[0];if(this.set=this.set.filter((o)=>!I0(o[0])),this.set.length===0)this.set=[i];else if(this.set.length>1){for(let o of this.set)if(o.length===1&&Ak(o[0])){this.set=[o];break}}}this.formatted=void 0}get range(){if(this.formatted===void 0){this.formatted="";for(let t=0;t<this.set.length;t++){if(t>0)this.formatted+="||";let n=this.set[t];for(let i=0;i<n.length;i++){if(i>0)this.formatted+=" ";this.formatted+=n[i].toString().trim()}}}return this.formatted}format(){return this.range}toString(){return this.range}parseRange(t){t=t.replace(Ek,"");let i=((this.options.includePrerelease&&bk)|(this.options.loose&&vk))+":"+t,o=_0.get(i);if(o)return o;let a=this.options.loose,c=a?Xr[hr.HYPHENRANGELOOSE]:Xr[hr.HYPHENRANGE];t=t.replace(c,Nk(this.options.includePrerelease)),gt("hyphen replace",t),t=t.replace(Xr[hr.COMPARATORTRIM],yk),gt("comparator trim",t),t=t.replace(Xr[hr.TILDETRIM],wk),gt("tilde trim",t),t=t.replace(Xr[hr.CARETTRIM],Sk),gt("caret trim",t);let m=t.split(" ").map((T)=>xk(T,this.options)).join(" ").split(/\s+/).map((T)=>Mk(T,this.options));if(a)m=m.filter((T)=>(gt("loose invalid filter",T,this.options),!!T.match(Xr[hr.COMPARATORLOOSE])));gt("range list",m);let E=new Map,_=m.map((T)=>new Ru(T,this.options));for(let T of _){if(I0(T))return[T];E.set(T.value,T)}if(E.size>1&&E.has(""))E.delete("");let I=[...E.values()];return _0.set(i,I),I}intersects(t,n){if(!(t instanceof bc))throw TypeError("a Range is required");return this.set.some((i)=>T0(i,n)&&t.set.some((o)=>T0(o,n)&&i.every((a)=>o.every((c)=>a.intersects(c,n)))))}test(t){if(!t)return!1;if(typeof t==="string")try{t=new mk(t,this.options)}catch(n){return!1}for(let n=0;n<this.set.length;n++)if($k(this.set[n],t,this.options))return!0;return!1}}R0.exports=bc;var pk=x0(),_0=new pk,hk=yu(),Ru=vc(),gt=wc(),mk=fr(),{safeRe:Xr,src:gk,t:hr,comparatorTrimReplace:yk,tildeTrimReplace:wk,caretTrimReplace:Sk}=Sa(),{FLAG_INCLUDE_PRERELEASE:bk,FLAG_LOOSE:vk}=wa(),Ek=new RegExp(gk[hr.BUILD],"g"),I0=(t)=>t.value==="<0.0.0-0",Ak=(t)=>t.value==="",T0=(t,n)=>{let i=!0,o=t.slice(),a=o.pop();while(i&&o.length)i=o.every((c)=>a.intersects(c,n)),a=o.pop();return i},xk=(t,n)=>(t=t.replace(Xr[hr.BUILD],""),gt("comp",t,n),t=Rk(t,n),gt("caret",t),t=Ik(t,n),gt("tildes",t),t=Ck(t,n),gt("xrange",t),t=kk(t,n),gt("stars",t),t),Zt=(t)=>!t||t.toLowerCase()==="x"||t==="*",_k=(t,n,i)=>Zt(t)&&!Zt(n)||Zt(n)&&i&&!Zt(i),Ik=(t,n)=>t.trim().split(/\s+/).map((i)=>Tk(i,n)).join(" "),Tk=(t,n)=>{let i=n.loose?Xr[hr.TILDELOOSE]:Xr[hr.TILDE];return t.replace(i,(o,a,c,m,E)=>{gt("tilde",t,o,a,c,m,E);let _;if(Zt(a))_="";else if(Zt(c))_=`>=${a}.0.0 <${+a+1}.0.0-0`;else if(Zt(m))_=`>=${a}.${c}.0 <${a}.${+c+1}.0-0`;else if(E)gt("replaceTilde pr",E),_=`>=${a}.${c}.${m}-${E} <${a}.${+c+1}.0-0`;else _=`>=${a}.${c}.${m} <${a}.${+c+1}.0-0`;return gt("tilde return",_),_})},Rk=(t,n)=>t.trim().split(/\s+/).map((i)=>Pk(i,n)).join(" "),Pk=(t,n)=>{gt("caret",t,n);let i=n.loose?Xr[hr.CARETLOOSE]:Xr[hr.CARET],o=n.includePrerelease?"-0":"";return t.replace(i,(a,c,m,E,_)=>{gt("caret",t,a,c,m,E,_);let I;if(Zt(c))I="";else if(Zt(m))I=`>=${c}.0.0${o} <${+c+1}.0.0-0`;else if(Zt(E))if(c==="0")I=`>=${c}.${m}.0${o} <${c}.${+m+1}.0-0`;else I=`>=${c}.${m}.0${o} <${+c+1}.0.0-0`;else if(_)if(gt("replaceCaret pr",_),c==="0")if(m==="0")I=`>=${c}.${m}.${E}-${_} <${c}.${m}.${+E+1}-0`;else I=`>=${c}.${m}.${E}-${_} <${c}.${+m+1}.0-0`;else I=`>=${c}.${m}.${E}-${_} <${+c+1}.0.0-0`;else if(gt("no pr"),c==="0")if(m==="0")I=`>=${c}.${m}.${E} <${c}.${m}.${+E+1}-0`;else I=`>=${c}.${m}.${E} <${c}.${+m+1}.0-0`;else I=`>=${c}.${m}.${E} <${+c+1}.0.0-0`;return gt("caret return",I),I})},Ck=(t,n)=>(gt("replaceXRanges",t,n),t.split(/\s+/).map((i)=>Ok(i,n)).join(" ")),Ok=(t,n)=>{t=t.trim();let i=n.loose?Xr[hr.XRANGELOOSE]:Xr[hr.XRANGE];return t.replace(i,(o,a,c,m,E,_)=>{if(gt("xRange",t,o,a,c,m,E,_),_k(c,m,E))return t;let I=Zt(c),T=I||Zt(m),R=T||Zt(E),P=R;if(a==="="&&P)a="";if(_=n.includePrerelease?"-0":"",I)if(a===">"||a==="<")o="<0.0.0-0";else o="*";else if(a&&P){if(T)m=0;if(E=0,a===">")if(a=">=",T)c=+c+1,m=0,E=0;else m=+m+1,E=0;else if(a==="<=")if(a="<",T)c=+c+1;else m=+m+1;if(a==="<")_="-0";o=`${a+c}.${m}.${E}${_}`}else if(T)o=`>=${c}.0.0${_} <${+c+1}.0.0-0`;else if(R)o=`>=${c}.${m}.0${_} <${c}.${+m+1}.0-0`;return gt("xRange return",o),o})},kk=(t,n)=>(gt("replaceStars",t,n),t.trim().replace(Xr[hr.STAR],"")),Mk=(t,n)=>(gt("replaceGTE0",t,n),t.trim().replace(Xr[n.includePrerelease?hr.GTE0PRE:hr.GTE0],"")),Nk=(t)=>(n,i,o,a,c,m,E,_,I,T,R,P)=>{if(Zt(o))i="";else if(Zt(a))i=`>=${o}.0.0${t?"-0":""}`;else if(Zt(c))i=`>=${o}.${a}.0${t?"-0":""}`;else if(m)i=`>=${i}`;else i=`>=${i}${t?"-0":""}`;if(Zt(I))_="";else if(Zt(T))_=`<${+I+1}.0.0-0`;else if(Zt(R))_=`<${I}.${+T+1}.0-0`;else if(P)_=`<=${I}.${T}.${R}-${P}`;else if(t)_=`<${I}.${T}.${+R+1}-0`;else _=`<=${_}`;return`${i} ${_}`.trim()},$k=(t,n,i)=>{for(let o=0;o<t.length;o++)if(!t[o].test(n))return!1;if(n.prerelease.length&&!i.includePrerelease){for(let o=0;o<t.length;o++){if(gt(t[o].semver),t[o].semver===Ru.ANY)continue;if(t[o].semver.prerelease.length>0){let a=t[o].semver;if(a.major===n.major&&a.minor===n.minor&&a.patch===n.patch)return!0}}return!1}return!0}});var vc=e(function(Hz,N0){var Ec=Symbol("SemVer ANY");class Pu{static get ANY(){return Ec}constructor(t,n){if(n=P0(n),t instanceof Pu)if(t.loose===!!n.loose)return t;else t=t.value;if(t=t.trim().split(/\s+/).join(" "),fh("comparator",t,n),this.options=n,this.loose=!!n.loose,this.parse(t),this.semver===Ec)this.value="";else this.value=this.operator+this.semver.version;fh("comp",this)}parse(t){let n=this.options.loose?C0[O0.COMPARATORLOOSE]:C0[O0.COMPARATOR],i=t.match(n);if(!i)throw TypeError(`Invalid comparator: ${t}`);if(this.operator=i[1]!==void 0?i[1]:"",this.operator==="=")this.operator="";if(!i[2])this.semver=Ec;else this.semver=new k0(i[2],this.options.loose)}toString(){return this.value}test(t){if(fh("Comparator.test",t,this.options.loose),this.semver===Ec||t===Ec)return!0;if(typeof t==="string")try{t=new k0(t,this.options)}catch(n){return!1}return dh(t,this.operator,this.semver,this.options)}intersects(t,n){if(!(t instanceof Pu))throw TypeError("a Comparator is required");if(this.operator===""){if(this.value==="")return!0;return new M0(t.value,n).test(this.value)}else if(t.operator===""){if(t.value==="")return!0;return new M0(this.value,n).test(t.semver)}if(n=P0(n),n.includePrerelease&&(this.value==="<0.0.0-0"||t.value==="<0.0.0-0"))return!1;if(!n.includePrerelease&&(this.value.startsWith("<0.0.0")||t.value.startsWith("<0.0.0")))return!1;if(this.operator.startsWith(">")&&t.operator.startsWith(">"))return!0;if(this.operator.startsWith("<")&&t.operator.startsWith("<"))return!0;if(this.semver.version===t.semver.version&&this.operator.includes("=")&&t.operator.includes("="))return!0;if(dh(this.semver,"<",t.semver,n)&&this.operator.startsWith(">")&&t.operator.startsWith("<"))return!0;if(dh(this.semver,">",t.semver,n)&&this.operator.startsWith("<")&&t.operator.startsWith(">"))return!0;return!1}}N0.exports=Pu;var P0=yu(),{safeRe:C0,t:O0}=Sa(),dh=uh(),fh=wc(),k0=fr(),M0=_n()});var Ac=e(function(Vz,$0){var Dk=_n(),Lk=(t,n,i)=>{try{n=new Dk(n,i)}catch(o){return!1}return n.test(t)};$0.exports=Lk});var L0=e(function(zz,D0){var jk=_n(),Uk=(t,n)=>new jk(t,n).set.map((i)=>i.map((o)=>o.value).join(" ").trim().split(" "));D0.exports=Uk});var U0=e(function(Gz,j0){var Fk=fr(),qk=_n(),Bk=(t,n,i)=>{let o=null,a=null,c=null;try{c=new qk(n,i)}catch(m){return null}return t.forEach((m)=>{if(c.test(m)){if(!o||a.compare(m)===-1)o=m,a=new Fk(o,i)}}),o};j0.exports=Bk});var q0=e(function(Kz,F0){var Wk=fr(),Hk=_n(),Vk=(t,n,i)=>{let o=null,a=null,c=null;try{c=new Hk(n,i)}catch(m){return null}return t.forEach((m)=>{if(c.test(m)){if(!o||a.compare(m)===1)o=m,a=new Wk(o,i)}}),o};F0.exports=Vk});var H0=e(function(Jz,W0){var ph=fr(),zk=_n(),B0=Sc(),Gk=(t,n)=>{t=new zk(t,n);let i=new ph("0.0.0");if(t.test(i))return i;if(i=new ph("0.0.0-0"),t.test(i))return i;i=null;for(let o=0;o<t.set.length;++o){let a=t.set[o],c=null;if(a.forEach((m)=>{let E=new ph(m.semver.version);switch(m.operator){case">":if(E.prerelease.length===0)E.patch++;else E.prerelease.push(0);E.raw=E.format();case"":case">=":if(!c||B0(E,c))c=E;break;case"<":case"<=":break;default:throw Error(`Unexpected operation: ${m.operator}`)}}),c&&(!i||B0(i,c)))i=c}if(i&&t.test(i))return i;return null};W0.exports=Gk});var z0=e(function(Yz,V0){var Kk=_n(),Jk=(t,n)=>{try{return new Kk(t,n).range||"*"}catch(i){return null}};V0.exports=Jk});var Cu=e(function(Xz,Y0){var Yk=fr(),J0=vc(),{ANY:Xk}=J0,Zk=_n(),Qk=Ac(),G0=Sc(),K0=Au(),eM=_u(),tM=xu(),rM=(t,n,i,o)=>{t=new Yk(t,o),n=new Zk(n,o);let a,c,m,E,_;switch(i){case">":a=G0,c=eM,m=K0,E=">",_=">=";break;case"<":a=K0,c=tM,m=G0,E="<",_="<=";break;default:throw TypeError('Must provide a hilo val of "<" or ">"')}if(Qk(t,n,o))return!1;for(let I=0;I<n.set.length;++I){let T=n.set[I],R=null,P=null;if(T.forEach((M)=>{if(M.semver===Xk)M=new J0(">=0.0.0");if(R=R||M,P=P||M,a(M.semver,R.semver,o))R=M;else if(m(M.semver,P.semver,o))P=M}),R.operator===E||R.operator===_)return!1;if((!P.operator||P.operator===E)&&c(t,P.semver))return!1;else if(P.operator===_&&m(t,P.semver))return!1}return!0};Y0.exports=rM});var Z0=e(function(Zz,X0){var nM=Cu(),sM=(t,n,i)=>nM(t,n,">",i);X0.exports=sM});var ev=e(function(Qz,Q0){var iM=Cu(),oM=(t,n,i)=>iM(t,n,"<",i);Q0.exports=oM});var nv=e(function(e9,rv){var tv=_n(),aM=(t,n,i)=>(t=new tv(t,i),n=new tv(n,i),t.intersects(n,i));rv.exports=aM});var iv=e(function(t9,sv){var cM=Ac(),lM=An();sv.exports=(t,n,i)=>{let o=[],a=null,c=null,m=t.sort((T,R)=>lM(T,R,i));for(let T of m)if(cM(T,n,i)){if(c=T,!a)a=T}else{if(c)o.push([a,c]);c=null,a=null}if(a)o.push([a,null]);let E=[];for(let[T,R]of o)if(T===R)E.push(T);else if(!R&&T===m[0])E.push("*");else if(!R)E.push(`>=${T}`);else if(T===m[0])E.push(`<=${R}`);else E.push(`${T} - ${R}`);let _=E.join(" || "),I=typeof n.raw==="string"?n.raw:String(n);return _.length<I.length?_:n}});var dv=e(function(r9,uv){var ov=_n(),gh=vc(),{ANY:hh}=gh,mh=Ac(),yh=An(),uM=(t,n,i={})=>{if(t===n)return!0;t=new ov(t,i),n=new ov(n,i);let o=!1;e:for(let a of t.set){for(let c of n.set){let m=fM(a,c,i);if(o=o||m!==null,m)continue e}if(o)return!1}return!0},dM=[new gh(">=0.0.0-0")],av=[new gh(">=0.0.0")],fM=(t,n,i)=>{if(t===n)return!0;if(t.length===1&&t[0].semver===hh)if(n.length===1&&n[0].semver===hh)return!0;else if(i.includePrerelease)t=dM;else t=av;if(n.length===1&&n[0].semver===hh)if(i.includePrerelease)return!0;else n=av;let o=new Set,a,c;for(let M of t)if(M.operator===">"||M.operator===">=")a=cv(a,M,i);else if(M.operator==="<"||M.operator==="<=")c=lv(c,M,i);else o.add(M.semver);if(o.size>1)return null;let m;if(a&&c){if(m=yh(a.semver,c.semver,i),m>0)return null;else if(m===0&&(a.operator!==">="||c.operator!=="<="))return null}for(let M of o){if(a&&!mh(M,String(a),i))return null;if(c&&!mh(M,String(c),i))return null;for(let N of n)if(!mh(M,String(N),i))return!1;return!0}let E,_,I,T,R=c&&!i.includePrerelease&&c.semver.prerelease.length?c.semver:!1,P=a&&!i.includePrerelease&&a.semver.prerelease.length?a.semver:!1;if(R&&R.prerelease.length===1&&c.operator==="<"&&R.prerelease[0]===0)R=!1;for(let M of n){if(T=T||M.operator===">"||M.operator===">=",I=I||M.operator==="<"||M.operator==="<=",a){if(P){if(M.semver.prerelease&&M.semver.prerelease.length&&M.semver.major===P.major&&M.semver.minor===P.minor&&M.semver.patch===P.patch)P=!1}if(M.operator===">"||M.operator===">="){if(E=cv(a,M,i),E===M&&E!==a)return!1}else if(a.operator===">="&&!M.test(a.semver))return!1}if(c){if(R){if(M.semver.prerelease&&M.semver.prerelease.length&&M.semver.major===R.major&&M.semver.minor===R.minor&&M.semver.patch===R.patch)R=!1}if(M.operator==="<"||M.operator==="<="){if(_=lv(c,M,i),_===M&&_!==c)return!1}else if(c.operator==="<="&&!M.test(c.semver))return!1}if(!M.operator&&(c||a)&&m!==0)return!1}if(a&&I&&!c&&m!==0)return!1;if(c&&T&&!a&&m!==0)return!1;if(P||R)return!1;return!0},cv=(t,n,i)=>{if(!t)return n;let o=yh(t.semver,n.semver,i);return o>0?t:o<0?n:n.operator===">"&&t.operator===">="?n:t},lv=(t,n,i)=>{if(!t)return n;let o=yh(t.semver,n.semver,i);return o<0?t:o>0?n:n.operator==="<"&&t.operator==="<="?n:t};uv.exports=uM});var pv=e(function(n9,fv){var ba=Sa(),Ou=wa(),pM=fr(),ku=oh(),hM=so(),mM=$b(),gM=Lb(),yM=Fb(),wM=Wb(),SM=Vb(),bM=Gb(),vM=Jb(),EM=Xb(),AM=An(),xM=t0(),_M=n0(),IM=Eu(),TM=a0(),RM=l0(),PM=Sc(),CM=Au(),OM=ch(),kM=lh(),MM=xu(),NM=_u(),$M=uh(),DM=w0(),LM=v0(),jM=vc(),UM=_n(),FM=Ac(),qM=L0(),BM=U0(),WM=q0(),HM=H0(),VM=z0(),zM=Cu(),GM=Z0(),KM=ev(),JM=nv(),YM=iv(),XM=dv();fv.exports={parse:hM,valid:mM,clean:gM,inc:yM,diff:wM,major:SM,minor:bM,patch:vM,prerelease:EM,compare:AM,rcompare:xM,compareLoose:_M,compareBuild:IM,sort:TM,rsort:RM,gt:PM,lt:CM,eq:OM,neq:kM,gte:MM,lte:NM,cmp:$M,coerce:DM,truncate:LM,Comparator:jM,Range:UM,satisfies:FM,toComparators:qM,maxSatisfying:BM,minSatisfying:WM,minVersion:HM,validRange:VM,outside:zM,gtr:GM,ltr:KM,intersects:JM,simplifyRange:YM,subset:XM,SemVer:pM,re:ba.re,src:ba.src,tokens:ba.t,SEMVER_SPEC_VERSION:Ou.SEMVER_SPEC_VERSION,RELEASE_TYPES:Ou.RELEASE_TYPES,compareIdentifiers:ku.compareIdentifiers,rcompareIdentifiers:ku.rcompareIdentifiers}});import{rm as K$}from"fs/promises";import{dirname as J$,join as Y$}from"path";var $c=new Map;function Dc(t){return{type:"agent-activity:changed",agentIds:Array.from($c.get(t)?.keys()??[],qi)}}function gA(t,n){let i=$c.get(t)??new Map,o=i.get(n);clearTimeout(o);let a=setTimeout(()=>{if(i.delete(n),!i.size)$c.delete(t);jn(t,Dc(t))},60000).unref();if(i.set(n,a),$c.set(t,i),!o)jn(t,Dc(t))}function Lc(t,n){let i=n.headers.get("x-moi-user-id");if(i&&/^a_[A-Za-z0-9_-]{43}$/.test(i))gA(t,i)}import{chmod as NA,rm as $A}from"fs/promises";function zh(t){return[t&&gs("algorithms",t.algorithms),t?.crit]}function yA(t){return t===void 0?{}:ys(t,A,"JWS Protected Header is invalid")}function wA(t){try{return de(t)}catch{throw new A("JWS Compact Serialization payload must use only ASCII characters")}}async function SA(t,n,i,o,a){let{protected:c,header:m,payload:E}=t,_=a??yA(c);if(!Fr(_,m))throw new A("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let I={..._,...m},T=Wr(_,jr(A,Br,n[1],_,I)),{alg:R}=I;if(typeof R!="string"||!R)throw new A('JWS "alg" (Algorithm) Header Parameter missing or invalid');if(n[0]&&!n[0].has(R))throw new Un('"alg" (Algorithm) Header Parameter value not allowed');if(T){if(typeof E!="string")throw new A("JWS Payload must be a string")}else if(typeof E!="string"&&!(E instanceof Uint8Array))throw new A("JWS Payload must be a string or an Uint8Array instance");let P=T||typeof E!="string"?E:o(E),M=!1;typeof i=="function"&&(i=await i(_,t),M=!0);let N=Kr(R),H=Rr(c!==void 0?de(c):new Uint8Array,de("."),typeof P=="string"?n[2]??=hs(P,"payload",A):P),Z=Gn(t.signature,"signature",A),V=await Ur(N,i,"verify"),me=await Vr(V,N.subtle,"verify");N.minRsaBits&&zr(N.alg,me);let te=!1;try{te=await crypto.subtle.verify(N.signing,me,Z,H)}catch{}if(!te)throw new Kn;let we={payload:typeof P=="string"?Gn(P,"payload",A):P};return c!==void 0&&(we.protectedHeader=_),m!==void 0&&(we.unprotectedHeader=m),M?[{...we,key:V},T]:[we,T]}async function Gh(t,n,i){if(t instanceof Uint8Array&&(t=kr.decode(t)),typeof t!="string")throw new A("Compact JWS must be a string or Uint8Array");let{0:o,1:a,2:c,length:m}=t.split(".");if(m!==3)throw new A("Invalid Compact JWS");return SA({payload:a,protected:o,signature:c},n,i,wA)}async function Kh(t,n,i){let[o,a]=await Gh(t,zh(i),n);if(!a)throw new Y("JWTs MUST NOT use unencoded payload");let c=_s(o.protectedHeader,o.payload,i);return{...o,payload:c}}function bA(t,n,i,o){let{kty:a,key_ops:c,ext:m,kid:E,alg:_,use:I,crv:T}=t;return(m===void 0||typeof m=="boolean")&&(c===void 0||Array.isArray(c)&&c.every((R,P)=>typeof R=="string"&&c.indexOf(R)===P)&&c.includes("verify"))&&n.kty.includes(a)&&(o===void 0||typeof o=="string"&&o===E)&&(_===void 0?a!=="AKP":i===_)&&(I===void 0||I==="sig")&&(!n.crv||T===n.crv)}async function Jh(t,n,i){let o=t.get(n)||t.set(n,{}).get(n),{alg:a}=i;if(o[a]===void 0){let c=yt(i,n,!0).then((m)=>{if(m.type!=="public")throw new Lr("JSON Web Key Set members must be public keys");return o[a]=m,m}).catch((m)=>{throw o[a]===c&&delete o[a],m});o[a]=c}return o[a]}function ld(t){let n;try{n=structuredClone(t)}catch{}if(!Mr(n))throw new Lr("JSON Web Key Set malformed");let i=n.keys.map((a)=>{let c=ht(a);return Array.isArray(c.key_ops)&&(c.key_ops=[...c.key_ops]),c}),o=new WeakMap;return Object.defineProperty(async(a,c)=>{let{alg:m,kid:E}={...a,...c?.header},_=typeof m=="string"?$t[m]:void 0;if(!_||_.secret)throw new L('Unsupported "alg" value for a JSON Web Key Set');let I=n.keys.filter((P,M)=>bA(i[M],_,m,E)),{0:T,length:R}=I;if(!R)throw new Gt;if(R!==1){let P=new zn;throw P[Symbol.asyncIterator]=async function*(){for(let M of I)try{yield await Jh(o,M,_)}catch{}},P}return Jh(o,T,_)},"jwks",{value:()=>structuredClone(n)})}function vA(){return typeof WebSocketPair<"u"||typeof navigator<"u"&&navigator.userAgent==="Cloudflare-Workers"||typeof EdgeRuntime<"u"&&EdgeRuntime==="vercel"}var ud;(typeof navigator>"u"||!navigator.userAgent?.startsWith?.("Mozilla/5.0 "))&&(ud="jose/v6.2.12");var dd=Symbol();async function EA(t,n,i,o=fetch){let a=await o(t,{method:"GET",signal:i,redirect:"manual",headers:n}).catch((c)=>{throw c.name==="TimeoutError"?new Vn:c});if(a.status!==200)throw new G("Expected 200 OK from the JSON Web Key Set HTTP response");try{return await a.json()}catch{throw new G("Failed to parse the JSON Web Key Set HTTP response as JSON")}}var AA=Symbol();function Pa(t,n){return Number.isFinite(t)&&Date.now()<t+n}function Yh(t,n,i){if(Number.isNaN(t))throw TypeError(`"${i}" option must not be NaN`);return typeof t=="number"?t:n}function Xh(t,n){if(!(t instanceof URL))throw TypeError("url must be an instance of URL");let i=new URL(t.href).href,o=n??{},a=o.timeoutDuration;if(typeof a=="number"&&(!Number.isInteger(a)||a<0))throw TypeError('"timeoutDuration" option must be a non-negative integer');let c=typeof a=="number"?a:5000,m=Yh(o.cooldownDuration,30000,"cooldownDuration"),E=Yh(o.cacheMaxAge,600000,"cacheMaxAge"),_=new Headers(o.headers);ud&&!_.has("User-Agent")&&_.set("User-Agent",ud),_.has("accept")||_.set("accept","application/json, application/jwk-set+json");let I=o[dd],T=o[AA],R,P,M=0,N=0,H;if(T&&typeof T=="object"){let{uat:V,jwks:me}=T;Pa(V,E)&&Mr(me)&&(R=V,H=ld(me))}let Z=async()=>{if(P&&vA()&&(P=void 0),!P){let V=++M,me=P=EA(i,_,AbortSignal.timeout(c),I).then((te)=>{let we=ld(te);if(V<=N)return;H=we;let Te=Date.now();T&&(T.uat=Te,T.jwks=te),R=Te,N=V}).finally(()=>{P===me&&(P=void 0)})}await P};return Object.defineProperties(async(V,me)=>{(!H||!Pa(R,E))&&await Z();try{return await H(V,me)}catch(te){if(te instanceof Gt&&!Pa(R,m))return await Z(),H(V,me);throw te}},{coolingDown:{get:()=>Pa(R,m),enumerable:!0},fresh:{get:()=>Pa(R,E),enumerable:!0},reload:{value:Z,enumerable:!0},reloading:{get:()=>!!P,enumerable:!0},jwks:{value:()=>H?.jwks(),enumerable:!0}})}import{constants as jc}from"fs";import{lstat as fd,mkdir as xA,open as _A,realpath as IA,rename as TA,rm as RA}from"fs/promises";import{dirname as PA,isAbsolute as Zh,relative as Qh,resolve as pd,sep as em}from"path";class bt extends Error{status;constructor(t,n=400){super(t);this.status=n}}var CA=new be;function OA(t,n){let i=Qh(t,n);return i!==""&&i!==".."&&!i.startsWith(`..${em}`)&&!Zh(i)}async function Uc(t,n,i=!1){if(!n||Zh(n)||n.includes("\\")||n.includes("\x00")||n.split("/").some((m)=>m===".."||m==="."))throw new bt("Use a file path relative to the workspace");t=await IA(t);let o=pd(t,n);if(!OA(t,o))throw new bt("File is outside the workspace");let a=t,c=Qh(t,o).split(em);for(let[m,E]of c.entries()){a=pd(a,E);try{let _=await fd(a);if(_.isSymbolicLink())throw new bt("Symbolic links are not supported");if(m<c.length-1&&!_.isDirectory())throw new bt("Parent is not a directory");if(m===c.length-1&&!_.isFile())throw new bt("Path is not a file")}catch(_){if(_.code!=="ENOENT")throw _;if(!i)throw new bt("File not found",404);if(m<c.length-1)await xA(a)}}return o}async function hd(t,n,i,o){return CA.runExclusive(async()=>{let a=await Uc(t,n,!o),c=pd(PA(a),`.moi-write-${crypto.randomUUID()}`),m=436;try{m=(await fd(a)).mode&511}catch{}let E=await _A(c,jc.O_WRONLY|jc.O_CREAT|jc.O_EXCL|jc.O_NOFOLLOW,m);try{if(o){let _=new TextDecoder("utf-8",{fatal:!0}).decode(await Bun.file(a).arrayBuffer());await E.writeFile(o(_))}else for await(let _ of i)await E.writeFile(_);if(await E.close(),await Uc(t,n,!0)!==a)throw new bt("File changed during upload",409);await TA(c,a)}finally{await E.close().catch(()=>{}),await RA(c,{force:!0})}return{ok:!0,bytes:(await fd(a)).size}})}function tm(t,n){let i=t?t.split(`
|
|
3
3
|
`):[];if(t.endsWith(`
|
|
4
4
|
`))i.pop();let o=[],a=n.split(`
|
|
5
5
|
`),c=0,m=0,E=t.endsWith(`
|
|
@@ -11,7 +11,7 @@ import{w,W,ue,qi,je,K,re,We,xn,Q,vr,Sr,Tr,Ji,Xi,Yi,Zi,O,Ft,ze,Qi,es,In,Ve,Cn,d,f
|
|
|
11
11
|
`)),t.didWarn=!0;return}let c=new Map;for(let E of n)gd(c,E.name,{version:E.version,modules:[]}).modules.push(E.modules);let m=new Map;for(let[E,_]of c)if(_.modules.length>1)m.set(E,_);if(m.size>0){let E=[`${Ks("[tldraw]",["bold","bgRed","textWhite"])} ${Ks("You have multiple instances of some tldraw libraries active. This can lead to bugs and unexpected behavior. ",["textRed","bold"])}`,"","This usually means that your bundler is misconfigured, and is importing the same library multiple times - usually once as an ES Module, and once as a CommonJS module.","","The following libraries have been imported multiple times:",...Array.from(m,([_,I])=>{let T=I.modules.map((R,P)=>R==="esm"?` ${P+1}. ES Modules`:` ${P+1}. CommonJS`).join(`
|
|
12
12
|
`);return` \u2022 \u274C ${Ks(_,["bold"])} v${I.version}:
|
|
13
13
|
${T}`}),"","You should configure your bundler to only import one version of each library."];console.log(E.join(`
|
|
14
|
-
`)),t.didWarn=!0;return}}function lm(t,n){let i=t.match(/^(\d+)\.(\d+)\.(\d+)(?:-(\w+))?$/),o=n.match(/^(\d+)\.(\d+)\.(\d+)(?:-(\w+))?$/);if(!i||!o)return t.localeCompare(n);if(i[1]!==o[1])return Number(i[1])-Number(o[1]);if(i[2]!==o[2])return Number(i[2])-Number(o[2]);if(i[3]!==o[3])return Number(i[3])-Number(o[3]);if(i[4]&&o[4])return i[4].localeCompare(o[4]);if(i[4])return 1;if(o[4])return-1;return 0}var qA={bold:"1",textBlue:"94",textRed:"31",textGreen:"32",bgRed:"41",textWhite:"97"};function Ks(t,n=[]){return`\x1B[${n.map((i)=>qA[i]).join(";")}m${t}\x1B[m`}function BA(){try{return"__NEXT_DATA__"in globalThis}catch{return!1}}function gd(t,n,i){if(t.has(n))return t.get(n);return t.set(n,i),i}var ki=g(Hm(),1),bR=g(qd(),1),vR=g(xg(),1),ER=g(Og(),1);function Jd(t,n){if(t===n)return!0;if(t.length!==n.length)return!1;for(let i=0;i<t.length;i++)if(!Object.is(t[i],n[i]))return!1;return!0}function hl(t){let n=(...i)=>{try{return t(...i)}catch(o){if(o instanceof Error&&Error.captureStackTrace)Error.captureStackTrace(o,n);throw o}};return n}var $s={ok(t){return{ok:!0,value:t}},err(t){return{ok:!1,error:t}},all(t){return t.every((n)=>n.ok)?$s.ok(t.map((n)=>n.value)):$s.err(t.find((n)=>!n.ok)?.error)}};function ja(t,n){let i=n&&t&&typeof t==="object"&&n in t?t[n]:t;throw Error(`Unknown switch case ${i}`)}var
|
|
14
|
+
`)),t.didWarn=!0;return}}function lm(t,n){let i=t.match(/^(\d+)\.(\d+)\.(\d+)(?:-(\w+))?$/),o=n.match(/^(\d+)\.(\d+)\.(\d+)(?:-(\w+))?$/);if(!i||!o)return t.localeCompare(n);if(i[1]!==o[1])return Number(i[1])-Number(o[1]);if(i[2]!==o[2])return Number(i[2])-Number(o[2]);if(i[3]!==o[3])return Number(i[3])-Number(o[3]);if(i[4]&&o[4])return i[4].localeCompare(o[4]);if(i[4])return 1;if(o[4])return-1;return 0}var qA={bold:"1",textBlue:"94",textRed:"31",textGreen:"32",bgRed:"41",textWhite:"97"};function Ks(t,n=[]){return`\x1B[${n.map((i)=>qA[i]).join(";")}m${t}\x1B[m`}function BA(){try{return"__NEXT_DATA__"in globalThis}catch{return!1}}function gd(t,n,i){if(t.has(n))return t.get(n);return t.set(n,i),i}var ki=g(Hm(),1),bR=g(qd(),1),vR=g(xg(),1),ER=g(Og(),1);function Jd(t,n){if(t===n)return!0;if(t.length!==n.length)return!1;for(let i=0;i<t.length;i++)if(!Object.is(t[i],n[i]))return!1;return!0}function hl(t){let n=(...i)=>{try{return t(...i)}catch(o){if(o instanceof Error&&Error.captureStackTrace)Error.captureStackTrace(o,n);throw o}};return n}var $s={ok(t){return{ok:!0,value:t}},err(t){return{ok:!1,error:t}},all(t){return t.every((n)=>n.ok)?$s.ok(t.map((n)=>n.value)):$s.err(t.find((n)=>!n.ok)?.error)}};function ja(t,n){let i=n&&t&&typeof t==="object"&&n in t?t[n]:t;throw Error(`Unknown switch case ${i}`)}var qe=hl((t,n)=>{if(!t)throw Error(n||"Assertion Error")}),YT=hl((t,n)=>{if(t==null)throw Error(n??"value must be defined");return t});/*!
|
|
15
15
|
* MIT License: https://github.com/NoHomey/bind-decorator/blob/master/License
|
|
16
16
|
* Copyright (c) 2016 Ivo Stratev
|
|
17
17
|
*/class ml{items=new WeakMap;get(t,n){if(!this.items.has(t))this.items.set(t,n(t));return this.items.get(t)}}var kg=new WeakMap;function Yd(t,n){if(typeof t!=="object"||t===null)return;let i=kg.get(t);if(!i)i={tags:{},extras:{}},kg.set(t,i);if(n.tags)i.tags={...i.tags,...n.tags};if(n.extras)i.extras={...i.extras,...n.extras}}/*!
|
|
@@ -51,16 +51,16 @@ get foo() {
|
|
|
51
51
|
getFoo() {
|
|
52
52
|
return 'foo'
|
|
53
53
|
}
|
|
54
|
-
`)}var er=Symbol.for("com.tldraw.state/UNINITIALIZED");function Ha(t){return t===er}var af=rn("WithDiff",()=>class{constructor(n,i){this.value=n,this.diff=i}value;diff});function Zo(t,n){return new af(t,n)}class fy{constructor(t,n,i){if(this.name=t,this.derive=n,i?.historyLength)this.historyBuffer=new Wa(i.historyLength);this.computeDiff=i?.computeDiff,this.isEqual=i?.isEqual??bl}name;derive;__isComputed=!0;lastChangedEpoch=Jn;lastTraversedEpoch=Jn;__debug_ancestor_epochs__=null;lastCheckedEpoch=Jn;parentSet=new Qs;parents=[];parentEpochs=[];children=new Qs;get isActivelyListening(){return!this.children.isEmpty}historyBuffer;state=er;error=null;computeDiff;isEqual;__unsafe__getWithoutCapture(t){let n=this.lastChangedEpoch===Jn,i=cr();if(!n&&(this.lastCheckedEpoch===i||this.isActivelyListening&&Qg()&&this.lastTraversedEpoch<Zg()||!Sl(this)))if(this.lastCheckedEpoch=i,this.error)if(!t)throw this.error.thrownValue;else return this.state;else return this.state;try{vl(this);let o=this.derive(this.state,this.lastCheckedEpoch),a=o instanceof af?o.value:o,c=this.state===er;if(c||!this.isEqual(this.state,a)){if(this.historyBuffer&&!c){let m=o instanceof af?o.diff:void 0;this.historyBuffer.pushEntry(this.lastChangedEpoch,cr(),m??this.computeDiff?.(this.state,a,this.lastCheckedEpoch,cr())??Pr)}this.lastChangedEpoch=cr(),this.state=a}return this.error=null,this.lastCheckedEpoch=cr(),this.state}catch(o){if(this.state!==er)this.state=er,this.lastChangedEpoch=cr();if(this.lastCheckedEpoch=cr(),this.historyBuffer)this.historyBuffer.clear();if(this.error={thrownValue:o},!t)throw o;return this.state}finally{El()}}get(){try{return this.__unsafe__getWithoutCapture()}finally{Xo(this)}}getDiffSince(t){if(this.__unsafe__getWithoutCapture(!0),Xo(this),t>=this.lastChangedEpoch)return bo;return this.historyBuffer?.getChangesSince(t)??Pr}}var Va=rn("Computed",()=>fy);function xR(t={},n,i,o){let a=o.value,c=Symbol.for("__@tldraw/state__computed__"+i);return o.value=function(){let m=this[c];if(!m)m=new Va(i,a.bind(this),t),Object.defineProperty(this,c,{enumerable:!1,configurable:!1,writable:!1,value:m});return m.get()},o.value[py]=!0,o}function _R(t={},n,i,o){let a=o.get,c=Symbol.for("__@tldraw/state__computed__"+i);return o.get=function(){let m=this[c];if(!m)m=new Va(i,a.bind(this),t),Object.defineProperty(this,c,{enumerable:!1,configurable:!1,writable:!1,value:m});return m.get()},o}function IR(t,n,i){
|
|
54
|
+
`)}var er=Symbol.for("com.tldraw.state/UNINITIALIZED");function Ha(t){return t===er}var af=rn("WithDiff",()=>class{constructor(n,i){this.value=n,this.diff=i}value;diff});function Zo(t,n){return new af(t,n)}class fy{constructor(t,n,i){if(this.name=t,this.derive=n,i?.historyLength)this.historyBuffer=new Wa(i.historyLength);this.computeDiff=i?.computeDiff,this.isEqual=i?.isEqual??bl}name;derive;__isComputed=!0;lastChangedEpoch=Jn;lastTraversedEpoch=Jn;__debug_ancestor_epochs__=null;lastCheckedEpoch=Jn;parentSet=new Qs;parents=[];parentEpochs=[];children=new Qs;get isActivelyListening(){return!this.children.isEmpty}historyBuffer;state=er;error=null;computeDiff;isEqual;__unsafe__getWithoutCapture(t){let n=this.lastChangedEpoch===Jn,i=cr();if(!n&&(this.lastCheckedEpoch===i||this.isActivelyListening&&Qg()&&this.lastTraversedEpoch<Zg()||!Sl(this)))if(this.lastCheckedEpoch=i,this.error)if(!t)throw this.error.thrownValue;else return this.state;else return this.state;try{vl(this);let o=this.derive(this.state,this.lastCheckedEpoch),a=o instanceof af?o.value:o,c=this.state===er;if(c||!this.isEqual(this.state,a)){if(this.historyBuffer&&!c){let m=o instanceof af?o.diff:void 0;this.historyBuffer.pushEntry(this.lastChangedEpoch,cr(),m??this.computeDiff?.(this.state,a,this.lastCheckedEpoch,cr())??Pr)}this.lastChangedEpoch=cr(),this.state=a}return this.error=null,this.lastCheckedEpoch=cr(),this.state}catch(o){if(this.state!==er)this.state=er,this.lastChangedEpoch=cr();if(this.lastCheckedEpoch=cr(),this.historyBuffer)this.historyBuffer.clear();if(this.error={thrownValue:o},!t)throw o;return this.state}finally{El()}}get(){try{return this.__unsafe__getWithoutCapture()}finally{Xo(this)}}getDiffSince(t){if(this.__unsafe__getWithoutCapture(!0),Xo(this),t>=this.lastChangedEpoch)return bo;return this.historyBuffer?.getChangesSince(t)??Pr}}var Va=rn("Computed",()=>fy);function xR(t={},n,i,o){let a=o.value,c=Symbol.for("__@tldraw/state__computed__"+i);return o.value=function(){let m=this[c];if(!m)m=new Va(i,a.bind(this),t),Object.defineProperty(this,c,{enumerable:!1,configurable:!1,writable:!1,value:m});return m.get()},o.value[py]=!0,o}function _R(t={},n,i,o){let a=o.get,c=Symbol.for("__@tldraw/state__computed__"+i);return o.get=function(){let m=this[c];if(!m)m=new Va(i,a.bind(this),t),Object.defineProperty(this,c,{enumerable:!1,configurable:!1,writable:!1,value:m});return m.get()},o}function IR(t,n,i){qe(i.kind==="method","@computed can only be used on methods");let o=Symbol.for("__@tldraw/state__computed__"+String(i.name)),a=function(){let c=this[o];if(!c)c=new Va(String(i.name),n.bind(this),t),Object.defineProperty(this,o,{enumerable:!1,configurable:!1,writable:!1,value:c});return c.get()};return a[py]=!0,a}function dy(t={},n){if(n.length===2){let[i,o]=n;return IR(t,i,o)}else{let[i,o,a]=n;if(a.get)return uy(),_R(t,i,o,a);else return xR(t,i,o,a)}}var py="@@__isComputedMethod__@@";function un(){if(arguments.length===1){let t=arguments[0];return(...n)=>dy(t,n)}else if(typeof arguments[0]==="string")return new Va(arguments[0],arguments[1],arguments[2]);else return dy(void 0,arguments)}class hy{constructor(t,n,i){this.name=t,this.runEffect=n,this._scheduleEffect=i?.scheduleEffect}name;runEffect;__isEffectScheduler=!0;_isActivelyListening=!1;get isActivelyListening(){return this._isActivelyListening}lastTraversedEpoch=Jn;lastReactedEpoch=Jn;_scheduleCount=0;__debug_ancestor_epochs__=null;get scheduleCount(){return this._scheduleCount}parentSet=new Qs;parentEpochs=[];parents=[];_scheduleEffect;maybeScheduleEffect(){if(!this._isActivelyListening)return;if(this.lastReactedEpoch===cr())return;if(this.parents.length&&!Sl(this)){this.lastReactedEpoch=cr();return}this.scheduleEffect()}scheduleEffect(){if(this._scheduleCount++,this._scheduleEffect)this._scheduleEffect(this.maybeExecute);else this.execute()}maybeExecute=()=>{if(!this._isActivelyListening)return;this.execute()};attach(){this._isActivelyListening=!0;for(let t=0,n=this.parents.length;t<n;t++)qa(this.parents[t],this)}detach(){this._isActivelyListening=!1;for(let t=0,n=this.parents.length;t<n;t++)Yo(this.parents[t],this)}execute(){try{vl(this);let t=cr(),n=this.runEffect(this.lastReactedEpoch);return this.lastReactedEpoch=t,n}finally{El()}}}var my=rn("EffectScheduler",()=>hy);function cf(t,n,i){let o=new my(t,n,i);return{scheduler:o,start:(a)=>{let c=a?.force??!1;if(o.attach(),c)o.scheduleEffect();else o.maybeScheduleEffect()},stop:()=>{o.detach()}}}var gy=1,RR=rn("apiVersion",()=>gy);if(RR!==gy)throw Error("You have multiple incompatible versions of @tldraw/state in your app. Please deduplicate the package.");Tn("@tldraw/state","5.2.3","esm");/*!
|
|
55
55
|
* This file was lovingly and delicately extracted from Immutable.js
|
|
56
56
|
* MIT License: https://github.com/immutable-js/immutable-js/blob/main/LICENSE
|
|
57
57
|
* Copyright (c) 2014-present, Lee Byron and other contributors.
|
|
58
|
-
*/function pf(t){return t>>>1&1073741824|t&3221225471}var PR=Object.prototype.valueOf;function Eo(t){if(t==null)return yy(t);if(typeof t.hashCode==="function")return pf(t.hashCode(t));let n=NR(t);if(n==null)return yy(n);switch(typeof n){case"boolean":return n?1108378657:1108378656;case"number":return CR(n);case"string":return OR(n);case"object":case"function":return MR(n);case"symbol":return kR(n);default:if(typeof n.toString==="function")return Iy(n.toString());throw Error("Value type "+typeof n+" cannot be hashed.")}}function yy(t){return t===null?1108378658:1108378659}function CR(t){if(t!==t||t===1/0)return 0;let n=t|0;if(n!==t)n^=t*4294967295;while(t>4294967295)t/=4294967295,n^=t;return pf(n)}function OR(t){let n=uf[t];if(n===void 0){if(n=Iy(t),df===$R)df=0,uf={};uf[t]=n,df++}return n}function Iy(t){let n=0;for(let i=0;i<t.length;i++)n=31*n+t.charCodeAt(i)|0;return pf(n)}function kR(t){let n=Sy[t];if(n!==void 0)return n;return n=Ty(),Sy[t]=n,n}function MR(t){let n=wy.get(t);if(n!==void 0)return n;return n=Ty(),wy.set(t,n),n}function NR(t){return t.valueOf!==PR&&typeof t.valueOf==="function"?t.valueOf(t):t}function Ty(){let t=++lf;if(lf&1073741824)lf=0;return t}var wy=new WeakMap,Sy=Object.create(null),lf=0,uf={},df=0,$R=24000,Qo=5,za=1<<Qo,ea=za-1,ei={};function by(){return{value:!1}}function Xn(t){if(t)t.value=!0}function hf(t,n=0){return t.slice(n)}class mf{}class gf{_root;size;__ownerID;__hash;__altered;constructor(t){return t===void 0||t===null?vo():t instanceof gf?t:vo().withMutations((n)=>{for(let[i,o]of t)n.set(i,o)})}get(t,n){return this._root?this._root.get(0,void 0,t,n):n}set(t,n){return Ay(this,t,n)}delete(t){return Ay(this,t,ei)}deleteAll(t){return this.withMutations((n)=>{for(let i of t)n.delete(i)})}__ensureOwner(t){if(t===this.__ownerID)return this;if(!t){if(this.size===0)return vo();return this.__ownerID=t,this.__altered=!1,this}return Sf(this.size,this._root,t,this.__hash)}withMutations(t){let n=this.asMutable();return t(n),n.wasAltered()?n.__ensureOwner(this.__ownerID):this}wasAltered(){return this.__altered}asMutable(){return this.__ownerID?this:this.__ensureOwner(new mf)}[Symbol.iterator](){return this.entries()[Symbol.iterator]()}entries(){return new Al(this,DR,!1)}keys(){return new Al(this,Ry,!1)}values(){return new Al(this,Py,!1)}}class yf{constructor(t,n){this.ownerID=t,this.entries=n}ownerID;entries;get(t,n,i,o){let a=this.entries;for(let c=0,m=a.length;c<m;c++)if(Object.is(i,a[c][0]))return a[c][1];return o}update(t,n,i,o,a,c,m){let E=a===ei,_=this.entries,I=0,T=_.length;for(;I<T;I++)if(Object.is(o,_[I][0]))break;let R=I<T;if(R?_[I][1]===a:E)return this;if(Xn(m),E||!R)Xn(c);if(E&&_.length===1)return;if(!R&&!E&&_.length>=HR)return UR(t,_,o,a);let P=t&&t===this.ownerID,M=P?_:hf(_);if(R)if(E)if(I===T-1)M.pop();else M[I]=M.pop();else M[I]=[o,a];else M.push([o,a]);if(P)return this.entries=M,this;return new yf(t,M)}}class xl{constructor(t,n,i){this.ownerID=t,this.bitmap=n,this.nodes=i}ownerID;bitmap;nodes;get(t,n,i,o){if(n===void 0)n=Eo(i);let a=1<<((t===0?n:n>>>t)&ea),c=this.bitmap;return(c&a)===0?o:this.nodes[_y(c&a-1)].get(t+Qo,n,i,o)}update(t,n,i,o,a,c,m){if(i===void 0)i=Eo(o);let E=(n===0?i:i>>>n)&ea,_=1<<E,I=this.bitmap,T=(I&_)!==0;if(!T&&a===ei)return this;let R=_y(I&_-1),P=this.nodes,M=T?P[R]:void 0,N=bf(M,t,n+Qo,i,o,a,c,m);if(N===M)return this;if(!T&&N&&P.length>=VR)return qR(t,P,I,E,N);if(T&&!N&&P.length===2&&xy(P[R^1]))return P[R^1];if(T&&N&&P.length===1&&xy(N))return N;let H=t&&t===this.ownerID,Z=T?N?I:I^_:I|_,V=T?N?Cy(P,R,N,H):WR(P,R,H):BR(P,R,N,H);if(H)return this.bitmap=Z,this.nodes=V,this;return new xl(t,Z,V)}}class wf{constructor(t,n,i){this.ownerID=t,this.count=n,this.nodes=i}ownerID;count;nodes;get(t,n,i,o){if(n===void 0)n=Eo(i);let a=(t===0?n:n>>>t)&ea,c=this.nodes[a];return c?c.get(t+Qo,n,i,o):o}update(t,n,i,o,a,c,m){if(i===void 0)i=Eo(o);let E=(n===0?i:i>>>n)&ea,_=a===ei,I=this.nodes,T=I[E];if(_&&!T)return this;let R=bf(T,t,n+Qo,i,o,a,c,m);if(R===T)return this;let P=this.count;if(!T)P++;else if(!R){if(P--,P<zR)return FR(t,I,P,E)}let M=t&&t===this.ownerID,N=Cy(I,E,R,M);if(M)return this.count=P,this.nodes=N,this;return new wf(t,P,N)}}class _l{constructor(t,n,i){this.ownerID=t,this.keyHash=n,this.entries=i}ownerID;keyHash;entries;get(t,n,i,o){let a=this.entries;for(let c=0,m=a.length;c<m;c++)if(Object.is(i,a[c][0]))return a[c][1];return o}update(t,n,i,o,a,c,m){if(i===void 0)i=Eo(o);let E=a===ei;if(i!==this.keyHash){if(E)return this;return Xn(m),Xn(c),vf(this,t,n,i,[o,a])}let _=this.entries,I=0,T=_.length;for(;I<T;I++)if(Object.is(o,_[I][0]))break;let R=I<T;if(R?_[I][1]===a:E)return this;if(Xn(m),E||!R)Xn(c);if(E&&T===2)return new Ao(t,this.keyHash,_[I^1]);let P=t&&t===this.ownerID,M=P?_:hf(_);if(R)if(E)if(I===T-1)M.pop();else M[I]=M.pop();else M[I]=[o,a];else M.push([o,a]);if(P)return this.entries=M,this;return new _l(t,this.keyHash,M)}}class Ao{constructor(t,n,i){this.ownerID=t,this.keyHash=n,this.entry=i}ownerID;keyHash;entry;get(t,n,i,o){return Object.is(i,this.entry[0])?this.entry[1]:o}update(t,n,i,o,a,c,m){let E=a===ei,_=Object.is(o,this.entry[0]);if(_?a===this.entry[1]:E)return this;if(Xn(m),E){Xn(c);return}if(_){if(t&&t===this.ownerID)return this.entry[1]=a,this;return new Ao(t,this.keyHash,[o,a])}return Xn(c),vf(this,t,n,Eo(o),[o,a])}}class Al{constructor(t,n,i){this._type=n,this._reverse=i,this._stack=t._root&&vy(t._root)}_type;_reverse;_stack;[Symbol.iterator](){return this}next(){let t=this._type,n=this._stack;while(n){let i=n.node,o=n.index++,a;if(i.entry){if(o===0)return ff(t,i.entry)}else if("entries"in i&&i.entries){if(a=i.entries.length-1,o<=a)return ff(t,i.entries[this._reverse?a-o:o])}else if(a=i.nodes.length-1,o<=a){let c=i.nodes[this._reverse?a-o:o];if(c){if(c.entry)return ff(t,c.entry);n=this._stack=vy(c,n)}continue}n=this._stack=this._stack.__prev}return jR()}}function ff(t,n){return LR(t,n[0],n[1])}function vy(t,n){return{node:t,index:0,__prev:n}}var Ry=0,Py=1,DR=2;function LR(t,n,i,o){let a=t===Ry?n:t===Py?i:[n,i];if(o)o.value=a;else o={value:a,done:!1};return o}function jR(){return{value:void 0,done:!0}}function Sf(t,n,i,o){let a=Object.create(gf.prototype);return a.size=t,a._root=n,a.__ownerID=i,a.__hash=o,a.__altered=!1,a}var Ey;function vo(){return Ey||(Ey=Sf(0))}function Ay(t,n,i){let o,a;if(!t._root){if(i===ei)return t;a=1,o=new yf(t.__ownerID,[[n,i]])}else{let c=by(),m=by();if(o=bf(t._root,t.__ownerID,0,void 0,n,i,c,m),!m.value)return t;a=t.size+(c.value?i===ei?-1:1:0)}if(t.__ownerID)return t.size=a,t._root=o,t.__hash=void 0,t.__altered=!0,t;return o?Sf(a,o):vo()}function bf(t,n,i,o,a,c,m,E){if(!t){if(c===ei)return t;return Xn(E),Xn(m),new Ao(n,o,[a,c])}return t.update(n,i,o,a,c,m,E)}function xy(t){return t.constructor===Ao||t.constructor===_l}function vf(t,n,i,o,a){if(t.keyHash===o)return new _l(n,o,[t.entry,a]);let c=(i===0?t.keyHash:t.keyHash>>>i)&ea,m=(i===0?o:o>>>i)&ea,E,_=c===m?[vf(t,n,i+Qo,o,a)]:(E=new Ao(n,o,a),c<m?[t,E]:[E,t]);return new xl(n,1<<c|1<<m,_)}function UR(t,n,i,o){if(!t)t=new mf;let a=new Ao(t,Eo(i),[i,o]);for(let c=0;c<n.length;c++){let m=n[c];a=a.update(t,0,void 0,m[0],m[1])}return a}function FR(t,n,i,o){let a=0,c=0,m=Array(i);for(let E=0,_=1,I=n.length;E<I;E++,_<<=1){let T=n[E];if(T!==void 0&&E!==o)a|=_,m[c++]=T}return new xl(t,a,m)}function qR(t,n,i,o,a){let c=0,m=Array(za);for(let E=0;i!==0;E++,i>>>=1)m[E]=i&1?n[c++]:void 0;return m[o]=a,new wf(t,c+1,m)}function _y(t){return t-=t>>1&1431655765,t=(t&858993459)+(t>>2&858993459),t=t+(t>>4)&252645135,t+=t>>8,t+=t>>16,t&127}function Cy(t,n,i,o){let a=o?t:hf(t);return a[n]=i,a}function BR(t,n,i,o){let a=t.length+1;if(o&&n+1===a)return t[n]=i,t;let c=Array(a),m=0;for(let E=0;E<a;E++)if(E===n)c[E]=i,m=-1;else c[E]=t[E+m];return c}function WR(t,n,i){let o=t.length-1;if(i&&n===o)return t.pop(),t;let a=Array(o),c=0;for(let m=0;m<o;m++){if(m===n)c=1;a[m]=t[m+c]}return a}var HR=za/4,VR=za/2,zR=za/4;class ta{constructor(t,n){this.name=t;let i=vo();if(n)i=i.withMutations((o)=>{for(let[a,c]of n)o.set(a,ji(`${t}:${String(a)}`,c))});this.atoms=ji(`${t}:atoms`,i)}name;atoms;getAtom(t){let n=this.atoms.__unsafe__getWithoutCapture().get(t);if(!n){this.atoms.get();return}return n}get(t){let n=this.getAtom(t)?.get();return Fe(n!==er),n}__unsafe__getWithoutCapture(t){let n=this.atoms.__unsafe__getWithoutCapture().get(t);if(!n)return;let i=n.__unsafe__getWithoutCapture();return Fe(i!==er),i}has(t){let n=this.getAtom(t);if(!n)return!1;return n.get()!==er}__unsafe__hasWithoutCapture(t){let n=this.atoms.__unsafe__getWithoutCapture().get(t);if(!n)return!1;return Fe(n.__unsafe__getWithoutCapture()!==er),!0}set(t,n){let i=this.atoms.__unsafe__getWithoutCapture().get(t);if(i)i.set(n);else this.atoms.update((o)=>o.set(t,ji(`${this.name}:${String(t)}`,n)));return this}update(t,n){let i=this.atoms.__unsafe__getWithoutCapture().get(t);if(!i)throw Error(`AtomMap: key ${t} not found`);let o=i.__unsafe__getWithoutCapture();Fe(o!==er),i.set(n(o))}delete(t){let n=this.atoms.__unsafe__getWithoutCapture().get(t);if(!n)return!1;return $i(()=>{n.set(er),this.atoms.update((i)=>i.delete(t))}),!0}deleteMany(t){return $i(()=>{let n=[],i=this.atoms.get().withMutations((o)=>{for(let a of t){let c=o.get(a);if(!c)continue;let m=c.get();Fe(m!==er),n.push([a,m]),o.delete(a),c.set(er)}});if(n.length)this.atoms.set(i);return n})}clear(){return $i(()=>{for(let t of this.atoms.__unsafe__getWithoutCapture().values())t.set(er);this.atoms.set(vo())})}*entries(){for(let[t,n]of this.atoms.get()){let i=n.get();Fe(i!==er),yield[t,i]}}*keys(){for(let t of this.atoms.get().keys())yield t}*values(){for(let t of this.atoms.get().values()){let n=t.get();Fe(n!==er),yield n}}get size(){return this.atoms.get().size}forEach(t,n){for(let[i,o]of this.entries())t.call(n,o,i,this)}[Symbol.iterator](){return this.entries()}[Symbol.toStringTag]="AtomMap"}var Il=!1;try{Il=!0}catch(t){}try{Il=Il||import.meta.env.DEV||import.meta.env.TEST||import.meta.env.MODE==="development"||import.meta.env.MODE==="test"}catch(t){}function Oy(){return Il}function ti(t){if(!Oy())return t;let n=Object.getPrototypeOf(t);if(n&&!(Array.isArray(t)||n===Object.prototype||n===null||n===Fa))throw console.error("cannot include non-js data in a record",t),Error("cannot include non-js data in a record");if(Object.isFrozen(t))return t;let i=Object.getOwnPropertyNames(t);for(let o of i){let a=t[o];if(a&&typeof a==="object")ti(a)}return Object.freeze(t)}class ra{constructor(t){this.previousValue=t}previousValue;nextValue;diff;get(){let t=this.diff?.removed?.size??0,n=this.diff?.added?.size??0;if(t===0&&n===0)return;return{value:this.nextValue,diff:this.diff}}_add(t,n){if(this.nextValue??=new Set(this.previousValue),this.nextValue.add(t),this.diff??={},n)this.diff.removed?.delete(t);else this.diff.added??=new Set,this.diff.added.add(t)}add(t){let n=this.previousValue.has(t);if(n){if(!this.diff?.removed?.has(t))return;return this._add(t,n)}if(this.nextValue?.has(t))return;this._add(t,n)}_remove(t,n){if(this.nextValue??=new Set(this.previousValue),this.nextValue.delete(t),this.diff??={},n)this.diff.removed??=new Set,this.diff.removed.add(t);else this.diff.added?.delete(t)}remove(t){let n=this.previousValue.has(t);if(!n){if(!this.diff?.added?.has(t))return;return this._remove(t,n)}if(this.diff?.removed?.has(t))return;this._remove(t,n)}}function GR(t){let n=[];for(let i=t.length-1;i>=0;i--){let o=t[i];if(!("id"in o)){let a=o.dependsOn,c=n[0];if(c)n[0]={...c,dependsOn:a.concat(c.dependsOn??[])}}else n.unshift(o)}return n}function dn({sequence:t,sequenceId:n,retroactive:i=!0}){let o={sequenceId:n,retroactive:i,sequence:GR(t)};return Ef(o),o}function Be(t,n){return Object.fromEntries(Pn(n).map(([i,o])=>[i,`${t}/${o}`]))}function et(t){let n=t.sequenceId;return dn({sequenceId:n,retroactive:t.retroactive??!0,sequence:t.sequence.map((i)=>("id"in i)?{...i,scope:"record",filter:(o)=>o.typeName===t.recordType&&(i.filter?.(o)??!0)&&(t.filter?.(o)??!0)}:i)})}function My(t){if(t.length===0)return[];let n=new Map(t.map((_)=>[_.id,_])),i=new Map,o=new Map,a=new Map;for(let _ of t)o.set(_.id,0),i.set(_.id,new Set),a.set(_.id,new Set);for(let _ of t){let{version:I,sequenceId:T}=na(_.id),R=`${T}/${I-1}`;if(n.has(R))i.get(R).add(_.id),o.set(_.id,o.get(_.id)+1);if(_.dependsOn){for(let P of _.dependsOn)if(n.has(P))i.get(P).add(_.id),a.get(_.id).add(P),o.set(_.id,o.get(_.id)+1)}}let c=t.filter((_)=>o.get(_.id)===0),m=[],E=new Set;while(c.length>0){let _,I=-1/0;for(let R of c){let P=0;for(let M of i.get(R.id)||[])if(!E.has(M)){if(P+=1,a.get(M).has(R.id))P+=100}if(P>I||P===I&&R.id.localeCompare(_?.id??"")<0)_=R,I=P}let T=_;c.splice(c.indexOf(T),1),m.push(T),E.add(T.id);for(let R of i.get(T.id)||[])if(!E.has(R)){if(o.set(R,o.get(R)-1),o.get(R)===0)c.push(n.get(R))}}if(m.length!==t.length){let _=t.filter((I)=>!E.has(I.id));Fe(!1,`Circular dependency in migrations: ${_[0].id}`)}return m}function na(t){let[n,i]=t.split("/");return{sequenceId:n,version:parseInt(i)}}function ky(t,n){if(n)Fe(t.startsWith(n+"/"),`Every migration in sequence '${n}' must have an id starting with '${n}/'. Got invalid id: '${t}'`);Fe(t.match(/^(.*?)\/(0|[1-9]\d*)$/),`Invalid migration id: '${t}'`)}function Ef(t){if(Fe(!t.sequenceId.includes("/"),`sequenceId cannot contain a '/', got ${t.sequenceId}`),Fe(t.sequenceId.length,"sequenceId must be a non-empty string"),t.sequence.length===0)return;ky(t.sequence[0].id,t.sequenceId);let n=na(t.sequence[0].id).version;Fe(n===1,`Expected the first migrationId to be '${t.sequenceId}/1' but got '${t.sequence[0].id}'`);for(let i=1;i<t.sequence.length;i++){let o=t.sequence[i].id;ky(o,t.sequenceId);let a=na(o).version;Fe(a===n+1,`Migration id numbers must increase in increments of 1, expected ${t.sequenceId}/${n+1} but got '${t.sequence[i].id}'`),n=a}}var si={IncompatibleSubtype:"incompatible-subtype",UnknownType:"unknown-type",TargetVersionTooNew:"target-version-too-new",TargetVersionTooOld:"target-version-too-old",MigrationError:"migration-error",UnrecognizedSubtype:"unrecognized-subtype"};function sa(t){for(let n in t)return!0;return!1}function Tl(t,n){let i=n?.mutateFirstDiff?t[0]:{added:{},removed:{},updated:{}};return Ny(i,n?.mutateFirstDiff?t.slice(1):t),i}function Ny(t,n){for(let i of n){let o=sa(t.removed);for(let c in i.added){let m=c,E=i.added[m];if(o&&t.removed[m]){let _=t.removed[m];if(delete t.removed[m],_!==E)t.updated[m]=[_,E]}else t.added[m]=E}let a=sa(t.added);for(let c in i.updated){let m=c,E=i.updated[m][1];if(a&&t.added[m]){if(t.added[m]=E,delete t.updated[m],o)delete t.removed[m];continue}let _=t.updated[m];if(_){if(_[1]=E,o)delete t.removed[m];continue}if(t.updated[m]=[i.updated[m][0],E],o)delete t.removed[m]}for(let c in i.removed){let m=c;if(t.added[m])delete t.added[m];else if(t.updated[m])t.removed[m]=t.updated[m][0],delete t.updated[m];else t.removed[m]=i.removed[m]}}}class ia{constructor(t,n){this.typeName=t,this.createDefaultProperties=n.createDefaultProperties,this.validator=n.validator??{validate:(o)=>o},this.scope=n.scope??"document",this.ephemeralKeys=n.ephemeralKeys;let i=new Set;if(n.ephemeralKeys){for(let[o,a]of Pn(n.ephemeralKeys))if(a)i.add(o)}this.ephemeralKeySet=i}typeName;createDefaultProperties;validator;ephemeralKeys;ephemeralKeySet;scope;create(t){let n={...this.createDefaultProperties(),id:t.id??this.createId()};for(let[i,o]of Object.entries(t))if(o!==void 0)n[i]=o;return n.typeName=this.typeName,n}clone(t){return{...tn(t),id:this.createId()}}createId(t){return this.typeName+":"+(t??Ls())}parseId(t){if(!this.isId(t))throw Error(`ID "${t}" is not a valid ID for type "${this.typeName}"`);return t.slice(this.typeName.length+1)}isInstance(t){return t?.typeName===this.typeName}isId(t){if(!t)return!1;for(let n=0;n<this.typeName.length;n++)if(t[n]!==this.typeName[n])return!1;return t[this.typeName.length]===":"}withDefaultProperties(t){return new ia(this.typeName,{createDefaultProperties:t,validator:this.validator,scope:this.scope,ephemeralKeys:this.ephemeralKeys})}validate(t,n){if(n&&this.validator.validateUsingKnownGoodVersion)return this.validator.validateUsingKnownGoodVersion(n,t);return this.validator.validate(t)}}function rt(t,n){return new ia(t,{createDefaultProperties:()=>({}),validator:n.validator,scope:n.scope,ephemeralKeys:n.ephemeralKeys})}function $y(t){if(t.length===0)return new Set;let n=t[0],i=t.slice(1),o=new Set;for(let a of n)if(i.every((c)=>c.has(a)))o.add(a);return o}function Dy(t,n){let i={};for(let o of n)if(!t.has(o))i.added??=new Set,i.added.add(o);for(let o of t)if(!n.has(o))i.removed??=new Set,i.removed.add(o);return i.added||i.removed?i:void 0}function Ly(t){if(typeof t!=="object"||t===null)return!1;return"eq"in t||"neq"in t||"gt"in t}function jy(t,n=""){let i=[];for(let[o,a]of Object.entries(t)){let c=n?`${n}\\${o}`:o;if(Ly(a))i.push({path:c,matcher:a});else if(typeof a==="object"&&a!==null)i.push(...jy(a,c))}return i}function Rl(t,n){for(let[i,o]of Object.entries(t)){let a=n[i];if(Ly(o)){if("eq"in o&&a!==o.eq)return!1;if("neq"in o&&(a===o.neq||a===void 0))return!1;if("gt"in o&&(typeof a!=="number"||a<=o.gt))return!1;continue}if(typeof a!=="object"||a===null)return!1;if(!Rl(o,a))return!1}return!0}function Af(t,n,i){let o=jy(i),a=Object.fromEntries(o.map(({path:c})=>[c,new Set]));for(let{path:c,matcher:m}of o){let E=t.index(n,c);if("eq"in m){let _=E.get().get(m.eq);if(_)for(let I of _)a[c].add(I)}else if("neq"in m){for(let[_,I]of E.get())if(_!==m.neq)for(let T of I)a[c].add(T)}else if("gt"in m){for(let[_,I]of E.get())if(typeof _==="number"&&_>m.gt)for(let T of I)a[c].add(T)}if(a[c].size===0)return new Set}return $y(Object.values(a))}class Pl{constructor(t,n){this.recordMap=t,this.history=n}recordMap;history;indexCache=new Map;historyCache=new Map;getAllIdsForType(t){let n=new Set;for(let i of this.recordMap.values())if(i.typeName===t)n.add(i.id);return n}getRecordById(t,n){let i=this.recordMap.get(n);if(i&&i.typeName===t)return i;return}getNestedValue(t,n){let i=t;for(let o of n){if(i==null||typeof i!=="object")return;i=i[o]}return i}filterHistory(t){if(this.historyCache.has(t))return this.historyCache.get(t);let n=un("filterHistory:"+t,(i,o)=>{if(Ha(i))return this.history.get();let a=this.history.getDiffSince(o);if(a===Pr)return this.history.get();let c={added:{},removed:{},updated:{}},m=0,E=0,_=0;for(let I of a){for(let T of Lt(I.added))if(T.typeName===t)if(c.removed[T.id]){let R=c.removed[T.id];if(delete c.removed[T.id],E--,R!==T)c.updated[T.id]=[R,T],_++}else c.added[T.id]=T,m++;for(let[T,R]of Lt(I.updated))if(R.typeName===t)if(c.added[R.id])c.added[R.id]=R;else if(c.updated[R.id])c.updated[R.id]=[c.updated[R.id][0],R];else c.updated[R.id]=[T,R],_++;for(let T of Lt(I.removed))if(T.typeName===t)if(c.added[T.id])delete c.added[T.id],m--;else if(c.updated[T.id])c.removed[T.id]=c.updated[T.id][0],delete c.updated[T.id],_--,E++;else c.removed[T.id]=T,E++}if(m||E||_)return Zo(this.history.get(),c);else return i},{historyLength:100});return this.historyCache.set(t,n),n}index(t,n){let i=t+":"+n;if(this.indexCache.has(i))return this.indexCache.get(i);let o=this.__uncached_createIndex(t,n);return this.indexCache.set(i,o),o}__uncached_createIndex(t,n){let i=this.filterHistory(t),o=n.split("\\"),a=o.length>1?(m)=>this.getNestedValue(m,o):(m)=>m[n],c=()=>{i.get();let m=new Map;for(let E of this.recordMap.values())if(E.typeName===t){let _=a(E);if(_!==void 0){if(!m.has(_))m.set(_,new Set);m.get(_).add(E.id)}}return m};return un("index:"+t+":"+n,(m,E)=>{if(Ha(m))return c();let _=i.getDiffSince(E);if(_===Pr)return c();let I=new Map,T=(N,H)=>{let Z=I.get(N);if(!Z)Z=new ra(m.get(N)??new Set);Z.add(H),I.set(N,Z)},R=(N,H)=>{let Z=I.get(N);if(!Z)Z=new ra(m.get(N)??new Set);Z.remove(H),I.set(N,Z)};for(let N of _){for(let H of Lt(N.added))if(H.typeName===t){let Z=a(H);if(Z!==void 0)T(Z,H.id)}for(let[H,Z]of Lt(N.updated))if(Z.typeName===t){let V=a(H),me=a(Z);if(V!==me){if(V!==void 0)R(V,Z.id);if(me!==void 0)T(me,Z.id)}}for(let H of Lt(N.removed))if(H.typeName===t){let Z=a(H);if(Z!==void 0)R(Z,H.id)}}let P=void 0,M=void 0;for(let[N,H]of I){let Z=H.get();if(!Z)continue;if(!P)P=new Map(m);if(!M)M=new Map;if(Z.value.size===0)P.delete(N);else P.set(N,Z.value);M.set(N,Z.diff)}if(P&&M)return Zo(P,M);return m},{historyLength:100})}record(t,n=()=>({}),i="record:"+t+(n?":"+n.toString():"")){let o=this.ids(t,n,i);return un(i,()=>{for(let a of o.get())return this.recordMap.get(a);return})}records(t,n=()=>({}),i="records:"+t+(n?":"+n.toString():"")){let o=this.ids(t,n,"ids:"+i);return un(i,()=>Array.from(o.get(),(a)=>this.recordMap.get(a)),{isEqual:Jd})}ids(t,n=()=>({}),i="ids:"+t+(n?":"+n.toString():"")){let o=this.filterHistory(t),a=()=>{o.get();let E=n();if(Object.keys(E).length===0)return this.getAllIdsForType(t);return Af(this,t,E)},c=(E)=>{let _=a(),I=Dy(E,_);if(I)return Zo(_,I);else return E},m=un("ids_query:"+i,n,{isEqual:ki.default});return un("query:"+i,(E,_)=>{let I=m.get();if(Ha(E))return a();if(_<m.lastChangedEpoch)return c(E);let T=o.getDiffSince(_);if(T===Pr)return c(E);let R=new ra(E);for(let M of T){for(let N of Lt(M.added))if(N.typeName===t&&Rl(I,N))R.add(N.id);for(let[N,H]of Lt(M.updated))if(H.typeName===t)if(Rl(I,H))R.add(H.id);else R.remove(H.id);for(let N of Lt(M.removed))if(N.typeName===t)R.remove(N.id)}let P=R.get();if(!P)return E;return Zo(P.value,P.diff)},{historyLength:50})}exec(t,n){let i=Af(this,t,n);if(i.size===0)return bo;return Array.from(i,(o)=>this.recordMap.get(o))}}class Cl{constructor(t){this.store=t}store;_beforeCreateHandlers={};_afterCreateHandlers={};_beforeChangeHandlers={};_afterChangeHandlers={};_beforeDeleteHandlers={};_afterDeleteHandlers={};_operationCompleteHandlers=[];_isEnabled=!0;isEnabled(){return this._isEnabled}setIsEnabled(t){this._isEnabled=t}handleBeforeCreate(t,n){if(!this._isEnabled)return t;let i=this._beforeCreateHandlers[t.typeName];if(i){let o=t;for(let a of i)o=a(o,n);return o}return t}handleAfterCreate(t,n){if(!this._isEnabled)return;let i=this._afterCreateHandlers[t.typeName];if(i)for(let o of i)o(t,n)}handleBeforeChange(t,n,i){if(!this._isEnabled)return n;let o=this._beforeChangeHandlers[n.typeName];if(o){let a=n;for(let c of o)a=c(t,a,i);return a}return n}handleAfterChange(t,n,i){if(!this._isEnabled)return;let o=this._afterChangeHandlers[n.typeName];if(o)for(let a of o)a(t,n,i)}handleBeforeDelete(t,n){if(!this._isEnabled)return!0;let i=this._beforeDeleteHandlers[t.typeName];if(i){for(let o of i)if(o(t,n)===!1)return!1}return!0}handleAfterDelete(t,n){if(!this._isEnabled)return;let i=this._afterDeleteHandlers[t.typeName];if(i)for(let o of i)o(t,n)}handleOperationComplete(t){if(!this._isEnabled)return;for(let n of this._operationCompleteHandlers)n(t)}register(t){let n=[];for(let[i,o]of Object.entries(t)){if(o?.beforeCreate)n.push(this.registerBeforeCreateHandler(i,o.beforeCreate));if(o?.afterCreate)n.push(this.registerAfterCreateHandler(i,o.afterCreate));if(o?.beforeChange)n.push(this.registerBeforeChangeHandler(i,o.beforeChange));if(o?.afterChange)n.push(this.registerAfterChangeHandler(i,o.afterChange));if(o?.beforeDelete)n.push(this.registerBeforeDeleteHandler(i,o.beforeDelete));if(o?.afterDelete)n.push(this.registerAfterDeleteHandler(i,o.afterDelete))}return()=>{for(let i of n)i()}}registerBeforeCreateHandler(t,n){if(!this._beforeCreateHandlers[t])this._beforeCreateHandlers[t]=[];return this._beforeCreateHandlers[t].push(n),()=>xo(this._beforeCreateHandlers[t],n)}registerAfterCreateHandler(t,n){if(!this._afterCreateHandlers[t])this._afterCreateHandlers[t]=[];return this._afterCreateHandlers[t].push(n),()=>xo(this._afterCreateHandlers[t],n)}registerBeforeChangeHandler(t,n){if(!this._beforeChangeHandlers[t])this._beforeChangeHandlers[t]=[];return this._beforeChangeHandlers[t].push(n),()=>xo(this._beforeChangeHandlers[t],n)}registerAfterChangeHandler(t,n){if(!this._afterChangeHandlers[t])this._afterChangeHandlers[t]=[];return this._afterChangeHandlers[t].push(n),()=>xo(this._afterChangeHandlers[t],n)}registerBeforeDeleteHandler(t,n){if(!this._beforeDeleteHandlers[t])this._beforeDeleteHandlers[t]=[];return this._beforeDeleteHandlers[t].push(n),()=>xo(this._beforeDeleteHandlers[t],n)}registerAfterDeleteHandler(t,n){if(!this._afterDeleteHandlers[t])this._afterDeleteHandlers[t]=[];return this._afterDeleteHandlers[t].push(n),()=>xo(this._afterDeleteHandlers[t],n)}registerOperationCompleteHandler(t){return this._operationCompleteHandlers.push(t),()=>xo(this._operationCompleteHandlers,t)}}function xo(t,n){let i=t.indexOf(n);if(i>=0)t.splice(i,1)}class Ol{id;records;history=ji("history",0,{historyLength:1000});query;listeners=new Set;historyAccumulator=new Uy;historyReactor;cancelHistoryReactor(){}schema;props;scopedTypes;sideEffects=new Cl(this);constructor(t){let{initialData:n,schema:i,id:o}=t;if(this.id=o??Ls(),this.schema=i,this.props=t.props,n)this.records=new ta("store",Pn(n).map(([a,c])=>[a,ti(this.schema.validateRecord(this,c,"initialize",null))]));else this.records=new ta("store");this.query=new Pl(this.records,this.history),this.historyReactor=cf("Store.historyReactor",()=>{this.history.get(),this._flushHistory()},{scheduleEffect:(a)=>this.cancelHistoryReactor=sf(a)}),this.scopedTypes={document:new Set(Lt(this.schema.types).filter((a)=>a.scope==="document").map((a)=>a.typeName)),session:new Set(Lt(this.schema.types).filter((a)=>a.scope==="session").map((a)=>a.typeName)),presence:new Set(Lt(this.schema.types).filter((a)=>a.scope==="presence").map((a)=>a.typeName))}}_flushHistory(){if(this.historyAccumulator.hasChanges()){let t=this.historyAccumulator.flush();for(let{changes:n,source:i}of t){let o=null,a=null,c=null;for(let{onHistory:m,filters:E}of this.listeners){if(E.source!=="all"&&E.source!==i)continue;if(E.scope!=="all")if(E.scope==="document"){if(a??=this.filterChangesByScope(n,"document"),!a)continue;m({changes:a,source:i})}else if(E.scope==="session"){if(o??=this.filterChangesByScope(n,"session"),!o)continue;m({changes:o,source:i})}else{if(c??=this.filterChangesByScope(n,"presence"),!c)continue;m({changes:c,source:i})}else m({changes:n,source:i})}}}}dispose(){this.cancelHistoryReactor()}filterChangesByScope(t,n){let i={added:Ko(t.added,(o,a)=>this.scopedTypes[n].has(a.typeName)),updated:Ko(t.updated,(o,a)=>this.scopedTypes[n].has(a[1].typeName)),removed:Ko(t.removed,(o,a)=>this.scopedTypes[n].has(a.typeName))};if(!sa(i.added)&&!sa(i.updated)&&!sa(i.removed))return null;return i}updateHistory(t){if(this.historyAccumulator.add({changes:t,source:this.isMergingRemoteChanges?"remote":"user"}),this.listeners.size===0)this.historyAccumulator.clear();this.history.set(this.history.get()+1,t)}validate(t){this.allRecords().forEach((n)=>this.schema.validateRecord(this,n,t,null))}put(t,n){this.atomic(()=>{let i={},o={},a,c=!1,m=this.isMergingRemoteChanges?"remote":"user";for(let E=0,_=t.length;E<_;E++){a=t[E];let I=this.records.__unsafe__getWithoutCapture(a.id);if(I){a=this.sideEffects.handleBeforeChange(I,a,m);let T=this.schema.validateRecord(this,a,n??"updateRecord",I);if(T===I)continue;a=ti(T),this.records.set(a.id,a),c=!0,i[a.id]=[I,a],this.addDiffForAfterEvent(I,a)}else a=this.sideEffects.handleBeforeCreate(a,m),c=!0,a=this.schema.validateRecord(this,a,n??"createRecord",null),a=ti(a),o[a.id]=a,this.addDiffForAfterEvent(null,a),this.records.set(a.id,a)}if(!c)return;this.updateHistory({added:o,updated:i,removed:{}})})}remove(t){this.atomic(()=>{let n=new Set(t),i=this.isMergingRemoteChanges?"remote":"user";if(this.sideEffects.isEnabled())for(let c of t){let m=this.records.__unsafe__getWithoutCapture(c);if(!m)continue;if(this.sideEffects.handleBeforeDelete(m,i)===!1)n.delete(c)}let o=this.records.deleteMany(n);if(o.length===0)return;let a={};for(let[c,m]of o)a[c]=m,this.addDiffForAfterEvent(m,null);this.updateHistory({added:{},updated:{},removed:a})})}get(t){return this.records.get(t)}unsafeGetWithoutCapture(t){return this.records.__unsafe__getWithoutCapture(t)}serialize(t="document"){let n={};for(let[i,o]of this.records)if(t==="all"||this.scopedTypes[t].has(o.typeName))n[i]=o;return n}getStoreSnapshot(t="document"){return{store:this.serialize(t),schema:this.schema.serialize()}}migrateSnapshot(t){let n=this.schema.migrateStoreSnapshot(t);if(n.type==="error")throw Error(`Failed to migrate snapshot: ${n.reason}`);return{store:n.value,schema:this.schema.serialize()}}loadStoreSnapshot(t){let n=this.schema.migrateStoreSnapshot(t);if(n.type==="error")throw Error(`Failed to migrate snapshot: ${n.reason}`);let i=this.sideEffects.isEnabled();try{this.sideEffects.setIsEnabled(!1),this.atomic(()=>{this.clear(),this.put(Object.values(n.value)),this.ensureStoreIsUsable()},!1)}finally{this.sideEffects.setIsEnabled(i)}}allRecords(){return Array.from(this.records.values())}clear(){this.remove(Array.from(this.records.keys()))}update(t,n){let i=this.unsafeGetWithoutCapture(t);if(!i){console.error(`Record ${t} not found. This is probably an error`);return}this.put([n(i)])}has(t){return this.records.has(t)}listen(t,n){this._flushHistory();let i={onHistory:t,filters:{source:n?.source??"all",scope:n?.scope??"all"}};if(!this.historyReactor.scheduler.isActivelyListening)this.historyReactor.start(),this.historyReactor.scheduler.execute();return this.listeners.add(i),()=>{if(this.listeners.delete(i),this.listeners.size===0)this.historyReactor.stop()}}isMergingRemoteChanges=!1;mergeRemoteChanges(t){if(this.isMergingRemoteChanges)return t();if(this._isInAtomicOp)throw Error("Cannot merge remote changes while in atomic operation");try{this.atomic(t,!0,!0)}finally{this.ensureStoreIsUsable()}}extractingChanges(t){let n=[],i=this.historyAccumulator.addInterceptor((o)=>n.push(o.changes));try{return $i(t),Tl(n)}finally{i()}}applyDiff(t,{runCallbacks:n=!0,ignoreEphemeralKeys:i=!1}={}){this.atomic(()=>{let o=Lt(t.added);for(let[c,m]of Lt(t.updated)){let E=this.schema.getType(m.typeName);if(i&&E.ephemeralKeySet.size){let _=this.get(m.id);if(!_){o.push(m);continue}let I=null;for(let[T,R]of Object.entries(m)){if(E.ephemeralKeySet.has(T)||Object.is(R,gr(_,T)))continue;if(!I)I={..._};I[T]=R}if(I)o.push(I)}else o.push(m)}let a=Xd(t.removed);if(o.length)this.put(o);if(a.length)this.remove(a)},n)}createCache(t){let n=new ml;return{get:(i)=>{let o=this.records.getAtom(i);if(!o)return;return n.get(o,()=>t(i,o)).get()}}}createComputedCache(t,n,i){return this.createCache((o,a)=>{let c=i?.areRecordsEqual?un(`${t}:${o}:isEqual`,()=>a.get(),{isEqual:i.areRecordsEqual}):a;return un(t+":"+o,()=>n(c.get()),{isEqual:i?.areResultsEqual})})}_integrityChecker;ensureStoreIsUsable(){this.atomic(()=>{this._integrityChecker??=this.schema.createIntegrityChecker(this),this._integrityChecker?.()})}_isPossiblyCorrupted=!1;markAsPossiblyCorrupted(){this._isPossiblyCorrupted=!0}isPossiblyCorrupted(){return this._isPossiblyCorrupted}pendingAfterEvents=null;addDiffForAfterEvent(t,n){if(Fe(this.pendingAfterEvents,"must be in event operation"),t===n)return;if(t&&n)Fe(t.id===n.id);if(!t&&!n)return;let i=(t||n).id,o=this.pendingAfterEvents.get(i);if(o)o.after=n;else this.pendingAfterEvents.set(i,{before:t,after:n})}flushAtomicCallbacks(t){let n=0,i=t?"remote":"user";while(this.pendingAfterEvents){let o=this.pendingAfterEvents;if(this.pendingAfterEvents=null,!this.sideEffects.isEnabled())continue;if(n++,n>100)throw Error("Maximum store update depth exceeded, bailing out");for(let{before:a,after:c}of o.values())if(a&&c&&a!==c&&!ki.default(a,c))this.sideEffects.handleAfterChange(a,c,i);else if(a&&!c)this.sideEffects.handleAfterDelete(a,i);else if(!a&&c)this.sideEffects.handleAfterCreate(c,i);if(!this.pendingAfterEvents)this.sideEffects.handleOperationComplete(i);else i="user"}}_isInAtomicOp=!1;atomic(t,n=!0,i=!1){return $i(()=>{if(this._isInAtomicOp){if(!this.pendingAfterEvents)this.pendingAfterEvents=new Map;let a=this.sideEffects.isEnabled();Fe(!i,"cannot call mergeRemoteChanges while in atomic operation");try{if(a&&!n)this.sideEffects.setIsEnabled(!1);return t()}finally{this.sideEffects.setIsEnabled(a)}}this.pendingAfterEvents=new Map;let o=this.sideEffects.isEnabled();if(this.sideEffects.setIsEnabled(n&&o),this._isInAtomicOp=!0,i)this.isMergingRemoteChanges=!0;try{let a=t();return this.isMergingRemoteChanges=!1,this.flushAtomicCallbacks(i),a}finally{this.pendingAfterEvents=null,this.sideEffects.setIsEnabled(o),this._isInAtomicOp=!1,this.isMergingRemoteChanges=!1}})}addHistoryInterceptor(t){return this.historyAccumulator.addInterceptor((n)=>t(n,this.isMergingRemoteChanges?"remote":"user"))}}function KR(t){if(t.length===0)return[];let n=[],i=[t[0]],o;for(let a=1,c=t.length;a<c;a++){if(o=t[a],i[0].source!==o.source)n.push(i),i=[];i.push(o)}return n.push(i),ti(n.map((a)=>({source:a[0].source,changes:a.length===1?a[0].changes:Tl(a.map((c)=>c.changes))})))}class Uy{_history=[];_interceptors=new Set;addInterceptor(t){return this._interceptors.add(t),()=>{this._interceptors.delete(t)}}add(t){this._history.push(t);for(let n of this._interceptors)n(t)}flush(){let t=KR(this._history);return this._history=[],t}clear(){this._history=[]}hasChanges(){return this._history.length>0}}function JR(t){if(t.schemaVersion>2||t.schemaVersion<1)return $s.err("Bad schema version");if(t.schemaVersion===2)return $s.ok(t);let n={schemaVersion:2,sequences:{"com.tldraw.store":t.storeVersion}};for(let[i,o]of Object.entries(t.recordVersions))if(n.sequences[`com.tldraw.${i}`]=o.version,"subTypeKey"in o)for(let[a,c]of Object.entries(o.subTypeVersions))n.sequences[`com.tldraw.${i}.${a}`]=c;return $s.ok(n)}class Ga{constructor(t,n){this.types=t,this.options=n;for(let o of n.migrations??[])Fe(!this.migrations[o.sequenceId],`Duplicate migration sequenceId ${o.sequenceId}`),Ef(o),this.migrations[o.sequenceId]=o;let i=Object.values(this.migrations).flatMap((o)=>o.sequence);this.sortedMigrations=My(i);for(let o of this.sortedMigrations){if(!o.dependsOn?.length)continue;for(let a of o.dependsOn){let c=i.find((m)=>m.id===a);Fe(c,`Migration '${o.id}' depends on missing migration '${a}'`)}}}types;options;static create(t,n){return new Ga(t,n??{})}migrations={};sortedMigrations;migrationCache=new WeakMap;validateRecord(t,n,i,o){try{let a=gr(this.types,n.typeName);if(!a)throw Error(`Missing definition for record type ${n.typeName}`);return a.validate(n,o??void 0)}catch(a){if(this.options.onValidationFailure)return this.options.onValidationFailure({store:t,record:n,phase:i,recordBefore:o,error:a});else throw a}}getMigrationsSince(t){let n=this.migrationCache.get(t);if(n)return n;let i=JR(t);if(!i.ok)return this.migrationCache.set(t,i),i;let o=i.value,a=new Set(Object.keys(o.sequences).filter((E)=>this.migrations[E]));for(let E in this.migrations)if(o.sequences[E]===void 0&&this.migrations[E].retroactive)a.add(E);if(a.size===0){let E=$s.ok([]);return this.migrationCache.set(t,E),E}let c=new Set;for(let E of a){let _=o.sequences[E];if(typeof _!=="number"&&this.migrations[E].retroactive||_===0){for(let R of this.migrations[E].sequence)c.add(R.id);continue}let I=`${E}/${_}`,T=this.migrations[E].sequence.findIndex((R)=>R.id===I);if(T===-1){let R=$s.err("Incompatible schema?");return this.migrationCache.set(t,R),R}for(let R of this.migrations[E].sequence.slice(T+1))c.add(R.id)}let m=$s.ok(this.sortedMigrations.filter(({id:E})=>c.has(E)));return this.migrationCache.set(t,m),m}migratePersistedRecord(t,n,i="up"){let o=this.getMigrationsSince(n);if(!o.ok)return console.error("Error migrating record",o.error),{type:"error",reason:si.MigrationError};let a=o.value;if(a.length===0)return{type:"success",value:t};if(!a.every((c)=>c.scope==="record"))return{type:"error",reason:i==="down"?si.TargetVersionTooOld:si.TargetVersionTooNew};if(i==="down"){if(!a.every((c)=>c.scope==="record"&&c.down))return{type:"error",reason:si.TargetVersionTooOld};a=a.slice().reverse()}t=tn(t);try{for(let c of a){if(c.scope==="store")throw Error();if(c.scope==="storage")throw Error();if(!(c.filter?c.filter(t):!0))continue;let E=c[i](t);if(E)t=tn(E)}}catch(c){return console.error("Error migrating record",c),{type:"error",reason:si.MigrationError}}return{type:"success",value:t}}migrateStorage(t){let n=t.getSchema();Fe(n,"Schema is missing.");let i=this.getMigrationsSince(n);if(!i.ok)throw console.error("Error migrating store",i.error),Error(i.error);let o=i.value;if(o.length===0)return;t.setSchema(this.serialize());for(let a of o)if(a.scope==="record"){let c=[];for(let[m,E]of t.entries()){if(!(a.filter?a.filter(E):!0))continue;let I=tn(E),T=a.up(I)??I;if(!ki.default(T,E))c.push([m,T])}for(let[m,E]of c)t.set(m,E)}else if(a.scope==="store"){let c=Object.fromEntries(t.entries()),m=tn(c);m=a.up(m)??m;for(let[E,_]of Object.entries(m)){if(!_)continue;if(!ki.default(_,c[E]))t.set(E,_)}for(let E of Object.keys(c))if(!m[E])t.delete(E)}else if(a.scope==="storage")a.up(t);else ja(a);for(let[a,c]of t.entries())if(this.getType(c.typeName).scope!=="document")t.delete(a)}migrateStoreSnapshot(t,n){let i=this.getMigrationsSince(t.schema);if(!i.ok)return console.error("Error migrating store",i.error),{type:"error",reason:si.MigrationError};if(i.value.length===0)return{type:"success",value:t.store};let a=Object.assign(new Map(Pn(t.store).map(ti)),{getSchema:()=>t.schema,setSchema:(c)=>{}});try{if(this.migrateStorage(a),n?.mutateInputStore){for(let[c,m]of a.entries())t.store[c]=m;for(let c of Object.keys(t.store))if(!a.has(c))delete t.store[c];return{type:"success",value:t.store}}else return{type:"success",value:Object.fromEntries(a.entries())}}catch(c){return console.error("Error migrating store",c),{type:"error",reason:si.MigrationError}}}createIntegrityChecker(t){return this.options.createIntegrityChecker?.(t)??void 0}serialize(){return{schemaVersion:2,sequences:Object.fromEntries(Object.values(this.migrations).map(({sequenceId:t,sequence:n})=>[t,n.length?na(n.at(-1).id).version:0]))}}serializeEarliestVersion(){return{schemaVersion:2,sequences:Object.fromEntries(Object.values(this.migrations).map(({sequenceId:t})=>[t,0]))}}getType(t){let n=gr(this.types,t);return Fe(n,"record type does not exist"),n}}Tn("@tldraw/store","5.2.3","esm");var YR=!0;function XR(t){if(!t.length)return null;let n="";for(let i of t)if(typeof i==="number")n+=`.${i}`;else if(i.startsWith("("))if(n.endsWith(")"))n=`${n.slice(0,-1)}, ${i.slice(1)}`;else n+=i;else n+=`.${i}`;if(n=n.replace(/id = [^,]+, /,"").replace(/id = [^)]+/,""),n.startsWith("."))return n.slice(1);return n}class ge extends Error{constructor(t,n=[]){let i=XR(n),o=t.split(`
|
|
58
|
+
*/function pf(t){return t>>>1&1073741824|t&3221225471}var PR=Object.prototype.valueOf;function Eo(t){if(t==null)return yy(t);if(typeof t.hashCode==="function")return pf(t.hashCode(t));let n=NR(t);if(n==null)return yy(n);switch(typeof n){case"boolean":return n?1108378657:1108378656;case"number":return CR(n);case"string":return OR(n);case"object":case"function":return MR(n);case"symbol":return kR(n);default:if(typeof n.toString==="function")return Iy(n.toString());throw Error("Value type "+typeof n+" cannot be hashed.")}}function yy(t){return t===null?1108378658:1108378659}function CR(t){if(t!==t||t===1/0)return 0;let n=t|0;if(n!==t)n^=t*4294967295;while(t>4294967295)t/=4294967295,n^=t;return pf(n)}function OR(t){let n=uf[t];if(n===void 0){if(n=Iy(t),df===$R)df=0,uf={};uf[t]=n,df++}return n}function Iy(t){let n=0;for(let i=0;i<t.length;i++)n=31*n+t.charCodeAt(i)|0;return pf(n)}function kR(t){let n=Sy[t];if(n!==void 0)return n;return n=Ty(),Sy[t]=n,n}function MR(t){let n=wy.get(t);if(n!==void 0)return n;return n=Ty(),wy.set(t,n),n}function NR(t){return t.valueOf!==PR&&typeof t.valueOf==="function"?t.valueOf(t):t}function Ty(){let t=++lf;if(lf&1073741824)lf=0;return t}var wy=new WeakMap,Sy=Object.create(null),lf=0,uf={},df=0,$R=24000,Qo=5,za=1<<Qo,ea=za-1,ei={};function by(){return{value:!1}}function Xn(t){if(t)t.value=!0}function hf(t,n=0){return t.slice(n)}class mf{}class gf{_root;size;__ownerID;__hash;__altered;constructor(t){return t===void 0||t===null?vo():t instanceof gf?t:vo().withMutations((n)=>{for(let[i,o]of t)n.set(i,o)})}get(t,n){return this._root?this._root.get(0,void 0,t,n):n}set(t,n){return Ay(this,t,n)}delete(t){return Ay(this,t,ei)}deleteAll(t){return this.withMutations((n)=>{for(let i of t)n.delete(i)})}__ensureOwner(t){if(t===this.__ownerID)return this;if(!t){if(this.size===0)return vo();return this.__ownerID=t,this.__altered=!1,this}return Sf(this.size,this._root,t,this.__hash)}withMutations(t){let n=this.asMutable();return t(n),n.wasAltered()?n.__ensureOwner(this.__ownerID):this}wasAltered(){return this.__altered}asMutable(){return this.__ownerID?this:this.__ensureOwner(new mf)}[Symbol.iterator](){return this.entries()[Symbol.iterator]()}entries(){return new Al(this,DR,!1)}keys(){return new Al(this,Ry,!1)}values(){return new Al(this,Py,!1)}}class yf{constructor(t,n){this.ownerID=t,this.entries=n}ownerID;entries;get(t,n,i,o){let a=this.entries;for(let c=0,m=a.length;c<m;c++)if(Object.is(i,a[c][0]))return a[c][1];return o}update(t,n,i,o,a,c,m){let E=a===ei,_=this.entries,I=0,T=_.length;for(;I<T;I++)if(Object.is(o,_[I][0]))break;let R=I<T;if(R?_[I][1]===a:E)return this;if(Xn(m),E||!R)Xn(c);if(E&&_.length===1)return;if(!R&&!E&&_.length>=HR)return UR(t,_,o,a);let P=t&&t===this.ownerID,M=P?_:hf(_);if(R)if(E)if(I===T-1)M.pop();else M[I]=M.pop();else M[I]=[o,a];else M.push([o,a]);if(P)return this.entries=M,this;return new yf(t,M)}}class xl{constructor(t,n,i){this.ownerID=t,this.bitmap=n,this.nodes=i}ownerID;bitmap;nodes;get(t,n,i,o){if(n===void 0)n=Eo(i);let a=1<<((t===0?n:n>>>t)&ea),c=this.bitmap;return(c&a)===0?o:this.nodes[_y(c&a-1)].get(t+Qo,n,i,o)}update(t,n,i,o,a,c,m){if(i===void 0)i=Eo(o);let E=(n===0?i:i>>>n)&ea,_=1<<E,I=this.bitmap,T=(I&_)!==0;if(!T&&a===ei)return this;let R=_y(I&_-1),P=this.nodes,M=T?P[R]:void 0,N=bf(M,t,n+Qo,i,o,a,c,m);if(N===M)return this;if(!T&&N&&P.length>=VR)return qR(t,P,I,E,N);if(T&&!N&&P.length===2&&xy(P[R^1]))return P[R^1];if(T&&N&&P.length===1&&xy(N))return N;let H=t&&t===this.ownerID,Z=T?N?I:I^_:I|_,V=T?N?Cy(P,R,N,H):WR(P,R,H):BR(P,R,N,H);if(H)return this.bitmap=Z,this.nodes=V,this;return new xl(t,Z,V)}}class wf{constructor(t,n,i){this.ownerID=t,this.count=n,this.nodes=i}ownerID;count;nodes;get(t,n,i,o){if(n===void 0)n=Eo(i);let a=(t===0?n:n>>>t)&ea,c=this.nodes[a];return c?c.get(t+Qo,n,i,o):o}update(t,n,i,o,a,c,m){if(i===void 0)i=Eo(o);let E=(n===0?i:i>>>n)&ea,_=a===ei,I=this.nodes,T=I[E];if(_&&!T)return this;let R=bf(T,t,n+Qo,i,o,a,c,m);if(R===T)return this;let P=this.count;if(!T)P++;else if(!R){if(P--,P<zR)return FR(t,I,P,E)}let M=t&&t===this.ownerID,N=Cy(I,E,R,M);if(M)return this.count=P,this.nodes=N,this;return new wf(t,P,N)}}class _l{constructor(t,n,i){this.ownerID=t,this.keyHash=n,this.entries=i}ownerID;keyHash;entries;get(t,n,i,o){let a=this.entries;for(let c=0,m=a.length;c<m;c++)if(Object.is(i,a[c][0]))return a[c][1];return o}update(t,n,i,o,a,c,m){if(i===void 0)i=Eo(o);let E=a===ei;if(i!==this.keyHash){if(E)return this;return Xn(m),Xn(c),vf(this,t,n,i,[o,a])}let _=this.entries,I=0,T=_.length;for(;I<T;I++)if(Object.is(o,_[I][0]))break;let R=I<T;if(R?_[I][1]===a:E)return this;if(Xn(m),E||!R)Xn(c);if(E&&T===2)return new Ao(t,this.keyHash,_[I^1]);let P=t&&t===this.ownerID,M=P?_:hf(_);if(R)if(E)if(I===T-1)M.pop();else M[I]=M.pop();else M[I]=[o,a];else M.push([o,a]);if(P)return this.entries=M,this;return new _l(t,this.keyHash,M)}}class Ao{constructor(t,n,i){this.ownerID=t,this.keyHash=n,this.entry=i}ownerID;keyHash;entry;get(t,n,i,o){return Object.is(i,this.entry[0])?this.entry[1]:o}update(t,n,i,o,a,c,m){let E=a===ei,_=Object.is(o,this.entry[0]);if(_?a===this.entry[1]:E)return this;if(Xn(m),E){Xn(c);return}if(_){if(t&&t===this.ownerID)return this.entry[1]=a,this;return new Ao(t,this.keyHash,[o,a])}return Xn(c),vf(this,t,n,Eo(o),[o,a])}}class Al{constructor(t,n,i){this._type=n,this._reverse=i,this._stack=t._root&&vy(t._root)}_type;_reverse;_stack;[Symbol.iterator](){return this}next(){let t=this._type,n=this._stack;while(n){let i=n.node,o=n.index++,a;if(i.entry){if(o===0)return ff(t,i.entry)}else if("entries"in i&&i.entries){if(a=i.entries.length-1,o<=a)return ff(t,i.entries[this._reverse?a-o:o])}else if(a=i.nodes.length-1,o<=a){let c=i.nodes[this._reverse?a-o:o];if(c){if(c.entry)return ff(t,c.entry);n=this._stack=vy(c,n)}continue}n=this._stack=this._stack.__prev}return jR()}}function ff(t,n){return LR(t,n[0],n[1])}function vy(t,n){return{node:t,index:0,__prev:n}}var Ry=0,Py=1,DR=2;function LR(t,n,i,o){let a=t===Ry?n:t===Py?i:[n,i];if(o)o.value=a;else o={value:a,done:!1};return o}function jR(){return{value:void 0,done:!0}}function Sf(t,n,i,o){let a=Object.create(gf.prototype);return a.size=t,a._root=n,a.__ownerID=i,a.__hash=o,a.__altered=!1,a}var Ey;function vo(){return Ey||(Ey=Sf(0))}function Ay(t,n,i){let o,a;if(!t._root){if(i===ei)return t;a=1,o=new yf(t.__ownerID,[[n,i]])}else{let c=by(),m=by();if(o=bf(t._root,t.__ownerID,0,void 0,n,i,c,m),!m.value)return t;a=t.size+(c.value?i===ei?-1:1:0)}if(t.__ownerID)return t.size=a,t._root=o,t.__hash=void 0,t.__altered=!0,t;return o?Sf(a,o):vo()}function bf(t,n,i,o,a,c,m,E){if(!t){if(c===ei)return t;return Xn(E),Xn(m),new Ao(n,o,[a,c])}return t.update(n,i,o,a,c,m,E)}function xy(t){return t.constructor===Ao||t.constructor===_l}function vf(t,n,i,o,a){if(t.keyHash===o)return new _l(n,o,[t.entry,a]);let c=(i===0?t.keyHash:t.keyHash>>>i)&ea,m=(i===0?o:o>>>i)&ea,E,_=c===m?[vf(t,n,i+Qo,o,a)]:(E=new Ao(n,o,a),c<m?[t,E]:[E,t]);return new xl(n,1<<c|1<<m,_)}function UR(t,n,i,o){if(!t)t=new mf;let a=new Ao(t,Eo(i),[i,o]);for(let c=0;c<n.length;c++){let m=n[c];a=a.update(t,0,void 0,m[0],m[1])}return a}function FR(t,n,i,o){let a=0,c=0,m=Array(i);for(let E=0,_=1,I=n.length;E<I;E++,_<<=1){let T=n[E];if(T!==void 0&&E!==o)a|=_,m[c++]=T}return new xl(t,a,m)}function qR(t,n,i,o,a){let c=0,m=Array(za);for(let E=0;i!==0;E++,i>>>=1)m[E]=i&1?n[c++]:void 0;return m[o]=a,new wf(t,c+1,m)}function _y(t){return t-=t>>1&1431655765,t=(t&858993459)+(t>>2&858993459),t=t+(t>>4)&252645135,t+=t>>8,t+=t>>16,t&127}function Cy(t,n,i,o){let a=o?t:hf(t);return a[n]=i,a}function BR(t,n,i,o){let a=t.length+1;if(o&&n+1===a)return t[n]=i,t;let c=Array(a),m=0;for(let E=0;E<a;E++)if(E===n)c[E]=i,m=-1;else c[E]=t[E+m];return c}function WR(t,n,i){let o=t.length-1;if(i&&n===o)return t.pop(),t;let a=Array(o),c=0;for(let m=0;m<o;m++){if(m===n)c=1;a[m]=t[m+c]}return a}var HR=za/4,VR=za/2,zR=za/4;class ta{constructor(t,n){this.name=t;let i=vo();if(n)i=i.withMutations((o)=>{for(let[a,c]of n)o.set(a,ji(`${t}:${String(a)}`,c))});this.atoms=ji(`${t}:atoms`,i)}name;atoms;getAtom(t){let n=this.atoms.__unsafe__getWithoutCapture().get(t);if(!n){this.atoms.get();return}return n}get(t){let n=this.getAtom(t)?.get();return qe(n!==er),n}__unsafe__getWithoutCapture(t){let n=this.atoms.__unsafe__getWithoutCapture().get(t);if(!n)return;let i=n.__unsafe__getWithoutCapture();return qe(i!==er),i}has(t){let n=this.getAtom(t);if(!n)return!1;return n.get()!==er}__unsafe__hasWithoutCapture(t){let n=this.atoms.__unsafe__getWithoutCapture().get(t);if(!n)return!1;return qe(n.__unsafe__getWithoutCapture()!==er),!0}set(t,n){let i=this.atoms.__unsafe__getWithoutCapture().get(t);if(i)i.set(n);else this.atoms.update((o)=>o.set(t,ji(`${this.name}:${String(t)}`,n)));return this}update(t,n){let i=this.atoms.__unsafe__getWithoutCapture().get(t);if(!i)throw Error(`AtomMap: key ${t} not found`);let o=i.__unsafe__getWithoutCapture();qe(o!==er),i.set(n(o))}delete(t){let n=this.atoms.__unsafe__getWithoutCapture().get(t);if(!n)return!1;return $i(()=>{n.set(er),this.atoms.update((i)=>i.delete(t))}),!0}deleteMany(t){return $i(()=>{let n=[],i=this.atoms.get().withMutations((o)=>{for(let a of t){let c=o.get(a);if(!c)continue;let m=c.get();qe(m!==er),n.push([a,m]),o.delete(a),c.set(er)}});if(n.length)this.atoms.set(i);return n})}clear(){return $i(()=>{for(let t of this.atoms.__unsafe__getWithoutCapture().values())t.set(er);this.atoms.set(vo())})}*entries(){for(let[t,n]of this.atoms.get()){let i=n.get();qe(i!==er),yield[t,i]}}*keys(){for(let t of this.atoms.get().keys())yield t}*values(){for(let t of this.atoms.get().values()){let n=t.get();qe(n!==er),yield n}}get size(){return this.atoms.get().size}forEach(t,n){for(let[i,o]of this.entries())t.call(n,o,i,this)}[Symbol.iterator](){return this.entries()}[Symbol.toStringTag]="AtomMap"}var Il=!1;try{Il=!0}catch(t){}try{Il=Il||import.meta.env.DEV||import.meta.env.TEST||import.meta.env.MODE==="development"||import.meta.env.MODE==="test"}catch(t){}function Oy(){return Il}function ti(t){if(!Oy())return t;let n=Object.getPrototypeOf(t);if(n&&!(Array.isArray(t)||n===Object.prototype||n===null||n===Fa))throw console.error("cannot include non-js data in a record",t),Error("cannot include non-js data in a record");if(Object.isFrozen(t))return t;let i=Object.getOwnPropertyNames(t);for(let o of i){let a=t[o];if(a&&typeof a==="object")ti(a)}return Object.freeze(t)}class ra{constructor(t){this.previousValue=t}previousValue;nextValue;diff;get(){let t=this.diff?.removed?.size??0,n=this.diff?.added?.size??0;if(t===0&&n===0)return;return{value:this.nextValue,diff:this.diff}}_add(t,n){if(this.nextValue??=new Set(this.previousValue),this.nextValue.add(t),this.diff??={},n)this.diff.removed?.delete(t);else this.diff.added??=new Set,this.diff.added.add(t)}add(t){let n=this.previousValue.has(t);if(n){if(!this.diff?.removed?.has(t))return;return this._add(t,n)}if(this.nextValue?.has(t))return;this._add(t,n)}_remove(t,n){if(this.nextValue??=new Set(this.previousValue),this.nextValue.delete(t),this.diff??={},n)this.diff.removed??=new Set,this.diff.removed.add(t);else this.diff.added?.delete(t)}remove(t){let n=this.previousValue.has(t);if(!n){if(!this.diff?.added?.has(t))return;return this._remove(t,n)}if(this.diff?.removed?.has(t))return;this._remove(t,n)}}function GR(t){let n=[];for(let i=t.length-1;i>=0;i--){let o=t[i];if(!("id"in o)){let a=o.dependsOn,c=n[0];if(c)n[0]={...c,dependsOn:a.concat(c.dependsOn??[])}}else n.unshift(o)}return n}function dn({sequence:t,sequenceId:n,retroactive:i=!0}){let o={sequenceId:n,retroactive:i,sequence:GR(t)};return Ef(o),o}function He(t,n){return Object.fromEntries(Pn(n).map(([i,o])=>[i,`${t}/${o}`]))}function Ze(t){let n=t.sequenceId;return dn({sequenceId:n,retroactive:t.retroactive??!0,sequence:t.sequence.map((i)=>("id"in i)?{...i,scope:"record",filter:(o)=>o.typeName===t.recordType&&(i.filter?.(o)??!0)&&(t.filter?.(o)??!0)}:i)})}function My(t){if(t.length===0)return[];let n=new Map(t.map((_)=>[_.id,_])),i=new Map,o=new Map,a=new Map;for(let _ of t)o.set(_.id,0),i.set(_.id,new Set),a.set(_.id,new Set);for(let _ of t){let{version:I,sequenceId:T}=na(_.id),R=`${T}/${I-1}`;if(n.has(R))i.get(R).add(_.id),o.set(_.id,o.get(_.id)+1);if(_.dependsOn){for(let P of _.dependsOn)if(n.has(P))i.get(P).add(_.id),a.get(_.id).add(P),o.set(_.id,o.get(_.id)+1)}}let c=t.filter((_)=>o.get(_.id)===0),m=[],E=new Set;while(c.length>0){let _,I=-1/0;for(let R of c){let P=0;for(let M of i.get(R.id)||[])if(!E.has(M)){if(P+=1,a.get(M).has(R.id))P+=100}if(P>I||P===I&&R.id.localeCompare(_?.id??"")<0)_=R,I=P}let T=_;c.splice(c.indexOf(T),1),m.push(T),E.add(T.id);for(let R of i.get(T.id)||[])if(!E.has(R)){if(o.set(R,o.get(R)-1),o.get(R)===0)c.push(n.get(R))}}if(m.length!==t.length){let _=t.filter((I)=>!E.has(I.id));qe(!1,`Circular dependency in migrations: ${_[0].id}`)}return m}function na(t){let[n,i]=t.split("/");return{sequenceId:n,version:parseInt(i)}}function ky(t,n){if(n)qe(t.startsWith(n+"/"),`Every migration in sequence '${n}' must have an id starting with '${n}/'. Got invalid id: '${t}'`);qe(t.match(/^(.*?)\/(0|[1-9]\d*)$/),`Invalid migration id: '${t}'`)}function Ef(t){if(qe(!t.sequenceId.includes("/"),`sequenceId cannot contain a '/', got ${t.sequenceId}`),qe(t.sequenceId.length,"sequenceId must be a non-empty string"),t.sequence.length===0)return;ky(t.sequence[0].id,t.sequenceId);let n=na(t.sequence[0].id).version;qe(n===1,`Expected the first migrationId to be '${t.sequenceId}/1' but got '${t.sequence[0].id}'`);for(let i=1;i<t.sequence.length;i++){let o=t.sequence[i].id;ky(o,t.sequenceId);let a=na(o).version;qe(a===n+1,`Migration id numbers must increase in increments of 1, expected ${t.sequenceId}/${n+1} but got '${t.sequence[i].id}'`),n=a}}var si={IncompatibleSubtype:"incompatible-subtype",UnknownType:"unknown-type",TargetVersionTooNew:"target-version-too-new",TargetVersionTooOld:"target-version-too-old",MigrationError:"migration-error",UnrecognizedSubtype:"unrecognized-subtype"};function sa(t){for(let n in t)return!0;return!1}function Tl(t,n){let i=n?.mutateFirstDiff?t[0]:{added:{},removed:{},updated:{}};return Ny(i,n?.mutateFirstDiff?t.slice(1):t),i}function Ny(t,n){for(let i of n){let o=sa(t.removed);for(let c in i.added){let m=c,E=i.added[m];if(o&&t.removed[m]){let _=t.removed[m];if(delete t.removed[m],_!==E)t.updated[m]=[_,E]}else t.added[m]=E}let a=sa(t.added);for(let c in i.updated){let m=c,E=i.updated[m][1];if(a&&t.added[m]){if(t.added[m]=E,delete t.updated[m],o)delete t.removed[m];continue}let _=t.updated[m];if(_){if(_[1]=E,o)delete t.removed[m];continue}if(t.updated[m]=[i.updated[m][0],E],o)delete t.removed[m]}for(let c in i.removed){let m=c;if(t.added[m])delete t.added[m];else if(t.updated[m])t.removed[m]=t.updated[m][0],delete t.updated[m];else t.removed[m]=i.removed[m]}}}class ia{constructor(t,n){this.typeName=t,this.createDefaultProperties=n.createDefaultProperties,this.validator=n.validator??{validate:(o)=>o},this.scope=n.scope??"document",this.ephemeralKeys=n.ephemeralKeys;let i=new Set;if(n.ephemeralKeys){for(let[o,a]of Pn(n.ephemeralKeys))if(a)i.add(o)}this.ephemeralKeySet=i}typeName;createDefaultProperties;validator;ephemeralKeys;ephemeralKeySet;scope;create(t){let n={...this.createDefaultProperties(),id:t.id??this.createId()};for(let[i,o]of Object.entries(t))if(o!==void 0)n[i]=o;return n.typeName=this.typeName,n}clone(t){return{...tn(t),id:this.createId()}}createId(t){return this.typeName+":"+(t??Ls())}parseId(t){if(!this.isId(t))throw Error(`ID "${t}" is not a valid ID for type "${this.typeName}"`);return t.slice(this.typeName.length+1)}isInstance(t){return t?.typeName===this.typeName}isId(t){if(!t)return!1;for(let n=0;n<this.typeName.length;n++)if(t[n]!==this.typeName[n])return!1;return t[this.typeName.length]===":"}withDefaultProperties(t){return new ia(this.typeName,{createDefaultProperties:t,validator:this.validator,scope:this.scope,ephemeralKeys:this.ephemeralKeys})}validate(t,n){if(n&&this.validator.validateUsingKnownGoodVersion)return this.validator.validateUsingKnownGoodVersion(n,t);return this.validator.validate(t)}}function rt(t,n){return new ia(t,{createDefaultProperties:()=>({}),validator:n.validator,scope:n.scope,ephemeralKeys:n.ephemeralKeys})}function $y(t){if(t.length===0)return new Set;let n=t[0],i=t.slice(1),o=new Set;for(let a of n)if(i.every((c)=>c.has(a)))o.add(a);return o}function Dy(t,n){let i={};for(let o of n)if(!t.has(o))i.added??=new Set,i.added.add(o);for(let o of t)if(!n.has(o))i.removed??=new Set,i.removed.add(o);return i.added||i.removed?i:void 0}function Ly(t){if(typeof t!=="object"||t===null)return!1;return"eq"in t||"neq"in t||"gt"in t}function jy(t,n=""){let i=[];for(let[o,a]of Object.entries(t)){let c=n?`${n}\\${o}`:o;if(Ly(a))i.push({path:c,matcher:a});else if(typeof a==="object"&&a!==null)i.push(...jy(a,c))}return i}function Rl(t,n){for(let[i,o]of Object.entries(t)){let a=n[i];if(Ly(o)){if("eq"in o&&a!==o.eq)return!1;if("neq"in o&&(a===o.neq||a===void 0))return!1;if("gt"in o&&(typeof a!=="number"||a<=o.gt))return!1;continue}if(typeof a!=="object"||a===null)return!1;if(!Rl(o,a))return!1}return!0}function Af(t,n,i){let o=jy(i),a=Object.fromEntries(o.map(({path:c})=>[c,new Set]));for(let{path:c,matcher:m}of o){let E=t.index(n,c);if("eq"in m){let _=E.get().get(m.eq);if(_)for(let I of _)a[c].add(I)}else if("neq"in m){for(let[_,I]of E.get())if(_!==m.neq)for(let T of I)a[c].add(T)}else if("gt"in m){for(let[_,I]of E.get())if(typeof _==="number"&&_>m.gt)for(let T of I)a[c].add(T)}if(a[c].size===0)return new Set}return $y(Object.values(a))}class Pl{constructor(t,n){this.recordMap=t,this.history=n}recordMap;history;indexCache=new Map;historyCache=new Map;getAllIdsForType(t){let n=new Set;for(let i of this.recordMap.values())if(i.typeName===t)n.add(i.id);return n}getRecordById(t,n){let i=this.recordMap.get(n);if(i&&i.typeName===t)return i;return}getNestedValue(t,n){let i=t;for(let o of n){if(i==null||typeof i!=="object")return;i=i[o]}return i}filterHistory(t){if(this.historyCache.has(t))return this.historyCache.get(t);let n=un("filterHistory:"+t,(i,o)=>{if(Ha(i))return this.history.get();let a=this.history.getDiffSince(o);if(a===Pr)return this.history.get();let c={added:{},removed:{},updated:{}},m=0,E=0,_=0;for(let I of a){for(let T of Lt(I.added))if(T.typeName===t)if(c.removed[T.id]){let R=c.removed[T.id];if(delete c.removed[T.id],E--,R!==T)c.updated[T.id]=[R,T],_++}else c.added[T.id]=T,m++;for(let[T,R]of Lt(I.updated))if(R.typeName===t)if(c.added[R.id])c.added[R.id]=R;else if(c.updated[R.id])c.updated[R.id]=[c.updated[R.id][0],R];else c.updated[R.id]=[T,R],_++;for(let T of Lt(I.removed))if(T.typeName===t)if(c.added[T.id])delete c.added[T.id],m--;else if(c.updated[T.id])c.removed[T.id]=c.updated[T.id][0],delete c.updated[T.id],_--,E++;else c.removed[T.id]=T,E++}if(m||E||_)return Zo(this.history.get(),c);else return i},{historyLength:100});return this.historyCache.set(t,n),n}index(t,n){let i=t+":"+n;if(this.indexCache.has(i))return this.indexCache.get(i);let o=this.__uncached_createIndex(t,n);return this.indexCache.set(i,o),o}__uncached_createIndex(t,n){let i=this.filterHistory(t),o=n.split("\\"),a=o.length>1?(m)=>this.getNestedValue(m,o):(m)=>m[n],c=()=>{i.get();let m=new Map;for(let E of this.recordMap.values())if(E.typeName===t){let _=a(E);if(_!==void 0){if(!m.has(_))m.set(_,new Set);m.get(_).add(E.id)}}return m};return un("index:"+t+":"+n,(m,E)=>{if(Ha(m))return c();let _=i.getDiffSince(E);if(_===Pr)return c();let I=new Map,T=(N,H)=>{let Z=I.get(N);if(!Z)Z=new ra(m.get(N)??new Set);Z.add(H),I.set(N,Z)},R=(N,H)=>{let Z=I.get(N);if(!Z)Z=new ra(m.get(N)??new Set);Z.remove(H),I.set(N,Z)};for(let N of _){for(let H of Lt(N.added))if(H.typeName===t){let Z=a(H);if(Z!==void 0)T(Z,H.id)}for(let[H,Z]of Lt(N.updated))if(Z.typeName===t){let V=a(H),me=a(Z);if(V!==me){if(V!==void 0)R(V,Z.id);if(me!==void 0)T(me,Z.id)}}for(let H of Lt(N.removed))if(H.typeName===t){let Z=a(H);if(Z!==void 0)R(Z,H.id)}}let P=void 0,M=void 0;for(let[N,H]of I){let Z=H.get();if(!Z)continue;if(!P)P=new Map(m);if(!M)M=new Map;if(Z.value.size===0)P.delete(N);else P.set(N,Z.value);M.set(N,Z.diff)}if(P&&M)return Zo(P,M);return m},{historyLength:100})}record(t,n=()=>({}),i="record:"+t+(n?":"+n.toString():"")){let o=this.ids(t,n,i);return un(i,()=>{for(let a of o.get())return this.recordMap.get(a);return})}records(t,n=()=>({}),i="records:"+t+(n?":"+n.toString():"")){let o=this.ids(t,n,"ids:"+i);return un(i,()=>Array.from(o.get(),(a)=>this.recordMap.get(a)),{isEqual:Jd})}ids(t,n=()=>({}),i="ids:"+t+(n?":"+n.toString():"")){let o=this.filterHistory(t),a=()=>{o.get();let E=n();if(Object.keys(E).length===0)return this.getAllIdsForType(t);return Af(this,t,E)},c=(E)=>{let _=a(),I=Dy(E,_);if(I)return Zo(_,I);else return E},m=un("ids_query:"+i,n,{isEqual:ki.default});return un("query:"+i,(E,_)=>{let I=m.get();if(Ha(E))return a();if(_<m.lastChangedEpoch)return c(E);let T=o.getDiffSince(_);if(T===Pr)return c(E);let R=new ra(E);for(let M of T){for(let N of Lt(M.added))if(N.typeName===t&&Rl(I,N))R.add(N.id);for(let[N,H]of Lt(M.updated))if(H.typeName===t)if(Rl(I,H))R.add(H.id);else R.remove(H.id);for(let N of Lt(M.removed))if(N.typeName===t)R.remove(N.id)}let P=R.get();if(!P)return E;return Zo(P.value,P.diff)},{historyLength:50})}exec(t,n){let i=Af(this,t,n);if(i.size===0)return bo;return Array.from(i,(o)=>this.recordMap.get(o))}}class Cl{constructor(t){this.store=t}store;_beforeCreateHandlers={};_afterCreateHandlers={};_beforeChangeHandlers={};_afterChangeHandlers={};_beforeDeleteHandlers={};_afterDeleteHandlers={};_operationCompleteHandlers=[];_isEnabled=!0;isEnabled(){return this._isEnabled}setIsEnabled(t){this._isEnabled=t}handleBeforeCreate(t,n){if(!this._isEnabled)return t;let i=this._beforeCreateHandlers[t.typeName];if(i){let o=t;for(let a of i)o=a(o,n);return o}return t}handleAfterCreate(t,n){if(!this._isEnabled)return;let i=this._afterCreateHandlers[t.typeName];if(i)for(let o of i)o(t,n)}handleBeforeChange(t,n,i){if(!this._isEnabled)return n;let o=this._beforeChangeHandlers[n.typeName];if(o){let a=n;for(let c of o)a=c(t,a,i);return a}return n}handleAfterChange(t,n,i){if(!this._isEnabled)return;let o=this._afterChangeHandlers[n.typeName];if(o)for(let a of o)a(t,n,i)}handleBeforeDelete(t,n){if(!this._isEnabled)return!0;let i=this._beforeDeleteHandlers[t.typeName];if(i){for(let o of i)if(o(t,n)===!1)return!1}return!0}handleAfterDelete(t,n){if(!this._isEnabled)return;let i=this._afterDeleteHandlers[t.typeName];if(i)for(let o of i)o(t,n)}handleOperationComplete(t){if(!this._isEnabled)return;for(let n of this._operationCompleteHandlers)n(t)}register(t){let n=[];for(let[i,o]of Object.entries(t)){if(o?.beforeCreate)n.push(this.registerBeforeCreateHandler(i,o.beforeCreate));if(o?.afterCreate)n.push(this.registerAfterCreateHandler(i,o.afterCreate));if(o?.beforeChange)n.push(this.registerBeforeChangeHandler(i,o.beforeChange));if(o?.afterChange)n.push(this.registerAfterChangeHandler(i,o.afterChange));if(o?.beforeDelete)n.push(this.registerBeforeDeleteHandler(i,o.beforeDelete));if(o?.afterDelete)n.push(this.registerAfterDeleteHandler(i,o.afterDelete))}return()=>{for(let i of n)i()}}registerBeforeCreateHandler(t,n){if(!this._beforeCreateHandlers[t])this._beforeCreateHandlers[t]=[];return this._beforeCreateHandlers[t].push(n),()=>xo(this._beforeCreateHandlers[t],n)}registerAfterCreateHandler(t,n){if(!this._afterCreateHandlers[t])this._afterCreateHandlers[t]=[];return this._afterCreateHandlers[t].push(n),()=>xo(this._afterCreateHandlers[t],n)}registerBeforeChangeHandler(t,n){if(!this._beforeChangeHandlers[t])this._beforeChangeHandlers[t]=[];return this._beforeChangeHandlers[t].push(n),()=>xo(this._beforeChangeHandlers[t],n)}registerAfterChangeHandler(t,n){if(!this._afterChangeHandlers[t])this._afterChangeHandlers[t]=[];return this._afterChangeHandlers[t].push(n),()=>xo(this._afterChangeHandlers[t],n)}registerBeforeDeleteHandler(t,n){if(!this._beforeDeleteHandlers[t])this._beforeDeleteHandlers[t]=[];return this._beforeDeleteHandlers[t].push(n),()=>xo(this._beforeDeleteHandlers[t],n)}registerAfterDeleteHandler(t,n){if(!this._afterDeleteHandlers[t])this._afterDeleteHandlers[t]=[];return this._afterDeleteHandlers[t].push(n),()=>xo(this._afterDeleteHandlers[t],n)}registerOperationCompleteHandler(t){return this._operationCompleteHandlers.push(t),()=>xo(this._operationCompleteHandlers,t)}}function xo(t,n){let i=t.indexOf(n);if(i>=0)t.splice(i,1)}class Ol{id;records;history=ji("history",0,{historyLength:1000});query;listeners=new Set;historyAccumulator=new Uy;historyReactor;cancelHistoryReactor(){}schema;props;scopedTypes;sideEffects=new Cl(this);constructor(t){let{initialData:n,schema:i,id:o}=t;if(this.id=o??Ls(),this.schema=i,this.props=t.props,n)this.records=new ta("store",Pn(n).map(([a,c])=>[a,ti(this.schema.validateRecord(this,c,"initialize",null))]));else this.records=new ta("store");this.query=new Pl(this.records,this.history),this.historyReactor=cf("Store.historyReactor",()=>{this.history.get(),this._flushHistory()},{scheduleEffect:(a)=>this.cancelHistoryReactor=sf(a)}),this.scopedTypes={document:new Set(Lt(this.schema.types).filter((a)=>a.scope==="document").map((a)=>a.typeName)),session:new Set(Lt(this.schema.types).filter((a)=>a.scope==="session").map((a)=>a.typeName)),presence:new Set(Lt(this.schema.types).filter((a)=>a.scope==="presence").map((a)=>a.typeName))}}_flushHistory(){if(this.historyAccumulator.hasChanges()){let t=this.historyAccumulator.flush();for(let{changes:n,source:i}of t){let o=null,a=null,c=null;for(let{onHistory:m,filters:E}of this.listeners){if(E.source!=="all"&&E.source!==i)continue;if(E.scope!=="all")if(E.scope==="document"){if(a??=this.filterChangesByScope(n,"document"),!a)continue;m({changes:a,source:i})}else if(E.scope==="session"){if(o??=this.filterChangesByScope(n,"session"),!o)continue;m({changes:o,source:i})}else{if(c??=this.filterChangesByScope(n,"presence"),!c)continue;m({changes:c,source:i})}else m({changes:n,source:i})}}}}dispose(){this.cancelHistoryReactor()}filterChangesByScope(t,n){let i={added:Ko(t.added,(o,a)=>this.scopedTypes[n].has(a.typeName)),updated:Ko(t.updated,(o,a)=>this.scopedTypes[n].has(a[1].typeName)),removed:Ko(t.removed,(o,a)=>this.scopedTypes[n].has(a.typeName))};if(!sa(i.added)&&!sa(i.updated)&&!sa(i.removed))return null;return i}updateHistory(t){if(this.historyAccumulator.add({changes:t,source:this.isMergingRemoteChanges?"remote":"user"}),this.listeners.size===0)this.historyAccumulator.clear();this.history.set(this.history.get()+1,t)}validate(t){this.allRecords().forEach((n)=>this.schema.validateRecord(this,n,t,null))}put(t,n){this.atomic(()=>{let i={},o={},a,c=!1,m=this.isMergingRemoteChanges?"remote":"user";for(let E=0,_=t.length;E<_;E++){a=t[E];let I=this.records.__unsafe__getWithoutCapture(a.id);if(I){a=this.sideEffects.handleBeforeChange(I,a,m);let T=this.schema.validateRecord(this,a,n??"updateRecord",I);if(T===I)continue;a=ti(T),this.records.set(a.id,a),c=!0,i[a.id]=[I,a],this.addDiffForAfterEvent(I,a)}else a=this.sideEffects.handleBeforeCreate(a,m),c=!0,a=this.schema.validateRecord(this,a,n??"createRecord",null),a=ti(a),o[a.id]=a,this.addDiffForAfterEvent(null,a),this.records.set(a.id,a)}if(!c)return;this.updateHistory({added:o,updated:i,removed:{}})})}remove(t){this.atomic(()=>{let n=new Set(t),i=this.isMergingRemoteChanges?"remote":"user";if(this.sideEffects.isEnabled())for(let c of t){let m=this.records.__unsafe__getWithoutCapture(c);if(!m)continue;if(this.sideEffects.handleBeforeDelete(m,i)===!1)n.delete(c)}let o=this.records.deleteMany(n);if(o.length===0)return;let a={};for(let[c,m]of o)a[c]=m,this.addDiffForAfterEvent(m,null);this.updateHistory({added:{},updated:{},removed:a})})}get(t){return this.records.get(t)}unsafeGetWithoutCapture(t){return this.records.__unsafe__getWithoutCapture(t)}serialize(t="document"){let n={};for(let[i,o]of this.records)if(t==="all"||this.scopedTypes[t].has(o.typeName))n[i]=o;return n}getStoreSnapshot(t="document"){return{store:this.serialize(t),schema:this.schema.serialize()}}migrateSnapshot(t){let n=this.schema.migrateStoreSnapshot(t);if(n.type==="error")throw Error(`Failed to migrate snapshot: ${n.reason}`);return{store:n.value,schema:this.schema.serialize()}}loadStoreSnapshot(t){let n=this.schema.migrateStoreSnapshot(t);if(n.type==="error")throw Error(`Failed to migrate snapshot: ${n.reason}`);let i=this.sideEffects.isEnabled();try{this.sideEffects.setIsEnabled(!1),this.atomic(()=>{this.clear(),this.put(Object.values(n.value)),this.ensureStoreIsUsable()},!1)}finally{this.sideEffects.setIsEnabled(i)}}allRecords(){return Array.from(this.records.values())}clear(){this.remove(Array.from(this.records.keys()))}update(t,n){let i=this.unsafeGetWithoutCapture(t);if(!i){console.error(`Record ${t} not found. This is probably an error`);return}this.put([n(i)])}has(t){return this.records.has(t)}listen(t,n){this._flushHistory();let i={onHistory:t,filters:{source:n?.source??"all",scope:n?.scope??"all"}};if(!this.historyReactor.scheduler.isActivelyListening)this.historyReactor.start(),this.historyReactor.scheduler.execute();return this.listeners.add(i),()=>{if(this.listeners.delete(i),this.listeners.size===0)this.historyReactor.stop()}}isMergingRemoteChanges=!1;mergeRemoteChanges(t){if(this.isMergingRemoteChanges)return t();if(this._isInAtomicOp)throw Error("Cannot merge remote changes while in atomic operation");try{this.atomic(t,!0,!0)}finally{this.ensureStoreIsUsable()}}extractingChanges(t){let n=[],i=this.historyAccumulator.addInterceptor((o)=>n.push(o.changes));try{return $i(t),Tl(n)}finally{i()}}applyDiff(t,{runCallbacks:n=!0,ignoreEphemeralKeys:i=!1}={}){this.atomic(()=>{let o=Lt(t.added);for(let[c,m]of Lt(t.updated)){let E=this.schema.getType(m.typeName);if(i&&E.ephemeralKeySet.size){let _=this.get(m.id);if(!_){o.push(m);continue}let I=null;for(let[T,R]of Object.entries(m)){if(E.ephemeralKeySet.has(T)||Object.is(R,gr(_,T)))continue;if(!I)I={..._};I[T]=R}if(I)o.push(I)}else o.push(m)}let a=Xd(t.removed);if(o.length)this.put(o);if(a.length)this.remove(a)},n)}createCache(t){let n=new ml;return{get:(i)=>{let o=this.records.getAtom(i);if(!o)return;return n.get(o,()=>t(i,o)).get()}}}createComputedCache(t,n,i){return this.createCache((o,a)=>{let c=i?.areRecordsEqual?un(`${t}:${o}:isEqual`,()=>a.get(),{isEqual:i.areRecordsEqual}):a;return un(t+":"+o,()=>n(c.get()),{isEqual:i?.areResultsEqual})})}_integrityChecker;ensureStoreIsUsable(){this.atomic(()=>{this._integrityChecker??=this.schema.createIntegrityChecker(this),this._integrityChecker?.()})}_isPossiblyCorrupted=!1;markAsPossiblyCorrupted(){this._isPossiblyCorrupted=!0}isPossiblyCorrupted(){return this._isPossiblyCorrupted}pendingAfterEvents=null;addDiffForAfterEvent(t,n){if(qe(this.pendingAfterEvents,"must be in event operation"),t===n)return;if(t&&n)qe(t.id===n.id);if(!t&&!n)return;let i=(t||n).id,o=this.pendingAfterEvents.get(i);if(o)o.after=n;else this.pendingAfterEvents.set(i,{before:t,after:n})}flushAtomicCallbacks(t){let n=0,i=t?"remote":"user";while(this.pendingAfterEvents){let o=this.pendingAfterEvents;if(this.pendingAfterEvents=null,!this.sideEffects.isEnabled())continue;if(n++,n>100)throw Error("Maximum store update depth exceeded, bailing out");for(let{before:a,after:c}of o.values())if(a&&c&&a!==c&&!ki.default(a,c))this.sideEffects.handleAfterChange(a,c,i);else if(a&&!c)this.sideEffects.handleAfterDelete(a,i);else if(!a&&c)this.sideEffects.handleAfterCreate(c,i);if(!this.pendingAfterEvents)this.sideEffects.handleOperationComplete(i);else i="user"}}_isInAtomicOp=!1;atomic(t,n=!0,i=!1){return $i(()=>{if(this._isInAtomicOp){if(!this.pendingAfterEvents)this.pendingAfterEvents=new Map;let a=this.sideEffects.isEnabled();qe(!i,"cannot call mergeRemoteChanges while in atomic operation");try{if(a&&!n)this.sideEffects.setIsEnabled(!1);return t()}finally{this.sideEffects.setIsEnabled(a)}}this.pendingAfterEvents=new Map;let o=this.sideEffects.isEnabled();if(this.sideEffects.setIsEnabled(n&&o),this._isInAtomicOp=!0,i)this.isMergingRemoteChanges=!0;try{let a=t();return this.isMergingRemoteChanges=!1,this.flushAtomicCallbacks(i),a}finally{this.pendingAfterEvents=null,this.sideEffects.setIsEnabled(o),this._isInAtomicOp=!1,this.isMergingRemoteChanges=!1}})}addHistoryInterceptor(t){return this.historyAccumulator.addInterceptor((n)=>t(n,this.isMergingRemoteChanges?"remote":"user"))}}function KR(t){if(t.length===0)return[];let n=[],i=[t[0]],o;for(let a=1,c=t.length;a<c;a++){if(o=t[a],i[0].source!==o.source)n.push(i),i=[];i.push(o)}return n.push(i),ti(n.map((a)=>({source:a[0].source,changes:a.length===1?a[0].changes:Tl(a.map((c)=>c.changes))})))}class Uy{_history=[];_interceptors=new Set;addInterceptor(t){return this._interceptors.add(t),()=>{this._interceptors.delete(t)}}add(t){this._history.push(t);for(let n of this._interceptors)n(t)}flush(){let t=KR(this._history);return this._history=[],t}clear(){this._history=[]}hasChanges(){return this._history.length>0}}function JR(t){if(t.schemaVersion>2||t.schemaVersion<1)return $s.err("Bad schema version");if(t.schemaVersion===2)return $s.ok(t);let n={schemaVersion:2,sequences:{"com.tldraw.store":t.storeVersion}};for(let[i,o]of Object.entries(t.recordVersions))if(n.sequences[`com.tldraw.${i}`]=o.version,"subTypeKey"in o)for(let[a,c]of Object.entries(o.subTypeVersions))n.sequences[`com.tldraw.${i}.${a}`]=c;return $s.ok(n)}class Ga{constructor(t,n){this.types=t,this.options=n;for(let o of n.migrations??[])qe(!this.migrations[o.sequenceId],`Duplicate migration sequenceId ${o.sequenceId}`),Ef(o),this.migrations[o.sequenceId]=o;let i=Object.values(this.migrations).flatMap((o)=>o.sequence);this.sortedMigrations=My(i);for(let o of this.sortedMigrations){if(!o.dependsOn?.length)continue;for(let a of o.dependsOn){let c=i.find((m)=>m.id===a);qe(c,`Migration '${o.id}' depends on missing migration '${a}'`)}}}types;options;static create(t,n){return new Ga(t,n??{})}migrations={};sortedMigrations;migrationCache=new WeakMap;validateRecord(t,n,i,o){try{let a=gr(this.types,n.typeName);if(!a)throw Error(`Missing definition for record type ${n.typeName}`);return a.validate(n,o??void 0)}catch(a){if(this.options.onValidationFailure)return this.options.onValidationFailure({store:t,record:n,phase:i,recordBefore:o,error:a});else throw a}}getMigrationsSince(t){let n=this.migrationCache.get(t);if(n)return n;let i=JR(t);if(!i.ok)return this.migrationCache.set(t,i),i;let o=i.value,a=new Set(Object.keys(o.sequences).filter((E)=>this.migrations[E]));for(let E in this.migrations)if(o.sequences[E]===void 0&&this.migrations[E].retroactive)a.add(E);if(a.size===0){let E=$s.ok([]);return this.migrationCache.set(t,E),E}let c=new Set;for(let E of a){let _=o.sequences[E];if(typeof _!=="number"&&this.migrations[E].retroactive||_===0){for(let R of this.migrations[E].sequence)c.add(R.id);continue}let I=`${E}/${_}`,T=this.migrations[E].sequence.findIndex((R)=>R.id===I);if(T===-1){let R=$s.err("Incompatible schema?");return this.migrationCache.set(t,R),R}for(let R of this.migrations[E].sequence.slice(T+1))c.add(R.id)}let m=$s.ok(this.sortedMigrations.filter(({id:E})=>c.has(E)));return this.migrationCache.set(t,m),m}migratePersistedRecord(t,n,i="up"){let o=this.getMigrationsSince(n);if(!o.ok)return console.error("Error migrating record",o.error),{type:"error",reason:si.MigrationError};let a=o.value;if(a.length===0)return{type:"success",value:t};if(!a.every((c)=>c.scope==="record"))return{type:"error",reason:i==="down"?si.TargetVersionTooOld:si.TargetVersionTooNew};if(i==="down"){if(!a.every((c)=>c.scope==="record"&&c.down))return{type:"error",reason:si.TargetVersionTooOld};a=a.slice().reverse()}t=tn(t);try{for(let c of a){if(c.scope==="store")throw Error();if(c.scope==="storage")throw Error();if(!(c.filter?c.filter(t):!0))continue;let E=c[i](t);if(E)t=tn(E)}}catch(c){return console.error("Error migrating record",c),{type:"error",reason:si.MigrationError}}return{type:"success",value:t}}migrateStorage(t){let n=t.getSchema();qe(n,"Schema is missing.");let i=this.getMigrationsSince(n);if(!i.ok)throw console.error("Error migrating store",i.error),Error(i.error);let o=i.value;if(o.length===0)return;t.setSchema(this.serialize());for(let a of o)if(a.scope==="record"){let c=[];for(let[m,E]of t.entries()){if(!(a.filter?a.filter(E):!0))continue;let I=tn(E),T=a.up(I)??I;if(!ki.default(T,E))c.push([m,T])}for(let[m,E]of c)t.set(m,E)}else if(a.scope==="store"){let c=Object.fromEntries(t.entries()),m=tn(c);m=a.up(m)??m;for(let[E,_]of Object.entries(m)){if(!_)continue;if(!ki.default(_,c[E]))t.set(E,_)}for(let E of Object.keys(c))if(!m[E])t.delete(E)}else if(a.scope==="storage")a.up(t);else ja(a);for(let[a,c]of t.entries())if(this.getType(c.typeName).scope!=="document")t.delete(a)}migrateStoreSnapshot(t,n){let i=this.getMigrationsSince(t.schema);if(!i.ok)return console.error("Error migrating store",i.error),{type:"error",reason:si.MigrationError};if(i.value.length===0)return{type:"success",value:t.store};let a=Object.assign(new Map(Pn(t.store).map(ti)),{getSchema:()=>t.schema,setSchema:(c)=>{}});try{if(this.migrateStorage(a),n?.mutateInputStore){for(let[c,m]of a.entries())t.store[c]=m;for(let c of Object.keys(t.store))if(!a.has(c))delete t.store[c];return{type:"success",value:t.store}}else return{type:"success",value:Object.fromEntries(a.entries())}}catch(c){return console.error("Error migrating store",c),{type:"error",reason:si.MigrationError}}}createIntegrityChecker(t){return this.options.createIntegrityChecker?.(t)??void 0}serialize(){return{schemaVersion:2,sequences:Object.fromEntries(Object.values(this.migrations).map(({sequenceId:t,sequence:n})=>[t,n.length?na(n.at(-1).id).version:0]))}}serializeEarliestVersion(){return{schemaVersion:2,sequences:Object.fromEntries(Object.values(this.migrations).map(({sequenceId:t})=>[t,0]))}}getType(t){let n=gr(this.types,t);return qe(n,"record type does not exist"),n}}Tn("@tldraw/store","5.2.3","esm");var YR=!0;function XR(t){if(!t.length)return null;let n="";for(let i of t)if(typeof i==="number")n+=`.${i}`;else if(i.startsWith("("))if(n.endsWith(")"))n=`${n.slice(0,-1)}, ${i.slice(1)}`;else n+=i;else n+=`.${i}`;if(n=n.replace(/id = [^,]+, /,"").replace(/id = [^)]+/,""),n.startsWith("."))return n.slice(1);return n}class ge extends Error{constructor(t,n=[]){let i=XR(n),o=t.split(`
|
|
59
59
|
`).map((a,c)=>c===0?a:` ${a}`).join(`
|
|
60
|
-
`);super(i?`At ${i}: ${o}`:o);this.rawMessage=t,this.path=n}rawMessage;path;name="ValidationError"}function fn(t,n){if(n instanceof ge)throw new ge(n.rawMessage,[t,...n.path]);throw new ge(n.toString(),[t])}function lr(t){if(t===null)return"null";if(Array.isArray(t))return"an array";let n=typeof t;switch(n){case"bigint":case"boolean":case"function":case"number":case"string":case"symbol":return`a ${n}`;case"object":return`an ${n}`;case"undefined":return"undefined";default:ja(n)}}class Ye{constructor(t,n,i=!1){this.validationFn=t,this.validateUsingKnownGoodVersionFn=n,this.skipSameValueCheck=i}validationFn;validateUsingKnownGoodVersionFn;skipSameValueCheck;validate(t){let n=this.validationFn(t);if(YR&&!this.skipSameValueCheck&&!Object.is(t,n))throw new ge("Validator functions must return the same value they were passed");return n}validateUsingKnownGoodVersion(t,n){if(Object.is(t,n))return t;if(this.validateUsingKnownGoodVersionFn)return this.validateUsingKnownGoodVersionFn(t,n);return this.validate(n)}isValid(t){try{return this.validate(t),!0}catch{return!1}}nullable(){return t1(this)}optional(){return By(this)}refine(t){return new Ye((n)=>t(this.validate(n)),(n,i)=>{let o=this.validateUsingKnownGoodVersion(n,i);if(Object.is(n,o))return n;return t(o)},!0)}check(t,n){if(typeof t==="string")return this.refine((i)=>{try{n(i)}catch(o){fn(`(check ${t})`,o)}return i});else return this.refine((i)=>(t(i),i))}}class If extends Ye{constructor(t){super((n)=>{let i=Fy.validate(n);for(let o=0;o<i.length;o++)try{t.validate(i[o])}catch(a){fn(o,a)}return i},(n,i)=>{if(Object.is(n,i))return n;if(!t.validateUsingKnownGoodVersion)return this.validate(i);let o=Fy.validate(i),a=n.length!==o.length;for(let c=0;c<o.length;c++){let m=o[c];if(c>=n.length){a=!0;try{t.validate(m)}catch(E){fn(c,E)}continue}if(Object.is(n[c],m))continue;try{let E=t.validateUsingKnownGoodVersion(n[c],m);if(!Object.is(E,n[c]))a=!0}catch(E){fn(c,E)}}return a?i:n});this.itemValidator=t}itemValidator;nonEmpty(){return this.check((t)=>{if(t.length===0)throw new ge("Expected a non-empty array")})}lengthGreaterThan1(){return this.check((t)=>{if(t.length<=1)throw new ge("Expected an array with length greater than 1")})}}class Ka extends Ye{constructor(t,n=!1){let i=[],o=[];for(let[a,c]of Object.entries(t))i.push(a),o.push(c);super((a)=>{if(typeof a!=="object"||a===null)throw new ge(`Expected object, got ${lr(a)}`);for(let c=0;c<i.length;c++){let m=i[c];try{o[c].validate(gr(a,m))}catch(E){fn(m,E)}}if(!n)for(let c in a){if(!kt(a,c))continue;if(!kt(t,c))throw new ge("Unexpected property",[c])}return a},(a,c)=>{if(Object.is(a,c))return a;if(typeof c!=="object"||c===null)throw new ge(`Expected object, got ${lr(c)}`);let m=!1;for(let E=0;E<i.length;E++){let _=i[E],I=gr(a,_),T=gr(c,_);if(Object.is(I,T))continue;try{let R=o[E],P=R.validateUsingKnownGoodVersion?R.validateUsingKnownGoodVersion(I,T):R.validate(T);if(!Object.is(P,I))m=!0}catch(R){fn(_,R)}}if(!n)for(let E in c){if(!kt(c,E))continue;if(!kt(t,E))throw new ge("Unexpected property",[E])}else if(!m){for(let E of Object.keys(c))if(!kt(t,E)&&!Object.is(gr(a,E),gr(c,E))){m=!0;break}}if(!m)for(let E in a){if(!kt(a,E))continue;if(!kt(c,E)){m=!0;break}}return m?c:a});this.config=t,this.shouldAllowUnknownProperties=n}config;shouldAllowUnknownProperties;allowUnknownProperties(){return new Ka(this.config,!0)}extend(t){return new Ka({...this.config,...t})}}class kl extends Ye{constructor(t,n,i,o){super((a)=>{this.expectObject(a);let c=this.getMatchingSchema(a);if(c===void 0)return this.unknownValueValidation(a,this.getVariant(a));try{return c.validate(a)}catch(m){fn(`(${t} = ${this.getVariant(a)})`,m)}},(a,c)=>{this.expectObject(c),this.expectObject(a);let m=this.getMatchingSchema(c);if(m===void 0)return this.unknownValueValidation(c,this.getVariant(c));try{if(gr(a,t)!==gr(c,t))return m.validate(c);if(m.validateUsingKnownGoodVersion)return m.validateUsingKnownGoodVersion(a,c);else return m.validate(c)}catch(E){fn(`(${t} = ${this.getVariant(c)})`,E)}});this.key=t,this.config=n,this.unknownValueValidation=i,this.useNumberKeys=o}key;config;unknownValueValidation;useNumberKeys;expectObject(t){if(typeof t!=="object"||t===null)throw new ge(`Expected an object, got ${lr(t)}`,[])}getVariant(t){return gr(t,this.key)}getMatchingSchema(t){let n=gr(t,this.key);if(!this.useNumberKeys&&typeof n!=="string")throw new ge(`Expected a string for key "${this.key}", got ${lr(n)}`);else if(this.useNumberKeys){let i=Number(n);if(i-i!==0)throw new ge(`Expected a number for key "${this.key}", got "${n}"`)}return kt(this.config,n)?this.config[n]:void 0}validateUnknownVariants(t){return new kl(this.key,this.config,t,this.useNumberKeys)}}class Tf extends Ye{constructor(t,n){super((i)=>{if(typeof i!=="object"||i===null)throw new ge(`Expected object, got ${lr(i)}`);for(let o in i){if(!kt(i,o))continue;try{t.validate(o),n.validate(i[o])}catch(a){fn(o,a)}}return i},(i,o)=>{if(typeof o!=="object"||o===null)throw new ge(`Expected object, got ${lr(o)}`);let a=o,c=!1,m=0;for(let E in a){if(!kt(a,E))continue;m++;let _=a[E];if(!kt(i,E)){c=!0;try{t.validate(E),n.validate(_)}catch(T){fn(E,T)}continue}let I=i[E];if(Object.is(I,_))continue;try{let T=n.validateUsingKnownGoodVersion?n.validateUsingKnownGoodVersion(I,_):n.validate(_);if(!Object.is(T,I))c=!0}catch(T){fn(E,T)}}if(!c){let E=0;for(let _ in i)if(kt(i,_))E++;if(E!==m)c=!0}return c?o:i});this.keyValidator=t,this.valueValidator=n}keyValidator;valueValidator}function Rf(t){return new Ye((n)=>{if(typeof n!==t)throw new ge(`Expected ${t}, got ${lr(n)}`);return n})}var ZR=new Ye((t)=>t),qy=new Ye((t)=>t),Ne=Rf("string"),Oe=new Ye((t)=>{if(Number.isFinite(t))return t;if(typeof t!=="number")throw new ge(`Expected number, got ${lr(t)}`);if(t!==t)throw new ge("Expected a number, got NaN");throw new ge(`Expected a finite number, got ${t}`)}),Ja=new Ye((t)=>{if(Number.isFinite(t)&&t>=0)return t;if(typeof t!=="number")throw new ge(`Expected number, got ${lr(t)}`);if(t!==t)throw new ge("Expected a number, got NaN");if(t<0)throw new ge(`Expected a positive number, got ${t}`);throw new ge(`Expected a finite number, got ${t}`)}),Rt=new Ye((t)=>{if(Number.isFinite(t)&&t>0)return t;if(typeof t!=="number")throw new ge(`Expected number, got ${lr(t)}`);if(t!==t)throw new ge("Expected a number, got NaN");if(t<=0)throw new ge(`Expected a non-zero positive number, got ${t}`);throw new ge(`Expected a finite number, got ${t}`)}),Ml=new Ye((t)=>{if(Number.isFinite(t)&&t!==0)return t;if(typeof t!=="number")throw new ge(`Expected number, got ${lr(t)}`);if(t!==t)throw new ge("Expected a number, got NaN");if(t===0)throw new ge("Expected a non-zero number, got 0");throw new ge(`Expected a finite number, got ${t}`)}),QR=new Ye((t)=>{if(Number.isFinite(t)&&t>=0&&t<=1)return t;if(typeof t!=="number")throw new ge(`Expected number, got ${lr(t)}`);if(t!==t)throw new ge("Expected a number, got NaN");throw new ge(`Expected a number between 0 and 1, got ${t}`)}),VF=new Ye((t)=>{if(Number.isInteger(t))return t;if(typeof t!=="number")throw new ge(`Expected number, got ${lr(t)}`);if(t!==t)throw new ge("Expected a number, got NaN");if(t-t!==0)throw new ge(`Expected a finite number, got ${t}`);throw new ge(`Expected an integer, got ${t}`)}),zF=new Ye((t)=>{if(Number.isInteger(t)&&t>=0)return t;if(typeof t!=="number")throw new ge(`Expected number, got ${lr(t)}`);if(t!==t)throw new ge("Expected a number, got NaN");if(t-t!==0)throw new ge(`Expected a finite number, got ${t}`);if(t<0)throw new ge(`Expected a positive integer, got ${t}`);throw new ge(`Expected an integer, got ${t}`)}),GF=new Ye((t)=>{if(Number.isInteger(t)&&t>0)return t;if(typeof t!=="number")throw new ge(`Expected number, got ${lr(t)}`);if(t!==t)throw new ge("Expected a number, got NaN");if(t-t!==0)throw new ge(`Expected a finite number, got ${t}`);if(t<=0)throw new ge(`Expected a non-zero positive integer, got ${t}`);throw new ge(`Expected an integer, got ${t}`)}),He=Rf("boolean"),KF=Rf("bigint");function yr(t){return new Ye((n)=>{if(n!==t)throw new ge(`Expected ${t}, got ${JSON.stringify(n)}`);return t})}var Fy=new Ye((t)=>{if(!Array.isArray(t))throw new ge(`Expected an array, got ${lr(t)}`);return t});function sn(t){return new If(t)}var JF=new Ye((t)=>{if(typeof t!=="object"||t===null)throw new ge(`Expected object, got ${lr(t)}`);return t});function De(t){return new Ka(t)}function xf(t){return typeof t==="object"&&t!==null&&(Object.getPrototypeOf(t)===Object.prototype||Object.getPrototypeOf(t)===null||Object.getPrototypeOf(t)===Fa)}function _f(t){if(t===null||typeof t==="number"||typeof t==="string"||typeof t==="boolean")return!0;if(Array.isArray(t)){for(let n=0;n<t.length;n++)if(!_f(t[n]))return!1;return!0}if(xf(t)){for(let n in t){if(!kt(t,n))continue;if(!_f(t[n]))return!1}return!0}return!1}var Mt=new Ye((t)=>{if(_f(t))return t;throw new ge(`Expected json serializable value, got ${typeof t}`)},(t,n)=>{if(Array.isArray(t)&&Array.isArray(n)){let i=t.length!==n.length;for(let o=0;o<n.length;o++){if(o>=t.length){i=!0,Mt.validate(n[o]);continue}let a=t[o],c=n[o];if(Object.is(a,c))continue;let m=Mt.validateUsingKnownGoodVersion(a,c);if(!Object.is(m,a))i=!0}return i?n:t}else if(xf(t)&&xf(n)){let i=!1;for(let o in n){if(!kt(n,o))continue;if(!kt(t,o)){i=!0,Mt.validate(n[o]);continue}let a=t[o],c=n[o];if(Object.is(a,c))continue;let m=Mt.validateUsingKnownGoodVersion(a,c);if(!Object.is(m,a))i=!0}if(!i)for(let o in t){if(!kt(t,o))continue;if(!kt(n,o)){i=!0;break}}return i?n:t}else return Mt.validate(n)});function e1(t,n){return new Tf(t,n)}function Pf(t,n){return new kl(t,n,(i,o)=>{throw new ge(`Expected one of ${Object.keys(n).map((a)=>JSON.stringify(a)).join(" or ")}, got ${JSON.stringify(o)}`,[t])},!1)}function En(t,n){return new Ye((i)=>{try{return n.validate(i)}catch(o){fn(t,o)}},(i,o)=>{try{if(n.validateUsingKnownGoodVersion)return n.validateUsingKnownGoodVersion(i,o);else return n.validate(o)}catch(a){fn(t,a)}})}function Nl(t){return new Ye((n)=>{if(!t.has(n)){let i=Array.from(t,(o)=>JSON.stringify(o)).join(" or ");throw new ge(`Expected ${i}, got ${n}`)}return n})}function By(t){return new Ye((n)=>{if(n===void 0)return;return t.validate(n)},(n,i)=>{if(i===void 0)return;if(t.validateUsingKnownGoodVersion&&n!==void 0)return t.validateUsingKnownGoodVersion(n,i);return t.validate(i)},t instanceof Ye&&t.skipSameValueCheck)}function t1(t){return new Ye((n)=>{if(n===null)return null;return t.validate(n)},(n,i)=>{if(i===null)return null;if(t.validateUsingKnownGoodVersion&&n!==null)return t.validateUsingKnownGoodVersion(n,i);return t.validate(i)},t instanceof Ye&&t.skipSameValueCheck)}function Bi(...t){return Nl(new Set(t))}function Cf(t){try{return new URL(t)}catch{if(t.startsWith("/")||t.startsWith("./"))try{return new URL(t,"http://example.com")}catch{throw new ge(`Expected a valid url, got ${JSON.stringify(t)}`)}throw new ge(`Expected a valid url, got ${JSON.stringify(t)}`)}}var r1=new Set(["http:","https:","mailto:"]),Us=Ne.check((t)=>{if(t==="")return;let n=Cf(t);if(!r1.has(n.protocol.toLowerCase()))throw new ge(`Expected a valid url, got ${JSON.stringify(t)} (invalid protocol)`)}),n1=new Set(["http:","https:","data:","asset:"]),_o=Ne.check((t)=>{if(t==="")return;let n=Cf(t);if(!n1.has(n.protocol.toLowerCase()))throw new ge(`Expected a valid url, got ${JSON.stringify(t)} (invalid protocol)`)}),YF=Ne.check((t)=>{if(t==="")return;if(!Cf(t).protocol.toLowerCase().match(/^https?:$/))throw new ge(`Expected a valid url, got ${JSON.stringify(t)} (invalid protocol)`)}),Of=Ne.refine((t)=>{try{return tf(t),t}catch{throw new ge(`Expected an index key, got ${JSON.stringify(t)}`)}});Tn("@tldraw/validate","5.2.3","esm");function lt(t){return Ne.refine((n)=>{if(!n.startsWith(`${t}:`))throw Error(`${t} ID must start with "${t}:"`);return n})}var Wi=lt("asset");function oi(t,n,i){let o=n instanceof Ye?n:n?De(n):Mt;return De({id:Wi,typeName:yr("asset"),type:yr(t),props:o,meta:i?De(i):Mt})}var $l={title:Ne,description:Ne,image:Ne,favicon:Ne,src:_o.nullable()},c4=oi("bookmark",De($l)),Wy=Be("com.tldraw.asset.bookmark",{MakeUrlsValid:1,AddFavicon:2}),kf=et({sequenceId:"com.tldraw.asset.bookmark",recordType:"asset",filter:(t)=>t.type==="bookmark",sequence:[{id:Wy.MakeUrlsValid,up:(t)=>{if(!_o.isValid(t.props.src))t.props.src=""},down:(t)=>{}},{id:Wy.AddFavicon,up:(t)=>{if(!_o.isValid(t.props.favicon))t.props.favicon=""},down:(t)=>{delete t.props.favicon}}]});var Dl={w:Oe,h:Oe,name:Ne,isAnimated:He,mimeType:Ne.nullable(),src:_o.nullable(),fileSize:Rt.optional(),pixelRatio:Ja.optional()},p4=oi("image",De(Dl)),oa=Be("com.tldraw.asset.image",{AddIsAnimated:1,RenameWidthHeight:2,MakeUrlsValid:3,AddFileSize:4,MakeFileSizeOptional:5,AddPixelRatio:6}),Mf=et({sequenceId:"com.tldraw.asset.image",recordType:"asset",filter:(t)=>t.type==="image",sequence:[{id:oa.AddIsAnimated,up:(t)=>{t.props.isAnimated=!1},down:(t)=>{delete t.props.isAnimated}},{id:oa.RenameWidthHeight,up:(t)=>{t.props.w=t.props.width,t.props.h=t.props.height,delete t.props.width,delete t.props.height},down:(t)=>{t.props.width=t.props.w,t.props.height=t.props.h,delete t.props.w,delete t.props.h}},{id:oa.MakeUrlsValid,up:(t)=>{if(!_o.isValid(t.props.src))t.props.src=""},down:(t)=>{}},{id:oa.AddFileSize,up:(t)=>{t.props.fileSize=-1},down:(t)=>{delete t.props.fileSize}},{id:oa.MakeFileSizeOptional,up:(t)=>{if(t.props.fileSize===-1)t.props.fileSize=void 0},down:(t)=>{if(t.props.fileSize===void 0)t.props.fileSize=-1}},{id:oa.AddPixelRatio,up:(t)=>{},down:(t)=>{delete t.props.pixelRatio}}]});var Ll={w:Oe,h:Oe,name:Ne,isAnimated:He,mimeType:Ne.nullable(),src:_o.nullable(),fileSize:Oe.optional()},w4=oi("video",De(Ll)),Ya=Be("com.tldraw.asset.video",{AddIsAnimated:1,RenameWidthHeight:2,MakeUrlsValid:3,AddFileSize:4,MakeFileSizeOptional:5}),Nf=et({sequenceId:"com.tldraw.asset.video",recordType:"asset",filter:(t)=>t.type==="video",sequence:[{id:Ya.AddIsAnimated,up:(t)=>{t.props.isAnimated=!1},down:(t)=>{delete t.props.isAnimated}},{id:Ya.RenameWidthHeight,up:(t)=>{t.props.w=t.props.width,t.props.h=t.props.height,delete t.props.width,delete t.props.height},down:(t)=>{t.props.width=t.props.w,t.props.height=t.props.h,delete t.props.w,delete t.props.h}},{id:Ya.MakeUrlsValid,up:(t)=>{if(!_o.isValid(t.props.src))t.props.src=""},down:(t)=>{}},{id:Ya.AddFileSize,up:(t)=>{t.props.fileSize=-1},down:(t)=>{delete t.props.fileSize}},{id:Ya.MakeFileSizeOptional,up:(t)=>{if(t.props.fileSize===-1)t.props.fileSize=void 0},down:(t)=>{if(t.props.fileSize===void 0)t.props.fileSize=-1}}]});var ts=De({x:Oe,y:Oe,z:Oe.optional()}),Hi=De({x:Oe,y:Oe,w:Oe,h:Oe});var Xa=QR;var Hy=Ne.refine((t)=>{if(!t.startsWith("page:")&&!t.startsWith("shape:"))throw Error('Parent ID must start with "page:" or "shape:"');return t}),hn=lt("shape");function $f(t,n,i){return De({id:hn,typeName:yr("shape"),x:Oe,y:Oe,rotation:Oe,index:Of,parentId:Hy,type:yr(t),isLocked:He,opacity:Xa,props:n?De(n):Mt,meta:i?De(i):Mt})}var Vy=lt("binding");function Df(t,n,i){return De({id:Vy,typeName:yr("binding"),type:yr(t),fromId:hn,toId:hn,props:n?De(n):Mt,meta:i?De(i):Mt})}var D4=Be("com.tldraw.binding",{}),s1=et({sequenceId:"com.tldraw.binding",recordType:"binding",sequence:[]});function aa(t){return`binding:${t??Ls()}`}function Lf(t){return t}function jf(t,n){return js(n,(i,o)=>`com.tldraw.binding.${t}/${o}`)}function zy(t){return rt("binding",{scope:"document",validator:En("binding",Pf("type",js(t,(n,{props:i,meta:o})=>Df(n,i,o))))}).withDefaultProperties(()=>({meta:{}}))}var ai=De({type:Ne,content:sn(ZR),attrs:qy.optional()});function Wt(t){return{type:"doc",content:t.split(`
|
|
61
|
-
`).map((o)=>{if(!o)return{type:"paragraph"};return{type:"paragraph",content:[{type:"text",text:o}]}})}}class Ke{constructor(t,n,i){this.id=t,this.defaultValue=n,this.type=i}id;defaultValue;type;static define(t,n){let{defaultValue:i,type:o=qy}=n;return new Ke(t,i,o)}static defineEnum(t,n){let{defaultValue:i,values:o}=n;return new Uf(t,i,o)}setDefaultValue(t){this.defaultValue=t}validate(t){return this.type.validate(t)}validateUsingKnownGoodVersion(t,n){if(this.type.validateUsingKnownGoodVersion)return this.type.validateUsingKnownGoodVersion(t,n);else return this.validate(n)}}class Uf extends Ke{constructor(t,n,i){super(t,n,Bi(...i));this.values=[...i]}values;addValues(...t){for(let n of t)if(!this.values.includes(n))this.values.push(n);this.type=Bi(...this.values)}removeValues(...t){for(let n of t)if(this.values.includes(n))this.values.splice(this.values.indexOf(n),1);this.type=Bi(...this.values)}}var jl=Be("com.tldraw.shape",{AddIsLocked:1,HoistOpacity:2,AddMeta:3,AddWhite:4}),Ff=et({sequenceId:"com.tldraw.shape",recordType:"shape",sequence:[{id:jl.AddIsLocked,up:(t)=>{t.isLocked=!1},down:(t)=>{delete t.isLocked}},{id:jl.HoistOpacity,up:(t)=>{t.opacity=Number(t.props.opacity??"1"),delete t.props.opacity},down:(t)=>{let n=t.opacity;delete t.opacity,t.props.opacity=n<0.175?"0.1":n<0.375?"0.25":n<0.625?"0.5":n<0.875?"0.75":"1"}},{id:jl.AddMeta,up:(t)=>{t.meta={}}},{id:jl.AddWhite,up:(t)=>{},down:(t)=>{if(t.props.color==="white")t.props.color="black"}}]});function mn(t){return`shape:${t??Ls()}`}function qf(t){let n=new Map;for(let[i,o]of Object.entries(t))if(o instanceof Ke){if(n.has(o))throw Error(`Duplicate style prop ${o.id}. Each style prop can only be used once within a shape.`);n.set(o,i)}return n}function ut(t){return t}function pt(t,n){return js(n,(i,o)=>`com.tldraw.shape.${t}/${o}`)}function Gy(t){return rt("shape",{scope:"document",validator:En("shape",Pf("type",js(t,(n,{props:i,meta:o})=>$f(n,i,o))))}).withDefaultProperties(()=>({x:0,y:0,rotation:0,isLocked:!1,opacity:1,meta:{}}))}function Ul(t,n){let i=[];for(let[o,{migrations:a}]of Object.entries(n)){let c=`com.tldraw.${t}.${o}`;if(!a)i.push(dn({sequenceId:c,retroactive:!0,sequence:[]}));else if("sequenceId"in a)Fe(c===a.sequenceId,`sequenceId mismatch for ${o} ${ia} migrations. Expected '${c}', got '${a.sequenceId}'`),i.push(a);else if("sequence"in a)i.push(dn({sequenceId:c,retroactive:!0,sequence:a.sequence.map((m)=>("id"in m)?Bf(t,o,m):m)}));else i.push(dn({sequenceId:c,retroactive:!0,sequence:Object.keys(a.migrators).map((m)=>Number(m)).sort((m,E)=>m-E).map((m)=>({id:`${c}/${m}`,scope:"record",filter:(E)=>E.typeName===t&&E.type===o,up:(E)=>{let _=a.migrators[m].up(E);if(_)return _},down:(E)=>{let _=a.migrators[m].down(E);if(_)return _}}))}))}return i}function Bf(t,n,i){return{id:i.id,dependsOn:i.dependsOn,scope:"record",filter:(o)=>o.typeName===t&&o.type===n,up:(o)=>{let a=i.up(o.props);if(a)o.props=a},down:typeof i.down==="function"?(o)=>{let a=i.down(o.props);if(a)o.props=a}:void 0}}var Ky=["black","grey","light-violet","violet","blue","light-blue","yellow","orange","green","light-green","light-red","red","white"],ur=Ke.defineEnum("tldraw:color",{defaultValue:"black",values:Ky}),ca=Ke.defineEnum("tldraw:labelColor",{defaultValue:"black",values:Ky});var ci=Ke.defineEnum("tldraw:dash",{defaultValue:"draw",values:["draw","solid","dashed","dotted","none"]});var Io=Ke.defineEnum("tldraw:fill",{defaultValue:"none",values:["none","semi","solid","pattern","fill","lined-fill"]});var li=Ke.defineEnum("tldraw:font",{defaultValue:"draw",values:["draw","sans","serif","mono"]});var $r=Ke.defineEnum("tldraw:size",{defaultValue:"m",values:["s","m","l","xl"]});var i1=["arc","elbow"],Jy=Ke.defineEnum("tldraw:arrowKind",{defaultValue:"arc",values:i1}),Yy=["arrow","triangle","square","dot","pipe","diamond","inverted","bar","none"],Xy=Ke.defineEnum("tldraw:arrowheadStart",{defaultValue:"none",values:Yy}),Zy=Ke.defineEnum("tldraw:arrowheadEnd",{defaultValue:"arrow",values:Yy}),Wf={kind:Jy,labelColor:ca,color:ur,fill:Io,dash:ci,size:$r,arrowheadStart:Xy,arrowheadEnd:Zy,font:li,start:ts,end:ts,bend:Oe,richText:ai,labelPosition:Oe,scale:Rt,elbowMidPoint:Oe},rs=pt("arrow",{AddLabelColor:1,AddIsPrecise:2,AddLabelPosition:3,ExtractBindings:4,AddScale:5,AddElbow:6,AddRichText:7,AddRichTextAttrs:8});function To(t){return Bf("shape","arrow",t)}var Hf=dn({sequenceId:"com.tldraw.shape.arrow",retroactive:!1,sequence:[To({id:rs.AddLabelColor,up:(t)=>{t.labelColor="black"},down:"retired"}),To({id:rs.AddIsPrecise,up:({start:t,end:n})=>{if(t.type==="binding")t.isPrecise=!(t.normalizedAnchor.x===0.5&&t.normalizedAnchor.y===0.5);if(n.type==="binding")n.isPrecise=!(n.normalizedAnchor.x===0.5&&n.normalizedAnchor.y===0.5)},down:({start:t,end:n})=>{if(t.type==="binding"){if(!t.isPrecise)t.normalizedAnchor={x:0.5,y:0.5};delete t.isPrecise}if(n.type==="binding"){if(!n.isPrecise)n.normalizedAnchor={x:0.5,y:0.5};delete n.isPrecise}}}),To({id:rs.AddLabelPosition,up:(t)=>{t.labelPosition=0.5},down:(t)=>{delete t.labelPosition}}),{id:rs.ExtractBindings,scope:"storage",up:(t)=>{let n=[];for(let i of t.values()){if(i.typeName!=="shape"||i.type!=="arrow")continue;let o=i,a=tn(o),{start:c,end:m}=o.props;if(c.type==="binding"){let E=aa(),_={typeName:"binding",id:E,type:"arrow",fromId:o.id,toId:c.boundShapeId,meta:{},props:{terminal:"start",normalizedAnchor:c.normalizedAnchor,isExact:c.isExact,isPrecise:c.isPrecise}};n.push([E,_]),a.props.start={x:0,y:0}}else delete a.props.start.type;if(m.type==="binding"){let E=aa(),_={typeName:"binding",id:E,type:"arrow",fromId:o.id,toId:m.boundShapeId,meta:{},props:{terminal:"end",normalizedAnchor:m.normalizedAnchor,isExact:m.isExact,isPrecise:m.isPrecise}};n.push([E,_]),a.props.end={x:0,y:0}}else delete a.props.end.type;n.push([o.id,a])}for(let[i,o]of n)t.set(i,o)}},To({id:rs.AddScale,up:(t)=>{t.scale=1},down:(t)=>{delete t.scale}}),To({id:rs.AddElbow,up:(t)=>{t.kind="arc",t.elbowMidPoint=0.5},down:(t)=>{delete t.kind,delete t.elbowMidPoint}}),To({id:rs.AddRichText,up:(t)=>{t.richText=Wt(t.text),delete t.text}}),To({id:rs.AddRichTextAttrs,up:(t)=>{},down:(t)=>{if(t.richText&&"attrs"in t.richText)delete t.richText.attrs}})]});var Qy=Bi("center","edge-point","edge","none"),Vf={terminal:Bi("start","end"),normalizedAnchor:ts,isExact:He,isPrecise:He,snap:Qy},ew=jf("arrow",{AddSnap:1}),zf=Lf({sequence:[{dependsOn:[rs.ExtractBindings]},{id:ew.AddSnap,up:(t)=>{t.snap="none"},down:(t)=>{delete t.snap}}]});var o1=En("camera",De({typeName:yr("camera"),id:lt("camera"),x:Oe,y:Oe,z:Oe,meta:Mt})),a1=Be("com.tldraw.camera",{AddMeta:1}),tw=et({sequenceId:"com.tldraw.camera",recordType:"camera",sequence:[{id:a1.AddMeta,up:(t)=>{t.meta={}}}]}),Ro=rt("camera",{validator:o1,scope:"session"}).withDefaultProperties(()=>({x:0,y:0,z:1,meta:{}}));var rw=new Set(["none","default","pointer","cross","grab","rotate","grabbing","resize-edge","resize-corner","text","move","ew-resize","ns-resize","nesw-resize","nwse-resize","nesw-rotate","nwse-rotate","swne-rotate","senw-rotate","zoom-in","zoom-out"]),Gf=Nl(rw),nw=De({type:Gf,rotation:Oe});var sw=new Set(["accent","white","black","selection-stroke","selection-fill","laser","muted-1"]),Kf=Nl(sw);var iw=new Set(["starting","paused","active","complete","stopping"]),Za=De({id:Ne,points:sn(ts),size:Ja,color:Kf,opacity:Oe,state:Nl(iw),delay:Oe,shrink:Oe,taper:He});var la=lt("page"),c1=En("page",De({typeName:yr("page"),id:la,name:Ne,index:Of,meta:Mt})),l1=Be("com.tldraw.page",{AddMeta:1}),ow=et({sequenceId:"com.tldraw.page",recordType:"page",sequence:[{id:l1.AddMeta,up:(t)=>{t.meta={}}}]}),Qa=rt("page",{validator:c1,scope:"document"}).withDefaultProperties(()=>({meta:{}}));var ui=lt("user"),u1=Be("com.tldraw.user",{Initial:1}),aw=et({sequenceId:"com.tldraw.user",recordType:"user",sequence:[{id:u1.Initial,up:(t)=>{}}]});function Fl(t){let n=t?.meta,i=n?De(Object.fromEntries(Object.entries(n).map(([a,c])=>[a,new Ye((m)=>{if(m===void 0)return;return c.validate(m)})]))).allowUnknownProperties():Mt,o=En("user",De({typeName:yr("user"),id:ui,name:Ne,color:Ne,imageUrl:Ne,meta:i}));return rt("user",{validator:o,scope:"document"}).withDefaultProperties(()=>({name:"",color:"",imageUrl:"",meta:{}}))}var zq=En("user",De({typeName:yr("user"),id:ui,name:Ne,color:Ne,imageUrl:Ne,meta:Mt})),Jf=Fl();var sB=lt("instance");function cw(t){let n={};for(let[o,a]of t)n[o]=By(a);let i=En("instance",De({typeName:yr("instance"),id:lt("instance"),currentPageId:la,followingUserId:ui.nullable(),brush:Hi.nullable(),opacityForNextShape:Xa,stylesForNextShape:De(n),cursor:nw,scribbles:sn(Za),isFocusMode:He,isDebugMode:He,isToolLocked:He,exportBackground:He,screenBounds:Hi,insets:sn(He),zoomBrush:Hi.nullable(),isPenMode:He,isGridMode:He,chatMessage:Ne,isChatting:He,highlightedUserIds:sn(ui),isFocused:He,devicePixelRatio:Oe,isCoarsePointer:He,isHoveringCanvas:He.nullable(),openMenus:sn(Ne),isChangingStyle:He,isReadonly:He,meta:Mt,duplicateProps:De({shapeIds:sn(lt("shape")),offset:De({x:Oe,y:Oe})}).nullable(),cameraState:Bi("idle","moving")}));return rt("instance",{validator:i,scope:"session",ephemeralKeys:{currentPageId:!1,meta:!1,followingUserId:!0,opacityForNextShape:!0,stylesForNextShape:!0,brush:!0,cursor:!0,scribbles:!0,isFocusMode:!0,isDebugMode:!0,isToolLocked:!0,exportBackground:!0,screenBounds:!0,insets:!0,zoomBrush:!0,isPenMode:!0,isGridMode:!0,chatMessage:!0,isChatting:!0,highlightedUserIds:!0,isFocused:!0,devicePixelRatio:!0,isCoarsePointer:!0,isHoveringCanvas:!0,openMenus:!0,isChangingStyle:!0,isReadonly:!0,duplicateProps:!0,cameraState:!0}}).withDefaultProperties(()=>({followingUserId:null,opacityForNextShape:1,stylesForNextShape:{},brush:null,scribbles:[],cursor:{type:"default",rotation:0},isFocusMode:!1,exportBackground:!1,isDebugMode:!1,isToolLocked:!1,screenBounds:{x:0,y:0,w:1080,h:720},insets:[!1,!1,!1,!1],zoomBrush:null,isGridMode:!1,isPenMode:!1,chatMessage:"",isChatting:!1,highlightedUserIds:[],isFocused:!1,devicePixelRatio:typeof window>"u"?1:window.devicePixelRatio,isCoarsePointer:!1,isHoveringCanvas:null,openMenus:[],isChangingStyle:!1,isReadonly:!1,meta:{},duplicateProps:null,cameraState:"idle"}))}var nt=Be("com.tldraw.instance",{AddTransparentExportBgs:1,RemoveDialog:2,AddToolLockMode:3,RemoveExtraPropsForNextShape:4,AddLabelColor:5,AddFollowingUserId:6,RemoveAlignJustify:7,AddZoom:8,AddVerticalAlign:9,AddScribbleDelay:10,RemoveUserId:11,AddIsPenModeAndIsGridMode:12,HoistOpacity:13,AddChat:14,AddHighlightedUserIds:15,ReplacePropsForNextShapeWithStylesForNextShape:16,AddMeta:17,RemoveCursorColor:18,AddLonelyProperties:19,ReadOnlyReadonly:20,AddHoveringCanvas:21,AddScribbles:22,AddInset:23,AddDuplicateProps:24,RemoveCanMoveCamera:25,AddCameraState:26}),lw=et({sequenceId:"com.tldraw.instance",recordType:"instance",sequence:[{id:nt.AddTransparentExportBgs,up:(t)=>({...t,exportBackground:!0})},{id:nt.RemoveDialog,up:({dialog:t,...n})=>n},{id:nt.AddToolLockMode,up:(t)=>({...t,isToolLocked:!1})},{id:nt.RemoveExtraPropsForNextShape,up:({propsForNextShape:t,...n})=>({...n,propsForNextShape:Object.fromEntries(Object.entries(t).filter(([i])=>["color","labelColor","dash","fill","size","font","align","verticalAlign","icon","geo","arrowheadStart","arrowheadEnd","spline"].includes(i)))})},{id:nt.AddLabelColor,up:({propsForNextShape:t,...n})=>({...n,propsForNextShape:{...t,labelColor:"black"}})},{id:nt.AddFollowingUserId,up:(t)=>({...t,followingUserId:null})},{id:nt.RemoveAlignJustify,up:(t)=>{let n=t.propsForNextShape.align;if(n==="justify")n="start";return{...t,propsForNextShape:{...t.propsForNextShape,align:n}}}},{id:nt.AddZoom,up:(t)=>({...t,zoomBrush:null})},{id:nt.AddVerticalAlign,up:(t)=>({...t,propsForNextShape:{...t.propsForNextShape,verticalAlign:"middle"}})},{id:nt.AddScribbleDelay,up:(t)=>{if(t.scribble!==null)return{...t,scribble:{...t.scribble,delay:0}};return{...t}}},{id:nt.RemoveUserId,up:({userId:t,...n})=>n},{id:nt.AddIsPenModeAndIsGridMode,up:(t)=>({...t,isPenMode:!1,isGridMode:!1})},{id:nt.HoistOpacity,up:({propsForNextShape:{opacity:t,...n},...i})=>({...i,opacityForNextShape:Number(t??"1"),propsForNextShape:n})},{id:nt.AddChat,up:(t)=>({...t,chatMessage:"",isChatting:!1})},{id:nt.AddHighlightedUserIds,up:(t)=>({...t,highlightedUserIds:[]})},{id:nt.ReplacePropsForNextShapeWithStylesForNextShape,up:({propsForNextShape:t,...n})=>({...n,stylesForNextShape:{}})},{id:nt.AddMeta,up:(t)=>({...t,meta:{}})},{id:nt.RemoveCursorColor,up:(t)=>{let{color:n,...i}=t.cursor;return{...t,cursor:i}}},{id:nt.AddLonelyProperties,up:(t)=>({...t,canMoveCamera:!0,isFocused:!1,devicePixelRatio:1,isCoarsePointer:!1,openMenus:[],isChangingStyle:!1,isReadOnly:!1})},{id:nt.ReadOnlyReadonly,up:({isReadOnly:t,...n})=>({...n,isReadonly:t})},{id:nt.AddHoveringCanvas,up:(t)=>({...t,isHoveringCanvas:null})},{id:nt.AddScribbles,up:({scribble:t,...n})=>({...n,scribbles:[]})},{id:nt.AddInset,up:(t)=>({...t,insets:[!1,!1,!1,!1]}),down:({insets:t,...n})=>({...n})},{id:nt.AddDuplicateProps,up:(t)=>({...t,duplicateProps:null}),down:({duplicateProps:t,...n})=>({...n})},{id:nt.RemoveCanMoveCamera,up:({canMoveCamera:t,...n})=>({...n}),down:(t)=>({...t,canMoveCamera:!0})},{id:nt.AddCameraState,up:(t)=>({...t,cameraState:"idle"}),down:({cameraState:t,...n})=>n}]}),ec="instance:instance";var d1=En("instance_page_state",De({typeName:yr("instance_page_state"),id:lt("instance_page_state"),pageId:la,selectedShapeIds:sn(hn),hintingShapeIds:sn(hn),erasingShapeIds:sn(hn),hoveredShapeId:hn.nullable(),editingShapeId:hn.nullable(),croppingShapeId:hn.nullable(),focusedGroupId:hn.nullable(),meta:Mt})),tc=Be("com.tldraw.instance_page_state",{AddCroppingId:1,RemoveInstanceIdAndCameraId:2,AddMeta:3,RenameProperties:4,RenamePropertiesAgain:5}),uw=et({sequenceId:"com.tldraw.instance_page_state",recordType:"instance_page_state",sequence:[{id:tc.AddCroppingId,up(t){t.croppingShapeId=null}},{id:tc.RemoveInstanceIdAndCameraId,up(t){delete t.instanceId,delete t.cameraId}},{id:tc.AddMeta,up:(t)=>{t.meta={}}},{id:tc.RenameProperties,up:(t)=>{},down:(t)=>{}},{id:tc.RenamePropertiesAgain,up:(t)=>{t.selectedShapeIds=t.selectedIds,delete t.selectedIds,t.hintingShapeIds=t.hintingIds,delete t.hintingIds,t.erasingShapeIds=t.erasingIds,delete t.erasingIds,t.hoveredShapeId=t.hoveredId,delete t.hoveredId,t.editingShapeId=t.editingId,delete t.editingId,t.croppingShapeId=t.croppingShapeId??t.croppingId??null,delete t.croppingId,t.focusedGroupId=t.focusLayerId,delete t.focusLayerId},down:(t)=>{t.selectedIds=t.selectedShapeIds,delete t.selectedShapeIds,t.hintingIds=t.hintingShapeIds,delete t.hintingShapeIds,t.erasingIds=t.erasingShapeIds,delete t.erasingShapeIds,t.hoveredId=t.hoveredShapeId,delete t.hoveredShapeId,t.editingId=t.editingShapeId,delete t.editingShapeId,t.croppingId=t.croppingShapeId,delete t.croppingShapeId,t.focusLayerId=t.focusedGroupId,delete t.focusedGroupId}}]}),Vi=rt("instance_page_state",{validator:d1,scope:"session",ephemeralKeys:{pageId:!1,selectedShapeIds:!1,editingShapeId:!0,croppingShapeId:!1,meta:!1,hintingShapeIds:!0,erasingShapeIds:!0,hoveredShapeId:!0,focusedGroupId:!0}}).withDefaultProperties(()=>({editingShapeId:null,croppingShapeId:null,selectedShapeIds:[],hoveredShapeId:null,erasingShapeIds:[],hintingShapeIds:[],focusedGroupId:null,meta:{}}));var f1=En("pointer",De({typeName:yr("pointer"),id:lt("pointer"),x:Oe,y:Oe,lastActivityTimestamp:Oe,meta:Mt})),p1=Be("com.tldraw.pointer",{AddMeta:1}),dw=et({sequenceId:"com.tldraw.pointer",recordType:"pointer",sequence:[{id:p1.AddMeta,up:(t)=>{t.meta={}}}]}),ua=rt("pointer",{validator:f1,scope:"session"}).withDefaultProperties(()=>({x:0,y:0,lastActivityTimestamp:0,meta:{}})),rc=ua.createId("pointer");var h1=En("instance_presence",De({typeName:yr("instance_presence"),id:lt("instance_presence"),userId:ui,userName:Ne,lastActivityTimestamp:Oe.nullable(),followingUserId:ui.nullable(),cursor:De({x:Oe,y:Oe,type:Gf,rotation:Oe}).nullable(),color:Ne,camera:De({x:Oe,y:Oe,z:Oe}).nullable(),screenBounds:Hi.nullable(),selectedShapeIds:sn(lt("shape")),currentPageId:lt("page"),brush:Hi.nullable(),scribbles:sn(Za),chatMessage:Ne,meta:Mt})),da=Be("com.tldraw.instance_presence",{AddScribbleDelay:1,RemoveInstanceId:2,AddChatMessage:3,AddMeta:4,RenameSelectedShapeIds:5,NullableCameraCursor:6}),fw=et({sequenceId:"com.tldraw.instance_presence",recordType:"instance_presence",sequence:[{id:da.AddScribbleDelay,up:(t)=>{if(t.scribble!==null)t.scribble.delay=0}},{id:da.RemoveInstanceId,up:(t)=>{delete t.instanceId}},{id:da.AddChatMessage,up:(t)=>{t.chatMessage=""}},{id:da.AddMeta,up:(t)=>{t.meta={}}},{id:da.RenameSelectedShapeIds,up:(t)=>{}},{id:da.NullableCameraCursor,up:(t)=>{},down:(t)=>{if(t.camera===null)t.camera={x:0,y:0,z:1};if(t.lastActivityTimestamp===null)t.lastActivityTimestamp=0;if(t.cursor===null)t.cursor={type:"default",x:0,y:0,rotation:0};if(t.screenBounds===null)t.screenBounds={x:0,y:0,w:1,h:1}}}]}),ql=rt("instance_presence",{validator:h1,scope:"presence"}).withDefaultProperties(()=>({lastActivityTimestamp:null,followingUserId:null,color:"#FF0000",camera:null,cursor:null,screenBounds:null,selectedShapeIds:[],brush:null,scribbles:[],chatMessage:"",meta:{}}));var m1=Be("com.tldraw.asset",{AddMeta:1}),Yf=et({sequenceId:"com.tldraw.asset",recordType:"asset",sequence:[{id:m1.AddMeta,up:(t)=>{t.meta={}}}]});function Xf(t){return rt("asset",{scope:"document",validator:En("asset",Pf("type",js(t,(n,{props:i,meta:o})=>oi(n,i,o))))}).withDefaultProperties(()=>({meta:{}}))}var Zf=rt("asset",{scope:"document"}).withDefaultProperties(()=>({meta:{}}));function pw(t,n){return rt(t,{scope:n.scope,validator:n.validator}).withDefaultProperties(n.createDefaultProperties??(()=>({})))}function hw(t){let n=[];for(let[i,o]of Object.entries(t)){let a=`com.tldraw.${i}`,{migrations:c}=o;if(!c)n.push(dn({sequenceId:a,retroactive:!0,sequence:[]}));else if("sequenceId"in c)Fe(a===c.sequenceId,`sequenceId mismatch for ${i} custom record migrations. Expected '${a}', got '${c.sequenceId}'`),n.push(c);else if("sequence"in c)n.push(dn({sequenceId:a,retroactive:!0,sequence:c.sequence.map((m)=>{if(!("id"in m))return m;return{id:m.id,dependsOn:m.dependsOn,scope:"record",filter:(E)=>E.typeName===i,up:(E)=>{let _=m.up(E);if(_)return _},down:typeof m.down==="function"?(E)=>{let _=m.down(E);if(_)return _}:void 0}})}))}return n}var g1=En("document",De({typeName:yr("document"),id:yr("document:document"),gridSize:Oe,name:Ne,meta:Mt}));var mw=Be("com.tldraw.document",{AddName:1,AddMeta:2}),gw=et({sequenceId:"com.tldraw.document",recordType:"document",sequence:[{id:mw.AddName,up:(t)=>{t.name=""},down:(t)=>{delete t.name}},{id:mw.AddMeta,up:(t)=>{t.meta={}}}]}),fa=rt("document",{validator:g1,scope:"document"}).withDefaultProperties(()=>({gridSize:10,name:"",meta:{}})),Bl=fa.createId("document");var Qf={w:Rt,h:Rt,assetId:Wi.nullable(),url:Us},yw=pt("bookmark",{NullAssetId:1,MakeUrlsValid:2}),ep=ut({sequence:[{id:yw.NullAssetId,up:(t)=>{if(t.assetId===void 0)t.assetId=null},down:"retired"},{id:yw.MakeUrlsValid,up:(t)=>{if(!Us.isValid(t.url))t.url=""},down:(t)=>{}}]});var zi=2,tp=3;var qs=new Uint8Array(128);for(let t=0;t<64;t++)qs["ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charCodeAt(t)]=t;var di=63,ww=61,bw=new Float64Array(31);for(let t=0;t<31;t++)bw[t]=Math.pow(2,t-15);var Sw=Math.pow(2,-14)/1024,vw=new Float64Array(1024);for(let t=0;t<1024;t++)vw[t]=1+t/1024;function y1(t,n){return t.getFloat16(n,!0)}function w1(t,n){return _1(t.getUint16(n,!0))}var gn=typeof DataView.prototype.getFloat16==="function"?y1:w1;function S1(t,n,i){t.setFloat16(n,i,!0)}function b1(t,n,i){t.setUint16(n,I1(i),!0)}var Ss=typeof DataView.prototype.setFloat16==="function"?S1:b1;function v1(t){return Uint8Array.fromBase64(t)}function E1(t){let n=t.length,i=0;if(n>0&&t.charCodeAt(n-1)===ww){if(i++,n>1&&t.charCodeAt(n-2)===ww)i++}let o=Math.floor(n*3/4)-i,a=new Uint8Array(o),c=0,m=Math.floor((n-i)/4)*4;for(let E=0;E<m;E+=4){let _=qs[t.charCodeAt(E)],I=qs[t.charCodeAt(E+1)],T=qs[t.charCodeAt(E+2)],R=qs[t.charCodeAt(E+3)],P=_<<18|I<<12|T<<6|R;a[c++]=P>>16&255,a[c++]=P>>8&255,a[c++]=P&255}if(i===1){let E=qs[t.charCodeAt(m)],_=qs[t.charCodeAt(m+1)],I=qs[t.charCodeAt(m+2)],T=E<<18|_<<12|I<<6;a[c++]=T>>16&255,a[c++]=T>>8&255}else if(i===2){let E=qs[t.charCodeAt(m)],_=qs[t.charCodeAt(m+1)],I=E<<18|_<<12;a[c++]=I>>16&255}return a}function A1(t){return t.toBase64()}function x1(t){let n=t.length,i=Math.floor(n/3)*3,o="";for(let c=0;c<i;c+=3){let m=t[c],E=t[c+1],_=t[c+2],I=m<<16|E<<8|_;o+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[I>>18&di]+"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[I>>12&di]+"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[I>>6&di]+"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[I&di]}let a=n-i;if(a===1){let c=t[i]<<16;o+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[c>>18&di]+"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[c>>12&di]+"=="}else if(a===2){let c=t[i]<<16|t[i+1]<<8;o+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[c>>18&di]+"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[c>>12&di]+"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[c>>6&di]+"="}return o}var Wl=typeof Uint8Array.prototype.toBase64==="function"?A1:x1,Po=typeof Uint8Array.fromBase64==="function"?v1:E1;function _1(t){let n=t>>15,i=t>>10&31,o=t&1023;if(i===0)return n?-o*Sw:o*Sw;if(i===31)return o?NaN:n?-1/0:1/0;let a=bw[i]*vw[o];return n?-a:a}function I1(t){if(t===0)return Object.is(t,-0)?32768:0;if(!Number.isFinite(t)){if(Number.isNaN(t))return 32256;return t>0?31744:64512}let n=t<0?1:0;t=Math.abs(t);let i=Math.floor(Math.log2(t)),o=i+15;if(o>=31)return n<<15|31744;if(o<=0){let m=Math.round(t*Math.pow(2,14)*1024);return n<<15|m&1023}let a=t/Math.pow(2,i)-1,c=Math.round(a*1024);if(c>=1024){if(c=0,o++,o>=31)return n<<15|31744}return n<<15|o<<10|c}class At{static _legacyEncodePoint(t,n,i){let o=new Uint8Array(6),a=new DataView(o.buffer);return Ss(a,0,t),Ss(a,2,n),Ss(a,4,i),Wl(o)}static _legacyEncodePoints(t){if(t.length===0)return"";let n=new Uint8Array(t.length*6),i=new DataView(n.buffer);for(let o=0;o<t.length;o++){let a=t[o],c=o*6;Ss(i,c,a.x),Ss(i,c+2,a.y),Ss(i,c+4,a.z??0.5)}return Wl(n)}static _legacyDecodePoints(t){let n=Po(t),i=new DataView(n.buffer,n.byteOffset,n.byteLength),o=[];for(let a=0;a<n.length;a+=6)o.push({x:gn(i,a),y:gn(i,a+2),z:gn(i,a+4)});return o}static encodePoints(t,n){if(n===2)return At.encodePoints2D(t);if(t.length===0)return"";let i=12,o=(t.length-1)*6,a=i+o,c=new Uint8Array(a),m=new DataView(c.buffer),E=t[0];m.setFloat32(0,E.x,!0),m.setFloat32(4,E.y,!0),m.setFloat32(8,E.z??0.5,!0);let{x:_,y:I}=E,T=E.z??0.5;for(let R=1;R<t.length;R++){let P=t[R],M=P.z??0.5,N=i+(R-1)*6;Ss(m,N,P.x-_),Ss(m,N+2,P.y-I),Ss(m,N+4,M-T),_=P.x,I=P.y,T=M}return Wl(c)}static decodePoints(t,n){if(n===2)return At.decodePoints2D(t);if(t.length===0)return[];let i=Po(t),o=new DataView(i.buffer,i.byteOffset,i.byteLength),a=[],c=o.getFloat32(0,!0),m=o.getFloat32(4,!0),E=o.getFloat32(8,!0);a.push({x:c,y:m,z:E});let _=12;for(let I=_;I<i.length;I+=6)c+=gn(o,I),m+=gn(o,I+2),E+=gn(o,I+4),a.push({x:c,y:m,z:E});return a}static decodeFirstPoint(t,n){if(n===2)return At.decodeFirstPoint2D(t);if(t.length<16)return null;let i=Po(t.slice(0,16)),o=new DataView(i.buffer,i.byteOffset,i.byteLength);return{x:o.getFloat32(0,!0),y:o.getFloat32(4,!0),z:o.getFloat32(8,!0)}}static decodeLastPoint(t,n){if(n===2)return At.decodeLastPoint2D(t);if(t.length<16)return null;let i=Po(t),o=new DataView(i.buffer,i.byteOffset,i.byteLength),a=o.getFloat32(0,!0),c=o.getFloat32(4,!0),m=o.getFloat32(8,!0),E=12;for(let _=E;_<i.length;_+=6)a+=gn(o,_),c+=gn(o,_+2),m+=gn(o,_+4);return{x:a,y:c,z:m}}static encodePoints2D(t){if(t.length===0)return"";let n=8,i=(t.length-1)*4,o=new Uint8Array(n+i),a=new DataView(o.buffer),c=t[0];a.setFloat32(0,c.x,!0),a.setFloat32(4,c.y,!0);let{x:m,y:E}=c;for(let _=1;_<t.length;_++){let I=t[_],T=n+(_-1)*4;Ss(a,T,I.x-m),Ss(a,T+2,I.y-E),m=I.x,E=I.y}return Wl(o)}static decodePoints2D(t){if(t.length===0)return[];let n=Po(t),i=new DataView(n.buffer,n.byteOffset,n.byteLength),o=[],a=i.getFloat32(0,!0),c=i.getFloat32(4,!0);o.push({x:a,y:c,z:0.5});let m=8;for(let E=m;E<n.length;E+=4)a+=gn(i,E),c+=gn(i,E+2),o.push({x:a,y:c,z:0.5});return o}static decodeFirstPoint2D(t){if(t.length<12)return null;let n=Po(t.slice(0,12)),i=new DataView(n.buffer,n.byteOffset,n.byteLength);return{x:i.getFloat32(0,!0),y:i.getFloat32(4,!0),z:0.5}}static decodeLastPoint2D(t){if(t.length<12)return null;let n=Po(t),i=new DataView(n.buffer,n.byteOffset,n.byteLength),o=i.getFloat32(0,!0),a=i.getFloat32(4,!0),c=8;for(let m=c;m<n.length;m+=4)o+=gn(i,m),a+=gn(i,m+2);return{x:o,y:a,z:0.5}}static isSinglePoint(t,n){return t.length<=(n===2?12:16)}}var rp=De({type:Bi("free","straight"),path:Ne,dim:Bi(zi,tp).optional()}),np={color:ur,fill:Io,dash:ci,size:$r,segments:sn(rp),isComplete:He,isClosed:He,isPen:He,scale:Rt,scaleX:Ml,scaleY:Ml},nc=pt("draw",{AddInPen:1,AddScale:2,Base64:3,LegacyPointsConversion:4,OmitNonPressureZ:5}),sp=ut({sequence:[{id:nc.AddInPen,up:(t)=>{let{points:n}=t.segments[0];if(n.length===0){t.isPen=!1;return}let i=!(n[0].z===0||n[0].z===0.5);if(n[1])i=i&&!(n[1].z===0||n[1].z===0.5);t.isPen=i},down:"retired"},{id:nc.AddScale,up:(t)=>{t.scale=1},down:(t)=>{delete t.scale}},{id:nc.Base64,up:(t)=>{t.segments=t.segments.map((n)=>{if(n.path!==void 0)return n;let{points:i,...o}=n,a=Array.isArray(i)?i:At._legacyDecodePoints(i);return{...o,path:At.encodePoints(a)}}),t.scaleX=t.scaleX??1,t.scaleY=t.scaleY??1},down:(t)=>{t.segments=t.segments.map((n)=>{let{path:i,...o}=n;return{...o,points:At.decodePoints(i)}}),delete t.scaleX,delete t.scaleY}},{id:nc.LegacyPointsConversion,up:(t)=>{t.segments=t.segments.map((n)=>{if(n.path!==void 0)return n;let{points:i,...o}=n,a=Array.isArray(i)?i:At._legacyDecodePoints(i);return{...o,path:At.encodePoints(a)}})},down:(t)=>{}},{id:nc.OmitNonPressureZ,up:(t)=>{},down:(t)=>{t.segments=t.segments.map((n)=>{if(n.dim===void 0)return n;let{dim:i,...o}=n;return i===zi?{...o,path:At.encodePoints(At.decodePoints(n.path,zi))}:o})}}]});var T1=/(^\/r\/[^/]+\/?$)/,R1=[{hostnames:["beta.tldraw.com","tldraw.com","localhost:3000"],canEditWhileLocked:!0,fromEmbedUrl:(t)=>{let n=ar(t);if(n&&n.pathname.match(T1))return t;return}},{hostnames:["figma.com"],canEditWhileLocked:!0,fromEmbedUrl:(t)=>{let n=ar(t);if(n&&n.pathname.match(/^\/embed\/?$/)){let i=n.searchParams.get("url");if(i)return i}return}},{hostnames:["google.*"],canEditWhileLocked:!0,fromEmbedUrl:(t)=>{let n=ar(t);if(!n)return;if(n.pathname.match(/^\/maps\/embed\/v1\/view\/?$/)&&n.searchParams.has("center")&&n.searchParams.get("zoom")){let o=n.searchParams.get("zoom"),[a,c]=n.searchParams.get("center").split(",");return`https://www.google.com/maps/@${a},${c},${o}z`}return}},{hostnames:["val.town"],canEditWhileLocked:!0,fromEmbedUrl:(t)=>{let n=ar(t),i=n&&n.pathname.match(/\/embed\/(.+)\/?/);if(i)return`https://www.val.town/v/${i[1]}`;return}},{hostnames:["codesandbox.io"],canEditWhileLocked:!0,fromEmbedUrl:(t)=>{let n=ar(t),i=n&&n.pathname.match(/\/embed\/([^/]+)\/?/);if(i)return`https://codesandbox.io/s/${i[1]}`;return}},{hostnames:["codepen.io"],canEditWhileLocked:!0,fromEmbedUrl:(t)=>{let n=/https:\/\/codepen.io\/([^/]+)\/embed\/([^/]+)/,i=t.match(n);if(i){let[o,a,c]=i;return`https://codepen.io/${a}/pen/${c}`}return}},{hostnames:["scratch.mit.edu"],canEditWhileLocked:!0,fromEmbedUrl:(t)=>{let n=/https:\/\/scratch.mit.edu\/projects\/embed\/([^/]+)/,i=t.match(n);if(i){let[o,a]=i;return`https://scratch.mit.edu/projects/${a}`}return}},{hostnames:["*.youtube.com","youtube.com","youtu.be"],canEditWhileLocked:!0,fromEmbedUrl:(t)=>{let n=ar(t);if(!n)return;if(n.hostname.replace(/^www./,"")==="youtube.com"){let o=n.pathname.match(/^\/embed\/([^/]+)\/?/);if(o)return`https://www.youtube.com/watch?v=${o[1]}`}return}},{hostnames:["calendar.google.*"],canEditWhileLocked:!0,fromEmbedUrl:(t)=>{let n=ar(t),i=n?.searchParams.get("src");if(n?.pathname.match(/\/calendar\/embed/)&&i){n.pathname="/calendar/u/0";let o=Array.from(n.searchParams.keys());for(let a of o)n.searchParams.delete(a);return n.searchParams.set("cid",i),n.href}return}},{hostnames:["docs.google.*"],canEditWhileLocked:!0,fromEmbedUrl:(t)=>{let n=ar(t);if(n?.pathname.match(/^\/presentation/)&&n?.pathname.match(/\/embed\/?$/)){n.pathname=n.pathname.replace(/\/embed$/,"/pub");let i=Array.from(n.searchParams.keys());for(let o of i)n.searchParams.delete(o);return n.href}return}},{hostnames:["gist.github.com"],canEditWhileLocked:!0,fromEmbedUrl:(t)=>{let n=ar(t);if(n&&n.pathname.match(/\/([^/]+)\/([^/]+)/)){if(!t.split("/").pop())return;return t}return}},{hostnames:["replit.com"],canEditWhileLocked:!0,fromEmbedUrl:(t)=>{let n=ar(t);if(n&&n.pathname.match(/\/@([^/]+)\/([^/]+)/)&&n.searchParams.has("embed"))return n.searchParams.delete("embed"),n.href;return}},{hostnames:["felt.com"],canEditWhileLocked:!0,fromEmbedUrl:(t)=>{let n=ar(t);if(n&&n.pathname.match(/^\/embed\/map\//))return n.pathname=n.pathname.replace(/^\/embed/,""),n.href;return}},{hostnames:["open.spotify.com"],canEditWhileLocked:!0,fromEmbedUrl:(t)=>{let n=ar(t);if(n&&n.pathname.match(/^\/embed\/(artist|album)\//))return n.origin+n.pathname.replace(/^\/embed/,"");return}},{hostnames:["vimeo.com","player.vimeo.com"],canEditWhileLocked:!0,fromEmbedUrl:(t)=>{let n=ar(t);if(n&&n.hostname==="player.vimeo.com"){let i=n.pathname.match(/^\/video\/([^/]+)\/?$/);if(i)return"https://vimeo.com/"+i[1]}return}},{hostnames:["observablehq.com"],canEditWhileLocked:!0,fromEmbedUrl:(t)=>{let n=ar(t);if(n&&n.pathname.match(/^\/embed\/@([^/]+)\/([^/]+)\/?$/))return`${n.origin}${n.pathname.replace("/embed","")}#cell-*`;if(n&&n.pathname.match(/^\/embed\/([^/]+)\/?$/))return`${n.origin}${n.pathname.replace("/embed","/d")}#cell-*`;return}},{hostnames:["desmos.com"],canEditWhileLocked:!0,fromEmbedUrl:(t)=>{let n=ar(t);if(n&&n.hostname==="www.desmos.com"&&n.pathname.match(/^\/calculator\/([^/]+)\/?$/)&&n.search==="?embed"&&n.hash==="")return t.replace("?embed","");return}}],ip={w:Rt,h:Rt,url:Ne},Hl=pt("embed",{GenOriginalUrlInEmbed:1,RemoveDoesResize:2,RemoveTmpOldUrl:3,RemovePermissionOverrides:4}),op=ut({sequence:[{id:Hl.GenOriginalUrlInEmbed,up:(t)=>{try{let n=t.url,i=new URL(n).host.replace("www.",""),o;for(let a of R1)if(a.hostnames.includes(i))try{o=a.fromEmbedUrl(n)}catch(c){console.warn(c)}t.tmpOldUrl=t.url,t.url=o??""}catch{t.url="",t.tmpOldUrl=t.url}},down:"retired"},{id:Hl.RemoveDoesResize,up:(t)=>{delete t.doesResize},down:"retired"},{id:Hl.RemoveTmpOldUrl,up:(t)=>{delete t.tmpOldUrl},down:"retired"},{id:Hl.RemovePermissionOverrides,up:(t)=>{delete t.overridePermissions},down:"retired"}]});var ap={w:Rt,h:Rt,name:Ne,color:{validate:(t)=>ur.validate(t)}},P1=pt("frame",{AddColorProp:1}),cp=ut({sequence:[{id:P1.AddColorProp,up:(t)=>{t.color="black"},down:(t)=>{delete t.color}}]});var sc=Ke.defineEnum("tldraw:horizontalAlign",{defaultValue:"middle",values:["start","middle","end","start-legacy","end-legacy","middle-legacy"]});var ic=Ke.defineEnum("tldraw:verticalAlign",{defaultValue:"middle",values:["start","middle","end"]});var Ew=Ke.defineEnum("tldraw:geo",{defaultValue:"rectangle",values:["cloud","rectangle","ellipse","triangle","diamond","pentagon","hexagon","octagon","star","rhombus","rhombus-2","oval","trapezoid","arrow-right","arrow-left","arrow-up","arrow-down","x-box","check-box","heart"]}),lp={geo:Ew,dash:ci,url:Us,w:Rt,h:Rt,growY:Ja,scale:Rt,labelColor:ca,color:ur,fill:Io,size:$r,font:li,align:sc,verticalAlign:ic,richText:ai},bs=pt("geo",{AddUrlProp:1,AddLabelColor:2,RemoveJustify:3,AddCheckBox:4,AddVerticalAlign:5,MigrateLegacyAlign:6,AddCloud:7,MakeUrlsValid:8,AddScale:9,AddRichText:10,AddRichTextAttrs:11}),up=ut({sequence:[{id:bs.AddUrlProp,up:(t)=>{t.url=""},down:"retired"},{id:bs.AddLabelColor,up:(t)=>{t.labelColor="black"},down:"retired"},{id:bs.RemoveJustify,up:(t)=>{if(t.align==="justify")t.align="start"},down:"retired"},{id:bs.AddCheckBox,up:(t)=>{},down:"retired"},{id:bs.AddVerticalAlign,up:(t)=>{t.verticalAlign="middle"},down:"retired"},{id:bs.MigrateLegacyAlign,up:(t)=>{let n;switch(t.align){case"start":n="start-legacy";break;case"end":n="end-legacy";break;default:n="middle-legacy";break}t.align=n},down:"retired"},{id:bs.AddCloud,up:(t)=>{},down:"retired"},{id:bs.MakeUrlsValid,up:(t)=>{if(!Us.isValid(t.url))t.url=""},down:(t)=>{}},{id:bs.AddScale,up:(t)=>{t.scale=1},down:(t)=>{delete t.scale}},{id:bs.AddRichText,up:(t)=>{t.richText=Wt(t.text),delete t.text}},{id:bs.AddRichTextAttrs,up:(t)=>{},down:(t)=>{if(t.richText&&"attrs"in t.richText)delete t.richText.attrs}}]});var dp={},fp=ut({sequence:[]});var pp={color:ur,size:$r,segments:sn(rp),isComplete:He,isPen:He,scale:Rt,scaleX:Ml,scaleY:Ml},Vl=pt("highlight",{AddScale:1,Base64:2,LegacyPointsConversion:3,OmitNonPressureZ:4}),hp=ut({sequence:[{id:Vl.AddScale,up:(t)=>{t.scale=1},down:(t)=>{delete t.scale}},{id:Vl.Base64,up:(t)=>{t.segments=t.segments.map((n)=>{if(n.path!==void 0)return n;let{points:i,...o}=n,a=Array.isArray(i)?i:At._legacyDecodePoints(i);return{...o,path:At.encodePoints(a)}}),t.scaleX=t.scaleX??1,t.scaleY=t.scaleY??1},down:(t)=>{t.segments=t.segments.map((n)=>{let{path:i,...o}=n;return{...o,points:At.decodePoints(i)}}),delete t.scaleX,delete t.scaleY}},{id:Vl.LegacyPointsConversion,up:(t)=>{t.segments=t.segments.map((n)=>{if(n.path!==void 0)return n;let{points:i,...o}=n,a=Array.isArray(i)?i:At._legacyDecodePoints(i);return{...o,path:At.encodePoints(a)}})},down:(t)=>{}},{id:Vl.OmitNonPressureZ,up:(t)=>{},down:(t)=>{t.segments=t.segments.map((n)=>{if(n.dim===void 0)return n;let{dim:i,...o}=n;return i===zi?{...o,path:At.encodePoints(At.decodePoints(n.path,zi))}:o})}}]});var Aw=De({topLeft:ts,bottomRight:ts,isCircle:He.optional()}),mp={w:Rt,h:Rt,playing:He,url:Us,assetId:Wi.nullable(),crop:Aw.nullable(),flipX:He,flipY:He,altText:Ne},oc=pt("image",{AddUrlProp:1,AddCropProp:2,MakeUrlsValid:3,AddFlipProps:4,AddAltText:5}),gp=ut({sequence:[{id:oc.AddUrlProp,up:(t)=>{t.url=""},down:"retired"},{id:oc.AddCropProp,up:(t)=>{t.crop=null},down:(t)=>{delete t.crop}},{id:oc.MakeUrlsValid,up:(t)=>{if(!Us.isValid(t.url))t.url=""},down:(t)=>{}},{id:oc.AddFlipProps,up:(t)=>{t.flipX=!1,t.flipY=!1},down:(t)=>{delete t.flipX,delete t.flipY}},{id:oc.AddAltText,up:(t)=>{t.altText=""},down:(t)=>{delete t.altText}}]});var xw=Ke.defineEnum("tldraw:spline",{defaultValue:"line",values:["cubic","line"]}),C1=De({id:Ne,index:Of,x:Oe,y:Oe}),yp={color:ur,dash:ci,size:$r,spline:xw,points:e1(Ne,C1),scale:Rt},ac=pt("line",{AddSnapHandles:1,RemoveExtraHandleProps:2,HandlesToPoints:3,PointIndexIds:4,AddScale:5}),wp=ut({sequence:[{id:ac.AddSnapHandles,up:(t)=>{for(let n of Object.values(t.handles))n.canSnap=!0},down:"retired"},{id:ac.RemoveExtraHandleProps,up:(t)=>{t.handles=Zd(Object.values(t.handles).map((n)=>[n.index,{x:n.x,y:n.y}]))},down:(t)=>{let n=Object.entries(t.handles).map(([i,o])=>({index:i,...o})).sort(So);t.handles=Object.fromEntries(n.map((i,o)=>{let a=o===0?"start":o===n.length-1?"end":`handle:${i.index}`;return[a,{id:a,type:"vertex",canBind:!1,canSnap:!0,index:i.index,x:i.x,y:i.y}]}))}},{id:ac.HandlesToPoints,up:(t)=>{let n=Object.entries(t.handles).map(([i,{x:o,y:a}])=>({x:o,y:a,index:i})).sort(So);t.points=n.map(({x:i,y:o})=>({x:i,y:o})),delete t.handles},down:(t)=>{let n=wl(t.points.length);t.handles=Object.fromEntries(t.points.map((i,o)=>[n[o],{x:i.x,y:i.y}])),delete t.points}},{id:ac.PointIndexIds,up:(t)=>{let n=wl(t.points.length);t.points=Object.fromEntries(t.points.map((i,o)=>{let a=n[o];return[a,{id:a,index:a,x:i.x,y:i.y}]}))},down:(t)=>{let n=Object.values(t.points).sort(So);t.points=n.map(({x:i,y:o})=>({x:i,y:o}))}},{id:ac.AddScale,up:(t)=>{t.scale=1},down:(t)=>{delete t.scale}}]});var Sp={color:ur,labelColor:ca,size:$r,font:li,fontSizeAdjustment:Ja.nullable(),align:sc,verticalAlign:ic,growY:Ja,url:Us,richText:ai,scale:Rt,textLastEditedBy:Ne.nullable()},yn=pt("note",{AddUrlProp:1,RemoveJustify:2,MigrateLegacyAlign:3,AddVerticalAlign:4,MakeUrlsValid:5,AddFontSizeAdjustment:6,AddScale:7,AddLabelColor:8,AddRichText:9,AddRichTextAttrs:10,AddFirstEditedBy:11,MakeFontSizeAdjustmentRatio:12,RenameFirstEditedByToLast:13}),bp=ut({sequence:[{id:yn.AddUrlProp,up:(t)=>{t.url=""},down:"retired"},{id:yn.RemoveJustify,up:(t)=>{if(t.align==="justify")t.align="start"},down:"retired"},{id:yn.MigrateLegacyAlign,up:(t)=>{switch(t.align){case"start":t.align="start-legacy";return;case"end":t.align="end-legacy";return;default:t.align="middle-legacy";return}},down:"retired"},{id:yn.AddVerticalAlign,up:(t)=>{t.verticalAlign="middle"},down:"retired"},{id:yn.MakeUrlsValid,up:(t)=>{if(!Us.isValid(t.url))t.url=""},down:(t)=>{}},{id:yn.AddFontSizeAdjustment,up:(t)=>{t.fontSizeAdjustment=0},down:(t)=>{delete t.fontSizeAdjustment}},{id:yn.AddScale,up:(t)=>{t.scale=1},down:(t)=>{delete t.scale}},{id:yn.AddLabelColor,up:(t)=>{t.labelColor="black"},down:(t)=>{delete t.labelColor}},{id:yn.AddRichText,up:(t)=>{t.richText=Wt(t.text),delete t.text}},{id:yn.AddRichTextAttrs,up:(t)=>{},down:(t)=>{if(t.richText&&"attrs"in t.richText)delete t.richText.attrs}},{id:yn.AddFirstEditedBy,up:(t)=>{t.textFirstEditedBy=null},down:(t)=>{delete t.textFirstEditedBy}},{id:yn.MakeFontSizeAdjustmentRatio,up:(t)=>{t.fontSizeAdjustment=t.fontSizeAdjustment===0?1:null},down:(t)=>{t.fontSizeAdjustment=0}},{id:yn.RenameFirstEditedByToLast,up:(t)=>{t.textLastEditedBy=t.textFirstEditedBy??null,delete t.textFirstEditedBy},down:(t)=>{t.textFirstEditedBy=t.textLastEditedBy??null,delete t.textLastEditedBy}}]});var vp=Ke.defineEnum("tldraw:textAlign",{defaultValue:"start",values:["start","middle","end"]});var Ep={color:ur,size:$r,font:li,textAlign:vp,w:Rt,richText:ai,scale:Rt,autoSize:He},zl=pt("text",{RemoveJustify:1,AddTextAlign:2,AddRichText:3,AddRichTextAttrs:4}),Ap=ut({sequence:[{id:zl.RemoveJustify,up:(t)=>{if(t.align==="justify")t.align="start"},down:"retired"},{id:zl.AddTextAlign,up:(t)=>{t.textAlign=t.align,delete t.align},down:(t)=>{t.align=t.textAlign,delete t.textAlign}},{id:zl.AddRichText,up:(t)=>{t.richText=Wt(t.text),delete t.text}},{id:zl.AddRichTextAttrs,up:(t)=>{},down:(t)=>{if(t.richText&&"attrs"in t.richText)delete t.richText.attrs}}]});var xp={w:Rt,h:Rt,time:Oe,playing:He,autoplay:He,url:Us,assetId:Wi.nullable(),altText:Ne},Gl=pt("video",{AddUrlProp:1,MakeUrlsValid:2,AddAltText:3,AddAutoplay:4}),_p=ut({sequence:[{id:Gl.AddUrlProp,up:(t)=>{t.url=""},down:"retired"},{id:Gl.MakeUrlsValid,up:(t)=>{if(!Us.isValid(t.url))t.url=""},down:(t)=>{}},{id:Gl.AddAltText,up:(t)=>{t.altText=""},down:(t)=>{delete t.altText}},{id:Gl.AddAutoplay,up:(t)=>{t.autoplay=!0},down:(t)=>{delete t.autoplay}}]});var cc=Be("com.tldraw.store",{RemoveCodeAndIconShapeTypes:1,AddInstancePresenceType:2,RemoveTLUserAndPresenceAndAddPointer:3,RemoveUserDocument:4,FixIndexKeys:5}),Tw=dn({sequenceId:"com.tldraw.store",retroactive:!1,sequence:[{id:cc.RemoveCodeAndIconShapeTypes,scope:"storage",up:(t)=>{for(let[n,i]of t.entries())if(i.typeName==="shape"&&"type"in i&&(i.type==="icon"||i.type==="code"))t.delete(n)}},{id:cc.AddInstancePresenceType,scope:"storage",up(t){}},{id:cc.RemoveTLUserAndPresenceAndAddPointer,scope:"storage",up:(t)=>{for(let[n,i]of t.entries())if(i.typeName.match(/^(user|user_presence)$/))t.delete(n)}},{id:cc.RemoveUserDocument,scope:"storage",up:(t)=>{for(let[n,i]of t.entries())if(i.typeName.match("user_document"))t.delete(n)}},{id:cc.FixIndexKeys,scope:"record",up:(t)=>{if(["shape","page"].includes(t.typeName)&&"index"in t){let n=t;if(n.index.endsWith("0")&&n.index!=="a0")n.index=n.index.slice(0,-1)+Iw(3);if(t.typeName==="shape"&&n.type==="line"){let i=n;for(let[o,a]of Pn(i.props.points))if(a.index.endsWith("0")&&a.index!=="a0")a.index=a.index.slice(0,-1)+Iw(3)}}},down:()=>{}}]}),_w="123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",O1=()=>_w.charAt(Math.floor(Math.random()*_w.length)),Iw=(t)=>Array.from({length:t},O1).join("");function Rw(t){if(t.typeName==="asset"){if("src"in t)t.src="<redacted>";if("src"in t.props)t.props.src="<redacted>"}}function Pw({error:t,phase:n,record:i,recordBefore:o}){throw Yd(t,{tags:{origin:"store.validateRecord",storePhase:n,isExistingValidationIssue:n==="initialize"},extras:{recordBefore:o?Rw(tn(o)):void 0,recordAfter:Rw(tn(i))}}),t}function k1(){return[Qa.create({id:"page:page",name:"Page 1",index:"a1",meta:{}})]}function Cw(t){let n=t.query.ids("page"),i=t.query.records("instance_page_state"),o=()=>{if(!t.has(Bl))return t.put([fa.create({id:Bl,name:t.props.defaultName})]),o();if(!t.has(rc))return t.put([ua.create({id:rc})]),o();let a=n.get();if(a.size===0)return t.put(k1()),o();let c=()=>[...a].map((T)=>t.get(T)).sort(So)[0].id,m=t.get(ec);if(!m)return t.put([t.schema.types.instance.create({id:ec,currentPageId:c(),exportBackground:!0})]),o();else if(!a.has(m.currentPageId))return t.put([{...m,currentPageId:c()}]),o();let E=new Set,_=new Set;for(let T of a){let R=Vi.createId(T);if(!t.get(R))E.add(R);let M=Ro.createId(T);if(!t.has(M))_.add(M)}if(E.size>0)t.put([...E].map((T)=>Vi.create({id:T,pageId:Vi.parseId(T)})));if(_.size>0)t.put([..._].map((T)=>Ro.create({id:T})));let I=i.get();for(let T of I){if(!a.has(T.pageId)){t.remove([T.id]);continue}if(T.croppingShapeId&&!t.has(T.croppingShapeId))return t.put([{...T,croppingShapeId:null}]),o();if(T.focusedGroupId&&!t.has(T.focusedGroupId))return t.put([{...T,focusedGroupId:null}]),o();if(T.hoveredShapeId&&!t.has(T.hoveredShapeId))return t.put([{...T,hoveredShapeId:null}]),o();let R=T.selectedShapeIds.filter((N)=>t.has(N));if(R.length!==T.selectedShapeIds.length)return t.put([{...T,selectedShapeIds:R}]),o();let P=T.hintingShapeIds.filter((N)=>t.has(N));if(P.length!==T.hintingShapeIds.length)return t.put([{...T,hintingShapeIds:P}]),o();let M=T.erasingShapeIds.filter((N)=>t.has(N));if(M.length!==T.erasingShapeIds.length)return t.put([{...T,erasingShapeIds:M}]),o()}};return o}var Ow={arrow:{migrations:Hf,props:Wf},bookmark:{migrations:ep,props:Qf},draw:{migrations:sp,props:np},embed:{migrations:op,props:ip},frame:{migrations:cp,props:ap},geo:{migrations:up,props:lp},group:{migrations:fp,props:dp},highlight:{migrations:hp,props:pp},image:{migrations:gp,props:mp},line:{migrations:wp,props:yp},note:{migrations:bp,props:Sp},text:{migrations:Ap,props:Ep},video:{migrations:_p,props:xp}},kw={arrow:{migrations:zf,props:Vf}},Mw={image:{migrations:Mf,props:Dl},video:{migrations:Nf,props:Ll},bookmark:{migrations:kf,props:$l}};function Ip({shapes:t=Ow,bindings:n=kw,assets:i=Mw,user:o,records:a={},migrations:c}={}){let m=new Map;for(let N of Lt(t))for(let H of qf(N.props??{}).keys()){if(m.has(H.id)&&m.get(H.id)!==H)throw Error(`Multiple StyleProp instances with the same id: ${H.id}`);m.set(H.id,H)}let E=Gy(t),_=zy(n),I=Xf(i),T=cw(m),R=o?Fl(o):Jf,P=new Set(["asset","binding","camera","document","instance","instance_page_state","page","instance_presence","pointer","shape","store","user"]),M={};for(let[N,H]of Object.entries(a)){if(P.has(N))throw Error(`Custom record type name '${N}' conflicts with tldraw's built-in record type of that name. Choose a different name instead.`);M[N]=pw(N,H)}return Ga.create({asset:I,binding:_,camera:Ro,document:fa,instance:T,instance_page_state:Vi,page:Qa,instance_presence:ql,pointer:ua,shape:E,user:R,...M},{migrations:[Tw,Yf,tw,gw,lw,uw,ow,fw,dw,Ff,aw,...Ul("asset",i),...Ul("shape",t),...Ul("binding",n),...hw(a),...o?.migrations??[],...c??[]],onValidationFailure:Pw,createIntegrityChecker:Cw})}Tn("@tldraw/tlschema","5.2.3","esm");function N1(t){if(!t||typeof t!=="object")return null;let n=t.sequences;if(!n||typeof n!=="object")return null;let i={};for(let[o,a]of Object.entries(n))if(typeof a==="number")i[o]=a;return Object.keys(i).length>0?i:null}function Nw(t,n){let i=N1(t);if(!i)return[];let o=[];for(let[a,c]of Object.entries(i)){let m=n[a];if(m===void 0)o.push({id:a,fileVersion:c});else if(c>m)o.push({id:a,fileVersion:c,runtimeVersion:m})}return o}function $w(t,n){if(t)return`Moi ${t.moi}, tldraw ${t.tldraw}`;return n.map((i)=>i.runtimeVersion===void 0?`${i.id} v${i.fileVersion} (unknown here)`:`${i.id} v${i.fileVersion} > v${i.runtimeVersion}`).join(", ")}var Dw={geo:{w:100,h:100,geo:"rectangle",dash:"draw",growY:0,url:"",scale:1,color:"black",labelColor:"black",fill:"none",size:"m",font:"draw",align:"middle",verticalAlign:"middle",richText:Wt("")},text:{color:"black",size:"m",w:8,font:"draw",textAlign:"start",autoSize:!0,scale:1,richText:Wt("")},note:{color:"black",richText:Wt(""),size:"m",font:"draw",align:"middle",verticalAlign:"middle",labelColor:"black",growY:0,fontSizeAdjustment:1,url:"",scale:1,textLastEditedBy:null},arrow:{kind:"arc",elbowMidPoint:0.5,dash:"draw",size:"m",fill:"none",color:"black",labelColor:"black",bend:0,start:{x:0,y:0},end:{x:2,y:0},arrowheadStart:"none",arrowheadEnd:"arrow",richText:Wt(""),labelPosition:0.5,font:"draw",scale:1},image:{w:100,h:100,assetId:null,playing:!0,url:"",crop:null,flipX:!1,flipY:!1,altText:""}};var L1=(t)=>()=>{throw Error(`${t} is not available on the server-side scratchpad store`)},j1={defaultName:"",assets:{upload:L1("Asset upload"),resolve:()=>null,remove:async()=>{}},users:{currentUser:null,resolve:()=>null},onMount:()=>{}};function lc(t){let n=Dw[t];if(!n)throw Error(`Unknown shape type "${t}"`);return{...n}}function Kl(t){return{...t.color?{color:t.color}:{},...t.size?{size:t.size}:{},...t.fill?{fill:t.fill}:{}}}function U1(t){let n=console.error,i=[];console.error=(...o)=>{i.push(o)};try{t()}finally{console.error=n}for(let o of i)n(...o)}function F1(t,n){let i=new Ol({schema:Ip(),props:j1}),o=t?.store?t:{store:{},schema:i.schema.serialize()};try{U1(()=>i.loadStoreSnapshot(o))}catch(a){let c=Nw(t?.schema,i.schema.serialize().sequences);if(c.length>0)throw Error(`Scratchpad was written by a newer Moi (${$w(n,c)}); this server has tldraw ${pn.tldraw}. Restart the newer server or update this install (bun install -g moi-computer@latest). `+"The canvas file is intact \u2014 do not reset it.");throw Error("Scratchpad snapshot failed to load (not a version mismatch \u2014 the file may be "+`corrupted): ${a instanceof Error?a.message:String(a)}`)}return i}function Uw(t){for(let n of t.allRecords())if(n.typeName==="page")return n.id;throw Error("Scratchpad has no page")}function uc(t,n){let i=ef;for(let o of t.allRecords())if(o.typeName==="shape"&&o.parentId===n&&o.index>i)i=o.index;return rf(i)}function dc(t){return{typeName:"shape",rotation:0,isLocked:!1,opacity:1,meta:{},...t}}function Lw(t,n,i){return{id:aa(),typeName:"binding",type:"arrow",fromId:t,toId:n,meta:{},props:{terminal:i,normalizedAnchor:{x:0.5,y:0.5},isPrecise:!1,isExact:!1,snap:"none"}}}var q1={lo:{dim:768,quality:78},hi:{dim:2048,quality:88}},B1=52428800;async function W1(t,n,i){let o=Bun.file(t);if(!i&&!await o.exists())throw Error(`Image file not found: ${t}`);let a=i??new Uint8Array(await o.arrayBuffer());if(a.length===0)throw Error(`Image file is empty: ${t}`);if(a.length>B1)throw Error(`Image is too large (${Math.round(a.length/1e6)}MB, max 50MB): ${t}`);let c=q1[n],{data:m,info:E}=await D1(a).rotate().resize(c.dim,c.dim,{fit:"inside",withoutEnlargement:!0}).webp({quality:c.quality}).toBuffer({resolveWithObject:!0});return{data:m,w:E.width,h:E.height,mimeType:"image/webp",name:$1(t)}}async function H1(t,n,i,o){let a=Uw(t),c=t.get(mn(i.name)),m=typeof c?.props?.assetId==="string"?c.props.assetId:void 0,{data:E,w:_,h:I,mimeType:T,name:R}=await W1(i.path,i.quality??"lo",o),{src:P}=await Tt(n,E,T),M=Zf.createId();if(t.put([{id:M,typeName:"asset",type:"image",meta:{},props:{name:R,src:P,w:_,h:I,mimeType:T,isAnimated:!1}}]),t.put([dc({id:mn(i.name),type:"image",x:i.x,y:i.y,index:uc(t,a),parentId:a,props:{...lc("image"),w:_,h:I,assetId:M}})]),m&&m!==M&&!Fw(t,m))t.remove([m]);return{name:i.name}}function V1(t,n){let i=Uw(t),o=(a)=>{let c=t.get(mn(a));if(!c||c.typeName!=="shape")throw Error(`No shape named "${a}"`);return c};switch(n.kind){case"add-rect":return t.put([dc({id:mn(n.name),type:"geo",x:n.x,y:n.y,index:uc(t,i),parentId:i,props:{...lc("geo"),geo:"rectangle",w:n.w,h:n.h,...Kl(n),...n.text?{richText:Wt(n.text)}:{}}})]),{name:n.name};case"add-text":return t.put([dc({id:mn(n.name),type:"text",x:n.x,y:n.y,index:uc(t,i),parentId:i,props:{...lc("text"),richText:Wt(n.text),...Kl(n)}})]),{name:n.name};case"add-note":return t.put([dc({id:mn(n.name),type:"note",x:n.x,y:n.y,index:uc(t,i),parentId:i,props:{...lc("note"),richText:Wt(n.text),...Kl(n)}})]),{name:n.name};case"add-arrow":{if("name"in n.from)o(n.from.name);if("name"in n.to)o(n.to.name);let a=mn(n.name);t.put([dc({id:a,type:"arrow",x:0,y:0,index:uc(t,i),parentId:i,props:{...lc("arrow"),...Kl(n),...n.elbow?{kind:"elbow"}:{},start:"name"in n.from?{x:0,y:0}:{x:n.from.x,y:n.from.y},end:"name"in n.to?{x:100,y:0}:{x:n.to.x,y:n.to.y}}})]);let c=[];if("name"in n.from)c.push(Lw(a,mn(n.from.name),"start"));if("name"in n.to)c.push(Lw(a,mn(n.to.name),"end"));if(c.length>0)t.put(c);return{name:n.name}}case"move":{let a=o(n.name);return t.put([{...a,x:n.x,y:n.y}]),{ok:!0}}case"set":{let a=o(n.name);return t.put([{...a,props:{...a.props,richText:Wt(n.text)}}]),{ok:!0}}case"delete":{let a=mn(n.name),c=t.get(a),m=typeof c?.props?.assetId==="string"?c.props.assetId:void 0,E=[a,...z1(t,n.name)];if(t.remove(E),m&&!Fw(t,m))t.remove([m]);return{ok:!0}}case"clear":{let a=t.allRecords().filter((c)=>c.typeName==="shape"||c.typeName==="binding"||c.typeName==="asset").map((c)=>c.id);if(a.length>0)t.remove(a);return{ok:!0}}default:throw Error(`Cannot execute op "${n.kind}" on the server`)}}function Fw(t,n){for(let i of t.allRecords()){if(i.typeName!=="shape")continue;if(i.props?.assetId===n)return!0}return!1}function z1(t,n){let i=mn(n),o=[];for(let a of t.allRecords()){if(a.typeName!=="binding")continue;let c=a;if(c.fromId===i||c.toId===i)o.push(a.id)}return o}var jw=new Map;function G1(t,n){let o=(jw.get(t)??Promise.resolve()).catch(()=>{}).then(n);return jw.set(t,o.catch(()=>{})),o}function Jl(t,n,i,o){return G1(t,async()=>{let{document:a,writer:c}=await at(t),m=F1(a,c),E=i.kind==="add-image"?await H1(m,t,i,o):V1(m,i),_=m.getStoreSnapshot();return await sr(_,t),h({type:"scratchpad:changed",workspaceId:n}),E})}var Tp=(t,n,i)=>(o,a)=>{let c=-1;return m(0);async function m(E){if(E<=c)throw Error("next() called multiple times");c=E;let _,I=!1,T;if(t[E])T=t[E][0][0],o.req.routeIndex=E;else T=E===t.length&&a||void 0;if(T)try{_=await T(o,()=>m(E+1))}catch(R){if(R instanceof Error&&n)o.error=R,_=await n(R,o),I=!0;else throw R}else if(o.finalized===!1&&i)_=await i(o);if(_&&(o.finalized===!1||I))o.res=_;return o}};var qw=Symbol();var Bw=(t,n)=>new Response(t,{headers:{"Content-Type":n.replace(/^[^;]+/,(o)=>o.toLowerCase())}}).formData();var Ww=32,K1=1e4,Yl=(t)=>("headers"in t),zw=async(t,n=Object.create(null))=>{let{all:i=!1,dot:o=!1}=n,m=(Yl(t)?t.headers:t.raw.headers).get("Content-Type")?.split(";")[0].trim().toLowerCase();if(m==="multipart/form-data"||m==="application/x-www-form-urlencoded")return J1(t,{all:i,dot:o});return{}};async function J1(t,n){if(!Yl(t)&&t.bodyCache.formData)return Hw(await t.bodyCache.formData,n);let i=Yl(t)?t.headers:t.raw.headers,o=await t.arrayBuffer(),a=Bw(o,i.get("Content-Type")||"");if(!Yl(t))t.bodyCache.formData=a;let c=await a;if(c)return Hw(c,n);return{}}function Hw(t,n){let i=Object.create(null),o={count:0};if(t.forEach((a,c)=>{if(!(n.all||c.endsWith("[]")))i[c]=a;else Y1(i,c,a)}),n.dot)Object.entries(i).forEach(([a,c])=>{if(a.includes("."))X1(i,a,c,o),delete i[a]});return i}var Y1=(t,n,i)=>{if(t[n]!==void 0)if(Array.isArray(t[n]))t[n].push(i);else t[n]=[t[n],i];else if(!n.endsWith("[]"))t[n]=i;else t[n]=[i]},X1=(t,n,i,o)=>{if(/(?:^|\.)__proto__\./.test(n))return;let a=t,c=n.split(".",Ww+2);if(c.length>Ww+1)Vw();c.forEach((m,E)=>{if(E===c.length-1)a[m]=i;else{if(!a[m]||typeof a[m]!=="object"||Array.isArray(a[m])||a[m]instanceof File){if(o.count++>=K1)Vw();a[m]=Object.create(null)}a=a[m]}})},Vw=()=>{throw Error("Nesting limit exceeded")};var Pp=(t)=>{let n=t.split("/");if(n[0]==="")n.shift();return n},Gw=(t)=>{let{groups:n,path:i}=Z1(t),o=Pp(i);return Q1(o,n)},Z1=(t)=>{let n=[];return t=t.replace(/\{[^}]+\}/g,(i,o)=>{let a=`@${o}`;return n.push([a,i]),a}),{groups:n,path:t}},Q1=(t,n)=>{for(let i=n.length-1;i>=0;i--){let[o]=n[i];for(let a=t.length-1;a>=0;a--)if(t[a].includes(o)){t[a]=t[a].replace(o,n[i][1]);break}}return t},Xl={},Kw=(t,n)=>{if(t==="*")return"*";let i=t.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);if(i){let o=`${t}#${n}`;if(!Xl[o])if(i[2])Xl[o]=n&&n[0]!==":"&&n[0]!=="*"?[o,i[1],new RegExp(`^${i[2]}(?=/${n})`)]:[t,i[1],new RegExp(`^${i[2]}$`)];else Xl[o]=[t,i[1],!0];return Xl[o]}return null},Jw=(t,n)=>{try{return n(t)}catch{return t.replace(/(?:%[0-9A-Fa-f]{2})+/g,(i)=>{try{return n(i)}catch{return i}})}},Cp=(t)=>Jw(t,decodeURI),Op=(t)=>{let n=t.url,i=n.indexOf("/",n.indexOf(":")+4),o=i;for(;o<n.length;o++){let a=n.charCodeAt(o);if(a===37){let c=n.indexOf("?",o),m=n.indexOf("#",o),E=c===-1?m===-1?void 0:m:m===-1?c:Math.min(c,m),_=n.slice(i,E);return Cp(_.includes("%25")?_.replace(/%25/g,"%2525"):_)}else if(a===63||a===35)break}return n.slice(i,o)};var Yw=(t)=>{let n=Op(t);return n.length>1&&n.at(-1)==="/"?n.slice(0,-1):n},eo=(t,n,...i)=>{if(i.length)n=eo(n,...i);return`${t?.[0]==="/"?"":"/"}${t}${n==="/"?"":`${t?.at(-1)==="/"?"":"/"}${n?.[0]==="/"?n.slice(1):n}`}`},Zl=(t)=>{if(t.charCodeAt(t.length-1)!==63||!t.includes(":"))return null;let n=t.split("/"),i=[],o="";return n.forEach((a)=>{if(a!==""&&!/\:/.test(a))o+="/"+a;else if(/\:/.test(a))if(a.charCodeAt(a.length-1)===63){if(i.length===0&&o==="")i.push("/");else i.push(o);let c=a.slice(0,-1);o+="/"+c,i.push(o)}else o+="/"+a}),i.filter((a,c,m)=>m.indexOf(a)===c)},Ql=(t)=>t.indexOf("%")!==-1?Jw(t,eP):t,Rp=(t)=>{if(t.indexOf("+")!==-1)t=t.replace(/\+/g," ");return Ql(t)},Xw=(t,n,i)=>{let o=t.indexOf("#",8);if(o!==-1)t=t.slice(0,o);let a;if(!i&&n&&n.indexOf("%")===-1&&n.indexOf("+")===-1){let E=t.indexOf("?",8);if(E===-1)return;if(!t.startsWith(n,E+1))E=t.indexOf(`&${n}`,E+1);while(E!==-1){let _=t.charCodeAt(E+n.length+1);if(_===61){let I=E+n.length+2,T=t.indexOf("&",I);return Rp(t.slice(I,T===-1?void 0:T))}else if(_==38||isNaN(_))return"";E=t.indexOf(`&${n}`,E+1)}if(a=/[%+]/.test(t),!a)return}let c=Object.create(null);a??=/[%+]/.test(t);let m=t.indexOf("?",8);while(m!==-1){let E=t.indexOf("&",m+1),_=t.indexOf("=",m);if(_>E&&E!==-1)_=-1;let I=t.slice(m+1,_===-1?E===-1?void 0:E:_);if(a)I=Rp(I);if(m=E,I==="")continue;let T;if(_===-1)T="";else if(T=t.slice(_+1,E===-1?void 0:E),a)T=Rp(T);if(i){if(!(c[I]&&Array.isArray(c[I])))c[I]=[];c[I].push(T)}else c[I]??=T}return n?c[n]:c},Zw=Xw,Qw=(t,n)=>Xw(t,n,!0),eP=decodeURIComponent;var eS=class{raw;#t;#e;routeIndex=0;path;bodyCache={};constructor(t,n="/",i=[[]]){this.raw=t,this.path=n,this.#e=i}param(t){return t?this.#r(t):this.#o()}#r(t){let n=this.#e[0][this.routeIndex]?.[1][t],i=this.#n(n);return i&&Ql(i)}#o(){let t={},n=Object.keys(this.#e[0][this.routeIndex]?.[1]??{});for(let i of n){let o=this.#n(this.#e[0][this.routeIndex][1][i]);if(o!==void 0)t[i]=Ql(o)}return t}#n(t){return this.#e[1]?this.#e[1][t]:t}query(t){return Zw(this.url,t)}queries(t){return Qw(this.url,t)}header(t){if(t)return this.raw.headers.get(t)??void 0;let n=Object.create(null);return this.raw.headers.forEach((i,o)=>{n[o]=i}),n}async parseBody(t){return zw(this,t)}#i=(t)=>{let{bodyCache:n,raw:i}=this,o=n[t];if(o)return o;for(let a in n)return n[a].then((c)=>{if(a==="json")c=JSON.stringify(c);return new Response(c)[t]()});return n[t]=i[t]()};json(){return this.#i("text").then((t)=>JSON.parse(t))}text(){return this.#i("text")}arrayBuffer(){return this.#i("arrayBuffer")}bytes(){return this.#i("arrayBuffer").then((t)=>new Uint8Array(t))}blob(){return this.#i("blob")}formData(){return this.#i("formData")}addValidatedData(t,n){(this.#t??={})[t]=n}valid(t){return this.#t?.[t]}get url(){return this.raw.url}get method(){return this.raw.method}get[qw](){return this.#e}get matchedRoutes(){return this.#e[0].map(([[,t]])=>t)}get routePath(){return this.#e[0].map(([[,t]])=>t)[this.routeIndex].path}};var tS={Stringify:1,BeforeStream:2,Stream:3},rS=(t,n)=>{let i=new String(t);return i.isEscaped=!0,i.callbacks=n,i};var kp=async(t,n,i,o,a)=>{if(typeof t==="object"&&!(t instanceof String)){if(!(t instanceof Promise))t=t.toString();if(t instanceof Promise)t=await t}let c=t.callbacks;if(!c?.length)return Promise.resolve(t);if(a)a[0]+=t;else a=[t];let m=Promise.all(c.map((E)=>E({phase:n,buffer:a,context:o}))).then((E)=>Promise.all(E.filter(Boolean).map((_)=>kp(_,n,!1,o,a))).then(()=>a[0]));if(i)return rS(await m,c);else return m};var tP="text/plain; charset=UTF-8",Mp=(t,n)=>({"Content-Type":t,...n}),fc=(t,n)=>new Response(t,n),Np=class{#t;#e;env={};#r;finalized=!1;error;#o;#n;#i;#S;#f;#a;#p;#u;#c;constructor(t,n){if(this.#t=t,n)this.#n=n.executionCtx,this.env=n.env,this.#a=n.notFoundHandler,this.#c=n.path,this.#u=n.matchResult}get req(){return this.#e??=new eS(this.#t,this.#c,this.#u),this.#e}get event(){if(this.#n&&"respondWith"in this.#n)return this.#n;else throw Error("This context has no FetchEvent")}get executionCtx(){if(this.#n)return this.#n;else throw Error("This context has no ExecutionContext")}get res(){return this.#i||=fc(null,{headers:this.#p??=new Headers})}set res(t){if(this.#i&&t){t=fc(t.body,t);for(let[n,i]of this.#i.headers.entries()){if(n==="content-type")continue;if(n==="set-cookie"){let o=this.#i.headers.getSetCookie();t.headers.delete("set-cookie");for(let a of o)t.headers.append("set-cookie",a)}else t.headers.set(n,i)}}this.#i=t,this.finalized=!0}render=(...t)=>(this.#f??=(n)=>this.html(n),this.#f(...t));setLayout=(t)=>this.#S=t;getLayout=()=>this.#S;setRenderer=(t)=>{this.#f=t};header=(t,n,i)=>{if(this.finalized)this.#i=fc(this.#i.body,this.#i);let o=this.#i?this.#i.headers:this.#p??=new Headers;if(n===void 0)o.delete(t);else if(i?.append)o.append(t,n);else o.set(t,n)};status=(t)=>{this.#o=t};set=(t,n)=>{this.#r??=new Map,this.#r.set(t,n)};get=(t)=>this.#r?this.#r.get(t):void 0;get var(){if(!this.#r)return{};return Object.fromEntries(this.#r)}#s(t,n,i){let o=this.#i?new Headers(this.#i.headers):this.#p;if(typeof n==="object"&&n.headers){o??=new Headers;for(let[c,m]of new Headers(n.headers))if(c==="set-cookie")o.append(c,m);else o.set(c,m)}if(i){if(!o){let c=0;for(let m in i)if(++c>1||typeof i[m]!=="string"){o=new Headers;break}}if(o)for(let c in i){let m=i[c];if(typeof m==="string")o.set(c,m);else{o.delete(c);for(let E of m)o.append(c,E)}}}let a=typeof n==="number"?n:n?.status??this.#o;return fc(t,{status:a,headers:o??i})}newResponse=(...t)=>this.#s(...t);body=(t,n,i)=>this.#s(t,n,i);text=(t,n,i)=>!this.#p&&!this.#o&&!n&&!i&&!this.finalized?new Response(t):this.#s(t,n,Mp(tP,i));json=(t,n,i)=>this.#s(JSON.stringify(t),n,Mp("application/json",i));html=(t,n,i)=>{let o=(a)=>this.#s(a,n,Mp("text/html; charset=UTF-8",i));return typeof t==="object"?kp(t,tS.Stringify,!1,{}).then(o):o(t)};redirect=(t,n)=>{let i=String(t);return this.header("Location",!/[^\x00-\xFF]/.test(i)?i:encodeURI(i)),this.newResponse(null,n??302)};notFound=()=>(this.#a??=()=>fc(),this.#a(this))};var tr="ALL",nS="all",sS=["get","post","put","delete","options","patch","query"],eu="Can not add a route since the matcher is already built.",tu=class extends Error{};var $p="__COMPOSED_HANDLER";var rP=(t)=>t.text("404 Not Found",404),iS=(t,n)=>{if("getResponse"in t){let i=t.getResponse();return n.newResponse(i.body,i)}return console.error(t),n.text("Internal Server Error",500)},oS=class t{get;post;put;delete;options;patch;query;all;on;use;router;getPath;_basePath="/";#t="/";routes=[];constructor(n={}){[...sS,nS].forEach((c)=>{this[c]=(m,...E)=>{let _=c.toUpperCase();if(typeof m==="string")this.#t=m;else this.#o(_,this.#t,m);return E.forEach((I)=>{this.#o(_,this.#t,I)}),this}}),this.on=(c,m,...E)=>{for(let _ of[m].flat()){this.#t=_;for(let I of[c].flat()){let T=I.toUpperCase();for(let R of E)this.#o(T,this.#t,R)}}return this},this.use=(c,...m)=>{if(typeof c==="string")this.#t=c;else this.#t="*",m.unshift(c);return m.forEach((E)=>{this.#o(tr,this.#t,E)}),this};let{strict:o,...a}=n;Object.assign(this,a),this.getPath=o??!0?n.getPath??Op:Yw}#e(){let n=new t({router:this.router,getPath:this.getPath});return n.errorHandler=this.errorHandler,n.#r=this.#r,n.routes=this.routes,n}#r=rP;errorHandler=iS;route(n,i){let o=this.basePath(n);return i.routes.map((a)=>{let c;if(i.errorHandler===iS)c=a.handler;else c=async(m,E)=>(await Tp([],i.errorHandler)(m,()=>a.handler(m,E))).res,c[$p]=a.handler;o.#o(a.method,a.path,c,a.basePath)}),this}basePath(n){let i=this.#e();return i._basePath=eo(this._basePath,n),i}onError=(n)=>(this.errorHandler=n,this);notFound=(n)=>(this.#r=n,this);mount(n,i,o){let a,c;if(o)if(typeof o==="function")c=o;else if(c=o.optionHandler,o.replaceRequest===!1)a=(_)=>_;else a=o.replaceRequest;let m=c?(_)=>{let I=c(_);return Array.isArray(I)?I:[I]}:(_)=>{let I=void 0;try{I=_.executionCtx}catch{}return[_.env,I]};a||=(()=>{let _=eo(this._basePath,n),I=_==="/"?0:_.length;return(T)=>{let R=new URL(T.url);return R.pathname=this.getPath(T).slice(I)||"/",new Request(R,T)}})();let E=async(_,I)=>{let T=await i(a(_.req.raw),...m(_));if(T)return T;await I()};return this.#o(tr,eo(n,"*"),E),this}#o(n,i,o,a){i=eo(this._basePath,i);let c={basePath:a!==void 0?eo(this._basePath,a):this._basePath,path:i,method:n,handler:o};this.router.add(n,i,[o,c]),this.routes.push(c)}#n(n,i){if(n instanceof Error)return this.errorHandler(n,i);throw n}#i(n,i,o,a){if(a==="HEAD")return(async()=>new Response(null,await this.#i(n,i,o,"GET")))();let c=this.getPath(n,{env:o}),m=this.router.match(a,c),E=new Np(n,{path:c,matchResult:m,env:o,executionCtx:i,notFoundHandler:this.#r});if(m[0].length===1){let I;try{I=m[0][0][0][0](E,async()=>{E.res=await this.#r(E)})}catch(T){return this.#n(T,E)}return I instanceof Promise?I.then((T)=>T||(E.finalized?E.res:this.#r(E))).catch((T)=>this.#n(T,E)):I??this.#r(E)}let _=Tp(m[0],this.errorHandler,this.#r);return(async()=>{try{let I=await _(E);if(!I.finalized)throw Error("Context is not finalized. Did you forget to return a Response object or `await next()`?");return I.res}catch(I){return this.#n(I,E)}})()}fetch=(n,...i)=>this.#i(n,i[1],i[0],n.method);request=(n,i,o,a)=>{if(n instanceof Request)return this.fetch(i?new Request(n,i):n,o,a);return n=n.toString(),this.fetch(new Request(/^https?:\/\//.test(n)?n:`http://localhost${eo("/",n)}`,i),o,a)};fire=()=>{addEventListener("fetch",(n)=>{n.respondWith(this.#i(n.request,n,void 0,n.request.method))})}};var rr=()=>Object.create(null);var ru=[];function Dp(t,n){let i=this.buildAllMatchers(),o=(a,c)=>{let m=i[a]||i[tr],E=m[2][c];if(E)return E;let _=c.match(m[0]);if(!_)return[[],ru];let I=_.indexOf("",1);return[m[1][I],_]};return this.match=o,o(t,n)}var pa="[^/]+",ro=".*",fi="(?:|/.*)",to=Symbol(),aS=new Set(".\\+*[^]$()");function nP(t,n){if(t.length===1)return n.length===1?t<n?-1:1:-1;if(n.length===1)return 1;if(t===ro||t===fi)return n===fi?-1:1;else if(n===ro||n===fi)return-1;if(t===pa)return 1;else if(n===pa)return-1;return t.length===n.length?t<n?-1:1:n.length-t.length}var cS=class t{#t;#e;#r=rr();insert(n,i,o,a,c){let m=this;for(let E=0,_=n.length;E<_;E++){let I=n[E],T=I.length===1?I==="*"?E===_-1?["","",ro]:["","",pa]:null:I==="/*"?["","",fi]:I.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),R;if(T){let P=T[1],M=T[2]||pa;if(P&&T[2]){if(M===".*")throw to;if(M=M.replace(/^\((?!\?:)(?=[^)]+\)$)/,"(?:"),/\((?!\?:)/.test(M))throw to;if(M.length===1&&aS.has(M))throw to}if(R=m.#r[M],!R){if(M!==ro&&M!==fi){for(let N in m.#r)if((M.length>1||N.length>1)&&N!==ro&&N!==fi)throw to}R=m.#r[M]=new t}if(P!=="")R.#e??=a.varIndex++,o.push([P,R.#e])}else if(R=m.#r[I],!R){for(let P in m.#r)if(P.length>1&&P!==ro&&P!==fi)throw to;R=m.#r[I]=new t}m=R}if(m.#t!==void 0)throw to;m.#t=c?-1:i}buildRegExpStr(){let i=Object.keys(this.#r).sort(nP).map((o)=>{let a=this.#r[o],c=a.buildRegExpStr();return c===""?"":(typeof a.#e==="number"?`(${o})@${a.#e}`:aS.has(o)?`\\${o}`:o)+c}).filter(Boolean);if(typeof this.#t==="number"&&this.#t!==-1)i.unshift(`#${this.#t}`);if(i.length===0)return"";if(i.length===1)return i[0];return"(?:"+i.join("|")+")"}};var Lp=class{#t={varIndex:0};#e=new cS;#r=0;paths=rr();insert(t,n){if(n){this.#e.insert(t.split(""),0,[],this.#t,!0);return}let i=[],o=[],a=t;for(let m=0;;){let E=!1;if(a=a.replace(/\{[^}]+\}/g,(_)=>{let I=`@\\${m}`;return o[m]=[I,_],m++,E=!0,I}),!E)break}let c=a.match(/(?::[^\/]+)|(?:\/\*$)|./g)||[];for(let m=o.length-1;m>=0;m--){let[E]=o[m];for(let _=c.length-1;_>=0;_--)if(c[_].indexOf(E)!==-1){c[_]=c[_].replace(E,o[m][1]);break}}this.#e.insert(c,this.#r,i,this.#t,!1),this.paths[t]=[this.#r++,i]}buildRegExp(){let t=this.#e.buildRegExpStr();if(t==="")return[/^$/,[],[]];let n=0,i=[],o=[];return t=t.replace(/#(\d+)|@(\d+)|\.\*\$/g,(a,c,m)=>{if(c!==void 0)return i[++n]=Number(c),"$()";if(m!==void 0)return o[Number(m)]=++n,"";return""}),[new RegExp(`^${t}`),i,o]}};var lS=rr();function uS(t){return lS[t]??=new RegExp(`^${t.replace(/\/:[^/{}]+(?:\{\[\^\/]\+})?(?=[/{]|$)|\/?\*$|([.\\+*[^\]$()?{}|])/g,(n,i)=>i?`\\${i}`:n==="/*"?fi:n==="*"?ro:`/:${pa}`)}$`)}function nu(t,n){for(let i of Object.keys(t).sort((o,a)=>a.length-o.length))if(uS(i).test(n))return[...t[i]];return}var su=class{name="RegExpRouter";#t;#e;#r;constructor(){this.#t={[tr]:rr()},this.#e={[tr]:rr()},this.#r={[tr]:new Lp}}#o(t,n){try{this.#r[t].insert(n,!/\*|\/:/.test(n))}catch(i){throw i===to?new tu(n):i}}add(t,n,i){let o=this.#t,a=this.#e;if(!o)throw Error(eu);if(!o[t]){this.#r[t]=new Lp;for(let E of[o,a]){E[t]=rr();for(let _ in E[tr])E[t][_]=[...E[tr][_]],this.#o(t,_)}}if(n==="/*")n="*";let c=t===tr?Object.keys(o):[t];if(/\*$/.test(n)){let E=uS(n);for(let _ of c)if(!o[_][n])this.#o(_,n),o[_][n]=nu(o[_],n)||nu(o[tr],n)||[];for(let _ of[o,a])for(let I of c)for(let T in _[I])E.test(T)&&_[I][T].push([i,n]);return}let m=Zl(n)||[n];for(let E of m)for(let _ of c){if(!a[_][E])this.#o(_,E),a[_][E]=nu(o[_],E)||nu(o[tr],E)||[];a[_][E].push([i,E])}}match=Dp;buildAllMatchers(){let t=rr();for(let n of Object.keys(this.#e))t[n]=this.#n(n);return this.#t=this.#e=this.#r=void 0,lS=rr(),t}#n(t){let n=this.#t[t],i=this.#e[t],o=this.#r[t],a=rr(),c=[],[m,E,_]=o.buildRegExp();for(let I of[n,i])for(let T in I){let R=I[T],P=o.paths[T];if(!P){a[T]=[R.map(([M])=>[M,rr()]),ru];continue}c[P[0]]=R.map(([M,N])=>[M,o.paths[N][1].reduceRight((H,[Z],V)=>(H[Z]=_[P[1][V][1]],H),rr())])}return[m,E.map((I)=>c[I]),a]}};var jp=class{name="SmartRouter";#t=[];#e=[];constructor(t){this.#t=t.routers}add(t,n,i){if(!this.#e)throw Error(eu);this.#e.push([t,n,i])}match(t,n){if(!this.#e)throw Error("Fatal error");let i=this.#t,o=this.#e,a=i.length,c=0,m;for(;c<a;c++){let E=i[c];try{for(let _=0,I=o.length;_<I;_++)E.add(...o[_]);m=E.match(t,n)}catch(_){if(_ instanceof tu)continue;throw _}this.match=E.match.bind(E),this.#t=[E],this.#e=void 0;break}if(c===a)throw Error("Fatal error");return this.name=`SmartRouter + ${this.activeRouter.name}`,m}get activeRouter(){if(this.#e||this.#t.length!==1)throw Error("No active router has been determined yet.");return this.#t[0]}};var Up=rr(),sP=0,dS=class t{#t=[];#e=rr();#r=[];#o;#n=Up;insert(n,i,o){let a=this,c=Gw(i),m=new Set,E=0;for(let _ of c){let I=c[++E],T=Kw(_,I)||(I===void 0&&_&&_.indexOf("*")===_.length-1?_:null),R=Array.isArray(T),P=R?T[0]:T||_,M=a.#e[P]||=new t;if(T&&!M.#o)M.#o=T,a.#r.push(M);if(a=M,R)m.add(T[1])}a.#t.push({[n]:{handler:o,possibleKeys:[...m],score:++sP}})}#i(n,i,o,a,c){for(let m=0,E=i.#t.length;m<E;m++){let _=i.#t[m],I=_[o]||_[tr];if(I){I.params=rr(),n.push(I);for(let T=0,R=I.possibleKeys.length;T<R;T++){let P=I.possibleKeys[T];I.params[P]=c?.[P]&&!T?c[P]:a[P]??c?.[P]}}}}search(n,i){let o=[];this.#n=Up;let c=[this],m=Pp(i),E=[],_=m.length,I=null;for(let T=0;T<_;T++){let R=m[T],P=T===_-1,M=[];for(let H=0,Z=c.length;H<Z;H++){let V=c[H],me=V.#e[R];if(me)if(me.#n=V.#n,P){if(me.#e["*"])this.#i(o,me.#e["*"],n,V.#n);this.#i(o,me,n,V.#n)}else M.push(me);for(let te of V.#r){let we=te.#o,Te=V.#n===Up?{}:{...V.#n};if(typeof we==="string"){if(we==="*"||R.startsWith(we.slice(0,-1))){if(this.#i(o,te,n,V.#n),we==="*")te.#n=Te,M.push(te)}continue}let[,$e,Ue]=we;if(!R&&Ue===!0)continue;if(Ue!==!0){if(!I){I=[];let yi=i[0]==="/"?1:0;for(let Qr=0;Qr<_;Qr++)I[Qr]=yi,yi+=m[Qr].length+1}let Ct=i.slice(I[T]),Ot=Ue.exec(Ct);if(Ot){if(Te[$e]=Ot[0],this.#i(o,te,n,V.#n,Te),Ot[0].length===Ct.length&&te.#e["*"])this.#i(o,te.#e["*"],n,V.#n,Te);for(let yi in te.#e){te.#n=Te;let Qr=Ot[0].match(/\//g)?.length??0;(E[Qr]||=[]).push(te);break}continue}}if(Ue===!0||Ue.test(R))if(Te[$e]=R,P){if(this.#i(o,te,n,Te,V.#n),te.#e["*"])this.#i(o,te.#e["*"],n,Te,V.#n)}else te.#n=Te,M.push(te)}}let N=E.shift();c=N?M.concat(N):M}if(o[1])o.sort((T,R)=>T.score-R.score);return[o.map(({handler:T,params:R})=>[T,R])]}};var Fp=class{name="TrieRouter";#t=new dS;add(t,n,i){for(let o of Zl(n)||[n])this.#t.insert(t,o,i)}match(t,n){return this.#t.search(t,n)}};var Bs=class extends oS{constructor(t={}){super(t);this.router=t.router??new jp({routers:[new su,new Fp]})}};import{isDeepStrictEqual as yv}from"util";import wh from"process";import pi from"fs";import $u from"path";import _c from"crypto";import wv from"assert";var Co=(t)=>{let n=typeof t;return t!==null&&(n==="object"||n==="function")},iu=new Set(["__proto__","prototype","constructor"]),iP=Math.max(...[...iu].map((t)=>t.length));var oP=(t)=>t>="0"&&t<="9";function fS(t){if(t==="0")return!0;if(/^[1-9]\d*$/.test(t)){let n=Number.parseInt(t,10);return n<=Number.MAX_SAFE_INTEGER&&n<=1e6}return!1}function qp(t,n){if(iu.has(t))return!1;if(t&&fS(t))n.push(Number.parseInt(t,10));else n.push(t);return!0}function aP(t){if(typeof t!=="string")throw TypeError(`Expected a string, got ${typeof t}`);let n=[],i="",o="",a=!1,c="start",m=!1,E=0;for(let _ of t){if(E++,m){i+=_,m=!1;continue}if(_==="\\"){if(c==="index")throw Error(`Invalid character '${_}' in an index at position ${E}`);if(c==="indexEnd")throw Error(`Invalid character '${_}' after an index at position ${E}`);m=!0,c=c==="start"?"property":c;continue}switch(_){case".":{if(c==="index")throw Error(`Invalid character '${_}' in an index at position ${E}`);if(c==="indexEnd"){c="property";break}if(!qp(i,n))return[];i="",c="property";break}case"[":{if(c==="index")throw Error(`Invalid character '${_}' in an index at position ${E}`);if(c==="indexEnd"){c="index";break}if(c==="property"&&i.length<=iP&&iu.has(i))return[];a=c==="property",c="index";break}case"]":{if(c==="indexEnd")throw Error(`Invalid character '${_}' after an index at position ${E}`);if(c!=="index"){if(c==="start")c="property";i+=_;break}if(o===""){i+="[]",c="property";break}if((i!==""||a)&&!qp(i,n))return[];i="",a=!1;let I=Number.parseInt(o,10),T=I<=1e6&&o===String(I);n.push(T?I:o),o="",c="indexEnd";break}default:{if(c==="index"){if(!oP(_))throw Error(`Invalid character '${_}' in an index at position ${E}`);o+=_;break}if(c==="indexEnd")throw Error(`Invalid character '${_}' after an index at position ${E}`);if(c==="start")c="property";i+=_}}}if(m)i+="\\";switch(c){case"property":{if(!qp(i,n))return[];break}case"index":throw Error("Index was not closed");case"start":{n.push("");break}}return n}function ou(t){if(typeof t==="string")return aP(t);if(Array.isArray(t)){let n=[];for(let[i,o]of t.entries()){if(typeof o!=="string"&&typeof o!=="number")throw TypeError(`Expected a string or number for path segment at index ${i}, got ${typeof o}`);if(typeof o==="number"&&!Number.isFinite(o))throw TypeError(`Path segment at index ${i} must be a finite number, got ${o}`);if(iu.has(o))return[];if(typeof o==="string"&&fS(o))n.push(Number.parseInt(o,10));else n.push(o)}return n}return[]}function Bp(t,n,i){if(!Co(t)||typeof n!=="string"&&!Array.isArray(n))return i===void 0?t:i;let o=ou(n);if(o.length===0)return i;for(let a=0;a<o.length;a++){let c=o[a];if(t=t[c],t===void 0||t===null){if(a!==o.length-1)return i;break}}return t===void 0?i:t}function pc(t,n,i){if(!Co(t)||typeof n!=="string"&&!Array.isArray(n))return t;let o=t,a=ou(n);if(a.length===0)return t;for(let c=0;c<a.length;c++){let m=a[c];if(c===a.length-1){t[m]=i;continue}let E=t[m];if(Co(E)){t=E;continue}let I=typeof a[c+1]==="number";t[m]=I?[]:{},t=t[m]}return o}function pS(t,n){if(!Co(t)||typeof n!=="string"&&!Array.isArray(n))return!1;let i=ou(n);if(i.length===0)return!1;for(let o=0;o<i.length;o++){let a=i[o];if(o===i.length-1){if(!Object.hasOwn(t,a))return!1;return delete t[a],!0}let c=t[a];if(!Co(c))return!1;t=c}}function au(t,n){if(!Co(t)||typeof n!=="string"&&!Array.isArray(n))return!1;let i=ou(n);if(i.length===0)return!1;for(let o of i){if(!Co(t)||!(o in t))return!1;t=t[o]}return!0}import vt from"path";import hS from"os";import Wp from"process";var no=hS.homedir(),Hp=hS.tmpdir(),{env:ha}=Wp,cP=(t)=>{let n=vt.join(no,"Library");return{data:vt.join(n,"Application Support",t),config:vt.join(n,"Preferences",t),cache:vt.join(n,"Caches",t),log:vt.join(n,"Logs",t),temp:vt.join(Hp,t)}},lP=(t)=>{let n=ha.APPDATA||vt.join(no,"AppData","Roaming"),i=ha.LOCALAPPDATA||vt.join(no,"AppData","Local");return{data:vt.join(i,t,"Data"),config:vt.join(n,t,"Config"),cache:vt.join(i,t,"Cache"),log:vt.join(i,t,"Log"),temp:vt.join(Hp,t)}},uP=(t)=>{let n=vt.basename(no);return{data:vt.join(ha.XDG_DATA_HOME||vt.join(no,".local","share"),t),config:vt.join(ha.XDG_CONFIG_HOME||vt.join(no,".config"),t),cache:vt.join(ha.XDG_CACHE_HOME||vt.join(no,".cache"),t),log:vt.join(ha.XDG_STATE_HOME||vt.join(no,".local","state"),t),temp:vt.join(Hp,n,t)}};function Vp(t,{suffix:n="nodejs"}={}){if(typeof t!=="string")throw TypeError(`Expected a string, got ${typeof t}`);if(n)t+=`-${n}`;if(Wp.platform==="darwin")return cP(t);if(Wp.platform==="win32")return lP(t);return uP(t)}import wP from"path";import qe from"fs";import{promisify as Er}from"util";var dP=(t,n)=>{let{onError:i}=n;return function(...a){return t.apply(void 0,a).catch(i)}},Ws=dP;var fP=(t,n)=>{let{onError:i}=n;return function(...a){try{return t.apply(void 0,a)}catch(c){return i(c)}}},vs=fP;var mS=250;var pP=(t,n)=>{let{isRetriable:i}=n;return function(a){let{timeout:c}=a,m=a.interval??mS,E=Date.now()+c;return function _(...I){return t.apply(void 0,I).catch((T)=>{if(!i(T))throw T;if(Date.now()>=E)throw T;let R=Math.round(m*Math.random());if(R>0)return new Promise((M)=>setTimeout(M,R)).then(()=>_.apply(void 0,I));else return _.apply(void 0,I)})}}},Hs=pP;var hP=(t,n)=>{let{isRetriable:i}=n;return function(a){let{timeout:c}=a,m=Date.now()+c;return function(..._){while(!0)try{return t.apply(void 0,_)}catch(I){if(!i(I))throw I;if(Date.now()>=m)throw I;continue}}}},Vs=hP;import yS from"process";var hc={isChangeErrorOk:(t)=>{if(!hc.isNodeError(t))return!1;let{code:n}=t;if(n==="ENOSYS")return!0;if(!gS&&(n==="EINVAL"||n==="EPERM"))return!0;return!1},isNodeError:(t)=>t instanceof Error,isRetriableError:(t)=>{if(!hc.isNodeError(t))return!1;let{code:n}=t;if(n==="EMFILE"||n==="ENFILE"||n==="EAGAIN"||n==="EBUSY"||n==="EACCESS"||n==="EACCES"||n==="EACCS"||n==="EPERM")return!0;return!1},onChangeError:(t)=>{if(!hc.isNodeError(t))throw t;if(hc.isChangeErrorOk(t))return;throw t}},zp=hc;var mc={onError:zp.onChangeError},on={onError:()=>{return}},gS=yS.getuid?!yS.getuid():!1,dr={isRetriable:zp.isRetriableError};var mP={attempt:{chmod:Ws(Er(qe.chmod),mc),chown:Ws(Er(qe.chown),mc),close:Ws(Er(qe.close),on),fsync:Ws(Er(qe.fsync),on),mkdir:Ws(Er(qe.mkdir),on),realpath:Ws(Er(qe.realpath),on),stat:Ws(Er(qe.stat),on),unlink:Ws(Er(qe.unlink),on),chmodSync:vs(qe.chmodSync,mc),chownSync:vs(qe.chownSync,mc),closeSync:vs(qe.closeSync,on),existsSync:vs(qe.existsSync,on),fsyncSync:vs(qe.fsync,on),mkdirSync:vs(qe.mkdirSync,on),realpathSync:vs(qe.realpathSync,on),statSync:vs(qe.statSync,on),unlinkSync:vs(qe.unlinkSync,on)},retry:{close:Hs(Er(qe.close),dr),fsync:Hs(Er(qe.fsync),dr),open:Hs(Er(qe.open),dr),readFile:Hs(Er(qe.readFile),dr),rename:Hs(Er(qe.rename),dr),stat:Hs(Er(qe.stat),dr),write:Hs(Er(qe.write),dr),writeFile:Hs(Er(qe.writeFile),dr),closeSync:Vs(qe.closeSync,dr),fsyncSync:Vs(qe.fsyncSync,dr),openSync:Vs(qe.openSync,dr),readFileSync:Vs(qe.readFileSync,dr),renameSync:Vs(qe.renameSync,dr),statSync:Vs(qe.statSync,dr),writeSync:Vs(qe.writeSync,dr),writeFileSync:Vs(qe.writeFileSync,dr)}},or=mP;import Oo from"process";var wS="utf8",Gp=438,SS=511;var bS={},vS=Oo.geteuid?Oo.geteuid():-1,ES=Oo.getegid?Oo.getegid():-1;var AS=1000,xS=!!Oo.getuid,nV=Oo.getuid?!Oo.getuid():!1,Kp=128;var _S=(t)=>t instanceof Error&&("code"in t);var Jp=(t)=>typeof t==="string",cu=(t)=>t===void 0;import yP from"path";import ma from"process";import IS from"process";var TS=IS.platform==="linux",lu=IS.platform==="win32";var Yp=["SIGHUP","SIGINT","SIGTERM"];if(!lu)Yp.push("SIGALRM","SIGABRT","SIGVTALRM","SIGXCPU","SIGXFSZ","SIGUSR2","SIGTRAP","SIGSYS","SIGQUIT","SIGIOT");if(TS)Yp.push("SIGIO","SIGPOLL","SIGPWR","SIGSTKFLT");var RS=Yp;class PS{constructor(){this.callbacks=new Set,this.exited=!1,this.exit=(t)=>{if(this.exited)return;this.exited=!0;for(let n of this.callbacks)n();if(t)if(lu&&(t!=="SIGINT"&&t!=="SIGTERM"&&t!=="SIGKILL"))ma.kill(ma.pid,"SIGTERM");else ma.kill(ma.pid,t)},this.hook=()=>{ma.once("exit",()=>this.exit());for(let t of RS)try{ma.once(t,()=>this.exit(t))}catch{}},this.register=(t)=>(this.callbacks.add(t),()=>{this.callbacks.delete(t)}),this.hook()}}var CS=new PS;var gP=CS.register,OS=gP;var Sn={store:{},create:(t)=>{let n=`000000${Math.floor(Math.random()*16777215).toString(16)}`.slice(-6),i=Date.now().toString().slice(-10),o="tmp-",a=`.tmp-${i}${n}`;return`${t}${a}`},get:(t,n,i=!0)=>{let o=Sn.truncate(n(t));if(o in Sn.store)return Sn.get(t,n,i);return Sn.store[o]=i,[o,()=>delete Sn.store[o]]},purge:(t)=>{if(!Sn.store[t])return;delete Sn.store[t],or.attempt.unlink(t)},purgeSync:(t)=>{if(!Sn.store[t])return;delete Sn.store[t],or.attempt.unlinkSync(t)},purgeSyncAll:()=>{for(let t in Sn.store)Sn.purgeSync(t)},truncate:(t)=>{let n=yP.basename(t);if(n.length<=Kp)return t;let i=/^(\.?)(.*?)((?:\.[^.]+)?(?:\.tmp-\d{10}[a-f0-9]{6})?)$/.exec(n);if(!i)return t;let o=n.length-Kp;return`${t.slice(0,-n.length)}${i[1]}${i[2].slice(0,-o)}${i[3]}`}};OS(Sn.purgeSyncAll);var gc=Sn;function Xp(t,n,i=bS){if(Jp(i))return Xp(t,n,{encoding:i});let a={timeout:i.timeout??AS},c=null,m=null,E=null;try{let _=or.attempt.realpathSync(t),I=!!_;t=_||t,[m,c]=gc.get(t,i.tmpCreate||gc.create,i.tmpPurge!==!1);let T=xS&&cu(i.chown),R=cu(i.mode);if(I&&(T||R)){let P=or.attempt.statSync(t);if(P){if(i={...i},T)i.chown={uid:P.uid,gid:P.gid};if(R)i.mode=P.mode}}if(!I){let P=wP.dirname(t);or.attempt.mkdirSync(P,{mode:SS,recursive:!0})}if(E=or.retry.openSync(a)(m,"w",i.mode||Gp),i.tmpCreated)i.tmpCreated(m);if(Jp(n))or.retry.writeSync(a)(E,n,0,i.encoding||wS);else if(!cu(n))or.retry.writeSync(a)(E,n,0,n.length,0);if(i.fsync!==!1)if(i.fsyncWait!==!1)or.retry.fsyncSync(a)(E);else or.attempt.fsync(E);if(or.retry.closeSync(a)(E),E=null,i.chown&&(i.chown.uid!==vS||i.chown.gid!==ES))or.attempt.chownSync(m,i.chown.uid,i.chown.gid);if(i.mode&&i.mode!==Gp)or.attempt.chmodSync(m,i.mode);try{or.retry.renameSync(a)(m,t)}catch(P){if(!_S(P))throw P;if(P.code!=="ENAMETOOLONG")throw P;or.retry.renameSync(a)(m,gc.truncate(t))}c(),m=null}finally{if(E)or.attempt.closeSync(E);if(m)gc.purge(m)}}var vv=g(Eb(),1),Ev=g(Mn(),1);var qC=(t,n,i,o)=>{if(i==="length"||i==="prototype")return;if(i==="arguments"||i==="caller")return;let a=Object.getOwnPropertyDescriptor(t,i),c=Object.getOwnPropertyDescriptor(n,i);if(!BC(a,c)&&o)return;Object.defineProperty(t,i,c)},BC=function(t,n){return t===void 0||t.configurable||t.writable===n.writable&&t.enumerable===n.enumerable&&t.configurable===n.configurable&&(t.writable||t.value===n.value)},WC=(t,n)=>{let i=Object.getPrototypeOf(n);if(i===Object.getPrototypeOf(t))return;Object.setPrototypeOf(t,i)},HC=(t,n)=>`/* Wrapped ${t}*/
|
|
62
|
-
${n}`,VC=Object.getOwnPropertyDescriptor(Function.prototype,"toString"),zC=Object.getOwnPropertyDescriptor(Function.prototype.toString,"name"),GC=(t,n,i)=>{let o=i===""?"":`with ${i.trim()}() `,a=HC.bind(null,o,n.toString());Object.defineProperty(a,"name",zC);let{writable:c,enumerable:m,configurable:E}=VC;Object.defineProperty(t,"toString",{value:a,writable:c,enumerable:m,configurable:E})};function rh(t,n,{ignoreNonConfigurable:i=!1}={}){let{name:o}=t;for(let a of Reflect.ownKeys(n))qC(t,n,a,i);return WC(t,n),GC(t,n,o),t}var KC=(t,n={})=>{if(typeof t!=="function")throw TypeError(`Expected the first argument to be a function, got \`${typeof t}\``);let{wait:i=0,maxWait:o=Number.POSITIVE_INFINITY,before:a=!1,after:c=!0}=n;if(i<0||o<0)throw RangeError("`wait` and `maxWait` must not be negative.");if(!a&&!c)throw Error("Both `before` and `after` are false, function wouldn't be called.");let m,E,_,I=function(...T){let R=this,P=()=>{if(m=void 0,E)clearTimeout(E),E=void 0;if(c)_=t.apply(R,T)},M=()=>{if(E=void 0,m)clearTimeout(m),m=void 0;if(c)_=t.apply(R,T)},N=a&&!m;if(clearTimeout(m),m=setTimeout(P,i),o>0&&o!==Number.POSITIVE_INFINITY&&!E)E=setTimeout(M,o);if(N)_=t.apply(R,T);return _};return rh(I,t),I.cancel=()=>{if(m)clearTimeout(m),m=void 0;if(E)clearTimeout(E),E=void 0},I},nh=KC;var ko=g(pv(),1);var ZM=Object.prototype.toString;function mv(t,n,i){if(!t)return!1;if(t.constructor===n)return!0;return ZM.call(t)===i}function gv(t){return mv(t,Uint8Array,"[object Uint8Array]")}function QM(t){return mv(t,ArrayBuffer,"[object ArrayBuffer]")}function eN(t){return gv(t)||QM(t)}function tN(t){if(!gv(t))throw TypeError(`Expected \`Uint8Array\`, got \`${typeof t}\``)}function rN(t){if(!eN(t))throw TypeError(`Expected \`Uint8Array\` or \`ArrayBuffer\`, got \`${typeof t}\``)}function Mu(t,n){if(t.length===0)return new Uint8Array(0);n??=t.reduce((a,c)=>a+c.length,0);let i=new Uint8Array(n),o=0;for(let a of t)tN(a),i.set(a,o),o+=a.length;return i}var hv={utf8:new globalThis.TextDecoder("utf8")};function xc(t,n="utf8"){return rN(t),hv[n]??=new globalThis.TextDecoder(n),hv[n].decode(t)}function nN(t){if(typeof t!=="string")throw TypeError(`Expected \`string\`, got \`${typeof t}\``)}var sN=new globalThis.TextEncoder;function Nu(t){return nN(t),sN.encode(t)}var s9=Array.from({length:256},(t,n)=>n.toString(16).padStart(2,"0"));var Sv="aes-256-cbc",Av=new Set(["aes-256-cbc","aes-256-gcm","aes-256-ctr"]),iN=(t)=>typeof t==="string"&&Av.has(t),hi=()=>Object.create(null),bv=(t)=>t!==void 0,Sh=(t,n)=>{let i=new Set(["undefined","symbol","function"]),o=typeof n;if(i.has(o))throw TypeError(`Setting a value of type \`${o}\` for key \`${t}\` is not allowed as it's not supported by JSON`)},io="__internal__",bh=`${io}.migrations.version`;class Du{path;events;#t;#e;#r;#o;#n={};#i=!1;#S;#f;#a;constructor(t={}){let n=this.#p(t);if(this.#o=n,this.#u(n),this.#s(n),this.#g(n),this.events=new EventTarget,this.#e=n.encryptionKey,this.#r=n.encryptionAlgorithm??Sv,this.path=this.#y(n),this.#h(n),n.watch)this._watch()}get(t,n){if(this.#o.accessPropertiesByDotNotation)return this._get(t,n);let{store:i}=this;return t in i?i[t]:n}set(t,n){if(typeof t!=="string"&&typeof t!=="object")throw TypeError(`Expected \`key\` to be of type \`string\` or \`object\`, got ${typeof t}`);if(typeof t!=="object"&&n===void 0)throw TypeError("Use `delete()` to clear values");if(this._containsReservedKey(t))throw TypeError(`Please don't use the ${io} key, as it's used to manage this module internal operations.`);let{store:i}=this,o=(a,c)=>{if(Sh(a,c),this.#o.accessPropertiesByDotNotation)pc(i,a,c);else{if(a==="__proto__"||a==="constructor"||a==="prototype")return;i[a]=c}};if(typeof t==="object"){let a=t;for(let[c,m]of Object.entries(a))o(c,m)}else o(t,n);this.store=i}has(t){if(this.#o.accessPropertiesByDotNotation)return au(this.store,t);return t in this.store}appendToArray(t,n){Sh(t,n);let i=this.#o.accessPropertiesByDotNotation?this._get(t,[]):(t in this.store)?this.store[t]:[];if(!Array.isArray(i))throw TypeError(`The key \`${t}\` is already set to a non-array value`);this.set(t,[...i,n])}reset(...t){for(let n of t)if(bv(this.#n[n]))this.set(n,this.#n[n])}delete(t){let{store:n}=this;if(this.#o.accessPropertiesByDotNotation)pS(n,t);else delete n[t];this.store=n}clear(){let t=hi();for(let n of Object.keys(this.#n))if(bv(this.#n[n]))if(Sh(n,this.#n[n]),this.#o.accessPropertiesByDotNotation)pc(t,n,this.#n[n]);else t[n]=this.#n[n];this.store=t}onDidChange(t,n){if(typeof t!=="string")throw TypeError(`Expected \`key\` to be of type \`string\`, got ${typeof t}`);if(typeof n!=="function")throw TypeError(`Expected \`callback\` to be of type \`function\`, got ${typeof n}`);return this._handleValueChange(()=>this.get(t),n)}onDidAnyChange(t){if(typeof t!=="function")throw TypeError(`Expected \`callback\` to be of type \`function\`, got ${typeof t}`);return this._handleStoreChange(t)}get size(){return Object.keys(this.store).filter((n)=>!this._isReservedKeyPath(n)).length}get store(){try{let t=pi.readFileSync(this.path,this.#e?null:"utf8"),n=this._decryptData(t);return((o)=>{let a=this._deserialize(o);if(!this.#i)this._validate(a);return Object.assign(hi(),a)})(n)}catch(t){if(t?.code==="ENOENT")return this._ensureDirectory(),hi();if(this.#o.clearInvalidConfig){let n=t;if(n.name==="SyntaxError")return hi();if(n.message?.startsWith("Config schema violation:"))return hi();if(n.message==="Failed to decrypt config data.")return hi()}throw t}}set store(t){if(this._ensureDirectory(),!au(t,io))try{let n=pi.readFileSync(this.path,this.#e?null:"utf8"),i=this._decryptData(n),o=this._deserialize(i);if(au(o,io))pc(t,io,Bp(o,io))}catch{}if(!this.#i)this._validate(t);this._write(t),this.events.dispatchEvent(new Event("change"))}*[Symbol.iterator](){for(let[t,n]of Object.entries(this.store))if(!this._isReservedKeyPath(t))yield[t,n]}_closeWatcher(){if(this.#S)this.#S.close(),this.#S=void 0;if(this.#f)pi.unwatchFile(this.path),this.#f=!1;this.#a=void 0}_decryptData(t){let n=this.#e;if(!n)return typeof t==="string"?t:xc(t);let i=this.#r,o=i==="aes-256-gcm"?16:0,a=":".codePointAt(0),c=typeof t==="string"?t.codePointAt(16):t[16];if(!(a!==void 0&&c===a)){if(i==="aes-256-cbc")return typeof t==="string"?t:xc(t);throw Error("Failed to decrypt config data.")}let E=(P)=>{if(o===0)return{ciphertext:P};let M=P.length-o;if(M<0)throw Error("Invalid authentication tag length.");return{ciphertext:P.slice(0,M),authenticationTag:P.slice(M)}},_=t.slice(0,16),I=t.slice(17),T=typeof I==="string"?Nu(I):I,R=(P)=>{let{ciphertext:M,authenticationTag:N}=E(T),H=_c.pbkdf2Sync(n,P,1e4,32,"sha512"),Z=_c.createDecipheriv(i,H,_);if(N)Z.setAuthTag(N);return xc(Mu([Z.update(M),Z.final()]))};try{return R(_)}catch{try{return R(_.toString())}catch{}}if(i==="aes-256-cbc")return typeof t==="string"?t:xc(t);throw Error("Failed to decrypt config data.")}_handleStoreChange(t){let n=this.store,i=()=>{let o=n,a=this.store;if(yv(a,o))return;n=a,t.call(this,a,o)};return this.events.addEventListener("change",i),()=>{this.events.removeEventListener("change",i)}}_handleValueChange(t,n){let i=t(),o=()=>{let a=i,c=t();if(yv(c,a))return;i=c,n.call(this,c,a)};return this.events.addEventListener("change",o),()=>{this.events.removeEventListener("change",o)}}_deserialize=(t)=>JSON.parse(t);_serialize=(t)=>JSON.stringify(t,void 0,"\t");_validate(t){if(!this.#t)return;if(this.#t(t)||!this.#t.errors)return;let i=this.#t.errors.map(({instancePath:o,message:a=""})=>`\`${o.slice(1)}\` ${a}`);throw Error("Config schema violation: "+i.join("; "))}_ensureDirectory(){pi.mkdirSync($u.dirname(this.path),{recursive:!0})}_write(t){let n=this._serialize(t),i=this.#e;if(i){let o=_c.randomBytes(16),a=_c.pbkdf2Sync(i,o,1e4,32,"sha512"),c=_c.createCipheriv(this.#r,a,o),m=Mu([c.update(Nu(n)),c.final()]),E=[o,Nu(":"),m];if(this.#r==="aes-256-gcm")E.push(c.getAuthTag());n=Mu(E)}if(wh.env.SNAP)pi.writeFileSync(this.path,n,{mode:this.#o.configFileMode});else try{Xp(this.path,n,{mode:this.#o.configFileMode})}catch(o){if(o?.code==="EXDEV"){pi.writeFileSync(this.path,n,{mode:this.#o.configFileMode});return}throw o}}_watch(){if(this._ensureDirectory(),!pi.existsSync(this.path))this._write(hi());if(wh.platform==="win32"||wh.platform==="darwin"){this.#a??=nh(()=>{this.events.dispatchEvent(new Event("change"))},{wait:100});let t=$u.dirname(this.path),n=$u.basename(this.path);this.#S=pi.watch(t,{persistent:!1,encoding:"utf8"},(i,o)=>{if(o&&o!==n)return;if(typeof this.#a==="function")this.#a()})}else this.#a??=nh(()=>{this.events.dispatchEvent(new Event("change"))},{wait:1000}),pi.watchFile(this.path,{persistent:!1},(t,n)=>{if(typeof this.#a==="function")this.#a()}),this.#f=!0}_migrate(t,n,i){let o=this._get(bh,"0.0.0"),a=Object.keys(t).filter((m)=>this._shouldPerformMigration(m,o,n)),c=structuredClone(this.store);for(let m of a)try{if(i)i(this,{fromVersion:o,toVersion:m,finalVersion:n,versions:a});let E=t[m];E?.(this),this._set(bh,m),o=m,c=structuredClone(this.store)}catch(E){this.store=c;let _=E instanceof Error?E.message:String(E);throw Error(`Something went wrong during the migration! Changes applied to the store until this failed migration will be restored. ${_}`)}if(this._isVersionInRangeFormat(o)||!ko.default.eq(o,n))this._set(bh,n)}_containsReservedKey(t){if(typeof t==="string")return this._isReservedKeyPath(t);if(!t||typeof t!=="object")return!1;return this._objectContainsReservedKey(t)}_objectContainsReservedKey(t){if(!t||typeof t!=="object")return!1;for(let[n,i]of Object.entries(t)){if(this._isReservedKeyPath(n))return!0;if(this._objectContainsReservedKey(i))return!0}return!1}_isReservedKeyPath(t){return t===io||t.startsWith(`${io}.`)}_isVersionInRangeFormat(t){return ko.default.clean(t)===null}_shouldPerformMigration(t,n,i){if(this._isVersionInRangeFormat(t)){if(n!=="0.0.0"&&ko.default.satisfies(n,t))return!1;return ko.default.satisfies(i,t)}if(ko.default.lte(t,n))return!1;if(ko.default.gt(t,i))return!1;return!0}_get(t,n){return Bp(this.store,t,n)}_set(t,n){let{store:i}=this;pc(i,t,n),this.store=i}#p(t){let n={configName:"config",fileExtension:"json",projectSuffix:"nodejs",clearInvalidConfig:!1,accessPropertiesByDotNotation:!0,configFileMode:438,...t};if(n.encryptionAlgorithm??=Sv,!iN(n.encryptionAlgorithm))throw TypeError(`The \`encryptionAlgorithm\` option must be one of: ${[...Av].join(", ")}`);if(!n.cwd){if(!n.projectName)throw Error("Please specify the `projectName` option.");n.cwd=Vp(n.projectName,{suffix:n.projectSuffix}).config}if(typeof n.fileExtension==="string")n.fileExtension=n.fileExtension.replace(/^\.+/,"");return n}#u(t){if(!(t.schema??t.ajvOptions??t.rootSchema))return;if(t.schema&&typeof t.schema!=="object")throw TypeError("The `schema` option must be an object.");let n=Ev.default.default,i=new vv.Ajv2020({allErrors:!0,useDefaults:!0,...t.ajvOptions});n(i);let o={...t.rootSchema,type:"object",properties:t.schema};this.#t=i.compile(o),this.#c(t.schema)}#c(t){let n=Object.entries(t??{});for(let[i,o]of n){if(!o||typeof o!=="object")continue;if(!Object.hasOwn(o,"default"))continue;let{default:a}=o;if(a===void 0)continue;this.#n[i]=a}}#s(t){if(t.defaults)Object.assign(this.#n,t.defaults)}#g(t){if(t.serialize)this._serialize=t.serialize;if(t.deserialize)this._deserialize=t.deserialize}#y(t){let n=typeof t.fileExtension==="string"?t.fileExtension:void 0,i=n?`.${n}`:"";return $u.resolve(t.cwd,`${t.configName??"config"}${i}`)}#h(t){if(t.migrations){this.#d(t),this._validate(this.store);return}let n=this.store,i=Object.assign(hi(),t.defaults??{},n);this._validate(i);try{wv.deepEqual(n,i)}catch{this.store=i}}#d(t){let{migrations:n,projectVersion:i}=t;if(!n)return;if(!i)throw Error("Please specify the `projectVersion` option.");this.#i=!0;try{let o=this.store,a=Object.assign(hi(),t.defaults??{},o);try{wv.deepEqual(o,a)}catch{this._write(a)}this._migrate(n,i,t.beforeEachMigration)}finally{this.#i=!1}}}var oN=["autoUpdateSkills","showOnboarding"];function _v(t){let n={};for(let i of oN)if(t[i]!==void 0)n[i]=t[i];return n}var aN=x,xv=null;function Iv(){return xv??=new Du({cwd:aN,configName:"settings",schema:{autoUpdateSkills:{type:"boolean",default:!1},showOnboarding:{type:"boolean",default:!0}}}),xv}function Lu(){return Iv().store}function Tv(t){let n=Iv();if(Object.keys(t).length>0)n.set(t);return n.store}import{mkdir as lN,rename as uN,readFile as dN}from"fs/promises";import{existsSync as fN}from"fs";import{basename as pN,join as Uu}from"path";var Rv=s({message:r().trim().min(1).max(50)}).strict();async function Ic(t){let n=await Ft(t);return{name:n.name,icon:n.icon}}async function mi(t,n){let{layout:i}=await ze(t,(o)=>{let a={...o};if(n.name!==void 0)if(n.name)a.name=n.name;else delete a.name;if(n.icon!==void 0)if(n.icon)a.icon=n.icon;else delete a.icon;return a});return i}function ju(t,n){return["Build a new view from this message. Follow the pending view steps in the moi-workspace skill.",`The view id is \`${t}\`. Write the view source to \`.moi/views/${t}.tsx\`.`,`Before building, set a provisional title and icon: \`moi views set ${t} --title "<title>" --icon <icon-id>\`. Use sentence case for the title.`,`Available view icons: ${n.join(", ")}`,'If the user asks for an additional view, create it with: `moi views create --requirements "<complete requirements>"`.']}import{join as cN}from"path";function Pv(t,n){return cN(ye(t,n),"moi-workspace","references","COLLAB.md")}async function Cv(t,n){if(p().environment!=="cloud")return;let i=Pv(t,n);return await Bun.file(i).exists()?i:void 0}async function va(t,n){let i=nr(t.id);try{let{getWorkspace:o}=await import("./chunk-8fvgvm56.js"),a=await o(t.id);if(a&&(a.harness??"claude-code")!==(t.harness??"claude-code"))throw new ae("Agent changed. Start a new chat");let{prepareWorkspaceHarness:c}=await import("./chunk-w6ksnv8y.js");await c(t);let{viewBuildId:m,...E}=n,_=ee(t.id,n.sessionId),I=await Or(t,_),T=n.context?.activeTab?.id??I.tabId??"overview",R=m??(n.isNew?xn(T):void 0),P=R?[]:(await _t(t)).filter((V)=>V.buildSessionId===_),M=R?await Ht(t,R):P.find((V)=>V.id===xn(T))??P[0],N=M&&(m===M.id||n.isNew);if(N&&M.buildSessionId&&M.buildSessionId!==_&&(M.status==="starting"||y(t).activeSessions().some((V)=>V.workspaceId===t.id&&V.sessionId===M.buildSessionId)))throw new U("This view is already being built in another chat",409);if(n.isNew&&I.tabId!==T)I.tabId=T==="overview"?void 0:T,await mt(t,_,{tabId:I.tabId}),await Ge(t,_,T,null);if(N)await Qe(t,M.id,{buildSessionId:_});let H=await Cv(t.path,t.harness),Z=await qr(t);if(await y(t).sendMessage({...E,sessionId:_,context:{...n.context,workspaceMode:t.remote?"remote":"local",session:{id:_,tabId:I.tabId,pinned:Z===_},...H?{collabReference:H}:{},directives:[...n.context?.directives??[],...N?ju(M.id,Se):[],...N&&I.fork?["Inherited conversation is background. Work on the current request; do not resume unrelated earlier tasks."]:[],...M&&n.isNew&&M.requirements!==n.content?[`Original view requirements:
|
|
63
|
-
${M.requirements}`]:[],...M&&n.attachments?.length?["Use the attachments as reference material for the intended view."]:[]]}}),M&&M.status!=="starting")await
|
|
60
|
+
`);super(i?`At ${i}: ${o}`:o);this.rawMessage=t,this.path=n}rawMessage;path;name="ValidationError"}function fn(t,n){if(n instanceof ge)throw new ge(n.rawMessage,[t,...n.path]);throw new ge(n.toString(),[t])}function lr(t){if(t===null)return"null";if(Array.isArray(t))return"an array";let n=typeof t;switch(n){case"bigint":case"boolean":case"function":case"number":case"string":case"symbol":return`a ${n}`;case"object":return`an ${n}`;case"undefined":return"undefined";default:ja(n)}}class Xe{constructor(t,n,i=!1){this.validationFn=t,this.validateUsingKnownGoodVersionFn=n,this.skipSameValueCheck=i}validationFn;validateUsingKnownGoodVersionFn;skipSameValueCheck;validate(t){let n=this.validationFn(t);if(YR&&!this.skipSameValueCheck&&!Object.is(t,n))throw new ge("Validator functions must return the same value they were passed");return n}validateUsingKnownGoodVersion(t,n){if(Object.is(t,n))return t;if(this.validateUsingKnownGoodVersionFn)return this.validateUsingKnownGoodVersionFn(t,n);return this.validate(n)}isValid(t){try{return this.validate(t),!0}catch{return!1}}nullable(){return t1(this)}optional(){return By(this)}refine(t){return new Xe((n)=>t(this.validate(n)),(n,i)=>{let o=this.validateUsingKnownGoodVersion(n,i);if(Object.is(n,o))return n;return t(o)},!0)}check(t,n){if(typeof t==="string")return this.refine((i)=>{try{n(i)}catch(o){fn(`(check ${t})`,o)}return i});else return this.refine((i)=>(t(i),i))}}class If extends Xe{constructor(t){super((n)=>{let i=Fy.validate(n);for(let o=0;o<i.length;o++)try{t.validate(i[o])}catch(a){fn(o,a)}return i},(n,i)=>{if(Object.is(n,i))return n;if(!t.validateUsingKnownGoodVersion)return this.validate(i);let o=Fy.validate(i),a=n.length!==o.length;for(let c=0;c<o.length;c++){let m=o[c];if(c>=n.length){a=!0;try{t.validate(m)}catch(E){fn(c,E)}continue}if(Object.is(n[c],m))continue;try{let E=t.validateUsingKnownGoodVersion(n[c],m);if(!Object.is(E,n[c]))a=!0}catch(E){fn(c,E)}}return a?i:n});this.itemValidator=t}itemValidator;nonEmpty(){return this.check((t)=>{if(t.length===0)throw new ge("Expected a non-empty array")})}lengthGreaterThan1(){return this.check((t)=>{if(t.length<=1)throw new ge("Expected an array with length greater than 1")})}}class Ka extends Xe{constructor(t,n=!1){let i=[],o=[];for(let[a,c]of Object.entries(t))i.push(a),o.push(c);super((a)=>{if(typeof a!=="object"||a===null)throw new ge(`Expected object, got ${lr(a)}`);for(let c=0;c<i.length;c++){let m=i[c];try{o[c].validate(gr(a,m))}catch(E){fn(m,E)}}if(!n)for(let c in a){if(!kt(a,c))continue;if(!kt(t,c))throw new ge("Unexpected property",[c])}return a},(a,c)=>{if(Object.is(a,c))return a;if(typeof c!=="object"||c===null)throw new ge(`Expected object, got ${lr(c)}`);let m=!1;for(let E=0;E<i.length;E++){let _=i[E],I=gr(a,_),T=gr(c,_);if(Object.is(I,T))continue;try{let R=o[E],P=R.validateUsingKnownGoodVersion?R.validateUsingKnownGoodVersion(I,T):R.validate(T);if(!Object.is(P,I))m=!0}catch(R){fn(_,R)}}if(!n)for(let E in c){if(!kt(c,E))continue;if(!kt(t,E))throw new ge("Unexpected property",[E])}else if(!m){for(let E of Object.keys(c))if(!kt(t,E)&&!Object.is(gr(a,E),gr(c,E))){m=!0;break}}if(!m)for(let E in a){if(!kt(a,E))continue;if(!kt(c,E)){m=!0;break}}return m?c:a});this.config=t,this.shouldAllowUnknownProperties=n}config;shouldAllowUnknownProperties;allowUnknownProperties(){return new Ka(this.config,!0)}extend(t){return new Ka({...this.config,...t})}}class kl extends Xe{constructor(t,n,i,o){super((a)=>{this.expectObject(a);let c=this.getMatchingSchema(a);if(c===void 0)return this.unknownValueValidation(a,this.getVariant(a));try{return c.validate(a)}catch(m){fn(`(${t} = ${this.getVariant(a)})`,m)}},(a,c)=>{this.expectObject(c),this.expectObject(a);let m=this.getMatchingSchema(c);if(m===void 0)return this.unknownValueValidation(c,this.getVariant(c));try{if(gr(a,t)!==gr(c,t))return m.validate(c);if(m.validateUsingKnownGoodVersion)return m.validateUsingKnownGoodVersion(a,c);else return m.validate(c)}catch(E){fn(`(${t} = ${this.getVariant(c)})`,E)}});this.key=t,this.config=n,this.unknownValueValidation=i,this.useNumberKeys=o}key;config;unknownValueValidation;useNumberKeys;expectObject(t){if(typeof t!=="object"||t===null)throw new ge(`Expected an object, got ${lr(t)}`,[])}getVariant(t){return gr(t,this.key)}getMatchingSchema(t){let n=gr(t,this.key);if(!this.useNumberKeys&&typeof n!=="string")throw new ge(`Expected a string for key "${this.key}", got ${lr(n)}`);else if(this.useNumberKeys){let i=Number(n);if(i-i!==0)throw new ge(`Expected a number for key "${this.key}", got "${n}"`)}return kt(this.config,n)?this.config[n]:void 0}validateUnknownVariants(t){return new kl(this.key,this.config,t,this.useNumberKeys)}}class Tf extends Xe{constructor(t,n){super((i)=>{if(typeof i!=="object"||i===null)throw new ge(`Expected object, got ${lr(i)}`);for(let o in i){if(!kt(i,o))continue;try{t.validate(o),n.validate(i[o])}catch(a){fn(o,a)}}return i},(i,o)=>{if(typeof o!=="object"||o===null)throw new ge(`Expected object, got ${lr(o)}`);let a=o,c=!1,m=0;for(let E in a){if(!kt(a,E))continue;m++;let _=a[E];if(!kt(i,E)){c=!0;try{t.validate(E),n.validate(_)}catch(T){fn(E,T)}continue}let I=i[E];if(Object.is(I,_))continue;try{let T=n.validateUsingKnownGoodVersion?n.validateUsingKnownGoodVersion(I,_):n.validate(_);if(!Object.is(T,I))c=!0}catch(T){fn(E,T)}}if(!c){let E=0;for(let _ in i)if(kt(i,_))E++;if(E!==m)c=!0}return c?o:i});this.keyValidator=t,this.valueValidator=n}keyValidator;valueValidator}function Rf(t){return new Xe((n)=>{if(typeof n!==t)throw new ge(`Expected ${t}, got ${lr(n)}`);return n})}var ZR=new Xe((t)=>t),qy=new Xe((t)=>t),Ne=Rf("string"),Oe=new Xe((t)=>{if(Number.isFinite(t))return t;if(typeof t!=="number")throw new ge(`Expected number, got ${lr(t)}`);if(t!==t)throw new ge("Expected a number, got NaN");throw new ge(`Expected a finite number, got ${t}`)}),Ja=new Xe((t)=>{if(Number.isFinite(t)&&t>=0)return t;if(typeof t!=="number")throw new ge(`Expected number, got ${lr(t)}`);if(t!==t)throw new ge("Expected a number, got NaN");if(t<0)throw new ge(`Expected a positive number, got ${t}`);throw new ge(`Expected a finite number, got ${t}`)}),Rt=new Xe((t)=>{if(Number.isFinite(t)&&t>0)return t;if(typeof t!=="number")throw new ge(`Expected number, got ${lr(t)}`);if(t!==t)throw new ge("Expected a number, got NaN");if(t<=0)throw new ge(`Expected a non-zero positive number, got ${t}`);throw new ge(`Expected a finite number, got ${t}`)}),Ml=new Xe((t)=>{if(Number.isFinite(t)&&t!==0)return t;if(typeof t!=="number")throw new ge(`Expected number, got ${lr(t)}`);if(t!==t)throw new ge("Expected a number, got NaN");if(t===0)throw new ge("Expected a non-zero number, got 0");throw new ge(`Expected a finite number, got ${t}`)}),QR=new Xe((t)=>{if(Number.isFinite(t)&&t>=0&&t<=1)return t;if(typeof t!=="number")throw new ge(`Expected number, got ${lr(t)}`);if(t!==t)throw new ge("Expected a number, got NaN");throw new ge(`Expected a number between 0 and 1, got ${t}`)}),VF=new Xe((t)=>{if(Number.isInteger(t))return t;if(typeof t!=="number")throw new ge(`Expected number, got ${lr(t)}`);if(t!==t)throw new ge("Expected a number, got NaN");if(t-t!==0)throw new ge(`Expected a finite number, got ${t}`);throw new ge(`Expected an integer, got ${t}`)}),zF=new Xe((t)=>{if(Number.isInteger(t)&&t>=0)return t;if(typeof t!=="number")throw new ge(`Expected number, got ${lr(t)}`);if(t!==t)throw new ge("Expected a number, got NaN");if(t-t!==0)throw new ge(`Expected a finite number, got ${t}`);if(t<0)throw new ge(`Expected a positive integer, got ${t}`);throw new ge(`Expected an integer, got ${t}`)}),GF=new Xe((t)=>{if(Number.isInteger(t)&&t>0)return t;if(typeof t!=="number")throw new ge(`Expected number, got ${lr(t)}`);if(t!==t)throw new ge("Expected a number, got NaN");if(t-t!==0)throw new ge(`Expected a finite number, got ${t}`);if(t<=0)throw new ge(`Expected a non-zero positive integer, got ${t}`);throw new ge(`Expected an integer, got ${t}`)}),ze=Rf("boolean"),KF=Rf("bigint");function yr(t){return new Xe((n)=>{if(n!==t)throw new ge(`Expected ${t}, got ${JSON.stringify(n)}`);return t})}var Fy=new Xe((t)=>{if(!Array.isArray(t))throw new ge(`Expected an array, got ${lr(t)}`);return t});function sn(t){return new If(t)}var JF=new Xe((t)=>{if(typeof t!=="object"||t===null)throw new ge(`Expected object, got ${lr(t)}`);return t});function Le(t){return new Ka(t)}function xf(t){return typeof t==="object"&&t!==null&&(Object.getPrototypeOf(t)===Object.prototype||Object.getPrototypeOf(t)===null||Object.getPrototypeOf(t)===Fa)}function _f(t){if(t===null||typeof t==="number"||typeof t==="string"||typeof t==="boolean")return!0;if(Array.isArray(t)){for(let n=0;n<t.length;n++)if(!_f(t[n]))return!1;return!0}if(xf(t)){for(let n in t){if(!kt(t,n))continue;if(!_f(t[n]))return!1}return!0}return!1}var Mt=new Xe((t)=>{if(_f(t))return t;throw new ge(`Expected json serializable value, got ${typeof t}`)},(t,n)=>{if(Array.isArray(t)&&Array.isArray(n)){let i=t.length!==n.length;for(let o=0;o<n.length;o++){if(o>=t.length){i=!0,Mt.validate(n[o]);continue}let a=t[o],c=n[o];if(Object.is(a,c))continue;let m=Mt.validateUsingKnownGoodVersion(a,c);if(!Object.is(m,a))i=!0}return i?n:t}else if(xf(t)&&xf(n)){let i=!1;for(let o in n){if(!kt(n,o))continue;if(!kt(t,o)){i=!0,Mt.validate(n[o]);continue}let a=t[o],c=n[o];if(Object.is(a,c))continue;let m=Mt.validateUsingKnownGoodVersion(a,c);if(!Object.is(m,a))i=!0}if(!i)for(let o in t){if(!kt(t,o))continue;if(!kt(n,o)){i=!0;break}}return i?n:t}else return Mt.validate(n)});function e1(t,n){return new Tf(t,n)}function Pf(t,n){return new kl(t,n,(i,o)=>{throw new ge(`Expected one of ${Object.keys(n).map((a)=>JSON.stringify(a)).join(" or ")}, got ${JSON.stringify(o)}`,[t])},!1)}function En(t,n){return new Xe((i)=>{try{return n.validate(i)}catch(o){fn(t,o)}},(i,o)=>{try{if(n.validateUsingKnownGoodVersion)return n.validateUsingKnownGoodVersion(i,o);else return n.validate(o)}catch(a){fn(t,a)}})}function Nl(t){return new Xe((n)=>{if(!t.has(n)){let i=Array.from(t,(o)=>JSON.stringify(o)).join(" or ");throw new ge(`Expected ${i}, got ${n}`)}return n})}function By(t){return new Xe((n)=>{if(n===void 0)return;return t.validate(n)},(n,i)=>{if(i===void 0)return;if(t.validateUsingKnownGoodVersion&&n!==void 0)return t.validateUsingKnownGoodVersion(n,i);return t.validate(i)},t instanceof Xe&&t.skipSameValueCheck)}function t1(t){return new Xe((n)=>{if(n===null)return null;return t.validate(n)},(n,i)=>{if(i===null)return null;if(t.validateUsingKnownGoodVersion&&n!==null)return t.validateUsingKnownGoodVersion(n,i);return t.validate(i)},t instanceof Xe&&t.skipSameValueCheck)}function Bi(...t){return Nl(new Set(t))}function Cf(t){try{return new URL(t)}catch{if(t.startsWith("/")||t.startsWith("./"))try{return new URL(t,"http://example.com")}catch{throw new ge(`Expected a valid url, got ${JSON.stringify(t)}`)}throw new ge(`Expected a valid url, got ${JSON.stringify(t)}`)}}var r1=new Set(["http:","https:","mailto:"]),Us=Ne.check((t)=>{if(t==="")return;let n=Cf(t);if(!r1.has(n.protocol.toLowerCase()))throw new ge(`Expected a valid url, got ${JSON.stringify(t)} (invalid protocol)`)}),n1=new Set(["http:","https:","data:","asset:"]),_o=Ne.check((t)=>{if(t==="")return;let n=Cf(t);if(!n1.has(n.protocol.toLowerCase()))throw new ge(`Expected a valid url, got ${JSON.stringify(t)} (invalid protocol)`)}),YF=Ne.check((t)=>{if(t==="")return;if(!Cf(t).protocol.toLowerCase().match(/^https?:$/))throw new ge(`Expected a valid url, got ${JSON.stringify(t)} (invalid protocol)`)}),Of=Ne.refine((t)=>{try{return tf(t),t}catch{throw new ge(`Expected an index key, got ${JSON.stringify(t)}`)}});Tn("@tldraw/validate","5.2.3","esm");function lt(t){return Ne.refine((n)=>{if(!n.startsWith(`${t}:`))throw Error(`${t} ID must start with "${t}:"`);return n})}var Wi=lt("asset");function oi(t,n,i){let o=n instanceof Xe?n:n?Le(n):Mt;return Le({id:Wi,typeName:yr("asset"),type:yr(t),props:o,meta:i?Le(i):Mt})}var $l={title:Ne,description:Ne,image:Ne,favicon:Ne,src:_o.nullable()},c4=oi("bookmark",Le($l)),Wy=He("com.tldraw.asset.bookmark",{MakeUrlsValid:1,AddFavicon:2}),kf=Ze({sequenceId:"com.tldraw.asset.bookmark",recordType:"asset",filter:(t)=>t.type==="bookmark",sequence:[{id:Wy.MakeUrlsValid,up:(t)=>{if(!_o.isValid(t.props.src))t.props.src=""},down:(t)=>{}},{id:Wy.AddFavicon,up:(t)=>{if(!_o.isValid(t.props.favicon))t.props.favicon=""},down:(t)=>{delete t.props.favicon}}]});var Dl={w:Oe,h:Oe,name:Ne,isAnimated:ze,mimeType:Ne.nullable(),src:_o.nullable(),fileSize:Rt.optional(),pixelRatio:Ja.optional()},p4=oi("image",Le(Dl)),oa=He("com.tldraw.asset.image",{AddIsAnimated:1,RenameWidthHeight:2,MakeUrlsValid:3,AddFileSize:4,MakeFileSizeOptional:5,AddPixelRatio:6}),Mf=Ze({sequenceId:"com.tldraw.asset.image",recordType:"asset",filter:(t)=>t.type==="image",sequence:[{id:oa.AddIsAnimated,up:(t)=>{t.props.isAnimated=!1},down:(t)=>{delete t.props.isAnimated}},{id:oa.RenameWidthHeight,up:(t)=>{t.props.w=t.props.width,t.props.h=t.props.height,delete t.props.width,delete t.props.height},down:(t)=>{t.props.width=t.props.w,t.props.height=t.props.h,delete t.props.w,delete t.props.h}},{id:oa.MakeUrlsValid,up:(t)=>{if(!_o.isValid(t.props.src))t.props.src=""},down:(t)=>{}},{id:oa.AddFileSize,up:(t)=>{t.props.fileSize=-1},down:(t)=>{delete t.props.fileSize}},{id:oa.MakeFileSizeOptional,up:(t)=>{if(t.props.fileSize===-1)t.props.fileSize=void 0},down:(t)=>{if(t.props.fileSize===void 0)t.props.fileSize=-1}},{id:oa.AddPixelRatio,up:(t)=>{},down:(t)=>{delete t.props.pixelRatio}}]});var Ll={w:Oe,h:Oe,name:Ne,isAnimated:ze,mimeType:Ne.nullable(),src:_o.nullable(),fileSize:Oe.optional()},w4=oi("video",Le(Ll)),Ya=He("com.tldraw.asset.video",{AddIsAnimated:1,RenameWidthHeight:2,MakeUrlsValid:3,AddFileSize:4,MakeFileSizeOptional:5}),Nf=Ze({sequenceId:"com.tldraw.asset.video",recordType:"asset",filter:(t)=>t.type==="video",sequence:[{id:Ya.AddIsAnimated,up:(t)=>{t.props.isAnimated=!1},down:(t)=>{delete t.props.isAnimated}},{id:Ya.RenameWidthHeight,up:(t)=>{t.props.w=t.props.width,t.props.h=t.props.height,delete t.props.width,delete t.props.height},down:(t)=>{t.props.width=t.props.w,t.props.height=t.props.h,delete t.props.w,delete t.props.h}},{id:Ya.MakeUrlsValid,up:(t)=>{if(!_o.isValid(t.props.src))t.props.src=""},down:(t)=>{}},{id:Ya.AddFileSize,up:(t)=>{t.props.fileSize=-1},down:(t)=>{delete t.props.fileSize}},{id:Ya.MakeFileSizeOptional,up:(t)=>{if(t.props.fileSize===-1)t.props.fileSize=void 0},down:(t)=>{if(t.props.fileSize===void 0)t.props.fileSize=-1}}]});var ts=Le({x:Oe,y:Oe,z:Oe.optional()}),Hi=Le({x:Oe,y:Oe,w:Oe,h:Oe});var Xa=QR;var Hy=Ne.refine((t)=>{if(!t.startsWith("page:")&&!t.startsWith("shape:"))throw Error('Parent ID must start with "page:" or "shape:"');return t}),hn=lt("shape");function $f(t,n,i){return Le({id:hn,typeName:yr("shape"),x:Oe,y:Oe,rotation:Oe,index:Of,parentId:Hy,type:yr(t),isLocked:ze,opacity:Xa,props:n?Le(n):Mt,meta:i?Le(i):Mt})}var Vy=lt("binding");function Df(t,n,i){return Le({id:Vy,typeName:yr("binding"),type:yr(t),fromId:hn,toId:hn,props:n?Le(n):Mt,meta:i?Le(i):Mt})}var D4=He("com.tldraw.binding",{}),s1=Ze({sequenceId:"com.tldraw.binding",recordType:"binding",sequence:[]});function aa(t){return`binding:${t??Ls()}`}function Lf(t){return t}function jf(t,n){return js(n,(i,o)=>`com.tldraw.binding.${t}/${o}`)}function zy(t){return rt("binding",{scope:"document",validator:En("binding",Pf("type",js(t,(n,{props:i,meta:o})=>Df(n,i,o))))}).withDefaultProperties(()=>({meta:{}}))}var ai=Le({type:Ne,content:sn(ZR),attrs:qy.optional()});function Wt(t){return{type:"doc",content:t.split(`
|
|
61
|
+
`).map((o)=>{if(!o)return{type:"paragraph"};return{type:"paragraph",content:[{type:"text",text:o}]}})}}class Ge{constructor(t,n,i){this.id=t,this.defaultValue=n,this.type=i}id;defaultValue;type;static define(t,n){let{defaultValue:i,type:o=qy}=n;return new Ge(t,i,o)}static defineEnum(t,n){let{defaultValue:i,values:o}=n;return new Uf(t,i,o)}setDefaultValue(t){this.defaultValue=t}validate(t){return this.type.validate(t)}validateUsingKnownGoodVersion(t,n){if(this.type.validateUsingKnownGoodVersion)return this.type.validateUsingKnownGoodVersion(t,n);else return this.validate(n)}}class Uf extends Ge{constructor(t,n,i){super(t,n,Bi(...i));this.values=[...i]}values;addValues(...t){for(let n of t)if(!this.values.includes(n))this.values.push(n);this.type=Bi(...this.values)}removeValues(...t){for(let n of t)if(this.values.includes(n))this.values.splice(this.values.indexOf(n),1);this.type=Bi(...this.values)}}var jl=He("com.tldraw.shape",{AddIsLocked:1,HoistOpacity:2,AddMeta:3,AddWhite:4}),Ff=Ze({sequenceId:"com.tldraw.shape",recordType:"shape",sequence:[{id:jl.AddIsLocked,up:(t)=>{t.isLocked=!1},down:(t)=>{delete t.isLocked}},{id:jl.HoistOpacity,up:(t)=>{t.opacity=Number(t.props.opacity??"1"),delete t.props.opacity},down:(t)=>{let n=t.opacity;delete t.opacity,t.props.opacity=n<0.175?"0.1":n<0.375?"0.25":n<0.625?"0.5":n<0.875?"0.75":"1"}},{id:jl.AddMeta,up:(t)=>{t.meta={}}},{id:jl.AddWhite,up:(t)=>{},down:(t)=>{if(t.props.color==="white")t.props.color="black"}}]});function mn(t){return`shape:${t??Ls()}`}function qf(t){let n=new Map;for(let[i,o]of Object.entries(t))if(o instanceof Ge){if(n.has(o))throw Error(`Duplicate style prop ${o.id}. Each style prop can only be used once within a shape.`);n.set(o,i)}return n}function ut(t){return t}function pt(t,n){return js(n,(i,o)=>`com.tldraw.shape.${t}/${o}`)}function Gy(t){return rt("shape",{scope:"document",validator:En("shape",Pf("type",js(t,(n,{props:i,meta:o})=>$f(n,i,o))))}).withDefaultProperties(()=>({x:0,y:0,rotation:0,isLocked:!1,opacity:1,meta:{}}))}function Ul(t,n){let i=[];for(let[o,{migrations:a}]of Object.entries(n)){let c=`com.tldraw.${t}.${o}`;if(!a)i.push(dn({sequenceId:c,retroactive:!0,sequence:[]}));else if("sequenceId"in a)qe(c===a.sequenceId,`sequenceId mismatch for ${o} ${ia} migrations. Expected '${c}', got '${a.sequenceId}'`),i.push(a);else if("sequence"in a)i.push(dn({sequenceId:c,retroactive:!0,sequence:a.sequence.map((m)=>("id"in m)?Bf(t,o,m):m)}));else i.push(dn({sequenceId:c,retroactive:!0,sequence:Object.keys(a.migrators).map((m)=>Number(m)).sort((m,E)=>m-E).map((m)=>({id:`${c}/${m}`,scope:"record",filter:(E)=>E.typeName===t&&E.type===o,up:(E)=>{let _=a.migrators[m].up(E);if(_)return _},down:(E)=>{let _=a.migrators[m].down(E);if(_)return _}}))}))}return i}function Bf(t,n,i){return{id:i.id,dependsOn:i.dependsOn,scope:"record",filter:(o)=>o.typeName===t&&o.type===n,up:(o)=>{let a=i.up(o.props);if(a)o.props=a},down:typeof i.down==="function"?(o)=>{let a=i.down(o.props);if(a)o.props=a}:void 0}}var Ky=["black","grey","light-violet","violet","blue","light-blue","yellow","orange","green","light-green","light-red","red","white"],ur=Ge.defineEnum("tldraw:color",{defaultValue:"black",values:Ky}),ca=Ge.defineEnum("tldraw:labelColor",{defaultValue:"black",values:Ky});var ci=Ge.defineEnum("tldraw:dash",{defaultValue:"draw",values:["draw","solid","dashed","dotted","none"]});var Io=Ge.defineEnum("tldraw:fill",{defaultValue:"none",values:["none","semi","solid","pattern","fill","lined-fill"]});var li=Ge.defineEnum("tldraw:font",{defaultValue:"draw",values:["draw","sans","serif","mono"]});var $r=Ge.defineEnum("tldraw:size",{defaultValue:"m",values:["s","m","l","xl"]});var i1=["arc","elbow"],Jy=Ge.defineEnum("tldraw:arrowKind",{defaultValue:"arc",values:i1}),Yy=["arrow","triangle","square","dot","pipe","diamond","inverted","bar","none"],Xy=Ge.defineEnum("tldraw:arrowheadStart",{defaultValue:"none",values:Yy}),Zy=Ge.defineEnum("tldraw:arrowheadEnd",{defaultValue:"arrow",values:Yy}),Wf={kind:Jy,labelColor:ca,color:ur,fill:Io,dash:ci,size:$r,arrowheadStart:Xy,arrowheadEnd:Zy,font:li,start:ts,end:ts,bend:Oe,richText:ai,labelPosition:Oe,scale:Rt,elbowMidPoint:Oe},rs=pt("arrow",{AddLabelColor:1,AddIsPrecise:2,AddLabelPosition:3,ExtractBindings:4,AddScale:5,AddElbow:6,AddRichText:7,AddRichTextAttrs:8});function To(t){return Bf("shape","arrow",t)}var Hf=dn({sequenceId:"com.tldraw.shape.arrow",retroactive:!1,sequence:[To({id:rs.AddLabelColor,up:(t)=>{t.labelColor="black"},down:"retired"}),To({id:rs.AddIsPrecise,up:({start:t,end:n})=>{if(t.type==="binding")t.isPrecise=!(t.normalizedAnchor.x===0.5&&t.normalizedAnchor.y===0.5);if(n.type==="binding")n.isPrecise=!(n.normalizedAnchor.x===0.5&&n.normalizedAnchor.y===0.5)},down:({start:t,end:n})=>{if(t.type==="binding"){if(!t.isPrecise)t.normalizedAnchor={x:0.5,y:0.5};delete t.isPrecise}if(n.type==="binding"){if(!n.isPrecise)n.normalizedAnchor={x:0.5,y:0.5};delete n.isPrecise}}}),To({id:rs.AddLabelPosition,up:(t)=>{t.labelPosition=0.5},down:(t)=>{delete t.labelPosition}}),{id:rs.ExtractBindings,scope:"storage",up:(t)=>{let n=[];for(let i of t.values()){if(i.typeName!=="shape"||i.type!=="arrow")continue;let o=i,a=tn(o),{start:c,end:m}=o.props;if(c.type==="binding"){let E=aa(),_={typeName:"binding",id:E,type:"arrow",fromId:o.id,toId:c.boundShapeId,meta:{},props:{terminal:"start",normalizedAnchor:c.normalizedAnchor,isExact:c.isExact,isPrecise:c.isPrecise}};n.push([E,_]),a.props.start={x:0,y:0}}else delete a.props.start.type;if(m.type==="binding"){let E=aa(),_={typeName:"binding",id:E,type:"arrow",fromId:o.id,toId:m.boundShapeId,meta:{},props:{terminal:"end",normalizedAnchor:m.normalizedAnchor,isExact:m.isExact,isPrecise:m.isPrecise}};n.push([E,_]),a.props.end={x:0,y:0}}else delete a.props.end.type;n.push([o.id,a])}for(let[i,o]of n)t.set(i,o)}},To({id:rs.AddScale,up:(t)=>{t.scale=1},down:(t)=>{delete t.scale}}),To({id:rs.AddElbow,up:(t)=>{t.kind="arc",t.elbowMidPoint=0.5},down:(t)=>{delete t.kind,delete t.elbowMidPoint}}),To({id:rs.AddRichText,up:(t)=>{t.richText=Wt(t.text),delete t.text}}),To({id:rs.AddRichTextAttrs,up:(t)=>{},down:(t)=>{if(t.richText&&"attrs"in t.richText)delete t.richText.attrs}})]});var Qy=Bi("center","edge-point","edge","none"),Vf={terminal:Bi("start","end"),normalizedAnchor:ts,isExact:ze,isPrecise:ze,snap:Qy},ew=jf("arrow",{AddSnap:1}),zf=Lf({sequence:[{dependsOn:[rs.ExtractBindings]},{id:ew.AddSnap,up:(t)=>{t.snap="none"},down:(t)=>{delete t.snap}}]});var o1=En("camera",Le({typeName:yr("camera"),id:lt("camera"),x:Oe,y:Oe,z:Oe,meta:Mt})),a1=He("com.tldraw.camera",{AddMeta:1}),tw=Ze({sequenceId:"com.tldraw.camera",recordType:"camera",sequence:[{id:a1.AddMeta,up:(t)=>{t.meta={}}}]}),Ro=rt("camera",{validator:o1,scope:"session"}).withDefaultProperties(()=>({x:0,y:0,z:1,meta:{}}));var rw=new Set(["none","default","pointer","cross","grab","rotate","grabbing","resize-edge","resize-corner","text","move","ew-resize","ns-resize","nesw-resize","nwse-resize","nesw-rotate","nwse-rotate","swne-rotate","senw-rotate","zoom-in","zoom-out"]),Gf=Nl(rw),nw=Le({type:Gf,rotation:Oe});var sw=new Set(["accent","white","black","selection-stroke","selection-fill","laser","muted-1"]),Kf=Nl(sw);var iw=new Set(["starting","paused","active","complete","stopping"]),Za=Le({id:Ne,points:sn(ts),size:Ja,color:Kf,opacity:Oe,state:Nl(iw),delay:Oe,shrink:Oe,taper:ze});var la=lt("page"),c1=En("page",Le({typeName:yr("page"),id:la,name:Ne,index:Of,meta:Mt})),l1=He("com.tldraw.page",{AddMeta:1}),ow=Ze({sequenceId:"com.tldraw.page",recordType:"page",sequence:[{id:l1.AddMeta,up:(t)=>{t.meta={}}}]}),Qa=rt("page",{validator:c1,scope:"document"}).withDefaultProperties(()=>({meta:{}}));var ui=lt("user"),u1=He("com.tldraw.user",{Initial:1}),aw=Ze({sequenceId:"com.tldraw.user",recordType:"user",sequence:[{id:u1.Initial,up:(t)=>{}}]});function Fl(t){let n=t?.meta,i=n?Le(Object.fromEntries(Object.entries(n).map(([a,c])=>[a,new Xe((m)=>{if(m===void 0)return;return c.validate(m)})]))).allowUnknownProperties():Mt,o=En("user",Le({typeName:yr("user"),id:ui,name:Ne,color:Ne,imageUrl:Ne,meta:i}));return rt("user",{validator:o,scope:"document"}).withDefaultProperties(()=>({name:"",color:"",imageUrl:"",meta:{}}))}var zq=En("user",Le({typeName:yr("user"),id:ui,name:Ne,color:Ne,imageUrl:Ne,meta:Mt})),Jf=Fl();var sB=lt("instance");function cw(t){let n={};for(let[o,a]of t)n[o]=By(a);let i=En("instance",Le({typeName:yr("instance"),id:lt("instance"),currentPageId:la,followingUserId:ui.nullable(),brush:Hi.nullable(),opacityForNextShape:Xa,stylesForNextShape:Le(n),cursor:nw,scribbles:sn(Za),isFocusMode:ze,isDebugMode:ze,isToolLocked:ze,exportBackground:ze,screenBounds:Hi,insets:sn(ze),zoomBrush:Hi.nullable(),isPenMode:ze,isGridMode:ze,chatMessage:Ne,isChatting:ze,highlightedUserIds:sn(ui),isFocused:ze,devicePixelRatio:Oe,isCoarsePointer:ze,isHoveringCanvas:ze.nullable(),openMenus:sn(Ne),isChangingStyle:ze,isReadonly:ze,meta:Mt,duplicateProps:Le({shapeIds:sn(lt("shape")),offset:Le({x:Oe,y:Oe})}).nullable(),cameraState:Bi("idle","moving")}));return rt("instance",{validator:i,scope:"session",ephemeralKeys:{currentPageId:!1,meta:!1,followingUserId:!0,opacityForNextShape:!0,stylesForNextShape:!0,brush:!0,cursor:!0,scribbles:!0,isFocusMode:!0,isDebugMode:!0,isToolLocked:!0,exportBackground:!0,screenBounds:!0,insets:!0,zoomBrush:!0,isPenMode:!0,isGridMode:!0,chatMessage:!0,isChatting:!0,highlightedUserIds:!0,isFocused:!0,devicePixelRatio:!0,isCoarsePointer:!0,isHoveringCanvas:!0,openMenus:!0,isChangingStyle:!0,isReadonly:!0,duplicateProps:!0,cameraState:!0}}).withDefaultProperties(()=>({followingUserId:null,opacityForNextShape:1,stylesForNextShape:{},brush:null,scribbles:[],cursor:{type:"default",rotation:0},isFocusMode:!1,exportBackground:!1,isDebugMode:!1,isToolLocked:!1,screenBounds:{x:0,y:0,w:1080,h:720},insets:[!1,!1,!1,!1],zoomBrush:null,isGridMode:!1,isPenMode:!1,chatMessage:"",isChatting:!1,highlightedUserIds:[],isFocused:!1,devicePixelRatio:typeof window>"u"?1:window.devicePixelRatio,isCoarsePointer:!1,isHoveringCanvas:null,openMenus:[],isChangingStyle:!1,isReadonly:!1,meta:{},duplicateProps:null,cameraState:"idle"}))}var nt=He("com.tldraw.instance",{AddTransparentExportBgs:1,RemoveDialog:2,AddToolLockMode:3,RemoveExtraPropsForNextShape:4,AddLabelColor:5,AddFollowingUserId:6,RemoveAlignJustify:7,AddZoom:8,AddVerticalAlign:9,AddScribbleDelay:10,RemoveUserId:11,AddIsPenModeAndIsGridMode:12,HoistOpacity:13,AddChat:14,AddHighlightedUserIds:15,ReplacePropsForNextShapeWithStylesForNextShape:16,AddMeta:17,RemoveCursorColor:18,AddLonelyProperties:19,ReadOnlyReadonly:20,AddHoveringCanvas:21,AddScribbles:22,AddInset:23,AddDuplicateProps:24,RemoveCanMoveCamera:25,AddCameraState:26}),lw=Ze({sequenceId:"com.tldraw.instance",recordType:"instance",sequence:[{id:nt.AddTransparentExportBgs,up:(t)=>({...t,exportBackground:!0})},{id:nt.RemoveDialog,up:({dialog:t,...n})=>n},{id:nt.AddToolLockMode,up:(t)=>({...t,isToolLocked:!1})},{id:nt.RemoveExtraPropsForNextShape,up:({propsForNextShape:t,...n})=>({...n,propsForNextShape:Object.fromEntries(Object.entries(t).filter(([i])=>["color","labelColor","dash","fill","size","font","align","verticalAlign","icon","geo","arrowheadStart","arrowheadEnd","spline"].includes(i)))})},{id:nt.AddLabelColor,up:({propsForNextShape:t,...n})=>({...n,propsForNextShape:{...t,labelColor:"black"}})},{id:nt.AddFollowingUserId,up:(t)=>({...t,followingUserId:null})},{id:nt.RemoveAlignJustify,up:(t)=>{let n=t.propsForNextShape.align;if(n==="justify")n="start";return{...t,propsForNextShape:{...t.propsForNextShape,align:n}}}},{id:nt.AddZoom,up:(t)=>({...t,zoomBrush:null})},{id:nt.AddVerticalAlign,up:(t)=>({...t,propsForNextShape:{...t.propsForNextShape,verticalAlign:"middle"}})},{id:nt.AddScribbleDelay,up:(t)=>{if(t.scribble!==null)return{...t,scribble:{...t.scribble,delay:0}};return{...t}}},{id:nt.RemoveUserId,up:({userId:t,...n})=>n},{id:nt.AddIsPenModeAndIsGridMode,up:(t)=>({...t,isPenMode:!1,isGridMode:!1})},{id:nt.HoistOpacity,up:({propsForNextShape:{opacity:t,...n},...i})=>({...i,opacityForNextShape:Number(t??"1"),propsForNextShape:n})},{id:nt.AddChat,up:(t)=>({...t,chatMessage:"",isChatting:!1})},{id:nt.AddHighlightedUserIds,up:(t)=>({...t,highlightedUserIds:[]})},{id:nt.ReplacePropsForNextShapeWithStylesForNextShape,up:({propsForNextShape:t,...n})=>({...n,stylesForNextShape:{}})},{id:nt.AddMeta,up:(t)=>({...t,meta:{}})},{id:nt.RemoveCursorColor,up:(t)=>{let{color:n,...i}=t.cursor;return{...t,cursor:i}}},{id:nt.AddLonelyProperties,up:(t)=>({...t,canMoveCamera:!0,isFocused:!1,devicePixelRatio:1,isCoarsePointer:!1,openMenus:[],isChangingStyle:!1,isReadOnly:!1})},{id:nt.ReadOnlyReadonly,up:({isReadOnly:t,...n})=>({...n,isReadonly:t})},{id:nt.AddHoveringCanvas,up:(t)=>({...t,isHoveringCanvas:null})},{id:nt.AddScribbles,up:({scribble:t,...n})=>({...n,scribbles:[]})},{id:nt.AddInset,up:(t)=>({...t,insets:[!1,!1,!1,!1]}),down:({insets:t,...n})=>({...n})},{id:nt.AddDuplicateProps,up:(t)=>({...t,duplicateProps:null}),down:({duplicateProps:t,...n})=>({...n})},{id:nt.RemoveCanMoveCamera,up:({canMoveCamera:t,...n})=>({...n}),down:(t)=>({...t,canMoveCamera:!0})},{id:nt.AddCameraState,up:(t)=>({...t,cameraState:"idle"}),down:({cameraState:t,...n})=>n}]}),ec="instance:instance";var d1=En("instance_page_state",Le({typeName:yr("instance_page_state"),id:lt("instance_page_state"),pageId:la,selectedShapeIds:sn(hn),hintingShapeIds:sn(hn),erasingShapeIds:sn(hn),hoveredShapeId:hn.nullable(),editingShapeId:hn.nullable(),croppingShapeId:hn.nullable(),focusedGroupId:hn.nullable(),meta:Mt})),tc=He("com.tldraw.instance_page_state",{AddCroppingId:1,RemoveInstanceIdAndCameraId:2,AddMeta:3,RenameProperties:4,RenamePropertiesAgain:5}),uw=Ze({sequenceId:"com.tldraw.instance_page_state",recordType:"instance_page_state",sequence:[{id:tc.AddCroppingId,up(t){t.croppingShapeId=null}},{id:tc.RemoveInstanceIdAndCameraId,up(t){delete t.instanceId,delete t.cameraId}},{id:tc.AddMeta,up:(t)=>{t.meta={}}},{id:tc.RenameProperties,up:(t)=>{},down:(t)=>{}},{id:tc.RenamePropertiesAgain,up:(t)=>{t.selectedShapeIds=t.selectedIds,delete t.selectedIds,t.hintingShapeIds=t.hintingIds,delete t.hintingIds,t.erasingShapeIds=t.erasingIds,delete t.erasingIds,t.hoveredShapeId=t.hoveredId,delete t.hoveredId,t.editingShapeId=t.editingId,delete t.editingId,t.croppingShapeId=t.croppingShapeId??t.croppingId??null,delete t.croppingId,t.focusedGroupId=t.focusLayerId,delete t.focusLayerId},down:(t)=>{t.selectedIds=t.selectedShapeIds,delete t.selectedShapeIds,t.hintingIds=t.hintingShapeIds,delete t.hintingShapeIds,t.erasingIds=t.erasingShapeIds,delete t.erasingShapeIds,t.hoveredId=t.hoveredShapeId,delete t.hoveredShapeId,t.editingId=t.editingShapeId,delete t.editingShapeId,t.croppingId=t.croppingShapeId,delete t.croppingShapeId,t.focusLayerId=t.focusedGroupId,delete t.focusedGroupId}}]}),Vi=rt("instance_page_state",{validator:d1,scope:"session",ephemeralKeys:{pageId:!1,selectedShapeIds:!1,editingShapeId:!0,croppingShapeId:!1,meta:!1,hintingShapeIds:!0,erasingShapeIds:!0,hoveredShapeId:!0,focusedGroupId:!0}}).withDefaultProperties(()=>({editingShapeId:null,croppingShapeId:null,selectedShapeIds:[],hoveredShapeId:null,erasingShapeIds:[],hintingShapeIds:[],focusedGroupId:null,meta:{}}));var f1=En("pointer",Le({typeName:yr("pointer"),id:lt("pointer"),x:Oe,y:Oe,lastActivityTimestamp:Oe,meta:Mt})),p1=He("com.tldraw.pointer",{AddMeta:1}),dw=Ze({sequenceId:"com.tldraw.pointer",recordType:"pointer",sequence:[{id:p1.AddMeta,up:(t)=>{t.meta={}}}]}),ua=rt("pointer",{validator:f1,scope:"session"}).withDefaultProperties(()=>({x:0,y:0,lastActivityTimestamp:0,meta:{}})),rc=ua.createId("pointer");var h1=En("instance_presence",Le({typeName:yr("instance_presence"),id:lt("instance_presence"),userId:ui,userName:Ne,lastActivityTimestamp:Oe.nullable(),followingUserId:ui.nullable(),cursor:Le({x:Oe,y:Oe,type:Gf,rotation:Oe}).nullable(),color:Ne,camera:Le({x:Oe,y:Oe,z:Oe}).nullable(),screenBounds:Hi.nullable(),selectedShapeIds:sn(lt("shape")),currentPageId:lt("page"),brush:Hi.nullable(),scribbles:sn(Za),chatMessage:Ne,meta:Mt})),da=He("com.tldraw.instance_presence",{AddScribbleDelay:1,RemoveInstanceId:2,AddChatMessage:3,AddMeta:4,RenameSelectedShapeIds:5,NullableCameraCursor:6}),fw=Ze({sequenceId:"com.tldraw.instance_presence",recordType:"instance_presence",sequence:[{id:da.AddScribbleDelay,up:(t)=>{if(t.scribble!==null)t.scribble.delay=0}},{id:da.RemoveInstanceId,up:(t)=>{delete t.instanceId}},{id:da.AddChatMessage,up:(t)=>{t.chatMessage=""}},{id:da.AddMeta,up:(t)=>{t.meta={}}},{id:da.RenameSelectedShapeIds,up:(t)=>{}},{id:da.NullableCameraCursor,up:(t)=>{},down:(t)=>{if(t.camera===null)t.camera={x:0,y:0,z:1};if(t.lastActivityTimestamp===null)t.lastActivityTimestamp=0;if(t.cursor===null)t.cursor={type:"default",x:0,y:0,rotation:0};if(t.screenBounds===null)t.screenBounds={x:0,y:0,w:1,h:1}}}]}),ql=rt("instance_presence",{validator:h1,scope:"presence"}).withDefaultProperties(()=>({lastActivityTimestamp:null,followingUserId:null,color:"#FF0000",camera:null,cursor:null,screenBounds:null,selectedShapeIds:[],brush:null,scribbles:[],chatMessage:"",meta:{}}));var m1=He("com.tldraw.asset",{AddMeta:1}),Yf=Ze({sequenceId:"com.tldraw.asset",recordType:"asset",sequence:[{id:m1.AddMeta,up:(t)=>{t.meta={}}}]});function Xf(t){return rt("asset",{scope:"document",validator:En("asset",Pf("type",js(t,(n,{props:i,meta:o})=>oi(n,i,o))))}).withDefaultProperties(()=>({meta:{}}))}var Zf=rt("asset",{scope:"document"}).withDefaultProperties(()=>({meta:{}}));function pw(t,n){return rt(t,{scope:n.scope,validator:n.validator}).withDefaultProperties(n.createDefaultProperties??(()=>({})))}function hw(t){let n=[];for(let[i,o]of Object.entries(t)){let a=`com.tldraw.${i}`,{migrations:c}=o;if(!c)n.push(dn({sequenceId:a,retroactive:!0,sequence:[]}));else if("sequenceId"in c)qe(a===c.sequenceId,`sequenceId mismatch for ${i} custom record migrations. Expected '${a}', got '${c.sequenceId}'`),n.push(c);else if("sequence"in c)n.push(dn({sequenceId:a,retroactive:!0,sequence:c.sequence.map((m)=>{if(!("id"in m))return m;return{id:m.id,dependsOn:m.dependsOn,scope:"record",filter:(E)=>E.typeName===i,up:(E)=>{let _=m.up(E);if(_)return _},down:typeof m.down==="function"?(E)=>{let _=m.down(E);if(_)return _}:void 0}})}))}return n}var g1=En("document",Le({typeName:yr("document"),id:yr("document:document"),gridSize:Oe,name:Ne,meta:Mt}));var mw=He("com.tldraw.document",{AddName:1,AddMeta:2}),gw=Ze({sequenceId:"com.tldraw.document",recordType:"document",sequence:[{id:mw.AddName,up:(t)=>{t.name=""},down:(t)=>{delete t.name}},{id:mw.AddMeta,up:(t)=>{t.meta={}}}]}),fa=rt("document",{validator:g1,scope:"document"}).withDefaultProperties(()=>({gridSize:10,name:"",meta:{}})),Bl=fa.createId("document");var Qf={w:Rt,h:Rt,assetId:Wi.nullable(),url:Us},yw=pt("bookmark",{NullAssetId:1,MakeUrlsValid:2}),ep=ut({sequence:[{id:yw.NullAssetId,up:(t)=>{if(t.assetId===void 0)t.assetId=null},down:"retired"},{id:yw.MakeUrlsValid,up:(t)=>{if(!Us.isValid(t.url))t.url=""},down:(t)=>{}}]});var zi=2,tp=3;var qs=new Uint8Array(128);for(let t=0;t<64;t++)qs["ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charCodeAt(t)]=t;var di=63,ww=61,bw=new Float64Array(31);for(let t=0;t<31;t++)bw[t]=Math.pow(2,t-15);var Sw=Math.pow(2,-14)/1024,vw=new Float64Array(1024);for(let t=0;t<1024;t++)vw[t]=1+t/1024;function y1(t,n){return t.getFloat16(n,!0)}function w1(t,n){return _1(t.getUint16(n,!0))}var gn=typeof DataView.prototype.getFloat16==="function"?y1:w1;function S1(t,n,i){t.setFloat16(n,i,!0)}function b1(t,n,i){t.setUint16(n,I1(i),!0)}var Ss=typeof DataView.prototype.setFloat16==="function"?S1:b1;function v1(t){return Uint8Array.fromBase64(t)}function E1(t){let n=t.length,i=0;if(n>0&&t.charCodeAt(n-1)===ww){if(i++,n>1&&t.charCodeAt(n-2)===ww)i++}let o=Math.floor(n*3/4)-i,a=new Uint8Array(o),c=0,m=Math.floor((n-i)/4)*4;for(let E=0;E<m;E+=4){let _=qs[t.charCodeAt(E)],I=qs[t.charCodeAt(E+1)],T=qs[t.charCodeAt(E+2)],R=qs[t.charCodeAt(E+3)],P=_<<18|I<<12|T<<6|R;a[c++]=P>>16&255,a[c++]=P>>8&255,a[c++]=P&255}if(i===1){let E=qs[t.charCodeAt(m)],_=qs[t.charCodeAt(m+1)],I=qs[t.charCodeAt(m+2)],T=E<<18|_<<12|I<<6;a[c++]=T>>16&255,a[c++]=T>>8&255}else if(i===2){let E=qs[t.charCodeAt(m)],_=qs[t.charCodeAt(m+1)],I=E<<18|_<<12;a[c++]=I>>16&255}return a}function A1(t){return t.toBase64()}function x1(t){let n=t.length,i=Math.floor(n/3)*3,o="";for(let c=0;c<i;c+=3){let m=t[c],E=t[c+1],_=t[c+2],I=m<<16|E<<8|_;o+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[I>>18&di]+"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[I>>12&di]+"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[I>>6&di]+"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[I&di]}let a=n-i;if(a===1){let c=t[i]<<16;o+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[c>>18&di]+"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[c>>12&di]+"=="}else if(a===2){let c=t[i]<<16|t[i+1]<<8;o+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[c>>18&di]+"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[c>>12&di]+"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[c>>6&di]+"="}return o}var Wl=typeof Uint8Array.prototype.toBase64==="function"?A1:x1,Po=typeof Uint8Array.fromBase64==="function"?v1:E1;function _1(t){let n=t>>15,i=t>>10&31,o=t&1023;if(i===0)return n?-o*Sw:o*Sw;if(i===31)return o?NaN:n?-1/0:1/0;let a=bw[i]*vw[o];return n?-a:a}function I1(t){if(t===0)return Object.is(t,-0)?32768:0;if(!Number.isFinite(t)){if(Number.isNaN(t))return 32256;return t>0?31744:64512}let n=t<0?1:0;t=Math.abs(t);let i=Math.floor(Math.log2(t)),o=i+15;if(o>=31)return n<<15|31744;if(o<=0){let m=Math.round(t*Math.pow(2,14)*1024);return n<<15|m&1023}let a=t/Math.pow(2,i)-1,c=Math.round(a*1024);if(c>=1024){if(c=0,o++,o>=31)return n<<15|31744}return n<<15|o<<10|c}class At{static _legacyEncodePoint(t,n,i){let o=new Uint8Array(6),a=new DataView(o.buffer);return Ss(a,0,t),Ss(a,2,n),Ss(a,4,i),Wl(o)}static _legacyEncodePoints(t){if(t.length===0)return"";let n=new Uint8Array(t.length*6),i=new DataView(n.buffer);for(let o=0;o<t.length;o++){let a=t[o],c=o*6;Ss(i,c,a.x),Ss(i,c+2,a.y),Ss(i,c+4,a.z??0.5)}return Wl(n)}static _legacyDecodePoints(t){let n=Po(t),i=new DataView(n.buffer,n.byteOffset,n.byteLength),o=[];for(let a=0;a<n.length;a+=6)o.push({x:gn(i,a),y:gn(i,a+2),z:gn(i,a+4)});return o}static encodePoints(t,n){if(n===2)return At.encodePoints2D(t);if(t.length===0)return"";let i=12,o=(t.length-1)*6,a=i+o,c=new Uint8Array(a),m=new DataView(c.buffer),E=t[0];m.setFloat32(0,E.x,!0),m.setFloat32(4,E.y,!0),m.setFloat32(8,E.z??0.5,!0);let{x:_,y:I}=E,T=E.z??0.5;for(let R=1;R<t.length;R++){let P=t[R],M=P.z??0.5,N=i+(R-1)*6;Ss(m,N,P.x-_),Ss(m,N+2,P.y-I),Ss(m,N+4,M-T),_=P.x,I=P.y,T=M}return Wl(c)}static decodePoints(t,n){if(n===2)return At.decodePoints2D(t);if(t.length===0)return[];let i=Po(t),o=new DataView(i.buffer,i.byteOffset,i.byteLength),a=[],c=o.getFloat32(0,!0),m=o.getFloat32(4,!0),E=o.getFloat32(8,!0);a.push({x:c,y:m,z:E});let _=12;for(let I=_;I<i.length;I+=6)c+=gn(o,I),m+=gn(o,I+2),E+=gn(o,I+4),a.push({x:c,y:m,z:E});return a}static decodeFirstPoint(t,n){if(n===2)return At.decodeFirstPoint2D(t);if(t.length<16)return null;let i=Po(t.slice(0,16)),o=new DataView(i.buffer,i.byteOffset,i.byteLength);return{x:o.getFloat32(0,!0),y:o.getFloat32(4,!0),z:o.getFloat32(8,!0)}}static decodeLastPoint(t,n){if(n===2)return At.decodeLastPoint2D(t);if(t.length<16)return null;let i=Po(t),o=new DataView(i.buffer,i.byteOffset,i.byteLength),a=o.getFloat32(0,!0),c=o.getFloat32(4,!0),m=o.getFloat32(8,!0),E=12;for(let _=E;_<i.length;_+=6)a+=gn(o,_),c+=gn(o,_+2),m+=gn(o,_+4);return{x:a,y:c,z:m}}static encodePoints2D(t){if(t.length===0)return"";let n=8,i=(t.length-1)*4,o=new Uint8Array(n+i),a=new DataView(o.buffer),c=t[0];a.setFloat32(0,c.x,!0),a.setFloat32(4,c.y,!0);let{x:m,y:E}=c;for(let _=1;_<t.length;_++){let I=t[_],T=n+(_-1)*4;Ss(a,T,I.x-m),Ss(a,T+2,I.y-E),m=I.x,E=I.y}return Wl(o)}static decodePoints2D(t){if(t.length===0)return[];let n=Po(t),i=new DataView(n.buffer,n.byteOffset,n.byteLength),o=[],a=i.getFloat32(0,!0),c=i.getFloat32(4,!0);o.push({x:a,y:c,z:0.5});let m=8;for(let E=m;E<n.length;E+=4)a+=gn(i,E),c+=gn(i,E+2),o.push({x:a,y:c,z:0.5});return o}static decodeFirstPoint2D(t){if(t.length<12)return null;let n=Po(t.slice(0,12)),i=new DataView(n.buffer,n.byteOffset,n.byteLength);return{x:i.getFloat32(0,!0),y:i.getFloat32(4,!0),z:0.5}}static decodeLastPoint2D(t){if(t.length<12)return null;let n=Po(t),i=new DataView(n.buffer,n.byteOffset,n.byteLength),o=i.getFloat32(0,!0),a=i.getFloat32(4,!0),c=8;for(let m=c;m<n.length;m+=4)o+=gn(i,m),a+=gn(i,m+2);return{x:o,y:a,z:0.5}}static isSinglePoint(t,n){return t.length<=(n===2?12:16)}}var rp=Le({type:Bi("free","straight"),path:Ne,dim:Bi(zi,tp).optional()}),np={color:ur,fill:Io,dash:ci,size:$r,segments:sn(rp),isComplete:ze,isClosed:ze,isPen:ze,scale:Rt,scaleX:Ml,scaleY:Ml},nc=pt("draw",{AddInPen:1,AddScale:2,Base64:3,LegacyPointsConversion:4,OmitNonPressureZ:5}),sp=ut({sequence:[{id:nc.AddInPen,up:(t)=>{let{points:n}=t.segments[0];if(n.length===0){t.isPen=!1;return}let i=!(n[0].z===0||n[0].z===0.5);if(n[1])i=i&&!(n[1].z===0||n[1].z===0.5);t.isPen=i},down:"retired"},{id:nc.AddScale,up:(t)=>{t.scale=1},down:(t)=>{delete t.scale}},{id:nc.Base64,up:(t)=>{t.segments=t.segments.map((n)=>{if(n.path!==void 0)return n;let{points:i,...o}=n,a=Array.isArray(i)?i:At._legacyDecodePoints(i);return{...o,path:At.encodePoints(a)}}),t.scaleX=t.scaleX??1,t.scaleY=t.scaleY??1},down:(t)=>{t.segments=t.segments.map((n)=>{let{path:i,...o}=n;return{...o,points:At.decodePoints(i)}}),delete t.scaleX,delete t.scaleY}},{id:nc.LegacyPointsConversion,up:(t)=>{t.segments=t.segments.map((n)=>{if(n.path!==void 0)return n;let{points:i,...o}=n,a=Array.isArray(i)?i:At._legacyDecodePoints(i);return{...o,path:At.encodePoints(a)}})},down:(t)=>{}},{id:nc.OmitNonPressureZ,up:(t)=>{},down:(t)=>{t.segments=t.segments.map((n)=>{if(n.dim===void 0)return n;let{dim:i,...o}=n;return i===zi?{...o,path:At.encodePoints(At.decodePoints(n.path,zi))}:o})}}]});var T1=/(^\/r\/[^/]+\/?$)/,R1=[{hostnames:["beta.tldraw.com","tldraw.com","localhost:3000"],canEditWhileLocked:!0,fromEmbedUrl:(t)=>{let n=ar(t);if(n&&n.pathname.match(T1))return t;return}},{hostnames:["figma.com"],canEditWhileLocked:!0,fromEmbedUrl:(t)=>{let n=ar(t);if(n&&n.pathname.match(/^\/embed\/?$/)){let i=n.searchParams.get("url");if(i)return i}return}},{hostnames:["google.*"],canEditWhileLocked:!0,fromEmbedUrl:(t)=>{let n=ar(t);if(!n)return;if(n.pathname.match(/^\/maps\/embed\/v1\/view\/?$/)&&n.searchParams.has("center")&&n.searchParams.get("zoom")){let o=n.searchParams.get("zoom"),[a,c]=n.searchParams.get("center").split(",");return`https://www.google.com/maps/@${a},${c},${o}z`}return}},{hostnames:["val.town"],canEditWhileLocked:!0,fromEmbedUrl:(t)=>{let n=ar(t),i=n&&n.pathname.match(/\/embed\/(.+)\/?/);if(i)return`https://www.val.town/v/${i[1]}`;return}},{hostnames:["codesandbox.io"],canEditWhileLocked:!0,fromEmbedUrl:(t)=>{let n=ar(t),i=n&&n.pathname.match(/\/embed\/([^/]+)\/?/);if(i)return`https://codesandbox.io/s/${i[1]}`;return}},{hostnames:["codepen.io"],canEditWhileLocked:!0,fromEmbedUrl:(t)=>{let n=/https:\/\/codepen.io\/([^/]+)\/embed\/([^/]+)/,i=t.match(n);if(i){let[o,a,c]=i;return`https://codepen.io/${a}/pen/${c}`}return}},{hostnames:["scratch.mit.edu"],canEditWhileLocked:!0,fromEmbedUrl:(t)=>{let n=/https:\/\/scratch.mit.edu\/projects\/embed\/([^/]+)/,i=t.match(n);if(i){let[o,a]=i;return`https://scratch.mit.edu/projects/${a}`}return}},{hostnames:["*.youtube.com","youtube.com","youtu.be"],canEditWhileLocked:!0,fromEmbedUrl:(t)=>{let n=ar(t);if(!n)return;if(n.hostname.replace(/^www./,"")==="youtube.com"){let o=n.pathname.match(/^\/embed\/([^/]+)\/?/);if(o)return`https://www.youtube.com/watch?v=${o[1]}`}return}},{hostnames:["calendar.google.*"],canEditWhileLocked:!0,fromEmbedUrl:(t)=>{let n=ar(t),i=n?.searchParams.get("src");if(n?.pathname.match(/\/calendar\/embed/)&&i){n.pathname="/calendar/u/0";let o=Array.from(n.searchParams.keys());for(let a of o)n.searchParams.delete(a);return n.searchParams.set("cid",i),n.href}return}},{hostnames:["docs.google.*"],canEditWhileLocked:!0,fromEmbedUrl:(t)=>{let n=ar(t);if(n?.pathname.match(/^\/presentation/)&&n?.pathname.match(/\/embed\/?$/)){n.pathname=n.pathname.replace(/\/embed$/,"/pub");let i=Array.from(n.searchParams.keys());for(let o of i)n.searchParams.delete(o);return n.href}return}},{hostnames:["gist.github.com"],canEditWhileLocked:!0,fromEmbedUrl:(t)=>{let n=ar(t);if(n&&n.pathname.match(/\/([^/]+)\/([^/]+)/)){if(!t.split("/").pop())return;return t}return}},{hostnames:["replit.com"],canEditWhileLocked:!0,fromEmbedUrl:(t)=>{let n=ar(t);if(n&&n.pathname.match(/\/@([^/]+)\/([^/]+)/)&&n.searchParams.has("embed"))return n.searchParams.delete("embed"),n.href;return}},{hostnames:["felt.com"],canEditWhileLocked:!0,fromEmbedUrl:(t)=>{let n=ar(t);if(n&&n.pathname.match(/^\/embed\/map\//))return n.pathname=n.pathname.replace(/^\/embed/,""),n.href;return}},{hostnames:["open.spotify.com"],canEditWhileLocked:!0,fromEmbedUrl:(t)=>{let n=ar(t);if(n&&n.pathname.match(/^\/embed\/(artist|album)\//))return n.origin+n.pathname.replace(/^\/embed/,"");return}},{hostnames:["vimeo.com","player.vimeo.com"],canEditWhileLocked:!0,fromEmbedUrl:(t)=>{let n=ar(t);if(n&&n.hostname==="player.vimeo.com"){let i=n.pathname.match(/^\/video\/([^/]+)\/?$/);if(i)return"https://vimeo.com/"+i[1]}return}},{hostnames:["observablehq.com"],canEditWhileLocked:!0,fromEmbedUrl:(t)=>{let n=ar(t);if(n&&n.pathname.match(/^\/embed\/@([^/]+)\/([^/]+)\/?$/))return`${n.origin}${n.pathname.replace("/embed","")}#cell-*`;if(n&&n.pathname.match(/^\/embed\/([^/]+)\/?$/))return`${n.origin}${n.pathname.replace("/embed","/d")}#cell-*`;return}},{hostnames:["desmos.com"],canEditWhileLocked:!0,fromEmbedUrl:(t)=>{let n=ar(t);if(n&&n.hostname==="www.desmos.com"&&n.pathname.match(/^\/calculator\/([^/]+)\/?$/)&&n.search==="?embed"&&n.hash==="")return t.replace("?embed","");return}}],ip={w:Rt,h:Rt,url:Ne},Hl=pt("embed",{GenOriginalUrlInEmbed:1,RemoveDoesResize:2,RemoveTmpOldUrl:3,RemovePermissionOverrides:4}),op=ut({sequence:[{id:Hl.GenOriginalUrlInEmbed,up:(t)=>{try{let n=t.url,i=new URL(n).host.replace("www.",""),o;for(let a of R1)if(a.hostnames.includes(i))try{o=a.fromEmbedUrl(n)}catch(c){console.warn(c)}t.tmpOldUrl=t.url,t.url=o??""}catch{t.url="",t.tmpOldUrl=t.url}},down:"retired"},{id:Hl.RemoveDoesResize,up:(t)=>{delete t.doesResize},down:"retired"},{id:Hl.RemoveTmpOldUrl,up:(t)=>{delete t.tmpOldUrl},down:"retired"},{id:Hl.RemovePermissionOverrides,up:(t)=>{delete t.overridePermissions},down:"retired"}]});var ap={w:Rt,h:Rt,name:Ne,color:{validate:(t)=>ur.validate(t)}},P1=pt("frame",{AddColorProp:1}),cp=ut({sequence:[{id:P1.AddColorProp,up:(t)=>{t.color="black"},down:(t)=>{delete t.color}}]});var sc=Ge.defineEnum("tldraw:horizontalAlign",{defaultValue:"middle",values:["start","middle","end","start-legacy","end-legacy","middle-legacy"]});var ic=Ge.defineEnum("tldraw:verticalAlign",{defaultValue:"middle",values:["start","middle","end"]});var Ew=Ge.defineEnum("tldraw:geo",{defaultValue:"rectangle",values:["cloud","rectangle","ellipse","triangle","diamond","pentagon","hexagon","octagon","star","rhombus","rhombus-2","oval","trapezoid","arrow-right","arrow-left","arrow-up","arrow-down","x-box","check-box","heart"]}),lp={geo:Ew,dash:ci,url:Us,w:Rt,h:Rt,growY:Ja,scale:Rt,labelColor:ca,color:ur,fill:Io,size:$r,font:li,align:sc,verticalAlign:ic,richText:ai},bs=pt("geo",{AddUrlProp:1,AddLabelColor:2,RemoveJustify:3,AddCheckBox:4,AddVerticalAlign:5,MigrateLegacyAlign:6,AddCloud:7,MakeUrlsValid:8,AddScale:9,AddRichText:10,AddRichTextAttrs:11}),up=ut({sequence:[{id:bs.AddUrlProp,up:(t)=>{t.url=""},down:"retired"},{id:bs.AddLabelColor,up:(t)=>{t.labelColor="black"},down:"retired"},{id:bs.RemoveJustify,up:(t)=>{if(t.align==="justify")t.align="start"},down:"retired"},{id:bs.AddCheckBox,up:(t)=>{},down:"retired"},{id:bs.AddVerticalAlign,up:(t)=>{t.verticalAlign="middle"},down:"retired"},{id:bs.MigrateLegacyAlign,up:(t)=>{let n;switch(t.align){case"start":n="start-legacy";break;case"end":n="end-legacy";break;default:n="middle-legacy";break}t.align=n},down:"retired"},{id:bs.AddCloud,up:(t)=>{},down:"retired"},{id:bs.MakeUrlsValid,up:(t)=>{if(!Us.isValid(t.url))t.url=""},down:(t)=>{}},{id:bs.AddScale,up:(t)=>{t.scale=1},down:(t)=>{delete t.scale}},{id:bs.AddRichText,up:(t)=>{t.richText=Wt(t.text),delete t.text}},{id:bs.AddRichTextAttrs,up:(t)=>{},down:(t)=>{if(t.richText&&"attrs"in t.richText)delete t.richText.attrs}}]});var dp={},fp=ut({sequence:[]});var pp={color:ur,size:$r,segments:sn(rp),isComplete:ze,isPen:ze,scale:Rt,scaleX:Ml,scaleY:Ml},Vl=pt("highlight",{AddScale:1,Base64:2,LegacyPointsConversion:3,OmitNonPressureZ:4}),hp=ut({sequence:[{id:Vl.AddScale,up:(t)=>{t.scale=1},down:(t)=>{delete t.scale}},{id:Vl.Base64,up:(t)=>{t.segments=t.segments.map((n)=>{if(n.path!==void 0)return n;let{points:i,...o}=n,a=Array.isArray(i)?i:At._legacyDecodePoints(i);return{...o,path:At.encodePoints(a)}}),t.scaleX=t.scaleX??1,t.scaleY=t.scaleY??1},down:(t)=>{t.segments=t.segments.map((n)=>{let{path:i,...o}=n;return{...o,points:At.decodePoints(i)}}),delete t.scaleX,delete t.scaleY}},{id:Vl.LegacyPointsConversion,up:(t)=>{t.segments=t.segments.map((n)=>{if(n.path!==void 0)return n;let{points:i,...o}=n,a=Array.isArray(i)?i:At._legacyDecodePoints(i);return{...o,path:At.encodePoints(a)}})},down:(t)=>{}},{id:Vl.OmitNonPressureZ,up:(t)=>{},down:(t)=>{t.segments=t.segments.map((n)=>{if(n.dim===void 0)return n;let{dim:i,...o}=n;return i===zi?{...o,path:At.encodePoints(At.decodePoints(n.path,zi))}:o})}}]});var Aw=Le({topLeft:ts,bottomRight:ts,isCircle:ze.optional()}),mp={w:Rt,h:Rt,playing:ze,url:Us,assetId:Wi.nullable(),crop:Aw.nullable(),flipX:ze,flipY:ze,altText:Ne},oc=pt("image",{AddUrlProp:1,AddCropProp:2,MakeUrlsValid:3,AddFlipProps:4,AddAltText:5}),gp=ut({sequence:[{id:oc.AddUrlProp,up:(t)=>{t.url=""},down:"retired"},{id:oc.AddCropProp,up:(t)=>{t.crop=null},down:(t)=>{delete t.crop}},{id:oc.MakeUrlsValid,up:(t)=>{if(!Us.isValid(t.url))t.url=""},down:(t)=>{}},{id:oc.AddFlipProps,up:(t)=>{t.flipX=!1,t.flipY=!1},down:(t)=>{delete t.flipX,delete t.flipY}},{id:oc.AddAltText,up:(t)=>{t.altText=""},down:(t)=>{delete t.altText}}]});var xw=Ge.defineEnum("tldraw:spline",{defaultValue:"line",values:["cubic","line"]}),C1=Le({id:Ne,index:Of,x:Oe,y:Oe}),yp={color:ur,dash:ci,size:$r,spline:xw,points:e1(Ne,C1),scale:Rt},ac=pt("line",{AddSnapHandles:1,RemoveExtraHandleProps:2,HandlesToPoints:3,PointIndexIds:4,AddScale:5}),wp=ut({sequence:[{id:ac.AddSnapHandles,up:(t)=>{for(let n of Object.values(t.handles))n.canSnap=!0},down:"retired"},{id:ac.RemoveExtraHandleProps,up:(t)=>{t.handles=Zd(Object.values(t.handles).map((n)=>[n.index,{x:n.x,y:n.y}]))},down:(t)=>{let n=Object.entries(t.handles).map(([i,o])=>({index:i,...o})).sort(So);t.handles=Object.fromEntries(n.map((i,o)=>{let a=o===0?"start":o===n.length-1?"end":`handle:${i.index}`;return[a,{id:a,type:"vertex",canBind:!1,canSnap:!0,index:i.index,x:i.x,y:i.y}]}))}},{id:ac.HandlesToPoints,up:(t)=>{let n=Object.entries(t.handles).map(([i,{x:o,y:a}])=>({x:o,y:a,index:i})).sort(So);t.points=n.map(({x:i,y:o})=>({x:i,y:o})),delete t.handles},down:(t)=>{let n=wl(t.points.length);t.handles=Object.fromEntries(t.points.map((i,o)=>[n[o],{x:i.x,y:i.y}])),delete t.points}},{id:ac.PointIndexIds,up:(t)=>{let n=wl(t.points.length);t.points=Object.fromEntries(t.points.map((i,o)=>{let a=n[o];return[a,{id:a,index:a,x:i.x,y:i.y}]}))},down:(t)=>{let n=Object.values(t.points).sort(So);t.points=n.map(({x:i,y:o})=>({x:i,y:o}))}},{id:ac.AddScale,up:(t)=>{t.scale=1},down:(t)=>{delete t.scale}}]});var Sp={color:ur,labelColor:ca,size:$r,font:li,fontSizeAdjustment:Ja.nullable(),align:sc,verticalAlign:ic,growY:Ja,url:Us,richText:ai,scale:Rt,textLastEditedBy:Ne.nullable()},yn=pt("note",{AddUrlProp:1,RemoveJustify:2,MigrateLegacyAlign:3,AddVerticalAlign:4,MakeUrlsValid:5,AddFontSizeAdjustment:6,AddScale:7,AddLabelColor:8,AddRichText:9,AddRichTextAttrs:10,AddFirstEditedBy:11,MakeFontSizeAdjustmentRatio:12,RenameFirstEditedByToLast:13}),bp=ut({sequence:[{id:yn.AddUrlProp,up:(t)=>{t.url=""},down:"retired"},{id:yn.RemoveJustify,up:(t)=>{if(t.align==="justify")t.align="start"},down:"retired"},{id:yn.MigrateLegacyAlign,up:(t)=>{switch(t.align){case"start":t.align="start-legacy";return;case"end":t.align="end-legacy";return;default:t.align="middle-legacy";return}},down:"retired"},{id:yn.AddVerticalAlign,up:(t)=>{t.verticalAlign="middle"},down:"retired"},{id:yn.MakeUrlsValid,up:(t)=>{if(!Us.isValid(t.url))t.url=""},down:(t)=>{}},{id:yn.AddFontSizeAdjustment,up:(t)=>{t.fontSizeAdjustment=0},down:(t)=>{delete t.fontSizeAdjustment}},{id:yn.AddScale,up:(t)=>{t.scale=1},down:(t)=>{delete t.scale}},{id:yn.AddLabelColor,up:(t)=>{t.labelColor="black"},down:(t)=>{delete t.labelColor}},{id:yn.AddRichText,up:(t)=>{t.richText=Wt(t.text),delete t.text}},{id:yn.AddRichTextAttrs,up:(t)=>{},down:(t)=>{if(t.richText&&"attrs"in t.richText)delete t.richText.attrs}},{id:yn.AddFirstEditedBy,up:(t)=>{t.textFirstEditedBy=null},down:(t)=>{delete t.textFirstEditedBy}},{id:yn.MakeFontSizeAdjustmentRatio,up:(t)=>{t.fontSizeAdjustment=t.fontSizeAdjustment===0?1:null},down:(t)=>{t.fontSizeAdjustment=0}},{id:yn.RenameFirstEditedByToLast,up:(t)=>{t.textLastEditedBy=t.textFirstEditedBy??null,delete t.textFirstEditedBy},down:(t)=>{t.textFirstEditedBy=t.textLastEditedBy??null,delete t.textLastEditedBy}}]});var vp=Ge.defineEnum("tldraw:textAlign",{defaultValue:"start",values:["start","middle","end"]});var Ep={color:ur,size:$r,font:li,textAlign:vp,w:Rt,richText:ai,scale:Rt,autoSize:ze},zl=pt("text",{RemoveJustify:1,AddTextAlign:2,AddRichText:3,AddRichTextAttrs:4}),Ap=ut({sequence:[{id:zl.RemoveJustify,up:(t)=>{if(t.align==="justify")t.align="start"},down:"retired"},{id:zl.AddTextAlign,up:(t)=>{t.textAlign=t.align,delete t.align},down:(t)=>{t.align=t.textAlign,delete t.textAlign}},{id:zl.AddRichText,up:(t)=>{t.richText=Wt(t.text),delete t.text}},{id:zl.AddRichTextAttrs,up:(t)=>{},down:(t)=>{if(t.richText&&"attrs"in t.richText)delete t.richText.attrs}}]});var xp={w:Rt,h:Rt,time:Oe,playing:ze,autoplay:ze,url:Us,assetId:Wi.nullable(),altText:Ne},Gl=pt("video",{AddUrlProp:1,MakeUrlsValid:2,AddAltText:3,AddAutoplay:4}),_p=ut({sequence:[{id:Gl.AddUrlProp,up:(t)=>{t.url=""},down:"retired"},{id:Gl.MakeUrlsValid,up:(t)=>{if(!Us.isValid(t.url))t.url=""},down:(t)=>{}},{id:Gl.AddAltText,up:(t)=>{t.altText=""},down:(t)=>{delete t.altText}},{id:Gl.AddAutoplay,up:(t)=>{t.autoplay=!0},down:(t)=>{delete t.autoplay}}]});var cc=He("com.tldraw.store",{RemoveCodeAndIconShapeTypes:1,AddInstancePresenceType:2,RemoveTLUserAndPresenceAndAddPointer:3,RemoveUserDocument:4,FixIndexKeys:5}),Tw=dn({sequenceId:"com.tldraw.store",retroactive:!1,sequence:[{id:cc.RemoveCodeAndIconShapeTypes,scope:"storage",up:(t)=>{for(let[n,i]of t.entries())if(i.typeName==="shape"&&"type"in i&&(i.type==="icon"||i.type==="code"))t.delete(n)}},{id:cc.AddInstancePresenceType,scope:"storage",up(t){}},{id:cc.RemoveTLUserAndPresenceAndAddPointer,scope:"storage",up:(t)=>{for(let[n,i]of t.entries())if(i.typeName.match(/^(user|user_presence)$/))t.delete(n)}},{id:cc.RemoveUserDocument,scope:"storage",up:(t)=>{for(let[n,i]of t.entries())if(i.typeName.match("user_document"))t.delete(n)}},{id:cc.FixIndexKeys,scope:"record",up:(t)=>{if(["shape","page"].includes(t.typeName)&&"index"in t){let n=t;if(n.index.endsWith("0")&&n.index!=="a0")n.index=n.index.slice(0,-1)+Iw(3);if(t.typeName==="shape"&&n.type==="line"){let i=n;for(let[o,a]of Pn(i.props.points))if(a.index.endsWith("0")&&a.index!=="a0")a.index=a.index.slice(0,-1)+Iw(3)}}},down:()=>{}}]}),_w="123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",O1=()=>_w.charAt(Math.floor(Math.random()*_w.length)),Iw=(t)=>Array.from({length:t},O1).join("");function Rw(t){if(t.typeName==="asset"){if("src"in t)t.src="<redacted>";if("src"in t.props)t.props.src="<redacted>"}}function Pw({error:t,phase:n,record:i,recordBefore:o}){throw Yd(t,{tags:{origin:"store.validateRecord",storePhase:n,isExistingValidationIssue:n==="initialize"},extras:{recordBefore:o?Rw(tn(o)):void 0,recordAfter:Rw(tn(i))}}),t}function k1(){return[Qa.create({id:"page:page",name:"Page 1",index:"a1",meta:{}})]}function Cw(t){let n=t.query.ids("page"),i=t.query.records("instance_page_state"),o=()=>{if(!t.has(Bl))return t.put([fa.create({id:Bl,name:t.props.defaultName})]),o();if(!t.has(rc))return t.put([ua.create({id:rc})]),o();let a=n.get();if(a.size===0)return t.put(k1()),o();let c=()=>[...a].map((T)=>t.get(T)).sort(So)[0].id,m=t.get(ec);if(!m)return t.put([t.schema.types.instance.create({id:ec,currentPageId:c(),exportBackground:!0})]),o();else if(!a.has(m.currentPageId))return t.put([{...m,currentPageId:c()}]),o();let E=new Set,_=new Set;for(let T of a){let R=Vi.createId(T);if(!t.get(R))E.add(R);let M=Ro.createId(T);if(!t.has(M))_.add(M)}if(E.size>0)t.put([...E].map((T)=>Vi.create({id:T,pageId:Vi.parseId(T)})));if(_.size>0)t.put([..._].map((T)=>Ro.create({id:T})));let I=i.get();for(let T of I){if(!a.has(T.pageId)){t.remove([T.id]);continue}if(T.croppingShapeId&&!t.has(T.croppingShapeId))return t.put([{...T,croppingShapeId:null}]),o();if(T.focusedGroupId&&!t.has(T.focusedGroupId))return t.put([{...T,focusedGroupId:null}]),o();if(T.hoveredShapeId&&!t.has(T.hoveredShapeId))return t.put([{...T,hoveredShapeId:null}]),o();let R=T.selectedShapeIds.filter((N)=>t.has(N));if(R.length!==T.selectedShapeIds.length)return t.put([{...T,selectedShapeIds:R}]),o();let P=T.hintingShapeIds.filter((N)=>t.has(N));if(P.length!==T.hintingShapeIds.length)return t.put([{...T,hintingShapeIds:P}]),o();let M=T.erasingShapeIds.filter((N)=>t.has(N));if(M.length!==T.erasingShapeIds.length)return t.put([{...T,erasingShapeIds:M}]),o()}};return o}var Ow={arrow:{migrations:Hf,props:Wf},bookmark:{migrations:ep,props:Qf},draw:{migrations:sp,props:np},embed:{migrations:op,props:ip},frame:{migrations:cp,props:ap},geo:{migrations:up,props:lp},group:{migrations:fp,props:dp},highlight:{migrations:hp,props:pp},image:{migrations:gp,props:mp},line:{migrations:wp,props:yp},note:{migrations:bp,props:Sp},text:{migrations:Ap,props:Ep},video:{migrations:_p,props:xp}},kw={arrow:{migrations:zf,props:Vf}},Mw={image:{migrations:Mf,props:Dl},video:{migrations:Nf,props:Ll},bookmark:{migrations:kf,props:$l}};function Ip({shapes:t=Ow,bindings:n=kw,assets:i=Mw,user:o,records:a={},migrations:c}={}){let m=new Map;for(let N of Lt(t))for(let H of qf(N.props??{}).keys()){if(m.has(H.id)&&m.get(H.id)!==H)throw Error(`Multiple StyleProp instances with the same id: ${H.id}`);m.set(H.id,H)}let E=Gy(t),_=zy(n),I=Xf(i),T=cw(m),R=o?Fl(o):Jf,P=new Set(["asset","binding","camera","document","instance","instance_page_state","page","instance_presence","pointer","shape","store","user"]),M={};for(let[N,H]of Object.entries(a)){if(P.has(N))throw Error(`Custom record type name '${N}' conflicts with tldraw's built-in record type of that name. Choose a different name instead.`);M[N]=pw(N,H)}return Ga.create({asset:I,binding:_,camera:Ro,document:fa,instance:T,instance_page_state:Vi,page:Qa,instance_presence:ql,pointer:ua,shape:E,user:R,...M},{migrations:[Tw,Yf,tw,gw,lw,uw,ow,fw,dw,Ff,aw,...Ul("asset",i),...Ul("shape",t),...Ul("binding",n),...hw(a),...o?.migrations??[],...c??[]],onValidationFailure:Pw,createIntegrityChecker:Cw})}Tn("@tldraw/tlschema","5.2.3","esm");function N1(t){if(!t||typeof t!=="object")return null;let n=t.sequences;if(!n||typeof n!=="object")return null;let i={};for(let[o,a]of Object.entries(n))if(typeof a==="number")i[o]=a;return Object.keys(i).length>0?i:null}function Nw(t,n){let i=N1(t);if(!i)return[];let o=[];for(let[a,c]of Object.entries(i)){let m=n[a];if(m===void 0)o.push({id:a,fileVersion:c});else if(c>m)o.push({id:a,fileVersion:c,runtimeVersion:m})}return o}function $w(t,n){if(t)return`Moi ${t.moi}, tldraw ${t.tldraw}`;return n.map((i)=>i.runtimeVersion===void 0?`${i.id} v${i.fileVersion} (unknown here)`:`${i.id} v${i.fileVersion} > v${i.runtimeVersion}`).join(", ")}var Dw={geo:{w:100,h:100,geo:"rectangle",dash:"draw",growY:0,url:"",scale:1,color:"black",labelColor:"black",fill:"none",size:"m",font:"draw",align:"middle",verticalAlign:"middle",richText:Wt("")},text:{color:"black",size:"m",w:8,font:"draw",textAlign:"start",autoSize:!0,scale:1,richText:Wt("")},note:{color:"black",richText:Wt(""),size:"m",font:"draw",align:"middle",verticalAlign:"middle",labelColor:"black",growY:0,fontSizeAdjustment:1,url:"",scale:1,textLastEditedBy:null},arrow:{kind:"arc",elbowMidPoint:0.5,dash:"draw",size:"m",fill:"none",color:"black",labelColor:"black",bend:0,start:{x:0,y:0},end:{x:2,y:0},arrowheadStart:"none",arrowheadEnd:"arrow",richText:Wt(""),labelPosition:0.5,font:"draw",scale:1},image:{w:100,h:100,assetId:null,playing:!0,url:"",crop:null,flipX:!1,flipY:!1,altText:""}};var L1=(t)=>()=>{throw Error(`${t} is not available on the server-side scratchpad store`)},j1={defaultName:"",assets:{upload:L1("Asset upload"),resolve:()=>null,remove:async()=>{}},users:{currentUser:null,resolve:()=>null},onMount:()=>{}};function lc(t){let n=Dw[t];if(!n)throw Error(`Unknown shape type "${t}"`);return{...n}}function Kl(t){return{...t.color?{color:t.color}:{},...t.size?{size:t.size}:{},...t.fill?{fill:t.fill}:{}}}function U1(t){let n=console.error,i=[];console.error=(...o)=>{i.push(o)};try{t()}finally{console.error=n}for(let o of i)n(...o)}function F1(t,n){let i=new Ol({schema:Ip(),props:j1}),o=t?.store?t:{store:{},schema:i.schema.serialize()};try{U1(()=>i.loadStoreSnapshot(o))}catch(a){let c=Nw(t?.schema,i.schema.serialize().sequences);if(c.length>0)throw Error(`Scratchpad was written by a newer Moi (${$w(n,c)}); this server has tldraw ${pn.tldraw}. Restart the newer server or update this install (bun install -g moi-computer@latest). `+"The canvas file is intact \u2014 do not reset it.");throw Error("Scratchpad snapshot failed to load (not a version mismatch \u2014 the file may be "+`corrupted): ${a instanceof Error?a.message:String(a)}`)}return i}function Uw(t){for(let n of t.allRecords())if(n.typeName==="page")return n.id;throw Error("Scratchpad has no page")}function uc(t,n){let i=ef;for(let o of t.allRecords())if(o.typeName==="shape"&&o.parentId===n&&o.index>i)i=o.index;return rf(i)}function dc(t){return{typeName:"shape",rotation:0,isLocked:!1,opacity:1,meta:{},...t}}function Lw(t,n,i){return{id:aa(),typeName:"binding",type:"arrow",fromId:t,toId:n,meta:{},props:{terminal:i,normalizedAnchor:{x:0.5,y:0.5},isPrecise:!1,isExact:!1,snap:"none"}}}var q1={lo:{dim:768,quality:78},hi:{dim:2048,quality:88}},B1=52428800;async function W1(t,n,i){let o=Bun.file(t);if(!i&&!await o.exists())throw Error(`Image file not found: ${t}`);let a=i??new Uint8Array(await o.arrayBuffer());if(a.length===0)throw Error(`Image file is empty: ${t}`);if(a.length>B1)throw Error(`Image is too large (${Math.round(a.length/1e6)}MB, max 50MB): ${t}`);let c=q1[n],{data:m,info:E}=await D1(a).rotate().resize(c.dim,c.dim,{fit:"inside",withoutEnlargement:!0}).webp({quality:c.quality}).toBuffer({resolveWithObject:!0});return{data:m,w:E.width,h:E.height,mimeType:"image/webp",name:$1(t)}}async function H1(t,n,i,o){let a=Uw(t),c=t.get(mn(i.name)),m=typeof c?.props?.assetId==="string"?c.props.assetId:void 0,{data:E,w:_,h:I,mimeType:T,name:R}=await W1(i.path,i.quality??"lo",o),{src:P}=await Tt(n,E,T),M=Zf.createId();if(t.put([{id:M,typeName:"asset",type:"image",meta:{},props:{name:R,src:P,w:_,h:I,mimeType:T,isAnimated:!1}}]),t.put([dc({id:mn(i.name),type:"image",x:i.x,y:i.y,index:uc(t,a),parentId:a,props:{...lc("image"),w:_,h:I,assetId:M}})]),m&&m!==M&&!Fw(t,m))t.remove([m]);return{name:i.name}}function V1(t,n){let i=Uw(t),o=(a)=>{let c=t.get(mn(a));if(!c||c.typeName!=="shape")throw Error(`No shape named "${a}"`);return c};switch(n.kind){case"add-rect":return t.put([dc({id:mn(n.name),type:"geo",x:n.x,y:n.y,index:uc(t,i),parentId:i,props:{...lc("geo"),geo:"rectangle",w:n.w,h:n.h,...Kl(n),...n.text?{richText:Wt(n.text)}:{}}})]),{name:n.name};case"add-text":return t.put([dc({id:mn(n.name),type:"text",x:n.x,y:n.y,index:uc(t,i),parentId:i,props:{...lc("text"),richText:Wt(n.text),...Kl(n)}})]),{name:n.name};case"add-note":return t.put([dc({id:mn(n.name),type:"note",x:n.x,y:n.y,index:uc(t,i),parentId:i,props:{...lc("note"),richText:Wt(n.text),...Kl(n)}})]),{name:n.name};case"add-arrow":{if("name"in n.from)o(n.from.name);if("name"in n.to)o(n.to.name);let a=mn(n.name);t.put([dc({id:a,type:"arrow",x:0,y:0,index:uc(t,i),parentId:i,props:{...lc("arrow"),...Kl(n),...n.elbow?{kind:"elbow"}:{},start:"name"in n.from?{x:0,y:0}:{x:n.from.x,y:n.from.y},end:"name"in n.to?{x:100,y:0}:{x:n.to.x,y:n.to.y}}})]);let c=[];if("name"in n.from)c.push(Lw(a,mn(n.from.name),"start"));if("name"in n.to)c.push(Lw(a,mn(n.to.name),"end"));if(c.length>0)t.put(c);return{name:n.name}}case"move":{let a=o(n.name);return t.put([{...a,x:n.x,y:n.y}]),{ok:!0}}case"set":{let a=o(n.name);return t.put([{...a,props:{...a.props,richText:Wt(n.text)}}]),{ok:!0}}case"delete":{let a=mn(n.name),c=t.get(a),m=typeof c?.props?.assetId==="string"?c.props.assetId:void 0,E=[a,...z1(t,n.name)];if(t.remove(E),m&&!Fw(t,m))t.remove([m]);return{ok:!0}}case"clear":{let a=t.allRecords().filter((c)=>c.typeName==="shape"||c.typeName==="binding"||c.typeName==="asset").map((c)=>c.id);if(a.length>0)t.remove(a);return{ok:!0}}default:throw Error(`Cannot execute op "${n.kind}" on the server`)}}function Fw(t,n){for(let i of t.allRecords()){if(i.typeName!=="shape")continue;if(i.props?.assetId===n)return!0}return!1}function z1(t,n){let i=mn(n),o=[];for(let a of t.allRecords()){if(a.typeName!=="binding")continue;let c=a;if(c.fromId===i||c.toId===i)o.push(a.id)}return o}var jw=new Map;function G1(t,n){let o=(jw.get(t)??Promise.resolve()).catch(()=>{}).then(n);return jw.set(t,o.catch(()=>{})),o}function Jl(t,n,i,o){return G1(t,async()=>{let{document:a,writer:c}=await at(t),m=F1(a,c),E=i.kind==="add-image"?await H1(m,t,i,o):V1(m,i),_=m.getStoreSnapshot();return await sr(_,t),h({type:"scratchpad:changed",workspaceId:n}),E})}var Tp=(t,n,i)=>(o,a)=>{let c=-1;return m(0);async function m(E){if(E<=c)throw Error("next() called multiple times");c=E;let _,I=!1,T;if(t[E])T=t[E][0][0],o.req.routeIndex=E;else T=E===t.length&&a||void 0;if(T)try{_=await T(o,()=>m(E+1))}catch(R){if(R instanceof Error&&n)o.error=R,_=await n(R,o),I=!0;else throw R}else if(o.finalized===!1&&i)_=await i(o);if(_&&(o.finalized===!1||I))o.res=_;return o}};var qw=Symbol();var Bw=(t,n)=>new Response(t,{headers:{"Content-Type":n.replace(/^[^;]+/,(o)=>o.toLowerCase())}}).formData();var Ww=32,K1=1e4,Yl=(t)=>("headers"in t),zw=async(t,n=Object.create(null))=>{let{all:i=!1,dot:o=!1}=n,m=(Yl(t)?t.headers:t.raw.headers).get("Content-Type")?.split(";")[0].trim().toLowerCase();if(m==="multipart/form-data"||m==="application/x-www-form-urlencoded")return J1(t,{all:i,dot:o});return{}};async function J1(t,n){if(!Yl(t)&&t.bodyCache.formData)return Hw(await t.bodyCache.formData,n);let i=Yl(t)?t.headers:t.raw.headers,o=await t.arrayBuffer(),a=Bw(o,i.get("Content-Type")||"");if(!Yl(t))t.bodyCache.formData=a;let c=await a;if(c)return Hw(c,n);return{}}function Hw(t,n){let i=Object.create(null),o={count:0};if(t.forEach((a,c)=>{if(!(n.all||c.endsWith("[]")))i[c]=a;else Y1(i,c,a)}),n.dot)Object.entries(i).forEach(([a,c])=>{if(a.includes("."))X1(i,a,c,o),delete i[a]});return i}var Y1=(t,n,i)=>{if(t[n]!==void 0)if(Array.isArray(t[n]))t[n].push(i);else t[n]=[t[n],i];else if(!n.endsWith("[]"))t[n]=i;else t[n]=[i]},X1=(t,n,i,o)=>{if(/(?:^|\.)__proto__\./.test(n))return;let a=t,c=n.split(".",Ww+2);if(c.length>Ww+1)Vw();c.forEach((m,E)=>{if(E===c.length-1)a[m]=i;else{if(!a[m]||typeof a[m]!=="object"||Array.isArray(a[m])||a[m]instanceof File){if(o.count++>=K1)Vw();a[m]=Object.create(null)}a=a[m]}})},Vw=()=>{throw Error("Nesting limit exceeded")};var Pp=(t)=>{let n=t.split("/");if(n[0]==="")n.shift();return n},Gw=(t)=>{let{groups:n,path:i}=Z1(t),o=Pp(i);return Q1(o,n)},Z1=(t)=>{let n=[];return t=t.replace(/\{[^}]+\}/g,(i,o)=>{let a=`@${o}`;return n.push([a,i]),a}),{groups:n,path:t}},Q1=(t,n)=>{for(let i=n.length-1;i>=0;i--){let[o]=n[i];for(let a=t.length-1;a>=0;a--)if(t[a].includes(o)){t[a]=t[a].replace(o,n[i][1]);break}}return t},Xl={},Kw=(t,n)=>{if(t==="*")return"*";let i=t.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);if(i){let o=`${t}#${n}`;if(!Xl[o])if(i[2])Xl[o]=n&&n[0]!==":"&&n[0]!=="*"?[o,i[1],new RegExp(`^${i[2]}(?=/${n})`)]:[t,i[1],new RegExp(`^${i[2]}$`)];else Xl[o]=[t,i[1],!0];return Xl[o]}return null},Jw=(t,n)=>{try{return n(t)}catch{return t.replace(/(?:%[0-9A-Fa-f]{2})+/g,(i)=>{try{return n(i)}catch{return i}})}},Cp=(t)=>Jw(t,decodeURI),Op=(t)=>{let n=t.url,i=n.indexOf("/",n.indexOf(":")+4),o=i;for(;o<n.length;o++){let a=n.charCodeAt(o);if(a===37){let c=n.indexOf("?",o),m=n.indexOf("#",o),E=c===-1?m===-1?void 0:m:m===-1?c:Math.min(c,m),_=n.slice(i,E);return Cp(_.includes("%25")?_.replace(/%25/g,"%2525"):_)}else if(a===63||a===35)break}return n.slice(i,o)};var Yw=(t)=>{let n=Op(t);return n.length>1&&n.at(-1)==="/"?n.slice(0,-1):n},eo=(t,n,...i)=>{if(i.length)n=eo(n,...i);return`${t?.[0]==="/"?"":"/"}${t}${n==="/"?"":`${t?.at(-1)==="/"?"":"/"}${n?.[0]==="/"?n.slice(1):n}`}`},Zl=(t)=>{if(t.charCodeAt(t.length-1)!==63||!t.includes(":"))return null;let n=t.split("/"),i=[],o="";return n.forEach((a)=>{if(a!==""&&!/\:/.test(a))o+="/"+a;else if(/\:/.test(a))if(a.charCodeAt(a.length-1)===63){if(i.length===0&&o==="")i.push("/");else i.push(o);let c=a.slice(0,-1);o+="/"+c,i.push(o)}else o+="/"+a}),i.filter((a,c,m)=>m.indexOf(a)===c)},Ql=(t)=>t.indexOf("%")!==-1?Jw(t,eP):t,Rp=(t)=>{if(t.indexOf("+")!==-1)t=t.replace(/\+/g," ");return Ql(t)},Xw=(t,n,i)=>{let o=t.indexOf("#",8);if(o!==-1)t=t.slice(0,o);let a;if(!i&&n&&n.indexOf("%")===-1&&n.indexOf("+")===-1){let E=t.indexOf("?",8);if(E===-1)return;if(!t.startsWith(n,E+1))E=t.indexOf(`&${n}`,E+1);while(E!==-1){let _=t.charCodeAt(E+n.length+1);if(_===61){let I=E+n.length+2,T=t.indexOf("&",I);return Rp(t.slice(I,T===-1?void 0:T))}else if(_==38||isNaN(_))return"";E=t.indexOf(`&${n}`,E+1)}if(a=/[%+]/.test(t),!a)return}let c=Object.create(null);a??=/[%+]/.test(t);let m=t.indexOf("?",8);while(m!==-1){let E=t.indexOf("&",m+1),_=t.indexOf("=",m);if(_>E&&E!==-1)_=-1;let I=t.slice(m+1,_===-1?E===-1?void 0:E:_);if(a)I=Rp(I);if(m=E,I==="")continue;let T;if(_===-1)T="";else if(T=t.slice(_+1,E===-1?void 0:E),a)T=Rp(T);if(i){if(!(c[I]&&Array.isArray(c[I])))c[I]=[];c[I].push(T)}else c[I]??=T}return n?c[n]:c},Zw=Xw,Qw=(t,n)=>Xw(t,n,!0),eP=decodeURIComponent;var eS=class{raw;#t;#e;routeIndex=0;path;bodyCache={};constructor(t,n="/",i=[[]]){this.raw=t,this.path=n,this.#e=i}param(t){return t?this.#r(t):this.#o()}#r(t){let n=this.#e[0][this.routeIndex]?.[1][t],i=this.#n(n);return i&&Ql(i)}#o(){let t={},n=Object.keys(this.#e[0][this.routeIndex]?.[1]??{});for(let i of n){let o=this.#n(this.#e[0][this.routeIndex][1][i]);if(o!==void 0)t[i]=Ql(o)}return t}#n(t){return this.#e[1]?this.#e[1][t]:t}query(t){return Zw(this.url,t)}queries(t){return Qw(this.url,t)}header(t){if(t)return this.raw.headers.get(t)??void 0;let n=Object.create(null);return this.raw.headers.forEach((i,o)=>{n[o]=i}),n}async parseBody(t){return zw(this,t)}#i=(t)=>{let{bodyCache:n,raw:i}=this,o=n[t];if(o)return o;for(let a in n)return n[a].then((c)=>{if(a==="json")c=JSON.stringify(c);return new Response(c)[t]()});return n[t]=i[t]()};json(){return this.#i("text").then((t)=>JSON.parse(t))}text(){return this.#i("text")}arrayBuffer(){return this.#i("arrayBuffer")}bytes(){return this.#i("arrayBuffer").then((t)=>new Uint8Array(t))}blob(){return this.#i("blob")}formData(){return this.#i("formData")}addValidatedData(t,n){(this.#t??={})[t]=n}valid(t){return this.#t?.[t]}get url(){return this.raw.url}get method(){return this.raw.method}get[qw](){return this.#e}get matchedRoutes(){return this.#e[0].map(([[,t]])=>t)}get routePath(){return this.#e[0].map(([[,t]])=>t)[this.routeIndex].path}};var tS={Stringify:1,BeforeStream:2,Stream:3},rS=(t,n)=>{let i=new String(t);return i.isEscaped=!0,i.callbacks=n,i};var kp=async(t,n,i,o,a)=>{if(typeof t==="object"&&!(t instanceof String)){if(!(t instanceof Promise))t=t.toString();if(t instanceof Promise)t=await t}let c=t.callbacks;if(!c?.length)return Promise.resolve(t);if(a)a[0]+=t;else a=[t];let m=Promise.all(c.map((E)=>E({phase:n,buffer:a,context:o}))).then((E)=>Promise.all(E.filter(Boolean).map((_)=>kp(_,n,!1,o,a))).then(()=>a[0]));if(i)return rS(await m,c);else return m};var tP="text/plain; charset=UTF-8",Mp=(t,n)=>({"Content-Type":t,...n}),fc=(t,n)=>new Response(t,n),Np=class{#t;#e;env={};#r;finalized=!1;error;#o;#n;#i;#S;#f;#a;#p;#u;#c;constructor(t,n){if(this.#t=t,n)this.#n=n.executionCtx,this.env=n.env,this.#a=n.notFoundHandler,this.#c=n.path,this.#u=n.matchResult}get req(){return this.#e??=new eS(this.#t,this.#c,this.#u),this.#e}get event(){if(this.#n&&"respondWith"in this.#n)return this.#n;else throw Error("This context has no FetchEvent")}get executionCtx(){if(this.#n)return this.#n;else throw Error("This context has no ExecutionContext")}get res(){return this.#i||=fc(null,{headers:this.#p??=new Headers})}set res(t){if(this.#i&&t){t=fc(t.body,t);for(let[n,i]of this.#i.headers.entries()){if(n==="content-type")continue;if(n==="set-cookie"){let o=this.#i.headers.getSetCookie();t.headers.delete("set-cookie");for(let a of o)t.headers.append("set-cookie",a)}else t.headers.set(n,i)}}this.#i=t,this.finalized=!0}render=(...t)=>(this.#f??=(n)=>this.html(n),this.#f(...t));setLayout=(t)=>this.#S=t;getLayout=()=>this.#S;setRenderer=(t)=>{this.#f=t};header=(t,n,i)=>{if(this.finalized)this.#i=fc(this.#i.body,this.#i);let o=this.#i?this.#i.headers:this.#p??=new Headers;if(n===void 0)o.delete(t);else if(i?.append)o.append(t,n);else o.set(t,n)};status=(t)=>{this.#o=t};set=(t,n)=>{this.#r??=new Map,this.#r.set(t,n)};get=(t)=>this.#r?this.#r.get(t):void 0;get var(){if(!this.#r)return{};return Object.fromEntries(this.#r)}#s(t,n,i){let o=this.#i?new Headers(this.#i.headers):this.#p;if(typeof n==="object"&&n.headers){o??=new Headers;for(let[c,m]of new Headers(n.headers))if(c==="set-cookie")o.append(c,m);else o.set(c,m)}if(i){if(!o){let c=0;for(let m in i)if(++c>1||typeof i[m]!=="string"){o=new Headers;break}}if(o)for(let c in i){let m=i[c];if(typeof m==="string")o.set(c,m);else{o.delete(c);for(let E of m)o.append(c,E)}}}let a=typeof n==="number"?n:n?.status??this.#o;return fc(t,{status:a,headers:o??i})}newResponse=(...t)=>this.#s(...t);body=(t,n,i)=>this.#s(t,n,i);text=(t,n,i)=>!this.#p&&!this.#o&&!n&&!i&&!this.finalized?new Response(t):this.#s(t,n,Mp(tP,i));json=(t,n,i)=>this.#s(JSON.stringify(t),n,Mp("application/json",i));html=(t,n,i)=>{let o=(a)=>this.#s(a,n,Mp("text/html; charset=UTF-8",i));return typeof t==="object"?kp(t,tS.Stringify,!1,{}).then(o):o(t)};redirect=(t,n)=>{let i=String(t);return this.header("Location",!/[^\x00-\xFF]/.test(i)?i:encodeURI(i)),this.newResponse(null,n??302)};notFound=()=>(this.#a??=()=>fc(),this.#a(this))};var tr="ALL",nS="all",sS=["get","post","put","delete","options","patch","query"],eu="Can not add a route since the matcher is already built.",tu=class extends Error{};var $p="__COMPOSED_HANDLER";var rP=(t)=>t.text("404 Not Found",404),iS=(t,n)=>{if("getResponse"in t){let i=t.getResponse();return n.newResponse(i.body,i)}return console.error(t),n.text("Internal Server Error",500)},oS=class t{get;post;put;delete;options;patch;query;all;on;use;router;getPath;_basePath="/";#t="/";routes=[];constructor(n={}){[...sS,nS].forEach((c)=>{this[c]=(m,...E)=>{let _=c.toUpperCase();if(typeof m==="string")this.#t=m;else this.#o(_,this.#t,m);return E.forEach((I)=>{this.#o(_,this.#t,I)}),this}}),this.on=(c,m,...E)=>{for(let _ of[m].flat()){this.#t=_;for(let I of[c].flat()){let T=I.toUpperCase();for(let R of E)this.#o(T,this.#t,R)}}return this},this.use=(c,...m)=>{if(typeof c==="string")this.#t=c;else this.#t="*",m.unshift(c);return m.forEach((E)=>{this.#o(tr,this.#t,E)}),this};let{strict:o,...a}=n;Object.assign(this,a),this.getPath=o??!0?n.getPath??Op:Yw}#e(){let n=new t({router:this.router,getPath:this.getPath});return n.errorHandler=this.errorHandler,n.#r=this.#r,n.routes=this.routes,n}#r=rP;errorHandler=iS;route(n,i){let o=this.basePath(n);return i.routes.map((a)=>{let c;if(i.errorHandler===iS)c=a.handler;else c=async(m,E)=>(await Tp([],i.errorHandler)(m,()=>a.handler(m,E))).res,c[$p]=a.handler;o.#o(a.method,a.path,c,a.basePath)}),this}basePath(n){let i=this.#e();return i._basePath=eo(this._basePath,n),i}onError=(n)=>(this.errorHandler=n,this);notFound=(n)=>(this.#r=n,this);mount(n,i,o){let a,c;if(o)if(typeof o==="function")c=o;else if(c=o.optionHandler,o.replaceRequest===!1)a=(_)=>_;else a=o.replaceRequest;let m=c?(_)=>{let I=c(_);return Array.isArray(I)?I:[I]}:(_)=>{let I=void 0;try{I=_.executionCtx}catch{}return[_.env,I]};a||=(()=>{let _=eo(this._basePath,n),I=_==="/"?0:_.length;return(T)=>{let R=new URL(T.url);return R.pathname=this.getPath(T).slice(I)||"/",new Request(R,T)}})();let E=async(_,I)=>{let T=await i(a(_.req.raw),...m(_));if(T)return T;await I()};return this.#o(tr,eo(n,"*"),E),this}#o(n,i,o,a){i=eo(this._basePath,i);let c={basePath:a!==void 0?eo(this._basePath,a):this._basePath,path:i,method:n,handler:o};this.router.add(n,i,[o,c]),this.routes.push(c)}#n(n,i){if(n instanceof Error)return this.errorHandler(n,i);throw n}#i(n,i,o,a){if(a==="HEAD")return(async()=>new Response(null,await this.#i(n,i,o,"GET")))();let c=this.getPath(n,{env:o}),m=this.router.match(a,c),E=new Np(n,{path:c,matchResult:m,env:o,executionCtx:i,notFoundHandler:this.#r});if(m[0].length===1){let I;try{I=m[0][0][0][0](E,async()=>{E.res=await this.#r(E)})}catch(T){return this.#n(T,E)}return I instanceof Promise?I.then((T)=>T||(E.finalized?E.res:this.#r(E))).catch((T)=>this.#n(T,E)):I??this.#r(E)}let _=Tp(m[0],this.errorHandler,this.#r);return(async()=>{try{let I=await _(E);if(!I.finalized)throw Error("Context is not finalized. Did you forget to return a Response object or `await next()`?");return I.res}catch(I){return this.#n(I,E)}})()}fetch=(n,...i)=>this.#i(n,i[1],i[0],n.method);request=(n,i,o,a)=>{if(n instanceof Request)return this.fetch(i?new Request(n,i):n,o,a);return n=n.toString(),this.fetch(new Request(/^https?:\/\//.test(n)?n:`http://localhost${eo("/",n)}`,i),o,a)};fire=()=>{addEventListener("fetch",(n)=>{n.respondWith(this.#i(n.request,n,void 0,n.request.method))})}};var rr=()=>Object.create(null);var ru=[];function Dp(t,n){let i=this.buildAllMatchers(),o=(a,c)=>{let m=i[a]||i[tr],E=m[2][c];if(E)return E;let _=c.match(m[0]);if(!_)return[[],ru];let I=_.indexOf("",1);return[m[1][I],_]};return this.match=o,o(t,n)}var pa="[^/]+",ro=".*",fi="(?:|/.*)",to=Symbol(),aS=new Set(".\\+*[^]$()");function nP(t,n){if(t.length===1)return n.length===1?t<n?-1:1:-1;if(n.length===1)return 1;if(t===ro||t===fi)return n===fi?-1:1;else if(n===ro||n===fi)return-1;if(t===pa)return 1;else if(n===pa)return-1;return t.length===n.length?t<n?-1:1:n.length-t.length}var cS=class t{#t;#e;#r=rr();insert(n,i,o,a,c){let m=this;for(let E=0,_=n.length;E<_;E++){let I=n[E],T=I.length===1?I==="*"?E===_-1?["","",ro]:["","",pa]:null:I==="/*"?["","",fi]:I.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),R;if(T){let P=T[1],M=T[2]||pa;if(P&&T[2]){if(M===".*")throw to;if(M=M.replace(/^\((?!\?:)(?=[^)]+\)$)/,"(?:"),/\((?!\?:)/.test(M))throw to;if(M.length===1&&aS.has(M))throw to}if(R=m.#r[M],!R){if(M!==ro&&M!==fi){for(let N in m.#r)if((M.length>1||N.length>1)&&N!==ro&&N!==fi)throw to}R=m.#r[M]=new t}if(P!=="")R.#e??=a.varIndex++,o.push([P,R.#e])}else if(R=m.#r[I],!R){for(let P in m.#r)if(P.length>1&&P!==ro&&P!==fi)throw to;R=m.#r[I]=new t}m=R}if(m.#t!==void 0)throw to;m.#t=c?-1:i}buildRegExpStr(){let i=Object.keys(this.#r).sort(nP).map((o)=>{let a=this.#r[o],c=a.buildRegExpStr();return c===""?"":(typeof a.#e==="number"?`(${o})@${a.#e}`:aS.has(o)?`\\${o}`:o)+c}).filter(Boolean);if(typeof this.#t==="number"&&this.#t!==-1)i.unshift(`#${this.#t}`);if(i.length===0)return"";if(i.length===1)return i[0];return"(?:"+i.join("|")+")"}};var Lp=class{#t={varIndex:0};#e=new cS;#r=0;paths=rr();insert(t,n){if(n){this.#e.insert(t.split(""),0,[],this.#t,!0);return}let i=[],o=[],a=t;for(let m=0;;){let E=!1;if(a=a.replace(/\{[^}]+\}/g,(_)=>{let I=`@\\${m}`;return o[m]=[I,_],m++,E=!0,I}),!E)break}let c=a.match(/(?::[^\/]+)|(?:\/\*$)|./g)||[];for(let m=o.length-1;m>=0;m--){let[E]=o[m];for(let _=c.length-1;_>=0;_--)if(c[_].indexOf(E)!==-1){c[_]=c[_].replace(E,o[m][1]);break}}this.#e.insert(c,this.#r,i,this.#t,!1),this.paths[t]=[this.#r++,i]}buildRegExp(){let t=this.#e.buildRegExpStr();if(t==="")return[/^$/,[],[]];let n=0,i=[],o=[];return t=t.replace(/#(\d+)|@(\d+)|\.\*\$/g,(a,c,m)=>{if(c!==void 0)return i[++n]=Number(c),"$()";if(m!==void 0)return o[Number(m)]=++n,"";return""}),[new RegExp(`^${t}`),i,o]}};var lS=rr();function uS(t){return lS[t]??=new RegExp(`^${t.replace(/\/:[^/{}]+(?:\{\[\^\/]\+})?(?=[/{]|$)|\/?\*$|([.\\+*[^\]$()?{}|])/g,(n,i)=>i?`\\${i}`:n==="/*"?fi:n==="*"?ro:`/:${pa}`)}$`)}function nu(t,n){for(let i of Object.keys(t).sort((o,a)=>a.length-o.length))if(uS(i).test(n))return[...t[i]];return}var su=class{name="RegExpRouter";#t;#e;#r;constructor(){this.#t={[tr]:rr()},this.#e={[tr]:rr()},this.#r={[tr]:new Lp}}#o(t,n){try{this.#r[t].insert(n,!/\*|\/:/.test(n))}catch(i){throw i===to?new tu(n):i}}add(t,n,i){let o=this.#t,a=this.#e;if(!o)throw Error(eu);if(!o[t]){this.#r[t]=new Lp;for(let E of[o,a]){E[t]=rr();for(let _ in E[tr])E[t][_]=[...E[tr][_]],this.#o(t,_)}}if(n==="/*")n="*";let c=t===tr?Object.keys(o):[t];if(/\*$/.test(n)){let E=uS(n);for(let _ of c)if(!o[_][n])this.#o(_,n),o[_][n]=nu(o[_],n)||nu(o[tr],n)||[];for(let _ of[o,a])for(let I of c)for(let T in _[I])E.test(T)&&_[I][T].push([i,n]);return}let m=Zl(n)||[n];for(let E of m)for(let _ of c){if(!a[_][E])this.#o(_,E),a[_][E]=nu(o[_],E)||nu(o[tr],E)||[];a[_][E].push([i,E])}}match=Dp;buildAllMatchers(){let t=rr();for(let n of Object.keys(this.#e))t[n]=this.#n(n);return this.#t=this.#e=this.#r=void 0,lS=rr(),t}#n(t){let n=this.#t[t],i=this.#e[t],o=this.#r[t],a=rr(),c=[],[m,E,_]=o.buildRegExp();for(let I of[n,i])for(let T in I){let R=I[T],P=o.paths[T];if(!P){a[T]=[R.map(([M])=>[M,rr()]),ru];continue}c[P[0]]=R.map(([M,N])=>[M,o.paths[N][1].reduceRight((H,[Z],V)=>(H[Z]=_[P[1][V][1]],H),rr())])}return[m,E.map((I)=>c[I]),a]}};var jp=class{name="SmartRouter";#t=[];#e=[];constructor(t){this.#t=t.routers}add(t,n,i){if(!this.#e)throw Error(eu);this.#e.push([t,n,i])}match(t,n){if(!this.#e)throw Error("Fatal error");let i=this.#t,o=this.#e,a=i.length,c=0,m;for(;c<a;c++){let E=i[c];try{for(let _=0,I=o.length;_<I;_++)E.add(...o[_]);m=E.match(t,n)}catch(_){if(_ instanceof tu)continue;throw _}this.match=E.match.bind(E),this.#t=[E],this.#e=void 0;break}if(c===a)throw Error("Fatal error");return this.name=`SmartRouter + ${this.activeRouter.name}`,m}get activeRouter(){if(this.#e||this.#t.length!==1)throw Error("No active router has been determined yet.");return this.#t[0]}};var Up=rr(),sP=0,dS=class t{#t=[];#e=rr();#r=[];#o;#n=Up;insert(n,i,o){let a=this,c=Gw(i),m=new Set,E=0;for(let _ of c){let I=c[++E],T=Kw(_,I)||(I===void 0&&_&&_.indexOf("*")===_.length-1?_:null),R=Array.isArray(T),P=R?T[0]:T||_,M=a.#e[P]||=new t;if(T&&!M.#o)M.#o=T,a.#r.push(M);if(a=M,R)m.add(T[1])}a.#t.push({[n]:{handler:o,possibleKeys:[...m],score:++sP}})}#i(n,i,o,a,c){for(let m=0,E=i.#t.length;m<E;m++){let _=i.#t[m],I=_[o]||_[tr];if(I){I.params=rr(),n.push(I);for(let T=0,R=I.possibleKeys.length;T<R;T++){let P=I.possibleKeys[T];I.params[P]=c?.[P]&&!T?c[P]:a[P]??c?.[P]}}}}search(n,i){let o=[];this.#n=Up;let c=[this],m=Pp(i),E=[],_=m.length,I=null;for(let T=0;T<_;T++){let R=m[T],P=T===_-1,M=[];for(let H=0,Z=c.length;H<Z;H++){let V=c[H],me=V.#e[R];if(me)if(me.#n=V.#n,P){if(me.#e["*"])this.#i(o,me.#e["*"],n,V.#n);this.#i(o,me,n,V.#n)}else M.push(me);for(let te of V.#r){let we=te.#o,Te=V.#n===Up?{}:{...V.#n};if(typeof we==="string"){if(we==="*"||R.startsWith(we.slice(0,-1))){if(this.#i(o,te,n,V.#n),we==="*")te.#n=Te,M.push(te)}continue}let[,De,je]=we;if(!R&&je===!0)continue;if(je!==!0){if(!I){I=[];let yi=i[0]==="/"?1:0;for(let Qr=0;Qr<_;Qr++)I[Qr]=yi,yi+=m[Qr].length+1}let Ct=i.slice(I[T]),Ot=je.exec(Ct);if(Ot){if(Te[De]=Ot[0],this.#i(o,te,n,V.#n,Te),Ot[0].length===Ct.length&&te.#e["*"])this.#i(o,te.#e["*"],n,V.#n,Te);for(let yi in te.#e){te.#n=Te;let Qr=Ot[0].match(/\//g)?.length??0;(E[Qr]||=[]).push(te);break}continue}}if(je===!0||je.test(R))if(Te[De]=R,P){if(this.#i(o,te,n,Te,V.#n),te.#e["*"])this.#i(o,te.#e["*"],n,Te,V.#n)}else te.#n=Te,M.push(te)}}let N=E.shift();c=N?M.concat(N):M}if(o[1])o.sort((T,R)=>T.score-R.score);return[o.map(({handler:T,params:R})=>[T,R])]}};var Fp=class{name="TrieRouter";#t=new dS;add(t,n,i){for(let o of Zl(n)||[n])this.#t.insert(t,o,i)}match(t,n){return this.#t.search(t,n)}};var Bs=class extends oS{constructor(t={}){super(t);this.router=t.router??new jp({routers:[new su,new Fp]})}};import{isDeepStrictEqual as yv}from"util";import wh from"process";import pi from"fs";import $u from"path";import _c from"crypto";import wv from"assert";var Co=(t)=>{let n=typeof t;return t!==null&&(n==="object"||n==="function")},iu=new Set(["__proto__","prototype","constructor"]),iP=Math.max(...[...iu].map((t)=>t.length));var oP=(t)=>t>="0"&&t<="9";function fS(t){if(t==="0")return!0;if(/^[1-9]\d*$/.test(t)){let n=Number.parseInt(t,10);return n<=Number.MAX_SAFE_INTEGER&&n<=1e6}return!1}function qp(t,n){if(iu.has(t))return!1;if(t&&fS(t))n.push(Number.parseInt(t,10));else n.push(t);return!0}function aP(t){if(typeof t!=="string")throw TypeError(`Expected a string, got ${typeof t}`);let n=[],i="",o="",a=!1,c="start",m=!1,E=0;for(let _ of t){if(E++,m){i+=_,m=!1;continue}if(_==="\\"){if(c==="index")throw Error(`Invalid character '${_}' in an index at position ${E}`);if(c==="indexEnd")throw Error(`Invalid character '${_}' after an index at position ${E}`);m=!0,c=c==="start"?"property":c;continue}switch(_){case".":{if(c==="index")throw Error(`Invalid character '${_}' in an index at position ${E}`);if(c==="indexEnd"){c="property";break}if(!qp(i,n))return[];i="",c="property";break}case"[":{if(c==="index")throw Error(`Invalid character '${_}' in an index at position ${E}`);if(c==="indexEnd"){c="index";break}if(c==="property"&&i.length<=iP&&iu.has(i))return[];a=c==="property",c="index";break}case"]":{if(c==="indexEnd")throw Error(`Invalid character '${_}' after an index at position ${E}`);if(c!=="index"){if(c==="start")c="property";i+=_;break}if(o===""){i+="[]",c="property";break}if((i!==""||a)&&!qp(i,n))return[];i="",a=!1;let I=Number.parseInt(o,10),T=I<=1e6&&o===String(I);n.push(T?I:o),o="",c="indexEnd";break}default:{if(c==="index"){if(!oP(_))throw Error(`Invalid character '${_}' in an index at position ${E}`);o+=_;break}if(c==="indexEnd")throw Error(`Invalid character '${_}' after an index at position ${E}`);if(c==="start")c="property";i+=_}}}if(m)i+="\\";switch(c){case"property":{if(!qp(i,n))return[];break}case"index":throw Error("Index was not closed");case"start":{n.push("");break}}return n}function ou(t){if(typeof t==="string")return aP(t);if(Array.isArray(t)){let n=[];for(let[i,o]of t.entries()){if(typeof o!=="string"&&typeof o!=="number")throw TypeError(`Expected a string or number for path segment at index ${i}, got ${typeof o}`);if(typeof o==="number"&&!Number.isFinite(o))throw TypeError(`Path segment at index ${i} must be a finite number, got ${o}`);if(iu.has(o))return[];if(typeof o==="string"&&fS(o))n.push(Number.parseInt(o,10));else n.push(o)}return n}return[]}function Bp(t,n,i){if(!Co(t)||typeof n!=="string"&&!Array.isArray(n))return i===void 0?t:i;let o=ou(n);if(o.length===0)return i;for(let a=0;a<o.length;a++){let c=o[a];if(t=t[c],t===void 0||t===null){if(a!==o.length-1)return i;break}}return t===void 0?i:t}function pc(t,n,i){if(!Co(t)||typeof n!=="string"&&!Array.isArray(n))return t;let o=t,a=ou(n);if(a.length===0)return t;for(let c=0;c<a.length;c++){let m=a[c];if(c===a.length-1){t[m]=i;continue}let E=t[m];if(Co(E)){t=E;continue}let I=typeof a[c+1]==="number";t[m]=I?[]:{},t=t[m]}return o}function pS(t,n){if(!Co(t)||typeof n!=="string"&&!Array.isArray(n))return!1;let i=ou(n);if(i.length===0)return!1;for(let o=0;o<i.length;o++){let a=i[o];if(o===i.length-1){if(!Object.hasOwn(t,a))return!1;return delete t[a],!0}let c=t[a];if(!Co(c))return!1;t=c}}function au(t,n){if(!Co(t)||typeof n!=="string"&&!Array.isArray(n))return!1;let i=ou(n);if(i.length===0)return!1;for(let o of i){if(!Co(t)||!(o in t))return!1;t=t[o]}return!0}import vt from"path";import hS from"os";import Wp from"process";var no=hS.homedir(),Hp=hS.tmpdir(),{env:ha}=Wp,cP=(t)=>{let n=vt.join(no,"Library");return{data:vt.join(n,"Application Support",t),config:vt.join(n,"Preferences",t),cache:vt.join(n,"Caches",t),log:vt.join(n,"Logs",t),temp:vt.join(Hp,t)}},lP=(t)=>{let n=ha.APPDATA||vt.join(no,"AppData","Roaming"),i=ha.LOCALAPPDATA||vt.join(no,"AppData","Local");return{data:vt.join(i,t,"Data"),config:vt.join(n,t,"Config"),cache:vt.join(i,t,"Cache"),log:vt.join(i,t,"Log"),temp:vt.join(Hp,t)}},uP=(t)=>{let n=vt.basename(no);return{data:vt.join(ha.XDG_DATA_HOME||vt.join(no,".local","share"),t),config:vt.join(ha.XDG_CONFIG_HOME||vt.join(no,".config"),t),cache:vt.join(ha.XDG_CACHE_HOME||vt.join(no,".cache"),t),log:vt.join(ha.XDG_STATE_HOME||vt.join(no,".local","state"),t),temp:vt.join(Hp,n,t)}};function Vp(t,{suffix:n="nodejs"}={}){if(typeof t!=="string")throw TypeError(`Expected a string, got ${typeof t}`);if(n)t+=`-${n}`;if(Wp.platform==="darwin")return cP(t);if(Wp.platform==="win32")return lP(t);return uP(t)}import wP from"path";import Be from"fs";import{promisify as Er}from"util";var dP=(t,n)=>{let{onError:i}=n;return function(...a){return t.apply(void 0,a).catch(i)}},Ws=dP;var fP=(t,n)=>{let{onError:i}=n;return function(...a){try{return t.apply(void 0,a)}catch(c){return i(c)}}},vs=fP;var mS=250;var pP=(t,n)=>{let{isRetriable:i}=n;return function(a){let{timeout:c}=a,m=a.interval??mS,E=Date.now()+c;return function _(...I){return t.apply(void 0,I).catch((T)=>{if(!i(T))throw T;if(Date.now()>=E)throw T;let R=Math.round(m*Math.random());if(R>0)return new Promise((M)=>setTimeout(M,R)).then(()=>_.apply(void 0,I));else return _.apply(void 0,I)})}}},Hs=pP;var hP=(t,n)=>{let{isRetriable:i}=n;return function(a){let{timeout:c}=a,m=Date.now()+c;return function(..._){while(!0)try{return t.apply(void 0,_)}catch(I){if(!i(I))throw I;if(Date.now()>=m)throw I;continue}}}},Vs=hP;import yS from"process";var hc={isChangeErrorOk:(t)=>{if(!hc.isNodeError(t))return!1;let{code:n}=t;if(n==="ENOSYS")return!0;if(!gS&&(n==="EINVAL"||n==="EPERM"))return!0;return!1},isNodeError:(t)=>t instanceof Error,isRetriableError:(t)=>{if(!hc.isNodeError(t))return!1;let{code:n}=t;if(n==="EMFILE"||n==="ENFILE"||n==="EAGAIN"||n==="EBUSY"||n==="EACCESS"||n==="EACCES"||n==="EACCS"||n==="EPERM")return!0;return!1},onChangeError:(t)=>{if(!hc.isNodeError(t))throw t;if(hc.isChangeErrorOk(t))return;throw t}},zp=hc;var mc={onError:zp.onChangeError},on={onError:()=>{return}},gS=yS.getuid?!yS.getuid():!1,dr={isRetriable:zp.isRetriableError};var mP={attempt:{chmod:Ws(Er(Be.chmod),mc),chown:Ws(Er(Be.chown),mc),close:Ws(Er(Be.close),on),fsync:Ws(Er(Be.fsync),on),mkdir:Ws(Er(Be.mkdir),on),realpath:Ws(Er(Be.realpath),on),stat:Ws(Er(Be.stat),on),unlink:Ws(Er(Be.unlink),on),chmodSync:vs(Be.chmodSync,mc),chownSync:vs(Be.chownSync,mc),closeSync:vs(Be.closeSync,on),existsSync:vs(Be.existsSync,on),fsyncSync:vs(Be.fsync,on),mkdirSync:vs(Be.mkdirSync,on),realpathSync:vs(Be.realpathSync,on),statSync:vs(Be.statSync,on),unlinkSync:vs(Be.unlinkSync,on)},retry:{close:Hs(Er(Be.close),dr),fsync:Hs(Er(Be.fsync),dr),open:Hs(Er(Be.open),dr),readFile:Hs(Er(Be.readFile),dr),rename:Hs(Er(Be.rename),dr),stat:Hs(Er(Be.stat),dr),write:Hs(Er(Be.write),dr),writeFile:Hs(Er(Be.writeFile),dr),closeSync:Vs(Be.closeSync,dr),fsyncSync:Vs(Be.fsyncSync,dr),openSync:Vs(Be.openSync,dr),readFileSync:Vs(Be.readFileSync,dr),renameSync:Vs(Be.renameSync,dr),statSync:Vs(Be.statSync,dr),writeSync:Vs(Be.writeSync,dr),writeFileSync:Vs(Be.writeFileSync,dr)}},or=mP;import Oo from"process";var wS="utf8",Gp=438,SS=511;var bS={},vS=Oo.geteuid?Oo.geteuid():-1,ES=Oo.getegid?Oo.getegid():-1;var AS=1000,xS=!!Oo.getuid,nV=Oo.getuid?!Oo.getuid():!1,Kp=128;var _S=(t)=>t instanceof Error&&("code"in t);var Jp=(t)=>typeof t==="string",cu=(t)=>t===void 0;import yP from"path";import ma from"process";import IS from"process";var TS=IS.platform==="linux",lu=IS.platform==="win32";var Yp=["SIGHUP","SIGINT","SIGTERM"];if(!lu)Yp.push("SIGALRM","SIGABRT","SIGVTALRM","SIGXCPU","SIGXFSZ","SIGUSR2","SIGTRAP","SIGSYS","SIGQUIT","SIGIOT");if(TS)Yp.push("SIGIO","SIGPOLL","SIGPWR","SIGSTKFLT");var RS=Yp;class PS{constructor(){this.callbacks=new Set,this.exited=!1,this.exit=(t)=>{if(this.exited)return;this.exited=!0;for(let n of this.callbacks)n();if(t)if(lu&&(t!=="SIGINT"&&t!=="SIGTERM"&&t!=="SIGKILL"))ma.kill(ma.pid,"SIGTERM");else ma.kill(ma.pid,t)},this.hook=()=>{ma.once("exit",()=>this.exit());for(let t of RS)try{ma.once(t,()=>this.exit(t))}catch{}},this.register=(t)=>(this.callbacks.add(t),()=>{this.callbacks.delete(t)}),this.hook()}}var CS=new PS;var gP=CS.register,OS=gP;var Sn={store:{},create:(t)=>{let n=`000000${Math.floor(Math.random()*16777215).toString(16)}`.slice(-6),i=Date.now().toString().slice(-10),o="tmp-",a=`.tmp-${i}${n}`;return`${t}${a}`},get:(t,n,i=!0)=>{let o=Sn.truncate(n(t));if(o in Sn.store)return Sn.get(t,n,i);return Sn.store[o]=i,[o,()=>delete Sn.store[o]]},purge:(t)=>{if(!Sn.store[t])return;delete Sn.store[t],or.attempt.unlink(t)},purgeSync:(t)=>{if(!Sn.store[t])return;delete Sn.store[t],or.attempt.unlinkSync(t)},purgeSyncAll:()=>{for(let t in Sn.store)Sn.purgeSync(t)},truncate:(t)=>{let n=yP.basename(t);if(n.length<=Kp)return t;let i=/^(\.?)(.*?)((?:\.[^.]+)?(?:\.tmp-\d{10}[a-f0-9]{6})?)$/.exec(n);if(!i)return t;let o=n.length-Kp;return`${t.slice(0,-n.length)}${i[1]}${i[2].slice(0,-o)}${i[3]}`}};OS(Sn.purgeSyncAll);var gc=Sn;function Xp(t,n,i=bS){if(Jp(i))return Xp(t,n,{encoding:i});let a={timeout:i.timeout??AS},c=null,m=null,E=null;try{let _=or.attempt.realpathSync(t),I=!!_;t=_||t,[m,c]=gc.get(t,i.tmpCreate||gc.create,i.tmpPurge!==!1);let T=xS&&cu(i.chown),R=cu(i.mode);if(I&&(T||R)){let P=or.attempt.statSync(t);if(P){if(i={...i},T)i.chown={uid:P.uid,gid:P.gid};if(R)i.mode=P.mode}}if(!I){let P=wP.dirname(t);or.attempt.mkdirSync(P,{mode:SS,recursive:!0})}if(E=or.retry.openSync(a)(m,"w",i.mode||Gp),i.tmpCreated)i.tmpCreated(m);if(Jp(n))or.retry.writeSync(a)(E,n,0,i.encoding||wS);else if(!cu(n))or.retry.writeSync(a)(E,n,0,n.length,0);if(i.fsync!==!1)if(i.fsyncWait!==!1)or.retry.fsyncSync(a)(E);else or.attempt.fsync(E);if(or.retry.closeSync(a)(E),E=null,i.chown&&(i.chown.uid!==vS||i.chown.gid!==ES))or.attempt.chownSync(m,i.chown.uid,i.chown.gid);if(i.mode&&i.mode!==Gp)or.attempt.chmodSync(m,i.mode);try{or.retry.renameSync(a)(m,t)}catch(P){if(!_S(P))throw P;if(P.code!=="ENAMETOOLONG")throw P;or.retry.renameSync(a)(m,gc.truncate(t))}c(),m=null}finally{if(E)or.attempt.closeSync(E);if(m)gc.purge(m)}}var vv=g(Eb(),1),Ev=g(Mn(),1);var qC=(t,n,i,o)=>{if(i==="length"||i==="prototype")return;if(i==="arguments"||i==="caller")return;let a=Object.getOwnPropertyDescriptor(t,i),c=Object.getOwnPropertyDescriptor(n,i);if(!BC(a,c)&&o)return;Object.defineProperty(t,i,c)},BC=function(t,n){return t===void 0||t.configurable||t.writable===n.writable&&t.enumerable===n.enumerable&&t.configurable===n.configurable&&(t.writable||t.value===n.value)},WC=(t,n)=>{let i=Object.getPrototypeOf(n);if(i===Object.getPrototypeOf(t))return;Object.setPrototypeOf(t,i)},HC=(t,n)=>`/* Wrapped ${t}*/
|
|
62
|
+
${n}`,VC=Object.getOwnPropertyDescriptor(Function.prototype,"toString"),zC=Object.getOwnPropertyDescriptor(Function.prototype.toString,"name"),GC=(t,n,i)=>{let o=i===""?"":`with ${i.trim()}() `,a=HC.bind(null,o,n.toString());Object.defineProperty(a,"name",zC);let{writable:c,enumerable:m,configurable:E}=VC;Object.defineProperty(t,"toString",{value:a,writable:c,enumerable:m,configurable:E})};function rh(t,n,{ignoreNonConfigurable:i=!1}={}){let{name:o}=t;for(let a of Reflect.ownKeys(n))qC(t,n,a,i);return WC(t,n),GC(t,n,o),t}var KC=(t,n={})=>{if(typeof t!=="function")throw TypeError(`Expected the first argument to be a function, got \`${typeof t}\``);let{wait:i=0,maxWait:o=Number.POSITIVE_INFINITY,before:a=!1,after:c=!0}=n;if(i<0||o<0)throw RangeError("`wait` and `maxWait` must not be negative.");if(!a&&!c)throw Error("Both `before` and `after` are false, function wouldn't be called.");let m,E,_,I=function(...T){let R=this,P=()=>{if(m=void 0,E)clearTimeout(E),E=void 0;if(c)_=t.apply(R,T)},M=()=>{if(E=void 0,m)clearTimeout(m),m=void 0;if(c)_=t.apply(R,T)},N=a&&!m;if(clearTimeout(m),m=setTimeout(P,i),o>0&&o!==Number.POSITIVE_INFINITY&&!E)E=setTimeout(M,o);if(N)_=t.apply(R,T);return _};return rh(I,t),I.cancel=()=>{if(m)clearTimeout(m),m=void 0;if(E)clearTimeout(E),E=void 0},I},nh=KC;var ko=g(pv(),1);var ZM=Object.prototype.toString;function mv(t,n,i){if(!t)return!1;if(t.constructor===n)return!0;return ZM.call(t)===i}function gv(t){return mv(t,Uint8Array,"[object Uint8Array]")}function QM(t){return mv(t,ArrayBuffer,"[object ArrayBuffer]")}function eN(t){return gv(t)||QM(t)}function tN(t){if(!gv(t))throw TypeError(`Expected \`Uint8Array\`, got \`${typeof t}\``)}function rN(t){if(!eN(t))throw TypeError(`Expected \`Uint8Array\` or \`ArrayBuffer\`, got \`${typeof t}\``)}function Mu(t,n){if(t.length===0)return new Uint8Array(0);n??=t.reduce((a,c)=>a+c.length,0);let i=new Uint8Array(n),o=0;for(let a of t)tN(a),i.set(a,o),o+=a.length;return i}var hv={utf8:new globalThis.TextDecoder("utf8")};function xc(t,n="utf8"){return rN(t),hv[n]??=new globalThis.TextDecoder(n),hv[n].decode(t)}function nN(t){if(typeof t!=="string")throw TypeError(`Expected \`string\`, got \`${typeof t}\``)}var sN=new globalThis.TextEncoder;function Nu(t){return nN(t),sN.encode(t)}var s9=Array.from({length:256},(t,n)=>n.toString(16).padStart(2,"0"));var Sv="aes-256-cbc",Av=new Set(["aes-256-cbc","aes-256-gcm","aes-256-ctr"]),iN=(t)=>typeof t==="string"&&Av.has(t),hi=()=>Object.create(null),bv=(t)=>t!==void 0,Sh=(t,n)=>{let i=new Set(["undefined","symbol","function"]),o=typeof n;if(i.has(o))throw TypeError(`Setting a value of type \`${o}\` for key \`${t}\` is not allowed as it's not supported by JSON`)},io="__internal__",bh=`${io}.migrations.version`;class Du{path;events;#t;#e;#r;#o;#n={};#i=!1;#S;#f;#a;constructor(t={}){let n=this.#p(t);if(this.#o=n,this.#u(n),this.#s(n),this.#g(n),this.events=new EventTarget,this.#e=n.encryptionKey,this.#r=n.encryptionAlgorithm??Sv,this.path=this.#y(n),this.#h(n),n.watch)this._watch()}get(t,n){if(this.#o.accessPropertiesByDotNotation)return this._get(t,n);let{store:i}=this;return t in i?i[t]:n}set(t,n){if(typeof t!=="string"&&typeof t!=="object")throw TypeError(`Expected \`key\` to be of type \`string\` or \`object\`, got ${typeof t}`);if(typeof t!=="object"&&n===void 0)throw TypeError("Use `delete()` to clear values");if(this._containsReservedKey(t))throw TypeError(`Please don't use the ${io} key, as it's used to manage this module internal operations.`);let{store:i}=this,o=(a,c)=>{if(Sh(a,c),this.#o.accessPropertiesByDotNotation)pc(i,a,c);else{if(a==="__proto__"||a==="constructor"||a==="prototype")return;i[a]=c}};if(typeof t==="object"){let a=t;for(let[c,m]of Object.entries(a))o(c,m)}else o(t,n);this.store=i}has(t){if(this.#o.accessPropertiesByDotNotation)return au(this.store,t);return t in this.store}appendToArray(t,n){Sh(t,n);let i=this.#o.accessPropertiesByDotNotation?this._get(t,[]):(t in this.store)?this.store[t]:[];if(!Array.isArray(i))throw TypeError(`The key \`${t}\` is already set to a non-array value`);this.set(t,[...i,n])}reset(...t){for(let n of t)if(bv(this.#n[n]))this.set(n,this.#n[n])}delete(t){let{store:n}=this;if(this.#o.accessPropertiesByDotNotation)pS(n,t);else delete n[t];this.store=n}clear(){let t=hi();for(let n of Object.keys(this.#n))if(bv(this.#n[n]))if(Sh(n,this.#n[n]),this.#o.accessPropertiesByDotNotation)pc(t,n,this.#n[n]);else t[n]=this.#n[n];this.store=t}onDidChange(t,n){if(typeof t!=="string")throw TypeError(`Expected \`key\` to be of type \`string\`, got ${typeof t}`);if(typeof n!=="function")throw TypeError(`Expected \`callback\` to be of type \`function\`, got ${typeof n}`);return this._handleValueChange(()=>this.get(t),n)}onDidAnyChange(t){if(typeof t!=="function")throw TypeError(`Expected \`callback\` to be of type \`function\`, got ${typeof t}`);return this._handleStoreChange(t)}get size(){return Object.keys(this.store).filter((n)=>!this._isReservedKeyPath(n)).length}get store(){try{let t=pi.readFileSync(this.path,this.#e?null:"utf8"),n=this._decryptData(t);return((o)=>{let a=this._deserialize(o);if(!this.#i)this._validate(a);return Object.assign(hi(),a)})(n)}catch(t){if(t?.code==="ENOENT")return this._ensureDirectory(),hi();if(this.#o.clearInvalidConfig){let n=t;if(n.name==="SyntaxError")return hi();if(n.message?.startsWith("Config schema violation:"))return hi();if(n.message==="Failed to decrypt config data.")return hi()}throw t}}set store(t){if(this._ensureDirectory(),!au(t,io))try{let n=pi.readFileSync(this.path,this.#e?null:"utf8"),i=this._decryptData(n),o=this._deserialize(i);if(au(o,io))pc(t,io,Bp(o,io))}catch{}if(!this.#i)this._validate(t);this._write(t),this.events.dispatchEvent(new Event("change"))}*[Symbol.iterator](){for(let[t,n]of Object.entries(this.store))if(!this._isReservedKeyPath(t))yield[t,n]}_closeWatcher(){if(this.#S)this.#S.close(),this.#S=void 0;if(this.#f)pi.unwatchFile(this.path),this.#f=!1;this.#a=void 0}_decryptData(t){let n=this.#e;if(!n)return typeof t==="string"?t:xc(t);let i=this.#r,o=i==="aes-256-gcm"?16:0,a=":".codePointAt(0),c=typeof t==="string"?t.codePointAt(16):t[16];if(!(a!==void 0&&c===a)){if(i==="aes-256-cbc")return typeof t==="string"?t:xc(t);throw Error("Failed to decrypt config data.")}let E=(P)=>{if(o===0)return{ciphertext:P};let M=P.length-o;if(M<0)throw Error("Invalid authentication tag length.");return{ciphertext:P.slice(0,M),authenticationTag:P.slice(M)}},_=t.slice(0,16),I=t.slice(17),T=typeof I==="string"?Nu(I):I,R=(P)=>{let{ciphertext:M,authenticationTag:N}=E(T),H=_c.pbkdf2Sync(n,P,1e4,32,"sha512"),Z=_c.createDecipheriv(i,H,_);if(N)Z.setAuthTag(N);return xc(Mu([Z.update(M),Z.final()]))};try{return R(_)}catch{try{return R(_.toString())}catch{}}if(i==="aes-256-cbc")return typeof t==="string"?t:xc(t);throw Error("Failed to decrypt config data.")}_handleStoreChange(t){let n=this.store,i=()=>{let o=n,a=this.store;if(yv(a,o))return;n=a,t.call(this,a,o)};return this.events.addEventListener("change",i),()=>{this.events.removeEventListener("change",i)}}_handleValueChange(t,n){let i=t(),o=()=>{let a=i,c=t();if(yv(c,a))return;i=c,n.call(this,c,a)};return this.events.addEventListener("change",o),()=>{this.events.removeEventListener("change",o)}}_deserialize=(t)=>JSON.parse(t);_serialize=(t)=>JSON.stringify(t,void 0,"\t");_validate(t){if(!this.#t)return;if(this.#t(t)||!this.#t.errors)return;let i=this.#t.errors.map(({instancePath:o,message:a=""})=>`\`${o.slice(1)}\` ${a}`);throw Error("Config schema violation: "+i.join("; "))}_ensureDirectory(){pi.mkdirSync($u.dirname(this.path),{recursive:!0})}_write(t){let n=this._serialize(t),i=this.#e;if(i){let o=_c.randomBytes(16),a=_c.pbkdf2Sync(i,o,1e4,32,"sha512"),c=_c.createCipheriv(this.#r,a,o),m=Mu([c.update(Nu(n)),c.final()]),E=[o,Nu(":"),m];if(this.#r==="aes-256-gcm")E.push(c.getAuthTag());n=Mu(E)}if(wh.env.SNAP)pi.writeFileSync(this.path,n,{mode:this.#o.configFileMode});else try{Xp(this.path,n,{mode:this.#o.configFileMode})}catch(o){if(o?.code==="EXDEV"){pi.writeFileSync(this.path,n,{mode:this.#o.configFileMode});return}throw o}}_watch(){if(this._ensureDirectory(),!pi.existsSync(this.path))this._write(hi());if(wh.platform==="win32"||wh.platform==="darwin"){this.#a??=nh(()=>{this.events.dispatchEvent(new Event("change"))},{wait:100});let t=$u.dirname(this.path),n=$u.basename(this.path);this.#S=pi.watch(t,{persistent:!1,encoding:"utf8"},(i,o)=>{if(o&&o!==n)return;if(typeof this.#a==="function")this.#a()})}else this.#a??=nh(()=>{this.events.dispatchEvent(new Event("change"))},{wait:1000}),pi.watchFile(this.path,{persistent:!1},(t,n)=>{if(typeof this.#a==="function")this.#a()}),this.#f=!0}_migrate(t,n,i){let o=this._get(bh,"0.0.0"),a=Object.keys(t).filter((m)=>this._shouldPerformMigration(m,o,n)),c=structuredClone(this.store);for(let m of a)try{if(i)i(this,{fromVersion:o,toVersion:m,finalVersion:n,versions:a});let E=t[m];E?.(this),this._set(bh,m),o=m,c=structuredClone(this.store)}catch(E){this.store=c;let _=E instanceof Error?E.message:String(E);throw Error(`Something went wrong during the migration! Changes applied to the store until this failed migration will be restored. ${_}`)}if(this._isVersionInRangeFormat(o)||!ko.default.eq(o,n))this._set(bh,n)}_containsReservedKey(t){if(typeof t==="string")return this._isReservedKeyPath(t);if(!t||typeof t!=="object")return!1;return this._objectContainsReservedKey(t)}_objectContainsReservedKey(t){if(!t||typeof t!=="object")return!1;for(let[n,i]of Object.entries(t)){if(this._isReservedKeyPath(n))return!0;if(this._objectContainsReservedKey(i))return!0}return!1}_isReservedKeyPath(t){return t===io||t.startsWith(`${io}.`)}_isVersionInRangeFormat(t){return ko.default.clean(t)===null}_shouldPerformMigration(t,n,i){if(this._isVersionInRangeFormat(t)){if(n!=="0.0.0"&&ko.default.satisfies(n,t))return!1;return ko.default.satisfies(i,t)}if(ko.default.lte(t,n))return!1;if(ko.default.gt(t,i))return!1;return!0}_get(t,n){return Bp(this.store,t,n)}_set(t,n){let{store:i}=this;pc(i,t,n),this.store=i}#p(t){let n={configName:"config",fileExtension:"json",projectSuffix:"nodejs",clearInvalidConfig:!1,accessPropertiesByDotNotation:!0,configFileMode:438,...t};if(n.encryptionAlgorithm??=Sv,!iN(n.encryptionAlgorithm))throw TypeError(`The \`encryptionAlgorithm\` option must be one of: ${[...Av].join(", ")}`);if(!n.cwd){if(!n.projectName)throw Error("Please specify the `projectName` option.");n.cwd=Vp(n.projectName,{suffix:n.projectSuffix}).config}if(typeof n.fileExtension==="string")n.fileExtension=n.fileExtension.replace(/^\.+/,"");return n}#u(t){if(!(t.schema??t.ajvOptions??t.rootSchema))return;if(t.schema&&typeof t.schema!=="object")throw TypeError("The `schema` option must be an object.");let n=Ev.default.default,i=new vv.Ajv2020({allErrors:!0,useDefaults:!0,...t.ajvOptions});n(i);let o={...t.rootSchema,type:"object",properties:t.schema};this.#t=i.compile(o),this.#c(t.schema)}#c(t){let n=Object.entries(t??{});for(let[i,o]of n){if(!o||typeof o!=="object")continue;if(!Object.hasOwn(o,"default"))continue;let{default:a}=o;if(a===void 0)continue;this.#n[i]=a}}#s(t){if(t.defaults)Object.assign(this.#n,t.defaults)}#g(t){if(t.serialize)this._serialize=t.serialize;if(t.deserialize)this._deserialize=t.deserialize}#y(t){let n=typeof t.fileExtension==="string"?t.fileExtension:void 0,i=n?`.${n}`:"";return $u.resolve(t.cwd,`${t.configName??"config"}${i}`)}#h(t){if(t.migrations){this.#d(t),this._validate(this.store);return}let n=this.store,i=Object.assign(hi(),t.defaults??{},n);this._validate(i);try{wv.deepEqual(n,i)}catch{this.store=i}}#d(t){let{migrations:n,projectVersion:i}=t;if(!n)return;if(!i)throw Error("Please specify the `projectVersion` option.");this.#i=!0;try{let o=this.store,a=Object.assign(hi(),t.defaults??{},o);try{wv.deepEqual(o,a)}catch{this._write(a)}this._migrate(n,i,t.beforeEachMigration)}finally{this.#i=!1}}}var oN=["autoUpdateSkills","showOnboarding"];function _v(t){let n={};for(let i of oN)if(t[i]!==void 0)n[i]=t[i];return n}var aN=x,xv=null;function Iv(){return xv??=new Du({cwd:aN,configName:"settings",schema:{autoUpdateSkills:{type:"boolean",default:!1},showOnboarding:{type:"boolean",default:!0}}}),xv}function Lu(){return Iv().store}function Tv(t){let n=Iv();if(Object.keys(t).length>0)n.set(t);return n.store}import{mkdir as lN,rename as uN,readFile as dN}from"fs/promises";import{existsSync as fN}from"fs";import{basename as pN,join as Uu}from"path";var Rv=s({message:r().trim().min(1).max(50)}).strict();async function Ic(t){let n=await Ft(t);return{name:n.name,icon:n.icon}}async function mi(t,n){let{layout:i}=await Ve(t,(o)=>{let a={...o};if(n.name!==void 0)if(n.name)a.name=n.name;else delete a.name;if(n.icon!==void 0)if(n.icon)a.icon=n.icon;else delete a.icon;return a});return i}function ju(t,n){return["Build a new view from this message. Follow the pending view steps in the moi-workspace skill.",`The view id is \`${t}\`. Write the view source to \`.moi/views/${t}.tsx\`.`,`Before building, set a provisional title and icon: \`moi views set ${t} --title "<title>" --icon <icon-id>\`. Use sentence case for the title.`,`Available view icons: ${n.join(", ")}`,'If the user asks for an additional view, create it with: `moi views create --requirements "<complete requirements>"`.']}import{join as cN}from"path";function Pv(t,n){return cN(ye(t,n),"moi-workspace","references","COLLAB.md")}async function Cv(t,n){if(p().environment!=="cloud")return;let i=Pv(t,n);return await Bun.file(i).exists()?i:void 0}async function va(t,n){let i=nr(t.id);try{let{getWorkspace:o}=await import("./chunk-sxs483zn.js"),a=await o(t.id);if(a&&(a.harness??"claude-code")!==(t.harness??"claude-code"))throw new ae("Agent changed. Start a new chat");let{prepareWorkspaceHarness:c}=await import("./chunk-tbwma23z.js");await c(t);let{viewBuildId:m,...E}=n,_=ee(t.id,n.sessionId),I=await Or(t,_),T=n.context?.activeTab?.id??I.tabId??"overview",R=m??(n.isNew?xn(T):void 0),P=R?[]:(await _t(t)).filter((V)=>V.buildSessionId===_),M=R?await Ht(t,R):P.find((V)=>V.id===xn(T))??P[0],N=M&&(m===M.id||n.isNew);if(N&&M.buildSessionId&&M.buildSessionId!==_&&(M.status==="starting"||y(t).activeSessions().some((V)=>V.workspaceId===t.id&&V.sessionId===M.buildSessionId)))throw new U("This view is already being built in another chat",409);if(n.isNew&&I.tabId!==T)I.tabId=T==="overview"?void 0:T,await mt(t,_,{tabId:I.tabId}),await $e(t,_,T,null);if(N)await et(t,M.id,{buildSessionId:_});let H=await Cv(t.path,t.harness),Z=await qr(t);if(await y(t).sendMessage({...E,sessionId:_,context:{...n.context,workspaceMode:t.remote?"remote":"local",session:{id:_,tabId:I.tabId,pinned:Z===_},...H?{collabReference:H}:{},directives:[...n.context?.directives??[],...N?ju(M.id,Se):[],...N&&I.fork?["Inherited conversation is background. Work on the current request; do not resume unrelated earlier tasks."]:[],...M&&n.isNew&&M.requirements!==n.content?[`Original view requirements:
|
|
63
|
+
${M.requirements}`]:[],...M&&n.attachments?.length?["Use the attachments as reference material for the intended view."]:[]]}}),M&&M.status!=="starting")await et(t,M.id,{status:"submitted",error:void 0})}finally{i()}}var Ov=s({name:r().trim().min(1).max(100),description:r().trim().min(1).max(500),features:u(r().trim().min(1).max(500)).min(1).max(6)}).strict(),kv=s({name:r().trim().min(1).max(24),icon:F(Se),theme:s({font:F(Object.keys(le)),color:F(Object.keys(ce))}).strict(),description:r().trim().min(1).max(200),views:u(Ov.extend({icon:F(Se)})).length(3),widgets:u(Ov).max(4)}).strict(),Mv=kv.extend({id:r().uuid()}),vh=s({options:u(kv).length(3)}).strict();function Nv(t){let n=vh.parse(t);if(new Set(n.options.map((i)=>i.name.toLowerCase())).size!==3)throw Error("The agent returned duplicate ideas. Try again");if(new Set(n.options.map((i)=>i.theme.font)).size!==3||new Set(n.options.map((i)=>i.theme.color)).size!==3)throw Error("Each idea needs a different font and color. Try again");return n.options.map((i)=>({...i,id:crypto.randomUUID()}))}function $v(t,n){if(!n.length)return`## ${t}
|
|
64
64
|
None planned.`;return`## ${t}
|
|
65
65
|
${n.map((i)=>[`### ${i.name}`,..."icon"in i?[`Use view icon: ${i.icon}`]:[],i.description,...i.features.map((o)=>`- ${o}`)].join(`
|
|
66
66
|
`)).join(`
|
|
@@ -72,12 +72,12 @@ Font: ${t.theme.font}
|
|
|
72
72
|
Color: ${t.theme.color}
|
|
73
73
|
These workspace presets are already configured; use the existing theme tokens.`,$v("Views",t.views),$v("Overview widgets",t.widgets),"Follow the workspace instructions and use the normal Moi tools to create the views and widgets. Keep this Overview chat as the main coordination chat and use each view\u2019s own build chat. Link to the views here so the user can follow their progress. Preserve the configured workspace name and icon. Use available data sources honestly and explain any access limitations."].join(`
|
|
74
74
|
|
|
75
|
-
`)}var hN={directory:Uu(x,"onboarding"),workspacesRoot:Ce,provisionWorkspace:J,registerWorkspace:z,getWorkspace:q,setWorkspaceConfig:mi,publishEvent:h,harnessFor:y,sendWorkspaceMessage:va,saveSelectedSession
|
|
75
|
+
`)}var hN={directory:Uu(x,"onboarding"),workspacesRoot:Ce,provisionWorkspace:J,registerWorkspace:z,getWorkspace:q,setWorkspaceConfig:mi,publishEvent:h,harnessFor:y,sendWorkspaceMessage:va,saveSelectedSession:$e,resolveRenamedSession:ee,readWorkspaceState:ne};function mN(t={}){let n={...hN,...t},i=new Map,o=new Map;function a(P){return Uu(n.directory,`${P}.json`)}async function c(P){try{return JSON.parse(await dN(a(P),"utf8"))}catch(M){if(M.code==="ENOENT")return;throw M}}async function m(P,M){await lN(n.directory,{recursive:!0});let N=a(P),H=`${N}.${crypto.randomUUID()}.tmp`;await Bun.write(H,JSON.stringify(M)),await uN(H,N)}function E(P,M){let N=(o.get(P)??Promise.resolve()).catch(()=>{}).then(M);return o.set(P,N),N.finally(()=>{if(o.get(P)===N)o.delete(P)}).catch(()=>{}),N}async function _(P){let M=P;return E(M,async()=>{i.get(M)?.abort(),await m(M,{status:"failed",error:"Discovery cancelled"})})}async function I(P){if(!P.runId||!P.harness)throw Error("Choose an agent first");let M=P.runId;return E(M,async()=>{let N=await c(M);if(N){if(N.status==="done"&&!N.ideas?.every((te)=>Mv.safeParse(te).success))return{status:"failed",error:"These ideas use an older format. Find ideas again"};if(N.status==="running"&&!i.has(M))return{status:"failed",error:"Discovery was interrupted. Try again"};return N}let H=n.harnessFor(P.harness);if(!H.runAction){let te={status:"failed",error:"This agent does not support ephemeral actions"};return await m(M,te),te}let Z=new AbortController;i.set(M,Z);let V={status:"running"};try{await m(M,V)}catch(te){throw i.delete(M),te}let me=setTimeout(()=>Z.abort(),180000);return Promise.resolve().then(async()=>{let te=Date.now(),we=(De)=>new Date(te-De*86400000).toISOString().slice(0,10),Te=`Research dates (UTC): today ${we(0)}; last 30 days start ${we(30)}; last 60 days start ${we(60)}.`;return H.runAction({model:"fast",prompt:`${Te}
|
|
76
76
|
|
|
77
|
-
${await Bun.file(v("server","onboarding","prompt.md")).text()}`,resultSchema:vh,progressSchema:Rv,onProgress:($e)=>E(M,async()=>{let Ue=await c(M);if(!Z.signal.aborted&&Ue?.status==="running")await m(M,{...Ue,progress:$e})}),signal:Z.signal})}).then((te)=>({status:"done",ideas:Nv(te)})).catch((te)=>({status:"failed",error:Z.signal.aborted?"Discovery stopped. Try again":String(te instanceof Error?te.message:te)})).then((te)=>E(M,async()=>{if((await c(M))?.status==="running")await m(M,te)})).finally(()=>{clearTimeout(me),i.delete(M)}).catch((te)=>console.error("[onboarding] could not save action result",te)),V})}async function T(P,M=!1){let N=P.operationId;return E(N,async()=>{let H=await c(N);if(H?.status==="done"||i.has(N))return H;if(H?.status==="failed"&&!M)return H;let Z=new AbortController;i.set(N,Z);let V={...H,status:"running",error:void 0,sessionId:H?.sessionId??crypto.randomUUID()};try{await m(N,V)}catch(me){throw i.delete(N),me}return R(N,P,V).catch(async(me)=>{await m(N,{...await c(N),status:"failed",error:me instanceof Error?me.message:String(me)})}).finally(()=>i.delete(N)).catch((me)=>console.error("[onboarding] could not save workspace result",me)),V})}async function R(P,M,N){let H=M.idea;if(!N.workspacePath){let Ue=n.workspacesRoot(),Ct=Uu(Ue,`onboarding-${P}`);if(fN(Ct))N.workspacePath=Ct;else N.workspacePath=await pr(H.name,Ue,n.getWorkspace);await m(P,N)}let Z=N.workspacePath;if(await n.provisionWorkspace(Z,M.harness),!N.workspaceId)await n.setWorkspaceConfig(Z,{name:H.name,icon:{type:"glyph",value:H.icon,background:"theme"}}),await ze(Z,(Ue)=>({...Ue,theme:Xe({...Ue.theme,...H.theme})}));let V=await n.registerWorkspace(Z,{id:N.workspaceId??pN(Z),harness:M.harness,name:H.name});N.workspaceId=V.id,await m(P,N);let me=Uu(Z,"onboarding-brief.md"),te=N.stage?await Bun.file(me).text():Dv(H);await Bun.write(me,te),n.publishEvent({type:"workspaces-list:changed"});let we=n.harnessFor(V);if(N.stage==="sending"||N.stage==="accepted"){let Ue=await we.listSessions(V);for(let Ot of Ue)if((await we.sessionEvents(V,Ot.sessionId)).some((Qr)=>Qr.kind==="turn"&&Qr.turn.role==="user"&&Qr.turn.parts.some((cd)=>cd.type==="text"&&cd.text.includes(te)))){N.sessionId=Ot.sessionId,await n.saveSelectedSession(V,Ot.sessionId),await m(P,{...N,status:"done",stage:"accepted"});return}let Ct=await n.readWorkspaceState(V);if(N.sessionId=Ct.selected.overview??N.sessionId,we.activeSessions().some((Ot)=>Ot.workspaceId===V.id))throw Error("The agent is still starting. Wait a moment and try again");if(N.stage==="sending")throw Error("Could not confirm the first message. Check the chat before sending the saved onboarding brief")}let Te=await we.authStatus?.();if(Te&&Te.status!=="available")throw Error("Reconnect the agent, then retry starting the workspace");await n.saveSelectedSession(V,N.sessionId),N.stage="sending",await m(P,N);let $e;try{await Promise.race([n.sendWorkspaceMessage(V,{workspaceId:V.id,workspacePath:V.path,sessionId:N.sessionId,isNew:!0,content:te,optimisticId:M.operationId,context:{activeTab:{id:"overview"}}}),new Promise((Ue,Ct)=>{$e=setTimeout(()=>Ct(Error("Could not confirm the first message. Check the chat before retrying")),90000)})])}finally{clearTimeout($e)}N.sessionId=n.resolveRenamedSession(V.id,N.sessionId),await n.saveSelectedSession(V,N.sessionId),await m(P,{...N,status:"done",stage:"accepted"})}return{discoverIdeas:I,cancelIdeas:_,createFromIdea:T}}var{discoverIdeas:Eh,cancelIdeas:Lv,createFromIdea:jv}=mN();var Uv=s({harness:F(["claude-code","codex"]),runId:r().uuid()}),gN=Uv.extend({ideaId:r().uuid(),operationId:r().uuid(),retry:k().optional()}),Ea=new Bs;Ea.use("*",async(t,n)=>{if(p().demo||!Lu().showOnboarding)return t.json({error:"Onboarding is not enabled"},403);t.header("Cache-Control","no-store"),await n()});Ea.post("/discover",async(t)=>{let n=Uv.safeParse(await t.req.json().catch(()=>{return}));if(!n.success)return t.json({error:"Invalid discovery request"},400);return t.json(await Eh(n.data))});Ea.post("/cancel",async(t)=>{let n=s({runId:r().uuid()}).safeParse(await t.req.json().catch(()=>{return}));if(!n.success)return t.json({error:"Invalid discovery request"},400);return await Lv(n.data.runId),t.json({status:"done"})});Ea.post("/create",async(t)=>{let n=gN.safeParse(await t.req.json().catch(()=>{return}));if(!n.success)return t.json({error:"Invalid workspace request"},400);let{harness:i,runId:o,ideaId:a,operationId:c,retry:m}=n.data,E=await Eh({harness:i,runId:o}),_=E.ideas?.find((I)=>I.id===a);if(E.status!=="done"||!_)return t.json({error:"Choose an available idea"},409);return t.json(await jv({harness:i,operationId:c,idea:_},m))});import{stat as vN}from"fs/promises";import{join as EN}from"path";var Fv=/^\s*(?:text\/(?!event-stream(?:[;\s]|$))[^;\s]+|application\/(?:javascript|json|xml|xml-dtd|ecmascript|dart|msgpack|postscript|rtf|tar|toml|vnd\.dart|vnd\.ms-fontobject|vnd\.ms-opentype|vnd\.msgpack|wasm|x-httpd-php|x-javascript|x-msgpack|x-ns-proxy-autoconfig|x-sh|x-tar|x-virtualbox-hdd|x-virtualbox-ova|x-virtualbox-ovf|x-virtualbox-vbox|x-virtualbox-vdi|x-virtualbox-vhd|x-virtualbox-vmdk|x-www-form-urlencoded)|font\/(?:otf|ttf)|image\/(?:bmp|vnd\.adobe\.photoshop|vnd\.microsoft\.icon|vnd\.ms-dds|x-icon|x-ms-bmp)|message\/rfc822|model\/gltf-binary|x-shader\/x-fragment|x-shader\/x-vertex|[^;\s]+?\+(?:json|text|xml|yaml|msgpack))(?:[;\s]|$)/i;var Ah=(t,n=wN)=>{let i=/\.([a-zA-Z0-9]+?)$/,o=t.match(i);if(!o)return;return n[o[1].toLowerCase()]};var yN={aac:"audio/aac",avi:"video/x-msvideo",avif:"image/avif",av1:"video/av1",bin:"application/octet-stream",bmp:"image/bmp",css:"text/css; charset=utf-8",csv:"text/csv; charset=utf-8",eot:"application/vnd.ms-fontobject",epub:"application/epub+zip",gif:"image/gif",gz:"application/gzip",htm:"text/html; charset=utf-8",html:"text/html; charset=utf-8",ico:"image/x-icon",ics:"text/calendar; charset=utf-8",jpeg:"image/jpeg",jpg:"image/jpeg",js:"text/javascript; charset=utf-8",json:"application/json",jsonld:"application/ld+json",map:"application/json",mid:"audio/x-midi",midi:"audio/x-midi",mjs:"text/javascript; charset=utf-8",mp3:"audio/mpeg",mp4:"video/mp4",mpeg:"video/mpeg",oga:"audio/ogg",ogv:"video/ogg",ogx:"application/ogg",opus:"audio/opus",otf:"font/otf",pdf:"application/pdf",png:"image/png",rtf:"application/rtf",svg:"image/svg+xml; charset=utf-8",tif:"image/tiff",tiff:"image/tiff",ts:"video/mp2t",ttf:"font/ttf",txt:"text/plain; charset=utf-8",wasm:"application/wasm",webm:"video/webm",weba:"audio/webm",webmanifest:"application/manifest+json",webp:"image/webp",woff:"font/woff",woff2:"font/woff2",xhtml:"application/xhtml+xml; charset=utf-8",xml:"application/xml; charset=utf-8",zip:"application/zip","3gp":"video/3gpp","3g2":"video/3gpp2",gltf:"model/gltf+json",glb:"model/gltf-binary"},wN=yN;var qv=(...t)=>{let n=t.filter((a)=>a!=="").join("/");n=n.replace(/(?<=\/)\/+/g,"");let i=n.split("/"),o=[];for(let a of i)if(a===".."&&o.length>0&&o.at(-1)!=="..")o.pop();else if(a!==".")o.push(a);return o.join("/")||"."};var Bv={br:".br",zstd:".zst",gzip:".gz"},SN=Object.keys(Bv),bN="index.html",Wv=(t)=>{let n=t.root??"./",i=t.path,o=t.join??qv;return async(a,c)=>{if(a.finalized)return c();let m;if(t.path)m=t.path;else try{if(m=Cp(a.req.path),/(?:^|[\/\\])\.{1,2}(?:$|[\/\\])|[\/\\]{2,}|\\/.test(m))throw Error()}catch{return await t.onNotFound?.(a.req.path,a),c()}let E=o(n,!i&&t.rewriteRequestPath?t.rewriteRequestPath(m):m);if(t.isDir&&await t.isDir(E))E=o(E,bN);let _=t.getContent,I=await _(E,a);if(I instanceof Response)return a.newResponse(I.body,I);if(I!=null){let T=t.mimes&&Ah(E,t.mimes)||Ah(E);if(a.header("Content-Type",T||"application/octet-stream"),t.precompressed&&(!T||Fv.test(T))){let R=new Set(a.req.header("Accept-Encoding")?.split(",").map((P)=>P.trim()));for(let P of SN){if(!R.has(P))continue;let M=await _(E+Bv[P],a);if(M){I=M,a.header("Content-Encoding",P),a.header("Vary","Accept-Encoding",{append:!0});break}}}return await t.onFound?.(E,a),a.body(I)}await t.onNotFound?.(E,a),await c();return}};var xh=(t={})=>async function(i,o){return Wv({...t,getContent:async(m)=>{let E=Bun.file(m);return await E.exists()?E:null},join:EN,isDir:async(m)=>{let E;try{E=(await vN(m)).isDirectory()}catch{}return E}})(i,o)};var _h="x-hono-disable-ssg",VG=(()=>{try{return new Response("SSG is disabled",{status:404,headers:{[_h]:"true"}})}catch{return null}})();var{write:T7}=Bun;var Hv=(t)=>(...n)=>{if(typeof n[0]==="function"){let[i,o]=n;return async function(c,m){let E=await i(c),_=await t(c,E,o);if(_)return _;await m()}}else{let[i,o,a]=n;return(async()=>{let c=await t(i,o,a);if(!c)throw Error("Failed to upgrade WebSocket");return c})()}};var Fu=(t)=>("server"in t.env)?t.env.server:t.env;var _N=Hv((t,n)=>{let i=Fu(t);if(!i)throw TypeError("env has to include the 2nd argument of fetch.");if(i.upgrade(t.req.raw,{data:{events:n,url:new URL(t.req.url),protocol:t.req.header("sec-websocket-protocol")?.split(",")[0]?.trim()??""}}))return new Response(null);return});var Vv=(t)=>t;import{existsSync as k$}from"fs";import{basename as XE,resolve as M$}from"path";var zv="Wait for active agents to finish, or stop them before updating Moi";var IN="cf-access-jwt-assertion",TN="CF_Authorization",RN=new Set(["ERR_JOSE_GENERIC","ERR_JWKS_INVALID","ERR_JWKS_TIMEOUT"]);function PN(t,n){let i=new URL("/cdn-cgi/access/certs",t.teamDomain),o=Xh(i,n?{[dd]:n}:{});return async(a)=>{try{let{payload:c}=await Kh(a,o,{issuer:t.teamDomain,audience:[...t.audience],algorithms:["RS256"],requiredClaims:["exp"],clockTolerance:60}),{sub:m,email:E}=c;return m&&typeof E==="string"&&E?{id:m,email:E}:null}catch(c){if(!(c instanceof G)||RN.has(c.code))console.error(`[moi] Cloudflare Access: could not load signing keys from ${i}: ${c}`);return null}}}function CN({id:t,email:n}){let i={id:t,color:Ui(t),email:n};return br(i)?i:null}var Ih=null;async function qu(t){let n=p().cloudflareAccess;if(!n)return{};if(Ih?.config!==n)Ih={config:n,verify:PN(n)};let i=t.headers.get(IN)??new Bun.CookieMap(t.headers.get("cookie")??"").get(TN),o=i?await Ih.verify(i):null,a=o?CN(o):null;return a?{provider:"cloudflare-access",profile:a}:{provider:"cloudflare-access"}}import{realpath as Gv}from"fs/promises";import{tmpdir as ON}from"os";import{resolve as Bu}from"path";class Gs extends Error{code;constructor(t,n){super(n);this.code=t}}function kN(t,n){if(!n||t.type!=="join"&&t.type!=="profile")return t;return t.profile.id===n.id?{...t,profile:n}:null}class Kv{options;slots=new Map;bindings=new Map;failures=new Map;livenessTimer=null;closed=!1;constructor(t={}){this.options=t}emit(t,n){if(t.closed)return;if((t.socket.getBufferedAmount?.()??0)>1048576){this.disconnect(t,"Collab updates need a fresh connection");return}try{if(t.socket.send(JSON.stringify(n))===0)this.disconnect(t,"Connection lost")}catch{this.disconnect(t,"Connection lost")}}send(t,n){if(t.stopping)throw new Gs("restarting","Collab is restarting");t.child.send(n)}async getSlot(t,n){if(this.closed||n.closed)throw new Gs("unavailable","Collab connection closed");let i=await Gv(t);if(n.workspacePaths.add(i),n.closed)throw new Gs("unavailable","Collab connection closed");if(!(this.options.enabled?await this.options.enabled(i):p().environment==="cloud"))throw new Gs("unavailable","Collaboration is only available in the cloud environment");if(this.closed||n.closed)throw new Gs("unavailable","Collab connection closed");let a=this.slots.get(i);if(a){if(a.stopping){if(await a.child.exited,this.slots.get(i)===a)this.slots.delete(i);return this.getSlot(i,n)}if(a.idleTimer)clearTimeout(a.idleTimer);return a.idleTimer=void 0,a.workspacePaths.add(Bu(t)),a}let c=this.failures.get(i);if(c&&c.retryAfter>Date.now())throw new Gs("restarting","Collab is recovering; reconnect shortly");let m=this.spawn(i);return m.workspacePaths.add(Bu(t)),m}spawn(t){let n=()=>{},i=()=>{},o=new Promise((m,E)=>{n=m,i=E});o.catch(()=>{});let a=crypto.randomUUID(),c={workspacePath:t,workspacePaths:new Set([t]),generation:a,child:void 0,ready:o,resolveReady:n,rejectReady:i,readyTimer:setTimeout(()=>{c.rejectReady(new Gs("startup_timeout","Collab did not start in time")),this.stopSlot(c,"Collab startup timed out")},this.options.startupTimeoutMs??1e4),stopping:!1,clients:new Map};try{c.child=Bun.spawn([process.execPath,this.options.workerPath??he("collab/worker.ts")],{cwd:ON(),env:{PATH:process.env.PATH,MOI_COLLAB_WORKSPACE:t,MOI_COLLAB_GENERATION:a},stdout:"inherit",stderr:"inherit",ipc:(m)=>this.receive(c,m),onExit:()=>this.exited(c)}),this.slots.set(t,c)}catch(m){throw clearTimeout(c.readyTimer),i(m instanceof Error?m:Error("Collab could not start")),m}return c}receive(t,n){if(t.stopping||n.generation!==t.generation)return;if(n.type==="ready"){clearTimeout(t.readyTimer),t.resolveReady();return}if(n.type==="client"){let i=t.clients.get(n.connectionId);if(i){if(this.emit(i,n.message),n.message.type==="welcome"&&i.workspaceId)this.emit(i,Dc(i.workspaceId))}return}}exited(t){let n=t.stopping;if(t.stopping=!0,clearTimeout(t.readyTimer),t.idleTimer)clearTimeout(t.idleTimer);let i=new Gs("worker_exited","Collab restarted; reconnect to restore presence");t.rejectReady(i);for(let o of[...t.clients.values()])this.disconnect(o,i.message);if(this.slots.get(t.workspacePath)===t)this.slots.delete(t.workspacePath);if(!n){let o=(this.failures.get(t.workspacePath)?.count??0)+1;this.failures.set(t.workspacePath,{count:o,retryAfter:Date.now()+Math.min(250*2**Math.min(o-1,7),30000)})}}scheduleIdle(t){if(t.stopping||t.clients.size||t.idleTimer)return;t.idleTimer=setTimeout(()=>this.stopSlot(t,"Collab workspace is idle"),this.options.idleTimeoutMs??60000),t.idleTimer.unref()}stopSlot(t,n){if(t.stopping)return;t.stopping=!0,clearTimeout(t.readyTimer),t.rejectReady(new Gs("restarting",n));for(let o of[...t.clients.values()])this.disconnect(o,n);try{t.child.send({type:"shutdown"})}catch{}let i=setTimeout(()=>t.child.kill("SIGKILL"),2000);i.unref(),t.child.exited.finally(()=>clearTimeout(i))}disconnect(t,n){if(t.closed)return;this.close(t.socket),t.socket.close(1012,n.slice(0,120))}open(t,n,i={}){let o={socket:t,workspacePaths:new Set([Bu(n)]),connectionId:crypto.randomUUID(),closed:!1,lastSeen:Date.now(),joined:!1,...i,queue:Promise.resolve()};this.bindings.set(t,o),o.queue=this.getSlot(n,o).then(async(a)=>{if(o.closed){this.scheduleIdle(a);return}o.slot=a,a.clients.set(o.connectionId,o),await a.ready}).catch((a)=>{this.emit(o,{type:"error",code:"unavailable",message:a instanceof Error?a.message:"Collab unavailable"}),this.disconnect(o,"Collab unavailable")}),this.livenessTimer??=setInterval(()=>{let a=Date.now();for(let c of this.bindings.values()){let m=c.joined?this.options.livenessTimeoutMs??60000:15000;if(a-c.lastSeen>m)this.disconnect(c,"Collab connection timed out")}},5000),this.livenessTimer.unref()}message(t,n){let i=this.bindings.get(t);if(!i||i.closed)return;if((typeof n==="string"?new TextEncoder().encode(n).length:n.byteLength)>Ki){this.disconnect(i,"Collab message is too large");return}let a;try{a=JSON.parse(typeof n==="string"?n:new TextDecoder().decode(n))}catch{}if(!Gi(a)){this.emit(i,{type:"error",code:"invalid_message",message:"Invalid collab message"});return}i.lastSeen=Date.now();let c=kN(a,i.verifiedProfile);if(!c){this.emit(i,{type:"error",code:"user_mismatch",message:"Presence here uses your Cloudflare Access user"}),this.disconnect(i,"User does not match Cloudflare Access");return}i.queue=i.queue.then(()=>{if(i.closed||!i.slot)return;if(c.type==="join")i.joined=!0;this.send(i.slot,{type:"client",connectionId:i.connectionId,message:c})}).catch(()=>this.disconnect(i,"Collab restarted"))}close(t){let n=this.bindings.get(t);if(!n)return;if(n.closed=!0,this.bindings.delete(t),!this.bindings.size&&this.livenessTimer)clearInterval(this.livenessTimer),this.livenessTimer=null;let i=n.slot;if(!i)return;if(i.clients.delete(n.connectionId),!i.stopping)try{this.send(i,{type:"leave",connectionId:n.connectionId})}catch{}this.scheduleIdle(i)}async stopWorkspace(t){let n=Bu(t),i=[...this.slots.values()].find((a)=>a.workspacePaths.has(n)),o=(a)=>{for(let c of this.bindings.values())if(c.workspacePaths.has(a))this.disconnect(c,"Collab stopped for this workspace")};if(o(n),i)o(i.workspacePath);if(!i)try{let a=await Gv(t);o(a),i=this.slots.get(a)}catch(a){if(a instanceof Error&&"code"in a&&(a.code==="ENOENT"||a.code==="ENOTDIR"))return;throw a}if(!i)return;this.stopSlot(i,"Collab stopped for this workspace"),await i.child.exited}async shutdown(){if(this.closed=!0,this.livenessTimer)clearInterval(this.livenessTimer);this.livenessTimer=null;let t=[...this.slots.values()];for(let n of t)this.stopSlot(n,"Moi is shutting down");await Promise.allSettled(t.map((n)=>n.child.exited))}debugSnapshot(){return[...this.slots.values()].map((t)=>({workspacePath:t.workspacePath,pid:t.child.pid,generation:t.generation,connections:t.clients.size,stopping:t.stopping}))}}var Mo=new Kv;var Th=new Map;function Jv(t){let n=p();if(n.environment!=="local"||n.demo||n.agentLauncher)throw Error("Agents can only be installed in local Moi");if(t!=="claude-code"&&t!=="codex")throw Error("This agent requires manual installation");let i=Th.get(t);if(i)return i;let o=(async()=>{if((await Cn())[t])return;let a=t==="claude-code"?"https://claude.ai/install":"https://chatgpt.com/codex/install",c=process.platform==="win32"?["powershell.exe","-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-Command",`$ErrorActionPreference = 'Stop'; irm ${a}.ps1 | iex`]:["bash","-o","pipefail","-c",In[t].command];if(await Bun.spawn(c,{stdin:"ignore",stdout:"inherit",stderr:"inherit",timeout:300000}).exited!==0)throw Error("Installation failed or timed out. Try again.");if(!(await Cn())[t])throw Error("The installer finished, but the agent could not be found. Restart Moi.")})().finally(()=>Th.delete(t));return Th.set(t,o),o}var No=new Bs;No.get("/status",async(t)=>{t.header("Cache-Control","no-store");let n=t.req.query("refresh")==="true";if(n)await Ve({refresh:!0});let i=await Promise.all(ie().map(async({id:o})=>[o,{availability:await B.getAvailability(o,n),login:B.getLogin(o)}]));return t.json(Object.fromEntries(i))});No.use("/:type/*",async(t,n)=>{let i=t.req.param("type");if(!Yt(i))return t.text("Unknown agent",404);let o=y(i);if(!o.startLogin||!o.authStatus)return t.text("This agent requires terminal sign-in",409);t.set("harnessType",i),t.header("Cache-Control","no-store"),await n()});No.post("/:type/auth/install",async(t)=>{let n=t.req.header("Origin");if(n&&n!==new URL(t.req.url).origin)return t.text("Invalid origin",403);try{let i=t.get("harnessType");return await Jv(i),await B.refresh(i),t.json({ok:!0})}catch(i){return t.text(i instanceof Error?i.message:"Could not install agent",400)}});No.post("/:type/auth/login",async(t)=>{try{return t.json(await B.startLogin(t.get("harnessType")))}catch(n){return t.text(n instanceof Error?n.message:"Could not start sign-in",500)}});No.post("/:type/auth/login/:id/code",async(t)=>{try{let n=await t.req.json();if(!n||typeof n!=="object"||!("code"in n)||typeof n.code!=="string"||n.code.length>4096||!n.code.trim())return t.text("Enter the authorization code",400);return await B.submitCode(t.get("harnessType"),t.req.param("id"),n.code),t.json({ok:!0})}catch(n){return t.text(n instanceof Error?n.message:"Could not submit code",400)}});var $o=new Map;function Yv(t){return[t.source,t.kind??"",t.name??"",t.module??"",t.fn??"",t.message].join("\x00")}function Wu(t,n){let i=$o.get(t)??[],o=n.message.slice(0,1000),a=Yv({...n,message:o}),c=i.findIndex((m)=>Yv(m)===a);if(c!==-1){let[m]=i.splice(c,1);m.count++,m.ts=Date.now(),i.push(m)}else if(i.push({ts:Date.now(),source:n.source,...n.kind?{kind:n.kind}:{},...n.name?{name:n.name}:{},...n.module?{module:n.module}:{},...n.fn?{fn:n.fn}:{},message:o,...n.stack?{stack:n.stack.slice(0,4000)}:{},count:1}),i.length>100)i.shift();$o.set(t,i)}function Xv(t){return($o.get(t)??[]).map((n)=>({...n}))}function Rh(t){return $o.get(t)?.length??0}function Zv(t){let n=Rh(t);return $o.delete(t),n}function Qv(t){let n=t.match(/^(widgets|views)\/([^/]+)$/);if(!n)return null;return{kind:n[1]==="widgets"?"widget":"view",name:n[2]}}function Hu(t,n,i){let o=new Set,a=new Set,c=new Set(i.map((_)=>_.name));for(let _ of i){if(_.status==="failed")Wu(t,{source:"build",kind:n,name:_.name,message:_.error??"Build failed"});if(_.status==="built"){a.add(_.name);for(let I of _.serverModules??[])o.add(I)}}let m=$o.get(t);if(!m)return;let E=m.filter((_)=>{if(_.kind===n&&_.name&&(a.has(_.name)||!c.has(_.name)))return!1;if(_.source==="rpc"&&_.module&&o.has(_.module))return!1;return!0});$o.set(t,E)}import{realpathSync as sE,statSync as lE}from"fs";import{mkdir as BN,readdir as uE,rm as iE}from"fs/promises";import{join as Ts,resolve as oE,sep as aE}from"path";import{readdir as MN}from"fs/promises";import{dirname as NN,join as Do,resolve as $N}from"path";var Ph=/\.[mc]?[jt]sx?$/,DN=/\.[mc]?ts$/,LN=256;async function Tc(t){try{return(await MN(t)).filter((i)=>/\.(tsx|ts)$/.test(i)&&!i.startsWith("_")&&!i.endsWith(".server.ts")).map((i)=>i.replace(/\.tsx?$/,""))}catch(n){if(n instanceof Error&&"code"in n&&n.code==="ENOENT")return[];throw n}}async function tE(t,n){for(let i of[".tsx",".ts"]){let o=Do(t,`${n}${i}`);if(await Bun.file(o).exists())return o}return null}var jN={ts:new Bun.Transpiler({loader:"ts"}),tsx:new Bun.Transpiler({loader:"tsx"})};function UN(t,n="tsx"){let i;try{i=jN[n].scanImports(t)}catch{return null}return i.map((o)=>o.path).filter((o)=>/^\.\.?\//.test(o))}async function Ch(t,n=1/0){let i={entrypoints:new Set([...t].map((a)=>$N(a))),modules:new Map,complete:!0},o=[...i.entrypoints];while(o.length>0){let a=o.pop();if(i.modules.has(a))continue;if(i.modules.size>=LN){i.complete=!1;break}let c={modifiedAt:0,imports:[]};i.modules.set(a,c);try{let m=Bun.file(a);if(!await m.exists()){i.complete=!1;continue}if(c.modifiedAt=m.lastModified,c.modifiedAt>=n){i.complete=!1;break}if(!Ph.test(a))continue;let E=UN(await m.text(),DN.test(a)?"ts":"tsx");if(!E){i.complete=!1;continue}for(let _ of E){let I=await qN(NN(a),_);if(!I){i.complete=!1;continue}c.imports.push(I),o.push(I)}}catch{i.complete=!1}}return i}async function rE(t){let n=[];for(let i of["views","widgets"]){let o=Do(t,".moi",i);for(let a of await Tc(o))for(let c of[".tsx",".ts",".server.ts"]){let m=Do(o,a+c);if(await Bun.file(m).exists())n.push(m)}}return Ch(n)}function Oh(t,n){let i=new Set,o=[...n];while(o.length>0){let a=o.pop();if(i.has(a))continue;i.add(a),o.push(...t.modules.get(a)?.imports??[])}return i}var eE=[".tsx",".ts",".jsx",".js",".mjs",".cjs",".json",".mts",".cts"],FN={".js":[".ts",".tsx"],".jsx":[".tsx"],".mjs":[".mts"]};async function qN(t,n){let i=Do(t,n),o=[i],a=/\.[^./\\]+$/.exec(i)?.[0]??"";for(let E of FN[a]??[])o.push(i.slice(0,i.length-a.length)+E);for(let E of eE)o.push(i+E);for(let E of o)if(await Bun.file(E).exists())return E;let c=await Bun.file(Do(i,"package.json")).json().catch(()=>null),m=typeof c==="object"&&c!==null&&"main"in c&&typeof c.main==="string"?c.main:null;if(m){let E=Do(i,m);if(await Bun.file(E).exists())return E}for(let E of eE){let _=Do(i,`index${E}`);if(await Bun.file(_).exists())return _}return null}var nE="%%MOI_APPLET_API_BASE%%";function bn(t,n){let i=Ts(t,".moi"),o=n==="widget"?"widgets":"views",a=Ts(i,o),c=Ts(i,".build",o),m=Ts(c,"manifest.json");return{moiRoot:i,sourceDir:a,buildDir:c,manifestPath:m}}function Vu(t,n,i){try{let{buildDir:o}=bn(t,n),a=lE(Ts(o,i,"index.js"));return`${a.size}-${Math.trunc(a.mtimeMs)}`}catch{return}}async function WN(t,n,i){let o=Bun.file(Ts(t,n,"index.js"));if(!await o.exists())return!0;return!(await Ch([i],o.lastModified)).complete}async function zu(t){try{let n=await uE(t,{withFileTypes:!0}),i=[];for(let o of n){if(!o.isDirectory())continue;if(await Bun.file(Ts(t,o.name,"index.js")).exists())i.push(o.name)}return i}catch{return[]}}async function HN(t,n){let i;try{i=await uE(t,{withFileTypes:!0})}catch{return}for(let o of i){if(o.isDirectory()){if(!n.has(o.name))await iE(Ts(t,o.name),{recursive:!0,force:!0}).catch(()=>{});continue}if(o.isFile()&&o.name.endsWith(".js"))await iE(Ts(t,o.name),{force:!0}).catch(()=>{})}}var VN=/\.js$/,zN=/^[a-zA-Z0-9_-][a-zA-Z0-9._-]*$/,GN="text/javascript; charset=utf-8",KN="public, max-age=604800, immutable",JN=/^chunk-[0-9a-z]+\.\w+$|-[0-9a-f]{6,}\.\w+$/i;async function Gu(t,n,i,o,a,c){if(!/^[a-zA-Z0-9_-]+$/.test(n))return new Response("Invalid name",{status:400});if(!zN.test(i)||i.includes(".."))return new Response("Invalid file",{status:400});let{buildDir:m}=bn(o,t),E=Ts(m,n,i),_=Bun.file(E);if(!await _.exists())return new Response(`"${n}" not built. Run: moi bundle`,{status:404});let I;if(JN.test(i))I={"Cache-Control":KN};else{let T=`"${_.size}-${Math.trunc(_.lastModified)}-${Bun.hash(a)}-url-base-v2"`;if(I={ETag:T,"Cache-Control":"private, no-cache"},c===T)return new Response(null,{status:304,headers:I})}if(VN.test(i)){let T=`(new URL(import.meta.url).pathname.match(/^\\/api\\/workspaces\\/[^/]+/)?.[0] ?? ${JSON.stringify(a)})`,R=(await _.text()).replace(/(["'])([^"'\n]*%%MOI_APPLET_API_BASE%%[^"'\n]*)\1/g,(P,M,N)=>"("+N.split(nE).map((H)=>JSON.stringify(H)).join(" + "+T+" + ")+")");return new Response(R,{headers:{"Content-Type":GN,...I}})}return new Response(_,{headers:{"Content-Type":_.type||"application/octet-stream",...I}})}var cE="index.js",YN="module";function kh(t,n,i){let o=new URL(t).pathname.split(`/workspaces/${encodeURIComponent(n)}/${i}/`)[1]??"",a=o.indexOf("/");if(a===-1)return{name:o.replace(/\.js$/,""),file:cE};let c=o.slice(a+1);return{name:o.slice(0,a),file:c===YN?cE:c}}var XN=/\.(mp4|webm|mov|m4v|mkv|mp3|wav|ogg|oga|m4a|flac|aac|opus|png|jpe?g|gif|webp|avif|svg|ico|pdf|vtt|srt)$/i;function Mh(t,n){let i;try{i=decodeURIComponent(n)}catch{return new Response("Bad path",{status:400})}if(!i||i.includes("\x00"))return new Response("Bad path",{status:400});if(i.split("/").some((_)=>_===""||_==="."||_===".."||_.startsWith(".")))return new Response("Forbidden",{status:403});if(!XN.test(i))return new Response("Unsupported file type",{status:415});let a=oE(t),c=oE(t,i);if(c!==a&&!c.startsWith(a+aE))return new Response("Forbidden",{status:403});let m;try{m=sE(c)}catch{return new Response("Not found",{status:404})}let E;try{E=sE(a)}catch{return new Response("Forbidden",{status:403})}if(m!==E&&!m.startsWith(E+aE))return new Response("Forbidden",{status:403});return m}async function dE(t,n,i,o){let a=Mh(t,n);if(a instanceof Response)return a;let c=Bun.file(a),m;try{m=lE(a,{bigint:!0})}catch{return new Response("Not found",{status:404})}let E=Number(m.size),_=c.type||"application/octet-stream",I=`"${E}-${m.mtimeNs}"`,T={ETag:I,"Cache-Control":"private, no-cache"};if(o===I)return new Response(null,{status:304,headers:T});let R=i?ZN(i,E):null;if(R==="invalid")return new Response("Range Not Satisfiable",{status:416,headers:{...T,"Content-Range":`bytes */${E}`,"Accept-Ranges":"bytes"}});if(R){let{start:P,end:M}=R;return new Response(c.slice(P,M+1),{status:206,headers:{...T,"Content-Type":_,"Content-Length":String(M-P+1),"Content-Range":`bytes ${P}-${M}/${E}`,"Accept-Ranges":"bytes"}})}return new Response(c,{headers:{...T,"Content-Type":_,"Content-Length":String(E),"Accept-Ranges":"bytes"}})}function ZN(t,n){let i=/^bytes=(\d*)-(\d*)$/.exec(t.trim());if(!i)return null;let o=i[1]!=="",a=i[2]!=="";if(!o&&!a)return null;if(n===0)return"invalid";let c,m;if(!o){let E=parseInt(i[2],10);c=Math.max(0,n-E),m=n-1}else c=parseInt(i[1],10),m=a?Math.min(parseInt(i[2],10),n-1):n-1;if(c>m||c>=n||c<0)return"invalid";return{start:c,end:m}}async function Ku(t,n,i,o){let a=performance.now(),{sourceDir:c,buildDir:m,moiRoot:E}=bn(t,n),_=await Tc(c);if(_.length>0)await BN(m,{recursive:!0});await HN(m,new Set(_)),await Yi(t,n,_);let I=await Promise.all(_.map(async(P)=>{if(o&&P!==o)return{name:P,status:"skipped"};let M=await tE(c,P);if(!M)return{name:P,status:"failed",error:"Source file not found"};if(!i&&!await WN(m,P,M))return{name:P,status:"skipped"};return{name:P,srcPath:M,status:"pending"}})),T=new Map((await Fi({moiRoot:E,kind:n,jobs:I.filter((P)=>P.status==="pending").map((P)=>({name:P.name,srcPath:P.srcPath,outDir:Ts(m,P.name)}))})).map((P)=>[P.name,P])),R=I.map((P)=>{if(P.status==="failed")return{name:P.name,status:"failed",error:P.error};if(P.status==="skipped")return{name:P.name,status:"skipped"};let M=T.get(P.name);if(!M)return{name:P.name,status:"failed",error:"Build worker returned no result"};if(M.status==="failed")return{name:P.name,status:"failed",error:M.error};return{name:P.name,status:"built",serverModules:M.serverModules,config:M.config??null}});return{names:_,results:R,ms:Math.round(performance.now()-a)}}import{tracingChannel as QN,channel as e$}from"diagnostics_channel";var mr=e$("lru-cache:metrics"),Rc=QN("lru-cache"),t$=typeof performance=="object"&&performance&&typeof performance.now=="function"?performance:Date,Nh=()=>mr.hasSubscribers||Rc.hasSubscribers,pE=new Set,fE=typeof process=="object"&&process?process:{},r$=(t,n,i,o)=>{typeof fE.emitWarning=="function"?fE.emitWarning(t,n,i,o):console.error(`[${i}] ${n}: ${t}`)},n$=(t)=>!pE.has(t),oo=(t)=>!!t&&t===Math.floor(t)&&t>0&&isFinite(t),hE=(t)=>oo(t)?t<=Math.pow(2,8)?Uint8Array:t<=Math.pow(2,16)?Uint16Array:t<=Math.pow(2,32)?Uint32Array:t<=Number.MAX_SAFE_INTEGER?Ju:null:null,Ju=class extends Array{constructor(t){super(t),this.fill(0)}},s$=class t{heap;length;static#t=!1;static create(n){let i=hE(n);if(!i)return[];t.#t=!0;let o=new t(n,i);return t.#t=!1,o}constructor(n,i){if(!t.#t)throw TypeError("instantiate Stack using Stack.create(n)");this.heap=new i(n),this.length=0}push(n){this.heap[this.length++]=n}pop(){return this.heap[--this.length]}},mE=class t{#t;#e;#r;#o;#n;#i;#S;#f;get perf(){return this.#f}ttl;ttlResolution;ttlAutopurge;updateAgeOnGet;updateAgeOnHas;allowStale;noDisposeOnSet;noUpdateTTL;maxEntrySize;sizeCalculation;noDeleteOnFetchRejection;noDeleteOnStaleGet;allowStaleOnFetchAbort;allowStaleOnFetchRejection;ignoreFetchAbort;backgroundFetchSize;#a;#p;#u;#c;#s;#g;#y;#h;#d;#A;#m;#x;#_;#b;#v;#I;#L;#w;#k;static unsafeExposeInternals(n){return{starts:n.#_,ttls:n.#b,autopurgeTimers:n.#v,sizes:n.#x,keyMap:n.#u,keyList:n.#c,valList:n.#s,next:n.#g,prev:n.#y,get head(){return n.#h},get tail(){return n.#d},free:n.#A,isBackgroundFetch:(i)=>n.#l(i),backgroundFetch:(i,o,a,c)=>n.#F(i,o,a,c),moveToTail:(i)=>n.#D(i),indexes:(i)=>n.#T(i),rindexes:(i)=>n.#R(i),isStale:(i)=>n.#E(i)}}get max(){return this.#t}get maxSize(){return this.#e}get calculatedSize(){return this.#p}get size(){return this.#a}get fetchMethod(){return this.#i}get memoMethod(){return this.#S}get dispose(){return this.#r}get onInsert(){return this.#o}get disposeAfter(){return this.#n}constructor(n){let{max:i=0,ttl:o,ttlResolution:a=1,ttlAutopurge:c,updateAgeOnGet:m,updateAgeOnHas:E,allowStale:_,dispose:I,onInsert:T,disposeAfter:R,noDisposeOnSet:P,noUpdateTTL:M,maxSize:N=0,maxEntrySize:H=0,sizeCalculation:Z,fetchMethod:V,memoMethod:me,noDeleteOnFetchRejection:te,noDeleteOnStaleGet:we,allowStaleOnFetchRejection:Te,allowStaleOnFetchAbort:$e,ignoreFetchAbort:Ue,backgroundFetchSize:Ct=1,perf:Ot}=n;if(this.backgroundFetchSize=Ct,Ot!==void 0&&typeof Ot?.now!="function")throw TypeError("perf option must have a now() method if specified");if(this.#f=Ot??t$,i!==0&&!oo(i))throw TypeError("max option must be a nonnegative integer");let yi=i?hE(i):Array;if(!yi)throw Error("invalid max value: "+i);if(this.#t=i,this.#e=N,this.maxEntrySize=H||this.#e,this.sizeCalculation=Z,this.sizeCalculation){if(!this.#e&&!this.maxEntrySize)throw TypeError("cannot set sizeCalculation without setting maxSize or maxEntrySize");if(typeof this.sizeCalculation!="function")throw TypeError("sizeCalculation set to non-function")}if(me!==void 0&&typeof me!="function")throw TypeError("memoMethod must be a function if defined");if(this.#S=me,V!==void 0&&typeof V!="function")throw TypeError("fetchMethod must be a function if specified");if(this.#i=V,this.#L=!!V,this.#u=new Map,this.#c=Array.from({length:i}).fill(void 0),this.#s=Array.from({length:i}).fill(void 0),this.#g=new yi(i),this.#y=new yi(i),this.#h=0,this.#d=0,this.#A=s$.create(i),this.#a=0,this.#p=0,typeof I=="function"&&(this.#r=I),typeof T=="function"&&(this.#o=T),typeof R=="function"?(this.#n=R,this.#m=[]):(this.#n=void 0,this.#m=void 0),this.#I=!!this.#r,this.#k=!!this.#o,this.#w=!!this.#n,this.noDisposeOnSet=!!P,this.noUpdateTTL=!!M,this.noDeleteOnFetchRejection=!!te,this.allowStaleOnFetchRejection=!!Te,this.allowStaleOnFetchAbort=!!$e,this.ignoreFetchAbort=!!Ue,this.maxEntrySize!==0){if(this.#e!==0&&!oo(this.#e))throw TypeError("maxSize must be a positive integer if specified");if(!oo(this.maxEntrySize))throw TypeError("maxEntrySize must be a positive integer if specified");this.#K()}if(this.allowStale=!!_,this.noDeleteOnStaleGet=!!we,this.updateAgeOnGet=!!m,this.updateAgeOnHas=!!E,this.ttlResolution=oo(a)||a===0?a:1,this.ttlAutopurge=!!c,this.ttl=o||0,this.ttl){if(!oo(this.ttl))throw TypeError("ttl must be a positive integer if specified");this.#q()}if(this.#t===0&&this.ttl===0&&this.#e===0)throw TypeError("At least one of max, maxSize, or ttl is required");if(!this.ttlAutopurge&&!this.#t&&!this.#e){let Qr="LRU_CACHE_UNBOUNDED";n$(Qr)&&(pE.add(Qr),r$("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning",Qr,t))}}getRemainingTTL(n){return this.#u.has(n)?1/0:0}#q(){let n=new Ju(this.#t),i=new Ju(this.#t);this.#b=n,this.#_=i;let o=this.ttlAutopurge?Array.from({length:this.#t}):void 0;this.#v=o,this.#B=(_,I,T=this.#f.now())=>{i[_]=I!==0?T:0,n[_]=I,a(_,I)},this.#M=(_)=>{i[_]=n[_]!==0?this.#f.now():0,a(_,n[_])};let a=this.ttlAutopurge?(_,I)=>{if(o?.[_]&&(clearTimeout(o[_]),o[_]=void 0),I&&I!==0&&o){let T=setTimeout(()=>{this.#E(_)?(this.#P(this.#c[_],"expire"),o[_]=void 0):a(_,E(_))},I+1);T.unref&&T.unref(),o[_]=T}}:()=>{};this.#C=(_,I)=>{if(n[I]){let T=n[I],R=i[I];if(!T||!R)return;_.ttl=T,_.start=R,_.now=c||m();let P=_.now-R;_.remainingTTL=T-P}};let c=0,m=()=>{let _=this.#f.now();if(this.ttlResolution>0){c=_;let I=setTimeout(()=>c=0,this.ttlResolution);I.unref&&I.unref()}return _};this.getRemainingTTL=(_)=>{let I=this.#u.get(_);return I===void 0?0:E(I)};let E=(_)=>{let I=n[_],T=i[_];if(!I||!T)return 1/0;let R=(c||m())-T;return I-R};this.#E=(_)=>{let I=i[_],T=n[_];return!!T&&!!I&&(c||m())-I>T}}#M=()=>{};#C=()=>{};#B=()=>{};#E=()=>!1;#K(){let n=new Ju(this.#t);this.#p=0,this.#x=n,this.#N=(i)=>{this.#p-=n[i],n[i]=0},this.#W=(i,o,a,c)=>{if(!oo(a)){if(this.#l(o))return this.backgroundFetchSize;if(c){if(typeof c!="function")throw TypeError("sizeCalculation must be a function");if(a=c(o,i),!oo(a))throw TypeError("sizeCalculation return invalid (expect positive integer)")}else throw TypeError("invalid size value (must be positive integer). When maxSize or maxEntrySize is used, sizeCalculation or size must be set.")}return a},this.#j=(i,o,a)=>{if(n[i]=o,this.#e){let c=this.#e-n[i];for(;this.#p>c;)this.#U(!0)}this.#p+=n[i],a&&(a.entrySize=o,a.totalCalculatedSize=this.#p)}}#N=(n)=>{};#j=(n,i,o)=>{};#W=(n,i,o,a)=>{if(o||a)throw TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0};*#T({allowStale:n=this.allowStale}={}){if(this.#a)for(let i=this.#d;this.#H(i)&&((n||!this.#E(i))&&(yield i),i!==this.#h);)i=this.#y[i]}*#R({allowStale:n=this.allowStale}={}){if(this.#a)for(let i=this.#h;this.#H(i)&&((n||!this.#E(i))&&(yield i),i!==this.#d);)i=this.#g[i]}#H(n){return n!==void 0&&this.#u.get(this.#c[n])===n}*entries(){for(let n of this.#T())this.#s[n]!==void 0&&this.#c[n]!==void 0&&!this.#l(this.#s[n])&&(yield[this.#c[n],this.#s[n]])}*rentries(){for(let n of this.#R())this.#s[n]!==void 0&&this.#c[n]!==void 0&&!this.#l(this.#s[n])&&(yield[this.#c[n],this.#s[n]])}*keys(){for(let n of this.#T()){let i=this.#c[n];i!==void 0&&!this.#l(this.#s[n])&&(yield i)}}*rkeys(){for(let n of this.#R()){let i=this.#c[n];i!==void 0&&!this.#l(this.#s[n])&&(yield i)}}*values(){for(let n of this.#T())this.#s[n]!==void 0&&!this.#l(this.#s[n])&&(yield this.#s[n])}*rvalues(){for(let n of this.#R())this.#s[n]!==void 0&&!this.#l(this.#s[n])&&(yield this.#s[n])}[Symbol.iterator](){return this.entries()}[Symbol.toStringTag]="LRUCache";find(n,i={}){for(let o of this.#T()){let a=this.#s[o],c=this.#l(a)?a.__staleWhileFetching:a;if(c!==void 0&&n(c,this.#c[o],this))return this.#$(this.#c[o],i)}}forEach(n,i=this){for(let o of this.#T()){let a=this.#s[o],c=this.#l(a)?a.__staleWhileFetching:a;c!==void 0&&n.call(i,c,this.#c[o],this)}}rforEach(n,i=this){for(let o of this.#R()){let a=this.#s[o],c=this.#l(a)?a.__staleWhileFetching:a;c!==void 0&&n.call(i,c,this.#c[o],this)}}purgeStale(){let n=!1;for(let i of this.#R({allowStale:!0}))this.#E(i)&&(this.#P(this.#c[i],"expire"),n=!0);return n}info(n){let i=this.#u.get(n);if(i===void 0)return;let o=this.#s[i],a=this.#l(o)?o.__staleWhileFetching:o;if(a===void 0)return;let c={value:a};if(this.#b&&this.#_){let m=this.#b[i],E=this.#_[i];if(m&&E){let _=m-(this.#f.now()-E);c.ttl=_,c.start=Date.now()}}return this.#x&&(c.size=this.#x[i]),c}dump(){let n=[];for(let i of this.#T({allowStale:!0})){let o=this.#c[i],a=this.#s[i],c=this.#l(a)?a.__staleWhileFetching:a;if(c===void 0||o===void 0)continue;let m={value:c};if(this.#b&&this.#_){m.ttl=this.#b[i];let E=this.#f.now()-this.#_[i];m.start=Math.floor(Date.now()-E)}this.#x&&(m.size=this.#x[i]),n.unshift([o,m])}return n}load(n){this.clear();for(let[i,o]of n){if(o.start){let a=Date.now()-o.start;o.start=this.#f.now()-a}this.#O(i,o.value,o)}}set(n,i,o={}){let{status:a=mr.hasSubscribers?{}:void 0}=o;o.status=a,a&&(a.op="set",a.key=n,i!==void 0&&(a.value=i),a.cache=this);let c=this.#O(n,i,o);return a&&mr.hasSubscribers&&mr.publish(a),c}#O(n,i,o,a){let{ttl:c=this.ttl,start:m,noDisposeOnSet:E=this.noDisposeOnSet,sizeCalculation:_=this.sizeCalculation,status:I}=o,T=this.#l(i);if(i===void 0)return I&&(I.set="deleted"),this.delete(n),this;let{noUpdateTTL:R=this.noUpdateTTL}=o;I&&!T&&(I.value=i);let P=this.#W(n,i,o.size||0,_,I);if(this.maxEntrySize&&P>this.maxEntrySize)return this.#P(n,"set"),I&&(I.set="miss",I.maxEntrySizeExceeded=!0),this;let M=this.#a===0?void 0:this.#u.get(n);if(M===void 0)M=this.#a===0?this.#d:this.#A.length!==0?this.#A.pop():this.#a===this.#t?this.#U(!1):this.#a,this.#c[M]=n,this.#s[M]=i,this.#u.set(n,M),this.#g[this.#d]=M,this.#y[M]=this.#d,this.#d=M,this.#a++,this.#j(M,P,I),I&&(I.set="add"),R=!1,this.#k&&!T&&this.#o?.(i,n,"add");else{this.#D(M);let N=this.#s[M];if(i!==N){if(!E)if(this.#l(N)){N!==a&&N.__abortController.abort(Error("replaced"));let{__staleWhileFetching:H}=N;H!==void 0&&H!==i&&(this.#I&&this.#r?.(H,n,"set"),this.#w&&this.#m?.push([H,n,"set"]))}else this.#I&&this.#r?.(N,n,"set"),this.#w&&this.#m?.push([N,n,"set"]);if(this.#N(M),this.#j(M,P,I),this.#s[M]=i,!T){let H=N&&this.#l(N)?N.__staleWhileFetching:N,Z=H===void 0?"add":i!==H?"replace":"update";I&&(I.set=Z,H!==void 0&&(I.oldValue=H)),this.#k&&this.onInsert?.(i,n,Z)}}else T||(I&&(I.set="update"),this.#k&&this.onInsert?.(i,n,"update"))}if(c!==0&&!this.#b&&this.#q(),this.#b&&(R||this.#B(M,c,m),I&&this.#C(I,M)),!E&&this.#w&&this.#m){let N=this.#m,H;for(;H=N?.shift();)this.#n?.(...H)}return this}pop(){try{for(;this.#a;){let n=this.#s[this.#h];if(this.#U(!0),this.#l(n)){if(n.__staleWhileFetching)return n.__staleWhileFetching}else if(n!==void 0)return n}}finally{if(this.#w&&this.#m){let n=this.#m,i;for(;i=n?.shift();)this.#n?.(...i)}}}#U(n){let i=this.#h,o=this.#c[i],a=this.#s[i],c=this.#l(a);c&&a.__abortController.abort(Error("evicted"));let m=c?a.__staleWhileFetching:a;return(this.#I||this.#w)&&m!==void 0&&(this.#I&&this.#r?.(m,o,"evict"),this.#w&&this.#m?.push([m,o,"evict"])),this.#N(i),this.#v?.[i]&&(clearTimeout(this.#v[i]),this.#v[i]=void 0),n&&(this.#c[i]=void 0,this.#s[i]=void 0,this.#A.push(i)),this.#a===1?(this.#h=this.#d=0,this.#A.length=0):this.#h=this.#g[i],this.#u.delete(o),this.#a--,i}has(n,i={}){let{status:o=mr.hasSubscribers?{}:void 0}=i;i.status=o,o&&(o.op="has",o.key=n,o.cache=this);let a=this.#J(n,i);return mr.hasSubscribers&&mr.publish(o),a}#J(n,i={}){let{updateAgeOnHas:o=this.updateAgeOnHas,status:a}=i,c=this.#u.get(n);if(c!==void 0){let m=this.#s[c];if(this.#l(m)&&m.__staleWhileFetching===void 0)return!1;if(this.#E(c))a&&(a.has="stale",this.#C(a,c));else return o&&this.#M(c),a&&(a.has="hit",this.#C(a,c)),!0}else a&&(a.has="miss");return!1}peek(n,i={}){let{status:o=Nh()?{}:void 0}=i;o&&(o.op="peek",o.key=n,o.cache=this),i.status=o;let a=this.#Y(n,i);return mr.hasSubscribers&&mr.publish(o),a}#Y(n,i){let{status:o,allowStale:a=this.allowStale}=i,c=this.#u.get(n);if(c===void 0||!a&&this.#E(c)){o&&(o.peek=c===void 0?"miss":"stale");return}let m=this.#s[c],E=this.#l(m)?m.__staleWhileFetching:m;return o&&(E!==void 0?(o.peek="hit",o.value=E):o.peek="miss"),E}#F(n,i,o,a){let c=i===void 0?void 0:this.#s[i];if(this.#l(c))return c;let m=new AbortController,{signal:E}=o;E?.addEventListener("abort",()=>m.abort(E.reason),{signal:m.signal});let _={signal:m.signal,options:o,context:a},I=(H,Z=!1)=>{let{aborted:V}=m.signal,me=o.ignoreFetchAbort&&H!==void 0,te=o.ignoreFetchAbort||!!(o.allowStaleOnFetchAbort&&H!==void 0);if(o.status&&(V&&!Z?(o.status.fetchAborted=!0,o.status.fetchError=m.signal.reason,me&&(o.status.fetchAbortIgnored=!0)):o.status.fetchResolved=!0),V&&!me&&!Z)return R(m.signal.reason,te);let we=M,Te=this.#s[i];return(Te===M||Te===void 0&&me&&Z)&&(H===void 0?we.__staleWhileFetching!==void 0?this.#s[i]=we.__staleWhileFetching:this.#P(n,"fetch"):(o.status&&(o.status.fetchUpdated=!0),this.#O(n,H,_.options,we))),H},T=(H)=>(o.status&&(o.status.fetchRejected=!0,o.status.fetchError=H),R(H,!1)),R=(H,Z)=>{let{aborted:V}=m.signal,me=V&&o.allowStaleOnFetchAbort,te=me||o.allowStaleOnFetchRejection,we=te||o.noDeleteOnFetchRejection,Te=M;if(this.#s[i]===M&&(!we||!Z&&Te.__staleWhileFetching===void 0?this.#P(n,"fetch"):me||(this.#s[i]=Te.__staleWhileFetching)),te)return o.status&&Te.__staleWhileFetching!==void 0&&(o.status.returnedStale=!0),Te.__staleWhileFetching;if(Te.__returned===Te)throw H},P=(H,Z)=>{let V=this.#i?.(n,c,_);m.signal.addEventListener("abort",()=>{(!o.ignoreFetchAbort||o.allowStaleOnFetchAbort)&&(H(void 0),o.allowStaleOnFetchAbort&&(H=(me)=>I(me,!0)))}),V&&V instanceof Promise?V.then((me)=>H(me===void 0?void 0:me),Z):V!==void 0&&H(V)};o.status&&(o.status.fetchDispatched=!0);let M=new Promise(P).then(I,T),N=Object.assign(M,{__abortController:m,__staleWhileFetching:c,__returned:void 0});return i===void 0?(this.#O(n,N,{..._.options,status:void 0}),i=this.#u.get(n)):this.#s[i]=N,N}#l(n){if(!this.#L)return!1;let i=n;return!!i&&i instanceof Promise&&i.hasOwnProperty("__staleWhileFetching")&&i.__abortController instanceof AbortController}fetch(n,i={}){let o=Rc.hasSubscribers,{status:a=Nh()?{}:void 0}=i;i.status=a,a&&i.context&&(a.context=i.context);let c=this.#V(n,i);return a&&o&&(a.trace=!0,Rc.tracePromise(()=>c,a).catch(()=>{})),c}async#V(n,i={}){let{allowStale:o=this.allowStale,updateAgeOnGet:a=this.updateAgeOnGet,noDeleteOnStaleGet:c=this.noDeleteOnStaleGet,ttl:m=this.ttl,noDisposeOnSet:E=this.noDisposeOnSet,size:_=0,sizeCalculation:I=this.sizeCalculation,noUpdateTTL:T=this.noUpdateTTL,noDeleteOnFetchRejection:R=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:P=this.allowStaleOnFetchRejection,ignoreFetchAbort:M=this.ignoreFetchAbort,allowStaleOnFetchAbort:N=this.allowStaleOnFetchAbort,context:H,forceRefresh:Z=!1,status:V,signal:me}=i;if(V&&(V.op="fetch",V.key=n,Z&&(V.forceRefresh=!0),V.cache=this),!this.#L)return V&&(V.fetch="get"),this.#$(n,{allowStale:o,updateAgeOnGet:a,noDeleteOnStaleGet:c,status:V});let te={allowStale:o,updateAgeOnGet:a,noDeleteOnStaleGet:c,ttl:m,noDisposeOnSet:E,size:_,sizeCalculation:I,noUpdateTTL:T,noDeleteOnFetchRejection:R,allowStaleOnFetchRejection:P,allowStaleOnFetchAbort:N,ignoreFetchAbort:M,status:V,signal:me},we=this.#u.get(n);if(we===void 0){V&&(V.fetch="miss");let Te=this.#F(n,we,te,H);return Te.__returned=Te}else{let Te=this.#s[we];if(this.#l(Te)){let Ot=o&&Te.__staleWhileFetching!==void 0;return V&&(V.fetch="inflight",Ot&&(V.returnedStale=!0)),Ot?Te.__staleWhileFetching:Te.__returned=Te}let $e=this.#E(we);if(!Z&&!$e)return V&&(V.fetch="hit"),this.#D(we),a&&this.#M(we),V&&this.#C(V,we),Te;let Ue=this.#F(n,we,te,H),Ct=Ue.__staleWhileFetching!==void 0&&o;return V&&(V.fetch=$e?"stale":"refresh",Ct&&$e&&(V.returnedStale=!0)),Ct?Ue.__staleWhileFetching:Ue.__returned=Ue}}forceFetch(n,i={}){let o=Rc.hasSubscribers,{status:a=Nh()?{}:void 0}=i;i.status=a,a&&i.context&&(a.context=i.context);let c=this.#X(n,i);return a&&o&&(a.trace=!0,Rc.tracePromise(()=>c,a).catch(()=>{})),c}async#X(n,i={}){let o=await this.#V(n,i);if(o===void 0)throw Error("fetch() returned undefined");return o}memo(n,i={}){let{status:o=mr.hasSubscribers?{}:void 0}=i;i.status=o,o&&(o.op="memo",o.key=n,i.context&&(o.context=i.context),o.cache=this);let a=this.#Z(n,i);return o&&(o.value=a),mr.hasSubscribers&&mr.publish(o),a}#Z(n,i={}){let o=this.#S;if(!o)throw Error("no memoMethod provided to constructor");let{context:a,status:c,forceRefresh:m,...E}=i;c&&m&&(c.forceRefresh=!0);let _=this.#$(n,E),I=m||_===void 0;if(c&&(c.memo=I?"miss":"hit",I||(c.value=_)),!I)return _;let T=o(n,_,{options:E,context:a});return c&&(c.value=T),this.#O(n,T,E),T}get(n,i={}){let{status:o=mr.hasSubscribers?{}:void 0}=i;i.status=o,o&&(o.op="get",o.key=n,o.cache=this);let a=this.#$(n,i);return o&&(a!==void 0&&(o.value=a),mr.hasSubscribers&&mr.publish(o)),a}#$(n,i={}){let{allowStale:o=this.allowStale,updateAgeOnGet:a=this.updateAgeOnGet,noDeleteOnStaleGet:c=this.noDeleteOnStaleGet,status:m}=i,E=this.#u.get(n);if(E===void 0){m&&(m.get="miss");return}let _=this.#s[E],I=this.#l(_);return m&&this.#C(m,E),this.#E(E)?I?(m&&(m.get="stale-fetching"),o&&_.__staleWhileFetching!==void 0?(m&&(m.returnedStale=!0),_.__staleWhileFetching):void 0):(c||this.#P(n,"expire"),m&&(m.get="stale"),o?(m&&(m.returnedStale=!0),_):void 0):(m&&(m.get=I?"fetching":"hit"),this.#D(E),a&&this.#M(E),I?_.__staleWhileFetching:_)}#z(n,i){this.#y[i]=n,this.#g[n]=i}#D(n){n!==this.#d&&(n===this.#h?this.#h=this.#g[n]:this.#z(this.#y[n],this.#g[n]),this.#z(this.#d,n),this.#d=n)}delete(n){return this.#P(n,"delete")}#P(n,i){mr.hasSubscribers&&mr.publish({op:"delete",delete:i,key:n,cache:this});let o=!1;if(this.#a!==0){let a=this.#u.get(n);if(a!==void 0)if(this.#v?.[a]&&(clearTimeout(this.#v[a]),this.#v[a]=void 0),o=!0,this.#a===1)this.#G(i);else{this.#N(a);let c=this.#s[a];if(this.#l(c)?c.__abortController.abort(Error("deleted")):(this.#I||this.#w)&&(this.#I&&this.#r?.(c,n,i),this.#w&&this.#m?.push([c,n,i])),this.#u.delete(n),this.#c[a]=void 0,this.#s[a]=void 0,a===this.#d)this.#d=this.#y[a];else if(a===this.#h)this.#h=this.#g[a];else{let m=this.#y[a];this.#g[m]=this.#g[a];let E=this.#g[a];this.#y[E]=this.#y[a]}this.#a--,this.#A.push(a)}}if(this.#w&&this.#m?.length){let a=this.#m,c;for(;c=a?.shift();)this.#n?.(...c)}return o}clear(){return this.#G("delete")}#G(n){for(let i of this.#R({allowStale:!0})){let o=this.#s[i];if(this.#l(o))o.__abortController.abort(Error("deleted"));else{let a=this.#c[i];this.#I&&this.#r?.(o,a,n),this.#w&&this.#m?.push([o,a,n])}}if(this.#u.clear(),this.#s.fill(void 0),this.#c.fill(void 0),this.#b&&this.#_){this.#b.fill(0),this.#_.fill(0);for(let i of this.#v??[])i!==void 0&&clearTimeout(i);this.#v?.fill(void 0)}if(this.#x&&this.#x.fill(0),this.#h=0,this.#d=0,this.#A.length=0,this.#p=0,this.#a=0,this.#w&&this.#m){let i=this.#m,o;for(;o=i?.shift();)this.#n?.(...o)}}};import{readFileSync as i$}from"fs";import{tmpdir as o$}from"os";import{join as a$}from"path";var c$=he("applets/functions-worker.ts"),gE=30000,yE=600000,wE=8;function $h(t,n){for(let{reject:i,timer:o}of t.pending.values())clearTimeout(o),i(Error(n));t.pending.clear()}function Yu(t,n){if(t.killed)return;t.killed=!0,$h(t,n);try{t.worker.kill()}catch{}}var l$=2000;function u$(t,n){if(t.killed)return;t.killed=!0,$h(t,n);let i=setTimeout(()=>{try{t.worker.kill()}catch{}},l$);i.unref?.(),t.worker.exited.then(()=>clearTimeout(i)).catch(()=>clearTimeout(i));try{t.worker.send({type:"shutdown"})}catch{clearTimeout(i);try{t.worker.kill()}catch{}}}var Os=new mE({max:wE,ttl:yE,ttlAutopurge:!0,updateAgeOnGet:!0,dispose:(t)=>Yu(t,"Functions worker idle-evicted")});function SE(t,n){let i=a$(t,".moi"),o=()=>{},a=new Promise((m)=>o=m),c={workspacePath:t,worker:void 0,readyPromise:a,pending:new Map,killed:!1,ready:!1,spawnedAt:Date.now(),lastCallAt:null,calls:0,errors:0,timeouts:0,modules:new Set};return c.worker=Bun.spawn(j([process.execPath,c$]),{cwd:o$(),env:{...process.env,...n,MEI_WORKSPACE_ROOT:t,MEI_FUNCTIONS_DIR:process.env.MEI_FUNCTIONS_DIR??i},stderr:"inherit",onExit(m,E){if(E!==0&&E!==null)console.error(`[mei] functions worker for ${t} exited with code ${E}`);if(c.killed=!0,$h(c,"Functions worker exited"),Os.peek(t)===c)Os.delete(t)},ipc(m){let E=m;if(E.type==="ready"){c.ready=!0,o();return}if(E.type==="loaded"&&E.module){c.modules.add(E.module);return}if(E.id){let _=c.pending.get(E.id);if(!_)return;if(c.pending.delete(E.id),clearTimeout(_.timer),E.type==="result")_.resolve(E.data);else if(E.type==="error")c.errors++,_.reject(Error(E.message??"Unknown error"))}}}),c}function d$(t,n){let i=Os.get(t);if(i&&!i.killed)return i;let o=SE(t,n);return Os.set(t,o),o}function Xu(t){let n=t.lastIndexOf("/");if(n===-1)return null;let i=t.slice(0,n),o=t.slice(n+1);if(!/^[A-Za-z0-9_$-]+(?:\/[A-Za-z0-9_$-]+)*$/.test(i))return null;if(!/^[A-Za-z0-9_$]+$/.test(o))return null;return{module:i,name:o}}function bE(t,n,i,o){t.calls++,t.lastCallAt=Date.now();let a=crypto.randomUUID();return new Promise((c,m)=>{let E=setTimeout(()=>{t.pending.delete(a),t.timeouts++,m(Error(`Function call timed out: ${n}/${i}`))},gE);t.pending.set(a,{resolve:c,reject:m,timer:E});try{t.worker.send({id:a,type:"call",module:n,name:i,args:o})}catch(_){t.pending.delete(a),clearTimeout(E),m(_ instanceof Error?_:Error("Failed to send to worker"))}})}async function vE(t,n,i,o){let a=await X(o),c=d$(o,a);return await c.readyPromise,bE(c,t,n,i)}async function EE(t,n,i,o){let a=await X(o),c=SE(o,a);try{return await c.readyPromise,await bE(c,t,n,i)}finally{Yu(c,"Ephemeral call finished")}}function AE(){for(let t of Os.values())Yu(t,"Server shutting down");Os.clear()}function xE(t){let n=Os.peek(t);if(n)Yu(n,"Workspace env changed");Os.delete(t)}var Zu={maxWorkers:wE,idleTtlMs:yE,callTimeoutMs:gE};function f$(t){if(!t||process.platform!=="linux")return null;try{let n=i$(`/proc/${t}/status`,"utf8").match(/^VmRSS:\s+(\d+)\s+kB/m);return n?Number(n[1])*1024:null}catch{return null}}function _E(){let t=[];for(let[n,i]of Os.entries()){if(i.killed)continue;t.push({workspacePath:n,pid:i.worker.pid,ready:i.ready,spawnedAt:i.spawnedAt,lastCallAt:i.lastCallAt,calls:i.calls,errors:i.errors,timeouts:i.timeouts,pending:i.pending.size,ttlRemainingMs:Os.getRemainingTTL(n),rssBytes:f$(i.worker.pid),modules:[...i.modules].sort()})}return t}function Pc(t,n){if(t.length===0)return;let i=Os.peek(n);if(!i||i.killed)return;u$(i,`Server code changed (${t.join(", ")})`)}function Qu(t){xE(t.path);for(let n of ie())n.onEnvChanged?.(t.path);B.invalidate(t),h({type:"env:changed",workspaceId:t.id})}import p$ from"sharp";async function ed(t){return`data:image/webp;base64,${(await p$(t,{animated:!0}).resize(128,128,{fit:"contain",background:{r:0,g:0,b:0,alpha:0}}).webp({quality:90}).toBuffer()).toString("base64")}`}import{existsSync as h$}from"fs";import{join as m$}from"path";var Dh=v("dist"),IE=m$(Dh,"index.html"),Aa=!process.env.MOI_DEV&&h$(IE);function TE(){return new Response(Bun.file(IE),{headers:{"Cache-Control":"no-cache"}})}import{statSync as g$}from"fs";import y$ from"sharp";var Lh=800,w$=/\.(png|jpe?g|webp|avif)$/i,S$=/\.(gif|svg)$/i;async function RE(t,n,i){let o=w$.test(n);if(!o&&!S$.test(n))return new Response("Not an image",{status:415});let a=Mh(t,n);if(a instanceof Response)return a;let c;try{c=g$(a)}catch{return new Response("Not found",{status:404})}let m=`"${c.size}-${Math.trunc(c.mtimeMs)}${o?`-${Lh}`:""}"`,E={ETag:m,"Cache-Control":"private, no-cache"};if(i===m)return new Response(null,{status:304,headers:E});if(!o){let _=Bun.file(a);return new Response(_,{headers:{...E,"Content-Type":_.type||"application/octet-stream"}})}try{let _=await y$(a).rotate().resize(Lh,Lh,{fit:"inside",withoutEnlargement:!0}).webp({quality:80}).toBuffer();return new Response(new Uint8Array(_),{headers:{...E,"Content-Type":"image/webp"}})}catch{return new Response("Preview failed",{status:415})}}import{existsSync as E$}from"fs";var xa=new Map;function Cc(t,n){let o=(xa.get(t)??Promise.resolve()).then(n,n);return xa.set(t,o),o.then(()=>{if(xa.get(t)===o)xa.delete(t)},()=>{if(xa.get(t)===o)xa.delete(t)}),o}import{realpath as PE,rm as b$}from"fs/promises";import{join as _a,relative as v$,sep as CE}from"path";async function kE(t,n){let i=_a(t,".moi","views");for(let o of[".tsx",".ts"]){let a=_a(i,`${n}${o}`),c=Bun.file(a);if(await c.exists())return{path:a,source:await c.text()}}return null}class td extends Error{}function OE(t,n){if(!n.startsWith(t+CE)||!Ph.test(n))return!1;return!v$(t,n).split(CE).some((i)=>i.startsWith(".")||["data","ui","node_modules"].includes(i))}async function ME(t,n,i){let o=await PE(t),a=_a(o,".moi"),c=_a(a,"views"),m=["tsx","ts"].map((T)=>_a(c,`${n}.${T}`)),E=new Set([...m,_a(c,`${n}.server.ts`)]),_=new Set(m),I=await rE(o).catch(()=>null);if(I?.complete){if((await Promise.all([...I.modules.keys()].map(async(R)=>await PE(R).catch(()=>null)===R))).every(Boolean)){let R=Oh(I,E),P=Oh(I,[...[...I.entrypoints].filter((M)=>!E.has(M)),...[...R].filter((M)=>!OE(a,M))]);if(m.some((M)=>P.has(M)))throw new td("Another applet imports this view. Remove that import before deleting it.");for(let M of R)if(!P.has(M)&&OE(a,M))_.add(M)}}await i?.(),await Promise.all([..._].map((T)=>b$(T,{force:!0})))}class ks extends Error{status;constructor(t,n){super(t);this.status=n;this.name="ViewMutationError"}}async function Oc(t){let{manifestPath:n}=bn(t,"view");try{let i=JSON.parse(await Bun.file(n).text());return{config:i.config??{},order:Array.isArray(i.order)?i.order:[]}}catch{return{config:{},order:[]}}}async function A$(t,n){let{manifestPath:i}=bn(t,"view");await Bun.write(i,JSON.stringify(n,null,2))}function x$(t,n){let i=new Set(n),o=t.filter((m)=>i.has(m)),a=new Set(o),c=n.filter((m)=>!a.has(m));return[...o,...c]}async function _$(t,n=!1,i){let{names:o,results:a,ms:c}=await Ku(t,"view",n,i),m=await Oc(t);for(let T of a)if(T.status==="built")m.config[T.name]=T.config??{};for(let T of Object.keys(m.config))if(!o.includes(T))delete m.config[T];m.order=x$(m.order,o);let{buildDir:E}=bn(t,"view");if(E$(E))await A$(t,m);let _=a.filter((T)=>T.status==="built").length,I=a.filter((T)=>T.status==="failed");console.log(`[bundle] ${_}/${o.length} views built in ${c}ms`+(I.length?`, ${I.length} failed`:"")+(n?" (forced)":""));for(let T of I)console.error(`[bundle] ${T.name}:
|
|
77
|
+
${await Bun.file(v("server","onboarding","prompt.md")).text()}`,resultSchema:vh,progressSchema:Rv,onProgress:(De)=>E(M,async()=>{let je=await c(M);if(!Z.signal.aborted&&je?.status==="running")await m(M,{...je,progress:De})}),signal:Z.signal})}).then((te)=>({status:"done",ideas:Nv(te)})).catch((te)=>({status:"failed",error:Z.signal.aborted?"Discovery stopped. Try again":String(te instanceof Error?te.message:te)})).then((te)=>E(M,async()=>{if((await c(M))?.status==="running")await m(M,te)})).finally(()=>{clearTimeout(me),i.delete(M)}).catch((te)=>console.error("[onboarding] could not save action result",te)),V})}async function T(P,M=!1){let N=P.operationId;return E(N,async()=>{let H=await c(N);if(H?.status==="done"||i.has(N))return H;if(H?.status==="failed"&&!M)return H;let Z=new AbortController;i.set(N,Z);let V={...H,status:"running",error:void 0,sessionId:H?.sessionId??crypto.randomUUID()};try{await m(N,V)}catch(me){throw i.delete(N),me}return R(N,P,V).catch(async(me)=>{await m(N,{...await c(N),status:"failed",error:me instanceof Error?me.message:String(me)})}).finally(()=>i.delete(N)).catch((me)=>console.error("[onboarding] could not save workspace result",me)),V})}async function R(P,M,N){let H=M.idea;if(!N.workspacePath){let je=n.workspacesRoot(),Ct=Uu(je,`onboarding-${P}`);if(fN(Ct))N.workspacePath=Ct;else N.workspacePath=await pr(H.name,je,n.getWorkspace);await m(P,N)}let Z=N.workspacePath;if(await n.provisionWorkspace(Z,M.harness),!N.workspaceId)await n.setWorkspaceConfig(Z,{name:H.name,icon:{type:"glyph",value:H.icon,background:"theme"}}),await Ve(Z,(je)=>({...je,theme:Ye({...je.theme,...H.theme})}));let V=await n.registerWorkspace(Z,{id:N.workspaceId??pN(Z),harness:M.harness,name:H.name});N.workspaceId=V.id,await m(P,N);let me=Uu(Z,"onboarding-brief.md"),te=N.stage?await Bun.file(me).text():Dv(H);await Bun.write(me,te),n.publishEvent({type:"workspaces-list:changed"});let we=n.harnessFor(V);if(N.stage==="sending"||N.stage==="accepted"){let je=await we.listSessions(V);for(let Ot of je)if((await we.sessionEvents(V,Ot.sessionId)).some((Qr)=>Qr.kind==="turn"&&Qr.turn.role==="user"&&Qr.turn.parts.some((cd)=>cd.type==="text"&&cd.text.includes(te)))){N.sessionId=Ot.sessionId,await n.saveSelectedSession(V,Ot.sessionId),await m(P,{...N,status:"done",stage:"accepted"});return}let Ct=await n.readWorkspaceState(V);if(N.sessionId=Ct.selected.overview??N.sessionId,we.activeSessions().some((Ot)=>Ot.workspaceId===V.id))throw Error("The agent is still starting. Wait a moment and try again");if(N.stage==="sending")throw Error("Could not confirm the first message. Check the chat before sending the saved onboarding brief")}let Te=await we.authStatus?.();if(Te&&Te.status!=="available")throw Error("Reconnect the agent, then retry starting the workspace");await n.saveSelectedSession(V,N.sessionId),N.stage="sending",await m(P,N);let De;try{await Promise.race([n.sendWorkspaceMessage(V,{workspaceId:V.id,workspacePath:V.path,sessionId:N.sessionId,isNew:!0,content:te,optimisticId:M.operationId,context:{activeTab:{id:"overview"}}}),new Promise((je,Ct)=>{De=setTimeout(()=>Ct(Error("Could not confirm the first message. Check the chat before retrying")),90000)})])}finally{clearTimeout(De)}N.sessionId=n.resolveRenamedSession(V.id,N.sessionId),await n.saveSelectedSession(V,N.sessionId),await m(P,{...N,status:"done",stage:"accepted"})}return{discoverIdeas:I,cancelIdeas:_,createFromIdea:T}}var{discoverIdeas:Eh,cancelIdeas:Lv,createFromIdea:jv}=mN();var Uv=s({harness:F(["claude-code","codex"]),runId:r().uuid()}),gN=Uv.extend({ideaId:r().uuid(),operationId:r().uuid(),retry:k().optional()}),Ea=new Bs;Ea.use("*",async(t,n)=>{if(p().demo||!Lu().showOnboarding)return t.json({error:"Onboarding is not enabled"},403);t.header("Cache-Control","no-store"),await n()});Ea.post("/discover",async(t)=>{let n=Uv.safeParse(await t.req.json().catch(()=>{return}));if(!n.success)return t.json({error:"Invalid discovery request"},400);return t.json(await Eh(n.data))});Ea.post("/cancel",async(t)=>{let n=s({runId:r().uuid()}).safeParse(await t.req.json().catch(()=>{return}));if(!n.success)return t.json({error:"Invalid discovery request"},400);return await Lv(n.data.runId),t.json({status:"done"})});Ea.post("/create",async(t)=>{let n=gN.safeParse(await t.req.json().catch(()=>{return}));if(!n.success)return t.json({error:"Invalid workspace request"},400);let{harness:i,runId:o,ideaId:a,operationId:c,retry:m}=n.data,E=await Eh({harness:i,runId:o}),_=E.ideas?.find((I)=>I.id===a);if(E.status!=="done"||!_)return t.json({error:"Choose an available idea"},409);return t.json(await jv({harness:i,operationId:c,idea:_},m))});import{stat as vN}from"fs/promises";import{join as EN}from"path";var Fv=/^\s*(?:text\/(?!event-stream(?:[;\s]|$))[^;\s]+|application\/(?:javascript|json|xml|xml-dtd|ecmascript|dart|msgpack|postscript|rtf|tar|toml|vnd\.dart|vnd\.ms-fontobject|vnd\.ms-opentype|vnd\.msgpack|wasm|x-httpd-php|x-javascript|x-msgpack|x-ns-proxy-autoconfig|x-sh|x-tar|x-virtualbox-hdd|x-virtualbox-ova|x-virtualbox-ovf|x-virtualbox-vbox|x-virtualbox-vdi|x-virtualbox-vhd|x-virtualbox-vmdk|x-www-form-urlencoded)|font\/(?:otf|ttf)|image\/(?:bmp|vnd\.adobe\.photoshop|vnd\.microsoft\.icon|vnd\.ms-dds|x-icon|x-ms-bmp)|message\/rfc822|model\/gltf-binary|x-shader\/x-fragment|x-shader\/x-vertex|[^;\s]+?\+(?:json|text|xml|yaml|msgpack))(?:[;\s]|$)/i;var Ah=(t,n=wN)=>{let i=/\.([a-zA-Z0-9]+?)$/,o=t.match(i);if(!o)return;return n[o[1].toLowerCase()]};var yN={aac:"audio/aac",avi:"video/x-msvideo",avif:"image/avif",av1:"video/av1",bin:"application/octet-stream",bmp:"image/bmp",css:"text/css; charset=utf-8",csv:"text/csv; charset=utf-8",eot:"application/vnd.ms-fontobject",epub:"application/epub+zip",gif:"image/gif",gz:"application/gzip",htm:"text/html; charset=utf-8",html:"text/html; charset=utf-8",ico:"image/x-icon",ics:"text/calendar; charset=utf-8",jpeg:"image/jpeg",jpg:"image/jpeg",js:"text/javascript; charset=utf-8",json:"application/json",jsonld:"application/ld+json",map:"application/json",mid:"audio/x-midi",midi:"audio/x-midi",mjs:"text/javascript; charset=utf-8",mp3:"audio/mpeg",mp4:"video/mp4",mpeg:"video/mpeg",oga:"audio/ogg",ogv:"video/ogg",ogx:"application/ogg",opus:"audio/opus",otf:"font/otf",pdf:"application/pdf",png:"image/png",rtf:"application/rtf",svg:"image/svg+xml; charset=utf-8",tif:"image/tiff",tiff:"image/tiff",ts:"video/mp2t",ttf:"font/ttf",txt:"text/plain; charset=utf-8",wasm:"application/wasm",webm:"video/webm",weba:"audio/webm",webmanifest:"application/manifest+json",webp:"image/webp",woff:"font/woff",woff2:"font/woff2",xhtml:"application/xhtml+xml; charset=utf-8",xml:"application/xml; charset=utf-8",zip:"application/zip","3gp":"video/3gpp","3g2":"video/3gpp2",gltf:"model/gltf+json",glb:"model/gltf-binary"},wN=yN;var qv=(...t)=>{let n=t.filter((a)=>a!=="").join("/");n=n.replace(/(?<=\/)\/+/g,"");let i=n.split("/"),o=[];for(let a of i)if(a===".."&&o.length>0&&o.at(-1)!=="..")o.pop();else if(a!==".")o.push(a);return o.join("/")||"."};var Bv={br:".br",zstd:".zst",gzip:".gz"},SN=Object.keys(Bv),bN="index.html",Wv=(t)=>{let n=t.root??"./",i=t.path,o=t.join??qv;return async(a,c)=>{if(a.finalized)return c();let m;if(t.path)m=t.path;else try{if(m=Cp(a.req.path),/(?:^|[\/\\])\.{1,2}(?:$|[\/\\])|[\/\\]{2,}|\\/.test(m))throw Error()}catch{return await t.onNotFound?.(a.req.path,a),c()}let E=o(n,!i&&t.rewriteRequestPath?t.rewriteRequestPath(m):m);if(t.isDir&&await t.isDir(E))E=o(E,bN);let _=t.getContent,I=await _(E,a);if(I instanceof Response)return a.newResponse(I.body,I);if(I!=null){let T=t.mimes&&Ah(E,t.mimes)||Ah(E);if(a.header("Content-Type",T||"application/octet-stream"),t.precompressed&&(!T||Fv.test(T))){let R=new Set(a.req.header("Accept-Encoding")?.split(",").map((P)=>P.trim()));for(let P of SN){if(!R.has(P))continue;let M=await _(E+Bv[P],a);if(M){I=M,a.header("Content-Encoding",P),a.header("Vary","Accept-Encoding",{append:!0});break}}}return await t.onFound?.(E,a),a.body(I)}await t.onNotFound?.(E,a),await c();return}};var xh=(t={})=>async function(i,o){return Wv({...t,getContent:async(m)=>{let E=Bun.file(m);return await E.exists()?E:null},join:EN,isDir:async(m)=>{let E;try{E=(await vN(m)).isDirectory()}catch{}return E}})(i,o)};var _h="x-hono-disable-ssg",VG=(()=>{try{return new Response("SSG is disabled",{status:404,headers:{[_h]:"true"}})}catch{return null}})();var{write:T7}=Bun;var Hv=(t)=>(...n)=>{if(typeof n[0]==="function"){let[i,o]=n;return async function(c,m){let E=await i(c),_=await t(c,E,o);if(_)return _;await m()}}else{let[i,o,a]=n;return(async()=>{let c=await t(i,o,a);if(!c)throw Error("Failed to upgrade WebSocket");return c})()}};var Fu=(t)=>("server"in t.env)?t.env.server:t.env;var _N=Hv((t,n)=>{let i=Fu(t);if(!i)throw TypeError("env has to include the 2nd argument of fetch.");if(i.upgrade(t.req.raw,{data:{events:n,url:new URL(t.req.url),protocol:t.req.header("sec-websocket-protocol")?.split(",")[0]?.trim()??""}}))return new Response(null);return});var Vv=(t)=>t;import{existsSync as k$}from"fs";import{basename as XE,resolve as M$}from"path";var zv="Wait for active agents to finish, or stop them before updating Moi";var IN="cf-access-jwt-assertion",TN="CF_Authorization",RN=new Set(["ERR_JOSE_GENERIC","ERR_JWKS_INVALID","ERR_JWKS_TIMEOUT"]);function PN(t,n){let i=new URL("/cdn-cgi/access/certs",t.teamDomain),o=Xh(i,n?{[dd]:n}:{});return async(a)=>{try{let{payload:c}=await Kh(a,o,{issuer:t.teamDomain,audience:[...t.audience],algorithms:["RS256"],requiredClaims:["exp"],clockTolerance:60}),{sub:m,email:E}=c;return m&&typeof E==="string"&&E?{id:m,email:E}:null}catch(c){if(!(c instanceof G)||RN.has(c.code))console.error(`[moi] Cloudflare Access: could not load signing keys from ${i}: ${c}`);return null}}}function CN({id:t,email:n}){let i={id:t,color:Ui(t),email:n};return br(i)?i:null}var Ih=null;async function qu(t){let n=p().cloudflareAccess;if(!n)return{};if(Ih?.config!==n)Ih={config:n,verify:PN(n)};let i=t.headers.get(IN)??new Bun.CookieMap(t.headers.get("cookie")??"").get(TN),o=i?await Ih.verify(i):null,a=o?CN(o):null;return a?{provider:"cloudflare-access",profile:a}:{provider:"cloudflare-access"}}import{realpath as Gv}from"fs/promises";import{tmpdir as ON}from"os";import{resolve as Bu}from"path";class Gs extends Error{code;constructor(t,n){super(n);this.code=t}}function kN(t,n){if(!n||t.type!=="join"&&t.type!=="profile")return t;return t.profile.id===n.id?{...t,profile:n}:null}class Kv{options;slots=new Map;bindings=new Map;failures=new Map;livenessTimer=null;closed=!1;constructor(t={}){this.options=t}emit(t,n){if(t.closed)return;if((t.socket.getBufferedAmount?.()??0)>1048576){this.disconnect(t,"Collab updates need a fresh connection");return}try{if(t.socket.send(JSON.stringify(n))===0)this.disconnect(t,"Connection lost")}catch{this.disconnect(t,"Connection lost")}}send(t,n){if(t.stopping)throw new Gs("restarting","Collab is restarting");t.child.send(n)}async getSlot(t,n){if(this.closed||n.closed)throw new Gs("unavailable","Collab connection closed");let i=await Gv(t);if(n.workspacePaths.add(i),n.closed)throw new Gs("unavailable","Collab connection closed");if(!(this.options.enabled?await this.options.enabled(i):p().environment==="cloud"))throw new Gs("unavailable","Collaboration is only available in the cloud environment");if(this.closed||n.closed)throw new Gs("unavailable","Collab connection closed");let a=this.slots.get(i);if(a){if(a.stopping){if(await a.child.exited,this.slots.get(i)===a)this.slots.delete(i);return this.getSlot(i,n)}if(a.idleTimer)clearTimeout(a.idleTimer);return a.idleTimer=void 0,a.workspacePaths.add(Bu(t)),a}let c=this.failures.get(i);if(c&&c.retryAfter>Date.now())throw new Gs("restarting","Collab is recovering; reconnect shortly");let m=this.spawn(i);return m.workspacePaths.add(Bu(t)),m}spawn(t){let n=()=>{},i=()=>{},o=new Promise((m,E)=>{n=m,i=E});o.catch(()=>{});let a=crypto.randomUUID(),c={workspacePath:t,workspacePaths:new Set([t]),generation:a,child:void 0,ready:o,resolveReady:n,rejectReady:i,readyTimer:setTimeout(()=>{c.rejectReady(new Gs("startup_timeout","Collab did not start in time")),this.stopSlot(c,"Collab startup timed out")},this.options.startupTimeoutMs??1e4),stopping:!1,clients:new Map};try{c.child=Bun.spawn([process.execPath,this.options.workerPath??he("collab/worker.ts")],{cwd:ON(),env:{PATH:process.env.PATH,MOI_COLLAB_WORKSPACE:t,MOI_COLLAB_GENERATION:a},stdout:"inherit",stderr:"inherit",ipc:(m)=>this.receive(c,m),onExit:()=>this.exited(c)}),this.slots.set(t,c)}catch(m){throw clearTimeout(c.readyTimer),i(m instanceof Error?m:Error("Collab could not start")),m}return c}receive(t,n){if(t.stopping||n.generation!==t.generation)return;if(n.type==="ready"){clearTimeout(t.readyTimer),t.resolveReady();return}if(n.type==="client"){let i=t.clients.get(n.connectionId);if(i){if(this.emit(i,n.message),n.message.type==="welcome"&&i.workspaceId)this.emit(i,Dc(i.workspaceId))}return}}exited(t){let n=t.stopping;if(t.stopping=!0,clearTimeout(t.readyTimer),t.idleTimer)clearTimeout(t.idleTimer);let i=new Gs("worker_exited","Collab restarted; reconnect to restore presence");t.rejectReady(i);for(let o of[...t.clients.values()])this.disconnect(o,i.message);if(this.slots.get(t.workspacePath)===t)this.slots.delete(t.workspacePath);if(!n){let o=(this.failures.get(t.workspacePath)?.count??0)+1;this.failures.set(t.workspacePath,{count:o,retryAfter:Date.now()+Math.min(250*2**Math.min(o-1,7),30000)})}}scheduleIdle(t){if(t.stopping||t.clients.size||t.idleTimer)return;t.idleTimer=setTimeout(()=>this.stopSlot(t,"Collab workspace is idle"),this.options.idleTimeoutMs??60000),t.idleTimer.unref()}stopSlot(t,n){if(t.stopping)return;t.stopping=!0,clearTimeout(t.readyTimer),t.rejectReady(new Gs("restarting",n));for(let o of[...t.clients.values()])this.disconnect(o,n);try{t.child.send({type:"shutdown"})}catch{}let i=setTimeout(()=>t.child.kill("SIGKILL"),2000);i.unref(),t.child.exited.finally(()=>clearTimeout(i))}disconnect(t,n){if(t.closed)return;this.close(t.socket),t.socket.close(1012,n.slice(0,120))}open(t,n,i={}){let o={socket:t,workspacePaths:new Set([Bu(n)]),connectionId:crypto.randomUUID(),closed:!1,lastSeen:Date.now(),joined:!1,...i,queue:Promise.resolve()};this.bindings.set(t,o),o.queue=this.getSlot(n,o).then(async(a)=>{if(o.closed){this.scheduleIdle(a);return}o.slot=a,a.clients.set(o.connectionId,o),await a.ready}).catch((a)=>{this.emit(o,{type:"error",code:"unavailable",message:a instanceof Error?a.message:"Collab unavailable"}),this.disconnect(o,"Collab unavailable")}),this.livenessTimer??=setInterval(()=>{let a=Date.now();for(let c of this.bindings.values()){let m=c.joined?this.options.livenessTimeoutMs??60000:15000;if(a-c.lastSeen>m)this.disconnect(c,"Collab connection timed out")}},5000),this.livenessTimer.unref()}message(t,n){let i=this.bindings.get(t);if(!i||i.closed)return;if((typeof n==="string"?new TextEncoder().encode(n).length:n.byteLength)>Ki){this.disconnect(i,"Collab message is too large");return}let a;try{a=JSON.parse(typeof n==="string"?n:new TextDecoder().decode(n))}catch{}if(!Gi(a)){this.emit(i,{type:"error",code:"invalid_message",message:"Invalid collab message"});return}i.lastSeen=Date.now();let c=kN(a,i.verifiedProfile);if(!c){this.emit(i,{type:"error",code:"user_mismatch",message:"Presence here uses your Cloudflare Access user"}),this.disconnect(i,"User does not match Cloudflare Access");return}i.queue=i.queue.then(()=>{if(i.closed||!i.slot)return;if(c.type==="join")i.joined=!0;this.send(i.slot,{type:"client",connectionId:i.connectionId,message:c})}).catch(()=>this.disconnect(i,"Collab restarted"))}close(t){let n=this.bindings.get(t);if(!n)return;if(n.closed=!0,this.bindings.delete(t),!this.bindings.size&&this.livenessTimer)clearInterval(this.livenessTimer),this.livenessTimer=null;let i=n.slot;if(!i)return;if(i.clients.delete(n.connectionId),!i.stopping)try{this.send(i,{type:"leave",connectionId:n.connectionId})}catch{}this.scheduleIdle(i)}async stopWorkspace(t){let n=Bu(t),i=[...this.slots.values()].find((a)=>a.workspacePaths.has(n)),o=(a)=>{for(let c of this.bindings.values())if(c.workspacePaths.has(a))this.disconnect(c,"Collab stopped for this workspace")};if(o(n),i)o(i.workspacePath);if(!i)try{let a=await Gv(t);o(a),i=this.slots.get(a)}catch(a){if(a instanceof Error&&"code"in a&&(a.code==="ENOENT"||a.code==="ENOTDIR"))return;throw a}if(!i)return;this.stopSlot(i,"Collab stopped for this workspace"),await i.child.exited}async shutdown(){if(this.closed=!0,this.livenessTimer)clearInterval(this.livenessTimer);this.livenessTimer=null;let t=[...this.slots.values()];for(let n of t)this.stopSlot(n,"Moi is shutting down");await Promise.allSettled(t.map((n)=>n.child.exited))}debugSnapshot(){return[...this.slots.values()].map((t)=>({workspacePath:t.workspacePath,pid:t.child.pid,generation:t.generation,connections:t.clients.size,stopping:t.stopping}))}}var Mo=new Kv;var Th=new Map;function Jv(t){let n=p();if(n.environment!=="local"||n.demo||n.agentLauncher)throw Error("Agents can only be installed in local Moi");if(t!=="claude-code"&&t!=="codex")throw Error("This agent requires manual installation");let i=Th.get(t);if(i)return i;let o=(async()=>{if((await Cn())[t])return;let a=t==="claude-code"?"https://claude.ai/install":"https://chatgpt.com/codex/install",c=process.platform==="win32"?["powershell.exe","-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-Command",`$ErrorActionPreference = 'Stop'; irm ${a}.ps1 | iex`]:["bash","-o","pipefail","-c",In[t].command];if(await Bun.spawn(c,{stdin:"ignore",stdout:"inherit",stderr:"inherit",timeout:300000}).exited!==0)throw Error("Installation failed or timed out. Try again.");if(!(await Cn())[t])throw Error("The installer finished, but the agent could not be found. Restart Moi.")})().finally(()=>Th.delete(t));return Th.set(t,o),o}var No=new Bs;No.get("/status",async(t)=>{t.header("Cache-Control","no-store");let n=t.req.query("refresh")==="true";if(n)await Ke({refresh:!0});let i=await Promise.all(ie().map(async({id:o})=>[o,{availability:await B.getAvailability(o,n),login:B.getLogin(o)}]));return t.json(Object.fromEntries(i))});No.use("/:type/*",async(t,n)=>{let i=t.req.param("type");if(!Yt(i))return t.text("Unknown agent",404);let o=y(i);if(!o.startLogin||!o.authStatus)return t.text("This agent requires terminal sign-in",409);t.set("harnessType",i),t.header("Cache-Control","no-store"),await n()});No.post("/:type/auth/install",async(t)=>{let n=t.req.header("Origin");if(n&&n!==new URL(t.req.url).origin)return t.text("Invalid origin",403);try{let i=t.get("harnessType");return await Jv(i),await B.refresh(i),t.json({ok:!0})}catch(i){return t.text(i instanceof Error?i.message:"Could not install agent",400)}});No.post("/:type/auth/login",async(t)=>{try{return t.json(await B.startLogin(t.get("harnessType")))}catch(n){return t.text(n instanceof Error?n.message:"Could not start sign-in",500)}});No.post("/:type/auth/login/:id/code",async(t)=>{try{let n=await t.req.json();if(!n||typeof n!=="object"||!("code"in n)||typeof n.code!=="string"||n.code.length>4096||!n.code.trim())return t.text("Enter the authorization code",400);return await B.submitCode(t.get("harnessType"),t.req.param("id"),n.code),t.json({ok:!0})}catch(n){return t.text(n instanceof Error?n.message:"Could not submit code",400)}});var $o=new Map;function Yv(t){return[t.source,t.kind??"",t.name??"",t.module??"",t.fn??"",t.message].join("\x00")}function Wu(t,n){let i=$o.get(t)??[],o=n.message.slice(0,1000),a=Yv({...n,message:o}),c=i.findIndex((m)=>Yv(m)===a);if(c!==-1){let[m]=i.splice(c,1);m.count++,m.ts=Date.now(),i.push(m)}else if(i.push({ts:Date.now(),source:n.source,...n.kind?{kind:n.kind}:{},...n.name?{name:n.name}:{},...n.module?{module:n.module}:{},...n.fn?{fn:n.fn}:{},message:o,...n.stack?{stack:n.stack.slice(0,4000)}:{},count:1}),i.length>100)i.shift();$o.set(t,i)}function Xv(t){return($o.get(t)??[]).map((n)=>({...n}))}function Rh(t){return $o.get(t)?.length??0}function Zv(t){let n=Rh(t);return $o.delete(t),n}function Qv(t){let n=t.match(/^(widgets|views)\/([^/]+)$/);if(!n)return null;return{kind:n[1]==="widgets"?"widget":"view",name:n[2]}}function Hu(t,n,i){let o=new Set,a=new Set,c=new Set(i.map((_)=>_.name));for(let _ of i){if(_.status==="failed")Wu(t,{source:"build",kind:n,name:_.name,message:_.error??"Build failed"});if(_.status==="built"){a.add(_.name);for(let I of _.serverModules??[])o.add(I)}}let m=$o.get(t);if(!m)return;let E=m.filter((_)=>{if(_.kind===n&&_.name&&(a.has(_.name)||!c.has(_.name)))return!1;if(_.source==="rpc"&&_.module&&o.has(_.module))return!1;return!0});$o.set(t,E)}import{realpathSync as sE,statSync as lE}from"fs";import{mkdir as BN,readdir as uE,rm as iE}from"fs/promises";import{join as Ts,resolve as oE,sep as aE}from"path";import{readdir as MN}from"fs/promises";import{dirname as NN,join as Do,resolve as $N}from"path";var Ph=/\.[mc]?[jt]sx?$/,DN=/\.[mc]?ts$/,LN=256;async function Tc(t){try{return(await MN(t)).filter((i)=>/\.(tsx|ts)$/.test(i)&&!i.startsWith("_")&&!i.endsWith(".server.ts")).map((i)=>i.replace(/\.tsx?$/,""))}catch(n){if(n instanceof Error&&"code"in n&&n.code==="ENOENT")return[];throw n}}async function tE(t,n){for(let i of[".tsx",".ts"]){let o=Do(t,`${n}${i}`);if(await Bun.file(o).exists())return o}return null}var jN={ts:new Bun.Transpiler({loader:"ts"}),tsx:new Bun.Transpiler({loader:"tsx"})};function UN(t,n="tsx"){let i;try{i=jN[n].scanImports(t)}catch{return null}return i.map((o)=>o.path).filter((o)=>/^\.\.?\//.test(o))}async function Ch(t,n=1/0){let i={entrypoints:new Set([...t].map((a)=>$N(a))),modules:new Map,complete:!0},o=[...i.entrypoints];while(o.length>0){let a=o.pop();if(i.modules.has(a))continue;if(i.modules.size>=LN){i.complete=!1;break}let c={modifiedAt:0,imports:[]};i.modules.set(a,c);try{let m=Bun.file(a);if(!await m.exists()){i.complete=!1;continue}if(c.modifiedAt=m.lastModified,c.modifiedAt>=n){i.complete=!1;break}if(!Ph.test(a))continue;let E=UN(await m.text(),DN.test(a)?"ts":"tsx");if(!E){i.complete=!1;continue}for(let _ of E){let I=await qN(NN(a),_);if(!I){i.complete=!1;continue}c.imports.push(I),o.push(I)}}catch{i.complete=!1}}return i}async function rE(t){let n=[];for(let i of["views","widgets"]){let o=Do(t,".moi",i);for(let a of await Tc(o))for(let c of[".tsx",".ts",".server.ts"]){let m=Do(o,a+c);if(await Bun.file(m).exists())n.push(m)}}return Ch(n)}function Oh(t,n){let i=new Set,o=[...n];while(o.length>0){let a=o.pop();if(i.has(a))continue;i.add(a),o.push(...t.modules.get(a)?.imports??[])}return i}var eE=[".tsx",".ts",".jsx",".js",".mjs",".cjs",".json",".mts",".cts"],FN={".js":[".ts",".tsx"],".jsx":[".tsx"],".mjs":[".mts"]};async function qN(t,n){let i=Do(t,n),o=[i],a=/\.[^./\\]+$/.exec(i)?.[0]??"";for(let E of FN[a]??[])o.push(i.slice(0,i.length-a.length)+E);for(let E of eE)o.push(i+E);for(let E of o)if(await Bun.file(E).exists())return E;let c=await Bun.file(Do(i,"package.json")).json().catch(()=>null),m=typeof c==="object"&&c!==null&&"main"in c&&typeof c.main==="string"?c.main:null;if(m){let E=Do(i,m);if(await Bun.file(E).exists())return E}for(let E of eE){let _=Do(i,`index${E}`);if(await Bun.file(_).exists())return _}return null}var nE="%%MOI_APPLET_API_BASE%%";function bn(t,n){let i=Ts(t,".moi"),o=n==="widget"?"widgets":"views",a=Ts(i,o),c=Ts(i,".build",o),m=Ts(c,"manifest.json");return{moiRoot:i,sourceDir:a,buildDir:c,manifestPath:m}}function Vu(t,n,i){try{let{buildDir:o}=bn(t,n),a=lE(Ts(o,i,"index.js"));return`${a.size}-${Math.trunc(a.mtimeMs)}`}catch{return}}async function WN(t,n,i){let o=Bun.file(Ts(t,n,"index.js"));if(!await o.exists())return!0;return!(await Ch([i],o.lastModified)).complete}async function zu(t){try{let n=await uE(t,{withFileTypes:!0}),i=[];for(let o of n){if(!o.isDirectory())continue;if(await Bun.file(Ts(t,o.name,"index.js")).exists())i.push(o.name)}return i}catch{return[]}}async function HN(t,n){let i;try{i=await uE(t,{withFileTypes:!0})}catch{return}for(let o of i){if(o.isDirectory()){if(!n.has(o.name))await iE(Ts(t,o.name),{recursive:!0,force:!0}).catch(()=>{});continue}if(o.isFile()&&o.name.endsWith(".js"))await iE(Ts(t,o.name),{force:!0}).catch(()=>{})}}var VN=/\.js$/,zN=/^[a-zA-Z0-9_-][a-zA-Z0-9._-]*$/,GN="text/javascript; charset=utf-8",KN="public, max-age=604800, immutable",JN=/^chunk-[0-9a-z]+\.\w+$|-[0-9a-f]{6,}\.\w+$/i;async function Gu(t,n,i,o,a,c){if(!/^[a-zA-Z0-9_-]+$/.test(n))return new Response("Invalid name",{status:400});if(!zN.test(i)||i.includes(".."))return new Response("Invalid file",{status:400});let{buildDir:m}=bn(o,t),E=Ts(m,n,i),_=Bun.file(E);if(!await _.exists())return new Response(`"${n}" not built. Run: moi bundle`,{status:404});let I;if(JN.test(i))I={"Cache-Control":KN};else{let T=`"${_.size}-${Math.trunc(_.lastModified)}-${Bun.hash(a)}-url-base-v2"`;if(I={ETag:T,"Cache-Control":"private, no-cache"},c===T)return new Response(null,{status:304,headers:I})}if(VN.test(i)){let T=`(new URL(import.meta.url).pathname.match(/^\\/api\\/workspaces\\/[^/]+/)?.[0] ?? ${JSON.stringify(a)})`,R=(await _.text()).replace(/(["'])([^"'\n]*%%MOI_APPLET_API_BASE%%[^"'\n]*)\1/g,(P,M,N)=>"("+N.split(nE).map((H)=>JSON.stringify(H)).join(" + "+T+" + ")+")");return new Response(R,{headers:{"Content-Type":GN,...I}})}return new Response(_,{headers:{"Content-Type":_.type||"application/octet-stream",...I}})}var cE="index.js",YN="module";function kh(t,n,i){let o=new URL(t).pathname.split(`/workspaces/${encodeURIComponent(n)}/${i}/`)[1]??"",a=o.indexOf("/");if(a===-1)return{name:o.replace(/\.js$/,""),file:cE};let c=o.slice(a+1);return{name:o.slice(0,a),file:c===YN?cE:c}}var XN=/\.(mp4|webm|mov|m4v|mkv|mp3|wav|ogg|oga|m4a|flac|aac|opus|png|jpe?g|gif|webp|avif|svg|ico|pdf|vtt|srt)$/i;function Mh(t,n){let i;try{i=decodeURIComponent(n)}catch{return new Response("Bad path",{status:400})}if(!i||i.includes("\x00"))return new Response("Bad path",{status:400});if(i.split("/").some((_)=>_===""||_==="."||_===".."||_.startsWith(".")))return new Response("Forbidden",{status:403});if(!XN.test(i))return new Response("Unsupported file type",{status:415});let a=oE(t),c=oE(t,i);if(c!==a&&!c.startsWith(a+aE))return new Response("Forbidden",{status:403});let m;try{m=sE(c)}catch{return new Response("Not found",{status:404})}let E;try{E=sE(a)}catch{return new Response("Forbidden",{status:403})}if(m!==E&&!m.startsWith(E+aE))return new Response("Forbidden",{status:403});return m}async function dE(t,n,i,o){let a=Mh(t,n);if(a instanceof Response)return a;let c=Bun.file(a),m;try{m=lE(a,{bigint:!0})}catch{return new Response("Not found",{status:404})}let E=Number(m.size),_=c.type||"application/octet-stream",I=`"${E}-${m.mtimeNs}"`,T={ETag:I,"Cache-Control":"private, no-cache"};if(o===I)return new Response(null,{status:304,headers:T});let R=i?ZN(i,E):null;if(R==="invalid")return new Response("Range Not Satisfiable",{status:416,headers:{...T,"Content-Range":`bytes */${E}`,"Accept-Ranges":"bytes"}});if(R){let{start:P,end:M}=R;return new Response(c.slice(P,M+1),{status:206,headers:{...T,"Content-Type":_,"Content-Length":String(M-P+1),"Content-Range":`bytes ${P}-${M}/${E}`,"Accept-Ranges":"bytes"}})}return new Response(c,{headers:{...T,"Content-Type":_,"Content-Length":String(E),"Accept-Ranges":"bytes"}})}function ZN(t,n){let i=/^bytes=(\d*)-(\d*)$/.exec(t.trim());if(!i)return null;let o=i[1]!=="",a=i[2]!=="";if(!o&&!a)return null;if(n===0)return"invalid";let c,m;if(!o){let E=parseInt(i[2],10);c=Math.max(0,n-E),m=n-1}else c=parseInt(i[1],10),m=a?Math.min(parseInt(i[2],10),n-1):n-1;if(c>m||c>=n||c<0)return"invalid";return{start:c,end:m}}async function Ku(t,n,i,o){let a=performance.now(),{sourceDir:c,buildDir:m,moiRoot:E}=bn(t,n),_=await Tc(c);if(_.length>0)await BN(m,{recursive:!0});await HN(m,new Set(_)),await Yi(t,n,_);let I=await Promise.all(_.map(async(P)=>{if(o&&P!==o)return{name:P,status:"skipped"};let M=await tE(c,P);if(!M)return{name:P,status:"failed",error:"Source file not found"};if(!i&&!await WN(m,P,M))return{name:P,status:"skipped"};return{name:P,srcPath:M,status:"pending"}})),T=new Map((await Fi({moiRoot:E,kind:n,jobs:I.filter((P)=>P.status==="pending").map((P)=>({name:P.name,srcPath:P.srcPath,outDir:Ts(m,P.name)}))})).map((P)=>[P.name,P])),R=I.map((P)=>{if(P.status==="failed")return{name:P.name,status:"failed",error:P.error};if(P.status==="skipped")return{name:P.name,status:"skipped"};let M=T.get(P.name);if(!M)return{name:P.name,status:"failed",error:"Build worker returned no result"};if(M.status==="failed")return{name:P.name,status:"failed",error:M.error};return{name:P.name,status:"built",serverModules:M.serverModules,config:M.config??null}});return{names:_,results:R,ms:Math.round(performance.now()-a)}}import{tracingChannel as QN,channel as e$}from"diagnostics_channel";var mr=e$("lru-cache:metrics"),Rc=QN("lru-cache"),t$=typeof performance=="object"&&performance&&typeof performance.now=="function"?performance:Date,Nh=()=>mr.hasSubscribers||Rc.hasSubscribers,pE=new Set,fE=typeof process=="object"&&process?process:{},r$=(t,n,i,o)=>{typeof fE.emitWarning=="function"?fE.emitWarning(t,n,i,o):console.error(`[${i}] ${n}: ${t}`)},n$=(t)=>!pE.has(t),oo=(t)=>!!t&&t===Math.floor(t)&&t>0&&isFinite(t),hE=(t)=>oo(t)?t<=Math.pow(2,8)?Uint8Array:t<=Math.pow(2,16)?Uint16Array:t<=Math.pow(2,32)?Uint32Array:t<=Number.MAX_SAFE_INTEGER?Ju:null:null,Ju=class extends Array{constructor(t){super(t),this.fill(0)}},s$=class t{heap;length;static#t=!1;static create(n){let i=hE(n);if(!i)return[];t.#t=!0;let o=new t(n,i);return t.#t=!1,o}constructor(n,i){if(!t.#t)throw TypeError("instantiate Stack using Stack.create(n)");this.heap=new i(n),this.length=0}push(n){this.heap[this.length++]=n}pop(){return this.heap[--this.length]}},mE=class t{#t;#e;#r;#o;#n;#i;#S;#f;get perf(){return this.#f}ttl;ttlResolution;ttlAutopurge;updateAgeOnGet;updateAgeOnHas;allowStale;noDisposeOnSet;noUpdateTTL;maxEntrySize;sizeCalculation;noDeleteOnFetchRejection;noDeleteOnStaleGet;allowStaleOnFetchAbort;allowStaleOnFetchRejection;ignoreFetchAbort;backgroundFetchSize;#a;#p;#u;#c;#s;#g;#y;#h;#d;#A;#m;#x;#_;#b;#v;#I;#L;#w;#k;static unsafeExposeInternals(n){return{starts:n.#_,ttls:n.#b,autopurgeTimers:n.#v,sizes:n.#x,keyMap:n.#u,keyList:n.#c,valList:n.#s,next:n.#g,prev:n.#y,get head(){return n.#h},get tail(){return n.#d},free:n.#A,isBackgroundFetch:(i)=>n.#l(i),backgroundFetch:(i,o,a,c)=>n.#F(i,o,a,c),moveToTail:(i)=>n.#D(i),indexes:(i)=>n.#T(i),rindexes:(i)=>n.#R(i),isStale:(i)=>n.#E(i)}}get max(){return this.#t}get maxSize(){return this.#e}get calculatedSize(){return this.#p}get size(){return this.#a}get fetchMethod(){return this.#i}get memoMethod(){return this.#S}get dispose(){return this.#r}get onInsert(){return this.#o}get disposeAfter(){return this.#n}constructor(n){let{max:i=0,ttl:o,ttlResolution:a=1,ttlAutopurge:c,updateAgeOnGet:m,updateAgeOnHas:E,allowStale:_,dispose:I,onInsert:T,disposeAfter:R,noDisposeOnSet:P,noUpdateTTL:M,maxSize:N=0,maxEntrySize:H=0,sizeCalculation:Z,fetchMethod:V,memoMethod:me,noDeleteOnFetchRejection:te,noDeleteOnStaleGet:we,allowStaleOnFetchRejection:Te,allowStaleOnFetchAbort:De,ignoreFetchAbort:je,backgroundFetchSize:Ct=1,perf:Ot}=n;if(this.backgroundFetchSize=Ct,Ot!==void 0&&typeof Ot?.now!="function")throw TypeError("perf option must have a now() method if specified");if(this.#f=Ot??t$,i!==0&&!oo(i))throw TypeError("max option must be a nonnegative integer");let yi=i?hE(i):Array;if(!yi)throw Error("invalid max value: "+i);if(this.#t=i,this.#e=N,this.maxEntrySize=H||this.#e,this.sizeCalculation=Z,this.sizeCalculation){if(!this.#e&&!this.maxEntrySize)throw TypeError("cannot set sizeCalculation without setting maxSize or maxEntrySize");if(typeof this.sizeCalculation!="function")throw TypeError("sizeCalculation set to non-function")}if(me!==void 0&&typeof me!="function")throw TypeError("memoMethod must be a function if defined");if(this.#S=me,V!==void 0&&typeof V!="function")throw TypeError("fetchMethod must be a function if specified");if(this.#i=V,this.#L=!!V,this.#u=new Map,this.#c=Array.from({length:i}).fill(void 0),this.#s=Array.from({length:i}).fill(void 0),this.#g=new yi(i),this.#y=new yi(i),this.#h=0,this.#d=0,this.#A=s$.create(i),this.#a=0,this.#p=0,typeof I=="function"&&(this.#r=I),typeof T=="function"&&(this.#o=T),typeof R=="function"?(this.#n=R,this.#m=[]):(this.#n=void 0,this.#m=void 0),this.#I=!!this.#r,this.#k=!!this.#o,this.#w=!!this.#n,this.noDisposeOnSet=!!P,this.noUpdateTTL=!!M,this.noDeleteOnFetchRejection=!!te,this.allowStaleOnFetchRejection=!!Te,this.allowStaleOnFetchAbort=!!De,this.ignoreFetchAbort=!!je,this.maxEntrySize!==0){if(this.#e!==0&&!oo(this.#e))throw TypeError("maxSize must be a positive integer if specified");if(!oo(this.maxEntrySize))throw TypeError("maxEntrySize must be a positive integer if specified");this.#K()}if(this.allowStale=!!_,this.noDeleteOnStaleGet=!!we,this.updateAgeOnGet=!!m,this.updateAgeOnHas=!!E,this.ttlResolution=oo(a)||a===0?a:1,this.ttlAutopurge=!!c,this.ttl=o||0,this.ttl){if(!oo(this.ttl))throw TypeError("ttl must be a positive integer if specified");this.#q()}if(this.#t===0&&this.ttl===0&&this.#e===0)throw TypeError("At least one of max, maxSize, or ttl is required");if(!this.ttlAutopurge&&!this.#t&&!this.#e){let Qr="LRU_CACHE_UNBOUNDED";n$(Qr)&&(pE.add(Qr),r$("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning",Qr,t))}}getRemainingTTL(n){return this.#u.has(n)?1/0:0}#q(){let n=new Ju(this.#t),i=new Ju(this.#t);this.#b=n,this.#_=i;let o=this.ttlAutopurge?Array.from({length:this.#t}):void 0;this.#v=o,this.#B=(_,I,T=this.#f.now())=>{i[_]=I!==0?T:0,n[_]=I,a(_,I)},this.#M=(_)=>{i[_]=n[_]!==0?this.#f.now():0,a(_,n[_])};let a=this.ttlAutopurge?(_,I)=>{if(o?.[_]&&(clearTimeout(o[_]),o[_]=void 0),I&&I!==0&&o){let T=setTimeout(()=>{this.#E(_)?(this.#P(this.#c[_],"expire"),o[_]=void 0):a(_,E(_))},I+1);T.unref&&T.unref(),o[_]=T}}:()=>{};this.#C=(_,I)=>{if(n[I]){let T=n[I],R=i[I];if(!T||!R)return;_.ttl=T,_.start=R,_.now=c||m();let P=_.now-R;_.remainingTTL=T-P}};let c=0,m=()=>{let _=this.#f.now();if(this.ttlResolution>0){c=_;let I=setTimeout(()=>c=0,this.ttlResolution);I.unref&&I.unref()}return _};this.getRemainingTTL=(_)=>{let I=this.#u.get(_);return I===void 0?0:E(I)};let E=(_)=>{let I=n[_],T=i[_];if(!I||!T)return 1/0;let R=(c||m())-T;return I-R};this.#E=(_)=>{let I=i[_],T=n[_];return!!T&&!!I&&(c||m())-I>T}}#M=()=>{};#C=()=>{};#B=()=>{};#E=()=>!1;#K(){let n=new Ju(this.#t);this.#p=0,this.#x=n,this.#N=(i)=>{this.#p-=n[i],n[i]=0},this.#W=(i,o,a,c)=>{if(!oo(a)){if(this.#l(o))return this.backgroundFetchSize;if(c){if(typeof c!="function")throw TypeError("sizeCalculation must be a function");if(a=c(o,i),!oo(a))throw TypeError("sizeCalculation return invalid (expect positive integer)")}else throw TypeError("invalid size value (must be positive integer). When maxSize or maxEntrySize is used, sizeCalculation or size must be set.")}return a},this.#j=(i,o,a)=>{if(n[i]=o,this.#e){let c=this.#e-n[i];for(;this.#p>c;)this.#U(!0)}this.#p+=n[i],a&&(a.entrySize=o,a.totalCalculatedSize=this.#p)}}#N=(n)=>{};#j=(n,i,o)=>{};#W=(n,i,o,a)=>{if(o||a)throw TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0};*#T({allowStale:n=this.allowStale}={}){if(this.#a)for(let i=this.#d;this.#H(i)&&((n||!this.#E(i))&&(yield i),i!==this.#h);)i=this.#y[i]}*#R({allowStale:n=this.allowStale}={}){if(this.#a)for(let i=this.#h;this.#H(i)&&((n||!this.#E(i))&&(yield i),i!==this.#d);)i=this.#g[i]}#H(n){return n!==void 0&&this.#u.get(this.#c[n])===n}*entries(){for(let n of this.#T())this.#s[n]!==void 0&&this.#c[n]!==void 0&&!this.#l(this.#s[n])&&(yield[this.#c[n],this.#s[n]])}*rentries(){for(let n of this.#R())this.#s[n]!==void 0&&this.#c[n]!==void 0&&!this.#l(this.#s[n])&&(yield[this.#c[n],this.#s[n]])}*keys(){for(let n of this.#T()){let i=this.#c[n];i!==void 0&&!this.#l(this.#s[n])&&(yield i)}}*rkeys(){for(let n of this.#R()){let i=this.#c[n];i!==void 0&&!this.#l(this.#s[n])&&(yield i)}}*values(){for(let n of this.#T())this.#s[n]!==void 0&&!this.#l(this.#s[n])&&(yield this.#s[n])}*rvalues(){for(let n of this.#R())this.#s[n]!==void 0&&!this.#l(this.#s[n])&&(yield this.#s[n])}[Symbol.iterator](){return this.entries()}[Symbol.toStringTag]="LRUCache";find(n,i={}){for(let o of this.#T()){let a=this.#s[o],c=this.#l(a)?a.__staleWhileFetching:a;if(c!==void 0&&n(c,this.#c[o],this))return this.#$(this.#c[o],i)}}forEach(n,i=this){for(let o of this.#T()){let a=this.#s[o],c=this.#l(a)?a.__staleWhileFetching:a;c!==void 0&&n.call(i,c,this.#c[o],this)}}rforEach(n,i=this){for(let o of this.#R()){let a=this.#s[o],c=this.#l(a)?a.__staleWhileFetching:a;c!==void 0&&n.call(i,c,this.#c[o],this)}}purgeStale(){let n=!1;for(let i of this.#R({allowStale:!0}))this.#E(i)&&(this.#P(this.#c[i],"expire"),n=!0);return n}info(n){let i=this.#u.get(n);if(i===void 0)return;let o=this.#s[i],a=this.#l(o)?o.__staleWhileFetching:o;if(a===void 0)return;let c={value:a};if(this.#b&&this.#_){let m=this.#b[i],E=this.#_[i];if(m&&E){let _=m-(this.#f.now()-E);c.ttl=_,c.start=Date.now()}}return this.#x&&(c.size=this.#x[i]),c}dump(){let n=[];for(let i of this.#T({allowStale:!0})){let o=this.#c[i],a=this.#s[i],c=this.#l(a)?a.__staleWhileFetching:a;if(c===void 0||o===void 0)continue;let m={value:c};if(this.#b&&this.#_){m.ttl=this.#b[i];let E=this.#f.now()-this.#_[i];m.start=Math.floor(Date.now()-E)}this.#x&&(m.size=this.#x[i]),n.unshift([o,m])}return n}load(n){this.clear();for(let[i,o]of n){if(o.start){let a=Date.now()-o.start;o.start=this.#f.now()-a}this.#O(i,o.value,o)}}set(n,i,o={}){let{status:a=mr.hasSubscribers?{}:void 0}=o;o.status=a,a&&(a.op="set",a.key=n,i!==void 0&&(a.value=i),a.cache=this);let c=this.#O(n,i,o);return a&&mr.hasSubscribers&&mr.publish(a),c}#O(n,i,o,a){let{ttl:c=this.ttl,start:m,noDisposeOnSet:E=this.noDisposeOnSet,sizeCalculation:_=this.sizeCalculation,status:I}=o,T=this.#l(i);if(i===void 0)return I&&(I.set="deleted"),this.delete(n),this;let{noUpdateTTL:R=this.noUpdateTTL}=o;I&&!T&&(I.value=i);let P=this.#W(n,i,o.size||0,_,I);if(this.maxEntrySize&&P>this.maxEntrySize)return this.#P(n,"set"),I&&(I.set="miss",I.maxEntrySizeExceeded=!0),this;let M=this.#a===0?void 0:this.#u.get(n);if(M===void 0)M=this.#a===0?this.#d:this.#A.length!==0?this.#A.pop():this.#a===this.#t?this.#U(!1):this.#a,this.#c[M]=n,this.#s[M]=i,this.#u.set(n,M),this.#g[this.#d]=M,this.#y[M]=this.#d,this.#d=M,this.#a++,this.#j(M,P,I),I&&(I.set="add"),R=!1,this.#k&&!T&&this.#o?.(i,n,"add");else{this.#D(M);let N=this.#s[M];if(i!==N){if(!E)if(this.#l(N)){N!==a&&N.__abortController.abort(Error("replaced"));let{__staleWhileFetching:H}=N;H!==void 0&&H!==i&&(this.#I&&this.#r?.(H,n,"set"),this.#w&&this.#m?.push([H,n,"set"]))}else this.#I&&this.#r?.(N,n,"set"),this.#w&&this.#m?.push([N,n,"set"]);if(this.#N(M),this.#j(M,P,I),this.#s[M]=i,!T){let H=N&&this.#l(N)?N.__staleWhileFetching:N,Z=H===void 0?"add":i!==H?"replace":"update";I&&(I.set=Z,H!==void 0&&(I.oldValue=H)),this.#k&&this.onInsert?.(i,n,Z)}}else T||(I&&(I.set="update"),this.#k&&this.onInsert?.(i,n,"update"))}if(c!==0&&!this.#b&&this.#q(),this.#b&&(R||this.#B(M,c,m),I&&this.#C(I,M)),!E&&this.#w&&this.#m){let N=this.#m,H;for(;H=N?.shift();)this.#n?.(...H)}return this}pop(){try{for(;this.#a;){let n=this.#s[this.#h];if(this.#U(!0),this.#l(n)){if(n.__staleWhileFetching)return n.__staleWhileFetching}else if(n!==void 0)return n}}finally{if(this.#w&&this.#m){let n=this.#m,i;for(;i=n?.shift();)this.#n?.(...i)}}}#U(n){let i=this.#h,o=this.#c[i],a=this.#s[i],c=this.#l(a);c&&a.__abortController.abort(Error("evicted"));let m=c?a.__staleWhileFetching:a;return(this.#I||this.#w)&&m!==void 0&&(this.#I&&this.#r?.(m,o,"evict"),this.#w&&this.#m?.push([m,o,"evict"])),this.#N(i),this.#v?.[i]&&(clearTimeout(this.#v[i]),this.#v[i]=void 0),n&&(this.#c[i]=void 0,this.#s[i]=void 0,this.#A.push(i)),this.#a===1?(this.#h=this.#d=0,this.#A.length=0):this.#h=this.#g[i],this.#u.delete(o),this.#a--,i}has(n,i={}){let{status:o=mr.hasSubscribers?{}:void 0}=i;i.status=o,o&&(o.op="has",o.key=n,o.cache=this);let a=this.#J(n,i);return mr.hasSubscribers&&mr.publish(o),a}#J(n,i={}){let{updateAgeOnHas:o=this.updateAgeOnHas,status:a}=i,c=this.#u.get(n);if(c!==void 0){let m=this.#s[c];if(this.#l(m)&&m.__staleWhileFetching===void 0)return!1;if(this.#E(c))a&&(a.has="stale",this.#C(a,c));else return o&&this.#M(c),a&&(a.has="hit",this.#C(a,c)),!0}else a&&(a.has="miss");return!1}peek(n,i={}){let{status:o=Nh()?{}:void 0}=i;o&&(o.op="peek",o.key=n,o.cache=this),i.status=o;let a=this.#Y(n,i);return mr.hasSubscribers&&mr.publish(o),a}#Y(n,i){let{status:o,allowStale:a=this.allowStale}=i,c=this.#u.get(n);if(c===void 0||!a&&this.#E(c)){o&&(o.peek=c===void 0?"miss":"stale");return}let m=this.#s[c],E=this.#l(m)?m.__staleWhileFetching:m;return o&&(E!==void 0?(o.peek="hit",o.value=E):o.peek="miss"),E}#F(n,i,o,a){let c=i===void 0?void 0:this.#s[i];if(this.#l(c))return c;let m=new AbortController,{signal:E}=o;E?.addEventListener("abort",()=>m.abort(E.reason),{signal:m.signal});let _={signal:m.signal,options:o,context:a},I=(H,Z=!1)=>{let{aborted:V}=m.signal,me=o.ignoreFetchAbort&&H!==void 0,te=o.ignoreFetchAbort||!!(o.allowStaleOnFetchAbort&&H!==void 0);if(o.status&&(V&&!Z?(o.status.fetchAborted=!0,o.status.fetchError=m.signal.reason,me&&(o.status.fetchAbortIgnored=!0)):o.status.fetchResolved=!0),V&&!me&&!Z)return R(m.signal.reason,te);let we=M,Te=this.#s[i];return(Te===M||Te===void 0&&me&&Z)&&(H===void 0?we.__staleWhileFetching!==void 0?this.#s[i]=we.__staleWhileFetching:this.#P(n,"fetch"):(o.status&&(o.status.fetchUpdated=!0),this.#O(n,H,_.options,we))),H},T=(H)=>(o.status&&(o.status.fetchRejected=!0,o.status.fetchError=H),R(H,!1)),R=(H,Z)=>{let{aborted:V}=m.signal,me=V&&o.allowStaleOnFetchAbort,te=me||o.allowStaleOnFetchRejection,we=te||o.noDeleteOnFetchRejection,Te=M;if(this.#s[i]===M&&(!we||!Z&&Te.__staleWhileFetching===void 0?this.#P(n,"fetch"):me||(this.#s[i]=Te.__staleWhileFetching)),te)return o.status&&Te.__staleWhileFetching!==void 0&&(o.status.returnedStale=!0),Te.__staleWhileFetching;if(Te.__returned===Te)throw H},P=(H,Z)=>{let V=this.#i?.(n,c,_);m.signal.addEventListener("abort",()=>{(!o.ignoreFetchAbort||o.allowStaleOnFetchAbort)&&(H(void 0),o.allowStaleOnFetchAbort&&(H=(me)=>I(me,!0)))}),V&&V instanceof Promise?V.then((me)=>H(me===void 0?void 0:me),Z):V!==void 0&&H(V)};o.status&&(o.status.fetchDispatched=!0);let M=new Promise(P).then(I,T),N=Object.assign(M,{__abortController:m,__staleWhileFetching:c,__returned:void 0});return i===void 0?(this.#O(n,N,{..._.options,status:void 0}),i=this.#u.get(n)):this.#s[i]=N,N}#l(n){if(!this.#L)return!1;let i=n;return!!i&&i instanceof Promise&&i.hasOwnProperty("__staleWhileFetching")&&i.__abortController instanceof AbortController}fetch(n,i={}){let o=Rc.hasSubscribers,{status:a=Nh()?{}:void 0}=i;i.status=a,a&&i.context&&(a.context=i.context);let c=this.#V(n,i);return a&&o&&(a.trace=!0,Rc.tracePromise(()=>c,a).catch(()=>{})),c}async#V(n,i={}){let{allowStale:o=this.allowStale,updateAgeOnGet:a=this.updateAgeOnGet,noDeleteOnStaleGet:c=this.noDeleteOnStaleGet,ttl:m=this.ttl,noDisposeOnSet:E=this.noDisposeOnSet,size:_=0,sizeCalculation:I=this.sizeCalculation,noUpdateTTL:T=this.noUpdateTTL,noDeleteOnFetchRejection:R=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:P=this.allowStaleOnFetchRejection,ignoreFetchAbort:M=this.ignoreFetchAbort,allowStaleOnFetchAbort:N=this.allowStaleOnFetchAbort,context:H,forceRefresh:Z=!1,status:V,signal:me}=i;if(V&&(V.op="fetch",V.key=n,Z&&(V.forceRefresh=!0),V.cache=this),!this.#L)return V&&(V.fetch="get"),this.#$(n,{allowStale:o,updateAgeOnGet:a,noDeleteOnStaleGet:c,status:V});let te={allowStale:o,updateAgeOnGet:a,noDeleteOnStaleGet:c,ttl:m,noDisposeOnSet:E,size:_,sizeCalculation:I,noUpdateTTL:T,noDeleteOnFetchRejection:R,allowStaleOnFetchRejection:P,allowStaleOnFetchAbort:N,ignoreFetchAbort:M,status:V,signal:me},we=this.#u.get(n);if(we===void 0){V&&(V.fetch="miss");let Te=this.#F(n,we,te,H);return Te.__returned=Te}else{let Te=this.#s[we];if(this.#l(Te)){let Ot=o&&Te.__staleWhileFetching!==void 0;return V&&(V.fetch="inflight",Ot&&(V.returnedStale=!0)),Ot?Te.__staleWhileFetching:Te.__returned=Te}let De=this.#E(we);if(!Z&&!De)return V&&(V.fetch="hit"),this.#D(we),a&&this.#M(we),V&&this.#C(V,we),Te;let je=this.#F(n,we,te,H),Ct=je.__staleWhileFetching!==void 0&&o;return V&&(V.fetch=De?"stale":"refresh",Ct&&De&&(V.returnedStale=!0)),Ct?je.__staleWhileFetching:je.__returned=je}}forceFetch(n,i={}){let o=Rc.hasSubscribers,{status:a=Nh()?{}:void 0}=i;i.status=a,a&&i.context&&(a.context=i.context);let c=this.#X(n,i);return a&&o&&(a.trace=!0,Rc.tracePromise(()=>c,a).catch(()=>{})),c}async#X(n,i={}){let o=await this.#V(n,i);if(o===void 0)throw Error("fetch() returned undefined");return o}memo(n,i={}){let{status:o=mr.hasSubscribers?{}:void 0}=i;i.status=o,o&&(o.op="memo",o.key=n,i.context&&(o.context=i.context),o.cache=this);let a=this.#Z(n,i);return o&&(o.value=a),mr.hasSubscribers&&mr.publish(o),a}#Z(n,i={}){let o=this.#S;if(!o)throw Error("no memoMethod provided to constructor");let{context:a,status:c,forceRefresh:m,...E}=i;c&&m&&(c.forceRefresh=!0);let _=this.#$(n,E),I=m||_===void 0;if(c&&(c.memo=I?"miss":"hit",I||(c.value=_)),!I)return _;let T=o(n,_,{options:E,context:a});return c&&(c.value=T),this.#O(n,T,E),T}get(n,i={}){let{status:o=mr.hasSubscribers?{}:void 0}=i;i.status=o,o&&(o.op="get",o.key=n,o.cache=this);let a=this.#$(n,i);return o&&(a!==void 0&&(o.value=a),mr.hasSubscribers&&mr.publish(o)),a}#$(n,i={}){let{allowStale:o=this.allowStale,updateAgeOnGet:a=this.updateAgeOnGet,noDeleteOnStaleGet:c=this.noDeleteOnStaleGet,status:m}=i,E=this.#u.get(n);if(E===void 0){m&&(m.get="miss");return}let _=this.#s[E],I=this.#l(_);return m&&this.#C(m,E),this.#E(E)?I?(m&&(m.get="stale-fetching"),o&&_.__staleWhileFetching!==void 0?(m&&(m.returnedStale=!0),_.__staleWhileFetching):void 0):(c||this.#P(n,"expire"),m&&(m.get="stale"),o?(m&&(m.returnedStale=!0),_):void 0):(m&&(m.get=I?"fetching":"hit"),this.#D(E),a&&this.#M(E),I?_.__staleWhileFetching:_)}#z(n,i){this.#y[i]=n,this.#g[n]=i}#D(n){n!==this.#d&&(n===this.#h?this.#h=this.#g[n]:this.#z(this.#y[n],this.#g[n]),this.#z(this.#d,n),this.#d=n)}delete(n){return this.#P(n,"delete")}#P(n,i){mr.hasSubscribers&&mr.publish({op:"delete",delete:i,key:n,cache:this});let o=!1;if(this.#a!==0){let a=this.#u.get(n);if(a!==void 0)if(this.#v?.[a]&&(clearTimeout(this.#v[a]),this.#v[a]=void 0),o=!0,this.#a===1)this.#G(i);else{this.#N(a);let c=this.#s[a];if(this.#l(c)?c.__abortController.abort(Error("deleted")):(this.#I||this.#w)&&(this.#I&&this.#r?.(c,n,i),this.#w&&this.#m?.push([c,n,i])),this.#u.delete(n),this.#c[a]=void 0,this.#s[a]=void 0,a===this.#d)this.#d=this.#y[a];else if(a===this.#h)this.#h=this.#g[a];else{let m=this.#y[a];this.#g[m]=this.#g[a];let E=this.#g[a];this.#y[E]=this.#y[a]}this.#a--,this.#A.push(a)}}if(this.#w&&this.#m?.length){let a=this.#m,c;for(;c=a?.shift();)this.#n?.(...c)}return o}clear(){return this.#G("delete")}#G(n){for(let i of this.#R({allowStale:!0})){let o=this.#s[i];if(this.#l(o))o.__abortController.abort(Error("deleted"));else{let a=this.#c[i];this.#I&&this.#r?.(o,a,n),this.#w&&this.#m?.push([o,a,n])}}if(this.#u.clear(),this.#s.fill(void 0),this.#c.fill(void 0),this.#b&&this.#_){this.#b.fill(0),this.#_.fill(0);for(let i of this.#v??[])i!==void 0&&clearTimeout(i);this.#v?.fill(void 0)}if(this.#x&&this.#x.fill(0),this.#h=0,this.#d=0,this.#A.length=0,this.#p=0,this.#a=0,this.#w&&this.#m){let i=this.#m,o;for(;o=i?.shift();)this.#n?.(...o)}}};import{readFileSync as i$}from"fs";import{tmpdir as o$}from"os";import{join as a$}from"path";var c$=he("applets/functions-worker.ts"),gE=30000,yE=600000,wE=8;function $h(t,n){for(let{reject:i,timer:o}of t.pending.values())clearTimeout(o),i(Error(n));t.pending.clear()}function Yu(t,n){if(t.killed)return;t.killed=!0,$h(t,n);try{t.worker.kill()}catch{}}var l$=2000;function u$(t,n){if(t.killed)return;t.killed=!0,$h(t,n);let i=setTimeout(()=>{try{t.worker.kill()}catch{}},l$);i.unref?.(),t.worker.exited.then(()=>clearTimeout(i)).catch(()=>clearTimeout(i));try{t.worker.send({type:"shutdown"})}catch{clearTimeout(i);try{t.worker.kill()}catch{}}}var Os=new mE({max:wE,ttl:yE,ttlAutopurge:!0,updateAgeOnGet:!0,dispose:(t)=>Yu(t,"Functions worker idle-evicted")});function SE(t,n){let i=a$(t,".moi"),o=()=>{},a=new Promise((m)=>o=m),c={workspacePath:t,worker:void 0,readyPromise:a,pending:new Map,killed:!1,ready:!1,spawnedAt:Date.now(),lastCallAt:null,calls:0,errors:0,timeouts:0,modules:new Set};return c.worker=Bun.spawn(j([process.execPath,c$]),{cwd:o$(),env:{...process.env,...n,MEI_WORKSPACE_ROOT:t,MEI_FUNCTIONS_DIR:process.env.MEI_FUNCTIONS_DIR??i},stderr:"inherit",onExit(m,E){if(E!==0&&E!==null)console.error(`[mei] functions worker for ${t} exited with code ${E}`);if(c.killed=!0,$h(c,"Functions worker exited"),Os.peek(t)===c)Os.delete(t)},ipc(m){let E=m;if(E.type==="ready"){c.ready=!0,o();return}if(E.type==="loaded"&&E.module){c.modules.add(E.module);return}if(E.id){let _=c.pending.get(E.id);if(!_)return;if(c.pending.delete(E.id),clearTimeout(_.timer),E.type==="result")_.resolve(E.data);else if(E.type==="error")c.errors++,_.reject(Error(E.message??"Unknown error"))}}}),c}function d$(t,n){let i=Os.get(t);if(i&&!i.killed)return i;let o=SE(t,n);return Os.set(t,o),o}function Xu(t){let n=t.lastIndexOf("/");if(n===-1)return null;let i=t.slice(0,n),o=t.slice(n+1);if(!/^[A-Za-z0-9_$-]+(?:\/[A-Za-z0-9_$-]+)*$/.test(i))return null;if(!/^[A-Za-z0-9_$]+$/.test(o))return null;return{module:i,name:o}}function bE(t,n,i,o){t.calls++,t.lastCallAt=Date.now();let a=crypto.randomUUID();return new Promise((c,m)=>{let E=setTimeout(()=>{t.pending.delete(a),t.timeouts++,m(Error(`Function call timed out: ${n}/${i}`))},gE);t.pending.set(a,{resolve:c,reject:m,timer:E});try{t.worker.send({id:a,type:"call",module:n,name:i,args:o})}catch(_){t.pending.delete(a),clearTimeout(E),m(_ instanceof Error?_:Error("Failed to send to worker"))}})}async function vE(t,n,i,o){let a=await X(o),c=d$(o,a);return await c.readyPromise,bE(c,t,n,i)}async function EE(t,n,i,o){let a=await X(o),c=SE(o,a);try{return await c.readyPromise,await bE(c,t,n,i)}finally{Yu(c,"Ephemeral call finished")}}function AE(){for(let t of Os.values())Yu(t,"Server shutting down");Os.clear()}function xE(t){let n=Os.peek(t);if(n)Yu(n,"Workspace env changed");Os.delete(t)}var Zu={maxWorkers:wE,idleTtlMs:yE,callTimeoutMs:gE};function f$(t){if(!t||process.platform!=="linux")return null;try{let n=i$(`/proc/${t}/status`,"utf8").match(/^VmRSS:\s+(\d+)\s+kB/m);return n?Number(n[1])*1024:null}catch{return null}}function _E(){let t=[];for(let[n,i]of Os.entries()){if(i.killed)continue;t.push({workspacePath:n,pid:i.worker.pid,ready:i.ready,spawnedAt:i.spawnedAt,lastCallAt:i.lastCallAt,calls:i.calls,errors:i.errors,timeouts:i.timeouts,pending:i.pending.size,ttlRemainingMs:Os.getRemainingTTL(n),rssBytes:f$(i.worker.pid),modules:[...i.modules].sort()})}return t}function Pc(t,n){if(t.length===0)return;let i=Os.peek(n);if(!i||i.killed)return;u$(i,`Server code changed (${t.join(", ")})`)}function Qu(t){xE(t.path);for(let n of ie())n.onEnvChanged?.(t.path);B.invalidate(t),h({type:"env:changed",workspaceId:t.id})}import p$ from"sharp";async function ed(t){return`data:image/webp;base64,${(await p$(t,{animated:!0}).resize(128,128,{fit:"contain",background:{r:0,g:0,b:0,alpha:0}}).webp({quality:90}).toBuffer()).toString("base64")}`}import{existsSync as h$}from"fs";import{join as m$}from"path";var Dh=v("dist"),IE=m$(Dh,"index.html"),Aa=!process.env.MOI_DEV&&h$(IE);function TE(){return new Response(Bun.file(IE),{headers:{"Cache-Control":"no-cache"}})}import{statSync as g$}from"fs";import y$ from"sharp";var Lh=800,w$=/\.(png|jpe?g|webp|avif)$/i,S$=/\.(gif|svg)$/i;async function RE(t,n,i){let o=w$.test(n);if(!o&&!S$.test(n))return new Response("Not an image",{status:415});let a=Mh(t,n);if(a instanceof Response)return a;let c;try{c=g$(a)}catch{return new Response("Not found",{status:404})}let m=`"${c.size}-${Math.trunc(c.mtimeMs)}${o?`-${Lh}`:""}"`,E={ETag:m,"Cache-Control":"private, no-cache"};if(i===m)return new Response(null,{status:304,headers:E});if(!o){let _=Bun.file(a);return new Response(_,{headers:{...E,"Content-Type":_.type||"application/octet-stream"}})}try{let _=await y$(a).rotate().resize(Lh,Lh,{fit:"inside",withoutEnlargement:!0}).webp({quality:80}).toBuffer();return new Response(new Uint8Array(_),{headers:{...E,"Content-Type":"image/webp"}})}catch{return new Response("Preview failed",{status:415})}}import{existsSync as E$}from"fs";var xa=new Map;function Cc(t,n){let o=(xa.get(t)??Promise.resolve()).then(n,n);return xa.set(t,o),o.then(()=>{if(xa.get(t)===o)xa.delete(t)},()=>{if(xa.get(t)===o)xa.delete(t)}),o}import{realpath as PE,rm as b$}from"fs/promises";import{join as _a,relative as v$,sep as CE}from"path";async function kE(t,n){let i=_a(t,".moi","views");for(let o of[".tsx",".ts"]){let a=_a(i,`${n}${o}`),c=Bun.file(a);if(await c.exists())return{path:a,source:await c.text()}}return null}class td extends Error{}function OE(t,n){if(!n.startsWith(t+CE)||!Ph.test(n))return!1;return!v$(t,n).split(CE).some((i)=>i.startsWith(".")||["data","ui","node_modules"].includes(i))}async function ME(t,n,i){let o=await PE(t),a=_a(o,".moi"),c=_a(a,"views"),m=["tsx","ts"].map((T)=>_a(c,`${n}.${T}`)),E=new Set([...m,_a(c,`${n}.server.ts`)]),_=new Set(m),I=await rE(o).catch(()=>null);if(I?.complete){if((await Promise.all([...I.modules.keys()].map(async(R)=>await PE(R).catch(()=>null)===R))).every(Boolean)){let R=Oh(I,E),P=Oh(I,[...[...I.entrypoints].filter((M)=>!E.has(M)),...[...R].filter((M)=>!OE(a,M))]);if(m.some((M)=>P.has(M)))throw new td("Another applet imports this view. Remove that import before deleting it.");for(let M of R)if(!P.has(M)&&OE(a,M))_.add(M)}}await i?.(),await Promise.all([..._].map((T)=>b$(T,{force:!0})))}class ks extends Error{status;constructor(t,n){super(t);this.status=n;this.name="ViewMutationError"}}async function Oc(t){let{manifestPath:n}=bn(t,"view");try{let i=JSON.parse(await Bun.file(n).text());return{config:i.config??{},order:Array.isArray(i.order)?i.order:[]}}catch{return{config:{},order:[]}}}async function A$(t,n){let{manifestPath:i}=bn(t,"view");await Bun.write(i,JSON.stringify(n,null,2))}function x$(t,n){let i=new Set(n),o=t.filter((m)=>i.has(m)),a=new Set(o),c=n.filter((m)=>!a.has(m));return[...o,...c]}async function _$(t,n=!1,i){let{names:o,results:a,ms:c}=await Ku(t,"view",n,i),m=await Oc(t);for(let T of a)if(T.status==="built")m.config[T.name]=T.config??{};for(let T of Object.keys(m.config))if(!o.includes(T))delete m.config[T];m.order=x$(m.order,o);let{buildDir:E}=bn(t,"view");if(E$(E))await A$(t,m);let _=a.filter((T)=>T.status==="built").length,I=a.filter((T)=>T.status==="failed");console.log(`[bundle] ${_}/${o.length} views built in ${c}ms`+(I.length?`, ${I.length} failed`:"")+(n?" (forced)":""));for(let T of I)console.error(`[bundle] ${T.name}:
|
|
78
78
|
${T.error}`);return a}function jh(t){let{buildDir:n}=bn(t,"view");return zu(n)}async function ao(t){let[n,i]=await Promise.all([jh(t),Oc(t)]),o=new Set(n);return[...i.order.filter((c)=>o.has(c)),...n.filter((c)=>!i.order.includes(c))].map((c)=>{let m=i.config[c]??{},E=typeof m.icon==="string"&&m.icon?m.icon:void 0,_=Array.isArray(m.requiredEnv)?m.requiredEnv:void 0,I=Vu(t,"view",c);return{id:c,status:"compiled",...I?{revision:I}:{},title:m.title||c,...E?{icon:E}:{},..._?{requiredEnv:_}:{}}})}async function NE(t){let{config:n}=await Oc(t),i={};for(let[o,a]of Object.entries(n)){if(!Array.isArray(a.requiredEnv))continue;for(let c of a.requiredEnv)(i[c]??=[]).push(o)}return i}async function kc(t){let n=await ao(t.path),i=new Set(n.map((a)=>a.id)),o=(await _t(t)).filter((a)=>!i.has(a.id));return[...n,...o]}async function $E(t){return Response.json({views:await ao(t)})}async function rd(t,n,i,o=!1,a){let c=await Oc(i),m=new Set(await jh(i)),E=await _$(i,o,a),_=await Oc(i),I=new Set(await jh(i));Hu(i,"view",E);let T=c.order.join("\x00")!==_.order.join("\x00"),R=m.size!==I.size||[...m].some((N)=>!I.has(N))||[...I].some((N)=>!m.has(N)),P=[];if(E.some((N)=>N.status==="built")||T||R)P=await ao(i),t({type:"views-list:changed",workspaceId:n,views:P});let M=new Set;for(let N of E)if(N.status==="built"){t({type:"view:changed",workspaceId:n,name:N.name}),await Qn({id:n,path:i},N.name,P.find((H)=>H.id===N.name));for(let H of N.serverModules??[])M.add(H)}if(M.size>0)Pc([...M],i);return E}async function DE(t,n,i,o,a){return Cc(i,async()=>{let c=(await ao(i)).find((_)=>_.id===o);if(!c)throw new ks("View not found",404);if(c.title===a)return c;let m=await kE(i,o);if(!m)throw new ks("View source not found",409);let E;try{E=Li(m.source,a)}catch(_){throw new ks(_ instanceof Error?_.message:"Could not update the view title",409)}if(E===m.source)return c;await Bun.write(m.path,E);try{let I=(await rd(t,n,i,!0,o)).find((R)=>R.name===o);if(I?.status!=="built")throw new ks(I?.error??"Could not rebuild the renamed view",422);let T=(await ao(i)).find((R)=>R.id===o);if(!T)throw new ks("Renamed view was not found after rebuilding",422);return T}catch(_){if(await Bun.file(m.path).text().catch(()=>null)===E)await Bun.write(m.path,m.source);throw _}})}async function LE(t,n,i){let{id:o,path:a}=n;await Cc(a,async()=>{if(!(await ao(a)).some((m)=>m.id===i))throw new ks("View not found",404);try{await ME(a,i,()=>Hr(n,i))}catch(m){if(m instanceof td)throw new ks(m.message,409);throw m}Pc([`views/${i}`],a),await Qn(n,i),t({type:"view:deleted",workspaceId:o,name:i}),t({type:"workspace-config:changed",workspaceId:o}),await rd(t,o,a,!1,i)})}function jE(t,n,i,o,a){return Gu("view",t,n,i,o,a)}import{existsSync as I$}from"fs";var Uh={rowSpan:1,colSpan:2},UE=[1,2,3,4];async function nd(t){let{manifestPath:n}=bn(t,"widget");try{return JSON.parse(await Bun.file(n).text()).config??{}}catch{return{}}}async function T$(t,n){let{manifestPath:i}=bn(t,"widget");await Bun.write(i,JSON.stringify({config:n},null,2))}async function R$(t,n=!1,i){let{names:o,results:a,ms:c}=await Ku(t,"widget",n,i),m=await nd(t);for(let T of a)if(T.status==="built")m[T.name]=T.config??Uh;for(let T of Object.keys(m))if(!o.includes(T))delete m[T];let{buildDir:E}=bn(t,"widget");if(I$(E))await T$(t,m);let _=a.filter((T)=>T.status==="built").length,I=a.filter((T)=>T.status==="failed");console.log(`[bundle] ${_}/${o.length} widgets built in ${c}ms`+(I.length?`, ${I.length} failed`:"")+(n?" (forced)":""));for(let T of I)console.error(`[bundle] ${T.name}:
|
|
79
|
-
${T.error}`);return a}function Fh(t){let{buildDir:n}=bn(t,"widget");return zu(n)}async function FE(t){let[n,i]=await Promise.all([Fh(t),nd(t)]);return n.map((o)=>{let a=i[o]??{},c=UE.includes(a.rowSpan)?a.rowSpan:Uh.rowSpan,m=UE.includes(a.colSpan)?a.colSpan:Uh.colSpan,E=Array.isArray(a.requiredEnv)?a.requiredEnv:void 0,_=Vu(t,"widget",o);return{id:o,config:{rowSpan:c,colSpan:m,...E?{requiredEnv:E}:{}},..._?{revision:_}:{}}})}async function qE(t){let n=await nd(t),i={};for(let[o,a]of Object.entries(n)){if(!Array.isArray(a.requiredEnv))continue;for(let c of a.requiredEnv)(i[c]??=[]).push(o)}return i}async function BE(t){return Response.json({widgets:await FE(t)})}async function WE(t,n,i,o=!1,a){let c=new Set(await Fh(i)),m=await nd(i),E=await R$(i,o,a),_=new Set(await Fh(i));Hu(i,"widget",E);let T=E.some((P)=>{if(P.status!=="built"||!P.config)return!1;let M=m[P.name];return!M||M.rowSpan!==P.config.rowSpan||M.colSpan!==P.config.colSpan})||c.size!==_.size||[...c].some((P)=>!_.has(P))||[..._].some((P)=>!c.has(P)),R=new Set;for(let P of E)if(P.status==="built"){t({type:"widget:changed",workspaceId:n,name:P.name});for(let M of P.serverModules??[])R.add(M)}if(R.size>0)Pc([...R],i);if(T){let P=await FE(i);t({type:"widgets-list:changed",workspaceId:n,widgets:P})}return E}function HE(t,n,i,o,a){return Gu("widget",t,n,i,o,a)}async function Mc(t){let[n,i]=await Promise.all([qE(t),NE(t)]),o={};for(let a of[n,i])for(let[c,m]of Object.entries(a))o[c]=[...o[c]??[],...m];return o}class Ia extends Error{sessionId;viewId;constructor(t,n,i){super(t instanceof Error?t.message:"Couldn\u2019t start view chat");this.sessionId=n;this.viewId=i}}async function P$(t,n,i,o){await mt(t,i,{tabId:n==="overview"?void 0:n}),await Ge(t,i,n,o)}async function VE(t,n,i,o,a){await va(t,{...a,workspaceId:t.id,workspacePath:t.path,agentId:t.agentId,sessionId:i,isNew:o,viewBuildId:n.id,content:n.requirements}),await Qe(t,n.id,{status:"submitted"},"starting")}async function zE(t,n,i,o){if(o)await Qe(t,o.id,{status:"failed",error:n instanceof Error?n.message:"Couldn\u2019t start view chat"},"starting");throw new Ia(n,i?ee(t.id,i):void 0,o?.id)}async function GE(t,n,i){let o=We(n),{view:a,sessionId:c,pinned:m}=await S(t,(E)=>{let _=E.pinnedSessionId,I=_??i.sessionId??crypto.randomUUID(),T=Is(E,n,i.requirements,I,!!i.attachments?.length);if(!_)ms(E,I,o),Yn(E,t.id,I,o);return{view:T,sessionId:I,pinned:_}});try{await VE(t,a,c,!m,i)}catch(E){return zE(t,E,c,a)}return{viewId:n,sessionId:ee(t.id,c)}}async function KE(t,n,i){if(!i.trim())throw Error("View requirements are required");if(n===void 0){let m=await Jt(t,{requirements:i.trim(),status:"submitted"});return{viewId:m.id,mode:"in-place",buildInstructions:ju(m.id,Se)}}if(!n)throw Error("Session id cannot be empty");n=ee(t.id,n);let o=y(t);if(!(await o.listSessions(t)).some((m)=>m.sessionId===n)&&!o.activeSessions().some((m)=>m.workspaceId===t.id&&m.sessionId===n))throw Error("Source chat not found");let a,c;try{let m=await Wn(t,n);try{a=await o.forkSession?.(t,n,m)}catch(I){if(!(I instanceof Xt))throw I}let E=!a;if(a??=crypto.randomUUID(),!E){await mt(t,a,{fork:{fromSessionId:n}});let I=await o.sessionEvents(t,a).catch(()=>{return});if(I)await mt(t,a,{fork:{fromSessionId:n,...Ds(I)}})}let _=await Pe(t,a,m);return c=await Jt(t,{status:"starting",requirements:i.trim(),buildSessionId:a}),await P$(t,We(c.id),a),await VE(t,c,a,E,_),{viewId:c.id,mode:"handoff",sessionId:ee(t.id,a)}}catch(m){return zE(t,m,a,c)}}async function JE(t){for(let n of await _t(t))if(n.status==="starting")await Qe(t,n.id,{status:"failed",error:"View chat startup was interrupted. Check the chat before continuing; it has not been retried."},"starting")}import{resolve as sd}from"path";function C$(t,n){if(t.isDefault!==n.isDefault)return t.isDefault?-1:1;return(n.lastRunAt??"").localeCompare(t.lastRunAt??"")||t.agentId.localeCompare(n.agentId)}async function O$(t,n){let i=sd(t),o=(await n()).find((a)=>sd(a.path)===i);if(!o)throw Error("No Hermes profile owns this folder");return{...o.name?{name:o.name}:{},agentId:o.agentId,...o.isDefault?{isDefault:!0}:{}}}async function YE(t,n,i=Ie,o=ve){if(n==="hermes")return O$(t,o);if(n!=="openclaw")return{};let a=sd(t),c=(await i()).filter((m)=>sd(m.path)===a).sort(C$)[0];if(!c)throw Error("OpenClaw is not initialized for this folder");return{...c.name?{name:c.name}:{},agentId:c.agentId,...c.isDefault?{isDefault:!0}:{},...c.lastRunAt?{lastRunAt:c.lastRunAt}:{}}}function Bh(t){return typeof t==="string"?t:void 0}async function N$(t,n,i){let o=Xu(n);if(!o)return new Response("Invalid module or function name",{status:400});let{module:a,name:c}=o;try{if(Number(t.headers.get("content-length")??0)>1e6)return new Response("Request body too large",{status:413});let E=await t.text(),_=await vE(a,c,E,i);return new Response(_,{headers:{"Content-Type":"application/json"}})}catch(m){let E=m instanceof Error?m.message:"Unknown error";return Wu(i,{source:"rpc",...Qv(a)??{},module:a,fn:c,message:E}),new Response(E,{status:500})}}function Wh(t,{reserveOperation:n=!0}={}){return Vv(async(i,o)=>{let a=i.req.param("id");if(!a)return i.text("Workspace not found",404);let c;try{if(n&&i.req.method!=="GET")c=nr(a);let m=await q(a);if(!m)return i.text("Workspace not found",404);if(m.remote&&p().environment!=="cloud")return i.text("Remote workspaces require Cloud mode",403);if(m.remote&&t==="owner")return i.text("Use the owner workspace address",404);if(t==="owner"&&p().unixSocket)Lc(a,i.req.raw);i.set("ws",m),await o()}catch(m){if(m instanceof ae)return i.text(m.message,409);throw m}finally{c?.()}})}var tt=Wh("personal"),Qt=Wh("owner"),_e=new Bs;_e.patch("/harness",Wh("personal",{reserveOperation:!1}),async(t)=>{if(p().demo)return t.text("Changing agents is unavailable in the demo",403);let n=await t.req.json().catch(()=>null);if(!n||!["claude-code","codex"].includes(n.harness))return t.text("Invalid agent selection",400);try{return t.json(await ln(t.get("ws"),n.harness))}catch(i){if(i instanceof ae)return t.text(i.message,409);throw i}});_e.get("/widgets",Qt,(t)=>BE(t.get("ws").path));_e.get("/widgets/*",Qt,(t)=>{let n=t.get("ws"),{name:i,file:o}=kh(t.req.url,n.id,"widgets");if(!i)return t.text("Not found",404);return HE(i,o,n.path,je(n.id),t.req.header("if-none-match"))});_e.get("/views",Qt,async(t)=>t.req.query("includePending")==="true"?t.json({views:await kc(t.get("ws"))}):$E(t.get("ws").path));var ZE="Use the owner workspace address for compiled views";_e.patch("/views/:viewId",tt,async(t)=>{let n=t.get("ws"),i=await t.req.json().catch(()=>null);if(await Ht(n,t.req.param("viewId")))try{if(typeof i?.requirements!=="string"&&typeof i?.title!=="string"&&typeof i?.icon!=="string")return t.text("Expected requirements, title, or icon",400);return t.json(await Jr(n,t.req.param("viewId"),{requirements:typeof i.requirements==="string"?i.requirements:void 0,title:typeof i.title==="string"?i.title.trim():void 0,icon:typeof i.icon==="string"?i.icon:void 0}))}catch(a){if(a instanceof U)return t.text(a.message,a.status);throw a}if(n.remote)return t.text(ZE,404);let o=typeof i?.title==="string"?i.title.trim():"";if(!o)return t.text("Expected { title: string }",400);try{return t.json(await DE(h,n.id,n.path,t.req.param("viewId"),o))}catch(a){if(a instanceof ks||a instanceof U)return t.text(a.message,a.status);throw a}});_e.delete("/views/:viewId",tt,async(t)=>{let n=t.get("ws");try{let i=t.req.param("viewId");if(await Ht(n,i)){let o=new Set(y(n).activeSessions().filter((a)=>a.workspaceId===n.id).map((a)=>a.sessionId));await ws(n,i,o)}else if(n.remote)return t.text(ZE,404);else await LE(h,n,i);return t.body(null,204)}catch(i){if(i instanceof ks||i instanceof U)return t.text(i.message,i.status);throw i}});_e.get("/views/*",Qt,(t)=>{let n=t.get("ws"),{name:i,file:o}=kh(t.req.url,n.id,"views");if(!i)return t.text("Not found",404);return jE(i,o,n.path,je(n.id),t.req.header("if-none-match"))});_e.post("/views",tt,async(t)=>{let n=t.get("ws");return t.json(await Jt(n),201)});_e.post("/views/:viewId/submit",tt,async(t)=>{let n=t.get("ws"),i=await t.req.json();if(typeof i?.requirements!=="string")return t.text("Expected { requirements: string }",400);if(i.optimisticId!==void 0&&typeof i.optimisticId!=="string")return t.text("Invalid optimisticId",400);let o=i.attachments??[];if(!wr(o))return t.text("Invalid attachments",400);for(let c of o){if(c.type!=="upload")continue;if(!/^[a-f0-9]{64}$/.test(c.uploadId))return t.text("Invalid upload id",400);if(!Bn(n.id,c.uploadId))return t.text("Attachment not found or expired",400)}let a=await od(n.harness??"claude-code");if(a.status!=="available")return t.text(a.reason,400);try{let c=await GE(n,t.req.param("viewId"),{requirements:i.requirements,sessionId:typeof i.sessionId==="string"?i.sessionId:void 0,attachments:o,optimisticId:i.optimisticId,model:typeof i.model==="string"?i.model:void 0,effort:typeof i.effort==="string"?i.effort:void 0,speedMode:Le(i.speedMode)?i.speedMode:void 0,stream:i.stream===!0?!0:void 0});return t.json({...c,state:await Ae(n)})}catch(c){if(c instanceof U)return t.text(c.message,c.status);if(c instanceof Ia)return t.json({error:c.message,viewId:c.viewId,sessionId:c.sessionId},500);throw c}});_e.get("/files/*",Qt,(t)=>{let n=t.get("ws"),i=new URL(t.req.url).pathname.split(`${je(n.id)}/files/`)[1]??"";return dE(n.path,i,t.req.header("range"),t.req.header("if-none-match"))});_e.post("/rpc/*",Qt,(t)=>{let n=t.get("ws"),i=new URL(t.req.url).pathname.split(`${je(n.id)}/rpc/`)[1]??"";return N$(t.req.raw,i,n.path)});_e.post("/applet-log",Qt,async(t)=>{let n;try{n=await t.req.json()}catch{return t.text("Invalid JSON",400)}let i=Array.isArray(n.events)?n.events.slice(0,10):[];for(let o of i){let a=o;if(a.source!=="load"&&a.source!=="render"&&a.source!=="window"&&a.source!=="runtime")continue;let m=(a.kind==="widget"||a.kind==="view")&&typeof a.name==="string"&&/^[a-zA-Z0-9_-]+$/.test(a.name);if(!m&&a.source!=="runtime")continue;if(typeof a.message!=="string"||!a.message)continue;Wu(t.get("ws").path,{source:a.source,...m?{kind:a.kind,name:a.name}:{},message:a.message,...typeof a.stack==="string"?{stack:a.stack}:{}})}return t.body(null,204)});_e.get("/preview/*",tt,(t)=>{let n=t.get("ws"),i=new URL(t.req.url).pathname.split(`${je(n.id)}/preview/`)[1]??"";return RE(n.path,i,t.req.header("if-none-match"))});_e.post("/uploads",tt,async(t)=>{let n=t.get("ws"),i;try{i=await t.req.formData()}catch{return t.text("Choose a file to upload",400)}let o=i.getAll("files").filter((c)=>c instanceof File);if(o.length===0)return t.text("Choose a file to upload",400);if(o.length>20)return t.text("You can upload up to 20 files at a time",400);let a=[];for(let c of o){if(c.size>Ze)return t.text(`Files can be up to ${Ze/1048576} MB`,413);try{let m=Buffer.from(await c.arrayBuffer());a.push(await Fn({workspaceId:n.id,filename:c.name||"file",mediaType:c.type||"application/octet-stream",bytes:m}))}catch{return t.text(`Couldn\u2019t process "${c.name}"`,400)}}return t.json(a)});_e.post("/uploads/from-path",tt,async(t)=>{let n=await t.req.json().catch(()=>null);if(!n||typeof n!=="object"||!("path"in n)||typeof n.path!=="string")return t.text("Choose a file from this workspace",400);let i=t.get("ws");try{return t.json(await ss(i.id,i.path,n.path))}catch(o){if(o instanceof Error&&"code"in o){if(o.code==="ENOENT")return t.text("This file no longer exists",400);if(o.code==="EACCES"||o.code==="EPERM")return t.text("This file can\u2019t be read by Moi",400);return t.text("Something went wrong while adding this file",400)}return t.text(o instanceof Error?o.message:"Something went wrong while adding this file",400)}});_e.get("/uploads/:uploadId",tt,(t)=>{let n=Bn(t.get("ws").id,t.req.param("uploadId"));if(!n)return t.text("Not found or expired",404);let i=n.data?new Uint8Array(n.data):n.path?Bun.file(n.path):null;if(!i)return t.text("Not found or expired",404);return new Response(i,{headers:{"Content-Type":n.mediaType,"Content-Disposition":`inline; filename="${n.filename.replaceAll('"',"")}"`,"Cache-Control":"private, max-age=1800, immutable"}})});_e.get("/state",tt,async(t)=>t.json(await Ae(t.get("ws"))));_e.put("/state/tabs",tt,async(t)=>{let n=await t.req.json().catch(()=>null),i=t.get("ws");return await S(i,(o)=>{o.openTabs=vr(n?.openTabs)}),t.json(await Ae(i))});_e.get("/sessions",tt,async(t)=>{let n=t.get("ws");return t.json(await y(n).listSessions(n))});_e.put("/sessions/:sessionId/pin",tt,async(t)=>{let n=t.get("ws"),i=t.req.param("sessionId"),o=y(n),a=(await o.listSessions(n)).some((m)=>m.sessionId===i),c=o.activeSessions().some((m)=>m.workspaceId===n.id&&m.sessionId===i);if(!a&&!c)return t.text("Chat not found",404);return await xs(n,i),t.json(await Ae(n))});_e.delete("/sessions/:sessionId/pin",tt,async(t)=>{let n=t.get("ws");return await As(n,t.req.param("sessionId")),t.json(await Ae(n))});_e.put("/sessions/:sessionId/selection",tt,async(t)=>{let n=t.get("ws"),i=await t.req.json().catch(()=>null);if(!i||typeof i!=="object")return t.text("Bad request",400);let o=i;if(!re(o.tabId))return t.text("Invalid chat tab",400);let a=Object.prototype.hasOwnProperty.call(o,"ifMatch");if(a&&o.ifMatch!==null&&typeof o.ifMatch!=="string")return t.text("ifMatch must be a chat id or null",400);if(await qr(n))return t.text("Unpin chat before switching",409);return await Ge(n,t.req.param("sessionId"),o.tabId,a?o.ifMatch:void 0),t.json(await Ae(n))});_e.delete("/sessions/:sessionId/selection",tt,async(t)=>{let n=t.get("ws"),o=(await t.req.json().catch(()=>null))?.tabId;if(!re(o))return t.text("Invalid chat tab",400);return await Ps(n,t.req.param("sessionId"),o),t.json(await Ae(n))});_e.on("PATCH",["/sessions/:sessionId/config","/state/chat-defaults"],tt,async(t)=>{let n=await t.req.json().catch(()=>null);if(typeof n!=="object"||n===null)return t.text("Expected a JSON object",400);let i={},o=n;for(let c of["model","effort"]){if(!(c in o))continue;let m=o[c];if(m!==null&&typeof m!=="string")return t.text(`${c} must be a string or null`,400);i[c]=m}if("speedMode"in o){let c=o.speedMode;if(c!==null&&!Le(c))return t.text('speedMode must be "normal", "fast", "ultrafast", or null',400);i.speedMode=c}let a=t.get("ws");return await Pe(a,t.req.param("sessionId"),i),t.json(await Ae(a))});_e.post("/sessions/:sessionId/archive",tt,async(t)=>{let n=t.get("ws"),i=y(n),o=t.req.param("sessionId");if(!i.archiveSession)return t.text("Chat archiving is not supported",501);try{return await Zn(n,o),t.json(await Ae(n))}catch(a){console.error(`[api] archive chat failed for ${i.id}`,a);let c=a instanceof Error&&a.message?a.message:"Couldn\u2019t archive chat";return t.text(c,500)}});_e.get("/sessions/:sessionId/events",tt,async(t)=>{let n=t.get("ws"),i=t.req.param("sessionId");return t.json(await y(n).sessionEvents(n,i))});_e.get("/mcp",tt,async(t)=>{let n=t.get("ws"),i=y(n);if(t.req.query("stream")!=="true")return t.json(await i.mcpStatus?.(n)??[]);let o=!1,a=new TextEncoder;return new Response(new ReadableStream({async start(c){let m=(E)=>{if(!o)c.enqueue(a.encode(JSON.stringify(E)+`
|
|
80
|
-
`))};try{let E=await i.mcpStatus?.(n,(_)=>m({connectors:_}))??[];m({connectors:E,done:!0})}catch{m({error:"Could not load connectors"})}finally{if(!o)c.close()}},cancel(){o=!0}}),{headers:{"Content-Type":"application/x-ndjson","Cache-Control":"no-store"}})});_e.get("/harness/debug",tt,async(t)=>{let n=t.get("ws"),i=y(n),o=Number(t.req.query("sinceWire")??0)||0,a=Number(t.req.query("sinceBroadcast")??0)||0;return t.json({harness:i.id,process:await i.debugInfo?.(n)??null,wire:as(i.wireScope?.(n)??n.id,o),broadcasts:os(n.id,a)})});_e.get("/env",tt,async(t)=>{let n=t.get("ws");return t.json(await Ut(n.path,Mc(n.path)))});_e.put("/env",tt,async(t)=>{let n=t.get("ws"),i=Ir(await t.req.json().catch(()=>null));if(typeof i==="string")return t.text(i,400);if(i.set!==void 0||i.remove!==void 0||i.inheritDotenv!==void 0)await Cr(n.path,i),Qu(n);return t.json(await Ut(n.path,Mc(n.path)))});_e.get("/skills",tt,async(t)=>{let n=t.get("ws");return t.json(await wt(n.path,n.harness))});_e.post("/skills/update",tt,async(t)=>{let n=t.get("ws"),i=await Dt(n.path,n.harness??"claude-code");return t.json(i.status)});_e.get("/harness",tt,async(t)=>{let n=t.get("ws"),i=y(n),o={harness:i.id,supportsStreaming:i.capabilities.supportsStreaming,supportsArchiving:Boolean(i.archiveSession)};if(!k$(n.path))return t.json({...o,isFolderMissing:!0,availability:{status:"unavailable",reason:"Workspace folder not found"},models:[]});let a=i.id==="codex"?/^(OPENAI_|CODEX_)/:/^(ANTHROPIC_|CLAUDE_|AWS_|GOOGLE_|AZURE_|CLOUD_ML_)/,c=i.authStatus&&Object.entries(await X(n.path)).some(([I,T])=>T!==process.env[I]&&(a.test(I)||/^(HOME|USERPROFILE|XDG_CONFIG_HOME)$/.test(I))),m=t.req.query("refresh")==="true";if(m)await Ve({refresh:!0});let[E,_]=await Promise.all([i.authStatus&&!c?Promise.resolve({status:"available"}):B.getAvailability(n,m),i.listModels(n).catch((I)=>(console.error(`[api] listModels failed for ${i.id}`,I),[]))]);return t.json({...o,availability:E,hasAuthOverrides:Boolean(c),models:_})});_e.get("/config",Qt,async(t)=>t.json(await Ic(t.get("ws").path)));_e.put("/config",Qt,async(t)=>{let n=t.get("ws"),i=await t.req.json().catch(()=>null);if(!i||typeof i!=="object"||Array.isArray(i))return t.text("Expected a workspace config object",400);let o=i,{name:a,icon:c}=o;if(a!==void 0&&a!==null&&typeof a!=="string")return t.text("Expected { name: string | null }",400);if(c!==void 0&&c!==null&&(!Sr(c)||c.type==="upload"))return t.text("Invalid icon",400);if(a===void 0&&c===void 0)return t.text("Expected a workspace config field",400);return await mi(n.path,{name:a,icon:c}),h({type:"workspace-config:changed",workspaceId:n.id,origin:Bh(o.origin)}),t.json(await Ic(n.path))});_e.post("/scratchpad/ops",Qt,async(t)=>{try{let n=await t.req.formData(),i=JSON.parse(String(n.get("op")));if(!i||typeof i.kind!=="string")return t.text("Invalid scratchpad edit",400);let o;if(i.kind==="add-image"){let c=n.get("image");if(!(c instanceof File))return t.text("Image file is required",400);o=new Uint8Array(await c.arrayBuffer())}let a=t.get("ws");return t.json(await Jl(a.path,a.id,i,o))}catch(n){return t.text(n instanceof Error?n.message:"Scratchpad edit failed",400)}});_e.get("/scratchpad",Qt,async(t)=>t.json(await at(t.get("ws").path)));_e.put("/scratchpad",Qt,async(t)=>{let n=t.get("ws"),i=await t.req.json().catch(()=>null);if(!i||typeof i!=="object"||!i.document)return t.text("Expected { document }",400);return await sr(i.document,n.path),h({type:"scratchpad:changed",workspaceId:n.id,origin:Bh(i.origin)}),t.body(null,204)});_e.post("/scratchpad/assets",Qt,async(t)=>{if(Number(t.req.header("content-length")??0)>St)return t.text(`Asset too large (max ${St/1048576} MB)`,413);let i=new Uint8Array(await t.req.arrayBuffer());if(i.length===0)return t.text("Empty body",400);if(i.length>St)return t.text(`Asset too large (max ${St/1048576} MB)`,413);let o=t.req.header("content-type")??"application/octet-stream";return t.json(await Tt(t.get("ws").path,i,o))});_e.get("/scratchpad/assets/:file",Qt,async(t)=>{let n=ir(t.get("ws").path,t.req.param("file"));if(!n||!await n.file.exists())return t.text("Not found",404);return new Response(n.file,{headers:{"Content-Type":n.mimeType,"Cache-Control":"public, max-age=31536000, immutable","Content-Disposition":"attachment","X-Content-Type-Options":"nosniff"}})});_e.put("/icon",Qt,async(t)=>{let n=t.get("ws"),i=new Uint8Array(await t.req.arrayBuffer());if(i.length===0)return t.text("Empty image body",400);let o;try{o=await ed(i)}catch(c){let m=c instanceof Error?c.message:String(c);return t.text(`Invalid image: ${m}`,400)}let a={type:"upload",value:o};return await mi(n.path,{icon:a}),h({type:"workspace-config:changed",workspaceId:t.get("ws").id}),t.json({icon:a})});_e.delete("/icon",Qt,async(t)=>(await mi(t.get("ws").path,{icon:null}),h({type:"workspace-config:changed",workspaceId:t.get("ws").id}),t.body(null,204)));_e.get("/",tt,async(t)=>{let n=t.get("ws"),i=await O(n.path);if(i.remote)return t.json({version:2,remote:i.remote,apiBase:je(i.remote.workspace_id,i.remote.user_id),isRemote:!0,cwd:n.path,harness:n.harness,agentId:n.agentId});let o=i;return t.json({...o,apiBase:je(n.id),isRemote:!1,name:o.name||XE(n.path),cwd:n.path,harness:n.harness,agentId:n.agentId})});_e.get("/applet-thumbnails",Qt,async(t)=>t.json({thumbnails:await Ji(t.get("ws").path)}));_e.get("/applet-thumbnails/:kind/:name",Qt,(t)=>{let n=t.req.param("kind");if(n!=="widget"&&n!=="view")return t.text("Not found",404);let[i,o]=t.req.param("name").split(":");return Zi(t.get("ws").path,n,i,t.req.header("if-none-match"),o!==void 0)});_e.put("/applet-thumbnails",Qt,async(t)=>{let n=await t.req.json().catch(()=>null);if(!n||typeof n!=="object"||Array.isArray(n))return t.text("Bad request",400);let i=n;if(!((i.kind==="widget"||i.kind==="view")&&Array.isArray(i.thumbnails)&&i.thumbnails.every((a)=>a&&typeof a==="object"&&!Array.isArray(a)&&typeof a.id==="string"&&Tr(a.id)&&typeof a.revision==="string"&&(a.image===void 0||a.image===null||typeof a.image==="string")&&(a.captureMs===void 0||typeof a.captureMs==="number"))))return t.text("Bad request",400);return await Xi(t.get("ws").path,i.kind,i.thumbnails),t.body(null,204)});function id(t){return nn((n)=>typeof n==="string"&&Object.hasOwn(t,n))}var $$=Rs({theme:Rs({font:id(le),color:id(ce),radius:id(Ee),agent:id(xe)}).optional(),widgetGrid:u(s({i:r().min(1),x:en().nonnegative(),y:en().nonnegative()})).optional(),origin:r().optional()}).refine((t)=>t.theme!==void 0||t.widgetGrid!==void 0);_e.put("/",tt,async(t)=>{let n=t.get("ws");if(n.remote)return t.text("Remote references contain only the owner address; save shared content to the owner",403);let i=$$.safeParse(await t.req.json().catch(()=>null));if(!i.success)return t.text("Invalid layout patch",400);let{origin:o,...a}=i.data,{changed:c}=await ze(n.path,(m)=>Qi(m,a));if(c)h({type:"workspace-config:changed",workspaceId:n.id,origin:o});return t.body(null,204)});_e.delete("/",tt,async(t)=>{let n=t.get("ws");if(n.remote)return t.text("Leaving remote workspaces is not available yet",403);if(!await ri(n.id))return t.text("Workspace not found",404);return y(n).stopWorkspace?.(n.path),await Mo.stopWorkspace(n.path),t.body(null,204)});var co=new Bs;function qh(t){return p().environment==="cloud"?t:t.filter((n)=>!n.remote)}async function Hh(t){return Promise.all(t.map(async(n)=>{let i=await O(n.path).catch(()=>null);if(!i)return n;if(i.remote)return{...n,remote:i.remote,name:i.remote.workspace_id};return{...n,name:i.name??n.name,icon:i.icon,theme:i.theme}}))}co.get("/",async(t)=>{let n=await D();return t.json(await Hh(qh(n)))});co.put("/order",async(t)=>{let n=await t.req.json();if(!Array.isArray(n?.ids)||n.ids.some((i)=>typeof i!=="string"))return t.text("Expected { ids: string[] }",400);try{let i=await D(),o=new Set(qh(i).map((m)=>m.id)),a=i.filter((m)=>!o.has(m.id)).map((m)=>m.id),c=await ni([...n.ids,...a]);return h({type:"workspaces-list:changed",origin:Bh(n.origin)}),t.json(await Hh(qh(c)))}catch(i){let o=i instanceof Error?i.message:String(i);return t.text(o,400)}});var QE="Workspace creation is not available in the Moi demo";co.post("/",async(t)=>{if(p().demo)return t.text(QE,403);let n=await t.req.json().catch(()=>null);if(n&&typeof n==="object"&&"remote"in n){if(p().environment!=="cloud")return t.text("Shared workspaces require Cloud mode",403);if(Object.keys(n).some((T)=>T!=="remote"&&T!=="harness"))return t.text("Remote registration expects only remote and harness",400);let _;try{_=K(n.remote)}catch(T){return t.text(T instanceof Error?T.message:"Invalid remote workspace",400)}let I=n.harness;if(I!==void 0){if(I!=="claude-code"&&I!=="codex")return t.text("Unknown workspace type",400);let T=await od(I);if(T.status!=="available")return t.text(T.reason,400)}try{return t.json(await gi(_,I),201)}catch(T){return t.text(T instanceof Error?T.message:"Could not open shared workspace",503)}}if(!n?.path)return t.text("Missing path",400);let i=n?.harness??"claude-code";if(!Yt(i))return t.text("Unknown workspace type",400);let o=i,a=await od(o);if(a.status!=="available")return t.text(a.reason,400);let c=M$(String(n.path)),m;try{m=await YE(c,o)}catch(_){let I=_ instanceof Error?_.message:String(_);return t.text(I,400)}try{await J(c,o)}catch(_){let I=_ instanceof Error?_.message:String(_);return t.text(`Could not initialize workspace: ${I}`,500)}let E=await z(c,{harness:o,...m});return t.json((await Hh([E]))[0],201)});co.get("/discover",async(t)=>t.json(await ii()));co.get("/previews",async(t)=>{let n=await D(),i=await Promise.all(n.map(async(o)=>{if(o.remote)return[o.id,{thumbnails:[]}];let a=await ao(o.path).catch(()=>[]),c=await es(o.path,{getHarnessPreview:(m)=>y(o).workspacePreview(o,m),viewIds:a.map((m)=>m.id),thumbnailUrl:(m,E,_)=>`/api/workspaces/${o.id}/applet-thumbnails/${m}/${E}:${Date.parse(_).toString(36)}`});return[o.id,c]}));return t.json(Object.fromEntries(i))});var D$=new Set(["claude-code","codex"]);async function od(t){return await y(t).availability?.()??{status:"available"}}co.post("/create",async(t)=>{if(p().demo)return t.text(QE,403);let n=await t.req.json(),i=n?.harness??"claude-code";if(!Yt(i))return t.text("Unknown workspace type",400);let o=i;if(!D$.has(o))return t.text("Workspaces of this type arrive through discovery, not creation",400);let a=await od(o);if(a.status!=="available")return t.text(a.reason,400);let c=n?.name===void 0?"My workspace":typeof n.name==="string"?n.name.trim():"",m=Ri(c);if(m)return t.text(m,400);let E=await pr(c,Ce());try{await J(E,o)}catch(I){let T=I instanceof Error?I.message:String(I);return t.text(`Could not create workspace: ${T}`,500)}await mi(E,{name:c});let _=await z(E,{id:XE(E),harness:o,name:c});return h({type:"workspaces-list:changed"}),t.json(_,201)});co.route("/:id",_e);var vn=new Bs;vn.route("/api/workspaces",co);vn.route("/api/harnesses",No);vn.route("/api/onboarding",Ea);vn.get("/api/config",(t)=>t.json(Ms()));vn.get("/api/proxy-user",async(t)=>(t.header("Cache-Control","private, no-store"),t.json(await qu(t.req.raw))));vn.get("/api/update",async(t)=>(t.header("Cache-Control","no-store"),t.json(await Ci())));vn.post("/api/update",async(t)=>{if(wi())return t.text(Ni()?"An update is installed \u2014 Moi is restarting.":"An update is already in progress.",409);if(Ii(ie().flatMap((i)=>i.activeSessions())))return t.text(zv,409);try{let i=await Di();if(!i)return t.text("This Moi cannot be updated from the app",409);let o=t.json(i);return Oi(),o}catch(i){return t.text(i instanceof Error?i.message:"Could not update moi.",500)}});vn.get("/api/settings",(t)=>t.json(Lu()));vn.patch("/api/settings",async(t)=>{let n;try{n=await t.req.json()}catch{return t.text("Invalid JSON body",400)}if(!n||typeof n!=="object"||Array.isArray(n))return t.text("Settings patch must be an object",400);let i;try{i=Tv(_v(n))}catch(o){return t.text(o instanceof Error?o.message:"Invalid settings patch",400)}return h({type:"app-settings:changed",settings:i}),t.json(i)});if(Aa)vn.get("*",xh({root:Dh,onFound:(t,n)=>{n.header("Cache-Control",t.endsWith("index.html")?"no-cache":"public, max-age=31536000, immutable")}}));vn.notFound((t)=>t.text("Not found",404));import{resolve as iA}from"path";function L$(t=5000){let n=new Map,i=new Map,o=0;function a(_,I){let T=i.get(_);if(!T)return;if(clearTimeout(T.timer),i.delete(_),I)T.reject(Error(I));else T.resolve()}function c(_){n.delete(_);for(let[I,T]of i)if(T.client===_)a(I,"The browser disconnected before acknowledging navigation.")}function m(_,I){if(!Q(I))return;if(I.type==="navigation:presence"&&(typeof I.workspaceId==="string"||I.workspaceId===null)&&typeof I.focused==="boolean"){let T=n.get(_),R=I.workspaceId;n.set(_,{workspaceId:R,focusOrder:I.focused?++o:T?.workspaceId===R?T.focusOrder:0});for(let[P,M]of i)if(M.client===_&&M.workspaceId!==R)a(P,"The browser switched workspaces before acknowledging navigation.")}else if(I.type==="navigation:result"&&typeof I.requestId==="string"){let T=i.get(I.requestId);if(!T||T.client!==_)return;if(typeof I.error==="string")a(I.requestId,I.error);else if(I.ok===!0)a(I.requestId)}}function E(_,I){let T=[...n].filter(([,M])=>M.workspaceId===_);if(T.sort((M,N)=>N[1].focusOrder-M[1].focusOrder),!T.length)return Promise.reject(Error("No browser is showing this workspace. Open it in Moi and try again."));if(T.length>1&&T[0][1].focusOrder===0)return Promise.reject(Error("Several browsers show this workspace. Focus the one to navigate, then try again."));let R=T[0][0],P=crypto.randomUUID();return new Promise((M,N)=>{let H=setTimeout(()=>a(P,"Navigation acknowledgement timed out. Check the browser before retrying."),t);i.set(P,{client:R,workspaceId:_,resolve:M,reject:N,timer:H});let Z={type:"navigation:request",requestId:P,workspaceId:_,href:I};try{R.send(JSON.stringify(Z))}catch{a(P,"Could not send navigation to the browser.")}})}return{receive:m,remove:c,navigate:E}}var Ta=L$();var ad=new Map,j$=1e4;function eA(t,n){let i=crypto.randomUUID();return new Promise((o,a)=>{let c=setTimeout(()=>{ad.delete(i),a(Error("No live canvas \u2014 open the Scratchpad tab for this workspace."))},j$);ad.set(i,{resolve:o,reject:a,timer:c}),h({type:"scratchpad:op",workspaceId:t,opId:i,op:n})})}function tA(t,n,i){let o=ad.get(t);if(!o)return;if(ad.delete(t),clearTimeout(o.timer),i)o.reject(Error(i));else o.resolve(n??{ok:!0})}function rA(t,n){if(n.font&&!(n.font in le))return{ok:!1,error:`Unknown font theme: ${n.font}`};if(n.color&&!(n.color in ce))return{ok:!1,error:`Unknown color theme: ${n.color}`};if(n.radius&&!(n.radius in Ee))return{ok:!1,error:`Unknown radius theme: ${n.radius}`};if(n.agent&&!(n.agent in xe))return{ok:!1,error:`Unknown agent theme: ${n.agent}`};let{font:i,color:o,radius:a,agent:c}=n;return{ok:!0,theme:Xe({...t,...i?{font:i}:{},...o?{color:o}:{},...a?{radius:a}:{},...c?{agent:c}:{}}),applied:{...i?{font:i}:{},...o?{color:o}:{},...a?{radius:a}:{},...c?{agent:c}:{}}}}var nA=(t,n)=>Response.json({error:t instanceof Error?t.message:"Cloud request failed",signIn:t instanceof fe},{status:n,headers:{[$n]:"1"}});function sA(t=Hn(x),n=D){return async function(o){let a=new URL(o.url);if(a.pathname!=="/remote/info"&&a.pathname!=="/remote/request")return;if(o.headers.get(qn)!=="1"||o.headers.has("origin"))return nA(Error("Only the moi CLI can use this"),403);try{if(a.pathname==="/remote/info"){let R=await t.loginInfo();return Response.json(R,{headers:{[qt]:R.login??"none"}})}let c=a.searchParams.get("path")??"",{workspace:m,access:E}=Gr(o.method,c);if(E==="own login")throw Error("This request needs your own Cloud login");if(m&&!(await n()).some((R)=>R.remote?.user_id===m.user_id&&R.remote.workspace_id===m.workspace_id))throw Error("This workspace is not linked on this machine");let{response:_,agent:I}=await t.send(c,{method:o.method,body:o.body??void 0,contentLength:o.headers.get("content-length")??void 0,contentType:o.headers.get("content-type")??void 0,signal:o.signal}),T=_.headers.get("content-type");return new Response(_.body,{status:_.status,headers:{[qt]:I?"agent":"human",...T?{"content-type":T}:{}}})}catch(c){return nA(c,502)}}}var U$=sA();async function Zr(t,n){let i=await D();if(i.length===0)return t.send(JSON.stringify({error:"No workspaces registered"})),null;let o=iA(String(n??i[0].path)),a=Me(i,o);if(!a)return t.send(JSON.stringify({error:`${o} is not inside a registered Moi workspace. Open it in Moi, or run from the workspace root.`})),null;return a}var oA=Bun.serve({port:W,hostname:ue,async fetch(t,n){if(new URL(t.url).pathname.startsWith("/remote/"))n.timeout(t,0);let i=await U$(t);if(i)return i;return n.upgrade(t)?new Response(null,{status:101}):new Response("Control WebSocket only",{status:426})},websocket:{async message(t,n){try{let i=JSON.parse(String(n));if(i.type==="workspace:register"){let o=iA(String(i.path)),a=await z(o);h({type:"workspace:open-requested",workspaceId:a.id}),t.send(JSON.stringify({id:a.id,path:a.path}));return}if(i.type==="workspace:list"){let o=await D();t.send(JSON.stringify({workspaces:o}));return}if(i.type==="server:info"){t.send(JSON.stringify({version:C,pid:process.pid,port:w,unixSocket:p().unixSocket??void 0,service:!!process.env.MOI_SERVICE}));return}if(i.type==="bundle"){let o=await Zr(t,i.path);if(!o)return;let a=o.path,c=!!i.force,m=typeof i.only==="string"?it(i.only):void 0;if(i.only&&!m){t.send(JSON.stringify({error:`Invalid applet selector "${i.only}"`}));return}let E=[];if(await Cc(a,async()=>{if(m?.segment!=="views"){for(let _ of await WE(h,o.id,a,c,m?.id))if(!m?.id||_.name===m.id)E.push({kind:"widget",name:_.name,status:_.status,error:_.error})}if(m?.segment!=="widgets"){for(let _ of await rd(h,o.id,a,c,m?.id))if(!m?.id||_.name===m.id)E.push({kind:"view",name:_.name,status:_.status,error:_.error})}}),m?.id&&E.length===0){t.send(JSON.stringify({error:`Applet "${m.segment}/${m.id}" not found`}));return}t.send(JSON.stringify({ok:!0,workspacePath:a,results:E,logCount:Rh(a)}));return}if(i.type==="debug:logs"){let o=await Zr(t,i.path);if(!o)return;if(i.clear===!0){t.send(JSON.stringify({ok:!0,cleared:Zv(o.path)}));return}t.send(JSON.stringify({ok:!0,entries:Xv(o.path)}));return}if(i.type==="call-server-fn"){let o=await Zr(t,i.path);if(!o)return;let a=Xu(String(i.fn??""));if(!a){t.send(JSON.stringify({error:`Invalid function path "${i.fn}". Use <module>/<fn>, e.g. widgets/hello/getGreeting.`}));return}let c;try{c=JSON.parse(String(i.args??"[]"))}catch(E){t.send(JSON.stringify({error:`Arguments must be valid JSON: ${E instanceof Error?E.message:String(E)}`}));return}if(!Array.isArray(c)){t.send(JSON.stringify({error:`Arguments must be a JSON array, e.g. '["ann", 10]'`}));return}let m=performance.now();try{let E=await EE(a.module,a.name,Nt(c),o.path);t.send(JSON.stringify({ok:!0,result:E,ms:Math.round(performance.now()-m)}))}catch(E){t.send(JSON.stringify({error:E instanceof Error?E.message:String(E),ms:Math.round(performance.now()-m)}))}return}if(i.type==="view:create"){let o=await Zr(t,i.path);if(!o)return;try{if(typeof i.requirements!=="string")throw Error("View requirements are required");if(i.fromSessionId!==void 0&&typeof i.fromSessionId!=="string")throw Error("Invalid session id");let a=await KE(o,i.fromSessionId,i.requirements),c;try{await Ta.navigate(o.id,`moi:/views/${a.viewId}`)}catch(m){c=`View was created, but could not open it: ${m instanceof Error?m.message:"Navigation failed"}. Open it with moi navigate 'moi:/views/${a.viewId}'.`}t.send(JSON.stringify({ok:!0,...a,...c?{warning:c}:{}}))}catch(a){t.send(JSON.stringify({error:a instanceof Error?a.message:"Couldn\u2019t start view",...a instanceof Ia?{sessionId:a.sessionId,viewId:a.viewId}:{}}))}return}if(i.type==="view:set"){let o=await Zr(t,i.path);if(!o)return;let a=typeof i.id==="string"?i.id.trim():"",c=typeof i.title==="string"?i.title.trim():void 0,m=typeof i.icon==="string"?i.icon.trim():void 0;if(!a){t.send(JSON.stringify({error:"A view id is required"}));return}if(!/^[a-z0-9][a-z0-9_-]*$/.test(a)){t.send(JSON.stringify({error:"Id must start with a lowercase letter or number and use a-z, 0-9, _, or -"}));return}if(m&&!/^[a-z0-9][a-z0-9-]*$/.test(m)){t.send(JSON.stringify({error:"Icon must start with a lowercase letter or number and use a-z, 0-9, or -"}));return}try{let E=await Jr(o,a,{title:c,icon:m});t.send(JSON.stringify({ok:!0,viewId:E.id}))}catch(E){t.send(JSON.stringify({error:E instanceof U?E.message:"Couldn\u2019t update view"}))}return}if(i.type==="tabs"){let o=await Zr(t,i.path);if(!o)return;let a=await kc(o);t.send(JSON.stringify({ok:!0,tabs:st(a)}));return}if(i.type==="navigate"){let o=await Zr(t,i.path);if(!o)return;try{let a=Pt(i.href);if(!a.startsWith("moi:/")||a.startsWith("moi:/files/"))throw Error("Navigation needs a workspace page address");let c=a.slice(5).split("?",1)[0];if(re(c)&&!o.remote)_i(c,await kc(o));await Ta.navigate(o.id,a),t.send(JSON.stringify({ok:!0,href:a}))}catch(a){t.send(JSON.stringify({error:a instanceof Error?a.message:"Navigation failed"}))}return}if(i.type==="views:reconcile"){let o=await Zr(t,i.path);if(!o)return;await Cs(o),t.send(JSON.stringify({ok:!0}));return}if(i.type==="applets:refresh"){if(typeof i.path!=="string"||!i.path){t.send(JSON.stringify({error:"Refresh requires a workspace path"}));return}let o=await Zr(t,i.path);if(!o)return;let a=typeof i.only==="string"?it(i.only):void 0;if(i.only!==void 0&&!a){t.send(JSON.stringify({error:`Invalid applet selector "${i.only}"`}));return}h({type:"applets:refresh",workspaceId:o.id,only:a?.segment,name:a?.id}),t.send(JSON.stringify({ok:!0}));return}if(i.type==="env:view"){let o=await Zr(t,i.path);if(!o)return;let a=await Ut(o.path,Mc(o.path));t.send(JSON.stringify({view:a}));return}if(i.type==="env:update"){let o=await Zr(t,i.path);if(!o)return;let a=Ir(i.patch);if(typeof a==="string"){t.send(JSON.stringify({error:a}));return}await Cr(o.path,a),Qu(o),t.send(JSON.stringify({ok:!0,backend:await ns()}));return}if(i.type==="env:resolve"){let o=await Zr(t,i.path);if(!o)return;t.send(JSON.stringify({env:await X(o.path)}));return}if(i.type==="theme"){let o=await Zr(t,i.path);if(!o)return;let a=o.path;if(!i.font&&!i.color&&!i.radius&&!i.agent){let m=Xe((await Ft(a)).theme);t.send(JSON.stringify({currentFont:m.font,currentColor:m.color,currentRadius:m.radius,currentAgent:m.agent}));return}let c=rA(void 0,{font:i.font,color:i.color,radius:i.radius,agent:i.agent});if(!c.ok){t.send(JSON.stringify({error:c.error}));return}await ze(a,(m)=>({...m,theme:Xe({...m.theme,...c.applied})})),h({type:"workspace-config:changed",workspaceId:o.id}),t.send(JSON.stringify({ok:!0,...c.applied}));return}if(i.type==="config"){let o=await Zr(t,i.path);if(!o)return;let a=o.path,c=typeof i.name==="string",m=typeof i.iconPath==="string",E=i.clearName===!0,_=i.clearIcon===!0;if(!c&&!m&&!E&&!_){let T=await Ic(a);t.send(JSON.stringify({name:T.name??null,hasIcon:!!T.icon,path:a}));return}let I={};if(E)I.name=null;else if(c)I.name=String(i.name);if(_)I.icon=null;else if(m)try{I.icon={type:"upload",value:await ed(String(i.iconPath))}}catch(T){let R=T instanceof Error?T.message:String(T);t.send(JSON.stringify({error:`Could not read image: ${R}`}));return}await mi(a,I),h({type:"workspace-config:changed",workspaceId:o.id}),t.send(JSON.stringify({ok:!0,name:I.name??null,icon:m,clearedName:E,clearedIcon:_}));return}if(i.type==="scratch"){let o=i.op;if(!o||typeof o.kind!=="string"){t.send(JSON.stringify({error:"Missing scratch op"}));return}let a=await Zr(t,i.path);if(!a)return;if(o.kind==="read"){t.send(JSON.stringify({shapes:await xt(a.path)}));return}if(o.kind==="read-image"){t.send(JSON.stringify(await Et(a.path,String(o.name))));return}if(o.kind.startsWith("add-")&&!o.name)o.name=`s_${crypto.randomUUID().slice(0,8)}`;try{let c=o.kind==="view"?await eA(a.id,o):await Jl(a.path,a.id,o);t.send(JSON.stringify({ok:!0,result:c}))}catch(c){t.send(JSON.stringify({error:c instanceof Error?c.message:String(c)}))}return}}catch(i){console.error("[control]",i),t.send(JSON.stringify({error:i instanceof Error?i.message:String(i)}))}}}});var F$=Date.now();function Nc(t){let n=Math.floor(t/1000),i=Math.floor(n/3600),o=Math.floor(n%3600/60),a=n%60;if(i>0)return`${i}h ${o}m ${a}s`;if(o>0)return`${o}m ${a}s`;return`${a}s`}function q$(t,n){let i=Math.round((n-t)/1000);if(i<1)return"now";if(i<60)return`${i}s ago`;let o=Math.floor(i/60);if(o<60)return`${o}m ${i%60}s ago`;return`${Math.floor(o/60)}h ${o%60}m ago`}function B$(t){return`${(t/1048576).toFixed(1)}mb`}function W$(t,n){let i=t.pending>0?"\u25B6 busy":t.ready?"\u25CB warm":"\u2026 spawning",o=`calls=${t.calls}`,a=[];if(t.errors>0)a.push(`${t.errors} error${t.errors===1?"":"s"}`);if(t.timeouts>0)a.push(`${t.timeouts} timeout${t.timeouts===1?"":"s"}`);if(a.length>0)o+=` (${a.join(", ")})`;let c=[i.padEnd(10),`ws=${Yr(t.workspacePath)}`,`pid=${t.pid??"?"}`,o,`pending=${t.pending}`,`age=${Nc(n-t.spawnedAt)}`,`lastCall=${t.lastCallAt===null?"never":q$(t.lastCallAt,n)}`,`reap=${t.ttlRemainingMs>0?"in "+Nc(t.ttlRemainingMs):"imminent"}`];if(t.rssBytes!==null)c.push(`rss=${B$(t.rssBytes)}`);let m=" "+c.join(" ");return m+=`
|
|
79
|
+
${T.error}`);return a}function Fh(t){let{buildDir:n}=bn(t,"widget");return zu(n)}async function FE(t){let[n,i]=await Promise.all([Fh(t),nd(t)]);return n.map((o)=>{let a=i[o]??{},c=UE.includes(a.rowSpan)?a.rowSpan:Uh.rowSpan,m=UE.includes(a.colSpan)?a.colSpan:Uh.colSpan,E=Array.isArray(a.requiredEnv)?a.requiredEnv:void 0,_=Vu(t,"widget",o);return{id:o,config:{rowSpan:c,colSpan:m,...E?{requiredEnv:E}:{}},..._?{revision:_}:{}}})}async function qE(t){let n=await nd(t),i={};for(let[o,a]of Object.entries(n)){if(!Array.isArray(a.requiredEnv))continue;for(let c of a.requiredEnv)(i[c]??=[]).push(o)}return i}async function BE(t){return Response.json({widgets:await FE(t)})}async function WE(t,n,i,o=!1,a){let c=new Set(await Fh(i)),m=await nd(i),E=await R$(i,o,a),_=new Set(await Fh(i));Hu(i,"widget",E);let T=E.some((P)=>{if(P.status!=="built"||!P.config)return!1;let M=m[P.name];return!M||M.rowSpan!==P.config.rowSpan||M.colSpan!==P.config.colSpan})||c.size!==_.size||[...c].some((P)=>!_.has(P))||[..._].some((P)=>!c.has(P)),R=new Set;for(let P of E)if(P.status==="built"){t({type:"widget:changed",workspaceId:n,name:P.name});for(let M of P.serverModules??[])R.add(M)}if(R.size>0)Pc([...R],i);if(T){let P=await FE(i);t({type:"widgets-list:changed",workspaceId:n,widgets:P})}return E}function HE(t,n,i,o,a){return Gu("widget",t,n,i,o,a)}async function Mc(t){let[n,i]=await Promise.all([qE(t),NE(t)]),o={};for(let a of[n,i])for(let[c,m]of Object.entries(a))o[c]=[...o[c]??[],...m];return o}class Ia extends Error{sessionId;viewId;constructor(t,n,i){super(t instanceof Error?t.message:"Couldn\u2019t start view chat");this.sessionId=n;this.viewId=i}}async function P$(t,n,i,o){await mt(t,i,{tabId:n==="overview"?void 0:n}),await $e(t,i,n,o)}async function VE(t,n,i,o,a){await va(t,{...a,workspaceId:t.id,workspacePath:t.path,agentId:t.agentId,sessionId:i,isNew:o,viewBuildId:n.id,content:n.requirements}),await et(t,n.id,{status:"submitted"},"starting")}async function zE(t,n,i,o){if(o)await et(t,o.id,{status:"failed",error:n instanceof Error?n.message:"Couldn\u2019t start view chat"},"starting");throw new Ia(n,i?ee(t.id,i):void 0,o?.id)}async function GE(t,n,i){let o=Ue(n),{view:a,sessionId:c,pinned:m}=await S(t,(E)=>{let _=E.pinnedSessionId,I=_??i.sessionId??crypto.randomUUID(),T=Is(E,n,i.requirements,I,!!i.attachments?.length);if(!_)ms(E,I,o),Yn(E,t.id,I,o);return{view:T,sessionId:I,pinned:_}});try{await VE(t,a,c,!m,i)}catch(E){return zE(t,E,c,a)}return{viewId:n,sessionId:ee(t.id,c)}}async function KE(t,n,i){if(!i.trim())throw Error("View requirements are required");if(n===void 0){let m=await Jt(t,{requirements:i.trim(),status:"submitted"});return{viewId:m.id,mode:"in-place",buildInstructions:ju(m.id,Se)}}if(!n)throw Error("Session id cannot be empty");n=ee(t.id,n);let o=y(t);if(!(await o.listSessions(t)).some((m)=>m.sessionId===n)&&!o.activeSessions().some((m)=>m.workspaceId===t.id&&m.sessionId===n))throw Error("Source chat not found");let a,c;try{let m=await Wn(t,n);try{a=await o.forkSession?.(t,n,m)}catch(I){if(!(I instanceof Xt))throw I}let E=!a;if(a??=crypto.randomUUID(),!E){await mt(t,a,{fork:{fromSessionId:n}});let I=await o.sessionEvents(t,a).catch(()=>{return});if(I)await mt(t,a,{fork:{fromSessionId:n,...Ds(I)}})}let _=await Pe(t,a,m);return c=await Jt(t,{status:"starting",requirements:i.trim(),buildSessionId:a}),await P$(t,Ue(c.id),a),await VE(t,c,a,E,_),{viewId:c.id,mode:"handoff",sessionId:ee(t.id,a)}}catch(m){return zE(t,m,a,c)}}async function JE(t){for(let n of await _t(t))if(n.status==="starting")await et(t,n.id,{status:"failed",error:"View chat startup was interrupted. Check the chat before continuing; it has not been retried."},"starting")}import{resolve as sd}from"path";function C$(t,n){if(t.isDefault!==n.isDefault)return t.isDefault?-1:1;return(n.lastRunAt??"").localeCompare(t.lastRunAt??"")||t.agentId.localeCompare(n.agentId)}async function O$(t,n){let i=sd(t),o=(await n()).find((a)=>sd(a.path)===i);if(!o)throw Error("No Hermes profile owns this folder");return{...o.name?{name:o.name}:{},agentId:o.agentId,...o.isDefault?{isDefault:!0}:{}}}async function YE(t,n,i=Ie,o=ve){if(n==="hermes")return O$(t,o);if(n!=="openclaw")return{};let a=sd(t),c=(await i()).filter((m)=>sd(m.path)===a).sort(C$)[0];if(!c)throw Error("OpenClaw is not initialized for this folder");return{...c.name?{name:c.name}:{},agentId:c.agentId,...c.isDefault?{isDefault:!0}:{},...c.lastRunAt?{lastRunAt:c.lastRunAt}:{}}}function Bh(t){return typeof t==="string"?t:void 0}async function N$(t,n,i){let o=Xu(n);if(!o)return new Response("Invalid module or function name",{status:400});let{module:a,name:c}=o;try{if(Number(t.headers.get("content-length")??0)>1e6)return new Response("Request body too large",{status:413});let E=await t.text(),_=await vE(a,c,E,i);return new Response(_,{headers:{"Content-Type":"application/json"}})}catch(m){let E=m instanceof Error?m.message:"Unknown error";return Wu(i,{source:"rpc",...Qv(a)??{},module:a,fn:c,message:E}),new Response(E,{status:500})}}function Wh(t,{reserveOperation:n=!0}={}){return Vv(async(i,o)=>{let a=i.req.param("id");if(!a)return i.text("Workspace not found",404);let c;try{if(n&&i.req.method!=="GET")c=nr(a);let m=await q(a);if(!m)return i.text("Workspace not found",404);if(m.remote&&p().environment!=="cloud")return i.text("Remote workspaces require Cloud mode",403);if(m.remote&&t==="owner")return i.text("Use the owner workspace address",404);if(t==="owner"&&p().unixSocket)Lc(a,i.req.raw);i.set("ws",m),await o()}catch(m){if(m instanceof ae)return i.text(m.message,409);throw m}finally{c?.()}})}var tt=Wh("personal"),Qt=Wh("owner"),_e=new Bs;_e.patch("/harness",Wh("personal",{reserveOperation:!1}),async(t)=>{if(p().demo)return t.text("Changing agents is unavailable in the demo",403);let n=await t.req.json().catch(()=>null);if(!n||!["claude-code","codex"].includes(n.harness))return t.text("Invalid agent selection",400);try{return t.json(await ln(t.get("ws"),n.harness))}catch(i){if(i instanceof ae)return t.text(i.message,409);throw i}});_e.get("/widgets",Qt,(t)=>BE(t.get("ws").path));_e.get("/widgets/*",Qt,(t)=>{let n=t.get("ws"),{name:i,file:o}=kh(t.req.url,n.id,"widgets");if(!i)return t.text("Not found",404);return HE(i,o,n.path,We(n.id),t.req.header("if-none-match"))});_e.get("/views",Qt,async(t)=>t.req.query("includePending")==="true"?t.json({views:await kc(t.get("ws"))}):$E(t.get("ws").path));var ZE="Use the owner workspace address for compiled views";_e.patch("/views/:viewId",tt,async(t)=>{let n=t.get("ws"),i=await t.req.json().catch(()=>null);if(await Ht(n,t.req.param("viewId")))try{if(typeof i?.requirements!=="string"&&typeof i?.title!=="string"&&typeof i?.icon!=="string")return t.text("Expected requirements, title, or icon",400);return t.json(await Jr(n,t.req.param("viewId"),{requirements:typeof i.requirements==="string"?i.requirements:void 0,title:typeof i.title==="string"?i.title.trim():void 0,icon:typeof i.icon==="string"?i.icon:void 0}))}catch(a){if(a instanceof U)return t.text(a.message,a.status);throw a}if(n.remote)return t.text(ZE,404);let o=typeof i?.title==="string"?i.title.trim():"";if(!o)return t.text("Expected { title: string }",400);try{return t.json(await DE(h,n.id,n.path,t.req.param("viewId"),o))}catch(a){if(a instanceof ks||a instanceof U)return t.text(a.message,a.status);throw a}});_e.delete("/views/:viewId",tt,async(t)=>{let n=t.get("ws");try{let i=t.req.param("viewId");if(await Ht(n,i)){let o=new Set(y(n).activeSessions().filter((a)=>a.workspaceId===n.id).map((a)=>a.sessionId));await ws(n,i,o)}else if(n.remote)return t.text(ZE,404);else await LE(h,n,i);return t.body(null,204)}catch(i){if(i instanceof ks||i instanceof U)return t.text(i.message,i.status);throw i}});_e.get("/views/*",Qt,(t)=>{let n=t.get("ws"),{name:i,file:o}=kh(t.req.url,n.id,"views");if(!i)return t.text("Not found",404);return jE(i,o,n.path,We(n.id),t.req.header("if-none-match"))});_e.post("/views",tt,async(t)=>{let n=t.get("ws");return t.json(await Jt(n),201)});_e.post("/views/:viewId/submit",tt,async(t)=>{let n=t.get("ws"),i=await t.req.json();if(typeof i?.requirements!=="string")return t.text("Expected { requirements: string }",400);if(i.optimisticId!==void 0&&typeof i.optimisticId!=="string")return t.text("Invalid optimisticId",400);let o=i.attachments??[];if(!wr(o))return t.text("Invalid attachments",400);for(let c of o){if(c.type!=="upload")continue;if(!/^[a-f0-9]{64}$/.test(c.uploadId))return t.text("Invalid upload id",400);if(!Bn(n.id,c.uploadId))return t.text("Attachment not found or expired",400)}let a=await od(n.harness??"claude-code");if(a.status!=="available")return t.text(a.reason,400);try{let c=await GE(n,t.req.param("viewId"),{requirements:i.requirements,sessionId:typeof i.sessionId==="string"?i.sessionId:void 0,attachments:o,optimisticId:i.optimisticId,model:typeof i.model==="string"?i.model:void 0,effort:typeof i.effort==="string"?i.effort:void 0,speedMode:Me(i.speedMode)?i.speedMode:void 0,stream:i.stream===!0?!0:void 0});return t.json({...c,state:await Ae(n)})}catch(c){if(c instanceof U)return t.text(c.message,c.status);if(c instanceof Ia)return t.json({error:c.message,viewId:c.viewId,sessionId:c.sessionId},500);throw c}});_e.get("/files/*",Qt,(t)=>{let n=t.get("ws"),i=new URL(t.req.url).pathname.split(`${We(n.id)}/files/`)[1]??"";return dE(n.path,i,t.req.header("range"),t.req.header("if-none-match"))});_e.post("/rpc/*",Qt,(t)=>{let n=t.get("ws"),i=new URL(t.req.url).pathname.split(`${We(n.id)}/rpc/`)[1]??"";return N$(t.req.raw,i,n.path)});_e.post("/applet-log",Qt,async(t)=>{let n;try{n=await t.req.json()}catch{return t.text("Invalid JSON",400)}let i=Array.isArray(n.events)?n.events.slice(0,10):[];for(let o of i){let a=o;if(a.source!=="load"&&a.source!=="render"&&a.source!=="window"&&a.source!=="runtime")continue;let m=(a.kind==="widget"||a.kind==="view")&&typeof a.name==="string"&&/^[a-zA-Z0-9_-]+$/.test(a.name);if(!m&&a.source!=="runtime")continue;if(typeof a.message!=="string"||!a.message)continue;Wu(t.get("ws").path,{source:a.source,...m?{kind:a.kind,name:a.name}:{},message:a.message,...typeof a.stack==="string"?{stack:a.stack}:{}})}return t.body(null,204)});_e.get("/preview/*",tt,(t)=>{let n=t.get("ws"),i=new URL(t.req.url).pathname.split(`${We(n.id)}/preview/`)[1]??"";return RE(n.path,i,t.req.header("if-none-match"))});_e.post("/uploads",tt,async(t)=>{let n=t.get("ws"),i;try{i=await t.req.formData()}catch{return t.text("Choose a file to upload",400)}let o=i.getAll("files").filter((c)=>c instanceof File);if(o.length===0)return t.text("Choose a file to upload",400);if(o.length>20)return t.text("You can upload up to 20 files at a time",400);let a=[];for(let c of o){if(c.size>Qe)return t.text(`Files can be up to ${Qe/1048576} MB`,413);try{let m=Buffer.from(await c.arrayBuffer());a.push(await Fn({workspaceId:n.id,filename:c.name||"file",mediaType:c.type||"application/octet-stream",bytes:m}))}catch{return t.text(`Couldn\u2019t process "${c.name}"`,400)}}return t.json(a)});_e.post("/uploads/from-path",tt,async(t)=>{let n=await t.req.json().catch(()=>null);if(!n||typeof n!=="object"||!("path"in n)||typeof n.path!=="string")return t.text("Choose a file from this workspace",400);let i=t.get("ws");try{return t.json(await ss(i.id,i.path,n.path))}catch(o){if(o instanceof Error&&"code"in o){if(o.code==="ENOENT")return t.text("This file no longer exists",400);if(o.code==="EACCES"||o.code==="EPERM")return t.text("This file can\u2019t be read by Moi",400);return t.text("Something went wrong while adding this file",400)}return t.text(o instanceof Error?o.message:"Something went wrong while adding this file",400)}});_e.get("/uploads/:uploadId",tt,(t)=>{let n=Bn(t.get("ws").id,t.req.param("uploadId"));if(!n)return t.text("Not found or expired",404);let i=n.data?new Uint8Array(n.data):n.path?Bun.file(n.path):null;if(!i)return t.text("Not found or expired",404);return new Response(i,{headers:{"Content-Type":n.mediaType,"Content-Disposition":`inline; filename="${n.filename.replaceAll('"',"")}"`,"Cache-Control":"private, max-age=1800, immutable"}})});_e.get("/state",tt,async(t)=>t.json(await Ae(t.get("ws"))));_e.put("/state/tabs",tt,async(t)=>{let n=await t.req.json().catch(()=>null),i=t.get("ws");return await S(i,(o)=>{o.openTabs=vr(n?.openTabs)}),t.json(await Ae(i))});_e.get("/sessions",tt,async(t)=>{let n=t.get("ws");return t.json(await y(n).listSessions(n))});_e.put("/sessions/:sessionId/pin",tt,async(t)=>{let n=t.get("ws"),i=t.req.param("sessionId"),o=y(n),a=(await o.listSessions(n)).some((m)=>m.sessionId===i),c=o.activeSessions().some((m)=>m.workspaceId===n.id&&m.sessionId===i);if(!a&&!c)return t.text("Chat not found",404);return await xs(n,i),t.json(await Ae(n))});_e.delete("/sessions/:sessionId/pin",tt,async(t)=>{let n=t.get("ws");return await As(n,t.req.param("sessionId")),t.json(await Ae(n))});_e.put("/sessions/:sessionId/selection",tt,async(t)=>{let n=t.get("ws"),i=await t.req.json().catch(()=>null);if(!i||typeof i!=="object")return t.text("Bad request",400);let o=i;if(!re(o.tabId))return t.text("Invalid chat tab",400);let a=Object.prototype.hasOwnProperty.call(o,"ifMatch");if(a&&o.ifMatch!==null&&typeof o.ifMatch!=="string")return t.text("ifMatch must be a chat id or null",400);if(await qr(n))return t.text("Unpin chat before switching",409);return await $e(n,t.req.param("sessionId"),o.tabId,a?o.ifMatch:void 0),t.json(await Ae(n))});_e.delete("/sessions/:sessionId/selection",tt,async(t)=>{let n=t.get("ws"),o=(await t.req.json().catch(()=>null))?.tabId;if(!re(o))return t.text("Invalid chat tab",400);return await Ps(n,t.req.param("sessionId"),o),t.json(await Ae(n))});_e.on("PATCH",["/sessions/:sessionId/config","/state/chat-defaults"],tt,async(t)=>{let n=await t.req.json().catch(()=>null);if(typeof n!=="object"||n===null)return t.text("Expected a JSON object",400);let i={},o=n;for(let c of["model","effort"]){if(!(c in o))continue;let m=o[c];if(m!==null&&typeof m!=="string")return t.text(`${c} must be a string or null`,400);i[c]=m}if("speedMode"in o){let c=o.speedMode;if(c!==null&&!Me(c))return t.text('speedMode must be "normal", "fast", "ultrafast", or null',400);i.speedMode=c}let a=t.get("ws");return await Pe(a,t.req.param("sessionId"),i),t.json(await Ae(a))});_e.post("/sessions/:sessionId/archive",tt,async(t)=>{let n=t.get("ws"),i=y(n),o=t.req.param("sessionId");if(!i.archiveSession)return t.text("Chat archiving is not supported",501);try{return await Zn(n,o),t.json(await Ae(n))}catch(a){console.error(`[api] archive chat failed for ${i.id}`,a);let c=a instanceof Error&&a.message?a.message:"Couldn\u2019t archive chat";return t.text(c,500)}});_e.get("/sessions/:sessionId/events",tt,async(t)=>{let n=t.get("ws"),i=t.req.param("sessionId");return t.json(await y(n).sessionEvents(n,i))});_e.get("/mcp",tt,async(t)=>{let n=t.get("ws"),i=y(n);if(t.req.query("stream")!=="true")return t.json(await i.mcpStatus?.(n)??[]);let o=!1,a=new TextEncoder;return new Response(new ReadableStream({async start(c){let m=(E)=>{if(!o)c.enqueue(a.encode(JSON.stringify(E)+`
|
|
80
|
+
`))};try{let E=await i.mcpStatus?.(n,(_)=>m({connectors:_}))??[];m({connectors:E,done:!0})}catch{m({error:"Could not load connectors"})}finally{if(!o)c.close()}},cancel(){o=!0}}),{headers:{"Content-Type":"application/x-ndjson","Cache-Control":"no-store"}})});_e.get("/harness/debug",tt,async(t)=>{let n=t.get("ws"),i=y(n),o=Number(t.req.query("sinceWire")??0)||0,a=Number(t.req.query("sinceBroadcast")??0)||0;return t.json({harness:i.id,process:await i.debugInfo?.(n)??null,wire:as(i.wireScope?.(n)??n.id,o),broadcasts:os(n.id,a)})});_e.get("/env",tt,async(t)=>{let n=t.get("ws");return t.json(await Ut(n.path,Mc(n.path)))});_e.put("/env",tt,async(t)=>{let n=t.get("ws"),i=Ir(await t.req.json().catch(()=>null));if(typeof i==="string")return t.text(i,400);if(i.set!==void 0||i.remove!==void 0||i.inheritDotenv!==void 0)await Cr(n.path,i),Qu(n);return t.json(await Ut(n.path,Mc(n.path)))});_e.get("/skills",tt,async(t)=>{let n=t.get("ws");return t.json(await wt(n.path,n.harness))});_e.post("/skills/update",tt,async(t)=>{let n=t.get("ws"),i=await Dt(n.path,n.harness??"claude-code");return t.json(i.status)});_e.get("/harness",tt,async(t)=>{let n=t.get("ws"),i=y(n),o={harness:i.id,supportsStreaming:i.capabilities.supportsStreaming,supportsArchiving:Boolean(i.archiveSession)};if(!k$(n.path))return t.json({...o,isFolderMissing:!0,availability:{status:"unavailable",reason:"Workspace folder not found"},models:[]});let a=i.id==="codex"?/^(OPENAI_|CODEX_)/:/^(ANTHROPIC_|CLAUDE_|AWS_|GOOGLE_|AZURE_|CLOUD_ML_)/,c=i.authStatus&&Object.entries(await X(n.path)).some(([I,T])=>T!==process.env[I]&&(a.test(I)||/^(HOME|USERPROFILE|XDG_CONFIG_HOME)$/.test(I))),m=t.req.query("refresh")==="true";if(m)await Ke({refresh:!0});let[E,_]=await Promise.all([i.authStatus&&!c?Promise.resolve({status:"available"}):B.getAvailability(n,m),i.listModels(n).catch((I)=>(console.error(`[api] listModels failed for ${i.id}`,I),[]))]);return t.json({...o,availability:E,hasAuthOverrides:Boolean(c),models:_})});_e.get("/config",Qt,async(t)=>t.json(await Ic(t.get("ws").path)));_e.put("/config",Qt,async(t)=>{let n=t.get("ws"),i=await t.req.json().catch(()=>null);if(!i||typeof i!=="object"||Array.isArray(i))return t.text("Expected a workspace config object",400);let o=i,{name:a,icon:c}=o;if(a!==void 0&&a!==null&&typeof a!=="string")return t.text("Expected { name: string | null }",400);if(c!==void 0&&c!==null&&(!Sr(c)||c.type==="upload"))return t.text("Invalid icon",400);if(a===void 0&&c===void 0)return t.text("Expected a workspace config field",400);return await mi(n.path,{name:a,icon:c}),h({type:"workspace-config:changed",workspaceId:n.id,origin:Bh(o.origin)}),t.json(await Ic(n.path))});_e.post("/scratchpad/ops",Qt,async(t)=>{try{let n=await t.req.formData(),i=JSON.parse(String(n.get("op")));if(!i||typeof i.kind!=="string")return t.text("Invalid scratchpad edit",400);let o;if(i.kind==="add-image"){let c=n.get("image");if(!(c instanceof File))return t.text("Image file is required",400);o=new Uint8Array(await c.arrayBuffer())}let a=t.get("ws");return t.json(await Jl(a.path,a.id,i,o))}catch(n){return t.text(n instanceof Error?n.message:"Scratchpad edit failed",400)}});_e.get("/scratchpad",Qt,async(t)=>t.json(await at(t.get("ws").path)));_e.put("/scratchpad",Qt,async(t)=>{let n=t.get("ws"),i=await t.req.json().catch(()=>null);if(!i||typeof i!=="object"||!i.document)return t.text("Expected { document }",400);return await sr(i.document,n.path),h({type:"scratchpad:changed",workspaceId:n.id,origin:Bh(i.origin)}),t.body(null,204)});_e.post("/scratchpad/assets",Qt,async(t)=>{if(Number(t.req.header("content-length")??0)>St)return t.text(`Asset too large (max ${St/1048576} MB)`,413);let i=new Uint8Array(await t.req.arrayBuffer());if(i.length===0)return t.text("Empty body",400);if(i.length>St)return t.text(`Asset too large (max ${St/1048576} MB)`,413);let o=t.req.header("content-type")??"application/octet-stream";return t.json(await Tt(t.get("ws").path,i,o))});_e.get("/scratchpad/assets/:file",Qt,async(t)=>{let n=ir(t.get("ws").path,t.req.param("file"));if(!n||!await n.file.exists())return t.text("Not found",404);return new Response(n.file,{headers:{"Content-Type":n.mimeType,"Cache-Control":"public, max-age=31536000, immutable","Content-Disposition":"attachment","X-Content-Type-Options":"nosniff"}})});_e.put("/icon",Qt,async(t)=>{let n=t.get("ws"),i=new Uint8Array(await t.req.arrayBuffer());if(i.length===0)return t.text("Empty image body",400);let o;try{o=await ed(i)}catch(c){let m=c instanceof Error?c.message:String(c);return t.text(`Invalid image: ${m}`,400)}let a={type:"upload",value:o};return await mi(n.path,{icon:a}),h({type:"workspace-config:changed",workspaceId:t.get("ws").id}),t.json({icon:a})});_e.delete("/icon",Qt,async(t)=>(await mi(t.get("ws").path,{icon:null}),h({type:"workspace-config:changed",workspaceId:t.get("ws").id}),t.body(null,204)));_e.get("/",tt,async(t)=>{let n=t.get("ws"),i=await O(n.path);if(i.remote)return t.json({version:2,remote:i.remote,apiBase:We(i.remote.workspace_id,i.remote.user_id),isRemote:!0,cwd:n.path,harness:n.harness,agentId:n.agentId});let o=i;return t.json({...o,apiBase:We(n.id),isRemote:!1,name:o.name||XE(n.path),cwd:n.path,harness:n.harness,agentId:n.agentId})});_e.get("/applet-thumbnails",Qt,async(t)=>t.json({thumbnails:await Ji(t.get("ws").path)}));_e.get("/applet-thumbnails/:kind/:name",Qt,(t)=>{let n=t.req.param("kind");if(n!=="widget"&&n!=="view")return t.text("Not found",404);let[i,o]=t.req.param("name").split(":");return Zi(t.get("ws").path,n,i,t.req.header("if-none-match"),o!==void 0)});_e.put("/applet-thumbnails",Qt,async(t)=>{let n=await t.req.json().catch(()=>null);if(!n||typeof n!=="object"||Array.isArray(n))return t.text("Bad request",400);let i=n;if(!((i.kind==="widget"||i.kind==="view")&&Array.isArray(i.thumbnails)&&i.thumbnails.every((a)=>a&&typeof a==="object"&&!Array.isArray(a)&&typeof a.id==="string"&&Tr(a.id)&&typeof a.revision==="string"&&(a.image===void 0||a.image===null||typeof a.image==="string")&&(a.captureMs===void 0||typeof a.captureMs==="number"))))return t.text("Bad request",400);return await Xi(t.get("ws").path,i.kind,i.thumbnails),t.body(null,204)});function id(t){return nn((n)=>typeof n==="string"&&Object.hasOwn(t,n))}var $$=Rs({theme:Rs({font:id(le),color:id(ce),radius:id(Ee),agent:id(xe)}).optional(),widgetGrid:u(s({i:r().min(1),x:en().nonnegative(),y:en().nonnegative()})).optional(),origin:r().optional()}).refine((t)=>t.theme!==void 0||t.widgetGrid!==void 0);_e.put("/",tt,async(t)=>{let n=t.get("ws");if(n.remote)return t.text("Remote references contain only the owner address; save shared content to the owner",403);let i=$$.safeParse(await t.req.json().catch(()=>null));if(!i.success)return t.text("Invalid layout patch",400);let{origin:o,...a}=i.data,{changed:c}=await Ve(n.path,(m)=>Qi(m,a));if(c)h({type:"workspace-config:changed",workspaceId:n.id,origin:o});return t.body(null,204)});_e.delete("/",tt,async(t)=>{let n=t.get("ws");if(n.remote)return t.text("Leaving remote workspaces is not available yet",403);if(!await ri(n.id))return t.text("Workspace not found",404);return y(n).stopWorkspace?.(n.path),await Mo.stopWorkspace(n.path),t.body(null,204)});var co=new Bs;function qh(t){return p().environment==="cloud"?t:t.filter((n)=>!n.remote)}async function Hh(t){return Promise.all(t.map(async(n)=>{let i=await O(n.path).catch(()=>null);if(!i)return n;if(i.remote)return{...n,remote:i.remote,name:i.remote.workspace_id};return{...n,name:i.name??n.name,icon:i.icon,theme:i.theme}}))}co.get("/",async(t)=>{let n=await D();return t.json(await Hh(qh(n)))});co.put("/order",async(t)=>{let n=await t.req.json();if(!Array.isArray(n?.ids)||n.ids.some((i)=>typeof i!=="string"))return t.text("Expected { ids: string[] }",400);try{let i=await D(),o=new Set(qh(i).map((m)=>m.id)),a=i.filter((m)=>!o.has(m.id)).map((m)=>m.id),c=await ni([...n.ids,...a]);return h({type:"workspaces-list:changed",origin:Bh(n.origin)}),t.json(await Hh(qh(c)))}catch(i){let o=i instanceof Error?i.message:String(i);return t.text(o,400)}});var QE="Workspace creation is not available in the Moi demo";co.post("/",async(t)=>{if(p().demo)return t.text(QE,403);let n=await t.req.json().catch(()=>null);if(n&&typeof n==="object"&&"remote"in n){if(p().environment!=="cloud")return t.text("Shared workspaces require Cloud mode",403);if(Object.keys(n).some((T)=>T!=="remote"&&T!=="harness"))return t.text("Remote registration expects only remote and harness",400);let _;try{_=K(n.remote)}catch(T){return t.text(T instanceof Error?T.message:"Invalid remote workspace",400)}let I=n.harness;if(I!==void 0){if(I!=="claude-code"&&I!=="codex")return t.text("Unknown workspace type",400);let T=await od(I);if(T.status!=="available")return t.text(T.reason,400)}try{return t.json(await gi(_,I),201)}catch(T){return t.text(T instanceof Error?T.message:"Could not open shared workspace",503)}}if(!n?.path)return t.text("Missing path",400);let i=n?.harness??"claude-code";if(!Yt(i))return t.text("Unknown workspace type",400);let o=i,a=await od(o);if(a.status!=="available")return t.text(a.reason,400);let c=M$(String(n.path)),m;try{m=await YE(c,o)}catch(_){let I=_ instanceof Error?_.message:String(_);return t.text(I,400)}try{await J(c,o)}catch(_){let I=_ instanceof Error?_.message:String(_);return t.text(`Could not initialize workspace: ${I}`,500)}let E=await z(c,{harness:o,...m});return t.json((await Hh([E]))[0],201)});co.get("/discover",async(t)=>t.json(await ii()));co.get("/previews",async(t)=>{let n=await D(),i=await Promise.all(n.map(async(o)=>{if(o.remote)return[o.id,{thumbnails:[]}];let a=await ao(o.path).catch(()=>[]),c=await es(o.path,{getHarnessPreview:(m)=>y(o).workspacePreview(o,m),viewIds:a.map((m)=>m.id),thumbnailUrl:(m,E,_)=>`/api/workspaces/${o.id}/applet-thumbnails/${m}/${E}:${Date.parse(_).toString(36)}`});return[o.id,c]}));return t.json(Object.fromEntries(i))});var D$=new Set(["claude-code","codex"]);async function od(t){return await y(t).availability?.()??{status:"available"}}co.post("/create",async(t)=>{if(p().demo)return t.text(QE,403);let n=await t.req.json(),i=n?.harness??"claude-code";if(!Yt(i))return t.text("Unknown workspace type",400);let o=i;if(!D$.has(o))return t.text("Workspaces of this type arrive through discovery, not creation",400);let a=await od(o);if(a.status!=="available")return t.text(a.reason,400);let c=n?.name===void 0?"My workspace":typeof n.name==="string"?n.name.trim():"",m=Ri(c);if(m)return t.text(m,400);let E=await pr(c,Ce());try{await J(E,o)}catch(I){let T=I instanceof Error?I.message:String(I);return t.text(`Could not create workspace: ${T}`,500)}await mi(E,{name:c});let _=await z(E,{id:XE(E),harness:o,name:c});return h({type:"workspaces-list:changed"}),t.json(_,201)});co.route("/:id",_e);var vn=new Bs;vn.route("/api/workspaces",co);vn.route("/api/harnesses",No);vn.route("/api/onboarding",Ea);vn.get("/api/config",(t)=>t.json(Ms()));vn.get("/api/proxy-user",async(t)=>(t.header("Cache-Control","private, no-store"),t.json(await qu(t.req.raw))));vn.get("/api/update",async(t)=>(t.header("Cache-Control","no-store"),t.json(await Ci())));vn.post("/api/update",async(t)=>{if(wi())return t.text(Ni()?"An update is installed \u2014 Moi is restarting.":"An update is already in progress.",409);if(Ii(ie().flatMap((i)=>i.activeSessions())))return t.text(zv,409);try{let i=await Di();if(!i)return t.text("This Moi cannot be updated from the app",409);let o=t.json(i);return Oi(),o}catch(i){return t.text(i instanceof Error?i.message:"Could not update moi.",500)}});vn.get("/api/settings",(t)=>t.json(Lu()));vn.patch("/api/settings",async(t)=>{let n;try{n=await t.req.json()}catch{return t.text("Invalid JSON body",400)}if(!n||typeof n!=="object"||Array.isArray(n))return t.text("Settings patch must be an object",400);let i;try{i=Tv(_v(n))}catch(o){return t.text(o instanceof Error?o.message:"Invalid settings patch",400)}return h({type:"app-settings:changed",settings:i}),t.json(i)});if(Aa)vn.get("*",xh({root:Dh,onFound:(t,n)=>{n.header("Cache-Control",t.endsWith("index.html")?"no-cache":"public, max-age=31536000, immutable")}}));vn.notFound((t)=>t.text("Not found",404));import{resolve as iA}from"path";function L$(t=5000){let n=new Map,i=new Map,o=0;function a(_,I){let T=i.get(_);if(!T)return;if(clearTimeout(T.timer),i.delete(_),I)T.reject(Error(I));else T.resolve()}function c(_){n.delete(_);for(let[I,T]of i)if(T.client===_)a(I,"The browser disconnected before acknowledging navigation.")}function m(_,I){if(!Q(I))return;if(I.type==="navigation:presence"&&(typeof I.workspaceId==="string"||I.workspaceId===null)&&typeof I.focused==="boolean"){let T=n.get(_),R=I.workspaceId;n.set(_,{workspaceId:R,focusOrder:I.focused?++o:T?.workspaceId===R?T.focusOrder:0});for(let[P,M]of i)if(M.client===_&&M.workspaceId!==R)a(P,"The browser switched workspaces before acknowledging navigation.")}else if(I.type==="navigation:result"&&typeof I.requestId==="string"){let T=i.get(I.requestId);if(!T||T.client!==_)return;if(typeof I.error==="string")a(I.requestId,I.error);else if(I.ok===!0)a(I.requestId)}}function E(_,I){let T=[...n].filter(([,M])=>M.workspaceId===_);if(T.sort((M,N)=>N[1].focusOrder-M[1].focusOrder),!T.length)return Promise.reject(Error("No browser is showing this workspace. Open it in Moi and try again."));if(T.length>1&&T[0][1].focusOrder===0)return Promise.reject(Error("Several browsers show this workspace. Focus the one to navigate, then try again."));let R=T[0][0],P=crypto.randomUUID();return new Promise((M,N)=>{let H=setTimeout(()=>a(P,"Navigation acknowledgement timed out. Check the browser before retrying."),t);i.set(P,{client:R,workspaceId:_,resolve:M,reject:N,timer:H});let Z={type:"navigation:request",requestId:P,workspaceId:_,href:I};try{R.send(JSON.stringify(Z))}catch{a(P,"Could not send navigation to the browser.")}})}return{receive:m,remove:c,navigate:E}}var Ta=L$();var ad=new Map,j$=1e4;function eA(t,n){let i=crypto.randomUUID();return new Promise((o,a)=>{let c=setTimeout(()=>{ad.delete(i),a(Error("No live canvas \u2014 open the Scratchpad tab for this workspace."))},j$);ad.set(i,{resolve:o,reject:a,timer:c}),h({type:"scratchpad:op",workspaceId:t,opId:i,op:n})})}function tA(t,n,i){let o=ad.get(t);if(!o)return;if(ad.delete(t),clearTimeout(o.timer),i)o.reject(Error(i));else o.resolve(n??{ok:!0})}function rA(t,n){if(n.font&&!(n.font in le))return{ok:!1,error:`Unknown font theme: ${n.font}`};if(n.color&&!(n.color in ce))return{ok:!1,error:`Unknown color theme: ${n.color}`};if(n.radius&&!(n.radius in Ee))return{ok:!1,error:`Unknown radius theme: ${n.radius}`};if(n.agent&&!(n.agent in xe))return{ok:!1,error:`Unknown agent theme: ${n.agent}`};let{font:i,color:o,radius:a,agent:c}=n;return{ok:!0,theme:Ye({...t,...i?{font:i}:{},...o?{color:o}:{},...a?{radius:a}:{},...c?{agent:c}:{}}),applied:{...i?{font:i}:{},...o?{color:o}:{},...a?{radius:a}:{},...c?{agent:c}:{}}}}var nA=(t,n)=>Response.json({error:t instanceof Error?t.message:"Cloud request failed",signIn:t instanceof fe},{status:n,headers:{[$n]:"1"}});function sA(t=Hn(x),n=D){return async function(o){let a=new URL(o.url);if(a.pathname!=="/remote/info"&&a.pathname!=="/remote/request")return;if(o.headers.get(qn)!=="1"||o.headers.has("origin"))return nA(Error("Only the moi CLI can use this"),403);try{if(a.pathname==="/remote/info"){let R=await t.loginInfo();return Response.json(R,{headers:{[qt]:R.login??"none"}})}let c=a.searchParams.get("path")??"",{workspace:m,access:E}=Gr(o.method,c);if(E==="own login")throw Error("This request needs your own Cloud login");if(m&&!(await n()).some((R)=>R.remote?.user_id===m.user_id&&R.remote.workspace_id===m.workspace_id))throw Error("This workspace is not linked on this machine");let{response:_,agent:I}=await t.send(c,{method:o.method,body:o.body??void 0,contentLength:o.headers.get("content-length")??void 0,contentType:o.headers.get("content-type")??void 0,signal:o.signal}),T=_.headers.get("content-type");return new Response(_.body,{status:_.status,headers:{[qt]:I?"agent":"human",...T?{"content-type":T}:{}}})}catch(c){return nA(c,502)}}}var U$=sA();async function Zr(t,n){let i=await D();if(i.length===0)return t.send(JSON.stringify({error:"No workspaces registered"})),null;let o=iA(String(n??i[0].path)),a=Fe(i,o);if(!a)return t.send(JSON.stringify({error:`${o} is not inside a registered Moi workspace. Open it in Moi, or run from the workspace root.`})),null;return a}var oA=Bun.serve({port:W,hostname:ue,async fetch(t,n){if(new URL(t.url).pathname.startsWith("/remote/"))n.timeout(t,0);let i=await U$(t);if(i)return i;return n.upgrade(t)?new Response(null,{status:101}):new Response("Control WebSocket only",{status:426})},websocket:{async message(t,n){try{let i=JSON.parse(String(n));if(i.type==="workspace:register"){let o=iA(String(i.path)),a=await z(o);h({type:"workspace:open-requested",workspaceId:a.id}),t.send(JSON.stringify({id:a.id,path:a.path}));return}if(i.type==="workspace:list"){let o=await D();t.send(JSON.stringify({workspaces:o}));return}if(i.type==="server:info"){t.send(JSON.stringify({version:C,pid:process.pid,port:w,unixSocket:p().unixSocket??void 0,service:!!process.env.MOI_SERVICE}));return}if(i.type==="bundle"){let o=await Zr(t,i.path);if(!o)return;let a=o.path,c=!!i.force,m=typeof i.only==="string"?it(i.only):void 0;if(i.only&&!m){t.send(JSON.stringify({error:`Invalid applet selector "${i.only}"`}));return}let E=[];if(await Cc(a,async()=>{if(m?.segment!=="views"){for(let _ of await WE(h,o.id,a,c,m?.id))if(!m?.id||_.name===m.id)E.push({kind:"widget",name:_.name,status:_.status,error:_.error})}if(m?.segment!=="widgets"){for(let _ of await rd(h,o.id,a,c,m?.id))if(!m?.id||_.name===m.id)E.push({kind:"view",name:_.name,status:_.status,error:_.error})}}),m?.id&&E.length===0){t.send(JSON.stringify({error:`Applet "${m.segment}/${m.id}" not found`}));return}t.send(JSON.stringify({ok:!0,workspacePath:a,results:E,logCount:Rh(a)}));return}if(i.type==="debug:logs"){let o=await Zr(t,i.path);if(!o)return;if(i.clear===!0){t.send(JSON.stringify({ok:!0,cleared:Zv(o.path)}));return}t.send(JSON.stringify({ok:!0,entries:Xv(o.path)}));return}if(i.type==="call-server-fn"){let o=await Zr(t,i.path);if(!o)return;let a=Xu(String(i.fn??""));if(!a){t.send(JSON.stringify({error:`Invalid function path "${i.fn}". Use <module>/<fn>, e.g. widgets/hello/getGreeting.`}));return}let c;try{c=JSON.parse(String(i.args??"[]"))}catch(E){t.send(JSON.stringify({error:`Arguments must be valid JSON: ${E instanceof Error?E.message:String(E)}`}));return}if(!Array.isArray(c)){t.send(JSON.stringify({error:`Arguments must be a JSON array, e.g. '["ann", 10]'`}));return}let m=performance.now();try{let E=await EE(a.module,a.name,Nt(c),o.path);t.send(JSON.stringify({ok:!0,result:E,ms:Math.round(performance.now()-m)}))}catch(E){t.send(JSON.stringify({error:E instanceof Error?E.message:String(E),ms:Math.round(performance.now()-m)}))}return}if(i.type==="view:create"){let o=await Zr(t,i.path);if(!o)return;try{if(typeof i.requirements!=="string")throw Error("View requirements are required");if(i.fromSessionId!==void 0&&typeof i.fromSessionId!=="string")throw Error("Invalid session id");let a=await KE(o,i.fromSessionId,i.requirements),c;try{await Ta.navigate(o.id,`moi:/views/${a.viewId}`)}catch(m){c=`View was created, but could not open it: ${m instanceof Error?m.message:"Navigation failed"}. Open it with moi navigate 'moi:/views/${a.viewId}'.`}t.send(JSON.stringify({ok:!0,...a,...c?{warning:c}:{}}))}catch(a){t.send(JSON.stringify({error:a instanceof Error?a.message:"Couldn\u2019t start view",...a instanceof Ia?{sessionId:a.sessionId,viewId:a.viewId}:{}}))}return}if(i.type==="view:set"){let o=await Zr(t,i.path);if(!o)return;let a=typeof i.id==="string"?i.id.trim():"",c=typeof i.title==="string"?i.title.trim():void 0,m=typeof i.icon==="string"?i.icon.trim():void 0;if(!a){t.send(JSON.stringify({error:"A view id is required"}));return}if(!/^[a-z0-9][a-z0-9_-]*$/.test(a)){t.send(JSON.stringify({error:"Id must start with a lowercase letter or number and use a-z, 0-9, _, or -"}));return}if(m&&!/^[a-z0-9][a-z0-9-]*$/.test(m)){t.send(JSON.stringify({error:"Icon must start with a lowercase letter or number and use a-z, 0-9, or -"}));return}try{let E=await Jr(o,a,{title:c,icon:m});t.send(JSON.stringify({ok:!0,viewId:E.id}))}catch(E){t.send(JSON.stringify({error:E instanceof U?E.message:"Couldn\u2019t update view"}))}return}if(i.type==="tabs"){let o=await Zr(t,i.path);if(!o)return;let a=await kc(o);t.send(JSON.stringify({ok:!0,tabs:st(a)}));return}if(i.type==="navigate"){let o=await Zr(t,i.path);if(!o)return;try{let a=Pt(i.href);if(!a.startsWith("moi:/")||a.startsWith("moi:/files/"))throw Error("Navigation needs a workspace page address");let c=a.slice(5).split("?",1)[0];if(re(c)&&!o.remote)_i(c,await kc(o));await Ta.navigate(o.id,a),t.send(JSON.stringify({ok:!0,href:a}))}catch(a){t.send(JSON.stringify({error:a instanceof Error?a.message:"Navigation failed"}))}return}if(i.type==="views:reconcile"){let o=await Zr(t,i.path);if(!o)return;await Cs(o),t.send(JSON.stringify({ok:!0}));return}if(i.type==="applets:refresh"){if(typeof i.path!=="string"||!i.path){t.send(JSON.stringify({error:"Refresh requires a workspace path"}));return}let o=await Zr(t,i.path);if(!o)return;let a=typeof i.only==="string"?it(i.only):void 0;if(i.only!==void 0&&!a){t.send(JSON.stringify({error:`Invalid applet selector "${i.only}"`}));return}h({type:"applets:refresh",workspaceId:o.id,only:a?.segment,name:a?.id}),t.send(JSON.stringify({ok:!0}));return}if(i.type==="env:view"){let o=await Zr(t,i.path);if(!o)return;let a=await Ut(o.path,Mc(o.path));t.send(JSON.stringify({view:a}));return}if(i.type==="env:update"){let o=await Zr(t,i.path);if(!o)return;let a=Ir(i.patch);if(typeof a==="string"){t.send(JSON.stringify({error:a}));return}await Cr(o.path,a),Qu(o),t.send(JSON.stringify({ok:!0,backend:await ns()}));return}if(i.type==="env:resolve"){let o=await Zr(t,i.path);if(!o)return;t.send(JSON.stringify({env:await X(o.path)}));return}if(i.type==="theme"){let o=await Zr(t,i.path);if(!o)return;let a=o.path;if(!i.font&&!i.color&&!i.radius&&!i.agent){let m=Ye((await Ft(a)).theme);t.send(JSON.stringify({currentFont:m.font,currentColor:m.color,currentRadius:m.radius,currentAgent:m.agent}));return}let c=rA(void 0,{font:i.font,color:i.color,radius:i.radius,agent:i.agent});if(!c.ok){t.send(JSON.stringify({error:c.error}));return}await Ve(a,(m)=>({...m,theme:Ye({...m.theme,...c.applied})})),h({type:"workspace-config:changed",workspaceId:o.id}),t.send(JSON.stringify({ok:!0,...c.applied}));return}if(i.type==="config"){let o=await Zr(t,i.path);if(!o)return;let a=o.path,c=typeof i.name==="string",m=typeof i.iconPath==="string",E=i.clearName===!0,_=i.clearIcon===!0;if(!c&&!m&&!E&&!_){let T=await Ic(a);t.send(JSON.stringify({name:T.name??null,hasIcon:!!T.icon,path:a}));return}let I={};if(E)I.name=null;else if(c)I.name=String(i.name);if(_)I.icon=null;else if(m)try{I.icon={type:"upload",value:await ed(String(i.iconPath))}}catch(T){let R=T instanceof Error?T.message:String(T);t.send(JSON.stringify({error:`Could not read image: ${R}`}));return}await mi(a,I),h({type:"workspace-config:changed",workspaceId:o.id}),t.send(JSON.stringify({ok:!0,name:I.name??null,icon:m,clearedName:E,clearedIcon:_}));return}if(i.type==="scratch"){let o=i.op;if(!o||typeof o.kind!=="string"){t.send(JSON.stringify({error:"Missing scratch op"}));return}let a=await Zr(t,i.path);if(!a)return;if(o.kind==="read"){t.send(JSON.stringify({shapes:await xt(a.path)}));return}if(o.kind==="read-image"){t.send(JSON.stringify(await Et(a.path,String(o.name))));return}if(o.kind.startsWith("add-")&&!o.name)o.name=`s_${crypto.randomUUID().slice(0,8)}`;try{let c=o.kind==="view"?await eA(a.id,o):await Jl(a.path,a.id,o);t.send(JSON.stringify({ok:!0,result:c}))}catch(c){t.send(JSON.stringify({error:c instanceof Error?c.message:String(c)}))}return}}catch(i){console.error("[control]",i),t.send(JSON.stringify({error:i instanceof Error?i.message:String(i)}))}}}});var F$=Date.now();function Nc(t){let n=Math.floor(t/1000),i=Math.floor(n/3600),o=Math.floor(n%3600/60),a=n%60;if(i>0)return`${i}h ${o}m ${a}s`;if(o>0)return`${o}m ${a}s`;return`${a}s`}function q$(t,n){let i=Math.round((n-t)/1000);if(i<1)return"now";if(i<60)return`${i}s ago`;let o=Math.floor(i/60);if(o<60)return`${o}m ${i%60}s ago`;return`${Math.floor(o/60)}h ${o%60}m ago`}function B$(t){return`${(t/1048576).toFixed(1)}mb`}function W$(t,n){let i=t.pending>0?"\u25B6 busy":t.ready?"\u25CB warm":"\u2026 spawning",o=`calls=${t.calls}`,a=[];if(t.errors>0)a.push(`${t.errors} error${t.errors===1?"":"s"}`);if(t.timeouts>0)a.push(`${t.timeouts} timeout${t.timeouts===1?"":"s"}`);if(a.length>0)o+=` (${a.join(", ")})`;let c=[i.padEnd(10),`ws=${Yr(t.workspacePath)}`,`pid=${t.pid??"?"}`,o,`pending=${t.pending}`,`age=${Nc(n-t.spawnedAt)}`,`lastCall=${t.lastCallAt===null?"never":q$(t.lastCallAt,n)}`,`reap=${t.ttlRemainingMs>0?"in "+Nc(t.ttlRemainingMs):"imminent"}`];if(t.rssBytes!==null)c.push(`rss=${B$(t.rssBytes)}`);let m=" "+c.join(" ");return m+=`
|
|
81
81
|
modules: ${t.modules.length>0?t.modules.join(", "):"(none loaded)"}`,m}function aA(){let t=Date.now(),n=[];n.push("Moi server status"),n.push("================="),n.push(""),n.push(`version ${C}${process.env.MOI_SERVICE?" (service-managed)":""}`),n.push(`uptime ${Nc(t-F$)}`);let{unixSocket:i}=p();n.push(i?`web socket ${i}`:`http port ${w}`),n.push(`control port ${W}`),n.push(`debug logging ${zt?"on (--debug)":"off"}`),n.push(`connected tabs ${Dr()}`),n.push("");for(let a of ie()){let c=a.statusLines?.(t);if(!c?.length)continue;n.push(...c),n.push("")}let o=_E();if(n.push(`function workers ${o.length}/${Zu.maxWorkers} (one per workspace, idle TTL ${Nc(Zu.idleTtlMs)}, call timeout ${Nc(Zu.callTimeoutMs)})`),o.length===0)n.push(" (none running \u2014 spawned lazily on the first server-function call)");else{let a=[...o].sort((c,m)=>m.pending-c.pending||(m.lastCallAt??0)-(c.lastCallAt??0));for(let c of a)n.push(W$(c,t))}return n.push(""),n.join(`
|
|
82
82
|
`)+`
|
|
83
|
-
`}import{join as cA}from"path";var H$=v("client","vendor","react"),V$=v("client","vendor","emojibase"),z$=/^\d[\w.-]*\/(development|production)\/(_impl\/)?[a-zA-Z0-9_-]+\.js$/;async function lA(t){let n=new URL(t.url).pathname.replace(/^\/vendor\/react\//,"");if(!z$.test(n)||n.includes(".."))return new Response("Not found",{status:404});let i=Bun.file(cA(H$,n));if(!await i.exists())return new Response("Not found",{status:404});return new Response(i,{headers:{"Content-Type":"text/javascript; charset=utf-8","Cache-Control":"public, max-age=31536000, immutable"}})}var G$=/^[a-z-]+\/[a-z]+\.json$/;async function uA(t){let n=new URL(t.url).pathname.replace(/^\/vendor\/emojibase\//,"");if(!G$.test(n)||n.includes(".."))return new Response("Not found",{status:404});let i=Bun.file(cA(V$,n));if(!await i.exists())return new Response("Not found",{status:404});return new Response(i,{headers:{"Content-Type":"application/json; charset=utf-8","Cache-Control":"public, max-age=3600"}})}function X$(t){if(typeof t!=="object"||t===null||!("type"in t))return!1;let n=t;if(n.type==="chat")return typeof n.workspaceId==="string"&&typeof n.content==="string"&&typeof n.sessionId==="string"&&typeof n.isNew==="boolean"&&(n.optimisticId===void 0||typeof n.optimisticId==="string")&&(n.model===void 0||typeof n.model==="string")&&(n.effort===void 0||typeof n.effort==="string")&&(n.speedMode===void 0||
|
|
83
|
+
`}import{join as cA}from"path";var H$=v("client","vendor","react"),V$=v("client","vendor","emojibase"),z$=/^\d[\w.-]*\/(development|production)\/(_impl\/)?[a-zA-Z0-9_-]+\.js$/;async function lA(t){let n=new URL(t.url).pathname.replace(/^\/vendor\/react\//,"");if(!z$.test(n)||n.includes(".."))return new Response("Not found",{status:404});let i=Bun.file(cA(H$,n));if(!await i.exists())return new Response("Not found",{status:404});return new Response(i,{headers:{"Content-Type":"text/javascript; charset=utf-8","Cache-Control":"public, max-age=31536000, immutable"}})}var G$=/^[a-z-]+\/[a-z]+\.json$/;async function uA(t){let n=new URL(t.url).pathname.replace(/^\/vendor\/emojibase\//,"");if(!G$.test(n)||n.includes(".."))return new Response("Not found",{status:404});let i=Bun.file(cA(V$,n));if(!await i.exists())return new Response("Not found",{status:404});return new Response(i,{headers:{"Content-Type":"application/json; charset=utf-8","Cache-Control":"public, max-age=3600"}})}function X$(t){if(typeof t!=="object"||t===null||!("type"in t))return!1;let n=t;if(n.type==="chat")return typeof n.workspaceId==="string"&&typeof n.content==="string"&&typeof n.sessionId==="string"&&typeof n.isNew==="boolean"&&(n.optimisticId===void 0||typeof n.optimisticId==="string")&&(n.model===void 0||typeof n.model==="string")&&(n.effort===void 0||typeof n.effort==="string")&&(n.speedMode===void 0||Me(n.speedMode))&&(n.stream===void 0||typeof n.stream==="boolean")&&(n.context===void 0||is(n.context))&&(n.attachments===void 0||wr(n.attachments));if(n.type==="stop")return typeof n.workspaceId==="string"&&typeof n.sessionId==="string";return!1}var Lo=Aa?TE:qc;function fA(){return{type:"sessions:status-snapshot",sessions:ie().flatMap((t)=>t.activeSessions())}}function Vh(t,n,i){return t.upgrade(n,{data:i})?new Response(null,{status:101}):new Response("Upgrade failed",{status:500})}var pA=await D();await fs(pA);await Promise.all(pA.map(JE));var{unixSocket:Ra}=p();if(Ra)await K$(Ra,{force:!0});var Z$=Ra?{unix:Ra}:{port:w,hostname:process.env.HOST??"127.0.0.1"},Q$=Ra?await am(Y$(J$(Ra),"ops.sock")):void 0,hA=Bun.serve({...Z$,idleTimeout:60,development:Aa?!1:{hmr:!0},routes:{"/status":()=>new Response(aA(),{headers:{"Content-Type":"text/plain; charset=utf-8","Cache-Control":"no-store"}}),"/vendor/react/*":(t)=>lA(t),"/vendor/emojibase/*":(t)=>uA(t),"/":Lo,...p().demo?{"/demo":Lo}:{},"/dev":Lo,"/dev/*":Lo,"/dev/workspace-setup/preview":Aa?new Response("Not found",{status:404}):qc,"/workspace/*":Lo,"/settings":Lo,"/onboarding":Lo,"/api/harness/events":(t,n)=>Vh(n,t,{channel:"chat",workspaceId:""}),"/api/events":(t,n)=>Vh(n,t,{channel:"events",workspaceId:""}),"/api/workspaces/:id/events":async(t,n)=>{let i=decodeURIComponent(new URL(t.url).pathname.split("/")[3]??""),o=await q(i);if(!o)return new Response("Workspace not found",{status:404});if(o.remote)return new Response("Use the owner workspace address",{status:404});let{provider:a,profile:c}=await qu(t);if(a&&!c)return new Response("Sign in through Cloudflare Access to join",{status:401});return Vh(n,t,{channel:"workspace",workspaceId:i,workspacePath:o.path,...c?{verifiedProfile:c}:{}})}},fetch:(t,n)=>{if(t.method==="POST"&&/^\/api\/harnesses\/(claude-code|codex)\/auth\/install$/.test(new URL(t.url).pathname))n.timeout(t,0);return vn.fetch(t)},websocket:{open(t){if(t.data.channel==="workspace")t.subscribe(Kt(t.data.workspaceId));else if(t.data.channel==="chat")t.subscribe(Nr),ls(t),ps(t,fA());else t.subscribe(Vt)},async message(t,n){if(t.data.channel==="workspace"){if(!t.data.presence&&String(n)==='{"type":"ping"}')t.send('{"type":"pong"}');else if(p().environment==="cloud"&&t.data.workspacePath){if(!t.data.presence)Mo.open(t,t.data.workspacePath,{workspaceId:t.data.workspaceId,verifiedProfile:t.data.verifiedProfile});t.data.presence=!0,Mo.message(t,n)}return}if(t.data.channel==="events"){try{let i=JSON.parse(String(n));if(i?.type==="scratchpad:op-result"&&typeof i.opId==="string")tA(i.opId,i.result,i.error);else Ta.receive(t,i)}catch{}return}try{let i=JSON.parse(String(n));if(!X$(i))return;if(i.type==="chat"&&(i.content?.trim()||i.attachments?.length)){let o=await q(i.workspaceId);if(!o)return;va(o,{workspaceId:i.workspaceId,workspacePath:o.path,sessionId:i.sessionId,isNew:i.isNew,content:i.content.trim(),attachments:i.attachments,optimisticId:i.optimisticId,model:i.model,effort:i.effort,speedMode:i.speedMode,stream:i.stream,context:i.context,agentId:o.agentId}).catch((a)=>{if(a instanceof Error)l(o.id,{kind:"error",sessionId:i.sessionId,content:a.message})})}if(i.type==="stop"){let o=await q(i.workspaceId);y(o??void 0).interrupt(i.workspaceId,i.sessionId).catch(()=>{})}}catch{}},close(t){if(t.data.channel==="workspace")Mo.close(t),t.unsubscribe(Kt(t.data.workspaceId));else if(t.data.channel==="chat")cs(t),t.unsubscribe(Nr);else Ta.remove(t),t.unsubscribe(Vt)}}});ds(hA);var eD=30000;setInterval(()=>{if(Dr()>0)us(fA())},eD);bi();Ai();var dA=!1;async function mA(){if(dA)return;dA=!0;try{hA.stop(!0),Q$?.stop(!0),om()}catch{}try{oA.stop(!0)}catch{}B.shutdown();for(let t of ie())t.shutdown?.();AE(),Mi(),await Mo.shutdown(),process.exit()}process.on("SIGTERM",mA);process.on("SIGINT",mA);
|