moi-computer 0.14.1 → 0.15.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chunk-2wx528xt.css +1 -0
- package/dist/chunk-48ffsm6s.js +1 -0
- package/dist/chunk-4jdt0bvd.css +1 -0
- package/dist/chunk-7kemzpb4.js +2 -0
- package/dist/{chunk-t22yw8s6.js → chunk-dt1f1hcw.js} +1 -1
- package/dist/chunk-k65jhev6.js +1 -0
- package/dist/chunk-krtr8ryc.js +581 -0
- package/dist/chunk-nwxqpp90.js +73 -0
- package/dist/chunk-p91drrjm.js +5 -0
- package/dist/chunk-ph69j3sr.js +1 -0
- package/dist/chunk-smak7mhd.css +1 -0
- package/dist/chunk-y2jh8973.js +2 -0
- package/dist/index.html +1 -1
- package/package.json +11 -7
- package/runtime/build-worker-entry.js +1 -1
- package/runtime/{chunk-jrkbyrmq.js → chunk-2mq864th.js} +2 -2
- package/runtime/{chunk-vtxbnqhj.js → chunk-3v7yq6th.js} +22 -22
- package/runtime/chunk-3ww4pa9m.js +2 -0
- package/runtime/{chunk-bf4je23j.js → chunk-5ann5pey.js} +2 -2
- package/runtime/{chunk-yr67rvnq.js → chunk-6hbv65q7.js} +4 -4
- package/runtime/{chunk-q7xvhh2t.js → chunk-6rk42dwa.js} +1 -1
- package/runtime/chunk-7zg31m0t.js +127 -0
- package/runtime/{chunk-f5vvtga3.js → chunk-891n5kgv.js} +62 -62
- package/runtime/chunk-9cr1atrp.js +2 -0
- package/runtime/chunk-bqm6dyp5.js +66 -0
- package/runtime/chunk-dq078yga.js +2 -0
- package/runtime/{chunk-3xv43vzy.js → chunk-evjb4414.js} +2 -2
- package/runtime/chunk-m32axt0d.js +3 -0
- package/runtime/{chunk-q06m17nb.js → chunk-npda2wb6.js} +2 -2
- package/runtime/chunk-pnk61cxm.js +83 -0
- package/runtime/chunk-r4cxwzmn.js +3 -0
- package/runtime/chunk-sw8trtr0.js +78 -0
- package/runtime/{chunk-qghmmzct.js → chunk-t7h0jn86.js} +20 -20
- package/runtime/{chunk-jcjcz9ae.js → chunk-ty057q5p.js} +2 -2
- package/runtime/chunk-vtp6hgm0.js +3 -0
- package/runtime/chunk-x3g9dgrr.js +3 -0
- package/runtime/{chunk-p24qxcr3.js → chunk-zfqhb9jr.js} +5 -5
- package/runtime/cli.js +146 -146
- package/runtime/functions-worker.js +1 -1
- package/runtime/gateway-client.js +1 -1
- package/runtime/third-party-notices.txt +6 -6
- package/runtime/worker.js +1 -1
- package/dist/chunk-60q353jq.css +0 -1
- package/dist/chunk-828s864r.js +0 -546
- package/dist/chunk-9ffaaaw3.css +0 -1
- package/dist/chunk-cq2r11fg.css +0 -1
- package/dist/chunk-gh11h6dc.js +0 -2
- package/dist/chunk-hhgsmxsq.js +0 -1
- package/dist/chunk-ht9zmff2.js +0 -5
- package/dist/chunk-jqa4c92z.js +0 -2
- package/dist/chunk-kkhswjz8.js +0 -2
- package/dist/chunk-nqh3kx2x.js +0 -1
- package/dist/chunk-rb2vsqvb.js +0 -1
- package/dist/chunk-yv6n9e3z.js +0 -72
- package/runtime/chunk-1drt3wyp.js +0 -127
- package/runtime/chunk-1ttazyr4.js +0 -83
- package/runtime/chunk-8ktr8n5m.js +0 -2
- package/runtime/chunk-m4zx92xc.js +0 -3
- package/runtime/chunk-n5c20498.js +0 -66
- package/runtime/chunk-pdzpsbmy.js +0 -3
- package/runtime/chunk-sxs483zn.js +0 -2
- package/runtime/chunk-tbwma23z.js +0 -2
- package/runtime/chunk-wbzwwpct.js +0 -3
- package/runtime/chunk-wgjqjgj9.js +0 -78
- package/runtime/chunk-yd4jjshe.js +0 -3
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{D,z,fe,ns,ne,mt,Ue,B,ie,ze,wn,Q,Ar,Pr,Ir,ss,as,os,ls,A,Ut,Ke,cs,us,Nn,Ge,On,d,f,me,yt,zt,gt,Vt,kn,Cr,Rn,Ln,Dr,Mn,Fn,Bn,jn,Wn,X,fs,Or,kr,ms,Gt,$t,hs,Rr,et,Un,ys,zn,gs,_s,bs,vs,Lr,l,Ss,Ts,Fe,qt,Mr,Ht,Es,Vn,m,se,Ae,S,xs,As,Fr,Ps,_t,Kn,Pe,Br,jr,he,q,Gn,M,P,Y,Wr,Jt,$n,qn,Hn,Ur,zr,Jn,Is,ws,Vr,Cs,Kr,Gr,$r,qr,bt,vt,Hr,Xt,Jr,Ds,Ie,Xr,ee,Xn,Yt,Yn,Zn,tt,Zt,Ls,te,Yr,Ms,Fs,ti,qe,Bs,ri,Zr,V,Tt,Qt,er,rt,js,Qr,ni,Ws,Us,tr,zs,j,be,we,y,ae,rr,tn,K,W,ai,k,oi,Be,li,ci,ui,pi,di,fi,nt}from"./chunk-7zg31m0t.js";import{x,u,Ce,Hs,C,ve,U,v,ge}from"./chunk-5ann5pey.js";import"./chunk-3v7yq6th.js";import{zi,Vi,Ki,yr,de,J,kt,Rt}from"./chunk-r4cxwzmn.js";import{ot,Ai,lt,Pi,At,cr,Pt,hn,ct,ur,Ii,It,wt,ki,Li,Mi,Fi,Bi,ji,Wi,Dt,ue,Te,Ee,pe,Ze}from"./chunk-sw8trtr0.js";import{le,lr,dn}from"./chunk-m32axt0d.js";import{Gi,$i,qi}from"./chunk-t7h0jn86.js";import{Lt}from"./chunk-2mq864th.js";import{Yi,es,xr,ts}from"./chunk-npda2wb6.js";import{Js,r,sn,R,p,s,$s,b,F,ln}from"./chunk-bqm6dyp5.js";import{g,e}from"./chunk-7c0zbz74.js";var Cg=e(function(dl,na){var Dx=200,rf="__lodash_hash_undefined__",Sl=1,ag=2,cg=9007199254740991,fl="[object Arguments]",Jd="[object Array]",$x="[object AsyncFunction]",lg="[object Boolean]",ug="[object Date]",dg="[object Error]",fg="[object Function]",Lx="[object GeneratorFunction]",pl="[object Map]",pg="[object Number]",jx="[object Null]",ra="[object Object]",Ym="[object Promise]",Ux="[object Proxy]",hg="[object RegExp]",hl="[object Set]",mg="[object String]",Fx="[object Symbol]",qx="[object Undefined]",Yd="[object WeakMap]",gg="[object ArrayBuffer]",ml="[object DataView]",Bx="[object Float32Array]",Wx="[object Float64Array]",Hx="[object Int8Array]",Vx="[object Int16Array]",zx="[object Int32Array]",Gx="[object Uint8Array]",Kx="[object Uint8ClampedArray]",Jx="[object Uint16Array]",Yx="[object Uint32Array]",Xx=/[\\^$.*+?()[\]{}|]/g,Zx=/^\[object .+?Constructor\]$/,Qx=/^(?:0|[1-9]\d*)$/,ut={};ut[Bx]=ut[Wx]=ut[Hx]=ut[Vx]=ut[zx]=ut[Gx]=ut[Kx]=ut[Jx]=ut[Yx]=!0;ut[fl]=ut[Jd]=ut[gg]=ut[lg]=ut[ml]=ut[ug]=ut[dg]=ut[fg]=ut[pl]=ut[pg]=ut[ra]=ut[hg]=ut[hl]=ut[mg]=ut[Yd]=!1;var yg=typeof global=="object"&&global&&global.Object===Object&&global,e_=typeof self=="object"&&self&&self.Object===Object&&self,is=yg||e_||Function("return this")(),wg=typeof dl=="object"&&dl&&!dl.nodeType&&dl,Xm=wg&&typeof na=="object"&&na&&!na.nodeType&&na,Sg=Xm&&Xm.exports===wg,zd=Sg&&yg.process,Zm=function(){try{return zd&&zd.binding&&zd.binding("util")}catch(t){}}(),Qm=Zm&&Zm.isTypedArray;function t_(t,n){var i=-1,o=t==null?0:t.length,a=0,c=[];while(++i<o){var h=t[i];if(n(h,i,t))c[a++]=h}return c}function r_(t,n){var i=-1,o=n.length,a=t.length;while(++i<o)t[a+i]=n[i];return t}function n_(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 i_(t,n){var i=-1,o=Array(t);while(++i<t)o[i]=n(i);return o}function s_(t){return function(n){return t(n)}}function o_(t,n){return t.has(n)}function a_(t,n){return t==null?void 0:t[n]}function c_(t){var n=-1,i=Array(t.size);return t.forEach(function(o,a){i[++n]=[a,o]}),i}function l_(t,n){return function(i){return t(n(i))}}function u_(t){var n=-1,i=Array(t.size);return t.forEach(function(o){i[++n]=o}),i}var d_=Array.prototype,f_=Function.prototype,bl=Object.prototype,Gd=is["__core-js_shared__"],bg=f_.toString,_i=bl.hasOwnProperty,eg=function(){var t=/[^.]+$/.exec(Gd&&Gd.keys&&Gd.keys.IE_PROTO||"");return t?"Symbol(src)_1."+t:""}(),vg=bl.toString,p_=RegExp("^"+bg.call(_i).replace(Xx,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),tg=Sg?is.Buffer:void 0,{Symbol:gl,Uint8Array:rg}=is,Eg=bl.propertyIsEnumerable,h_=d_.splice,Po=gl?gl.toStringTag:void 0,ng=Object.getOwnPropertySymbols,m_=tg?tg.isBuffer:void 0,g_=l_(Object.keys,Object),Xd=ia(is,"DataView"),Ka=ia(is,"Map"),Zd=ia(is,"Promise"),Qd=ia(is,"Set"),ef=ia(is,"WeakMap"),Ja=ia(Object,"create"),y_=ko(Xd),w_=ko(Ka),S_=ko(Zd),b_=ko(Qd),v_=ko(ef),ig=gl?gl.prototype:void 0,Kd=ig?ig.valueOf:void 0;function Co(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 E_(){this.__data__=Ja?Ja(null):{},this.size=0}function A_(t){var n=this.has(t)&&delete this.__data__[t];return this.size-=n?1:0,n}function x_(t){var n=this.__data__;if(Ja){var i=n[t];return i===rf?void 0:i}return _i.call(n,t)?n[t]:void 0}function __(t){var n=this.__data__;return Ja?n[t]!==void 0:_i.call(n,t)}function I_(t,n){var i=this.__data__;return this.size+=this.has(t)?0:1,i[t]=Ja&&n===void 0?rf:n,this}Co.prototype.clear=E_;Co.prototype.delete=A_;Co.prototype.get=x_;Co.prototype.has=__;Co.prototype.set=I_;function ds(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 T_(){this.__data__=[],this.size=0}function R_(t){var n=this.__data__,i=vl(n,t);if(i<0)return!1;var o=n.length-1;if(i==o)n.pop();else h_.call(n,i,1);return--this.size,!0}function P_(t){var n=this.__data__,i=vl(n,t);return i<0?void 0:n[i][1]}function C_(t){return vl(this.__data__,t)>-1}function O_(t,n){var i=this.__data__,o=vl(i,t);if(o<0)++this.size,i.push([t,n]);else i[o][1]=n;return this}ds.prototype.clear=T_;ds.prototype.delete=R_;ds.prototype.get=P_;ds.prototype.has=C_;ds.prototype.set=O_;function Oo(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 k_(){this.size=0,this.__data__={hash:new Co,map:new(Ka||ds),string:new Co}}function M_(t){var n=El(this,t).delete(t);return this.size-=n?1:0,n}function N_(t){return El(this,t).get(t)}function D_(t){return El(this,t).has(t)}function $_(t,n){var i=El(this,t),o=i.size;return i.set(t,n),this.size+=i.size==o?0:1,this}Oo.prototype.clear=k_;Oo.prototype.delete=M_;Oo.prototype.get=N_;Oo.prototype.has=D_;Oo.prototype.set=$_;function yl(t){var n=-1,i=t==null?0:t.length;this.__data__=new Oo;while(++n<i)this.add(t[n])}function L_(t){return this.__data__.set(t,rf),this}function j_(t){return this.__data__.has(t)}yl.prototype.add=yl.prototype.push=L_;yl.prototype.has=j_;function oo(t){var n=this.__data__=new ds(t);this.size=n.size}function U_(){this.__data__=new ds,this.size=0}function F_(t){var n=this.__data__,i=n.delete(t);return this.size=n.size,i}function q_(t){return this.__data__.get(t)}function B_(t){return this.__data__.has(t)}function W_(t,n){var i=this.__data__;if(i instanceof ds){var o=i.__data__;if(!Ka||o.length<Dx-1)return o.push([t,n]),this.size=++i.size,this;i=this.__data__=new Oo(o)}return i.set(t,n),this.size=i.size,this}oo.prototype.clear=U_;oo.prototype.delete=F_;oo.prototype.get=q_;oo.prototype.has=B_;oo.prototype.set=W_;function H_(t,n){var i=wl(t),o=!i&&sI(t),a=!i&&!o&&tf(t),c=!i&&!o&&!a&&Pg(t),h=i||o||a||c,w=h?i_(t.length,String):[],E=w.length;for(var _ in t)if((n||_i.call(t,_))&&!(h&&(_=="length"||a&&(_=="offset"||_=="parent")||c&&(_=="buffer"||_=="byteLength"||_=="byteOffset")||eI(_,E))))w.push(_);return w}function vl(t,n){var i=t.length;while(i--)if(_g(t[i][0],n))return i;return-1}function V_(t,n,i){var o=n(t);return wl(t)?o:r_(o,i(t))}function Xa(t){if(t==null)return t===void 0?qx:jx;return Po&&Po in Object(t)?Z_(t):iI(t)}function sg(t){return Ya(t)&&Xa(t)==fl}function Ag(t,n,i,o,a){if(t===n)return!0;if(t==null||n==null||!Ya(t)&&!Ya(n))return t!==t&&n!==n;return z_(t,n,i,o,Ag,a)}function z_(t,n,i,o,a,c){var h=wl(t),w=wl(n),E=h?Jd:so(t),_=w?Jd:so(n);E=E==fl?ra:E,_=_==fl?ra:_;var I=E==ra,T=_==ra,O=E==_;if(O&&tf(t)){if(!tf(n))return!1;h=!0,I=!1}if(O&&!I)return c||(c=new oo),h||Pg(t)?xg(t,n,i,o,a,c):Y_(t,n,E,i,o,a,c);if(!(i&Sl)){var N=I&&_i.call(t,"__wrapped__"),L=T&&_i.call(n,"__wrapped__");if(N||L){var H=N?t.value():t,Z=L?n.value():n;return c||(c=new oo),a(H,Z,i,o,c)}}if(!O)return!1;return c||(c=new oo),X_(t,n,i,o,a,c)}function G_(t){if(!Rg(t)||rI(t))return!1;var n=Ig(t)?p_:Zx;return n.test(ko(t))}function K_(t){return Ya(t)&&Tg(t.length)&&!!ut[Xa(t)]}function J_(t){if(!nI(t))return g_(t);var n=[];for(var i in Object(t))if(_i.call(t,i)&&i!="constructor")n.push(i);return n}function xg(t,n,i,o,a,c){var h=i&Sl,w=t.length,E=n.length;if(w!=E&&!(h&&E>w))return!1;var _=c.get(t);if(_&&c.get(n))return _==n;var I=-1,T=!0,O=i&ag?new yl:void 0;c.set(t,n),c.set(n,t);while(++I<w){var N=t[I],L=n[I];if(o)var H=h?o(L,N,I,n,t,c):o(N,L,I,t,n,c);if(H!==void 0){if(H)continue;T=!1;break}if(O){if(!n_(n,function(Z,G){if(!o_(O,G)&&(N===Z||a(N,Z,i,o,c)))return O.push(G)})){T=!1;break}}else if(!(N===L||a(N,L,i,o,c))){T=!1;break}}return c.delete(t),c.delete(n),T}function Y_(t,n,i,o,a,c,h){switch(i){case ml:if(t.byteLength!=n.byteLength||t.byteOffset!=n.byteOffset)return!1;t=t.buffer,n=n.buffer;case gg:if(t.byteLength!=n.byteLength||!c(new rg(t),new rg(n)))return!1;return!0;case lg:case ug:case pg:return _g(+t,+n);case dg:return t.name==n.name&&t.message==n.message;case hg:case mg:return t==n+"";case pl:var w=c_;case hl:var E=o&Sl;if(w||(w=u_),t.size!=n.size&&!E)return!1;var _=h.get(t);if(_)return _==n;o|=ag,h.set(t,n);var I=xg(w(t),w(n),o,a,c,h);return h.delete(t),I;case Fx:if(Kd)return Kd.call(t)==Kd.call(n)}return!1}function X_(t,n,i,o,a,c){var h=i&Sl,w=og(t),E=w.length,_=og(n),I=_.length;if(E!=I&&!h)return!1;var T=E;while(T--){var O=w[T];if(!(h?O in n:_i.call(n,O)))return!1}var N=c.get(t);if(N&&c.get(n))return N==n;var L=!0;c.set(t,n),c.set(n,t);var H=h;while(++T<E){O=w[T];var Z=t[O],G=n[O];if(o)var oe=h?o(G,Z,O,n,t,c):o(Z,G,O,t,n,c);if(!(oe===void 0?Z===G||a(Z,G,i,o,c):oe)){L=!1;break}H||(H=O=="constructor")}if(L&&!H){var re=t.constructor,xe=n.constructor;if(re!=xe&&(("constructor"in t)&&("constructor"in n))&&!(typeof re=="function"&&re instanceof re&&typeof xe=="function"&&xe instanceof xe))L=!1}return c.delete(t),c.delete(n),L}function og(t){return V_(t,cI,Q_)}function El(t,n){var i=t.__data__;return tI(n)?i[typeof n=="string"?"string":"hash"]:i.map}function ia(t,n){var i=a_(t,n);return G_(i)?i:void 0}function Z_(t){var n=_i.call(t,Po),i=t[Po];try{t[Po]=void 0;var o=!0}catch(c){}var a=vg.call(t);if(o)if(n)t[Po]=i;else delete t[Po];return a}var Q_=!ng?lI:function(t){if(t==null)return[];return t=Object(t),t_(ng(t),function(n){return Eg.call(t,n)})},so=Xa;if(Xd&&so(new Xd(new ArrayBuffer(1)))!=ml||Ka&&so(new Ka)!=pl||Zd&&so(Zd.resolve())!=Ym||Qd&&so(new Qd)!=hl||ef&&so(new ef)!=Yd)so=function(t){var n=Xa(t),i=n==ra?t.constructor:void 0,o=i?ko(i):"";if(o)switch(o){case y_:return ml;case w_:return pl;case S_:return Ym;case b_:return hl;case v_:return Yd}return n};function eI(t,n){return n=n==null?cg:n,!!n&&(typeof t=="number"||Qx.test(t))&&(t>-1&&t%1==0&&t<n)}function tI(t){var n=typeof t;return n=="string"||n=="number"||n=="symbol"||n=="boolean"?t!=="__proto__":t===null}function rI(t){return!!eg&&eg in t}function nI(t){var n=t&&t.constructor,i=typeof n=="function"&&n.prototype||bl;return t===i}function iI(t){return vg.call(t)}function ko(t){if(t!=null){try{return bg.call(t)}catch(n){}try{return t+""}catch(n){}}return""}function _g(t,n){return t===n||t!==t&&n!==n}var sI=sg(function(){return arguments}())?sg:function(t){return Ya(t)&&_i.call(t,"callee")&&!Eg.call(t,"callee")},wl=Array.isArray;function oI(t){return t!=null&&Tg(t.length)&&!Ig(t)}var tf=m_||uI;function aI(t,n){return Ag(t,n)}function Ig(t){if(!Rg(t))return!1;var n=Xa(t);return n==fg||n==Lx||n==$x||n==Ux}function Tg(t){return typeof t=="number"&&t>-1&&t%1==0&&t<=cg}function Rg(t){var n=typeof t;return t!=null&&(n=="object"||n=="function")}function Ya(t){return t!=null&&typeof t=="object"}var Pg=Qm?s_(Qm):K_;function cI(t){return oI(t)?H_(t):J_(t)}function lI(){return[]}function uI(){return!1}na.exports=aI});var yf=e(function(Al,oa){var dI=200,hf="__lodash_hash_undefined__",qg=1,Pl=2,Bg=9007199254740991,xl="[object Arguments]",of="[object Array]",Wg="[object Boolean]",Hg="[object Date]",Vg="[object Error]",zg="[object Function]",fI="[object GeneratorFunction]",_l="[object Map]",Gg="[object Number]",sa="[object Object]",Og="[object Promise]",Kg="[object RegExp]",Il="[object Set]",Jg="[object String]",pI="[object Symbol]",af="[object WeakMap]",Yg="[object ArrayBuffer]",Tl="[object DataView]",hI="[object Float32Array]",mI="[object Float64Array]",gI="[object Int8Array]",yI="[object Int16Array]",wI="[object Int32Array]",SI="[object Uint8Array]",bI="[object Uint8ClampedArray]",vI="[object Uint16Array]",EI="[object Uint32Array]",AI=/[\\^$.*+?()[\]{}|]/g,xI=/^\[object .+?Constructor\]$/,_I=/^(?:0|[1-9]\d*)$/,dt={};dt[hI]=dt[mI]=dt[gI]=dt[yI]=dt[wI]=dt[SI]=dt[bI]=dt[vI]=dt[EI]=!0;dt[xl]=dt[of]=dt[Yg]=dt[Wg]=dt[Tl]=dt[Hg]=dt[Vg]=dt[zg]=dt[_l]=dt[Gg]=dt[sa]=dt[Kg]=dt[Il]=dt[Jg]=dt[af]=!1;var Xg=typeof global=="object"&&global&&global.Object===Object&&global,II=typeof self=="object"&&self&&self.Object===Object&&self,lo=Xg||II||Function("return this")(),Zg=typeof Al=="object"&&Al&&!Al.nodeType&&Al,kg=Zg&&typeof oa=="object"&&oa&&!oa.nodeType&&oa,TI=kg&&kg.exports===Zg,Mg=TI&&Xg.process,Ng=function(){try{return Mg&&Mg.binding("util")}catch(t){}}(),Dg=Ng&&Ng.isTypedArray;function RI(t,n){var i=-1,o=t?t.length:0;while(++i<o)if(n(t[i],i,t))return!0;return!1}function PI(t,n){var i=-1,o=Array(t);while(++i<t)o[i]=n(i);return o}function CI(t){return function(n){return t(n)}}function OI(t,n){return t==null?void 0:t[n]}function cf(t){var n=!1;if(t!=null&&typeof t.toString!="function")try{n=!!(t+"")}catch(i){}return n}function kI(t){var n=-1,i=Array(t.size);return t.forEach(function(o,a){i[++n]=[a,o]}),i}function MI(t,n){return function(i){return t(n(i))}}function NI(t){var n=-1,i=Array(t.size);return t.forEach(function(o){i[++n]=o}),i}var DI=Array.prototype,$I=Function.prototype,Cl=Object.prototype,nf=lo["__core-js_shared__"],$g=function(){var t=/[^.]+$/.exec(nf&&nf.keys&&nf.keys.IE_PROTO||"");return t?"Symbol(src)_1."+t:""}(),Qg=$I.toString,{hasOwnProperty:ps,toString:ec}=Cl,LI=RegExp("^"+Qg.call(ps).replace(AI,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),{Symbol:Lg,Uint8Array:jg}=lo,jI=Cl.propertyIsEnumerable,UI=DI.splice,FI=MI(Object.keys,Object),lf=aa(lo,"DataView"),Za=aa(lo,"Map"),uf=aa(lo,"Promise"),df=aa(lo,"Set"),ff=aa(lo,"WeakMap"),Qa=aa(Object,"create"),qI=Do(lf),BI=Do(Za),WI=Do(uf),HI=Do(df),VI=Do(ff),Ug=Lg?Lg.prototype:void 0,sf=Ug?Ug.valueOf:void 0;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 zI(){this.__data__=Qa?Qa(null):{}}function GI(t){return this.has(t)&&delete this.__data__[t]}function KI(t){var n=this.__data__;if(Qa){var i=n[t];return i===hf?void 0:i}return ps.call(n,t)?n[t]:void 0}function JI(t){var n=this.__data__;return Qa?n[t]!==void 0:ps.call(n,t)}function YI(t,n){var i=this.__data__;return i[t]=Qa&&n===void 0?hf:n,this}Mo.prototype.clear=zI;Mo.prototype.delete=GI;Mo.prototype.get=KI;Mo.prototype.has=JI;Mo.prototype.set=YI;function Rs(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 XI(){this.__data__=[]}function ZI(t){var n=this.__data__,i=Ol(n,t);if(i<0)return!1;var o=n.length-1;if(i==o)n.pop();else UI.call(n,i,1);return!0}function QI(t){var n=this.__data__,i=Ol(n,t);return i<0?void 0:n[i][1]}function eT(t){return Ol(this.__data__,t)>-1}function tT(t,n){var i=this.__data__,o=Ol(i,t);if(o<0)i.push([t,n]);else i[o][1]=n;return this}Rs.prototype.clear=XI;Rs.prototype.delete=ZI;Rs.prototype.get=QI;Rs.prototype.has=eT;Rs.prototype.set=tT;function No(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__={hash:new Mo,map:new(Za||Rs),string:new Mo}}function nT(t){return kl(this,t).delete(t)}function iT(t){return kl(this,t).get(t)}function sT(t){return kl(this,t).has(t)}function oT(t,n){return kl(this,t).set(t,n),this}No.prototype.clear=rT;No.prototype.delete=nT;No.prototype.get=iT;No.prototype.has=sT;No.prototype.set=oT;function Rl(t){var n=-1,i=t?t.length:0;this.__data__=new No;while(++n<i)this.add(t[n])}function aT(t){return this.__data__.set(t,hf),this}function cT(t){return this.__data__.has(t)}Rl.prototype.add=Rl.prototype.push=aT;Rl.prototype.has=cT;function co(t){this.__data__=new Rs(t)}function lT(){this.__data__=new Rs}function uT(t){return this.__data__.delete(t)}function dT(t){return this.__data__.get(t)}function fT(t){return this.__data__.has(t)}function pT(t,n){var i=this.__data__;if(i instanceof Rs){var o=i.__data__;if(!Za||o.length<dI-1)return o.push([t,n]),this;i=this.__data__=new No(o)}return i.set(t,n),this}co.prototype.clear=lT;co.prototype.delete=uT;co.prototype.get=dT;co.prototype.has=fT;co.prototype.set=pT;function hT(t,n){var i=pf(t)||IT(t)?PI(t.length,String):[],o=i.length,a=!!o;for(var c in t)if((n||ps.call(t,c))&&!(a&&(c=="length"||ET(c,o))))i.push(c);return i}function Ol(t,n){var i=t.length;while(i--)if(ry(t[i][0],n))return i;return-1}function mT(t){return ec.call(t)}function ey(t,n,i,o,a){if(t===n)return!0;if(t==null||n==null||!mf(t)&&!gf(n))return t!==t&&n!==n;return gT(t,n,ey,i,o,a)}function gT(t,n,i,o,a,c){var h=pf(t),w=pf(n),E=of,_=of;if(!h)E=ao(t),E=E==xl?sa:E;if(!w)_=ao(n),_=_==xl?sa:_;var I=E==sa&&!cf(t),T=_==sa&&!cf(n),O=E==_;if(O&&!I)return c||(c=new co),h||PT(t)?ty(t,n,i,o,a,c):bT(t,n,E,i,o,a,c);if(!(a&Pl)){var N=I&&ps.call(t,"__wrapped__"),L=T&&ps.call(n,"__wrapped__");if(N||L){var H=N?t.value():t,Z=L?n.value():n;return c||(c=new co),i(H,Z,o,a,c)}}if(!O)return!1;return c||(c=new co),vT(t,n,i,o,a,c)}function yT(t){if(!mf(t)||xT(t))return!1;var n=iy(t)||cf(t)?LI:xI;return n.test(Do(t))}function wT(t){return gf(t)&&sy(t.length)&&!!dt[ec.call(t)]}function ST(t){if(!_T(t))return FI(t);var n=[];for(var i in Object(t))if(ps.call(t,i)&&i!="constructor")n.push(i);return n}function ty(t,n,i,o,a,c){var h=a&Pl,w=t.length,E=n.length;if(w!=E&&!(h&&E>w))return!1;var _=c.get(t);if(_&&c.get(n))return _==n;var I=-1,T=!0,O=a&qg?new Rl:void 0;c.set(t,n),c.set(n,t);while(++I<w){var N=t[I],L=n[I];if(o)var H=h?o(L,N,I,n,t,c):o(N,L,I,t,n,c);if(H!==void 0){if(H)continue;T=!1;break}if(O){if(!RI(n,function(Z,G){if(!O.has(G)&&(N===Z||i(N,Z,o,a,c)))return O.add(G)})){T=!1;break}}else if(!(N===L||i(N,L,o,a,c))){T=!1;break}}return c.delete(t),c.delete(n),T}function bT(t,n,i,o,a,c,h){switch(i){case Tl:if(t.byteLength!=n.byteLength||t.byteOffset!=n.byteOffset)return!1;t=t.buffer,n=n.buffer;case Yg:if(t.byteLength!=n.byteLength||!o(new jg(t),new jg(n)))return!1;return!0;case Wg:case Hg:case Gg:return ry(+t,+n);case Vg:return t.name==n.name&&t.message==n.message;case Kg:case Jg:return t==n+"";case _l:var w=kI;case Il:var E=c&Pl;if(w||(w=NI),t.size!=n.size&&!E)return!1;var _=h.get(t);if(_)return _==n;c|=qg,h.set(t,n);var I=ty(w(t),w(n),o,a,c,h);return h.delete(t),I;case pI:if(sf)return sf.call(t)==sf.call(n)}return!1}function vT(t,n,i,o,a,c){var h=a&Pl,w=Fg(t),E=w.length,_=Fg(n),I=_.length;if(E!=I&&!h)return!1;var T=E;while(T--){var O=w[T];if(!(h?O in n:ps.call(n,O)))return!1}var N=c.get(t);if(N&&c.get(n))return N==n;var L=!0;c.set(t,n),c.set(n,t);var H=h;while(++T<E){O=w[T];var Z=t[O],G=n[O];if(o)var oe=h?o(G,Z,O,n,t,c):o(Z,G,O,t,n,c);if(!(oe===void 0?Z===G||i(Z,G,o,a,c):oe)){L=!1;break}H||(H=O=="constructor")}if(L&&!H){var re=t.constructor,xe=n.constructor;if(re!=xe&&(("constructor"in t)&&("constructor"in n))&&!(typeof re=="function"&&re instanceof re&&typeof xe=="function"&&xe instanceof xe))L=!1}return c.delete(t),c.delete(n),L}function kl(t,n){var i=t.__data__;return AT(n)?i[typeof n=="string"?"string":"hash"]:i.map}function aa(t,n){var i=OI(t,n);return yT(i)?i:void 0}var ao=mT;if(lf&&ao(new lf(new ArrayBuffer(1)))!=Tl||Za&&ao(new Za)!=_l||uf&&ao(uf.resolve())!=Og||df&&ao(new df)!=Il||ff&&ao(new ff)!=af)ao=function(t){var n=ec.call(t),i=n==sa?t.constructor:void 0,o=i?Do(i):void 0;if(o)switch(o){case qI:return Tl;case BI:return _l;case WI:return Og;case HI:return Il;case VI:return af}return n};function ET(t,n){return n=n==null?Bg:n,!!n&&(typeof t=="number"||_I.test(t))&&(t>-1&&t%1==0&&t<n)}function AT(t){var n=typeof t;return n=="string"||n=="number"||n=="symbol"||n=="boolean"?t!=="__proto__":t===null}function xT(t){return!!$g&&$g in t}function _T(t){var n=t&&t.constructor,i=typeof n=="function"&&n.prototype||Cl;return t===i}function Do(t){if(t!=null){try{return Qg.call(t)}catch(n){}try{return t+""}catch(n){}}return""}function ry(t,n){return t===n||t!==t&&n!==n}function IT(t){return TT(t)&&ps.call(t,"callee")&&(!jI.call(t,"callee")||ec.call(t)==xl)}var pf=Array.isArray;function ny(t){return t!=null&&sy(t.length)&&!iy(t)}function TT(t){return gf(t)&&ny(t)}function RT(t,n,i){i=typeof i=="function"?i:void 0;var o=i?i(t,n):void 0;return o===void 0?ey(t,n,i):!!o}function iy(t){var n=mf(t)?ec.call(t):"";return n==zg||n==fI}function sy(t){return typeof t=="number"&&t>-1&&t%1==0&&t<=Bg}function mf(t){var n=typeof t;return!!t&&(n=="object"||n=="function")}function gf(t){return!!t&&typeof t=="object"}var PT=Dg?CI(Dg):wT;function Fg(t){return ny(t)?hT(t):ST(t)}oa.exports=RT});var fy=e(function(vL,dy){var CT=200,bf="__lodash_hash_undefined__",OT=1/0,kT="[object Function]",MT="[object GeneratorFunction]",NT=/[\\^$.*+?()[\]{}|]/g,DT=/^\[object .+?Constructor\]$/,$T=typeof global=="object"&&global&&global.Object===Object&&global,LT=typeof self=="object"&&self&&self.Object===Object&&self,vf=$T||LT||Function("return this")();function jT(t,n){var i=t?t.length:0;return!!i&&qT(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 FT(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 qT(t,n,i){if(n!==n)return FT(t,BT,i);var o=i-1,a=t.length;while(++o<a)if(t[o]===n)return o;return-1}function BT(t){return t!==t}function WT(t,n){return t.has(n)}function HT(t,n){return t==null?void 0:t[n]}function VT(t){var n=!1;if(t!=null&&typeof t.toString!="function")try{n=!!(t+"")}catch(i){}return n}function ay(t){var n=-1,i=Array(t.size);return t.forEach(function(o){i[++n]=o}),i}var zT=Array.prototype,GT=Function.prototype,cy=Object.prototype,wf=vf["__core-js_shared__"],oy=function(){var t=/[^.]+$/.exec(wf&&wf.keys&&wf.keys.IE_PROTO||"");return t?"Symbol(src)_1."+t:""}(),ly=GT.toString,{hasOwnProperty:Ef,toString:KT}=cy,JT=RegExp("^"+ly.call(Ef).replace(NT,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),YT=zT.splice,XT=Af(vf,"Map"),Sf=Af(vf,"Set"),tc=Af(Object,"create");function $o(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 ZT(){this.__data__=tc?tc(null):{}}function QT(t){return this.has(t)&&delete this.__data__[t]}function eR(t){var n=this.__data__;if(tc){var i=n[t];return i===bf?void 0:i}return Ef.call(n,t)?n[t]:void 0}function tR(t){var n=this.__data__;return tc?n[t]!==void 0:Ef.call(n,t)}function rR(t,n){var i=this.__data__;return i[t]=tc&&n===void 0?bf:n,this}$o.prototype.clear=ZT;$o.prototype.delete=QT;$o.prototype.get=eR;$o.prototype.has=tR;$o.prototype.set=rR;function ca(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 nR(){this.__data__=[]}function iR(t){var n=this.__data__,i=Nl(n,t);if(i<0)return!1;var o=n.length-1;if(i==o)n.pop();else YT.call(n,i,1);return!0}function sR(t){var n=this.__data__,i=Nl(n,t);return i<0?void 0:n[i][1]}function oR(t){return Nl(this.__data__,t)>-1}function aR(t,n){var i=this.__data__,o=Nl(i,t);if(o<0)i.push([t,n]);else i[o][1]=n;return this}ca.prototype.clear=nR;ca.prototype.delete=iR;ca.prototype.get=sR;ca.prototype.has=oR;ca.prototype.set=aR;function la(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 cR(){this.__data__={hash:new $o,map:new(XT||ca),string:new $o}}function lR(t){return Dl(this,t).delete(t)}function uR(t){return Dl(this,t).get(t)}function dR(t){return Dl(this,t).has(t)}function fR(t,n){return Dl(this,t).set(t,n),this}la.prototype.clear=cR;la.prototype.delete=lR;la.prototype.get=uR;la.prototype.has=dR;la.prototype.set=fR;function Ml(t){var n=-1,i=t?t.length:0;this.__data__=new la;while(++n<i)this.add(t[n])}function pR(t){return this.__data__.set(t,bf),this}function hR(t){return this.__data__.has(t)}Ml.prototype.add=Ml.prototype.push=pR;Ml.prototype.has=hR;function Nl(t,n){var i=t.length;while(i--)if(ER(t[i][0],n))return i;return-1}function mR(t){if(!uy(t)||SR(t))return!1;var n=AR(t)||VT(t)?JT:DT;return n.test(bR(t))}function gR(t,n,i){var o=-1,a=jT,c=t.length,h=!0,w=[],E=w;if(i)h=!1,a=UT;else if(c>=CT){var _=n?null:yR(t);if(_)return ay(_);h=!1,a=WT,E=new Ml}else E=n?[]:w;e:while(++o<c){var I=t[o],T=n?n(I):I;if(I=i||I!==0?I:0,h&&T===T){var O=E.length;while(O--)if(E[O]===T)continue e;if(n)E.push(T);w.push(I)}else if(!a(E,T,i)){if(E!==w)E.push(T);w.push(I)}}return w}var yR=!(Sf&&1/ay(new Sf([,-0]))[1]==OT)?xR:function(t){return new Sf(t)};function Dl(t,n){var i=t.__data__;return wR(n)?i[typeof n=="string"?"string":"hash"]:i.map}function Af(t,n){var i=HT(t,n);return mR(i)?i:void 0}function wR(t){var n=typeof t;return n=="string"||n=="number"||n=="symbol"||n=="boolean"?t!=="__proto__":t===null}function SR(t){return!!oy&&oy in t}function bR(t){if(t!=null){try{return ly.call(t)}catch(n){}try{return t+""}catch(n){}}return""}function vR(t){return t&&t.length?gR(t):[]}function ER(t,n){return t===n||t!==t&&n!==n}function AR(t){var n=uy(t)?KT.call(t):"";return n==kT||n==MT}function uy(t){var n=typeof t;return!!t&&(n=="object"||n=="function")}function xR(){}dy.exports=vR});var Py=e(function(Sj,Ry){var Ty="Expected a function",_y=NaN,WR="[object Symbol]",HR=/^\s+|\s+$/g,VR=/^[-+]0x[0-9a-f]+$/i,zR=/^0b[01]+$/i,GR=/^0o[0-7]+$/i,KR=parseInt,JR=typeof global=="object"&&global&&global.Object===Object&&global,YR=typeof self=="object"&&self&&self.Object===Object&&self,XR=JR||YR||Function("return this")(),ZR=Object.prototype,QR=ZR.toString,{max:e1,min:t1}=Math,Of=function(){return XR.Date.now()};function r1(t,n,i){var o,a,c,h,w,E,_=0,I=!1,T=!1,O=!0;if(typeof t!="function")throw TypeError(Ty);if(n=Iy(n)||0,ql(i))I=!!i.leading,T="maxWait"in i,c=T?e1(Iy(i.maxWait)||0,n):c,O="trailing"in i?!!i.trailing:O;function N(je){var We=o,jt=a;return o=a=void 0,_=je,h=t.apply(jt,We),h}function L(je){return _=je,w=setTimeout(G,n),I?N(je):h}function H(je){var We=je-E,jt=je-_,Ft=n-We;return T?t1(Ft,c-jt):Ft}function Z(je){var We=je-E,jt=je-_;return E===void 0||We>=n||We<0||T&&jt>=c}function G(){var je=Of();if(Z(je))return oe(je);w=setTimeout(G,H(je))}function oe(je){if(w=void 0,O&&o)return N(je);return o=a=void 0,h}function re(){if(w!==void 0)clearTimeout(w);_=0,o=E=a=w=void 0}function xe(){return w===void 0?h:oe(Of())}function Oe(){var je=Of(),We=Z(je);if(o=arguments,a=this,E=je,We){if(w===void 0)return L(E);if(T)return w=setTimeout(G,n),N(E)}if(w===void 0)w=setTimeout(G,n);return h}return Oe.cancel=re,Oe.flush=xe,Oe}function n1(t,n,i){var o=!0,a=!0;if(typeof t!="function")throw TypeError(Ty);if(ql(i))o="leading"in i?!!i.leading:o,a="trailing"in i?!!i.trailing:a;return r1(t,n,{leading:o,maxWait:n,trailing:a})}function ql(t){var n=typeof t;return!!t&&(n=="object"||n=="function")}function i1(t){return!!t&&typeof t=="object"}function s1(t){return typeof t=="symbol"||i1(t)&&QR.call(t)==WR}function Iy(t){if(typeof t=="number")return t;if(s1(t))return _y;if(ql(t)){var n=typeof t.valueOf=="function"?t.valueOf():t;t=ql(n)?n+"":n}if(typeof t!="string")return t===0?t:+t;t=t.replace(HR,"");var i=zR.test(t);return i||GR.test(t)?KR(t.slice(2),i?2:8):VR.test(t)?_y:+t}Ry.exports=n1});var kh=e(function(yb){Object.defineProperty(yb,"__esModule",{value:!0});yb.dynamicAnchor=void 0;var Na=d(),bC=me(),Nu=Vt(),mb=Cr(),vC={keyword:"$dynamicAnchor",schemaType:"string",code:(t)=>gb(t,t.schema)};function gb(t,n){let{gen:i,it:o}=t;o.schemaEnv.root.dynamicAnchors[n]=!0;let a=Na._`${bC.default.dynamicAnchors}${Na.getProperty(n)}`,c=o.errSchemaPath==="#"?o.validateName:EC(t);i.if(Na._`!${a}`,()=>i.assign(a,c))}yb.dynamicAnchor=gb;function EC(t){let{schemaEnv:n,schema:i,self:o}=t.it,{root:a,baseId:c,localRefs:h,meta:w}=n.root,{schemaId:E}=o.opts,_=new Nu.SchemaEnv({schema:i,schemaId:E,root:a,baseId:c,localRefs:h,meta:w});return Nu.compileSchema.call(o,_),mb.getValidate(t,_)}yb.default=vC});var Mh=e(function(bb){Object.defineProperty(bb,"__esModule",{value:!0});bb.dynamicRef=void 0;var Du=d(),xC=me(),$u=Cr(),_C={keyword:"$dynamicRef",schemaType:"string",code:(t)=>Sb(t,t.schema)};function Sb(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)h();else{let E=i.let("valid",!1);h(E),t.ok(E)}function h(E){if(a.schemaEnv.root.dynamicAnchors[c]){let _=i.let("_v",Du._`${xC.default.dynamicAnchors}${Du.getProperty(c)}`);i.if(_,w(_,E),w(a.validateName,E))}else w(a.validateName,E)()}function w(E,_){return _?()=>i.block(()=>{$u.callRef(t,E),i.let(_,!0)}):()=>$u.callRef(t,E)}}bb.dynamicRef=Sb;bb.default=_C});var _b=e(function(xb){Object.defineProperty(xb,"__esModule",{value:!0});var Eb=kh(),Ab=f(),TC={keyword:"$recursiveAnchor",schemaType:"boolean",code(t){if(t.schema)Eb.dynamicAnchor(t,"");else Ab.checkStrictMode(t.it,"$recursiveAnchor: false is ignored")}};xb.default=TC});var Rb=e(function(Tb){Object.defineProperty(Tb,"__esModule",{value:!0});var Ib=Mh(),PC={keyword:"$recursiveRef",schemaType:"string",code:(t)=>Ib.dynamicRef(t,t.schema)};Tb.default=PC});var Cb=e(function(Pb){Object.defineProperty(Pb,"__esModule",{value:!0});var OC=kh(),kC=Mh(),MC=_b(),NC=Rb(),DC=[OC.default,kC.default,MC.default,NC.default];Pb.default=DC});var kb=e(function(Ob){Object.defineProperty(Ob,"__esModule",{value:!0});var Lu=Dr(),LC={keyword:"dependentRequired",type:"object",schemaType:"object",error:Lu.error,code:(t)=>Lu.validatePropertyDeps(t)};Ob.default=LC});var Db=e(function(Nb){Object.defineProperty(Nb,"__esModule",{value:!0});var Mb=Dr(),UC={keyword:"dependentSchemas",type:"object",schemaType:"object",code:(t)=>Mb.validateSchemaDeps(t)};Nb.default=UC});var jb=e(function(Lb){Object.defineProperty(Lb,"__esModule",{value:!0});var $b=f(),qC={keyword:["maxContains","minContains"],type:"array",schemaType:"number",code({keyword:t,parentSchema:n,it:i}){if(n.contains===void 0)$b.checkStrictMode(i,`"${t}" without "contains" is ignored`)}};Lb.default=qC});var Fb=e(function(Ub){Object.defineProperty(Ub,"__esModule",{value:!0});var WC=kb(),HC=Db(),VC=jb(),zC=[WC.default,HC.default,VC.default];Ub.default=zC});var Bb=e(function(qb){Object.defineProperty(qb,"__esModule",{value:!0});var _r=d(),ju=f(),KC=me(),JC={message:"must NOT have unevaluated properties",params:({params:t})=>_r._`{unevaluatedProperty: ${t.unevaluatedProperty}}`},YC={keyword:"unevaluatedProperties",type:"object",schemaType:["boolean","object"],trackErrors:!0,error:JC,code(t){let{gen:n,schema:i,data:o,errsCount:a,it:c}=t;if(!a)throw Error("ajv implementation error");let{allErrors:h,props:w}=c;if(w instanceof _r.Name)n.if(_r._`${w} !== true`,()=>n.forIn("key",o,(T)=>n.if(_(w,T),()=>E(T))));else if(w!==!0)n.forIn("key",o,(T)=>w===void 0?E(T):n.if(I(w,T),()=>E(T)));c.props=!0,t.ok(_r._`${a} === ${KC.default.errors}`);function E(T){if(i===!1){if(t.setParams({unevaluatedProperty:T}),t.error(),!h)n.break();return}if(!ju.alwaysValidSchema(c,i)){let O=n.name("valid");if(t.subschema({keyword:"unevaluatedProperties",dataProp:T,dataPropType:ju.Type.Str},O),!h)n.if(_r.not(O),()=>n.break())}}function _(T,O){return _r._`!${T} || !${T}[${O}]`}function I(T,O){let N=[];for(let L in T)if(T[L]===!0)N.push(_r._`${O} !== ${L}`);return _r.and(...N)}}};qb.default=YC});var Hb=e(function(Wb){Object.defineProperty(Wb,"__esModule",{value:!0});var mn=d(),Uu=f(),ZC={message:({params:{len:t}})=>mn.str`must NOT have more than ${t} items`,params:({params:{len:t}})=>mn._`{limit: ${t}}`},QC={keyword:"unevaluatedItems",type:"array",schemaType:["boolean","object"],error:ZC,code(t){let{gen:n,schema:i,data:o,it:a}=t,c=a.items||0;if(c===!0)return;let h=n.const("len",mn._`${o}.length`);if(i===!1)t.setParams({len:c}),t.fail(mn._`${h} > ${c}`);else if(typeof i=="object"&&!Uu.alwaysValidSchema(a,i)){let E=n.var("valid",mn._`${h} <= ${c}`);n.if(mn.not(E),()=>w(E,c)),t.ok(E)}a.items=!0;function w(E,_){n.forRange("i",_,h,(I)=>{if(t.subschema({keyword:"unevaluatedItems",dataProp:I,dataPropType:Uu.Type.Num},E),!a.allErrors)n.if(mn.not(E),()=>n.break())})}}};Wb.default=QC});var zb=e(function(Vb){Object.defineProperty(Vb,"__esModule",{value:!0});var tO=Bb(),rO=Hb(),nO=[tO.default,rO.default];Vb.default=nO});var Kb=e(function(Gb){Object.defineProperty(Gb,"__esModule",{value:!0});var sO=Rn(),oO=Ln(),aO=Mn(),cO=Cb(),lO=Fb(),uO=zb(),dO=Fn(),Fu=Bn(),fO=[cO.default,sO.default,oO.default,(0,aO.default)(!0),dO.default,Fu.metadataVocabulary,Fu.contentVocabulary,lO.default,uO.default];Gb.default=fO});var Jb=e(function(e9,hO){hO.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 Yb=e(function(t9,mO){mO.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 Xb=e(function(r9,gO){gO.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 Zb=e(function(n9,yO){yO.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 Qb=e(function(i9,wO){wO.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 e0=e(function(s9,SO){SO.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 t0=e(function(o9,bO){bO.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 r0=e(function(a9,vO){vO.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 i0=e(function(n0){Object.defineProperty(n0,"__esModule",{value:!0});var EO=Jb(),AO=Yb(),xO=Xb(),_O=Zb(),IO=Qb(),TO=e0(),RO=t0(),PO=r0(),CO=["/properties"];function OO(t){return[EO,AO,xO,_O,IO,n(this,TO),RO,n(this,PO)].forEach((i)=>this.addMetaSchema(i,void 0,!1)),this;function n(i,o){return t?i.$dataMetaSchema(o,CO):o}}n0.default=OO});var s0=e(function(gn,Dh){Object.defineProperty(gn,"__esModule",{value:!0});gn.MissingRefError=gn.ValidationError=gn.CodeGen=gn.Name=gn.nil=gn.stringify=gn.str=gn._=gn.KeywordCxt=gn.Ajv2020=void 0;var MO=kn(),NO=Kb(),DO=jn(),$O=i0(),Nh="https://json-schema.org/draft/2020-12/schema";class $c extends MO.default{constructor(t={}){super({...t,dynamicRef:!0,next:!0,unevaluated:!0})}_addVocabularies(){if(super._addVocabularies(),NO.default.forEach((t)=>this.addVocabulary(t)),this.opts.discriminator)this.addKeyword(DO.default)}_addDefaultMetaSchema(){super._addDefaultMetaSchema();let{$data:t,meta:n}=this.opts;if(!n)return;$O.default.call(this,t),this.refs["http://json-schema.org/schema"]=Nh}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(Nh)?Nh:void 0)}}gn.Ajv2020=$c;Dh.exports=gn=$c;Dh.exports.Ajv2020=$c;Object.defineProperty(gn,"__esModule",{value:!0});gn.default=$c;var LO=yt();Object.defineProperty(gn,"KeywordCxt",{enumerable:!0,get:function(){return LO.KeywordCxt}});var Da=d();Object.defineProperty(gn,"_",{enumerable:!0,get:function(){return Da._}});Object.defineProperty(gn,"str",{enumerable:!0,get:function(){return Da.str}});Object.defineProperty(gn,"stringify",{enumerable:!0,get:function(){return Da.stringify}});Object.defineProperty(gn,"nil",{enumerable:!0,get:function(){return Da.nil}});Object.defineProperty(gn,"Name",{enumerable:!0,get:function(){return Da.Name}});Object.defineProperty(gn,"CodeGen",{enumerable:!0,get:function(){return Da.CodeGen}});var jO=zt();Object.defineProperty(gn,"ValidationError",{enumerable:!0,get:function(){return jO.default}});var UO=gt();Object.defineProperty(gn,"MissingRefError",{enumerable:!0,get:function(){return UO.default}})});var $a=e(function(b9,o0){var YO=Number.MAX_SAFE_INTEGER||9007199254740991,XO=["major","premajor","minor","preminor","patch","prepatch","prerelease"];o0.exports={MAX_LENGTH:256,MAX_SAFE_COMPONENT_LENGTH:16,MAX_SAFE_BUILD_LENGTH:250,MAX_SAFE_INTEGER:YO,RELEASE_TYPES:XO,SEMVER_SPEC_VERSION:"2.0.0",FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2}});var Lc=e(function(v9,a0){var ZO=typeof process==="object"&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...t)=>console.error("SEMVER",...t):()=>{};a0.exports=ZO});var La=e(function(Zi,c0){var{MAX_SAFE_COMPONENT_LENGTH:jh,MAX_SAFE_BUILD_LENGTH:QO,MAX_LENGTH:ek}=$a(),tk=Lc();Zi=c0.exports={};var rk=Zi.re=[],nk=Zi.safeRe=[],ce=Zi.src=[],ik=Zi.safeSrc=[],ye=Zi.t={},sk=0,Uh="[a-zA-Z0-9-]",ok=[["\\s",1],["\\d",ek],[Uh,QO]],ak=(t)=>{for(let[n,i]of ok)t=t.split(`${n}*`).join(`${n}{0,${i}}`).split(`${n}+`).join(`${n}{1,${i}}`);return t},Me=(t,n,i)=>{let o=ak(n),a=sk++;tk(t,a,n),ye[t]=a,ce[a]=n,ik[a]=o,rk[a]=new RegExp(n,i?"g":void 0),nk[a]=new RegExp(o,i?"g":void 0)};Me("NUMERICIDENTIFIER","0|[1-9]\\d*");Me("NUMERICIDENTIFIERLOOSE","\\d+");Me("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${Uh}*`);Me("MAINVERSION",`(${ce[ye.NUMERICIDENTIFIER]})\\.(${ce[ye.NUMERICIDENTIFIER]})\\.(${ce[ye.NUMERICIDENTIFIER]})`);Me("MAINVERSIONLOOSE",`(${ce[ye.NUMERICIDENTIFIERLOOSE]})\\.(${ce[ye.NUMERICIDENTIFIERLOOSE]})\\.(${ce[ye.NUMERICIDENTIFIERLOOSE]})`);Me("PRERELEASEIDENTIFIER",`(?:${ce[ye.NONNUMERICIDENTIFIER]}|${ce[ye.NUMERICIDENTIFIER]})`);Me("PRERELEASEIDENTIFIERLOOSE",`(?:${ce[ye.NONNUMERICIDENTIFIER]}|${ce[ye.NUMERICIDENTIFIERLOOSE]})`);Me("PRERELEASE",`(?:-(${ce[ye.PRERELEASEIDENTIFIER]}(?:\\.${ce[ye.PRERELEASEIDENTIFIER]})*))`);Me("PRERELEASELOOSE",`(?:-?(${ce[ye.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${ce[ye.PRERELEASEIDENTIFIERLOOSE]})*))`);Me("BUILDIDENTIFIER",`${Uh}+`);Me("BUILD",`(?:\\+(${ce[ye.BUILDIDENTIFIER]}(?:\\.${ce[ye.BUILDIDENTIFIER]})*))`);Me("FULLPLAIN",`v?${ce[ye.MAINVERSION]}${ce[ye.PRERELEASE]}?${ce[ye.BUILD]}?`);Me("FULL",`^${ce[ye.FULLPLAIN]}$`);Me("LOOSEPLAIN",`[v=\\s]*${ce[ye.MAINVERSIONLOOSE]}${ce[ye.PRERELEASELOOSE]}?${ce[ye.BUILD]}?`);Me("LOOSE",`^${ce[ye.LOOSEPLAIN]}$`);Me("GTLT","((?:<|>)?=?)");Me("XRANGEIDENTIFIERLOOSE",`${ce[ye.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`);Me("XRANGEIDENTIFIER",`${ce[ye.NUMERICIDENTIFIER]}|x|X|\\*`);Me("XRANGEPLAIN",`[v=\\s]*(${ce[ye.XRANGEIDENTIFIER]})(?:\\.(${ce[ye.XRANGEIDENTIFIER]})(?:\\.(${ce[ye.XRANGEIDENTIFIER]})(?:${ce[ye.PRERELEASE]})?${ce[ye.BUILD]}?)?)?`);Me("XRANGEPLAINLOOSE",`[v=\\s]*(${ce[ye.XRANGEIDENTIFIERLOOSE]})(?:\\.(${ce[ye.XRANGEIDENTIFIERLOOSE]})(?:\\.(${ce[ye.XRANGEIDENTIFIERLOOSE]})(?:${ce[ye.PRERELEASELOOSE]})?${ce[ye.BUILD]}?)?)?`);Me("XRANGE",`^${ce[ye.GTLT]}\\s*${ce[ye.XRANGEPLAIN]}$`);Me("XRANGELOOSE",`^${ce[ye.GTLT]}\\s*${ce[ye.XRANGEPLAINLOOSE]}$`);Me("COERCEPLAIN",`(^|[^\\d])(\\d{1,${jh}})(?:\\.(\\d{1,${jh}}))?(?:\\.(\\d{1,${jh}}))?`);Me("COERCE",`${ce[ye.COERCEPLAIN]}(?:$|[^\\d])`);Me("COERCEFULL",ce[ye.COERCEPLAIN]+`(?:${ce[ye.PRERELEASE]})?(?:${ce[ye.BUILD]})?(?:$|[^\\d])`);Me("COERCERTL",ce[ye.COERCE],!0);Me("COERCERTLFULL",ce[ye.COERCEFULL],!0);Me("LONETILDE","(?:~>?)");Me("TILDETRIM",`(\\s*)${ce[ye.LONETILDE]}\\s+`,!0);Zi.tildeTrimReplace="$1~";Me("TILDE",`^${ce[ye.LONETILDE]}${ce[ye.XRANGEPLAIN]}$`);Me("TILDELOOSE",`^${ce[ye.LONETILDE]}${ce[ye.XRANGEPLAINLOOSE]}$`);Me("LONECARET","(?:\\^)");Me("CARETTRIM",`(\\s*)${ce[ye.LONECARET]}\\s+`,!0);Zi.caretTrimReplace="$1^";Me("CARET",`^${ce[ye.LONECARET]}${ce[ye.XRANGEPLAIN]}$`);Me("CARETLOOSE",`^${ce[ye.LONECARET]}${ce[ye.XRANGEPLAINLOOSE]}$`);Me("COMPARATORLOOSE",`^${ce[ye.GTLT]}\\s*(${ce[ye.LOOSEPLAIN]})$|^$`);Me("COMPARATOR",`^${ce[ye.GTLT]}\\s*(${ce[ye.FULLPLAIN]})$|^$`);Me("COMPARATORTRIM",`(\\s*)${ce[ye.GTLT]}\\s*(${ce[ye.LOOSEPLAIN]}|${ce[ye.XRANGEPLAIN]})`,!0);Zi.comparatorTrimReplace="$1$2$3";Me("HYPHENRANGE",`^\\s*(${ce[ye.XRANGEPLAIN]})\\s+-\\s+(${ce[ye.XRANGEPLAIN]})\\s*$`);Me("HYPHENRANGELOOSE",`^\\s*(${ce[ye.XRANGEPLAINLOOSE]})\\s+-\\s+(${ce[ye.XRANGEPLAINLOOSE]})\\s*$`);Me("STAR","(<|>)?=?\\s*\\*");Me("GTE0","^\\s*>=\\s*0\\.0\\.0\\s*$");Me("GTE0PRE","^\\s*>=\\s*0\\.0\\.0-0\\s*$")});var qu=e(function(E9,l0){var ck=Object.freeze({loose:!0}),lk=Object.freeze({}),uk=(t)=>{if(!t)return lk;if(typeof t!=="object")return ck;return t};l0.exports=uk});var Fh=e(function(A9,f0){var u0=/^[0-9]+$/,d0=(t,n)=>{if(typeof t==="number"&&typeof n==="number")return t===n?0:t<n?-1:1;let i=u0.test(t),o=u0.test(n);if(i&&o)t=+t,n=+n;return t===n?0:i&&!o?-1:o&&!i?1:t<n?-1:1},dk=(t,n)=>d0(n,t);f0.exports={compareIdentifiers:d0,rcompareIdentifiers:dk}});var gr=e(function(x9,h0){var Bu=Lc(),{MAX_LENGTH:p0,MAX_SAFE_INTEGER:Wu}=$a(),{safeRe:Hu,t:Vu}=La(),fk=qu(),{compareIdentifiers:qh}=Fh(),pk=(t,n)=>{let i=n.split(".");if(i.length>t.length)return!1;for(let o=0;o<i.length;o++)if(qh(t[o],i[o])!==0)return!1;return!0};class Si{constructor(t,n){if(n=fk(n),t instanceof Si)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>p0)throw TypeError(`version is longer than ${p0} characters`);Bu("SemVer",t,n),this.options=n,this.loose=!!n.loose,this.includePrerelease=!!n.includePrerelease;let i=t.trim().match(n.loose?Hu[Vu.LOOSE]:Hu[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>Wu||this.major<0)throw TypeError("Invalid major version");if(this.minor>Wu||this.minor<0)throw TypeError("Invalid minor version");if(this.patch>Wu||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<Wu)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(Bu("SemVer.compare",this.version,this.options,t),!(t instanceof Si)){if(typeof t==="string"&&t===this.version)return 0;t=new Si(t,this.options)}if(t.version===this.version)return 0;return this.compareMain(t)||this.comparePre(t)}compareMain(t){if(!(t instanceof Si))t=new Si(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 Si))t=new Si(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(Bu("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 qh(i,o)}while(++n)}compareBuild(t){if(!(t instanceof Si))t=new Si(t,this.options);let n=0;do{let i=this.build[n],o=t.build[n];if(Bu("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 qh(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?Hu[Vu.PRERELEASELOOSE]:Hu[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(pk(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}}h0.exports=Si});var xo=e(function(_9,g0){var m0=gr(),hk=(t,n,i=!1)=>{if(t instanceof m0)return t;try{return new m0(t,n)}catch(o){if(!i)return null;throw o}};g0.exports=hk});var w0=e(function(I9,y0){var mk=xo(),gk=(t,n)=>{let i=mk(t,n);return i?i.version:null};y0.exports=gk});var b0=e(function(T9,S0){var yk=xo(),wk=(t,n)=>{let i=yk(t.trim().replace(/^[=v]+/,""),n);return i?i.version:null};S0.exports=wk});var A0=e(function(R9,E0){var v0=gr(),Sk=(t,n,i,o,a)=>{if(typeof i==="string")a=o,o=i,i=void 0;try{return new v0(t instanceof v0?t.version:t,i).inc(n,o,a).version}catch(c){return null}};E0.exports=Sk});var I0=e(function(P9,_0){var x0=xo(),bk=(t,n)=>{let i=x0(t,null,!0),o=x0(n,null,!0),a=i.compare(o);if(a===0)return null;let c=a>0,h=c?i:o,w=c?o:i,E=!!h.prerelease.length;if(!!w.prerelease.length&&!E){if(!w.patch&&!w.minor)return"major";if(w.compareMain(h)===0){if(w.minor&&!w.patch)return"minor";return"patch"}}let I=E?"pre":"";if(i.major!==o.major)return I+"major";if(i.minor!==o.minor)return I+"minor";if(i.patch!==o.patch)return I+"patch";return"prerelease"};_0.exports=bk});var R0=e(function(C9,T0){var vk=gr(),Ek=(t,n)=>new vk(t,n).major;T0.exports=Ek});var C0=e(function(O9,P0){var Ak=gr(),xk=(t,n)=>new Ak(t,n).minor;P0.exports=xk});var k0=e(function(k9,O0){var _k=gr(),Ik=(t,n)=>new _k(t,n).patch;O0.exports=Ik});var N0=e(function(M9,M0){var Tk=xo(),Rk=(t,n)=>{let i=Tk(t,n);return i&&i.prerelease.length?i.prerelease:null};M0.exports=Rk});var Dn=e(function(N9,$0){var D0=gr(),Pk=(t,n,i)=>new D0(t,i).compare(new D0(n,i));$0.exports=Pk});var j0=e(function(D9,L0){var Ck=Dn(),Ok=(t,n,i)=>Ck(n,t,i);L0.exports=Ok});var F0=e(function($9,U0){var kk=Dn(),Mk=(t,n)=>kk(t,n,!0);U0.exports=Mk});var zu=e(function(L9,B0){var q0=gr(),Nk=(t,n,i)=>{let o=new q0(t,i),a=new q0(n,i);return o.compare(a)||o.compareBuild(a)};B0.exports=Nk});var H0=e(function(j9,W0){var Dk=zu(),$k=(t,n)=>t.sort((i,o)=>Dk(i,o,n));W0.exports=$k});var z0=e(function(U9,V0){var Lk=zu(),jk=(t,n)=>t.sort((i,o)=>Lk(o,i,n));V0.exports=jk});var jc=e(function(F9,G0){var Uk=Dn(),Fk=(t,n,i)=>Uk(t,n,i)>0;G0.exports=Fk});var Gu=e(function(q9,K0){var qk=Dn(),Bk=(t,n,i)=>qk(t,n,i)<0;K0.exports=Bk});var Bh=e(function(B9,J0){var Wk=Dn(),Hk=(t,n,i)=>Wk(t,n,i)===0;J0.exports=Hk});var Wh=e(function(W9,Y0){var Vk=Dn(),zk=(t,n,i)=>Vk(t,n,i)!==0;Y0.exports=zk});var Ku=e(function(H9,X0){var Gk=Dn(),Kk=(t,n,i)=>Gk(t,n,i)>=0;X0.exports=Kk});var Ju=e(function(V9,Z0){var Jk=Dn(),Yk=(t,n,i)=>Jk(t,n,i)<=0;Z0.exports=Yk});var Hh=e(function(z9,Q0){var Xk=Bh(),Zk=Wh(),Qk=jc(),eM=Ku(),tM=Gu(),rM=Ju(),nM=(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 Xk(t,i,o);case"!=":return Zk(t,i,o);case">":return Qk(t,i,o);case">=":return eM(t,i,o);case"<":return tM(t,i,o);case"<=":return rM(t,i,o);default:throw TypeError(`Invalid operator: ${n}`)}};Q0.exports=nM});var tv=e(function(G9,ev){var iM=gr(),sM=xo(),{safeRe:Yu,t:Xu}=La(),oM=(t,n)=>{if(t instanceof iM)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?Yu[Xu.COERCEFULL]:Yu[Xu.COERCE]);else{let E=n.includePrerelease?Yu[Xu.COERCERTLFULL]:Yu[Xu.COERCERTL],_;while((_=E.exec(t))&&(!i||i.index+i[0].length!==t.length)){if(!i||_.index+_[0].length!==i.index+i[0].length)i=_;E.lastIndex=_.index+_[1].length+_[2].length}E.lastIndex=-1}if(i===null)return null;let o=i[2],a=i[3]||"0",c=i[4]||"0",h=n.includePrerelease&&i[5]?`-${i[5]}`:"",w=n.includePrerelease&&i[6]?`+${i[6]}`:"";return sM(`${o}.${a}.${c}${h}${w}`,n)};ev.exports=oM});var iv=e(function(K9,nv){var aM=xo(),rv=$a(),cM=gr(),lM=(t,n,i)=>{if(!rv.RELEASE_TYPES.includes(n))return null;let o=uM(t,i);return o&&dM(o,n)},uM=(t,n)=>{let i=t instanceof cM?t.version:t;return aM(i,n)},dM=(t,n)=>{if(fM(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()},fM=(t)=>t.startsWith("pre");nv.exports=lM});var av=e(function(J9,ov){class sv{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}}ov.exports=sv});var Qn=e(function(Y9,dv){var pM=/\s+/g;class Uc{constructor(t,n){if(n=mM(n),t instanceof Uc)if(t.loose===!!n.loose&&t.includePrerelease===!!n.includePrerelease)return t;else return new Uc(t.raw,n);if(t instanceof Zu)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(pM," "),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)=>!lv(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&&xM(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(AM,"");let i=((this.options.includePrerelease&&vM)|(this.options.loose&&EM))+":"+t,o=cv.get(i);if(o)return o;let a=this.options.loose,c=a?rn[wr.HYPHENRANGELOOSE]:rn[wr.HYPHENRANGE];t=t.replace(c,DM(this.options.includePrerelease)),St("hyphen replace",t),t=t.replace(rn[wr.COMPARATORTRIM],wM),St("comparator trim",t),t=t.replace(rn[wr.TILDETRIM],SM),St("tilde trim",t),t=t.replace(rn[wr.CARETTRIM],bM),St("caret trim",t);let h=t.split(" ").map((I)=>_M(I,this.options)).join(" ").split(/\s+/).map((I)=>NM(I,this.options));if(a)h=h.filter((I)=>(St("loose invalid filter",I,this.options),!!I.match(rn[wr.COMPARATORLOOSE])));St("range list",h);let w=new Map,E=h.map((I)=>new Zu(I,this.options));for(let I of E){if(lv(I))return[I];w.set(I.value,I)}if(w.size>1&&w.has(""))w.delete("");let _=[...w.values()];return cv.set(i,_),_}intersects(t,n){if(!(t instanceof Uc))throw TypeError("a Range is required");return this.set.some((i)=>uv(i,n)&&t.set.some((o)=>uv(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 gM(t,this.options)}catch(n){return!1}for(let n=0;n<this.set.length;n++)if($M(this.set[n],t,this.options))return!0;return!1}}dv.exports=Uc;var hM=av(),cv=new hM,mM=qu(),Zu=Fc(),St=Lc(),gM=gr(),{safeRe:rn,src:yM,t:wr,comparatorTrimReplace:wM,tildeTrimReplace:SM,caretTrimReplace:bM}=La(),{FLAG_INCLUDE_PRERELEASE:vM,FLAG_LOOSE:EM}=$a(),AM=new RegExp(yM[wr.BUILD],"g"),lv=(t)=>t.value==="<0.0.0-0",xM=(t)=>t.value==="",uv=(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},_M=(t,n)=>(t=t.replace(rn[wr.BUILD],""),St("comp",t,n),t=PM(t,n),St("caret",t),t=TM(t,n),St("tildes",t),t=OM(t,n),St("xrange",t),t=MM(t,n),St("stars",t),t),nr=(t)=>!t||t.toLowerCase()==="x"||t==="*",IM=(t,n,i)=>nr(t)&&!nr(n)||nr(n)&&i&&!nr(i),TM=(t,n)=>t.trim().split(/\s+/).map((i)=>RM(i,n)).join(" "),RM=(t,n)=>{let i=n.loose?rn[wr.TILDELOOSE]:rn[wr.TILDE];return t.replace(i,(o,a,c,h,w)=>{St("tilde",t,o,a,c,h,w);let E;if(nr(a))E="";else if(nr(c))E=`>=${a}.0.0 <${+a+1}.0.0-0`;else if(nr(h))E=`>=${a}.${c}.0 <${a}.${+c+1}.0-0`;else if(w)St("replaceTilde pr",w),E=`>=${a}.${c}.${h}-${w} <${a}.${+c+1}.0-0`;else E=`>=${a}.${c}.${h} <${a}.${+c+1}.0-0`;return St("tilde return",E),E})},PM=(t,n)=>t.trim().split(/\s+/).map((i)=>CM(i,n)).join(" "),CM=(t,n)=>{St("caret",t,n);let i=n.loose?rn[wr.CARETLOOSE]:rn[wr.CARET],o=n.includePrerelease?"-0":"";return t.replace(i,(a,c,h,w,E)=>{St("caret",t,a,c,h,w,E);let _;if(nr(c))_="";else if(nr(h))_=`>=${c}.0.0${o} <${+c+1}.0.0-0`;else if(nr(w))if(c==="0")_=`>=${c}.${h}.0${o} <${c}.${+h+1}.0-0`;else _=`>=${c}.${h}.0${o} <${+c+1}.0.0-0`;else if(E)if(St("replaceCaret pr",E),c==="0")if(h==="0")_=`>=${c}.${h}.${w}-${E} <${c}.${h}.${+w+1}-0`;else _=`>=${c}.${h}.${w}-${E} <${c}.${+h+1}.0-0`;else _=`>=${c}.${h}.${w}-${E} <${+c+1}.0.0-0`;else if(St("no pr"),c==="0")if(h==="0")_=`>=${c}.${h}.${w} <${c}.${h}.${+w+1}-0`;else _=`>=${c}.${h}.${w} <${c}.${+h+1}.0-0`;else _=`>=${c}.${h}.${w} <${+c+1}.0.0-0`;return St("caret return",_),_})},OM=(t,n)=>(St("replaceXRanges",t,n),t.split(/\s+/).map((i)=>kM(i,n)).join(" ")),kM=(t,n)=>{t=t.trim();let i=n.loose?rn[wr.XRANGELOOSE]:rn[wr.XRANGE];return t.replace(i,(o,a,c,h,w,E)=>{if(St("xRange",t,o,a,c,h,w,E),IM(c,h,w))return t;let _=nr(c),I=_||nr(h),T=I||nr(w),O=T;if(a==="="&&O)a="";if(E=n.includePrerelease?"-0":"",_)if(a===">"||a==="<")o="<0.0.0-0";else o="*";else if(a&&O){if(I)h=0;if(w=0,a===">")if(a=">=",I)c=+c+1,h=0,w=0;else h=+h+1,w=0;else if(a==="<=")if(a="<",I)c=+c+1;else h=+h+1;if(a==="<")E="-0";o=`${a+c}.${h}.${w}${E}`}else if(I)o=`>=${c}.0.0${E} <${+c+1}.0.0-0`;else if(T)o=`>=${c}.${h}.0${E} <${c}.${+h+1}.0-0`;return St("xRange return",o),o})},MM=(t,n)=>(St("replaceStars",t,n),t.trim().replace(rn[wr.STAR],"")),NM=(t,n)=>(St("replaceGTE0",t,n),t.trim().replace(rn[n.includePrerelease?wr.GTE0PRE:wr.GTE0],"")),DM=(t)=>(n,i,o,a,c,h,w,E,_,I,T,O)=>{if(nr(o))i="";else if(nr(a))i=`>=${o}.0.0${t?"-0":""}`;else if(nr(c))i=`>=${o}.${a}.0${t?"-0":""}`;else if(h)i=`>=${i}`;else i=`>=${i}${t?"-0":""}`;if(nr(_))E="";else if(nr(I))E=`<${+_+1}.0.0-0`;else if(nr(T))E=`<${_}.${+I+1}.0-0`;else if(O)E=`<=${_}.${I}.${T}-${O}`;else if(t)E=`<${_}.${I}.${+T+1}-0`;else E=`<=${E}`;return`${i} ${E}`.trim()},$M=(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(St(t[o].semver),t[o].semver===Zu.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 Fc=e(function(X9,yv){var qc=Symbol("SemVer ANY");class Qu{static get ANY(){return qc}constructor(t,n){if(n=fv(n),t instanceof Qu)if(t.loose===!!n.loose)return t;else t=t.value;if(t=t.trim().split(/\s+/).join(" "),zh("comparator",t,n),this.options=n,this.loose=!!n.loose,this.parse(t),this.semver===qc)this.value="";else this.value=this.operator+this.semver.version;zh("comp",this)}parse(t){let n=this.options.loose?pv[hv.COMPARATORLOOSE]:pv[hv.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=qc;else this.semver=new mv(i[2],this.options.loose)}toString(){return this.value}test(t){if(zh("Comparator.test",t,this.options.loose),this.semver===qc||t===qc)return!0;if(typeof t==="string")try{t=new mv(t,this.options)}catch(n){return!1}return Vh(t,this.operator,this.semver,this.options)}intersects(t,n){if(!(t instanceof Qu))throw TypeError("a Comparator is required");if(this.operator===""){if(this.value==="")return!0;return new gv(t.value,n).test(this.value)}else if(t.operator===""){if(t.value==="")return!0;return new gv(this.value,n).test(t.semver)}if(n=fv(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(Vh(this.semver,"<",t.semver,n)&&this.operator.startsWith(">")&&t.operator.startsWith("<"))return!0;if(Vh(this.semver,">",t.semver,n)&&this.operator.startsWith("<")&&t.operator.startsWith(">"))return!0;return!1}}yv.exports=Qu;var fv=qu(),{safeRe:pv,t:hv}=La(),Vh=Hh(),zh=Lc(),mv=gr(),gv=Qn()});var Bc=e(function(Z9,wv){var LM=Qn(),jM=(t,n,i)=>{try{n=new LM(n,i)}catch(o){return!1}return n.test(t)};wv.exports=jM});var bv=e(function(Q9,Sv){var UM=Qn(),FM=(t,n)=>new UM(t,n).set.map((i)=>i.map((o)=>o.value).join(" ").trim().split(" "));Sv.exports=FM});var Ev=e(function(e7,vv){var qM=gr(),BM=Qn(),WM=(t,n,i)=>{let o=null,a=null,c=null;try{c=new BM(n,i)}catch(h){return null}return t.forEach((h)=>{if(c.test(h)){if(!o||a.compare(h)===-1)o=h,a=new qM(o,i)}}),o};vv.exports=WM});var xv=e(function(t7,Av){var HM=gr(),VM=Qn(),zM=(t,n,i)=>{let o=null,a=null,c=null;try{c=new VM(n,i)}catch(h){return null}return t.forEach((h)=>{if(c.test(h)){if(!o||a.compare(h)===1)o=h,a=new HM(o,i)}}),o};Av.exports=zM});var Tv=e(function(r7,Iv){var Gh=gr(),GM=Qn(),_v=jc(),KM=(t,n)=>{t=new GM(t,n);let i=new Gh("0.0.0");if(t.test(i))return i;if(i=new Gh("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((h)=>{let w=new Gh(h.semver.version);switch(h.operator){case">":if(w.prerelease.length===0)w.patch++;else w.prerelease.push(0);w.raw=w.format();case"":case">=":if(!c||_v(w,c))c=w;break;case"<":case"<=":break;default:throw Error(`Unexpected operation: ${h.operator}`)}}),c&&(!i||_v(i,c)))i=c}if(i&&t.test(i))return i;return null};Iv.exports=KM});var Pv=e(function(n7,Rv){var JM=Qn(),YM=(t,n)=>{try{return new JM(t,n).range||"*"}catch(i){return null}};Rv.exports=YM});var ed=e(function(i7,Mv){var XM=gr(),kv=Fc(),{ANY:ZM}=kv,QM=Qn(),eN=Bc(),Cv=jc(),Ov=Gu(),tN=Ju(),rN=Ku(),nN=(t,n,i,o)=>{t=new XM(t,o),n=new QM(n,o);let a,c,h,w,E;switch(i){case">":a=Cv,c=tN,h=Ov,w=">",E=">=";break;case"<":a=Ov,c=rN,h=Cv,w="<",E="<=";break;default:throw TypeError('Must provide a hilo val of "<" or ">"')}if(eN(t,n,o))return!1;for(let _=0;_<n.set.length;++_){let I=n.set[_],T=null,O=null;if(I.forEach((N)=>{if(N.semver===ZM)N=new kv(">=0.0.0");if(T=T||N,O=O||N,a(N.semver,T.semver,o))T=N;else if(h(N.semver,O.semver,o))O=N}),T.operator===w||T.operator===E)return!1;if((!O.operator||O.operator===w)&&c(t,O.semver))return!1;else if(O.operator===E&&h(t,O.semver))return!1}return!0};Mv.exports=nN});var Dv=e(function(s7,Nv){var iN=ed(),sN=(t,n,i)=>iN(t,n,">",i);Nv.exports=sN});var Lv=e(function(o7,$v){var oN=ed(),aN=(t,n,i)=>oN(t,n,"<",i);$v.exports=aN});var Fv=e(function(a7,Uv){var jv=Qn(),cN=(t,n,i)=>(t=new jv(t,i),n=new jv(n,i),t.intersects(n,i));Uv.exports=cN});var Bv=e(function(c7,qv){var lN=Bc(),uN=Dn();qv.exports=(t,n,i)=>{let o=[],a=null,c=null,h=t.sort((I,T)=>uN(I,T,i));for(let I of h)if(lN(I,n,i)){if(c=I,!a)a=I}else{if(c)o.push([a,c]);c=null,a=null}if(a)o.push([a,null]);let w=[];for(let[I,T]of o)if(I===T)w.push(I);else if(!T&&I===h[0])w.push("*");else if(!T)w.push(`>=${I}`);else if(I===h[0])w.push(`<=${T}`);else w.push(`${I} - ${T}`);let E=w.join(" || "),_=typeof n.raw==="string"?n.raw:String(n);return E.length<_.length?E:n}});var Kv=e(function(l7,Gv){var Wv=Qn(),Yh=Fc(),{ANY:Kh}=Yh,Jh=Bc(),Xh=Dn(),dN=(t,n,i={})=>{if(t===n)return!0;t=new Wv(t,i),n=new Wv(n,i);let o=!1;e:for(let a of t.set){for(let c of n.set){let h=pN(a,c,i);if(o=o||h!==null,h)continue e}if(o)return!1}return!0},fN=[new Yh(">=0.0.0-0")],Hv=[new Yh(">=0.0.0")],pN=(t,n,i)=>{if(t===n)return!0;if(t.length===1&&t[0].semver===Kh)if(n.length===1&&n[0].semver===Kh)return!0;else if(i.includePrerelease)t=fN;else t=Hv;if(n.length===1&&n[0].semver===Kh)if(i.includePrerelease)return!0;else n=Hv;let o=new Set,a,c;for(let N of t)if(N.operator===">"||N.operator===">=")a=Vv(a,N,i);else if(N.operator==="<"||N.operator==="<=")c=zv(c,N,i);else o.add(N.semver);if(o.size>1)return null;let h;if(a&&c){if(h=Xh(a.semver,c.semver,i),h>0)return null;else if(h===0&&(a.operator!==">="||c.operator!=="<="))return null}for(let N of o){if(a&&!Jh(N,String(a),i))return null;if(c&&!Jh(N,String(c),i))return null;for(let L of n)if(!Jh(N,String(L),i))return!1;return!0}let w,E,_,I,T=c&&!i.includePrerelease&&c.semver.prerelease.length?c.semver:!1,O=a&&!i.includePrerelease&&a.semver.prerelease.length?a.semver:!1;if(T&&T.prerelease.length===1&&c.operator==="<"&&T.prerelease[0]===0)T=!1;for(let N of n){if(I=I||N.operator===">"||N.operator===">=",_=_||N.operator==="<"||N.operator==="<=",a){if(O){if(N.semver.prerelease&&N.semver.prerelease.length&&N.semver.major===O.major&&N.semver.minor===O.minor&&N.semver.patch===O.patch)O=!1}if(N.operator===">"||N.operator===">="){if(w=Vv(a,N,i),w===N&&w!==a)return!1}else if(a.operator===">="&&!N.test(a.semver))return!1}if(c){if(T){if(N.semver.prerelease&&N.semver.prerelease.length&&N.semver.major===T.major&&N.semver.minor===T.minor&&N.semver.patch===T.patch)T=!1}if(N.operator==="<"||N.operator==="<="){if(E=zv(c,N,i),E===N&&E!==c)return!1}else if(c.operator==="<="&&!N.test(c.semver))return!1}if(!N.operator&&(c||a)&&h!==0)return!1}if(a&&_&&!c&&h!==0)return!1;if(c&&I&&!a&&h!==0)return!1;if(O||T)return!1;return!0},Vv=(t,n,i)=>{if(!t)return n;let o=Xh(t.semver,n.semver,i);return o>0?t:o<0?n:n.operator===">"&&t.operator===">="?n:t},zv=(t,n,i)=>{if(!t)return n;let o=Xh(t.semver,n.semver,i);return o<0?t:o>0?n:n.operator==="<"&&t.operator==="<="?n:t};Gv.exports=dN});var Yv=e(function(u7,Jv){var ja=La(),td=$a(),hN=gr(),rd=Fh(),mN=xo(),gN=w0(),yN=b0(),wN=A0(),SN=I0(),bN=R0(),vN=C0(),EN=k0(),AN=N0(),xN=Dn(),_N=j0(),IN=F0(),TN=zu(),RN=H0(),PN=z0(),CN=jc(),ON=Gu(),kN=Bh(),MN=Wh(),NN=Ku(),DN=Ju(),$N=Hh(),LN=tv(),jN=iv(),UN=Fc(),FN=Qn(),qN=Bc(),BN=bv(),WN=Ev(),HN=xv(),VN=Tv(),zN=Pv(),GN=ed(),KN=Dv(),JN=Lv(),YN=Fv(),XN=Bv(),ZN=Kv();Jv.exports={parse:mN,valid:gN,clean:yN,inc:wN,diff:SN,major:bN,minor:vN,patch:EN,prerelease:AN,compare:xN,rcompare:_N,compareLoose:IN,compareBuild:TN,sort:RN,rsort:PN,gt:CN,lt:ON,eq:kN,neq:MN,gte:NN,lte:DN,cmp:$N,coerce:LN,truncate:jN,Comparator:UN,Range:FN,satisfies:qN,toComparators:BN,maxSatisfying:WN,minSatisfying:HN,minVersion:VN,validRange:zN,outside:GN,gtr:KN,ltr:JN,intersects:YN,simplifyRange:XN,subset:ZN,SemVer:hN,re:ja.re,src:ja.src,tokens:ja.t,SEMVER_SPEC_VERSION:td.SEMVER_SPEC_VERSION,RELEASE_TYPES:td.RELEASE_TYPES,compareIdentifiers:rd.compareIdentifiers,rcompareIdentifiers:rd.rcompareIdentifiers}});import{rm as G$}from"fs/promises";import{dirname as K$,join as J$}from"path";var tl=new Map;function rl(t){return{type:"agent-activity:changed",agentIds:Array.from(tl.get(t)?.keys()??[],ns)}}function ZA(t,n){let i=tl.get(t)??new Map,o=i.get(n);clearTimeout(o);let a=setTimeout(()=>{if(i.delete(n),!i.size)tl.delete(t);Vn(t,rl(t))},60000).unref();if(i.set(n,a),tl.set(t,i),!o)Vn(t,rl(t))}function nl(t,n){let i=n.headers.get("x-moi-user-id");if(i&&/^a_[A-Za-z0-9_-]{43}$/.test(i))ZA(t,i)}import{chmod as gx,rm as yx}from"fs/promises";function xm(t){return[t&&Cs("algorithms",t.algorithms),t?.crit]}function QA(t){return t===void 0?{}:ws(t,P,"JWS Protected Header is invalid")}function ex(t){try{return he(t)}catch{throw new P("JWS Compact Serialization payload must use only ASCII characters")}}async function tx(t,n,i,o,a){let{protected:c,header:h,payload:w}=t,E=a??QA(c);if(!zr(E,h))throw new P("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let _={...E,...h},I=Gr(E,Kr(P,Vr,n[1],E,_)),{alg:T}=_;if(typeof T!="string"||!T)throw new P('JWS "alg" (Algorithm) Header Parameter missing or invalid');if(n[0]&&!n[0].has(T))throw new Gn('"alg" (Algorithm) Header Parameter value not allowed');if(I){if(typeof w!="string")throw new P("JWS Payload must be a string")}else if(typeof w!="string"&&!(w instanceof Uint8Array))throw new P("JWS Payload must be a string or an Uint8Array instance");let O=I||typeof w!="string"?w:o(w),N=!1;typeof i=="function"&&(i=await i(E,t),N=!0);let L=Jr(T),H=jr(c!==void 0?he(c):new Uint8Array,he("."),typeof O=="string"?n[2]??=Is(O,"payload",P):O),Z=Jn(t.signature,"signature",P),G=await $r(L,i,"verify"),oe=await Hr(G,L.subtle,"verify");L.minRsaBits&&qr(L.alg,oe);let re=!1;try{re=await crypto.subtle.verify(L.signing,oe,Z,H)}catch{}if(!re)throw new Hn;let xe={payload:typeof O=="string"?Jn(O,"payload",P):O};return c!==void 0&&(xe.protectedHeader=E),h!==void 0&&(xe.unprotectedHeader=h),N?[{...xe,key:G},I]:[xe,I]}async function _m(t,n,i){if(t instanceof Uint8Array&&(t=Br.decode(t)),typeof t!="string")throw new P("Compact JWS must be a string or Uint8Array");let{0:o,1:a,2:c,length:h}=t.split(".");if(h!==3)throw new P("Invalid Compact JWS");return tx({payload:a,protected:o,signature:c},n,i,ex)}async function Im(t,n,i){let[o,a]=await _m(t,xm(i),n);if(!a)throw new Y("JWTs MUST NOT use unencoded payload");let c=Ds(o.protectedHeader,o.payload,i);return{...o,payload:c}}function rx(t,n,i,o){let{kty:a,key_ops:c,ext:h,kid:w,alg:E,use:_,crv:I}=t;return(h===void 0||typeof h=="boolean")&&(c===void 0||Array.isArray(c)&&c.every((T,O)=>typeof T=="string"&&c.indexOf(T)===O)&&c.includes("verify"))&&n.kty.includes(a)&&(o===void 0||typeof o=="string"&&o===w)&&(E===void 0?a!=="AKP":i===E)&&(_===void 0||_==="sig")&&(!n.crv||I===n.crv)}async function Tm(t,n,i){let o=t.get(n)||t.set(n,{}).get(n),{alg:a}=i;if(o[a]===void 0){let c=vt(i,n,!0).then((h)=>{if(h.type!=="public")throw new Wr("JSON Web Key Set members must be public keys");return o[a]=h,h}).catch((h)=>{throw o[a]===c&&delete o[a],h});o[a]=c}return o[a]}function kd(t){let n;try{n=structuredClone(t)}catch{}if(!Ur(n))throw new Wr("JSON Web Key Set malformed");let i=n.keys.map((a)=>{let c=bt(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:h,kid:w}={...a,...c?.header},E=typeof h=="string"?Xt[h]:void 0;if(!E||E.secret)throw new M('Unsupported "alg" value for a JSON Web Key Set');let _=n.keys.filter((O,N)=>rx(i[N],E,h,w)),{0:I,length:T}=_;if(!T)throw new Jt;if(T!==1){let O=new $n;throw O[Symbol.asyncIterator]=async function*(){for(let N of _)try{yield await Tm(o,N,E)}catch{}},O}return Tm(o,I,E)},"jwks",{value:()=>structuredClone(n)})}function nx(){return typeof WebSocketPair<"u"||typeof navigator<"u"&&navigator.userAgent==="Cloudflare-Workers"||typeof EdgeRuntime<"u"&&EdgeRuntime==="vercel"}var Md;(typeof navigator>"u"||!navigator.userAgent?.startsWith?.("Mozilla/5.0 "))&&(Md="jose/v6.2.12");var Nd=Symbol();async function ix(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 qn:c});if(a.status!==200)throw new q("Expected 200 OK from the JSON Web Key Set HTTP response");try{return await a.json()}catch{throw new q("Failed to parse the JSON Web Key Set HTTP response as JSON")}}var sx=Symbol();function Ga(t,n){return Number.isFinite(t)&&Date.now()<t+n}function Rm(t,n,i){if(Number.isNaN(t))throw TypeError(`"${i}" option must not be NaN`);return typeof t=="number"?t:n}function Pm(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,h=Rm(o.cooldownDuration,30000,"cooldownDuration"),w=Rm(o.cacheMaxAge,600000,"cacheMaxAge"),E=new Headers(o.headers);Md&&!E.has("User-Agent")&&E.set("User-Agent",Md),E.has("accept")||E.set("accept","application/json, application/jwk-set+json");let _=o[Nd],I=o[sx],T,O,N=0,L=0,H;if(I&&typeof I=="object"){let{uat:G,jwks:oe}=I;Ga(G,w)&&Ur(oe)&&(T=G,H=kd(oe))}let Z=async()=>{if(O&&nx()&&(O=void 0),!O){let G=++N,oe=O=ix(i,E,AbortSignal.timeout(c),_).then((re)=>{let xe=kd(re);if(G<=L)return;H=xe;let Oe=Date.now();I&&(I.uat=Oe,I.jwks=re),T=Oe,L=G}).finally(()=>{O===oe&&(O=void 0)})}await O};return Object.defineProperties(async(G,oe)=>{(!H||!Ga(T,w))&&await Z();try{return await H(G,oe)}catch(re){if(re instanceof Jt&&!Ga(T,h))return await Z(),H(G,oe);throw re}},{coolingDown:{get:()=>Ga(T,h),enumerable:!0},fresh:{get:()=>Ga(T,w),enumerable:!0},reload:{value:Z,enumerable:!0},reloading:{get:()=>!!O,enumerable:!0},jwks:{value:()=>H?.jwks(),enumerable:!0}})}import{constants as il}from"fs";import{lstat as Dd,mkdir as ox,open as ax,realpath as cx,rename as lx,rm as ux}from"fs/promises";import{dirname as dx,isAbsolute as Cm,relative as Om,resolve as $d,sep as km}from"path";class Et extends Error{status;constructor(t,n=400){super(t);this.status=n}}var fx=new Ie;function px(t,n){let i=Om(t,n);return i!==""&&i!==".."&&!i.startsWith(`..${km}`)&&!Cm(i)}async function sl(t,n,i=!1){if(!n||Cm(n)||n.includes("\\")||n.includes("\x00")||n.split("/").some((h)=>h===".."||h==="."))throw new Et("Use a file path relative to the workspace");t=await cx(t);let o=$d(t,n);if(!px(t,o))throw new Et("File is outside the workspace");let a=t,c=Om(t,o).split(km);for(let[h,w]of c.entries()){a=$d(a,w);try{let E=await Dd(a);if(E.isSymbolicLink())throw new Et("Symbolic links are not supported");if(h<c.length-1&&!E.isDirectory())throw new Et("Parent is not a directory");if(h===c.length-1&&!E.isFile())throw new Et("Path is not a file")}catch(E){if(E.code!=="ENOENT")throw E;if(!i)throw new Et("File not found",404);if(h<c.length-1)await ox(a)}}return o}async function Ld(t,n,i,o){return fx.runExclusive(async()=>{let a=await sl(t,n,!o),c=$d(dx(a),`.moi-write-${crypto.randomUUID()}`),h=436;try{h=(await Dd(a)).mode&511}catch{}let w=await ax(c,il.O_WRONLY|il.O_CREAT|il.O_EXCL|il.O_NOFOLLOW,h);try{if(o){let E=new TextDecoder("utf-8",{fatal:!0}).decode(await Bun.file(a).arrayBuffer());await w.writeFile(o(E))}else for await(let E of i)await w.writeFile(E);if(await w.close(),await sl(t,n,!0)!==a)throw new Et("File changed during upload",409);await lx(c,a)}finally{await w.close().catch(()=>{}),await ux(c,{force:!0})}return{ok:!0,bytes:(await Dd(a)).size}})}function Mm(t,n){let i=t?t.split(`
|
|
3
|
+
`):[];if(t.endsWith(`
|
|
4
|
+
`))i.pop();let o=[],a=n.split(`
|
|
5
|
+
`),c=0,h=0,w=t.endsWith(`
|
|
6
|
+
`);for(let E=0;E<a.length;E++){let _=/^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@(?:.*)$/.exec(a[E]);if(!_){if(a[E]===""||a[E]?.startsWith("--- ")||a[E]?.startsWith("+++ "))continue;throw new Et("Expected a unified diff",422)}h++;let I=Number(_[2]??1),T=Number(_[4]??1),O=Number(_[1])-(I?1:0);if(O<c||O>i.length)throw new Et("Patch does not match the file",409);if(o.push(...i.slice(c,O)),c=O,Number(_[3])-(T?1:0)!==o.length)throw new Et("Invalid patch position",422);let N=0,L=0;while(N<I||L<T){let H=a[++E];if(H===void 0)throw new Et("Incomplete patch",422);let Z=H[0],G=H.slice(1);if(Z===" "||Z==="-"){if(i[c++]!==G)throw new Et("Patch does not match the file",409);N++}if(Z===" "||Z==="+")o.push(G),L++,w=!0;if(![" ","+","-"].includes(Z??"")||N>I||L>T)throw new Et("Invalid patch hunk",422);if(a[E+1]==="\"){if(Z!=="-")w=!1;E++}}}if(!h)throw new Et("Patch has no hunks",422);if(c<i.length)w=t.endsWith(`
|
|
7
|
+
`);return o.push(...i.slice(c)),o.join(`
|
|
8
|
+
`)+(o.length&&w?`
|
|
9
|
+
`:"")}var hx=["bundle","check","call-server-fn","theme","ui-components","views","debug"];function mx(t,n){if(!hx.includes(t)||t==="debug"&&n[0]!=="logs")throw new Et("Unsupported workspace command");if(n.some((i)=>/^--(?:dir|path)(?:=|$)/.test(i)))throw new Et("Workspace is selected by the remote link, not --dir or --path");if(["bundle","check","views"].includes(t)){let i=t==="views"?n[0]==="set"?2:1:0,o=[...n];return o.splice(i,0,"."),[t,...o]}return[t,...n]}function Nm(t,n,i){return Bun.spawn([process.execPath,ge("cli.ts"),...mx(n,i)],{cwd:t,stdin:"ignore",stdout:"pipe",stderr:"pipe",detached:!0,env:{...process.env,NO_COLOR:"1",FORCE_COLOR:"0"}})}var Dm=r().uuid(),wx=b([s({command:r().min(1).max(1e5),id:Dm.optional()}).strict(),s({cancel:Dm}).strict()]),Sx=s({command:r(),args:p(r().max(1e5)).max(500).default([])}).strict(),bx=s({patch:r().min(1).max(4194304)}).strict(),jd=new Set;function ta(t){try{process.kill(-t.pid,"SIGKILL")}catch{t.kill("SIGKILL")}}async function $m(t,n){let i=[],o=0;for await(let a of t){if(o+=a.byteLength,o>8388608)throw ta(n),new Et("Command output exceeded 8 MiB; use exec for streaming",413);i.push(a)}return new TextDecoder().decode(Buffer.concat(i))}function Lm(t,n){jd.add(t);let i=()=>ta(t);if(n.addEventListener("abort",i,{once:!0}),n.aborted)i();t.exited.finally(()=>{jd.delete(t),n.removeEventListener("abort",i)})}function jm(){for(let t of jd)ta(t)}function vx(t=W){let n=new Map,i=new Map;return async(o)=>{try{let a=new URL(o.url),c=/^\/workspaces\/([A-Za-z0-9_-]+)\/(files\/(.+)|exec|commands)$/.exec(a.pathname);if(!c)return Response.json({error:"Not found"},{status:404});let h=await t(c[1]);if(!h||h.remote)return Response.json({error:"Workspace unavailable"},{status:404});nl(h.id,o);let w=h.path;if(c[3]){let E=decodeURIComponent(c[3]);if(o.method==="GET"||o.method==="HEAD"){let _=Bun.file(await sl(w,E));return new Response(o.method==="HEAD"?null:_,{headers:{"content-type":_.type,"content-length":String(_.size),"cache-control":"no-store"}})}if(o.method==="PUT")return Response.json(await Ld(w,E,o.body??new Blob([]).stream()));if(o.method==="PATCH"){let{patch:_}=bx.parse(await o.json());return Response.json(await Ld(w,E,new ReadableStream,(I)=>Mm(I,_)))}}if(o.method!=="POST")return Response.json({error:"Method not allowed"},{status:405});if(c[2]==="commands"){let{command:E,args:_}=Sx.parse(await o.json()),I=Nm(w,E,_);Lm(I,o.signal);let[T,O,N]=await Promise.all([$m(I.stdout,I),$m(I.stderr,I),I.exited]);return Response.json({exitCode:N,stdout:T,stderr:O})}if(c[2]==="exec"){let E=wx.parse(await o.json()),_=JSON.stringify([h.id,o.headers.get("x-moi-user-id"),"cancel"in E?E.cancel:E.id]);for(let[G,oe]of i)if(oe<Date.now())i.delete(G);if("cancel"in E){i.set(_,Date.now()+60000);let G=n.get(_);if(G)ta(G);return Response.json({cancelled:!0})}if(i.has(_))throw new Et("Execution was cancelled",409);if(E.id&&n.has(_))throw new Et("Execution already exists",409);let{command:I}=E,T=Bun.spawn(["/bin/sh","-c",I],{cwd:w,stdin:"ignore",stdout:"pipe",stderr:"pipe",detached:!0});if(Lm(T,o.signal),E.id)n.set(_,T),T.exited.finally(()=>n.delete(_));let O=new TextEncoder,N=new TransformStream,L=N.writable.getWriter(),H=(G)=>L.write(O.encode(JSON.stringify(G)+`
|
|
10
|
+
`)),Z=async(G,oe)=>{let re=new TextDecoder;for await(let Oe of oe)await H({type:G,data:re.decode(Oe,{stream:!0})});let xe=re.decode();if(xe)await H({type:G,data:xe})};return L.closed.catch(()=>ta(T)),Promise.all([Z("stdout",T.stdout),Z("stderr",T.stderr),T.exited]).then(async([,,G])=>{await H({type:"exit",code:G}),await L.close()}).catch(async(G)=>{ta(T),await L.abort(G).catch(()=>{})}),new Response(N.readable,{headers:{"content-type":"application/x-ndjson","cache-control":"no-store, no-transform","content-encoding":"identity","x-content-type-options":"nosniff"}})}return Response.json({error:"Method not allowed"},{status:405})}catch(a){let c=a instanceof Et?a.status:a instanceof Js||a instanceof SyntaxError||a instanceof URIError?400:500;if(c===500)console.error("[operations]",a);return Response.json({error:a instanceof Et?a.message:c===400?"Invalid operation request":"Operation failed"},{status:c})}}}async function Um(t){await yx(t,{force:!0});let n=Bun.serve({...{unix:t},idleTimeout:0,fetch:vx()});return await gx(t,432),n}var al=void 0;import{existsSync as xx}from"fs";import{lstat as _x,rm as Ix,rmdir as Tx}from"fs/promises";import{dirname as Rx,join as Px}from"path";import{realpath as Fm}from"fs/promises";import{tmpdir as Ex}from"os";import{resolve as cl}from"path";class xi extends Error{code;constructor(t,n){super(n);this.code=t}}function Ax(t,n){if(!n||t.type!=="join"&&t.type!=="profile")return t;return t.profile.id===n.id?{...t,profile:n}:null}class qm{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 xi("restarting","Collab is restarting");t.child.send(n)}async getSlot(t,n){if(this.closed||n.closed)throw new xi("unavailable","Collab connection closed");let i=await Fm(t);if(n.workspacePaths.add(i),n.closed)throw new xi("unavailable","Collab connection closed");if(!(this.options.enabled?await this.options.enabled(i):u().environment==="cloud"))throw new xi("unavailable","Collaboration is only available in the cloud environment");if(this.closed||n.closed)throw new xi("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(cl(t)),a}let c=this.failures.get(i);if(c&&c.retryAfter>Date.now())throw new xi("restarting","Collab is recovering; reconnect shortly");let h=this.spawn(i);return h.workspacePaths.add(cl(t)),h}spawn(t){let n=()=>{},i=()=>{},o=new Promise((h,w)=>{n=h,i=w});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 xi("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??ge("collab/worker.ts")],{cwd:Ex(),env:{PATH:process.env.PATH,MOI_COLLAB_WORKSPACE:t,MOI_COLLAB_GENERATION:a},stdout:"inherit",stderr:"inherit",ipc:(h)=>this.receive(c,h),onExit:()=>this.exited(c)}),this.slots.set(t,c)}catch(h){throw clearTimeout(c.readyTimer),i(h instanceof Error?h:Error("Collab could not start")),h}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,rl(i.workspaceId))}return}}exited(t){let n=t.stopping;if(t.stopping=!0,clearTimeout(t.readyTimer),t.idleTimer)clearTimeout(t.idleTimer);let i=new xi("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 xi("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([cl(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 h=c.joined?this.options.livenessTimeoutMs??60000:15000;if(a-c.lastSeen>h)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)>es){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(!ts(a)){this.emit(i,{type:"error",code:"invalid_message",message:"Invalid collab message"});return}i.lastSeen=Date.now();let c=Ax(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=cl(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 Fm(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 Ro=new qm;async function ll(t){y(t).stopWorkspace?.(t.path),await Ro.stopWorkspace(t.path)}async function Bd(t,n){let i=await ui(t,n,Ls);if(i.status==="updated"){if(n)await ll(i.entry);m({type:"workspaces-list:changed"})}return i}async function Ud(t){await Tx(t).catch((n)=>{if(!["ENOENT","ENOTEMPTY","EEXIST"].includes(n.code))throw n})}function Fd(t){return _x(t).catch((n)=>{if(n.code!=="ENOENT")throw n;return})}async function Cx(t){if((await Fd(t.path))?.isSymbolicLink())return;let i=Px(t.path,".moi");if(t.remote){if(xx(i)&&!ne((await A(t.path)).remote,t.remote))return;await ll(t)}await ms(t.path);for(let o of Vi(t.path,t.harness)){let a=Rx(o),c=await Fd(a);if(c&&!c.isDirectory())continue;let h=await Fd(o);if(h&&!h.isDirectory())continue;if(await Ki(o),await Ud(o),a!==t.path)await Ud(a)}await Ix(i,{recursive:!0,force:!0}),await Ud(t.path)}async function Wm(t){for(let n of t)try{await Cx(n),await xs(n.id),await fi(n.id)}catch(i){console.warn(`Could not finish deleting workspace ${n.id}; it will be retried`,i)}}async function Wd(t){let n=await di(t);if(n.length)m({type:"workspaces-list:changed"});await Wm(n)}var qd;function Bm(t=new Date){return qd??=pi(t).then(Wm).finally(()=>qd=void 0),qd}var Ox=86400000;function Hm(){if(u().environment!=="cloud")return;Bm(),setInterval(()=>void Bm(),Ox).unref?.()}var Vm=new Ie;async function Hd(t,n){let i=t&&B(t);return Vm.runExclusive(async()=>{let o=await k(),a=i&&o.find((_)=>ne(_.remote,i));if(a){if(!n||a.harness)return a;return await nt(a.id,n),{...a,harness:n}}let c=new Map;for(let{id:_,owner:I}of await tt())c.set(mt(_,I.id),{workspace_id:_,user_id:I.id});let h=new Map(c),w=[];for(let _ of o){if(!_.remote)continue;let I=mt(_.remote.workspace_id,_.remote.user_id);if(c.has(I))h.delete(I);else w.push(_)}await Wd(w);let E;for(let _ of h.values()){let I=i&&ne(_,i);try{let T=await Ai(_,I?n:void 0);if(m({type:"workspaces-list:changed"}),I)E=T}catch(T){if(I)throw T;console.warn("Could not create remote workspace reference",_,T)}}return E})}function zm(t,n){return Vm.runExclusive(async()=>{let i=await W(t);if(!i)return;if(!ne(i.remote,n))throw Error("Workspace reference changed");await Zt(n.user_id,n.workspace_id),await Wd([i])})}function ul(){if(u().environment!=="cloud")return;return Hd().catch((t)=>{if(!(t instanceof ee))console.warn("Remote workspace sync failed",t)})}function Gm(){if(u().environment!=="cloud")return;ul(),setInterval(ul,3600000).unref()}import{basename as $P}from"path";import LP from"sharp";function kx(){if(globalThis.__TLDRAW_LIBRARY_VERSIONS__)return globalThis.__TLDRAW_LIBRARY_VERSIONS__;let t={versions:[],didWarn:!1,scheduledNotice:null};return Object.defineProperty(globalThis,"__TLDRAW_LIBRARY_VERSIONS__",{value:t,writable:!1,configurable:!1,enumerable:!1}),t}function ei(t,n,i){if(!t||!n||!i)throw Error("Missing name/version/module system in built version of tldraw library");let o=kx();if(Nx()){if(o.versions.some((c)=>c.name===t&&c.version===n&&c.modules===i))return}if(o.versions.push({name:t,version:n,modules:i}),!o.scheduledNotice)try{o.scheduledNotice=setTimeout(()=>{o.scheduledNotice=null,Km(o)},100)}catch{Km(o)}}function Km(t){if(!t.versions.length)return;if(t.didWarn)return;let n=t.versions.sort((w,E)=>Jm(w.version,E.version)),i=n[n.length-1].version,o=new Set,a=new Map;for(let w of n){if(a.has(w.name)){o.delete(w.name),Vd(a,w.name,new Set).add(w.version);continue}if(w.version===i)o.add(w.name);else o.delete(w.name),Vd(a,w.name,new Set).add(w.version)}if(a.size>0){let w=[`${rs("[tldraw]",["bold","bgRed","textWhite"])} ${rs("You have multiple versions of tldraw libraries installed. This can lead to bugs and unexpected behavior.",["textRed","bold"])}`,"",`The latest version you have installed is ${rs(`v${i}`,["bold","textBlue"])}. The following libraries are on the latest version:`,...Array.from(o,(E)=>` \u2022 \u2705 ${rs(E,["bold"])}`),"","The following libraries are not on the latest version, or have multiple versions installed:",...Array.from(a,([E,_])=>{let I=Array.from(_).sort(Jm).map((T)=>rs(`v${T}`,T===i?["textGreen"]:["textRed"]));return` \u2022 \u274C ${rs(E,["bold"])} (${I.join(", ")})`})];console.log(w.join(`
|
|
11
|
+
`)),t.didWarn=!0;return}let c=new Map;for(let w of n)Vd(c,w.name,{version:w.version,modules:[]}).modules.push(w.modules);let h=new Map;for(let[w,E]of c)if(E.modules.length>1)h.set(w,E);if(h.size>0){let w=[`${rs("[tldraw]",["bold","bgRed","textWhite"])} ${rs("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(h,([E,_])=>{let I=_.modules.map((T,O)=>T==="esm"?` ${O+1}. ES Modules`:` ${O+1}. CommonJS`).join(`
|
|
12
|
+
`);return` \u2022 \u274C ${rs(E,["bold"])} v${_.version}:
|
|
13
|
+
${I}`}),"","You should configure your bundler to only import one version of each library."];console.log(w.join(`
|
|
14
|
+
`)),t.didWarn=!0;return}}function Jm(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 Mx={bold:"1",textBlue:"94",textRed:"31",textGreen:"32",bgRed:"41",textWhite:"97"};function rs(t,n=[]){return`\x1B[${n.map((i)=>Mx[i]).join(";")}m${t}\x1B[m`}function Nx(){try{return"__NEXT_DATA__"in globalThis}catch{return!1}}function Vd(t,n,i){if(t.has(n))return t.get(n);return t.set(n,i),i}var fo=g(Cg(),1),h1=g(yf(),1),m1=g(fy(),1);function xf(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 $l(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 br={ok(t){return{ok:!0,value:t}},err(t){return{ok:!1,error:t}},all(t){return t.every((n)=>n.ok)?br.ok(t.map((n)=>n.value)):br.err(t.find((n)=>!n.ok)?.error)}};function rc(t,n){let i=n&&t&&typeof t==="object"&&n in t?t[n]:t;throw Error(`Unknown switch case ${i}`)}var Ve=$l((t,n)=>{if(!t)throw Error(n||"Assertion Error")}),_R=$l((t,n)=>{if(t==null)throw Error(n??"value must be defined");return t});/*!
|
|
15
|
+
* MIT License: https://github.com/NoHomey/bind-decorator/blob/master/License
|
|
16
|
+
* Copyright (c) 2016 Ivo Stratev
|
|
17
|
+
*/class Ll{items=new WeakMap;get(t,n){if(!this.items.has(t))this.items.set(t,n(t));return this.items.get(t)}}var py=new WeakMap;function _f(t,n){if(typeof t!=="object"||t===null)return;let i=py.get(t);if(!i)i={tags:{},extras:{}},py.set(t,i);if(n.tags)i.tags={...i.tags,...n.tags};if(n.extras)i.extras={...i.extras,...n.extras}}/*!
|
|
18
|
+
* MIT License: https://github.com/ai/nanoid/blob/main/LICENSE
|
|
19
|
+
* Modified code originally from <https://github.com/ai/nanoid>
|
|
20
|
+
* Copyright 2017 Andrey Sitnik <andrey@sitnik.ru>
|
|
21
|
+
*
|
|
22
|
+
* `nanoid` is currently only distributed as an ES module. Some tools (jest, playwright) don't
|
|
23
|
+
* properly support ESM-only code yet, and tldraw itself is distributed as both an ES module and a
|
|
24
|
+
* CommonJS module. By including nanoid here, we can make sure it works well in every environment
|
|
25
|
+
* where tldraw is used. We can also remove some unused features like custom alphabets.
|
|
26
|
+
*/var my=globalThis.crypto;var Lo,ua;function RR(t){if(!Lo||Lo.length<t)Lo=new Uint8Array(t*128),my.getRandomValues(Lo),ua=0;else if(ua+t>Lo.length)my.getRandomValues(Lo),ua=0;ua+=t}function PR(t=21){RR(t-=0);let n="";for(let i=ua-t;i<ua;i++)n+="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict"[Lo[i]&63];return n}var CR=PR;function Ti(t){return CR(t)}/*!
|
|
27
|
+
* MIT License: https://github.com/vHeemstra/is-apng/blob/main/license
|
|
28
|
+
* Copyright (c) Philip van Heemstra
|
|
29
|
+
*//*!
|
|
30
|
+
* MIT License
|
|
31
|
+
* Modified code originally from <https://github.com/qzb/is-animated>
|
|
32
|
+
* Copyright (c) 2016 Józef Sokołowski <j.k.sokolowski@gmail.com>
|
|
33
|
+
*//*!
|
|
34
|
+
* MIT License: https://github.com/alexgorbatchev/crc/blob/master/LICENSE
|
|
35
|
+
* Copyright: 2014 Alex Gorbatchev
|
|
36
|
+
* Code: crc32, https://github.com/alexgorbatchev/crc/blob/master/src/calculators/crc32.ts
|
|
37
|
+
*/var gy=[0,1996959894,3993919788,2567524794,124634137,1886057615,3915621685,2657392035,249268274,2044508324,3772115230,2547177864,162941995,2125561021,3887607047,2428444049,498536548,1789927666,4089016648,2227061214,450548861,1843258603,4107580753,2211677639,325883990,1684777152,4251122042,2321926636,335633487,1661365465,4195302755,2366115317,997073096,1281953886,3579855332,2724688242,1006888145,1258607687,3524101629,2768942443,901097722,1119000684,3686517206,2898065728,853044451,1172266101,3705015759,2882616665,651767980,1373503546,3369554304,3218104598,565507253,1454621731,3485111705,3099436303,671266974,1594198024,3322730930,2970347812,795835527,1483230225,3244367275,3060149565,1994146192,31158534,2563907772,4023717930,1907459465,112637215,2680153253,3904427059,2013776290,251722036,2517215374,3775830040,2137656763,141376813,2439277719,3865271297,1802195444,476864866,2238001368,4066508878,1812370925,453092731,2181625025,4111451223,1706088902,314042704,2344532202,4240017532,1658658271,366619977,2362670323,4224994405,1303535960,984961486,2747007092,3569037538,1256170817,1037604311,2765210733,3554079995,1131014506,879679996,2909243462,3663771856,1141124467,855842277,2852801631,3708648649,1342533948,654459306,3188396048,3373015174,1466479909,544179635,3110523913,3462522015,1591671054,702138776,2966460450,3352799412,1504918807,783551873,3082640443,3233442989,3988292384,2596254646,62317068,1957810842,3939845945,2647816111,81470997,1943803523,3814918930,2489596804,225274430,2053790376,3826175755,2466906013,167816743,2097651377,4027552580,2265490386,503444072,1762050814,4150417245,2154129355,426522225,1852507879,4275313526,2312317920,282753626,1742555852,4189708143,2394877945,397917763,1622183637,3604390888,2714866558,953729732,1340076626,3518719985,2797360999,1068828381,1219638859,3624741850,2936675148,906185462,1090812512,3747672003,2825379669,829329135,1181335161,3412177804,3160834842,628085408,1382605366,3423369109,3138078467,570562233,1426400815,3317316542,2998733608,733239954,1555261956,3268935591,3050360625,752459403,1541320221,2607071920,3965973030,1969922972,40735498,2617837225,3943577151,1913087877,83908371,2512341634,3803740692,2075208622,213261112,2463272603,3855990285,2094854071,198958881,2262029012,4057260610,1759359992,534414190,2176718541,4139329115,1873836001,414664567,2282248934,4279200368,1711684554,285281116,2405801727,4167216745,1634467795,376229701,2685067896,3608007406,1308918612,956543938,2808555105,3495958263,1231636301,1047427035,2932959818,3654703836,1088359270,936918000,2847714899,3736837829,1202900863,817233897,3183342108,3401237130,1404277552,615818150,3134207493,3453421203,1423857449,601450431,3009837614,3294710456,1567103746,711928724,3020668471,3272380065,1510334235,755167117];if(typeof Int32Array<"u")gy=new Int32Array(gy);/*!
|
|
38
|
+
* MIT License: https://github.com/sindresorhus/is-webp/blob/main/license
|
|
39
|
+
* Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (https://sindresorhus.com)
|
|
40
|
+
*/var NR=Object.freeze(["image/svg+xml"]),DR=Object.freeze(["image/jpeg","image/png","image/webp"]),$R=Object.freeze(["image/gif","image/apng","image/avif"]),yy=Object.freeze([...DR,...NR,...$R]),wy=Object.freeze(["video/mp4","video/webm","video/quicktime"]),Sy=Object.freeze([...yy,...wy]),LR=Sy.join(",");var jR=g(yf(),1);function Bt(t,n){return Object.prototype.hasOwnProperty.call(t,n)}function dr(t,n){if(!Bt(t,n))return;return t[n]}function If(t){return Object.keys(t)}function Ri(t){return Object.values(t)}function Pn(t){return Object.entries(t)}function nc(t){return Object.fromEntries(t)}function da(t,n){let i={},o=!1;for(let a in t){if(!Object.prototype.hasOwnProperty.call(t,a))continue;let c=t[a];if(n(a,c))i[a]=c;else o=!0}return o?i:t}function Ci(t,n){let i={};for(let o in t){if(!Object.prototype.hasOwnProperty.call(t,o))continue;i[o]=n(o,t[o])}return i}var by={Good:"#40C057",Mid:"#FFC078",Poor:"#E03131"},UR=by.Good;var Ey="A"+"0".repeat(26);function FR(t){if(t>="a"&&t<="z")return t.charCodeAt(0)-97+2;else if(t>="A"&&t<="Z")return 90-t.charCodeAt(0)+2;throw Error("invalid order key head: "+t)}function ic(t){let n=FR(t[0]);if(n>t.length)throw Error("invalid order key: "+t);return t.slice(0,n)}function jl(t){let n=t.charCodeAt(0);if(n<=57)return n-48;if(n<=90)return n-55;return n-61}function Ul(t){if(t===Ey)throw Error("invalid order key: "+t);let n=ic(t);if(t.length>n.length&&t[t.length-1]==="0")throw Error("invalid order key: "+t)}function fa(t,n){if(n!=null&&t>=n)throw Error(t+" >= "+n);if(t.slice(-1)==="0"||n&&n.slice(-1)==="0")throw Error("trailing zero");if(n){let a=0;while((t[a]||"0")===n[a])a++;if(a>0)return n.slice(0,a)+fa(t.slice(a),n.slice(a))}let i=t?jl(t[0]):0,o=n!=null?jl(n[0]):62;if(o-i>1)return"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"[Math.round(0.5*(i+o))];if(n&&n.length>1)return n.slice(0,1);return"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"[i]+fa(t.slice(1),null)}function vy(t){let[n,...i]=t.split(""),o=!0;for(let a=i.length-1;o&&a>=0;a--){let c=jl(i[a])+1;if(c===62)i[a]="0";else i[a]="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"[c],o=!1}if(o){if(n==="Z")return"a0";if(n==="z")return null;let a=String.fromCharCode(n.charCodeAt(0)+1);if(a>"a")i.push("0");else i.pop();return a+i.join("")}return n+i.join("")}function qR(t){let[n,...i]=t.split(""),o=!0;for(let a=i.length-1;o&&a>=0;a--){let c=jl(i[a])-1;if(c===-1)i[a]="z";else i[a]="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"[c],o=!1}if(o){if(n==="a")return"Zz";if(n==="A")return null;let a=String.fromCharCode(n.charCodeAt(0)-1);if(a<"Z")i.push("z");else i.pop();return a+i.join("")}return n+i.join("")}function uo(t,n){if(t!=null&&n!=null&&t>=n)throw Error(t+" >= "+n);if(t==null){if(n==null)return"a0";let w=ic(n),E=n.slice(w.length);if(w===Ey)return w+fa("",E);if(w<n)return w;let _=qR(w);if(_==null)throw Error("cannot decrement any more");return _}if(n==null){let w=ic(t),E=t.slice(w.length),_=vy(w);return _==null?w+fa(E,null):_}let i=ic(t),o=t.slice(i.length),a=ic(n),c=n.slice(a.length);if(i===a)return i+fa(o,c);let h=vy(i);if(h==null)throw Error("cannot increment any more");if(h<n)return h;return i+fa(o,null)}function Tf(t,n,i){if(i===0)return[];if(i===1)return[uo(t,n)];if(n==null){let c=uo(t,n),h=[c];for(let w=0;w<i-1;w++)c=uo(c,n),h.push(c);return h}if(t==null){let c=uo(t,n),h=[c];for(let w=0;w<i-1;w++)c=uo(t,c),h.push(c);return h.reverse(),h}let o=Math.floor(i/2),a=uo(t,n);return[...Tf(t,a,o),a,...Tf(a,n,i-o-1)]}function BR(t,n){let i=uo(t,n);for(let o=0;o<16;o++){if(Math.random()<0.5)t=i;else n=i;i=uo(t,n)}return i}function Ay(t,n,i){if(i===0)return[];if(t!=null)Ul(t);if(n!=null)Ul(n);let o=Tf(t,n,i+1),a=Array(i);for(let c=0;c<i;c++)a[c]=BR(o[c],o[c+1]);return a}var xy=Ay,Rf="a0";function Pf(t){try{Ul(t)}catch{throw Error("invalid index: "+t)}}function Cf(t=null){return xy(t,null,1)[0]}function Fl(t,n="a1"){return[n,...xy(n,null,t)]}function jo(t,n){if(t.index<n.index)return-1;else if(t.index>n.index)return 1;return 0}var o1=g(Py(),1),Cy=()=>typeof process<"u"&&!1,a1=0.9,Oy=(t)=>Math.floor(1000/t)*a1;class kf{targetFps;targetTimePerFrame;fpsQueue=[];frameRaf;flushRaf;lastFlushTime;constructor(t=120){this.targetFps=t,this.targetTimePerFrame=Oy(t),this.lastFlushTime=-this.targetTimePerFrame}updateTargetFps(t){if(t===this.targetFps)return;this.targetFps=t,this.targetTimePerFrame=Oy(t),this.lastFlushTime=-this.targetTimePerFrame}flush(){let t=this.fpsQueue.splice(0,this.fpsQueue.length);for(let n of t)n()}tick(t=!1){if(this.frameRaf)return;let n=Date.now();if(n-this.lastFlushTime<this.targetTimePerFrame){this.frameRaf=requestAnimationFrame(()=>{this.frameRaf=void 0,this.tick(!0)});return}if(t){if(this.flushRaf)return;this.lastFlushTime=n,this.flush()}else{if(this.flushRaf)return;this.flushRaf=requestAnimationFrame(()=>{this.flushRaf=void 0,this.lastFlushTime=Date.now(),this.flush()})}}fpsThrottle(t){if(Cy())return t.cancel=()=>{if(this.frameRaf)cancelAnimationFrame(this.frameRaf),this.frameRaf=void 0;if(this.flushRaf)cancelAnimationFrame(this.flushRaf),this.flushRaf=void 0},t;let n=()=>{if(this.fpsQueue.includes(t))return;this.fpsQueue.push(t),this.tick()};return n.cancel=()=>{let i=this.fpsQueue.indexOf(t);if(i>-1)this.fpsQueue.splice(i,1)},n}throttleToNextFrame(t){if(Cy())return t(),()=>{return};if(!this.fpsQueue.includes(t))this.fpsQueue.push(t),this.tick();return()=>{let n=this.fpsQueue.indexOf(t);if(n>-1)this.fpsQueue.splice(n,1)}}}var c1=new kf(120);function Mf(t){return c1.throttleToNextFrame(t)}function fr(t,n){try{return new URL(t,n)}catch{return}}function l1(){if(typeof globalThis<"u"&&globalThis.structuredClone)return[globalThis.structuredClone,!0];if(typeof global<"u"&&global.structuredClone)return[global.structuredClone,!0];if(typeof window<"u"&&window.structuredClone)return[window.structuredClone,!0];return[(t)=>t?JSON.parse(JSON.stringify(t)):t,!1]}var ky=l1(),an=ky[0],u1=ky[1],sc=Object.getPrototypeOf(an({}));var My=new Set;function Nf(t){if(My.has(t))return;My.add(t),console.warn(`[tldraw] ${t}`)}ei("@tldraw/utils","5.6.2","esm");function Ny(t){return t&&typeof t==="object"&&"parents"in t}function oc(t){for(let n=0,i=t.parents.length;n<i;n++){let o=t.parents[n];if(o.__unsafe__getWithoutCapture(!0),o.lastChangedEpoch!==t.parentEpochs[n])return!0}return!1}function pa(t,n){if(!t.children.remove(n))return;if(t.children.isEmpty&&Ny(t))for(let i=0,o=t.parents.length;i<o;i++)pa(t.parents[i],t)}function ac(t,n){if(!t.children.add(n))return;if(Ny(t))for(let i=0,o=t.parents.length;i<o;i++)ac(t.parents[i],t)}function Bl(t,n){return t===n||Object.is(t,n)||Boolean(t&&n&&typeof t.equals==="function"&&t.equals(n))}function cn(t,n){let i=Symbol.for(`com.tldraw.state/${t}`),o=globalThis;return o[i]??=n(),o[i]}var Os=cn("empty_array",()=>Object.freeze([]));class ks{set=null;array=null;arraySize=0;get isEmpty(){if(this.set)return this.set.size===0;return this.arraySize===0}add(t){if(this.set){if(this.set.has(t))return!1;return this.set.add(t),!0}if(!this.array)this.array=Array(8);else if(this.array.indexOf(t)!==-1)return!1;if(this.arraySize<8)return this.array[this.arraySize]=t,this.arraySize++,!0;return this.set=new Set(this.array),this.set.add(t),this.array=null,this.arraySize=0,!0}remove(t){if(this.set)return this.set.delete(t);if(!this.array)return!1;let n=this.array.indexOf(t);if(n===-1)return!1;return this.arraySize--,this.array[n]=this.array[this.arraySize],this.array[this.arraySize]=void 0,!0}visit(t){if(this.set){this.set.forEach(t);return}if(!this.array)return;for(let n=0;n<this.arraySize;n++)t(this.array[n])}*[Symbol.iterator](){if(this.set)yield*this.set;else if(this.array)for(let t=0;t<this.arraySize;t++)yield this.array[t]}has(t){if(this.set)return this.set.has(t);return this.array?this.array.indexOf(t)!==-1:!1}clear(){if(this.set)this.set.clear();else if(this.array)this.array.fill(void 0,0,this.arraySize),this.arraySize=0}size(){if(this.set)return this.set.size;return this.arraySize}}function cc(t){return!!(t&&t.__isComputed===!0)}class Dy{constructor(t,n){this.below=t,this.child=n}below;child;offset=0;maybeRemoved}var lc=cn("capture",()=>({stack:null}));function Wl(t){if(lc.stack=new Dy(lc.stack,t),t.__debug_ancestor_epochs__){let n=t.__debug_ancestor_epochs__;t.__debug_ancestor_epochs__=null;for(let i of t.parents)i.__unsafe__getWithoutCapture(!0);g1(t,n)}t.parentSet.clear()}function Hl(){let t=lc.stack;lc.stack=t.below;let{child:n,offset:i,maybeRemoved:o}=t;if(i<n.parents.length){for(let a=i;a<n.parents.length;a++){let c=n.parents[a];if(!n.parentSet.has(c))pa(c,n)}n.parents.length=i,n.parentEpochs.length=i}if(o)for(let a=0;a<o.length;a++){let c=o[a];if(!n.parentSet.has(c))pa(c,n)}if(n.__debug_ancestor_epochs__)$y(n,n.__debug_ancestor_epochs__)}function ha(t){let n=lc.stack;if(!n)return;let{child:i}=n;if(!i.parentSet.add(t))return;if(i.isActivelyListening)ac(t,i);if(n.offset<i.parents.length){let o=i.parents[n.offset];if(o!==t)if(!n.maybeRemoved)n.maybeRemoved=[o];else n.maybeRemoved.push(o)}i.parents[n.offset]=t,i.parentEpochs[n.offset]=t.lastChangedEpoch,n.offset++}function $y(t,n){for(let i=0;i<t.parents.length;i++){let o=t.parents[i];if(n.set(o,t.parentEpochs[i]),cc(o))$y(o,n)}}function Ly(t,n){let i={};for(let o=0;o<t.parents.length;o++){let a=t.parents[o];if(!n.has(a))continue;if(a.lastChangedEpoch!==n.get(a))if(cc(a))i[a.name]=Ly(a,n);else i[a.name]=null}return i}function g1(t,n){let i=Ly(t,n);if(Object.keys(i).length===0){console.log(`Effect(${t.name}) was executed manually.`);return}let o=cc(t)?`Computed(${t.name}) is recomputing because:`:`Effect(${t.name}) is executing because:`;function a(c,h){let w=`
|
|
41
|
+
`+" ".repeat(h)+"\u21B3 ";for(let[E,_]of Object.entries(c))if(_)o+=`${w}Computed(${E}) changed`,a(_,h+2);else o+=`${w}Atom(${E}) changed`}a(i,1),console.log(o)}var Tr=Symbol.for("com.tldraw.state/RESET_VALUE");class uc{constructor(t){this.capacity=t,this.buffer=Array(t)}capacity;index=0;buffer;pushEntry(t,n,i){if(i===Tr||i===void 0){this.clear();return}this.buffer[this.index]=[t,n,i],this.index=(this.index+1)%this.capacity}clear(){this.index=0,this.buffer.fill(void 0)}getChangesSince(t){let{index:n,capacity:i,buffer:o}=this;for(let a=0;a<i;a++){let c=(n-1+i-a)%i,h=o[c];if(!h)return Tr;let[w,E]=h;if(a===0&&t>=E)return Os;if(w<=t&&t<E){let _=a+1,I=Array(_);for(let T=0;T<_;T++)I[T]=o[(c+T)%i][2];return I}}return Tr}}var ii=-1;class jy{constructor(t,n){this.parent=t,this.isSync=n}parent;isSync;asyncProcessCount=0;initialAtomValues=new Map;commit(){if(this.parent===null){Fy(this.initialAtomValues.keys());return}let t=this.parent.initialAtomValues;if(t.size===0){this.parent.initialAtomValues=this.initialAtomValues;return}this.initialAtomValues.forEach((n,i)=>{if(!t.has(i))t.set(i,n)})}abort(){ft.globalEpoch++,this.initialAtomValues.forEach((t,n)=>{n.set(t),n.historyBuffer?.clear()}),this.commit()}}var ft=cn("transactions",()=>({globalEpoch:ii+1,globalIsReacting:!1,currentTransaction:null,cleanupReactors:null}));function yn(){return ft.globalEpoch}function Uy(){return ft.currentTransaction!==null}var Vl;function Df(t){if(t.lastTraversedEpoch===ft.globalEpoch)return;if(t.lastTraversedEpoch=ft.globalEpoch,"__isEffectScheduler"in t)Vl.add(t);else t.children.visit(Df)}function Fy(t){if(ft.globalIsReacting){for(let i of t)y1(i);return}let n=ft.currentTransaction;try{ft.currentTransaction=null,ft.globalIsReacting=!0;let i=new Set;Vl=i;for(let a of t)a.children.visit(Df);for(let a of i)a.maybeScheduleEffect();let o=0;while(ft.cleanupReactors?.size){if(o++>1000)throw Error("Reaction update depth limit exceeded");let a=ft.cleanupReactors;ft.cleanupReactors=null;for(let c of a)c.maybeScheduleEffect()}}finally{ft.cleanupReactors=null,ft.globalIsReacting=!1,ft.currentTransaction=n,Vl=void 0}}function qy(t,n){if(ft.currentTransaction){if(!ft.currentTransaction.initialAtomValues.has(t))ft.currentTransaction.initialAtomValues.set(t,n)}else Fy([t])}function y1(t){Vl=ft.cleanupReactors??=new Set,t.children.visit(Df)}function By(){ft.globalEpoch++}function Wy(t){let n=new jy(ft.currentTransaction,!0);ft.currentTransaction=n;try{let i=void 0,o=!1;try{i=t(()=>o=!0)}catch(a){throw n.abort(),a}if(ft.currentTransaction!==n)throw Error("Transaction boundaries overlap");if(o)n.abort();else n.commit();return i}finally{ft.currentTransaction=n.parent}}function po(t){if(ft.currentTransaction)return t();return Wy(t)}class Hy{constructor(t,n,i){if(this.name=t,this.current=n,this.isEqual=i?.isEqual??Bl,i?.historyLength)this.historyBuffer=new uc(i.historyLength);this.computeDiff=i?.computeDiff}name;current;isEqual;computeDiff;lastChangedEpoch=yn();children=new ks;historyBuffer;__unsafe__getWithoutCapture(t){return this.current}get(){return ha(this),this.current}set(t,n){if(this.isEqual(this.current,t))return this.current;let i;if(this.historyBuffer)i=n!==void 0?n:this.computeDiff?this.computeDiff(this.current,t,this.lastChangedEpoch,yn()+1):Tr;By();let o=yn();if(this.historyBuffer)this.historyBuffer.pushEntry(this.lastChangedEpoch,o,i);this.lastChangedEpoch=o;let a=this.current;return this.current=t,qy(this,a),t}update(t){return this.set(t(this.current))}getDiffSince(t){if(ha(this),t>=this.lastChangedEpoch)return Os;return this.historyBuffer?.getChangesSince(t)??Tr}}var Vy=cn("Atom",()=>Hy);function ho(t,n,i){return new Vy(t,n,i)}function zy(){Nf(`Using \`@computed\` as a decorator for getters is deprecated and will be removed in the near future. Please refactor to use \`@computed\` as a decorator for methods.
|
|
42
|
+
|
|
43
|
+
// Before
|
|
44
|
+
@computed
|
|
45
|
+
get foo() {
|
|
46
|
+
return 'foo'
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
// After
|
|
50
|
+
@computed
|
|
51
|
+
getFoo() {
|
|
52
|
+
return 'foo'
|
|
53
|
+
}
|
|
54
|
+
`)}var Wt=Symbol.for("com.tldraw.state/UNINITIALIZED");function Ns(t){return t===Wt}var Lf=cn("WithDiff",()=>class{constructor(n,i){this.value=n,this.diff=i}value;diff});function ma(t,n){return new Lf(t,n)}class Ky{constructor(t,n,i){if(this.name=t,this.derive=n,i?.historyLength)this.historyBuffer=new uc(i.historyLength);this.computeDiff=i?.computeDiff,this.isEqual=i?.isEqual??Bl}name;derive;__isComputed=!0;lastChangedEpoch=ii;lastTraversedEpoch=ii;__debug_ancestor_epochs__=null;lastCheckedEpoch=ii;parentSet=new ks;parents=[];parentEpochs=[];children=new ks;get isActivelyListening(){return!this.children.isEmpty}historyBuffer;state=Wt;error=null;computeDiff;isEqual;__unsafe__getWithoutCapture(t){let n=this.lastChangedEpoch===ii,i=yn();if(!n&&(this.lastCheckedEpoch===i||this.isActivelyListening&&!Uy()&&this.lastTraversedEpoch<=this.lastCheckedEpoch||!oc(this)))if(this.lastCheckedEpoch=i,this.error)if(!t)throw this.error.thrownValue;else return this.state;else return this.state;try{Wl(this);let o=this.derive(this.state,this.lastCheckedEpoch),a=o instanceof Lf?o.value:o,c=this.state===Wt,h=yn();if(c||!this.isEqual(this.state,a)){if(this.historyBuffer&&!c){let w=o instanceof Lf?o.diff:void 0;this.historyBuffer.pushEntry(this.lastChangedEpoch,h,w!==void 0?w:this.computeDiff?this.computeDiff(this.state,a,this.lastCheckedEpoch,h):Tr)}this.lastChangedEpoch=h,this.state=a}return this.error=null,this.lastCheckedEpoch=h,this.state}catch(o){let a=yn();if(this.error===null)this.state=Wt,this.lastChangedEpoch=a;if(this.lastCheckedEpoch=a,this.historyBuffer)this.historyBuffer.clear();if(this.error={thrownValue:o},!t)throw o;return this.state}finally{Hl()}}get(){try{return this.__unsafe__getWithoutCapture()}finally{ha(this)}}getDiffSince(t){if(this.__unsafe__getWithoutCapture(!0),ha(this),t>=this.lastChangedEpoch)return Os;return this.historyBuffer?.getChangesSince(t)??Tr}}var jf=cn("Computed",()=>Ky),w1="@@__computedDerivationKey__@@";function $f(t,n,i){let o=Symbol("__@tldraw/state__computed__"+t),a=function(){let c=this[o];if(!c)c=new jf(t,n.bind(this),i),Object.defineProperty(this,o,{enumerable:!1,configurable:!1,writable:!1,value:c});return c.get()};return a[w1]=o,a}function Gy(t={},n){if(n.length===2){let[i,o]=n;return Ve(o.kind==="method","@computed can only be used on methods"),$f(String(o.name),i,t)}else{let[i,o,a]=n;if(a.get)zy(),a.get=$f(o,a.get,t);else a.value=$f(o,a.value,t);return a}}function Sn(){if(arguments.length<=1){let t=arguments[0];return(...n)=>Gy(t,n)}else if(typeof arguments[0]==="string")return new jf(arguments[0],arguments[1],arguments[2]);else return Gy(void 0,arguments)}class Jy{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=ii;lastReactedEpoch=ii;_scheduleCount=0;_executeDepth=0;_wasScheduledWhileExecuting=!1;__debug_ancestor_epochs__=null;get scheduleCount(){return this._scheduleCount}parentSet=new ks;parentEpochs=[];parents=[];_scheduleEffect;maybeScheduleEffect(){if(!this._isActivelyListening)return;if(this.lastReactedEpoch===yn())return;if((this.lastReactedEpoch!==ii||this.parents.length>0)&&!oc(this)){this.lastReactedEpoch=yn();return}this.scheduleEffect()}scheduleEffect(){if(this._scheduleCount++,this._scheduleEffect)this._scheduleEffect(this.maybeExecute);else this.maybeExecute()}maybeExecute=()=>{if(!this._isActivelyListening)return;if(this._executeDepth>0){this._wasScheduledWhileExecuting=!0;return}this.execute()};attach(){this._isActivelyListening=!0;for(let t=0,n=this.parents.length;t<n;t++){let i=this.parents[t];i.__unsafe__getWithoutCapture(!0),ac(i,this)}}detach(){this._isActivelyListening=!1;for(let t=0,n=this.parents.length;t<n;t++)pa(this.parents[t],this)}execute(){if(this._executeDepth>0)return this.executeOnce();this._wasScheduledWhileExecuting=!1;let t=this.executeOnce();for(let n=0;this._wasScheduledWhileExecuting;n++){if(this._wasScheduledWhileExecuting=!1,n>=1000)throw Error("Reaction update depth limit exceeded");if(!this._isActivelyListening)break;if(!oc(this)){this.lastReactedEpoch=yn();break}t=this.executeOnce()}return t}executeOnce(){this._executeDepth++;try{Wl(this);let t=yn(),n=this.runEffect(this.lastReactedEpoch);return this.lastReactedEpoch=t,n}finally{Hl(),this._executeDepth--}}}var Yy=cn("EffectScheduler",()=>Jy);function Uf(t,n,i){let o=new Yy(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 Xy=1,b1=cn("apiVersion",()=>Xy);if(b1!==Xy)throw Error("You have multiple incompatible versions of @tldraw/state in your app. Please deduplicate the package.");ei("@tldraw/state","5.6.2","esm");/*!
|
|
55
|
+
* This file was lovingly and delicately extracted from Immutable.js
|
|
56
|
+
* MIT License: https://github.com/immutable-js/immutable-js/blob/main/LICENSE
|
|
57
|
+
* Copyright (c) 2014-present, Lee Byron and other contributors.
|
|
58
|
+
*/function Hf(t){return t>>>1&1073741824|t&3221225471}var v1=Object.prototype.valueOf;function Fo(t){if(t==null)return Zy(t);if(typeof t.hashCode==="function")return Hf(t.hashCode(t));let n=I1(t);if(n==null)return Zy(n);switch(typeof n){case"boolean":return n?1108378657:1108378656;case"number":return E1(n);case"string":return A1(n);case"object":case"function":return _1(n);case"symbol":return x1(n);default:if(typeof n.toString==="function")return aw(n.toString());throw Error("Value type "+typeof n+" cannot be hashed.")}}function Zy(t){return t===null?1108378658:1108378659}function E1(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 Hf(n)}function A1(t){let n=qf[t];if(n===void 0){if(n=aw(t),Bf===T1)Bf=0,qf=Object.create(null);qf[t]=n,Bf++}return n}function aw(t){let n=0;for(let i=0;i<t.length;i++)n=31*n+t.charCodeAt(i)|0;return Hf(n)}function x1(t){let n=ew[t];if(n!==void 0)return n;return n=cw(),ew[t]=n,n}function _1(t){let n=Qy.get(t);if(n!==void 0)return n;return n=cw(),Qy.set(t,n),n}function I1(t){return t.valueOf!==v1&&typeof t.valueOf==="function"?t.valueOf(t):t}function cw(){let t=++Ff;if(Ff&1073741824)Ff=0;return t}var Qy=new WeakMap,ew=Object.create(null),Ff=0,qf=Object.create(null),Bf=0,T1=24000,ga=5,dc=1<<ga,ya=dc-1,qs={};function tw(){return{value:!1}}function si(t){if(t)t.value=!0}function Vf(t,n=0){return t.slice(n)}function wa(t,n){return t===n||t!==t&&n!==n}class zf{}class Gf{_root;size;__ownerID;__hash;__altered;constructor(t){return t===void 0||t===null?Uo():t instanceof Gf?t:Uo().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 iw(this,t,n)}delete(t){return iw(this,t,qs)}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 Uo();return this.__ownerID=t,this.__altered=!1,this}return Yf(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 zf)}[Symbol.iterator](){return this.entries()[Symbol.iterator]()}entries(){return new zl(this,R1,!1)}keys(){return new zl(this,lw,!1)}values(){return new zl(this,uw,!1)}}class Kf{constructor(t,n){this.ownerID=t,this.entries=n}ownerID;entries;get(t,n,i,o){let a=this.entries;for(let c=0,h=a.length;c<h;c++)if(wa(i,a[c][0]))return a[c][1];return o}update(t,n,i,o,a,c,h){let w=a===qs,E=this.entries,_=0,I=E.length;for(;_<I;_++)if(wa(o,E[_][0]))break;let T=_<I;if(T?E[_][1]===a:w)return this;if(si(h),w||!T)si(c);if(w&&E.length===1)return;if(!T&&!w&&E.length>=$1)return O1(t,E,o,a);let O=t&&t===this.ownerID,N=O?E:Vf(E);if(T)if(w)if(_===I-1)N.pop();else N[_]=N.pop();else N[_]=[o,a];else N.push([o,a]);if(O)return this.entries=N,this;return new Kf(t,N)}}class Gl{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=Fo(i);let a=1<<((t===0?n:n>>>t)&ya),c=this.bitmap;return(c&a)===0?o:this.nodes[ow(c&a-1)].get(t+ga,n,i,o)}update(t,n,i,o,a,c,h){if(i===void 0)i=Fo(o);let w=(n===0?i:i>>>n)&ya,E=1<<w,_=this.bitmap,I=(_&E)!==0;if(!I&&a===qs)return this;let T=ow(_&E-1),O=this.nodes,N=I?O[T]:void 0,L=Xf(N,t,n+ga,i,o,a,c,h);if(L===N)return this;if(!I&&L&&O.length>=L1)return M1(t,O,_,w,L);if(I&&!L&&O.length===2&&sw(O[T^1]))return O[T^1];if(I&&L&&O.length===1&&sw(L))return L;let H=t&&t===this.ownerID,Z=I?L?_:_^E:_|E,G=I?L?dw(O,T,L,H):D1(O,T,H):N1(O,T,L,H);if(H)return this.bitmap=Z,this.nodes=G,this;return new Gl(t,Z,G)}}class Jf{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=Fo(i);let a=(t===0?n:n>>>t)&ya,c=this.nodes[a];return c?c.get(t+ga,n,i,o):o}update(t,n,i,o,a,c,h){if(i===void 0)i=Fo(o);let w=(n===0?i:i>>>n)&ya,E=a===qs,_=this.nodes,I=_[w];if(E&&!I)return this;let T=Xf(I,t,n+ga,i,o,a,c,h);if(T===I)return this;let O=this.count;if(!I)O++;else if(!T){if(O--,O<j1)return k1(t,_,O,w)}let N=t&&t===this.ownerID,L=dw(_,w,T,N);if(N)return this.count=O,this.nodes=L,this;return new Jf(t,O,L)}}class Kl{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,h=a.length;c<h;c++)if(wa(i,a[c][0]))return a[c][1];return o}update(t,n,i,o,a,c,h){if(i===void 0)i=Fo(o);let w=a===qs;if(i!==this.keyHash){if(w)return this;return si(h),si(c),Zf(this,t,n,i,[o,a])}let E=this.entries,_=0,I=E.length;for(;_<I;_++)if(wa(o,E[_][0]))break;let T=_<I;if(T?E[_][1]===a:w)return this;if(si(h),w||!T)si(c);if(w&&I===2)return new qo(t,this.keyHash,E[_^1]);let O=t&&t===this.ownerID,N=O?E:Vf(E);if(T)if(w)if(_===I-1)N.pop();else N[_]=N.pop();else N[_]=[o,a];else N.push([o,a]);if(O)return this.entries=N,this;return new Kl(t,this.keyHash,N)}}class qo{constructor(t,n,i){this.ownerID=t,this.keyHash=n,this.entry=i}ownerID;keyHash;entry;get(t,n,i,o){return wa(i,this.entry[0])?this.entry[1]:o}update(t,n,i,o,a,c,h){let w=a===qs,E=wa(o,this.entry[0]);if(E?a===this.entry[1]:w)return this;if(si(h),w){si(c);return}if(E){if(t&&t===this.ownerID)return this.entry[1]=a,this;return new qo(t,this.keyHash,[o,a])}return si(c),Zf(this,t,n,Fo(o),[o,a])}}class zl{constructor(t,n,i){this._type=n,this._reverse=i,this._stack=t._root&&rw(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 Wf(t,i.entry)}else if("entries"in i&&i.entries){if(a=i.entries.length-1,o<=a)return Wf(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 Wf(t,c.entry);n=this._stack=rw(c,n)}continue}n=this._stack=this._stack.__prev}return C1()}}function Wf(t,n){return P1(t,n[0],n[1])}function rw(t,n){return{node:t,index:0,__prev:n}}var lw=0,uw=1,R1=2;function P1(t,n,i,o){let a=t===lw?n:t===uw?i:[n,i];if(o)o.value=a;else o={value:a,done:!1};return o}function C1(){return{value:void 0,done:!0}}function Yf(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 nw;function Uo(){return nw||(nw=Yf(0))}function iw(t,n,i){let o,a;if(!t._root){if(i===qs)return t;a=1,o=new Kf(t.__ownerID,[[n,i]])}else{let c=tw(),h=tw();if(o=Xf(t._root,t.__ownerID,0,void 0,n,i,c,h),!h.value)return t;a=t.size+(c.value?i===qs?-1:1:0)}if(t.__ownerID)return t.size=a,t._root=o,t.__hash=void 0,t.__altered=!0,t;return o?Yf(a,o):Uo()}function Xf(t,n,i,o,a,c,h,w){if(!t){if(c===qs)return t;return si(w),si(h),new qo(n,o,[a,c])}return t.update(n,i,o,a,c,h,w)}function sw(t){return t.constructor===qo||t.constructor===Kl}function Zf(t,n,i,o,a){if(t.keyHash===o)return new Kl(n,o,[t.entry,a]);let c=(i===0?t.keyHash:t.keyHash>>>i)&ya,h=(i===0?o:o>>>i)&ya,w,E=c===h?[Zf(t,n,i+ga,o,a)]:(w=new qo(n,o,a),c<h?[t,w]:[w,t]);return new Gl(n,1<<c|1<<h,E)}function O1(t,n,i,o){if(!t)t=new zf;let a=new qo(t,Fo(i),[i,o]);for(let c=0;c<n.length;c++){let h=n[c];a=a.update(t,0,void 0,h[0],h[1])}return a}function k1(t,n,i,o){let a=0,c=0,h=Array(i);for(let w=0,E=1,_=n.length;w<_;w++,E<<=1){let I=n[w];if(I!==void 0&&w!==o)a|=E,h[c++]=I}return new Gl(t,a,h)}function M1(t,n,i,o,a){let c=0,h=Array(dc);for(let w=0;i!==0;w++,i>>>=1)h[w]=i&1?n[c++]:void 0;return h[o]=a,new Jf(t,c+1,h)}function ow(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 dw(t,n,i,o){let a=o?t:Vf(t);return a[n]=i,a}function N1(t,n,i,o){let a=t.length+1;if(o&&n+1===a)return t[n]=i,t;let c=Array(a),h=0;for(let w=0;w<a;w++)if(w===n)c[w]=i,h=-1;else c[w]=t[w+h];return c}function D1(t,n,i){let o=t.length-1;if(i&&n===o)return t.pop(),t;let a=Array(o),c=0;for(let h=0;h<o;h++){if(h===n)c=1;a[h]=t[h+c]}return a}var $1=dc/4,L1=dc/2,j1=dc/4;class Sa{constructor(t,n){this.name=t;let i=Uo();if(n)i=i.withMutations((o)=>{for(let[a,c]of n)o.set(a,ho(`${t}:${String(a)}`,c))});this.atoms=ho(`${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 Ve(n!==Wt),n}__unsafe__getWithoutCapture(t){let n=this.atoms.__unsafe__getWithoutCapture().get(t);if(!n)return;let i=n.__unsafe__getWithoutCapture();return Ve(i!==Wt),i}has(t){let n=this.getAtom(t);if(!n)return!1;return n.get()!==Wt}__unsafe__hasWithoutCapture(t){let n=this.atoms.__unsafe__getWithoutCapture().get(t);if(!n)return!1;return Ve(n.__unsafe__getWithoutCapture()!==Wt),!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,ho(`${this.name}:${String(t)}`,n)));return this}getOrInsert(t,n){return this.getOrInsertComputed(t,()=>n)}getOrInsertComputed(t,n){let i=this.getAtom(t);if(i){let a=i.get();if(a!==Wt)return a}let o=n(t);return this.set(t,o),o}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();Ve(o!==Wt),i.set(n(o))}delete(t){let n=this.atoms.__unsafe__getWithoutCapture().get(t);if(!n)return!1;return po(()=>{n.set(Wt),this.atoms.update((i)=>i.delete(t))}),!0}deleteMany(t){return po(()=>{let n=[],i=this.atoms.__unsafe__getWithoutCapture().withMutations((o)=>{for(let a of t){let c=o.get(a);if(!c)continue;let h=c.__unsafe__getWithoutCapture();Ve(h!==Wt),n.push([a,h]),o.delete(a),c.set(Wt)}});if(n.length)this.atoms.set(i);return n})}clear(){return po(()=>{for(let t of this.atoms.__unsafe__getWithoutCapture().values())t.set(Wt);this.atoms.set(Uo())})}*entries(){for(let[t,n]of this.atoms.get()){let i=n.get();if(i===Wt)continue;yield[t,i]}}*keys(){for(let[t,n]of this.atoms.get()){if(n.__unsafe__getWithoutCapture()===Wt)continue;yield t}}*values(){for(let t of this.atoms.get().values()){let n=t.get();if(n===Wt)continue;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 Jl=!1;try{Jl=!0}catch(t){}try{Jl=Jl||import.meta.env.DEV||import.meta.env.TEST||import.meta.env.MODE==="development"||import.meta.env.MODE==="test"}catch(t){}function fw(){return Jl}function Vs(t){if(!fw())return t;let n=Object.getPrototypeOf(t);if(n&&!(Array.isArray(t)||n===Object.prototype||n===null||n===sc))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")Vs(a)}return Object.freeze(t)}class fc{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;if(n===0)delete this.diff.added;if(t===0)delete this.diff.removed;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 U1(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 bn({sequence:t,sequenceId:n,retroactive:i=!0}){let o={sequenceId:n,retroactive:i,sequence:U1(t)};return Qf(o),o}function Je(t,n){return Object.fromEntries(Pn(n).map(([i,o])=>[i,`${t}/${o}`]))}function Ye(t){let n=t.sequenceId;return bn({sequenceId:n,retroactive:t.retroactive??!0,sequence:t.sequence.map((i)=>({...i,scope:"record",filter:(o)=>o.typeName===t.recordType&&(i.filter?.(o)??!0)&&(t.filter?.(o)??!0)}))})}function hw(t){if(t.length===0)return[];let n=new Map(t.map((E)=>[E.id,E])),i=new Map,o=new Map,a=new Map;for(let E of t)o.set(E.id,0),i.set(E.id,new Set),a.set(E.id,new Set);for(let E of t){let{version:_,sequenceId:I}=ba(E.id),T=`${I}/${_-1}`;if(n.has(T))i.get(T).add(E.id),o.set(E.id,o.get(E.id)+1);if(E.dependsOn)for(let O of E.dependsOn){if(!n.has(O))continue;a.get(E.id).add(O);let N=i.get(O);if(N.has(E.id))continue;N.add(E.id),o.set(E.id,o.get(E.id)+1)}}let c=t.filter((E)=>o.get(E.id)===0),h=[],w=new Set;while(c.length>0){let E,_=-1/0;for(let T of c){let O=0;for(let N of i.get(T.id)||[])if(!w.has(N)){if(O+=1,a.get(N).has(T.id))O+=100}if(O>_||O===_&&T.id.localeCompare(E?.id??"")<0)E=T,_=O}let I=E;c.splice(c.indexOf(I),1),h.push(I),w.add(I.id);for(let T of i.get(I.id)||[])if(!w.has(T)){if(o.set(T,o.get(T)-1),o.get(T)===0)c.push(n.get(T))}}if(h.length!==t.length){let E=t.filter((_)=>!w.has(_.id));Ve(!1,`Circular dependency in migrations: ${E[0].id}`)}return h}function ba(t){let[n,i]=t.split("/");return{sequenceId:n,version:parseInt(i)}}function pw(t,n){if(n)Ve(t.startsWith(n+"/"),`Every migration in sequence '${n}' must have an id starting with '${n}/'. Got invalid id: '${t}'`);Ve(t.match(/^(.*?)\/(0|[1-9]\d*)$/),`Invalid migration id: '${t}'`)}function Qf(t){if(Ve(!t.sequenceId.includes("/"),`sequenceId cannot contain a '/', got ${t.sequenceId}`),Ve(t.sequenceId.length,"sequenceId must be a non-empty string"),t.sequence.length===0)return;pw(t.sequence[0].id,t.sequenceId);let n=ba(t.sequence[0].id).version;Ve(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;pw(o,t.sequenceId);let a=ba(o).version;Ve(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 Gs={IncompatibleSubtype:"incompatible-subtype",UnknownType:"unknown-type",TargetVersionTooNew:"target-version-too-new",TargetVersionTooOld:"target-version-too-old",MigrationError:"migration-error",UnrecognizedSubtype:"unrecognized-subtype"};function mw(){return{added:{},updated:{},removed:{}}}function tp(t){return!Oi(t.added)&&!Oi(t.updated)&&!Oi(t.removed)}function Oi(t){for(let n in t)return!0;return!1}function Yl(t,n){if(n?.mutateFirstDiff){let o=t[0];if(!o)return mw();for(let a in o.updated){let c=a,[h,w]=o.updated[c];o.updated[c]=[h,w]}return ep(o,t,1),o}let i={added:{},removed:{},updated:{}};return ep(i,t),i}function ep(t,n,i=0){yw(t,n,i)}function gw(t,n,i){return yw(t,n,0,i)}function yw(t,n,i,o){let a=0,c=o!==void 0;for(let h=i;h<n.length;h++){let w=n[h],E=Oi(t.removed);for(let I in w.added){let T=I,O=w.added[T];if(o!==void 0&&O.typeName!==o)continue;if(E&&t.removed[T]){let N=t.removed[T];if(delete t.removed[T],c)a--;if(N!==O){if(t.updated[T]=[N,O],c)a++}}else{if(c&&!t.added[T])a++;t.added[T]=O}}let _=Oi(t.added);for(let I in w.updated){let T=I,O=w.updated[T][1];if(o!==void 0&&O.typeName!==o)continue;if(_&&t.added[T]){if(t.added[T]=O,c&&t.updated[T])a--;if(delete t.updated[T],E){if(c&&t.removed[T])a--;delete t.removed[T]}continue}let N=t.updated[T];if(N){if(N[1]=O,E){if(c&&t.removed[T])a--;delete t.removed[T]}continue}if(t.updated[T]=[w.updated[T][0],O],c)a++;if(E){if(c&&t.removed[T])a--;delete t.removed[T]}}for(let I in w.removed){let T=I;if(o!==void 0&&w.removed[T].typeName!==o)continue;if(t.added[T]){if(delete t.added[T],c)a--}else if(t.updated[T])t.removed[T]=t.updated[T][0],delete t.updated[T];else{if(c&&!t.removed[T])a++;t.removed[T]=w.removed[T]}}}return a}class va{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 Pn(t))if(o!==void 0)n[i]=o;return n.typeName=this.typeName,n}clone(t){return{...an(t),id:this.createId()}}createId(t){return this.typeName+":"+(t??Ti())}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 va(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 st(t,n){return new va(t,{createDefaultProperties:()=>({}),validator:n.validator,scope:n.scope,ephemeralKeys:n.ephemeralKeys})}function ww(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 Sw(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 bw(t){if(typeof t!=="object"||t===null)return!1;return"eq"in t||"neq"in t||"gt"in t}function vw(t,n=""){let i=[];for(let[o,a]of Object.entries(t)){let c=n?`${n}\\${o}`:o;if(bw(a))i.push({path:c,matcher:a});else if(typeof a==="object"&&a!==null)i.push(...vw(a,c))}return i}function Xl(t,n){for(let[i,o]of Object.entries(t)){let a=n[i];if(bw(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(!Xl(o,a))return!1}return!0}function rp(t,n,i){let o=vw(i),a=nc(o.map(({path:c})=>[c,new Set]));for(let{path:c,matcher:h}of o){let w=t.index(n,c);if("eq"in h){let E=w.get().get(h.eq);if(E)for(let _ of E)a[c].add(_)}else if("neq"in h){for(let[E,_]of w.get())if(E!==h.neq)for(let I of _)a[c].add(I)}else if("gt"in h){for(let[E,_]of w.get())if(typeof E==="number"&&E>h.gt)for(let I of _)a[c].add(I)}if(a[c].size===0)return new Set}return ww(Ri(a))}class Zl{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=Sn("filterHistory:"+t,(i,o)=>{if(Ns(i))return this.history.get();let a=Math.max(this.history.get(),i+1),c=this.history.getDiffSince(o);if(c===Tr)return a;let h={added:{},removed:{},updated:{}};if(gw(h,c,t))return ma(a,h);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?(h)=>this.getNestedValue(h,o):(h)=>h[n],c=()=>{i.get();let h=new Map;for(let w of this.recordMap.values())if(w.typeName===t){let E=a(w);if(E!==void 0){if(!h.has(E))h.set(E,new Set);h.get(E).add(w.id)}}return h};return Sn("index:"+t+":"+n,(h,w)=>{if(Ns(h))return c();let E=i.getDiffSince(w);if(E===Tr)return c();let _=new Map,I=(H)=>{let Z=_.get(H);if(!Z)Z=new fc(h.get(H)??new Set),_.set(H,Z);return Z},T=(H,Z)=>I(H).add(Z),O=(H,Z)=>I(H).remove(Z);for(let H of E){for(let Z in H.added){let G=H.added[Z];if(G.typeName===t){let oe=a(G);if(oe!==void 0)T(oe,G.id)}}for(let Z in H.updated){let[G,oe]=H.updated[Z];if(oe.typeName===t){let re=a(G),xe=a(oe);if(re!==xe){if(re!==void 0)O(re,oe.id);if(xe!==void 0)T(xe,oe.id)}}}for(let Z in H.removed){let G=H.removed[Z];if(G.typeName===t){let oe=a(G);if(oe!==void 0)O(oe,G.id)}}}let N=void 0,L=void 0;for(let[H,Z]of _){let G=Z.get();if(!G)continue;if(!N)N=new Map(h);if(!L)L=new Map;if(G.value.size===0)N.delete(H);else N.set(H,G.value);L.set(H,G.diff)}if(N&&L)return ma(N,L);return h},{historyLength:100})}record(t,n=()=>({}),i="record:"+t+":"+n.toString()){let o=this.ids(t,n,i);return Sn(i,()=>{for(let a of o.get())return this.recordMap.get(a);return})}records(t,n=()=>({}),i="records:"+t+":"+n.toString()){let o=this.ids(t,n,"ids:"+i);return Sn(i,()=>Array.from(o.get(),(a)=>this.recordMap.get(a)),{isEqual:xf})}ids(t,n=()=>({}),i="ids:"+t+":"+n.toString()){let o=this.filterHistory(t),a=()=>{o.get();let w=n();if(!Oi(w))return this.getAllIdsForType(t);return rp(this,t,w)},c=(w)=>{let E=a(),_=Sw(w,E);if(_)return ma(E,_);else return w},h=Sn("ids_query:"+i,()=>n(),{isEqual:fo.default});return Sn("query:"+i,(w,E)=>{let _=h.get();if(Ns(w))return a();if(E<h.lastChangedEpoch)return c(w);let I=o.getDiffSince(E);if(I===Tr)return c(w);let T=new fc(w);for(let N of I){for(let L in N.added){let H=N.added[L];if(H.typeName===t&&Xl(_,H))T.add(H.id)}for(let L in N.updated){let H=N.updated[L][1];if(H.typeName===t)if(Xl(_,H))T.add(H.id);else T.remove(H.id)}for(let L in N.removed){let H=N.removed[L];if(H.typeName===t)T.remove(H.id)}}let O=T.get();if(!O)return w;return ma(O.value,O.diff)},{historyLength:50})}exec(t,n){let i=rp(this,t,n);if(i.size===0)return Os;return Array.from(i,(o)=>this.recordMap.get(o))}}class Ql{constructor(t){this.store=t}store;_beforeCreateHandlers={};_afterCreateHandlers={};_beforeChangeHandlers={};_afterChangeHandlers={};_beforeDeleteHandlers={};_afterDeleteHandlers={};_operationCompleteHandlers=[];_isEnabled=!0;addHandler(t,n,i){return t[n]=[...t[n]??[],i],()=>{t[n]=Ew(t[n]??[],i)}}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){return this.addHandler(this._beforeCreateHandlers,t,n)}registerAfterCreateHandler(t,n){return this.addHandler(this._afterCreateHandlers,t,n)}registerBeforeChangeHandler(t,n){return this.addHandler(this._beforeChangeHandlers,t,n)}registerAfterChangeHandler(t,n){return this.addHandler(this._afterChangeHandlers,t,n)}registerBeforeDeleteHandler(t,n){return this.addHandler(this._beforeDeleteHandlers,t,n)}registerAfterDeleteHandler(t,n){return this.addHandler(this._afterDeleteHandlers,t,n)}registerOperationCompleteHandler(t){return this._operationCompleteHandlers=[...this._operationCompleteHandlers,t],()=>{this._operationCompleteHandlers=Ew(this._operationCompleteHandlers,t)}}}function Ew(t,n){let i=t.indexOf(n);if(i<0)return t;return[...t.slice(0,i),...t.slice(i+1)]}var np=Symbol("deleted record");class eu{id;records;history=ho("history",0,{historyLength:1000});query;listeners=new Set;historyAccumulator=new Aw;historyReactor;cancelHistoryReactor=null;schema;props;scopedTypes;sideEffects=new Ql(this);constructor(t){let{initialData:n,schema:i,id:o}=t;if(this.id=o??Ti(),this.schema=i,this.props=t.props,n)this.records=new Sa("store",Pn(n).map(([c,h])=>[c,Vs(this.schema.validateRecord(this,h,"initialize",null))]));else this.records=new Sa("store");this.query=new Zl(this.records,this.history),this.historyReactor=Uf("Store.historyReactor",()=>{this.history.get(),this._flushHistory()},{scheduleEffect:(c)=>this.cancelHistoryReactor=Mf(c)});let a={document:new Set,session:new Set,presence:new Set};for(let c of Ri(this.schema.types))a[c.scope].add(c.typeName);this.scopedTypes=a}isFlushingHistory=!1;_flushHistory(){let t=this.history.__unsafe__getWithoutCapture(),n=this.historyAccumulator.flush(t);if(n.length>0){let i=[],o=this.isFlushingHistory;this.isFlushingHistory=!0;for(let{changes:a,source:c}of n){let h=new Map;for(let{onHistory:w,filters:E}of this.listeners){if(E.source!=="all"&&E.source!==c)continue;let _=a;if(E.scope!=="all"){if(!h.has(E.scope))h.set(E.scope,this.filterChangesByScope(a,E.scope));let I=h.get(E.scope);if(!I)continue;_=I}try{w({changes:_,source:c})}catch(I){i.push(I)}}}if(this.isFlushingHistory=o,i.length>0)throw i[0]}}dispose(){try{this._flushHistory()}finally{this.cancelHistoryReactor?.()}}filterChangesByScope(t,n){let i={added:da(t.added,(o,a)=>this.scopedTypes[n].has(a.typeName)),updated:da(t.updated,(o,a)=>this.scopedTypes[n].has(a[1].typeName)),removed:da(t.removed,(o,a)=>this.scopedTypes[n].has(a.typeName))};if(tp(i))return null;return i}updateHistory(t){let n=this.history.__unsafe__getWithoutCapture()+1;if(this.history.set(n,t),this.historyAccumulator.add({changes:t,source:this.isMergingRemoteChanges?"remote":"user"},n),this.listeners.size===0)this.historyAccumulator.clear()}validate(t){this.allRecords().forEach((n)=>this.schema.validateRecord(this,n,t,null))}put(t,n){this.atomic(()=>{let i={},o={},a,c=this.isMergingRemoteChanges?"remote":"user";for(let h=0,w=t.length;h<w;h++){a=t[h];let E=this.records.__unsafe__getWithoutCapture(a.id);if(E){a=this.sideEffects.handleBeforeChange(E,a,c);let _=this.schema.validateRecord(this,a,n??"updateRecord",E);if(_===E)continue;if(a=Vs(_),this.records.set(a.id,a),o[a.id])o[a.id]=a;else{let I=i[a.id]?.[0]??E;if(I===a)delete i[a.id];else i[a.id]=[I,a]}this.addDiffForAfterEvent(E,a)}else a=this.sideEffects.handleBeforeCreate(a,c),a=this.schema.validateRecord(this,a,n??"createRecord",null),a=Vs(a),o[a.id]=a,this.addDiffForAfterEvent(null,a),this.records.set(a.id,a)}if(!Oi(o)&&!Oi(i))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 h=this.records.__unsafe__getWithoutCapture(c);if(!h)continue;if(this.sideEffects.handleBeforeDelete(h,i)===!1)n.delete(c)}let o=this.records.deleteMany(n);if(o.length===0)return;let a={};for(let[c,h]of o)a[c]=h,this.addDiffForAfterEvent(h,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.isFlushingHistory)try{this._flushHistory()}catch(o){console.error(o)}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,a)=>{while(n.length&&n[n.length-1].version>=a)n.pop();n.push({version:a,changes:o.changes})});try{po(t);let o=this.history.__unsafe__getWithoutCapture();while(n.length&&n[n.length-1].version>o)n.pop();return Yl(n.map((a)=>a.changes))}finally{i()}}applyDiff(t,{runCallbacks:n=!0,ignoreEphemeralKeys:i=!1}={}){this.atomic(()=>{let o=Ri(t.added);for(let[c,h]of Ri(t.updated)){let w=this.schema.getType(h.typeName);if(i&&w.ephemeralKeySet.size){let E=this.unsafeGetWithoutCapture(h.id);if(!E){o.push(h);continue}let _=null;for(let[I,T]of Object.entries(h)){if(w.ephemeralKeySet.has(I)||Object.is(T,dr(E,I)))continue;if(!_)_={...E};_[I]=T}for(let I of Object.keys(E)){if(w.ephemeralKeySet.has(I)||Object.hasOwn(h,I))continue;if(!_)_={...E};delete _[I]}if(_)o.push(_)}else o.push(h)}let a=If(t.removed);if(o.length)this.put(o);if(a.length)this.remove(a)},n)}createCache(t){let n=new Ll;return{get:(i)=>{let o=this.records.getAtom(i);if(!o)return;return n.get(o,()=>t(i,o)).get()}}}createComputedCache(t,n,i){let o=i?.areRecordsEqual,a=i?.areResultsEqual;return this.createCache((c,h)=>{let w=o?Sn(`${t}:${c}:isEqual`,()=>h.get(),{isEqual:(E,_)=>Ns(E)||Ns(_)?E===_:o(E,_)}):h;return Sn(t+":"+c,()=>{let E=w.get();if(Ns(E))return np;return n(E)},{isEqual:a?(E,_)=>E===np||_===np?E===_:a(E,_):void 0})})}_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(Ve(this.pendingAfterEvents,"must be in event operation"),t===n)return;if(t&&n)Ve(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&&!fo.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);i="user"}}_isInAtomicOp=!1;atomic(t,n=!0,i=!1){return po(()=>{if(this._isInAtomicOp){if(!this.pendingAfterEvents)this.pendingAfterEvents=new Map;let a=this.sideEffects.isEnabled();Ve(!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 F1(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),Vs(n.map((a)=>({source:a[0].source,changes:a.length===1?a[0].changes:Yl(a.map((c)=>c.changes))})))}class Aw{_history=[];_versions=[];_interceptors=new Set;addInterceptor(t){return this._interceptors.add(t),()=>{this._interceptors.delete(t)}}add(t,n){this.discardFrom(n),this._history.push(t),this._versions.push(n);for(let i of this._interceptors)i(t,n)}flush(t){this.discardFrom(t+1);let n=F1(this._history);return this.clear(),n}clear(){this._history=[],this._versions=[]}discardFrom(t){while(this._versions.length&&this._versions[this._versions.length-1]>=t)this._versions.pop(),this._history.pop()}}function Ea(t){return typeof t==="object"&&t!==null&&!Array.isArray(t)}function q1(t){if(!Ea(t))return br.err("Bad schema");if(t.schemaVersion===2){if(!Ea(t.sequences))return br.err("Bad schema: missing sequences");return br.ok(t)}if(t.schemaVersion!==1)return br.err("Bad schema version");if(!Ea(t.recordVersions))return br.err("Bad schema: missing recordVersions");let n={schemaVersion:2,sequences:{"com.tldraw.store":t.storeVersion}};for(let[i,o]of Object.entries(t.recordVersions)){if(!Ea(o))return br.err("Bad schema: malformed recordVersions");if(n.sequences[`com.tldraw.${i}`]=o.version,"subTypeKey"in o){if(!Ea(o.subTypeVersions))return br.err("Bad schema: malformed subTypeVersions");for(let[a,c]of Object.entries(o.subTypeVersions))n.sequences[`com.tldraw.${i}.${a}`]=c}}return br.ok(n)}class pc{constructor(t,n){this.types=t,this.options=n;for(let o of n.migrations??[])Ve(!this.migrations[o.sequenceId],`Duplicate migration sequenceId ${o.sequenceId}`),Qf(o),this.migrations[o.sequenceId]=o;let i=Object.values(this.migrations).flatMap((o)=>o.sequence);this.sortedMigrations=hw(i);for(let o of this.sortedMigrations){if(!o.dependsOn?.length)continue;for(let a of o.dependsOn){let c=i.find((h)=>h.id===a);Ve(c,`Migration '${o.id}' depends on missing migration '${a}'`)}}}types;options;static create(t,n){return new pc(t,n??{})}migrations={};sortedMigrations;migrationCache=new WeakMap;validateRecord(t,n,i,o){try{let a=dr(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){if(!Ea(t))return this.computeMigrationsSince(t);let n=this.migrationCache.get(t);if(n)return n;let i=this.computeMigrationsSince(t);return this.migrationCache.set(t,i),i}computeMigrationsSince(t){let n=q1(t);if(!n.ok)return n;let i=n.value,o=new Set(Object.keys(i.sequences).filter((c)=>dr(this.migrations,c)));for(let c in this.migrations)if(i.sequences[c]===void 0&&this.migrations[c].retroactive)o.add(c);if(o.size===0)return br.ok([]);let a=new Set;for(let c of o){let h=i.sequences[c];if(h!==void 0&&typeof h!=="number")return br.err("Incompatible schema?");if(h===void 0&&this.migrations[c].retroactive||h===0){for(let _ of this.migrations[c].sequence)a.add(_.id);continue}let w=`${c}/${h}`,E=this.migrations[c].sequence.findIndex((_)=>_.id===w);if(E===-1)return br.err("Incompatible schema?");for(let _ of this.migrations[c].sequence.slice(E+1))a.add(_.id)}return br.ok(this.sortedMigrations.filter(({id:c})=>a.has(c)))}migratePersistedRecord(t,n,i="up"){let o=this.getMigrationsSince(n);if(!o.ok)return console.error("Error migrating record",o.error),{type:"error",reason:Gs.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"?Gs.TargetVersionTooOld:Gs.TargetVersionTooNew};if(i==="down"){if(!a.every((c)=>c.scope==="record"&&c.down))return{type:"error",reason:Gs.TargetVersionTooOld};a=a.slice().reverse()}try{t=an(t);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 w=c[i](t);if(w)t=an(w)}}catch(c){return console.error("Error migrating record",c),{type:"error",reason:Gs.MigrationError}}return{type:"success",value:t}}migrateStorage(t){let n=t.getSchema();Ve(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 c of o)if(c.scope==="record"){let h=[];for(let[w,E]of t.entries()){if(!(c.filter?c.filter(E):!0))continue;let I=an(E),T=c.up(I)??I;if(!fo.default(T,E))h.push([w,T])}for(let[w,E]of h)t.set(w,E)}else if(c.scope==="store"){let h=Object.fromEntries(t.entries()),w=an(h);w=c.up(w)??w;for(let[E,_]of Object.entries(w)){if(!_)continue;if(!fo.default(_,h[E]))t.set(E,_)}for(let E of Object.keys(h))if(!w[E])t.delete(E)}else if(c.scope==="storage")c.up(t);else rc(c);let a=[];for(let[c,h]of t.entries())if(this.getType(h.typeName).scope!=="document")a.push(c);for(let c of a)t.delete(c)}migrateStoreSnapshot(t,n){let i=this.getMigrationsSince(t.schema);if(!i.ok)return console.error("Error migrating store",i.error),{type:"error",reason:Gs.MigrationError};if(i.value.length===0)return{type:"success",value:t.store};try{let a=Object.assign(new Map(Pn(t.store).map(Vs)),{getSchema:()=>t.schema,setSchema:(c)=>{}});if(this.migrateStorage(a),n?.mutateInputStore){for(let[c,h]of a.entries())t.store[c]=h;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(a){return console.error("Error migrating store",a),{type:"error",reason:Gs.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?ba(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=dr(this.types,t);return Ve(n,"record type does not exist"),n}}ei("@tldraw/store","5.6.2","esm");var B1=!0;function W1(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 Se extends Error{constructor(t,n=[]){let i=W1(n),o=t.split(`
|
|
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 vn(t,n){if(n instanceof Se)throw new Se(n.rawMessage,[t,...n.path]);throw new Se(n.toString(),[t])}function pr(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:rc(n)}}class Qe{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(B1&&!this.skipSameValueCheck&&!Object.is(t,n))throw new Se("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 G1(this)}optional(){return Iw(this)}refine(t){return new Qe((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){vn(`(check ${t})`,o)}return i});else return this.refine((i)=>(t(i),i))}}class op extends Qe{constructor(t){super((n)=>{let i=xw.validate(n);for(let o=0;o<i.length;o++)try{t.validate(i[o])}catch(a){vn(o,a)}return i},(n,i)=>{if(Object.is(n,i))return n;if(!t.validateUsingKnownGoodVersion)return this.validate(i);let o=xw.validate(i),a=n.length!==o.length;for(let c=0;c<o.length;c++){let h=o[c];if(c>=n.length){a=!0;try{t.validate(h)}catch(w){vn(c,w)}continue}if(Object.is(n[c],h))continue;try{let w=t.validateUsingKnownGoodVersion(n[c],h);if(!Object.is(w,n[c]))a=!0}catch(w){vn(c,w)}}return a?i:n});this.itemValidator=t}itemValidator;nonEmpty(){return this.check((t)=>{if(t.length===0)throw new Se("Expected a non-empty array")})}lengthGreaterThan1(){return this.check((t)=>{if(t.length<=1)throw new Se("Expected an array with length greater than 1")})}}class hc extends Qe{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 Se(`Expected object, got ${pr(a)}`);for(let c=0;c<i.length;c++){let h=i[c];try{o[c].validate(dr(a,h))}catch(w){vn(h,w)}}if(!n)for(let c in a){if(!Bt(a,c))continue;if(!Bt(t,c))throw new Se("Unexpected property",[c])}return a},(a,c)=>{if(Object.is(a,c))return a;if(typeof c!=="object"||c===null)throw new Se(`Expected object, got ${pr(c)}`);let h=!1;for(let w=0;w<i.length;w++){let E=i[w],_=dr(a,E),I=dr(c,E);if(Object.is(_,I))continue;try{let T=o[w],O=T.validateUsingKnownGoodVersion?T.validateUsingKnownGoodVersion(_,I):T.validate(I);if(!Object.is(O,_))h=!0}catch(T){vn(E,T)}}if(!n)for(let w in c){if(!Bt(c,w))continue;if(!Bt(t,w))throw new Se("Unexpected property",[w])}else if(!h){for(let w of Object.keys(c))if(!Bt(t,w)&&!Object.is(dr(a,w),dr(c,w))){h=!0;break}}if(!h)for(let w in a){if(!Bt(a,w))continue;if(!Bt(c,w)){h=!0;break}}return h?c:a});this.config=t,this.shouldAllowUnknownProperties=n}config;shouldAllowUnknownProperties;allowUnknownProperties(){return new hc(this.config,!0)}extend(t){return new hc({...this.config,...t})}}class tu extends Qe{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(h){vn(`(${t} = ${this.getVariant(a)})`,h)}},(a,c)=>{this.expectObject(c),this.expectObject(a);let h=this.getMatchingSchema(c);if(h===void 0)return this.unknownValueValidation(c,this.getVariant(c));try{if(dr(a,t)!==dr(c,t))return h.validate(c);if(h.validateUsingKnownGoodVersion)return h.validateUsingKnownGoodVersion(a,c);else return h.validate(c)}catch(w){vn(`(${t} = ${this.getVariant(c)})`,w)}});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 Se(`Expected an object, got ${pr(t)}`,[])}getVariant(t){return dr(t,this.key)}getMatchingSchema(t){let n=dr(t,this.key);if(!this.useNumberKeys&&typeof n!=="string")throw new Se(`Expected a string for key "${this.key}", got ${pr(n)}`);else if(this.useNumberKeys){let i=Number(n);if(i-i!==0)throw new Se(`Expected a number for key "${this.key}", got "${n}"`)}return Bt(this.config,n)?this.config[n]:void 0}validateUnknownVariants(t){return new tu(this.key,this.config,t,this.useNumberKeys)}}class ap extends Qe{constructor(t,n){super((i)=>{if(typeof i!=="object"||i===null)throw new Se(`Expected object, got ${pr(i)}`);for(let o in i){if(!Bt(i,o))continue;try{t.validate(o),n.validate(i[o])}catch(a){vn(o,a)}}return i},(i,o)=>{if(typeof o!=="object"||o===null)throw new Se(`Expected object, got ${pr(o)}`);let a=o,c=!1,h=0;for(let w in a){if(!Bt(a,w))continue;h++;let E=a[w];if(!Bt(i,w)){c=!0;try{t.validate(w),n.validate(E)}catch(I){vn(w,I)}continue}let _=i[w];if(Object.is(_,E))continue;try{let I=n.validateUsingKnownGoodVersion?n.validateUsingKnownGoodVersion(_,E):n.validate(E);if(!Object.is(I,_))c=!0}catch(I){vn(w,I)}}if(!c){let w=0;for(let E in i)if(Bt(i,E))w++;if(w!==h)c=!0}return c?o:i});this.keyValidator=t,this.valueValidator=n}keyValidator;valueValidator}function cp(t){return new Qe((n)=>{if(typeof n!==t)throw new Se(`Expected ${t}, got ${pr(n)}`);return n})}var H1=new Qe((t)=>t),_w=new Qe((t)=>t),Ne=cp("string"),_e=new Qe((t)=>{if(Number.isFinite(t))return t;if(typeof t!=="number")throw new Se(`Expected number, got ${pr(t)}`);if(t!==t)throw new Se("Expected a number, got NaN");throw new Se(`Expected a finite number, got ${t}`)}),mc=new Qe((t)=>{if(Number.isFinite(t)&&t>=0)return t;if(typeof t!=="number")throw new Se(`Expected number, got ${pr(t)}`);if(t!==t)throw new Se("Expected a number, got NaN");if(t<0)throw new Se(`Expected a positive number, got ${t}`);throw new Se(`Expected a finite number, got ${t}`)}),Nt=new Qe((t)=>{if(Number.isFinite(t)&&t>0)return t;if(typeof t!=="number")throw new Se(`Expected number, got ${pr(t)}`);if(t!==t)throw new Se("Expected a number, got NaN");if(t<=0)throw new Se(`Expected a non-zero positive number, got ${t}`);throw new Se(`Expected a finite number, got ${t}`)}),ru=new Qe((t)=>{if(Number.isFinite(t)&&t!==0)return t;if(typeof t!=="number")throw new Se(`Expected number, got ${pr(t)}`);if(t!==t)throw new Se("Expected a number, got NaN");if(t===0)throw new Se("Expected a non-zero number, got 0");throw new Se(`Expected a finite number, got ${t}`)}),V1=new Qe((t)=>{if(Number.isFinite(t)&&t>=0&&t<=1)return t;if(typeof t!=="number")throw new Se(`Expected number, got ${pr(t)}`);if(t!==t)throw new Se("Expected a number, got NaN");throw new Se(`Expected a number between 0 and 1, got ${t}`)}),Pq=new Qe((t)=>{if(Number.isInteger(t))return t;if(typeof t!=="number")throw new Se(`Expected number, got ${pr(t)}`);if(t!==t)throw new Se("Expected a number, got NaN");if(t-t!==0)throw new Se(`Expected a finite number, got ${t}`);throw new Se(`Expected an integer, got ${t}`)}),Cq=new Qe((t)=>{if(Number.isInteger(t)&&t>=0)return t;if(typeof t!=="number")throw new Se(`Expected number, got ${pr(t)}`);if(t!==t)throw new Se("Expected a number, got NaN");if(t-t!==0)throw new Se(`Expected a finite number, got ${t}`);if(t<0)throw new Se(`Expected a positive integer, got ${t}`);throw new Se(`Expected an integer, got ${t}`)}),Oq=new Qe((t)=>{if(Number.isInteger(t)&&t>0)return t;if(typeof t!=="number")throw new Se(`Expected number, got ${pr(t)}`);if(t!==t)throw new Se("Expected a number, got NaN");if(t-t!==0)throw new Se(`Expected a finite number, got ${t}`);if(t<=0)throw new Se(`Expected a non-zero positive integer, got ${t}`);throw new Se(`Expected an integer, got ${t}`)}),$e=cp("boolean"),kq=cp("bigint");function Ct(t){return new Qe((n)=>{if(n!==t)throw new Se(`Expected ${t}, got ${JSON.stringify(n)}`);return t})}var xw=new Qe((t)=>{if(!Array.isArray(t))throw new Se(`Expected an array, got ${pr(t)}`);return t});function un(t){return new op(t)}var Mq=new Qe((t)=>{if(typeof t!=="object"||t===null)throw new Se(`Expected object, got ${pr(t)}`);return t});function ke(t){return new hc(t)}function ip(t){return typeof t==="object"&&t!==null&&(Object.getPrototypeOf(t)===Object.prototype||Object.getPrototypeOf(t)===null||Object.getPrototypeOf(t)===sc)}function sp(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(!sp(t[n]))return!1;return!0}if(ip(t)){for(let n in t){if(!Bt(t,n))continue;if(!sp(t[n]))return!1}return!0}return!1}var xt=new Qe((t)=>{if(sp(t))return t;throw new Se(`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,xt.validate(n[o]);continue}let a=t[o],c=n[o];if(Object.is(a,c))continue;let h=xt.validateUsingKnownGoodVersion(a,c);if(!Object.is(h,a))i=!0}return i?n:t}else if(ip(t)&&ip(n)){let i=!1;for(let o in n){if(!Bt(n,o))continue;if(!Bt(t,o)){i=!0,xt.validate(n[o]);continue}let a=t[o],c=n[o];if(Object.is(a,c))continue;let h=xt.validateUsingKnownGoodVersion(a,c);if(!Object.is(h,a))i=!0}if(!i)for(let o in t){if(!Bt(t,o))continue;if(!Bt(n,o)){i=!0;break}}return i?n:t}else return xt.validate(n)});function z1(t,n){return new ap(t,n)}function nu(t,n){return new tu(t,n,(i,o)=>{throw new Se(`Expected one of ${Object.keys(n).map((a)=>JSON.stringify(a)).join(" or ")}, got ${JSON.stringify(o)}`,[t])},!1)}function Cn(t,n){return new Qe((i)=>{try{return n.validate(i)}catch(o){vn(t,o)}},(i,o)=>{try{if(n.validateUsingKnownGoodVersion)return n.validateUsingKnownGoodVersion(i,o);else return n.validate(o)}catch(a){vn(t,a)}})}function iu(t){return new Qe((n)=>{if(!t.has(n)){let i=Array.from(t,(o)=>JSON.stringify(o)).join(" or ");throw new Se(`Expected ${i}, got ${n}`)}return n})}function Iw(t){return new Qe((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 Qe&&t.skipSameValueCheck)}function G1(t){return new Qe((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 Qe&&t.skipSameValueCheck)}function mo(...t){return iu(new Set(t))}function lp(t){try{return new URL(t)}catch{if(t.startsWith("/")||t.startsWith("./"))try{return new URL(t,"http://example.com")}catch{throw new Se(`Expected a valid url, got ${JSON.stringify(t)}`)}throw new Se(`Expected a valid url, got ${JSON.stringify(t)}`)}}var K1=new Set(["javascript:","vbscript:","data:","blob:","filesystem:","file:","about:","view-source:","chrome:","chrome-extension:","moz-extension:","resource:","jar:","asset:","ms-msdt:","search-ms:","search:","ms-officecmd:","ms-appinstaller:","shell:","hcp:","ms-its:","its:","mk:","res:","ms-word:","ms-excel:","ms-powerpoint:","ms-visio:","ms-access:","ms-project:","ms-publisher:","ms-spd:","ms-infopath:","smb:","ldap:","ldaps:","ms-cxh:","ms-cxh-full:","ms-settings:","microsoft-edge:","intent:","jnlp:","itms-services:","steam:"]),J1=/^\d{1,5}(?:[/?#]|$)/,vr=Ne.check((t)=>{if(t==="")return;let n=lp(t),i=n.protocol.toLowerCase();if(K1.has(i)||i.length===2||J1.test(n.href.slice(i.length)))throw new Se(`Expected a valid url, got ${JSON.stringify(t)} (invalid protocol)`)}),Y1=new Set(["http:","https:","data:","asset:"]),Bo=Ne.check((t)=>{if(t==="")return;let n=lp(t);if(!Y1.has(n.protocol.toLowerCase()))throw new Se(`Expected a valid url, got ${JSON.stringify(t)} (invalid protocol)`)}),Nq=Ne.check((t)=>{if(t==="")return;if(!lp(t).protocol.toLowerCase().match(/^https?:$/))throw new Se(`Expected a valid url, got ${JSON.stringify(t)} (invalid protocol)`)}),up=Ne.refine((t)=>{try{return Pf(t),t}catch{throw new Se(`Expected an index key, got ${JSON.stringify(t)}`)}});ei("@tldraw/validate","5.6.2","esm");function Le(t){return Ne.refine((n)=>{if(!n.startsWith(`${t}:`))throw Error(`${t} ID must start with "${t}:"`);return n})}var go=Le("asset");function Ks(t,n,i){let o=n instanceof Qe?n:n?ke(n):xt;return ke({id:go,typeName:Ct("asset"),type:Ct(t),props:o,meta:i?ke(i):xt})}var su={title:Ne,description:Ne,image:Ne,favicon:Ne,src:Bo.nullable()},zq=Ks("bookmark",ke(su)),Tw=Je("com.tldraw.asset.bookmark",{MakeUrlsValid:1,AddFavicon:2}),dp=Ye({sequenceId:"com.tldraw.asset.bookmark",recordType:"asset",filter:(t)=>t.type==="bookmark",sequence:[{id:Tw.MakeUrlsValid,up:(t)=>{if(!Bo.isValid(t.props.src))t.props.src=""},down:(t)=>{}},{id:Tw.AddFavicon,up:(t)=>{if(!Bo.isValid(t.props.favicon))t.props.favicon=""},down:(t)=>{delete t.props.favicon}}]});var ou={w:_e,h:_e,name:Ne,isAnimated:$e,mimeType:Ne.nullable(),src:Bo.nullable(),fileSize:Nt.optional(),pixelRatio:mc.optional()},Xq=Ks("image",ke(ou)),Aa=Je("com.tldraw.asset.image",{AddIsAnimated:1,RenameWidthHeight:2,MakeUrlsValid:3,AddFileSize:4,MakeFileSizeOptional:5,AddPixelRatio:6}),fp=Ye({sequenceId:"com.tldraw.asset.image",recordType:"asset",filter:(t)=>t.type==="image",sequence:[{id:Aa.AddIsAnimated,up:(t)=>{t.props.isAnimated=!1},down:(t)=>{delete t.props.isAnimated}},{id:Aa.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:Aa.MakeUrlsValid,up:(t)=>{if(!Bo.isValid(t.props.src))t.props.src=""},down:(t)=>{}},{id:Aa.AddFileSize,up:(t)=>{t.props.fileSize=-1},down:(t)=>{delete t.props.fileSize}},{id:Aa.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:Aa.AddPixelRatio,up:(t)=>{},down:(t)=>{delete t.props.pixelRatio}}]});var au={w:_e,h:_e,name:Ne,isAnimated:$e,mimeType:Ne.nullable(),src:Bo.nullable(),fileSize:_e.optional()},rB=Ks("video",ke(au)),gc=Je("com.tldraw.asset.video",{AddIsAnimated:1,RenameWidthHeight:2,MakeUrlsValid:3,AddFileSize:4,MakeFileSizeOptional:5}),pp=Ye({sequenceId:"com.tldraw.asset.video",recordType:"asset",filter:(t)=>t.type==="video",sequence:[{id:gc.AddIsAnimated,up:(t)=>{t.props.isAnimated=!1},down:(t)=>{delete t.props.isAnimated}},{id:gc.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:gc.MakeUrlsValid,up:(t)=>{if(!Bo.isValid(t.props.src))t.props.src=""},down:(t)=>{}},{id:gc.AddFileSize,up:(t)=>{t.props.fileSize=-1},down:(t)=>{delete t.props.fileSize}},{id:gc.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 hi=ke({x:_e,y:_e,z:_e.optional()}),yo=ke({x:_e,y:_e,w:_e,h:_e});var yc=V1;var Rw=Ne.refine((t)=>{if(!t.startsWith("page:")&&!t.startsWith("shape:"))throw Error('Parent ID must start with "page:" or "shape:"');return t}),En=Le("shape");function hp(t,n,i){return ke({id:En,typeName:Ct("shape"),x:_e,y:_e,rotation:_e,index:up,parentId:Rw,type:Ct(t),isLocked:$e,opacity:yc,props:n?ke(n):xt,meta:i?ke(i):xt})}var Pw=Le("binding");function mp(t,n,i){return ke({id:Pw,typeName:Ct("binding"),type:Ct(t),fromId:En,toId:En,props:n?ke(n):xt,meta:i?ke(i):xt})}var bB=Je("com.tldraw.binding",{}),X1=Ye({sequenceId:"com.tldraw.binding",recordType:"binding",sequence:[]});function xa(t){return`binding:${t??Ti()}`}function gp(t){return t}function yp(t,n){return Ci(n,(i,o)=>`com.tldraw.binding.${t}/${o}`)}function Cw(t){return st("binding",{scope:"document",validator:Cn("binding",nu("type",Ci(t,(n,{props:i,meta:o})=>mp(n,i,o))))}).withDefaultProperties(()=>({meta:{}}))}var mi=ke({type:Ne,content:un(H1),attrs:_w.optional()});function Kt(t){return{type:"doc",content:t.split(`
|
|
61
|
+
`).map((o)=>{if(!o)return{type:"paragraph"};return{type:"paragraph",content:[{type:"text",text:o}]}})}}class Xe{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=_w}=n;return new Xe(t,i,o)}static defineEnum(t,n){let{defaultValue:i,values:o}=n;return new wp(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 wp extends Xe{constructor(t,n,i){super(t,n,mo(...i));this.values=[...i]}values;addValues(...t){for(let n of t)if(!this.values.includes(n))this.values.push(n);this.type=mo(...this.values)}removeValues(...t){for(let n of t)if(this.values.includes(n))this.values.splice(this.values.indexOf(n),1);this.type=mo(...this.values)}}var cu=Je("com.tldraw.shape",{AddIsLocked:1,HoistOpacity:2,AddMeta:3,AddWhite:4}),Sp=Ye({sequenceId:"com.tldraw.shape",recordType:"shape",sequence:[{id:cu.AddIsLocked,up:(t)=>{t.isLocked=!1},down:(t)=>{delete t.isLocked}},{id:cu.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:cu.AddMeta,up:(t)=>{t.meta={}}},{id:cu.AddWhite,up:(t)=>{},down:(t)=>{if(t.props.color==="white")t.props.color="black"}}]});function An(t){return`shape:${t??Ti()}`}function bp(t){let n=new Map;for(let[i,o]of Object.entries(t))if(o instanceof Xe){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 pt(t){return t}function ht(t,n){return Ci(n,(i,o)=>`com.tldraw.shape.${t}/${o}`)}function Ow(t){return st("shape",{scope:"document",validator:Cn("shape",nu("type",Ci(t,(n,{props:i,meta:o})=>hp(n,i,o))))}).withDefaultProperties(()=>({x:0,y:0,rotation:0,isLocked:!1,opacity:1,meta:{}}))}function lu(t,n){let i=[];for(let[o,{migrations:a}]of Object.entries(n)){let c=`com.tldraw.${t}.${o}`;if(!a)i.push(bn({sequenceId:c,retroactive:!0,sequence:[]}));else if("sequenceId"in a)Ve(c===a.sequenceId,`sequenceId mismatch for ${o} ${va} migrations. Expected '${c}', got '${a.sequenceId}'`),i.push(a);else if("sequence"in a)i.push(bn({sequenceId:c,retroactive:!0,sequence:a.sequence.map((h)=>("id"in h)?vp(t,o,h):h)}));else i.push(bn({sequenceId:c,retroactive:!0,sequence:Object.keys(a.migrators).map((h)=>Number(h)).sort((h,w)=>h-w).map((h)=>({id:`${c}/${h}`,scope:"record",filter:(w)=>w.typeName===t&&w.type===o,up:(w)=>{let E=a.migrators[h].up(w);if(E)return E},down:(w)=>{let E=a.migrators[h].down(w);if(E)return E}}))}))}return i}function vp(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 kw=["black","grey","light-violet","violet","blue","light-blue","yellow","orange","green","light-green","light-red","red","white"],hr=Xe.defineEnum("tldraw:color",{defaultValue:"black",values:kw}),_a=Xe.defineEnum("tldraw:labelColor",{defaultValue:"black",values:kw});var Ys=Xe.defineEnum("tldraw:dash",{defaultValue:"draw",values:["draw","solid","dashed","dotted","none"]});var Wo=Xe.defineEnum("tldraw:fill",{defaultValue:"none",values:["none","semi","solid","pattern","fill","lined-fill"]});var Xs=Xe.defineEnum("tldraw:font",{defaultValue:"draw",values:["draw","sans","serif","mono"]});var Nr=Xe.defineEnum("tldraw:size",{defaultValue:"m",values:["s","m","l","xl"]});var Z1=["arc","elbow"],Mw=Xe.defineEnum("tldraw:arrowKind",{defaultValue:"arc",values:Z1}),Nw=["arrow","triangle","square","dot","pipe","diamond","inverted","bar","none"],Dw=Xe.defineEnum("tldraw:arrowheadStart",{defaultValue:"none",values:Nw}),$w=Xe.defineEnum("tldraw:arrowheadEnd",{defaultValue:"arrow",values:Nw}),Ep={kind:Mw,labelColor:_a,color:hr,fill:Wo,dash:Ys,size:Nr,arrowheadStart:Dw,arrowheadEnd:$w,font:Xs,start:hi,end:hi,bend:_e,richText:mi,labelPosition:_e,scale:Nt,elbowMidPoint:_e},gi=ht("arrow",{AddLabelColor:1,AddIsPrecise:2,AddLabelPosition:3,ExtractBindings:4,AddScale:5,AddElbow:6,AddRichText:7,AddRichTextAttrs:8});function Ho(t){return vp("shape","arrow",t)}var Ap=bn({sequenceId:"com.tldraw.shape.arrow",retroactive:!1,sequence:[Ho({id:gi.AddLabelColor,up:(t)=>{t.labelColor="black"},down:"retired"}),Ho({id:gi.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}}}),Ho({id:gi.AddLabelPosition,up:(t)=>{t.labelPosition=0.5},down:(t)=>{delete t.labelPosition}}),{id:gi.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=an(o),{start:c,end:h}=o.props;if(c.type==="binding"){let w=xa(),E={typeName:"binding",id:w,type:"arrow",fromId:o.id,toId:c.boundShapeId,meta:{},props:{terminal:"start",normalizedAnchor:c.normalizedAnchor,isExact:c.isExact,isPrecise:c.isPrecise}};n.push([w,E]),a.props.start={x:0,y:0}}else delete a.props.start.type;if(h.type==="binding"){let w=xa(),E={typeName:"binding",id:w,type:"arrow",fromId:o.id,toId:h.boundShapeId,meta:{},props:{terminal:"end",normalizedAnchor:h.normalizedAnchor,isExact:h.isExact,isPrecise:h.isPrecise}};n.push([w,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)}},Ho({id:gi.AddScale,up:(t)=>{t.scale=1},down:(t)=>{delete t.scale}}),Ho({id:gi.AddElbow,up:(t)=>{t.kind="arc",t.elbowMidPoint=0.5},down:(t)=>{delete t.kind,delete t.elbowMidPoint}}),Ho({id:gi.AddRichText,up:(t)=>{t.richText=Kt(t.text),delete t.text}}),Ho({id:gi.AddRichTextAttrs,up:(t)=>{},down:(t)=>{if(t.richText&&"attrs"in t.richText)delete t.richText.attrs}})]});var Lw=mo("center","edge-point","edge","none"),xp={terminal:mo("start","end"),normalizedAnchor:hi,isExact:$e,isPrecise:$e,snap:Lw},jw=yp("arrow",{AddSnap:1}),_p=gp({sequence:[{dependsOn:[gi.ExtractBindings]},{id:jw.AddSnap,up:(t)=>{t.snap="none"},down:(t)=>{delete t.snap}}]});var Q1=Cn("camera",ke({typeName:Ct("camera"),id:Le("camera"),x:_e,y:_e,z:_e,meta:xt})),eP=Je("com.tldraw.camera",{AddMeta:1}),Uw=Ye({sequenceId:"com.tldraw.camera",recordType:"camera",sequence:[{id:eP.AddMeta,up:(t)=>{t.meta={}}}]}),Vo=st("camera",{validator:Q1,scope:"session"}).withDefaultProperties(()=>({x:0,y:0,z:1,meta:{}}));var Fw=new Set(["none","default","pointer","cross","comment","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"]),Ip=iu(Fw),qw=ke({type:Ip,rotation:_e});var Bw=new Set(["accent","white","black","selection-stroke","selection-fill","laser","muted-1"]),Tp=iu(Bw);var Ww=new Set(["starting","paused","active","complete","stopping"]),wc=ke({id:Ne,points:un(hi),size:mc,color:Tp,opacity:_e,state:iu(Ww),delay:_e,shrink:_e,taper:$e});var Ia=Le("page"),tP=Cn("page",ke({typeName:Ct("page"),id:Ia,name:Ne,index:up,meta:xt})),rP=Je("com.tldraw.page",{AddMeta:1}),Hw=Ye({sequenceId:"com.tldraw.page",recordType:"page",sequence:[{id:rP.AddMeta,up:(t)=>{t.meta={}}}]}),Sc=st("page",{validator:tP,scope:"document"}).withDefaultProperties(()=>({meta:{}}));var Zs=Le("user"),nP=Je("com.tldraw.user",{Initial:1}),Vw=Ye({sequenceId:"com.tldraw.user",recordType:"user",sequence:[{id:nP.Initial,up:(t)=>{}}]});function uu(t){let n=t?.meta,i=n?ke(Object.fromEntries(Object.entries(n).map(([a,c])=>[a,new Qe((h)=>{if(h===void 0)return;return c.validate(h)})]))).allowUnknownProperties():xt,o=Cn("user",ke({typeName:Ct("user"),id:Zs,name:Ne,color:Ne,imageUrl:Ne,meta:i}));return st("user",{validator:o,scope:"document"}).withDefaultProperties(()=>({name:"",color:"",imageUrl:"",meta:{}}))}var CW=Cn("user",ke({typeName:Ct("user"),id:Zs,name:Ne,color:Ne,imageUrl:Ne,meta:xt})),Rp=uu();var BW=Le("instance");function zw(t){let n={};for(let[o,a]of t)n[o]=Iw(a);let i=Cn("instance",ke({typeName:Ct("instance"),id:Le("instance"),currentPageId:Ia,followingUserId:Zs.nullable(),brush:yo.nullable(),opacityForNextShape:yc,stylesForNextShape:ke(n),cursor:qw,scribbles:un(wc),isFocusMode:$e,isDebugMode:$e,isToolLocked:$e,exportBackground:$e,screenBounds:yo,insets:un($e),zoomBrush:yo.nullable(),isPenMode:$e,isGridMode:$e,chatMessage:Ne,isChatting:$e,highlightedUserIds:un(Zs),isFocused:$e,devicePixelRatio:_e,isCoarsePointer:$e,isHoveringCanvas:$e.nullable(),openMenus:un(Ne),isChangingStyle:$e,isReadonly:$e,meta:xt,duplicateProps:ke({shapeIds:un(Le("shape")),offset:ke({x:_e,y:_e})}).nullable(),cameraState:mo("idle","moving")}));return st("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:!0,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 at=Je("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}),Gw=Ye({sequenceId:"com.tldraw.instance",recordType:"instance",sequence:[{id:at.AddTransparentExportBgs,up:(t)=>({...t,exportBackground:!0})},{id:at.RemoveDialog,up:({dialog:t,...n})=>n},{id:at.AddToolLockMode,up:(t)=>({...t,isToolLocked:!1})},{id:at.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:at.AddLabelColor,up:({propsForNextShape:t,...n})=>({...n,propsForNextShape:{...t,labelColor:"black"}})},{id:at.AddFollowingUserId,up:(t)=>({...t,followingUserId:null})},{id:at.RemoveAlignJustify,up:(t)=>{let n=t.propsForNextShape.align;if(n==="justify")n="start";return{...t,propsForNextShape:{...t.propsForNextShape,align:n}}}},{id:at.AddZoom,up:(t)=>({...t,zoomBrush:null})},{id:at.AddVerticalAlign,up:(t)=>({...t,propsForNextShape:{...t.propsForNextShape,verticalAlign:"middle"}})},{id:at.AddScribbleDelay,up:(t)=>{if(t.scribble!==null)return{...t,scribble:{...t.scribble,delay:0}};return{...t}}},{id:at.RemoveUserId,up:({userId:t,...n})=>n},{id:at.AddIsPenModeAndIsGridMode,up:(t)=>({...t,isPenMode:!1,isGridMode:!1})},{id:at.HoistOpacity,up:({propsForNextShape:{opacity:t,...n},...i})=>({...i,opacityForNextShape:Number(t??"1"),propsForNextShape:n})},{id:at.AddChat,up:(t)=>({...t,chatMessage:"",isChatting:!1})},{id:at.AddHighlightedUserIds,up:(t)=>({...t,highlightedUserIds:[]})},{id:at.ReplacePropsForNextShapeWithStylesForNextShape,up:({propsForNextShape:t,...n})=>({...n,stylesForNextShape:{}})},{id:at.AddMeta,up:(t)=>({...t,meta:{}})},{id:at.RemoveCursorColor,up:(t)=>{let{color:n,...i}=t.cursor;return{...t,cursor:i}}},{id:at.AddLonelyProperties,up:(t)=>({...t,canMoveCamera:!0,isFocused:!1,devicePixelRatio:1,isCoarsePointer:!1,openMenus:[],isChangingStyle:!1,isReadOnly:!1})},{id:at.ReadOnlyReadonly,up:({isReadOnly:t,...n})=>({...n,isReadonly:t})},{id:at.AddHoveringCanvas,up:(t)=>({...t,isHoveringCanvas:null})},{id:at.AddScribbles,up:({scribble:t,...n})=>({...n,scribbles:[]})},{id:at.AddInset,up:(t)=>({...t,insets:[!1,!1,!1,!1]}),down:({insets:t,...n})=>({...n})},{id:at.AddDuplicateProps,up:(t)=>({...t,duplicateProps:null}),down:({duplicateProps:t,...n})=>({...n})},{id:at.RemoveCanMoveCamera,up:({canMoveCamera:t,...n})=>({...n}),down:(t)=>({...t,canMoveCamera:!0})},{id:at.AddCameraState,up:(t)=>({...t,cameraState:"idle"}),down:({cameraState:t,...n})=>n}]}),bc="instance:instance";var iP=Cn("instance_page_state",ke({typeName:Ct("instance_page_state"),id:Le("instance_page_state"),pageId:Ia,selectedShapeIds:un(En),hintingShapeIds:un(En),erasingShapeIds:un(En),hoveredShapeId:En.nullable(),editingShapeId:En.nullable(),croppingShapeId:En.nullable(),focusedGroupId:En.nullable(),meta:xt})),vc=Je("com.tldraw.instance_page_state",{AddCroppingId:1,RemoveInstanceIdAndCameraId:2,AddMeta:3,RenameProperties:4,RenamePropertiesAgain:5}),Kw=Ye({sequenceId:"com.tldraw.instance_page_state",recordType:"instance_page_state",sequence:[{id:vc.AddCroppingId,up(t){t.croppingShapeId=null}},{id:vc.RemoveInstanceIdAndCameraId,up(t){delete t.instanceId,delete t.cameraId}},{id:vc.AddMeta,up:(t)=>{t.meta={}}},{id:vc.RenameProperties,up:(t)=>{},down:(t)=>{}},{id:vc.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}}]}),wo=st("instance_page_state",{validator:iP,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 sP=Cn("pointer",ke({typeName:Ct("pointer"),id:Le("pointer"),x:_e,y:_e,lastActivityTimestamp:_e,meta:xt})),oP=Je("com.tldraw.pointer",{AddMeta:1}),Jw=Ye({sequenceId:"com.tldraw.pointer",recordType:"pointer",sequence:[{id:oP.AddMeta,up:(t)=>{t.meta={}}}]}),Ta=st("pointer",{validator:sP,scope:"session"}).withDefaultProperties(()=>({x:0,y:0,lastActivityTimestamp:0,meta:{}})),Ec=Ta.createId("pointer");var aP=Cn("instance_presence",ke({typeName:Ct("instance_presence"),id:Le("instance_presence"),userId:Zs,userName:Ne,lastActivityTimestamp:_e.nullable(),followingUserId:Zs.nullable(),cursor:ke({x:_e,y:_e,type:Ip,rotation:_e}).nullable(),color:Ne,camera:ke({x:_e,y:_e,z:_e}).nullable(),screenBounds:yo.nullable(),selectedShapeIds:un(Le("shape")),currentPageId:Le("page"),brush:yo.nullable(),scribbles:un(wc),chatMessage:Ne,meta:xt})),Ra=Je("com.tldraw.instance_presence",{AddScribbleDelay:1,RemoveInstanceId:2,AddChatMessage:3,AddMeta:4,RenameSelectedShapeIds:5,NullableCameraCursor:6}),Yw=Ye({sequenceId:"com.tldraw.instance_presence",recordType:"instance_presence",sequence:[{id:Ra.AddScribbleDelay,up:(t)=>{if(t.scribble!==null)t.scribble.delay=0}},{id:Ra.RemoveInstanceId,up:(t)=>{delete t.instanceId}},{id:Ra.AddChatMessage,up:(t)=>{t.chatMessage=""}},{id:Ra.AddMeta,up:(t)=>{t.meta={}}},{id:Ra.RenameSelectedShapeIds,up:(t)=>{}},{id:Ra.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}}}]}),du=st("instance_presence",{validator:aP,scope:"presence"}).withDefaultProperties(()=>({lastActivityTimestamp:null,followingUserId:null,color:"#FF0000",camera:null,cursor:null,screenBounds:null,selectedShapeIds:[],brush:null,scribbles:[],chatMessage:"",meta:{}}));var cP=Je("com.tldraw.asset",{AddMeta:1}),Pp=Ye({sequenceId:"com.tldraw.asset",recordType:"asset",sequence:[{id:cP.AddMeta,up:(t)=>{t.meta={}}}]});function Cp(t){return st("asset",{scope:"document",validator:Cn("asset",nu("type",Ci(t,(n,{props:i,meta:o})=>Ks(n,i,o))))}).withDefaultProperties(()=>({meta:{}}))}var Op=st("asset",{scope:"document"}).withDefaultProperties(()=>({meta:{}}));function Xw(t,n){return st(t,{scope:n.scope,validator:n.validator}).withDefaultProperties(n.createDefaultProperties??(()=>({})))}function Zw(t){let n=[];for(let[i,o]of Object.entries(t)){let a=`com.tldraw.${i}`,{migrations:c}=o;if(!c)n.push(bn({sequenceId:a,retroactive:!0,sequence:[]}));else if("sequenceId"in c)Ve(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(bn({sequenceId:a,retroactive:!0,sequence:c.sequence.map((h)=>{if(!("id"in h))return h;return{id:h.id,dependsOn:h.dependsOn,scope:"record",filter:(w)=>w.typeName===i,up:(w)=>{let E=h.up(w);if(E)return E},down:typeof h.down==="function"?(w)=>{let E=h.down(w);if(E)return E}:void 0}})}))}return n}var lP=Cn("document",ke({typeName:Ct("document"),id:Ct("document:document"),gridSize:_e,name:Ne,meta:xt}));var Qw=Je("com.tldraw.document",{AddName:1,AddMeta:2}),eS=Ye({sequenceId:"com.tldraw.document",recordType:"document",sequence:[{id:Qw.AddName,up:(t)=>{t.name=""},down:(t)=>{delete t.name}},{id:Qw.AddMeta,up:(t)=>{t.meta={}}}]}),Pa=st("document",{validator:lP,scope:"document"}).withDefaultProperties(()=>({gridSize:10,name:"",meta:{}})),fu=Pa.createId("document");var uP=new Set(["http:","https:","mailto:"]);function Ni(t){if(!vr.isValid(t))return!1;if(t===""||t.startsWith("/")||t.startsWith("./"))return!0;return uP.has(new URL(t).protocol.toLowerCase())}var kp={w:Nt,h:Nt,assetId:go.nullable(),url:vr},pu=ht("bookmark",{NullAssetId:1,MakeUrlsValid:2,AllowAppLinkUrls:3,BlockMoreLinkProtocols:4}),Mp=pt({sequence:[{id:pu.NullAssetId,up:(t)=>{if(t.assetId===void 0)t.assetId=null},down:"retired"},{id:pu.MakeUrlsValid,up:(t)=>{if(!vr.isValid(t.url))t.url=""},down:(t)=>{}},{id:pu.AllowAppLinkUrls,up:(t)=>{},down:(t)=>{if(!Ni(t.url))t.url=""}},{id:pu.BlockMoreLinkProtocols,up:(t)=>{if(!vr.isValid(t.url))t.url=""},down:(t)=>{}}]});var So=2,Np=3;var Di=new Uint8Array(128);for(let t=0;t<64;t++)Di["ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charCodeAt(t)]=t;var Qs=63,tS=61,nS=new Float64Array(31);for(let t=0;t<31;t++)nS[t]=Math.pow(2,t-15);var rS=Math.pow(2,-14)/1024,iS=new Float64Array(1024);for(let t=0;t<1024;t++)iS[t]=1+t/1024;function dP(t,n){return t.getFloat16(n,!0)}function fP(t,n){return SP(t.getUint16(n,!0))}var xn=typeof DataView.prototype.getFloat16==="function"?dP:fP;function pP(t,n,i){t.setFloat16(n,i,!0)}function hP(t,n,i){t.setUint16(n,bP(i),!0)}var yi=typeof DataView.prototype.setFloat16==="function"?pP:hP;function mP(t){return Uint8Array.fromBase64(t)}function gP(t){let n=t.length,i=0;if(n>0&&t.charCodeAt(n-1)===tS){if(i++,n>1&&t.charCodeAt(n-2)===tS)i++}let o=Math.floor(n*3/4)-i,a=new Uint8Array(o),c=0,h=Math.floor((n-i)/4)*4;for(let w=0;w<h;w+=4){let E=Di[t.charCodeAt(w)],_=Di[t.charCodeAt(w+1)],I=Di[t.charCodeAt(w+2)],T=Di[t.charCodeAt(w+3)],O=E<<18|_<<12|I<<6|T;a[c++]=O>>16&255,a[c++]=O>>8&255,a[c++]=O&255}if(i===1){let w=Di[t.charCodeAt(h)],E=Di[t.charCodeAt(h+1)],_=Di[t.charCodeAt(h+2)],I=w<<18|E<<12|_<<6;a[c++]=I>>16&255,a[c++]=I>>8&255}else if(i===2){let w=Di[t.charCodeAt(h)],E=Di[t.charCodeAt(h+1)],_=w<<18|E<<12;a[c++]=_>>16&255}return a}function yP(t){return t.toBase64()}function wP(t){let n=t.length,i=Math.floor(n/3)*3,o="";for(let c=0;c<i;c+=3){let h=t[c],w=t[c+1],E=t[c+2],_=h<<16|w<<8|E;o+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[_>>18&Qs]+"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[_>>12&Qs]+"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[_>>6&Qs]+"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[_&Qs]}let a=n-i;if(a===1){let c=t[i]<<16;o+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[c>>18&Qs]+"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[c>>12&Qs]+"=="}else if(a===2){let c=t[i]<<16|t[i+1]<<8;o+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[c>>18&Qs]+"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[c>>12&Qs]+"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[c>>6&Qs]+"="}return o}var hu=typeof Uint8Array.prototype.toBase64==="function"?yP:wP,zo=typeof Uint8Array.fromBase64==="function"?mP:gP;function SP(t){let n=t>>15,i=t>>10&31,o=t&1023;if(i===0)return n?-o*rS:o*rS;if(i===31)return o?NaN:n?-1/0:1/0;let a=nS[i]*iS[o];return n?-a:a}function bP(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 h=Math.round(t*Math.pow(2,14)*1024);return n<<15|h&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 Mt{static _legacyEncodePoint(t,n,i){let o=new Uint8Array(6),a=new DataView(o.buffer);return yi(a,0,t),yi(a,2,n),yi(a,4,i),hu(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;yi(i,c,a.x),yi(i,c+2,a.y),yi(i,c+4,a.z??0.5)}return hu(n)}static _legacyDecodePoints(t){let n=zo(t),i=new DataView(n.buffer,n.byteOffset,n.byteLength),o=[];for(let a=0;a<n.length;a+=6)o.push({x:xn(i,a),y:xn(i,a+2),z:xn(i,a+4)});return o}static encodePoints(t,n){if(n===2)return Mt.encodePoints2D(t);if(t.length===0)return"";let i=12,o=(t.length-1)*6,a=i+o,c=new Uint8Array(a),h=new DataView(c.buffer),w=t[0];h.setFloat32(0,w.x,!0),h.setFloat32(4,w.y,!0),h.setFloat32(8,w.z??0.5,!0);let{x:E,y:_}=w,I=w.z??0.5;for(let T=1;T<t.length;T++){let O=t[T],N=O.z??0.5,L=i+(T-1)*6;yi(h,L,O.x-E),yi(h,L+2,O.y-_),yi(h,L+4,N-I),E=O.x,_=O.y,I=N}return hu(c)}static decodePoints(t,n){if(n===2)return Mt.decodePoints2D(t);if(t.length===0)return[];let i=zo(t),o=new DataView(i.buffer,i.byteOffset,i.byteLength),a=[],c=o.getFloat32(0,!0),h=o.getFloat32(4,!0),w=o.getFloat32(8,!0);a.push({x:c,y:h,z:w});let E=12;for(let _=E;_<i.length;_+=6)c+=xn(o,_),h+=xn(o,_+2),w+=xn(o,_+4),a.push({x:c,y:h,z:w});return a}static decodeFirstPoint(t,n){if(n===2)return Mt.decodeFirstPoint2D(t);if(t.length<16)return null;let i=zo(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 Mt.decodeLastPoint2D(t);if(t.length<16)return null;let i=zo(t),o=new DataView(i.buffer,i.byteOffset,i.byteLength),a=o.getFloat32(0,!0),c=o.getFloat32(4,!0),h=o.getFloat32(8,!0),w=12;for(let E=w;E<i.length;E+=6)a+=xn(o,E),c+=xn(o,E+2),h+=xn(o,E+4);return{x:a,y:c,z:h}}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:h,y:w}=c;for(let E=1;E<t.length;E++){let _=t[E],I=n+(E-1)*4;yi(a,I,_.x-h),yi(a,I+2,_.y-w),h=_.x,w=_.y}return hu(o)}static decodePoints2D(t){if(t.length===0)return[];let n=zo(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 h=8;for(let w=h;w<n.length;w+=4)a+=xn(i,w),c+=xn(i,w+2),o.push({x:a,y:c,z:0.5});return o}static decodeFirstPoint2D(t){if(t.length<12)return null;let n=zo(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=zo(t),i=new DataView(n.buffer,n.byteOffset,n.byteLength),o=i.getFloat32(0,!0),a=i.getFloat32(4,!0),c=8;for(let h=c;h<n.length;h+=4)o+=xn(i,h),a+=xn(i,h+2);return{x:o,y:a,z:0.5}}static isSinglePoint(t,n){return t.length<=(n===2?12:16)}}var Dp=ke({type:mo("free","straight"),path:Ne,dim:mo(So,Np).optional()}),$p={color:hr,fill:Wo,dash:Ys,size:Nr,segments:un(Dp),isComplete:$e,isClosed:$e,isPen:$e,scale:Nt,scaleX:ru,scaleY:ru},Ac=ht("draw",{AddInPen:1,AddScale:2,Base64:3,LegacyPointsConversion:4,OmitNonPressureZ:5}),Lp=pt({sequence:[{id:Ac.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:Ac.AddScale,up:(t)=>{t.scale=1},down:(t)=>{delete t.scale}},{id:Ac.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:Mt._legacyDecodePoints(i);return{...o,path:Mt.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:Mt.decodePoints(i)}}),delete t.scaleX,delete t.scaleY}},{id:Ac.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:Mt._legacyDecodePoints(i);return{...o,path:Mt.encodePoints(a)}})},down:(t)=>{}},{id:Ac.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===So?{...o,path:Mt.encodePoints(Mt.decodePoints(n.path,So))}:o})}}]});var vP=/(^\/r\/[^/]+\/?$)/,EP=[{hostnames:["beta.tldraw.com","tldraw.com","localhost:3000"],canEditWhileLocked:!0,fromEmbedUrl:(t)=>{let n=fr(t);if(n&&n.pathname.match(vP))return t;return}},{hostnames:["figma.com"],canEditWhileLocked:!0,fromEmbedUrl:(t)=>{let n=fr(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=fr(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=fr(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=fr(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=fr(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=fr(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=fr(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=fr(t);if(n&&n.pathname.match(/\/([^/]+)\/([^/]+)/)){if(!t.split("/").pop())return;return t}return}},{hostnames:["replit.com"],canEditWhileLocked:!0,fromEmbedUrl:(t)=>{let n=fr(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=fr(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=fr(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=fr(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=fr(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=fr(t);if(n&&n.hostname==="www.desmos.com"&&n.pathname.match(/^\/calculator\/([^/]+)\/?$/)&&n.search==="?embed"&&n.hash==="")return t.replace("?embed","");return}}],jp={w:Nt,h:Nt,url:Ne},mu=ht("embed",{GenOriginalUrlInEmbed:1,RemoveDoesResize:2,RemoveTmpOldUrl:3,RemovePermissionOverrides:4}),Up=pt({sequence:[{id:mu.GenOriginalUrlInEmbed,up:(t)=>{try{let n=t.url,i=new URL(n).host.replace("www.",""),o;for(let a of EP)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:mu.RemoveDoesResize,up:(t)=>{delete t.doesResize},down:"retired"},{id:mu.RemoveTmpOldUrl,up:(t)=>{delete t.tmpOldUrl},down:"retired"},{id:mu.RemovePermissionOverrides,up:(t)=>{delete t.overridePermissions},down:"retired"}]});var Fp={w:Nt,h:Nt,name:Ne,color:{validate:(t)=>hr.validate(t)}},AP=ht("frame",{AddColorProp:1}),qp=pt({sequence:[{id:AP.AddColorProp,up:(t)=>{t.color="black"},down:(t)=>{delete t.color}}]});var xc=Xe.defineEnum("tldraw:horizontalAlign",{defaultValue:"middle",values:["start","middle","end","start-legacy","end-legacy","middle-legacy"]});var _c=Xe.defineEnum("tldraw:verticalAlign",{defaultValue:"middle",values:["start","middle","end"]});var sS=Xe.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"]}),Bp={geo:sS,dash:Ys,url:vr,w:Nt,h:Nt,growY:mc,scale:Nt,flipX:$e,flipY:$e,labelColor:_a,color:hr,fill:Wo,size:Nr,font:Xs,align:xc,verticalAlign:_c,richText:mi},fn=ht("geo",{AddUrlProp:1,AddLabelColor:2,RemoveJustify:3,AddCheckBox:4,AddVerticalAlign:5,MigrateLegacyAlign:6,AddCloud:7,MakeUrlsValid:8,AddScale:9,AddRichText:10,AddRichTextAttrs:11,AddFlipProps:12,AllowAppLinkUrls:13,BlockMoreLinkProtocols:14}),Wp=pt({sequence:[{id:fn.AddUrlProp,up:(t)=>{t.url=""},down:"retired"},{id:fn.AddLabelColor,up:(t)=>{t.labelColor="black"},down:"retired"},{id:fn.RemoveJustify,up:(t)=>{if(t.align==="justify")t.align="start"},down:"retired"},{id:fn.AddCheckBox,up:(t)=>{},down:"retired"},{id:fn.AddVerticalAlign,up:(t)=>{t.verticalAlign="middle"},down:"retired"},{id:fn.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:fn.AddCloud,up:(t)=>{},down:"retired"},{id:fn.MakeUrlsValid,up:(t)=>{if(!vr.isValid(t.url))t.url=""},down:(t)=>{}},{id:fn.AddScale,up:(t)=>{t.scale=1},down:(t)=>{delete t.scale}},{id:fn.AddRichText,up:(t)=>{t.richText=Kt(t.text),delete t.text}},{id:fn.AddRichTextAttrs,up:(t)=>{},down:(t)=>{if(t.richText&&"attrs"in t.richText)delete t.richText.attrs}},{id:fn.AddFlipProps,up:(t)=>{t.flipX=!1,t.flipY=!1},down:(t)=>{delete t.flipX,delete t.flipY}},{id:fn.AllowAppLinkUrls,up:(t)=>{},down:(t)=>{if(!Ni(t.url))t.url=""}},{id:fn.BlockMoreLinkProtocols,up:(t)=>{if(!vr.isValid(t.url))t.url=""},down:(t)=>{}}]});var Hp={},Vp=pt({sequence:[]});var zp={color:hr,size:Nr,segments:un(Dp),isComplete:$e,isPen:$e,scale:Nt,scaleX:ru,scaleY:ru},gu=ht("highlight",{AddScale:1,Base64:2,LegacyPointsConversion:3,OmitNonPressureZ:4}),Gp=pt({sequence:[{id:gu.AddScale,up:(t)=>{t.scale=1},down:(t)=>{delete t.scale}},{id:gu.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:Mt._legacyDecodePoints(i);return{...o,path:Mt.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:Mt.decodePoints(i)}}),delete t.scaleX,delete t.scaleY}},{id:gu.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:Mt._legacyDecodePoints(i);return{...o,path:Mt.encodePoints(a)}})},down:(t)=>{}},{id:gu.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===So?{...o,path:Mt.encodePoints(Mt.decodePoints(n.path,So))}:o})}}]});var oS=ke({topLeft:hi,bottomRight:hi,isCircle:$e.optional()}),Kp={w:Nt,h:Nt,playing:$e,url:vr,assetId:go.nullable(),crop:oS.nullable(),flipX:$e,flipY:$e,altText:Ne},Go=ht("image",{AddUrlProp:1,AddCropProp:2,MakeUrlsValid:3,AddFlipProps:4,AddAltText:5,AllowAppLinkUrls:6,BlockMoreLinkProtocols:7}),Jp=pt({sequence:[{id:Go.AddUrlProp,up:(t)=>{t.url=""},down:"retired"},{id:Go.AddCropProp,up:(t)=>{t.crop=null},down:(t)=>{delete t.crop}},{id:Go.MakeUrlsValid,up:(t)=>{if(!vr.isValid(t.url))t.url=""},down:(t)=>{}},{id:Go.AddFlipProps,up:(t)=>{t.flipX=!1,t.flipY=!1},down:(t)=>{delete t.flipX,delete t.flipY}},{id:Go.AddAltText,up:(t)=>{t.altText=""},down:(t)=>{delete t.altText}},{id:Go.AllowAppLinkUrls,up:(t)=>{},down:(t)=>{if(!Ni(t.url))t.url=""}},{id:Go.BlockMoreLinkProtocols,up:(t)=>{if(!vr.isValid(t.url))t.url=""},down:(t)=>{}}]});var aS=Xe.defineEnum("tldraw:spline",{defaultValue:"line",values:["cubic","line"]}),xP=ke({id:Ne,index:up,x:_e,y:_e}),Yp={color:hr,dash:Ys,size:Nr,spline:aS,points:z1(Ne,xP),scale:Nt},Ic=ht("line",{AddSnapHandles:1,RemoveExtraHandleProps:2,HandlesToPoints:3,PointIndexIds:4,AddScale:5}),Xp=pt({sequence:[{id:Ic.AddSnapHandles,up:(t)=>{for(let n of Object.values(t.handles))n.canSnap=!0},down:"retired"},{id:Ic.RemoveExtraHandleProps,up:(t)=>{t.handles=nc(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(jo);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:Ic.HandlesToPoints,up:(t)=>{let n=Object.entries(t.handles).map(([i,{x:o,y:a}])=>({x:o,y:a,index:i})).sort(jo);t.points=n.map(({x:i,y:o})=>({x:i,y:o})),delete t.handles},down:(t)=>{let n=Fl(t.points.length);t.handles=Object.fromEntries(t.points.map((i,o)=>[n[o],{x:i.x,y:i.y}])),delete t.points}},{id:Ic.PointIndexIds,up:(t)=>{let n=Fl(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(jo);t.points=n.map(({x:i,y:o})=>({x:i,y:o}))}},{id:Ic.AddScale,up:(t)=>{t.scale=1},down:(t)=>{delete t.scale}}]});var Zp={color:hr,labelColor:_a,size:Nr,font:Xs,fontSizeAdjustment:mc.nullable(),align:xc,verticalAlign:_c,growY:mc,url:vr,richText:mi,scale:Nt,textLastEditedBy:Ne.nullable()},en=ht("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,AllowAppLinkUrls:14,BlockMoreLinkProtocols:15}),Qp=pt({sequence:[{id:en.AddUrlProp,up:(t)=>{t.url=""},down:"retired"},{id:en.RemoveJustify,up:(t)=>{if(t.align==="justify")t.align="start"},down:"retired"},{id:en.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:en.AddVerticalAlign,up:(t)=>{t.verticalAlign="middle"},down:"retired"},{id:en.MakeUrlsValid,up:(t)=>{if(!vr.isValid(t.url))t.url=""},down:(t)=>{}},{id:en.AddFontSizeAdjustment,up:(t)=>{t.fontSizeAdjustment=0},down:(t)=>{delete t.fontSizeAdjustment}},{id:en.AddScale,up:(t)=>{t.scale=1},down:(t)=>{delete t.scale}},{id:en.AddLabelColor,up:(t)=>{t.labelColor="black"},down:(t)=>{delete t.labelColor}},{id:en.AddRichText,up:(t)=>{t.richText=Kt(t.text),delete t.text}},{id:en.AddRichTextAttrs,up:(t)=>{},down:(t)=>{if(t.richText&&"attrs"in t.richText)delete t.richText.attrs}},{id:en.AddFirstEditedBy,up:(t)=>{t.textFirstEditedBy=null},down:(t)=>{delete t.textFirstEditedBy}},{id:en.MakeFontSizeAdjustmentRatio,up:(t)=>{t.fontSizeAdjustment=t.fontSizeAdjustment===0?1:null},down:(t)=>{t.fontSizeAdjustment=0}},{id:en.RenameFirstEditedByToLast,up:(t)=>{t.textLastEditedBy=t.textFirstEditedBy??null,delete t.textFirstEditedBy},down:(t)=>{t.textFirstEditedBy=t.textLastEditedBy??null,delete t.textLastEditedBy}},{id:en.AllowAppLinkUrls,up:(t)=>{},down:(t)=>{if(!Ni(t.url))t.url=""}},{id:en.BlockMoreLinkProtocols,up:(t)=>{if(!vr.isValid(t.url))t.url=""},down:(t)=>{}}]});var eh=Xe.defineEnum("tldraw:textAlign",{defaultValue:"start",values:["start","middle","end"]});var th={color:hr,size:Nr,font:Xs,textAlign:eh,w:Nt,richText:mi,scale:Nt,autoSize:$e},yu=ht("text",{RemoveJustify:1,AddTextAlign:2,AddRichText:3,AddRichTextAttrs:4}),rh=pt({sequence:[{id:yu.RemoveJustify,up:(t)=>{if(t.align==="justify")t.align="start"},down:"retired"},{id:yu.AddTextAlign,up:(t)=>{t.textAlign=t.align,delete t.align},down:(t)=>{t.align=t.textAlign,delete t.textAlign}},{id:yu.AddRichText,up:(t)=>{t.richText=Kt(t.text),delete t.text}},{id:yu.AddRichTextAttrs,up:(t)=>{},down:(t)=>{if(t.richText&&"attrs"in t.richText)delete t.richText.attrs}}]});var nh={w:Nt,h:Nt,time:_e,playing:$e,autoplay:$e,url:vr,assetId:go.nullable(),altText:Ne},Ca=ht("video",{AddUrlProp:1,MakeUrlsValid:2,AddAltText:3,AddAutoplay:4,AllowAppLinkUrls:5,BlockMoreLinkProtocols:6}),ih=pt({sequence:[{id:Ca.AddUrlProp,up:(t)=>{t.url=""},down:"retired"},{id:Ca.MakeUrlsValid,up:(t)=>{if(!vr.isValid(t.url))t.url=""},down:(t)=>{}},{id:Ca.AddAltText,up:(t)=>{t.altText=""},down:(t)=>{delete t.altText}},{id:Ca.AddAutoplay,up:(t)=>{t.autoplay=!0},down:(t)=>{delete t.autoplay}},{id:Ca.AllowAppLinkUrls,up:(t)=>{},down:(t)=>{if(!Ni(t.url))t.url=""}},{id:Ca.BlockMoreLinkProtocols,up:(t)=>{if(!vr.isValid(t.url))t.url=""},down:(t)=>{}}]});var Tc=Je("com.tldraw.store",{RemoveCodeAndIconShapeTypes:1,AddInstancePresenceType:2,RemoveTLUserAndPresenceAndAddPointer:3,RemoveUserDocument:4,FixIndexKeys:5}),uS=bn({sequenceId:"com.tldraw.store",retroactive:!1,sequence:[{id:Tc.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:Tc.AddInstancePresenceType,scope:"storage",up(t){}},{id:Tc.RemoveTLUserAndPresenceAndAddPointer,scope:"storage",up:(t)=>{for(let[n,i]of t.entries())if(i.typeName.match(/^(user|user_presence)$/))t.delete(n)}},{id:Tc.RemoveUserDocument,scope:"storage",up:(t)=>{for(let[n,i]of t.entries())if(i.typeName.match("user_document"))t.delete(n)}},{id:Tc.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)+lS(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)+lS(3)}}},down:()=>{}}]}),cS="123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",_P=()=>cS.charAt(Math.floor(Math.random()*cS.length)),lS=(t)=>Array.from({length:t},_P).join("");function dS(t){if(t.typeName==="asset"){if("src"in t)t.src="<redacted>";if("src"in t.props)t.props.src="<redacted>"}}function fS({error:t,phase:n,record:i,recordBefore:o}){throw _f(t,{tags:{origin:"store.validateRecord",storePhase:n,isExistingValidationIssue:n==="initialize"},extras:{recordBefore:o?dS(an(o)):void 0,recordAfter:dS(an(i))}}),t}function IP(){return[Sc.create({id:"page:page",name:"Page 1",index:"a1",meta:{}})]}function pS(t){let n=t.query.ids("page"),i=t.query.records("instance_page_state"),o=()=>{if(!t.has(fu))return t.put([Pa.create({id:fu,name:t.props.defaultName})]),o();if(!t.has(Ec))return t.put([Ta.create({id:Ec})]),o();let a=n.get();if(a.size===0)return t.put(IP()),o();let c=()=>[...a].map((I)=>t.get(I)).sort(jo)[0].id,h=t.get(bc);if(!h)return t.put([t.schema.types.instance.create({id:bc,currentPageId:c()})]),o();else if(!a.has(h.currentPageId))return t.put([{...h,currentPageId:c()}]),o();let w=new Set,E=new Set;for(let I of a){let T=wo.createId(I);if(!t.get(T))w.add(T);let N=Vo.createId(I);if(!t.has(N))E.add(N)}if(w.size>0)t.put([...w].map((I)=>wo.create({id:I,pageId:wo.parseId(I)})));if(E.size>0)t.put([...E].map((I)=>Vo.create({id:I})));let _=i.get();for(let I of _){if(!a.has(I.pageId)){t.remove([I.id]);continue}if(I.croppingShapeId&&!t.has(I.croppingShapeId))return t.put([{...I,croppingShapeId:null}]),o();if(I.focusedGroupId&&!t.has(I.focusedGroupId))return t.put([{...I,focusedGroupId:null}]),o();if(I.hoveredShapeId&&!t.has(I.hoveredShapeId))return t.put([{...I,hoveredShapeId:null}]),o();let T=I.selectedShapeIds.filter((L)=>t.has(L));if(T.length!==I.selectedShapeIds.length)return t.put([{...I,selectedShapeIds:T}]),o();let O=I.hintingShapeIds.filter((L)=>t.has(L));if(O.length!==I.hintingShapeIds.length)return t.put([{...I,hintingShapeIds:O}]),o();let N=I.erasingShapeIds.filter((L)=>t.has(L));if(N.length!==I.erasingShapeIds.length)return t.put([{...I,erasingShapeIds:N}]),o()}};return o}var hS={arrow:{migrations:Ap,props:Ep},bookmark:{migrations:Mp,props:kp},draw:{migrations:Lp,props:$p},embed:{migrations:Up,props:jp},frame:{migrations:qp,props:Fp},geo:{migrations:Wp,props:Bp},group:{migrations:Vp,props:Hp},highlight:{migrations:Gp,props:zp},image:{migrations:Jp,props:Kp},line:{migrations:Xp,props:Yp},note:{migrations:Qp,props:Zp},text:{migrations:rh,props:th},video:{migrations:ih,props:nh}},mS={arrow:{migrations:_p,props:xp}},gS={image:{migrations:fp,props:ou},video:{migrations:pp,props:au},bookmark:{migrations:dp,props:su}};function sh({shapes:t=hS,bindings:n=mS,assets:i=gS,user:o,records:a={},migrations:c}={}){let h=new Map;for(let L of Ri(t))for(let H of bp(L.props??{}).keys()){if(h.has(H.id)&&h.get(H.id)!==H)throw Error(`Multiple StyleProp instances with the same id: ${H.id}`);h.set(H.id,H)}let w=Ow(t),E=Cw(n),_=Cp(i),I=zw(h),T=o?uu(o):Rp,O=new Set(["asset","binding","camera","document","instance","instance_page_state","page","instance_presence","pointer","shape","store","user"]),N={};for(let[L,H]of Object.entries(a)){if(O.has(L))throw Error(`Custom record type name '${L}' conflicts with tldraw's built-in record type of that name. Choose a different name instead.`);N[L]=Xw(L,H)}return pc.create({asset:_,binding:E,camera:Vo,document:Pa,instance:I,instance_page_state:wo,page:Sc,instance_presence:du,pointer:Ta,shape:w,user:T,...N},{migrations:[uS,Pp,Uw,eS,Gw,Kw,Hw,Yw,Jw,Sp,Vw,...lu("asset",i),...lu("shape",t),...lu("binding",n),...Zw(a),...o?.migrations??[],...c??[]],onValidationFailure:fS,createIntegrityChecker:pS})}var PP=Ne.check((t)=>{if(t.length===0||t.length>64)throw new Se(`Expected an emoji of 1-64 characters, got ${t.length}`)}),CP=nu("type",{shape:ke({type:Ct("shape"),shapeId:Le("shape"),x:_e,y:_e,isPrecise:$e}),point:ke({type:Ct("point"),x:_e,y:_e}),region:ke({type:Ct("region"),x:_e,y:_e,w:_e,h:_e,pinX:_e.optional(),pinY:_e.optional()}),page:ke({type:Ct("page")})});function oh(t,n=[]){return Ye({sequenceId:`com.tldraw.${t}`,recordType:t,retroactive:!0,sequence:[{id:`com.tldraw.${t}/1`,up:(i)=>i},...n]})}var OP={scope:"document",migrations:oh("comment-thread",[{id:"com.tldraw.comment-thread/2",up:(t)=>{let n=t.anchor;if(n?.type==="shape"&&n.x===void 0)t.anchor={...n,x:1,y:0,isPrecise:!1};return t},down:(t)=>{let n=t.anchor;if(n?.type==="shape")t.anchor={type:"shape",shapeId:n.shapeId};return t}},{id:"com.tldraw.comment-thread/3",up:(t)=>t,down:(t)=>{let n=t.anchor;if(n?.type==="region"){let{pinX:i,pinY:o,...a}=n;t.anchor=a}return t}}]),validator:ke({id:Le("comment-thread"),typeName:Ct("comment-thread"),pageId:Le("page"),anchor:CP,createdBy:Ne,createdAt:_e,resolved:ke({at:_e,by:Ne}).nullable(),isDeleted:$e,meta:xt})},kP={scope:"document",migrations:oh("comment"),validator:ke({id:Le("comment"),typeName:Ct("comment"),threadId:Le("comment-thread"),pageId:Le("page"),authorId:Ne,createdAt:_e,editedAt:_e.nullable(),body:mi,isDeleted:$e,meta:xt})},MP={scope:"document",migrations:oh("comment-reaction"),validator:ke({id:Le("comment-reaction"),typeName:Ct("comment-reaction"),commentId:Le("comment"),threadId:Le("comment-thread"),pageId:Le("page"),userId:Ne,emoji:PP,createdAt:_e,meta:xt})};ei("@tldraw/tlschema","5.6.2","esm");function DP(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 yS(t,n){let i=DP(t);if(!i)return[];let o=[];for(let[a,c]of Object.entries(i)){let h=n[a];if(h===void 0)o.push({id:a,fileVersion:c});else if(c>h)o.push({id:a,fileVersion:c,runtimeVersion:h})}return o}function wS(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 SS={geo:{w:100,h:100,geo:"rectangle",flipX:!1,flipY:!1,dash:"draw",growY:0,url:"",scale:1,color:"black",labelColor:"black",fill:"none",size:"m",font:"draw",align:"middle",verticalAlign:"middle",richText:Kt("")},text:{color:"black",size:"m",w:8,font:"draw",textAlign:"start",autoSize:!0,scale:1,richText:Kt("")},note:{color:"black",richText:Kt(""),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:Kt(""),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 jP=(t)=>()=>{throw Error(`${t} is not available on the server-side scratchpad store`)},UP={defaultName:"",assets:{upload:jP("Asset upload"),resolve:()=>null,remove:async()=>{}},users:{currentUser:null,resolve:()=>null},onMount:()=>{}};function Rc(t){let n=SS[t];if(!n)throw Error(`Unknown shape type "${t}"`);return{...n}}function wu(t){return{...t.color?{color:t.color}:{},...t.size?{size:t.size}:{},...t.fill?{fill:t.fill}:{}}}function FP(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 qP(t,n){let i=new eu({schema:sh(),props:UP}),o=t?.store?t:{store:{},schema:i.schema.serialize()};try{FP(()=>i.loadStoreSnapshot(o))}catch(a){let c=yS(t?.schema,i.schema.serialize().sequences);if(c.length>0)throw Error(`Scratchpad was written by a newer Moi (${wS(n,c)}); this server has tldraw ${hn.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 ES(t){for(let n of t.allRecords())if(n.typeName==="page")return n.id;throw Error("Scratchpad has no page")}function Pc(t,n){let i=Rf;for(let o of t.allRecords())if(o.typeName==="shape"&&o.parentId===n&&o.index>i)i=o.index;return Cf(i)}function Cc(t){return{typeName:"shape",rotation:0,isLocked:!1,opacity:1,meta:{},...t}}function bS(t,n,i){return{id:xa(),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 BP={lo:{dim:768,quality:78},hi:{dim:2048,quality:88}},WP=52428800;async function HP(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>WP)throw Error(`Image is too large (${Math.round(a.length/1e6)}MB, max 50MB): ${t}`);let c=BP[n],{data:h,info:w}=await LP(a).rotate().resize(c.dim,c.dim,{fit:"inside",withoutEnlargement:!0}).webp({quality:c.quality}).toBuffer({resolveWithObject:!0});return{data:h,w:w.width,h:w.height,mimeType:"image/webp",name:$P(t)}}async function VP(t,n,i,o){let a=ES(t),c=t.get(An(i.name)),h=typeof c?.props?.assetId==="string"?c.props.assetId:void 0,{data:w,w:E,h:_,mimeType:I,name:T}=await HP(i.path,i.quality??"lo",o),{src:O}=await Pt(n,w,I),N=Op.createId();if(t.put([{id:N,typeName:"asset",type:"image",meta:{},props:{name:T,src:O,w:E,h:_,mimeType:I,isAnimated:!1}}]),t.put([Cc({id:An(i.name),type:"image",x:i.x,y:i.y,index:Pc(t,a),parentId:a,props:{...Rc("image"),w:E,h:_,assetId:N}})]),h&&h!==N&&!AS(t,h))t.remove([h]);return{name:i.name}}function zP(t,n){let i=ES(t),o=(a)=>{let c=t.get(An(a));if(!c||c.typeName!=="shape")throw Error(`No shape named "${a}"`);return c};switch(n.kind){case"add-rect":return t.put([Cc({id:An(n.name),type:"geo",x:n.x,y:n.y,index:Pc(t,i),parentId:i,props:{...Rc("geo"),geo:"rectangle",w:n.w,h:n.h,...wu(n),...n.text?{richText:Kt(n.text)}:{}}})]),{name:n.name};case"add-text":return t.put([Cc({id:An(n.name),type:"text",x:n.x,y:n.y,index:Pc(t,i),parentId:i,props:{...Rc("text"),richText:Kt(n.text),...wu(n)}})]),{name:n.name};case"add-note":return t.put([Cc({id:An(n.name),type:"note",x:n.x,y:n.y,index:Pc(t,i),parentId:i,props:{...Rc("note"),richText:Kt(n.text),...wu(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=An(n.name);t.put([Cc({id:a,type:"arrow",x:0,y:0,index:Pc(t,i),parentId:i,props:{...Rc("arrow"),...wu(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(bS(a,An(n.from.name),"start"));if("name"in n.to)c.push(bS(a,An(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:Kt(n.text)}}]),{ok:!0}}case"delete":{let a=An(n.name),c=t.get(a),h=typeof c?.props?.assetId==="string"?c.props.assetId:void 0,w=[a,...GP(t,n.name)];if(t.remove(w),h&&!AS(t,h))t.remove([h]);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 AS(t,n){for(let i of t.allRecords()){if(i.typeName!=="shape")continue;if(i.props?.assetId===n)return!0}return!1}function GP(t,n){let i=An(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 vS=new Map;function KP(t,n){let o=(vS.get(t)??Promise.resolve()).catch(()=>{}).then(n);return vS.set(t,o.catch(()=>{})),o}function Su(t,n,i,o){return KP(t,async()=>{let{document:a,writer:c}=await ct(t),h=qP(a,c),w=i.kind==="add-image"?await VP(h,t,i,o):zP(h,i),E=h.getStoreSnapshot();return await ur(E,t),m({type:"scratchpad:changed",workspaceId:n}),w})}var ah=(t,n,i)=>(o,a)=>{let c=-1;return h(0);async function h(w){if(w<=c)throw Error("next() called multiple times");c=w;let E,_=!1,I;if(t[w])I=t[w][0][0],o.req.routeIndex=w;else I=w===t.length&&a||void 0;if(I)try{E=await I(o,()=>h(w+1))}catch(T){if(T instanceof Error&&n)o.error=T,E=await n(T,o),_=!0;else throw T}else if(o.finalized===!1&&i)E=await i(o);if(E&&(o.finalized===!1||_))o.res=E;return o}};var xS=Symbol();var _S=(t,n)=>new Response(t,{headers:{"Content-Type":n.replace(/^[^;]+/,(o)=>o.toLowerCase())}}).formData();var IS=32,JP=1e4,bu=(t)=>("headers"in t),PS=async(t,n=Object.create(null))=>{let{all:i=!1,dot:o=!1}=n,h=(bu(t)?t.headers:t.raw.headers).get("Content-Type")?.split(";")[0].trim().toLowerCase();if(h==="multipart/form-data"||h==="application/x-www-form-urlencoded")return YP(t,{all:i,dot:o});return{}};async function YP(t,n){if(!bu(t)&&t.bodyCache.formData)return TS(await t.bodyCache.formData,n);let i=bu(t)?t.headers:t.raw.headers,o=await t.arrayBuffer(),a=_S(o,i.get("Content-Type")||"");if(!bu(t))t.bodyCache.formData=a;let c=await a;if(c)return TS(c,n);return{}}function TS(t,n){let i=Object.create(null),o={count:0};if(t.forEach((a,c)=>{if(!(n.all||c.endsWith("[]")))i[c]=a;else XP(i,c,a)}),n.dot)Object.entries(i).forEach(([a,c])=>{if(a.includes("."))ZP(i,a,c,o),delete i[a]});return i}var XP=(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]},ZP=(t,n,i,o)=>{if(/(?:^|\.)__proto__\./.test(n))return;let a=t,c=n.split(".",IS+2);if(c.length>IS+1)RS();c.forEach((h,w)=>{if(w===c.length-1)a[h]=i;else{if(!a[h]||typeof a[h]!=="object"||Array.isArray(a[h])||a[h]instanceof File){if(o.count++>=JP)RS();a[h]=Object.create(null)}a=a[h]}})},RS=()=>{throw Error("Nesting limit exceeded")};var lh=(t)=>{let n=t.split("/");if(n[0]==="")n.shift();return n},CS=(t)=>{let{groups:n,path:i}=QP(t),o=lh(i);return eC(o,n)},QP=(t)=>{let n=[];return t=t.replace(/\{[^}]+\}/g,(i,o)=>{let a=`@${o}`;return n.push([a,i]),a}),{groups:n,path:t}},eC=(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},vu={},OS=(t,n)=>{if(t==="*")return"*";let i=t.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);if(i){let o=`${t}#${n}`;if(!vu[o])if(i[2])vu[o]=n&&n[0]!==":"&&n[0]!=="*"?[o,i[1],new RegExp(`^${i[2]}(?=/${n})`)]:[t,i[1],new RegExp(`^${i[2]}$`)];else vu[o]=[t,i[1],!0];return vu[o]}return null},kS=(t,n)=>{try{return n(t)}catch{return t.replace(/(?:%[0-9A-Fa-f]{2})+/g,(i)=>{try{return n(i)}catch{return i}})}},uh=(t)=>kS(t,decodeURI),dh=(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),h=n.indexOf("#",o),w=c===-1?h===-1?void 0:h:h===-1?c:Math.min(c,h),E=n.slice(i,w);return uh(E.includes("%25")?E.replace(/%25/g,"%2525"):E)}else if(a===63||a===35)break}return n.slice(i,o)};var MS=(t)=>{let n=dh(t);return n.length>1&&n.at(-1)==="/"?n.slice(0,-1):n},bo=(t,n,...i)=>{if(i.length)n=bo(n,...i);return`${t?.[0]==="/"?"":"/"}${t}${n==="/"?"":`${t?.at(-1)==="/"?"":"/"}${n?.[0]==="/"?n.slice(1):n}`}`},Eu=(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,h)=>h.indexOf(a)===c)},Au=(t)=>t.indexOf("%")!==-1?kS(t,tC):t,ch=(t)=>{if(t.indexOf("+")!==-1)t=t.replace(/\+/g," ");return Au(t)},NS=(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 w=t.indexOf("?",8);if(w===-1)return;if(!t.startsWith(n,w+1))w=t.indexOf(`&${n}`,w+1);while(w!==-1){let E=t.charCodeAt(w+n.length+1);if(E===61){let _=w+n.length+2,I=t.indexOf("&",_);return ch(t.slice(_,I===-1?void 0:I))}else if(E==38||isNaN(E))return"";w=t.indexOf(`&${n}`,w+1)}if(a=/[%+]/.test(t),!a)return}let c=Object.create(null);a??=/[%+]/.test(t);let h=t.indexOf("?",8);while(h!==-1){let w=t.indexOf("&",h+1),E=t.indexOf("=",h);if(E>w&&w!==-1)E=-1;let _=t.slice(h+1,E===-1?w===-1?void 0:w:E);if(a)_=ch(_);if(h=w,_==="")continue;let I;if(E===-1)I="";else if(I=t.slice(E+1,w===-1?void 0:w),a)I=ch(I);if(i){if(!(c[_]&&Array.isArray(c[_])))c[_]=[];c[_].push(I)}else c[_]??=I}return n?c[n]:c},DS=NS,$S=(t,n)=>NS(t,n,!0),tC=decodeURIComponent;var LS=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&&Au(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]=Au(o)}return t}#n(t){return this.#e[1]?this.#e[1][t]:t}query(t){return DS(this.url,t)}queries(t){return $S(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 PS(this,t)}#s=(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.#s("text").then((t)=>JSON.parse(t))}text(){return this.#s("text")}arrayBuffer(){return this.#s("arrayBuffer")}bytes(){return this.#s("arrayBuffer").then((t)=>new Uint8Array(t))}blob(){return this.#s("blob")}formData(){return this.#s("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[xS](){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 jS={Stringify:1,BeforeStream:2,Stream:3},US=(t,n)=>{let i=new String(t);return i.isEscaped=!0,i.callbacks=n,i};var fh=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 h=Promise.all(c.map((w)=>w({phase:n,buffer:a,context:o}))).then((w)=>Promise.all(w.filter(Boolean).map((E)=>fh(E,n,!1,o,a))).then(()=>a[0]));if(i)return US(await h,c);else return h};var rC="text/plain; charset=UTF-8",ph=(t,n)=>({"Content-Type":t,...n}),Oc=(t,n)=>new Response(t,n),hh=class{#t;#e;env={};#r;finalized=!1;error;#o;#n;#s;#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 LS(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.#s||=Oc(null,{headers:this.#p??=new Headers})}set res(t){if(this.#s&&t){t=Oc(t.body,t);for(let[n,i]of this.#s.headers.entries()){if(n==="content-type")continue;if(n==="set-cookie"){let o=this.#s.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.#s=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.#s=Oc(this.#s.body,this.#s);let o=this.#s?this.#s.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)}#i(t,n,i){let o=this.#s?new Headers(this.#s.headers):this.#p;if(typeof n==="object"&&n.headers){o??=new Headers;for(let[c,h]of new Headers(n.headers))if(c==="set-cookie")o.append(c,h);else o.set(c,h)}if(i){if(!o){let c=0;for(let h in i)if(++c>1||typeof i[h]!=="string"){o=new Headers;break}}if(o)for(let c in i){let h=i[c];if(typeof h==="string")o.set(c,h);else{o.delete(c);for(let w of h)o.append(c,w)}}}let a=typeof n==="number"?n:n?.status??this.#o;return Oc(t,{status:a,headers:o??i})}newResponse=(...t)=>this.#i(...t);body=(t,n,i)=>this.#i(t,n,i);text=(t,n,i)=>!this.#p&&!this.#o&&!n&&!i&&!this.finalized?new Response(t):this.#i(t,n,ph(rC,i));json=(t,n,i)=>this.#i(JSON.stringify(t),n,ph("application/json",i));html=(t,n,i)=>{let o=(a)=>this.#i(a,n,ph("text/html; charset=UTF-8",i));return typeof t==="object"?fh(t,jS.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??=()=>Oc(),this.#a(this))};var sr="ALL",FS="all",qS=["get","post","put","delete","options","patch","query"],xu="Can not add a route since the matcher is already built.",_u=class extends Error{};var mh="__COMPOSED_HANDLER";var nC=(t)=>t.text("404 Not Found",404),BS=(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)},WS=class t{get;post;put;delete;options;patch;query;all;on;use;router;getPath;_basePath="/";#t="/";routes=[];constructor(n={}){[...qS,FS].forEach((c)=>{this[c]=(h,...w)=>{let E=c.toUpperCase();if(typeof h==="string")this.#t=h;else this.#o(E,this.#t,h);return w.forEach((_)=>{this.#o(E,this.#t,_)}),this}}),this.on=(c,h,...w)=>{for(let E of[h].flat()){this.#t=E;for(let _ of[c].flat()){let I=_.toUpperCase();for(let T of w)this.#o(I,this.#t,T)}}return this},this.use=(c,...h)=>{if(typeof c==="string")this.#t=c;else this.#t="*",h.unshift(c);return h.forEach((w)=>{this.#o(sr,this.#t,w)}),this};let{strict:o,...a}=n;Object.assign(this,a),this.getPath=o??!0?n.getPath??dh:MS}#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=nC;errorHandler=BS;route(n,i){let o=this.basePath(n);return i.routes.map((a)=>{let c;if(i.errorHandler===BS)c=a.handler;else c=async(h,w)=>(await ah([],i.errorHandler)(h,()=>a.handler(h,w))).res,c[mh]=a.handler;o.#o(a.method,a.path,c,a.basePath)}),this}basePath(n){let i=this.#e();return i._basePath=bo(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=(E)=>E;else a=o.replaceRequest;let h=c?(E)=>{let _=c(E);return Array.isArray(_)?_:[_]}:(E)=>{let _=void 0;try{_=E.executionCtx}catch{}return[E.env,_]};a||=(()=>{let E=bo(this._basePath,n),_=E==="/"?0:E.length;return(I)=>{let T=new URL(I.url);return T.pathname=this.getPath(I).slice(_)||"/",new Request(T,I)}})();let w=async(E,_)=>{let I=await i(a(E.req.raw),...h(E));if(I)return I;await _()};return this.#o(sr,bo(n,"*"),w),this}#o(n,i,o,a){i=bo(this._basePath,i);let c={basePath:a!==void 0?bo(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}#s(n,i,o,a){if(a==="HEAD")return(async()=>new Response(null,await this.#s(n,i,o,"GET")))();let c=this.getPath(n,{env:o}),h=this.router.match(a,c),w=new hh(n,{path:c,matchResult:h,env:o,executionCtx:i,notFoundHandler:this.#r});if(h[0].length===1){let _;try{_=h[0][0][0][0](w,async()=>{w.res=await this.#r(w)})}catch(I){return this.#n(I,w)}return _ instanceof Promise?_.then((I)=>I||(w.finalized?w.res:this.#r(w))).catch((I)=>this.#n(I,w)):_??this.#r(w)}let E=ah(h[0],this.errorHandler,this.#r);return(async()=>{try{let _=await E(w);if(!_.finalized)throw Error("Context is not finalized. Did you forget to return a Response object or `await next()`?");return _.res}catch(_){return this.#n(_,w)}})()}fetch=(n,...i)=>this.#s(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${bo("/",n)}`,i),o,a)};fire=()=>{addEventListener("fetch",(n)=>{n.respondWith(this.#s(n.request,n,void 0,n.request.method))})}};var or=()=>Object.create(null);var Iu=[];function gh(t,n){let i=this.buildAllMatchers(),o=(a,c)=>{let h=i[a]||i[sr],w=h[2][c];if(w)return w;let E=c.match(h[0]);if(!E)return[[],Iu];let _=E.indexOf("",1);return[h[1][_],E]};return this.match=o,o(t,n)}var Oa="[^/]+",Eo=".*",eo="(?:|/.*)",vo=Symbol(),HS=new Set(".\\+*[^]$()");function iC(t,n){if(t.length===1)return n.length===1?t<n?-1:1:-1;if(n.length===1)return 1;if(t===Eo||t===eo)return n===eo?-1:1;else if(n===Eo||n===eo)return-1;if(t===Oa)return 1;else if(n===Oa)return-1;return t.length===n.length?t<n?-1:1:n.length-t.length}var VS=class t{#t;#e;#r=or();insert(n,i,o,a,c){let h=this;for(let w=0,E=n.length;w<E;w++){let _=n[w],I=_.length===1?_==="*"?w===E-1?["","",Eo]:["","",Oa]:null:_==="/*"?["","",eo]:_.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),T;if(I){let O=I[1],N=I[2]||Oa;if(O&&I[2]){if(N===".*")throw vo;if(N=N.replace(/^\((?!\?:)(?=[^)]+\)$)/,"(?:"),/\((?!\?:)/.test(N))throw vo;if(N.length===1&&HS.has(N))throw vo}if(T=h.#r[N],!T){if(N!==Eo&&N!==eo){for(let L in h.#r)if((N.length>1||L.length>1)&&L!==Eo&&L!==eo)throw vo}T=h.#r[N]=new t}if(O!=="")T.#e??=a.varIndex++,o.push([O,T.#e])}else if(T=h.#r[_],!T){for(let O in h.#r)if(O.length>1&&O!==Eo&&O!==eo)throw vo;T=h.#r[_]=new t}h=T}if(h.#t!==void 0)throw vo;h.#t=c?-1:i}buildRegExpStr(){let i=Object.keys(this.#r).sort(iC).map((o)=>{let a=this.#r[o],c=a.buildRegExpStr();return c===""?"":(typeof a.#e==="number"?`(${o})@${a.#e}`:HS.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 yh=class{#t={varIndex:0};#e=new VS;#r=0;paths=or();insert(t,n){if(n){this.#e.insert(t.split(""),0,[],this.#t,!0);return}let i=[],o=[],a=t;for(let h=0;;){let w=!1;if(a=a.replace(/\{[^}]+\}/g,(E)=>{let _=`@\\${h}`;return o[h]=[_,E],h++,w=!0,_}),!w)break}let c=a.match(/(?::[^\/]+)|(?:\/\*$)|./g)||[];for(let h=o.length-1;h>=0;h--){let[w]=o[h];for(let E=c.length-1;E>=0;E--)if(c[E].indexOf(w)!==-1){c[E]=c[E].replace(w,o[h][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,h)=>{if(c!==void 0)return i[++n]=Number(c),"$()";if(h!==void 0)return o[Number(h)]=++n,"";return""}),[new RegExp(`^${t}`),i,o]}};var zS=or();function GS(t){return zS[t]??=new RegExp(`^${t.replace(/\/:[^/{}]+(?:\{\[\^\/]\+})?(?=[/{]|$)|\/?\*$|([.\\+*[^\]$()?{}|])/g,(n,i)=>i?`\\${i}`:n==="/*"?eo:n==="*"?Eo:`/:${Oa}`)}$`)}function Tu(t,n){for(let i of Object.keys(t).sort((o,a)=>a.length-o.length))if(GS(i).test(n))return[...t[i]];return}var Ru=class{name="RegExpRouter";#t;#e;#r;constructor(){this.#t={[sr]:or()},this.#e={[sr]:or()},this.#r={[sr]:new yh}}#o(t,n){try{this.#r[t].insert(n,!/\*|\/:/.test(n))}catch(i){throw i===vo?new _u(n):i}}add(t,n,i){let o=this.#t,a=this.#e;if(!o)throw Error(xu);if(!o[t]){this.#r[t]=new yh;for(let w of[o,a]){w[t]=or();for(let E in w[sr])w[t][E]=[...w[sr][E]],this.#o(t,E)}}if(n==="/*")n="*";let c=t===sr?Object.keys(o):[t];if(/\*$/.test(n)){let w=GS(n);for(let E of c)if(!o[E][n])this.#o(E,n),o[E][n]=Tu(o[E],n)||Tu(o[sr],n)||[];for(let E of[o,a])for(let _ of c)for(let I in E[_])w.test(I)&&E[_][I].push([i,n]);return}let h=Eu(n)||[n];for(let w of h)for(let E of c){if(!a[E][w])this.#o(E,w),a[E][w]=Tu(o[E],w)||Tu(o[sr],w)||[];a[E][w].push([i,w])}}match=gh;buildAllMatchers(){let t=or();for(let n of Object.keys(this.#e))t[n]=this.#n(n);return this.#t=this.#e=this.#r=void 0,zS=or(),t}#n(t){let n=this.#t[t],i=this.#e[t],o=this.#r[t],a=or(),c=[],[h,w,E]=o.buildRegExp();for(let _ of[n,i])for(let I in _){let T=_[I],O=o.paths[I];if(!O){a[I]=[T.map(([N])=>[N,or()]),Iu];continue}c[O[0]]=T.map(([N,L])=>[N,o.paths[L][1].reduceRight((H,[Z],G)=>(H[Z]=E[O[1][G][1]],H),or())])}return[h,w.map((_)=>c[_]),a]}};var wh=class{name="SmartRouter";#t=[];#e=[];constructor(t){this.#t=t.routers}add(t,n,i){if(!this.#e)throw Error(xu);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,h;for(;c<a;c++){let w=i[c];try{for(let E=0,_=o.length;E<_;E++)w.add(...o[E]);h=w.match(t,n)}catch(E){if(E instanceof _u)continue;throw E}this.match=w.match.bind(w),this.#t=[w],this.#e=void 0;break}if(c===a)throw Error("Fatal error");return this.name=`SmartRouter + ${this.activeRouter.name}`,h}get activeRouter(){if(this.#e||this.#t.length!==1)throw Error("No active router has been determined yet.");return this.#t[0]}};var Sh=or(),sC=0,KS=class t{#t=[];#e=or();#r=[];#o;#n=Sh;insert(n,i,o){let a=this,c=CS(i),h=new Set,w=0;for(let E of c){let _=c[++w],I=OS(E,_)||(_===void 0&&E&&E.indexOf("*")===E.length-1?E:null),T=Array.isArray(I),O=T?I[0]:I||E,N=a.#e[O]||=new t;if(I&&!N.#o)N.#o=I,a.#r.push(N);if(a=N,T)h.add(I[1])}a.#t.push({[n]:{handler:o,possibleKeys:[...h],score:++sC}})}#s(n,i,o,a,c){for(let h=0,w=i.#t.length;h<w;h++){let E=i.#t[h],_=E[o]||E[sr];if(_){_.params=or(),n.push(_);for(let I=0,T=_.possibleKeys.length;I<T;I++){let O=_.possibleKeys[I];_.params[O]=c?.[O]&&!I?c[O]:a[O]??c?.[O]}}}}search(n,i){let o=[];this.#n=Sh;let c=[this],h=lh(i),w=[],E=h.length,_=null;for(let I=0;I<E;I++){let T=h[I],O=I===E-1,N=[];for(let H=0,Z=c.length;H<Z;H++){let G=c[H],oe=G.#e[T];if(oe)if(oe.#n=G.#n,O){if(oe.#e["*"])this.#s(o,oe.#e["*"],n,G.#n);this.#s(o,oe,n,G.#n)}else N.push(oe);for(let re of G.#r){let xe=re.#o,Oe=G.#n===Sh?{}:{...G.#n};if(typeof xe==="string"){if(xe==="*"||T.startsWith(xe.slice(0,-1))){if(this.#s(o,re,n,G.#n),xe==="*")re.#n=Oe,N.push(re)}continue}let[,je,We]=xe;if(!T&&We===!0)continue;if(We!==!0){if(!_){_=[];let io=i[0]==="/"?1:0;for(let on=0;on<E;on++)_[on]=io,io+=h[on].length+1}let jt=i.slice(_[I]),Ft=We.exec(jt);if(Ft){if(Oe[je]=Ft[0],this.#s(o,re,n,G.#n,Oe),Ft[0].length===jt.length&&re.#e["*"])this.#s(o,re.#e["*"],n,G.#n,Oe);for(let io in re.#e){re.#n=Oe;let on=Ft[0].match(/\//g)?.length??0;(w[on]||=[]).push(re);break}continue}}if(We===!0||We.test(T))if(Oe[je]=T,O){if(this.#s(o,re,n,Oe,G.#n),re.#e["*"])this.#s(o,re.#e["*"],n,Oe,G.#n)}else re.#n=Oe,N.push(re)}}let L=w.shift();c=L?N.concat(L):N}if(o[1])o.sort((I,T)=>I.score-T.score);return[o.map(({handler:I,params:T})=>[I,T])]}};var bh=class{name="TrieRouter";#t=new KS;add(t,n,i){for(let o of Eu(n)||[n])this.#t.insert(t,o,i)}match(t,n){return this.#t.search(t,n)}};var Ui=class extends WS{constructor(t={}){super(t);this.router=t.router??new wh({routers:[new Ru,new bh]})}};import{isDeepStrictEqual as eE}from"util";import Zh from"process";import to from"fs";import sd from"path";import Hc from"crypto";import tE from"assert";var Ko=(t)=>{let n=typeof t;return t!==null&&(n==="object"||n==="function")},Pu=new Set(["__proto__","prototype","constructor"]),oC=Math.max(...[...Pu].map((t)=>t.length));var aC=(t)=>t>="0"&&t<="9";function JS(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 vh(t,n){if(Pu.has(t))return!1;if(t&&JS(t))n.push(Number.parseInt(t,10));else n.push(t);return!0}function cC(t){if(typeof t!=="string")throw TypeError(`Expected a string, got ${typeof t}`);let n=[],i="",o="",a=!1,c="start",h=!1,w=0;for(let E of t){if(w++,h){i+=E,h=!1;continue}if(E==="\\"){if(c==="index")throw Error(`Invalid character '${E}' in an index at position ${w}`);if(c==="indexEnd")throw Error(`Invalid character '${E}' after an index at position ${w}`);h=!0,c=c==="start"?"property":c;continue}switch(E){case".":{if(c==="index")throw Error(`Invalid character '${E}' in an index at position ${w}`);if(c==="indexEnd"){c="property";break}if(!vh(i,n))return[];i="",c="property";break}case"[":{if(c==="index")throw Error(`Invalid character '${E}' in an index at position ${w}`);if(c==="indexEnd"){c="index";break}if(c==="property"&&i.length<=oC&&Pu.has(i))return[];a=c==="property",c="index";break}case"]":{if(c==="indexEnd")throw Error(`Invalid character '${E}' after an index at position ${w}`);if(c!=="index"){if(c==="start")c="property";i+=E;break}if(o===""){i+="[]",c="property";break}if((i!==""||a)&&!vh(i,n))return[];i="",a=!1;let _=Number.parseInt(o,10),I=_<=1e6&&o===String(_);n.push(I?_:o),o="",c="indexEnd";break}default:{if(c==="index"){if(!aC(E))throw Error(`Invalid character '${E}' in an index at position ${w}`);o+=E;break}if(c==="indexEnd")throw Error(`Invalid character '${E}' after an index at position ${w}`);if(c==="start")c="property";i+=E}}}if(h)i+="\\";switch(c){case"property":{if(!vh(i,n))return[];break}case"index":throw Error("Index was not closed");case"start":{n.push("");break}}return n}function Cu(t){if(typeof t==="string")return cC(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(Pu.has(o))return[];if(typeof o==="string"&&JS(o))n.push(Number.parseInt(o,10));else n.push(o)}return n}return[]}function Eh(t,n,i){if(!Ko(t)||typeof n!=="string"&&!Array.isArray(n))return i===void 0?t:i;let o=Cu(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 kc(t,n,i){if(!Ko(t)||typeof n!=="string"&&!Array.isArray(n))return t;let o=t,a=Cu(n);if(a.length===0)return t;for(let c=0;c<a.length;c++){let h=a[c];if(c===a.length-1){t[h]=i;continue}let w=t[h];if(Ko(w)){t=w;continue}let _=typeof a[c+1]==="number";t[h]=_?[]:{},t=t[h]}return o}function YS(t,n){if(!Ko(t)||typeof n!=="string"&&!Array.isArray(n))return!1;let i=Cu(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(!Ko(c))return!1;t=c}}function Ou(t,n){if(!Ko(t)||typeof n!=="string"&&!Array.isArray(n))return!1;let i=Cu(n);if(i.length===0)return!1;for(let o of i){if(!Ko(t)||!(o in t))return!1;t=t[o]}return!0}import Ot from"path";import XS from"os";import Ah from"process";var Ao=XS.homedir(),xh=XS.tmpdir(),{env:ka}=Ah,lC=(t)=>{let n=Ot.join(Ao,"Library");return{data:Ot.join(n,"Application Support",t),config:Ot.join(n,"Preferences",t),cache:Ot.join(n,"Caches",t),log:Ot.join(n,"Logs",t),temp:Ot.join(xh,t)}},uC=(t)=>{let n=ka.APPDATA||Ot.join(Ao,"AppData","Roaming"),i=ka.LOCALAPPDATA||Ot.join(Ao,"AppData","Local");return{data:Ot.join(i,t,"Data"),config:Ot.join(n,t,"Config"),cache:Ot.join(i,t,"Cache"),log:Ot.join(i,t,"Log"),temp:Ot.join(xh,t)}},dC=(t)=>{let n=Ot.basename(Ao);return{data:Ot.join(ka.XDG_DATA_HOME||Ot.join(Ao,".local","share"),t),config:Ot.join(ka.XDG_CONFIG_HOME||Ot.join(Ao,".config"),t),cache:Ot.join(ka.XDG_CACHE_HOME||Ot.join(Ao,".cache"),t),log:Ot.join(ka.XDG_STATE_HOME||Ot.join(Ao,".local","state"),t),temp:Ot.join(xh,n,t)}};function _h(t,{suffix:n="nodejs"}={}){if(typeof t!=="string")throw TypeError(`Expected a string, got ${typeof t}`);if(n)t+=`-${n}`;if(Ah.platform==="darwin")return lC(t);if(Ah.platform==="win32")return uC(t);return dC(t)}import SC from"path";import He from"fs";import{promisify as Er}from"util";var fC=(t,n)=>{let{onError:i}=n;return function(...a){return t.apply(void 0,a).catch(i)}},Hi=fC;var pC=(t,n)=>{let{onError:i}=n;return function(...a){try{return t.apply(void 0,a)}catch(c){return i(c)}}},wi=pC;var ZS=250;var hC=(t,n)=>{let{isRetriable:i}=n;return function(a){let{timeout:c}=a,h=a.interval??ZS,w=Date.now()+c;return function E(..._){return t.apply(void 0,_).catch((I)=>{if(!i(I))throw I;if(Date.now()>=w)throw I;let T=Math.round(h*Math.random());if(T>0)return new Promise((N)=>setTimeout(N,T)).then(()=>E.apply(void 0,_));else return E.apply(void 0,_)})}}},Ji=hC;var mC=(t,n)=>{let{isRetriable:i}=n;return function(a){let{timeout:c}=a,h=Date.now()+c;return function(...E){while(!0)try{return t.apply(void 0,E)}catch(_){if(!i(_))throw _;if(Date.now()>=h)throw _;continue}}}},Xi=mC;import eb from"process";var Mc={isChangeErrorOk:(t)=>{if(!Mc.isNodeError(t))return!1;let{code:n}=t;if(n==="ENOSYS")return!0;if(!QS&&(n==="EINVAL"||n==="EPERM"))return!0;return!1},isNodeError:(t)=>t instanceof Error,isRetriableError:(t)=>{if(!Mc.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(!Mc.isNodeError(t))throw t;if(Mc.isChangeErrorOk(t))return;throw t}},Ih=Mc;var Nc={onError:Ih.onChangeError},pn={onError:()=>{return}},QS=eb.getuid?!eb.getuid():!1,mr={isRetriable:Ih.isRetriableError};var gC={attempt:{chmod:Hi(Er(He.chmod),Nc),chown:Hi(Er(He.chown),Nc),close:Hi(Er(He.close),pn),fsync:Hi(Er(He.fsync),pn),mkdir:Hi(Er(He.mkdir),pn),realpath:Hi(Er(He.realpath),pn),stat:Hi(Er(He.stat),pn),unlink:Hi(Er(He.unlink),pn),chmodSync:wi(He.chmodSync,Nc),chownSync:wi(He.chownSync,Nc),closeSync:wi(He.closeSync,pn),existsSync:wi(He.existsSync,pn),fsyncSync:wi(He.fsync,pn),mkdirSync:wi(He.mkdirSync,pn),realpathSync:wi(He.realpathSync,pn),statSync:wi(He.statSync,pn),unlinkSync:wi(He.unlinkSync,pn)},retry:{close:Ji(Er(He.close),mr),fsync:Ji(Er(He.fsync),mr),open:Ji(Er(He.open),mr),readFile:Ji(Er(He.readFile),mr),rename:Ji(Er(He.rename),mr),stat:Ji(Er(He.stat),mr),write:Ji(Er(He.write),mr),writeFile:Ji(Er(He.writeFile),mr),closeSync:Xi(He.closeSync,mr),fsyncSync:Xi(He.fsyncSync,mr),openSync:Xi(He.openSync,mr),readFileSync:Xi(He.readFileSync,mr),renameSync:Xi(He.renameSync,mr),statSync:Xi(He.statSync,mr),writeSync:Xi(He.writeSync,mr),writeFileSync:Xi(He.writeFileSync,mr)}},ar=gC;import Jo from"process";var tb="utf8",Th=438,rb=511;var nb={},ib=Jo.geteuid?Jo.geteuid():-1,sb=Jo.getegid?Jo.getegid():-1;var ob=1000,ab=!!Jo.getuid,uG=Jo.getuid?!Jo.getuid():!1,Rh=128;var cb=(t)=>t instanceof Error&&("code"in t);var Ph=(t)=>typeof t==="string",ku=(t)=>t===void 0;import wC from"path";import Ma from"process";import lb from"process";var ub=lb.platform==="linux",Mu=lb.platform==="win32";var Ch=["SIGHUP","SIGINT","SIGTERM"];if(!Mu)Ch.push("SIGALRM","SIGABRT","SIGVTALRM","SIGXCPU","SIGXFSZ","SIGUSR2","SIGTRAP","SIGSYS","SIGQUIT","SIGIOT");if(ub)Ch.push("SIGIO","SIGPOLL","SIGPWR","SIGSTKFLT");var db=Ch;class fb{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(Mu&&(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 db)try{Ma.once(t,()=>this.exit(t))}catch{}},this.register=(t)=>(this.callbacks.add(t),()=>{this.callbacks.delete(t)}),this.hook()}}var pb=new fb;var yC=pb.register,hb=yC;var _n={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=_n.truncate(n(t));if(o in _n.store)return _n.get(t,n,i);return _n.store[o]=i,[o,()=>delete _n.store[o]]},purge:(t)=>{if(!_n.store[t])return;delete _n.store[t],ar.attempt.unlink(t)},purgeSync:(t)=>{if(!_n.store[t])return;delete _n.store[t],ar.attempt.unlinkSync(t)},purgeSyncAll:()=>{for(let t in _n.store)_n.purgeSync(t)},truncate:(t)=>{let n=wC.basename(t);if(n.length<=Rh)return t;let i=/^(\.?)(.*?)((?:\.[^.]+)?(?:\.tmp-\d{10}[a-f0-9]{6})?)$/.exec(n);if(!i)return t;let o=n.length-Rh;return`${t.slice(0,-n.length)}${i[1]}${i[2].slice(0,-o)}${i[3]}`}};hb(_n.purgeSyncAll);var Dc=_n;function Oh(t,n,i=nb){if(Ph(i))return Oh(t,n,{encoding:i});let a={timeout:i.timeout??ob},c=null,h=null,w=null;try{let E=ar.attempt.realpathSync(t),_=!!E;t=E||t,[h,c]=Dc.get(t,i.tmpCreate||Dc.create,i.tmpPurge!==!1);let I=ab&&ku(i.chown),T=ku(i.mode);if(_&&(I||T)){let O=ar.attempt.statSync(t);if(O){if(i={...i},I)i.chown={uid:O.uid,gid:O.gid};if(T)i.mode=O.mode}}if(!_){let O=SC.dirname(t);ar.attempt.mkdirSync(O,{mode:rb,recursive:!0})}if(w=ar.retry.openSync(a)(h,"w",i.mode||Th),i.tmpCreated)i.tmpCreated(h);if(Ph(n))ar.retry.writeSync(a)(w,n,0,i.encoding||tb);else if(!ku(n))ar.retry.writeSync(a)(w,n,0,n.length,0);if(i.fsync!==!1)if(i.fsyncWait!==!1)ar.retry.fsyncSync(a)(w);else ar.attempt.fsync(w);if(ar.retry.closeSync(a)(w),w=null,i.chown&&(i.chown.uid!==ib||i.chown.gid!==sb))ar.attempt.chownSync(h,i.chown.uid,i.chown.gid);if(i.mode&&i.mode!==Th)ar.attempt.chmodSync(h,i.mode);try{ar.retry.renameSync(a)(h,t)}catch(O){if(!cb(O))throw O;if(O.code!=="ENAMETOOLONG")throw O;ar.retry.renameSync(a)(h,Dc.truncate(t))}c(),h=null}finally{if(w)ar.attempt.closeSync(w);if(h)Dc.purge(h)}}var iE=g(s0(),1),sE=g(Wn(),1);var BO=(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(!WO(a,c)&&o)return;Object.defineProperty(t,i,c)},WO=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)},HO=(t,n)=>{let i=Object.getPrototypeOf(n);if(i===Object.getPrototypeOf(t))return;Object.setPrototypeOf(t,i)},VO=(t,n)=>`/* Wrapped ${t}*/
|
|
62
|
+
${n}`,zO=Object.getOwnPropertyDescriptor(Function.prototype,"toString"),GO=Object.getOwnPropertyDescriptor(Function.prototype.toString,"name"),KO=(t,n,i)=>{let o=i===""?"":`with ${i.trim()}() `,a=VO.bind(null,o,n.toString());Object.defineProperty(a,"name",GO);let{writable:c,enumerable:h,configurable:w}=zO;Object.defineProperty(t,"toString",{value:a,writable:c,enumerable:h,configurable:w})};function $h(t,n,{ignoreNonConfigurable:i=!1}={}){let{name:o}=t;for(let a of Reflect.ownKeys(n))BO(t,n,a,i);return HO(t,n),KO(t,n,o),t}var JO=(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 h,w,E,_=function(...I){let T=this,O=()=>{if(h=void 0,w)clearTimeout(w),w=void 0;if(c)E=t.apply(T,I)},N=()=>{if(w=void 0,h)clearTimeout(h),h=void 0;if(c)E=t.apply(T,I)},L=a&&!h;if(clearTimeout(h),h=setTimeout(O,i),o>0&&o!==Number.POSITIVE_INFINITY&&!w)w=setTimeout(N,o);if(L)E=t.apply(T,I);return E};return $h(_,t),_.cancel=()=>{if(h)clearTimeout(h),h=void 0;if(w)clearTimeout(w),w=void 0},_},Lh=JO;var Yo=g(Yv(),1);var QN=Object.prototype.toString;function Zv(t,n,i){if(!t)return!1;if(t.constructor===n)return!0;return QN.call(t)===i}function Qv(t){return Zv(t,Uint8Array,"[object Uint8Array]")}function eD(t){return Zv(t,ArrayBuffer,"[object ArrayBuffer]")}function tD(t){return Qv(t)||eD(t)}function rD(t){if(!Qv(t))throw TypeError(`Expected \`Uint8Array\`, got \`${typeof t}\``)}function nD(t){if(!tD(t))throw TypeError(`Expected \`Uint8Array\` or \`ArrayBuffer\`, got \`${typeof t}\``)}function nd(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)rD(a),i.set(a,o),o+=a.length;return i}var Xv={utf8:new globalThis.TextDecoder("utf8")};function Wc(t,n="utf8"){return nD(t),Xv[n]??=new globalThis.TextDecoder(n),Xv[n].decode(t)}function iD(t){if(typeof t!=="string")throw TypeError(`Expected \`string\`, got \`${typeof t}\``)}var sD=new globalThis.TextEncoder;function id(t){return iD(t),sD.encode(t)}var d7=Array.from({length:256},(t,n)=>n.toString(16).padStart(2,"0"));var rE="aes-256-cbc",oE=new Set(["aes-256-cbc","aes-256-gcm","aes-256-ctr"]),oD=(t)=>typeof t==="string"&&oE.has(t),ro=()=>Object.create(null),nE=(t)=>t!==void 0,Qh=(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`)},_o="__internal__",em=`${_o}.migrations.version`;class od{path;events;#t;#e;#r;#o;#n={};#s=!1;#S;#f;#a;constructor(t={}){let n=this.#p(t);if(this.#o=n,this.#u(n),this.#i(n),this.#g(n),this.events=new EventTarget,this.#e=n.encryptionKey,this.#r=n.encryptionAlgorithm??rE,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 ${_o} key, as it's used to manage this module internal operations.`);let{store:i}=this,o=(a,c)=>{if(Qh(a,c),this.#o.accessPropertiesByDotNotation)kc(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,h]of Object.entries(a))o(c,h)}else o(t,n);this.store=i}has(t){if(this.#o.accessPropertiesByDotNotation)return Ou(this.store,t);return t in this.store}appendToArray(t,n){Qh(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(nE(this.#n[n]))this.set(n,this.#n[n])}delete(t){let{store:n}=this;if(this.#o.accessPropertiesByDotNotation)YS(n,t);else delete n[t];this.store=n}clear(){let t=ro();for(let n of Object.keys(this.#n))if(nE(this.#n[n]))if(Qh(n,this.#n[n]),this.#o.accessPropertiesByDotNotation)kc(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=to.readFileSync(this.path,this.#e?null:"utf8"),n=this._decryptData(t);return((o)=>{let a=this._deserialize(o);if(!this.#s)this._validate(a);return Object.assign(ro(),a)})(n)}catch(t){if(t?.code==="ENOENT")return this._ensureDirectory(),ro();if(this.#o.clearInvalidConfig){let n=t;if(n.name==="SyntaxError")return ro();if(n.message?.startsWith("Config schema violation:"))return ro();if(n.message==="Failed to decrypt config data.")return ro()}throw t}}set store(t){if(this._ensureDirectory(),!Ou(t,_o))try{let n=to.readFileSync(this.path,this.#e?null:"utf8"),i=this._decryptData(n),o=this._deserialize(i);if(Ou(o,_o))kc(t,_o,Eh(o,_o))}catch{}if(!this.#s)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)to.unwatchFile(this.path),this.#f=!1;this.#a=void 0}_decryptData(t){let n=this.#e;if(!n)return typeof t==="string"?t:Wc(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:Wc(t);throw Error("Failed to decrypt config data.")}let w=(O)=>{if(o===0)return{ciphertext:O};let N=O.length-o;if(N<0)throw Error("Invalid authentication tag length.");return{ciphertext:O.slice(0,N),authenticationTag:O.slice(N)}},E=t.slice(0,16),_=t.slice(17),I=typeof _==="string"?id(_):_,T=(O)=>{let{ciphertext:N,authenticationTag:L}=w(I),H=Hc.pbkdf2Sync(n,O,1e4,32,"sha512"),Z=Hc.createDecipheriv(i,H,E);if(L)Z.setAuthTag(L);return Wc(nd([Z.update(N),Z.final()]))};try{return T(E)}catch{try{return T(E.toString())}catch{}}if(i==="aes-256-cbc")return typeof t==="string"?t:Wc(t);throw Error("Failed to decrypt config data.")}_handleStoreChange(t){let n=this.store,i=()=>{let o=n,a=this.store;if(eE(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(eE(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(){to.mkdirSync(sd.dirname(this.path),{recursive:!0})}_write(t){let n=this._serialize(t),i=this.#e;if(i){let o=Hc.randomBytes(16),a=Hc.pbkdf2Sync(i,o,1e4,32,"sha512"),c=Hc.createCipheriv(this.#r,a,o),h=nd([c.update(id(n)),c.final()]),w=[o,id(":"),h];if(this.#r==="aes-256-gcm")w.push(c.getAuthTag());n=nd(w)}if(Zh.env.SNAP)to.writeFileSync(this.path,n,{mode:this.#o.configFileMode});else try{Oh(this.path,n,{mode:this.#o.configFileMode})}catch(o){if(o?.code==="EXDEV"){to.writeFileSync(this.path,n,{mode:this.#o.configFileMode});return}throw o}}_watch(){if(this._ensureDirectory(),!to.existsSync(this.path))this._write(ro());if(Zh.platform==="win32"||Zh.platform==="darwin"){this.#a??=Lh(()=>{this.events.dispatchEvent(new Event("change"))},{wait:100});let t=sd.dirname(this.path),n=sd.basename(this.path);this.#S=to.watch(t,{persistent:!1,encoding:"utf8"},(i,o)=>{if(o&&o!==n)return;if(typeof this.#a==="function")this.#a()})}else this.#a??=Lh(()=>{this.events.dispatchEvent(new Event("change"))},{wait:1000}),to.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(em,"0.0.0"),a=Object.keys(t).filter((h)=>this._shouldPerformMigration(h,o,n)),c=structuredClone(this.store);for(let h of a)try{if(i)i(this,{fromVersion:o,toVersion:h,finalVersion:n,versions:a});let w=t[h];w?.(this),this._set(em,h),o=h,c=structuredClone(this.store)}catch(w){this.store=c;let E=w instanceof Error?w.message:String(w);throw Error(`Something went wrong during the migration! Changes applied to the store until this failed migration will be restored. ${E}`)}if(this._isVersionInRangeFormat(o)||!Yo.default.eq(o,n))this._set(em,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===_o||t.startsWith(`${_o}.`)}_isVersionInRangeFormat(t){return Yo.default.clean(t)===null}_shouldPerformMigration(t,n,i){if(this._isVersionInRangeFormat(t)){if(n!=="0.0.0"&&Yo.default.satisfies(n,t))return!1;return Yo.default.satisfies(i,t)}if(Yo.default.lte(t,n))return!1;if(Yo.default.gt(t,i))return!1;return!0}_get(t,n){return Eh(this.store,t,n)}_set(t,n){let{store:i}=this;kc(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??=rE,!oD(n.encryptionAlgorithm))throw TypeError(`The \`encryptionAlgorithm\` option must be one of: ${[...oE].join(", ")}`);if(!n.cwd){if(!n.projectName)throw Error("Please specify the `projectName` option.");n.cwd=_h(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=sE.default.default,i=new iE.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}}#i(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 sd.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(ro(),t.defaults??{},n);this._validate(i);try{tE.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.#s=!0;try{let o=this.store,a=Object.assign(ro(),t.defaults??{},o);try{tE.deepEqual(o,a)}catch{this._write(a)}this._migrate(n,i,t.beforeEachMigration)}finally{this.#s=!1}}}var aD=["autoUpdateSkills","showOnboarding"];function cE(t){let n={};for(let i of aD)if(t[i]!==void 0)n[i]=t[i];return n}var cD=x,aE=null;function lE(){return aE??=new od({cwd:cD,configName:"settings",schema:{autoUpdateSkills:{type:"boolean",default:!1},showOnboarding:{type:"boolean",default:!0}}}),aE}function ad(){return lE().store}function uE(t){let n=lE();if(Object.keys(t).length>0)n.set(t);return n.store}import{mkdir as uD,rename as dD,readFile as fD}from"fs/promises";import{existsSync as pD}from"fs";import{basename as hD,join as ld}from"path";var dE=s({message:r().trim().min(1).max(50)}).strict();async function Vc(t){let n=await Ut(t);return{name:n.name,icon:n.icon}}async function no(t,n){let{layout:i}=await Ke(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 cd(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 lD}from"path";function fE(t,n){return lD(de(t,n),"moi-workspace","references","COLLAB.md")}async function pE(t,n){if(u().environment!=="cloud")return;let i=fE(t,n);return await Bun.file(i).exists()?i:void 0}async function Ua(t,n){let i=lr(t.id);try{let{getWorkspace:o}=await import("./chunk-9cr1atrp.js"),a=await o(t.id);if(a&&(a.harness??"claude-code")!==(t.harness??"claude-code"))throw new le("Agent changed. Start a new chat");let{prepareWorkspaceHarness:c}=await import("./chunk-3ww4pa9m.js");await c(t);let{viewBuildId:h,...w}=n,E=te(t.id,n.sessionId),_=await Fr(t,E),I=n.context?.activeTab?.id??_.tabId??"overview",T=h??(n.isNew?wn(I):void 0),O=T?[]:(await Tt(t)).filter((G)=>G.buildSessionId===E),N=T?await Qt(t,T):O.find((G)=>G.id===wn(I))??O[0],L=N&&(h===N.id||n.isNew);if(L&&N.buildSessionId&&N.buildSessionId!==E&&(N.status==="starting"||y(t).activeSessions().some((G)=>G.workspaceId===t.id&&G.sessionId===N.buildSessionId)))throw new V("This view is already being built in another chat",409);if(n.isNew&&_.tabId!==I)_.tabId=I==="overview"?void 0:I,await _t(t,E,{tabId:_.tabId}),await qe(t,E,I,null);if(L)await rt(t,N.id,{buildSessionId:E});let H=await pE(t.path,t.harness),Z=await Yr(t);if(await y(t).sendMessage({...w,sessionId:E,context:{...n.context,workspaceMode:t.remote?"remote":"local",session:{id:E,tabId:_.tabId,pinned:Z===E},...H?{collabReference:H}:{},directives:[...n.context?.directives??[],...L?cd(N.id,ve):[],...L&&_.fork?["Inherited conversation is background. Work on the current request; do not resume unrelated earlier tasks."]:[],...N&&n.isNew&&N.requirements!==n.content?[`Original view requirements:
|
|
63
|
+
${N.requirements}`]:[],...N&&n.attachments?.length?["Use the attachments as reference material for the intended view."]:[]]}}),N&&N.status!=="starting")await rt(t,N.id,{status:"submitted",error:void 0})}finally{i()}}var hE=s({name:r().trim().min(1).max(100),description:r().trim().min(1).max(500),features:p(r().trim().min(1).max(500)).min(1).max(6)}).strict(),mE=s({name:r().trim().min(1).max(24),icon:F(ve),theme:s({font:F(Object.keys(ue)),color:F(Object.keys(pe))}).strict(),description:r().trim().min(1).max(200),views:p(hE.extend({icon:F(ve)})).length(3),widgets:p(hE).max(4)}).strict(),gE=mE.extend({id:r().uuid()}),tm=s({options:p(mE).length(3)}).strict();function yE(t){let n=tm.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 wE(t,n){if(!n.length)return`## ${t}
|
|
64
|
+
None planned.`;return`## ${t}
|
|
65
|
+
${n.map((i)=>[`### ${i.name}`,..."icon"in i?[`Use view icon: ${i.icon}`]:[],i.description,...i.features.map((o)=>`- ${o}`)].join(`
|
|
66
|
+
`)).join(`
|
|
67
|
+
|
|
68
|
+
`)}`}function SE(t){return[`Build the Moi workspace \u201C${t.name}\u201D. Start implementing this plan now.`,`## Workspace
|
|
69
|
+
${t.description}
|
|
70
|
+
Icon: ${t.icon} (theme background, already configured).`,`## Theme
|
|
71
|
+
Font: ${t.theme.font}
|
|
72
|
+
Color: ${t.theme.color}
|
|
73
|
+
These workspace presets are already configured; use the existing theme tokens.`,wE("Views",t.views),wE("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
|
+
|
|
75
|
+
`)}var mD={directory:ld(x,"onboarding"),workspacesRoot:Ce,provisionWorkspace:J,registerWorkspace:K,getWorkspace:W,setWorkspaceConfig:no,publishEvent:m,harnessFor:y,sendWorkspaceMessage:Ua,saveSelectedSession:qe,resolveRenamedSession:te,readWorkspaceState:se};function gD(t={}){let n={...mD,...t},i=new Map,o=new Map;function a(O){return ld(n.directory,`${O}.json`)}async function c(O){try{return JSON.parse(await fD(a(O),"utf8"))}catch(N){if(N.code==="ENOENT")return;throw N}}async function h(O,N){await uD(n.directory,{recursive:!0});let L=a(O),H=`${L}.${crypto.randomUUID()}.tmp`;await Bun.write(H,JSON.stringify(N)),await dD(H,L)}function w(O,N){let L=(o.get(O)??Promise.resolve()).catch(()=>{}).then(N);return o.set(O,L),L.finally(()=>{if(o.get(O)===L)o.delete(O)}).catch(()=>{}),L}async function E(O){let N=O;return w(N,async()=>{i.get(N)?.abort(),await h(N,{status:"failed",error:"Discovery cancelled"})})}async function _(O){if(!O.runId||!O.harness)throw Error("Choose an agent first");let N=O.runId;return w(N,async()=>{let L=await c(N);if(L){if(L.status==="done"&&!L.ideas?.every((re)=>gE.safeParse(re).success))return{status:"failed",error:"These ideas use an older format. Find ideas again"};if(L.status==="running"&&!i.has(N))return{status:"failed",error:"Discovery was interrupted. Try again"};return L}let H=n.harnessFor(O.harness);if(!H.runAction){let re={status:"failed",error:"This agent does not support ephemeral actions"};return await h(N,re),re}let Z=new AbortController;i.set(N,Z);let G={status:"running"};try{await h(N,G)}catch(re){throw i.delete(N),re}let oe=setTimeout(()=>Z.abort(),180000);return Promise.resolve().then(async()=>{let re=Date.now(),xe=(je)=>new Date(re-je*86400000).toISOString().slice(0,10),Oe=`Research dates (UTC): today ${xe(0)}; last 30 days start ${xe(30)}; last 60 days start ${xe(60)}.`;return H.runAction({model:"fast",prompt:`${Oe}
|
|
76
|
+
|
|
77
|
+
${await Bun.file(v("server","onboarding","prompt.md")).text()}`,resultSchema:tm,progressSchema:dE,onProgress:(je)=>w(N,async()=>{let We=await c(N);if(!Z.signal.aborted&&We?.status==="running")await h(N,{...We,progress:je})}),signal:Z.signal})}).then((re)=>({status:"done",ideas:yE(re)})).catch((re)=>({status:"failed",error:Z.signal.aborted?"Discovery stopped. Try again":String(re instanceof Error?re.message:re)})).then((re)=>w(N,async()=>{if((await c(N))?.status==="running")await h(N,re)})).finally(()=>{clearTimeout(oe),i.delete(N)}).catch((re)=>console.error("[onboarding] could not save action result",re)),G})}async function I(O,N=!1){let L=O.operationId;return w(L,async()=>{let H=await c(L);if(H?.status==="done"||i.has(L))return H;if(H?.status==="failed"&&!N)return H;let Z=new AbortController;i.set(L,Z);let G={...H,status:"running",error:void 0,sessionId:H?.sessionId??crypto.randomUUID()};try{await h(L,G)}catch(oe){throw i.delete(L),oe}return T(L,O,G).catch(async(oe)=>{await h(L,{...await c(L),status:"failed",error:oe instanceof Error?oe.message:String(oe)})}).finally(()=>i.delete(L)).catch((oe)=>console.error("[onboarding] could not save workspace result",oe)),G})}async function T(O,N,L){let H=N.idea;if(!L.workspacePath){let We=n.workspacesRoot(),jt=ld(We,`onboarding-${O}`);if(pD(jt))L.workspacePath=jt;else L.workspacePath=await yr(H.name,We,n.getWorkspace);await h(O,L)}let Z=L.workspacePath;if(await n.provisionWorkspace(Z,N.harness),!L.workspaceId)await n.setWorkspaceConfig(Z,{name:H.name,icon:{type:"glyph",value:H.icon,background:"theme"}}),await Ke(Z,(We)=>({...We,theme:Ze({...We.theme,...H.theme})}));let G=await n.registerWorkspace(Z,{id:L.workspaceId??hD(Z),harness:N.harness,name:H.name});L.workspaceId=G.id,await h(O,L);let oe=ld(Z,"onboarding-brief.md"),re=L.stage?await Bun.file(oe).text():SE(H);await Bun.write(oe,re),n.publishEvent({type:"workspaces-list:changed"});let xe=n.harnessFor(G);if(L.stage==="sending"||L.stage==="accepted"){let We=await xe.listSessions(G);for(let Ft of We)if((await xe.sessionEvents(G,Ft.sessionId)).some((on)=>on.kind==="turn"&&on.turn.role==="user"&&on.turn.parts.some((Od)=>Od.type==="text"&&Od.text.includes(re)))){L.sessionId=Ft.sessionId,await n.saveSelectedSession(G,Ft.sessionId),await h(O,{...L,status:"done",stage:"accepted"});return}let jt=await n.readWorkspaceState(G);if(L.sessionId=jt.selected.overview??L.sessionId,xe.activeSessions().some((Ft)=>Ft.workspaceId===G.id))throw Error("The agent is still starting. Wait a moment and try again");if(L.stage==="sending")throw Error("Could not confirm the first message. Check the chat before sending the saved onboarding brief")}let Oe=await xe.authStatus?.();if(Oe&&Oe.status!=="available")throw Error("Reconnect the agent, then retry starting the workspace");await n.saveSelectedSession(G,L.sessionId),L.stage="sending",await h(O,L);let je;try{await Promise.race([n.sendWorkspaceMessage(G,{workspaceId:G.id,workspacePath:G.path,sessionId:L.sessionId,isNew:!0,content:re,optimisticId:N.operationId,context:{activeTab:{id:"overview"}}}),new Promise((We,jt)=>{je=setTimeout(()=>jt(Error("Could not confirm the first message. Check the chat before retrying")),90000)})])}finally{clearTimeout(je)}L.sessionId=n.resolveRenamedSession(G.id,L.sessionId),await n.saveSelectedSession(G,L.sessionId),await h(O,{...L,status:"done",stage:"accepted"})}return{discoverIdeas:_,cancelIdeas:E,createFromIdea:I}}var{discoverIdeas:rm,cancelIdeas:bE,createFromIdea:vE}=gD();var EE=s({harness:F(["claude-code","codex"]),runId:r().uuid()}),yD=EE.extend({ideaId:r().uuid(),operationId:r().uuid(),retry:R().optional()}),Fa=new Ui;Fa.use("*",async(t,n)=>{if(u().demo||!ad().showOnboarding)return t.json({error:"Onboarding is not enabled"},403);t.header("Cache-Control","no-store"),await n()});Fa.post("/discover",async(t)=>{let n=EE.safeParse(await t.req.json().catch(()=>{return}));if(!n.success)return t.json({error:"Invalid discovery request"},400);return t.json(await rm(n.data))});Fa.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 bE(n.data.runId),t.json({status:"done"})});Fa.post("/create",async(t)=>{let n=yD.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:h}=n.data,w=await rm({harness:i,runId:o}),E=w.ideas?.find((_)=>_.id===a);if(w.status!=="done"||!E)return t.json({error:"Choose an available idea"},409);return t.json(await vE({harness:i,operationId:c,idea:E},h))});import{stat as ED}from"fs/promises";import{join as AD}from"path";var AE=/^\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 nm=(t,n=SD)=>{let i=/\.([a-zA-Z0-9]+?)$/,o=t.match(i);if(!o)return;return n[o[1].toLowerCase()]};var wD={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"},SD=wD;var xE=(...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 _E={br:".br",zstd:".zst",gzip:".gz"},bD=Object.keys(_E),vD="index.html",IE=(t)=>{let n=t.root??"./",i=t.path,o=t.join??xE;return async(a,c)=>{if(a.finalized)return c();let h;if(t.path)h=t.path;else try{if(h=uh(a.req.path),/(?:^|[\/\\])\.{1,2}(?:$|[\/\\])|[\/\\]{2,}|\\/.test(h))throw Error()}catch{return await t.onNotFound?.(a.req.path,a),c()}let w=o(n,!i&&t.rewriteRequestPath?t.rewriteRequestPath(h):h);if(t.isDir&&await t.isDir(w))w=o(w,vD);let E=t.getContent,_=await E(w,a);if(_ instanceof Response)return a.newResponse(_.body,_);if(_!=null){let I=t.mimes&&nm(w,t.mimes)||nm(w);if(a.header("Content-Type",I||"application/octet-stream"),t.precompressed&&(!I||AE.test(I))){let T=new Set(a.req.header("Accept-Encoding")?.split(",").map((O)=>O.trim()));for(let O of bD){if(!T.has(O))continue;let N=await E(w+_E[O],a);if(N){_=N,a.header("Content-Encoding",O),a.header("Vary","Accept-Encoding",{append:!0});break}}}return await t.onFound?.(w,a),a.body(_)}await t.onNotFound?.(w,a),await c();return}};var im=(t={})=>async function(i,o){return IE({...t,getContent:async(h)=>{let w=Bun.file(h);return await w.exists()?w:null},join:AD,isDir:async(h)=>{let w;try{w=(await ED(h)).isDirectory()}catch{}return w}})(i,o)};var sm="x-hono-disable-ssg",ZK=(()=>{try{return new Response("SSG is disabled",{status:404,headers:{[sm]:"true"}})}catch{return null}})();var{write:NJ}=Bun;var TE=(t)=>(...n)=>{if(typeof n[0]==="function"){let[i,o]=n;return async function(c,h){let w=await i(c),E=await t(c,w,o);if(E)return E;await h()}}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 ud=(t)=>("server"in t.env)?t.env.server:t.env;var ID=TE((t,n)=>{let i=ud(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 RE=(t)=>t;import{existsSync as O$}from"fs";import{basename as kA,resolve as k$}from"path";var PE="Wait for active agents to finish, or stop them before updating Moi";var TD="cf-access-jwt-assertion",RD="CF_Authorization",PD=new Set(["ERR_JOSE_GENERIC","ERR_JWKS_INVALID","ERR_JWKS_TIMEOUT"]);function CD(t,n){let i=new URL("/cdn-cgi/access/certs",t.teamDomain),o=Pm(i,n?{[Nd]:n}:{});return async(a)=>{try{let{payload:c}=await Im(a,o,{issuer:t.teamDomain,audience:[...t.audience],algorithms:["RS256"],requiredClaims:["exp"],clockTolerance:60}),{sub:h,email:w}=c;return h&&typeof w==="string"&&w?{id:h,email:w}:null}catch(c){if(!(c instanceof q)||PD.has(c.code))console.error(`[moi] Cloudflare Access: could not load signing keys from ${i}: ${c}`);return null}}}function OD({id:t,email:n}){let i={id:t,color:Yi(t),email:n};return xr(i)?i:null}var om=null;async function dd(t){let n=u().cloudflareAccess;if(!n)return{};if(om?.config!==n)om={config:n,verify:CD(n)};let i=t.headers.get(TD)??new Bun.CookieMap(t.headers.get("cookie")??"").get(RD),o=i?await om.verify(i):null,a=o?OD(o):null;return a?{provider:"cloudflare-access",profile:a}:{provider:"cloudflare-access"}}var am=new Map;function CE(t){let n=u();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=am.get(t);if(i)return i;let o=(async()=>{if((await On())[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",Nn[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 On())[t])throw Error("The installer finished, but the agent could not be found. Restart Moi.")})().finally(()=>am.delete(t));return am.set(t,o),o}var Xo=new Ui;Xo.get("/status",async(t)=>{t.header("Cache-Control","no-store");let n=t.req.query("refresh")==="true";if(n)await Ge({refresh:!0});let i=await Promise.all(ae().map(async({id:o})=>[o,{availability:await j.getAvailability(o,n),login:j.getLogin(o)}]));return t.json(Object.fromEntries(i))});Xo.use("/:type/*",async(t,n)=>{let i=t.req.param("type");if(!rr(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()});Xo.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 CE(i),await j.refresh(i),t.json({ok:!0})}catch(i){return t.text(i instanceof Error?i.message:"Could not install agent",400)}});Xo.post("/:type/auth/login",async(t)=>{try{return t.json(await j.startLogin(t.get("harnessType")))}catch(n){return t.text(n instanceof Error?n.message:"Could not start sign-in",500)}});Xo.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 j.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 Zo=new Map;function OE(t){return[t.source,t.kind??"",t.name??"",t.module??"",t.fn??"",t.message].join("\x00")}function fd(t,n){let i=Zo.get(t)??[],o=n.message.slice(0,1000),a=OE({...n,message:o}),c=i.findIndex((h)=>OE(h)===a);if(c!==-1){let[h]=i.splice(c,1);h.count++,h.ts=Date.now(),i.push(h)}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();Zo.set(t,i)}function kE(t){return(Zo.get(t)??[]).map((n)=>({...n}))}function cm(t){return Zo.get(t)?.length??0}function ME(t){let n=cm(t);return Zo.delete(t),n}function NE(t){let n=t.match(/^(widgets|views)\/([^/]+)$/);if(!n)return null;return{kind:n[1]==="widgets"?"widget":"view",name:n[2]}}function pd(t,n,i){let o=new Set,a=new Set,c=new Set(i.map((E)=>E.name));for(let E of i){if(E.status==="failed")fd(t,{source:"build",kind:n,name:E.name,message:E.error??"Build failed"});if(E.status==="built"){a.add(E.name);for(let _ of E.serverModules??[])o.add(_)}}let h=Zo.get(t);if(!h)return;let w=h.filter((E)=>{if(E.kind===n&&E.name&&(a.has(E.name)||!c.has(E.name)))return!1;if(E.source==="rpc"&&E.module&&o.has(E.module))return!1;return!0});Zo.set(t,w)}import{realpathSync as UE,statSync as HE}from"fs";import{mkdir as qD,readdir as VE,rm as FE}from"fs/promises";import{join as bi,resolve as qE,sep as BE}from"path";import{readdir as kD}from"fs/promises";import{dirname as MD,join as Qo,resolve as ND}from"path";var lm=/\.[mc]?[jt]sx?$/,DD=/\.[mc]?ts$/,$D=256;async function zc(t){try{return(await kD(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 $E(t,n){for(let i of[".tsx",".ts"]){let o=Qo(t,`${n}${i}`);if(await Bun.file(o).exists())return o}return null}var LD={ts:new Bun.Transpiler({loader:"ts"}),tsx:new Bun.Transpiler({loader:"tsx"})};function jD(t,n="tsx"){let i;try{i=LD[n].scanImports(t)}catch{return null}return i.map((o)=>o.path).filter((o)=>/^\.\.?\//.test(o))}async function um(t,n=1/0){let i={entrypoints:new Set([...t].map((a)=>ND(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>=$D){i.complete=!1;break}let c={modifiedAt:0,imports:[]};i.modules.set(a,c);try{let h=Bun.file(a);if(!await h.exists()){i.complete=!1;continue}if(c.modifiedAt=h.lastModified,c.modifiedAt>=n){i.complete=!1;break}if(!lm.test(a))continue;let w=jD(await h.text(),DD.test(a)?"ts":"tsx");if(!w){i.complete=!1;continue}for(let E of w){let _=await FD(MD(a),E);if(!_){i.complete=!1;continue}c.imports.push(_),o.push(_)}}catch{i.complete=!1}}return i}async function LE(t){let n=[];for(let i of["views","widgets"]){let o=Qo(t,".moi",i);for(let a of await zc(o))for(let c of[".tsx",".ts",".server.ts"]){let h=Qo(o,a+c);if(await Bun.file(h).exists())n.push(h)}}return um(n)}function dm(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 DE=[".tsx",".ts",".jsx",".js",".mjs",".cjs",".json",".mts",".cts"],UD={".js":[".ts",".tsx"],".jsx":[".tsx"],".mjs":[".mts"]};async function FD(t,n){let i=Qo(t,n),o=[i],a=/\.[^./\\]+$/.exec(i)?.[0]??"";for(let w of UD[a]??[])o.push(i.slice(0,i.length-a.length)+w);for(let w of DE)o.push(i+w);for(let w of o)if(await Bun.file(w).exists())return w;let c=await Bun.file(Qo(i,"package.json")).json().catch(()=>null),h=typeof c==="object"&&c!==null&&"main"in c&&typeof c.main==="string"?c.main:null;if(h){let w=Qo(i,h);if(await Bun.file(w).exists())return w}for(let w of DE){let E=Qo(i,`index${w}`);if(await Bun.file(E).exists())return E}return null}var jE="%%MOI_APPLET_API_BASE%%";function In(t,n){let i=bi(t,".moi"),o=n==="widget"?"widgets":"views",a=bi(i,o),c=bi(i,".build",o),h=bi(c,"manifest.json");return{moiRoot:i,sourceDir:a,buildDir:c,manifestPath:h}}function hd(t,n,i){try{let{buildDir:o}=In(t,n),a=HE(bi(o,i,"index.js"));return`${a.size}-${Math.trunc(a.mtimeMs)}`}catch{return}}async function BD(t,n,i){let o=Bun.file(bi(t,n,"index.js"));if(!await o.exists())return!0;return!(await um([i],o.lastModified)).complete}async function md(t){try{let n=await VE(t,{withFileTypes:!0}),i=[];for(let o of n){if(!o.isDirectory())continue;if(await Bun.file(bi(t,o.name,"index.js")).exists())i.push(o.name)}return i}catch{return[]}}async function WD(t,n){let i;try{i=await VE(t,{withFileTypes:!0})}catch{return}for(let o of i){if(o.isDirectory()){if(!n.has(o.name))await FE(bi(t,o.name),{recursive:!0,force:!0}).catch(()=>{});continue}if(o.isFile()&&o.name.endsWith(".js"))await FE(bi(t,o.name),{force:!0}).catch(()=>{})}}var HD=/\.js$/,VD=/^[a-zA-Z0-9_-][a-zA-Z0-9._-]*$/,zD="text/javascript; charset=utf-8",GD="public, max-age=604800, immutable",KD=/^chunk-[0-9a-z]+\.\w+$|-[0-9a-f]{6,}\.\w+$/i;async function gd(t,n,i,o,a,c){if(!/^[a-zA-Z0-9_-]+$/.test(n))return new Response("Invalid name",{status:400});if(!VD.test(i)||i.includes(".."))return new Response("Invalid file",{status:400});let{buildDir:h}=In(o,t),w=bi(h,n,i),E=Bun.file(w);if(!await E.exists())return new Response(`"${n}" not built. Run: moi bundle`,{status:404});let _;if(KD.test(i))_={"Cache-Control":GD};else{let I=`"${E.size}-${Math.trunc(E.lastModified)}-${Bun.hash(a)}-url-base-v2"`;if(_={ETag:I,"Cache-Control":"private, no-cache"},c===I)return new Response(null,{status:304,headers:_})}if(HD.test(i)){let I=`(new URL(import.meta.url).pathname.match(/^\\/api\\/workspaces\\/[^/]+/)?.[0] ?? ${JSON.stringify(a)})`,T=(await E.text()).replace(/(["'])([^"'\n]*%%MOI_APPLET_API_BASE%%[^"'\n]*)\1/g,(O,N,L)=>"("+L.split(jE).map((H)=>JSON.stringify(H)).join(" + "+I+" + ")+")");return new Response(T,{headers:{"Content-Type":zD,..._}})}return new Response(E,{headers:{"Content-Type":E.type||"application/octet-stream",..._}})}var WE="index.js",JD="module";function fm(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:WE};let c=o.slice(a+1);return{name:o.slice(0,a),file:c===JD?WE:c}}var YD=/\.(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 pm(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((E)=>E===""||E==="."||E===".."||E.startsWith(".")))return new Response("Forbidden",{status:403});if(!YD.test(i))return new Response("Unsupported file type",{status:415});let a=qE(t),c=qE(t,i);if(c!==a&&!c.startsWith(a+BE))return new Response("Forbidden",{status:403});let h;try{h=UE(c)}catch{return new Response("Not found",{status:404})}let w;try{w=UE(a)}catch{return new Response("Forbidden",{status:403})}if(h!==w&&!h.startsWith(w+BE))return new Response("Forbidden",{status:403});return h}async function zE(t,n,i,o){let a=pm(t,n);if(a instanceof Response)return a;let c=Bun.file(a),h;try{h=HE(a,{bigint:!0})}catch{return new Response("Not found",{status:404})}let w=Number(h.size),E=c.type||"application/octet-stream",_=`"${w}-${h.mtimeNs}"`,I={ETag:_,"Cache-Control":"private, no-cache"};if(o===_)return new Response(null,{status:304,headers:I});let T=i?XD(i,w):null;if(T==="invalid")return new Response("Range Not Satisfiable",{status:416,headers:{...I,"Content-Range":`bytes */${w}`,"Accept-Ranges":"bytes"}});if(T){let{start:O,end:N}=T;return new Response(c.slice(O,N+1),{status:206,headers:{...I,"Content-Type":E,"Content-Length":String(N-O+1),"Content-Range":`bytes ${O}-${N}/${w}`,"Accept-Ranges":"bytes"}})}return new Response(c,{headers:{...I,"Content-Type":E,"Content-Length":String(w),"Accept-Ranges":"bytes"}})}function XD(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,h;if(!o){let w=parseInt(i[2],10);c=Math.max(0,n-w),h=n-1}else c=parseInt(i[1],10),h=a?Math.min(parseInt(i[2],10),n-1):n-1;if(c>h||c>=n||c<0)return"invalid";return{start:c,end:h}}async function yd(t,n,i,o){let a=performance.now(),{sourceDir:c,buildDir:h,moiRoot:w}=In(t,n),E=await zc(c);if(E.length>0)await qD(h,{recursive:!0});await WD(h,new Set(E)),await os(t,n,E);let _=await Promise.all(E.map(async(O)=>{if(o&&O!==o)return{name:O,status:"skipped"};let N=await $E(c,O);if(!N)return{name:O,status:"failed",error:"Source file not found"};if(!i&&!await BD(h,O,N))return{name:O,status:"skipped"};return{name:O,srcPath:N,status:"pending"}})),I=new Map((await qi({moiRoot:w,kind:n,jobs:_.filter((O)=>O.status==="pending").map((O)=>({name:O.name,srcPath:O.srcPath,outDir:bi(h,O.name)}))})).map((O)=>[O.name,O])),T=_.map((O)=>{if(O.status==="failed")return{name:O.name,status:"failed",error:O.error};if(O.status==="skipped")return{name:O.name,status:"skipped"};let N=I.get(O.name);if(!N)return{name:O.name,status:"failed",error:"Build worker returned no result"};if(N.status==="failed")return{name:O.name,status:"failed",error:N.error};return{name:O.name,status:"built",serverModules:N.serverModules,config:N.config??null}});return{names:E,results:T,ms:Math.round(performance.now()-a)}}import{tracingChannel as ZD,channel as QD}from"diagnostics_channel";var Sr=QD("lru-cache:metrics"),Gc=ZD("lru-cache"),e$=typeof performance=="object"&&performance&&typeof performance.now=="function"?performance:Date,hm=()=>Sr.hasSubscribers||Gc.hasSubscribers,KE=new Set,GE=typeof process=="object"&&process?process:{},t$=(t,n,i,o)=>{typeof GE.emitWarning=="function"?GE.emitWarning(t,n,i,o):console.error(`[${i}] ${n}: ${t}`)},r$=(t)=>!KE.has(t),Io=(t)=>!!t&&t===Math.floor(t)&&t>0&&isFinite(t),JE=(t)=>Io(t)?t<=Math.pow(2,8)?Uint8Array:t<=Math.pow(2,16)?Uint16Array:t<=Math.pow(2,32)?Uint32Array:t<=Number.MAX_SAFE_INTEGER?wd:null:null,wd=class extends Array{constructor(t){super(t),this.fill(0)}},n$=class t{heap;length;static#t=!1;static create(n){let i=JE(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]}},YE=class t{#t;#e;#r;#o;#n;#s;#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;#i;#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.#i,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.#$(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.#s}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:h,updateAgeOnHas:w,allowStale:E,dispose:_,onInsert:I,disposeAfter:T,noDisposeOnSet:O,noUpdateTTL:N,maxSize:L=0,maxEntrySize:H=0,sizeCalculation:Z,fetchMethod:G,memoMethod:oe,noDeleteOnFetchRejection:re,noDeleteOnStaleGet:xe,allowStaleOnFetchRejection:Oe,allowStaleOnFetchAbort:je,ignoreFetchAbort:We,backgroundFetchSize:jt=1,perf:Ft}=n;if(this.backgroundFetchSize=jt,Ft!==void 0&&typeof Ft?.now!="function")throw TypeError("perf option must have a now() method if specified");if(this.#f=Ft??e$,i!==0&&!Io(i))throw TypeError("max option must be a nonnegative integer");let io=i?JE(i):Array;if(!io)throw Error("invalid max value: "+i);if(this.#t=i,this.#e=L,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(oe!==void 0&&typeof oe!="function")throw TypeError("memoMethod must be a function if defined");if(this.#S=oe,G!==void 0&&typeof G!="function")throw TypeError("fetchMethod must be a function if specified");if(this.#s=G,this.#L=!!G,this.#u=new Map,this.#c=Array.from({length:i}).fill(void 0),this.#i=Array.from({length:i}).fill(void 0),this.#g=new io(i),this.#y=new io(i),this.#h=0,this.#d=0,this.#A=n$.create(i),this.#a=0,this.#p=0,typeof _=="function"&&(this.#r=_),typeof I=="function"&&(this.#o=I),typeof T=="function"?(this.#n=T,this.#m=[]):(this.#n=void 0,this.#m=void 0),this.#I=!!this.#r,this.#k=!!this.#o,this.#w=!!this.#n,this.noDisposeOnSet=!!O,this.noUpdateTTL=!!N,this.noDeleteOnFetchRejection=!!re,this.allowStaleOnFetchRejection=!!Oe,this.allowStaleOnFetchAbort=!!je,this.ignoreFetchAbort=!!We,this.maxEntrySize!==0){if(this.#e!==0&&!Io(this.#e))throw TypeError("maxSize must be a positive integer if specified");if(!Io(this.maxEntrySize))throw TypeError("maxEntrySize must be a positive integer if specified");this.#K()}if(this.allowStale=!!E,this.noDeleteOnStaleGet=!!xe,this.updateAgeOnGet=!!h,this.updateAgeOnHas=!!w,this.ttlResolution=Io(a)||a===0?a:1,this.ttlAutopurge=!!c,this.ttl=o||0,this.ttl){if(!Io(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 on="LRU_CACHE_UNBOUNDED";r$(on)&&(KE.add(on),t$("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning",on,t))}}getRemainingTTL(n){return this.#u.has(n)?1/0:0}#q(){let n=new wd(this.#t),i=new wd(this.#t);this.#b=n,this.#_=i;let o=this.ttlAutopurge?Array.from({length:this.#t}):void 0;this.#v=o,this.#B=(E,_,I=this.#f.now())=>{i[E]=_!==0?I:0,n[E]=_,a(E,_)},this.#M=(E)=>{i[E]=n[E]!==0?this.#f.now():0,a(E,n[E])};let a=this.ttlAutopurge?(E,_)=>{if(o?.[E]&&(clearTimeout(o[E]),o[E]=void 0),_&&_!==0&&o){let I=setTimeout(()=>{this.#E(E)?(this.#P(this.#c[E],"expire"),o[E]=void 0):a(E,w(E))},_+1);I.unref&&I.unref(),o[E]=I}}:()=>{};this.#C=(E,_)=>{if(n[_]){let I=n[_],T=i[_];if(!I||!T)return;E.ttl=I,E.start=T,E.now=c||h();let O=E.now-T;E.remainingTTL=I-O}};let c=0,h=()=>{let E=this.#f.now();if(this.ttlResolution>0){c=E;let _=setTimeout(()=>c=0,this.ttlResolution);_.unref&&_.unref()}return E};this.getRemainingTTL=(E)=>{let _=this.#u.get(E);return _===void 0?0:w(_)};let w=(E)=>{let _=n[E],I=i[E];if(!_||!I)return 1/0;let T=(c||h())-I;return _-T};this.#E=(E)=>{let _=i[E],I=n[E];return!!I&&!!_&&(c||h())-_>I}}#M=()=>{};#C=()=>{};#B=()=>{};#E=()=>!1;#K(){let n=new wd(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(!Io(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),!Io(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.#i[n]!==void 0&&this.#c[n]!==void 0&&!this.#l(this.#i[n])&&(yield[this.#c[n],this.#i[n]])}*rentries(){for(let n of this.#R())this.#i[n]!==void 0&&this.#c[n]!==void 0&&!this.#l(this.#i[n])&&(yield[this.#c[n],this.#i[n]])}*keys(){for(let n of this.#T()){let i=this.#c[n];i!==void 0&&!this.#l(this.#i[n])&&(yield i)}}*rkeys(){for(let n of this.#R()){let i=this.#c[n];i!==void 0&&!this.#l(this.#i[n])&&(yield i)}}*values(){for(let n of this.#T())this.#i[n]!==void 0&&!this.#l(this.#i[n])&&(yield this.#i[n])}*rvalues(){for(let n of this.#R())this.#i[n]!==void 0&&!this.#l(this.#i[n])&&(yield this.#i[n])}[Symbol.iterator](){return this.entries()}[Symbol.toStringTag]="LRUCache";find(n,i={}){for(let o of this.#T()){let a=this.#i[o],c=this.#l(a)?a.__staleWhileFetching:a;if(c!==void 0&&n(c,this.#c[o],this))return this.#D(this.#c[o],i)}}forEach(n,i=this){for(let o of this.#T()){let a=this.#i[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.#i[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.#i[i],a=this.#l(o)?o.__staleWhileFetching:o;if(a===void 0)return;let c={value:a};if(this.#b&&this.#_){let h=this.#b[i],w=this.#_[i];if(h&&w){let E=h-(this.#f.now()-w);c.ttl=E,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.#i[i],c=this.#l(a)?a.__staleWhileFetching:a;if(c===void 0||o===void 0)continue;let h={value:c};if(this.#b&&this.#_){h.ttl=this.#b[i];let w=this.#f.now()-this.#_[i];h.start=Math.floor(Date.now()-w)}this.#x&&(h.size=this.#x[i]),n.unshift([o,h])}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=Sr.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&&Sr.hasSubscribers&&Sr.publish(a),c}#O(n,i,o,a){let{ttl:c=this.ttl,start:h,noDisposeOnSet:w=this.noDisposeOnSet,sizeCalculation:E=this.sizeCalculation,status:_}=o,I=this.#l(i);if(i===void 0)return _&&(_.set="deleted"),this.delete(n),this;let{noUpdateTTL:T=this.noUpdateTTL}=o;_&&!I&&(_.value=i);let O=this.#W(n,i,o.size||0,E,_);if(this.maxEntrySize&&O>this.maxEntrySize)return this.#P(n,"set"),_&&(_.set="miss",_.maxEntrySizeExceeded=!0),this;let N=this.#a===0?void 0:this.#u.get(n);if(N===void 0)N=this.#a===0?this.#d:this.#A.length!==0?this.#A.pop():this.#a===this.#t?this.#U(!1):this.#a,this.#c[N]=n,this.#i[N]=i,this.#u.set(n,N),this.#g[this.#d]=N,this.#y[N]=this.#d,this.#d=N,this.#a++,this.#j(N,O,_),_&&(_.set="add"),T=!1,this.#k&&!I&&this.#o?.(i,n,"add");else{this.#$(N);let L=this.#i[N];if(i!==L){if(!w)if(this.#l(L)){L!==a&&L.__abortController.abort(Error("replaced"));let{__staleWhileFetching:H}=L;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?.(L,n,"set"),this.#w&&this.#m?.push([L,n,"set"]);if(this.#N(N),this.#j(N,O,_),this.#i[N]=i,!I){let H=L&&this.#l(L)?L.__staleWhileFetching:L,Z=H===void 0?"add":i!==H?"replace":"update";_&&(_.set=Z,H!==void 0&&(_.oldValue=H)),this.#k&&this.onInsert?.(i,n,Z)}}else I||(_&&(_.set="update"),this.#k&&this.onInsert?.(i,n,"update"))}if(c!==0&&!this.#b&&this.#q(),this.#b&&(T||this.#B(N,c,h),_&&this.#C(_,N)),!w&&this.#w&&this.#m){let L=this.#m,H;for(;H=L?.shift();)this.#n?.(...H)}return this}pop(){try{for(;this.#a;){let n=this.#i[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.#i[i],c=this.#l(a);c&&a.__abortController.abort(Error("evicted"));let h=c?a.__staleWhileFetching:a;return(this.#I||this.#w)&&h!==void 0&&(this.#I&&this.#r?.(h,o,"evict"),this.#w&&this.#m?.push([h,o,"evict"])),this.#N(i),this.#v?.[i]&&(clearTimeout(this.#v[i]),this.#v[i]=void 0),n&&(this.#c[i]=void 0,this.#i[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=Sr.hasSubscribers?{}:void 0}=i;i.status=o,o&&(o.op="has",o.key=n,o.cache=this);let a=this.#J(n,i);return Sr.hasSubscribers&&Sr.publish(o),a}#J(n,i={}){let{updateAgeOnHas:o=this.updateAgeOnHas,status:a}=i,c=this.#u.get(n);if(c!==void 0){let h=this.#i[c];if(this.#l(h)&&h.__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=hm()?{}:void 0}=i;o&&(o.op="peek",o.key=n,o.cache=this),i.status=o;let a=this.#Y(n,i);return Sr.hasSubscribers&&Sr.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 h=this.#i[c],w=this.#l(h)?h.__staleWhileFetching:h;return o&&(w!==void 0?(o.peek="hit",o.value=w):o.peek="miss"),w}#F(n,i,o,a){let c=i===void 0?void 0:this.#i[i];if(this.#l(c))return c;let h=new AbortController,{signal:w}=o;w?.addEventListener("abort",()=>h.abort(w.reason),{signal:h.signal});let E={signal:h.signal,options:o,context:a},_=(H,Z=!1)=>{let{aborted:G}=h.signal,oe=o.ignoreFetchAbort&&H!==void 0,re=o.ignoreFetchAbort||!!(o.allowStaleOnFetchAbort&&H!==void 0);if(o.status&&(G&&!Z?(o.status.fetchAborted=!0,o.status.fetchError=h.signal.reason,oe&&(o.status.fetchAbortIgnored=!0)):o.status.fetchResolved=!0),G&&!oe&&!Z)return T(h.signal.reason,re);let xe=N,Oe=this.#i[i];return(Oe===N||Oe===void 0&&oe&&Z)&&(H===void 0?xe.__staleWhileFetching!==void 0?this.#i[i]=xe.__staleWhileFetching:this.#P(n,"fetch"):(o.status&&(o.status.fetchUpdated=!0),this.#O(n,H,E.options,xe))),H},I=(H)=>(o.status&&(o.status.fetchRejected=!0,o.status.fetchError=H),T(H,!1)),T=(H,Z)=>{let{aborted:G}=h.signal,oe=G&&o.allowStaleOnFetchAbort,re=oe||o.allowStaleOnFetchRejection,xe=re||o.noDeleteOnFetchRejection,Oe=N;if(this.#i[i]===N&&(!xe||!Z&&Oe.__staleWhileFetching===void 0?this.#P(n,"fetch"):oe||(this.#i[i]=Oe.__staleWhileFetching)),re)return o.status&&Oe.__staleWhileFetching!==void 0&&(o.status.returnedStale=!0),Oe.__staleWhileFetching;if(Oe.__returned===Oe)throw H},O=(H,Z)=>{let G=this.#s?.(n,c,E);h.signal.addEventListener("abort",()=>{(!o.ignoreFetchAbort||o.allowStaleOnFetchAbort)&&(H(void 0),o.allowStaleOnFetchAbort&&(H=(oe)=>_(oe,!0)))}),G&&G instanceof Promise?G.then((oe)=>H(oe===void 0?void 0:oe),Z):G!==void 0&&H(G)};o.status&&(o.status.fetchDispatched=!0);let N=new Promise(O).then(_,I),L=Object.assign(N,{__abortController:h,__staleWhileFetching:c,__returned:void 0});return i===void 0?(this.#O(n,L,{...E.options,status:void 0}),i=this.#u.get(n)):this.#i[i]=L,L}#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=Gc.hasSubscribers,{status:a=hm()?{}: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,Gc.tracePromise(()=>c,a).catch(()=>{})),c}async#V(n,i={}){let{allowStale:o=this.allowStale,updateAgeOnGet:a=this.updateAgeOnGet,noDeleteOnStaleGet:c=this.noDeleteOnStaleGet,ttl:h=this.ttl,noDisposeOnSet:w=this.noDisposeOnSet,size:E=0,sizeCalculation:_=this.sizeCalculation,noUpdateTTL:I=this.noUpdateTTL,noDeleteOnFetchRejection:T=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:O=this.allowStaleOnFetchRejection,ignoreFetchAbort:N=this.ignoreFetchAbort,allowStaleOnFetchAbort:L=this.allowStaleOnFetchAbort,context:H,forceRefresh:Z=!1,status:G,signal:oe}=i;if(G&&(G.op="fetch",G.key=n,Z&&(G.forceRefresh=!0),G.cache=this),!this.#L)return G&&(G.fetch="get"),this.#D(n,{allowStale:o,updateAgeOnGet:a,noDeleteOnStaleGet:c,status:G});let re={allowStale:o,updateAgeOnGet:a,noDeleteOnStaleGet:c,ttl:h,noDisposeOnSet:w,size:E,sizeCalculation:_,noUpdateTTL:I,noDeleteOnFetchRejection:T,allowStaleOnFetchRejection:O,allowStaleOnFetchAbort:L,ignoreFetchAbort:N,status:G,signal:oe},xe=this.#u.get(n);if(xe===void 0){G&&(G.fetch="miss");let Oe=this.#F(n,xe,re,H);return Oe.__returned=Oe}else{let Oe=this.#i[xe];if(this.#l(Oe)){let Ft=o&&Oe.__staleWhileFetching!==void 0;return G&&(G.fetch="inflight",Ft&&(G.returnedStale=!0)),Ft?Oe.__staleWhileFetching:Oe.__returned=Oe}let je=this.#E(xe);if(!Z&&!je)return G&&(G.fetch="hit"),this.#$(xe),a&&this.#M(xe),G&&this.#C(G,xe),Oe;let We=this.#F(n,xe,re,H),jt=We.__staleWhileFetching!==void 0&&o;return G&&(G.fetch=je?"stale":"refresh",jt&&je&&(G.returnedStale=!0)),jt?We.__staleWhileFetching:We.__returned=We}}forceFetch(n,i={}){let o=Gc.hasSubscribers,{status:a=hm()?{}: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,Gc.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=Sr.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),Sr.hasSubscribers&&Sr.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:h,...w}=i;c&&h&&(c.forceRefresh=!0);let E=this.#D(n,w),_=h||E===void 0;if(c&&(c.memo=_?"miss":"hit",_||(c.value=E)),!_)return E;let I=o(n,E,{options:w,context:a});return c&&(c.value=I),this.#O(n,I,w),I}get(n,i={}){let{status:o=Sr.hasSubscribers?{}:void 0}=i;i.status=o,o&&(o.op="get",o.key=n,o.cache=this);let a=this.#D(n,i);return o&&(a!==void 0&&(o.value=a),Sr.hasSubscribers&&Sr.publish(o)),a}#D(n,i={}){let{allowStale:o=this.allowStale,updateAgeOnGet:a=this.updateAgeOnGet,noDeleteOnStaleGet:c=this.noDeleteOnStaleGet,status:h}=i,w=this.#u.get(n);if(w===void 0){h&&(h.get="miss");return}let E=this.#i[w],_=this.#l(E);return h&&this.#C(h,w),this.#E(w)?_?(h&&(h.get="stale-fetching"),o&&E.__staleWhileFetching!==void 0?(h&&(h.returnedStale=!0),E.__staleWhileFetching):void 0):(c||this.#P(n,"expire"),h&&(h.get="stale"),o?(h&&(h.returnedStale=!0),E):void 0):(h&&(h.get=_?"fetching":"hit"),this.#$(w),a&&this.#M(w),_?E.__staleWhileFetching:E)}#z(n,i){this.#y[i]=n,this.#g[n]=i}#$(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){Sr.hasSubscribers&&Sr.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.#i[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.#i[a]=void 0,a===this.#d)this.#d=this.#y[a];else if(a===this.#h)this.#h=this.#g[a];else{let h=this.#y[a];this.#g[h]=this.#g[a];let w=this.#g[a];this.#y[w]=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.#i[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.#i.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 s$}from"os";import{join as o$}from"path";var a$=ge("applets/functions-worker.ts"),XE=30000,ZE=600000,QE=8;function mm(t,n){for(let{reject:i,timer:o}of t.pending.values())clearTimeout(o),i(Error(n));t.pending.clear()}function Sd(t,n){if(t.killed)return;t.killed=!0,mm(t,n);try{t.worker.kill()}catch{}}var c$=2000;function l$(t,n){if(t.killed)return;t.killed=!0,mm(t,n);let i=setTimeout(()=>{try{t.worker.kill()}catch{}},c$);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 vi=new YE({max:QE,ttl:ZE,ttlAutopurge:!0,updateAgeOnGet:!0,dispose:(t)=>Sd(t,"Functions worker idle-evicted")});function eA(t,n){let i=o$(t,".moi"),o=()=>{},a=new Promise((h)=>o=h),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(U([process.execPath,a$]),{cwd:s$(),env:{...process.env,...n,MEI_WORKSPACE_ROOT:t,MEI_FUNCTIONS_DIR:process.env.MEI_FUNCTIONS_DIR??i},stderr:"inherit",onExit(h,w){if(w!==0&&w!==null)console.error(`[mei] functions worker for ${t} exited with code ${w}`);if(c.killed=!0,mm(c,"Functions worker exited"),vi.peek(t)===c)vi.delete(t)},ipc(h){let w=h;if(w.type==="ready"){c.ready=!0,o();return}if(w.type==="loaded"&&w.module){c.modules.add(w.module);return}if(w.id){let E=c.pending.get(w.id);if(!E)return;if(c.pending.delete(w.id),clearTimeout(E.timer),w.type==="result")E.resolve(w.data);else if(w.type==="error")c.errors++,E.reject(Error(w.message??"Unknown error"))}}}),c}function u$(t,n){let i=vi.get(t);if(i&&!i.killed)return i;let o=eA(t,n);return vi.set(t,o),o}function bd(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 tA(t,n,i,o){t.calls++,t.lastCallAt=Date.now();let a=crypto.randomUUID();return new Promise((c,h)=>{let w=setTimeout(()=>{t.pending.delete(a),t.timeouts++,h(Error(`Function call timed out: ${n}/${i}`))},XE);t.pending.set(a,{resolve:c,reject:h,timer:w});try{t.worker.send({id:a,type:"call",module:n,name:i,args:o})}catch(E){t.pending.delete(a),clearTimeout(w),h(E instanceof Error?E:Error("Failed to send to worker"))}})}async function rA(t,n,i,o){let a=await X(o),c=u$(o,a);return await c.readyPromise,tA(c,t,n,i)}async function nA(t,n,i,o){let a=await X(o),c=eA(o,a);try{return await c.readyPromise,await tA(c,t,n,i)}finally{Sd(c,"Ephemeral call finished")}}function iA(){for(let t of vi.values())Sd(t,"Server shutting down");vi.clear()}function sA(t){let n=vi.peek(t);if(n)Sd(n,"Workspace env changed");vi.delete(t)}var vd={maxWorkers:QE,idleTtlMs:ZE,callTimeoutMs:XE};function d$(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 oA(){let t=[];for(let[n,i]of vi.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:vi.getRemainingTTL(n),rssBytes:d$(i.worker.pid),modules:[...i.modules].sort()})}return t}function Kc(t,n){if(t.length===0)return;let i=vi.peek(n);if(!i||i.killed)return;l$(i,`Server code changed (${t.join(", ")})`)}function Ed(t){sA(t.path);for(let n of ae())n.onEnvChanged?.(t.path);j.invalidate(t),m({type:"env:changed",workspaceId:t.id})}import f$ from"sharp";async function Ad(t){return`data:image/webp;base64,${(await f$(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 p$}from"fs";import{join as h$}from"path";var gm=v("dist"),aA=h$(gm,"index.html"),qa=!process.env.MOI_DEV&&p$(aA);function cA(){return new Response(Bun.file(aA),{headers:{"Cache-Control":"no-cache"}})}import{statSync as m$}from"fs";import g$ from"sharp";var ym=800,y$=/\.(png|jpe?g|webp|avif)$/i,w$=/\.(gif|svg)$/i;async function lA(t,n,i){let o=y$.test(n);if(!o&&!w$.test(n))return new Response("Not an image",{status:415});let a=pm(t,n);if(a instanceof Response)return a;let c;try{c=m$(a)}catch{return new Response("Not found",{status:404})}let h=`"${c.size}-${Math.trunc(c.mtimeMs)}${o?`-${ym}`:""}"`,w={ETag:h,"Cache-Control":"private, no-cache"};if(i===h)return new Response(null,{status:304,headers:w});if(!o){let E=Bun.file(a);return new Response(E,{headers:{...w,"Content-Type":E.type||"application/octet-stream"}})}try{let E=await g$(a).rotate().resize(ym,ym,{fit:"inside",withoutEnlargement:!0}).webp({quality:80}).toBuffer();return new Response(new Uint8Array(E),{headers:{...w,"Content-Type":"image/webp"}})}catch{return new Response("Preview failed",{status:415})}}import{existsSync as v$}from"fs";var Ba=new Map;function Jc(t,n){let o=(Ba.get(t)??Promise.resolve()).then(n,n);return Ba.set(t,o),o.then(()=>{if(Ba.get(t)===o)Ba.delete(t)},()=>{if(Ba.get(t)===o)Ba.delete(t)}),o}import{realpath as uA,rm as S$}from"fs/promises";import{join as Wa,relative as b$,sep as dA}from"path";async function pA(t,n){let i=Wa(t,".moi","views");for(let o of[".tsx",".ts"]){let a=Wa(i,`${n}${o}`),c=Bun.file(a);if(await c.exists())return{path:a,source:await c.text()}}return null}class xd extends Error{}function fA(t,n){if(!n.startsWith(t+dA)||!lm.test(n))return!1;return!b$(t,n).split(dA).some((i)=>i.startsWith(".")||["data","ui","node_modules"].includes(i))}async function hA(t,n,i){let o=await uA(t),a=Wa(o,".moi"),c=Wa(a,"views"),h=["tsx","ts"].map((I)=>Wa(c,`${n}.${I}`)),w=new Set([...h,Wa(c,`${n}.server.ts`)]),E=new Set(h),_=await LE(o).catch(()=>null);if(_?.complete){if((await Promise.all([..._.modules.keys()].map(async(T)=>await uA(T).catch(()=>null)===T))).every(Boolean)){let T=dm(_,w),O=dm(_,[...[..._.entrypoints].filter((N)=>!w.has(N)),...[...T].filter((N)=>!fA(a,N))]);if(h.some((N)=>O.has(N)))throw new xd("Another applet imports this view. Remove that import before deleting it.");for(let N of T)if(!O.has(N)&&fA(a,N))E.add(N)}}await i?.(),await Promise.all([...E].map((I)=>S$(I,{force:!0})))}class Ei extends Error{status;constructor(t,n){super(t);this.status=n;this.name="ViewMutationError"}}async function Yc(t){let{manifestPath:n}=In(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 E$(t,n){let{manifestPath:i}=In(t,"view");await Bun.write(i,JSON.stringify(n,null,2))}function A$(t,n){let i=new Set(n),o=t.filter((h)=>i.has(h)),a=new Set(o),c=n.filter((h)=>!a.has(h));return[...o,...c]}async function x$(t,n=!1,i){let{names:o,results:a,ms:c}=await yd(t,"view",n,i),h=await Yc(t);for(let I of a)if(I.status==="built")h.config[I.name]=I.config??{};for(let I of Object.keys(h.config))if(!o.includes(I))delete h.config[I];h.order=A$(h.order,o);let{buildDir:w}=In(t,"view");if(v$(w))await E$(t,h);let E=a.filter((I)=>I.status==="built").length,_=a.filter((I)=>I.status==="failed");console.log(`[bundle] ${E}/${o.length} views built in ${c}ms`+(_.length?`, ${_.length} failed`:"")+(n?" (forced)":""));for(let I of _)console.error(`[bundle] ${I.name}:
|
|
78
|
+
${I.error}`);return a}function wm(t){let{buildDir:n}=In(t,"view");return md(n)}async function To(t){let[n,i]=await Promise.all([wm(t),Yc(t)]),o=new Set(n);return[...i.order.filter((c)=>o.has(c)),...n.filter((c)=>!i.order.includes(c))].map((c)=>{let h=i.config[c]??{},w=typeof h.icon==="string"&&h.icon?h.icon:void 0,E=Array.isArray(h.requiredEnv)?h.requiredEnv:void 0,_=hd(t,"view",c);return{id:c,status:"compiled",..._?{revision:_}:{},title:h.title||c,...w?{icon:w}:{},...E?{requiredEnv:E}:{}}})}async function mA(t){let{config:n}=await Yc(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 Xc(t){let n=await To(t.path),i=new Set(n.map((a)=>a.id)),o=(await Tt(t)).filter((a)=>!i.has(a.id));return[...n,...o]}async function gA(t){return Response.json({views:await To(t)})}async function _d(t,n,i,o=!1,a){let c=await Yc(i),h=new Set(await wm(i)),w=await x$(i,o,a),E=await Yc(i),_=new Set(await wm(i));pd(i,"view",w);let I=c.order.join("\x00")!==E.order.join("\x00"),T=h.size!==_.size||[...h].some((L)=>!_.has(L))||[..._].some((L)=>!h.has(L)),O=[];if(w.some((L)=>L.status==="built")||I||T)O=await To(i),t({type:"views-list:changed",workspaceId:n,views:O});let N=new Set;for(let L of w)if(L.status==="built"){t({type:"view:changed",workspaceId:n,name:L.name}),await ni({id:n,path:i},L.name,O.find((H)=>H.id===L.name));for(let H of L.serverModules??[])N.add(H)}if(N.size>0)Kc([...N],i);return w}async function yA(t,n,i,o,a){return Jc(i,async()=>{let c=(await To(i)).find((E)=>E.id===o);if(!c)throw new Ei("View not found",404);if(c.title===a)return c;let h=await pA(i,o);if(!h)throw new Ei("View source not found",409);let w;try{w=Gi(h.source,a)}catch(E){throw new Ei(E instanceof Error?E.message:"Could not update the view title",409)}if(w===h.source)return c;await Bun.write(h.path,w);try{let _=(await _d(t,n,i,!0,o)).find((T)=>T.name===o);if(_?.status!=="built")throw new Ei(_?.error??"Could not rebuild the renamed view",422);let I=(await To(i)).find((T)=>T.id===o);if(!I)throw new Ei("Renamed view was not found after rebuilding",422);return I}catch(E){if(await Bun.file(h.path).text().catch(()=>null)===w)await Bun.write(h.path,h.source);throw E}})}async function wA(t,n,i){let{id:o,path:a}=n;await Jc(a,async()=>{if(!(await To(a)).some((h)=>h.id===i))throw new Ei("View not found",404);try{await hA(a,i,()=>Zr(n,i))}catch(h){if(h instanceof xd)throw new Ei(h.message,409);throw h}Kc([`views/${i}`],a),await ni(n,i),t({type:"view:deleted",workspaceId:o,name:i}),t({type:"workspace-config:changed",workspaceId:o}),await _d(t,o,a,!1,i)})}function SA(t,n,i,o,a){return gd("view",t,n,i,o,a)}import{existsSync as _$}from"fs";var Sm={rowSpan:1,colSpan:2},bA=[1,2,3,4];async function Id(t){let{manifestPath:n}=In(t,"widget");try{return JSON.parse(await Bun.file(n).text()).config??{}}catch{return{}}}async function I$(t,n){let{manifestPath:i}=In(t,"widget");await Bun.write(i,JSON.stringify({config:n},null,2))}async function T$(t,n=!1,i){let{names:o,results:a,ms:c}=await yd(t,"widget",n,i),h=await Id(t);for(let I of a)if(I.status==="built")h[I.name]=I.config??Sm;for(let I of Object.keys(h))if(!o.includes(I))delete h[I];let{buildDir:w}=In(t,"widget");if(_$(w))await I$(t,h);let E=a.filter((I)=>I.status==="built").length,_=a.filter((I)=>I.status==="failed");console.log(`[bundle] ${E}/${o.length} widgets built in ${c}ms`+(_.length?`, ${_.length} failed`:"")+(n?" (forced)":""));for(let I of _)console.error(`[bundle] ${I.name}:
|
|
79
|
+
${I.error}`);return a}function bm(t){let{buildDir:n}=In(t,"widget");return md(n)}async function vA(t){let[n,i]=await Promise.all([bm(t),Id(t)]);return n.map((o)=>{let a=i[o]??{},c=bA.includes(a.rowSpan)?a.rowSpan:Sm.rowSpan,h=bA.includes(a.colSpan)?a.colSpan:Sm.colSpan,w=Array.isArray(a.requiredEnv)?a.requiredEnv:void 0,E=hd(t,"widget",o);return{id:o,config:{rowSpan:c,colSpan:h,...w?{requiredEnv:w}:{}},...E?{revision:E}:{}}})}async function EA(t){let n=await Id(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 AA(t){return Response.json({widgets:await vA(t)})}async function xA(t,n,i,o=!1,a){let c=new Set(await bm(i)),h=await Id(i),w=await T$(i,o,a),E=new Set(await bm(i));pd(i,"widget",w);let I=w.some((O)=>{if(O.status!=="built"||!O.config)return!1;let N=h[O.name];return!N||N.rowSpan!==O.config.rowSpan||N.colSpan!==O.config.colSpan})||c.size!==E.size||[...c].some((O)=>!E.has(O))||[...E].some((O)=>!c.has(O)),T=new Set;for(let O of w)if(O.status==="built"){t({type:"widget:changed",workspaceId:n,name:O.name});for(let N of O.serverModules??[])T.add(N)}if(T.size>0)Kc([...T],i);if(I){let O=await vA(i);t({type:"widgets-list:changed",workspaceId:n,widgets:O})}return w}function _A(t,n,i,o,a){return gd("widget",t,n,i,o,a)}async function Zc(t){let[n,i]=await Promise.all([EA(t),mA(t)]),o={};for(let a of[n,i])for(let[c,h]of Object.entries(a))o[c]=[...o[c]??[],...h];return o}class Ha 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 R$(t,n,i,o){await _t(t,i,{tabId:n==="overview"?void 0:n}),await qe(t,i,n,o)}async function IA(t,n,i,o,a){await Ua(t,{...a,workspaceId:t.id,workspacePath:t.path,agentId:t.agentId,sessionId:i,isNew:o,viewBuildId:n.id,content:n.requirements}),await rt(t,n.id,{status:"submitted"},"starting")}async function TA(t,n,i,o){if(o)await rt(t,o.id,{status:"failed",error:n instanceof Error?n.message:"Couldn\u2019t start view chat"},"starting");throw new Ha(n,i?te(t.id,i):void 0,o?.id)}async function RA(t,n,i){let o=ze(n),{view:a,sessionId:c,pinned:h}=await S(t,(w)=>{let E=w.pinnedSessionId,_=E??i.sessionId??crypto.randomUUID(),I=js(w,n,i.requirements,_,!!i.attachments?.length);if(!E)Ps(w,_,o),ti(w,t.id,_,o);return{view:I,sessionId:_,pinned:E}});try{await IA(t,a,c,!h,i)}catch(w){return TA(t,w,c,a)}return{viewId:n,sessionId:te(t.id,c)}}async function PA(t,n,i){if(!i.trim())throw Error("View requirements are required");if(n===void 0){let h=await er(t,{requirements:i.trim(),status:"submitted"});return{viewId:h.id,mode:"in-place",buildInstructions:cd(h.id,ve)}}if(!n)throw Error("Session id cannot be empty");n=te(t.id,n);let o=y(t);if(!(await o.listSessions(t)).some((h)=>h.sessionId===n)&&!o.activeSessions().some((h)=>h.workspaceId===t.id&&h.sessionId===n))throw Error("Source chat not found");let a,c;try{let h=await Kn(t,n);try{a=await o.forkSession?.(t,n,h)}catch(_){if(!(_ instanceof tr))throw _}let w=!a;if(a??=crypto.randomUUID(),!w){await _t(t,a,{fork:{fromSessionId:n}});let _=await o.sessionEvents(t,a).catch(()=>{return});if(_)await _t(t,a,{fork:{fromSessionId:n,...zs(_)}})}let E=await Pe(t,a,h);return c=await er(t,{status:"starting",requirements:i.trim(),buildSessionId:a}),await R$(t,ze(c.id),a),await IA(t,c,a,w,E),{viewId:c.id,mode:"handoff",sessionId:te(t.id,a)}}catch(h){return TA(t,h,a,c)}}async function CA(t){for(let n of await Tt(t))if(n.status==="starting")await rt(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 Td}from"path";function P$(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 C$(t,n){let i=Td(t),o=(await n()).find((a)=>Td(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 OA(t,n,i=we,o=be){if(n==="hermes")return C$(t,o);if(n!=="openclaw")return{};let a=Td(t),c=(await i()).filter((h)=>Td(h.path)===a).sort(P$)[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 vm(t){return typeof t==="string"?t:void 0}async function M$(t,n,i){let o=bd(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 w=await t.text(),E=await rA(a,c,w,i);return new Response(E,{headers:{"Content-Type":"application/json"}})}catch(h){let w=h instanceof Error?h.message:"Unknown error";return fd(i,{source:"rpc",...NE(a)??{},module:a,fn:c,message:w}),new Response(w,{status:500})}}function Em(t,{reserveOperation:n=!0}={}){return RE(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=lr(a);let h=await W(a);if(!h)return i.text("Workspace not found",404);if(h.remote&&u().environment!=="cloud")return i.text("Remote workspaces require Cloud mode",403);if(h.remote&&t==="owner")return i.text("Use the owner workspace address",404);if(t==="owner"&&u().unixSocket)nl(a,i.req.raw);i.set("ws",h),await o()}catch(h){if(h instanceof le)return i.text(h.message,409);throw h}finally{c?.()}})}var it=Em("personal"),ir=Em("owner"),Re=new Ui;Re.patch("/harness",Em("personal",{reserveOperation:!1}),async(t)=>{if(u().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 dn(t.get("ws"),n.harness))}catch(i){if(i instanceof le)return t.text(i.message,409);throw i}});Re.get("/widgets",ir,(t)=>AA(t.get("ws").path));Re.get("/widgets/*",ir,(t)=>{let n=t.get("ws"),{name:i,file:o}=fm(t.req.url,n.id,"widgets");if(!i)return t.text("Not found",404);return _A(i,o,n.path,Ue(n.id),t.req.header("if-none-match"))});Re.get("/views",ir,async(t)=>t.req.query("includePending")==="true"?t.json({views:await Xc(t.get("ws"))}):gA(t.get("ws").path));var MA="Use the owner workspace address for compiled views";Re.patch("/views/:viewId",it,async(t)=>{let n=t.get("ws"),i=await t.req.json().catch(()=>null);if(await Qt(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 Qr(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 V)return t.text(a.message,a.status);throw a}if(n.remote)return t.text(MA,404);let o=typeof i?.title==="string"?i.title.trim():"";if(!o)return t.text("Expected { title: string }",400);try{return t.json(await yA(m,n.id,n.path,t.req.param("viewId"),o))}catch(a){if(a instanceof Ei||a instanceof V)return t.text(a.message,a.status);throw a}});Re.delete("/views/:viewId",it,async(t)=>{let n=t.get("ws");try{let i=t.req.param("viewId");if(await Qt(n,i)){let o=new Set(y(n).activeSessions().filter((a)=>a.workspaceId===n.id).map((a)=>a.sessionId));await Us(n,i,o)}else if(n.remote)return t.text(MA,404);else await wA(m,n,i);return t.body(null,204)}catch(i){if(i instanceof Ei||i instanceof V)return t.text(i.message,i.status);throw i}});Re.get("/views/*",ir,(t)=>{let n=t.get("ws"),{name:i,file:o}=fm(t.req.url,n.id,"views");if(!i)return t.text("Not found",404);return SA(i,o,n.path,Ue(n.id),t.req.header("if-none-match"))});Re.post("/views",it,async(t)=>{let n=t.get("ws");return t.json(await er(n),201)});Re.post("/views/:viewId/submit",it,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(!Rr(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(!zn(n.id,c.uploadId))return t.text("Attachment not found or expired",400)}let a=await Pd(n.harness??"claude-code");if(a.status!=="available")return t.text(a.reason,400);try{let c=await RA(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:Fe(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 V)return t.text(c.message,c.status);if(c instanceof Ha)return t.json({error:c.message,viewId:c.viewId,sessionId:c.sessionId},500);throw c}});Re.get("/files/*",ir,(t)=>{let n=t.get("ws"),i=new URL(t.req.url).pathname.split(`${Ue(n.id)}/files/`)[1]??"";return zE(n.path,i,t.req.header("range"),t.req.header("if-none-match"))});Re.post("/rpc/*",ir,(t)=>{let n=t.get("ws"),i=new URL(t.req.url).pathname.split(`${Ue(n.id)}/rpc/`)[1]??"";return M$(t.req.raw,i,n.path)});Re.post("/applet-log",ir,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 h=(a.kind==="widget"||a.kind==="view")&&typeof a.name==="string"&&/^[a-zA-Z0-9_-]+$/.test(a.name);if(!h&&a.source!=="runtime")continue;if(typeof a.message!=="string"||!a.message)continue;fd(t.get("ws").path,{source:a.source,...h?{kind:a.kind,name:a.name}:{},message:a.message,...typeof a.stack==="string"?{stack:a.stack}:{}})}return t.body(null,204)});Re.get("/preview/*",it,(t)=>{let n=t.get("ws"),i=new URL(t.req.url).pathname.split(`${Ue(n.id)}/preview/`)[1]??"";return lA(n.path,i,t.req.header("if-none-match"))});Re.post("/uploads",it,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>et)return t.text(`Files can be up to ${et/1048576} MB`,413);try{let h=Buffer.from(await c.arrayBuffer());a.push(await Un({workspaceId:n.id,filename:c.name||"file",mediaType:c.type||"application/octet-stream",bytes:h}))}catch{return t.text(`Couldn\u2019t process "${c.name}"`,400)}}return t.json(a)});Re.post("/uploads/from-path",it,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 ys(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)}});Re.get("/uploads/:uploadId",it,(t)=>{let n=zn(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"}})});Re.get("/state",it,async(t)=>t.json(await Ae(t.get("ws"))));Re.put("/state/tabs",it,async(t)=>{let n=await t.req.json().catch(()=>null),i=t.get("ws");return await S(i,(o)=>{o.openTabs=Ar(n?.openTabs)}),t.json(await Ae(i))});Re.get("/sessions",it,async(t)=>{let n=t.get("ws");return t.json(await y(n).listSessions(n))});Re.put("/sessions/:sessionId/pin",it,async(t)=>{let n=t.get("ws"),i=t.req.param("sessionId"),o=y(n),a=(await o.listSessions(n)).some((h)=>h.sessionId===i),c=o.activeSessions().some((h)=>h.workspaceId===n.id&&h.sessionId===i);if(!a&&!c)return t.text("Chat not found",404);return await Ms(n,i),t.json(await Ae(n))});Re.delete("/sessions/:sessionId/pin",it,async(t)=>{let n=t.get("ws");return await Fs(n,t.req.param("sessionId")),t.json(await Ae(n))});Re.put("/sessions/:sessionId/selection",it,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(!ie(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 Yr(n))return t.text("Unpin chat before switching",409);return await qe(n,t.req.param("sessionId"),o.tabId,a?o.ifMatch:void 0),t.json(await Ae(n))});Re.delete("/sessions/:sessionId/selection",it,async(t)=>{let n=t.get("ws"),o=(await t.req.json().catch(()=>null))?.tabId;if(!ie(o))return t.text("Invalid chat tab",400);return await Bs(n,t.req.param("sessionId"),o),t.json(await Ae(n))});Re.on("PATCH",["/sessions/:sessionId/config","/state/chat-defaults"],it,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 h=o[c];if(h!==null&&typeof h!=="string")return t.text(`${c} must be a string or null`,400);i[c]=h}if("speedMode"in o){let c=o.speedMode;if(c!==null&&!Fe(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))});Re.post("/sessions/:sessionId/archive",it,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 ri(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)}});Re.get("/sessions/:sessionId/events",it,async(t)=>{let n=t.get("ws"),i=t.req.param("sessionId");return t.json(await y(n).sessionEvents(n,i))});Re.get("/mcp",it,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 h=(w)=>{if(!o)c.enqueue(a.encode(JSON.stringify(w)+`
|
|
80
|
+
`))};try{let w=await i.mcpStatus?.(n,(E)=>h({connectors:E}))??[];h({connectors:w,done:!0})}catch{h({error:"Could not load connectors"})}finally{if(!o)c.close()}},cancel(){o=!0}}),{headers:{"Content-Type":"application/x-ndjson","Cache-Control":"no-store"}})});Re.get("/harness/debug",it,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:gs(i.wireScope?.(n)??n.id,o),broadcasts:_s(n.id,a)})});Re.get("/env",it,async(t)=>{let n=t.get("ws");return t.json(await Gt(n.path,Zc(n.path)))});Re.put("/env",it,async(t)=>{let n=t.get("ws"),i=Or(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 kr(n.path,i),Ed(n);return t.json(await Gt(n.path,Zc(n.path)))});Re.get("/skills",it,async(t)=>{let n=t.get("ws");return t.json(await kt(n.path,n.harness))});Re.post("/skills/update",it,async(t)=>{let n=t.get("ws"),i=await Rt(n.path,n.harness??"claude-code");return t.json(i.status)});Re.get("/harness",it,async(t)=>{let n=t.get("ws"),i=y(n),o={harness:i.id,supportsStreaming:i.capabilities.supportsStreaming,supportsArchiving:Boolean(i.archiveSession)};if(!O$(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])=>I!==process.env[_]&&(a.test(_)||/^(HOME|USERPROFILE|XDG_CONFIG_HOME)$/.test(_))),h=t.req.query("refresh")==="true";if(h)await Ge({refresh:!0});let[w,E]=await Promise.all([i.authStatus&&!c?Promise.resolve({status:"available"}):j.getAvailability(n,h),i.listModels(n).catch((_)=>(console.error(`[api] listModels failed for ${i.id}`,_),[]))]);return t.json({...o,availability:w,hasAuthOverrides:Boolean(c),models:E})});Re.get("/config",ir,async(t)=>t.json(await Vc(t.get("ws").path)));Re.put("/config",ir,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&&(!Pr(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 no(n.path,{name:a,icon:c}),m({type:"workspace-config:changed",workspaceId:n.id,origin:vm(o.origin)}),t.json(await Vc(n.path))});Re.post("/scratchpad/ops",ir,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 Su(a.path,a.id,i,o))}catch(n){return t.text(n instanceof Error?n.message:"Scratchpad edit failed",400)}});Re.get("/scratchpad",ir,async(t)=>t.json(await ct(t.get("ws").path)));Re.put("/scratchpad",ir,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 ur(i.document,n.path),m({type:"scratchpad:changed",workspaceId:n.id,origin:vm(i.origin)}),t.body(null,204)});Re.post("/scratchpad/assets",ir,async(t)=>{if(Number(t.req.header("content-length")??0)>At)return t.text(`Asset too large (max ${At/1048576} MB)`,413);let i=new Uint8Array(await t.req.arrayBuffer());if(i.length===0)return t.text("Empty body",400);if(i.length>At)return t.text(`Asset too large (max ${At/1048576} MB)`,413);let o=t.req.header("content-type")??"application/octet-stream";return t.json(await Pt(t.get("ws").path,i,o))});Re.get("/scratchpad/assets/:file",ir,async(t)=>{let n=cr(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"}})});Re.put("/icon",ir,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 Ad(i)}catch(c){let h=c instanceof Error?c.message:String(c);return t.text(`Invalid image: ${h}`,400)}let a={type:"upload",value:o};return await no(n.path,{icon:a}),m({type:"workspace-config:changed",workspaceId:t.get("ws").id}),t.json({icon:a})});Re.delete("/icon",ir,async(t)=>(await no(t.get("ws").path,{icon:null}),m({type:"workspace-config:changed",workspaceId:t.get("ws").id}),t.body(null,204)));Re.get("/",it,async(t)=>{let n=t.get("ws"),i=await A(n.path);if(i.remote)return t.json({version:2,remote:i.remote,apiBase:Ue(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:Ue(n.id),isRemote:!1,name:o.name||kA(n.path),cwd:n.path,harness:n.harness,agentId:n.agentId})});Re.get("/applet-thumbnails",ir,async(t)=>t.json({thumbnails:await ss(t.get("ws").path)}));Re.get("/applet-thumbnails/:kind/:name",ir,(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 ls(t.get("ws").path,n,i,t.req.header("if-none-match"),o!==void 0)});Re.put("/applet-thumbnails",ir,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"&&Ir(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 as(t.get("ws").path,i.kind,i.thumbnails),t.body(null,204)});function Rd(t){return ln((n)=>typeof n==="string"&&Object.hasOwn(t,n))}var N$=$s({theme:$s({font:Rd(ue),color:Rd(pe),radius:Rd(Te),agent:Rd(Ee)}).optional(),widgetGrid:p(s({i:r().min(1),x:sn().nonnegative(),y:sn().nonnegative()})).optional(),origin:r().optional()}).refine((t)=>t.theme!==void 0||t.widgetGrid!==void 0);Re.put("/",it,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=N$.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 Ke(n.path,(h)=>cs(h,a));if(c)m({type:"workspace-config:changed",workspaceId:n.id,origin:o});return t.body(null,204)});Re.delete("/",it,async(t)=>{let n=t.get("ws");if(n.remote){try{await zm(n.id,n.remote)}catch(o){return t.text(o instanceof Error?o.message:"Could not leave workspace",503)}return t.body(null,204)}if(u().environment==="cloud"){if((await Bd(n.id,!0)).status!=="updated")return t.text("Workspace not found",404);return t.body(null,204)}if(!await ai(n.id))return t.text("Workspace not found",404);return await ll(n),t.body(null,204)});var Qi=new Ui;function NA(t){return u().environment==="cloud"?t:t.filter((n)=>!n.remote)}async function Qc(t){return Promise.all(t.map(async(n)=>{let i=await A(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}}))}Qi.get("/",async(t)=>{let n=await k();return t.json(await Qc(NA(n)))});Qi.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=new Set(n.ids),o=(await k()).filter((c)=>!i.has(c.id)).map((c)=>c.id),a=await oi([...n.ids,...o]);return m({type:"workspaces-list:changed",origin:vm(n.origin)}),t.json(await Qc(NA(a)))}catch(i){let o=i instanceof Error?i.message:String(i);return t.text(o,400)}});var DA="Workspace creation is not available in the Moi demo";Qi.post("/",async(t)=>{if(u().demo)return t.text(DA,403);let n=await t.req.json().catch(()=>null);if(n&&typeof n==="object"&&"remote"in n){if(u().environment!=="cloud")return t.text("Remote workspaces require Cloud mode",403);if(Object.keys(n).some((I)=>I!=="remote"&&I!=="harness"))return t.text("Remote registration expects only remote and harness",400);let E;try{E=B(n.remote)}catch(I){return t.text(I instanceof Error?I.message:"Invalid remote workspace",400)}let _=n.harness;if(_!==void 0){if(_!=="claude-code"&&_!=="codex")return t.text("Unknown workspace type",400);let I=await Pd(_);if(I.status!=="available")return t.text(I.reason,400)}try{let I=await Hd(E,_);return I?t.json(I,201):t.text("Workspace is not shared with this account",404)}catch(I){return t.text(I instanceof Error?I.message:"Could not open shared workspace",503)}}if(!n?.path)return t.text("Missing path",400);let i=n?.harness??"claude-code";if(!rr(i))return t.text("Unknown workspace type",400);let o=i,a=await Pd(o);if(a.status!=="available")return t.text(a.reason,400);let c=k$(String(n.path)),h;try{h=await OA(c,o)}catch(E){let _=E instanceof Error?E.message:String(E);return t.text(_,400)}try{await J(c,o)}catch(E){let _=E instanceof Error?E.message:String(E);return t.text(`Could not initialize workspace: ${_}`,500)}let w=await K(c,{harness:o,...h});return t.json((await Qc([w]))[0],201)});Qi.get("/suggestions",async(t)=>t.json(await li()));Qi.get("/trash",async(t)=>{if(u().environment!=="cloud")return t.json([]);return t.json(await Qc(await ci()))});Qi.post("/trash/:id/restore",async(t)=>{if(u().environment!=="cloud")return t.text("Workspace not found",404);let n=await Bd(t.req.param("id"),!1);if(n.status!=="updated")return n.status==="missing"?t.text("Workspace not found",404):t.text("This workspace can no longer be restored",410);return t.json((await Qc([n.entry]))[0])});Qi.get("/previews",async(t)=>{let n=await k(),i=await Promise.all(n.map(async(o)=>{if(o.remote)return[o.id,{thumbnails:[]}];let a=await To(o.path).catch(()=>[]),c=await us(o.path,{getHarnessPreview:(h)=>y(o).workspacePreview(o,h),viewIds:a.map((h)=>h.id),thumbnailUrl:(h,w,E)=>`/api/workspaces/${o.id}/applet-thumbnails/${h}/${w}:${Date.parse(E).toString(36)}`});return[o.id,c]}));return t.json(Object.fromEntries(i))});var D$=new Set(["claude-code","codex"]);async function Pd(t){return await y(t).availability?.()??{status:"available"}}Qi.post("/create",async(t)=>{if(u().demo)return t.text(DA,403);let n=await t.req.json(),i=n?.harness??"claude-code";if(!rr(i))return t.text("Unknown workspace type",400);let o=i;if(!D$.has(o))return t.text("Add this type of workspace from Suggestions",400);let a=await Pd(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():"",h=zi(c);if(h)return t.text(h,400);let w=await yr(c,Ce());try{await J(w,o)}catch(_){let I=_ instanceof Error?_.message:String(_);return t.text(`Could not create workspace: ${I}`,500)}await no(w,{name:c});let E=await K(w,{id:kA(w),harness:o,name:c});return m({type:"workspaces-list:changed"}),t.json(E,201)});Qi.route("/:id",Re);var Tn=new Ui;Tn.route("/api/workspaces",Qi);Tn.route("/api/harnesses",Xo);Tn.route("/api/onboarding",Fa);Tn.get("/api/config",(t)=>t.json(Hs()));Tn.get("/api/proxy-user",async(t)=>(t.header("Cache-Control","private, no-store"),t.json(await dd(t.req.raw))));Tn.get("/api/update",async(t)=>(t.header("Cache-Control","no-store"),t.json(await Mi())));Tn.post("/api/update",async(t)=>{if(Fi())return t.text(ji()?"An update is installed \u2014 Moi is restarting.":"An update is already in progress.",409);if(Li(ae().flatMap((i)=>i.activeSessions())))return t.text(PE,409);try{let i=await Bi();if(!i)return t.text("This Moi cannot be updated from the app",409);let o=t.json(i);return Wi(),o}catch(i){return t.text(i instanceof Error?i.message:"Could not update moi.",500)}});Tn.get("/api/settings",(t)=>t.json(ad()));Tn.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=uE(cE(n))}catch(o){return t.text(o instanceof Error?o.message:"Invalid settings patch",400)}return m({type:"app-settings:changed",settings:i}),t.json(i)});if(qa)Tn.get("*",im({root:gm,onFound:(t,n)=>{n.header("Cache-Control",t.endsWith("index.html")?"no-cache":"public, max-age=31536000, immutable")}}));Tn.notFound((t)=>t.text("Not found",404));import{resolve as qA}from"path";function $$(t=5000){let n=new Map,i=new Map,o=0;function a(E,_){let I=i.get(E);if(!I)return;if(clearTimeout(I.timer),i.delete(E),_)I.reject(Error(_));else I.resolve()}function c(E){n.delete(E);for(let[_,I]of i)if(I.client===E)a(_,"The browser disconnected before acknowledging navigation.")}function h(E,_){if(!Q(_))return;if(_.type==="navigation:presence"&&(typeof _.workspaceId==="string"||_.workspaceId===null)&&typeof _.focused==="boolean"){let I=n.get(E),T=_.workspaceId;n.set(E,{workspaceId:T,focusOrder:_.focused?++o:I?.workspaceId===T?I.focusOrder:0});for(let[O,N]of i)if(N.client===E&&N.workspaceId!==T)a(O,"The browser switched workspaces before acknowledging navigation.")}else if(_.type==="navigation:result"&&typeof _.requestId==="string"){let I=i.get(_.requestId);if(!I||I.client!==E)return;if(typeof _.error==="string")a(_.requestId,_.error);else if(_.ok===!0)a(_.requestId)}}function w(E,_){let I=[...n].filter(([,N])=>N.workspaceId===E);if(I.sort((N,L)=>L[1].focusOrder-N[1].focusOrder),!I.length)return Promise.reject(Error("No browser is showing this workspace. Open it in Moi and try again."));if(I.length>1&&I[0][1].focusOrder===0)return Promise.reject(Error("Several browsers show this workspace. Focus the one to navigate, then try again."));let T=I[0][0],O=crypto.randomUUID();return new Promise((N,L)=>{let H=setTimeout(()=>a(O,"Navigation acknowledgement timed out. Check the browser before retrying."),t);i.set(O,{client:T,workspaceId:E,resolve:N,reject:L,timer:H});let Z={type:"navigation:request",requestId:O,workspaceId:E,href:_};try{T.send(JSON.stringify(Z))}catch{a(O,"Could not send navigation to the browser.")}})}return{receive:h,remove:c,navigate:w}}var Va=$$();var Cd=new Map,L$=1e4;function $A(t,n){let i=crypto.randomUUID();return new Promise((o,a)=>{let c=setTimeout(()=>{Cd.delete(i),a(Error("No live canvas \u2014 open the Scratchpad tab for this workspace."))},L$);Cd.set(i,{resolve:o,reject:a,timer:c}),m({type:"scratchpad:op",workspaceId:t,opId:i,op:n})})}function LA(t,n,i){let o=Cd.get(t);if(!o)return;if(Cd.delete(t),clearTimeout(o.timer),i)o.reject(Error(i));else o.resolve(n??{ok:!0})}function jA(t,n){if(n.font&&!(n.font in ue))return{ok:!1,error:`Unknown font theme: ${n.font}`};if(n.color&&!(n.color in pe))return{ok:!1,error:`Unknown color theme: ${n.color}`};if(n.radius&&!(n.radius in Te))return{ok:!1,error:`Unknown radius theme: ${n.radius}`};if(n.agent&&!(n.agent in Ee))return{ok:!1,error:`Unknown agent theme: ${n.agent}`};let{font:i,color:o,radius:a,agent:c}=n;return{ok:!0,theme:Ze({...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 UA=(t,n)=>Response.json({error:t instanceof Error?t.message:"Cloud request failed",signIn:t instanceof ee},{status:n,headers:{[Xn]:"1"}});function FA(t=Zn(x),n=k){return async function(o){let a=new URL(o.url);if(a.pathname!=="/remote/info"&&a.pathname!=="/remote/request")return;if(o.headers.get(Yn)!=="1"||o.headers.has("origin"))return UA(Error("Only the moi CLI can use this"),403);try{if(a.pathname==="/remote/info"){let T=await t.loginInfo();return Response.json(T,{headers:{[Yt]:T.login??"none"}})}let c=a.searchParams.get("path")??"",{workspace:h,access:w}=Xr(o.method,c);if(w==="own login")throw Error("This request needs your own Cloud login");if(h&&!(await n()).some((T)=>T.remote?.user_id===h.user_id&&T.remote.workspace_id===h.workspace_id))throw Error("This workspace is not linked on this machine");let{response:E,agent:_}=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}),I=E.headers.get("content-type");return new Response(E.body,{status:E.status,headers:{[Yt]:_?"agent":"human",...I?{"content-type":I}:{}}})}catch(c){return UA(c,502)}}}var j$=FA();async function nn(t,n){let i=await k();if(i.length===0)return t.send(JSON.stringify({error:"No workspaces registered"})),null;let o=qA(String(n??i[0].path)),a=Be(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 BA=Bun.serve({port:z,hostname:fe,async fetch(t,n){if(new URL(t.url).pathname.startsWith("/remote/"))n.timeout(t,0);let i=await j$(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=qA(String(i.path)),a=await K(o);m({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 k();t.send(JSON.stringify({workspaces:o}));return}if(i.type==="server:info"){t.send(JSON.stringify({version:C,pid:process.pid,port:D,unixSocket:u().unixSocket??void 0,service:!!process.env.MOI_SERVICE}));return}if(i.type==="bundle"){let o=await nn(t,i.path);if(!o)return;let a=o.path,c=!!i.force,h=typeof i.only==="string"?ot(i.only):void 0;if(i.only&&!h){t.send(JSON.stringify({error:`Invalid applet selector "${i.only}"`}));return}let w=[];if(await Jc(a,async()=>{if(h?.segment!=="views"){for(let E of await xA(m,o.id,a,c,h?.id))if(!h?.id||E.name===h.id)w.push({kind:"widget",name:E.name,status:E.status,error:E.error})}if(h?.segment!=="widgets"){for(let E of await _d(m,o.id,a,c,h?.id))if(!h?.id||E.name===h.id)w.push({kind:"view",name:E.name,status:E.status,error:E.error})}}),h?.id&&w.length===0){t.send(JSON.stringify({error:`Applet "${h.segment}/${h.id}" not found`}));return}t.send(JSON.stringify({ok:!0,workspacePath:a,results:w,logCount:cm(a)}));return}if(i.type==="debug:logs"){let o=await nn(t,i.path);if(!o)return;if(i.clear===!0){t.send(JSON.stringify({ok:!0,cleared:ME(o.path)}));return}t.send(JSON.stringify({ok:!0,entries:kE(o.path)}));return}if(i.type==="call-server-fn"){let o=await nn(t,i.path);if(!o)return;let a=bd(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(w){t.send(JSON.stringify({error:`Arguments must be valid JSON: ${w instanceof Error?w.message:String(w)}`}));return}if(!Array.isArray(c)){t.send(JSON.stringify({error:`Arguments must be a JSON array, e.g. '["ann", 10]'`}));return}let h=performance.now();try{let w=await nA(a.module,a.name,Lt(c),o.path);t.send(JSON.stringify({ok:!0,result:w,ms:Math.round(performance.now()-h)}))}catch(w){t.send(JSON.stringify({error:w instanceof Error?w.message:String(w),ms:Math.round(performance.now()-h)}))}return}if(i.type==="view:create"){let o=await nn(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 PA(o,i.fromSessionId,i.requirements),c;try{await Va.navigate(o.id,`moi:/views/${a.viewId}`)}catch(h){c=`View was created, but could not open it: ${h instanceof Error?h.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 Ha?{sessionId:a.sessionId,viewId:a.viewId}:{}}))}return}if(i.type==="view:set"){let o=await nn(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,h=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(h&&!/^[a-z0-9][a-z0-9-]*$/.test(h)){t.send(JSON.stringify({error:"Icon must start with a lowercase letter or number and use a-z, 0-9, or -"}));return}try{let w=await Qr(o,a,{title:c,icon:h});t.send(JSON.stringify({ok:!0,viewId:w.id}))}catch(w){t.send(JSON.stringify({error:w instanceof V?w.message:"Couldn\u2019t update view"}))}return}if(i.type==="tabs"){let o=await nn(t,i.path);if(!o)return;let a=await Xc(o);t.send(JSON.stringify({ok:!0,tabs:lt(a)}));return}if(i.type==="navigate"){let o=await nn(t,i.path);if(!o)return;try{let a=Dt(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(ie(c)&&!o.remote)Pi(c,await Xc(o));await Va.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 nn(t,i.path);if(!o)return;await Ws(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 nn(t,i.path);if(!o)return;let a=typeof i.only==="string"?ot(i.only):void 0;if(i.only!==void 0&&!a){t.send(JSON.stringify({error:`Invalid applet selector "${i.only}"`}));return}m({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 nn(t,i.path);if(!o)return;let a=await Gt(o.path,Zc(o.path));t.send(JSON.stringify({view:a}));return}if(i.type==="env:update"){let o=await nn(t,i.path);if(!o)return;let a=Or(i.patch);if(typeof a==="string"){t.send(JSON.stringify({error:a}));return}await kr(o.path,a),Ed(o),t.send(JSON.stringify({ok:!0,backend:await fs()}));return}if(i.type==="env:resolve"){let o=await nn(t,i.path);if(!o)return;t.send(JSON.stringify({env:await X(o.path)}));return}if(i.type==="theme"){let o=await nn(t,i.path);if(!o)return;let a=o.path;if(!i.font&&!i.color&&!i.radius&&!i.agent){let h=Ze((await Ut(a)).theme);t.send(JSON.stringify({currentFont:h.font,currentColor:h.color,currentRadius:h.radius,currentAgent:h.agent}));return}let c=jA(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 Ke(a,(h)=>({...h,theme:Ze({...h.theme,...c.applied})})),m({type:"workspace-config:changed",workspaceId:o.id}),t.send(JSON.stringify({ok:!0,...c.applied}));return}if(i.type==="config"){let o=await nn(t,i.path);if(!o)return;let a=o.path,c=typeof i.name==="string",h=typeof i.iconPath==="string",w=i.clearName===!0,E=i.clearIcon===!0;if(!c&&!h&&!w&&!E){let I=await Vc(a);t.send(JSON.stringify({name:I.name??null,hasIcon:!!I.icon,path:a}));return}let _={};if(w)_.name=null;else if(c)_.name=String(i.name);if(E)_.icon=null;else if(h)try{_.icon={type:"upload",value:await Ad(String(i.iconPath))}}catch(I){let T=I instanceof Error?I.message:String(I);t.send(JSON.stringify({error:`Could not read image: ${T}`}));return}await no(a,_),m({type:"workspace-config:changed",workspaceId:o.id}),t.send(JSON.stringify({ok:!0,name:_.name??null,icon:h,clearedName:w,clearedIcon:E}));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 nn(t,i.path);if(!a)return;if(o.kind==="read"){t.send(JSON.stringify({shapes:await wt(a.path)}));return}if(o.kind==="read-image"){t.send(JSON.stringify(await It(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 $A(a.id,o):await Su(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 U$=Date.now();function el(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 F$(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 q$(t){return`${(t/1048576).toFixed(1)}mb`}function B$(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=${tn(t.workspacePath)}`,`pid=${t.pid??"?"}`,o,`pending=${t.pending}`,`age=${el(n-t.spawnedAt)}`,`lastCall=${t.lastCallAt===null?"never":F$(t.lastCallAt,n)}`,`reap=${t.ttlRemainingMs>0?"in "+el(t.ttlRemainingMs):"imminent"}`];if(t.rssBytes!==null)c.push(`rss=${q$(t.rssBytes)}`);let h=" "+c.join(" ");return h+=`
|
|
81
|
+
modules: ${t.modules.length>0?t.modules.join(", "):"(none loaded)"}`,h}function WA(){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 ${el(t-U$)}`);let{unixSocket:i}=u();n.push(i?`web socket ${i}`:`http port ${D}`),n.push(`control port ${z}`),n.push(`debug logging ${$t?"on (--debug)":"off"}`),n.push(`connected tabs ${Lr()}`),n.push("");for(let a of ae()){let c=a.statusLines?.(t);if(!c?.length)continue;n.push(...c),n.push("")}let o=oA();if(n.push(`function workers ${o.length}/${vd.maxWorkers} (one per workspace, idle TTL ${el(vd.idleTtlMs)}, call timeout ${el(vd.callTimeoutMs)})`),o.length===0)n.push(" (none running \u2014 spawned lazily on the first server-function call)");else{let a=[...o].sort((c,h)=>h.pending-c.pending||(h.lastCallAt??0)-(c.lastCallAt??0));for(let c of a)n.push(B$(c,t))}return n.push(""),n.join(`
|
|
82
|
+
`)+`
|
|
83
|
+
`}import{join as HA}from"path";var W$=v("client","vendor","react"),H$=v("client","vendor","emojibase"),V$=/^\d[\w.-]*\/(development|production)\/(_impl\/)?[a-zA-Z0-9_-]+\.js$/;async function VA(t){let n=new URL(t.url).pathname.replace(/^\/vendor\/react\//,"");if(!V$.test(n)||n.includes(".."))return new Response("Not found",{status:404});let i=Bun.file(HA(W$,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 z$=/^[a-z-]+\/[a-z]+\.json$/;async function zA(t){let n=new URL(t.url).pathname.replace(/^\/vendor\/emojibase\//,"");if(!z$.test(n)||n.includes(".."))return new Response("Not found",{status:404});let i=Bun.file(HA(H$,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 Y$(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||Fe(n.speedMode))&&(n.stream===void 0||typeof n.stream==="boolean")&&(n.context===void 0||hs(n.context))&&(n.attachments===void 0||Rr(n.attachments));if(n.type==="stop")return typeof n.workspaceId==="string"&&typeof n.sessionId==="string";return!1}var ea=qa?cA:al;function KA(){return{type:"sessions:status-snapshot",sessions:ae().flatMap((t)=>t.activeSessions())}}function Am(t,n,i){return t.upgrade(n,{data:i})?new Response(null,{status:101}):new Response("Upgrade failed",{status:500})}var JA=await k();await As(JA);await Promise.all(JA.map(CA));var{unixSocket:za}=u();if(za)await G$(za,{force:!0});var X$=za?{unix:za}:{port:D,hostname:process.env.HOST??"127.0.0.1"},Z$=za?await Um(J$(K$(za),"ops.sock")):void 0,YA=Bun.serve({...X$,idleTimeout:60,development:qa?!1:{hmr:!0},routes:{"/status":()=>new Response(WA(),{headers:{"Content-Type":"text/plain; charset=utf-8","Cache-Control":"no-store"}}),"/vendor/react/*":(t)=>VA(t),"/vendor/emojibase/*":(t)=>zA(t),"/":ea,...u().demo?{"/demo":ea}:{},"/dev":ea,"/dev/*":ea,"/dev/workspace-setup/preview":qa?new Response("Not found",{status:404}):al,"/workspace/*":ea,"/settings":ea,"/onboarding":ea,"/api/harness/events":(t,n)=>Am(n,t,{channel:"chat",workspaceId:""}),"/api/events":(t,n)=>Am(n,t,{channel:"events",workspaceId:""}),"/api/workspaces/:id/events":async(t,n)=>{let i=decodeURIComponent(new URL(t.url).pathname.split("/")[3]??""),o=await W(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 dd(t);if(a&&!c)return new Response("Sign in through Cloudflare Access to join",{status:401});return Am(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 Tn.fetch(t)},websocket:{open(t){if(t.data.channel==="workspace")t.subscribe(Ht(t.data.workspaceId));else if(t.data.channel==="chat")t.subscribe(Mr),bs(t),Ts(t,KA());else t.subscribe(qt)},async message(t,n){if(t.data.channel==="workspace"){if(!t.data.presence&&String(n)==='{"type":"ping"}')t.send('{"type":"pong"}');else if(u().environment==="cloud"&&t.data.workspacePath){if(!t.data.presence)Ro.open(t,t.data.workspacePath,{workspaceId:t.data.workspaceId,verifiedProfile:t.data.verifiedProfile});t.data.presence=!0,Ro.message(t,n)}return}if(t.data.channel==="events"){try{let i=JSON.parse(String(n));if(i?.type==="remote-workspaces:updated")ul();else if(i?.type==="scratchpad:op-result"&&typeof i.opId==="string")LA(i.opId,i.result,i.error);else Va.receive(t,i)}catch{}return}try{let i=JSON.parse(String(n));if(!Y$(i))return;if(i.type==="chat"&&(i.content?.trim()||i.attachments?.length)){let o=await W(i.workspaceId);if(!o)return;Ua(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 W(i.workspaceId);y(o??void 0).interrupt(i.workspaceId,i.sessionId).catch(()=>{})}}catch{}},close(t){if(t.data.channel==="workspace")Ro.close(t),t.unsubscribe(Ht(t.data.workspaceId));else if(t.data.channel==="chat")vs(t),t.unsubscribe(Mr);else Va.remove(t),t.unsubscribe(qt)}}});Es(YA);var Q$=30000;setInterval(()=>{if(Lr()>0)Ss(KA())},Q$);Ii();Hm();Gm();ki();var GA=!1;async function XA(){if(GA)return;GA=!0;try{YA.stop(!0),Z$?.stop(!0),jm()}catch{}try{BA.stop(!0)}catch{}j.shutdown();for(let t of ae())t.shutdown?.();iA(),$i(),await Ro.shutdown(),process.exit()}process.on("SIGTERM",XA);process.on("SIGINT",XA);
|