tempest.games 0.1.17 → 0.1.19
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/bin/backend.bun.js
CHANGED
|
@@ -34,7 +34,7 @@ var P4=Object.create;var{getPrototypeOf:r4,defineProperty:fl,getOwnPropertyNames
|
|
|
34
34
|
* vary
|
|
35
35
|
* Copyright(c) 2014-2017 Douglas Christopher Wilson
|
|
36
36
|
* MIT Licensed
|
|
37
|
-
*/cv.exports=u3;cv.exports.append=oF;var V3=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;function oF(n,i){if(typeof n!=="string")throw new TypeError("header argument is required");if(!i)throw new TypeError("field argument is required");var o=!Array.isArray(i)?iF(String(i)):i;for(var c=0;c<o.length;c++)if(!V3.test(o[c]))throw new TypeError("field argument contains an invalid header name");if(n==="*")return n;var p=n,a=iF(n.toLowerCase());if(o.indexOf("*")!==-1||a.indexOf("*")!==-1)return"*";for(var x=0;x<o.length;x++){var m=o[x].toLowerCase();if(a.indexOf(m)===-1)a.push(m),p=p?p+", "+o[x]:o[x]}return p}function iF(n){var i=0,o=[],c=0;for(var p=0,a=n.length;p<a;p++)switch(n.charCodeAt(p)){case 32:if(c===i)c=i=p+1;break;case 44:o.push(n.substring(c,i)),c=i=p+1;break;default:i=p+1;break}return o.push(n.substring(c,i)),o}function u3(n,i){if(!n||!n.getHeader||!n.setHeader)throw new TypeError("res argument is required");var o=n.getHeader("Vary")||"",c=Array.isArray(o)?o.join(", "):String(o);if(o=oF(c,i))n.setHeader("Vary",o)}});var pv=h((KL,pF)=>{(function(){var n=nF(),i=cF(),o={origin:"*",methods:"GET,HEAD,PUT,PATCH,POST,DELETE",preflightContinue:!1,optionsSuccessStatus:204};function c(M){return typeof M==="string"||M instanceof String}function p(M,A){if(Array.isArray(A)){for(var R=0;R<A.length;++R)if(p(M,A[R]))return!0;return!1}else if(c(A))return M===A;else if(A instanceof RegExp)return A.test(M);else return!!A}function a(M,A){var R=A.headers.origin,G=[],Q;if(!M.origin||M.origin==="*")G.push([{key:"Access-Control-Allow-Origin",value:"*"}]);else if(c(M.origin))G.push([{key:"Access-Control-Allow-Origin",value:M.origin}]),G.push([{key:"Vary",value:"Origin"}]);else Q=p(R,M.origin),G.push([{key:"Access-Control-Allow-Origin",value:Q?R:!1}]),G.push([{key:"Vary",value:"Origin"}]);return G}function x(M){var A=M.methods;if(A.join)A=M.methods.join(",");return{key:"Access-Control-Allow-Methods",value:A}}function m(M){if(M.credentials===!0)return{key:"Access-Control-Allow-Credentials",value:"true"};return null}function l(M,A){var R=M.allowedHeaders||M.headers,G=[];if(!R)R=A.headers["access-control-request-headers"],G.push([{key:"Vary",value:"Access-Control-Request-Headers"}]);else if(R.join)R=R.join(",");if(R&&R.length)G.push([{key:"Access-Control-Allow-Headers",value:R}]);return G}function f(M){var A=M.exposedHeaders;if(!A)return null;else if(A.join)A=A.join(",");if(A&&A.length)return{key:"Access-Control-Expose-Headers",value:A};return null}function v(M){var A=(typeof M.maxAge==="number"||M.maxAge)&&M.maxAge.toString();if(A&&A.length)return{key:"Access-Control-Max-Age",value:A};return null}function $(M,A){for(var R=0,G=M.length;R<G;R++){var Q=M[R];if(Q){if(Array.isArray(Q))$(Q,A);else if(Q.key==="Vary"&&Q.value)i(A,Q.value);else if(Q.value)A.setHeader(Q.key,Q.value)}}}function T(M,A,R,G){var Q=[],b=A.method&&A.method.toUpperCase&&A.method.toUpperCase();if(b==="OPTIONS")if(Q.push(a(M,A)),Q.push(m(M,A)),Q.push(x(M,A)),Q.push(l(M,A)),Q.push(v(M,A)),Q.push(f(M,A)),$(Q,R),M.preflightContinue)G();else R.statusCode=M.optionsSuccessStatus,R.setHeader("Content-Length","0"),R.end();else Q.push(a(M,A)),Q.push(m(M,A)),Q.push(f(M,A)),$(Q,R),G()}function F(M){var A=null;if(typeof M==="function")A=M;else A=function(R,G){G(null,M)};return function R(G,Q,b){A(G,function(D,Y){if(D)b(D);else{var K=n({},o,Y),E=null;if(K.origin&&typeof K.origin==="function")E=K.origin;else if(K.origin)E=function(y,V){V(null,K.origin)};if(E)E(G.headers.origin,function(y,V){if(y||!V)b(y);else K.origin=V,T(K,G,Q,b)});else b()}})}}pF.exports=F})()});var av=h(($F)=>{Object.defineProperty($F,"__esModule",{value:!0});$F.Server=$F.BaseServer=void 0;var _3=import.meta.require("querystring"),b3=import.meta.require("url"),aF=Df(),Gm=iv(),j3=import.meta.require("events"),xF=ov(),y3=xi(),B3=gA(),L3=import.meta.require("ws"),mF=nv(),N3=_a(),$n=y3.default("engine"),zp=Symbol("responseHeaders");function D3(n){try{let i=JSON.parse(n);if(typeof i.sid==="string")return i.sid}catch(i){}}class ja extends j3.EventEmitter{constructor(n={}){super();if(this.middlewares=[],this.clients={},this.clientsCount=0,this.opts=Object.assign({wsEngine:L3.Server,pingTimeout:20000,pingInterval:25000,upgradeTimeout:1e4,maxHttpBufferSize:1e6,transports:["polling","websocket"],allowUpgrades:!0,httpCompression:{threshold:1024},cors:!1,allowEIO3:!1},n),n.cookie)this.opts.cookie=Object.assign({name:"io",path:"/",httpOnly:n.cookie.path!==!1,sameSite:"lax"},n.cookie);if(this.opts.cors)this.use(pv()(this.opts.cors));if(n.perMessageDeflate)this.opts.perMessageDeflate=Object.assign({threshold:1024},n.perMessageDeflate);this.init()}_computePath(n){let i=(n.path||"/engine.io").replace(/\/$/,"");if(n.addTrailingSlash!==!1)i+="/";return i}upgrades(n){if(!this.opts.allowUpgrades)return[];return Gm.default[n].upgradesTo||[]}verify(n,i,o){let c=n._query.transport;if(!~this.opts.transports.indexOf(c)||c==="webtransport")return $n('unknown transport "%s"',c),o(En.errors.UNKNOWN_TRANSPORT,{transport:c});if(C3(n.headers.origin)){let x=n.headers.origin;return n.headers.origin=null,$n("origin header invalid"),o(En.errors.BAD_REQUEST,{name:"INVALID_ORIGIN",origin:x})}let a=n._query.sid;if(a){if(!this.clients.hasOwnProperty(a))return $n('unknown sid "%s"',a),o(En.errors.UNKNOWN_SID,{sid:a});let x=this.clients[a].transport.name;if(!i&&x!==c)return $n("bad request: unexpected transport without upgrade"),o(En.errors.BAD_REQUEST,{name:"TRANSPORT_MISMATCH",transport:c,previousTransport:x})}else{if(n.method!=="GET")return o(En.errors.BAD_HANDSHAKE_METHOD,{method:n.method});if(c==="websocket"&&!i)return $n("invalid transport upgrade"),o(En.errors.BAD_REQUEST,{name:"TRANSPORT_HANDSHAKE_ERROR"});if(!this.opts.allowRequest)return o();return this.opts.allowRequest(n,(x,m)=>{if(!m)return o(En.errors.FORBIDDEN,{message:x});o()})}o()}use(n){this.middlewares.push(n)}_applyMiddlewares(n,i,o){if(this.middlewares.length===0)return $n("no middleware to apply, skipping"),o();let c=(p)=>{$n("applying middleware n\xB0%d",p+1),this.middlewares[p](n,i,(a)=>{if(a)return o(a);if(p+1<this.middlewares.length)c(p+1);else o()})};c(0)}close(){$n("closing all open clients");for(let n in this.clients)if(this.clients.hasOwnProperty(n))this.clients[n].close(!0);return this.cleanup(),this}generateId(n){return aF.generateId()}async handshake(n,i,o){let c=i._query.EIO==="4"?4:3;if(c===3&&!this.opts.allowEIO3){$n("unsupported protocol version"),this.emit("connection_error",{req:i,code:En.errors.UNSUPPORTED_PROTOCOL_VERSION,message:En.errorMessages[En.errors.UNSUPPORTED_PROTOCOL_VERSION],context:{protocol:c}}),o(En.errors.UNSUPPORTED_PROTOCOL_VERSION);return}let p;try{p=await this.generateId(i)}catch(m){$n("error while generating an id"),this.emit("connection_error",{req:i,code:En.errors.BAD_REQUEST,message:En.errorMessages[En.errors.BAD_REQUEST],context:{name:"ID_GENERATION_ERROR",error:m}}),o(En.errors.BAD_REQUEST);return}$n('handshaking client "%s"',p);try{var a=this.createTransport(n,i);if(n==="polling")a.maxHttpBufferSize=this.opts.maxHttpBufferSize,a.httpCompression=this.opts.httpCompression;else if(n==="websocket")a.perMessageDeflate=this.opts.perMessageDeflate}catch(m){$n('error handshaking to transport "%s"',n),this.emit("connection_error",{req:i,code:En.errors.BAD_REQUEST,message:En.errorMessages[En.errors.BAD_REQUEST],context:{name:"TRANSPORT_HANDSHAKE_ERROR",error:m}}),o(En.errors.BAD_REQUEST);return}let x=new xF.Socket(p,this,a,i,c);return a.on("headers",(m,l)=>{if(!l._query.sid){if(this.opts.cookie)m["Set-Cookie"]=[B3.serialize(this.opts.cookie.name,p,this.opts.cookie)];this.emit("initial_headers",m,l)}this.emit("headers",m,l)}),a.onRequest(i),this.clients[p]=x,this.clientsCount++,x.once("close",()=>{delete this.clients[p],this.clientsCount--}),this.emit("connection",x),a}async onWebTransportSession(n){let i=setTimeout(()=>{$n("the client failed to establish a bidirectional stream in the given period"),n.close()},this.opts.upgradeTimeout),c=await n.incomingBidirectionalStreams.getReader().read();if(c.done){$n("session is closed");return}let p=c.value,a=N3.createPacketDecoderStream(this.opts.maxHttpBufferSize,"nodebuffer"),x=p.readable.pipeThrough(a).getReader(),{value:m,done:l}=await x.read();if(l){$n("stream is closed");return}if(clearTimeout(i),m.type!=="open")return $n("invalid WebTransport handshake"),n.close();if(m.data===void 0){let $=new mF.WebTransport(n,p,x),T=aF.generateId();$n('handshaking client "%s" (WebTransport)',T);let F=new xF.Socket(T,this,$,null,4);this.clients[T]=F,this.clientsCount++,F.once("close",()=>{delete this.clients[T],this.clientsCount--}),this.emit("connection",F);return}let f=D3(m.data);if(!f)return $n("invalid WebTransport handshake"),n.close();let v=this.clients[f];if(!v)$n("upgrade attempt for closed client"),n.close();else if(v.upgrading)$n("transport has already been trying to upgrade"),n.close();else if(v.upgraded)$n("transport had already been upgraded"),n.close();else{$n("upgrading existing transport");let $=new mF.WebTransport(n,p,x);v._maybeUpgrade($)}}}$F.BaseServer=ja;ja.errors={UNKNOWN_TRANSPORT:0,UNKNOWN_SID:1,BAD_HANDSHAKE_METHOD:2,BAD_REQUEST:3,FORBIDDEN:4,UNSUPPORTED_PROTOCOL_VERSION:5};ja.errorMessages={0:"Transport unknown",1:"Session ID unknown",2:"Bad handshake method",3:"Bad request",4:"Forbidden",5:"Unsupported protocol version"};class vF{constructor(n,i){this.req=n,this.socket=i,n[zp]={}}setHeader(n,i){this.req[zp][n]=i}getHeader(n){return this.req[zp][n]}removeHeader(n){delete this.req[zp][n]}write(){}writeHead(){}end(){this.socket.destroy()}}class En extends ja{init(){if(!~this.opts.transports.indexOf("websocket"))return;if(this.ws)this.ws.close();if(this.ws=new this.opts.wsEngine({noServer:!0,clientTracking:!1,perMessageDeflate:this.opts.perMessageDeflate,maxPayload:this.opts.maxHttpBufferSize}),typeof this.ws.on==="function")this.ws.on("headers",(n,i)=>{let o=i[zp]||{};if(delete i[zp],!i._query.sid)this.emit("initial_headers",o,i);this.emit("headers",o,i),$n("writing headers: %j",o),Object.keys(o).forEach((p)=>{n.push(`${p}: ${o[p]}`)})})}cleanup(){if(this.ws)$n("closing webSocketServer"),this.ws.close()}prepare(n){if(!n._query)n._query=~n.url.indexOf("?")?_3.parse(b3.parse(n.url).query):{}}createTransport(n,i){return new Gm.default[n](i)}handleRequest(n,i){$n('handling "%s" http request "%s"',n.method,n.url),this.prepare(n),n.res=i;let o=(c,p)=>{if(c!==void 0){this.emit("connection_error",{req:n,code:c,message:En.errorMessages[c],context:p}),lF(i,c,p);return}if(n._query.sid)$n("setting new request for existing client"),this.clients[n._query.sid].transport.onRequest(n);else{let a=(x,m)=>lF(i,x,m);this.handshake(n._query.transport,n,a)}};this._applyMiddlewares(n,i,(c)=>{if(c)o(En.errors.BAD_REQUEST,{name:"MIDDLEWARE_FAILURE"});else this.verify(n,!1,o)})}handleUpgrade(n,i,o){this.prepare(n);let c=new vF(n,i),p=(a,x)=>{if(a!==void 0){this.emit("connection_error",{req:n,code:a,message:En.errorMessages[a],context:x}),fF(i,a,x);return}let m=Buffer.from(o);o=null,c.writeHead(),this.ws.handleUpgrade(n,i,m,(l)=>{this.onWebSocket(n,i,l)})};this._applyMiddlewares(n,c,(a)=>{if(a)p(En.errors.BAD_REQUEST,{name:"MIDDLEWARE_FAILURE"});else this.verify(n,!0,p)})}onWebSocket(n,i,o){if(o.on("error",p),Gm.default[n._query.transport]!==void 0&&!Gm.default[n._query.transport].prototype.handlesUpgrades){$n("transport doesnt handle upgraded requests"),o.close();return}let c=n._query.sid;if(n.websocket=o,c){let a=this.clients[c];if(!a)$n("upgrade attempt for closed client"),o.close();else if(a.upgrading)$n("transport has already been trying to upgrade"),o.close();else if(a.upgraded)$n("transport had already been upgraded"),o.close();else{$n("upgrading existing transport"),o.removeListener("error",p);let x=this.createTransport(n._query.transport,n);x.perMessageDeflate=this.opts.perMessageDeflate,a._maybeUpgrade(x)}}else{let a=(x,m)=>fF(i,x,m);this.handshake(n._query.transport,n,a)}function p(){$n("websocket error before upgrade")}}attach(n,i={}){let o=this._computePath(i),c=i.destroyUpgradeTimeout||1000;function p(x){return o===x.url.slice(0,o.length)}let a=n.listeners("request").slice(0);if(n.removeAllListeners("request"),n.on("close",this.close.bind(this)),n.on("listening",this.init.bind(this)),n.on("request",(x,m)=>{if(p(x))$n('intercepting request for path "%s"',o),this.handleRequest(x,m);else{let l=0,f=a.length;for(;l<f;l++)a[l].call(n,x,m)}}),~this.opts.transports.indexOf("websocket"))n.on("upgrade",(x,m,l)=>{if(p(x))this.handleUpgrade(x,m,l);else if(i.destroyUpgrade!==!1)setTimeout(function(){if(m.writable&&m.bytesWritten<=0)return m.on("error",(f)=>{$n("error while destroying upgrade: %s",f.message)}),m.end()},c)})}}$F.Server=En;function lF(n,i,o){let c=i===En.errors.FORBIDDEN?403:400,p=o&&o.message?o.message:En.errorMessages[i];n.writeHead(c,{"Content-Type":"application/json"}),n.end(JSON.stringify({code:i,message:p}))}function fF(n,i,o={}){if(n.on("error",()=>{$n("ignoring error from closed connection")}),n.writable){let c=o.message||En.errorMessages[i],p=Buffer.byteLength(c);n.write("HTTP/1.1 400 Bad Request\r\nConnection: close\r\nContent-type: text/html\r\nContent-Length: "+p+"\r\n\r\n"+c)}n.destroy()}var ba=[0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1];function C3(n){if(n+="",n.length<1)return!1;if(!ba[n.charCodeAt(0)])return $n('invalid header, index 0, char "%s"',n.charCodeAt(0)),!0;if(n.length<2)return!1;if(!ba[n.charCodeAt(1)])return $n('invalid header, index 1, char "%s"',n.charCodeAt(1)),!0;if(n.length<3)return!1;if(!ba[n.charCodeAt(2)])return $n('invalid header, index 2, char "%s"',n.charCodeAt(2)),!0;if(n.length<4)return!1;if(!ba[n.charCodeAt(3)])return $n('invalid header, index 3, char "%s"',n.charCodeAt(3)),!0;for(let i=4;i<n.length;++i)if(!ba[n.charCodeAt(i)])return $n('invalid header, index "%i", char "%s"',i,n.charCodeAt(i)),!0;return!1}});var FF=h((SF)=>{Object.defineProperty(SF,"__esModule",{value:!0});SF.Polling=void 0;var I3=_c(),wF=import.meta.require("zlib"),k3=fm(),s3=xi(),io=s3.default("engine:polling"),Z3={gzip:wF.createGzip,deflate:wF.createDeflate};class JF extends I3.Transport{constructor(n){super(n);this.closeTimeout=30000}get name(){return"polling"}onRequest(n){let i=n.res;if(n.res=null,n.getMethod()==="get")this.onPollRequest(n,i);else if(n.getMethod()==="post")this.onDataRequest(n,i);else i.writeStatus("500 Internal Server Error"),i.end()}onPollRequest(n,i){if(this.req){io("request overlap"),this.onError("overlap from client"),i.writeStatus("500 Internal Server Error"),i.end();return}io("setting request"),this.req=n,this.res=i;let o=()=>{this.writable=!1,this.onError("poll connection closed prematurely")},c=()=>{this.req=this.res=null};if(n.cleanup=c,i.onAborted(o),this.writable=!0,this.emit("ready"),this.writable&&this.shouldClose)io("triggering empty send to append close packet"),this.send([{type:"noop"}])}onDataRequest(n,i){if(this.dataReq){this.onError("data request overlap from client"),i.writeStatus("500 Internal Server Error"),i.end();return}let o=Number(n.headers["content-length"]);if(!o){this.onError("content-length header required"),i.writeStatus("411 Length Required").end();return}if(o>this.maxHttpBufferSize){this.onError("payload too large"),i.writeStatus("413 Payload Too Large").end();return}if(n.headers["content-type"]==="application/octet-stream"&&this.protocol===4)return this.onError("invalid content");this.dataReq=n,this.dataRes=i;let p,a=0,x={"Content-Type":"text/html"};this.headers(n,x);for(let l in x)i.writeHeader(l,String(x[l]));let m=(l)=>{this.onData(l.toString()),this.onDataRequestCleanup(),i.cork(()=>{i.end("ok")})};i.onAborted(()=>{this.onDataRequestCleanup(),this.onError("data request connection closed prematurely")}),i.onData((l,f)=>{let v=a+l.byteLength;if(v>o){this.onError("content-length mismatch"),i.close();return}if(!p){if(f){m(Buffer.from(l));return}p=Buffer.allocUnsafe(o)}if(Buffer.from(l).copy(p,a),f){if(v!=o){this.onError("content-length mismatch"),i.writeStatus("400 Content-Length Mismatch").end(),this.onDataRequestCleanup();return}m(p);return}a=v})}onDataRequestCleanup(){this.dataReq=this.dataRes=null}onData(n){io('received "%s"',n);let i=(o)=>{if(o.type==="close")return io("got xhr close packet"),this.onClose(),!1;this.onPacket(o)};if(this.protocol===3)this.parser.decodePayload(n,i);else this.parser.decodePayload(n).forEach(i)}onClose(){if(this.writable)this.send([{type:"noop"}]);super.onClose()}send(n){if(this.writable=!1,this.shouldClose)io("appending close packet to payload"),n.push({type:"close"}),this.shouldClose(),this.shouldClose=null;let i=(o)=>{let c=n.some((p)=>{return p.options&&p.options.compress});this.write(o,{compress:c})};if(this.protocol===3)this.parser.encodePayload(n,this.supportsBinary,i);else this.parser.encodePayload(n,i)}write(n,i){io('writing "%s"',n),this.doWrite(n,i,()=>{this.req.cleanup(),this.emit("drain")})}doWrite(n,i,o){let c=typeof n==="string",a={"Content-Type":c?"text/plain; charset=UTF-8":"application/octet-stream"},x=(f)=>{this.headers(this.req,a),this.res.cork(()=>{Object.keys(a).forEach((v)=>{this.res.writeHeader(v,String(a[v]))}),this.res.end(f)}),o()};if(!this.httpCompression||!i.compress){x(n);return}if((c?Buffer.byteLength(n):n.length)<this.httpCompression.threshold){x(n);return}let l=k3(this.req).encodings(["gzip","deflate"]);if(!l){x(n);return}this.compress(n,l,(f,v)=>{if(f){this.res.writeStatus("500 Internal Server Error"),this.res.end(),o(f);return}a["Content-Encoding"]=l,x(v)})}compress(n,i,o){io("compressing");let c=[],p=0;Z3[i](this.httpCompression).on("error",o).on("data",function(a){c.push(a),p+=a.length}).on("end",function(){o(null,Buffer.concat(c,p))}).end(n)}doClose(n){io("closing");let i,o=()=>{clearTimeout(i),n(),this.onClose()};if(this.writable)io("transport writable - closing right away"),this.send([{type:"close"}]),o();else if(this.discarded)io("transport discarded - closing right away"),o();else io("transport not writable - buffering orderly close"),this.shouldClose=o,i=setTimeout(o,this.closeTimeout)}headers(n,i){i=i||{};let o=n.headers["user-agent"];if(o&&(~o.indexOf(";MSIE")||~o.indexOf("Trident/")))i["X-XSS-Protection"]="0";return i["cache-control"]="no-store",this.emit("headers",i,n),i}}SF.Polling=JF});var XF=h((WF)=>{Object.defineProperty(WF,"__esModule",{value:!0});WF.WebSocket=void 0;var t3=_c(),q3=xi(),MF=q3.default("engine:ws");class RF extends t3.Transport{constructor(n){super(n);this.writable=!1,this.perMessageDeflate=null}get name(){return"websocket"}get handlesUpgrades(){return!0}send(n){this.writable=!1;for(let i=0;i<n.length;i++){let o=n[i],c=i+1===n.length,p=(a)=>{let x=typeof a!=="string",m=this.perMessageDeflate&&Buffer.byteLength(a)>this.perMessageDeflate.threshold;if(MF('writing "%s"',a),this.socket.send(a,x,m),c)this.emit("drain"),this.writable=!0,this.emit("ready")};if(o.options&&typeof o.options.wsPreEncoded==="string")p(o.options.wsPreEncoded);else this.parser.encodePacket(o,this.supportsBinary,p)}}doClose(n){MF("closing"),n&&n(),this.socket.end()}}WF.WebSocket=RF});var YF=h((GF)=>{Object.defineProperty(GF,"__esModule",{value:!0});var P3=FF(),r3=XF();GF.default={polling:P3.Polling,websocket:r3.WebSocket}});var OF=h((HF)=>{Object.defineProperty(HF,"__esModule",{value:!0});HF.uServer=void 0;var d3=xi(),bc=av(),e3=YF(),vc=d3.default("engine:uws");class zF extends bc.BaseServer{init(){}cleanup(){}prepare(n,i){n.method=n.getMethod().toUpperCase(),n.url=n.getUrl();let o=new URLSearchParams(n.getQuery());n._query=Object.fromEntries(o.entries()),n.headers={},n.forEach((c,p)=>{n.headers[c]=p}),n.connection={remoteAddress:Buffer.from(i.getRemoteAddressAsText()).toString()},i.onAborted(()=>{vc("response has been aborted")})}createTransport(n,i){return new e3.default[n](i)}attach(n,i={}){let o=this._computePath(i);n.any(o,this.handleRequest.bind(this)).ws(o,{compression:i.compression,idleTimeout:i.idleTimeout,maxBackpressure:i.maxBackpressure,maxPayloadLength:this.opts.maxHttpBufferSize,upgrade:this.handleUpgrade.bind(this),open:(c)=>{let p=c.getUserData().transport;p.socket=c,p.writable=!0,p.emit("ready")},message:(c,p,a)=>{c.getUserData().transport.onData(a?p:Buffer.from(p).toString())},close:(c,p,a)=>{c.getUserData().transport.onClose(p,a)}})}_applyMiddlewares(n,i,o){if(this.middlewares.length===0)return o();n.res=new QF(i),super._applyMiddlewares(n,n.res,(c)=>{n.res.writeHead(),o(c)})}handleRequest(n,i){vc('handling "%s" http request "%s"',i.getMethod(),i.getUrl()),this.prepare(i,n),i.res=n;let o=(c,p)=>{if(c!==void 0){this.emit("connection_error",{req:i,code:c,message:bc.Server.errorMessages[c],context:p}),this.abortRequest(i.res,c,p);return}if(i._query.sid)vc("setting new request for existing client"),this.clients[i._query.sid].transport.onRequest(i);else{let a=(x,m)=>this.abortRequest(n,x,m);this.handshake(i._query.transport,i,a)}};this._applyMiddlewares(i,n,(c)=>{if(c)o(bc.Server.errors.BAD_REQUEST,{name:"MIDDLEWARE_FAILURE"});else this.verify(i,!1,o)})}handleUpgrade(n,i,o){vc("on upgrade"),this.prepare(i,n),i.res=n;let c=async(p,a)=>{if(p!==void 0){this.emit("connection_error",{req:i,code:p,message:bc.Server.errorMessages[p],context:a}),this.abortRequest(n,p,a);return}let x=i._query.sid,m;if(x){let l=this.clients[x];if(!l)return vc("upgrade attempt for closed client"),n.close();else if(l.upgrading)return vc("transport has already been trying to upgrade"),n.close();else if(l.upgraded)return vc("transport had already been upgraded"),n.close();else vc("upgrading existing transport"),m=this.createTransport(i._query.transport,i),l._maybeUpgrade(m)}else if(m=await this.handshake(i._query.transport,i,(l,f)=>this.abortRequest(n,l,f)),!m)return;i.res.writeStatus("101 Switching Protocols"),n.upgrade({transport:m},i.getHeader("sec-websocket-key"),i.getHeader("sec-websocket-protocol"),i.getHeader("sec-websocket-extensions"),o)};this._applyMiddlewares(i,n,(p)=>{if(p)c(bc.Server.errors.BAD_REQUEST,{name:"MIDDLEWARE_FAILURE"});else this.verify(i,!0,c)})}abortRequest(n,i,o){let c=i===bc.Server.errors.FORBIDDEN?"403 Forbidden":"400 Bad Request",p=o&&o.message?o.message:bc.Server.errorMessages[i];n.writeStatus(c),n.writeHeader("Content-Type","application/json"),n.end(JSON.stringify({code:i,message:p}))}}HF.uServer=zF;class QF{constructor(n){this.res=n,this.statusWritten=!1,this.headers=[],this.isAborted=!1}set statusCode(n){if(!n)return;this.writeStatus(n===200?"200 OK":"204 No Content")}writeHead(n){this.statusCode=n}setHeader(n,i){if(Array.isArray(i))i.forEach((o)=>{this.writeHeader(n,o)});else this.writeHeader(n,i)}removeHeader(){}getHeader(){}writeStatus(n){if(this.isAborted)return;return this.res.writeStatus(n),this.statusWritten=!0,this.writeBufferedHeaders(),this}writeHeader(n,i){if(this.isAborted)return;if(n==="Content-Length")return;if(this.statusWritten)this.res.writeHeader(n,i);else this.headers.push([n,i])}writeBufferedHeaders(){this.headers.forEach(([n,i])=>{this.res.writeHeader(n,i)})}end(n){if(this.isAborted)return;this.res.cork(()=>{if(!this.statusWritten)this.writeBufferedHeaders();this.res.end(n)})}onData(n){if(this.isAborted)return;this.res.onData(n)}onAborted(n){if(this.isAborted)return;this.res.onAborted(()=>{this.isAborted=!0,n()})}cork(n){if(this.isAborted)return;this.res.cork(n)}}});var bF=h((Qp)=>{Object.defineProperty(Qp,"__esModule",{value:!0});Qp.protocol=Qp.Transport=Qp.Socket=Qp.uServer=Qp.parser=Qp.transports=Qp.Server=void 0;Qp.listen=aX;Qp.attach=uF;var nX=import.meta.require("http"),UF=av();Object.defineProperty(Qp,"Server",{enumerable:!0,get:function(){return UF.Server}});var iX=iv();Qp.transports=iX.default;var VF=_a();Qp.parser=VF;var oX=OF();Object.defineProperty(Qp,"uServer",{enumerable:!0,get:function(){return oX.uServer}});var cX=ov();Object.defineProperty(Qp,"Socket",{enumerable:!0,get:function(){return cX.Socket}});var pX=_c();Object.defineProperty(Qp,"Transport",{enumerable:!0,get:function(){return pX.Transport}});Qp.protocol=VF.protocol;function aX(n,i,o){if(typeof i==="function")o=i,i={};let c=nX.createServer(function(a,x){x.writeHead(501),x.end("Not Implemented")}),p=uF(c,i);return p.httpServer=c,c.listen(n,o),p}function uF(n,i){let o=new UF.Server(i);return o.attach(n,i),o}});var jF=h(($X)=>{$X.Emitter=Hi;function Hi(n){if(n)return vX(n)}function vX(n){for(var i in Hi.prototype)n[i]=Hi.prototype[i];return n}Hi.prototype.on=Hi.prototype.addEventListener=function(n,i){return this._callbacks=this._callbacks||{},(this._callbacks["$"+n]=this._callbacks["$"+n]||[]).push(i),this};Hi.prototype.once=function(n,i){function o(){this.off(n,o),i.apply(this,arguments)}return o.fn=i,this.on(n,o),this};Hi.prototype.off=Hi.prototype.removeListener=Hi.prototype.removeAllListeners=Hi.prototype.removeEventListener=function(n,i){if(this._callbacks=this._callbacks||{},arguments.length==0)return this._callbacks={},this;var o=this._callbacks["$"+n];if(!o)return this;if(arguments.length==1)return delete this._callbacks["$"+n],this;var c;for(var p=0;p<o.length;p++)if(c=o[p],c===i||c.fn===i){o.splice(p,1);break}if(o.length===0)delete this._callbacks["$"+n];return this};Hi.prototype.emit=function(n){this._callbacks=this._callbacks||{};var i=new Array(arguments.length-1),o=this._callbacks["$"+n];for(var c=1;c<arguments.length;c++)i[c-1]=arguments[c];if(o){o=o.slice(0);for(var c=0,p=o.length;c<p;++c)o[c].apply(this,i)}return this};Hi.prototype.emitReserved=Hi.prototype.emit;Hi.prototype.listeners=function(n){return this._callbacks=this._callbacks||{},this._callbacks["$"+n]||[]};Hi.prototype.hasListeners=function(n){return!!this.listeners(n).length}});var xv=h((LF)=>{Object.defineProperty(LF,"__esModule",{value:!0});LF.hasBinary=LF.isBinary=void 0;var wX=typeof ArrayBuffer==="function",JX=(n)=>{return typeof ArrayBuffer.isView==="function"?ArrayBuffer.isView(n):n.buffer instanceof ArrayBuffer},yF=Object.prototype.toString,SX=typeof Blob==="function"||typeof Blob!=="undefined"&&yF.call(Blob)==="[object BlobConstructor]",AX=typeof File==="function"||typeof File!=="undefined"&&yF.call(File)==="[object FileConstructor]";function BF(n){return wX&&(n instanceof ArrayBuffer||JX(n))||SX&&n instanceof Blob||AX&&n instanceof File}LF.isBinary=BF;function Ym(n,i){if(!n||typeof n!=="object")return!1;if(Array.isArray(n)){for(let o=0,c=n.length;o<c;o++)if(Ym(n[o]))return!0;return!1}if(BF(n))return!0;if(n.toJSON&&typeof n.toJSON==="function"&&arguments.length===1)return Ym(n.toJSON(),!0);for(let o in n)if(Object.prototype.hasOwnProperty.call(n,o)&&Ym(n[o]))return!0;return!1}LF.hasBinary=Ym});var hF=h((DF)=>{Object.defineProperty(DF,"__esModule",{value:!0});DF.reconstructPacket=DF.deconstructPacket=void 0;var MX=xv();function RX(n){let i=[],o=n.data,c=n;return c.data=mv(o,i),c.attachments=i.length,{packet:c,buffers:i}}DF.deconstructPacket=RX;function mv(n,i){if(!n)return n;if(MX.isBinary(n)){let o={_placeholder:!0,num:i.length};return i.push(n),o}else if(Array.isArray(n)){let o=new Array(n.length);for(let c=0;c<n.length;c++)o[c]=mv(n[c],i);return o}else if(typeof n==="object"&&!(n instanceof Date)){let o={};for(let c in n)if(Object.prototype.hasOwnProperty.call(n,c))o[c]=mv(n[c],i);return o}return n}function WX(n,i){return n.data=lv(n.data,i),delete n.attachments,n}DF.reconstructPacket=WX;function lv(n,i){if(!n)return n;if(n&&n._placeholder===!0)if(typeof n.num==="number"&&n.num>=0&&n.num<i.length)return i[n.num];else throw new Error("illegal attachments");else if(Array.isArray(n))for(let o=0;o<n.length;o++)n[o]=lv(n[o],i);else if(typeof n==="object"){for(let o in n)if(Object.prototype.hasOwnProperty.call(n,o))n[o]=lv(n[o],i)}return n}});var ya=h((PF)=>{Object.defineProperty(PF,"__esModule",{value:!0});PF.Decoder=PF.Encoder=PF.PacketType=PF.protocol=void 0;var XX=jF(),sF=hF(),ZF=xv(),GX=xi(),fv=GX.default("socket.io-parser"),YX=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"];PF.protocol=5;var sn;(function(n){n[n.CONNECT=0]="CONNECT",n[n.DISCONNECT=1]="DISCONNECT",n[n.EVENT=2]="EVENT",n[n.ACK=3]="ACK",n[n.CONNECT_ERROR=4]="CONNECT_ERROR",n[n.BINARY_EVENT=5]="BINARY_EVENT",n[n.BINARY_ACK=6]="BINARY_ACK"})(sn=PF.PacketType||(PF.PacketType={}));class tF{constructor(n){this.replacer=n}encode(n){if(fv("encoding packet %j",n),n.type===sn.EVENT||n.type===sn.ACK){if(ZF.hasBinary(n))return this.encodeAsBinary({type:n.type===sn.EVENT?sn.BINARY_EVENT:sn.BINARY_ACK,nsp:n.nsp,data:n.data,id:n.id})}return[this.encodeAsString(n)]}encodeAsString(n){let i=""+n.type;if(n.type===sn.BINARY_EVENT||n.type===sn.BINARY_ACK)i+=n.attachments+"-";if(n.nsp&&n.nsp!=="/")i+=n.nsp+",";if(n.id!=null)i+=n.id;if(n.data!=null)i+=JSON.stringify(n.data,this.replacer);return fv("encoded %j as %s",n,i),i}encodeAsBinary(n){let i=sF.deconstructPacket(n),o=this.encodeAsString(i.packet),c=i.buffers;return c.unshift(o),c}}PF.Encoder=tF;function IF(n){return Object.prototype.toString.call(n)==="[object Object]"}class vv extends XX.Emitter{constructor(n){super();this.reviver=n}add(n){let i;if(typeof n==="string"){if(this.reconstructor)throw new Error("got plaintext data when reconstructing a packet");i=this.decodeString(n);let o=i.type===sn.BINARY_EVENT;if(o||i.type===sn.BINARY_ACK){if(i.type=o?sn.EVENT:sn.ACK,this.reconstructor=new qF(i),i.attachments===0)super.emitReserved("decoded",i)}else super.emitReserved("decoded",i)}else if(ZF.isBinary(n)||n.base64){if(!this.reconstructor)throw new Error("got binary data when not reconstructing a packet");else if(i=this.reconstructor.takeBinaryData(n),i)this.reconstructor=null,super.emitReserved("decoded",i)}else throw new Error("Unknown type: "+n)}decodeString(n){let i=0,o={type:Number(n.charAt(0))};if(sn[o.type]===void 0)throw new Error("unknown packet type "+o.type);if(o.type===sn.BINARY_EVENT||o.type===sn.BINARY_ACK){let p=i+1;while(n.charAt(++i)!=="-"&&i!=n.length);let a=n.substring(p,i);if(a!=Number(a)||n.charAt(i)!=="-")throw new Error("Illegal attachments");o.attachments=Number(a)}if(n.charAt(i+1)==="/"){let p=i+1;while(++i){if(n.charAt(i)===",")break;if(i===n.length)break}o.nsp=n.substring(p,i)}else o.nsp="/";let c=n.charAt(i+1);if(c!==""&&Number(c)==c){let p=i+1;while(++i){let a=n.charAt(i);if(a==null||Number(a)!=a){--i;break}if(i===n.length)break}o.id=Number(n.substring(p,i+1))}if(n.charAt(++i)){let p=this.tryParse(n.substr(i));if(vv.isPayloadValid(o.type,p))o.data=p;else throw new Error("invalid payload")}return fv("decoded %s as %j",n,o),o}tryParse(n){try{return JSON.parse(n,this.reviver)}catch(i){return!1}}static isPayloadValid(n,i){switch(n){case sn.CONNECT:return IF(i);case sn.DISCONNECT:return i===void 0;case sn.CONNECT_ERROR:return typeof i==="string"||IF(i);case sn.EVENT:case sn.BINARY_EVENT:return Array.isArray(i)&&(typeof i[0]==="number"||typeof i[0]==="string"&&YX.indexOf(i[0])===-1);case sn.ACK:case sn.BINARY_ACK:return Array.isArray(i)}}destroy(){if(this.reconstructor)this.reconstructor.finishedReconstruction(),this.reconstructor=null}}PF.Decoder=vv;class qF{constructor(n){this.packet=n,this.buffers=[],this.reconPack=n}takeBinaryData(n){if(this.buffers.push(n),this.buffers.length===this.reconPack.attachments){let i=sF.reconstructPacket(this.reconPack,this.buffers);return this.finishedReconstruction(),i}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}});var nM=h((dF)=>{Object.defineProperty(dF,"__esModule",{value:!0});dF.Client=void 0;var zm=ya(),HX=xi(),EX=import.meta.require("url"),Ao=HX("socket.io:client");class gF{constructor(n,i){this.sockets=new Map,this.nsps=new Map,this.server=n,this.conn=i,this.encoder=n.encoder,this.decoder=new n._parser.Decoder,this.id=i.id,this.setup()}get request(){return this.conn.request}setup(){this.onclose=this.onclose.bind(this),this.ondata=this.ondata.bind(this),this.onerror=this.onerror.bind(this),this.ondecoded=this.ondecoded.bind(this),this.decoder.on("decoded",this.ondecoded),this.conn.on("data",this.ondata),this.conn.on("error",this.onerror),this.conn.on("close",this.onclose),this.connectTimeout=setTimeout(()=>{if(this.nsps.size===0)Ao("no namespace joined yet, close the client"),this.close();else Ao("the client has already joined a namespace, nothing to do")},this.server._connectTimeout)}connect(n,i={}){if(this.server._nsps.has(n))return Ao("connecting to namespace %s",n),this.doConnect(n,i);this.server._checkNamespace(n,i,(o)=>{if(o)this.doConnect(n,i);else Ao("creation of namespace %s was denied",n),this._packet({type:zm.PacketType.CONNECT_ERROR,nsp:n,data:{message:"Invalid namespace"}})})}doConnect(n,i){let o=this.server.of(n);o._add(this,i,(c)=>{if(this.sockets.set(c.id,c),this.nsps.set(o.name,c),this.connectTimeout)clearTimeout(this.connectTimeout),this.connectTimeout=void 0})}_disconnect(){for(let n of this.sockets.values())n.disconnect();this.sockets.clear(),this.close()}_remove(n){if(this.sockets.has(n.id)){let i=this.sockets.get(n.id).nsp.name;this.sockets.delete(n.id),this.nsps.delete(i)}else Ao("ignoring remove for %s",n.id)}close(){if(this.conn.readyState==="open")Ao("forcing transport close"),this.conn.close(),this.onclose("forced server close")}_packet(n,i={}){if(this.conn.readyState!=="open"){Ao("ignoring packet write %j",n);return}let o=i.preEncoded?n:this.encoder.encode(n);this.writeToEngine(o,i)}writeToEngine(n,i){if(i.volatile&&!this.conn.transport.writable){Ao("volatile packet is discarded since the transport is not currently writable");return}let o=Array.isArray(n)?n:[n];for(let c of o)this.conn.write(c,i)}ondata(n){try{this.decoder.add(n)}catch(i){Ao("invalid packet format"),this.onerror(i)}}ondecoded(n){let i,o;if(this.conn.protocol===3){let p=EX.parse(n.nsp,!0);i=p.pathname,o=p.query}else i=n.nsp,o=n.data;let c=this.nsps.get(i);if(!c&&n.type===zm.PacketType.CONNECT)this.connect(i,o);else if(c&&n.type!==zm.PacketType.CONNECT&&n.type!==zm.PacketType.CONNECT_ERROR)process.nextTick(function(){c._onpacket(n)});else Ao("invalid state (packet type: %s)",n.type),this.close()}onerror(n){for(let i of this.sockets.values())i._onerror(n);this.conn.close()}onclose(n,i){Ao("client close with reason %s",n),this.destroy();for(let o of this.sockets.values())o._onclose(n,i);this.sockets.clear(),this.decoder.destroy()}destroy(){if(this.conn.removeListener("data",this.ondata),this.conn.removeListener("error",this.onerror),this.conn.removeListener("close",this.onclose),this.decoder.removeListener("decoded",this.ondecoded),this.connectTimeout)clearTimeout(this.connectTimeout),this.connectTimeout=void 0}}dF.Client=gF});var Qm=h((oM)=>{Object.defineProperty(oM,"__esModule",{value:!0});oM.StrictEventEmitter=void 0;var OX=import.meta.require("events");class iM extends OX.EventEmitter{on(n,i){return super.on(n,i)}once(n,i){return super.once(n,i)}emit(n,...i){return super.emit(n,...i)}emitReserved(n,...i){return super.emit(n,...i)}emitUntyped(n,...i){return super.emit(n,...i)}listeners(n){return super.listeners(n)}}oM.StrictEventEmitter=iM});var $v=h((pM)=>{Object.defineProperty(pM,"__esModule",{value:!0});pM.RESERVED_EVENTS=void 0;pM.RESERVED_EVENTS=new Set(["connect","connect_error","disconnect","disconnecting","newListener","removeListener"])});var wv=h((xM)=>{Object.defineProperty(xM,"__esModule",{value:!0});xM.RemoteSocket=xM.BroadcastOperator=void 0;var UX=$v(),VX=ya();class No{constructor(n,i=new Set,o=new Set,c={}){this.adapter=n,this.rooms=i,this.exceptRooms=o,this.flags=c}to(n){let i=new Set(this.rooms);if(Array.isArray(n))n.forEach((o)=>i.add(o));else i.add(n);return new No(this.adapter,i,this.exceptRooms,this.flags)}in(n){return this.to(n)}except(n){let i=new Set(this.exceptRooms);if(Array.isArray(n))n.forEach((o)=>i.add(o));else i.add(n);return new No(this.adapter,this.rooms,i,this.flags)}compress(n){let i=Object.assign({},this.flags,{compress:n});return new No(this.adapter,this.rooms,this.exceptRooms,i)}get volatile(){let n=Object.assign({},this.flags,{volatile:!0});return new No(this.adapter,this.rooms,this.exceptRooms,n)}get local(){let n=Object.assign({},this.flags,{local:!0});return new No(this.adapter,this.rooms,this.exceptRooms,n)}timeout(n){let i=Object.assign({},this.flags,{timeout:n});return new No(this.adapter,this.rooms,this.exceptRooms,i)}emit(n,...i){if(UX.RESERVED_EVENTS.has(n))throw new Error(`"${String(n)}" is a reserved event name`);let o=[n,...i],c={type:VX.PacketType.EVENT,data:o};if(typeof o[o.length-1]!=="function")return this.adapter.broadcast(c,{rooms:this.rooms,except:this.exceptRooms,flags:this.flags}),!0;let a=o.pop(),x=!1,m=[],l=setTimeout(()=>{x=!0,a.apply(this,[new Error("operation has timed out"),this.flags.expectSingleResponse?null:m])},this.flags.timeout),f=-1,v=0,$=0,T=()=>{if(!x&&f===v&&m.length===$)clearTimeout(l),a.apply(this,[null,this.flags.expectSingleResponse?m[0]:m])};return this.adapter.broadcastWithAck(c,{rooms:this.rooms,except:this.exceptRooms,flags:this.flags},(F)=>{$+=F,v++,T()},(F)=>{m.push(F),T()}),this.adapter.serverCount().then((F)=>{f=F,T()}),!0}emitWithAck(n,...i){return new Promise((o,c)=>{i.push((p,a)=>{if(p)return p.responses=a,c(p);else return o(a)}),this.emit(n,...i)})}allSockets(){if(!this.adapter)throw new Error("No adapter for this namespace, are you trying to get the list of clients of a dynamic namespace?");return this.adapter.sockets(this.rooms)}fetchSockets(){return this.adapter.fetchSockets({rooms:this.rooms,except:this.exceptRooms,flags:this.flags}).then((n)=>{return n.map((i)=>{if(i.server)return i;else return new Tv(this.adapter,i)})})}socketsJoin(n){this.adapter.addSockets({rooms:this.rooms,except:this.exceptRooms,flags:this.flags},Array.isArray(n)?n:[n])}socketsLeave(n){this.adapter.delSockets({rooms:this.rooms,except:this.exceptRooms,flags:this.flags},Array.isArray(n)?n:[n])}disconnectSockets(n=!1){this.adapter.disconnectSockets({rooms:this.rooms,except:this.exceptRooms,flags:this.flags},n)}}xM.BroadcastOperator=No;class Tv{constructor(n,i){this.id=i.id,this.handshake=i.handshake,this.rooms=new Set(i.rooms),this.data=i.data,this.operator=new No(n,new Set([this.id]),new Set,{expectSingleResponse:!0})}timeout(n){return this.operator.timeout(n)}emit(n,...i){return this.operator.emit(n,...i)}join(n){return this.operator.socketsJoin(n)}leave(n){return this.operator.socketsLeave(n)}disconnect(n=!1){return this.operator.disconnectSockets(n),this}}xM.RemoteSocket=Tv});var Jv=h((Hp)=>{var vM=Hp&&Hp.__importDefault||function(n){return n&&n.__esModule?n:{default:n}};Object.defineProperty(Hp,"__esModule",{value:!0});Hp.Socket=void 0;var oo=ya(),_X=vM(xi()),bX=Qm(),lM=vM(Df()),jX=wv(),yX=$v(),Wi=_X.default("socket.io:socket"),BX=new Set(["transport error","transport close","forced close","ping timeout","server shutting down","forced server close"]);function fM(){}class $M extends bX.StrictEventEmitter{constructor(n,i,o,c){super();if(this.nsp=n,this.client=i,this.recovered=!1,this.data={},this.connected=!1,this.acks=new Map,this.fns=[],this.flags={},this.server=n.server,this.adapter=this.nsp.adapter,c)this.id=c.sid,this.pid=c.pid,c.rooms.forEach((p)=>this.join(p)),this.data=c.data,c.missedPackets.forEach((p)=>{this.packet({type:oo.PacketType.EVENT,data:p})}),this.recovered=!0;else{if(i.conn.protocol===3)this.id=n.name!=="/"?n.name+"#"+i.id:i.id;else this.id=lM.default.generateId();if(this.server._opts.connectionStateRecovery)this.pid=lM.default.generateId()}this.handshake=this.buildHandshake(o),this.on("error",fM)}buildHandshake(n){var i,o,c,p;return{headers:((i=this.request)===null||i===void 0?void 0:i.headers)||{},time:new Date+"",address:this.conn.remoteAddress,xdomain:!!((o=this.request)===null||o===void 0?void 0:o.headers.origin),secure:!this.request||!!this.request.connection.encrypted,issued:+new Date,url:(c=this.request)===null||c===void 0?void 0:c.url,query:((p=this.request)===null||p===void 0?void 0:p._query)||{},auth:n}}emit(n,...i){if(yX.RESERVED_EVENTS.has(n))throw new Error(`"${String(n)}" is a reserved event name`);let o=[n,...i],c={type:oo.PacketType.EVENT,data:o};if(typeof o[o.length-1]==="function"){let a=this.nsp._ids++;Wi("emitting packet with ack id %d",a),this.registerAckCallback(a,o.pop()),c.id=a}let p=Object.assign({},this.flags);if(this.flags={},this.nsp.server.opts.connectionStateRecovery)this.adapter.broadcast(c,{rooms:new Set([this.id]),except:new Set,flags:p});else this.notifyOutgoingListeners(c),this.packet(c,p);return!0}emitWithAck(n,...i){let o=this.flags.timeout!==void 0;return new Promise((c,p)=>{i.push((a,x)=>{if(o)return a?p(a):c(x);else return c(a)}),this.emit(n,...i)})}registerAckCallback(n,i){let o=this.flags.timeout;if(o===void 0){this.acks.set(n,i);return}let c=setTimeout(()=>{Wi("event with ack id %d has timed out after %d ms",n,o),this.acks.delete(n),i.call(this,new Error("operation has timed out"))},o);this.acks.set(n,(...p)=>{clearTimeout(c),i.apply(this,[null,...p])})}to(n){return this.newBroadcastOperator().to(n)}in(n){return this.newBroadcastOperator().in(n)}except(n){return this.newBroadcastOperator().except(n)}send(...n){return this.emit("message",...n),this}write(...n){return this.emit("message",...n),this}packet(n,i={}){n.nsp=this.nsp.name,i.compress=i.compress!==!1,this.client._packet(n,i)}join(n){return Wi("join room %s",n),this.adapter.addAll(this.id,new Set(Array.isArray(n)?n:[n]))}leave(n){return Wi("leave room %s",n),this.adapter.del(this.id,n)}leaveAll(){this.adapter.delAll(this.id)}_onconnect(){if(Wi("socket connected - writing packet"),this.connected=!0,this.join(this.id),this.conn.protocol===3)this.packet({type:oo.PacketType.CONNECT});else this.packet({type:oo.PacketType.CONNECT,data:{sid:this.id,pid:this.pid}})}_onpacket(n){switch(Wi("got packet %j",n),n.type){case oo.PacketType.EVENT:this.onevent(n);break;case oo.PacketType.BINARY_EVENT:this.onevent(n);break;case oo.PacketType.ACK:this.onack(n);break;case oo.PacketType.BINARY_ACK:this.onack(n);break;case oo.PacketType.DISCONNECT:this.ondisconnect();break}}onevent(n){let i=n.data||[];if(Wi("emitting event %j",i),n.id!=null)Wi("attaching ack callback to event"),i.push(this.ack(n.id));if(this._anyListeners&&this._anyListeners.length){let o=this._anyListeners.slice();for(let c of o)c.apply(this,i)}this.dispatch(i)}ack(n){let i=this,o=!1;return function(){if(o)return;let c=Array.prototype.slice.call(arguments);Wi("sending ack %j",c),i.packet({id:n,type:oo.PacketType.ACK,data:c}),o=!0}}onack(n){let i=this.acks.get(n.id);if(typeof i=="function")Wi("calling ack %s with %j",n.id,n.data),i.apply(this,n.data),this.acks.delete(n.id);else Wi("bad ack %s",n.id)}ondisconnect(){Wi("got disconnect packet"),this._onclose("client namespace disconnect")}_onerror(n){this.emitReserved("error",n)}_onclose(n,i){if(!this.connected)return this;if(Wi("closing socket - reason %s",n),this.emitReserved("disconnecting",n,i),this.server._opts.connectionStateRecovery&&BX.has(n))Wi("connection state recovery is enabled for sid %s",this.id),this.adapter.persistSession({sid:this.id,pid:this.pid,rooms:[...this.rooms],data:this.data});this._cleanup(),this.client._remove(this),this.connected=!1,this.emitReserved("disconnect",n,i);return}_cleanup(){this.leaveAll(),this.nsp._remove(this),this.join=fM}_error(n){this.packet({type:oo.PacketType.CONNECT_ERROR,data:n})}disconnect(n=!1){if(!this.connected)return this;if(n)this.client._disconnect();else this.packet({type:oo.PacketType.DISCONNECT}),this._onclose("server namespace disconnect");return this}compress(n){return this.flags.compress=n,this}get volatile(){return this.flags.volatile=!0,this}get broadcast(){return this.newBroadcastOperator()}get local(){return this.newBroadcastOperator().local}timeout(n){return this.flags.timeout=n,this}dispatch(n){Wi("dispatching an event %j",n),this.run(n,(i)=>{process.nextTick(()=>{if(i)return this._onerror(i);if(this.connected)super.emitUntyped.apply(this,n);else Wi("ignore packet received after disconnection")})})}use(n){return this.fns.push(n),this}run(n,i){if(!this.fns.length)return i();let o=this.fns.slice(0);function c(p){o[p](n,(a)=>{if(a)return i(a);if(!o[p+1])return i();c(p+1)})}c(0)}get disconnected(){return!this.connected}get request(){return this.client.request}get conn(){return this.client.conn}get rooms(){return this.adapter.socketRooms(this.id)||new Set}onAny(n){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(n),this}prependAny(n){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(n),this}offAny(n){if(!this._anyListeners)return this;if(n){let i=this._anyListeners;for(let o=0;o<i.length;o++)if(n===i[o])return i.splice(o,1),this}else this._anyListeners=[];return this}listenersAny(){return this._anyListeners||[]}onAnyOutgoing(n){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.push(n),this}prependAnyOutgoing(n){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.unshift(n),this}offAnyOutgoing(n){if(!this._anyOutgoingListeners)return this;if(n){let i=this._anyOutgoingListeners;for(let o=0;o<i.length;o++)if(n===i[o])return i.splice(o,1),this}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(n){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length){let i=this._anyOutgoingListeners.slice();for(let o of i)o.apply(this,n.data)}}newBroadcastOperator(){let n=Object.assign({},this.flags);return this.flags={},new jX.BroadcastOperator(this.adapter,new Set,new Set([this.id]),n)}}Hp.Socket=$M});var Sv=h((Do)=>{var LX=Do&&Do.__importDefault||function(n){return n&&n.__esModule?n:{default:n}};Object.defineProperty(Do,"__esModule",{value:!0});Do.Namespace=Do.RESERVED_EVENTS=void 0;var TM=Jv(),NX=Qm(),DX=LX(xi()),hi=wv(),Ba=DX.default("socket.io:namespace");Do.RESERVED_EVENTS=new Set(["connect","connection","new_namespace"]);class wM extends NX.StrictEventEmitter{constructor(n,i){super();this.sockets=new Map,this._preConnectSockets=new Map,this._fns=[],this._ids=0,this.server=n,this.name=i,this._initAdapter()}_initAdapter(){this.adapter=new(this.server.adapter())(this)}use(n){return this._fns.push(n),this}run(n,i){if(!this._fns.length)return i();let o=this._fns.slice(0);function c(p){o[p](n,(a)=>{if(a)return i(a);if(!o[p+1])return i();c(p+1)})}c(0)}to(n){return new hi.BroadcastOperator(this.adapter).to(n)}in(n){return new hi.BroadcastOperator(this.adapter).in(n)}except(n){return new hi.BroadcastOperator(this.adapter).except(n)}async _add(n,i,o){var c;Ba("adding socket to nsp %s",this.name);let p=await this._createSocket(n,i);if(this._preConnectSockets.set(p.id,p),((c=this.server.opts.connectionStateRecovery)===null||c===void 0?void 0:c.skipMiddlewares)&&p.recovered&&n.conn.readyState==="open")return this._doConnect(p,o);this.run(p,(a)=>{process.nextTick(()=>{if(n.conn.readyState!=="open"){Ba("next called after client was closed - ignoring socket"),p._cleanup();return}if(a)if(Ba("middleware error, sending CONNECT_ERROR packet to the client"),p._cleanup(),n.conn.protocol===3)return p._error(a.data||a.message);else return p._error({message:a.message,data:a.data});this._doConnect(p,o)})})}async _createSocket(n,i){let{pid:o,offset:c}=i;if(this.server.opts.connectionStateRecovery&&typeof o==="string"&&typeof c==="string"){let p;try{p=await this.adapter.restoreSession(o,c)}catch(a){Ba("error while restoring session: %s",a)}if(p)return Ba("connection state recovered for sid %s",p.sid),new TM.Socket(this,n,i,p)}return new TM.Socket(this,n,i)}_doConnect(n,i){if(this._preConnectSockets.delete(n.id),this.sockets.set(n.id,n),n._onconnect(),i)i(n);this.emitReserved("connect",n),this.emitReserved("connection",n)}_remove(n){this.sockets.delete(n.id)||this._preConnectSockets.delete(n.id)}emit(n,...i){return new hi.BroadcastOperator(this.adapter).emit(n,...i)}send(...n){return this.emit("message",...n),this}write(...n){return this.emit("message",...n),this}serverSideEmit(n,...i){if(Do.RESERVED_EVENTS.has(n))throw new Error(`"${String(n)}" is a reserved event name`);return i.unshift(n),this.adapter.serverSideEmit(i),!0}serverSideEmitWithAck(n,...i){return new Promise((o,c)=>{i.push((p,a)=>{if(p)return p.responses=a,c(p);else return o(a)}),this.serverSideEmit(n,...i)})}_onServerSideEmit(n){super.emitUntyped.apply(this,n)}allSockets(){return new hi.BroadcastOperator(this.adapter).allSockets()}compress(n){return new hi.BroadcastOperator(this.adapter).compress(n)}get volatile(){return new hi.BroadcastOperator(this.adapter).volatile}get local(){return new hi.BroadcastOperator(this.adapter).local}timeout(n){return new hi.BroadcastOperator(this.adapter).timeout(n)}fetchSockets(){return new hi.BroadcastOperator(this.adapter).fetchSockets()}socketsJoin(n){return new hi.BroadcastOperator(this.adapter).socketsJoin(n)}socketsLeave(n){return new hi.BroadcastOperator(this.adapter).socketsLeave(n)}disconnectSockets(n=!1){return new hi.BroadcastOperator(this.adapter).disconnectSockets(n)}}Do.Namespace=wM});var WM=h((MM)=>{Object.defineProperty(MM,"__esModule",{value:!0});MM.yeast=MM.decode=MM.encode=void 0;var AM="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_".split(""),Hm=64,FM={},JM=0,$c=0,SM;function Av(n){let i="";do i=AM[n%Hm]+i,n=Math.floor(n/Hm);while(n>0);return i}MM.encode=Av;function CX(n){let i=0;for($c=0;$c<n.length;$c++)i=i*Hm+FM[n.charAt($c)];return i}MM.decode=CX;function hX(){let n=Av(+new Date);if(n!==SM)return JM=0,SM=n;return n+"."+Av(JM++)}MM.yeast=hX;for(;$c<Hm;$c++)FM[AM[$c]]=$c});var Rv=h((XM)=>{var Fv;Object.defineProperty(XM,"__esModule",{value:!0});XM.SessionAwareAdapter=XM.Adapter=void 0;var sX=import.meta.require("events"),ZX=WM(),Em=import.meta.require("ws"),tX=typeof((Fv=Em===null||Em===void 0?void 0:Em.Sender)===null||Fv===void 0?void 0:Fv.frame)==="function";class Mv extends sX.EventEmitter{constructor(n){super();this.nsp=n,this.rooms=new Map,this.sids=new Map,this.encoder=n.server.encoder}init(){}close(){}serverCount(){return Promise.resolve(1)}addAll(n,i){if(!this.sids.has(n))this.sids.set(n,new Set);for(let o of i){if(this.sids.get(n).add(o),!this.rooms.has(o))this.rooms.set(o,new Set),this.emit("create-room",o);if(!this.rooms.get(o).has(n))this.rooms.get(o).add(n),this.emit("join-room",o,n)}}del(n,i){if(this.sids.has(n))this.sids.get(n).delete(i);this._del(i,n)}_del(n,i){let o=this.rooms.get(n);if(o!=null){if(o.delete(i))this.emit("leave-room",n,i);if(o.size===0&&this.rooms.delete(n))this.emit("delete-room",n)}}delAll(n){if(!this.sids.has(n))return;for(let i of this.sids.get(n))this._del(i,n);this.sids.delete(n)}broadcast(n,i){let o=i.flags||{},c={preEncoded:!0,volatile:o.volatile,compress:o.compress};n.nsp=this.nsp.name;let p=this._encode(n,c);this.apply(i,(a)=>{if(typeof a.notifyOutgoingListeners==="function")a.notifyOutgoingListeners(n);a.client.writeToEngine(p,c)})}broadcastWithAck(n,i,o,c){let p=i.flags||{},a={preEncoded:!0,volatile:p.volatile,compress:p.compress};n.nsp=this.nsp.name,n.id=this.nsp._ids++;let x=this._encode(n,a),m=0;this.apply(i,(l)=>{if(m++,l.acks.set(n.id,c),typeof l.notifyOutgoingListeners==="function")l.notifyOutgoingListeners(n);l.client.writeToEngine(x,a)}),o(m)}_encode(n,i){let o=this.encoder.encode(n);if(tX&&o.length===1&&typeof o[0]==="string"){let c=Buffer.from("4"+o[0]);i.wsPreEncodedFrame=Em.Sender.frame(c,{readOnly:!1,mask:!1,rsv1:!1,opcode:1,fin:!0})}return o}sockets(n){let i=new Set;return this.apply({rooms:n},(o)=>{i.add(o.id)}),Promise.resolve(i)}socketRooms(n){return this.sids.get(n)}fetchSockets(n){let i=[];return this.apply(n,(o)=>{i.push(o)}),Promise.resolve(i)}addSockets(n,i){this.apply(n,(o)=>{o.join(i)})}delSockets(n,i){this.apply(n,(o)=>{i.forEach((c)=>o.leave(c))})}disconnectSockets(n,i){this.apply(n,(o)=>{o.disconnect(i)})}apply(n,i){let o=n.rooms,c=this.computeExceptSids(n.except);if(o.size){let p=new Set;for(let a of o){if(!this.rooms.has(a))continue;for(let x of this.rooms.get(a)){if(p.has(x)||c.has(x))continue;let m=this.nsp.sockets.get(x);if(m)i(m),p.add(x)}}}else for(let[p]of this.sids){if(c.has(p))continue;let a=this.nsp.sockets.get(p);if(a)i(a)}}computeExceptSids(n){let i=new Set;if(n&&n.size>0){for(let o of n)if(this.rooms.has(o))this.rooms.get(o).forEach((c)=>i.add(c))}return i}serverSideEmit(n){console.warn("this adapter does not support the serverSideEmit() functionality")}persistSession(n){}restoreSession(n,i){return null}}XM.Adapter=Mv;class KM extends Mv{constructor(n){super(n);this.nsp=n,this.sessions=new Map,this.packets=[],this.maxDisconnectionDuration=n.server.opts.connectionStateRecovery.maxDisconnectionDuration,setInterval(()=>{let o=Date.now()-this.maxDisconnectionDuration;this.sessions.forEach((c,p)=>{if(c.disconnectedAt<o)this.sessions.delete(p)});for(let c=this.packets.length-1;c>=0;c--)if(this.packets[c].emittedAt<o){this.packets.splice(0,c+1);break}},60000).unref()}persistSession(n){n.disconnectedAt=Date.now(),this.sessions.set(n.pid,n)}restoreSession(n,i){let o=this.sessions.get(n);if(!o)return null;if(o.disconnectedAt+this.maxDisconnectionDuration<Date.now())return this.sessions.delete(n),null;let p=this.packets.findIndex((x)=>x.id===i);if(p===-1)return null;let a=[];for(let x=p+1;x<this.packets.length;x++){let m=this.packets[x];if(qX(o.rooms,m.opts))a.push(m.data)}return Promise.resolve(Object.assign(Object.assign({},o),{missedPackets:a}))}broadcast(n,i){var o;let c=n.type===2,p=n.id===void 0,a=((o=i.flags)===null||o===void 0?void 0:o.volatile)===void 0;if(c&&p&&a){let x=ZX.yeast();n.data.push(x),this.packets.push({id:x,opts:i,data:n.data,emittedAt:Date.now()})}super.broadcast(n,i)}}XM.SessionAwareAdapter=KM;function qX(n,i){let o=i.rooms.size===0||n.some((p)=>i.rooms.has(p)),c=n.every((p)=>!i.except.has(p));return o&&c}});var zM=h((Fo)=>{var rX=Fo&&Fo.__rest||function(n,i){var o={};for(var c in n)if(Object.prototype.hasOwnProperty.call(n,c)&&i.indexOf(c)<0)o[c]=n[c];if(n!=null&&typeof Object.getOwnPropertySymbols==="function"){for(var p=0,c=Object.getOwnPropertySymbols(n);p<c.length;p++)if(i.indexOf(c[p])<0&&Object.prototype.propertyIsEnumerable.call(n,c[p]))o[c[p]]=n[c[p]]}return o};Object.defineProperty(Fo,"__esModule",{value:!0});Fo.ClusterAdapterWithHeartbeat=Fo.ClusterAdapter=Fo.MessageType=void 0;var gX=Rv(),dX=xi(),eX=import.meta.require("crypto"),Pn=dX.debug("socket.io-adapter"),n5="emitter",Om=5000;function Op(){return eX.randomBytes(8).toString("hex")}var an;(function(n){n[n.INITIAL_HEARTBEAT=1]="INITIAL_HEARTBEAT",n[n.HEARTBEAT=2]="HEARTBEAT",n[n.BROADCAST=3]="BROADCAST",n[n.SOCKETS_JOIN=4]="SOCKETS_JOIN",n[n.SOCKETS_LEAVE=5]="SOCKETS_LEAVE",n[n.DISCONNECT_SOCKETS=6]="DISCONNECT_SOCKETS",n[n.FETCH_SOCKETS=7]="FETCH_SOCKETS",n[n.FETCH_SOCKETS_RESPONSE=8]="FETCH_SOCKETS_RESPONSE",n[n.SERVER_SIDE_EMIT=9]="SERVER_SIDE_EMIT",n[n.SERVER_SIDE_EMIT_RESPONSE=10]="SERVER_SIDE_EMIT_RESPONSE",n[n.BROADCAST_CLIENT_COUNT=11]="BROADCAST_CLIENT_COUNT",n[n.BROADCAST_ACK=12]="BROADCAST_ACK",n[n.ADAPTER_CLOSE=13]="ADAPTER_CLOSE"})(an=Fo.MessageType||(Fo.MessageType={}));function jc(n){return{rooms:[...n.rooms],except:[...n.except],flags:n.flags}}function Ep(n){return{rooms:new Set(n.rooms),except:new Set(n.except),flags:n.flags}}class Wv extends gX.Adapter{constructor(n){super(n);this.requests=new Map,this.ackRequests=new Map,this.uid=Op()}onMessage(n,i){if(n.uid===this.uid)return Pn("[%s] ignore message from self",this.uid);switch(Pn("[%s] new event of type %d from %s",this.uid,n.type,n.uid),n.type){case an.BROADCAST:{if(n.data.requestId!==void 0)super.broadcastWithAck(n.data.packet,Ep(n.data.opts),(c)=>{Pn("[%s] waiting for %d client acknowledgements",this.uid,c),this.publishResponse(n.uid,{type:an.BROADCAST_CLIENT_COUNT,data:{requestId:n.data.requestId,clientCount:c}})},(c)=>{Pn("[%s] received acknowledgement with value %j",this.uid,c),this.publishResponse(n.uid,{type:an.BROADCAST_ACK,data:{requestId:n.data.requestId,packet:c}})});else{let c=n.data.packet,p=Ep(n.data.opts);this.addOffsetIfNecessary(c,p,i),super.broadcast(c,p)}break}case an.SOCKETS_JOIN:super.addSockets(Ep(n.data.opts),n.data.rooms);break;case an.SOCKETS_LEAVE:super.delSockets(Ep(n.data.opts),n.data.rooms);break;case an.DISCONNECT_SOCKETS:super.disconnectSockets(Ep(n.data.opts),n.data.close);break;case an.FETCH_SOCKETS:{Pn("[%s] calling fetchSockets with opts %j",this.uid,n.data.opts),super.fetchSockets(Ep(n.data.opts)).then((o)=>{this.publishResponse(n.uid,{type:an.FETCH_SOCKETS_RESPONSE,data:{requestId:n.data.requestId,sockets:o.map((c)=>{let p=c.handshake,{sessionStore:a}=p,x=rX(p,["sessionStore"]);return{id:c.id,handshake:x,rooms:[...c.rooms],data:c.data}})}})});break}case an.SERVER_SIDE_EMIT:{let o=n.data.packet;if(n.data.requestId===void 0){this.nsp._onServerSideEmit(o);return}let p=!1,a=(x)=>{if(p)return;p=!0,Pn("[%s] calling acknowledgement with %j",this.uid,x),this.publishResponse(n.uid,{type:an.SERVER_SIDE_EMIT_RESPONSE,data:{requestId:n.data.requestId,packet:x}})};this.nsp._onServerSideEmit([...o,a]);break}case an.BROADCAST_CLIENT_COUNT:case an.BROADCAST_ACK:case an.FETCH_SOCKETS_RESPONSE:case an.SERVER_SIDE_EMIT_RESPONSE:this.onResponse(n);break;default:Pn("[%s] unknown message type: %s",this.uid,n.type)}}onResponse(n){var i,o;let c=n.data.requestId;switch(Pn("[%s] received response %s to request %s",this.uid,n.type,c),n.type){case an.BROADCAST_CLIENT_COUNT:{(i=this.ackRequests.get(c))===null||i===void 0||i.clientCountCallback(n.data.clientCount);break}case an.BROADCAST_ACK:{(o=this.ackRequests.get(c))===null||o===void 0||o.ack(n.data.packet);break}case an.FETCH_SOCKETS_RESPONSE:{let p=this.requests.get(c);if(!p)return;if(p.current++,n.data.sockets.forEach((a)=>p.responses.push(a)),p.current===p.expected)clearTimeout(p.timeout),p.resolve(p.responses),this.requests.delete(c);break}case an.SERVER_SIDE_EMIT_RESPONSE:{let p=this.requests.get(c);if(!p)return;if(p.current++,p.responses.push(n.data.packet),p.current===p.expected)clearTimeout(p.timeout),p.resolve(null,p.responses),this.requests.delete(c);break}default:Pn("[%s] unknown response type: %s",this.uid,n.type)}}async broadcast(n,i){var o;if(!((o=i.flags)===null||o===void 0?void 0:o.local))try{let p=await this.publishAndReturnOffset({type:an.BROADCAST,data:{packet:n,opts:jc(i)}});this.addOffsetIfNecessary(n,i,p)}catch(p){return Pn("[%s] error while broadcasting message: %s",this.uid,p.message)}super.broadcast(n,i)}addOffsetIfNecessary(n,i,o){var c;if(!this.nsp.server.opts.connectionStateRecovery)return;let p=n.type===2,a=n.id===void 0,x=((c=i.flags)===null||c===void 0?void 0:c.volatile)===void 0;if(p&&a&&x)n.data.push(o)}broadcastWithAck(n,i,o,c){var p;if(!((p=i===null||i===void 0?void 0:i.flags)===null||p===void 0?void 0:p.local)){let x=Op();this.ackRequests.set(x,{clientCountCallback:o,ack:c}),this.publish({type:an.BROADCAST,data:{packet:n,requestId:x,opts:jc(i)}}),setTimeout(()=>{this.ackRequests.delete(x)},i.flags.timeout)}super.broadcastWithAck(n,i,o,c)}async addSockets(n,i){var o;if(!((o=n.flags)===null||o===void 0?void 0:o.local))try{await this.publishAndReturnOffset({type:an.SOCKETS_JOIN,data:{opts:jc(n),rooms:i}})}catch(p){Pn("[%s] error while publishing message: %s",this.uid,p.message)}super.addSockets(n,i)}async delSockets(n,i){var o;if(!((o=n.flags)===null||o===void 0?void 0:o.local))try{await this.publishAndReturnOffset({type:an.SOCKETS_LEAVE,data:{opts:jc(n),rooms:i}})}catch(p){Pn("[%s] error while publishing message: %s",this.uid,p.message)}super.delSockets(n,i)}async disconnectSockets(n,i){var o;if(!((o=n.flags)===null||o===void 0?void 0:o.local))try{await this.publishAndReturnOffset({type:an.DISCONNECT_SOCKETS,data:{opts:jc(n),close:i}})}catch(p){Pn("[%s] error while publishing message: %s",this.uid,p.message)}super.disconnectSockets(n,i)}async fetchSockets(n){var i;let[o,c]=await Promise.all([super.fetchSockets(n),this.serverCount()]),p=c-1;if(((i=n.flags)===null||i===void 0?void 0:i.local)||p<=0)return o;let a=Op();return new Promise((x,m)=>{let l=setTimeout(()=>{let v=this.requests.get(a);if(v)m(new Error(`timeout reached: only ${v.current} responses received out of ${v.expected}`)),this.requests.delete(a)},n.flags.timeout||Om),f={type:an.FETCH_SOCKETS,resolve:x,timeout:l,current:0,expected:p,responses:o};this.requests.set(a,f),this.publish({type:an.FETCH_SOCKETS,data:{opts:jc(n),requestId:a}})})}async serverSideEmit(n){if(typeof n[n.length-1]!=="function")return this.publish({type:an.SERVER_SIDE_EMIT,data:{packet:n}});let o=n.pop(),c=await this.serverCount()-1;if(Pn('[%s] waiting for %d responses to "serverSideEmit" request',this.uid,c),c<=0)return o(null,[]);let p=Op(),a=setTimeout(()=>{let m=this.requests.get(p);if(m)o(new Error(`timeout reached: only ${m.current} responses received out of ${m.expected}`),m.responses),this.requests.delete(p)},Om),x={type:an.SERVER_SIDE_EMIT,resolve:o,timeout:a,current:0,expected:c,responses:[]};this.requests.set(p,x),this.publish({type:an.SERVER_SIDE_EMIT,data:{requestId:p,packet:n}})}publish(n){this.publishAndReturnOffset(n).catch((i)=>{Pn("[%s] error while publishing message: %s",this.uid,i)})}publishAndReturnOffset(n){return n.uid=this.uid,n.nsp=this.nsp.name,this.doPublish(n)}publishResponse(n,i){i.uid=this.uid,i.nsp=this.nsp.name,this.doPublishResponse(n,i).catch((o)=>{Pn("[%s] error while publishing response: %s",this.uid,o)})}}Fo.ClusterAdapter=Wv;class YM extends Wv{constructor(n,i){super(n);this.nodesMap=new Map,this.customRequests=new Map,this._opts=Object.assign({heartbeatInterval:5000,heartbeatTimeout:1e4},i),this.cleanupTimer=setInterval(()=>{let o=Date.now();this.nodesMap.forEach((c,p)=>{if(o-c>this._opts.heartbeatTimeout)Pn("[%s] node %s seems down",this.uid,p),this.removeNode(p)})},1000)}init(){this.publish({type:an.INITIAL_HEARTBEAT})}scheduleHeartbeat(){if(this.heartbeatTimer)this.heartbeatTimer.refresh();else this.heartbeatTimer=setTimeout(()=>{this.publish({type:an.HEARTBEAT})},this._opts.heartbeatInterval)}close(){if(this.publish({type:an.ADAPTER_CLOSE}),clearTimeout(this.heartbeatTimer),this.cleanupTimer)clearInterval(this.cleanupTimer)}onMessage(n,i){if(n.uid===this.uid)return Pn("[%s] ignore message from self",this.uid);if(n.uid&&n.uid!==n5)this.nodesMap.set(n.uid,Date.now());switch(Pn("[%s] new event of type %d from %s",this.uid,n.type,n.uid),n.type){case an.INITIAL_HEARTBEAT:this.publish({type:an.HEARTBEAT});break;case an.HEARTBEAT:break;case an.ADAPTER_CLOSE:this.removeNode(n.uid);break;default:super.onMessage(n,i)}}serverCount(){return Promise.resolve(1+this.nodesMap.size)}publish(n){return this.scheduleHeartbeat(),super.publish(n)}async serverSideEmit(n){if(typeof n[n.length-1]!=="function")return this.publish({type:an.SERVER_SIDE_EMIT,data:{packet:n}});let o=n.pop(),c=this.nodesMap.size;if(Pn('[%s] waiting for %d responses to "serverSideEmit" request',this.uid,c),c<=0)return o(null,[]);let p=Op(),a=setTimeout(()=>{let m=this.customRequests.get(p);if(m)o(new Error(`timeout reached: missing ${m.missingUids.size} responses`),m.responses),this.customRequests.delete(p)},Om),x={type:an.SERVER_SIDE_EMIT,resolve:o,timeout:a,missingUids:new Set([...this.nodesMap.keys()]),responses:[]};this.customRequests.set(p,x),this.publish({type:an.SERVER_SIDE_EMIT,data:{requestId:p,packet:n}})}async fetchSockets(n){var i;let[o,c]=await Promise.all([super.fetchSockets({rooms:n.rooms,except:n.except,flags:{local:!0}}),this.serverCount()]),p=c-1;if(((i=n.flags)===null||i===void 0?void 0:i.local)||p<=0)return o;let a=Op();return new Promise((x,m)=>{let l=setTimeout(()=>{let v=this.customRequests.get(a);if(v)m(new Error(`timeout reached: missing ${v.missingUids.size} responses`)),this.customRequests.delete(a)},n.flags.timeout||Om),f={type:an.FETCH_SOCKETS,resolve:x,timeout:l,missingUids:new Set([...this.nodesMap.keys()]),responses:o};this.customRequests.set(a,f),this.publish({type:an.FETCH_SOCKETS,data:{opts:jc(n),requestId:a}})})}onResponse(n){let i=n.data.requestId;switch(Pn("[%s] received response %s to request %s",this.uid,n.type,i),n.type){case an.FETCH_SOCKETS_RESPONSE:{let o=this.customRequests.get(i);if(!o)return;if(n.data.sockets.forEach((c)=>o.responses.push(c)),o.missingUids.delete(n.uid),o.missingUids.size===0)clearTimeout(o.timeout),o.resolve(o.responses),this.customRequests.delete(i);break}case an.SERVER_SIDE_EMIT_RESPONSE:{let o=this.customRequests.get(i);if(!o)return;if(o.responses.push(n.data.packet),o.missingUids.delete(n.uid),o.missingUids.size===0)clearTimeout(o.timeout),o.resolve(null,o.responses),this.customRequests.delete(i);break}default:super.onResponse(n)}}removeNode(n){this.customRequests.forEach((i,o)=>{if(i.missingUids.delete(n),i.missingUids.size===0){if(clearTimeout(i.timeout),i.type===an.FETCH_SOCKETS)i.resolve(i.responses);else if(i.type===an.SERVER_SIDE_EMIT)i.resolve(null,i.responses);this.customRequests.delete(o)}}),this.nodesMap.delete(n)}}Fo.ClusterAdapterWithHeartbeat=YM});var Um=h((yc)=>{Object.defineProperty(yc,"__esModule",{value:!0});yc.MessageType=yc.ClusterAdapterWithHeartbeat=yc.ClusterAdapter=yc.SessionAwareAdapter=yc.Adapter=void 0;var QM=Rv();Object.defineProperty(yc,"Adapter",{enumerable:!0,get:function(){return QM.Adapter}});Object.defineProperty(yc,"SessionAwareAdapter",{enumerable:!0,get:function(){return QM.SessionAwareAdapter}});var Kv=zM();Object.defineProperty(yc,"ClusterAdapter",{enumerable:!0,get:function(){return Kv.ClusterAdapter}});Object.defineProperty(yc,"ClusterAdapterWithHeartbeat",{enumerable:!0,get:function(){return Kv.ClusterAdapterWithHeartbeat}});Object.defineProperty(yc,"MessageType",{enumerable:!0,get:function(){return Kv.MessageType}})});var UM=h((Up)=>{var o5=Up&&Up.__importDefault||function(n){return n&&n.__esModule?n:{default:n}};Object.defineProperty(Up,"__esModule",{value:!0});Up.ParentNamespace=void 0;var HM=Sv(),c5=Um(),p5=o5(xi()),EM=p5.default("socket.io:parent-namespace");class Vm extends HM.Namespace{constructor(n){super(n,"/_"+Vm.count++);this.children=new Set}_initAdapter(){this.adapter=new OM(this)}emit(n,...i){return this.children.forEach((o)=>{o.emit(n,...i)}),!0}createChild(n){EM("creating child namespace %s",n);let i=new HM.Namespace(this.server,n);if(this._fns.forEach((o)=>i.use(o)),this.listeners("connect").forEach((o)=>i.on("connect",o)),this.listeners("connection").forEach((o)=>i.on("connection",o)),this.children.add(i),this.server._opts.cleanupEmptyChildNamespaces){let o=i._remove;i._remove=(c)=>{if(o.call(i,c),i.sockets.size===0)EM("closing child namespace %s",n),i.adapter.close(),this.server._nsps.delete(i.name),this.children.delete(i)}}return this.server._nsps.set(n,i),this.server.sockets.emitReserved("new_namespace",i),i}fetchSockets(){throw new Error("fetchSockets() is not supported on parent namespaces")}}Up.ParentNamespace=Vm;Vm.count=0;class OM extends c5.Adapter{broadcast(n,i){this.nsp.children.forEach((o)=>{o.adapter.broadcast(n,i)})}}});var yM=h((Lc)=>{var a5=Lc&&Lc.__importDefault||function(n){return n&&n.__esModule?n:{default:n}};Object.defineProperty(Lc,"__esModule",{value:!0});Lc.patchAdapter=m5;Lc.restoreAdapter=l5;Lc.serveFile=v5;var Bc=Um(),VM=import.meta.require("fs"),x5=a5(xi()),um=x5.default("socket.io:adapter-uws"),Xv="\x1F",{addAll:_M,del:bM,broadcast:jM}=Bc.Adapter.prototype;function m5(n){Bc.Adapter.prototype.addAll=function(i,o){let c=!this.sids.has(i);_M.call(this,i,o);let p=this.nsp.sockets.get(i)||this.nsp._preConnectSockets.get(i);if(!p)return;if(p.conn.transport.name==="websocket"){uM(this.nsp.name,p,c,o);return}if(c)p.conn.on("upgrade",()=>{let a=this.sids.get(i);if(a)uM(this.nsp.name,p,c,a)})},Bc.Adapter.prototype.del=function(i,o){bM.call(this,i,o);let c=this.nsp.sockets.get(i)||this.nsp._preConnectSockets.get(i);if(c&&c.conn.transport.name==="websocket"){let p=c.conn.id,a=c.conn.transport.socket,x=`${this.nsp.name}${Xv}${o}`;um("unsubscribe connection %s from topic %s",p,x),a.unsubscribe(x)}},Bc.Adapter.prototype.broadcast=function(i,o){if(!(o.rooms.size<=1&&o.except.size===0)){jM.call(this,i,o);return}let p=o.flags||{},a={preEncoded:!0,volatile:p.volatile,compress:p.compress};i.nsp=this.nsp.name;let x=this.encoder.encode(i),m=o.rooms.size===0?this.nsp.name:`${this.nsp.name}${Xv}${o.rooms.keys().next().value}`;um("fast publish to %s",m),x.forEach((l)=>{let f=typeof l!=="string";n.publish(m,f?l:"4"+l,f)}),this.apply(o,(l)=>{if(l.conn.transport.name!=="websocket")l.client.writeToEngine(x,a)})}}function uM(n,i,o,c){let p=i.conn.id,a=i.conn.transport.socket;if(o)um("subscribe connection %s to topic %s",p,n),a.subscribe(n);c.forEach((x)=>{let m=`${n}${Xv}${x}`;um("subscribe connection %s to topic %s",p,m),a.subscribe(m)})}function l5(){Bc.Adapter.prototype.addAll=_M,Bc.Adapter.prototype.del=bM,Bc.Adapter.prototype.broadcast=jM}var f5=(n)=>{let{buffer:i,byteOffset:o,byteLength:c}=n;return i.slice(o,o+c)};function v5(n,i){let{size:o}=VM.statSync(i),c=VM.createReadStream(i),p=()=>!c.destroyed&&c.destroy(),a=(m)=>{throw p(),m},x=(m)=>{let l=f5(m);n.cork(()=>{let f=n.getWriteOffset(),[v,$]=n.tryEnd(l,o);if(!$&&!v)c.pause(),n.onWritable((T)=>{let[F,M]=n.tryEnd(l.slice(T-f),o);if(!M&&F)c.resume();return F})})};n.onAborted(p),c.on("data",x).on("error",a).on("end",p)}});var BM=h((dL,$5)=>{$5.exports={name:"socket.io",version:"4.8.1",description:"node.js realtime framework server",keywords:["realtime","framework","websocket","tcp","events","socket","io"],files:["dist/","client-dist/","wrapper.mjs","!**/*.tsbuildinfo"],directories:{doc:"docs/",example:"example/",lib:"lib/",test:"test/"},type:"commonjs",main:"./dist/index.js",exports:{types:"./dist/index.d.ts",import:"./wrapper.mjs",require:"./dist/index.js"},types:"./dist/index.d.ts",license:"MIT",homepage:"https://github.com/socketio/socket.io/tree/main/packages/socket.io#readme",repository:{type:"git",url:"git+https://github.com/socketio/socket.io.git"},bugs:{url:"https://github.com/socketio/socket.io/issues"},scripts:{compile:"rimraf ./dist && tsc",test:"npm run format:check && npm run compile && npm run test:types && npm run test:unit","test:types":"tsd","test:unit":"nyc mocha --require ts-node/register --reporter spec --slow 200 --bail --timeout 10000 test/index.ts","format:check":"prettier --check \"lib/**/*.ts\" \"test/**/*.ts\"","format:fix":"prettier --write \"lib/**/*.ts\" \"test/**/*.ts\"",prepack:"npm run compile"},dependencies:{accepts:"~1.3.4",base64id:"~2.0.0",cors:"~2.8.5",debug:"~4.3.2","engine.io":"~6.6.0","socket.io-adapter":"~2.5.2","socket.io-parser":"~4.2.4"},contributors:[{name:"Guillermo Rauch",email:"rauchg@gmail.com"},{name:"Arnout Kazemier",email:"info@3rd-eden.com"},{name:"Vladimir Dronnikov",email:"dronnikov@gmail.com"},{name:"Einar Otto Stangvik",email:"einaros@gmail.com"}],engines:{node:">=10.2.0"},tsd:{directory:"test"}}});var ZM=h((Ki,La)=>{var __dirname="/home/runner/work/wayforge/wayforge/node_modules/.pnpm/socket.io@4.8.1/node_modules/socket.io/dist",T5=Ki&&Ki.__createBinding||(Object.create?function(n,i,o,c){if(c===void 0)c=o;var p=Object.getOwnPropertyDescriptor(i,o);if(!p||("get"in p?!i.__esModule:p.writable||p.configurable))p={enumerable:!0,get:function(){return i[o]}};Object.defineProperty(n,c,p)}:function(n,i,o,c){if(c===void 0)c=o;n[c]=i[o]}),w5=Ki&&Ki.__setModuleDefault||(Object.create?function(n,i){Object.defineProperty(n,"default",{enumerable:!0,value:i})}:function(n,i){n.default=i}),J5=Ki&&Ki.__importStar||function(n){if(n&&n.__esModule)return n;var i={};if(n!=null){for(var o in n)if(o!=="default"&&Object.prototype.hasOwnProperty.call(n,o))T5(i,n,o)}return w5(i,n),i},kM=Ki&&Ki.__importDefault||function(n){return n&&n.__esModule?n:{default:n}};Object.defineProperty(Ki,"__esModule",{value:!0});Ki.Namespace=Ki.Socket=Ki.Server=void 0;var S5=import.meta.require("http"),A5=import.meta.require("fs"),Gv=import.meta.require("zlib"),F5=fm(),_m=import.meta.require("stream"),LM=import.meta.require("path"),NM=bF(),M5=nM(),DM=import.meta.require("events"),zv=Sv();Object.defineProperty(Ki,"Namespace",{enumerable:!0,get:function(){return zv.Namespace}});var R5=UM(),CM=Um(),W5=J5(ya()),K5=kM(xi()),sM=Jv();Object.defineProperty(Ki,"Socket",{enumerable:!0,get:function(){return sM.Socket}});var X5=Qm(),Yv=yM(),G5=kM(pv()),_i=K5.default("socket.io:server"),hM=BM().version,IM=/\.map/;class Vp extends X5.StrictEventEmitter{constructor(n,i={}){super();if(this._nsps=new Map,this.parentNsps=new Map,this.parentNamespacesFromRegExp=new Map,typeof n==="object"&&n instanceof Object&&!n.listen)i=n,n=void 0;if(this.path(i.path||"/socket.io"),this.connectTimeout(i.connectTimeout||45000),this.serveClient(i.serveClient!==!1),this._parser=i.parser||W5,this.encoder=new this._parser.Encoder,this.opts=i,i.connectionStateRecovery)i.connectionStateRecovery=Object.assign({maxDisconnectionDuration:120000,skipMiddlewares:!0},i.connectionStateRecovery),this.adapter(i.adapter||CM.SessionAwareAdapter);else this.adapter(i.adapter||CM.Adapter);if(i.cleanupEmptyChildNamespaces=!!i.cleanupEmptyChildNamespaces,this.sockets=this.of("/"),n||typeof n=="number")this.attach(n);if(this.opts.cors)this._corsMiddleware=G5.default(this.opts.cors)}get _opts(){return this.opts}serveClient(n){if(!arguments.length)return this._serveClient;return this._serveClient=n,this}_checkNamespace(n,i,o){if(this.parentNsps.size===0)return o(!1);let c=this.parentNsps.keys(),p=()=>{let a=c.next();if(a.done)return o(!1);a.value(n,i,(x,m)=>{if(x||!m)return p();if(this._nsps.has(n))return _i("dynamic namespace %s already exists",n),o(this._nsps.get(n));let l=this.parentNsps.get(a.value).createChild(n);_i("dynamic namespace %s was created",n),o(l)})};p()}path(n){if(!arguments.length)return this._path;this._path=n.replace(/\/$/,"");let i=this._path.replace(/[-\/\\^$*+?.()|[\]{}]/g,"\\$&");return this.clientPathRegex=new RegExp("^"+i+"/socket\\.io(\\.msgpack|\\.esm)?(\\.min)?\\.js(\\.map)?(?:\\?|$)"),this}connectTimeout(n){if(n===void 0)return this._connectTimeout;return this._connectTimeout=n,this}adapter(n){if(!arguments.length)return this._adapter;this._adapter=n;for(let i of this._nsps.values())i._initAdapter();return this}listen(n,i={}){return this.attach(n,i)}attach(n,i={}){if(typeof n=="function")throw new Error("You are trying to attach socket.io to an express request handler function. Please pass a http.Server instance.");if(Number(n)==n)n=Number(n);if(typeof n=="number"){_i("creating http server and binding to %d",n);let o=n;n=S5.createServer((c,p)=>{p.writeHead(404),p.end()}),n.listen(o)}return Object.assign(i,this.opts),i.path=i.path||this._path,this.initEngine(n,i),this}attachApp(n,i={}){Object.assign(i,this.opts),i.path=i.path||this._path,_i("creating uWebSockets.js-based engine with opts %j",i);let o=new NM.uServer(i);if(o.attach(n,i),this.bind(o),this._serveClient)n.get(`${this._path}/*`,(c,p)=>{if(!this.clientPathRegex.test(p.getUrl())){p.setYield(!0);return}let a=p.getUrl().replace(this._path,"").replace(/\?.*$/,"").replace(/^\//,""),x=IM.test(a),m=x?"map":"source",l='"'+hM+'"',f="W/"+l,v=p.getHeader("if-none-match");if(v){if(l===v||f===v){_i("serve client %s 304",m),c.writeStatus("304 Not Modified"),c.end();return}}_i("serve client %s",m),c.writeHeader("cache-control","public, max-age=0"),c.writeHeader("content-type","application/"+(x?"json":"javascript")+"; charset=utf-8"),c.writeHeader("etag",l);let $=LM.join(__dirname,"../client-dist/",a);Yv.serveFile(c,$)});Yv.patchAdapter(n)}initEngine(n,i){if(_i("creating engine.io instance with opts %j",i),this.eio=NM.attach(n,i),this._serveClient)this.attachServe(n);this.httpServer=n,this.bind(this.eio)}attachServe(n){_i("attaching client serving req handler");let i=n.listeners("request").slice(0);n.removeAllListeners("request"),n.on("request",(o,c)=>{if(this.clientPathRegex.test(o.url))if(this._corsMiddleware)this._corsMiddleware(o,c,()=>{this.serve(o,c)});else this.serve(o,c);else for(let p=0;p<i.length;p++)i[p].call(n,o,c)})}serve(n,i){let o=n.url.replace(this._path,"").replace(/\?.*$/,""),c=IM.test(o),p=c?"map":"source",a='"'+hM+'"',x="W/"+a,m=n.headers["if-none-match"];if(m){if(a===m||x===m){_i("serve client %s 304",p),i.writeHead(304),i.end();return}}_i("serve client %s",p),i.setHeader("Cache-Control","public, max-age=0"),i.setHeader("Content-Type","application/"+(c?"json":"javascript")+"; charset=utf-8"),i.setHeader("ETag",a),Vp.sendFile(o,n,i)}static sendFile(n,i,o){let c=A5.createReadStream(LM.join(__dirname,"../client-dist/",n)),p=F5(i).encodings(["br","gzip","deflate"]),a=(x)=>{if(x)o.end()};switch(p){case"br":o.writeHead(200,{"content-encoding":"br"}),_m.pipeline(c,Gv.createBrotliCompress(),o,a);break;case"gzip":o.writeHead(200,{"content-encoding":"gzip"}),_m.pipeline(c,Gv.createGzip(),o,a);break;case"deflate":o.writeHead(200,{"content-encoding":"deflate"}),_m.pipeline(c,Gv.createDeflate(),o,a);break;default:o.writeHead(200),_m.pipeline(c,o,a)}}bind(n){return this.engine=n,this.engine.on("connection",this.onconnection.bind(this)),this}onconnection(n){_i("incoming connection with id %s",n.id);let i=new M5.Client(this,n);if(n.protocol===3)i.connect("/");return this}of(n,i){if(typeof n==="function"||n instanceof RegExp){let c=new R5.ParentNamespace(this);if(_i("initializing parent namespace %s",c.name),typeof n==="function")this.parentNsps.set(n,c);else this.parentNsps.set((p,a,x)=>x(null,n.test(p)),c),this.parentNamespacesFromRegExp.set(n,c);if(i)c.on("connect",i);return c}if(String(n)[0]!=="/")n="/"+n;let o=this._nsps.get(n);if(!o){for(let[c,p]of this.parentNamespacesFromRegExp)if(c.test(n))return _i("attaching namespace %s to parent namespace %s",n,c),p.createChild(n);if(_i("initializing namespace %s",n),o=new zv.Namespace(this,n),this._nsps.set(n,o),n!=="/")this.sockets.emitReserved("new_namespace",o)}if(i)o.on("connect",i);return o}async close(n){if(await Promise.allSettled([...this._nsps.values()].map(async(i)=>{i.sockets.forEach((o)=>{o._onclose("server shutting down")}),await i.adapter.close()})),this.engine.close(),Yv.restoreAdapter(),this.httpServer)this.httpServer.close(n);else n&&n()}use(n){return this.sockets.use(n),this}to(n){return this.sockets.to(n)}in(n){return this.sockets.in(n)}except(n){return this.sockets.except(n)}send(...n){return this.sockets.emit("message",...n),this}write(...n){return this.sockets.emit("message",...n),this}serverSideEmit(n,...i){return this.sockets.serverSideEmit(n,...i)}serverSideEmitWithAck(n,...i){return this.sockets.serverSideEmitWithAck(n,...i)}allSockets(){return this.sockets.allSockets()}compress(n){return this.sockets.compress(n)}get volatile(){return this.sockets.volatile}get local(){return this.sockets.local}timeout(n){return this.sockets.timeout(n)}fetchSockets(){return this.sockets.fetchSockets()}socketsJoin(n){return this.sockets.socketsJoin(n)}socketsLeave(n){return this.sockets.socketsLeave(n)}disconnectSockets(n=!1){return this.sockets.disconnectSockets(n)}}Ki.Server=Vp;var Y5=Object.keys(DM.EventEmitter.prototype).filter(function(n){return typeof DM.EventEmitter.prototype[n]==="function"});Y5.forEach(function(n){Vp.prototype[n]=function(){return this.sockets[n].apply(this.sockets,arguments)}});La.exports=(n,i)=>new Vp(n,i);La.exports.Server=Vp;La.exports.Namespace=zv.Namespace;La.exports.Socket=sM.Socket});import{createHash as eR}from"crypto";import{createServer as bG}from"http";import{createServer as jG}from"https";function gc(n=Math.random){return n().toString(36).slice(2)}class ca extends Promise{fate;resolve;reject;done=!1;constructor(n){let i,o;super((c,p)=>{i=c,o=p});this.resolve=i,this.reject=o,this.use(n instanceof Promise?n:new Promise(n))}pass(n,i){if(n===this.fate)this.resolve(i),this.done=!0}fail(n,i){if(n===this.fate)this.reject(i),this.done=!0}use(n){if(n instanceof Promise){let i=n;this.fate=i,i.then((o)=>{this.pass(i,o)},(o)=>{this.fail(i,o)})}else this.resolve(n),this.fate=void 0}}function H$(n){return Object.entries(n)}var E$=(n,i,o=nn.STORE)=>{return pa(o,{key:`${n.key}:JSON`,get:({get:c})=>i.toJson(c(n)),set:({set:c},p)=>{c(n,i.fromJson(p))}})};function U(n){while(n.child!==null)n=n.child;return n}function O$(n){while(n.parent!==null)n=n.parent;return n}class xn{Subscriber;subscribers=new Map;subscribe(n,i){return this.subscribers.set(n,i),()=>{this.unsubscribe(n)}}unsubscribe(n){this.subscribers.delete(n)}next(n){let i=this.subscribers.values();for(let o of i)o(n)}}class $l extends xn{state;constructor(n){super();this.state=n}next(n){this.state=n,super.next(n)}}function so(n,i,o){let c={key:i.key,type:"atom_family"},p=n.families.get(i.key);if(p)n.logger.error("\u2757","atom_family",i.key,`Overwriting an existing ${mo(p)} "${p.key}" in store "${n.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);let a=new xn,m=Object.assign((l)=>{let f=r(l),v={key:i.key,subKey:f},$=`${i.key}(${f})`,T=U(n),F=i.default,M={key:$,default:F instanceof Function?F(l):F};if(i.effects)M.effects=i.effects(l);let A=Zo(T,M,v);return a.next({type:"state_creation",token:A}),A},c,{subject:a,install:(l)=>so(l,i),internalRoles:o});return n.families.set(i.key,m),n.defaults.set(i.key,i.default),c}function U$(n,i){if("mutable"in i)return aa(n,i);return so(n,i)}function to(n,i,o){let c={key:i.key,type:"readonly_selector_family"},p=n.families.get(i.key);if(p)n.logger.error("\u2757","readonly_selector_family",i.key,`Overwriting an existing ${mo(p)} "${p.key}" in store "${n.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);let a=new xn,m=Object.assign((l)=>{let f=r(l),v={key:i.key,subKey:f},$=`${i.key}(${f})`,T=U(n),F=xa(T,{key:$,get:i.get(l)},v);return a.next({type:"state_creation",token:F}),F},c,{internalRoles:o,subject:a,install:(l)=>to(l,i),default:(l)=>{return i.get(l)({get:(...v)=>Mn(n,...v),find:(v,$)=>Sn(n,v,$),seek:(v,$)=>Bn(n,v,$),json:(v)=>Zn(n,v)})}});return n.families.set(i.key,m),c}function Tl(n,i){if("set"in i)return ma(n,i);return to(n,i)}var n8={atom_family:"atom",mutable_atom_family:"mutable_atom",selector_family:"selector",readonly_selector_family:"readonly_selector",molecule_family:"molecule"};function dc(n,i){let o=r(i),c=`${n.key}(${o})`,p=n8[n.type],a={key:c,type:p};if(p==="molecule")Object.assign(a,{key:i,family:n});else Object.assign(a,{family:{key:n.key,subKey:o}});return Object.assign(a,{counterfeit:!0}),a}function si(n){let i={key:n.key,type:n.type};if("family"in n)i.family=n.family;return i}class yi{a;b;cardinality;relations=new Map;contents=new Map;isAType;isBType;isContent;makeContentKey=(n,i)=>`${n}:${i}`;warn;getRelatedKeys(n){return this.relations.get(n)}addRelation(n,i){let o=this.relations.get(n),c=this.relations.get(i);if(o)o.add(i);else o=new Set([i]),this.relations.set(n,o);if(c)c.add(n);else c=new Set([n]),this.relations.set(i,c)}deleteRelation(n,i){let o=this.relations.get(n);if(o){if(o.delete(i),o.size===0)this.relations.delete(n);let c=this.relations.get(i);if(c){if(c.delete(n),c.size===0)this.relations.delete(i)}}}replaceRelationsUnsafely(n,i){this.relations.set(n,new Set(i));for(let o of i){let c=new Set().add(n);this.relations.set(o,c)}}replaceRelationsSafely(n,i){let o=this.relations.get(n),c=this.isAType?.(n)?n:void 0,p=c===void 0?n:void 0;if(o)for(let a of o){c??=a,p??=a;let x=this.relations.get(a);if(x){if(x.size===1)this.relations.delete(a);else x.delete(n);this.contents.delete(this.makeContentKey(c,p))}}this.relations.set(n,new Set(i));for(let a of i){let x=this.relations.get(a);if(x)x.add(n);else x=new Set().add(n),this.relations.set(a,x)}}getContentInternal(n){return this.contents.get(n)}setContent(n,i){this.contents.set(n,i)}deleteContent(n){this.contents.delete(n)}constructor(n,i){if(this.a=n.between[0],this.b=n.between[1],this.cardinality=n.cardinality,!i?.externalStore)this.relations=new Map(n.relations?.map(([o,c])=>[o,new Set(c)])),this.contents=new Map(n.contents);if(this.isAType=i?.isAType??null,this.isBType=i?.isBType??null,this.isContent=i?.isContent??null,i?.makeContentKey)this.makeContentKey=i.makeContentKey;if(i?.externalStore){let o=i.externalStore;if(this.has=(c,p)=>o.has(c,p),this.addRelation=(c,p)=>{o.addRelation(c,p)},this.deleteRelation=(c,p)=>{o.deleteRelation(c,p)},this.replaceRelationsSafely=(c,p)=>{o.replaceRelationsSafely(c,p)},this.replaceRelationsUnsafely=(c,p)=>{o.replaceRelationsUnsafely(c,p)},this.getRelatedKeys=(c)=>o.getRelatedKeys(c),o.getContent)this.getContentInternal=(c)=>{return o.getContent(c)},this.setContent=(c,p)=>{o.setContent(c,p)},this.deleteContent=(c)=>{o.deleteContent(c)};for(let[c,p]of n.relations??[]){let a=this.isAType?.(c)?c:void 0,x=a===void 0?c:void 0;for(let m of p)a??=m,x??=m,this.addRelation(a,x)}for(let[c,p]of n.contents??[])this.setContent(c,p)}if(i?.warn)this.warn=i.warn}toJSON(){return{between:[this.a,this.b],cardinality:this.cardinality,relations:[...this.relations.entries()].map(([n,i])=>[n,[...i]]),contents:[...this.contents.entries()]}}set(n,...i){let o=typeof i[0]==="string"?i[0]:n[this.b],c=i[1]??typeof i[0]==="string"?void 0:i[0];switch(n=typeof n==="string"?n:n[this.a],this.cardinality){case"1:1":{let p=this.getRelatedKey(n);if(p&&p!==o)this.delete(n,p)}case"1:n":{let p=this.getRelatedKey(o);if(p&&p!==n)this.delete(p,o)}}if(c){let p=this.makeContentKey(n,o);this.setContent(p,c)}return this.addRelation(n,o),this}delete(n,i){i=typeof i==="string"?i:n[this.b];let o=typeof n==="string"?n:n[this.a];if(o===void 0&&typeof i==="string"){let c=this.getRelatedKeys(i);if(c)for(let p of c)this.delete(p,i)}if(typeof o==="string"&&i===void 0){let c=this.getRelatedKeys(o);if(c)for(let p of c)this.delete(o,p)}if(typeof o==="string"&&typeof i==="string"){this.deleteRelation(o,i);let c=this.makeContentKey(o,i);this.deleteContent(c)}return this}getRelatedKey(n){let i=this.getRelatedKeys(n);if(i){if(i.size>1)this.warn?.(`${i.size} related keys were found for key "${n}": (${[...i].map((c)=>`"${c}"`).join(", ")}). Only one related key was expected.`);let o;for(let c of i){o=c;break}return o}}replaceRelations(n,i,o){let c=!Array.isArray(i),p=c?Object.keys(i):i;if(o?.reckless)this.replaceRelationsUnsafely(n,p);else this.replaceRelationsSafely(n,p);if(c)for(let a of p){let x=this.makeContentKey(n,a),m=i[a];this.setContent(x,m)}return this}getContent(n,i){let o=this.makeContentKey(n,i);return this.getContentInternal(o)}getRelationEntries(n){let i=n[this.a],o=n[this.b];if(i!==void 0&&o===void 0){let c=this.getRelatedKeys(i);if(c)return[...c].map((p)=>{return[p,this.getContent(i,p)]})}if(i===void 0&&o!==void 0){let c=this.getRelatedKeys(o);if(c)return[...c].map((p)=>{return[p,this.getContent(p,o)]})}return[]}has(n,i){if(i)return this.getRelatedKeys(n)?.has(i)??!1;return this.relations.has(n)}}function tn(n){return"epoch"in n.transactionMeta}function Fn(n){return"phase"in n.transactionMeta}var V$=(n)=>{let i=U(n);if(!Fn(i)){n.logger.warn("\uD83D\uDC1E","transaction","???","abortTransaction called outside of a transaction. This is probably a bug in AtomIO.");return}n.logger.info("\uD83E\uDE82","transaction",i.transactionMeta.update.key,"Aborting transaction"),i.parent.child=null};var i8=(n)=>n[0].toUpperCase()+n.slice(1);function mo(n){return n.type.split("_").map(i8).join(" ")}class Ui extends Error{constructor(...n){let i=n[0],o=n.length===2?n[1]:n[2];if(n.length===2)super(`${mo(i)} ${r(i.key)} not found in store "${o.config.name}".`);else{let c=n[1];super(`${mo(i)} "${i.key}" member ${r(c)} not found in store "${o.config.name}".`)}}}function qo(n,i,o){return(...c)=>{let p=d(n,o);if(p)return p.run(c,i);throw new Ui(n,o)}}var mx=(n)=>(i)=>n instanceof Function?n(i):n;var Po=(n,i)=>{if(i.valueMap.has(n.key))return i.logger.info("\uD83D\uDCD6",n.type,n.key,"reading cached value"),u$(n,i);if(n.type==="selector"||n.type==="readonly_selector")return i.logger.info("\uD83E\uDDEE",n.type,n.key,"computing value"),n.get();let o=n.default instanceof Function?n.default():n.default;return i.logger.info("\uD83D\uDC81","atom",n.key,"could not find cached value; using default",o),n.default instanceof Function?n.default():n.default};var _$=(n,i)=>{if(n.operation.open){let o=performance.now();return n.logger.info("\u2757",i.type,i.key,`deferring setState at T-${o} until setState for "${n.operation.token.key}" is done`),o}n.operation={open:!0,done:new Set,prev:new Map,time:Date.now(),token:i},n.logger.info("\u2B55",i.type,i.key,`operation start in store "${n.config.name}"${!Fn(n)?"":` ${n.transactionMeta.phase} "${n.transactionMeta.update.key}"`}`)},b$=(n)=>{if(n.operation.open)n.logger.info("\uD83D\uDD34",n.operation.token.type,n.operation.token.key,`operation done in store "${n.config.name}"`);n.operation={open:!1},n.on.operationClose.next(n.operation)},j$=(n,i)=>{if(!n.operation.open)return n.logger.error("\uD83D\uDC1E","unknown",i,"isDone called outside of an operation. This is probably a bug in AtomIO."),!0;return n.operation.done.has(i)},ec=(n,i)=>{if(!n.operation.open){n.logger.error("\uD83D\uDC1E","unknown",i,"markDone called outside of an operation. This is probably a bug in AtomIO.");return}n.operation.done.add(i)};var y$=(n,i,o)=>{switch(n.type){case"mutable_atom":o.logger.info("\uD83D\uDCE2",n.type,n.key,"is now (",i.newValue,") subscribers:",n.subject.subscribers);break;default:o.logger.info("\uD83D\uDCE2",n.type,n.key,"went (",i.oldValue,"->",i.newValue,") subscribers:",n.subject.subscribers)}n.subject.next(i)};var wl=(n,i)=>{let o=U(i),c=o.selectorAtoms.getRelatedKeys(n.key);if(o.logger.info("\uD83E\uDDF9",n.type,n.key,c?`evicting ${c.size} states downstream:`:"no downstream states",c??"to evict"),c){if(o.operation.open)o.logger.info("\uD83E\uDDF9",n.type,n.key,`[ ${[...o.operation.done].join(", ")} ] already done`);for(let p of c){if(j$(o,p))continue;B$(p,o),ec(o,p)}}};function o8(n,i){if(N$(i.newValue))return!1;if(n.includes("\uD83D\uDD0D"))return!1;return!0}var L$=(n,i,o)=>{let{key:c}=n,p=U(o);if(!Fn(p)||p.transactionMeta.phase!=="building"){o.logger.error("\uD83D\uDC1E","atom",c,"stowUpdate called outside of a transaction. This is probably a bug.");return}if(!o8(c,i))return;let x={type:"atom_update",key:c,...i};if(n.family)x.family=n.family;p.transactionMeta.update.updates.push(x),o.logger.info("\uD83D\uDCC1","atom",c,"stowed (",i.oldValue,"->",i.newValue,")")};var D$=(n,i,o)=>{let c=Po(n,o),p=c;if(n.type==="mutable_atom"&&Fn(o)){let{parent:x}=o;p=la(n,x,o)}if(p=mx(i)(p),o.logger.info("\uD83D\uDCDD","atom",n.key,"set to",p),p=Zi(n.key,p,n.subject,o),C$(n.key,o))h$(n.key,o);ec(o,n.key),wl(n,o);let a={oldValue:c,newValue:p};if(tn(o))y$(n,a,o);else if(o.parent){if(o.on.transactionApplying.state===null)L$(n,a,o);else if(n.key.startsWith("*")){let x=n.key.slice(1),m=o.atoms.get(x),l=o.valueMap.get(x);if(m.type==="mutable_atom"&&Fn(o)){let{parent:v}=o;l=la(m,v,o)}if(l.do(a.newValue)===null)wl(m,o)}}};var lx=(n,i,o)=>{switch(n.type){case"atom":case"mutable_atom":D$(n,i,o);break;case"selector":n.set(i);break}};function fx(n,i){if(i.family){let o=n.families.get(i.family.key);if(o)return o}}function Qn(n,...i){let o,c,p,a;if(i.length===2){if(o=i[0],a=i[1],c=fx(n,o)??null,c)p=o.family?oi(o.family.subKey):null,o=Sn(n,c,p)}else c=i[0],p=i[1],a=i[2],o=Sn(n,c,p);if("counterfeit"in o){let l=n.disposalTraces.buffer.find((f)=>f?.key===o.key);n.logger.error("\u274C",o.type,o.key,`could not be set because it was not found in the store "${n.config.name}".`,l?`This state was previously disposed:\n${l.trace}`:"No previous disposal trace was found.");return}let x=_$(n,o);if(x){let l=n.on.operationClose.subscribe(`waiting to set "${o.key}" at T-${x}`,()=>{l(),n.logger.info("\uD83D\uDFE2",o.type,o.key,`resuming deferred setState from T-${x}`),Qn(n,o,a)});return}let m=d(o,n);lx(m,a,n),b$(n)}function vx(n,i,o){let{key:c,newValue:p,oldValue:a}=i,x=n==="newValue"?p:a,m={key:c,type:"atom"};if(i.family)Object.assign(m,{family:i.family});Qn(o,m,x)}function I$(n,i){let o=new xn,c={type:"molecule_family",key:i.key,dependsOn:i.dependsOn??"all"},p={...c,subject:o,new:i.new};return n.moleculeFamilies.set(i.key,p),c}function lo(n,i,o){let c=_o(o,i,n.key);n.tokens.set(c.key,c);let p=Fn(o)&&o.transactionMeta.phase==="building",a=o.moleculeInProgress===n.key;if(!p&&!a)n.subject.next({type:"state_creation",token:c});return c}class ci extends Set{mode="record";subject=new xn;cacheLimit=0;cache=[];cacheIdx=-1;cacheUpdateNumber=-1;constructor(n,i=0){super(n);if(n instanceof ci)this.parent=n,this.cacheUpdateNumber=n.cacheUpdateNumber;if(i)this.cacheLimit=i,this.cache=new Array(i),this.subscribe("auto cache",(o)=>{this.cacheIdx++,this.cacheIdx%=this.cacheLimit,this.cache[this.cacheIdx]=o})}toJSON(){return{members:[...this],cache:this.cache,cacheLimit:this.cacheLimit,cacheIdx:this.cacheIdx,cacheUpdateNumber:this.cacheUpdateNumber}}static fromJSON(n){let i=new ci(n.members,n.cacheLimit);return i.cache=n.cache,i.cacheIdx=n.cacheIdx,i.cacheUpdateNumber=n.cacheUpdateNumber,i}add(n){let i=super.add(n);if(this.mode==="record")this.cacheUpdateNumber++,this.emit(`add:${r(n)}`);return i}clear(){let n=this.mode==="record"?[...this]:null;if(super.clear(),n)this.cacheUpdateNumber++,this.emit(`clear:${JSON.stringify(n)}`)}delete(n){let i=super.delete(n);if(this.mode==="record")this.cacheUpdateNumber++,this.emit(`del:${r(n)}`);return i}parent;child=null;transactionUpdates=null;transaction(n){this.mode="transaction",this.transactionUpdates=[],this.child=new ci(this);let i=this.child._subscribe("transaction",(o)=>{this.transactionUpdates?.push(o)});try{if(n(this.child)){for(let c of this.transactionUpdates)this.doStep(c);this.cacheUpdateNumber++,this.emit(`tx:${this.transactionUpdates.join(";")}`)}}catch(o){throw console.error("Failed to apply transaction to SetRTX:",o),o}finally{i(),this.child=null,this.transactionUpdates=null,this.mode="record"}}_subscribe(n,i){return this.subject.subscribe(n,i)}subscribe(n,i){return this.subject.subscribe(n,(o)=>{i(`${this.cacheUpdateNumber}=${o}`)})}emit(n){this.subject.next(n)}doStep(n){let i=n.indexOf(":"),o=n.substring(0,i),c=n.substring(i+1);switch(o){case"add":this.add(JSON.parse(c));break;case"clear":this.clear();break;case"del":this.delete(JSON.parse(c));break;case"tx":for(let p of c.split(";"))this.doStep(p)}}getUpdateNumber(n){let i=n.indexOf("=");return Number(n.substring(0,i))}do(n){let i=n.indexOf("="),o=Number(n.substring(0,i)),c=o-this.cacheUpdateNumber;if(c>0){if(c===1){this.mode="playback";let a=n.substring(i+1);return this.doStep(a),this.mode="record",this.cacheUpdateNumber=o,null}return this.cacheUpdateNumber+1}if(Math.abs(c)<this.cacheLimit){let a=this.cacheIdx+c;if(this.cache[a]===n)return null;this.mode="playback";let m=!1;while(!m){this.cacheIdx%=this.cacheLimit;let f=this.cache[this.cacheIdx];if(this.cacheIdx--,!f)return"OUT_OF_RANGE";this.undo(f),m=this.cacheIdx===a-1}let l=n.substring(i+1);return this.doStep(l),this.mode="record",this.cacheUpdateNumber=o,null}return"OUT_OF_RANGE"}undoStep(n){let i=n.indexOf(":"),o=n.substring(0,i),c=n.substring(i+1);switch(o){case"add":this.delete(JSON.parse(c));break;case"del":this.add(JSON.parse(c));break;case"clear":{let p=JSON.parse(c);for(let a of p)this.add(a);break}case"tx":{let p=c.split(";");for(let a=p.length-1;a>=0;a--)this.undoStep(p[a])}}}undo(n){let i=n.indexOf("=");if(Number(n.substring(0,i))===this.cacheUpdateNumber){this.mode="playback";let c=n.substring(i+1);return this.undoStep(c),this.mode="record",this.cacheUpdateNumber--,null}return this.cacheUpdateNumber}}function Ln(n){return n[0].toUpperCase()+n.slice(1)}class Al{options;defaultContent;toolkit;retrieve;molecules=new Map;relations;states;core;transact(n,i){let o=this.toolkit;this.toolkit=n,i(this),this.toolkit=o}store;alternates;[Symbol.dispose](){this.alternates.delete(this.store.config.name)}in(n){let i=n.config.name,o=this.alternates.get(i);if(o)return o;let c=new Al(this.options,this.defaultContent,n);return this.alternates.set(i,c),c.alternates=this.alternates,c}constructor(n,i,o=nn.STORE){this.store=o,this.options=n,this.defaultContent=i,this.alternates=new Map,this.alternates.set(o.config.name,this),this.store.miscResources.set(`join:${n.key}`,this),this.retrieve=(Y,K)=>{let E=this.toolkit.seek(Y,K);if(E)return E;let y=this.store.molecules.get(r(K));if(y){let V=d(Y,o);return lo(y,V,o)}if(o.config.lifespan==="immortal")throw new Ui(Y,K,o);return _o(o,Y,K)},this.toolkit={get:(...Y)=>Mn(o,...Y),set:(...Y)=>{Qn(o,...Y)},find:this.retrieve,seek:(...Y)=>Bn(o,...Y),json:(Y)=>Zn(o,Y),dispose:(...Y)=>{zi(o,...Y)}};let c=n.between[0],p=n.between[1],a=aa(o,{key:`${n.key}/relatedKeys`,default:()=>new ci,mutable:!0,fromJson:(Y)=>ci.fromJSON(Y),toJson:(Y)=>Y.toJSON()},["join","relations"]);this.core={findRelatedKeysState:a};let x=({get:Y},K)=>Y(this.retrieve(a,K)),m=(Y,K,E)=>{let{set:y}=Y,V=this.retrieve(a,K),X=this.retrieve(a,E);y(V,(Z)=>Z.add(E)),y(X,(Z)=>Z.add(K))},l=(Y,K,E)=>{let{set:y}=Y,V=this.retrieve(a,K),X=this.retrieve(a,E),Z,C;y(V,(on)=>{if(on.delete(E),on.size===0)Z=`"${K}"`;return on}),y(X,(on)=>{if(on.delete(K),on.size===0)C=`"${E}"`;return on})},f=(Y,K,E)=>{let{get:y,set:V}=Y,X=this.retrieve(a,K),Z=y(X);for(let C of Z){if(E.includes(C))continue;let mn=this.retrieve(a,C);V(mn,(ln)=>{return ln.delete(K),ln})}V(X,(C)=>{return C.transaction((on)=>{on.clear();for(let mn of E){let ln=x(Y,mn),Vn=ln.has(K);if(this.relations.cardinality==="1:n"){let ji=[];for(let H of ln){if(H===K)continue;let s=x(Y,H);if(s.delete(mn),s.size===0)ji.push(H)}if(!Vn&&ln.size>0)ln.clear();for(let H of ji){let s=[mn,H].sort(),wn=`"${s[0]}:${s[1]}"`;this.molecules.delete(wn)}}if(!Vn)ln.add(K);on.add(mn)}return!0}),C})},v=(Y,K,E)=>{let{set:y}=Y,V=this.retrieve(a,K);y(V,(X)=>{return X.transaction((Z)=>{for(let C of E)Z.add(C);return!0}),X});for(let X of E){let Z=this.retrieve(a,X);y(Z,(C)=>{return C.add(K),C})}return!0},$=(Y,K,E)=>{let y=x(Y,K);return E?y.has(E):y.size>0},T={getRelatedKeys:(Y)=>x(this.toolkit,Y),addRelation:(Y,K)=>{m(this.toolkit,Y,K)},deleteRelation:(Y,K)=>{l(this.toolkit,Y,K)},replaceRelationsSafely:(Y,K)=>{f(this.toolkit,Y,K)},replaceRelationsUnsafely:(Y,K)=>{v(this.toolkit,Y,K)},has:(Y,K)=>$(this.toolkit,Y,K)},F,M,A;if(i){M=so(o,{key:`${n.key}/content`,default:i},["join","content"]),A=I$(o,{key:`${n.key}/content-molecules`,new:class V{Z;constructor(X,Z){this.key=Z}}});let Y=({get:V},X)=>V(this.retrieve(M,X)),K=({set:V},X,Z)=>{V(this.retrieve(M,X),Z)},E=(V,X)=>{let Z=o.molecules.get(`"${X}"`);if(Z)this.toolkit.dispose(Z),this.molecules.delete(`"${X}"`)};F=Object.assign(T,{getContent:(V)=>{return Y(this.toolkit,V)},setContent:(V,X)=>{K(this.toolkit,V,X)},deleteContent:(V)=>{E(this.toolkit,V)}})}else F=T;let R=new yi(n,{externalStore:F,isAType:n.isAType,isBType:n.isBType,makeContentKey:(...Y)=>{let K=Y.sort(),E=`${K[0]}:${K[1]}`,[y,V]=K.map((X)=>this.molecules.get(r(X)));if(o.config.lifespan==="immortal"&&y&&V){let X=U(o),Z=bo(X,[y,V],A,E);this.molecules.set(`"${E}"`,d(Z,X))}return E}}),G=()=>to(o,{key:`${n.key}/singleRelatedKey`,get:(Y)=>({get:K})=>{let E=this.retrieve(a,Y),y=K(E);for(let V of y)return V;return null}},["join","keys"]),Q=()=>{return to(o,{key:`${n.key}/multipleRelatedKeys`,get:(Y)=>({get:K})=>{let E=Sl(a,o),y=this.retrieve(E,Y);return K(y).members}},["join","keys"])},b=()=>to(o,{key:`${n.key}/singleRelatedEntry`,get:(Y)=>({get:K})=>{let E=this.retrieve(a,Y),y=K(E);for(let V of y){let X=R.isAType?.(Y)?Y:void 0,Z=X===void 0?Y:void 0;X??=V,Z??=V;let C=R.makeContentKey(X,Z),on=this.retrieve(M,C),mn=K(on);return[V,mn]}return null}},["join","entries"]),D=()=>to(o,{key:`${n.key}/multipleRelatedEntries`,get:(Y)=>({get:K})=>{let E=Sl(a,o),y=this.retrieve(E,Y);return K(y).members.map((X)=>{let Z=R.isAType?.(Y)?Y:void 0,C=Z===void 0?Y:void 0;Z??=X,C??=X;let on=R.makeContentKey(Z,C),mn=this.retrieve(M,on),ln=K(mn);return[X,ln]})}},["join","entries"]);switch(n.cardinality){case"1:1":{let Y=G(),K=`${c}KeyOf${Ln(p)}`,E=`${p}KeyOf${Ln(c)}`,y={[K]:Y,[E]:Y},V;if(i){let X=b(),Z=`${c}EntryOf${Ln(p)}`,C=`${p}EntryOf${Ln(c)}`,on={[Z]:X,[C]:X};V=Object.assign(y,on)}else V=y;this.relations=R,this.states=V;break}case"1:n":{let Y=G(),K=Q(),E=`${c}KeyOf${Ln(p)}`,y=`${p}KeysOf${Ln(c)}`,V={[E]:Y,[y]:K},X;if(i){let Z=b(),C=D(),on=`${c}EntryOf${Ln(p)}`,mn=`${p}EntriesOf${Ln(c)}`,ln={[on]:Z,[mn]:C};X=Object.assign(V,ln)}else X=V;this.relations=R,this.states=X;break}default:{let Y=Q(),K=`${c}KeysOf${Ln(p)}`,E=`${p}KeysOf${Ln(c)}`,y={[K]:Y,[E]:Y},V;if(i){let X=D(),Z=`${c}EntriesOf${Ln(p)}`,C=`${p}EntriesOf${Ln(c)}`,on={[Z]:X,[C]:X};V=Object.assign(y,on)}else V=y;this.relations=R,this.states=V}}}}function $x(n,i,o=nn.STORE){return Jl(o).set(n.key,new Al(n,i,o)),{key:n.key,type:"join",a:n.between[0],b:n.between[1],cardinality:n.cardinality}}function Jl(n){if("joins"in n&&n.joins instanceof Map)return n.joins;let i=new Map;return n.joins=i,i}function fa(n,i){let o=Jl(i),c=o.get(n.key);if(c===void 0){if(c=Jl(nn.STORE).get(n.key)?.in(i),c===void 0)throw new Error(`Join "${n.key}" not found in store "${i.config.name}"`);o.set(n.key,c)}return c}function np(n,i,o){let c=fa(n,o),p;switch(n.cardinality){case"1:1":{let a=`${n.a}KeyOf${Ln(n.b)}`,x=`${n.b}KeyOf${Ln(n.a)}`;p={get[a](){let l=c.states[a];return c.retrieve(l,i)},get[x](){let l=c.states[x];return c.retrieve(l,i)}};let m=`${n.a}EntryOf${Ln(n.b)}`;if(m in c.states){let l=`${n.b}EntryOf${Ln(n.a)}`;Object.assign(p,{get[m](){let f=c.states[m];return c.retrieve(f,i)},get[l](){let f=c.states[l];return c.retrieve(f,i)}})}break}case"1:n":{let a=`${n.a}KeyOf${Ln(n.b)}`,x=`${n.b}KeysOf${Ln(n.a)}`;p={get[a](){let l=c.states[a];return c.retrieve(l,i)},get[x](){let l=c.states[x];return c.retrieve(l,i)}};let m=`${n.a}EntryOf${Ln(n.b)}`;if(m in c.states){let l=`${n.b}EntriesOf${Ln(n.a)}`;Object.assign(p,{get[m](){let f=c.states[m];return c.retrieve(f,i)},get[l](){let f=c.states[l];return c.retrieve(f,i)}})}break}case"n:n":{let a=`${n.a}KeysOf${Ln(n.b)}`,x=`${n.b}KeysOf${Ln(n.a)}`;p={get[a](){let l=c.states[a];return c.retrieve(l,i)},get[x](){let l=c.states[x];return c.retrieve(l,i)}};let m=`${n.a}EntriesOf${Ln(n.b)}`;if(m in c.states){let l=`${n.b}EntriesOf${Ln(n.a)}`;Object.assign(p,{get[m](){let f=c.states[m];return c.retrieve(f,i)},get[l](){let f=c.states[l];return c.retrieve(f,i)}})}}}return p}function k$(n,i){return np(n,i,nn.STORE)}function Rc(n,i,o){let c=fa(n,o),p=U(o);if(Fn(p)){let{toolkit:a}=p.transactionMeta;c.transact(a,({relations:x})=>{i(x)})}else i(c.relations)}function c8(n,i){return fa(n,i).core.findRelatedKeysState}function s$(n){return c8(n,nn.STORE)}function Tx(n){return{store:n}}function Mn(n,...i){let o,c,p;if(i.length===1){if(o=i[0],o.type!=="molecule"){if(c=fx(n,o)??null,c)p=o.family?oi(o.family.subKey):null,o=Sn(n,c,p)}}else{c=i[0],p=i[1];let a;if(c.type==="molecule_family")a=Bn(n,c,p)??dc(c,p);else a=Sn(n,c,p);o=a}if("counterfeit"in o&&"family"in o){c=o.type==="molecule"?d(o.family,n):n.families.get(o.family.key);let a=o.type==="molecule"?o.key:o.family.subKey,x=n.disposalTraces.buffer.find((m)=>m?.key===o.key);switch(n.logger.error("\u274C",o.type,o.key,`could not be retrieved because it was not found in the store "${n.config.name}".`,x?`This state was previously disposed:\n${x.trace}`:"No previous disposal trace was found."),c.type){case"atom_family":case"mutable_atom_family":return n.defaults.get(c.key);case"selector_family":case"readonly_selector_family":{if(n.defaults.has(c.key))return n.defaults.get(o.family.key);let m=d(c,n).default(a);return n.defaults.set(c.key,m),m}case"molecule_family":throw new Ui(c,a,n)}}switch(o.type){case"atom":case"mutable_atom":case"selector":case"readonly_selector":return Po(d(o,n),n);case"molecule":return d(o,n).instance}}class ip{i;type="molecule";stringKey;family;_dependsOn;get dependsOn(){if(this.family)return this.family.dependsOn;return this._dependsOn}subject=new xn;tokens=new Map;above=new Map;below=new Map;joins=new Map;instance;constructor(n,i,o){this.key=i;if(this.stringKey=r(i),o)this.family=o,this._dependsOn=o.dependsOn;if(n)for(let c of n)this.above.set(c.stringKey,c)}}function Z$(n){return n[0].toUpperCase()+n.slice(1)}function bo(n,i,o,c,...p){let a=O$(n),x=U(n),m=r(c);x.moleculeInProgress=m;let l=Array.isArray(i)?i:[i],f=l.map((R)=>{if(R instanceof ip)return R;let G=r(R.key),Q=n.molecules.get(G);if(!Q)throw new Error(`Molecule ${G} not found in store "${n.config.name}"`);return Q}),v=new ip(f,c,o);x.molecules.set(m,v);for(let R of f)R.below.set(v.stringKey,v);let $={get:(...R)=>Mn(U(a),...R),set:(...R)=>{Qn(U(a),...R)},seek:(R,G)=>Bn(U(a),R,G),json:(R)=>Zn(U(a),R),run:(R,G=gc())=>qo(R,G,U(n)),make:(R,G,Q,...b)=>bo(U(a),R,G,Q,...b),dispose:(R)=>{zi(U(a),R)},env:()=>Tx(U(a)),bond:(R,G)=>{if(R.type==="join"){let{as:Q}=G,b=fa(R,a);b.molecules.set(m,v),v.joins.set(R.key,b);let D=T.subject.subscribe(`join:${R.key}-${m}`,(X)=>{if(X.type==="molecule_disposal"){if(r(X.token.key)===m)D(),b.molecules.delete(m)}});if(Q===null)return;let Y=R.a===Q?R.b:R.a,K=k$(R,c),E=K[`${Y}KeysOf${Z$(Q)}`],y=K[`${Y}EntriesOf${Z$(Q)}`],V={relatedKeys:E};if(y)V=Object.assign(V,{relatedEntries:y});return V}return lo(v,d(R,a),U(a))},claim:(R,G)=>{let{exclusive:Q}=G,b=U(n).molecules.get(r(R.key));if(b)if(Q){for(let D of b.above.values())D.below.delete(b.stringKey);b.above.clear(),b.above.set(v.stringKey,v),v.below.set(b.stringKey,b)}else b.above.set(v.stringKey,v),v.below.set(b.stringKey,b)},spawn:(R,G,...Q)=>bo(U(n),[v],d(R,n),G,...Q)},T=d(o,n),F=T.new;v.instance=new F($,c,...p);let M={type:"molecule",key:c,family:o},A={type:"molecule_creation",subType:"classic",token:M,family:o,context:l,params:p};if(tn(x))T.subject.next(A);else if(Fn(x)&&x.on.transactionApplying.state===null)x.transactionMeta.update.updates.push(A);return x.moleculeInProgress=null,M}function Ml(n,i,o){switch(i){case"newValue":{t$(n,o);break}case"oldValue":{zi(o,n.token);break}}}function Rl(n,i,o){switch(i){case"newValue":{zi(o,n.token);break}case"oldValue":{t$(n,o),o.valueMap.set(n.token.key,n.value);break}}}function t$(n,i){let{family:o}=n.token;if(o){let c=i.families.get(o.key);if(c)Sn(i,c,oi(o.subKey))}}function Wl(n,i,o){switch(i){case"newValue":switch(n.subType){case"classic":bo(o,n.context,n.family,n.token.key,...n.params);break;case"modern":Fl(o,n.provenance,n.key);break}break;case"oldValue":switch(n.subType){case"classic":zi(o,n.token);break;case"modern":va(o,n.key);break}break}}function Kl(n,i,o){switch(i){case"newValue":switch(n.subType){case"classic":zi(o,n.token);break;case"modern":va(o,n.key);break}break;case"oldValue":switch(n.subType){case"classic":{let c=bo(o,n.context,n.family,n.token.key);for(let[p,a]of n.values){let x=`${p}(${r(c.key)})`,m=d(c,o),l=m.tokens.has(x),f=o.families.get(p);if(f&&!l)lo(m,f,o);o.valueMap.set(x,a)}}break;case"modern":{Fl(o,n.provenance,n.key);for(let[c,p]of n.values){let a=o.families.get(c);if(a){Sn(o,a,n.key);let x=`${c}(${r(n.key)})`;o.valueMap.set(x,p)}}}}break}}function wx(n,i,o){let c=n==="newValue"?i.updates:[...i.updates].reverse();for(let p of c)switch(p.type){case"atom_update":case"selector_update":vx(n,p,o);break;case"state_creation":Ml(p,n,o);break;case"state_disposal":Rl(p,n,o);break;case"molecule_creation":Wl(p,n,o);break;case"molecule_disposal":Kl(p,n,o);break;case"transaction_update":wx(n,p,o);break}}function q$(n,i,o){if(tn(o)&&n)o.transactionMeta.epoch.set(n,i)}function P$(n,i,o){if(!tn(o))return;let p=o.transactionMeta.actionContinuities.getRelatedKey(n);if(p!==void 0)o.transactionMeta.epoch.set(p,i)}var r$=(n,i)=>{let o=U(i),{parent:c}=o;if(c===null||!Fn(o)||o.transactionMeta?.phase!=="building"){i.logger.warn("\uD83D\uDC1E","transaction","???","applyTransaction called outside of a transaction. This is probably a bug in AtomIO.");return}o.transactionMeta.phase="applying",o.transactionMeta.update.output=n,c.child=null,c.on.transactionApplying.next(o.transactionMeta);let{updates:p}=o.transactionMeta.update;if(i.logger.info("\uD83D\uDEC4","transaction",o.transactionMeta.update.key,`Applying transaction with ${p.length} updates:`,p),wx("newValue",o.transactionMeta.update,c),tn(c))P$(o.transactionMeta.update.key,o.transactionMeta.update.epoch,c),d({key:o.transactionMeta.update.key,type:"transaction"},i)?.subject.next(o.transactionMeta.update),i.logger.info("\uD83D\uDEEC","transaction",o.transactionMeta.update.key,"Finished applying transaction.");else if(Fn(c))c.transactionMeta.update.updates.push(o.transactionMeta.update);c.on.transactionApplying.next(null)};function g$(n,i,o){if(!tn(o))return;let{epoch:p,actionContinuities:a}=o.transactionMeta;if(a.set(n,i),!p.has(n))p.set(n,-1)}class ti extends Map{n;deleted=new Set;constructor(n){super();this.source=n}get(n){if(super.has(n))return super.get(n);if(!this.deleted.has(n)&&this.source.has(n))return this.source.get(n);return}set(n,i){return this.deleted.delete(n),super.set(n,i)}hasOwn(n){return super.has(n)}has(n){return!this.deleted.has(n)&&(super.has(n)||this.source.has(n))}delete(n){return this.deleted.add(n),super.delete(n)}}var d$=(n,i,o,c)=>{let p=U(o),a={parent:p,child:null,on:p.on,loggers:p.loggers,logger:p.logger,config:p.config,atoms:new ti(p.atoms),atomsThatAreDefault:new Set(p.atomsThatAreDefault),families:new ti(p.families),operation:{open:!1},readonlySelectors:new ti(p.readonlySelectors),timelines:new ti(p.timelines),timelineTopics:new yi(p.timelineTopics.toJSON()),trackers:new Map,transactions:new ti(p.transactions),selectorAtoms:new yi(p.selectorAtoms.toJSON()),selectorGraph:new yi(p.selectorGraph.toJSON(),{makeContentKey:(...f)=>f.sort().join(":")}),selectors:new ti(p.selectors),valueMap:new ti(p.valueMap),defaults:p.defaults,disposalTraces:o.disposalTraces.copy(),molecules:new ti(p.molecules),moleculeFamilies:new ti(p.moleculeFamilies),moleculeInProgress:p.moleculeInProgress,miscResources:new ti(p.miscResources)},x=e$(n,o),m={phase:"building",update:{type:"transaction_update",key:n,id:c,epoch:x===void 0?Number.NaN:x+1,updates:[],params:i,output:void 0},toolkit:{get:(...f)=>Mn(l,...f),set:(...f)=>{Qn(l,...f)},run:(f,v=gc())=>qo(f,v,l),find:(f,v)=>Sn(l,f,v),seek:(f,v)=>Bn(l,f,v),json:(f)=>Zn(l,f),make:(f,v,$,...T)=>bo(l,f,v,$,...T),dispose:(...f)=>{zi(l,...f)},env:()=>Tx(l)}},l=Object.assign(a,{transactionMeta:m});return p.child=l,o.logger.info("\uD83D\uDEEB","transaction",n,"Building transaction with params:",i),l};function Xl(n,i){let o={key:n.key,type:"transaction",run:(a,x)=>{let m=d$(n.key,a,i,x);try{let l=U(i),{toolkit:f}=m.transactionMeta,v=n.do(f,...a);return r$(v,l),v}catch(l){throw V$(c),i.logger.warn("\uD83D\uDCA5","transaction",n.key,"caught:",l),l}},install:(a)=>Xl(n,a),subject:new xn},c=U(i);c.transactions.set(o.key,o);let p=si(o);return i.on.transactionCreation.next(p),p}function e$(n,i){let o=tn(i),c=o?i.transactionMeta.actionContinuities.getRelatedKey(n):void 0;return o&&c!==void 0?i.transactionMeta.epoch.get(c):void 0}class Jx{_buffer;_index=0;constructor(n){let i;if(typeof n==="number")i=n;else i=n.length;this._buffer=Array.from({length:i})}get buffer(){return this._buffer}get index(){return this._index}add(n){this._buffer[this._index]=n,this._index=(this._index+1)%this._buffer.length}copy(){let n=new Jx([...this._buffer]);return n._index=this._index,n}}class n0{parent=null;child=null;valueMap=new Map;defaults=new Map;atoms=new Map;selectors=new Map;readonlySelectors=new Map;atomsThatAreDefault=new Set;selectorAtoms=new yi({between:["selectorKey","atomKey"],cardinality:"n:n"});selectorGraph=new yi({between:["upstreamSelectorKey","downstreamSelectorKey"],cardinality:"n:n"},{makeContentKey:(...n)=>n.sort().join(":")});trackers=new Map;families=new Map;transactions=new Map;transactionMeta={epoch:new Map,actionContinuities:new yi({between:["continuity","action"],cardinality:"1:n"})};timelines=new Map;timelineTopics=new yi({between:["timelineKey","topicKey"],cardinality:"1:n"});disposalTraces=new Jx(100);molecules=new Map;moleculeFamilies=new Map;moleculeInProgress=null;miscResources=new Map;on={atomCreation:new xn,atomDisposal:new xn,selectorCreation:new xn,selectorDisposal:new xn,timelineCreation:new xn,transactionCreation:new xn,transactionApplying:new $l(null),operationClose:new xn,moleculeCreationStart:new xn,moleculeCreationDone:new xn,moleculeDisposal:new xn};operation={open:!1};config={name:"IMPLICIT_STORE",lifespan:"ephemeral"};loggers=[new Wc("warn",(n,i,o)=>!o.includes("\uD83D\uDD0D"))];logger={error:(...n)=>{for(let i of this.loggers)i.error(...n)},info:(...n)=>{for(let i of this.loggers)i.info(...n)},warn:(...n)=>{for(let i of this.loggers)i.warn(...n)}};constructor(n,i=null){if(this.config={...i?.config,...n},i!==null){if(this.valueMap=new Map(i?.valueMap),this.operation={...i?.operation},tn(i))this.transactionMeta={epoch:new Map(i?.transactionMeta.epoch),actionContinuities:new yi(i?.transactionMeta.actionContinuities.toJSON())};for(let[,c]of i.families){if(c.internalRoles?.includes("mutable")||c.internalRoles?.includes("join"))continue;c.install(this)}let o=new Set;for(let[,c]of i.atoms){if(o.has(c.key))continue;if(c.install(this),c.type==="mutable_atom"){let p=Zn(i,c),a=jo(c);o.add(p.key),o.add(a.key)}}for(let[,c]of i.readonlySelectors)c.install(this);for(let[,c]of i.selectors){if(o.has(c.key))continue;c.install(this)}for(let[,c]of i.transactions)c.install(this);for(let[,c]of i.timelines)c.install(this)}}}var nn={get STORE(){if(!globalThis.ATOM_IO_IMPLICIT_STORE)globalThis.ATOM_IO_IMPLICIT_STORE=new n0({name:"IMPLICIT_STORE",lifespan:"ephemeral"});return globalThis.ATOM_IO_IMPLICIT_STORE}};function d(n,i){let o,c=i;while(c!==null){switch(n.type){case"atom":case"mutable_atom":o=c.atoms.get(n.key);break;case"selector":o=c.selectors.get(n.key);break;case"readonly_selector":o=c.readonlySelectors.get(n.key);break;case"atom_family":case"mutable_atom_family":case"selector_family":case"readonly_selector_family":o=c.families.get(n.key);break;case"timeline":o=c.timelines.get(n.key);break;case"transaction":o=c.transactions.get(n.key);break;case"molecule":o=c.molecules.get(r(n.key));break;case"molecule_family":o=c.moleculeFamilies.get(n.key);break}if(o)return o;c=c.child}throw new Ui(n,i)}function Sx(n,i){let o;o=d(n,i);let{family:c}=n;for(let x of o.joins.values())x.relations.delete(o.key),x.molecules.delete(o.stringKey);let p=[];for(let x of o.above.values())p.push(si(x));let a=[];for(let x of o.tokens.values()){let m=x.family;a.push([m.key,i.valueMap.get(x.key)])}if(c){let x=d(c,i),m={type:"molecule_disposal",subType:"classic",token:n,family:c,context:p,values:a};if(n.family)m.family=n.family;for(let f of o.tokens.values())zi(i,f);for(let f of o.below.values())if(f.dependsOn==="all")Sx(f,i);else if(f.above.delete(o.stringKey),f.above.size===0)Sx(f,i);if(o.below.clear(),Fn(i)&&i.transactionMeta.phase==="building")i.transactionMeta.update.updates.push(m);else x.subject.next(m);i.molecules.delete(o.stringKey)}for(let x of o.above.values())x.below.delete(o.stringKey)}function _o(n,i,o){let c=n.families.get(i.key);if(c===void 0)throw new Ui(i,n);let p=c(o),a=U(n);if(p.family&&a.moleculeInProgress===null){if(tn(a))switch(p.type){case"atom":case"mutable_atom":n.on.atomCreation.next(p);break;case"selector":case"readonly_selector":n.on.selectorCreation.next(p);break}else if(Fn(a)&&a.on.transactionApplying.state===null)a.transactionMeta.update.updates.push({type:"state_creation",token:p})}return p}function Bn(n,i,o){let c=r(o),p=`${i.key}(${c})`,a=U(n),x;switch(i.type){case"atom_family":case"mutable_atom_family":x=a.atoms.get(p);break;case"selector_family":x=a.selectors.get(p);break;case"readonly_selector_family":x=a.readonlySelectors.get(p);break;case"molecule_family":x=a.molecules.get(r(o))}if(x)return si(x);return x}function Sn(n,i,o){let c=Bn(n,i,o);if(c)return c;let p=n.molecules.get(r(o));if(p)return lo(p,i,n);if(n.config.lifespan==="immortal"){let a=dc(i,o);return n.logger.error("\u274C",a.type,a.key,`was not found in store "${n.config.name}"; returned a counterfeit token.`),a}return c=_o(n,i,o),c}function zi(n,...i){let o,c;if(i.length===1)o=i[0],c=o.key;else{let a=i[0],x=i[1];o=a.type==="molecule_family"?Bn(n,a,x)??dc(a,x):Sn(n,a,x)}try{d(o,n)}catch(a){let x=n.disposalTraces.buffer.find((m)=>m?.key===o.key);n.logger.error("\u274C",o.type,o.key,`could not be disposed because it was not found in the store "${n.config.name}".`,x?`\n This state was most recently disposed\n${x.trace}`:"No previous disposal trace was found.");return}switch(o.type){case"atom":case"mutable_atom":Gl(o,n);break;case"selector":case"readonly_selector":i0(o,n);break;case"molecule":Sx(o,n);break}let{stack:p}=new Error;if(p){let a=p?.split("\n")?.slice(3)?.join("\n");n.disposalTraces.add({key:o.key,trace:a})}}var Ax=(n,i)=>U(i).atoms.has(n),p8=(n,i)=>U(i).selectors.has(n),a8=(n,i)=>U(i).readonlySelectors.has(n),o0=(n,i)=>Ax(n,i)||p8(n,i)||a8(n,i);var Fx=(n,i)=>{return U(i).selectorGraph.getRelationEntries({downstreamSelectorKey:n}).filter(([c,{source:p}])=>p!==n).map(([c,{source:p}])=>p).filter((c)=>o0(c,i))};var Yl=(n,i,o)=>{let c=[],p=Fx(n,o);while(p.length>0){let a=p.shift();if(i.has(a))continue;if(i.add(a),!Ax(a,o))p.push(...Fx(a,o));else if(!c.includes(a))c.push(a)}return c},c0=(n,i)=>{let o=n.key,c=Fx(o,i),p=new Set;return c.flatMap((a)=>Ax(a,i)?a:Yl(a,p,i))};var p0=(n,i,o,c)=>{let p=U(c);if(i.type==="atom"||i.type==="mutable_atom")p.selectorAtoms.set({selectorKey:n,atomKey:i.key}),c.logger.info("\uD83D\uDD0D","selector",n,`discovers root atom "${i.key}"`);else{let a=Yl(i.key,o,c);c.logger.info("\uD83D\uDD0D","selector",n,`discovers root atoms: [ ${a.map((x)=>`"${x}"`).join(", ")} ]`);for(let x of a)p.selectorAtoms=p.selectorAtoms.set({selectorKey:n,atomKey:x})}o.add(i.key)};var Mx=(n,i,o)=>({get:(...c)=>{let p=U(o),a;if(c.length===2){let[l,f]=c;switch(l.type){case"molecule_family":return Mn(o,l,f);default:if(o.config.lifespan==="ephemeral")a=Sn(o,l,f);else{let v=Bn(o,l,f);if(v)a=v;else throw new Ui(l,f,o)}}}else[a]=c;if(a.type==="molecule")return Mn(o,a);let x=d(a,o),m=Po(x,o);return o.logger.info("\uD83D\uDD0C","selector",n,`registers dependency ( "${a.key}" =`,m,")"),p.selectorGraph.set({upstreamSelectorKey:a.key,downstreamSelectorKey:n},{source:a.key}),p0(n,a,i,o),m},set:(...c)=>{let p,a;if(c.length===2)p=c[0],a=c[1];else{let l=c[0],f=c[1];a=c[2];let v=o.config.lifespan==="ephemeral"?Sn(o,l,f):Bn(o,l,f);if(!v)throw new Ui(l,f,o);p=v}let x=U(o),m=d(p,x);lx(m,a,x)},find:(c,p)=>Sn(o,c,p),seek:(c,p)=>Bn(o,c,p),json:(c)=>Zn(o,c)});var xa=(n,i,o)=>{let c=U(n),p=new xn,a=new Set,{get:x,find:m,seek:l,json:f}=Mx(i.key,a,c),v=()=>{let M=i.get({get:x,find:m,seek:l,json:f});return Zi(i.key,M,p,U(n)),a.clear(),M},$={...i,subject:p,install:(M)=>xa(M,i,o),get:v,type:"readonly_selector",...o&&{family:o}};c.readonlySelectors.set(i.key,$);let T=v();n.logger.info("\u2728",$.type,$.key,"=",T);let F={key:i.key,type:"readonly_selector"};if(o)F.family=o;return F};var $a=(n,i,o)=>{let c=U(n),p=new xn,a=new Set,x=Mx(i.key,a,c),{find:m,get:l,seek:f,json:v}=x,$={find:m,get:l,seek:f,json:v},T=(G=i.get,Q=U(n))=>{let b=G($);return Zi(i.key,b,p,Q),a.clear(),b},M={...i,subject:p,install:(G)=>$a(G,i,o),get:T,set:(G)=>{let Q=U(n),b=T(i.get,Q),D=mx(G)(b);if(n.logger.info("\uD83D\uDCDD","selector",i.key,"set (",b,"->",D,")"),Zi(i.key,D,p,Q),ec(Q,i.key),tn(Q))p.next({newValue:D,oldValue:b});i.set(x,D)},type:"selector",...o&&{family:o}};c.selectors.set(i.key,M);let A=T();n.logger.info("\u2728",M.type,M.key,"=",A);let R={key:i.key,type:"selector"};if(o)R.family=o;return R};function pa(n,i){if("set"in i){let p=$a(n,i,void 0);return n.on.selectorCreation.next(p),p}let c=xa(n,i,void 0);return n.on.selectorCreation.next(c),c}function i0(n,i){let o=U(i),{key:c}=n,p=d(n,o);if(!p.family)i.logger.error("\u274C","selector",c,"Standalone selectors cannot be disposed.");else{let a=o.molecules.get(p.family.subKey);if(a)a.tokens.delete(c);switch(n.type){case"selector":o.selectors.delete(c),d({key:p.family.key,type:"selector_family"},i).subject.next({type:"state_disposal",token:n});break;case"readonly_selector":o.readonlySelectors.delete(c),d({key:p.family.key,type:"readonly_selector_family"},i).subject.next({type:"state_disposal",token:n});break}if(o.valueMap.delete(c),o.selectorAtoms.delete(c),o.selectorGraph.delete(c),i.logger.info("\uD83D\uDD25",n.type,c,"deleted"),Fn(o)&&o.transactionMeta.phase==="building")o.transactionMeta.update.updates.push({type:"state_disposal",token:n});else i.on.selectorDisposal.next(n)}}function ma(n,i,o){let c={key:i.key,type:"selector_family"},p=n.families.get(i.key);if(p)n.logger.error("\u2757","selector_family",i.key,`Overwriting an existing ${mo(p)} "${p.key}" in store "${n.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);let a=new xn,m=Object.assign((l)=>{let f=r(l),v={key:i.key,subKey:f},$=`${i.key}(${f})`,T=U(n),F=$a(T,{key:$,get:i.get(l),set:i.set(l)},v);return a.next({type:"state_creation",token:F}),F},c,{internalRoles:o,subject:a,install:(l)=>ma(l,i),default:(l)=>{return i.get(l)({get:(...v)=>Mn(n,...v),find:(v,$)=>Sn(n,v,$),seek:(v,$)=>Bn(n,v,$),json:(v)=>Zn(n,v)})}});return n.families.set(i.key,m),c}function a0(n,i,o=nn.STORE){let c=ma(o,{key:`${n.key}:JSON`,get:(a)=>({seek:x,get:m})=>{let l=x(n,a);if(l)return i.toJson(m(l));let f=r(a),v=o.molecules.get(f);if(v){let T=lo(v,n,o);return i.toJson(m(T))}if(o.config.lifespan==="immortal")throw new Error(`No molecule found for key "${f}"`);let $=_o(o,n,a);return i.toJson(m($))},set:(a)=>({seek:x,set:m},l)=>{let f=x(n,a);if(f)m(f,i.fromJson(l));else{let v=r(a),$=o.molecules.get(v);if($){let T=lo($,n,o);m(T,i.fromJson(l))}else{if(o.config.lifespan==="immortal")throw new Error(`No molecule found for key "${v}"`);m(_o(o,n,a),i.fromJson(l))}}}},["mutable","json"]);return d(n,o).subject.subscribe(`store=${o.config.name}::json-selector-family`,(a)=>{if(a.token.family)Bn(o,c,oi(a.token.family.subKey))}),c}var oi=(n)=>JSON.parse(n),r=(n)=>JSON.stringify(n),YE=[Array.prototype,Boolean.prototype,Number.prototype,Object.prototype,String.prototype];var x0=(n,i)=>{let o=U(i);if(o.operation.open)return o.operation.prev.get(n.key);return o.valueMap.get(n.key)};var Hl=(n,i)=>{let o=U(i);return c0(n,i).map((p)=>{let a=o.atoms.get(p);if(a===void 0)throw new Error(`Atom "${p}", a dependency of selector "${n.key}", not found in store "${i.config.name}".`);return a.subject.subscribe(`${n.type}:${n.key}`,(x)=>{i.logger.info("\uD83D\uDCE2",n.type,n.key,"root",p,"went",x.oldValue,"->",x.newValue);let m=x0(n,o),l=Po(n,o);i.logger.info("\u2728",n.type,n.key,"went",m,"->",l),n.subject.next({newValue:l,oldValue:m})})})};function Si(n,i,o,c){function p($){if(c.operation.open){let T=c.on.operationClose.subscribe(`state subscription ${o}`,()=>{T(),i($)})}else i($)}let a=d(n,c);c.logger.info("\uD83D\uDC40",a.type,a.key,`Adding subscription "${o}"`);let x=a.type==="selector"||a.type==="readonly_selector",m=null,l=p;if(x)m=Hl(a,c),l=($)=>{if(m)m.length=0,m.push(...Hl(a,c));p($)};let f=a.subject.subscribe(o,l);return()=>{if(c.logger.info("\uD83D\uDE48",a.type,a.key,`Removing subscription "${o}"`),f(),m)for(let $ of m)$()}}var zl=(n,i,o,c)=>{let p=d(n,c);c.logger.info("\uD83D\uDC40","timeline",n.key,`Adding subscription "${o}"`);let a=p.subject.subscribe(o,i);return()=>{c.logger.info("\uD83D\uDE48","timeline",n.key,`Removing subscription "${o}" from timeline`),a()}};var Ql=(n,i,o,c)=>{let p=d(n,c);c.logger.info("\uD83D\uDC40","transaction",n.key,`Adding subscription "${o}"`);let a=p.subject.subscribe(o,i);return()=>{c.logger.info("\uD83D\uDE48","transaction",n.key,`Removing subscription "${o}"`),a()}};class ro{Update;initializeState(n,i){let o=`*${n.key}`;i.atoms.delete(o),i.valueMap.delete(o);let c=n.family?{key:`*${n.family.key}`,subKey:n.family.subKey}:void 0,p=Zo(i,{key:o,default:null},c);if(i.parent?.valueMap.has(o)){let a=i.parent.valueMap.get(o);i.valueMap.set(o,a)}return p}unsubscribeFromInnerValue;unsubscribeFromState;observeCore(n,i,o){let c=`tracker:${o.config.name}:${Fn(o)?o.transactionMeta.update.key:"main"}:${n.key}`,p=Mn(o,n);this.unsubscribeFromInnerValue=p.subscribe(c,(a)=>{Qn(o,i,a)}),this.unsubscribeFromState=Si(n,(a)=>{if(a.newValue!==a.oldValue)this.unsubscribeFromInnerValue(),this.unsubscribeFromInnerValue=a.newValue.subscribe(c,(x)=>{Qn(o,i,x)})},c,o)}updateCore(n,i,o){let c=`tracker:${o.config.name}:${Fn(o)?o.transactionMeta.update.key:"main"}:${n.key}`;Si(i,({newValue:p,oldValue:a})=>{let x=o.timelineTopics.getRelatedKey(i.key);if(x){if(o.timelines.get(x)?.timeTraveling){let f=zl({key:x,type:"timeline"},(v)=>{f(),Qn(o,n,($)=>{if(v==="redo"&&p)$.do(p);else if(v==="undo"&&a)$.undo(a);return $})},c,o);return}}let m=o.on.operationClose.subscribe(c,()=>{m();let l=Mn(o,n),f=p===null?-1:l.getUpdateNumber(p),v=f-l.cacheUpdateNumber;if(p&&v===1)Qn(o,n,($)=>($.do(p),$));else o.logger.info("\u274C","mutable_atom",n.key,`could not be updated. Expected update number ${l.cacheUpdateNumber+1}, but got ${f}`)})},c,o)}mutableState;latestUpdateState;dispose;constructor(n,i){this.mutableState=n;let o=U(i);this.latestUpdateState=this.initializeState(n,o),this.observeCore(n,this.latestUpdateState,o),this.updateCore(n,this.latestUpdateState,o),o.trackers.set(n.key,this),this.dispose=()=>{this.unsubscribeFromInnerValue(),this.unsubscribeFromState(),o.trackers.delete(n.key)}}}function Ta(n,i,o){n.logger.info("\uD83D\uDD28","atom",i.key,`creating in store "${n.config.name}"`);let c=U(n),p=c.atoms.get(i.key);if(p&&p.type==="mutable_atom")return n.logger.error("\u274C","atom",i.key,"Tried to create atom, but it already exists in the store."),si(p);let a=new xn,x={...i,type:"mutable_atom",install:(f)=>{return f.logger.info("\uD83D\uDEE0\uFE0F","atom",i.key,`installing in store "${f.config.name}"`),Ta(f,i,o)},subject:a};if(o)x.family=o;let m=i.default();c.atoms.set(x.key,x),Rx(i.key,n),Zi(i.key,m,a,c);let l=si(x);if(i.effects){let f=0,v=[];for(let $ of i.effects){let T=$({setSelf:(F)=>{Qn(n,l,F)},onSet:(F)=>Si(l,F,`effect[${f}]`,n)});if(T)v.push(T);++f}x.cleanup=()=>{for(let $ of v)$()}}if(new ro(l,n),!o)E$(l,i,n);return l}class El{Update;latestUpdateAtoms;mutableAtoms;constructor(n,i){let o=so(i,{key:`*${n.key}`,default:null},["mutable","updates"]);this.latestUpdateAtoms=d(o,i),this.mutableAtoms=n,this.mutableAtoms.subject.subscribe(`store=${i.config.name}::tracker-atom-family`,(c)=>{if(c.token.family){let p=oi(c.token.family.subKey);Bn(i,this.latestUpdateAtoms,p),new ro(c.token,i)}}),this.latestUpdateAtoms.subject.subscribe(`store=${i.config.name}::tracker-atom-family`,(c)=>{if(c.token.family){let p=oi(c.token.family.subKey),a=Bn(i,this.mutableAtoms,p);if(a)new ro(a,i)}})}}function aa(n,i,o){let c={key:i.key,type:"mutable_atom_family"},p=n.families.get(i.key);if(p)n.logger.error("\u2757","mutable_atom_family",i.key,`Overwriting an existing ${mo(p)} "${p.key}" in store "${n.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);let a=new xn,m=Object.assign((l)=>{let f=r(l),v={key:i.key,subKey:f},$=`${i.key}(${f})`,T=U(n),F={key:$,default:()=>i.default(l),toJson:i.toJson,fromJson:i.fromJson,mutable:!0};if(i.effects)F.effects=i.effects(l);let M=Ta(T,F,v);return a.next({type:"state_creation",token:M}),M},c,{subject:a,install:(l)=>aa(l,i),toJson:i.toJson,fromJson:i.fromJson,internalRoles:o});return n.families.set(i.key,m),a0(m,i,n),new El(m,n),c}var Sl=(n,i)=>{let o=U(i),c=`${n.key}:JSON`;return o.families.get(c)};var Zn=(n,i)=>{if(i.family){let c=U(n),a={key:`${i.family.key}:JSON`,type:"selector_family"},x=d(a,c),m=JSON.parse(i.family.subKey);return Sn(n,x,m)}return{type:"selector",key:`${i.key}:JSON`}};var jo=(n)=>{let o={type:"atom",key:`*${n.key}`};if(n.family)o.family={key:`*${n.family.key}`,subKey:n.family.subKey};return o};function N$(n){return typeof n==="object"&&n!==null&&"do"in n&&"undo"in n&&"subscribe"in n}function la(n,i,o){let c=i.valueMap.get(n.key),p=o.valueMap.get(n.key);if(c===p){if(c===void 0)return typeof n.default==="function"?n.default():n.default;i.logger.info("\uD83D\uDCC3","atom",n.key,"copying");let a=n.toJson(c),x=n.fromJson(a);return o.valueMap.set(n.key,x),new ro(n,i),x}return p}function Zi(n,i,o,c){let p=c.valueMap.get(n);if(p instanceof ca)p.use(i);if(i instanceof Promise){let a=new ca(i);return c.valueMap.set(n,a),a.then((x)=>{Zi(n,x,o,c),o.next({newValue:x,oldValue:a})}).catch((x)=>{c.logger.error("\uD83D\uDCA5","state",n,"rejected:",x)}),a}return c.valueMap.set(n,i),i}var u$=(n,i)=>{let o=i.valueMap.get(n.key);if(n.type==="mutable_atom"&&Fn(i)){let{parent:c}=i;o=la(n,c,i)}return o},B$=(n,i)=>{let o=i.valueMap.get(n);if(o instanceof ca){let c=o,p=i.selectors.get(n)??i.readonlySelectors.get(n);if(p)c.use(p.get());return}if(i.operation.open)i.operation.prev.set(n,o);i.valueMap.delete(n),i.logger.info("\uD83D\uDDD1","state",n,"evicted")};var C$=(n,i)=>{return U(i).atomsThatAreDefault.has(n)},Rx=(n,i)=>{let o=U(i);o.atomsThatAreDefault=new Set(o.atomsThatAreDefault).add(n)},h$=(n,i)=>{let o=U(i);o.atomsThatAreDefault=new Set(U(i).atomsThatAreDefault),o.atomsThatAreDefault.delete(n)};function Zo(n,i,o){n.logger.info("\uD83D\uDD28","atom",i.key,`creating in store "${n.config.name}"`);let c=U(n),p=c.atoms.get(i.key);if(p&&p.type==="atom")return n.logger.error("\u274C","atom",i.key,"Tried to create atom, but it already exists in the store."),si(p);let a=new xn,x={...i,type:"atom",install:(f)=>{return f.logger.info("\uD83D\uDEE0\uFE0F","atom",i.key,`installing in store "${f.config.name}"`),Zo(f,i,o)},subject:a};if(o)x.family=o;let m=i.default;if(i.default instanceof Function)m=i.default();c.atoms.set(x.key,x),Rx(i.key,n),Zi(i.key,m,a,c);let l=si(x);if(i.effects){let f=0,v=[];for(let $ of i.effects){let T=$({setSelf:(F)=>{Qn(n,l,F)},onSet:(F)=>Si(l,F,`effect[${f}]`,n)});if(T)v.push(T);++f}x.cleanup=()=>{for(let $ of v)$()}}return l}function m0(n,i){if("mutable"in i){let p=Ta(n,i,void 0);return n.on.atomCreation.next(p),p}let c=Zo(n,i,void 0);return n.on.atomCreation.next(c),c}function Gl(n,i){let o=U(i),{key:c}=n,p=d(n,o);if(!p.family)i.logger.error("\u274C","atom",c,"Standalone atoms cannot be disposed.");else{p.cleanup?.();let a=i.valueMap.get(p.key);d({key:p.family.key,type:"atom_family"},i).subject.next({type:"state_disposal",token:n,value:a});let m=o.molecules.get(p.family.subKey);if(m)m.tokens.delete(c);if(o.atoms.delete(c),o.valueMap.delete(c),o.selectorAtoms.delete(c),o.atomsThatAreDefault.delete(c),i.timelineTopics.delete(c),n.type==="mutable_atom"){let l=jo(n);Gl(l,i),i.trackers.delete(c)}if(i.logger.info("\uD83D\uDD25","atom",c,"deleted"),Fn(o)&&o.transactionMeta.phase==="building")o.transactionMeta.update.updates.push({type:"state_disposal",token:n});else i.on.atomDisposal.next(n)}}var iV=Symbol("provenance");function Fl(n,i,o){let c=r(o);try{let p=[],a;if(i==="root")p.push(n.molecules.get('"root"')),a="all";else if(typeof i==="string"&&i.startsWith(x8)){a="any";let v=r(i),$=n.molecules.get(v);if(!$)throw new Error(`Molecule ${v} not found in store "${n.config.name}"`);p.push($)}else if(o.startsWith("T$--")){a="all";for(let $ of i){let T=r($),F=n.molecules.get(T);if(!F)throw new Error(`Molecule ${T} not found in store "${n.config.name}"`);p.push(F)}}else{a="any";let $=r(i),T=n.molecules.get($);if(!T)throw new Error(`Molecule ${$} not found in store "${n.config.name}"`);p.push(T)}let x=new ip(p,o);x._dependsOn=a,n.molecules.set(c,x);for(let v of p)v.below.set(x.stringKey,x);let m={type:"molecule_creation",subType:"modern",key:x.key,provenance:i},l=U(n);if(Fn(l)&&l.transactionMeta.phase==="building")l.transactionMeta.update.updates.push(m);else l.on.moleculeCreationStart.next(m)}catch(p){if(p instanceof Error)n.logger.error("\u274C","molecule",c,"allocation failed:",p.message)}return o}function va(n,i){let o=r(i),c=n.molecules.get(o);if(!c)throw new Error(`Molecule ${o} not found in store "${n.config.name}"`);for(let f of c.joins.values())f.relations.delete(c.key),f.molecules.delete(c.stringKey);let p;if(c.above.size===1)p=c.above.values().next().value.key;else p=[...c.above.values()].map(({key:f})=>f);let a=[];for(let f of c.tokens.values()){let v=f.family;a.push([v.key,n.valueMap.get(f.key)])}for(let f of c.tokens.values())zi(n,f);for(let f of c.below.values())if(f.dependsOn==="all")va(n,f.key);else if(f.above.delete(c.stringKey),f.above.size===0)va(n,f.key);c.below.clear();let x={type:"molecule_disposal",subType:"modern",key:c.key,values:a,provenance:p},m=U(n);if(Fn(m)&&m.transactionMeta.phase==="building")m.transactionMeta.update.updates.push(x);else m.on.moleculeDisposal.next(x);m.molecules.delete(c.stringKey);for(let f of c.above.values())f.below.delete(c.stringKey)}var x8="T$";function go(n){return m0(nn.STORE,n)}function Kc(n){return U$(nn.STORE,n)}var Ol=(n)=>(i,o,c,p,...a)=>{console[n](`${i} ${o} "${c}" ${p}`,...a)},m8={error:Ol("error"),info:Ol("info"),warn:Ol("warn")};class Wc{n;i;o;constructor(n,i,o=m8){this.logLevel=n;this.filter=i;this.logger=o}error=(...n)=>{if((this.filter?.(...n)??!0)&&this.logLevel!==null)this.logger.error(...n)};info=(...n)=>{if((this.filter?.(...n)??!0)&&this.logLevel==="info")this.logger.info(...n)};warn=(...n)=>{if((this.filter?.(...n)??!0)&&this.logLevel!=="error"&&this.logLevel!==null)this.logger.warn(...n)}}function Wx(n){return Tl(nn.STORE,n)}function Xc(n){return Xl(n,nn.STORE)}class l0 extends Map{set(n,i){if(this.has(n))return console.warn("Tried to set a key that already exists in an InvariantMap",{key:n,value:i}),this;return super.set(n,i)}clear(){throw new Error("Cannot clear an InvariantMap")}}class Kx{n;type="continuity";globals=[];actions=[];perspectives=[];constructor(n){this.key=n}static existing=new l0;static create(n,i){let o=new Kx(n),{type:c,globals:p,actions:a,perspectives:x}=i(o),m={type:c,key:n,globals:p,actions:a,perspectives:x};return Kx.existing.set(n,m),m}add(...n){switch(n[0].type){case"atom":case"mutable_atom":this.globals.push(...n);break;case"transaction":this.actions.push(...n);break;case"atom_family":{let[o,c]=n;this.perspectives.push({type:"realtime_perspective",resourceAtoms:o,viewAtoms:c})}break}return this}}function f0(n){let{key:i,config:o}=n,c=Kx.create(i,o),{actions:p}=c;for(let a of p)g$(i,a.key,nn.STORE);return q$(i,-1,nn.STORE),c}var SV=go({key:"usersInRoomIndex",mutable:!0,default:()=>new ci,toJson:(n)=>n.toJSON(),fromJson:(n)=>ci.fromJSON(n)}),Ul=go({key:"roomIndex",default:()=>new ci,mutable:!0,toJson:(n)=>n.toJSON(),fromJson:(n)=>ci.fromJSON(n)}),l8={enteredAtEpoch:0},wa=$x({key:"usersInRooms",between:["room","user"],cardinality:"1:n",isAType:(n)=>typeof n==="string",isBType:(n)=>typeof n==="string"},l8),AV=Wx({key:"usersInMyRoomView",get:(n)=>({find:i})=>{let o=s$(wa);return[i(o,n)]}});import{spawn as f8}from"child_process";class op{n;listeners;globalListeners;handleEvent(n,...i){for(let c of this.globalListeners)c(n,...i);let o=this.listeners.get(n);if(o)for(let c of o)c(...i)}id="no_id_retrieved";constructor(n){this.emit=n;this.listeners=new Map,this.globalListeners=new Set}on(n,i){let o=this.listeners.get(n);if(o)o.add(i);else this.listeners.set(n,new Set([i]));return this}onAny(n){return this.globalListeners.add(n),this}off(n,i){let o=this.listeners.get(n);if(o)if(i)o.delete(i);else this.listeners.delete(n);return this}offAny(n){return this.globalListeners.delete(n),this}}class Ja extends op{n;i;o;incompleteData="";unprocessedEvents=[];incompleteLog="";unprocessedLogs=[];id="#####";handleLog(n){if(Array.isArray(n)){let[i,...o]=n;switch(i){case"i":this.logger.info(this.id,this.key,...o);break;case"w":this.logger.warn(this.id,this.key,...o);break;case"e":this.logger.error(this.id,this.key,...o);break}}}constructor(n,i,o=console){super((c,...p)=>{let a=JSON.stringify([c,...p])+"\x03",x=(m)=>{if(m.code==="EPIPE")console.error("EPIPE error during write",this.process.stdin);this.process.stdin.removeListener("error",x)};return this.process.stdin.once("error",x),this.process.stdin.write(a),this});this.process=n;this.key=i;this.logger=o;if(this.process=n,this.process.stdout.on("data",(c)=>{let p=c.toString();if(p==="\u2728")return;this.unprocessedEvents.push(...p.split("\x03"));let a=this.unprocessedEvents.shift();this.incompleteData+=a??"";try{if(this.incompleteData.startsWith("error"))console.log("\u2757",this.incompleteData);let x=oi(this.incompleteData);this.handleEvent(...x);while(this.unprocessedEvents.length>0){let m=this.unprocessedEvents.shift();if(m){if(this.unprocessedEvents.length===0)this.incompleteData=m;x=oi(m),this.handleEvent(...x)}}this.incompleteData=""}catch(x){console.warn("\u26A0\uFE0F----------------\u26A0\uFE0F"),console.warn(this.incompleteData),console.warn("\u26A0\uFE0F----------------\u26A0\uFE0F"),console.error(x)}}),this.process.stderr.on("data",(c)=>{let p=c.toString();this.unprocessedLogs.push(...p.split("\x03"));let a=this.unprocessedLogs.shift();this.incompleteLog+=a??"";try{let x=oi(this.incompleteLog);this.handleLog(x);while(this.unprocessedLogs.length>0)if(this.incompleteLog=this.unprocessedLogs.shift()??"",this.incompleteLog)x=oi(this.incompleteLog),this.handleLog(x)}catch(x){console.error("\u274C\u274C\u274C"),console.error(this.incompleteLog),console.error(x),console.error("\u274C\u274C\u274C\uFE0F")}}),n.pid)this.id=n.pid.toString()}}class v0 extends op{in;out;id="no_id_retrieved";disposalFunctions=[];constructor(n){super((...i)=>{return this.out.next(i),this});this.id=n,this.in=new xn,this.out=new xn,this.in.subscribe("socket",(i)=>{this.handleEvent(...i)})}dispose(){for(let n of this.disposalFunctions)n()}}class Vl extends op{incompleteData="";unprocessedEvents=[];relays;relayServices;process;id="#####";log(...n){this.process.stderr.write(r(n.map((i)=>i instanceof ci?`{ ${i.toJSON().members.join(" | ")} }`:i))+"\x03")}logger={info:(...n)=>{this.log("i",...n)},warn:(...n)=>{this.log("w",...n)},error:(...n)=>{this.log("e",...n)}};constructor(){super((n,...i)=>{let o=JSON.stringify([n,...i]);return this.process.stdout.write(o+"\x03"),this});if(this.process=process,this.process.stdin.resume(),this.relays=new Map,this.relayServices=[],this.process.stdin.on("data",(n)=>{let i=n.toString();this.unprocessedEvents.push(...i.split("\x03"));let o=this.unprocessedEvents.shift();this.incompleteData+=o??"";try{let c=oi(this.incompleteData);this.logger.info("\uD83C\uDFB0","received",c),this.handleEvent(...c);while(this.unprocessedEvents.length>0){let p=this.unprocessedEvents.shift();if(p){if(this.unprocessedEvents.length===0)this.incompleteData=p;let a=oi(p);this.handleEvent(...a)}}this.incompleteData=""}catch(c){if(c instanceof Error)this.logger.error("\u2757",c.message,c.cause,c.stack)}}),this.on("exit",()=>{this.logger.info("\uD83D\uDD25",this.id,'received "exit"'),process.exit(0)}),process.on("exit",(n)=>{this.logger.info("\uD83D\uDD25",this.id,`exited with code ${n}`)}),process.on("end",()=>{this.logger.info("\uD83D\uDD25",this.id,"ended"),process.exit(0)}),process.on("SIGTERM",()=>{this.logger.error("\uD83D\uDD25",this.id,"terminated"),process.exit(0)}),process.on("SIGINT",()=>{this.logger.error("\uD83D\uDD25",this.id,"interrupted"),process.exit(0)}),process.pid)this.id=process.pid?.toString();this.on("user-joins",(n)=>{this.logger.info("\uD83D\uDC64","user",n,"joined");let i=new v0(`user:${n}`);this.relays.set(n,i),this.logger.info("\uD83D\uDD17","attaching services:",`[${[...this.relayServices.keys()].join(", ")}]`);for(let o of this.relayServices){let c=o(i);if(c)i.disposalFunctions.push(c)}this.on(`user:${n}`,(...o)=>{i.in.next(o)}),i.out.subscribe("socket",(o)=>{this.emit(...o)})}),this.on("user-leaves",(n)=>{let i=this.relays.get(n);if(this.off(`relay:${n}`),i)i.dispose(),this.relays.delete(n)}),process.stdout.write("\u2728")}relay(n){this.logger.info("\uD83D\uDD17","running relay method"),this.relayServices.push(n)}}var ul=Kc({key:"roomArguments",default:["echo",["Hello World!"]]}),$0=Wx({key:"room",get:(n)=>async({get:i,find:o})=>{let c=o(ul,n),p=i(c),[a,x]=p,m=await new Promise((l)=>{let f=f8(a,x,{env:process.env}),v=($)=>{if($.toString()==="\u2728")f.stdout.off("data",v),l(f)};f.stdout.on("data",v)});return new Ja(m,n)}});var kV=Xc({key:"createRoom",do:({get:n,set:i,find:o},c,p,a)=>{let x=a?[p,a]:[p],m=o(ul,c);i(m,x),i(Ul,(v)=>v.add(c));let l=o($0,c);return n(l)}}),sV=Xc({key:"joinRoom",do:(n,i,o,c)=>{let p={enteredAtEpoch:c};return Rc(wa,(a)=>{a.set({room:i,user:o},p)},n.env().store),p}}),ZV=Xc({key:"leaveRoom",do:(n,i,o)=>{Rc(wa,(c)=>{c.delete({room:i,user:o})},n.env().store)}}),tV=Xc({key:"destroyRoom",do:(n,i)=>{Rc(wa,(o)=>{o.delete({room:i})},n.env().store),n.set(Ul,(o)=>(o.delete(i),o))}});function _l(n,i){return i.map((o)=>{switch(o.type){case"transaction_update":{let c=_l(n,o.updates);return{...o,updates:c}}default:return o}}).filter((o)=>{switch(o.type){case"atom_update":case"selector_update":return n.includes(o.key);case"state_creation":return n.includes(o.token.key);case"molecule_creation":return!0;case"transaction_update":return!0}})}var rV=Kc({key:"redactor",default:{occlude:(n)=>n}}),cp=Kc({key:"unacknowledgedUpdates",default:()=>[]});var Xx=Kc({key:"sockets",default:null}),bl=go({key:"socketsIndex",mutable:!0,default:()=>new ci,toJson:(n)=>n.toJSON(),fromJson:(n)=>ci.fromJSON(n)}),jl=go({key:"usersIndex",mutable:!0,default:()=>new ci,toJson:(n)=>n.toJSON(),fromJson:(n)=>ci.fromJSON(n)}),Gc=$x({key:"usersOfSockets",between:["user","socket"],cardinality:"1:1",isAType:(n)=>n.startsWith("user::"),isBType:(n)=>n.startsWith("socket::")});function T0(n,i,o,c){let p=i.key;return function a(){let x=[];for(let l of i.globals){let f=l.type==="mutable_atom"?Zn(n,l):l,v=Mn(n,f);x.push(f,v)}for(let l of i.perspectives){let{viewAtoms:f,resourceAtoms:v}=l,$=Sn(n,f,o),T=Mn(n,$);n.logger.info("\uD83D\uDC41","atom",v.key,`${o} can see`,{viewAtoms:f,resourceAtoms:v,userView:T});for(let F of T){let M=F.type==="mutable_atom"?Zn(n,F):F,A=Mn(n,M);x.push(M,A)}}let m=tn(n)?n.transactionMeta.epoch.get(p)??null:null;c?.emit(`continuity-init:${p}`,m,x)}}function w0(n,i,o){let c=i.key;return function p(a){n.logger.info("\uD83D\uDECE\uFE0F","continuity",c,"received",a);let{key:x,id:m}=a,l=`tx-run:${x}:${m}`,f=`${l}:start`,v=`${l}:end`;performance.mark(f);try{qo({type:"transaction",key:x},m,n)(...a.params)}catch(T){if(T instanceof Error)n.logger.error("\u274C","continuity",c,`failed to run transaction ${x} from ${o} with update ${m}`,T.message)}performance.mark(v);let $=performance.measure(l,f,v);n?.logger.info("\uD83D\uDE80","transaction",x,m,o,$.duration)}}function J0(n,i,o,c){let p=i.key;return function a(x){if(n.logger.info("\uD83D\uDC4D","continuity",p,`${o} acknowledged epoch ${x}`),c[0]?.epoch===x)Qn(n,cp,o,(l)=>{return l.shift(),n.logger.info("\uD83D\uDC4D","continuity",p,`${o} unacknowledged update queue now has`,l.length,"items"),l})}}function S0(n,i,o,c){let p=i.key,a=[];for(let x of i.actions){let m=Ql(x,(l)=>{try{let f=i.globals.map((T)=>{if(T.type==="atom")return T.key;return jo(T).key}).concat(i.perspectives.flatMap((T)=>{let{viewAtoms:F}=T,M=Sn(n,F,o);return Mn(n,M).map((R)=>{return R.type==="mutable_atom"?"*"+R.key:R.key})})),v=_l(f,l.updates),$={...l,updates:v};Qn(n,cp,o,(T)=>{if($)T.push($),T.sort((F,M)=>F.epoch-M.epoch),n.logger.info("\uD83D\uDC4D","continuity",p,`${o} unacknowledged update queue now has`,T.length,"items");return T}),c?.emit(`tx-new:${p}`,$)}catch(f){if(f instanceof Error)n.logger.error("\u274C","continuity",p,`${o} failed to send update from transaction ${x.key} to ${o}`,f.message)}},`sync-continuity:${p}:${o}`,n);a.push(m)}return a}function A0(n,i,o,c){let p=i.key,a=[];for(let x of i.perspectives){let{viewAtoms:m}=x,l=Sn(n,m,o),f=Si(l,({oldValue:v,newValue:$})=>{let T=v.map((R)=>R.key),F=$.map((R)=>R.key),M=v.filter((R)=>!F.includes(R.key)),A=$.filter((R)=>!T.includes(R.key)).flatMap((R)=>{let G=R.type==="mutable_atom"?Zn(n,R):R,Q=Mn(n,G);return[G,Q]});if(n.logger.info("\uD83D\uDC41","atom",x.resourceAtoms.key,`${o} has a new perspective`,{oldKeys:T,newKeys:F,revealed:A,concealed:M}),A.length>0)c?.emit(`reveal:${p}`,A);if(M.length>0)c?.emit(`conceal:${p}`,M)},`sync-continuity:${p}:${o}:perspective:${x.resourceAtoms.key}`,n);a.push(f)}return a}function F0({socket:n,store:i=nn.STORE}){return function o(c){let p=n,a=c.key,x=np(Gc,`socket::${p.id}`,i).userKeyOfSocket,m=Mn(i,x);if(!m)return i.logger.error("\u274C","continuity",a,`Tried to create a synchronizer for a socket (${p.id}) that is not connected to a user.`),()=>{};let l=np(Gc,m,i).socketKeyOfUser,f=Si(l,({newValue:G})=>{if(i.logger.info("\uD83D\uDC4B","continuity",a,`seeing ${m} on new socket ${G}`),G===null){i.logger.warn("\u274C","continuity",a,`User (${m}) is not connected to a socket, waiting for them to reappear.`);return}let Q=Sn(i,Xx,G);p=Mn(i,Q);for(let D of v)p?.emit(`tx-new:${a}`,D)},`sync-continuity:${a}:${m}`,i),v=Mn(i,cp,m),$=[],T=A0(i,c,m,p),F=S0(i,c,m,p);$.push(...T,...F);let M=T0(i,c,m,n);p.off(`get:${a}`,M),p.on(`get:${a}`,M);let A=w0(i,c,m);p.off(`tx-run:${a}`,A),p.on(`tx-run:${a}`,A);let R=J0(i,c,m,v);return p?.on(`ack:${a}`,R),()=>{for(let G of $)G();p?.off(`ack:${a}`,R),p?.off(`get:${a}`,M),p?.off(`tx-run:${a}`,A)}}}var i4=vl($f(),1);var J=Symbol.for("drizzle:entityKind"),v_=Symbol.for("drizzle:hasOwnEntityKind");function z(n,i){if(!n||typeof n!=="object")return!1;if(n instanceof i)return!0;if(!Object.prototype.hasOwnProperty.call(i,J))throw new Error(`Class "${i.name??"<unknown>"}" doesn't look like a Drizzle entity. If this is incorrect and the class is provided by Drizzle, please report this as a bug.`);let o=Object.getPrototypeOf(n).constructor;if(o)while(o){if(J in o&&o[J]===i[J])return!0;o=Object.getPrototypeOf(o)}return!1}class bn{constructor(n,i){this.table=n,this.config=i,this.name=i.name,this.keyAsName=i.keyAsName,this.notNull=i.notNull,this.default=i.default,this.defaultFn=i.defaultFn,this.onUpdateFn=i.onUpdateFn,this.hasDefault=i.hasDefault,this.primary=i.primaryKey,this.isUnique=i.isUnique,this.uniqueName=i.uniqueName,this.uniqueType=i.uniqueType,this.dataType=i.dataType,this.columnType=i.columnType,this.generated=i.generated,this.generatedIdentity=i.generatedIdentity}static[J]="Column";name;keyAsName;primary;notNull;default;defaultFn;onUpdateFn;hasDefault;isUnique;uniqueName;uniqueType;dataType;columnType;enumValues=void 0;generated=void 0;generatedIdentity=void 0;config;mapFromDriverValue(n){return n}mapToDriverValue(n){return n}shouldDisableInsert(){return this.config.generated!==void 0&&this.config.generated.type!=="byDefault"}}class Tf{static[J]="ColumnBuilder";config;constructor(n,i,o){this.config={name:n,keyAsName:n==="",notNull:!1,default:void 0,hasDefault:!1,primaryKey:!1,isUnique:!1,uniqueName:void 0,uniqueType:void 0,dataType:i,columnType:o,generated:void 0}}$type(){return this}notNull(){return this.config.notNull=!0,this}default(n){return this.config.default=n,this.config.hasDefault=!0,this}$defaultFn(n){return this.config.defaultFn=n,this.config.hasDefault=!0,this}$default=this.$defaultFn;$onUpdateFn(n){return this.config.onUpdateFn=n,this.config.hasDefault=!0,this}$onUpdate=this.$onUpdateFn;primaryKey(){return this.config.primaryKey=!0,this.config.notNull=!0,this}setName(n){if(this.config.name!=="")return;this.config.name=n}}var To=Symbol.for("drizzle:Name");class wf{static[J]="PgForeignKeyBuilder";reference;_onUpdate="no action";_onDelete="no action";constructor(n,i){if(this.reference=()=>{let{name:o,columns:c,foreignColumns:p}=n();return{name:o,columns:c,foreignTable:p[0].table,foreignColumns:p}},i)this._onUpdate=i.onUpdate,this._onDelete=i.onDelete}onUpdate(n){return this._onUpdate=n===void 0?"no action":n,this}onDelete(n){return this._onDelete=n===void 0?"no action":n,this}build(n){return new K1(n,this)}}class K1{constructor(n,i){this.table=n,this.reference=i.reference,this.onUpdate=i._onUpdate,this.onDelete=i._onDelete}static[J]="PgForeignKey";reference;onUpdate;onDelete;getName(){let{name:n,columns:i,foreignColumns:o}=this.reference(),c=i.map((x)=>x.name),p=o.map((x)=>x.name),a=[this.table[To],...c,o[0].table[To],...p];return n??`${a.join("_")}_fk`}}function Ix(n,...i){return n(...i)}function X1(n,i){return`${n[To]}_${i.join("_")}_unique`}function G1(n,i,o){for(let c=i;c<n.length;c++){let p=n[c];if(p==="\\"){c++;continue}if(p==='"')return[n.slice(i,c).replace(/\\/g,""),c+1];if(o)continue;if(p===","||p==="}")return[n.slice(i,c).replace(/\\/g,""),c]}return[n.slice(i).replace(/\\/g,""),n.length]}function Y1(n,i=0){let o=[],c=i,p=!1;while(c<n.length){let a=n[c];if(a===","){if(p||c===i)o.push("");p=!0,c++;continue}if(p=!1,a==="\\"){c+=2;continue}if(a==='"'){let[l,f]=G1(n,c+1,!0);o.push(l),c=f;continue}if(a==="}")return[o,c+1];if(a==="{"){let[l,f]=Y1(n,c+1);o.push(l),c=f;continue}let[x,m]=G1(n,c,!1);o.push(x),c=m}return[o,c]}function z1(n){let[i]=Y1(n,1);return i}function Jf(n){return`{${n.map((i)=>{if(Array.isArray(i))return Jf(i);if(typeof i==="string")return`"${i.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`;return`${i}`}).join(",")}}`}class I extends Tf{foreignKeyConfigs=[];static[J]="PgColumnBuilder";array(n){return new H1(this.config.name,this,n)}references(n,i={}){return this.foreignKeyConfigs.push({ref:n,actions:i}),this}unique(n,i){return this.config.isUnique=!0,this.config.uniqueName=n,this.config.uniqueType=i?.nulls,this}generatedAlwaysAs(n){return this.config.generated={as:n,type:"always",mode:"stored"},this}buildForeignKeys(n,i){return this.foreignKeyConfigs.map(({ref:o,actions:c})=>{return Ix((p,a)=>{let x=new wf(()=>{let m=p();return{columns:[n],foreignColumns:[m]}});if(a.onUpdate)x.onUpdate(a.onUpdate);if(a.onDelete)x.onDelete(a.onDelete);return x.build(i)},o,c)})}buildExtraConfigColumn(n){return new Q1(n,this.config)}}class u extends bn{constructor(n,i){if(!i.uniqueName)i.uniqueName=X1(n,[i.name]);super(n,i);this.table=n}static[J]="PgColumn"}class Q1 extends u{static[J]="ExtraConfigColumn";getSQLType(){return this.getSQLType()}indexConfig={order:this.config.order??"asc",nulls:this.config.nulls??"last",opClass:this.config.opClass};defaultConfig={order:"asc",nulls:"last",opClass:void 0};asc(){return this.indexConfig.order="asc",this}desc(){return this.indexConfig.order="desc",this}nullsFirst(){return this.indexConfig.nulls="first",this}nullsLast(){return this.indexConfig.nulls="last",this}op(n){return this.indexConfig.opClass=n,this}}class za{static[J]="IndexedColumn";constructor(n,i,o,c){this.name=n,this.keyAsName=i,this.type=o,this.indexConfig=c}name;keyAsName;type;indexConfig}class H1 extends I{static[J]="PgArrayBuilder";constructor(n,i,o){super(n,"array","PgArray");this.config.baseBuilder=i,this.config.size=o}build(n){let i=this.config.baseBuilder.build(n);return new Sf(n,this.config,i)}}class Sf extends u{constructor(n,i,o,c){super(n,i);this.baseColumn=o,this.range=c,this.size=i.size}size;static[J]="PgArray";getSQLType(){return`${this.baseColumn.getSQLType()}[${typeof this.size==="number"?this.size:""}]`}mapFromDriverValue(n){if(typeof n==="string")n=z1(n);return n.map((i)=>this.baseColumn.mapFromDriverValue(i))}mapToDriverValue(n,i=!1){let o=n.map((c)=>c===null?null:z(this.baseColumn,Sf)?this.baseColumn.mapToDriverValue(c,!0):this.baseColumn.mapToDriverValue(c));if(i)return o;return Jf(o)}}var Af=Symbol.for("drizzle:isPgEnum");function E1(n){return!!n&&typeof n==="function"&&Af in n&&n[Af]===!0}class O1 extends I{static[J]="PgEnumColumnBuilder";constructor(n,i){super(n,"string","PgEnumColumn");this.config.enum=i}build(n){return new U1(n,this.config)}}class U1 extends u{static[J]="PgEnumColumn";enum=this.config.enum;enumValues=this.config.enum.enumValues;constructor(n,i){super(n,i);this.enum=i.enum}getSQLType(){return this.enum.enumName}}function kx(n,i){return UW(n,i,void 0)}function UW(n,i,o){let c=Object.assign((p)=>new O1(p??"",c),{enumName:n,enumValues:i,schema:o,[Af]:!0});return c}class fi{static[J]="Subquery";constructor(n,i,o,c=!1){this._={brand:"Subquery",sql:n,selectedFields:i,alias:o,isWith:c}}}class Qa extends fi{static[J]="WithSubquery"}var V1="0.36.1";var Ff,Mf,Un={startActiveSpan(n,i){if(!Ff)return i();if(!Mf)Mf=Ff.trace.getTracer("drizzle-orm",V1);return Ix((o,c)=>c.startActiveSpan(n,(p)=>{try{return i(p)}catch(a){throw p.setStatus({code:o.SpanStatusCode.ERROR,message:a instanceof Error?a.message:"Unknown error"}),a}finally{p.end()}}),Ff,Mf)}};var hn=Symbol.for("drizzle:ViewBaseConfig");var sx=Symbol.for("drizzle:Schema"),u1=Symbol.for("drizzle:Columns"),_1=Symbol.for("drizzle:ExtraConfigColumns"),Rf=Symbol.for("drizzle:OriginalName"),Wf=Symbol.for("drizzle:BaseName"),b1=Symbol.for("drizzle:IsAlias"),j1=Symbol.for("drizzle:ExtraConfigBuilder"),VW=Symbol.for("drizzle:IsDrizzleTable");class L{static[J]="Table";static Symbol={Name:To,Schema:sx,OriginalName:Rf,Columns:u1,ExtraConfigColumns:_1,BaseName:Wf,IsAlias:b1,ExtraConfigBuilder:j1};[To];[Rf];[sx];[u1];[_1];[Wf];[b1]=!1;[VW]=!0;[j1]=void 0;constructor(n,i,o){this[To]=this[Rf]=n,this[sx]=i,this[Wf]=o}}function di(n){return n[To]}function Oc(n){return`${n[sx]??"public"}.${n[To]}`}function Kf(n){return n!==null&&n!==void 0&&typeof n.getSQL==="function"}function uW(n){let i={sql:"",params:[]};for(let o of n)if(i.sql+=o.sql,i.params.push(...o.params),o.typings?.length){if(!i.typings)i.typings=[];i.typings.push(...o.typings)}return i}class pi{static[J]="StringChunk";value;constructor(n){this.value=Array.isArray(n)?n:[n]}getSQL(){return new k([this])}}class k{constructor(n){this.queryChunks=n}static[J]="SQL";decoder=B1;shouldInlineParams=!1;append(n){return this.queryChunks.push(...n.queryChunks),this}toQuery(n){return Un.startActiveSpan("drizzle.buildSQL",(i)=>{let o=this.buildQueryFromSourceParams(this.queryChunks,n);return i?.setAttributes({"drizzle.query.text":o.sql,"drizzle.query.params":JSON.stringify(o.params)}),o})}buildQueryFromSourceParams(n,i){let o=Object.assign({},i,{inlineParams:i.inlineParams||this.shouldInlineParams,paramStartIndex:i.paramStartIndex||{value:0}}),{casing:c,escapeName:p,escapeParam:a,prepareTyping:x,inlineParams:m,paramStartIndex:l}=o;return uW(n.map((f)=>{if(z(f,pi))return{sql:f.value.join(""),params:[]};if(z(f,Zx))return{sql:p(f.value),params:[]};if(f===void 0)return{sql:"",params:[]};if(Array.isArray(f)){let v=[new pi("(")];for(let[$,T]of f.entries())if(v.push(T),$<f.length-1)v.push(new pi(", "));return v.push(new pi(")")),this.buildQueryFromSourceParams(v,o)}if(z(f,k))return this.buildQueryFromSourceParams(f.queryChunks,{...o,inlineParams:m||f.shouldInlineParams});if(z(f,L)){let v=f[L.Symbol.Schema],$=f[L.Symbol.Name];return{sql:v===void 0?p($):p(v)+"."+p($),params:[]}}if(z(f,bn)){let v=c.getColumnCasing(f);if(i.invokeSource==="indexes")return{sql:p(v),params:[]};return{sql:p(f.table[L.Symbol.Name])+"."+p(v),params:[]}}if(z(f,Vi)){let v=f[hn].schema,$=f[hn].name;return{sql:v===void 0?p($):p(v)+"."+p($),params:[]}}if(z(f,Li)){if(z(f.value,pc))return{sql:a(l.value++,f),params:[f],typings:["none"]};let v=f.value===null?null:f.encoder.mapToDriverValue(f.value);if(z(v,k))return this.buildQueryFromSourceParams([v],o);if(m)return{sql:this.mapInlineParam(v,o),params:[]};let $=["none"];if(x)$=[x(f.encoder)];return{sql:a(l.value++,v),params:[v],typings:$}}if(z(f,pc))return{sql:a(l.value++,f),params:[f],typings:["none"]};if(z(f,k.Aliased)&&f.fieldAlias!==void 0)return{sql:p(f.fieldAlias),params:[]};if(z(f,fi)){if(f._.isWith)return{sql:p(f._.alias),params:[]};return this.buildQueryFromSourceParams([new pi("("),f._.sql,new pi(") "),new Zx(f._.alias)],o)}if(E1(f)){if(f.schema)return{sql:p(f.schema)+"."+p(f.enumName),params:[]};return{sql:p(f.enumName),params:[]}}if(Kf(f)){if(f.shouldOmitSQLParens?.())return this.buildQueryFromSourceParams([f.getSQL()],o);return this.buildQueryFromSourceParams([new pi("("),f.getSQL(),new pi(")")],o)}if(m)return{sql:this.mapInlineParam(f,o),params:[]};return{sql:a(l.value++,f),params:[f],typings:["none"]}}))}mapInlineParam(n,{escapeString:i}){if(n===null)return"null";if(typeof n==="number"||typeof n==="boolean")return n.toString();if(typeof n==="string")return i(n);if(typeof n==="object"){let o=n.toString();if(o==="[object Object]")return i(JSON.stringify(n));return i(o)}throw new Error("Unexpected param value: "+n)}getSQL(){return this}as(n){if(n===void 0)return this;return new k.Aliased(this,n)}mapWith(n){return this.decoder=typeof n==="function"?{mapFromDriverValue:n}:n,this}inlineParams(){return this.shouldInlineParams=!0,this}if(n){return n?this:void 0}}class Zx{constructor(n){this.value=n}static[J]="Name";brand;getSQL(){return new k([this])}}function y1(n){return typeof n==="object"&&n!==null&&"mapToDriverValue"in n&&typeof n.mapToDriverValue==="function"}var B1={mapFromDriverValue:(n)=>n},L1={mapToDriverValue:(n)=>n},d_={...B1,...L1};class Li{constructor(n,i=L1){this.value=n,this.encoder=i}static[J]="Param";brand;getSQL(){return new k([this])}}function S(n,...i){let o=[];if(i.length>0||n.length>0&&n[0]!=="")o.push(new pi(n[0]));for(let[c,p]of i.entries())o.push(p,new pi(n[c+1]));return new k(o)}((n)=>{function i(){return new k([])}n.empty=i;function o(l){return new k(l)}n.fromList=o;function c(l){return new k([new pi(l)])}n.raw=c;function p(l,f){let v=[];for(let[$,T]of l.entries()){if($>0&&f!==void 0)v.push(f);v.push(T)}return new k(v)}n.join=p;function a(l){return new Zx(l)}n.identifier=a;function x(l){return new pc(l)}n.placeholder=x;function m(l,f){return new Li(l,f)}n.param=m})(S||(S={}));((n)=>{class i{constructor(o,c){this.sql=o,this.fieldAlias=c}static[J]="SQL.Aliased";isSelectionField=!1;getSQL(){return this.sql}clone(){return new i(this.sql,this.fieldAlias)}}n.Aliased=i})(k||(k={}));class pc{constructor(n){this.name=n}static[J]="Placeholder";getSQL(){return new k([this])}}function Xf(n,i){return n.map((o)=>{if(z(o,pc)){if(!(o.name in i))throw new Error(`No value for placeholder "${o.name}" was provided`);return i[o.name]}if(z(o,Li)&&z(o.value,pc)){if(!(o.value.name in i))throw new Error(`No value for placeholder "${o.value.name}" was provided`);return o.encoder.mapToDriverValue(i[o.value.name])}return o})}class Vi{static[J]="View";[hn];constructor({name:n,schema:i,selectedFields:o,query:c}){this[hn]={name:n,originalName:n,schema:i,selectedFields:o,query:c,isExisting:!c,isAlias:!1}}getSQL(){return new k([this])}}bn.prototype.getSQL=function(){return new k([this])};L.prototype.getSQL=function(){return new k([this])};fi.prototype.getSQL=function(){return new k([this])};class Ap{constructor(n){this.table=n}static[J]="ColumnAliasProxyHandler";get(n,i){if(i==="table")return this.table;return n[i]}}class Ha{constructor(n,i){this.alias=n,this.replaceOriginalName=i}static[J]="TableAliasProxyHandler";get(n,i){if(i===L.Symbol.IsAlias)return!0;if(i===L.Symbol.Name)return this.alias;if(this.replaceOriginalName&&i===L.Symbol.OriginalName)return this.alias;if(i===hn)return{...n[hn],name:this.alias,isAlias:!0};if(i===L.Symbol.Columns){let c=n[L.Symbol.Columns];if(!c)return c;let p={};return Object.keys(c).map((a)=>{p[a]=new Proxy(c[a],new Ap(new Proxy(n,this)))}),p}let o=n[i];if(z(o,bn))return new Proxy(o,new Ap(new Proxy(n,this)));return o}}function tx(n,i){return new Proxy(n,new Ha(i,!1))}function Ho(n,i){return new Proxy(n,new Ap(new Proxy(n.table,new Ha(i,!1))))}function Gf(n,i){return new k.Aliased(Ea(n.sql,i),n.fieldAlias)}function Ea(n,i){return S.join(n.queryChunks.map((o)=>{if(z(o,bn))return Ho(o,i);if(z(o,k))return Ea(o,i);if(z(o,k.Aliased))return Gf(o,i);return o}))}class qx extends Error{static[J]="DrizzleError";constructor({message:n,cause:i}){super(n);this.name="DrizzleError",this.cause=i}}class Yf extends qx{static[J]="TransactionRollbackError";constructor(){super({message:"Rollback"})}}function ui(n,i){if(y1(i)&&!Kf(n)&&!z(n,Li)&&!z(n,pc)&&!z(n,bn)&&!z(n,L)&&!z(n,Vi))return new Li(n,i);return n}var Eo=(n,i)=>{return S`${n} = ${ui(i,n)}`},N1=(n,i)=>{return S`${n} <> ${ui(i,n)}`};function Uc(...n){let i=n.filter((o)=>o!==void 0);if(i.length===0)return;if(i.length===1)return new k(i);return new k([new pi("("),S.join(i,new pi(" and ")),new pi(")")])}function D1(...n){let i=n.filter((o)=>o!==void 0);if(i.length===0)return;if(i.length===1)return new k(i);return new k([new pi("("),S.join(i,new pi(" or ")),new pi(")")])}function C1(n){return S`not ${n}`}var Px=(n,i)=>{return S`${n} > ${ui(i,n)}`},h1=(n,i)=>{return S`${n} >= ${ui(i,n)}`},I1=(n,i)=>{return S`${n} < ${ui(i,n)}`},k1=(n,i)=>{return S`${n} <= ${ui(i,n)}`};function s1(n,i){if(Array.isArray(i)){if(i.length===0)return S`false`;return S`${n} in ${i.map((o)=>ui(o,n))}`}return S`${n} in ${ui(i,n)}`}function Z1(n,i){if(Array.isArray(i)){if(i.length===0)return S`true`;return S`${n} not in ${i.map((o)=>ui(o,n))}`}return S`${n} not in ${ui(i,n)}`}function t1(n){return S`${n} is null`}function q1(n){return S`${n} is not null`}function P1(n){return S`exists ${n}`}function r1(n){return S`not exists ${n}`}function g1(n,i,o){return S`${n} between ${ui(i,n)} and ${ui(o,n)}`}function d1(n,i,o){return S`${n} not between ${ui(i,n)} and ${ui(o,n)}`}function e1(n,i){return S`${n} like ${i}`}function nw(n,i){return S`${n} not like ${i}`}function iw(n,i){return S`${n} ilike ${i}`}function ow(n,i){return S`${n} not ilike ${i}`}function cw(n){return S`${n} asc`}function pw(n){return S`${n} desc`}class aw{static[J]="ConsoleLogWriter";write(n){console.log(n)}}class zf{static[J]="DefaultLogger";writer;constructor(n){this.writer=n?.writer??new aw}logQuery(n,i){let o=i.map((p)=>{try{return JSON.stringify(p)}catch{return String(p)}}),c=o.length?` -- params: [${o.join(", ")}]`:"";this.writer.write(`Query: ${n}${c}`)}}class Qf{static[J]="NoopLogger";logQuery(){}}class Qi{static[J]="QueryPromise";[Symbol.toStringTag]="QueryPromise";catch(n){return this.then(void 0,n)}finally(n){return this.then((i)=>{return n?.(),i},(i)=>{throw n?.(),i})}then(n,i){return this.execute().then(n,i)}}function xw(n,i,o){let c={},p=n.reduce((a,{path:x,field:m},l)=>{let f;if(z(m,bn))f=m;else if(z(m,k))f=m.decoder;else f=m.sql.decoder;let v=a;for(let[$,T]of x.entries())if($<x.length-1){if(!(T in v))v[T]={};v=v[T]}else{let F=i[l],M=v[T]=F===null?null:f.mapFromDriverValue(F);if(o&&z(m,bn)&&x.length===2){let A=x[0];if(!(A in c))c[A]=M===null?di(m.table):!1;else if(typeof c[A]==="string"&&c[A]!==di(m.table))c[A]=!1}}return a},{});if(o&&Object.keys(c).length>0){for(let[a,x]of Object.entries(c))if(typeof x==="string"&&!o[x])p[a]=null}return p}function ei(n,i){return Object.entries(n).reduce((o,[c,p])=>{if(typeof c!=="string")return o;let a=i?[...i,c]:[c];if(z(p,bn)||z(p,k)||z(p,k.Aliased))o.push({path:a,field:p});else if(z(p,L))o.push(...ei(p[L.Symbol.Columns],a));else o.push(...ei(p,a));return o},[])}function Hf(n,i){let o=Object.keys(n),c=Object.keys(i);if(o.length!==c.length)return!1;for(let[p,a]of o.entries())if(a!==c[p])return!1;return!0}function rx(n,i){let o=Object.entries(i).filter(([,c])=>c!==void 0).map(([c,p])=>{if(z(p,k))return[c,p];else return[c,new Li(p,n[L.Symbol.Columns][c])]});if(o.length===0)throw new Error("No values to set");return Object.fromEntries(o)}function mw(n,i){for(let o of i)for(let c of Object.getOwnPropertyNames(o.prototype)){if(c==="constructor")continue;Object.defineProperty(n.prototype,c,Object.getOwnPropertyDescriptor(o.prototype,c)||Object.create(null))}}function lw(n){return n[L.Symbol.Columns]}function Ef(n){return z(n,fi)?n._.alias:z(n,Vi)?n[hn].name:z(n,k)?void 0:n[L.Symbol.IsAlias]?n[L.Symbol.Name]:n[L.Symbol.BaseName]}function An(n,i){return{name:typeof n==="string"&&n.length>0?n:"",config:typeof n==="object"?n:i}}function fw(n){if(typeof n!=="object"||n===null)return!1;if(n.constructor.name!=="Object")return!1;if("logger"in n){let i=typeof n.logger;if(i!=="boolean"&&(i!=="object"||typeof n.logger.logQuery!=="function")&&i!=="undefined")return!1;return!0}if("schema"in n){let i=typeof n.logger;if(i!=="object"&&i!=="undefined")return!1;return!0}if("casing"in n){let i=typeof n.logger;if(i!=="string"&&i!=="undefined")return!1;return!0}if("mode"in n){if(n.mode!=="default"||n.mode!=="planetscale"||n.mode!==void 0)return!1;return!0}if("connection"in n){let i=typeof n.connection;if(i!=="string"&&i!=="object"&&i!=="undefined")return!1;return!0}if("client"in n){let i=typeof n.client;if(i!=="object"&&i!=="function"&&i!=="undefined")return!1;return!0}if(Object.keys(n).length===0)return!0;return!1}class ac extends I{static[J]="PgIntColumnBaseBuilder";generatedAlwaysAsIdentity(n){if(n){let{name:i,...o}=n;this.config.generatedIdentity={type:"always",sequenceName:i,sequenceOptions:o}}else this.config.generatedIdentity={type:"always"};return this.config.hasDefault=!0,this.config.notNull=!0,this}generatedByDefaultAsIdentity(n){if(n){let{name:i,...o}=n;this.config.generatedIdentity={type:"byDefault",sequenceName:i,sequenceOptions:o}}else this.config.generatedIdentity={type:"byDefault"};return this.config.hasDefault=!0,this.config.notNull=!0,this}}class vw extends ac{static[J]="PgBigInt53Builder";constructor(n){super(n,"number","PgBigInt53")}build(n){return new $w(n,this.config)}}class $w extends u{static[J]="PgBigInt53";getSQLType(){return"bigint"}mapFromDriverValue(n){if(typeof n==="number")return n;return Number(n)}}class Tw extends ac{static[J]="PgBigInt64Builder";constructor(n){super(n,"bigint","PgBigInt64")}build(n){return new ww(n,this.config)}}class ww extends u{static[J]="PgBigInt64";getSQLType(){return"bigint"}mapFromDriverValue(n){return BigInt(n)}}function Jw(n,i){let{name:o,config:c}=An(n,i);if(c.mode==="number")return new vw(o);return new Tw(o)}class Sw extends I{static[J]="PgBigSerial53Builder";constructor(n){super(n,"number","PgBigSerial53");this.config.hasDefault=!0,this.config.notNull=!0}build(n){return new Aw(n,this.config)}}class Aw extends u{static[J]="PgBigSerial53";getSQLType(){return"bigserial"}mapFromDriverValue(n){if(typeof n==="number")return n;return Number(n)}}class Fw extends I{static[J]="PgBigSerial64Builder";constructor(n){super(n,"bigint","PgBigSerial64");this.config.hasDefault=!0}build(n){return new Mw(n,this.config)}}class Mw extends u{static[J]="PgBigSerial64";getSQLType(){return"bigserial"}mapFromDriverValue(n){return BigInt(n)}}function Rw(n,i){let{name:o,config:c}=An(n,i);if(c.mode==="number")return new Sw(o);return new Fw(o)}class Ww extends I{static[J]="PgBooleanBuilder";constructor(n){super(n,"boolean","PgBoolean")}build(n){return new Kw(n,this.config)}}class Kw extends u{static[J]="PgBoolean";getSQLType(){return"boolean"}}function Oa(n){return new Ww(n??"")}class Xw extends I{static[J]="PgCharBuilder";constructor(n,i){super(n,"string","PgChar");this.config.length=i.length,this.config.enumValues=i.enum}build(n){return new Gw(n,this.config)}}class Gw extends u{static[J]="PgChar";length=this.config.length;enumValues=this.config.enumValues;getSQLType(){return this.length===void 0?"char":`char(${this.length})`}}function Yw(n,i={}){let{name:o,config:c}=An(n,i);return new Xw(o,c)}class zw extends I{static[J]="PgCidrBuilder";constructor(n){super(n,"string","PgCidr")}build(n){return new Qw(n,this.config)}}class Qw extends u{static[J]="PgCidr";getSQLType(){return"cidr"}}function Hw(n){return new zw(n??"")}class Ew extends I{static[J]="PgCustomColumnBuilder";constructor(n,i,o){super(n,"custom","PgCustomColumn");this.config.fieldConfig=i,this.config.customTypeParams=o}build(n){return new Ow(n,this.config)}}class Ow extends u{static[J]="PgCustomColumn";sqlName;mapTo;mapFrom;constructor(n,i){super(n,i);this.sqlName=i.customTypeParams.dataType(i.fieldConfig),this.mapTo=i.customTypeParams.toDriver,this.mapFrom=i.customTypeParams.fromDriver}getSQLType(){return this.sqlName}mapFromDriverValue(n){return typeof this.mapFrom==="function"?this.mapFrom(n):n}mapToDriverValue(n){return typeof this.mapTo==="function"?this.mapTo(n):n}}function Uw(n){return(i,o)=>{let{name:c,config:p}=An(i,o);return new Ew(c,p,n)}}class Bo extends I{static[J]="PgDateColumnBaseBuilder";defaultNow(){return this.default(S`now()`)}}class Vw extends Bo{static[J]="PgDateBuilder";constructor(n){super(n,"date","PgDate")}build(n){return new gx(n,this.config)}}class gx extends u{static[J]="PgDate";getSQLType(){return"date"}mapFromDriverValue(n){return new Date(n)}mapToDriverValue(n){return n.toISOString()}}class uw extends Bo{static[J]="PgDateStringBuilder";constructor(n){super(n,"string","PgDateString")}build(n){return new dx(n,this.config)}}class dx extends u{static[J]="PgDateString";getSQLType(){return"date"}}function _w(n,i){let{name:o,config:c}=An(n,i);if(c?.mode==="date")return new Vw(o);return new uw(o)}class bw extends I{static[J]="PgDoublePrecisionBuilder";constructor(n){super(n,"number","PgDoublePrecision")}build(n){return new jw(n,this.config)}}class jw extends u{static[J]="PgDoublePrecision";getSQLType(){return"double precision"}mapFromDriverValue(n){if(typeof n==="string")return Number.parseFloat(n);return n}}function yw(n){return new bw(n??"")}class Bw extends I{static[J]="PgInetBuilder";constructor(n){super(n,"string","PgInet")}build(n){return new Lw(n,this.config)}}class Lw extends u{static[J]="PgInet";getSQLType(){return"inet"}}function Nw(n){return new Bw(n??"")}class Dw extends ac{static[J]="PgIntegerBuilder";constructor(n){super(n,"number","PgInteger")}build(n){return new Cw(n,this.config)}}class Cw extends u{static[J]="PgInteger";getSQLType(){return"integer"}mapFromDriverValue(n){if(typeof n==="string")return Number.parseInt(n);return n}}function ex(n){return new Dw(n??"")}class hw extends I{static[J]="PgIntervalBuilder";constructor(n,i){super(n,"string","PgInterval");this.config.intervalConfig=i}build(n){return new Iw(n,this.config)}}class Iw extends u{static[J]="PgInterval";fields=this.config.intervalConfig.fields;precision=this.config.intervalConfig.precision;getSQLType(){let n=this.fields?` ${this.fields}`:"",i=this.precision?`(${this.precision})`:"";return`interval${n}${i}`}}function kw(n,i={}){let{name:o,config:c}=An(n,i);return new hw(o,c)}class sw extends I{static[J]="PgJsonBuilder";constructor(n){super(n,"json","PgJson")}build(n){return new nm(n,this.config)}}class nm extends u{static[J]="PgJson";constructor(n,i){super(n,i)}getSQLType(){return"json"}mapToDriverValue(n){return JSON.stringify(n)}mapFromDriverValue(n){if(typeof n==="string")try{return JSON.parse(n)}catch{return n}return n}}function Zw(n){return new sw(n??"")}class tw extends I{static[J]="PgJsonbBuilder";constructor(n){super(n,"json","PgJsonb")}build(n){return new im(n,this.config)}}class im extends u{static[J]="PgJsonb";constructor(n,i){super(n,i)}getSQLType(){return"jsonb"}mapToDriverValue(n){return JSON.stringify(n)}mapFromDriverValue(n){if(typeof n==="string")try{return JSON.parse(n)}catch{return n}return n}}function qw(n){return new tw(n??"")}class Pw extends I{static[J]="PgLineBuilder";constructor(n){super(n,"array","PgLine")}build(n){return new rw(n,this.config)}}class rw extends u{static[J]="PgLine";getSQLType(){return"line"}mapFromDriverValue(n){let[i,o,c]=n.slice(1,-1).split(",");return[Number.parseFloat(i),Number.parseFloat(o),Number.parseFloat(c)]}mapToDriverValue(n){return`{${n[0]},${n[1]},${n[2]}}`}}class gw extends I{static[J]="PgLineABCBuilder";constructor(n){super(n,"json","PgLineABC")}build(n){return new dw(n,this.config)}}class dw extends u{static[J]="PgLineABC";getSQLType(){return"line"}mapFromDriverValue(n){let[i,o,c]=n.slice(1,-1).split(",");return{a:Number.parseFloat(i),b:Number.parseFloat(o),c:Number.parseFloat(c)}}mapToDriverValue(n){return`{${n.a},${n.b},${n.c}}`}}function ew(n,i){let{name:o,config:c}=An(n,i);if(!c?.mode||c.mode==="tuple")return new Pw(o);return new gw(o)}class nJ extends I{static[J]="PgMacaddrBuilder";constructor(n){super(n,"string","PgMacaddr")}build(n){return new iJ(n,this.config)}}class iJ extends u{static[J]="PgMacaddr";getSQLType(){return"macaddr"}}function oJ(n){return new nJ(n??"")}class cJ extends I{static[J]="PgMacaddr8Builder";constructor(n){super(n,"string","PgMacaddr8")}build(n){return new pJ(n,this.config)}}class pJ extends u{static[J]="PgMacaddr8";getSQLType(){return"macaddr8"}}function aJ(n){return new cJ(n??"")}class xJ extends I{static[J]="PgNumericBuilder";constructor(n,i,o){super(n,"string","PgNumeric");this.config.precision=i,this.config.scale=o}build(n){return new om(n,this.config)}}class om extends u{static[J]="PgNumeric";precision;scale;constructor(n,i){super(n,i);this.precision=i.precision,this.scale=i.scale}getSQLType(){if(this.precision!==void 0&&this.scale!==void 0)return`numeric(${this.precision}, ${this.scale})`;else if(this.precision===void 0)return"numeric";else return`numeric(${this.precision})`}}function mJ(n,i){let{name:o,config:c}=An(n,i);return new xJ(o,c?.precision,c?.scale)}class lJ extends I{static[J]="PgPointTupleBuilder";constructor(n){super(n,"array","PgPointTuple")}build(n){return new fJ(n,this.config)}}class fJ extends u{static[J]="PgPointTuple";getSQLType(){return"point"}mapFromDriverValue(n){if(typeof n==="string"){let[i,o]=n.slice(1,-1).split(",");return[Number.parseFloat(i),Number.parseFloat(o)]}return[n.x,n.y]}mapToDriverValue(n){return`(${n[0]},${n[1]})`}}class vJ extends I{static[J]="PgPointObjectBuilder";constructor(n){super(n,"json","PgPointObject")}build(n){return new $J(n,this.config)}}class $J extends u{static[J]="PgPointObject";getSQLType(){return"point"}mapFromDriverValue(n){if(typeof n==="string"){let[i,o]=n.slice(1,-1).split(",");return{x:Number.parseFloat(i),y:Number.parseFloat(o)}}return n}mapToDriverValue(n){return`(${n.x},${n.y})`}}function TJ(n,i){let{name:o,config:c}=An(n,i);if(!c?.mode||c.mode==="tuple")return new lJ(o);return new vJ(o)}function _W(n){let i=[];for(let o=0;o<n.length;o+=2)i.push(Number.parseInt(n.slice(o,o+2),16));return new Uint8Array(i)}function wJ(n,i){let o=new ArrayBuffer(8),c=new DataView(o);for(let p=0;p<8;p++)c.setUint8(p,n[i+p]);return c.getFloat64(0,!0)}function Of(n){let i=_W(n),o=0,c=i[o];o+=1;let p=new DataView(i.buffer),a=p.getUint32(o,c===1);o+=4;let x;if(a&536870912)x=p.getUint32(o,c===1),o+=4;if((a&65535)===1){let m=wJ(i,o);o+=8;let l=wJ(i,o);return o+=8,[m,l]}throw new Error("Unsupported geometry type")}class JJ extends I{static[J]="PgGeometryBuilder";constructor(n){super(n,"array","PgGeometry")}build(n){return new SJ(n,this.config)}}class SJ extends u{static[J]="PgGeometry";getSQLType(){return"geometry(point)"}mapFromDriverValue(n){return Of(n)}mapToDriverValue(n){return`point(${n[0]} ${n[1]})`}}class AJ extends I{static[J]="PgGeometryObjectBuilder";constructor(n){super(n,"json","PgGeometryObject")}build(n){return new FJ(n,this.config)}}class FJ extends u{static[J]="PgGeometryObject";getSQLType(){return"geometry(point)"}mapFromDriverValue(n){let i=Of(n);return{x:i[0],y:i[1]}}mapToDriverValue(n){return`point(${n.x} ${n.y})`}}function MJ(n,i){let{name:o,config:c}=An(n,i);if(!c?.mode||c.mode==="tuple")return new JJ(o);return new AJ(o)}class RJ extends I{static[J]="PgRealBuilder";constructor(n,i){super(n,"number","PgReal");this.config.length=i}build(n){return new WJ(n,this.config)}}class WJ extends u{static[J]="PgReal";constructor(n,i){super(n,i)}getSQLType(){return"real"}mapFromDriverValue=(n)=>{if(typeof n==="string")return Number.parseFloat(n);return n}}function KJ(n){return new RJ(n??"")}class XJ extends I{static[J]="PgSerialBuilder";constructor(n){super(n,"number","PgSerial");this.config.hasDefault=!0,this.config.notNull=!0}build(n){return new GJ(n,this.config)}}class GJ extends u{static[J]="PgSerial";getSQLType(){return"serial"}}function YJ(n){return new XJ(n??"")}class zJ extends ac{static[J]="PgSmallIntBuilder";constructor(n){super(n,"number","PgSmallInt")}build(n){return new QJ(n,this.config)}}class QJ extends u{static[J]="PgSmallInt";getSQLType(){return"smallint"}mapFromDriverValue=(n)=>{if(typeof n==="string")return Number(n);return n}}function HJ(n){return new zJ(n??"")}class EJ extends I{static[J]="PgSmallSerialBuilder";constructor(n){super(n,"number","PgSmallSerial");this.config.hasDefault=!0,this.config.notNull=!0}build(n){return new OJ(n,this.config)}}class OJ extends u{static[J]="PgSmallSerial";getSQLType(){return"smallserial"}}function UJ(n){return new EJ(n??"")}class VJ extends I{static[J]="PgTextBuilder";constructor(n,i){super(n,"string","PgText");this.config.enumValues=i.enum}build(n){return new uJ(n,this.config)}}class uJ extends u{static[J]="PgText";enumValues=this.config.enumValues;getSQLType(){return"text"}}function _J(n,i={}){let{name:o,config:c}=An(n,i);return new VJ(o,c)}class bJ extends Bo{constructor(n,i,o){super(n,"string","PgTime");this.withTimezone=i,this.precision=o,this.config.withTimezone=i,this.config.precision=o}static[J]="PgTimeBuilder";build(n){return new cm(n,this.config)}}class cm extends u{static[J]="PgTime";withTimezone;precision;constructor(n,i){super(n,i);this.withTimezone=i.withTimezone,this.precision=i.precision}getSQLType(){return`time${this.precision===void 0?"":`(${this.precision})`}${this.withTimezone?" with time zone":""}`}}function jJ(n,i={}){let{name:o,config:c}=An(n,i);return new bJ(o,c.withTimezone??!1,c.precision)}class yJ extends Bo{static[J]="PgTimestampBuilder";constructor(n,i,o){super(n,"date","PgTimestamp");this.config.withTimezone=i,this.config.precision=o}build(n){return new pm(n,this.config)}}class pm extends u{static[J]="PgTimestamp";withTimezone;precision;constructor(n,i){super(n,i);this.withTimezone=i.withTimezone,this.precision=i.precision}getSQLType(){return`timestamp${this.precision===void 0?"":` (${this.precision})`}${this.withTimezone?" with time zone":""}`}mapFromDriverValue=(n)=>{return new Date(this.withTimezone?n:n+"+0000")};mapToDriverValue=(n)=>{return n.toISOString()}}class BJ extends Bo{static[J]="PgTimestampStringBuilder";constructor(n,i,o){super(n,"string","PgTimestampString");this.config.withTimezone=i,this.config.precision=o}build(n){return new am(n,this.config)}}class am extends u{static[J]="PgTimestampString";withTimezone;precision;constructor(n,i){super(n,i);this.withTimezone=i.withTimezone,this.precision=i.precision}getSQLType(){return`timestamp${this.precision===void 0?"":`(${this.precision})`}${this.withTimezone?" with time zone":""}`}}function wo(n,i={}){let{name:o,config:c}=An(n,i);if(c?.mode==="string")return new BJ(o,c.withTimezone??!1,c.precision);return new yJ(o,c?.withTimezone??!1,c?.precision)}class LJ extends I{static[J]="PgUUIDBuilder";constructor(n){super(n,"string","PgUUID")}defaultRandom(){return this.default(S`gen_random_uuid()`)}build(n){return new xm(n,this.config)}}class xm extends u{static[J]="PgUUID";getSQLType(){return"uuid"}}function Ni(n){return new LJ(n??"")}class NJ extends I{static[J]="PgVarcharBuilder";constructor(n,i){super(n,"string","PgVarchar");this.config.length=i.length,this.config.enumValues=i.enum}build(n){return new DJ(n,this.config)}}class DJ extends u{static[J]="PgVarchar";length=this.config.length;enumValues=this.config.enumValues;getSQLType(){return this.length===void 0?"varchar":`varchar(${this.length})`}}function vi(n,i={}){let{name:o,config:c}=An(n,i);return new NJ(o,c)}class CJ extends I{static[J]="PgBinaryVectorBuilder";constructor(n,i){super(n,"string","PgBinaryVector");this.config.dimensions=i.dimensions}build(n){return new hJ(n,this.config)}}class hJ extends u{static[J]="PgBinaryVector";dimensions=this.config.dimensions;getSQLType(){return`bit(${this.dimensions})`}}function IJ(n,i){let{name:o,config:c}=An(n,i);return new CJ(o,c)}class kJ extends I{static[J]="PgHalfVectorBuilder";constructor(n,i){super(n,"array","PgHalfVector");this.config.dimensions=i.dimensions}build(n){return new sJ(n,this.config)}}class sJ extends u{static[J]="PgHalfVector";dimensions=this.config.dimensions;getSQLType(){return`halfvec(${this.dimensions})`}mapToDriverValue(n){return JSON.stringify(n)}mapFromDriverValue(n){return n.slice(1,-1).split(",").map((i)=>Number.parseFloat(i))}}function ZJ(n,i){let{name:o,config:c}=An(n,i);return new kJ(o,c)}class tJ extends I{static[J]="PgSparseVectorBuilder";constructor(n,i){super(n,"string","PgSparseVector");this.config.dimensions=i.dimensions}build(n){return new qJ(n,this.config)}}class qJ extends u{static[J]="PgSparseVector";dimensions=this.config.dimensions;getSQLType(){return`sparsevec(${this.dimensions})`}}function PJ(n,i){let{name:o,config:c}=An(n,i);return new tJ(o,c)}class rJ extends I{static[J]="PgVectorBuilder";constructor(n,i){super(n,"array","PgVector");this.config.dimensions=i.dimensions}build(n){return new gJ(n,this.config)}}class gJ extends u{static[J]="PgVector";dimensions=this.config.dimensions;getSQLType(){return`vector(${this.dimensions})`}mapToDriverValue(n){return JSON.stringify(n)}mapFromDriverValue(n){return n.slice(1,-1).split(",").map((i)=>Number.parseFloat(i))}}function dJ(n,i){let{name:o,config:c}=An(n,i);return new rJ(o,c)}function eJ(){return{bigint:Jw,bigserial:Rw,boolean:Oa,char:Yw,cidr:Hw,customType:Uw,date:_w,doublePrecision:yw,inet:Nw,integer:ex,interval:kw,json:Zw,jsonb:qw,line:ew,macaddr:oJ,macaddr8:aJ,numeric:mJ,point:TJ,geometry:MJ,real:KJ,serial:YJ,smallint:HJ,smallserial:UJ,text:_J,time:jJ,timestamp:wo,uuid:Ni,varchar:vi,bit:IJ,halfvec:ZJ,sparsevec:PJ,vector:dJ}}var Uf=Symbol.for("drizzle:PgInlineForeignKeys"),nS=Symbol.for("drizzle:EnableRLS");class no extends L{static[J]="PgTable";static Symbol=Object.assign({},L.Symbol,{InlineForeignKeys:Uf,EnableRLS:nS});[Uf]=[];[nS]=!1;[L.Symbol.ExtraConfigBuilder]=void 0}function bW(n,i,o,c,p=n){let a=new no(n,c,p),x=typeof i==="function"?i(eJ()):i,m=Object.fromEntries(Object.entries(x).map(([v,$])=>{let T=$;T.setName(v);let F=T.build(a);return a[Uf].push(...T.buildForeignKeys(F,a)),[v,F]})),l=Object.fromEntries(Object.entries(x).map(([v,$])=>{let T=$;T.setName(v);let F=T.buildExtraConfigColumn(a);return[v,F]})),f=Object.assign(a,m);if(f[L.Symbol.Columns]=m,f[L.Symbol.ExtraConfigColumns]=l,o)f[no.Symbol.ExtraConfigBuilder]=o;return Object.assign(f,{enableRLS:()=>{return f[no.Symbol.EnableRLS]=!0,f}})}var xc=(n,i,o)=>{return bW(n,i,o,void 0)};function iS(...n){if(n[0].columns)return new Ua(n[0].columns,n[0].name);return new Ua(n)}class Ua{static[J]="PgPrimaryKeyBuilder";columns;name;constructor(n,i){this.columns=n,this.name=i}build(n){return new oS(n,this.columns,this.name)}}class oS{constructor(n,i,o){this.table=n,this.columns=i,this.name=o}static[J]="PgPrimaryKey";columns;name;getName(){return this.name??`${this.table[no.Symbol.Name]}_${this.columns.map((n)=>n.name).join("_")}_pk`}}class Vf{constructor(n,i,o){this.sourceTable=n,this.referencedTable=i,this.relationName=o,this.referencedTableName=i[L.Symbol.Name]}static[J]="Relation";referencedTableName;fieldName}class cS{constructor(n,i){this.table=n,this.config=i}static[J]="Relations"}class mc extends Vf{constructor(n,i,o,c){super(n,i,o?.relationName);this.config=o,this.isNullable=c}static[J]="One";withFieldName(n){let i=new mc(this.sourceTable,this.referencedTable,this.config,this.isNullable);return i.fieldName=n,i}}class Va extends Vf{constructor(n,i,o){super(n,i,o?.relationName);this.config=o}static[J]="Many";withFieldName(n){let i=new Va(this.sourceTable,this.referencedTable,this.config);return i.fieldName=n,i}}function pS(){return{and:Uc,between:g1,eq:Eo,exists:P1,gt:Px,gte:h1,ilike:iw,inArray:s1,isNull:t1,isNotNull:q1,like:e1,lt:I1,lte:k1,ne:N1,not:C1,notBetween:d1,notExists:r1,notLike:nw,notIlike:ow,notInArray:Z1,or:D1,sql:S}}function aS(){return{sql:S,asc:cw,desc:pw}}function xS(n,i){if(Object.keys(n).length===1&&"default"in n&&!z(n.default,L))n=n.default;let o={},c={},p={};for(let[a,x]of Object.entries(n))if(z(x,L)){let m=Oc(x),l=c[m];o[m]=a,p[a]={tsName:a,dbName:x[L.Symbol.Name],schema:x[L.Symbol.Schema],columns:x[L.Symbol.Columns],relations:l?.relations??{},primaryKey:l?.primaryKey??[]};for(let v of Object.values(x[L.Symbol.Columns]))if(v.primary)p[a].primaryKey.push(v);let f=x[L.Symbol.ExtraConfigBuilder]?.(x[L.Symbol.ExtraConfigColumns]);if(f){for(let v of Object.values(f))if(z(v,Ua))p[a].primaryKey.push(...v.columns)}}else if(z(x,cS)){let m=Oc(x.table),l=o[m],f=x.config(i(x.table)),v;for(let[$,T]of Object.entries(f))if(l){let F=p[l];if(F.relations[$]=T,v)F.primaryKey.push(...v)}else{if(!(m in c))c[m]={relations:{},primaryKey:v};c[m].relations[$]=T}}return{tables:p,tableNamesMap:o}}function jW(n){return function i(o,c){return new mc(n,o,c,c?.fields.reduce((p,a)=>p&&a.notNull,!0)??!1)}}function yW(n){return function i(o,c){return new Va(n,o,c)}}function mS(n,i,o){if(z(o,mc)&&o.config)return{fields:o.config.fields,references:o.config.references};let c=i[Oc(o.referencedTable)];if(!c)throw new Error(`Table "${o.referencedTable[L.Symbol.Name]}" not found in schema`);let p=n[c];if(!p)throw new Error(`Table "${c}" not found in schema`);let a=o.sourceTable,x=i[Oc(a)];if(!x)throw new Error(`Table "${a[L.Symbol.Name]}" not found in schema`);let m=[];for(let l of Object.values(p.relations))if(o.relationName&&o!==l&&l.relationName===o.relationName||!o.relationName&&l.referencedTable===o.sourceTable)m.push(l);if(m.length>1)throw o.relationName?new Error(`There are multiple relations with name "${o.relationName}" in table "${c}"`):new Error(`There are multiple relations between "${c}" and "${o.sourceTable[L.Symbol.Name]}". Please specify relation name`);if(m[0]&&z(m[0],mc)&&m[0].config)return{fields:m[0].config.references,references:m[0].config.fields};throw new Error(`There is not enough information to infer relation "${x}.${o.fieldName}"`)}function lS(n){return{one:jW(n),many:yW(n)}}function mm(n,i,o,c,p=(a)=>a){let a={};for(let[x,m]of c.entries())if(m.isJson){let l=i.relations[m.tsKey],f=o[x],v=typeof f==="string"?JSON.parse(f):f;a[m.tsKey]=z(l,mc)?v&&mm(n,n[m.relationTableTsKey],v,m.selection,p):v.map(($)=>mm(n,n[m.relationTableTsKey],$,m.selection,p))}else{let l=p(o[x]),f=m.field,v;if(z(f,bn))v=f;else if(z(f,k))v=f.decoder;else v=f.sql.decoder;a[m.tsKey]=l===null?null:v.mapFromDriverValue(l)}return a}var tM=vl(ZM(),1),{Server:qM,Namespace:eL,Socket:nN}=tM.default;import{readFileSync as lR}from"fs";import{resolve as Vv}from"path";var Wn;(function(n){n.assertEqual=(p)=>p;function i(p){}n.assertIs=i;function o(p){throw new Error}n.assertNever=o,n.arrayToEnum=(p)=>{let a={};for(let x of p)a[x]=x;return a},n.getValidEnumValues=(p)=>{let a=n.objectKeys(p).filter((m)=>typeof p[p[m]]!=="number"),x={};for(let m of a)x[m]=p[m];return n.objectValues(x)},n.objectValues=(p)=>{return n.objectKeys(p).map(function(a){return p[a]})},n.objectKeys=typeof Object.keys==="function"?(p)=>Object.keys(p):(p)=>{let a=[];for(let x in p)if(Object.prototype.hasOwnProperty.call(p,x))a.push(x);return a},n.find=(p,a)=>{for(let x of p)if(a(x))return x;return},n.isInteger=typeof Number.isInteger==="function"?(p)=>Number.isInteger(p):(p)=>typeof p==="number"&&isFinite(p)&&Math.floor(p)===p;function c(p,a=" | "){return p.map((x)=>typeof x==="string"?`'${x}'`:x).join(a)}n.joinValues=c,n.jsonStringifyReplacer=(p,a)=>{if(typeof a==="bigint")return a.toString();return a}})(Wn||(Wn={}));var Hv;(function(n){n.mergeShapes=(i,o)=>{return{...i,...o}}})(Hv||(Hv={}));var N=Wn.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Tc=(n)=>{switch(typeof n){case"undefined":return N.undefined;case"string":return N.string;case"number":return isNaN(n)?N.nan:N.number;case"boolean":return N.boolean;case"function":return N.function;case"bigint":return N.bigint;case"symbol":return N.symbol;case"object":if(Array.isArray(n))return N.array;if(n===null)return N.null;if(n.then&&typeof n.then==="function"&&n.catch&&typeof n.catch==="function")return N.promise;if(typeof Map!=="undefined"&&n instanceof Map)return N.map;if(typeof Set!=="undefined"&&n instanceof Set)return N.set;if(typeof Date!=="undefined"&&n instanceof Date)return N.date;return N.object;default:return N.unknown}},O=Wn.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),z5=(n)=>{return JSON.stringify(n,null,2).replace(/"([^"]+)":/g,"$1:")};class Ii extends Error{constructor(n){super();this.issues=[],this.addIssue=(o)=>{this.issues=[...this.issues,o]},this.addIssues=(o=[])=>{this.issues=[...this.issues,...o]};let i=new.target.prototype;if(Object.setPrototypeOf)Object.setPrototypeOf(this,i);else this.__proto__=i;this.name="ZodError",this.issues=n}get errors(){return this.issues}format(n){let i=n||function(p){return p.message},o={_errors:[]},c=(p)=>{for(let a of p.issues)if(a.code==="invalid_union")a.unionErrors.map(c);else if(a.code==="invalid_return_type")c(a.returnTypeError);else if(a.code==="invalid_arguments")c(a.argumentsError);else if(a.path.length===0)o._errors.push(i(a));else{let x=o,m=0;while(m<a.path.length){let l=a.path[m];if(m!==a.path.length-1)x[l]=x[l]||{_errors:[]};else x[l]=x[l]||{_errors:[]},x[l]._errors.push(i(a));x=x[l],m++}}};return c(this),o}static assert(n){if(!(n instanceof Ii))throw new Error(`Not a ZodError: ${n}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,Wn.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(n=(i)=>i.message){let i={},o=[];for(let c of this.issues)if(c.path.length>0)i[c.path[0]]=i[c.path[0]]||[],i[c.path[0]].push(n(c));else o.push(n(c));return{formErrors:o,fieldErrors:i}}get formErrors(){return this.flatten()}}Ii.create=(n)=>{return new Ii(n)};var jp=(n,i)=>{let o;switch(n.code){case O.invalid_type:if(n.received===N.undefined)o="Required";else o=`Expected ${n.expected}, received ${n.received}`;break;case O.invalid_literal:o=`Invalid literal value, expected ${JSON.stringify(n.expected,Wn.jsonStringifyReplacer)}`;break;case O.unrecognized_keys:o=`Unrecognized key(s) in object: ${Wn.joinValues(n.keys,", ")}`;break;case O.invalid_union:o="Invalid input";break;case O.invalid_union_discriminator:o=`Invalid discriminator value. Expected ${Wn.joinValues(n.options)}`;break;case O.invalid_enum_value:o=`Invalid enum value. Expected ${Wn.joinValues(n.options)}, received '${n.received}'`;break;case O.invalid_arguments:o="Invalid function arguments";break;case O.invalid_return_type:o="Invalid function return type";break;case O.invalid_date:o="Invalid date";break;case O.invalid_string:if(typeof n.validation==="object")if("includes"in n.validation){if(o=`Invalid input: must include "${n.validation.includes}"`,typeof n.validation.position==="number")o=`${o} at one or more positions greater than or equal to ${n.validation.position}`}else if("startsWith"in n.validation)o=`Invalid input: must start with "${n.validation.startsWith}"`;else if("endsWith"in n.validation)o=`Invalid input: must end with "${n.validation.endsWith}"`;else Wn.assertNever(n.validation);else if(n.validation!=="regex")o=`Invalid ${n.validation}`;else o="Invalid";break;case O.too_small:if(n.type==="array")o=`Array must contain ${n.exact?"exactly":n.inclusive?"at least":"more than"} ${n.minimum} element(s)`;else if(n.type==="string")o=`String must contain ${n.exact?"exactly":n.inclusive?"at least":"over"} ${n.minimum} character(s)`;else if(n.type==="number")o=`Number must be ${n.exact?"exactly equal to ":n.inclusive?"greater than or equal to ":"greater than "}${n.minimum}`;else if(n.type==="date")o=`Date must be ${n.exact?"exactly equal to ":n.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(n.minimum))}`;else o="Invalid input";break;case O.too_big:if(n.type==="array")o=`Array must contain ${n.exact?"exactly":n.inclusive?"at most":"less than"} ${n.maximum} element(s)`;else if(n.type==="string")o=`String must contain ${n.exact?"exactly":n.inclusive?"at most":"under"} ${n.maximum} character(s)`;else if(n.type==="number")o=`Number must be ${n.exact?"exactly":n.inclusive?"less than or equal to":"less than"} ${n.maximum}`;else if(n.type==="bigint")o=`BigInt must be ${n.exact?"exactly":n.inclusive?"less than or equal to":"less than"} ${n.maximum}`;else if(n.type==="date")o=`Date must be ${n.exact?"exactly":n.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(n.maximum))}`;else o="Invalid input";break;case O.custom:o="Invalid input";break;case O.invalid_intersection_types:o="Intersection results could not be merged";break;case O.not_multiple_of:o=`Number must be a multiple of ${n.multipleOf}`;break;case O.not_finite:o="Number must be finite";break;default:o=i.defaultError,Wn.assertNever(n)}return{message:o}},gM=jp;function Q5(n){gM=n}function bm(){return gM}var jm=(n)=>{let{data:i,path:o,errorMaps:c,issueData:p}=n,a=[...o,...p.path||[]],x={...p,path:a};if(p.message!==void 0)return{...p,path:a,message:p.message};let m="",l=c.filter((f)=>!!f).slice().reverse();for(let f of l)m=f(x,{data:i,defaultError:m}).message;return{...p,path:a,message:m}},H5=[];function B(n,i){let o=bm(),c=jm({issueData:i,data:n.data,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,o,o===jp?void 0:jp].filter((p)=>!!p)});n.common.issues.push(c)}class Xi{constructor(){this.value="valid"}dirty(){if(this.value==="valid")this.value="dirty"}abort(){if(this.value!=="aborted")this.value="aborted"}static mergeArray(n,i){let o=[];for(let c of i){if(c.status==="aborted")return e;if(c.status==="dirty")n.dirty();o.push(c.value)}return{status:n.value,value:o}}static async mergeObjectAsync(n,i){let o=[];for(let c of i){let p=await c.key,a=await c.value;o.push({key:p,value:a})}return Xi.mergeObjectSync(n,o)}static mergeObjectSync(n,i){let o={};for(let c of i){let{key:p,value:a}=c;if(p.status==="aborted")return e;if(a.status==="aborted")return e;if(p.status==="dirty")n.dirty();if(a.status==="dirty")n.dirty();if(p.value!=="__proto__"&&(typeof a.value!=="undefined"||c.alwaysSet))o[p.value]=a.value}return{status:n.value,value:o}}}var e=Object.freeze({status:"aborted"}),_p=(n)=>({status:"dirty",value:n}),Ei=(n)=>({status:"valid",value:n}),Ev=(n)=>n.status==="aborted",Ov=(n)=>n.status==="dirty",Ca=(n)=>n.status==="valid",ha=(n)=>typeof Promise!=="undefined"&&n instanceof Promise;function ym(n,i,o,c){if(o==="a"&&!c)throw new TypeError("Private accessor was defined without a getter");if(typeof i==="function"?n!==i||!c:!i.has(n))throw new TypeError("Cannot read private member from an object whose class did not declare it");return o==="m"?c:o==="a"?c.call(n):c?c.value:i.get(n)}function dM(n,i,o,c,p){if(c==="m")throw new TypeError("Private method is not writable");if(c==="a"&&!p)throw new TypeError("Private accessor was defined without a setter");if(typeof i==="function"?n!==i||!p:!i.has(n))throw new TypeError("Cannot write private member to an object whose class did not declare it");return c==="a"?p.call(n,o):p?p.value=o:i.set(n,o),o}var t;(function(n){n.errToObj=(i)=>typeof i==="string"?{message:i}:i||{},n.toString=(i)=>typeof i==="string"?i:i===null||i===void 0?void 0:i.message})(t||(t={}));var Na,Da;class Ko{constructor(n,i,o,c){this._cachedPath=[],this.parent=n,this.data=i,this._path=o,this._key=c}get path(){if(!this._cachedPath.length)if(this._key instanceof Array)this._cachedPath.push(...this._path,...this._key);else this._cachedPath.push(...this._path,this._key);return this._cachedPath}}var PM=(n,i)=>{if(Ca(i))return{success:!0,data:i.value};else{if(!n.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let o=new Ii(n.common.issues);return this._error=o,this._error}}}};function fn(n){if(!n)return{};let{errorMap:i,invalid_type_error:o,required_error:c,description:p}=n;if(i&&(o||c))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);if(i)return{errorMap:i,description:p};return{errorMap:(x,m)=>{var l,f;let{message:v}=n;if(x.code==="invalid_enum_value")return{message:v!==null&&v!==void 0?v:m.defaultError};if(typeof m.data==="undefined")return{message:(l=v!==null&&v!==void 0?v:c)!==null&&l!==void 0?l:m.defaultError};if(x.code!=="invalid_type")return{message:m.defaultError};return{message:(f=v!==null&&v!==void 0?v:o)!==null&&f!==void 0?f:m.defaultError}},description:p}}class vn{constructor(n){this.spa=this.safeParseAsync,this._def=n,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this)}get description(){return this._def.description}_getType(n){return Tc(n.data)}_getOrReturnCtx(n,i){return i||{common:n.parent.common,data:n.data,parsedType:Tc(n.data),schemaErrorMap:this._def.errorMap,path:n.path,parent:n.parent}}_processInputParams(n){return{status:new Xi,ctx:{common:n.parent.common,data:n.data,parsedType:Tc(n.data),schemaErrorMap:this._def.errorMap,path:n.path,parent:n.parent}}}_parseSync(n){let i=this._parse(n);if(ha(i))throw new Error("Synchronous parse encountered promise.");return i}_parseAsync(n){let i=this._parse(n);return Promise.resolve(i)}parse(n,i){let o=this.safeParse(n,i);if(o.success)return o.data;throw o.error}safeParse(n,i){var o;let c={common:{issues:[],async:(o=i===null||i===void 0?void 0:i.async)!==null&&o!==void 0?o:!1,contextualErrorMap:i===null||i===void 0?void 0:i.errorMap},path:(i===null||i===void 0?void 0:i.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:n,parsedType:Tc(n)},p=this._parseSync({data:n,path:c.path,parent:c});return PM(c,p)}async parseAsync(n,i){let o=await this.safeParseAsync(n,i);if(o.success)return o.data;throw o.error}async safeParseAsync(n,i){let o={common:{issues:[],contextualErrorMap:i===null||i===void 0?void 0:i.errorMap,async:!0},path:(i===null||i===void 0?void 0:i.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:n,parsedType:Tc(n)},c=this._parse({data:n,path:o.path,parent:o}),p=await(ha(c)?c:Promise.resolve(c));return PM(o,p)}refine(n,i){let o=(c)=>{if(typeof i==="string"||typeof i==="undefined")return{message:i};else if(typeof i==="function")return i(c);else return i};return this._refinement((c,p)=>{let a=n(c),x=()=>p.addIssue({code:O.custom,...o(c)});if(typeof Promise!=="undefined"&&a instanceof Promise)return a.then((m)=>{if(!m)return x(),!1;else return!0});if(!a)return x(),!1;else return!0})}refinement(n,i){return this._refinement((o,c)=>{if(!n(o))return c.addIssue(typeof i==="function"?i(o,c):i),!1;else return!0})}_refinement(n){return new co({schema:this,typeName:g.ZodEffects,effect:{type:"refinement",refinement:n}})}superRefine(n){return this._refinement(n)}optional(){return Wo.create(this,this._def)}nullable(){return ho.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Ro.create(this,this._def)}promise(){return hc.create(this,this._def)}or(n){return Np.create([this,n],this._def)}and(n){return Dp.create(this,n,this._def)}transform(n){return new co({...fn(this._def),schema:this,typeName:g.ZodEffects,effect:{type:"transform",transform:n}})}default(n){let i=typeof n==="function"?n:()=>n;return new kp({...fn(this._def),innerType:this,defaultValue:i,typeName:g.ZodDefault})}brand(){return new Lm({typeName:g.ZodBranded,type:this,...fn(this._def)})}catch(n){let i=typeof n==="function"?n:()=>n;return new sp({...fn(this._def),innerType:this,catchValue:i,typeName:g.ZodCatch})}describe(n){return new this.constructor({...this._def,description:n})}pipe(n){return qa.create(this,n)}readonly(){return Zp.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}var E5=/^c[^\s-]{8,}$/i,O5=/^[0-9a-z]+$/,U5=/^[0-9A-HJKMNP-TV-Z]{26}$/,V5=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,u5=/^[a-z0-9_-]{21}$/i,_5=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,b5=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,j5="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Qv,y5=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,B5=/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,L5=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,eM="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",N5=new RegExp(`^${eM}\$`);function nR(n){let i="([01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d";if(n.precision)i=`${i}\\.\\d{${n.precision}}`;else if(n.precision==null)i=`${i}(\\.\\d+)?`;return i}function D5(n){return new RegExp(`^${nR(n)}\$`)}function iR(n){let i=`${eM}T${nR(n)}`,o=[];if(o.push(n.local?"Z?":"Z"),n.offset)o.push("([+-]\\d{2}:?\\d{2})");return i=`${i}(${o.join("|")})`,new RegExp(`^${i}\$`)}function C5(n,i){if((i==="v4"||!i)&&y5.test(n))return!0;if((i==="v6"||!i)&&B5.test(n))return!0;return!1}class Mo extends vn{_parse(n){if(this._def.coerce)n.data=String(n.data);if(this._getType(n)!==N.string){let p=this._getOrReturnCtx(n);return B(p,{code:O.invalid_type,expected:N.string,received:p.parsedType}),e}let o=new Xi,c=void 0;for(let p of this._def.checks)if(p.kind==="min"){if(n.data.length<p.value)c=this._getOrReturnCtx(n,c),B(c,{code:O.too_small,minimum:p.value,type:"string",inclusive:!0,exact:!1,message:p.message}),o.dirty()}else if(p.kind==="max"){if(n.data.length>p.value)c=this._getOrReturnCtx(n,c),B(c,{code:O.too_big,maximum:p.value,type:"string",inclusive:!0,exact:!1,message:p.message}),o.dirty()}else if(p.kind==="length"){let a=n.data.length>p.value,x=n.data.length<p.value;if(a||x){if(c=this._getOrReturnCtx(n,c),a)B(c,{code:O.too_big,maximum:p.value,type:"string",inclusive:!0,exact:!0,message:p.message});else if(x)B(c,{code:O.too_small,minimum:p.value,type:"string",inclusive:!0,exact:!0,message:p.message});o.dirty()}}else if(p.kind==="email"){if(!b5.test(n.data))c=this._getOrReturnCtx(n,c),B(c,{validation:"email",code:O.invalid_string,message:p.message}),o.dirty()}else if(p.kind==="emoji"){if(!Qv)Qv=new RegExp(j5,"u");if(!Qv.test(n.data))c=this._getOrReturnCtx(n,c),B(c,{validation:"emoji",code:O.invalid_string,message:p.message}),o.dirty()}else if(p.kind==="uuid"){if(!V5.test(n.data))c=this._getOrReturnCtx(n,c),B(c,{validation:"uuid",code:O.invalid_string,message:p.message}),o.dirty()}else if(p.kind==="nanoid"){if(!u5.test(n.data))c=this._getOrReturnCtx(n,c),B(c,{validation:"nanoid",code:O.invalid_string,message:p.message}),o.dirty()}else if(p.kind==="cuid"){if(!E5.test(n.data))c=this._getOrReturnCtx(n,c),B(c,{validation:"cuid",code:O.invalid_string,message:p.message}),o.dirty()}else if(p.kind==="cuid2"){if(!O5.test(n.data))c=this._getOrReturnCtx(n,c),B(c,{validation:"cuid2",code:O.invalid_string,message:p.message}),o.dirty()}else if(p.kind==="ulid"){if(!U5.test(n.data))c=this._getOrReturnCtx(n,c),B(c,{validation:"ulid",code:O.invalid_string,message:p.message}),o.dirty()}else if(p.kind==="url")try{new URL(n.data)}catch(a){c=this._getOrReturnCtx(n,c),B(c,{validation:"url",code:O.invalid_string,message:p.message}),o.dirty()}else if(p.kind==="regex"){if(p.regex.lastIndex=0,!p.regex.test(n.data))c=this._getOrReturnCtx(n,c),B(c,{validation:"regex",code:O.invalid_string,message:p.message}),o.dirty()}else if(p.kind==="trim")n.data=n.data.trim();else if(p.kind==="includes"){if(!n.data.includes(p.value,p.position))c=this._getOrReturnCtx(n,c),B(c,{code:O.invalid_string,validation:{includes:p.value,position:p.position},message:p.message}),o.dirty()}else if(p.kind==="toLowerCase")n.data=n.data.toLowerCase();else if(p.kind==="toUpperCase")n.data=n.data.toUpperCase();else if(p.kind==="startsWith"){if(!n.data.startsWith(p.value))c=this._getOrReturnCtx(n,c),B(c,{code:O.invalid_string,validation:{startsWith:p.value},message:p.message}),o.dirty()}else if(p.kind==="endsWith"){if(!n.data.endsWith(p.value))c=this._getOrReturnCtx(n,c),B(c,{code:O.invalid_string,validation:{endsWith:p.value},message:p.message}),o.dirty()}else if(p.kind==="datetime"){if(!iR(p).test(n.data))c=this._getOrReturnCtx(n,c),B(c,{code:O.invalid_string,validation:"datetime",message:p.message}),o.dirty()}else if(p.kind==="date"){if(!N5.test(n.data))c=this._getOrReturnCtx(n,c),B(c,{code:O.invalid_string,validation:"date",message:p.message}),o.dirty()}else if(p.kind==="time"){if(!D5(p).test(n.data))c=this._getOrReturnCtx(n,c),B(c,{code:O.invalid_string,validation:"time",message:p.message}),o.dirty()}else if(p.kind==="duration"){if(!_5.test(n.data))c=this._getOrReturnCtx(n,c),B(c,{validation:"duration",code:O.invalid_string,message:p.message}),o.dirty()}else if(p.kind==="ip"){if(!C5(n.data,p.version))c=this._getOrReturnCtx(n,c),B(c,{validation:"ip",code:O.invalid_string,message:p.message}),o.dirty()}else if(p.kind==="base64"){if(!L5.test(n.data))c=this._getOrReturnCtx(n,c),B(c,{validation:"base64",code:O.invalid_string,message:p.message}),o.dirty()}else Wn.assertNever(p);return{status:o.value,value:n.data}}_regex(n,i,o){return this.refinement((c)=>n.test(c),{validation:i,code:O.invalid_string,...t.errToObj(o)})}_addCheck(n){return new Mo({...this._def,checks:[...this._def.checks,n]})}email(n){return this._addCheck({kind:"email",...t.errToObj(n)})}url(n){return this._addCheck({kind:"url",...t.errToObj(n)})}emoji(n){return this._addCheck({kind:"emoji",...t.errToObj(n)})}uuid(n){return this._addCheck({kind:"uuid",...t.errToObj(n)})}nanoid(n){return this._addCheck({kind:"nanoid",...t.errToObj(n)})}cuid(n){return this._addCheck({kind:"cuid",...t.errToObj(n)})}cuid2(n){return this._addCheck({kind:"cuid2",...t.errToObj(n)})}ulid(n){return this._addCheck({kind:"ulid",...t.errToObj(n)})}base64(n){return this._addCheck({kind:"base64",...t.errToObj(n)})}ip(n){return this._addCheck({kind:"ip",...t.errToObj(n)})}datetime(n){var i,o;if(typeof n==="string")return this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:n});return this._addCheck({kind:"datetime",precision:typeof(n===null||n===void 0?void 0:n.precision)==="undefined"?null:n===null||n===void 0?void 0:n.precision,offset:(i=n===null||n===void 0?void 0:n.offset)!==null&&i!==void 0?i:!1,local:(o=n===null||n===void 0?void 0:n.local)!==null&&o!==void 0?o:!1,...t.errToObj(n===null||n===void 0?void 0:n.message)})}date(n){return this._addCheck({kind:"date",message:n})}time(n){if(typeof n==="string")return this._addCheck({kind:"time",precision:null,message:n});return this._addCheck({kind:"time",precision:typeof(n===null||n===void 0?void 0:n.precision)==="undefined"?null:n===null||n===void 0?void 0:n.precision,...t.errToObj(n===null||n===void 0?void 0:n.message)})}duration(n){return this._addCheck({kind:"duration",...t.errToObj(n)})}regex(n,i){return this._addCheck({kind:"regex",regex:n,...t.errToObj(i)})}includes(n,i){return this._addCheck({kind:"includes",value:n,position:i===null||i===void 0?void 0:i.position,...t.errToObj(i===null||i===void 0?void 0:i.message)})}startsWith(n,i){return this._addCheck({kind:"startsWith",value:n,...t.errToObj(i)})}endsWith(n,i){return this._addCheck({kind:"endsWith",value:n,...t.errToObj(i)})}min(n,i){return this._addCheck({kind:"min",value:n,...t.errToObj(i)})}max(n,i){return this._addCheck({kind:"max",value:n,...t.errToObj(i)})}length(n,i){return this._addCheck({kind:"length",value:n,...t.errToObj(i)})}nonempty(n){return this.min(1,t.errToObj(n))}trim(){return new Mo({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new Mo({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new Mo({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find((n)=>n.kind==="datetime")}get isDate(){return!!this._def.checks.find((n)=>n.kind==="date")}get isTime(){return!!this._def.checks.find((n)=>n.kind==="time")}get isDuration(){return!!this._def.checks.find((n)=>n.kind==="duration")}get isEmail(){return!!this._def.checks.find((n)=>n.kind==="email")}get isURL(){return!!this._def.checks.find((n)=>n.kind==="url")}get isEmoji(){return!!this._def.checks.find((n)=>n.kind==="emoji")}get isUUID(){return!!this._def.checks.find((n)=>n.kind==="uuid")}get isNANOID(){return!!this._def.checks.find((n)=>n.kind==="nanoid")}get isCUID(){return!!this._def.checks.find((n)=>n.kind==="cuid")}get isCUID2(){return!!this._def.checks.find((n)=>n.kind==="cuid2")}get isULID(){return!!this._def.checks.find((n)=>n.kind==="ulid")}get isIP(){return!!this._def.checks.find((n)=>n.kind==="ip")}get isBase64(){return!!this._def.checks.find((n)=>n.kind==="base64")}get minLength(){let n=null;for(let i of this._def.checks)if(i.kind==="min"){if(n===null||i.value>n)n=i.value}return n}get maxLength(){let n=null;for(let i of this._def.checks)if(i.kind==="max"){if(n===null||i.value<n)n=i.value}return n}}Mo.create=(n)=>{var i;return new Mo({checks:[],typeName:g.ZodString,coerce:(i=n===null||n===void 0?void 0:n.coerce)!==null&&i!==void 0?i:!1,...fn(n)})};function h5(n,i){let o=(n.toString().split(".")[1]||"").length,c=(i.toString().split(".")[1]||"").length,p=o>c?o:c,a=parseInt(n.toFixed(p).replace(".","")),x=parseInt(i.toFixed(p).replace(".",""));return a%x/Math.pow(10,p)}class Jc extends vn{constructor(){super(...arguments);this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(n){if(this._def.coerce)n.data=Number(n.data);if(this._getType(n)!==N.number){let p=this._getOrReturnCtx(n);return B(p,{code:O.invalid_type,expected:N.number,received:p.parsedType}),e}let o=void 0,c=new Xi;for(let p of this._def.checks)if(p.kind==="int"){if(!Wn.isInteger(n.data))o=this._getOrReturnCtx(n,o),B(o,{code:O.invalid_type,expected:"integer",received:"float",message:p.message}),c.dirty()}else if(p.kind==="min"){if(p.inclusive?n.data<p.value:n.data<=p.value)o=this._getOrReturnCtx(n,o),B(o,{code:O.too_small,minimum:p.value,type:"number",inclusive:p.inclusive,exact:!1,message:p.message}),c.dirty()}else if(p.kind==="max"){if(p.inclusive?n.data>p.value:n.data>=p.value)o=this._getOrReturnCtx(n,o),B(o,{code:O.too_big,maximum:p.value,type:"number",inclusive:p.inclusive,exact:!1,message:p.message}),c.dirty()}else if(p.kind==="multipleOf"){if(h5(n.data,p.value)!==0)o=this._getOrReturnCtx(n,o),B(o,{code:O.not_multiple_of,multipleOf:p.value,message:p.message}),c.dirty()}else if(p.kind==="finite"){if(!Number.isFinite(n.data))o=this._getOrReturnCtx(n,o),B(o,{code:O.not_finite,message:p.message}),c.dirty()}else Wn.assertNever(p);return{status:c.value,value:n.data}}gte(n,i){return this.setLimit("min",n,!0,t.toString(i))}gt(n,i){return this.setLimit("min",n,!1,t.toString(i))}lte(n,i){return this.setLimit("max",n,!0,t.toString(i))}lt(n,i){return this.setLimit("max",n,!1,t.toString(i))}setLimit(n,i,o,c){return new Jc({...this._def,checks:[...this._def.checks,{kind:n,value:i,inclusive:o,message:t.toString(c)}]})}_addCheck(n){return new Jc({...this._def,checks:[...this._def.checks,n]})}int(n){return this._addCheck({kind:"int",message:t.toString(n)})}positive(n){return this._addCheck({kind:"min",value:0,inclusive:!1,message:t.toString(n)})}negative(n){return this._addCheck({kind:"max",value:0,inclusive:!1,message:t.toString(n)})}nonpositive(n){return this._addCheck({kind:"max",value:0,inclusive:!0,message:t.toString(n)})}nonnegative(n){return this._addCheck({kind:"min",value:0,inclusive:!0,message:t.toString(n)})}multipleOf(n,i){return this._addCheck({kind:"multipleOf",value:n,message:t.toString(i)})}finite(n){return this._addCheck({kind:"finite",message:t.toString(n)})}safe(n){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:t.toString(n)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:t.toString(n)})}get minValue(){let n=null;for(let i of this._def.checks)if(i.kind==="min"){if(n===null||i.value>n)n=i.value}return n}get maxValue(){let n=null;for(let i of this._def.checks)if(i.kind==="max"){if(n===null||i.value<n)n=i.value}return n}get isInt(){return!!this._def.checks.find((n)=>n.kind==="int"||n.kind==="multipleOf"&&Wn.isInteger(n.value))}get isFinite(){let n=null,i=null;for(let o of this._def.checks)if(o.kind==="finite"||o.kind==="int"||o.kind==="multipleOf")return!0;else if(o.kind==="min"){if(i===null||o.value>i)i=o.value}else if(o.kind==="max"){if(n===null||o.value<n)n=o.value}return Number.isFinite(i)&&Number.isFinite(n)}}Jc.create=(n)=>{return new Jc({checks:[],typeName:g.ZodNumber,coerce:(n===null||n===void 0?void 0:n.coerce)||!1,...fn(n)})};class Sc extends vn{constructor(){super(...arguments);this.min=this.gte,this.max=this.lte}_parse(n){if(this._def.coerce)n.data=BigInt(n.data);if(this._getType(n)!==N.bigint){let p=this._getOrReturnCtx(n);return B(p,{code:O.invalid_type,expected:N.bigint,received:p.parsedType}),e}let o=void 0,c=new Xi;for(let p of this._def.checks)if(p.kind==="min"){if(p.inclusive?n.data<p.value:n.data<=p.value)o=this._getOrReturnCtx(n,o),B(o,{code:O.too_small,type:"bigint",minimum:p.value,inclusive:p.inclusive,message:p.message}),c.dirty()}else if(p.kind==="max"){if(p.inclusive?n.data>p.value:n.data>=p.value)o=this._getOrReturnCtx(n,o),B(o,{code:O.too_big,type:"bigint",maximum:p.value,inclusive:p.inclusive,message:p.message}),c.dirty()}else if(p.kind==="multipleOf"){if(n.data%p.value!==BigInt(0))o=this._getOrReturnCtx(n,o),B(o,{code:O.not_multiple_of,multipleOf:p.value,message:p.message}),c.dirty()}else Wn.assertNever(p);return{status:c.value,value:n.data}}gte(n,i){return this.setLimit("min",n,!0,t.toString(i))}gt(n,i){return this.setLimit("min",n,!1,t.toString(i))}lte(n,i){return this.setLimit("max",n,!0,t.toString(i))}lt(n,i){return this.setLimit("max",n,!1,t.toString(i))}setLimit(n,i,o,c){return new Sc({...this._def,checks:[...this._def.checks,{kind:n,value:i,inclusive:o,message:t.toString(c)}]})}_addCheck(n){return new Sc({...this._def,checks:[...this._def.checks,n]})}positive(n){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:t.toString(n)})}negative(n){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:t.toString(n)})}nonpositive(n){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:t.toString(n)})}nonnegative(n){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:t.toString(n)})}multipleOf(n,i){return this._addCheck({kind:"multipleOf",value:n,message:t.toString(i)})}get minValue(){let n=null;for(let i of this._def.checks)if(i.kind==="min"){if(n===null||i.value>n)n=i.value}return n}get maxValue(){let n=null;for(let i of this._def.checks)if(i.kind==="max"){if(n===null||i.value<n)n=i.value}return n}}Sc.create=(n)=>{var i;return new Sc({checks:[],typeName:g.ZodBigInt,coerce:(i=n===null||n===void 0?void 0:n.coerce)!==null&&i!==void 0?i:!1,...fn(n)})};class yp extends vn{_parse(n){if(this._def.coerce)n.data=Boolean(n.data);if(this._getType(n)!==N.boolean){let o=this._getOrReturnCtx(n);return B(o,{code:O.invalid_type,expected:N.boolean,received:o.parsedType}),e}return Ei(n.data)}}yp.create=(n)=>{return new yp({typeName:g.ZodBoolean,coerce:(n===null||n===void 0?void 0:n.coerce)||!1,...fn(n)})};class Nc extends vn{_parse(n){if(this._def.coerce)n.data=new Date(n.data);if(this._getType(n)!==N.date){let p=this._getOrReturnCtx(n);return B(p,{code:O.invalid_type,expected:N.date,received:p.parsedType}),e}if(isNaN(n.data.getTime())){let p=this._getOrReturnCtx(n);return B(p,{code:O.invalid_date}),e}let o=new Xi,c=void 0;for(let p of this._def.checks)if(p.kind==="min"){if(n.data.getTime()<p.value)c=this._getOrReturnCtx(n,c),B(c,{code:O.too_small,message:p.message,inclusive:!0,exact:!1,minimum:p.value,type:"date"}),o.dirty()}else if(p.kind==="max"){if(n.data.getTime()>p.value)c=this._getOrReturnCtx(n,c),B(c,{code:O.too_big,message:p.message,inclusive:!0,exact:!1,maximum:p.value,type:"date"}),o.dirty()}else Wn.assertNever(p);return{status:o.value,value:new Date(n.data.getTime())}}_addCheck(n){return new Nc({...this._def,checks:[...this._def.checks,n]})}min(n,i){return this._addCheck({kind:"min",value:n.getTime(),message:t.toString(i)})}max(n,i){return this._addCheck({kind:"max",value:n.getTime(),message:t.toString(i)})}get minDate(){let n=null;for(let i of this._def.checks)if(i.kind==="min"){if(n===null||i.value>n)n=i.value}return n!=null?new Date(n):null}get maxDate(){let n=null;for(let i of this._def.checks)if(i.kind==="max"){if(n===null||i.value<n)n=i.value}return n!=null?new Date(n):null}}Nc.create=(n)=>{return new Nc({checks:[],coerce:(n===null||n===void 0?void 0:n.coerce)||!1,typeName:g.ZodDate,...fn(n)})};class Ia extends vn{_parse(n){if(this._getType(n)!==N.symbol){let o=this._getOrReturnCtx(n);return B(o,{code:O.invalid_type,expected:N.symbol,received:o.parsedType}),e}return Ei(n.data)}}Ia.create=(n)=>{return new Ia({typeName:g.ZodSymbol,...fn(n)})};class Bp extends vn{_parse(n){if(this._getType(n)!==N.undefined){let o=this._getOrReturnCtx(n);return B(o,{code:O.invalid_type,expected:N.undefined,received:o.parsedType}),e}return Ei(n.data)}}Bp.create=(n)=>{return new Bp({typeName:g.ZodUndefined,...fn(n)})};class Lp extends vn{_parse(n){if(this._getType(n)!==N.null){let o=this._getOrReturnCtx(n);return B(o,{code:O.invalid_type,expected:N.null,received:o.parsedType}),e}return Ei(n.data)}}Lp.create=(n)=>{return new Lp({typeName:g.ZodNull,...fn(n)})};class Dc extends vn{constructor(){super(...arguments);this._any=!0}_parse(n){return Ei(n.data)}}Dc.create=(n)=>{return new Dc({typeName:g.ZodAny,...fn(n)})};class wc extends vn{constructor(){super(...arguments);this._unknown=!0}_parse(n){return Ei(n.data)}}wc.create=(n)=>{return new wc({typeName:g.ZodUnknown,...fn(n)})};class Uo extends vn{_parse(n){let i=this._getOrReturnCtx(n);return B(i,{code:O.invalid_type,expected:N.never,received:i.parsedType}),e}}Uo.create=(n)=>{return new Uo({typeName:g.ZodNever,...fn(n)})};class ka extends vn{_parse(n){if(this._getType(n)!==N.undefined){let o=this._getOrReturnCtx(n);return B(o,{code:O.invalid_type,expected:N.void,received:o.parsedType}),e}return Ei(n.data)}}ka.create=(n)=>{return new ka({typeName:g.ZodVoid,...fn(n)})};class Ro extends vn{_parse(n){let{ctx:i,status:o}=this._processInputParams(n),c=this._def;if(i.parsedType!==N.array)return B(i,{code:O.invalid_type,expected:N.array,received:i.parsedType}),e;if(c.exactLength!==null){let a=i.data.length>c.exactLength.value,x=i.data.length<c.exactLength.value;if(a||x)B(i,{code:a?O.too_big:O.too_small,minimum:x?c.exactLength.value:void 0,maximum:a?c.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:c.exactLength.message}),o.dirty()}if(c.minLength!==null){if(i.data.length<c.minLength.value)B(i,{code:O.too_small,minimum:c.minLength.value,type:"array",inclusive:!0,exact:!1,message:c.minLength.message}),o.dirty()}if(c.maxLength!==null){if(i.data.length>c.maxLength.value)B(i,{code:O.too_big,maximum:c.maxLength.value,type:"array",inclusive:!0,exact:!1,message:c.maxLength.message}),o.dirty()}if(i.common.async)return Promise.all([...i.data].map((a,x)=>{return c.type._parseAsync(new Ko(i,a,i.path,x))})).then((a)=>{return Xi.mergeArray(o,a)});let p=[...i.data].map((a,x)=>{return c.type._parseSync(new Ko(i,a,i.path,x))});return Xi.mergeArray(o,p)}get element(){return this._def.type}min(n,i){return new Ro({...this._def,minLength:{value:n,message:t.toString(i)}})}max(n,i){return new Ro({...this._def,maxLength:{value:n,message:t.toString(i)}})}length(n,i){return new Ro({...this._def,exactLength:{value:n,message:t.toString(i)}})}nonempty(n){return this.min(1,n)}}Ro.create=(n,i)=>{return new Ro({type:n,minLength:null,maxLength:null,exactLength:null,typeName:g.ZodArray,...fn(i)})};function up(n){if(n instanceof In){let i={};for(let o in n.shape){let c=n.shape[o];i[o]=Wo.create(up(c))}return new In({...n._def,shape:()=>i})}else if(n instanceof Ro)return new Ro({...n._def,type:up(n.element)});else if(n instanceof Wo)return Wo.create(up(n.unwrap()));else if(n instanceof ho)return ho.create(up(n.unwrap()));else if(n instanceof Vo)return Vo.create(n.items.map((i)=>up(i)));else return n}class In extends vn{constructor(){super(...arguments);this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let n=this._def.shape(),i=Wn.objectKeys(n);return this._cached={shape:n,keys:i}}_parse(n){if(this._getType(n)!==N.object){let l=this._getOrReturnCtx(n);return B(l,{code:O.invalid_type,expected:N.object,received:l.parsedType}),e}let{status:o,ctx:c}=this._processInputParams(n),{shape:p,keys:a}=this._getCached(),x=[];if(!(this._def.catchall instanceof Uo&&this._def.unknownKeys==="strip")){for(let l in c.data)if(!a.includes(l))x.push(l)}let m=[];for(let l of a){let f=p[l],v=c.data[l];m.push({key:{status:"valid",value:l},value:f._parse(new Ko(c,v,c.path,l)),alwaysSet:l in c.data})}if(this._def.catchall instanceof Uo){let l=this._def.unknownKeys;if(l==="passthrough")for(let f of x)m.push({key:{status:"valid",value:f},value:{status:"valid",value:c.data[f]}});else if(l==="strict"){if(x.length>0)B(c,{code:O.unrecognized_keys,keys:x}),o.dirty()}else if(l==="strip");else throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let l=this._def.catchall;for(let f of x){let v=c.data[f];m.push({key:{status:"valid",value:f},value:l._parse(new Ko(c,v,c.path,f)),alwaysSet:f in c.data})}}if(c.common.async)return Promise.resolve().then(async()=>{let l=[];for(let f of m){let v=await f.key,$=await f.value;l.push({key:v,value:$,alwaysSet:f.alwaysSet})}return l}).then((l)=>{return Xi.mergeObjectSync(o,l)});else return Xi.mergeObjectSync(o,m)}get shape(){return this._def.shape()}strict(n){return t.errToObj,new In({...this._def,unknownKeys:"strict",...n!==void 0?{errorMap:(i,o)=>{var c,p,a,x;let m=(a=(p=(c=this._def).errorMap)===null||p===void 0?void 0:p.call(c,i,o).message)!==null&&a!==void 0?a:o.defaultError;if(i.code==="unrecognized_keys")return{message:(x=t.errToObj(n).message)!==null&&x!==void 0?x:m};return{message:m}}}:{}})}strip(){return new In({...this._def,unknownKeys:"strip"})}passthrough(){return new In({...this._def,unknownKeys:"passthrough"})}extend(n){return new In({...this._def,shape:()=>({...this._def.shape(),...n})})}merge(n){return new In({unknownKeys:n._def.unknownKeys,catchall:n._def.catchall,shape:()=>({...this._def.shape(),...n._def.shape()}),typeName:g.ZodObject})}setKey(n,i){return this.augment({[n]:i})}catchall(n){return new In({...this._def,catchall:n})}pick(n){let i={};return Wn.objectKeys(n).forEach((o)=>{if(n[o]&&this.shape[o])i[o]=this.shape[o]}),new In({...this._def,shape:()=>i})}omit(n){let i={};return Wn.objectKeys(this.shape).forEach((o)=>{if(!n[o])i[o]=this.shape[o]}),new In({...this._def,shape:()=>i})}deepPartial(){return up(this)}partial(n){let i={};return Wn.objectKeys(this.shape).forEach((o)=>{let c=this.shape[o];if(n&&!n[o])i[o]=c;else i[o]=c.optional()}),new In({...this._def,shape:()=>i})}required(n){let i={};return Wn.objectKeys(this.shape).forEach((o)=>{if(n&&!n[o])i[o]=this.shape[o];else{let p=this.shape[o];while(p instanceof Wo)p=p._def.innerType;i[o]=p}}),new In({...this._def,shape:()=>i})}keyof(){return oR(Wn.objectKeys(this.shape))}}In.create=(n,i)=>{return new In({shape:()=>n,unknownKeys:"strip",catchall:Uo.create(),typeName:g.ZodObject,...fn(i)})};In.strictCreate=(n,i)=>{return new In({shape:()=>n,unknownKeys:"strict",catchall:Uo.create(),typeName:g.ZodObject,...fn(i)})};In.lazycreate=(n,i)=>{return new In({shape:n,unknownKeys:"strip",catchall:Uo.create(),typeName:g.ZodObject,...fn(i)})};class Np extends vn{_parse(n){let{ctx:i}=this._processInputParams(n),o=this._def.options;function c(p){for(let x of p)if(x.result.status==="valid")return x.result;for(let x of p)if(x.result.status==="dirty")return i.common.issues.push(...x.ctx.common.issues),x.result;let a=p.map((x)=>new Ii(x.ctx.common.issues));return B(i,{code:O.invalid_union,unionErrors:a}),e}if(i.common.async)return Promise.all(o.map(async(p)=>{let a={...i,common:{...i.common,issues:[]},parent:null};return{result:await p._parseAsync({data:i.data,path:i.path,parent:a}),ctx:a}})).then(c);else{let p=void 0,a=[];for(let m of o){let l={...i,common:{...i.common,issues:[]},parent:null},f=m._parseSync({data:i.data,path:i.path,parent:l});if(f.status==="valid")return f;else if(f.status==="dirty"&&!p)p={result:f,ctx:l};if(l.common.issues.length)a.push(l.common.issues)}if(p)return i.common.issues.push(...p.ctx.common.issues),p.result;let x=a.map((m)=>new Ii(m));return B(i,{code:O.invalid_union,unionErrors:x}),e}}get options(){return this._def.options}}Np.create=(n,i)=>{return new Np({options:n,typeName:g.ZodUnion,...fn(i)})};var Co=(n)=>{if(n instanceof Cp)return Co(n.schema);else if(n instanceof co)return Co(n.innerType());else if(n instanceof hp)return[n.value];else if(n instanceof Ac)return n.options;else if(n instanceof Ip)return Wn.objectValues(n.enum);else if(n instanceof kp)return Co(n._def.innerType);else if(n instanceof Bp)return[void 0];else if(n instanceof Lp)return[null];else if(n instanceof Wo)return[void 0,...Co(n.unwrap())];else if(n instanceof ho)return[null,...Co(n.unwrap())];else if(n instanceof Lm)return Co(n.unwrap());else if(n instanceof Zp)return Co(n.unwrap());else if(n instanceof sp)return Co(n._def.innerType);else return[]};class Bm extends vn{_parse(n){let{ctx:i}=this._processInputParams(n);if(i.parsedType!==N.object)return B(i,{code:O.invalid_type,expected:N.object,received:i.parsedType}),e;let o=this.discriminator,c=i.data[o],p=this.optionsMap.get(c);if(!p)return B(i,{code:O.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[o]}),e;if(i.common.async)return p._parseAsync({data:i.data,path:i.path,parent:i});else return p._parseSync({data:i.data,path:i.path,parent:i})}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(n,i,o){let c=new Map;for(let p of i){let a=Co(p.shape[n]);if(!a.length)throw new Error(`A discriminator value for key \`${n}\` could not be extracted from all schema options`);for(let x of a){if(c.has(x))throw new Error(`Discriminator property ${String(n)} has duplicate value ${String(x)}`);c.set(x,p)}}return new Bm({typeName:g.ZodDiscriminatedUnion,discriminator:n,options:i,optionsMap:c,...fn(o)})}}function Uv(n,i){let o=Tc(n),c=Tc(i);if(n===i)return{valid:!0,data:n};else if(o===N.object&&c===N.object){let p=Wn.objectKeys(i),a=Wn.objectKeys(n).filter((m)=>p.indexOf(m)!==-1),x={...n,...i};for(let m of a){let l=Uv(n[m],i[m]);if(!l.valid)return{valid:!1};x[m]=l.data}return{valid:!0,data:x}}else if(o===N.array&&c===N.array){if(n.length!==i.length)return{valid:!1};let p=[];for(let a=0;a<n.length;a++){let x=n[a],m=i[a],l=Uv(x,m);if(!l.valid)return{valid:!1};p.push(l.data)}return{valid:!0,data:p}}else if(o===N.date&&c===N.date&&+n===+i)return{valid:!0,data:n};else return{valid:!1}}class Dp extends vn{_parse(n){let{status:i,ctx:o}=this._processInputParams(n),c=(p,a)=>{if(Ev(p)||Ev(a))return e;let x=Uv(p.value,a.value);if(!x.valid)return B(o,{code:O.invalid_intersection_types}),e;if(Ov(p)||Ov(a))i.dirty();return{status:i.value,value:x.data}};if(o.common.async)return Promise.all([this._def.left._parseAsync({data:o.data,path:o.path,parent:o}),this._def.right._parseAsync({data:o.data,path:o.path,parent:o})]).then(([p,a])=>c(p,a));else return c(this._def.left._parseSync({data:o.data,path:o.path,parent:o}),this._def.right._parseSync({data:o.data,path:o.path,parent:o}))}}Dp.create=(n,i,o)=>{return new Dp({left:n,right:i,typeName:g.ZodIntersection,...fn(o)})};class Vo extends vn{_parse(n){let{status:i,ctx:o}=this._processInputParams(n);if(o.parsedType!==N.array)return B(o,{code:O.invalid_type,expected:N.array,received:o.parsedType}),e;if(o.data.length<this._def.items.length)return B(o,{code:O.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),e;if(!this._def.rest&&o.data.length>this._def.items.length)B(o,{code:O.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),i.dirty();let p=[...o.data].map((a,x)=>{let m=this._def.items[x]||this._def.rest;if(!m)return null;return m._parse(new Ko(o,a,o.path,x))}).filter((a)=>!!a);if(o.common.async)return Promise.all(p).then((a)=>{return Xi.mergeArray(i,a)});else return Xi.mergeArray(i,p)}get items(){return this._def.items}rest(n){return new Vo({...this._def,rest:n})}}Vo.create=(n,i)=>{if(!Array.isArray(n))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Vo({items:n,typeName:g.ZodTuple,rest:null,...fn(i)})};class sa extends vn{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(n){let{status:i,ctx:o}=this._processInputParams(n);if(o.parsedType!==N.object)return B(o,{code:O.invalid_type,expected:N.object,received:o.parsedType}),e;let c=[],p=this._def.keyType,a=this._def.valueType;for(let x in o.data)c.push({key:p._parse(new Ko(o,x,o.path,x)),value:a._parse(new Ko(o,o.data[x],o.path,x)),alwaysSet:x in o.data});if(o.common.async)return Xi.mergeObjectAsync(i,c);else return Xi.mergeObjectSync(i,c)}get element(){return this._def.valueType}static create(n,i,o){if(i instanceof vn)return new sa({keyType:n,valueType:i,typeName:g.ZodRecord,...fn(o)});return new sa({keyType:Mo.create(),valueType:n,typeName:g.ZodRecord,...fn(i)})}}class Za extends vn{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(n){let{status:i,ctx:o}=this._processInputParams(n);if(o.parsedType!==N.map)return B(o,{code:O.invalid_type,expected:N.map,received:o.parsedType}),e;let c=this._def.keyType,p=this._def.valueType,a=[...o.data.entries()].map(([x,m],l)=>{return{key:c._parse(new Ko(o,x,o.path,[l,"key"])),value:p._parse(new Ko(o,m,o.path,[l,"value"]))}});if(o.common.async){let x=new Map;return Promise.resolve().then(async()=>{for(let m of a){let l=await m.key,f=await m.value;if(l.status==="aborted"||f.status==="aborted")return e;if(l.status==="dirty"||f.status==="dirty")i.dirty();x.set(l.value,f.value)}return{status:i.value,value:x}})}else{let x=new Map;for(let m of a){let{key:l,value:f}=m;if(l.status==="aborted"||f.status==="aborted")return e;if(l.status==="dirty"||f.status==="dirty")i.dirty();x.set(l.value,f.value)}return{status:i.value,value:x}}}}Za.create=(n,i,o)=>{return new Za({valueType:i,keyType:n,typeName:g.ZodMap,...fn(o)})};class Cc extends vn{_parse(n){let{status:i,ctx:o}=this._processInputParams(n);if(o.parsedType!==N.set)return B(o,{code:O.invalid_type,expected:N.set,received:o.parsedType}),e;let c=this._def;if(c.minSize!==null){if(o.data.size<c.minSize.value)B(o,{code:O.too_small,minimum:c.minSize.value,type:"set",inclusive:!0,exact:!1,message:c.minSize.message}),i.dirty()}if(c.maxSize!==null){if(o.data.size>c.maxSize.value)B(o,{code:O.too_big,maximum:c.maxSize.value,type:"set",inclusive:!0,exact:!1,message:c.maxSize.message}),i.dirty()}let p=this._def.valueType;function a(m){let l=new Set;for(let f of m){if(f.status==="aborted")return e;if(f.status==="dirty")i.dirty();l.add(f.value)}return{status:i.value,value:l}}let x=[...o.data.values()].map((m,l)=>p._parse(new Ko(o,m,o.path,l)));if(o.common.async)return Promise.all(x).then((m)=>a(m));else return a(x)}min(n,i){return new Cc({...this._def,minSize:{value:n,message:t.toString(i)}})}max(n,i){return new Cc({...this._def,maxSize:{value:n,message:t.toString(i)}})}size(n,i){return this.min(n,i).max(n,i)}nonempty(n){return this.min(1,n)}}Cc.create=(n,i)=>{return new Cc({valueType:n,minSize:null,maxSize:null,typeName:g.ZodSet,...fn(i)})};class bp extends vn{constructor(){super(...arguments);this.validate=this.implement}_parse(n){let{ctx:i}=this._processInputParams(n);if(i.parsedType!==N.function)return B(i,{code:O.invalid_type,expected:N.function,received:i.parsedType}),e;function o(x,m){return jm({data:x,path:i.path,errorMaps:[i.common.contextualErrorMap,i.schemaErrorMap,bm(),jp].filter((l)=>!!l),issueData:{code:O.invalid_arguments,argumentsError:m}})}function c(x,m){return jm({data:x,path:i.path,errorMaps:[i.common.contextualErrorMap,i.schemaErrorMap,bm(),jp].filter((l)=>!!l),issueData:{code:O.invalid_return_type,returnTypeError:m}})}let p={errorMap:i.common.contextualErrorMap},a=i.data;if(this._def.returns instanceof hc){let x=this;return Ei(async function(...m){let l=new Ii([]),f=await x._def.args.parseAsync(m,p).catch((T)=>{throw l.addIssue(o(m,T)),l}),v=await Reflect.apply(a,this,f);return await x._def.returns._def.type.parseAsync(v,p).catch((T)=>{throw l.addIssue(c(v,T)),l})})}else{let x=this;return Ei(function(...m){let l=x._def.args.safeParse(m,p);if(!l.success)throw new Ii([o(m,l.error)]);let f=Reflect.apply(a,this,l.data),v=x._def.returns.safeParse(f,p);if(!v.success)throw new Ii([c(f,v.error)]);return v.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...n){return new bp({...this._def,args:Vo.create(n).rest(wc.create())})}returns(n){return new bp({...this._def,returns:n})}implement(n){return this.parse(n)}strictImplement(n){return this.parse(n)}static create(n,i,o){return new bp({args:n?n:Vo.create([]).rest(wc.create()),returns:i||wc.create(),typeName:g.ZodFunction,...fn(o)})}}class Cp extends vn{get schema(){return this._def.getter()}_parse(n){let{ctx:i}=this._processInputParams(n);return this._def.getter()._parse({data:i.data,path:i.path,parent:i})}}Cp.create=(n,i)=>{return new Cp({getter:n,typeName:g.ZodLazy,...fn(i)})};class hp extends vn{_parse(n){if(n.data!==this._def.value){let i=this._getOrReturnCtx(n);return B(i,{received:i.data,code:O.invalid_literal,expected:this._def.value}),e}return{status:"valid",value:n.data}}get value(){return this._def.value}}hp.create=(n,i)=>{return new hp({value:n,typeName:g.ZodLiteral,...fn(i)})};function oR(n,i){return new Ac({values:n,typeName:g.ZodEnum,...fn(i)})}class Ac extends vn{constructor(){super(...arguments);Na.set(this,void 0)}_parse(n){if(typeof n.data!=="string"){let i=this._getOrReturnCtx(n),o=this._def.values;return B(i,{expected:Wn.joinValues(o),received:i.parsedType,code:O.invalid_type}),e}if(!ym(this,Na,"f"))dM(this,Na,new Set(this._def.values),"f");if(!ym(this,Na,"f").has(n.data)){let i=this._getOrReturnCtx(n),o=this._def.values;return B(i,{received:i.data,code:O.invalid_enum_value,options:o}),e}return Ei(n.data)}get options(){return this._def.values}get enum(){let n={};for(let i of this._def.values)n[i]=i;return n}get Values(){let n={};for(let i of this._def.values)n[i]=i;return n}get Enum(){let n={};for(let i of this._def.values)n[i]=i;return n}extract(n,i=this._def){return Ac.create(n,{...this._def,...i})}exclude(n,i=this._def){return Ac.create(this.options.filter((o)=>!n.includes(o)),{...this._def,...i})}}Na=new WeakMap;Ac.create=oR;class Ip extends vn{constructor(){super(...arguments);Da.set(this,void 0)}_parse(n){let i=Wn.getValidEnumValues(this._def.values),o=this._getOrReturnCtx(n);if(o.parsedType!==N.string&&o.parsedType!==N.number){let c=Wn.objectValues(i);return B(o,{expected:Wn.joinValues(c),received:o.parsedType,code:O.invalid_type}),e}if(!ym(this,Da,"f"))dM(this,Da,new Set(Wn.getValidEnumValues(this._def.values)),"f");if(!ym(this,Da,"f").has(n.data)){let c=Wn.objectValues(i);return B(o,{received:o.data,code:O.invalid_enum_value,options:c}),e}return Ei(n.data)}get enum(){return this._def.values}}Da=new WeakMap;Ip.create=(n,i)=>{return new Ip({values:n,typeName:g.ZodNativeEnum,...fn(i)})};class hc extends vn{unwrap(){return this._def.type}_parse(n){let{ctx:i}=this._processInputParams(n);if(i.parsedType!==N.promise&&i.common.async===!1)return B(i,{code:O.invalid_type,expected:N.promise,received:i.parsedType}),e;let o=i.parsedType===N.promise?i.data:Promise.resolve(i.data);return Ei(o.then((c)=>{return this._def.type.parseAsync(c,{path:i.path,errorMap:i.common.contextualErrorMap})}))}}hc.create=(n,i)=>{return new hc({type:n,typeName:g.ZodPromise,...fn(i)})};class co extends vn{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===g.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(n){let{status:i,ctx:o}=this._processInputParams(n),c=this._def.effect||null,p={addIssue:(a)=>{if(B(o,a),a.fatal)i.abort();else i.dirty()},get path(){return o.path}};if(p.addIssue=p.addIssue.bind(p),c.type==="preprocess"){let a=c.transform(o.data,p);if(o.common.async)return Promise.resolve(a).then(async(x)=>{if(i.value==="aborted")return e;let m=await this._def.schema._parseAsync({data:x,path:o.path,parent:o});if(m.status==="aborted")return e;if(m.status==="dirty")return _p(m.value);if(i.value==="dirty")return _p(m.value);return m});else{if(i.value==="aborted")return e;let x=this._def.schema._parseSync({data:a,path:o.path,parent:o});if(x.status==="aborted")return e;if(x.status==="dirty")return _p(x.value);if(i.value==="dirty")return _p(x.value);return x}}if(c.type==="refinement"){let a=(x)=>{let m=c.refinement(x,p);if(o.common.async)return Promise.resolve(m);if(m instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return x};if(o.common.async===!1){let x=this._def.schema._parseSync({data:o.data,path:o.path,parent:o});if(x.status==="aborted")return e;if(x.status==="dirty")i.dirty();return a(x.value),{status:i.value,value:x.value}}else return this._def.schema._parseAsync({data:o.data,path:o.path,parent:o}).then((x)=>{if(x.status==="aborted")return e;if(x.status==="dirty")i.dirty();return a(x.value).then(()=>{return{status:i.value,value:x.value}})})}if(c.type==="transform")if(o.common.async===!1){let a=this._def.schema._parseSync({data:o.data,path:o.path,parent:o});if(!Ca(a))return a;let x=c.transform(a.value,p);if(x instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:i.value,value:x}}else return this._def.schema._parseAsync({data:o.data,path:o.path,parent:o}).then((a)=>{if(!Ca(a))return a;return Promise.resolve(c.transform(a.value,p)).then((x)=>({status:i.value,value:x}))});Wn.assertNever(c)}}co.create=(n,i,o)=>{return new co({schema:n,typeName:g.ZodEffects,effect:i,...fn(o)})};co.createWithPreprocess=(n,i,o)=>{return new co({schema:i,effect:{type:"preprocess",transform:n},typeName:g.ZodEffects,...fn(o)})};class Wo extends vn{_parse(n){if(this._getType(n)===N.undefined)return Ei(void 0);return this._def.innerType._parse(n)}unwrap(){return this._def.innerType}}Wo.create=(n,i)=>{return new Wo({innerType:n,typeName:g.ZodOptional,...fn(i)})};class ho extends vn{_parse(n){if(this._getType(n)===N.null)return Ei(null);return this._def.innerType._parse(n)}unwrap(){return this._def.innerType}}ho.create=(n,i)=>{return new ho({innerType:n,typeName:g.ZodNullable,...fn(i)})};class kp extends vn{_parse(n){let{ctx:i}=this._processInputParams(n),o=i.data;if(i.parsedType===N.undefined)o=this._def.defaultValue();return this._def.innerType._parse({data:o,path:i.path,parent:i})}removeDefault(){return this._def.innerType}}kp.create=(n,i)=>{return new kp({innerType:n,typeName:g.ZodDefault,defaultValue:typeof i.default==="function"?i.default:()=>i.default,...fn(i)})};class sp extends vn{_parse(n){let{ctx:i}=this._processInputParams(n),o={...i,common:{...i.common,issues:[]}},c=this._def.innerType._parse({data:o.data,path:o.path,parent:{...o}});if(ha(c))return c.then((p)=>{return{status:"valid",value:p.status==="valid"?p.value:this._def.catchValue({get error(){return new Ii(o.common.issues)},input:o.data})}});else return{status:"valid",value:c.status==="valid"?c.value:this._def.catchValue({get error(){return new Ii(o.common.issues)},input:o.data})}}removeCatch(){return this._def.innerType}}sp.create=(n,i)=>{return new sp({innerType:n,typeName:g.ZodCatch,catchValue:typeof i.catch==="function"?i.catch:()=>i.catch,...fn(i)})};class ta extends vn{_parse(n){if(this._getType(n)!==N.nan){let o=this._getOrReturnCtx(n);return B(o,{code:O.invalid_type,expected:N.nan,received:o.parsedType}),e}return{status:"valid",value:n.data}}}ta.create=(n)=>{return new ta({typeName:g.ZodNaN,...fn(n)})};var I5=Symbol("zod_brand");class Lm extends vn{_parse(n){let{ctx:i}=this._processInputParams(n),o=i.data;return this._def.type._parse({data:o,path:i.path,parent:i})}unwrap(){return this._def.type}}class qa extends vn{_parse(n){let{status:i,ctx:o}=this._processInputParams(n);if(o.common.async)return(async()=>{let p=await this._def.in._parseAsync({data:o.data,path:o.path,parent:o});if(p.status==="aborted")return e;if(p.status==="dirty")return i.dirty(),_p(p.value);else return this._def.out._parseAsync({data:p.value,path:o.path,parent:o})})();else{let c=this._def.in._parseSync({data:o.data,path:o.path,parent:o});if(c.status==="aborted")return e;if(c.status==="dirty")return i.dirty(),{status:"dirty",value:c.value};else return this._def.out._parseSync({data:c.value,path:o.path,parent:o})}}static create(n,i){return new qa({in:n,out:i,typeName:g.ZodPipeline})}}class Zp extends vn{_parse(n){let i=this._def.innerType._parse(n),o=(c)=>{if(Ca(c))c.value=Object.freeze(c.value);return c};return ha(i)?i.then((c)=>o(c)):o(i)}unwrap(){return this._def.innerType}}Zp.create=(n,i)=>{return new Zp({innerType:n,typeName:g.ZodReadonly,...fn(i)})};function cR(n,i={},o){if(n)return Dc.create().superRefine((c,p)=>{var a,x;if(!n(c)){let m=typeof i==="function"?i(c):typeof i==="string"?{message:i}:i,l=(x=(a=m.fatal)!==null&&a!==void 0?a:o)!==null&&x!==void 0?x:!0,f=typeof m==="string"?{message:m}:m;p.addIssue({code:"custom",...f,fatal:l})}});return Dc.create()}var k5={object:In.lazycreate},g;(function(n){n.ZodString="ZodString",n.ZodNumber="ZodNumber",n.ZodNaN="ZodNaN",n.ZodBigInt="ZodBigInt",n.ZodBoolean="ZodBoolean",n.ZodDate="ZodDate",n.ZodSymbol="ZodSymbol",n.ZodUndefined="ZodUndefined",n.ZodNull="ZodNull",n.ZodAny="ZodAny",n.ZodUnknown="ZodUnknown",n.ZodNever="ZodNever",n.ZodVoid="ZodVoid",n.ZodArray="ZodArray",n.ZodObject="ZodObject",n.ZodUnion="ZodUnion",n.ZodDiscriminatedUnion="ZodDiscriminatedUnion",n.ZodIntersection="ZodIntersection",n.ZodTuple="ZodTuple",n.ZodRecord="ZodRecord",n.ZodMap="ZodMap",n.ZodSet="ZodSet",n.ZodFunction="ZodFunction",n.ZodLazy="ZodLazy",n.ZodLiteral="ZodLiteral",n.ZodEnum="ZodEnum",n.ZodEffects="ZodEffects",n.ZodNativeEnum="ZodNativeEnum",n.ZodOptional="ZodOptional",n.ZodNullable="ZodNullable",n.ZodDefault="ZodDefault",n.ZodCatch="ZodCatch",n.ZodPromise="ZodPromise",n.ZodBranded="ZodBranded",n.ZodPipeline="ZodPipeline",n.ZodReadonly="ZodReadonly"})(g||(g={}));var s5=(n,i={message:`Input not instance of ${n.name}`})=>cR((o)=>o instanceof n,i),pR=Mo.create,aR=Jc.create,Z5=ta.create,t5=Sc.create,xR=yp.create,q5=Nc.create,P5=Ia.create,r5=Bp.create,g5=Lp.create,d5=Dc.create,e5=wc.create,n9=Uo.create,i9=ka.create,o9=Ro.create,Pa=In.create,c9=In.strictCreate,p9=Np.create,a9=Bm.create,x9=Dp.create,m9=Vo.create,l9=sa.create,f9=Za.create,v9=Cc.create,$9=bp.create,T9=Cp.create,w9=hp.create,J9=Ac.create,S9=Ip.create,A9=hc.create,rM=co.create,F9=Wo.create,M9=ho.create,R9=co.createWithPreprocess,W9=qa.create,K9=()=>pR().optional(),X9=()=>aR().optional(),G9=()=>xR().optional(),Y9={string:(n)=>Mo.create({...n,coerce:!0}),number:(n)=>Jc.create({...n,coerce:!0}),boolean:(n)=>yp.create({...n,coerce:!0}),bigint:(n)=>Sc.create({...n,coerce:!0}),date:(n)=>Nc.create({...n,coerce:!0})},z9=e,Gn=Object.freeze({__proto__:null,defaultErrorMap:jp,setErrorMap:Q5,getErrorMap:bm,makeIssue:jm,EMPTY_PATH:H5,addIssueToContext:B,ParseStatus:Xi,INVALID:e,DIRTY:_p,OK:Ei,isAborted:Ev,isDirty:Ov,isValid:Ca,isAsync:ha,get util(){return Wn},get objectUtil(){return Hv},ZodParsedType:N,getParsedType:Tc,ZodType:vn,datetimeRegex:iR,ZodString:Mo,ZodNumber:Jc,ZodBigInt:Sc,ZodBoolean:yp,ZodDate:Nc,ZodSymbol:Ia,ZodUndefined:Bp,ZodNull:Lp,ZodAny:Dc,ZodUnknown:wc,ZodNever:Uo,ZodVoid:ka,ZodArray:Ro,ZodObject:In,ZodUnion:Np,ZodDiscriminatedUnion:Bm,ZodIntersection:Dp,ZodTuple:Vo,ZodRecord:sa,ZodMap:Za,ZodSet:Cc,ZodFunction:bp,ZodLazy:Cp,ZodLiteral:hp,ZodEnum:Ac,ZodNativeEnum:Ip,ZodPromise:hc,ZodEffects:co,ZodTransformer:co,ZodOptional:Wo,ZodNullable:ho,ZodDefault:kp,ZodCatch:sp,ZodNaN:ta,BRAND:I5,ZodBranded:Lm,ZodPipeline:qa,ZodReadonly:Zp,custom:cR,Schema:vn,ZodSchema:vn,late:k5,get ZodFirstPartyTypeKind(){return g},coerce:Y9,any:d5,array:o9,bigint:t5,boolean:xR,date:q5,discriminatedUnion:a9,effect:rM,enum:J9,function:$9,instanceof:s5,intersection:x9,lazy:T9,literal:w9,map:f9,nan:Z5,nativeEnum:S9,never:n9,null:g5,nullable:M9,number:aR,object:Pa,oboolean:G9,onumber:X9,optional:F9,ostring:K9,pipeline:W9,preprocess:R9,promise:A9,record:l9,set:v9,strictObject:c9,string:pR,symbol:P5,transformer:rM,tuple:m9,undefined:r5,union:p9,unknown:e5,void:i9,NEVER:z9,ZodIssueCode:O,quotelessJson:z5,ZodError:Ii});function mR(n){let i=n.runtimeEnvStrict??n.runtimeEnv??process.env;if(n.emptyStringAsUndefined??!1){for(let[K,E]of Object.entries(i))if(E==="")delete i[K]}if(!!n.skipValidation)return i;let p=typeof n.client==="object"?n.client:{},a=typeof n.server==="object"?n.server:{},x=typeof n.shared==="object"?n.shared:{},m=Pa(p),l=Pa(a),f=Pa(x),v=n.isServer??(typeof window==="undefined"||("Deno"in window)),$=m.merge(f),T=l.merge(f).merge(m),F=v?T.safeParse(i):$.safeParse(i),M=n.onValidationError??((K)=>{throw console.error("\u274C Invalid environment variables:",K.flatten().fieldErrors),new Error("Invalid environment variables")}),A=n.onInvalidAccess??((K)=>{throw new Error("\u274C Attempted to access a server-side environment variable on the client")});if(F.success===!1)return M(F.error);let R=(K)=>{if(!n.clientPrefix)return!0;return!K.startsWith(n.clientPrefix)&&!(K in f.shape)},G=(K)=>{return v||!R(K)},Q=(K)=>{return K==="__esModule"||K==="$$typeof"},b=(n.extends??[]).reduce((K,E)=>{return Object.assign(K,E)},{}),D=Object.assign(F.data,b);return new Proxy(D,{get(K,E){if(typeof E!=="string")return;if(Q(E))return;if(!G(E))return A(E);return Reflect.get(K,E)}})}var Q9="__vite_start_time"in globalThis,H9=typeof window!=="undefined",mN="vitest"in globalThis,rn=mR({isServer:!Q9&&!H9,server:{CI:Gn.string().transform((n)=>!0).optional(),POSTGRES_USER:Gn.string(),POSTGRES_PASSWORD:Gn.string(),POSTGRES_DATABASE:Gn.string(),POSTGRES_HOST:Gn.string(),POSTGRES_PORT:Gn.string().transform((n)=>Number.parseInt(n,10)),BACKEND_PORT:Gn.string().transform((n)=>Number.parseInt(n,10)),RUN_WORKERS_FROM_SOURCE:Gn.union([Gn.literal("true"),Gn.literal("false")]).optional().transform((n)=>n==="true"),FRONTEND_PORT:Gn.string().transform((n)=>Number.parseInt(n,10)),FRONTEND_ORIGINS:Gn.string().transform((n)=>JSON.parse(n)).pipe(Gn.array(Gn.string())),OPENAI_API_KEY:Gn.string().optional()},clientPrefix:"VITE_",client:{VITE_BACKEND_ORIGIN:Gn.string(),VITE_USE_SELF_SIGNED_CERTIFICATE:Gn.union([Gn.literal("true"),Gn.literal("false")]).optional().transform((n)=>n==="true")},runtimeEnv:import.meta.env,emptyStringAsUndefined:!0});var fR=Vv(import.meta.dirname,"../dev"),uv=rn.VITE_USE_SELF_SIGNED_CERTIFICATE?{cert:lR(Vv(fR,"./cert.pem"),"utf-8"),key:lR(Vv(fR,"./key.pem"),"utf-8")}:void 0;var Fc=new Vl,Jn=rn.VITE_USE_SELF_SIGNED_CERTIFICATE?console:Fc.logger;nn.STORE.loggers[0]=new Wc("warn",void 0,Jn);import{spawn as E9}from"child_process";import{resolve as O9}from"path";function _v(n,i,o=n.logger){let c=rn.RUN_WORKERS_FROM_SOURCE?"ts":"js",p=i.endsWith(".bun")?"bun":"node",x=[O9(import.meta.dir,`${i}.${c}`)];if(p==="node"&&c==="ts")x.push("--experimental-strip-types");let m=E9(p,x);return new Ja(m,i,o)}var vR=vl($f(),1);var U9=604800000,Nm=(()=>{let{__userSessionMap:n}=globalThis;if(!n){n=globalThis.__userSessionMap=new Map;let i=new vR.CronJob("00 00 03 * * *",()=>{for(let[o,c]of n.entries()){let p=Date.now();for(let[a,x]of c.entries())if(p-x>U9)c.delete(a);if(c.size===0)n.delete(o)}});i.start(),process.on("exit",()=>{i.stop(),Jn.info("\uD83D\uDEEC autoExpiry stopped")})}return n})();import XG from"path";import nG from"os";import iG from"fs";var Dm=new Map,bv=new Map,jv=Symbol("OriginError"),tp={};class po extends Promise{constructor(n,i,o,c,p={}){let a,x;super((m,l)=>{a=m,x=l});this.tagged=Array.isArray(n.raw),this.strings=n,this.args=i,this.handler=o,this.canceller=c,this.options=p,this.state=null,this.statement=null,this.resolve=(m)=>(this.active=!1,a(m)),this.reject=(m)=>(this.active=!1,x(m)),this.active=!1,this.cancelled=null,this.executed=!1,this.signature="",this[jv]=this.handler.debug?new Error:this.tagged&&V9(this.strings)}get origin(){return(this.handler.debug?this[jv].stack:this.tagged&&bv.has(this.strings)?bv.get(this.strings):bv.set(this.strings,this[jv].stack).get(this.strings))||""}static get[Symbol.species](){return Promise}cancel(){return this.canceller&&(this.canceller(this),this.canceller=null)}simple(){return this.options.simple=!0,this.options.prepare=!1,this}async readable(){return this.simple(),this.streaming=!0,this}async writable(){return this.simple(),this.streaming=!0,this}cursor(n=1,i){if(this.options.simple=!1,typeof n==="function")i=n,n=1;if(this.cursorRows=n,typeof i==="function")return this.cursorFn=i,this;let o;return{[Symbol.asyncIterator]:()=>({next:()=>{if(this.executed&&!this.active)return{done:!0};o&&o();let c=new Promise((p,a)=>{this.cursorFn=(x)=>{return p({value:x,done:!1}),new Promise((m)=>o=m)},this.resolve=()=>(this.active=!1,p({done:!0})),this.reject=(x)=>(this.active=!1,a(x))});return this.execute(),c},return(){return o&&o(tp),{done:!0}}})}}describe(){return this.options.simple=!1,this.onlyDescribe=this.options.prepare=!0,this}stream(){throw new Error(".stream has been renamed to .forEach")}forEach(n){return this.forEachFn=n,this.handle(),this}raw(){return this.isRaw=!0,this}values(){return this.isRaw="values",this}async handle(){!this.executed&&(this.executed=!0)&&await 1&&this.handler(this)}execute(){return this.handle(),this}then(){return this.handle(),super.then.apply(this,arguments)}catch(){return this.handle(),super.catch.apply(this,arguments)}finally(){return this.handle(),super.finally.apply(this,arguments)}}function V9(n){if(Dm.has(n))return Dm.get(n);let i=Error.stackTraceLimit;return Error.stackTraceLimit=4,Dm.set(n,new Error),Error.stackTraceLimit=i,Dm.get(n)}class qp extends Error{constructor(n){super(n.message);this.name=this.constructor.name,Object.assign(this,n)}}var en={connection:$R,postgres:TR,generic:wR,notSupported:JR};function $R(n,i,o){let{host:c,port:p}=o||i,a=Object.assign(new Error("write "+n+" "+(i.path||c+":"+p)),{code:n,errno:n,address:i.path||c},i.path?{}:{port:p});return Error.captureStackTrace(a,$R),a}function TR(n){let i=new qp(n);return Error.captureStackTrace(i,TR),i}function wR(n,i){let o=Object.assign(new Error(n+": "+i),{code:n});return Error.captureStackTrace(o,wR),o}function JR(n){let i=Object.assign(new Error(n+" (B) is not supported"),{code:"MESSAGE_NOT_SUPPORTED",name:n});return Error.captureStackTrace(i,JR),i}var u9={string:{to:25,from:null,serialize:(n)=>""+n},number:{to:0,from:[21,23,26,700,701],serialize:(n)=>""+n,parse:(n)=>+n},json:{to:114,from:[114,3802],serialize:(n)=>JSON.stringify(n),parse:(n)=>JSON.parse(n)},boolean:{to:16,from:16,serialize:(n)=>n===!0?"t":"f",parse:(n)=>n==="t"},date:{to:1184,from:[1082,1114,1184],serialize:(n)=>(n instanceof Date?n:new Date(n)).toISOString(),parse:(n)=>new Date(n)},bytea:{to:17,from:17,serialize:(n)=>"\\x"+Buffer.from(n).toString("hex"),parse:(n)=>Buffer.from(n.slice(2),"hex")}};class Im{then(){yv()}catch(){yv()}finally(){yv()}}class ea extends Im{constructor(n){super();this.value=Zm(n)}}class uo extends Im{constructor(n,i,o){super();this.value=n,this.type=i,this.array=o}}class km extends Im{constructor(n,i){super();this.first=n,this.rest=i}build(n,i,o,c){let p=_9.map(([a,x])=>({fn:x,i:n.search(a)})).sort((a,x)=>a.i-x.i).pop();return p.i===-1?Cv(this.first,c):p.fn(this.first,this.rest,i,o,c)}}function sm(n,i,o,c){let p=n instanceof uo?n.value:n;if(p===void 0){if(n instanceof uo?n.value=c.transform.undefined:p=n=c.transform.undefined,p===void 0)throw en.generic("UNDEFINED_VALUE","Undefined values are not allowed")}return"$"+o.push(n instanceof uo?(i.push(n.value),n.array?n.array[n.type||hm(n.value)]||n.type||MR(n.value):n.type):(i.push(n),hm(n)))}var AR=WR(u9);function Nv(n,i,o,c,p,a){for(let x=1;x<n.strings.length;x++)i+=Dv(i,o,c,p,a)+n.strings[x],o=n.args[x];return i}function Dv(n,i,o,c,p){return i instanceof km?i.build(n,o,c,p):i instanceof po?Lv(i,o,c,p):i instanceof ea?i.value:i&&i[0]instanceof po?i.reduce((a,x)=>a+" "+Lv(x,o,c,p),""):sm(i,o,c,p)}function Lv(n,i,o,c){return n.fragment=!0,Nv(n,n.strings[0],n.args[0],i,o,c)}function FR(n,i,o,c,p){return n.map((a)=>"("+c.map((x)=>Dv("values",a[x],i,o,p)).join(",")+")").join(",")}function SR(n,i,o,c,p){let a=Array.isArray(n[0]),x=i.length?i.flat():Object.keys(a?n[0]:n);return FR(a?n:[n],o,c,x,p)}function Cm(n,i,o,c,p){if(typeof n==="string"&&(n=[n].concat(i)),Array.isArray(n))return Cv(n,p);let a;return(i.length?i.flat():Object.keys(n)).map((m)=>{return a=n[m],(a instanceof po?Lv(a,o,c,p):a instanceof ea?a.value:sm(a,o,c,p))+" as "+Zm(p.transform.column.to?p.transform.column.to(m):m)}).join(",")}var _9=Object.entries({values:SR,in:(...n)=>{let i=SR(...n);return i==="()"?"(null)":i},select:Cm,as:Cm,returning:Cm,"\\(":Cm,update(n,i,o,c,p){return(i.length?i.flat():Object.keys(n)).map((a)=>Zm(p.transform.column.to?p.transform.column.to(a):a)+"="+Dv("values",n[a],o,c,p))},insert(n,i,o,c,p){let a=i.length?i.flat():Object.keys(Array.isArray(n)?n[0]:n);return"("+Cv(a,p)+")values"+FR(Array.isArray(n)?n:[n],o,c,a,p)}}).map(([n,i])=>[new RegExp("((?:^|[\\s(])"+n+"(?:$|[\\s(]))(?![\\s\\S]*\\1)","i"),i]);function yv(){throw en.generic("NOT_TAGGED_CALL","Query not called as a tagged template literal")}var{serializers:b9,parsers:j9}=AR;function MR(n){if(Array.isArray(n))return MR(n[0]);return typeof n==="string"?1009:0}var RR=function(n){let i=WR(n||{});return{serializers:Object.assign({},b9,i.serializers),parsers:Object.assign({},j9,i.parsers)}};function WR(n){return Object.keys(n).reduce((i,o)=>{if(n[o].from&&[].concat(n[o].from).forEach((c)=>i.parsers[c]=n[o].parse),n[o].serialize)i.serializers[n[o].to]=n[o].serialize,n[o].from&&[].concat(n[o].from).forEach((c)=>i.serializers[c]=n[o].serialize);return i},{parsers:{},serializers:{}})}function Cv(n,{transform:{column:i}}){return n.map((o)=>Zm(i.to?i.to(o):o)).join(",")}var Zm=function n(i){return'"'+i.replace(/"/g,'""').replace(/\./g,'"."')+'"'},hm=function n(i){return i instanceof uo?i.type:i instanceof Date?1184:i instanceof Uint8Array?17:i===!0||i===!1?16:typeof i==="bigint"?20:Array.isArray(i)?n(i[0]):0},y9=/\\/g,B9=/"/g;function L9(n){return n.replace(y9,"\\\\").replace(B9,'\\"')}var KR=function n(i,o,c,p){if(Array.isArray(i)===!1)return i;if(!i.length)return"{}";let a=i[0],x=p===1020?";":",";if(Array.isArray(a)&&!a.type)return"{"+i.map((m)=>n(m,o,c,p)).join(x)+"}";return"{"+i.map((m)=>{if(m===void 0){if(m=c.transform.undefined,m===void 0)throw en.generic("UNDEFINED_VALUE","Undefined values are not allowed")}return m===null?"null":'"'+L9(o?o(m.type?m.value:m):""+m)+'"'}).join(x)+"}"},Bv={i:0,char:null,str:"",quoted:!1,last:0},XR=function n(i,o,c){return Bv.i=Bv.last=0,GR(Bv,i,o,c)};function GR(n,i,o,c){let p=[],a=c===1020?";":",";for(;n.i<i.length;n.i++){if(n.char=i[n.i],n.quoted)if(n.char==="\\")n.str+=i[++n.i];else if(n.char==='"')p.push(o?o(n.str):n.str),n.str="",n.quoted=i[n.i+1]==='"',n.last=n.i+2;else n.str+=n.char;else if(n.char==='"')n.quoted=!0;else if(n.char==="{")n.last=++n.i,p.push(GR(n,i,o,c));else if(n.char==="}"){n.quoted=!1,n.last<n.i&&p.push(o?o(i.slice(n.last,n.i)):i.slice(n.last,n.i)),n.last=n.i+1;break}else if(n.char===a&&n.p!=="}"&&n.p!=='"')p.push(o?o(i.slice(n.last,n.i)):i.slice(n.last,n.i)),n.last=n.i+1;n.p=n.char}return n.last<n.i&&p.push(o?o(i.slice(n.last,n.i+1)):i.slice(n.last,n.i+1)),p}var Ic=(n)=>{let i=n[0];for(let o=1;o<n.length;o++)i+=n[o]==="_"?n[++o].toUpperCase():n[o];return i},kc=(n)=>{let i=n[0].toUpperCase();for(let o=1;o<n.length;o++)i+=n[o]==="_"?n[++o].toUpperCase():n[o];return i},sc=(n)=>n.replace(/_/g,"-"),ra=(n)=>n.replace(/([A-Z])/g,"_$1").toLowerCase(),ga=(n)=>(n.slice(0,1)+n.slice(1).replace(/([A-Z])/g,"_$1")).toLowerCase(),da=(n)=>n.replace(/-/g,"_");function hv(n){return function i(o,c){return typeof o==="object"&&o!==null&&(c.type===114||c.type===3802)?Array.isArray(o)?o.map((p)=>i(p,c)):Object.entries(o).reduce((p,[a,x])=>Object.assign(p,{[n(a)]:i(x,c)}),{}):o}}Ic.column={from:Ic};Ic.value={from:hv(Ic)};ra.column={to:ra};var Iv={...Ic};Iv.column.to=ra;kc.column={from:kc};kc.value={from:hv(kc)};ga.column={to:ga};var kv={...kc};kv.column.to=ga;sc.column={from:sc};sc.value={from:hv(sc)};da.column={to:da};var sv={...sc};sv.column.to=da;import YR from"net";import h9 from"tls";import nx from"crypto";import Zv from"stream";import{performance as zR}from"perf_hooks";class Zc extends Array{constructor(){super();Object.defineProperties(this,{count:{value:null,writable:!0},state:{value:null,writable:!0},command:{value:null,writable:!0},columns:{value:null,writable:!0},statement:{value:null,writable:!0}})}static get[Symbol.species](){return Array}}var ki=N9;function N9(n=[]){let i=n.slice(),o=0;return{get length(){return i.length-o},remove:(c)=>{let p=i.indexOf(c);return p===-1?null:(i.splice(p,1),c)},push:(c)=>(i.push(c),c),shift:()=>{let c=i[o++];if(o===i.length)o=0,i=[];else i[o-1]=void 0;return c}}}var Gi=Buffer.allocUnsafe(256),D9="BCcDdEFfHPpQSX".split("").reduce((n,i)=>{let o=i.charCodeAt(0);return n[i]=()=>{return Gi[0]=o,On.i=5,On},n},{}),On=Object.assign(C9,D9,{N:String.fromCharCode(0),i:0,inc(n){return On.i+=n,On},str(n){let i=Buffer.byteLength(n);return tm(i),On.i+=Gi.write(n,On.i,i,"utf8"),On},i16(n){return tm(2),Gi.writeUInt16BE(n,On.i),On.i+=2,On},i32(n,i){if(i||i===0)return Gi.writeUInt32BE(n,i),On;return tm(4),Gi.writeUInt32BE(n,On.i),On.i+=4,On},z(n){return tm(n),Gi.fill(0,On.i,On.i+n),On.i+=n,On},raw(n){return Gi=Buffer.concat([Gi.subarray(0,On.i),n]),On.i=Gi.length,On},end(n=1){Gi.writeUInt32BE(On.i-n,n);let i=Gi.subarray(0,On.i);return On.i=0,Gi=Buffer.allocUnsafe(256),i}}),q=On;function tm(n){if(Gi.length-On.i<n){let i=Gi,o=i.length;Gi=Buffer.allocUnsafe(o+(o>>1)+n),i.copy(Gi)}}function C9(){return On.i=0,On}var Pv=ER,I9=1,Mc=q().S().end(),QR=q().H().end(),k9=q().i32(8).i32(80877103).end(8),s9=Buffer.concat([q().E().str(q.N).i32(0).end(),Mc]),Z9=q().D().str("S").str(q.N).end(),Pp=()=>{},t9=new Set(["FetchPreparedStatement","RevalidateCachedQuery","transformAssignedExpr"]),q9={83:"severity_local",86:"severity",67:"code",77:"message",68:"detail",72:"hint",80:"position",112:"internal_position",113:"internal_query",87:"where",115:"schema_name",116:"table_name",99:"column_name",100:"data type_name",110:"constraint_name",70:"file",76:"line",82:"routine"};function ER(n,i={},{onopen:o=Pp,onend:c=Pp,onclose:p=Pp}={}){let{ssl:a,max:x,user:m,host:l,port:f,database:v,parsers:$,transform:T,onnotice:F,onnotify:M,onparameter:A,max_pipeline:R,keep_alive:G,backoff:Q,target_session_attrs:b}=n,D=ki(),Y=I9++,K={pid:null,secret:null},E=qv(ml,n.idle_timeout),y=qv(ml,n.max_lifetime),V=qv(l4,n.connect_timeout),X=null,Z,C=new Zc,on=Buffer.alloc(0),mn=n.fetch_types,ln={},Vn={},ji=Math.random().toString(36).slice(2),H=1,s=0,wn=0,Yn=0,ni=0,Tn=0,un=0,gn=0,Dn=null,jn=null,$i=!1,_n=null,ao=null,Ti=null,Io=null,ii=null,yn=null,xo=null,Go=null,_=null,na=null,wi={queue:i.closed,idleTimer:E,connect(w){Ti=w||!0,X$()},terminate:oa,execute:ia,cancel:p4,end:ml,count:0,id:Y};return i.closed&&i.closed.push(wi),wi;async function c4(){let w;try{w=n.socket?await Promise.resolve(n.socket(n)):new YR.Socket}catch(W){rc(W);return}return w.on("error",rc),w.on("close",G$),w.on("drain",W$),w}async function p4({pid:w,secret:W},P,Kn){try{Z=q().i32(16).i32(80877102).i32(w).i32(W).end(16),await K$(),X.once("error",Kn),X.once("close",P)}catch(kn){Kn(kn)}}function ia(w){if($i)return xx(w,en.connection("CONNECTION_DESTROYED",n));if(w.cancelled)return;try{return w.state=K,_?D.push(w):(_=w,_.active=!0),m4(w),mi(a4(w))&&!w.describeFirst&&!w.cursorFn&&D.length<R&&(!w.options.onexecute||w.options.onexecute(wi))}catch(W){return D.length===0&&mi(Mc),Yo(W),!0}}function a4(w){if(w.parameters.length>=65534)throw en.generic("MAX_PARAMETERS_EXCEEDED","Max number of parameters (65534) exceeded");return w.options.simple?q().Q().str(w.statement.string+q.N).end():w.describeFirst?Buffer.concat([F$(w),QR]):w.prepare?w.prepared?ax(w):Buffer.concat([F$(w),ax(w)]):x4(w)}function F$(w){return Buffer.concat([z$(w.statement.string,w.parameters,w.statement.types,w.statement.name),Z4("S",w.statement.name)])}function ax(w){return Buffer.concat([s4(w.parameters,w.statement.types,w.statement.name,w.cursorName),w.cursorFn?Q$("",w.cursorRows):s9])}function x4(w){return Buffer.concat([z$(w.statement.string,w.parameters,w.statement.types),Z9,ax(w)])}function m4(w){let W=[],P=[],Kn=Nv(w,w.strings[0],w.args[0],W,P,n);!w.tagged&&w.args.forEach((kn)=>sm(kn,W,P,n)),w.prepare=n.prepare&&("prepare"in w.options?w.options.prepare:!0),w.string=Kn,w.signature=w.prepare&&P+Kn,w.onlyDescribe&&delete Vn[w.signature],w.parameters=w.parameters||W,w.prepared=w.prepare&&w.signature in Vn,w.describeFirst=w.onlyDescribe||W.length&&!w.prepared,w.statement=w.prepared?Vn[w.signature]:{string:Kn,types:P,name:w.prepare?ji+H++:""},typeof n.debug==="function"&&n.debug(Y,Kn,W,P)}function mi(w,W){if(yn=yn?Buffer.concat([yn,w]):Buffer.from(w),W||yn.length>=1024)return M$(W);return jn===null&&(jn=setImmediate(M$)),!0}function M$(w){let W=X.write(yn,w);return jn!==null&&clearImmediate(jn),yn=jn=null,W}function l4(){Yo(en.connection("CONNECT_TIMEOUT",n,X)),X.destroy()}async function R$(){if(mi(k9),!await new Promise((W)=>X.once("data",(P)=>W(P[0]===83)))&&a==="prefer")return Pc();X.removeAllListeners(),X=h9.connect({socket:X,servername:YR.isIP(X.host)?void 0:X.host,...a==="require"||a==="allow"||a==="prefer"?{rejectUnauthorized:!1}:a==="verify-full"?{}:typeof a==="object"?a:{}}),X.on("secureConnect",Pc),X.on("error",rc),X.on("close",G$),X.on("drain",W$)}function W$(){!_&&o(wi)}function xl(w){if(_n){if(_n.push(w),wn-=w.length,wn>=0)return}on=_n?Buffer.concat(_n,Tn-wn):on.length===0?w:Buffer.concat([on,w],on.length+w.length);while(on.length>4){if(Tn=on.readUInt32BE(1),Tn>=on.length){wn=Tn-on.length,_n=[on];break}try{f4(on.subarray(0,Tn+1))}catch(W){_&&(_.cursorFn||_.describeFirst)&&mi(Mc),Yo(W)}on=on.subarray(Tn+1),wn=0,_n=null}}async function K$(){if($i=!1,ln={},X||(X=await c4()),!X)return;if(V.start(),n.socket)return a?R$():Pc();if(X.on("connect",a?R$:Pc),n.path)return X.connect(n.path);X.ssl=a,X.connect(f[Yn],l[Yn]),X.host=l[Yn],X.port=f[Yn],Yn=(Yn+1)%f.length}function X$(){setTimeout(K$,s?s+un-zR.now():0)}function Pc(){try{Vn={},mn=n.fetch_types,ji=Math.random().toString(36).slice(2),H=1,y.start(),X.on("data",xl),G&&X.setKeepAlive&&X.setKeepAlive(!0,1000*G);let w=q4();mi(w)}catch(w){rc(w)}}function rc(w){if(wi.queue===i.connecting&&n.host[ni+1])return;Yo(w);while(D.length)xx(D.shift(),w)}function Yo(w){ii&&(ii.destroy(w),ii=null),_&&xx(_,w),Ti&&(xx(Ti,w),Ti=null)}function xx(w,W){"query"in W||"parameters"in W||Object.defineProperties(W,{stack:{value:W.stack+w.origin.replace(/.*\n/,"\n"),enumerable:n.debug},query:{value:w.string,enumerable:n.debug},parameters:{value:w.parameters,enumerable:n.debug},args:{value:w.args,enumerable:n.debug},types:{value:w.statement&&w.statement.types,enumerable:n.debug}}),w.reject(W)}function ml(){return Io||(!wi.reserved&&c(wi),!wi.reserved&&!Ti&&!_&&D.length===0?(oa(),new Promise((w)=>X&&X.readyState!=="closed"?X.once("close",w):w())):Io=new Promise((w)=>xo=w))}function oa(){if($i=!0,ii||_||Ti||D.length)rc(en.connection("CONNECTION_DESTROYED",n));if(clearImmediate(jn),X)X.removeListener("data",xl),X.removeListener("connect",Pc),X.readyState==="open"&&X.end(q().X().end());xo&&(xo(),Io=xo=null)}async function G$(w){if(on=Buffer.alloc(0),wn=0,_n=null,clearImmediate(jn),X.removeListener("data",xl),X.removeListener("connect",Pc),E.cancel(),y.cancel(),V.cancel(),X.removeAllListeners(),X=null,Ti)return X$();!w&&(_||D.length)&&rc(en.connection("CONNECTION_CLOSED",n,X)),s=zR.now(),w&&n.shared.retries++,un=(typeof Q==="function"?Q(n.shared.retries):Q)*1000,p(wi,en.connection("CONNECTION_CLOSED",n,X))}function f4(w,W=w[0]){(W===68?v4:W===100?B4:W===65?V4:W===83?$4:W===90?T4:W===67?w4:W===50?Y$:W===49?J4:W===116?S4:W===84?A4:W===82?F4:W===110?G4:W===75?Y4:W===69?O4:W===115?u4:W===51?_4:W===71?b4:W===78?N4:W===72?j4:W===99?L4:W===73?D4:W===86?C4:W===118?h4:W===87?y4:I4)(w)}function v4(w){let W=7,P,Kn,kn,Ji=_.isRaw?new Array(_.statement.columns.length):{};for(let Yi=0;Yi<_.statement.columns.length;Yi++)Kn=_.statement.columns[Yi],P=w.readInt32BE(W),W+=4,kn=P===-1?null:_.isRaw===!0?w.subarray(W,W+=P):Kn.parser===void 0?w.toString("utf8",W,W+=P):Kn.parser.array===!0?Kn.parser(w.toString("utf8",W+1,W+=P)):Kn.parser(w.toString("utf8",W,W+=P)),_.isRaw?Ji[Yi]=_.isRaw===!0?kn:T.value.from?T.value.from(kn,Kn):kn:Ji[Kn.name]=T.value.from?T.value.from(kn,Kn):kn;_.forEachFn?_.forEachFn(T.row.from?T.row.from(Ji):Ji,C):C[gn++]=T.row.from?T.row.from(Ji):Ji}function $4(w){let[W,P]=w.toString("utf8",5,w.length-1).split(q.N);if(ln[W]=P,n.parameters[W]!==P)n.parameters[W]=P,A&&A(W,P)}function T4(w){if(_&&_.options.simple&&_.resolve(ao||C),_=ao=null,C=new Zc,V.cancel(),Ti){if(b){if(!ln.in_hot_standby||!ln.default_transaction_read_only)return E4();else if(H4(b,ln))return oa()}if(mn)return Ti===!0&&(Ti=null),z4();Ti!==!0&&ia(Ti),n.shared.retries=ni=0,Ti=null;return}while(D.length&&(_=D.shift())&&(_.active=!0,_.cancelled))ER(n).cancel(_.state,_.cancelled.resolve,_.cancelled.reject);if(_)return;wi.reserved?!wi.reserved.release&&w[5]===73?Io?oa():(wi.reserved=null,o(wi)):wi.reserved():Io?oa():o(wi)}function w4(w){gn=0;for(let W=w.length-1;W>0;W--){if(w[W]===32&&w[W+1]<58&&C.count===null)C.count=+w.toString("utf8",W+1,w.length-1);if(w[W-1]>=65){C.command=w.toString("utf8",5,W),C.state=K;break}}if(na&&(na(),na=null),C.command==="BEGIN"&&x!==1&&!wi.reserved)return Yo(en.generic("UNSAFE_TRANSACTION","Only use sql.begin, sql.reserved or max: 1"));if(_.options.simple)return Y$();if(_.cursorFn)C.count&&_.cursorFn(C),mi(Mc);_.resolve(C)}function J4(){_.parsing=!1}function Y$(){!C.statement&&(C.statement=_.statement),C.columns=_.statement.columns}function S4(w){let W=w.readUInt16BE(5);for(let P=0;P<W;++P)!_.statement.types[P]&&(_.statement.types[P]=w.readUInt32BE(7+P*4));_.prepare&&(Vn[_.signature]=_.statement),_.describeFirst&&!_.onlyDescribe&&(mi(ax(_)),_.describeFirst=!1)}function A4(w){if(C.command)ao=ao||[C],ao.push(C=new Zc),C.count=null,_.statement.columns=null;let W=w.readUInt16BE(5),P=7,Kn;_.statement.columns=Array(W);for(let kn=0;kn<W;++kn){Kn=P;while(w[P++]!==0);let Ji=w.readUInt32BE(P),Yi=w.readUInt16BE(P+4),ko=w.readUInt32BE(P+6);_.statement.columns[kn]={name:T.column.from?T.column.from(w.toString("utf8",Kn,P-1)):w.toString("utf8",Kn,P-1),parser:$[ko],table:Ji,number:Yi,type:ko},P+=18}if(C.statement=_.statement,_.onlyDescribe)return _.resolve(_.statement),mi(Mc)}async function F4(w,W=w.readUInt32BE(5)){(W===3?M4:W===5?R4:W===10?W4:W===11?K4:W===12?X4:W!==0?k4:Pp)(w,W)}async function M4(){let w=await ll();mi(q().p().str(w).z(1).end())}async function R4(w){let W="md5"+await HR(Buffer.concat([Buffer.from(await HR(await ll()+m)),w.subarray(9)]));mi(q().p().str(W).z(1).end())}async function W4(){Go=(await nx.randomBytes(18)).toString("base64"),q().p().str("SCRAM-SHA-256"+q.N);let w=q.i;mi(q.inc(4).str("n,,n=*,r="+Go).i32(q.i-w-4,w).end())}async function K4(w){let W=w.toString("utf8",9).split(",").reduce((Yi,ko)=>(Yi[ko[0]]=ko.slice(2),Yi),{}),P=await nx.pbkdf2Sync(await ll(),Buffer.from(W.s,"base64"),parseInt(W.i),32,"sha256"),Kn=await qm(P,"Client Key"),kn="n=*,r="+Go+",r="+W.r+",s="+W.s+",i="+W.i+",c=biws,r="+W.r;Dn=(await qm(await qm(P,"Server Key"),kn)).toString("base64");let Ji="c=biws,r="+W.r+",p="+r9(Kn,Buffer.from(await qm(await P9(Kn),kn))).toString("base64");mi(q().p().str(Ji).end())}function X4(w){if(w.toString("utf8",9).split(q.N,1)[0].slice(2)===Dn)return;Yo(en.generic("SASL_SIGNATURE_MISMATCH","The server did not return the correct signature")),X.destroy()}function ll(){return Promise.resolve(typeof n.pass==="function"?n.pass():n.pass)}function G4(){if(C.statement=_.statement,C.statement.columns=[],_.onlyDescribe)return _.resolve(_.statement),mi(Mc)}function Y4(w){K.pid=w.readUInt32BE(5),K.secret=w.readUInt32BE(9)}async function z4(){mn=!1,(await new po([`
|
|
37
|
+
*/cv.exports=u3;cv.exports.append=oF;var V3=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;function oF(n,i){if(typeof n!=="string")throw new TypeError("header argument is required");if(!i)throw new TypeError("field argument is required");var o=!Array.isArray(i)?iF(String(i)):i;for(var c=0;c<o.length;c++)if(!V3.test(o[c]))throw new TypeError("field argument contains an invalid header name");if(n==="*")return n;var p=n,a=iF(n.toLowerCase());if(o.indexOf("*")!==-1||a.indexOf("*")!==-1)return"*";for(var x=0;x<o.length;x++){var m=o[x].toLowerCase();if(a.indexOf(m)===-1)a.push(m),p=p?p+", "+o[x]:o[x]}return p}function iF(n){var i=0,o=[],c=0;for(var p=0,a=n.length;p<a;p++)switch(n.charCodeAt(p)){case 32:if(c===i)c=i=p+1;break;case 44:o.push(n.substring(c,i)),c=i=p+1;break;default:i=p+1;break}return o.push(n.substring(c,i)),o}function u3(n,i){if(!n||!n.getHeader||!n.setHeader)throw new TypeError("res argument is required");var o=n.getHeader("Vary")||"",c=Array.isArray(o)?o.join(", "):String(o);if(o=oF(c,i))n.setHeader("Vary",o)}});var pv=h((KL,pF)=>{(function(){var n=nF(),i=cF(),o={origin:"*",methods:"GET,HEAD,PUT,PATCH,POST,DELETE",preflightContinue:!1,optionsSuccessStatus:204};function c(M){return typeof M==="string"||M instanceof String}function p(M,A){if(Array.isArray(A)){for(var R=0;R<A.length;++R)if(p(M,A[R]))return!0;return!1}else if(c(A))return M===A;else if(A instanceof RegExp)return A.test(M);else return!!A}function a(M,A){var R=A.headers.origin,G=[],Q;if(!M.origin||M.origin==="*")G.push([{key:"Access-Control-Allow-Origin",value:"*"}]);else if(c(M.origin))G.push([{key:"Access-Control-Allow-Origin",value:M.origin}]),G.push([{key:"Vary",value:"Origin"}]);else Q=p(R,M.origin),G.push([{key:"Access-Control-Allow-Origin",value:Q?R:!1}]),G.push([{key:"Vary",value:"Origin"}]);return G}function x(M){var A=M.methods;if(A.join)A=M.methods.join(",");return{key:"Access-Control-Allow-Methods",value:A}}function m(M){if(M.credentials===!0)return{key:"Access-Control-Allow-Credentials",value:"true"};return null}function l(M,A){var R=M.allowedHeaders||M.headers,G=[];if(!R)R=A.headers["access-control-request-headers"],G.push([{key:"Vary",value:"Access-Control-Request-Headers"}]);else if(R.join)R=R.join(",");if(R&&R.length)G.push([{key:"Access-Control-Allow-Headers",value:R}]);return G}function f(M){var A=M.exposedHeaders;if(!A)return null;else if(A.join)A=A.join(",");if(A&&A.length)return{key:"Access-Control-Expose-Headers",value:A};return null}function v(M){var A=(typeof M.maxAge==="number"||M.maxAge)&&M.maxAge.toString();if(A&&A.length)return{key:"Access-Control-Max-Age",value:A};return null}function $(M,A){for(var R=0,G=M.length;R<G;R++){var Q=M[R];if(Q){if(Array.isArray(Q))$(Q,A);else if(Q.key==="Vary"&&Q.value)i(A,Q.value);else if(Q.value)A.setHeader(Q.key,Q.value)}}}function T(M,A,R,G){var Q=[],b=A.method&&A.method.toUpperCase&&A.method.toUpperCase();if(b==="OPTIONS")if(Q.push(a(M,A)),Q.push(m(M,A)),Q.push(x(M,A)),Q.push(l(M,A)),Q.push(v(M,A)),Q.push(f(M,A)),$(Q,R),M.preflightContinue)G();else R.statusCode=M.optionsSuccessStatus,R.setHeader("Content-Length","0"),R.end();else Q.push(a(M,A)),Q.push(m(M,A)),Q.push(f(M,A)),$(Q,R),G()}function F(M){var A=null;if(typeof M==="function")A=M;else A=function(R,G){G(null,M)};return function R(G,Q,b){A(G,function(D,Y){if(D)b(D);else{var K=n({},o,Y),E=null;if(K.origin&&typeof K.origin==="function")E=K.origin;else if(K.origin)E=function(y,V){V(null,K.origin)};if(E)E(G.headers.origin,function(y,V){if(y||!V)b(y);else K.origin=V,T(K,G,Q,b)});else b()}})}}pF.exports=F})()});var av=h(($F)=>{Object.defineProperty($F,"__esModule",{value:!0});$F.Server=$F.BaseServer=void 0;var _3=import.meta.require("querystring"),b3=import.meta.require("url"),aF=Df(),Gm=iv(),j3=import.meta.require("events"),xF=ov(),y3=xi(),B3=gA(),L3=import.meta.require("ws"),mF=nv(),N3=_a(),$n=y3.default("engine"),zp=Symbol("responseHeaders");function D3(n){try{let i=JSON.parse(n);if(typeof i.sid==="string")return i.sid}catch(i){}}class ja extends j3.EventEmitter{constructor(n={}){super();if(this.middlewares=[],this.clients={},this.clientsCount=0,this.opts=Object.assign({wsEngine:L3.Server,pingTimeout:20000,pingInterval:25000,upgradeTimeout:1e4,maxHttpBufferSize:1e6,transports:["polling","websocket"],allowUpgrades:!0,httpCompression:{threshold:1024},cors:!1,allowEIO3:!1},n),n.cookie)this.opts.cookie=Object.assign({name:"io",path:"/",httpOnly:n.cookie.path!==!1,sameSite:"lax"},n.cookie);if(this.opts.cors)this.use(pv()(this.opts.cors));if(n.perMessageDeflate)this.opts.perMessageDeflate=Object.assign({threshold:1024},n.perMessageDeflate);this.init()}_computePath(n){let i=(n.path||"/engine.io").replace(/\/$/,"");if(n.addTrailingSlash!==!1)i+="/";return i}upgrades(n){if(!this.opts.allowUpgrades)return[];return Gm.default[n].upgradesTo||[]}verify(n,i,o){let c=n._query.transport;if(!~this.opts.transports.indexOf(c)||c==="webtransport")return $n('unknown transport "%s"',c),o(En.errors.UNKNOWN_TRANSPORT,{transport:c});if(C3(n.headers.origin)){let x=n.headers.origin;return n.headers.origin=null,$n("origin header invalid"),o(En.errors.BAD_REQUEST,{name:"INVALID_ORIGIN",origin:x})}let a=n._query.sid;if(a){if(!this.clients.hasOwnProperty(a))return $n('unknown sid "%s"',a),o(En.errors.UNKNOWN_SID,{sid:a});let x=this.clients[a].transport.name;if(!i&&x!==c)return $n("bad request: unexpected transport without upgrade"),o(En.errors.BAD_REQUEST,{name:"TRANSPORT_MISMATCH",transport:c,previousTransport:x})}else{if(n.method!=="GET")return o(En.errors.BAD_HANDSHAKE_METHOD,{method:n.method});if(c==="websocket"&&!i)return $n("invalid transport upgrade"),o(En.errors.BAD_REQUEST,{name:"TRANSPORT_HANDSHAKE_ERROR"});if(!this.opts.allowRequest)return o();return this.opts.allowRequest(n,(x,m)=>{if(!m)return o(En.errors.FORBIDDEN,{message:x});o()})}o()}use(n){this.middlewares.push(n)}_applyMiddlewares(n,i,o){if(this.middlewares.length===0)return $n("no middleware to apply, skipping"),o();let c=(p)=>{$n("applying middleware n\xB0%d",p+1),this.middlewares[p](n,i,(a)=>{if(a)return o(a);if(p+1<this.middlewares.length)c(p+1);else o()})};c(0)}close(){$n("closing all open clients");for(let n in this.clients)if(this.clients.hasOwnProperty(n))this.clients[n].close(!0);return this.cleanup(),this}generateId(n){return aF.generateId()}async handshake(n,i,o){let c=i._query.EIO==="4"?4:3;if(c===3&&!this.opts.allowEIO3){$n("unsupported protocol version"),this.emit("connection_error",{req:i,code:En.errors.UNSUPPORTED_PROTOCOL_VERSION,message:En.errorMessages[En.errors.UNSUPPORTED_PROTOCOL_VERSION],context:{protocol:c}}),o(En.errors.UNSUPPORTED_PROTOCOL_VERSION);return}let p;try{p=await this.generateId(i)}catch(m){$n("error while generating an id"),this.emit("connection_error",{req:i,code:En.errors.BAD_REQUEST,message:En.errorMessages[En.errors.BAD_REQUEST],context:{name:"ID_GENERATION_ERROR",error:m}}),o(En.errors.BAD_REQUEST);return}$n('handshaking client "%s"',p);try{var a=this.createTransport(n,i);if(n==="polling")a.maxHttpBufferSize=this.opts.maxHttpBufferSize,a.httpCompression=this.opts.httpCompression;else if(n==="websocket")a.perMessageDeflate=this.opts.perMessageDeflate}catch(m){$n('error handshaking to transport "%s"',n),this.emit("connection_error",{req:i,code:En.errors.BAD_REQUEST,message:En.errorMessages[En.errors.BAD_REQUEST],context:{name:"TRANSPORT_HANDSHAKE_ERROR",error:m}}),o(En.errors.BAD_REQUEST);return}let x=new xF.Socket(p,this,a,i,c);return a.on("headers",(m,l)=>{if(!l._query.sid){if(this.opts.cookie)m["Set-Cookie"]=[B3.serialize(this.opts.cookie.name,p,this.opts.cookie)];this.emit("initial_headers",m,l)}this.emit("headers",m,l)}),a.onRequest(i),this.clients[p]=x,this.clientsCount++,x.once("close",()=>{delete this.clients[p],this.clientsCount--}),this.emit("connection",x),a}async onWebTransportSession(n){let i=setTimeout(()=>{$n("the client failed to establish a bidirectional stream in the given period"),n.close()},this.opts.upgradeTimeout),c=await n.incomingBidirectionalStreams.getReader().read();if(c.done){$n("session is closed");return}let p=c.value,a=N3.createPacketDecoderStream(this.opts.maxHttpBufferSize,"nodebuffer"),x=p.readable.pipeThrough(a).getReader(),{value:m,done:l}=await x.read();if(l){$n("stream is closed");return}if(clearTimeout(i),m.type!=="open")return $n("invalid WebTransport handshake"),n.close();if(m.data===void 0){let $=new mF.WebTransport(n,p,x),T=aF.generateId();$n('handshaking client "%s" (WebTransport)',T);let F=new xF.Socket(T,this,$,null,4);this.clients[T]=F,this.clientsCount++,F.once("close",()=>{delete this.clients[T],this.clientsCount--}),this.emit("connection",F);return}let f=D3(m.data);if(!f)return $n("invalid WebTransport handshake"),n.close();let v=this.clients[f];if(!v)$n("upgrade attempt for closed client"),n.close();else if(v.upgrading)$n("transport has already been trying to upgrade"),n.close();else if(v.upgraded)$n("transport had already been upgraded"),n.close();else{$n("upgrading existing transport");let $=new mF.WebTransport(n,p,x);v._maybeUpgrade($)}}}$F.BaseServer=ja;ja.errors={UNKNOWN_TRANSPORT:0,UNKNOWN_SID:1,BAD_HANDSHAKE_METHOD:2,BAD_REQUEST:3,FORBIDDEN:4,UNSUPPORTED_PROTOCOL_VERSION:5};ja.errorMessages={0:"Transport unknown",1:"Session ID unknown",2:"Bad handshake method",3:"Bad request",4:"Forbidden",5:"Unsupported protocol version"};class vF{constructor(n,i){this.req=n,this.socket=i,n[zp]={}}setHeader(n,i){this.req[zp][n]=i}getHeader(n){return this.req[zp][n]}removeHeader(n){delete this.req[zp][n]}write(){}writeHead(){}end(){this.socket.destroy()}}class En extends ja{init(){if(!~this.opts.transports.indexOf("websocket"))return;if(this.ws)this.ws.close();if(this.ws=new this.opts.wsEngine({noServer:!0,clientTracking:!1,perMessageDeflate:this.opts.perMessageDeflate,maxPayload:this.opts.maxHttpBufferSize}),typeof this.ws.on==="function")this.ws.on("headers",(n,i)=>{let o=i[zp]||{};if(delete i[zp],!i._query.sid)this.emit("initial_headers",o,i);this.emit("headers",o,i),$n("writing headers: %j",o),Object.keys(o).forEach((p)=>{n.push(`${p}: ${o[p]}`)})})}cleanup(){if(this.ws)$n("closing webSocketServer"),this.ws.close()}prepare(n){if(!n._query)n._query=~n.url.indexOf("?")?_3.parse(b3.parse(n.url).query):{}}createTransport(n,i){return new Gm.default[n](i)}handleRequest(n,i){$n('handling "%s" http request "%s"',n.method,n.url),this.prepare(n),n.res=i;let o=(c,p)=>{if(c!==void 0){this.emit("connection_error",{req:n,code:c,message:En.errorMessages[c],context:p}),lF(i,c,p);return}if(n._query.sid)$n("setting new request for existing client"),this.clients[n._query.sid].transport.onRequest(n);else{let a=(x,m)=>lF(i,x,m);this.handshake(n._query.transport,n,a)}};this._applyMiddlewares(n,i,(c)=>{if(c)o(En.errors.BAD_REQUEST,{name:"MIDDLEWARE_FAILURE"});else this.verify(n,!1,o)})}handleUpgrade(n,i,o){this.prepare(n);let c=new vF(n,i),p=(a,x)=>{if(a!==void 0){this.emit("connection_error",{req:n,code:a,message:En.errorMessages[a],context:x}),fF(i,a,x);return}let m=Buffer.from(o);o=null,c.writeHead(),this.ws.handleUpgrade(n,i,m,(l)=>{this.onWebSocket(n,i,l)})};this._applyMiddlewares(n,c,(a)=>{if(a)p(En.errors.BAD_REQUEST,{name:"MIDDLEWARE_FAILURE"});else this.verify(n,!0,p)})}onWebSocket(n,i,o){if(o.on("error",p),Gm.default[n._query.transport]!==void 0&&!Gm.default[n._query.transport].prototype.handlesUpgrades){$n("transport doesnt handle upgraded requests"),o.close();return}let c=n._query.sid;if(n.websocket=o,c){let a=this.clients[c];if(!a)$n("upgrade attempt for closed client"),o.close();else if(a.upgrading)$n("transport has already been trying to upgrade"),o.close();else if(a.upgraded)$n("transport had already been upgraded"),o.close();else{$n("upgrading existing transport"),o.removeListener("error",p);let x=this.createTransport(n._query.transport,n);x.perMessageDeflate=this.opts.perMessageDeflate,a._maybeUpgrade(x)}}else{let a=(x,m)=>fF(i,x,m);this.handshake(n._query.transport,n,a)}function p(){$n("websocket error before upgrade")}}attach(n,i={}){let o=this._computePath(i),c=i.destroyUpgradeTimeout||1000;function p(x){return o===x.url.slice(0,o.length)}let a=n.listeners("request").slice(0);if(n.removeAllListeners("request"),n.on("close",this.close.bind(this)),n.on("listening",this.init.bind(this)),n.on("request",(x,m)=>{if(p(x))$n('intercepting request for path "%s"',o),this.handleRequest(x,m);else{let l=0,f=a.length;for(;l<f;l++)a[l].call(n,x,m)}}),~this.opts.transports.indexOf("websocket"))n.on("upgrade",(x,m,l)=>{if(p(x))this.handleUpgrade(x,m,l);else if(i.destroyUpgrade!==!1)setTimeout(function(){if(m.writable&&m.bytesWritten<=0)return m.on("error",(f)=>{$n("error while destroying upgrade: %s",f.message)}),m.end()},c)})}}$F.Server=En;function lF(n,i,o){let c=i===En.errors.FORBIDDEN?403:400,p=o&&o.message?o.message:En.errorMessages[i];n.writeHead(c,{"Content-Type":"application/json"}),n.end(JSON.stringify({code:i,message:p}))}function fF(n,i,o={}){if(n.on("error",()=>{$n("ignoring error from closed connection")}),n.writable){let c=o.message||En.errorMessages[i],p=Buffer.byteLength(c);n.write("HTTP/1.1 400 Bad Request\r\nConnection: close\r\nContent-type: text/html\r\nContent-Length: "+p+"\r\n\r\n"+c)}n.destroy()}var ba=[0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1];function C3(n){if(n+="",n.length<1)return!1;if(!ba[n.charCodeAt(0)])return $n('invalid header, index 0, char "%s"',n.charCodeAt(0)),!0;if(n.length<2)return!1;if(!ba[n.charCodeAt(1)])return $n('invalid header, index 1, char "%s"',n.charCodeAt(1)),!0;if(n.length<3)return!1;if(!ba[n.charCodeAt(2)])return $n('invalid header, index 2, char "%s"',n.charCodeAt(2)),!0;if(n.length<4)return!1;if(!ba[n.charCodeAt(3)])return $n('invalid header, index 3, char "%s"',n.charCodeAt(3)),!0;for(let i=4;i<n.length;++i)if(!ba[n.charCodeAt(i)])return $n('invalid header, index "%i", char "%s"',i,n.charCodeAt(i)),!0;return!1}});var FF=h((SF)=>{Object.defineProperty(SF,"__esModule",{value:!0});SF.Polling=void 0;var I3=_c(),wF=import.meta.require("zlib"),k3=fm(),s3=xi(),io=s3.default("engine:polling"),Z3={gzip:wF.createGzip,deflate:wF.createDeflate};class JF extends I3.Transport{constructor(n){super(n);this.closeTimeout=30000}get name(){return"polling"}onRequest(n){let i=n.res;if(n.res=null,n.getMethod()==="get")this.onPollRequest(n,i);else if(n.getMethod()==="post")this.onDataRequest(n,i);else i.writeStatus("500 Internal Server Error"),i.end()}onPollRequest(n,i){if(this.req){io("request overlap"),this.onError("overlap from client"),i.writeStatus("500 Internal Server Error"),i.end();return}io("setting request"),this.req=n,this.res=i;let o=()=>{this.writable=!1,this.onError("poll connection closed prematurely")},c=()=>{this.req=this.res=null};if(n.cleanup=c,i.onAborted(o),this.writable=!0,this.emit("ready"),this.writable&&this.shouldClose)io("triggering empty send to append close packet"),this.send([{type:"noop"}])}onDataRequest(n,i){if(this.dataReq){this.onError("data request overlap from client"),i.writeStatus("500 Internal Server Error"),i.end();return}let o=Number(n.headers["content-length"]);if(!o){this.onError("content-length header required"),i.writeStatus("411 Length Required").end();return}if(o>this.maxHttpBufferSize){this.onError("payload too large"),i.writeStatus("413 Payload Too Large").end();return}if(n.headers["content-type"]==="application/octet-stream"&&this.protocol===4)return this.onError("invalid content");this.dataReq=n,this.dataRes=i;let p,a=0,x={"Content-Type":"text/html"};this.headers(n,x);for(let l in x)i.writeHeader(l,String(x[l]));let m=(l)=>{this.onData(l.toString()),this.onDataRequestCleanup(),i.cork(()=>{i.end("ok")})};i.onAborted(()=>{this.onDataRequestCleanup(),this.onError("data request connection closed prematurely")}),i.onData((l,f)=>{let v=a+l.byteLength;if(v>o){this.onError("content-length mismatch"),i.close();return}if(!p){if(f){m(Buffer.from(l));return}p=Buffer.allocUnsafe(o)}if(Buffer.from(l).copy(p,a),f){if(v!=o){this.onError("content-length mismatch"),i.writeStatus("400 Content-Length Mismatch").end(),this.onDataRequestCleanup();return}m(p);return}a=v})}onDataRequestCleanup(){this.dataReq=this.dataRes=null}onData(n){io('received "%s"',n);let i=(o)=>{if(o.type==="close")return io("got xhr close packet"),this.onClose(),!1;this.onPacket(o)};if(this.protocol===3)this.parser.decodePayload(n,i);else this.parser.decodePayload(n).forEach(i)}onClose(){if(this.writable)this.send([{type:"noop"}]);super.onClose()}send(n){if(this.writable=!1,this.shouldClose)io("appending close packet to payload"),n.push({type:"close"}),this.shouldClose(),this.shouldClose=null;let i=(o)=>{let c=n.some((p)=>{return p.options&&p.options.compress});this.write(o,{compress:c})};if(this.protocol===3)this.parser.encodePayload(n,this.supportsBinary,i);else this.parser.encodePayload(n,i)}write(n,i){io('writing "%s"',n),this.doWrite(n,i,()=>{this.req.cleanup(),this.emit("drain")})}doWrite(n,i,o){let c=typeof n==="string",a={"Content-Type":c?"text/plain; charset=UTF-8":"application/octet-stream"},x=(f)=>{this.headers(this.req,a),this.res.cork(()=>{Object.keys(a).forEach((v)=>{this.res.writeHeader(v,String(a[v]))}),this.res.end(f)}),o()};if(!this.httpCompression||!i.compress){x(n);return}if((c?Buffer.byteLength(n):n.length)<this.httpCompression.threshold){x(n);return}let l=k3(this.req).encodings(["gzip","deflate"]);if(!l){x(n);return}this.compress(n,l,(f,v)=>{if(f){this.res.writeStatus("500 Internal Server Error"),this.res.end(),o(f);return}a["Content-Encoding"]=l,x(v)})}compress(n,i,o){io("compressing");let c=[],p=0;Z3[i](this.httpCompression).on("error",o).on("data",function(a){c.push(a),p+=a.length}).on("end",function(){o(null,Buffer.concat(c,p))}).end(n)}doClose(n){io("closing");let i,o=()=>{clearTimeout(i),n(),this.onClose()};if(this.writable)io("transport writable - closing right away"),this.send([{type:"close"}]),o();else if(this.discarded)io("transport discarded - closing right away"),o();else io("transport not writable - buffering orderly close"),this.shouldClose=o,i=setTimeout(o,this.closeTimeout)}headers(n,i){i=i||{};let o=n.headers["user-agent"];if(o&&(~o.indexOf(";MSIE")||~o.indexOf("Trident/")))i["X-XSS-Protection"]="0";return i["cache-control"]="no-store",this.emit("headers",i,n),i}}SF.Polling=JF});var XF=h((WF)=>{Object.defineProperty(WF,"__esModule",{value:!0});WF.WebSocket=void 0;var t3=_c(),q3=xi(),MF=q3.default("engine:ws");class RF extends t3.Transport{constructor(n){super(n);this.writable=!1,this.perMessageDeflate=null}get name(){return"websocket"}get handlesUpgrades(){return!0}send(n){this.writable=!1;for(let i=0;i<n.length;i++){let o=n[i],c=i+1===n.length,p=(a)=>{let x=typeof a!=="string",m=this.perMessageDeflate&&Buffer.byteLength(a)>this.perMessageDeflate.threshold;if(MF('writing "%s"',a),this.socket.send(a,x,m),c)this.emit("drain"),this.writable=!0,this.emit("ready")};if(o.options&&typeof o.options.wsPreEncoded==="string")p(o.options.wsPreEncoded);else this.parser.encodePacket(o,this.supportsBinary,p)}}doClose(n){MF("closing"),n&&n(),this.socket.end()}}WF.WebSocket=RF});var YF=h((GF)=>{Object.defineProperty(GF,"__esModule",{value:!0});var P3=FF(),r3=XF();GF.default={polling:P3.Polling,websocket:r3.WebSocket}});var OF=h((HF)=>{Object.defineProperty(HF,"__esModule",{value:!0});HF.uServer=void 0;var d3=xi(),bc=av(),e3=YF(),vc=d3.default("engine:uws");class zF extends bc.BaseServer{init(){}cleanup(){}prepare(n,i){n.method=n.getMethod().toUpperCase(),n.url=n.getUrl();let o=new URLSearchParams(n.getQuery());n._query=Object.fromEntries(o.entries()),n.headers={},n.forEach((c,p)=>{n.headers[c]=p}),n.connection={remoteAddress:Buffer.from(i.getRemoteAddressAsText()).toString()},i.onAborted(()=>{vc("response has been aborted")})}createTransport(n,i){return new e3.default[n](i)}attach(n,i={}){let o=this._computePath(i);n.any(o,this.handleRequest.bind(this)).ws(o,{compression:i.compression,idleTimeout:i.idleTimeout,maxBackpressure:i.maxBackpressure,maxPayloadLength:this.opts.maxHttpBufferSize,upgrade:this.handleUpgrade.bind(this),open:(c)=>{let p=c.getUserData().transport;p.socket=c,p.writable=!0,p.emit("ready")},message:(c,p,a)=>{c.getUserData().transport.onData(a?p:Buffer.from(p).toString())},close:(c,p,a)=>{c.getUserData().transport.onClose(p,a)}})}_applyMiddlewares(n,i,o){if(this.middlewares.length===0)return o();n.res=new QF(i),super._applyMiddlewares(n,n.res,(c)=>{n.res.writeHead(),o(c)})}handleRequest(n,i){vc('handling "%s" http request "%s"',i.getMethod(),i.getUrl()),this.prepare(i,n),i.res=n;let o=(c,p)=>{if(c!==void 0){this.emit("connection_error",{req:i,code:c,message:bc.Server.errorMessages[c],context:p}),this.abortRequest(i.res,c,p);return}if(i._query.sid)vc("setting new request for existing client"),this.clients[i._query.sid].transport.onRequest(i);else{let a=(x,m)=>this.abortRequest(n,x,m);this.handshake(i._query.transport,i,a)}};this._applyMiddlewares(i,n,(c)=>{if(c)o(bc.Server.errors.BAD_REQUEST,{name:"MIDDLEWARE_FAILURE"});else this.verify(i,!1,o)})}handleUpgrade(n,i,o){vc("on upgrade"),this.prepare(i,n),i.res=n;let c=async(p,a)=>{if(p!==void 0){this.emit("connection_error",{req:i,code:p,message:bc.Server.errorMessages[p],context:a}),this.abortRequest(n,p,a);return}let x=i._query.sid,m;if(x){let l=this.clients[x];if(!l)return vc("upgrade attempt for closed client"),n.close();else if(l.upgrading)return vc("transport has already been trying to upgrade"),n.close();else if(l.upgraded)return vc("transport had already been upgraded"),n.close();else vc("upgrading existing transport"),m=this.createTransport(i._query.transport,i),l._maybeUpgrade(m)}else if(m=await this.handshake(i._query.transport,i,(l,f)=>this.abortRequest(n,l,f)),!m)return;i.res.writeStatus("101 Switching Protocols"),n.upgrade({transport:m},i.getHeader("sec-websocket-key"),i.getHeader("sec-websocket-protocol"),i.getHeader("sec-websocket-extensions"),o)};this._applyMiddlewares(i,n,(p)=>{if(p)c(bc.Server.errors.BAD_REQUEST,{name:"MIDDLEWARE_FAILURE"});else this.verify(i,!0,c)})}abortRequest(n,i,o){let c=i===bc.Server.errors.FORBIDDEN?"403 Forbidden":"400 Bad Request",p=o&&o.message?o.message:bc.Server.errorMessages[i];n.writeStatus(c),n.writeHeader("Content-Type","application/json"),n.end(JSON.stringify({code:i,message:p}))}}HF.uServer=zF;class QF{constructor(n){this.res=n,this.statusWritten=!1,this.headers=[],this.isAborted=!1}set statusCode(n){if(!n)return;this.writeStatus(n===200?"200 OK":"204 No Content")}writeHead(n){this.statusCode=n}setHeader(n,i){if(Array.isArray(i))i.forEach((o)=>{this.writeHeader(n,o)});else this.writeHeader(n,i)}removeHeader(){}getHeader(){}writeStatus(n){if(this.isAborted)return;return this.res.writeStatus(n),this.statusWritten=!0,this.writeBufferedHeaders(),this}writeHeader(n,i){if(this.isAborted)return;if(n==="Content-Length")return;if(this.statusWritten)this.res.writeHeader(n,i);else this.headers.push([n,i])}writeBufferedHeaders(){this.headers.forEach(([n,i])=>{this.res.writeHeader(n,i)})}end(n){if(this.isAborted)return;this.res.cork(()=>{if(!this.statusWritten)this.writeBufferedHeaders();this.res.end(n)})}onData(n){if(this.isAborted)return;this.res.onData(n)}onAborted(n){if(this.isAborted)return;this.res.onAborted(()=>{this.isAborted=!0,n()})}cork(n){if(this.isAborted)return;this.res.cork(n)}}});var bF=h((Qp)=>{Object.defineProperty(Qp,"__esModule",{value:!0});Qp.protocol=Qp.Transport=Qp.Socket=Qp.uServer=Qp.parser=Qp.transports=Qp.Server=void 0;Qp.listen=aX;Qp.attach=uF;var nX=import.meta.require("http"),UF=av();Object.defineProperty(Qp,"Server",{enumerable:!0,get:function(){return UF.Server}});var iX=iv();Qp.transports=iX.default;var VF=_a();Qp.parser=VF;var oX=OF();Object.defineProperty(Qp,"uServer",{enumerable:!0,get:function(){return oX.uServer}});var cX=ov();Object.defineProperty(Qp,"Socket",{enumerable:!0,get:function(){return cX.Socket}});var pX=_c();Object.defineProperty(Qp,"Transport",{enumerable:!0,get:function(){return pX.Transport}});Qp.protocol=VF.protocol;function aX(n,i,o){if(typeof i==="function")o=i,i={};let c=nX.createServer(function(a,x){x.writeHead(501),x.end("Not Implemented")}),p=uF(c,i);return p.httpServer=c,c.listen(n,o),p}function uF(n,i){let o=new UF.Server(i);return o.attach(n,i),o}});var jF=h(($X)=>{$X.Emitter=Hi;function Hi(n){if(n)return vX(n)}function vX(n){for(var i in Hi.prototype)n[i]=Hi.prototype[i];return n}Hi.prototype.on=Hi.prototype.addEventListener=function(n,i){return this._callbacks=this._callbacks||{},(this._callbacks["$"+n]=this._callbacks["$"+n]||[]).push(i),this};Hi.prototype.once=function(n,i){function o(){this.off(n,o),i.apply(this,arguments)}return o.fn=i,this.on(n,o),this};Hi.prototype.off=Hi.prototype.removeListener=Hi.prototype.removeAllListeners=Hi.prototype.removeEventListener=function(n,i){if(this._callbacks=this._callbacks||{},arguments.length==0)return this._callbacks={},this;var o=this._callbacks["$"+n];if(!o)return this;if(arguments.length==1)return delete this._callbacks["$"+n],this;var c;for(var p=0;p<o.length;p++)if(c=o[p],c===i||c.fn===i){o.splice(p,1);break}if(o.length===0)delete this._callbacks["$"+n];return this};Hi.prototype.emit=function(n){this._callbacks=this._callbacks||{};var i=new Array(arguments.length-1),o=this._callbacks["$"+n];for(var c=1;c<arguments.length;c++)i[c-1]=arguments[c];if(o){o=o.slice(0);for(var c=0,p=o.length;c<p;++c)o[c].apply(this,i)}return this};Hi.prototype.emitReserved=Hi.prototype.emit;Hi.prototype.listeners=function(n){return this._callbacks=this._callbacks||{},this._callbacks["$"+n]||[]};Hi.prototype.hasListeners=function(n){return!!this.listeners(n).length}});var xv=h((LF)=>{Object.defineProperty(LF,"__esModule",{value:!0});LF.hasBinary=LF.isBinary=void 0;var wX=typeof ArrayBuffer==="function",JX=(n)=>{return typeof ArrayBuffer.isView==="function"?ArrayBuffer.isView(n):n.buffer instanceof ArrayBuffer},yF=Object.prototype.toString,SX=typeof Blob==="function"||typeof Blob!=="undefined"&&yF.call(Blob)==="[object BlobConstructor]",AX=typeof File==="function"||typeof File!=="undefined"&&yF.call(File)==="[object FileConstructor]";function BF(n){return wX&&(n instanceof ArrayBuffer||JX(n))||SX&&n instanceof Blob||AX&&n instanceof File}LF.isBinary=BF;function Ym(n,i){if(!n||typeof n!=="object")return!1;if(Array.isArray(n)){for(let o=0,c=n.length;o<c;o++)if(Ym(n[o]))return!0;return!1}if(BF(n))return!0;if(n.toJSON&&typeof n.toJSON==="function"&&arguments.length===1)return Ym(n.toJSON(),!0);for(let o in n)if(Object.prototype.hasOwnProperty.call(n,o)&&Ym(n[o]))return!0;return!1}LF.hasBinary=Ym});var hF=h((DF)=>{Object.defineProperty(DF,"__esModule",{value:!0});DF.reconstructPacket=DF.deconstructPacket=void 0;var MX=xv();function RX(n){let i=[],o=n.data,c=n;return c.data=mv(o,i),c.attachments=i.length,{packet:c,buffers:i}}DF.deconstructPacket=RX;function mv(n,i){if(!n)return n;if(MX.isBinary(n)){let o={_placeholder:!0,num:i.length};return i.push(n),o}else if(Array.isArray(n)){let o=new Array(n.length);for(let c=0;c<n.length;c++)o[c]=mv(n[c],i);return o}else if(typeof n==="object"&&!(n instanceof Date)){let o={};for(let c in n)if(Object.prototype.hasOwnProperty.call(n,c))o[c]=mv(n[c],i);return o}return n}function WX(n,i){return n.data=lv(n.data,i),delete n.attachments,n}DF.reconstructPacket=WX;function lv(n,i){if(!n)return n;if(n&&n._placeholder===!0)if(typeof n.num==="number"&&n.num>=0&&n.num<i.length)return i[n.num];else throw new Error("illegal attachments");else if(Array.isArray(n))for(let o=0;o<n.length;o++)n[o]=lv(n[o],i);else if(typeof n==="object"){for(let o in n)if(Object.prototype.hasOwnProperty.call(n,o))n[o]=lv(n[o],i)}return n}});var ya=h((PF)=>{Object.defineProperty(PF,"__esModule",{value:!0});PF.Decoder=PF.Encoder=PF.PacketType=PF.protocol=void 0;var XX=jF(),sF=hF(),ZF=xv(),GX=xi(),fv=GX.default("socket.io-parser"),YX=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"];PF.protocol=5;var sn;(function(n){n[n.CONNECT=0]="CONNECT",n[n.DISCONNECT=1]="DISCONNECT",n[n.EVENT=2]="EVENT",n[n.ACK=3]="ACK",n[n.CONNECT_ERROR=4]="CONNECT_ERROR",n[n.BINARY_EVENT=5]="BINARY_EVENT",n[n.BINARY_ACK=6]="BINARY_ACK"})(sn=PF.PacketType||(PF.PacketType={}));class tF{constructor(n){this.replacer=n}encode(n){if(fv("encoding packet %j",n),n.type===sn.EVENT||n.type===sn.ACK){if(ZF.hasBinary(n))return this.encodeAsBinary({type:n.type===sn.EVENT?sn.BINARY_EVENT:sn.BINARY_ACK,nsp:n.nsp,data:n.data,id:n.id})}return[this.encodeAsString(n)]}encodeAsString(n){let i=""+n.type;if(n.type===sn.BINARY_EVENT||n.type===sn.BINARY_ACK)i+=n.attachments+"-";if(n.nsp&&n.nsp!=="/")i+=n.nsp+",";if(n.id!=null)i+=n.id;if(n.data!=null)i+=JSON.stringify(n.data,this.replacer);return fv("encoded %j as %s",n,i),i}encodeAsBinary(n){let i=sF.deconstructPacket(n),o=this.encodeAsString(i.packet),c=i.buffers;return c.unshift(o),c}}PF.Encoder=tF;function IF(n){return Object.prototype.toString.call(n)==="[object Object]"}class vv extends XX.Emitter{constructor(n){super();this.reviver=n}add(n){let i;if(typeof n==="string"){if(this.reconstructor)throw new Error("got plaintext data when reconstructing a packet");i=this.decodeString(n);let o=i.type===sn.BINARY_EVENT;if(o||i.type===sn.BINARY_ACK){if(i.type=o?sn.EVENT:sn.ACK,this.reconstructor=new qF(i),i.attachments===0)super.emitReserved("decoded",i)}else super.emitReserved("decoded",i)}else if(ZF.isBinary(n)||n.base64){if(!this.reconstructor)throw new Error("got binary data when not reconstructing a packet");else if(i=this.reconstructor.takeBinaryData(n),i)this.reconstructor=null,super.emitReserved("decoded",i)}else throw new Error("Unknown type: "+n)}decodeString(n){let i=0,o={type:Number(n.charAt(0))};if(sn[o.type]===void 0)throw new Error("unknown packet type "+o.type);if(o.type===sn.BINARY_EVENT||o.type===sn.BINARY_ACK){let p=i+1;while(n.charAt(++i)!=="-"&&i!=n.length);let a=n.substring(p,i);if(a!=Number(a)||n.charAt(i)!=="-")throw new Error("Illegal attachments");o.attachments=Number(a)}if(n.charAt(i+1)==="/"){let p=i+1;while(++i){if(n.charAt(i)===",")break;if(i===n.length)break}o.nsp=n.substring(p,i)}else o.nsp="/";let c=n.charAt(i+1);if(c!==""&&Number(c)==c){let p=i+1;while(++i){let a=n.charAt(i);if(a==null||Number(a)!=a){--i;break}if(i===n.length)break}o.id=Number(n.substring(p,i+1))}if(n.charAt(++i)){let p=this.tryParse(n.substr(i));if(vv.isPayloadValid(o.type,p))o.data=p;else throw new Error("invalid payload")}return fv("decoded %s as %j",n,o),o}tryParse(n){try{return JSON.parse(n,this.reviver)}catch(i){return!1}}static isPayloadValid(n,i){switch(n){case sn.CONNECT:return IF(i);case sn.DISCONNECT:return i===void 0;case sn.CONNECT_ERROR:return typeof i==="string"||IF(i);case sn.EVENT:case sn.BINARY_EVENT:return Array.isArray(i)&&(typeof i[0]==="number"||typeof i[0]==="string"&&YX.indexOf(i[0])===-1);case sn.ACK:case sn.BINARY_ACK:return Array.isArray(i)}}destroy(){if(this.reconstructor)this.reconstructor.finishedReconstruction(),this.reconstructor=null}}PF.Decoder=vv;class qF{constructor(n){this.packet=n,this.buffers=[],this.reconPack=n}takeBinaryData(n){if(this.buffers.push(n),this.buffers.length===this.reconPack.attachments){let i=sF.reconstructPacket(this.reconPack,this.buffers);return this.finishedReconstruction(),i}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}});var nM=h((dF)=>{Object.defineProperty(dF,"__esModule",{value:!0});dF.Client=void 0;var zm=ya(),HX=xi(),EX=import.meta.require("url"),Ao=HX("socket.io:client");class gF{constructor(n,i){this.sockets=new Map,this.nsps=new Map,this.server=n,this.conn=i,this.encoder=n.encoder,this.decoder=new n._parser.Decoder,this.id=i.id,this.setup()}get request(){return this.conn.request}setup(){this.onclose=this.onclose.bind(this),this.ondata=this.ondata.bind(this),this.onerror=this.onerror.bind(this),this.ondecoded=this.ondecoded.bind(this),this.decoder.on("decoded",this.ondecoded),this.conn.on("data",this.ondata),this.conn.on("error",this.onerror),this.conn.on("close",this.onclose),this.connectTimeout=setTimeout(()=>{if(this.nsps.size===0)Ao("no namespace joined yet, close the client"),this.close();else Ao("the client has already joined a namespace, nothing to do")},this.server._connectTimeout)}connect(n,i={}){if(this.server._nsps.has(n))return Ao("connecting to namespace %s",n),this.doConnect(n,i);this.server._checkNamespace(n,i,(o)=>{if(o)this.doConnect(n,i);else Ao("creation of namespace %s was denied",n),this._packet({type:zm.PacketType.CONNECT_ERROR,nsp:n,data:{message:"Invalid namespace"}})})}doConnect(n,i){let o=this.server.of(n);o._add(this,i,(c)=>{if(this.sockets.set(c.id,c),this.nsps.set(o.name,c),this.connectTimeout)clearTimeout(this.connectTimeout),this.connectTimeout=void 0})}_disconnect(){for(let n of this.sockets.values())n.disconnect();this.sockets.clear(),this.close()}_remove(n){if(this.sockets.has(n.id)){let i=this.sockets.get(n.id).nsp.name;this.sockets.delete(n.id),this.nsps.delete(i)}else Ao("ignoring remove for %s",n.id)}close(){if(this.conn.readyState==="open")Ao("forcing transport close"),this.conn.close(),this.onclose("forced server close")}_packet(n,i={}){if(this.conn.readyState!=="open"){Ao("ignoring packet write %j",n);return}let o=i.preEncoded?n:this.encoder.encode(n);this.writeToEngine(o,i)}writeToEngine(n,i){if(i.volatile&&!this.conn.transport.writable){Ao("volatile packet is discarded since the transport is not currently writable");return}let o=Array.isArray(n)?n:[n];for(let c of o)this.conn.write(c,i)}ondata(n){try{this.decoder.add(n)}catch(i){Ao("invalid packet format"),this.onerror(i)}}ondecoded(n){let i,o;if(this.conn.protocol===3){let p=EX.parse(n.nsp,!0);i=p.pathname,o=p.query}else i=n.nsp,o=n.data;let c=this.nsps.get(i);if(!c&&n.type===zm.PacketType.CONNECT)this.connect(i,o);else if(c&&n.type!==zm.PacketType.CONNECT&&n.type!==zm.PacketType.CONNECT_ERROR)process.nextTick(function(){c._onpacket(n)});else Ao("invalid state (packet type: %s)",n.type),this.close()}onerror(n){for(let i of this.sockets.values())i._onerror(n);this.conn.close()}onclose(n,i){Ao("client close with reason %s",n),this.destroy();for(let o of this.sockets.values())o._onclose(n,i);this.sockets.clear(),this.decoder.destroy()}destroy(){if(this.conn.removeListener("data",this.ondata),this.conn.removeListener("error",this.onerror),this.conn.removeListener("close",this.onclose),this.decoder.removeListener("decoded",this.ondecoded),this.connectTimeout)clearTimeout(this.connectTimeout),this.connectTimeout=void 0}}dF.Client=gF});var Qm=h((oM)=>{Object.defineProperty(oM,"__esModule",{value:!0});oM.StrictEventEmitter=void 0;var OX=import.meta.require("events");class iM extends OX.EventEmitter{on(n,i){return super.on(n,i)}once(n,i){return super.once(n,i)}emit(n,...i){return super.emit(n,...i)}emitReserved(n,...i){return super.emit(n,...i)}emitUntyped(n,...i){return super.emit(n,...i)}listeners(n){return super.listeners(n)}}oM.StrictEventEmitter=iM});var $v=h((pM)=>{Object.defineProperty(pM,"__esModule",{value:!0});pM.RESERVED_EVENTS=void 0;pM.RESERVED_EVENTS=new Set(["connect","connect_error","disconnect","disconnecting","newListener","removeListener"])});var wv=h((xM)=>{Object.defineProperty(xM,"__esModule",{value:!0});xM.RemoteSocket=xM.BroadcastOperator=void 0;var UX=$v(),VX=ya();class No{constructor(n,i=new Set,o=new Set,c={}){this.adapter=n,this.rooms=i,this.exceptRooms=o,this.flags=c}to(n){let i=new Set(this.rooms);if(Array.isArray(n))n.forEach((o)=>i.add(o));else i.add(n);return new No(this.adapter,i,this.exceptRooms,this.flags)}in(n){return this.to(n)}except(n){let i=new Set(this.exceptRooms);if(Array.isArray(n))n.forEach((o)=>i.add(o));else i.add(n);return new No(this.adapter,this.rooms,i,this.flags)}compress(n){let i=Object.assign({},this.flags,{compress:n});return new No(this.adapter,this.rooms,this.exceptRooms,i)}get volatile(){let n=Object.assign({},this.flags,{volatile:!0});return new No(this.adapter,this.rooms,this.exceptRooms,n)}get local(){let n=Object.assign({},this.flags,{local:!0});return new No(this.adapter,this.rooms,this.exceptRooms,n)}timeout(n){let i=Object.assign({},this.flags,{timeout:n});return new No(this.adapter,this.rooms,this.exceptRooms,i)}emit(n,...i){if(UX.RESERVED_EVENTS.has(n))throw new Error(`"${String(n)}" is a reserved event name`);let o=[n,...i],c={type:VX.PacketType.EVENT,data:o};if(typeof o[o.length-1]!=="function")return this.adapter.broadcast(c,{rooms:this.rooms,except:this.exceptRooms,flags:this.flags}),!0;let a=o.pop(),x=!1,m=[],l=setTimeout(()=>{x=!0,a.apply(this,[new Error("operation has timed out"),this.flags.expectSingleResponse?null:m])},this.flags.timeout),f=-1,v=0,$=0,T=()=>{if(!x&&f===v&&m.length===$)clearTimeout(l),a.apply(this,[null,this.flags.expectSingleResponse?m[0]:m])};return this.adapter.broadcastWithAck(c,{rooms:this.rooms,except:this.exceptRooms,flags:this.flags},(F)=>{$+=F,v++,T()},(F)=>{m.push(F),T()}),this.adapter.serverCount().then((F)=>{f=F,T()}),!0}emitWithAck(n,...i){return new Promise((o,c)=>{i.push((p,a)=>{if(p)return p.responses=a,c(p);else return o(a)}),this.emit(n,...i)})}allSockets(){if(!this.adapter)throw new Error("No adapter for this namespace, are you trying to get the list of clients of a dynamic namespace?");return this.adapter.sockets(this.rooms)}fetchSockets(){return this.adapter.fetchSockets({rooms:this.rooms,except:this.exceptRooms,flags:this.flags}).then((n)=>{return n.map((i)=>{if(i.server)return i;else return new Tv(this.adapter,i)})})}socketsJoin(n){this.adapter.addSockets({rooms:this.rooms,except:this.exceptRooms,flags:this.flags},Array.isArray(n)?n:[n])}socketsLeave(n){this.adapter.delSockets({rooms:this.rooms,except:this.exceptRooms,flags:this.flags},Array.isArray(n)?n:[n])}disconnectSockets(n=!1){this.adapter.disconnectSockets({rooms:this.rooms,except:this.exceptRooms,flags:this.flags},n)}}xM.BroadcastOperator=No;class Tv{constructor(n,i){this.id=i.id,this.handshake=i.handshake,this.rooms=new Set(i.rooms),this.data=i.data,this.operator=new No(n,new Set([this.id]),new Set,{expectSingleResponse:!0})}timeout(n){return this.operator.timeout(n)}emit(n,...i){return this.operator.emit(n,...i)}join(n){return this.operator.socketsJoin(n)}leave(n){return this.operator.socketsLeave(n)}disconnect(n=!1){return this.operator.disconnectSockets(n),this}}xM.RemoteSocket=Tv});var Jv=h((Hp)=>{var vM=Hp&&Hp.__importDefault||function(n){return n&&n.__esModule?n:{default:n}};Object.defineProperty(Hp,"__esModule",{value:!0});Hp.Socket=void 0;var oo=ya(),_X=vM(xi()),bX=Qm(),lM=vM(Df()),jX=wv(),yX=$v(),Wi=_X.default("socket.io:socket"),BX=new Set(["transport error","transport close","forced close","ping timeout","server shutting down","forced server close"]);function fM(){}class $M extends bX.StrictEventEmitter{constructor(n,i,o,c){super();if(this.nsp=n,this.client=i,this.recovered=!1,this.data={},this.connected=!1,this.acks=new Map,this.fns=[],this.flags={},this.server=n.server,this.adapter=this.nsp.adapter,c)this.id=c.sid,this.pid=c.pid,c.rooms.forEach((p)=>this.join(p)),this.data=c.data,c.missedPackets.forEach((p)=>{this.packet({type:oo.PacketType.EVENT,data:p})}),this.recovered=!0;else{if(i.conn.protocol===3)this.id=n.name!=="/"?n.name+"#"+i.id:i.id;else this.id=lM.default.generateId();if(this.server._opts.connectionStateRecovery)this.pid=lM.default.generateId()}this.handshake=this.buildHandshake(o),this.on("error",fM)}buildHandshake(n){var i,o,c,p;return{headers:((i=this.request)===null||i===void 0?void 0:i.headers)||{},time:new Date+"",address:this.conn.remoteAddress,xdomain:!!((o=this.request)===null||o===void 0?void 0:o.headers.origin),secure:!this.request||!!this.request.connection.encrypted,issued:+new Date,url:(c=this.request)===null||c===void 0?void 0:c.url,query:((p=this.request)===null||p===void 0?void 0:p._query)||{},auth:n}}emit(n,...i){if(yX.RESERVED_EVENTS.has(n))throw new Error(`"${String(n)}" is a reserved event name`);let o=[n,...i],c={type:oo.PacketType.EVENT,data:o};if(typeof o[o.length-1]==="function"){let a=this.nsp._ids++;Wi("emitting packet with ack id %d",a),this.registerAckCallback(a,o.pop()),c.id=a}let p=Object.assign({},this.flags);if(this.flags={},this.nsp.server.opts.connectionStateRecovery)this.adapter.broadcast(c,{rooms:new Set([this.id]),except:new Set,flags:p});else this.notifyOutgoingListeners(c),this.packet(c,p);return!0}emitWithAck(n,...i){let o=this.flags.timeout!==void 0;return new Promise((c,p)=>{i.push((a,x)=>{if(o)return a?p(a):c(x);else return c(a)}),this.emit(n,...i)})}registerAckCallback(n,i){let o=this.flags.timeout;if(o===void 0){this.acks.set(n,i);return}let c=setTimeout(()=>{Wi("event with ack id %d has timed out after %d ms",n,o),this.acks.delete(n),i.call(this,new Error("operation has timed out"))},o);this.acks.set(n,(...p)=>{clearTimeout(c),i.apply(this,[null,...p])})}to(n){return this.newBroadcastOperator().to(n)}in(n){return this.newBroadcastOperator().in(n)}except(n){return this.newBroadcastOperator().except(n)}send(...n){return this.emit("message",...n),this}write(...n){return this.emit("message",...n),this}packet(n,i={}){n.nsp=this.nsp.name,i.compress=i.compress!==!1,this.client._packet(n,i)}join(n){return Wi("join room %s",n),this.adapter.addAll(this.id,new Set(Array.isArray(n)?n:[n]))}leave(n){return Wi("leave room %s",n),this.adapter.del(this.id,n)}leaveAll(){this.adapter.delAll(this.id)}_onconnect(){if(Wi("socket connected - writing packet"),this.connected=!0,this.join(this.id),this.conn.protocol===3)this.packet({type:oo.PacketType.CONNECT});else this.packet({type:oo.PacketType.CONNECT,data:{sid:this.id,pid:this.pid}})}_onpacket(n){switch(Wi("got packet %j",n),n.type){case oo.PacketType.EVENT:this.onevent(n);break;case oo.PacketType.BINARY_EVENT:this.onevent(n);break;case oo.PacketType.ACK:this.onack(n);break;case oo.PacketType.BINARY_ACK:this.onack(n);break;case oo.PacketType.DISCONNECT:this.ondisconnect();break}}onevent(n){let i=n.data||[];if(Wi("emitting event %j",i),n.id!=null)Wi("attaching ack callback to event"),i.push(this.ack(n.id));if(this._anyListeners&&this._anyListeners.length){let o=this._anyListeners.slice();for(let c of o)c.apply(this,i)}this.dispatch(i)}ack(n){let i=this,o=!1;return function(){if(o)return;let c=Array.prototype.slice.call(arguments);Wi("sending ack %j",c),i.packet({id:n,type:oo.PacketType.ACK,data:c}),o=!0}}onack(n){let i=this.acks.get(n.id);if(typeof i=="function")Wi("calling ack %s with %j",n.id,n.data),i.apply(this,n.data),this.acks.delete(n.id);else Wi("bad ack %s",n.id)}ondisconnect(){Wi("got disconnect packet"),this._onclose("client namespace disconnect")}_onerror(n){this.emitReserved("error",n)}_onclose(n,i){if(!this.connected)return this;if(Wi("closing socket - reason %s",n),this.emitReserved("disconnecting",n,i),this.server._opts.connectionStateRecovery&&BX.has(n))Wi("connection state recovery is enabled for sid %s",this.id),this.adapter.persistSession({sid:this.id,pid:this.pid,rooms:[...this.rooms],data:this.data});this._cleanup(),this.client._remove(this),this.connected=!1,this.emitReserved("disconnect",n,i);return}_cleanup(){this.leaveAll(),this.nsp._remove(this),this.join=fM}_error(n){this.packet({type:oo.PacketType.CONNECT_ERROR,data:n})}disconnect(n=!1){if(!this.connected)return this;if(n)this.client._disconnect();else this.packet({type:oo.PacketType.DISCONNECT}),this._onclose("server namespace disconnect");return this}compress(n){return this.flags.compress=n,this}get volatile(){return this.flags.volatile=!0,this}get broadcast(){return this.newBroadcastOperator()}get local(){return this.newBroadcastOperator().local}timeout(n){return this.flags.timeout=n,this}dispatch(n){Wi("dispatching an event %j",n),this.run(n,(i)=>{process.nextTick(()=>{if(i)return this._onerror(i);if(this.connected)super.emitUntyped.apply(this,n);else Wi("ignore packet received after disconnection")})})}use(n){return this.fns.push(n),this}run(n,i){if(!this.fns.length)return i();let o=this.fns.slice(0);function c(p){o[p](n,(a)=>{if(a)return i(a);if(!o[p+1])return i();c(p+1)})}c(0)}get disconnected(){return!this.connected}get request(){return this.client.request}get conn(){return this.client.conn}get rooms(){return this.adapter.socketRooms(this.id)||new Set}onAny(n){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(n),this}prependAny(n){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(n),this}offAny(n){if(!this._anyListeners)return this;if(n){let i=this._anyListeners;for(let o=0;o<i.length;o++)if(n===i[o])return i.splice(o,1),this}else this._anyListeners=[];return this}listenersAny(){return this._anyListeners||[]}onAnyOutgoing(n){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.push(n),this}prependAnyOutgoing(n){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.unshift(n),this}offAnyOutgoing(n){if(!this._anyOutgoingListeners)return this;if(n){let i=this._anyOutgoingListeners;for(let o=0;o<i.length;o++)if(n===i[o])return i.splice(o,1),this}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(n){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length){let i=this._anyOutgoingListeners.slice();for(let o of i)o.apply(this,n.data)}}newBroadcastOperator(){let n=Object.assign({},this.flags);return this.flags={},new jX.BroadcastOperator(this.adapter,new Set,new Set([this.id]),n)}}Hp.Socket=$M});var Sv=h((Do)=>{var LX=Do&&Do.__importDefault||function(n){return n&&n.__esModule?n:{default:n}};Object.defineProperty(Do,"__esModule",{value:!0});Do.Namespace=Do.RESERVED_EVENTS=void 0;var TM=Jv(),NX=Qm(),DX=LX(xi()),hi=wv(),Ba=DX.default("socket.io:namespace");Do.RESERVED_EVENTS=new Set(["connect","connection","new_namespace"]);class wM extends NX.StrictEventEmitter{constructor(n,i){super();this.sockets=new Map,this._preConnectSockets=new Map,this._fns=[],this._ids=0,this.server=n,this.name=i,this._initAdapter()}_initAdapter(){this.adapter=new(this.server.adapter())(this)}use(n){return this._fns.push(n),this}run(n,i){if(!this._fns.length)return i();let o=this._fns.slice(0);function c(p){o[p](n,(a)=>{if(a)return i(a);if(!o[p+1])return i();c(p+1)})}c(0)}to(n){return new hi.BroadcastOperator(this.adapter).to(n)}in(n){return new hi.BroadcastOperator(this.adapter).in(n)}except(n){return new hi.BroadcastOperator(this.adapter).except(n)}async _add(n,i,o){var c;Ba("adding socket to nsp %s",this.name);let p=await this._createSocket(n,i);if(this._preConnectSockets.set(p.id,p),((c=this.server.opts.connectionStateRecovery)===null||c===void 0?void 0:c.skipMiddlewares)&&p.recovered&&n.conn.readyState==="open")return this._doConnect(p,o);this.run(p,(a)=>{process.nextTick(()=>{if(n.conn.readyState!=="open"){Ba("next called after client was closed - ignoring socket"),p._cleanup();return}if(a)if(Ba("middleware error, sending CONNECT_ERROR packet to the client"),p._cleanup(),n.conn.protocol===3)return p._error(a.data||a.message);else return p._error({message:a.message,data:a.data});this._doConnect(p,o)})})}async _createSocket(n,i){let{pid:o,offset:c}=i;if(this.server.opts.connectionStateRecovery&&typeof o==="string"&&typeof c==="string"){let p;try{p=await this.adapter.restoreSession(o,c)}catch(a){Ba("error while restoring session: %s",a)}if(p)return Ba("connection state recovered for sid %s",p.sid),new TM.Socket(this,n,i,p)}return new TM.Socket(this,n,i)}_doConnect(n,i){if(this._preConnectSockets.delete(n.id),this.sockets.set(n.id,n),n._onconnect(),i)i(n);this.emitReserved("connect",n),this.emitReserved("connection",n)}_remove(n){this.sockets.delete(n.id)||this._preConnectSockets.delete(n.id)}emit(n,...i){return new hi.BroadcastOperator(this.adapter).emit(n,...i)}send(...n){return this.emit("message",...n),this}write(...n){return this.emit("message",...n),this}serverSideEmit(n,...i){if(Do.RESERVED_EVENTS.has(n))throw new Error(`"${String(n)}" is a reserved event name`);return i.unshift(n),this.adapter.serverSideEmit(i),!0}serverSideEmitWithAck(n,...i){return new Promise((o,c)=>{i.push((p,a)=>{if(p)return p.responses=a,c(p);else return o(a)}),this.serverSideEmit(n,...i)})}_onServerSideEmit(n){super.emitUntyped.apply(this,n)}allSockets(){return new hi.BroadcastOperator(this.adapter).allSockets()}compress(n){return new hi.BroadcastOperator(this.adapter).compress(n)}get volatile(){return new hi.BroadcastOperator(this.adapter).volatile}get local(){return new hi.BroadcastOperator(this.adapter).local}timeout(n){return new hi.BroadcastOperator(this.adapter).timeout(n)}fetchSockets(){return new hi.BroadcastOperator(this.adapter).fetchSockets()}socketsJoin(n){return new hi.BroadcastOperator(this.adapter).socketsJoin(n)}socketsLeave(n){return new hi.BroadcastOperator(this.adapter).socketsLeave(n)}disconnectSockets(n=!1){return new hi.BroadcastOperator(this.adapter).disconnectSockets(n)}}Do.Namespace=wM});var WM=h((MM)=>{Object.defineProperty(MM,"__esModule",{value:!0});MM.yeast=MM.decode=MM.encode=void 0;var AM="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_".split(""),Hm=64,FM={},JM=0,$c=0,SM;function Av(n){let i="";do i=AM[n%Hm]+i,n=Math.floor(n/Hm);while(n>0);return i}MM.encode=Av;function CX(n){let i=0;for($c=0;$c<n.length;$c++)i=i*Hm+FM[n.charAt($c)];return i}MM.decode=CX;function hX(){let n=Av(+new Date);if(n!==SM)return JM=0,SM=n;return n+"."+Av(JM++)}MM.yeast=hX;for(;$c<Hm;$c++)FM[AM[$c]]=$c});var Rv=h((XM)=>{var Fv;Object.defineProperty(XM,"__esModule",{value:!0});XM.SessionAwareAdapter=XM.Adapter=void 0;var sX=import.meta.require("events"),ZX=WM(),Em=import.meta.require("ws"),tX=typeof((Fv=Em===null||Em===void 0?void 0:Em.Sender)===null||Fv===void 0?void 0:Fv.frame)==="function";class Mv extends sX.EventEmitter{constructor(n){super();this.nsp=n,this.rooms=new Map,this.sids=new Map,this.encoder=n.server.encoder}init(){}close(){}serverCount(){return Promise.resolve(1)}addAll(n,i){if(!this.sids.has(n))this.sids.set(n,new Set);for(let o of i){if(this.sids.get(n).add(o),!this.rooms.has(o))this.rooms.set(o,new Set),this.emit("create-room",o);if(!this.rooms.get(o).has(n))this.rooms.get(o).add(n),this.emit("join-room",o,n)}}del(n,i){if(this.sids.has(n))this.sids.get(n).delete(i);this._del(i,n)}_del(n,i){let o=this.rooms.get(n);if(o!=null){if(o.delete(i))this.emit("leave-room",n,i);if(o.size===0&&this.rooms.delete(n))this.emit("delete-room",n)}}delAll(n){if(!this.sids.has(n))return;for(let i of this.sids.get(n))this._del(i,n);this.sids.delete(n)}broadcast(n,i){let o=i.flags||{},c={preEncoded:!0,volatile:o.volatile,compress:o.compress};n.nsp=this.nsp.name;let p=this._encode(n,c);this.apply(i,(a)=>{if(typeof a.notifyOutgoingListeners==="function")a.notifyOutgoingListeners(n);a.client.writeToEngine(p,c)})}broadcastWithAck(n,i,o,c){let p=i.flags||{},a={preEncoded:!0,volatile:p.volatile,compress:p.compress};n.nsp=this.nsp.name,n.id=this.nsp._ids++;let x=this._encode(n,a),m=0;this.apply(i,(l)=>{if(m++,l.acks.set(n.id,c),typeof l.notifyOutgoingListeners==="function")l.notifyOutgoingListeners(n);l.client.writeToEngine(x,a)}),o(m)}_encode(n,i){let o=this.encoder.encode(n);if(tX&&o.length===1&&typeof o[0]==="string"){let c=Buffer.from("4"+o[0]);i.wsPreEncodedFrame=Em.Sender.frame(c,{readOnly:!1,mask:!1,rsv1:!1,opcode:1,fin:!0})}return o}sockets(n){let i=new Set;return this.apply({rooms:n},(o)=>{i.add(o.id)}),Promise.resolve(i)}socketRooms(n){return this.sids.get(n)}fetchSockets(n){let i=[];return this.apply(n,(o)=>{i.push(o)}),Promise.resolve(i)}addSockets(n,i){this.apply(n,(o)=>{o.join(i)})}delSockets(n,i){this.apply(n,(o)=>{i.forEach((c)=>o.leave(c))})}disconnectSockets(n,i){this.apply(n,(o)=>{o.disconnect(i)})}apply(n,i){let o=n.rooms,c=this.computeExceptSids(n.except);if(o.size){let p=new Set;for(let a of o){if(!this.rooms.has(a))continue;for(let x of this.rooms.get(a)){if(p.has(x)||c.has(x))continue;let m=this.nsp.sockets.get(x);if(m)i(m),p.add(x)}}}else for(let[p]of this.sids){if(c.has(p))continue;let a=this.nsp.sockets.get(p);if(a)i(a)}}computeExceptSids(n){let i=new Set;if(n&&n.size>0){for(let o of n)if(this.rooms.has(o))this.rooms.get(o).forEach((c)=>i.add(c))}return i}serverSideEmit(n){console.warn("this adapter does not support the serverSideEmit() functionality")}persistSession(n){}restoreSession(n,i){return null}}XM.Adapter=Mv;class KM extends Mv{constructor(n){super(n);this.nsp=n,this.sessions=new Map,this.packets=[],this.maxDisconnectionDuration=n.server.opts.connectionStateRecovery.maxDisconnectionDuration,setInterval(()=>{let o=Date.now()-this.maxDisconnectionDuration;this.sessions.forEach((c,p)=>{if(c.disconnectedAt<o)this.sessions.delete(p)});for(let c=this.packets.length-1;c>=0;c--)if(this.packets[c].emittedAt<o){this.packets.splice(0,c+1);break}},60000).unref()}persistSession(n){n.disconnectedAt=Date.now(),this.sessions.set(n.pid,n)}restoreSession(n,i){let o=this.sessions.get(n);if(!o)return null;if(o.disconnectedAt+this.maxDisconnectionDuration<Date.now())return this.sessions.delete(n),null;let p=this.packets.findIndex((x)=>x.id===i);if(p===-1)return null;let a=[];for(let x=p+1;x<this.packets.length;x++){let m=this.packets[x];if(qX(o.rooms,m.opts))a.push(m.data)}return Promise.resolve(Object.assign(Object.assign({},o),{missedPackets:a}))}broadcast(n,i){var o;let c=n.type===2,p=n.id===void 0,a=((o=i.flags)===null||o===void 0?void 0:o.volatile)===void 0;if(c&&p&&a){let x=ZX.yeast();n.data.push(x),this.packets.push({id:x,opts:i,data:n.data,emittedAt:Date.now()})}super.broadcast(n,i)}}XM.SessionAwareAdapter=KM;function qX(n,i){let o=i.rooms.size===0||n.some((p)=>i.rooms.has(p)),c=n.every((p)=>!i.except.has(p));return o&&c}});var zM=h((Fo)=>{var rX=Fo&&Fo.__rest||function(n,i){var o={};for(var c in n)if(Object.prototype.hasOwnProperty.call(n,c)&&i.indexOf(c)<0)o[c]=n[c];if(n!=null&&typeof Object.getOwnPropertySymbols==="function"){for(var p=0,c=Object.getOwnPropertySymbols(n);p<c.length;p++)if(i.indexOf(c[p])<0&&Object.prototype.propertyIsEnumerable.call(n,c[p]))o[c[p]]=n[c[p]]}return o};Object.defineProperty(Fo,"__esModule",{value:!0});Fo.ClusterAdapterWithHeartbeat=Fo.ClusterAdapter=Fo.MessageType=void 0;var gX=Rv(),dX=xi(),eX=import.meta.require("crypto"),Pn=dX.debug("socket.io-adapter"),n5="emitter",Om=5000;function Op(){return eX.randomBytes(8).toString("hex")}var an;(function(n){n[n.INITIAL_HEARTBEAT=1]="INITIAL_HEARTBEAT",n[n.HEARTBEAT=2]="HEARTBEAT",n[n.BROADCAST=3]="BROADCAST",n[n.SOCKETS_JOIN=4]="SOCKETS_JOIN",n[n.SOCKETS_LEAVE=5]="SOCKETS_LEAVE",n[n.DISCONNECT_SOCKETS=6]="DISCONNECT_SOCKETS",n[n.FETCH_SOCKETS=7]="FETCH_SOCKETS",n[n.FETCH_SOCKETS_RESPONSE=8]="FETCH_SOCKETS_RESPONSE",n[n.SERVER_SIDE_EMIT=9]="SERVER_SIDE_EMIT",n[n.SERVER_SIDE_EMIT_RESPONSE=10]="SERVER_SIDE_EMIT_RESPONSE",n[n.BROADCAST_CLIENT_COUNT=11]="BROADCAST_CLIENT_COUNT",n[n.BROADCAST_ACK=12]="BROADCAST_ACK",n[n.ADAPTER_CLOSE=13]="ADAPTER_CLOSE"})(an=Fo.MessageType||(Fo.MessageType={}));function jc(n){return{rooms:[...n.rooms],except:[...n.except],flags:n.flags}}function Ep(n){return{rooms:new Set(n.rooms),except:new Set(n.except),flags:n.flags}}class Wv extends gX.Adapter{constructor(n){super(n);this.requests=new Map,this.ackRequests=new Map,this.uid=Op()}onMessage(n,i){if(n.uid===this.uid)return Pn("[%s] ignore message from self",this.uid);switch(Pn("[%s] new event of type %d from %s",this.uid,n.type,n.uid),n.type){case an.BROADCAST:{if(n.data.requestId!==void 0)super.broadcastWithAck(n.data.packet,Ep(n.data.opts),(c)=>{Pn("[%s] waiting for %d client acknowledgements",this.uid,c),this.publishResponse(n.uid,{type:an.BROADCAST_CLIENT_COUNT,data:{requestId:n.data.requestId,clientCount:c}})},(c)=>{Pn("[%s] received acknowledgement with value %j",this.uid,c),this.publishResponse(n.uid,{type:an.BROADCAST_ACK,data:{requestId:n.data.requestId,packet:c}})});else{let c=n.data.packet,p=Ep(n.data.opts);this.addOffsetIfNecessary(c,p,i),super.broadcast(c,p)}break}case an.SOCKETS_JOIN:super.addSockets(Ep(n.data.opts),n.data.rooms);break;case an.SOCKETS_LEAVE:super.delSockets(Ep(n.data.opts),n.data.rooms);break;case an.DISCONNECT_SOCKETS:super.disconnectSockets(Ep(n.data.opts),n.data.close);break;case an.FETCH_SOCKETS:{Pn("[%s] calling fetchSockets with opts %j",this.uid,n.data.opts),super.fetchSockets(Ep(n.data.opts)).then((o)=>{this.publishResponse(n.uid,{type:an.FETCH_SOCKETS_RESPONSE,data:{requestId:n.data.requestId,sockets:o.map((c)=>{let p=c.handshake,{sessionStore:a}=p,x=rX(p,["sessionStore"]);return{id:c.id,handshake:x,rooms:[...c.rooms],data:c.data}})}})});break}case an.SERVER_SIDE_EMIT:{let o=n.data.packet;if(n.data.requestId===void 0){this.nsp._onServerSideEmit(o);return}let p=!1,a=(x)=>{if(p)return;p=!0,Pn("[%s] calling acknowledgement with %j",this.uid,x),this.publishResponse(n.uid,{type:an.SERVER_SIDE_EMIT_RESPONSE,data:{requestId:n.data.requestId,packet:x}})};this.nsp._onServerSideEmit([...o,a]);break}case an.BROADCAST_CLIENT_COUNT:case an.BROADCAST_ACK:case an.FETCH_SOCKETS_RESPONSE:case an.SERVER_SIDE_EMIT_RESPONSE:this.onResponse(n);break;default:Pn("[%s] unknown message type: %s",this.uid,n.type)}}onResponse(n){var i,o;let c=n.data.requestId;switch(Pn("[%s] received response %s to request %s",this.uid,n.type,c),n.type){case an.BROADCAST_CLIENT_COUNT:{(i=this.ackRequests.get(c))===null||i===void 0||i.clientCountCallback(n.data.clientCount);break}case an.BROADCAST_ACK:{(o=this.ackRequests.get(c))===null||o===void 0||o.ack(n.data.packet);break}case an.FETCH_SOCKETS_RESPONSE:{let p=this.requests.get(c);if(!p)return;if(p.current++,n.data.sockets.forEach((a)=>p.responses.push(a)),p.current===p.expected)clearTimeout(p.timeout),p.resolve(p.responses),this.requests.delete(c);break}case an.SERVER_SIDE_EMIT_RESPONSE:{let p=this.requests.get(c);if(!p)return;if(p.current++,p.responses.push(n.data.packet),p.current===p.expected)clearTimeout(p.timeout),p.resolve(null,p.responses),this.requests.delete(c);break}default:Pn("[%s] unknown response type: %s",this.uid,n.type)}}async broadcast(n,i){var o;if(!((o=i.flags)===null||o===void 0?void 0:o.local))try{let p=await this.publishAndReturnOffset({type:an.BROADCAST,data:{packet:n,opts:jc(i)}});this.addOffsetIfNecessary(n,i,p)}catch(p){return Pn("[%s] error while broadcasting message: %s",this.uid,p.message)}super.broadcast(n,i)}addOffsetIfNecessary(n,i,o){var c;if(!this.nsp.server.opts.connectionStateRecovery)return;let p=n.type===2,a=n.id===void 0,x=((c=i.flags)===null||c===void 0?void 0:c.volatile)===void 0;if(p&&a&&x)n.data.push(o)}broadcastWithAck(n,i,o,c){var p;if(!((p=i===null||i===void 0?void 0:i.flags)===null||p===void 0?void 0:p.local)){let x=Op();this.ackRequests.set(x,{clientCountCallback:o,ack:c}),this.publish({type:an.BROADCAST,data:{packet:n,requestId:x,opts:jc(i)}}),setTimeout(()=>{this.ackRequests.delete(x)},i.flags.timeout)}super.broadcastWithAck(n,i,o,c)}async addSockets(n,i){var o;if(!((o=n.flags)===null||o===void 0?void 0:o.local))try{await this.publishAndReturnOffset({type:an.SOCKETS_JOIN,data:{opts:jc(n),rooms:i}})}catch(p){Pn("[%s] error while publishing message: %s",this.uid,p.message)}super.addSockets(n,i)}async delSockets(n,i){var o;if(!((o=n.flags)===null||o===void 0?void 0:o.local))try{await this.publishAndReturnOffset({type:an.SOCKETS_LEAVE,data:{opts:jc(n),rooms:i}})}catch(p){Pn("[%s] error while publishing message: %s",this.uid,p.message)}super.delSockets(n,i)}async disconnectSockets(n,i){var o;if(!((o=n.flags)===null||o===void 0?void 0:o.local))try{await this.publishAndReturnOffset({type:an.DISCONNECT_SOCKETS,data:{opts:jc(n),close:i}})}catch(p){Pn("[%s] error while publishing message: %s",this.uid,p.message)}super.disconnectSockets(n,i)}async fetchSockets(n){var i;let[o,c]=await Promise.all([super.fetchSockets(n),this.serverCount()]),p=c-1;if(((i=n.flags)===null||i===void 0?void 0:i.local)||p<=0)return o;let a=Op();return new Promise((x,m)=>{let l=setTimeout(()=>{let v=this.requests.get(a);if(v)m(new Error(`timeout reached: only ${v.current} responses received out of ${v.expected}`)),this.requests.delete(a)},n.flags.timeout||Om),f={type:an.FETCH_SOCKETS,resolve:x,timeout:l,current:0,expected:p,responses:o};this.requests.set(a,f),this.publish({type:an.FETCH_SOCKETS,data:{opts:jc(n),requestId:a}})})}async serverSideEmit(n){if(typeof n[n.length-1]!=="function")return this.publish({type:an.SERVER_SIDE_EMIT,data:{packet:n}});let o=n.pop(),c=await this.serverCount()-1;if(Pn('[%s] waiting for %d responses to "serverSideEmit" request',this.uid,c),c<=0)return o(null,[]);let p=Op(),a=setTimeout(()=>{let m=this.requests.get(p);if(m)o(new Error(`timeout reached: only ${m.current} responses received out of ${m.expected}`),m.responses),this.requests.delete(p)},Om),x={type:an.SERVER_SIDE_EMIT,resolve:o,timeout:a,current:0,expected:c,responses:[]};this.requests.set(p,x),this.publish({type:an.SERVER_SIDE_EMIT,data:{requestId:p,packet:n}})}publish(n){this.publishAndReturnOffset(n).catch((i)=>{Pn("[%s] error while publishing message: %s",this.uid,i)})}publishAndReturnOffset(n){return n.uid=this.uid,n.nsp=this.nsp.name,this.doPublish(n)}publishResponse(n,i){i.uid=this.uid,i.nsp=this.nsp.name,this.doPublishResponse(n,i).catch((o)=>{Pn("[%s] error while publishing response: %s",this.uid,o)})}}Fo.ClusterAdapter=Wv;class YM extends Wv{constructor(n,i){super(n);this.nodesMap=new Map,this.customRequests=new Map,this._opts=Object.assign({heartbeatInterval:5000,heartbeatTimeout:1e4},i),this.cleanupTimer=setInterval(()=>{let o=Date.now();this.nodesMap.forEach((c,p)=>{if(o-c>this._opts.heartbeatTimeout)Pn("[%s] node %s seems down",this.uid,p),this.removeNode(p)})},1000)}init(){this.publish({type:an.INITIAL_HEARTBEAT})}scheduleHeartbeat(){if(this.heartbeatTimer)this.heartbeatTimer.refresh();else this.heartbeatTimer=setTimeout(()=>{this.publish({type:an.HEARTBEAT})},this._opts.heartbeatInterval)}close(){if(this.publish({type:an.ADAPTER_CLOSE}),clearTimeout(this.heartbeatTimer),this.cleanupTimer)clearInterval(this.cleanupTimer)}onMessage(n,i){if(n.uid===this.uid)return Pn("[%s] ignore message from self",this.uid);if(n.uid&&n.uid!==n5)this.nodesMap.set(n.uid,Date.now());switch(Pn("[%s] new event of type %d from %s",this.uid,n.type,n.uid),n.type){case an.INITIAL_HEARTBEAT:this.publish({type:an.HEARTBEAT});break;case an.HEARTBEAT:break;case an.ADAPTER_CLOSE:this.removeNode(n.uid);break;default:super.onMessage(n,i)}}serverCount(){return Promise.resolve(1+this.nodesMap.size)}publish(n){return this.scheduleHeartbeat(),super.publish(n)}async serverSideEmit(n){if(typeof n[n.length-1]!=="function")return this.publish({type:an.SERVER_SIDE_EMIT,data:{packet:n}});let o=n.pop(),c=this.nodesMap.size;if(Pn('[%s] waiting for %d responses to "serverSideEmit" request',this.uid,c),c<=0)return o(null,[]);let p=Op(),a=setTimeout(()=>{let m=this.customRequests.get(p);if(m)o(new Error(`timeout reached: missing ${m.missingUids.size} responses`),m.responses),this.customRequests.delete(p)},Om),x={type:an.SERVER_SIDE_EMIT,resolve:o,timeout:a,missingUids:new Set([...this.nodesMap.keys()]),responses:[]};this.customRequests.set(p,x),this.publish({type:an.SERVER_SIDE_EMIT,data:{requestId:p,packet:n}})}async fetchSockets(n){var i;let[o,c]=await Promise.all([super.fetchSockets({rooms:n.rooms,except:n.except,flags:{local:!0}}),this.serverCount()]),p=c-1;if(((i=n.flags)===null||i===void 0?void 0:i.local)||p<=0)return o;let a=Op();return new Promise((x,m)=>{let l=setTimeout(()=>{let v=this.customRequests.get(a);if(v)m(new Error(`timeout reached: missing ${v.missingUids.size} responses`)),this.customRequests.delete(a)},n.flags.timeout||Om),f={type:an.FETCH_SOCKETS,resolve:x,timeout:l,missingUids:new Set([...this.nodesMap.keys()]),responses:o};this.customRequests.set(a,f),this.publish({type:an.FETCH_SOCKETS,data:{opts:jc(n),requestId:a}})})}onResponse(n){let i=n.data.requestId;switch(Pn("[%s] received response %s to request %s",this.uid,n.type,i),n.type){case an.FETCH_SOCKETS_RESPONSE:{let o=this.customRequests.get(i);if(!o)return;if(n.data.sockets.forEach((c)=>o.responses.push(c)),o.missingUids.delete(n.uid),o.missingUids.size===0)clearTimeout(o.timeout),o.resolve(o.responses),this.customRequests.delete(i);break}case an.SERVER_SIDE_EMIT_RESPONSE:{let o=this.customRequests.get(i);if(!o)return;if(o.responses.push(n.data.packet),o.missingUids.delete(n.uid),o.missingUids.size===0)clearTimeout(o.timeout),o.resolve(null,o.responses),this.customRequests.delete(i);break}default:super.onResponse(n)}}removeNode(n){this.customRequests.forEach((i,o)=>{if(i.missingUids.delete(n),i.missingUids.size===0){if(clearTimeout(i.timeout),i.type===an.FETCH_SOCKETS)i.resolve(i.responses);else if(i.type===an.SERVER_SIDE_EMIT)i.resolve(null,i.responses);this.customRequests.delete(o)}}),this.nodesMap.delete(n)}}Fo.ClusterAdapterWithHeartbeat=YM});var Um=h((yc)=>{Object.defineProperty(yc,"__esModule",{value:!0});yc.MessageType=yc.ClusterAdapterWithHeartbeat=yc.ClusterAdapter=yc.SessionAwareAdapter=yc.Adapter=void 0;var QM=Rv();Object.defineProperty(yc,"Adapter",{enumerable:!0,get:function(){return QM.Adapter}});Object.defineProperty(yc,"SessionAwareAdapter",{enumerable:!0,get:function(){return QM.SessionAwareAdapter}});var Kv=zM();Object.defineProperty(yc,"ClusterAdapter",{enumerable:!0,get:function(){return Kv.ClusterAdapter}});Object.defineProperty(yc,"ClusterAdapterWithHeartbeat",{enumerable:!0,get:function(){return Kv.ClusterAdapterWithHeartbeat}});Object.defineProperty(yc,"MessageType",{enumerable:!0,get:function(){return Kv.MessageType}})});var UM=h((Up)=>{var o5=Up&&Up.__importDefault||function(n){return n&&n.__esModule?n:{default:n}};Object.defineProperty(Up,"__esModule",{value:!0});Up.ParentNamespace=void 0;var HM=Sv(),c5=Um(),p5=o5(xi()),EM=p5.default("socket.io:parent-namespace");class Vm extends HM.Namespace{constructor(n){super(n,"/_"+Vm.count++);this.children=new Set}_initAdapter(){this.adapter=new OM(this)}emit(n,...i){return this.children.forEach((o)=>{o.emit(n,...i)}),!0}createChild(n){EM("creating child namespace %s",n);let i=new HM.Namespace(this.server,n);if(this._fns.forEach((o)=>i.use(o)),this.listeners("connect").forEach((o)=>i.on("connect",o)),this.listeners("connection").forEach((o)=>i.on("connection",o)),this.children.add(i),this.server._opts.cleanupEmptyChildNamespaces){let o=i._remove;i._remove=(c)=>{if(o.call(i,c),i.sockets.size===0)EM("closing child namespace %s",n),i.adapter.close(),this.server._nsps.delete(i.name),this.children.delete(i)}}return this.server._nsps.set(n,i),this.server.sockets.emitReserved("new_namespace",i),i}fetchSockets(){throw new Error("fetchSockets() is not supported on parent namespaces")}}Up.ParentNamespace=Vm;Vm.count=0;class OM extends c5.Adapter{broadcast(n,i){this.nsp.children.forEach((o)=>{o.adapter.broadcast(n,i)})}}});var yM=h((Lc)=>{var a5=Lc&&Lc.__importDefault||function(n){return n&&n.__esModule?n:{default:n}};Object.defineProperty(Lc,"__esModule",{value:!0});Lc.patchAdapter=m5;Lc.restoreAdapter=l5;Lc.serveFile=v5;var Bc=Um(),VM=import.meta.require("fs"),x5=a5(xi()),um=x5.default("socket.io:adapter-uws"),Xv="\x1F",{addAll:_M,del:bM,broadcast:jM}=Bc.Adapter.prototype;function m5(n){Bc.Adapter.prototype.addAll=function(i,o){let c=!this.sids.has(i);_M.call(this,i,o);let p=this.nsp.sockets.get(i)||this.nsp._preConnectSockets.get(i);if(!p)return;if(p.conn.transport.name==="websocket"){uM(this.nsp.name,p,c,o);return}if(c)p.conn.on("upgrade",()=>{let a=this.sids.get(i);if(a)uM(this.nsp.name,p,c,a)})},Bc.Adapter.prototype.del=function(i,o){bM.call(this,i,o);let c=this.nsp.sockets.get(i)||this.nsp._preConnectSockets.get(i);if(c&&c.conn.transport.name==="websocket"){let p=c.conn.id,a=c.conn.transport.socket,x=`${this.nsp.name}${Xv}${o}`;um("unsubscribe connection %s from topic %s",p,x),a.unsubscribe(x)}},Bc.Adapter.prototype.broadcast=function(i,o){if(!(o.rooms.size<=1&&o.except.size===0)){jM.call(this,i,o);return}let p=o.flags||{},a={preEncoded:!0,volatile:p.volatile,compress:p.compress};i.nsp=this.nsp.name;let x=this.encoder.encode(i),m=o.rooms.size===0?this.nsp.name:`${this.nsp.name}${Xv}${o.rooms.keys().next().value}`;um("fast publish to %s",m),x.forEach((l)=>{let f=typeof l!=="string";n.publish(m,f?l:"4"+l,f)}),this.apply(o,(l)=>{if(l.conn.transport.name!=="websocket")l.client.writeToEngine(x,a)})}}function uM(n,i,o,c){let p=i.conn.id,a=i.conn.transport.socket;if(o)um("subscribe connection %s to topic %s",p,n),a.subscribe(n);c.forEach((x)=>{let m=`${n}${Xv}${x}`;um("subscribe connection %s to topic %s",p,m),a.subscribe(m)})}function l5(){Bc.Adapter.prototype.addAll=_M,Bc.Adapter.prototype.del=bM,Bc.Adapter.prototype.broadcast=jM}var f5=(n)=>{let{buffer:i,byteOffset:o,byteLength:c}=n;return i.slice(o,o+c)};function v5(n,i){let{size:o}=VM.statSync(i),c=VM.createReadStream(i),p=()=>!c.destroyed&&c.destroy(),a=(m)=>{throw p(),m},x=(m)=>{let l=f5(m);n.cork(()=>{let f=n.getWriteOffset(),[v,$]=n.tryEnd(l,o);if(!$&&!v)c.pause(),n.onWritable((T)=>{let[F,M]=n.tryEnd(l.slice(T-f),o);if(!M&&F)c.resume();return F})})};n.onAborted(p),c.on("data",x).on("error",a).on("end",p)}});var BM=h((dL,$5)=>{$5.exports={name:"socket.io",version:"4.8.1",description:"node.js realtime framework server",keywords:["realtime","framework","websocket","tcp","events","socket","io"],files:["dist/","client-dist/","wrapper.mjs","!**/*.tsbuildinfo"],directories:{doc:"docs/",example:"example/",lib:"lib/",test:"test/"},type:"commonjs",main:"./dist/index.js",exports:{types:"./dist/index.d.ts",import:"./wrapper.mjs",require:"./dist/index.js"},types:"./dist/index.d.ts",license:"MIT",homepage:"https://github.com/socketio/socket.io/tree/main/packages/socket.io#readme",repository:{type:"git",url:"git+https://github.com/socketio/socket.io.git"},bugs:{url:"https://github.com/socketio/socket.io/issues"},scripts:{compile:"rimraf ./dist && tsc",test:"npm run format:check && npm run compile && npm run test:types && npm run test:unit","test:types":"tsd","test:unit":"nyc mocha --require ts-node/register --reporter spec --slow 200 --bail --timeout 10000 test/index.ts","format:check":"prettier --check \"lib/**/*.ts\" \"test/**/*.ts\"","format:fix":"prettier --write \"lib/**/*.ts\" \"test/**/*.ts\"",prepack:"npm run compile"},dependencies:{accepts:"~1.3.4",base64id:"~2.0.0",cors:"~2.8.5",debug:"~4.3.2","engine.io":"~6.6.0","socket.io-adapter":"~2.5.2","socket.io-parser":"~4.2.4"},contributors:[{name:"Guillermo Rauch",email:"rauchg@gmail.com"},{name:"Arnout Kazemier",email:"info@3rd-eden.com"},{name:"Vladimir Dronnikov",email:"dronnikov@gmail.com"},{name:"Einar Otto Stangvik",email:"einaros@gmail.com"}],engines:{node:">=10.2.0"},tsd:{directory:"test"}}});var ZM=h((Ki,La)=>{var __dirname="/home/runner/work/wayforge/wayforge/node_modules/.pnpm/socket.io@4.8.1/node_modules/socket.io/dist",T5=Ki&&Ki.__createBinding||(Object.create?function(n,i,o,c){if(c===void 0)c=o;var p=Object.getOwnPropertyDescriptor(i,o);if(!p||("get"in p?!i.__esModule:p.writable||p.configurable))p={enumerable:!0,get:function(){return i[o]}};Object.defineProperty(n,c,p)}:function(n,i,o,c){if(c===void 0)c=o;n[c]=i[o]}),w5=Ki&&Ki.__setModuleDefault||(Object.create?function(n,i){Object.defineProperty(n,"default",{enumerable:!0,value:i})}:function(n,i){n.default=i}),J5=Ki&&Ki.__importStar||function(n){if(n&&n.__esModule)return n;var i={};if(n!=null){for(var o in n)if(o!=="default"&&Object.prototype.hasOwnProperty.call(n,o))T5(i,n,o)}return w5(i,n),i},kM=Ki&&Ki.__importDefault||function(n){return n&&n.__esModule?n:{default:n}};Object.defineProperty(Ki,"__esModule",{value:!0});Ki.Namespace=Ki.Socket=Ki.Server=void 0;var S5=import.meta.require("http"),A5=import.meta.require("fs"),Gv=import.meta.require("zlib"),F5=fm(),_m=import.meta.require("stream"),LM=import.meta.require("path"),NM=bF(),M5=nM(),DM=import.meta.require("events"),zv=Sv();Object.defineProperty(Ki,"Namespace",{enumerable:!0,get:function(){return zv.Namespace}});var R5=UM(),CM=Um(),W5=J5(ya()),K5=kM(xi()),sM=Jv();Object.defineProperty(Ki,"Socket",{enumerable:!0,get:function(){return sM.Socket}});var X5=Qm(),Yv=yM(),G5=kM(pv()),_i=K5.default("socket.io:server"),hM=BM().version,IM=/\.map/;class Vp extends X5.StrictEventEmitter{constructor(n,i={}){super();if(this._nsps=new Map,this.parentNsps=new Map,this.parentNamespacesFromRegExp=new Map,typeof n==="object"&&n instanceof Object&&!n.listen)i=n,n=void 0;if(this.path(i.path||"/socket.io"),this.connectTimeout(i.connectTimeout||45000),this.serveClient(i.serveClient!==!1),this._parser=i.parser||W5,this.encoder=new this._parser.Encoder,this.opts=i,i.connectionStateRecovery)i.connectionStateRecovery=Object.assign({maxDisconnectionDuration:120000,skipMiddlewares:!0},i.connectionStateRecovery),this.adapter(i.adapter||CM.SessionAwareAdapter);else this.adapter(i.adapter||CM.Adapter);if(i.cleanupEmptyChildNamespaces=!!i.cleanupEmptyChildNamespaces,this.sockets=this.of("/"),n||typeof n=="number")this.attach(n);if(this.opts.cors)this._corsMiddleware=G5.default(this.opts.cors)}get _opts(){return this.opts}serveClient(n){if(!arguments.length)return this._serveClient;return this._serveClient=n,this}_checkNamespace(n,i,o){if(this.parentNsps.size===0)return o(!1);let c=this.parentNsps.keys(),p=()=>{let a=c.next();if(a.done)return o(!1);a.value(n,i,(x,m)=>{if(x||!m)return p();if(this._nsps.has(n))return _i("dynamic namespace %s already exists",n),o(this._nsps.get(n));let l=this.parentNsps.get(a.value).createChild(n);_i("dynamic namespace %s was created",n),o(l)})};p()}path(n){if(!arguments.length)return this._path;this._path=n.replace(/\/$/,"");let i=this._path.replace(/[-\/\\^$*+?.()|[\]{}]/g,"\\$&");return this.clientPathRegex=new RegExp("^"+i+"/socket\\.io(\\.msgpack|\\.esm)?(\\.min)?\\.js(\\.map)?(?:\\?|$)"),this}connectTimeout(n){if(n===void 0)return this._connectTimeout;return this._connectTimeout=n,this}adapter(n){if(!arguments.length)return this._adapter;this._adapter=n;for(let i of this._nsps.values())i._initAdapter();return this}listen(n,i={}){return this.attach(n,i)}attach(n,i={}){if(typeof n=="function")throw new Error("You are trying to attach socket.io to an express request handler function. Please pass a http.Server instance.");if(Number(n)==n)n=Number(n);if(typeof n=="number"){_i("creating http server and binding to %d",n);let o=n;n=S5.createServer((c,p)=>{p.writeHead(404),p.end()}),n.listen(o)}return Object.assign(i,this.opts),i.path=i.path||this._path,this.initEngine(n,i),this}attachApp(n,i={}){Object.assign(i,this.opts),i.path=i.path||this._path,_i("creating uWebSockets.js-based engine with opts %j",i);let o=new NM.uServer(i);if(o.attach(n,i),this.bind(o),this._serveClient)n.get(`${this._path}/*`,(c,p)=>{if(!this.clientPathRegex.test(p.getUrl())){p.setYield(!0);return}let a=p.getUrl().replace(this._path,"").replace(/\?.*$/,"").replace(/^\//,""),x=IM.test(a),m=x?"map":"source",l='"'+hM+'"',f="W/"+l,v=p.getHeader("if-none-match");if(v){if(l===v||f===v){_i("serve client %s 304",m),c.writeStatus("304 Not Modified"),c.end();return}}_i("serve client %s",m),c.writeHeader("cache-control","public, max-age=0"),c.writeHeader("content-type","application/"+(x?"json":"javascript")+"; charset=utf-8"),c.writeHeader("etag",l);let $=LM.join(__dirname,"../client-dist/",a);Yv.serveFile(c,$)});Yv.patchAdapter(n)}initEngine(n,i){if(_i("creating engine.io instance with opts %j",i),this.eio=NM.attach(n,i),this._serveClient)this.attachServe(n);this.httpServer=n,this.bind(this.eio)}attachServe(n){_i("attaching client serving req handler");let i=n.listeners("request").slice(0);n.removeAllListeners("request"),n.on("request",(o,c)=>{if(this.clientPathRegex.test(o.url))if(this._corsMiddleware)this._corsMiddleware(o,c,()=>{this.serve(o,c)});else this.serve(o,c);else for(let p=0;p<i.length;p++)i[p].call(n,o,c)})}serve(n,i){let o=n.url.replace(this._path,"").replace(/\?.*$/,""),c=IM.test(o),p=c?"map":"source",a='"'+hM+'"',x="W/"+a,m=n.headers["if-none-match"];if(m){if(a===m||x===m){_i("serve client %s 304",p),i.writeHead(304),i.end();return}}_i("serve client %s",p),i.setHeader("Cache-Control","public, max-age=0"),i.setHeader("Content-Type","application/"+(c?"json":"javascript")+"; charset=utf-8"),i.setHeader("ETag",a),Vp.sendFile(o,n,i)}static sendFile(n,i,o){let c=A5.createReadStream(LM.join(__dirname,"../client-dist/",n)),p=F5(i).encodings(["br","gzip","deflate"]),a=(x)=>{if(x)o.end()};switch(p){case"br":o.writeHead(200,{"content-encoding":"br"}),_m.pipeline(c,Gv.createBrotliCompress(),o,a);break;case"gzip":o.writeHead(200,{"content-encoding":"gzip"}),_m.pipeline(c,Gv.createGzip(),o,a);break;case"deflate":o.writeHead(200,{"content-encoding":"deflate"}),_m.pipeline(c,Gv.createDeflate(),o,a);break;default:o.writeHead(200),_m.pipeline(c,o,a)}}bind(n){return this.engine=n,this.engine.on("connection",this.onconnection.bind(this)),this}onconnection(n){_i("incoming connection with id %s",n.id);let i=new M5.Client(this,n);if(n.protocol===3)i.connect("/");return this}of(n,i){if(typeof n==="function"||n instanceof RegExp){let c=new R5.ParentNamespace(this);if(_i("initializing parent namespace %s",c.name),typeof n==="function")this.parentNsps.set(n,c);else this.parentNsps.set((p,a,x)=>x(null,n.test(p)),c),this.parentNamespacesFromRegExp.set(n,c);if(i)c.on("connect",i);return c}if(String(n)[0]!=="/")n="/"+n;let o=this._nsps.get(n);if(!o){for(let[c,p]of this.parentNamespacesFromRegExp)if(c.test(n))return _i("attaching namespace %s to parent namespace %s",n,c),p.createChild(n);if(_i("initializing namespace %s",n),o=new zv.Namespace(this,n),this._nsps.set(n,o),n!=="/")this.sockets.emitReserved("new_namespace",o)}if(i)o.on("connect",i);return o}async close(n){if(await Promise.allSettled([...this._nsps.values()].map(async(i)=>{i.sockets.forEach((o)=>{o._onclose("server shutting down")}),await i.adapter.close()})),this.engine.close(),Yv.restoreAdapter(),this.httpServer)this.httpServer.close(n);else n&&n()}use(n){return this.sockets.use(n),this}to(n){return this.sockets.to(n)}in(n){return this.sockets.in(n)}except(n){return this.sockets.except(n)}send(...n){return this.sockets.emit("message",...n),this}write(...n){return this.sockets.emit("message",...n),this}serverSideEmit(n,...i){return this.sockets.serverSideEmit(n,...i)}serverSideEmitWithAck(n,...i){return this.sockets.serverSideEmitWithAck(n,...i)}allSockets(){return this.sockets.allSockets()}compress(n){return this.sockets.compress(n)}get volatile(){return this.sockets.volatile}get local(){return this.sockets.local}timeout(n){return this.sockets.timeout(n)}fetchSockets(){return this.sockets.fetchSockets()}socketsJoin(n){return this.sockets.socketsJoin(n)}socketsLeave(n){return this.sockets.socketsLeave(n)}disconnectSockets(n=!1){return this.sockets.disconnectSockets(n)}}Ki.Server=Vp;var Y5=Object.keys(DM.EventEmitter.prototype).filter(function(n){return typeof DM.EventEmitter.prototype[n]==="function"});Y5.forEach(function(n){Vp.prototype[n]=function(){return this.sockets[n].apply(this.sockets,arguments)}});La.exports=(n,i)=>new Vp(n,i);La.exports.Server=Vp;La.exports.Namespace=zv.Namespace;La.exports.Socket=sM.Socket});import{createHash as eR}from"crypto";import{createServer as bG}from"http";import{createServer as jG}from"https";function gc(n=Math.random){return n().toString(36).slice(2)}class ca extends Promise{fate;resolve;reject;done=!1;constructor(n){let i,o;super((c,p)=>{i=c,o=p});this.resolve=i,this.reject=o,this.use(n instanceof Promise?n:new Promise(n))}pass(n,i){if(n===this.fate)this.resolve(i),this.done=!0}fail(n,i){if(n===this.fate)this.reject(i),this.done=!0}use(n){if(n instanceof Promise){let i=n;this.fate=i,i.then((o)=>{this.pass(i,o)},(o)=>{this.fail(i,o)})}else this.resolve(n),this.fate=void 0}}function H$(n){return Object.entries(n)}var E$=(n,i,o=nn.STORE)=>{return pa(o,{key:`${n.key}:JSON`,get:({get:c})=>i.toJson(c(n)),set:({set:c},p)=>{c(n,i.fromJson(p))}})};function U(n){while(n.child!==null)n=n.child;return n}function O$(n){while(n.parent!==null)n=n.parent;return n}class xn{Subscriber;subscribers=new Map;subscribe(n,i){return this.subscribers.set(n,i),()=>{this.unsubscribe(n)}}unsubscribe(n){this.subscribers.delete(n)}next(n){let i=this.subscribers.values();for(let o of i)o(n)}}class $l extends xn{state;constructor(n){super();this.state=n}next(n){this.state=n,super.next(n)}}function so(n,i,o){let c={key:i.key,type:"atom_family"},p=n.families.get(i.key);if(p)n.logger.error("\u2757","atom_family",i.key,`Overwriting an existing ${mo(p)} "${p.key}" in store "${n.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);let a=new xn,m=Object.assign((l)=>{let f=r(l),v={key:i.key,subKey:f},$=`${i.key}(${f})`,T=U(n),F=i.default,M={key:$,default:F instanceof Function?F(l):F};if(i.effects)M.effects=i.effects(l);let A=Zo(T,M,v);return a.next({type:"state_creation",token:A}),A},c,{subject:a,install:(l)=>so(l,i),internalRoles:o});return n.families.set(i.key,m),n.defaults.set(i.key,i.default),c}function U$(n,i){if("mutable"in i)return aa(n,i);return so(n,i)}function to(n,i,o){let c={key:i.key,type:"readonly_selector_family"},p=n.families.get(i.key);if(p)n.logger.error("\u2757","readonly_selector_family",i.key,`Overwriting an existing ${mo(p)} "${p.key}" in store "${n.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);let a=new xn,m=Object.assign((l)=>{let f=r(l),v={key:i.key,subKey:f},$=`${i.key}(${f})`,T=U(n),F=xa(T,{key:$,get:i.get(l)},v);return a.next({type:"state_creation",token:F}),F},c,{internalRoles:o,subject:a,install:(l)=>to(l,i),default:(l)=>{return i.get(l)({get:(...v)=>Mn(n,...v),find:(v,$)=>Sn(n,v,$),seek:(v,$)=>Bn(n,v,$),json:(v)=>Zn(n,v)})}});return n.families.set(i.key,m),c}function Tl(n,i){if("set"in i)return ma(n,i);return to(n,i)}var n8={atom_family:"atom",mutable_atom_family:"mutable_atom",selector_family:"selector",readonly_selector_family:"readonly_selector",molecule_family:"molecule"};function dc(n,i){let o=r(i),c=`${n.key}(${o})`,p=n8[n.type],a={key:c,type:p};if(p==="molecule")Object.assign(a,{key:i,family:n});else Object.assign(a,{family:{key:n.key,subKey:o}});return Object.assign(a,{counterfeit:!0}),a}function si(n){let i={key:n.key,type:n.type};if("family"in n)i.family=n.family;return i}class yi{a;b;cardinality;relations=new Map;contents=new Map;isAType;isBType;isContent;makeContentKey=(n,i)=>`${n}:${i}`;warn;getRelatedKeys(n){return this.relations.get(n)}addRelation(n,i){let o=this.relations.get(n),c=this.relations.get(i);if(o)o.add(i);else o=new Set([i]),this.relations.set(n,o);if(c)c.add(n);else c=new Set([n]),this.relations.set(i,c)}deleteRelation(n,i){let o=this.relations.get(n);if(o){if(o.delete(i),o.size===0)this.relations.delete(n);let c=this.relations.get(i);if(c){if(c.delete(n),c.size===0)this.relations.delete(i)}}}replaceRelationsUnsafely(n,i){this.relations.set(n,new Set(i));for(let o of i){let c=new Set().add(n);this.relations.set(o,c)}}replaceRelationsSafely(n,i){let o=this.relations.get(n),c=this.isAType?.(n)?n:void 0,p=c===void 0?n:void 0;if(o)for(let a of o){c??=a,p??=a;let x=this.relations.get(a);if(x){if(x.size===1)this.relations.delete(a);else x.delete(n);this.contents.delete(this.makeContentKey(c,p))}}this.relations.set(n,new Set(i));for(let a of i){let x=this.relations.get(a);if(x)x.add(n);else x=new Set().add(n),this.relations.set(a,x)}}getContentInternal(n){return this.contents.get(n)}setContent(n,i){this.contents.set(n,i)}deleteContent(n){this.contents.delete(n)}constructor(n,i){if(this.a=n.between[0],this.b=n.between[1],this.cardinality=n.cardinality,!i?.externalStore)this.relations=new Map(n.relations?.map(([o,c])=>[o,new Set(c)])),this.contents=new Map(n.contents);if(this.isAType=i?.isAType??null,this.isBType=i?.isBType??null,this.isContent=i?.isContent??null,i?.makeContentKey)this.makeContentKey=i.makeContentKey;if(i?.externalStore){let o=i.externalStore;if(this.has=(c,p)=>o.has(c,p),this.addRelation=(c,p)=>{o.addRelation(c,p)},this.deleteRelation=(c,p)=>{o.deleteRelation(c,p)},this.replaceRelationsSafely=(c,p)=>{o.replaceRelationsSafely(c,p)},this.replaceRelationsUnsafely=(c,p)=>{o.replaceRelationsUnsafely(c,p)},this.getRelatedKeys=(c)=>o.getRelatedKeys(c),o.getContent)this.getContentInternal=(c)=>{return o.getContent(c)},this.setContent=(c,p)=>{o.setContent(c,p)},this.deleteContent=(c)=>{o.deleteContent(c)};for(let[c,p]of n.relations??[]){let a=this.isAType?.(c)?c:void 0,x=a===void 0?c:void 0;for(let m of p)a??=m,x??=m,this.addRelation(a,x)}for(let[c,p]of n.contents??[])this.setContent(c,p)}if(i?.warn)this.warn=i.warn}toJSON(){return{between:[this.a,this.b],cardinality:this.cardinality,relations:[...this.relations.entries()].map(([n,i])=>[n,[...i]]),contents:[...this.contents.entries()]}}set(n,...i){let o=typeof i[0]==="string"?i[0]:n[this.b],c=i[1]??typeof i[0]==="string"?void 0:i[0];switch(n=typeof n==="string"?n:n[this.a],this.cardinality){case"1:1":{let p=this.getRelatedKey(n);if(p&&p!==o)this.delete(n,p)}case"1:n":{let p=this.getRelatedKey(o);if(p&&p!==n)this.delete(p,o)}}if(c){let p=this.makeContentKey(n,o);this.setContent(p,c)}return this.addRelation(n,o),this}delete(n,i){i=typeof i==="string"?i:n[this.b];let o=typeof n==="string"?n:n[this.a];if(o===void 0&&typeof i==="string"){let c=this.getRelatedKeys(i);if(c)for(let p of c)this.delete(p,i)}if(typeof o==="string"&&i===void 0){let c=this.getRelatedKeys(o);if(c)for(let p of c)this.delete(o,p)}if(typeof o==="string"&&typeof i==="string"){this.deleteRelation(o,i);let c=this.makeContentKey(o,i);this.deleteContent(c)}return this}getRelatedKey(n){let i=this.getRelatedKeys(n);if(i){if(i.size>1)this.warn?.(`${i.size} related keys were found for key "${n}": (${[...i].map((c)=>`"${c}"`).join(", ")}). Only one related key was expected.`);let o;for(let c of i){o=c;break}return o}}replaceRelations(n,i,o){let c=!Array.isArray(i),p=c?Object.keys(i):i;if(o?.reckless)this.replaceRelationsUnsafely(n,p);else this.replaceRelationsSafely(n,p);if(c)for(let a of p){let x=this.makeContentKey(n,a),m=i[a];this.setContent(x,m)}return this}getContent(n,i){let o=this.makeContentKey(n,i);return this.getContentInternal(o)}getRelationEntries(n){let i=n[this.a],o=n[this.b];if(i!==void 0&&o===void 0){let c=this.getRelatedKeys(i);if(c)return[...c].map((p)=>{return[p,this.getContent(i,p)]})}if(i===void 0&&o!==void 0){let c=this.getRelatedKeys(o);if(c)return[...c].map((p)=>{return[p,this.getContent(p,o)]})}return[]}has(n,i){if(i)return this.getRelatedKeys(n)?.has(i)??!1;return this.relations.has(n)}}function tn(n){return"epoch"in n.transactionMeta}function Fn(n){return"phase"in n.transactionMeta}var V$=(n)=>{let i=U(n);if(!Fn(i)){n.logger.warn("\uD83D\uDC1E","transaction","???","abortTransaction called outside of a transaction. This is probably a bug in AtomIO.");return}n.logger.info("\uD83E\uDE82","transaction",i.transactionMeta.update.key,"Aborting transaction"),i.parent.child=null};var i8=(n)=>n[0].toUpperCase()+n.slice(1);function mo(n){return n.type.split("_").map(i8).join(" ")}class Ui extends Error{constructor(...n){let i=n[0],o=n.length===2?n[1]:n[2];if(n.length===2)super(`${mo(i)} ${r(i.key)} not found in store "${o.config.name}".`);else{let c=n[1];super(`${mo(i)} "${i.key}" member ${r(c)} not found in store "${o.config.name}".`)}}}function qo(n,i,o){return(...c)=>{let p=d(n,o);if(p)return p.run(c,i);throw new Ui(n,o)}}var mx=(n)=>(i)=>n instanceof Function?n(i):n;var Po=(n,i)=>{if(i.valueMap.has(n.key))return i.logger.info("\uD83D\uDCD6",n.type,n.key,"reading cached value"),u$(n,i);if(n.type==="selector"||n.type==="readonly_selector")return i.logger.info("\uD83E\uDDEE",n.type,n.key,"computing value"),n.get();let o=n.default instanceof Function?n.default():n.default;return i.logger.info("\uD83D\uDC81","atom",n.key,"could not find cached value; using default",o),n.default instanceof Function?n.default():n.default};var _$=(n,i)=>{if(n.operation.open){let o=performance.now();return n.logger.info("\u2757",i.type,i.key,`deferring setState at T-${o} until setState for "${n.operation.token.key}" is done`),o}n.operation={open:!0,done:new Set,prev:new Map,time:Date.now(),token:i},n.logger.info("\u2B55",i.type,i.key,`operation start in store "${n.config.name}"${!Fn(n)?"":` ${n.transactionMeta.phase} "${n.transactionMeta.update.key}"`}`)},b$=(n)=>{if(n.operation.open)n.logger.info("\uD83D\uDD34",n.operation.token.type,n.operation.token.key,`operation done in store "${n.config.name}"`);n.operation={open:!1},n.on.operationClose.next(n.operation)},j$=(n,i)=>{if(!n.operation.open)return n.logger.error("\uD83D\uDC1E","unknown",i,"isDone called outside of an operation. This is probably a bug in AtomIO."),!0;return n.operation.done.has(i)},ec=(n,i)=>{if(!n.operation.open){n.logger.error("\uD83D\uDC1E","unknown",i,"markDone called outside of an operation. This is probably a bug in AtomIO.");return}n.operation.done.add(i)};var y$=(n,i,o)=>{switch(n.type){case"mutable_atom":o.logger.info("\uD83D\uDCE2",n.type,n.key,"is now (",i.newValue,") subscribers:",n.subject.subscribers);break;default:o.logger.info("\uD83D\uDCE2",n.type,n.key,"went (",i.oldValue,"->",i.newValue,") subscribers:",n.subject.subscribers)}n.subject.next(i)};var wl=(n,i)=>{let o=U(i),c=o.selectorAtoms.getRelatedKeys(n.key);if(o.logger.info("\uD83E\uDDF9",n.type,n.key,c?`evicting ${c.size} states downstream:`:"no downstream states",c??"to evict"),c){if(o.operation.open)o.logger.info("\uD83E\uDDF9",n.type,n.key,`[ ${[...o.operation.done].join(", ")} ] already done`);for(let p of c){if(j$(o,p))continue;B$(p,o),ec(o,p)}}};function o8(n,i){if(N$(i.newValue))return!1;if(n.includes("\uD83D\uDD0D"))return!1;return!0}var L$=(n,i,o)=>{let{key:c}=n,p=U(o);if(!Fn(p)||p.transactionMeta.phase!=="building"){o.logger.error("\uD83D\uDC1E","atom",c,"stowUpdate called outside of a transaction. This is probably a bug.");return}if(!o8(c,i))return;let x={type:"atom_update",key:c,...i};if(n.family)x.family=n.family;p.transactionMeta.update.updates.push(x),o.logger.info("\uD83D\uDCC1","atom",c,"stowed (",i.oldValue,"->",i.newValue,")")};var D$=(n,i,o)=>{let c=Po(n,o),p=c;if(n.type==="mutable_atom"&&Fn(o)){let{parent:x}=o;p=la(n,x,o)}if(p=mx(i)(p),o.logger.info("\uD83D\uDCDD","atom",n.key,"set to",p),p=Zi(n.key,p,n.subject,o),C$(n.key,o))h$(n.key,o);ec(o,n.key),wl(n,o);let a={oldValue:c,newValue:p};if(tn(o))y$(n,a,o);else if(o.parent){if(o.on.transactionApplying.state===null)L$(n,a,o);else if(n.key.startsWith("*")){let x=n.key.slice(1),m=o.atoms.get(x),l=o.valueMap.get(x);if(m.type==="mutable_atom"&&Fn(o)){let{parent:v}=o;l=la(m,v,o)}if(l.do(a.newValue)===null)wl(m,o)}}};var lx=(n,i,o)=>{switch(n.type){case"atom":case"mutable_atom":D$(n,i,o);break;case"selector":n.set(i);break}};function fx(n,i){if(i.family){let o=n.families.get(i.family.key);if(o)return o}}function Qn(n,...i){let o,c,p,a;if(i.length===2){if(o=i[0],a=i[1],c=fx(n,o)??null,c)p=o.family?oi(o.family.subKey):null,o=Sn(n,c,p)}else c=i[0],p=i[1],a=i[2],o=Sn(n,c,p);if("counterfeit"in o){let l=n.disposalTraces.buffer.find((f)=>f?.key===o.key);n.logger.error("\u274C",o.type,o.key,`could not be set because it was not found in the store "${n.config.name}".`,l?`This state was previously disposed:\n${l.trace}`:"No previous disposal trace was found.");return}let x=_$(n,o);if(x){let l=n.on.operationClose.subscribe(`waiting to set "${o.key}" at T-${x}`,()=>{l(),n.logger.info("\uD83D\uDFE2",o.type,o.key,`resuming deferred setState from T-${x}`),Qn(n,o,a)});return}let m=d(o,n);lx(m,a,n),b$(n)}function vx(n,i,o){let{key:c,newValue:p,oldValue:a}=i,x=n==="newValue"?p:a,m={key:c,type:"atom"};if(i.family)Object.assign(m,{family:i.family});Qn(o,m,x)}function I$(n,i){let o=new xn,c={type:"molecule_family",key:i.key,dependsOn:i.dependsOn??"all"},p={...c,subject:o,new:i.new};return n.moleculeFamilies.set(i.key,p),c}function lo(n,i,o){let c=_o(o,i,n.key);n.tokens.set(c.key,c);let p=Fn(o)&&o.transactionMeta.phase==="building",a=o.moleculeInProgress===n.key;if(!p&&!a)n.subject.next({type:"state_creation",token:c});return c}class ci extends Set{mode="record";subject=new xn;cacheLimit=0;cache=[];cacheIdx=-1;cacheUpdateNumber=-1;constructor(n,i=0){super(n);if(n instanceof ci)this.parent=n,this.cacheUpdateNumber=n.cacheUpdateNumber;if(i)this.cacheLimit=i,this.cache=new Array(i),this.subscribe("auto cache",(o)=>{this.cacheIdx++,this.cacheIdx%=this.cacheLimit,this.cache[this.cacheIdx]=o})}toJSON(){return{members:[...this],cache:this.cache,cacheLimit:this.cacheLimit,cacheIdx:this.cacheIdx,cacheUpdateNumber:this.cacheUpdateNumber}}static fromJSON(n){let i=new ci(n.members,n.cacheLimit);return i.cache=n.cache,i.cacheIdx=n.cacheIdx,i.cacheUpdateNumber=n.cacheUpdateNumber,i}add(n){let i=super.add(n);if(this.mode==="record")this.cacheUpdateNumber++,this.emit(`add:${r(n)}`);return i}clear(){let n=this.mode==="record"?[...this]:null;if(super.clear(),n)this.cacheUpdateNumber++,this.emit(`clear:${JSON.stringify(n)}`)}delete(n){let i=super.delete(n);if(this.mode==="record")this.cacheUpdateNumber++,this.emit(`del:${r(n)}`);return i}parent;child=null;transactionUpdates=null;transaction(n){this.mode="transaction",this.transactionUpdates=[],this.child=new ci(this);let i=this.child._subscribe("transaction",(o)=>{this.transactionUpdates?.push(o)});try{if(n(this.child)){for(let c of this.transactionUpdates)this.doStep(c);this.cacheUpdateNumber++,this.emit(`tx:${this.transactionUpdates.join(";")}`)}}catch(o){throw console.error("Failed to apply transaction to SetRTX:",o),o}finally{i(),this.child=null,this.transactionUpdates=null,this.mode="record"}}_subscribe(n,i){return this.subject.subscribe(n,i)}subscribe(n,i){return this.subject.subscribe(n,(o)=>{i(`${this.cacheUpdateNumber}=${o}`)})}emit(n){this.subject.next(n)}doStep(n){let i=n.indexOf(":"),o=n.substring(0,i),c=n.substring(i+1);switch(o){case"add":this.add(JSON.parse(c));break;case"clear":this.clear();break;case"del":this.delete(JSON.parse(c));break;case"tx":for(let p of c.split(";"))this.doStep(p)}}getUpdateNumber(n){let i=n.indexOf("=");return Number(n.substring(0,i))}do(n){let i=n.indexOf("="),o=Number(n.substring(0,i)),c=o-this.cacheUpdateNumber;if(c>0){if(c===1){this.mode="playback";let a=n.substring(i+1);return this.doStep(a),this.mode="record",this.cacheUpdateNumber=o,null}return this.cacheUpdateNumber+1}if(Math.abs(c)<this.cacheLimit){let a=this.cacheIdx+c;if(this.cache[a]===n)return null;this.mode="playback";let m=!1;while(!m){this.cacheIdx%=this.cacheLimit;let f=this.cache[this.cacheIdx];if(this.cacheIdx--,!f)return"OUT_OF_RANGE";this.undo(f),m=this.cacheIdx===a-1}let l=n.substring(i+1);return this.doStep(l),this.mode="record",this.cacheUpdateNumber=o,null}return"OUT_OF_RANGE"}undoStep(n){let i=n.indexOf(":"),o=n.substring(0,i),c=n.substring(i+1);switch(o){case"add":this.delete(JSON.parse(c));break;case"del":this.add(JSON.parse(c));break;case"clear":{let p=JSON.parse(c);for(let a of p)this.add(a);break}case"tx":{let p=c.split(";");for(let a=p.length-1;a>=0;a--)this.undoStep(p[a])}}}undo(n){let i=n.indexOf("=");if(Number(n.substring(0,i))===this.cacheUpdateNumber){this.mode="playback";let c=n.substring(i+1);return this.undoStep(c),this.mode="record",this.cacheUpdateNumber--,null}return this.cacheUpdateNumber}}function Ln(n){return n[0].toUpperCase()+n.slice(1)}class Al{options;defaultContent;toolkit;retrieve;molecules=new Map;relations;states;core;transact(n,i){let o=this.toolkit;this.toolkit=n,i(this),this.toolkit=o}store;alternates;[Symbol.dispose](){this.alternates.delete(this.store.config.name)}in(n){let i=n.config.name,o=this.alternates.get(i);if(o)return o;let c=new Al(this.options,this.defaultContent,n);return this.alternates.set(i,c),c.alternates=this.alternates,c}constructor(n,i,o=nn.STORE){this.store=o,this.options=n,this.defaultContent=i,this.alternates=new Map,this.alternates.set(o.config.name,this),this.store.miscResources.set(`join:${n.key}`,this),this.retrieve=(Y,K)=>{let E=this.toolkit.seek(Y,K);if(E)return E;let y=this.store.molecules.get(r(K));if(y){let V=d(Y,o);return lo(y,V,o)}if(o.config.lifespan==="immortal")throw new Ui(Y,K,o);return _o(o,Y,K)},this.toolkit={get:(...Y)=>Mn(o,...Y),set:(...Y)=>{Qn(o,...Y)},find:this.retrieve,seek:(...Y)=>Bn(o,...Y),json:(Y)=>Zn(o,Y),dispose:(...Y)=>{zi(o,...Y)}};let c=n.between[0],p=n.between[1],a=aa(o,{key:`${n.key}/relatedKeys`,default:()=>new ci,mutable:!0,fromJson:(Y)=>ci.fromJSON(Y),toJson:(Y)=>Y.toJSON()},["join","relations"]);this.core={findRelatedKeysState:a};let x=({get:Y},K)=>Y(this.retrieve(a,K)),m=(Y,K,E)=>{let{set:y}=Y,V=this.retrieve(a,K),X=this.retrieve(a,E);y(V,(Z)=>Z.add(E)),y(X,(Z)=>Z.add(K))},l=(Y,K,E)=>{let{set:y}=Y,V=this.retrieve(a,K),X=this.retrieve(a,E),Z,C;y(V,(on)=>{if(on.delete(E),on.size===0)Z=`"${K}"`;return on}),y(X,(on)=>{if(on.delete(K),on.size===0)C=`"${E}"`;return on})},f=(Y,K,E)=>{let{get:y,set:V}=Y,X=this.retrieve(a,K),Z=y(X);for(let C of Z){if(E.includes(C))continue;let mn=this.retrieve(a,C);V(mn,(ln)=>{return ln.delete(K),ln})}V(X,(C)=>{return C.transaction((on)=>{on.clear();for(let mn of E){let ln=x(Y,mn),Vn=ln.has(K);if(this.relations.cardinality==="1:n"){let ji=[];for(let H of ln){if(H===K)continue;let s=x(Y,H);if(s.delete(mn),s.size===0)ji.push(H)}if(!Vn&&ln.size>0)ln.clear();for(let H of ji){let s=[mn,H].sort(),Jn=`"${s[0]}:${s[1]}"`;this.molecules.delete(Jn)}}if(!Vn)ln.add(K);on.add(mn)}return!0}),C})},v=(Y,K,E)=>{let{set:y}=Y,V=this.retrieve(a,K);y(V,(X)=>{return X.transaction((Z)=>{for(let C of E)Z.add(C);return!0}),X});for(let X of E){let Z=this.retrieve(a,X);y(Z,(C)=>{return C.add(K),C})}return!0},$=(Y,K,E)=>{let y=x(Y,K);return E?y.has(E):y.size>0},T={getRelatedKeys:(Y)=>x(this.toolkit,Y),addRelation:(Y,K)=>{m(this.toolkit,Y,K)},deleteRelation:(Y,K)=>{l(this.toolkit,Y,K)},replaceRelationsSafely:(Y,K)=>{f(this.toolkit,Y,K)},replaceRelationsUnsafely:(Y,K)=>{v(this.toolkit,Y,K)},has:(Y,K)=>$(this.toolkit,Y,K)},F,M,A;if(i){M=so(o,{key:`${n.key}/content`,default:i},["join","content"]),A=I$(o,{key:`${n.key}/content-molecules`,new:class V{Z;constructor(X,Z){this.key=Z}}});let Y=({get:V},X)=>V(this.retrieve(M,X)),K=({set:V},X,Z)=>{V(this.retrieve(M,X),Z)},E=(V,X)=>{let Z=o.molecules.get(`"${X}"`);if(Z)this.toolkit.dispose(Z),this.molecules.delete(`"${X}"`)};F=Object.assign(T,{getContent:(V)=>{return Y(this.toolkit,V)},setContent:(V,X)=>{K(this.toolkit,V,X)},deleteContent:(V)=>{E(this.toolkit,V)}})}else F=T;let R=new yi(n,{externalStore:F,isAType:n.isAType,isBType:n.isBType,makeContentKey:(...Y)=>{let K=Y.sort(),E=`${K[0]}:${K[1]}`,[y,V]=K.map((X)=>this.molecules.get(r(X)));if(o.config.lifespan==="immortal"&&y&&V){let X=U(o),Z=bo(X,[y,V],A,E);this.molecules.set(`"${E}"`,d(Z,X))}return E}}),G=()=>to(o,{key:`${n.key}/singleRelatedKey`,get:(Y)=>({get:K})=>{let E=this.retrieve(a,Y),y=K(E);for(let V of y)return V;return null}},["join","keys"]),Q=()=>{return to(o,{key:`${n.key}/multipleRelatedKeys`,get:(Y)=>({get:K})=>{let E=Sl(a,o),y=this.retrieve(E,Y);return K(y).members}},["join","keys"])},b=()=>to(o,{key:`${n.key}/singleRelatedEntry`,get:(Y)=>({get:K})=>{let E=this.retrieve(a,Y),y=K(E);for(let V of y){let X=R.isAType?.(Y)?Y:void 0,Z=X===void 0?Y:void 0;X??=V,Z??=V;let C=R.makeContentKey(X,Z),on=this.retrieve(M,C),mn=K(on);return[V,mn]}return null}},["join","entries"]),D=()=>to(o,{key:`${n.key}/multipleRelatedEntries`,get:(Y)=>({get:K})=>{let E=Sl(a,o),y=this.retrieve(E,Y);return K(y).members.map((X)=>{let Z=R.isAType?.(Y)?Y:void 0,C=Z===void 0?Y:void 0;Z??=X,C??=X;let on=R.makeContentKey(Z,C),mn=this.retrieve(M,on),ln=K(mn);return[X,ln]})}},["join","entries"]);switch(n.cardinality){case"1:1":{let Y=G(),K=`${c}KeyOf${Ln(p)}`,E=`${p}KeyOf${Ln(c)}`,y={[K]:Y,[E]:Y},V;if(i){let X=b(),Z=`${c}EntryOf${Ln(p)}`,C=`${p}EntryOf${Ln(c)}`,on={[Z]:X,[C]:X};V=Object.assign(y,on)}else V=y;this.relations=R,this.states=V;break}case"1:n":{let Y=G(),K=Q(),E=`${c}KeyOf${Ln(p)}`,y=`${p}KeysOf${Ln(c)}`,V={[E]:Y,[y]:K},X;if(i){let Z=b(),C=D(),on=`${c}EntryOf${Ln(p)}`,mn=`${p}EntriesOf${Ln(c)}`,ln={[on]:Z,[mn]:C};X=Object.assign(V,ln)}else X=V;this.relations=R,this.states=X;break}default:{let Y=Q(),K=`${c}KeysOf${Ln(p)}`,E=`${p}KeysOf${Ln(c)}`,y={[K]:Y,[E]:Y},V;if(i){let X=D(),Z=`${c}EntriesOf${Ln(p)}`,C=`${p}EntriesOf${Ln(c)}`,on={[Z]:X,[C]:X};V=Object.assign(y,on)}else V=y;this.relations=R,this.states=V}}}}function $x(n,i,o=nn.STORE){return Jl(o).set(n.key,new Al(n,i,o)),{key:n.key,type:"join",a:n.between[0],b:n.between[1],cardinality:n.cardinality}}function Jl(n){if("joins"in n&&n.joins instanceof Map)return n.joins;let i=new Map;return n.joins=i,i}function fa(n,i){let o=Jl(i),c=o.get(n.key);if(c===void 0){if(c=Jl(nn.STORE).get(n.key)?.in(i),c===void 0)throw new Error(`Join "${n.key}" not found in store "${i.config.name}"`);o.set(n.key,c)}return c}function np(n,i,o){let c=fa(n,o),p;switch(n.cardinality){case"1:1":{let a=`${n.a}KeyOf${Ln(n.b)}`,x=`${n.b}KeyOf${Ln(n.a)}`;p={get[a](){let l=c.states[a];return c.retrieve(l,i)},get[x](){let l=c.states[x];return c.retrieve(l,i)}};let m=`${n.a}EntryOf${Ln(n.b)}`;if(m in c.states){let l=`${n.b}EntryOf${Ln(n.a)}`;Object.assign(p,{get[m](){let f=c.states[m];return c.retrieve(f,i)},get[l](){let f=c.states[l];return c.retrieve(f,i)}})}break}case"1:n":{let a=`${n.a}KeyOf${Ln(n.b)}`,x=`${n.b}KeysOf${Ln(n.a)}`;p={get[a](){let l=c.states[a];return c.retrieve(l,i)},get[x](){let l=c.states[x];return c.retrieve(l,i)}};let m=`${n.a}EntryOf${Ln(n.b)}`;if(m in c.states){let l=`${n.b}EntriesOf${Ln(n.a)}`;Object.assign(p,{get[m](){let f=c.states[m];return c.retrieve(f,i)},get[l](){let f=c.states[l];return c.retrieve(f,i)}})}break}case"n:n":{let a=`${n.a}KeysOf${Ln(n.b)}`,x=`${n.b}KeysOf${Ln(n.a)}`;p={get[a](){let l=c.states[a];return c.retrieve(l,i)},get[x](){let l=c.states[x];return c.retrieve(l,i)}};let m=`${n.a}EntriesOf${Ln(n.b)}`;if(m in c.states){let l=`${n.b}EntriesOf${Ln(n.a)}`;Object.assign(p,{get[m](){let f=c.states[m];return c.retrieve(f,i)},get[l](){let f=c.states[l];return c.retrieve(f,i)}})}}}return p}function k$(n,i){return np(n,i,nn.STORE)}function Rc(n,i,o){let c=fa(n,o),p=U(o);if(Fn(p)){let{toolkit:a}=p.transactionMeta;c.transact(a,({relations:x})=>{i(x)})}else i(c.relations)}function c8(n,i){return fa(n,i).core.findRelatedKeysState}function s$(n){return c8(n,nn.STORE)}function Tx(n){return{store:n}}function Mn(n,...i){let o,c,p;if(i.length===1){if(o=i[0],o.type!=="molecule"){if(c=fx(n,o)??null,c)p=o.family?oi(o.family.subKey):null,o=Sn(n,c,p)}}else{c=i[0],p=i[1];let a;if(c.type==="molecule_family")a=Bn(n,c,p)??dc(c,p);else a=Sn(n,c,p);o=a}if("counterfeit"in o&&"family"in o){c=o.type==="molecule"?d(o.family,n):n.families.get(o.family.key);let a=o.type==="molecule"?o.key:o.family.subKey,x=n.disposalTraces.buffer.find((m)=>m?.key===o.key);switch(n.logger.error("\u274C",o.type,o.key,`could not be retrieved because it was not found in the store "${n.config.name}".`,x?`This state was previously disposed:\n${x.trace}`:"No previous disposal trace was found."),c.type){case"atom_family":case"mutable_atom_family":return n.defaults.get(c.key);case"selector_family":case"readonly_selector_family":{if(n.defaults.has(c.key))return n.defaults.get(o.family.key);let m=d(c,n).default(a);return n.defaults.set(c.key,m),m}case"molecule_family":throw new Ui(c,a,n)}}switch(o.type){case"atom":case"mutable_atom":case"selector":case"readonly_selector":return Po(d(o,n),n);case"molecule":return d(o,n).instance}}class ip{i;type="molecule";stringKey;family;_dependsOn;get dependsOn(){if(this.family)return this.family.dependsOn;return this._dependsOn}subject=new xn;tokens=new Map;above=new Map;below=new Map;joins=new Map;instance;constructor(n,i,o){this.key=i;if(this.stringKey=r(i),o)this.family=o,this._dependsOn=o.dependsOn;if(n)for(let c of n)this.above.set(c.stringKey,c)}}function Z$(n){return n[0].toUpperCase()+n.slice(1)}function bo(n,i,o,c,...p){let a=O$(n),x=U(n),m=r(c);x.moleculeInProgress=m;let l=Array.isArray(i)?i:[i],f=l.map((R)=>{if(R instanceof ip)return R;let G=r(R.key),Q=n.molecules.get(G);if(!Q)throw new Error(`Molecule ${G} not found in store "${n.config.name}"`);return Q}),v=new ip(f,c,o);x.molecules.set(m,v);for(let R of f)R.below.set(v.stringKey,v);let $={get:(...R)=>Mn(U(a),...R),set:(...R)=>{Qn(U(a),...R)},seek:(R,G)=>Bn(U(a),R,G),json:(R)=>Zn(U(a),R),run:(R,G=gc())=>qo(R,G,U(n)),make:(R,G,Q,...b)=>bo(U(a),R,G,Q,...b),dispose:(R)=>{zi(U(a),R)},env:()=>Tx(U(a)),bond:(R,G)=>{if(R.type==="join"){let{as:Q}=G,b=fa(R,a);b.molecules.set(m,v),v.joins.set(R.key,b);let D=T.subject.subscribe(`join:${R.key}-${m}`,(X)=>{if(X.type==="molecule_disposal"){if(r(X.token.key)===m)D(),b.molecules.delete(m)}});if(Q===null)return;let Y=R.a===Q?R.b:R.a,K=k$(R,c),E=K[`${Y}KeysOf${Z$(Q)}`],y=K[`${Y}EntriesOf${Z$(Q)}`],V={relatedKeys:E};if(y)V=Object.assign(V,{relatedEntries:y});return V}return lo(v,d(R,a),U(a))},claim:(R,G)=>{let{exclusive:Q}=G,b=U(n).molecules.get(r(R.key));if(b)if(Q){for(let D of b.above.values())D.below.delete(b.stringKey);b.above.clear(),b.above.set(v.stringKey,v),v.below.set(b.stringKey,b)}else b.above.set(v.stringKey,v),v.below.set(b.stringKey,b)},spawn:(R,G,...Q)=>bo(U(n),[v],d(R,n),G,...Q)},T=d(o,n),F=T.new;v.instance=new F($,c,...p);let M={type:"molecule",key:c,family:o},A={type:"molecule_creation",subType:"classic",token:M,family:o,context:l,params:p};if(tn(x))T.subject.next(A);else if(Fn(x)&&x.on.transactionApplying.state===null)x.transactionMeta.update.updates.push(A);return x.moleculeInProgress=null,M}function Ml(n,i,o){switch(i){case"newValue":{t$(n,o);break}case"oldValue":{zi(o,n.token);break}}}function Rl(n,i,o){switch(i){case"newValue":{zi(o,n.token);break}case"oldValue":{t$(n,o),o.valueMap.set(n.token.key,n.value);break}}}function t$(n,i){let{family:o}=n.token;if(o){let c=i.families.get(o.key);if(c)Sn(i,c,oi(o.subKey))}}function Wl(n,i,o){switch(i){case"newValue":switch(n.subType){case"classic":bo(o,n.context,n.family,n.token.key,...n.params);break;case"modern":Fl(o,n.provenance,n.key);break}break;case"oldValue":switch(n.subType){case"classic":zi(o,n.token);break;case"modern":va(o,n.key);break}break}}function Kl(n,i,o){switch(i){case"newValue":switch(n.subType){case"classic":zi(o,n.token);break;case"modern":va(o,n.key);break}break;case"oldValue":switch(n.subType){case"classic":{let c=bo(o,n.context,n.family,n.token.key);for(let[p,a]of n.values){let x=`${p}(${r(c.key)})`,m=d(c,o),l=m.tokens.has(x),f=o.families.get(p);if(f&&!l)lo(m,f,o);o.valueMap.set(x,a)}}break;case"modern":{Fl(o,n.provenance,n.key);for(let[c,p]of n.values){let a=o.families.get(c);if(a){Sn(o,a,n.key);let x=`${c}(${r(n.key)})`;o.valueMap.set(x,p)}}}}break}}function wx(n,i,o){let c=n==="newValue"?i.updates:[...i.updates].reverse();for(let p of c)switch(p.type){case"atom_update":case"selector_update":vx(n,p,o);break;case"state_creation":Ml(p,n,o);break;case"state_disposal":Rl(p,n,o);break;case"molecule_creation":Wl(p,n,o);break;case"molecule_disposal":Kl(p,n,o);break;case"transaction_update":wx(n,p,o);break}}function q$(n,i,o){if(tn(o)&&n)o.transactionMeta.epoch.set(n,i)}function P$(n,i,o){if(!tn(o))return;let p=o.transactionMeta.actionContinuities.getRelatedKey(n);if(p!==void 0)o.transactionMeta.epoch.set(p,i)}var r$=(n,i)=>{let o=U(i),{parent:c}=o;if(c===null||!Fn(o)||o.transactionMeta?.phase!=="building"){i.logger.warn("\uD83D\uDC1E","transaction","???","applyTransaction called outside of a transaction. This is probably a bug in AtomIO.");return}o.transactionMeta.phase="applying",o.transactionMeta.update.output=n,c.child=null,c.on.transactionApplying.next(o.transactionMeta);let{updates:p}=o.transactionMeta.update;if(i.logger.info("\uD83D\uDEC4","transaction",o.transactionMeta.update.key,`Applying transaction with ${p.length} updates:`,p),wx("newValue",o.transactionMeta.update,c),tn(c))P$(o.transactionMeta.update.key,o.transactionMeta.update.epoch,c),d({key:o.transactionMeta.update.key,type:"transaction"},i)?.subject.next(o.transactionMeta.update),i.logger.info("\uD83D\uDEEC","transaction",o.transactionMeta.update.key,"Finished applying transaction.");else if(Fn(c))c.transactionMeta.update.updates.push(o.transactionMeta.update);c.on.transactionApplying.next(null)};function g$(n,i,o){if(!tn(o))return;let{epoch:p,actionContinuities:a}=o.transactionMeta;if(a.set(n,i),!p.has(n))p.set(n,-1)}class ti extends Map{n;deleted=new Set;constructor(n){super();this.source=n}get(n){if(super.has(n))return super.get(n);if(!this.deleted.has(n)&&this.source.has(n))return this.source.get(n);return}set(n,i){return this.deleted.delete(n),super.set(n,i)}hasOwn(n){return super.has(n)}has(n){return!this.deleted.has(n)&&(super.has(n)||this.source.has(n))}delete(n){return this.deleted.add(n),super.delete(n)}}var d$=(n,i,o,c)=>{let p=U(o),a={parent:p,child:null,on:p.on,loggers:p.loggers,logger:p.logger,config:p.config,atoms:new ti(p.atoms),atomsThatAreDefault:new Set(p.atomsThatAreDefault),families:new ti(p.families),operation:{open:!1},readonlySelectors:new ti(p.readonlySelectors),timelines:new ti(p.timelines),timelineTopics:new yi(p.timelineTopics.toJSON()),trackers:new Map,transactions:new ti(p.transactions),selectorAtoms:new yi(p.selectorAtoms.toJSON()),selectorGraph:new yi(p.selectorGraph.toJSON(),{makeContentKey:(...f)=>f.sort().join(":")}),selectors:new ti(p.selectors),valueMap:new ti(p.valueMap),defaults:p.defaults,disposalTraces:o.disposalTraces.copy(),molecules:new ti(p.molecules),moleculeFamilies:new ti(p.moleculeFamilies),moleculeInProgress:p.moleculeInProgress,miscResources:new ti(p.miscResources)},x=e$(n,o),m={phase:"building",update:{type:"transaction_update",key:n,id:c,epoch:x===void 0?Number.NaN:x+1,updates:[],params:i,output:void 0},toolkit:{get:(...f)=>Mn(l,...f),set:(...f)=>{Qn(l,...f)},run:(f,v=gc())=>qo(f,v,l),find:(f,v)=>Sn(l,f,v),seek:(f,v)=>Bn(l,f,v),json:(f)=>Zn(l,f),make:(f,v,$,...T)=>bo(l,f,v,$,...T),dispose:(...f)=>{zi(l,...f)},env:()=>Tx(l)}},l=Object.assign(a,{transactionMeta:m});return p.child=l,o.logger.info("\uD83D\uDEEB","transaction",n,"Building transaction with params:",i),l};function Xl(n,i){let o={key:n.key,type:"transaction",run:(a,x)=>{let m=d$(n.key,a,i,x);try{let l=U(i),{toolkit:f}=m.transactionMeta,v=n.do(f,...a);return r$(v,l),v}catch(l){throw V$(c),i.logger.warn("\uD83D\uDCA5","transaction",n.key,"caught:",l),l}},install:(a)=>Xl(n,a),subject:new xn},c=U(i);c.transactions.set(o.key,o);let p=si(o);return i.on.transactionCreation.next(p),p}function e$(n,i){let o=tn(i),c=o?i.transactionMeta.actionContinuities.getRelatedKey(n):void 0;return o&&c!==void 0?i.transactionMeta.epoch.get(c):void 0}class Jx{_buffer;_index=0;constructor(n){let i;if(typeof n==="number")i=n;else i=n.length;this._buffer=Array.from({length:i})}get buffer(){return this._buffer}get index(){return this._index}add(n){this._buffer[this._index]=n,this._index=(this._index+1)%this._buffer.length}copy(){let n=new Jx([...this._buffer]);return n._index=this._index,n}}class n0{parent=null;child=null;valueMap=new Map;defaults=new Map;atoms=new Map;selectors=new Map;readonlySelectors=new Map;atomsThatAreDefault=new Set;selectorAtoms=new yi({between:["selectorKey","atomKey"],cardinality:"n:n"});selectorGraph=new yi({between:["upstreamSelectorKey","downstreamSelectorKey"],cardinality:"n:n"},{makeContentKey:(...n)=>n.sort().join(":")});trackers=new Map;families=new Map;transactions=new Map;transactionMeta={epoch:new Map,actionContinuities:new yi({between:["continuity","action"],cardinality:"1:n"})};timelines=new Map;timelineTopics=new yi({between:["timelineKey","topicKey"],cardinality:"1:n"});disposalTraces=new Jx(100);molecules=new Map;moleculeFamilies=new Map;moleculeInProgress=null;miscResources=new Map;on={atomCreation:new xn,atomDisposal:new xn,selectorCreation:new xn,selectorDisposal:new xn,timelineCreation:new xn,transactionCreation:new xn,transactionApplying:new $l(null),operationClose:new xn,moleculeCreationStart:new xn,moleculeCreationDone:new xn,moleculeDisposal:new xn};operation={open:!1};config={name:"IMPLICIT_STORE",lifespan:"ephemeral"};loggers=[new Wc("warn",(n,i,o)=>!o.includes("\uD83D\uDD0D"))];logger={error:(...n)=>{for(let i of this.loggers)i.error(...n)},info:(...n)=>{for(let i of this.loggers)i.info(...n)},warn:(...n)=>{for(let i of this.loggers)i.warn(...n)}};constructor(n,i=null){if(this.config={...i?.config,...n},i!==null){if(this.valueMap=new Map(i?.valueMap),this.operation={...i?.operation},tn(i))this.transactionMeta={epoch:new Map(i?.transactionMeta.epoch),actionContinuities:new yi(i?.transactionMeta.actionContinuities.toJSON())};for(let[,c]of i.families){if(c.internalRoles?.includes("mutable")||c.internalRoles?.includes("join"))continue;c.install(this)}let o=new Set;for(let[,c]of i.atoms){if(o.has(c.key))continue;if(c.install(this),c.type==="mutable_atom"){let p=Zn(i,c),a=jo(c);o.add(p.key),o.add(a.key)}}for(let[,c]of i.readonlySelectors)c.install(this);for(let[,c]of i.selectors){if(o.has(c.key))continue;c.install(this)}for(let[,c]of i.transactions)c.install(this);for(let[,c]of i.timelines)c.install(this)}}}var nn={get STORE(){if(!globalThis.ATOM_IO_IMPLICIT_STORE)globalThis.ATOM_IO_IMPLICIT_STORE=new n0({name:"IMPLICIT_STORE",lifespan:"ephemeral"});return globalThis.ATOM_IO_IMPLICIT_STORE}};function d(n,i){let o,c=i;while(c!==null){switch(n.type){case"atom":case"mutable_atom":o=c.atoms.get(n.key);break;case"selector":o=c.selectors.get(n.key);break;case"readonly_selector":o=c.readonlySelectors.get(n.key);break;case"atom_family":case"mutable_atom_family":case"selector_family":case"readonly_selector_family":o=c.families.get(n.key);break;case"timeline":o=c.timelines.get(n.key);break;case"transaction":o=c.transactions.get(n.key);break;case"molecule":o=c.molecules.get(r(n.key));break;case"molecule_family":o=c.moleculeFamilies.get(n.key);break}if(o)return o;c=c.child}throw new Ui(n,i)}function Sx(n,i){let o;o=d(n,i);let{family:c}=n;for(let x of o.joins.values())x.relations.delete(o.key),x.molecules.delete(o.stringKey);let p=[];for(let x of o.above.values())p.push(si(x));let a=[];for(let x of o.tokens.values()){let m=x.family;a.push([m.key,i.valueMap.get(x.key)])}if(c){let x=d(c,i),m={type:"molecule_disposal",subType:"classic",token:n,family:c,context:p,values:a};if(n.family)m.family=n.family;for(let f of o.tokens.values())zi(i,f);for(let f of o.below.values())if(f.dependsOn==="all")Sx(f,i);else if(f.above.delete(o.stringKey),f.above.size===0)Sx(f,i);if(o.below.clear(),Fn(i)&&i.transactionMeta.phase==="building")i.transactionMeta.update.updates.push(m);else x.subject.next(m);i.molecules.delete(o.stringKey)}for(let x of o.above.values())x.below.delete(o.stringKey)}function _o(n,i,o){let c=n.families.get(i.key);if(c===void 0)throw new Ui(i,n);let p=c(o),a=U(n);if(p.family&&a.moleculeInProgress===null){if(tn(a))switch(p.type){case"atom":case"mutable_atom":n.on.atomCreation.next(p);break;case"selector":case"readonly_selector":n.on.selectorCreation.next(p);break}else if(Fn(a)&&a.on.transactionApplying.state===null)a.transactionMeta.update.updates.push({type:"state_creation",token:p})}return p}function Bn(n,i,o){let c=r(o),p=`${i.key}(${c})`,a=U(n),x;switch(i.type){case"atom_family":case"mutable_atom_family":x=a.atoms.get(p);break;case"selector_family":x=a.selectors.get(p);break;case"readonly_selector_family":x=a.readonlySelectors.get(p);break;case"molecule_family":x=a.molecules.get(r(o))}if(x)return si(x);return x}function Sn(n,i,o){let c=Bn(n,i,o);if(c)return c;let p=n.molecules.get(r(o));if(p)return lo(p,i,n);if(n.config.lifespan==="immortal"){let a=dc(i,o);return n.logger.error("\u274C",a.type,a.key,`was not found in store "${n.config.name}"; returned a counterfeit token.`),a}return c=_o(n,i,o),c}function zi(n,...i){let o,c;if(i.length===1)o=i[0],c=o.key;else{let a=i[0],x=i[1];o=a.type==="molecule_family"?Bn(n,a,x)??dc(a,x):Sn(n,a,x)}try{d(o,n)}catch(a){let x=n.disposalTraces.buffer.find((m)=>m?.key===o.key);n.logger.error("\u274C",o.type,o.key,`could not be disposed because it was not found in the store "${n.config.name}".`,x?`\n This state was most recently disposed\n${x.trace}`:"No previous disposal trace was found.");return}switch(o.type){case"atom":case"mutable_atom":Gl(o,n);break;case"selector":case"readonly_selector":i0(o,n);break;case"molecule":Sx(o,n);break}let{stack:p}=new Error;if(p){let a=p?.split("\n")?.slice(3)?.join("\n");n.disposalTraces.add({key:o.key,trace:a})}}var Ax=(n,i)=>U(i).atoms.has(n),p8=(n,i)=>U(i).selectors.has(n),a8=(n,i)=>U(i).readonlySelectors.has(n),o0=(n,i)=>Ax(n,i)||p8(n,i)||a8(n,i);var Fx=(n,i)=>{return U(i).selectorGraph.getRelationEntries({downstreamSelectorKey:n}).filter(([c,{source:p}])=>p!==n).map(([c,{source:p}])=>p).filter((c)=>o0(c,i))};var Yl=(n,i,o)=>{let c=[],p=Fx(n,o);while(p.length>0){let a=p.shift();if(i.has(a))continue;if(i.add(a),!Ax(a,o))p.push(...Fx(a,o));else if(!c.includes(a))c.push(a)}return c},c0=(n,i)=>{let o=n.key,c=Fx(o,i),p=new Set;return c.flatMap((a)=>Ax(a,i)?a:Yl(a,p,i))};var p0=(n,i,o,c)=>{let p=U(c);if(i.type==="atom"||i.type==="mutable_atom")p.selectorAtoms.set({selectorKey:n,atomKey:i.key}),c.logger.info("\uD83D\uDD0D","selector",n,`discovers root atom "${i.key}"`);else{let a=Yl(i.key,o,c);c.logger.info("\uD83D\uDD0D","selector",n,`discovers root atoms: [ ${a.map((x)=>`"${x}"`).join(", ")} ]`);for(let x of a)p.selectorAtoms=p.selectorAtoms.set({selectorKey:n,atomKey:x})}o.add(i.key)};var Mx=(n,i,o)=>({get:(...c)=>{let p=U(o),a;if(c.length===2){let[l,f]=c;switch(l.type){case"molecule_family":return Mn(o,l,f);default:if(o.config.lifespan==="ephemeral")a=Sn(o,l,f);else{let v=Bn(o,l,f);if(v)a=v;else throw new Ui(l,f,o)}}}else[a]=c;if(a.type==="molecule")return Mn(o,a);let x=d(a,o),m=Po(x,o);return o.logger.info("\uD83D\uDD0C","selector",n,`registers dependency ( "${a.key}" =`,m,")"),p.selectorGraph.set({upstreamSelectorKey:a.key,downstreamSelectorKey:n},{source:a.key}),p0(n,a,i,o),m},set:(...c)=>{let p,a;if(c.length===2)p=c[0],a=c[1];else{let l=c[0],f=c[1];a=c[2];let v=o.config.lifespan==="ephemeral"?Sn(o,l,f):Bn(o,l,f);if(!v)throw new Ui(l,f,o);p=v}let x=U(o),m=d(p,x);lx(m,a,x)},find:(c,p)=>Sn(o,c,p),seek:(c,p)=>Bn(o,c,p),json:(c)=>Zn(o,c)});var xa=(n,i,o)=>{let c=U(n),p=new xn,a=new Set,{get:x,find:m,seek:l,json:f}=Mx(i.key,a,c),v=()=>{let M=i.get({get:x,find:m,seek:l,json:f});return Zi(i.key,M,p,U(n)),a.clear(),M},$={...i,subject:p,install:(M)=>xa(M,i,o),get:v,type:"readonly_selector",...o&&{family:o}};c.readonlySelectors.set(i.key,$);let T=v();n.logger.info("\u2728",$.type,$.key,"=",T);let F={key:i.key,type:"readonly_selector"};if(o)F.family=o;return F};var $a=(n,i,o)=>{let c=U(n),p=new xn,a=new Set,x=Mx(i.key,a,c),{find:m,get:l,seek:f,json:v}=x,$={find:m,get:l,seek:f,json:v},T=(G=i.get,Q=U(n))=>{let b=G($);return Zi(i.key,b,p,Q),a.clear(),b},M={...i,subject:p,install:(G)=>$a(G,i,o),get:T,set:(G)=>{let Q=U(n),b=T(i.get,Q),D=mx(G)(b);if(n.logger.info("\uD83D\uDCDD","selector",i.key,"set (",b,"->",D,")"),Zi(i.key,D,p,Q),ec(Q,i.key),tn(Q))p.next({newValue:D,oldValue:b});i.set(x,D)},type:"selector",...o&&{family:o}};c.selectors.set(i.key,M);let A=T();n.logger.info("\u2728",M.type,M.key,"=",A);let R={key:i.key,type:"selector"};if(o)R.family=o;return R};function pa(n,i){if("set"in i){let p=$a(n,i,void 0);return n.on.selectorCreation.next(p),p}let c=xa(n,i,void 0);return n.on.selectorCreation.next(c),c}function i0(n,i){let o=U(i),{key:c}=n,p=d(n,o);if(!p.family)i.logger.error("\u274C","selector",c,"Standalone selectors cannot be disposed.");else{let a=o.molecules.get(p.family.subKey);if(a)a.tokens.delete(c);switch(n.type){case"selector":o.selectors.delete(c),d({key:p.family.key,type:"selector_family"},i).subject.next({type:"state_disposal",token:n});break;case"readonly_selector":o.readonlySelectors.delete(c),d({key:p.family.key,type:"readonly_selector_family"},i).subject.next({type:"state_disposal",token:n});break}if(o.valueMap.delete(c),o.selectorAtoms.delete(c),o.selectorGraph.delete(c),i.logger.info("\uD83D\uDD25",n.type,c,"deleted"),Fn(o)&&o.transactionMeta.phase==="building")o.transactionMeta.update.updates.push({type:"state_disposal",token:n});else i.on.selectorDisposal.next(n)}}function ma(n,i,o){let c={key:i.key,type:"selector_family"},p=n.families.get(i.key);if(p)n.logger.error("\u2757","selector_family",i.key,`Overwriting an existing ${mo(p)} "${p.key}" in store "${n.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);let a=new xn,m=Object.assign((l)=>{let f=r(l),v={key:i.key,subKey:f},$=`${i.key}(${f})`,T=U(n),F=$a(T,{key:$,get:i.get(l),set:i.set(l)},v);return a.next({type:"state_creation",token:F}),F},c,{internalRoles:o,subject:a,install:(l)=>ma(l,i),default:(l)=>{return i.get(l)({get:(...v)=>Mn(n,...v),find:(v,$)=>Sn(n,v,$),seek:(v,$)=>Bn(n,v,$),json:(v)=>Zn(n,v)})}});return n.families.set(i.key,m),c}function a0(n,i,o=nn.STORE){let c=ma(o,{key:`${n.key}:JSON`,get:(a)=>({seek:x,get:m})=>{let l=x(n,a);if(l)return i.toJson(m(l));let f=r(a),v=o.molecules.get(f);if(v){let T=lo(v,n,o);return i.toJson(m(T))}if(o.config.lifespan==="immortal")throw new Error(`No molecule found for key "${f}"`);let $=_o(o,n,a);return i.toJson(m($))},set:(a)=>({seek:x,set:m},l)=>{let f=x(n,a);if(f)m(f,i.fromJson(l));else{let v=r(a),$=o.molecules.get(v);if($){let T=lo($,n,o);m(T,i.fromJson(l))}else{if(o.config.lifespan==="immortal")throw new Error(`No molecule found for key "${v}"`);m(_o(o,n,a),i.fromJson(l))}}}},["mutable","json"]);return d(n,o).subject.subscribe(`store=${o.config.name}::json-selector-family`,(a)=>{if(a.token.family)Bn(o,c,oi(a.token.family.subKey))}),c}var oi=(n)=>JSON.parse(n),r=(n)=>JSON.stringify(n),YE=[Array.prototype,Boolean.prototype,Number.prototype,Object.prototype,String.prototype];var x0=(n,i)=>{let o=U(i);if(o.operation.open)return o.operation.prev.get(n.key);return o.valueMap.get(n.key)};var Hl=(n,i)=>{let o=U(i);return c0(n,i).map((p)=>{let a=o.atoms.get(p);if(a===void 0)throw new Error(`Atom "${p}", a dependency of selector "${n.key}", not found in store "${i.config.name}".`);return a.subject.subscribe(`${n.type}:${n.key}`,(x)=>{i.logger.info("\uD83D\uDCE2",n.type,n.key,"root",p,"went",x.oldValue,"->",x.newValue);let m=x0(n,o),l=Po(n,o);i.logger.info("\u2728",n.type,n.key,"went",m,"->",l),n.subject.next({newValue:l,oldValue:m})})})};function Si(n,i,o,c){function p($){if(c.operation.open){let T=c.on.operationClose.subscribe(`state subscription ${o}`,()=>{T(),i($)})}else i($)}let a=d(n,c);c.logger.info("\uD83D\uDC40",a.type,a.key,`Adding subscription "${o}"`);let x=a.type==="selector"||a.type==="readonly_selector",m=null,l=p;if(x)m=Hl(a,c),l=($)=>{if(m)m.length=0,m.push(...Hl(a,c));p($)};let f=a.subject.subscribe(o,l);return()=>{if(c.logger.info("\uD83D\uDE48",a.type,a.key,`Removing subscription "${o}"`),f(),m)for(let $ of m)$()}}var zl=(n,i,o,c)=>{let p=d(n,c);c.logger.info("\uD83D\uDC40","timeline",n.key,`Adding subscription "${o}"`);let a=p.subject.subscribe(o,i);return()=>{c.logger.info("\uD83D\uDE48","timeline",n.key,`Removing subscription "${o}" from timeline`),a()}};var Ql=(n,i,o,c)=>{let p=d(n,c);c.logger.info("\uD83D\uDC40","transaction",n.key,`Adding subscription "${o}"`);let a=p.subject.subscribe(o,i);return()=>{c.logger.info("\uD83D\uDE48","transaction",n.key,`Removing subscription "${o}"`),a()}};class ro{Update;initializeState(n,i){let o=`*${n.key}`;i.atoms.delete(o),i.valueMap.delete(o);let c=n.family?{key:`*${n.family.key}`,subKey:n.family.subKey}:void 0,p=Zo(i,{key:o,default:null},c);if(i.parent?.valueMap.has(o)){let a=i.parent.valueMap.get(o);i.valueMap.set(o,a)}return p}unsubscribeFromInnerValue;unsubscribeFromState;observeCore(n,i,o){let c=`tracker:${o.config.name}:${Fn(o)?o.transactionMeta.update.key:"main"}:${n.key}`,p=Mn(o,n);this.unsubscribeFromInnerValue=p.subscribe(c,(a)=>{Qn(o,i,a)}),this.unsubscribeFromState=Si(n,(a)=>{if(a.newValue!==a.oldValue)this.unsubscribeFromInnerValue(),this.unsubscribeFromInnerValue=a.newValue.subscribe(c,(x)=>{Qn(o,i,x)})},c,o)}updateCore(n,i,o){let c=`tracker:${o.config.name}:${Fn(o)?o.transactionMeta.update.key:"main"}:${n.key}`;Si(i,({newValue:p,oldValue:a})=>{let x=o.timelineTopics.getRelatedKey(i.key);if(x){if(o.timelines.get(x)?.timeTraveling){let f=zl({key:x,type:"timeline"},(v)=>{f(),Qn(o,n,($)=>{if(v==="redo"&&p)$.do(p);else if(v==="undo"&&a)$.undo(a);return $})},c,o);return}}let m=o.on.operationClose.subscribe(c,()=>{m();let l=Mn(o,n),f=p===null?-1:l.getUpdateNumber(p),v=f-l.cacheUpdateNumber;if(p&&v===1)Qn(o,n,($)=>($.do(p),$));else o.logger.info("\u274C","mutable_atom",n.key,`could not be updated. Expected update number ${l.cacheUpdateNumber+1}, but got ${f}`)})},c,o)}mutableState;latestUpdateState;dispose;constructor(n,i){this.mutableState=n;let o=U(i);this.latestUpdateState=this.initializeState(n,o),this.observeCore(n,this.latestUpdateState,o),this.updateCore(n,this.latestUpdateState,o),o.trackers.set(n.key,this),this.dispose=()=>{this.unsubscribeFromInnerValue(),this.unsubscribeFromState(),o.trackers.delete(n.key)}}}function Ta(n,i,o){n.logger.info("\uD83D\uDD28","atom",i.key,`creating in store "${n.config.name}"`);let c=U(n),p=c.atoms.get(i.key);if(p&&p.type==="mutable_atom")return n.logger.error("\u274C","atom",i.key,"Tried to create atom, but it already exists in the store."),si(p);let a=new xn,x={...i,type:"mutable_atom",install:(f)=>{return f.logger.info("\uD83D\uDEE0\uFE0F","atom",i.key,`installing in store "${f.config.name}"`),Ta(f,i,o)},subject:a};if(o)x.family=o;let m=i.default();c.atoms.set(x.key,x),Rx(i.key,n),Zi(i.key,m,a,c);let l=si(x);if(i.effects){let f=0,v=[];for(let $ of i.effects){let T=$({setSelf:(F)=>{Qn(n,l,F)},onSet:(F)=>Si(l,F,`effect[${f}]`,n)});if(T)v.push(T);++f}x.cleanup=()=>{for(let $ of v)$()}}if(new ro(l,n),!o)E$(l,i,n);return l}class El{Update;latestUpdateAtoms;mutableAtoms;constructor(n,i){let o=so(i,{key:`*${n.key}`,default:null},["mutable","updates"]);this.latestUpdateAtoms=d(o,i),this.mutableAtoms=n,this.mutableAtoms.subject.subscribe(`store=${i.config.name}::tracker-atom-family`,(c)=>{if(c.token.family){let p=oi(c.token.family.subKey);Bn(i,this.latestUpdateAtoms,p),new ro(c.token,i)}}),this.latestUpdateAtoms.subject.subscribe(`store=${i.config.name}::tracker-atom-family`,(c)=>{if(c.token.family){let p=oi(c.token.family.subKey),a=Bn(i,this.mutableAtoms,p);if(a)new ro(a,i)}})}}function aa(n,i,o){let c={key:i.key,type:"mutable_atom_family"},p=n.families.get(i.key);if(p)n.logger.error("\u2757","mutable_atom_family",i.key,`Overwriting an existing ${mo(p)} "${p.key}" in store "${n.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);let a=new xn,m=Object.assign((l)=>{let f=r(l),v={key:i.key,subKey:f},$=`${i.key}(${f})`,T=U(n),F={key:$,default:()=>i.default(l),toJson:i.toJson,fromJson:i.fromJson,mutable:!0};if(i.effects)F.effects=i.effects(l);let M=Ta(T,F,v);return a.next({type:"state_creation",token:M}),M},c,{subject:a,install:(l)=>aa(l,i),toJson:i.toJson,fromJson:i.fromJson,internalRoles:o});return n.families.set(i.key,m),a0(m,i,n),new El(m,n),c}var Sl=(n,i)=>{let o=U(i),c=`${n.key}:JSON`;return o.families.get(c)};var Zn=(n,i)=>{if(i.family){let c=U(n),a={key:`${i.family.key}:JSON`,type:"selector_family"},x=d(a,c),m=JSON.parse(i.family.subKey);return Sn(n,x,m)}return{type:"selector",key:`${i.key}:JSON`}};var jo=(n)=>{let o={type:"atom",key:`*${n.key}`};if(n.family)o.family={key:`*${n.family.key}`,subKey:n.family.subKey};return o};function N$(n){return typeof n==="object"&&n!==null&&"do"in n&&"undo"in n&&"subscribe"in n}function la(n,i,o){let c=i.valueMap.get(n.key),p=o.valueMap.get(n.key);if(c===p){if(c===void 0)return typeof n.default==="function"?n.default():n.default;i.logger.info("\uD83D\uDCC3","atom",n.key,"copying");let a=n.toJson(c),x=n.fromJson(a);return o.valueMap.set(n.key,x),new ro(n,i),x}return p}function Zi(n,i,o,c){let p=c.valueMap.get(n);if(p instanceof ca)p.use(i);if(i instanceof Promise){let a=new ca(i);return c.valueMap.set(n,a),a.then((x)=>{Zi(n,x,o,c),o.next({newValue:x,oldValue:a})}).catch((x)=>{c.logger.error("\uD83D\uDCA5","state",n,"rejected:",x)}),a}return c.valueMap.set(n,i),i}var u$=(n,i)=>{let o=i.valueMap.get(n.key);if(n.type==="mutable_atom"&&Fn(i)){let{parent:c}=i;o=la(n,c,i)}return o},B$=(n,i)=>{let o=i.valueMap.get(n);if(o instanceof ca){let c=o,p=i.selectors.get(n)??i.readonlySelectors.get(n);if(p)c.use(p.get());return}if(i.operation.open)i.operation.prev.set(n,o);i.valueMap.delete(n),i.logger.info("\uD83D\uDDD1","state",n,"evicted")};var C$=(n,i)=>{return U(i).atomsThatAreDefault.has(n)},Rx=(n,i)=>{let o=U(i);o.atomsThatAreDefault=new Set(o.atomsThatAreDefault).add(n)},h$=(n,i)=>{let o=U(i);o.atomsThatAreDefault=new Set(U(i).atomsThatAreDefault),o.atomsThatAreDefault.delete(n)};function Zo(n,i,o){n.logger.info("\uD83D\uDD28","atom",i.key,`creating in store "${n.config.name}"`);let c=U(n),p=c.atoms.get(i.key);if(p&&p.type==="atom")return n.logger.error("\u274C","atom",i.key,"Tried to create atom, but it already exists in the store."),si(p);let a=new xn,x={...i,type:"atom",install:(f)=>{return f.logger.info("\uD83D\uDEE0\uFE0F","atom",i.key,`installing in store "${f.config.name}"`),Zo(f,i,o)},subject:a};if(o)x.family=o;let m=i.default;if(i.default instanceof Function)m=i.default();c.atoms.set(x.key,x),Rx(i.key,n),Zi(i.key,m,a,c);let l=si(x);if(i.effects){let f=0,v=[];for(let $ of i.effects){let T=$({setSelf:(F)=>{Qn(n,l,F)},onSet:(F)=>Si(l,F,`effect[${f}]`,n)});if(T)v.push(T);++f}x.cleanup=()=>{for(let $ of v)$()}}return l}function m0(n,i){if("mutable"in i){let p=Ta(n,i,void 0);return n.on.atomCreation.next(p),p}let c=Zo(n,i,void 0);return n.on.atomCreation.next(c),c}function Gl(n,i){let o=U(i),{key:c}=n,p=d(n,o);if(!p.family)i.logger.error("\u274C","atom",c,"Standalone atoms cannot be disposed.");else{p.cleanup?.();let a=i.valueMap.get(p.key);d({key:p.family.key,type:"atom_family"},i).subject.next({type:"state_disposal",token:n,value:a});let m=o.molecules.get(p.family.subKey);if(m)m.tokens.delete(c);if(o.atoms.delete(c),o.valueMap.delete(c),o.selectorAtoms.delete(c),o.atomsThatAreDefault.delete(c),i.timelineTopics.delete(c),n.type==="mutable_atom"){let l=jo(n);Gl(l,i),i.trackers.delete(c)}if(i.logger.info("\uD83D\uDD25","atom",c,"deleted"),Fn(o)&&o.transactionMeta.phase==="building")o.transactionMeta.update.updates.push({type:"state_disposal",token:n});else i.on.atomDisposal.next(n)}}var iV=Symbol("provenance");function Fl(n,i,o){let c=r(o);try{let p=[],a;if(i==="root")p.push(n.molecules.get('"root"')),a="all";else if(typeof i==="string"&&i.startsWith(x8)){a="any";let v=r(i),$=n.molecules.get(v);if(!$)throw new Error(`Molecule ${v} not found in store "${n.config.name}"`);p.push($)}else if(o.startsWith("T$--")){a="all";for(let $ of i){let T=r($),F=n.molecules.get(T);if(!F)throw new Error(`Molecule ${T} not found in store "${n.config.name}"`);p.push(F)}}else{a="any";let $=r(i),T=n.molecules.get($);if(!T)throw new Error(`Molecule ${$} not found in store "${n.config.name}"`);p.push(T)}let x=new ip(p,o);x._dependsOn=a,n.molecules.set(c,x);for(let v of p)v.below.set(x.stringKey,x);let m={type:"molecule_creation",subType:"modern",key:x.key,provenance:i},l=U(n);if(Fn(l)&&l.transactionMeta.phase==="building")l.transactionMeta.update.updates.push(m);else l.on.moleculeCreationStart.next(m)}catch(p){if(p instanceof Error)n.logger.error("\u274C","molecule",c,"allocation failed:",p.message)}return o}function va(n,i){let o=r(i),c=n.molecules.get(o);if(!c)throw new Error(`Molecule ${o} not found in store "${n.config.name}"`);for(let f of c.joins.values())f.relations.delete(c.key),f.molecules.delete(c.stringKey);let p;if(c.above.size===1)p=c.above.values().next().value.key;else p=[...c.above.values()].map(({key:f})=>f);let a=[];for(let f of c.tokens.values()){let v=f.family;a.push([v.key,n.valueMap.get(f.key)])}for(let f of c.tokens.values())zi(n,f);for(let f of c.below.values())if(f.dependsOn==="all")va(n,f.key);else if(f.above.delete(c.stringKey),f.above.size===0)va(n,f.key);c.below.clear();let x={type:"molecule_disposal",subType:"modern",key:c.key,values:a,provenance:p},m=U(n);if(Fn(m)&&m.transactionMeta.phase==="building")m.transactionMeta.update.updates.push(x);else m.on.moleculeDisposal.next(x);m.molecules.delete(c.stringKey);for(let f of c.above.values())f.below.delete(c.stringKey)}var x8="T$";function go(n){return m0(nn.STORE,n)}function Kc(n){return U$(nn.STORE,n)}var Ol=(n)=>(i,o,c,p,...a)=>{console[n](`${i} ${o} "${c}" ${p}`,...a)},m8={error:Ol("error"),info:Ol("info"),warn:Ol("warn")};class Wc{n;i;o;constructor(n,i,o=m8){this.logLevel=n;this.filter=i;this.logger=o}error=(...n)=>{if((this.filter?.(...n)??!0)&&this.logLevel!==null)this.logger.error(...n)};info=(...n)=>{if((this.filter?.(...n)??!0)&&this.logLevel==="info")this.logger.info(...n)};warn=(...n)=>{if((this.filter?.(...n)??!0)&&this.logLevel!=="error"&&this.logLevel!==null)this.logger.warn(...n)}}function Wx(n){return Tl(nn.STORE,n)}function Xc(n){return Xl(n,nn.STORE)}class l0 extends Map{set(n,i){if(this.has(n))return console.warn("Tried to set a key that already exists in an InvariantMap",{key:n,value:i}),this;return super.set(n,i)}clear(){throw new Error("Cannot clear an InvariantMap")}}class Kx{n;type="continuity";globals=[];actions=[];perspectives=[];constructor(n){this.key=n}static existing=new l0;static create(n,i){let o=new Kx(n),{type:c,globals:p,actions:a,perspectives:x}=i(o),m={type:c,key:n,globals:p,actions:a,perspectives:x};return Kx.existing.set(n,m),m}add(...n){switch(n[0].type){case"atom":case"mutable_atom":this.globals.push(...n);break;case"transaction":this.actions.push(...n);break;case"atom_family":{let[o,c]=n;this.perspectives.push({type:"realtime_perspective",resourceAtoms:o,viewAtoms:c})}break}return this}}function f0(n){let{key:i,config:o}=n,c=Kx.create(i,o),{actions:p}=c;for(let a of p)g$(i,a.key,nn.STORE);return q$(i,-1,nn.STORE),c}var SV=go({key:"usersInRoomIndex",mutable:!0,default:()=>new ci,toJson:(n)=>n.toJSON(),fromJson:(n)=>ci.fromJSON(n)}),Ul=go({key:"roomIndex",default:()=>new ci,mutable:!0,toJson:(n)=>n.toJSON(),fromJson:(n)=>ci.fromJSON(n)}),l8={enteredAtEpoch:0},wa=$x({key:"usersInRooms",between:["room","user"],cardinality:"1:n",isAType:(n)=>typeof n==="string",isBType:(n)=>typeof n==="string"},l8),AV=Wx({key:"usersInMyRoomView",get:(n)=>({find:i})=>{let o=s$(wa);return[i(o,n)]}});import{spawn as f8}from"child_process";class op{n;listeners;globalListeners;handleEvent(n,...i){for(let c of this.globalListeners)c(n,...i);let o=this.listeners.get(n);if(o)for(let c of o)c(...i)}id="no_id_retrieved";constructor(n){this.emit=n;this.listeners=new Map,this.globalListeners=new Set}on(n,i){let o=this.listeners.get(n);if(o)o.add(i);else this.listeners.set(n,new Set([i]));return this}onAny(n){return this.globalListeners.add(n),this}off(n,i){let o=this.listeners.get(n);if(o)if(i)o.delete(i);else this.listeners.delete(n);return this}offAny(n){return this.globalListeners.delete(n),this}}class Ja extends op{n;i;o;incompleteData="";unprocessedEvents=[];incompleteLog="";unprocessedLogs=[];id="#####";handleLog(n){if(Array.isArray(n)){let[i,...o]=n;switch(i){case"i":this.logger.info(this.id,this.key,...o);break;case"w":this.logger.warn(this.id,this.key,...o);break;case"e":this.logger.error(this.id,this.key,...o);break}}}constructor(n,i,o=console){super((c,...p)=>{let a=JSON.stringify([c,...p])+"\x03",x=(m)=>{if(m.code==="EPIPE")console.error("EPIPE error during write",this.process.stdin);this.process.stdin.removeListener("error",x)};return this.process.stdin.once("error",x),this.process.stdin.write(a),this});this.process=n;this.key=i;this.logger=o;if(this.process=n,this.process.stdout.on("data",(c)=>{let p=c.toString();if(p==="\u2728")return;this.unprocessedEvents.push(...p.split("\x03"));let a=this.unprocessedEvents.shift();this.incompleteData+=a??"";try{if(this.incompleteData.startsWith("error"))console.log("\u2757",this.incompleteData);let x=oi(this.incompleteData);this.handleEvent(...x);while(this.unprocessedEvents.length>0){let m=this.unprocessedEvents.shift();if(m){if(this.unprocessedEvents.length===0)this.incompleteData=m;x=oi(m),this.handleEvent(...x)}}this.incompleteData=""}catch(x){console.warn("\u26A0\uFE0F----------------\u26A0\uFE0F"),console.warn(this.incompleteData),console.warn("\u26A0\uFE0F----------------\u26A0\uFE0F"),console.error(x)}}),this.process.stderr.on("data",(c)=>{let p=c.toString();this.unprocessedLogs.push(...p.split("\x03"));let a=this.unprocessedLogs.shift();this.incompleteLog+=a??"";try{let x=oi(this.incompleteLog);this.handleLog(x);while(this.unprocessedLogs.length>0)if(this.incompleteLog=this.unprocessedLogs.shift()??"",this.incompleteLog)x=oi(this.incompleteLog),this.handleLog(x)}catch(x){console.error("\u274C\u274C\u274C"),console.error(this.incompleteLog),console.error(x),console.error("\u274C\u274C\u274C\uFE0F")}}),n.pid)this.id=n.pid.toString()}}class v0 extends op{in;out;id="no_id_retrieved";disposalFunctions=[];constructor(n){super((...i)=>{return this.out.next(i),this});this.id=n,this.in=new xn,this.out=new xn,this.in.subscribe("socket",(i)=>{this.handleEvent(...i)})}dispose(){for(let n of this.disposalFunctions)n()}}class Vl extends op{incompleteData="";unprocessedEvents=[];relays;relayServices;process;id="#####";log(...n){this.process.stderr.write(r(n.map((i)=>i instanceof ci?`{ ${i.toJSON().members.join(" | ")} }`:i))+"\x03")}logger={info:(...n)=>{this.log("i",...n)},warn:(...n)=>{this.log("w",...n)},error:(...n)=>{this.log("e",...n)}};constructor(){super((n,...i)=>{let o=JSON.stringify([n,...i]);return this.process.stdout.write(o+"\x03"),this});if(this.process=process,this.process.stdin.resume(),this.relays=new Map,this.relayServices=[],this.process.stdin.on("data",(n)=>{let i=n.toString();this.unprocessedEvents.push(...i.split("\x03"));let o=this.unprocessedEvents.shift();this.incompleteData+=o??"";try{let c=oi(this.incompleteData);this.logger.info("\uD83C\uDFB0","received",c),this.handleEvent(...c);while(this.unprocessedEvents.length>0){let p=this.unprocessedEvents.shift();if(p){if(this.unprocessedEvents.length===0)this.incompleteData=p;let a=oi(p);this.handleEvent(...a)}}this.incompleteData=""}catch(c){if(c instanceof Error)this.logger.error("\u2757",c.message,c.cause,c.stack)}}),this.on("exit",()=>{this.logger.info("\uD83D\uDD25",this.id,'received "exit"'),process.exit(0)}),process.on("exit",(n)=>{this.logger.info("\uD83D\uDD25",this.id,`exited with code ${n}`)}),process.on("end",()=>{this.logger.info("\uD83D\uDD25",this.id,"ended"),process.exit(0)}),process.on("SIGTERM",()=>{this.logger.error("\uD83D\uDD25",this.id,"terminated"),process.exit(0)}),process.on("SIGINT",()=>{this.logger.error("\uD83D\uDD25",this.id,"interrupted"),process.exit(0)}),process.pid)this.id=process.pid?.toString();this.on("user-joins",(n)=>{this.logger.info("\uD83D\uDC64","user",n,"joined");let i=new v0(`user:${n}`);this.relays.set(n,i),this.logger.info("\uD83D\uDD17","attaching services:",`[${[...this.relayServices.keys()].join(", ")}]`);for(let o of this.relayServices){let c=o(i);if(c)i.disposalFunctions.push(c)}this.on(`user:${n}`,(...o)=>{i.in.next(o)}),i.out.subscribe("socket",(o)=>{this.emit(...o)})}),this.on("user-leaves",(n)=>{let i=this.relays.get(n);if(this.off(`relay:${n}`),i)i.dispose(),this.relays.delete(n)}),process.stdout.write("\u2728")}relay(n){this.logger.info("\uD83D\uDD17","running relay method"),this.relayServices.push(n)}}var ul=Kc({key:"roomArguments",default:["echo",["Hello World!"]]}),$0=Wx({key:"room",get:(n)=>async({get:i,find:o})=>{let c=o(ul,n),p=i(c),[a,x]=p,m=await new Promise((l)=>{let f=f8(a,x,{env:process.env}),v=($)=>{if($.toString()==="\u2728")f.stdout.off("data",v),l(f)};f.stdout.on("data",v)});return new Ja(m,n)}});var kV=Xc({key:"createRoom",do:({get:n,set:i,find:o},c,p,a)=>{let x=a?[p,a]:[p],m=o(ul,c);i(m,x),i(Ul,(v)=>v.add(c));let l=o($0,c);return n(l)}}),sV=Xc({key:"joinRoom",do:(n,i,o,c)=>{let p={enteredAtEpoch:c};return Rc(wa,(a)=>{a.set({room:i,user:o},p)},n.env().store),p}}),ZV=Xc({key:"leaveRoom",do:(n,i,o)=>{Rc(wa,(c)=>{c.delete({room:i,user:o})},n.env().store)}}),tV=Xc({key:"destroyRoom",do:(n,i)=>{Rc(wa,(o)=>{o.delete({room:i})},n.env().store),n.set(Ul,(o)=>(o.delete(i),o))}});function _l(n,i){return i.map((o)=>{switch(o.type){case"transaction_update":{let c=_l(n,o.updates);return{...o,updates:c}}default:return o}}).filter((o)=>{switch(o.type){case"atom_update":case"selector_update":return n.includes(o.key);case"state_creation":return n.includes(o.token.key);case"molecule_creation":return!0;case"transaction_update":return!0}})}var rV=Kc({key:"redactor",default:{occlude:(n)=>n}}),cp=Kc({key:"unacknowledgedUpdates",default:()=>[]});var Xx=Kc({key:"sockets",default:null}),bl=go({key:"socketsIndex",mutable:!0,default:()=>new ci,toJson:(n)=>n.toJSON(),fromJson:(n)=>ci.fromJSON(n)}),jl=go({key:"usersIndex",mutable:!0,default:()=>new ci,toJson:(n)=>n.toJSON(),fromJson:(n)=>ci.fromJSON(n)}),Gc=$x({key:"usersOfSockets",between:["user","socket"],cardinality:"1:1",isAType:(n)=>n.startsWith("user::"),isBType:(n)=>n.startsWith("socket::")});function T0(n,i,o,c){let p=i.key;return function a(){let x=[];for(let l of i.globals){let f=l.type==="mutable_atom"?Zn(n,l):l,v=Mn(n,f);x.push(f,v)}for(let l of i.perspectives){let{viewAtoms:f,resourceAtoms:v}=l,$=Sn(n,f,o),T=Mn(n,$);n.logger.info("\uD83D\uDC41","atom",v.key,`${o} can see`,{viewAtoms:f,resourceAtoms:v,userView:T});for(let F of T){let M=F.type==="mutable_atom"?Zn(n,F):F,A=Mn(n,M);x.push(M,A)}}let m=tn(n)?n.transactionMeta.epoch.get(p)??null:null;c?.emit(`continuity-init:${p}`,m,x)}}function w0(n,i,o){let c=i.key;return function p(a){n.logger.info("\uD83D\uDECE\uFE0F","continuity",c,"received",a);let{key:x,id:m}=a,l=`tx-run:${x}:${m}`,f=`${l}:start`,v=`${l}:end`;performance.mark(f);try{qo({type:"transaction",key:x},m,n)(...a.params)}catch(T){if(T instanceof Error)n.logger.error("\u274C","continuity",c,`failed to run transaction ${x} from ${o} with update ${m}`,T.message)}performance.mark(v);let $=performance.measure(l,f,v);n?.logger.info("\uD83D\uDE80","transaction",x,m,o,$.duration)}}function J0(n,i,o,c){let p=i.key;return function a(x){if(n.logger.info("\uD83D\uDC4D","continuity",p,`${o} acknowledged epoch ${x}`),c[0]?.epoch===x)Qn(n,cp,o,(l)=>{return l.shift(),n.logger.info("\uD83D\uDC4D","continuity",p,`${o} unacknowledged update queue now has`,l.length,"items"),l})}}function S0(n,i,o,c){let p=i.key,a=[];for(let x of i.actions){let m=Ql(x,(l)=>{try{let f=i.globals.map((T)=>{if(T.type==="atom")return T.key;return jo(T).key}).concat(i.perspectives.flatMap((T)=>{let{viewAtoms:F}=T,M=Sn(n,F,o);return Mn(n,M).map((R)=>{return R.type==="mutable_atom"?"*"+R.key:R.key})})),v=_l(f,l.updates),$={...l,updates:v};Qn(n,cp,o,(T)=>{if($)T.push($),T.sort((F,M)=>F.epoch-M.epoch),n.logger.info("\uD83D\uDC4D","continuity",p,`${o} unacknowledged update queue now has`,T.length,"items");return T}),c?.emit(`tx-new:${p}`,$)}catch(f){if(f instanceof Error)n.logger.error("\u274C","continuity",p,`${o} failed to send update from transaction ${x.key} to ${o}`,f.message)}},`sync-continuity:${p}:${o}`,n);a.push(m)}return a}function A0(n,i,o,c){let p=i.key,a=[];for(let x of i.perspectives){let{viewAtoms:m}=x,l=Sn(n,m,o),f=Si(l,({oldValue:v,newValue:$})=>{let T=v.map((R)=>R.key),F=$.map((R)=>R.key),M=v.filter((R)=>!F.includes(R.key)),A=$.filter((R)=>!T.includes(R.key)).flatMap((R)=>{let G=R.type==="mutable_atom"?Zn(n,R):R,Q=Mn(n,G);return[G,Q]});if(n.logger.info("\uD83D\uDC41","atom",x.resourceAtoms.key,`${o} has a new perspective`,{oldKeys:T,newKeys:F,revealed:A,concealed:M}),A.length>0)c?.emit(`reveal:${p}`,A);if(M.length>0)c?.emit(`conceal:${p}`,M)},`sync-continuity:${p}:${o}:perspective:${x.resourceAtoms.key}`,n);a.push(f)}return a}function F0({socket:n,store:i=nn.STORE}){return function o(c){let p=n,a=c.key,x=np(Gc,`socket::${p.id}`,i).userKeyOfSocket,m=Mn(i,x);if(!m)return i.logger.error("\u274C","continuity",a,`Tried to create a synchronizer for a socket (${p.id}) that is not connected to a user.`),()=>{};let l=np(Gc,m,i).socketKeyOfUser,f=Si(l,({newValue:G})=>{if(i.logger.info("\uD83D\uDC4B","continuity",a,`seeing ${m} on new socket ${G}`),G===null){i.logger.warn("\u274C","continuity",a,`User (${m}) is not connected to a socket, waiting for them to reappear.`);return}let Q=Sn(i,Xx,G);p=Mn(i,Q);for(let D of v)p?.emit(`tx-new:${a}`,D)},`sync-continuity:${a}:${m}`,i),v=Mn(i,cp,m),$=[],T=A0(i,c,m,p),F=S0(i,c,m,p);$.push(...T,...F);let M=T0(i,c,m,n);p.off(`get:${a}`,M),p.on(`get:${a}`,M);let A=w0(i,c,m);p.off(`tx-run:${a}`,A),p.on(`tx-run:${a}`,A);let R=J0(i,c,m,v);return p?.on(`ack:${a}`,R),()=>{for(let G of $)G();p?.off(`ack:${a}`,R),p?.off(`get:${a}`,M),p?.off(`tx-run:${a}`,A)}}}var i4=vl($f(),1);var J=Symbol.for("drizzle:entityKind"),v_=Symbol.for("drizzle:hasOwnEntityKind");function z(n,i){if(!n||typeof n!=="object")return!1;if(n instanceof i)return!0;if(!Object.prototype.hasOwnProperty.call(i,J))throw new Error(`Class "${i.name??"<unknown>"}" doesn't look like a Drizzle entity. If this is incorrect and the class is provided by Drizzle, please report this as a bug.`);let o=Object.getPrototypeOf(n).constructor;if(o)while(o){if(J in o&&o[J]===i[J])return!0;o=Object.getPrototypeOf(o)}return!1}class bn{constructor(n,i){this.table=n,this.config=i,this.name=i.name,this.keyAsName=i.keyAsName,this.notNull=i.notNull,this.default=i.default,this.defaultFn=i.defaultFn,this.onUpdateFn=i.onUpdateFn,this.hasDefault=i.hasDefault,this.primary=i.primaryKey,this.isUnique=i.isUnique,this.uniqueName=i.uniqueName,this.uniqueType=i.uniqueType,this.dataType=i.dataType,this.columnType=i.columnType,this.generated=i.generated,this.generatedIdentity=i.generatedIdentity}static[J]="Column";name;keyAsName;primary;notNull;default;defaultFn;onUpdateFn;hasDefault;isUnique;uniqueName;uniqueType;dataType;columnType;enumValues=void 0;generated=void 0;generatedIdentity=void 0;config;mapFromDriverValue(n){return n}mapToDriverValue(n){return n}shouldDisableInsert(){return this.config.generated!==void 0&&this.config.generated.type!=="byDefault"}}class Tf{static[J]="ColumnBuilder";config;constructor(n,i,o){this.config={name:n,keyAsName:n==="",notNull:!1,default:void 0,hasDefault:!1,primaryKey:!1,isUnique:!1,uniqueName:void 0,uniqueType:void 0,dataType:i,columnType:o,generated:void 0}}$type(){return this}notNull(){return this.config.notNull=!0,this}default(n){return this.config.default=n,this.config.hasDefault=!0,this}$defaultFn(n){return this.config.defaultFn=n,this.config.hasDefault=!0,this}$default=this.$defaultFn;$onUpdateFn(n){return this.config.onUpdateFn=n,this.config.hasDefault=!0,this}$onUpdate=this.$onUpdateFn;primaryKey(){return this.config.primaryKey=!0,this.config.notNull=!0,this}setName(n){if(this.config.name!=="")return;this.config.name=n}}var To=Symbol.for("drizzle:Name");class wf{static[J]="PgForeignKeyBuilder";reference;_onUpdate="no action";_onDelete="no action";constructor(n,i){if(this.reference=()=>{let{name:o,columns:c,foreignColumns:p}=n();return{name:o,columns:c,foreignTable:p[0].table,foreignColumns:p}},i)this._onUpdate=i.onUpdate,this._onDelete=i.onDelete}onUpdate(n){return this._onUpdate=n===void 0?"no action":n,this}onDelete(n){return this._onDelete=n===void 0?"no action":n,this}build(n){return new K1(n,this)}}class K1{constructor(n,i){this.table=n,this.reference=i.reference,this.onUpdate=i._onUpdate,this.onDelete=i._onDelete}static[J]="PgForeignKey";reference;onUpdate;onDelete;getName(){let{name:n,columns:i,foreignColumns:o}=this.reference(),c=i.map((x)=>x.name),p=o.map((x)=>x.name),a=[this.table[To],...c,o[0].table[To],...p];return n??`${a.join("_")}_fk`}}function Ix(n,...i){return n(...i)}function X1(n,i){return`${n[To]}_${i.join("_")}_unique`}function G1(n,i,o){for(let c=i;c<n.length;c++){let p=n[c];if(p==="\\"){c++;continue}if(p==='"')return[n.slice(i,c).replace(/\\/g,""),c+1];if(o)continue;if(p===","||p==="}")return[n.slice(i,c).replace(/\\/g,""),c]}return[n.slice(i).replace(/\\/g,""),n.length]}function Y1(n,i=0){let o=[],c=i,p=!1;while(c<n.length){let a=n[c];if(a===","){if(p||c===i)o.push("");p=!0,c++;continue}if(p=!1,a==="\\"){c+=2;continue}if(a==='"'){let[l,f]=G1(n,c+1,!0);o.push(l),c=f;continue}if(a==="}")return[o,c+1];if(a==="{"){let[l,f]=Y1(n,c+1);o.push(l),c=f;continue}let[x,m]=G1(n,c,!1);o.push(x),c=m}return[o,c]}function z1(n){let[i]=Y1(n,1);return i}function Jf(n){return`{${n.map((i)=>{if(Array.isArray(i))return Jf(i);if(typeof i==="string")return`"${i.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`;return`${i}`}).join(",")}}`}class I extends Tf{foreignKeyConfigs=[];static[J]="PgColumnBuilder";array(n){return new H1(this.config.name,this,n)}references(n,i={}){return this.foreignKeyConfigs.push({ref:n,actions:i}),this}unique(n,i){return this.config.isUnique=!0,this.config.uniqueName=n,this.config.uniqueType=i?.nulls,this}generatedAlwaysAs(n){return this.config.generated={as:n,type:"always",mode:"stored"},this}buildForeignKeys(n,i){return this.foreignKeyConfigs.map(({ref:o,actions:c})=>{return Ix((p,a)=>{let x=new wf(()=>{let m=p();return{columns:[n],foreignColumns:[m]}});if(a.onUpdate)x.onUpdate(a.onUpdate);if(a.onDelete)x.onDelete(a.onDelete);return x.build(i)},o,c)})}buildExtraConfigColumn(n){return new Q1(n,this.config)}}class u extends bn{constructor(n,i){if(!i.uniqueName)i.uniqueName=X1(n,[i.name]);super(n,i);this.table=n}static[J]="PgColumn"}class Q1 extends u{static[J]="ExtraConfigColumn";getSQLType(){return this.getSQLType()}indexConfig={order:this.config.order??"asc",nulls:this.config.nulls??"last",opClass:this.config.opClass};defaultConfig={order:"asc",nulls:"last",opClass:void 0};asc(){return this.indexConfig.order="asc",this}desc(){return this.indexConfig.order="desc",this}nullsFirst(){return this.indexConfig.nulls="first",this}nullsLast(){return this.indexConfig.nulls="last",this}op(n){return this.indexConfig.opClass=n,this}}class za{static[J]="IndexedColumn";constructor(n,i,o,c){this.name=n,this.keyAsName=i,this.type=o,this.indexConfig=c}name;keyAsName;type;indexConfig}class H1 extends I{static[J]="PgArrayBuilder";constructor(n,i,o){super(n,"array","PgArray");this.config.baseBuilder=i,this.config.size=o}build(n){let i=this.config.baseBuilder.build(n);return new Sf(n,this.config,i)}}class Sf extends u{constructor(n,i,o,c){super(n,i);this.baseColumn=o,this.range=c,this.size=i.size}size;static[J]="PgArray";getSQLType(){return`${this.baseColumn.getSQLType()}[${typeof this.size==="number"?this.size:""}]`}mapFromDriverValue(n){if(typeof n==="string")n=z1(n);return n.map((i)=>this.baseColumn.mapFromDriverValue(i))}mapToDriverValue(n,i=!1){let o=n.map((c)=>c===null?null:z(this.baseColumn,Sf)?this.baseColumn.mapToDriverValue(c,!0):this.baseColumn.mapToDriverValue(c));if(i)return o;return Jf(o)}}var Af=Symbol.for("drizzle:isPgEnum");function E1(n){return!!n&&typeof n==="function"&&Af in n&&n[Af]===!0}class O1 extends I{static[J]="PgEnumColumnBuilder";constructor(n,i){super(n,"string","PgEnumColumn");this.config.enum=i}build(n){return new U1(n,this.config)}}class U1 extends u{static[J]="PgEnumColumn";enum=this.config.enum;enumValues=this.config.enum.enumValues;constructor(n,i){super(n,i);this.enum=i.enum}getSQLType(){return this.enum.enumName}}function kx(n,i){return UW(n,i,void 0)}function UW(n,i,o){let c=Object.assign((p)=>new O1(p??"",c),{enumName:n,enumValues:i,schema:o,[Af]:!0});return c}class fi{static[J]="Subquery";constructor(n,i,o,c=!1){this._={brand:"Subquery",sql:n,selectedFields:i,alias:o,isWith:c}}}class Qa extends fi{static[J]="WithSubquery"}var V1="0.36.1";var Ff,Mf,Un={startActiveSpan(n,i){if(!Ff)return i();if(!Mf)Mf=Ff.trace.getTracer("drizzle-orm",V1);return Ix((o,c)=>c.startActiveSpan(n,(p)=>{try{return i(p)}catch(a){throw p.setStatus({code:o.SpanStatusCode.ERROR,message:a instanceof Error?a.message:"Unknown error"}),a}finally{p.end()}}),Ff,Mf)}};var hn=Symbol.for("drizzle:ViewBaseConfig");var sx=Symbol.for("drizzle:Schema"),u1=Symbol.for("drizzle:Columns"),_1=Symbol.for("drizzle:ExtraConfigColumns"),Rf=Symbol.for("drizzle:OriginalName"),Wf=Symbol.for("drizzle:BaseName"),b1=Symbol.for("drizzle:IsAlias"),j1=Symbol.for("drizzle:ExtraConfigBuilder"),VW=Symbol.for("drizzle:IsDrizzleTable");class L{static[J]="Table";static Symbol={Name:To,Schema:sx,OriginalName:Rf,Columns:u1,ExtraConfigColumns:_1,BaseName:Wf,IsAlias:b1,ExtraConfigBuilder:j1};[To];[Rf];[sx];[u1];[_1];[Wf];[b1]=!1;[VW]=!0;[j1]=void 0;constructor(n,i,o){this[To]=this[Rf]=n,this[sx]=i,this[Wf]=o}}function di(n){return n[To]}function Oc(n){return`${n[sx]??"public"}.${n[To]}`}function Kf(n){return n!==null&&n!==void 0&&typeof n.getSQL==="function"}function uW(n){let i={sql:"",params:[]};for(let o of n)if(i.sql+=o.sql,i.params.push(...o.params),o.typings?.length){if(!i.typings)i.typings=[];i.typings.push(...o.typings)}return i}class pi{static[J]="StringChunk";value;constructor(n){this.value=Array.isArray(n)?n:[n]}getSQL(){return new k([this])}}class k{constructor(n){this.queryChunks=n}static[J]="SQL";decoder=B1;shouldInlineParams=!1;append(n){return this.queryChunks.push(...n.queryChunks),this}toQuery(n){return Un.startActiveSpan("drizzle.buildSQL",(i)=>{let o=this.buildQueryFromSourceParams(this.queryChunks,n);return i?.setAttributes({"drizzle.query.text":o.sql,"drizzle.query.params":JSON.stringify(o.params)}),o})}buildQueryFromSourceParams(n,i){let o=Object.assign({},i,{inlineParams:i.inlineParams||this.shouldInlineParams,paramStartIndex:i.paramStartIndex||{value:0}}),{casing:c,escapeName:p,escapeParam:a,prepareTyping:x,inlineParams:m,paramStartIndex:l}=o;return uW(n.map((f)=>{if(z(f,pi))return{sql:f.value.join(""),params:[]};if(z(f,Zx))return{sql:p(f.value),params:[]};if(f===void 0)return{sql:"",params:[]};if(Array.isArray(f)){let v=[new pi("(")];for(let[$,T]of f.entries())if(v.push(T),$<f.length-1)v.push(new pi(", "));return v.push(new pi(")")),this.buildQueryFromSourceParams(v,o)}if(z(f,k))return this.buildQueryFromSourceParams(f.queryChunks,{...o,inlineParams:m||f.shouldInlineParams});if(z(f,L)){let v=f[L.Symbol.Schema],$=f[L.Symbol.Name];return{sql:v===void 0?p($):p(v)+"."+p($),params:[]}}if(z(f,bn)){let v=c.getColumnCasing(f);if(i.invokeSource==="indexes")return{sql:p(v),params:[]};return{sql:p(f.table[L.Symbol.Name])+"."+p(v),params:[]}}if(z(f,Vi)){let v=f[hn].schema,$=f[hn].name;return{sql:v===void 0?p($):p(v)+"."+p($),params:[]}}if(z(f,Li)){if(z(f.value,pc))return{sql:a(l.value++,f),params:[f],typings:["none"]};let v=f.value===null?null:f.encoder.mapToDriverValue(f.value);if(z(v,k))return this.buildQueryFromSourceParams([v],o);if(m)return{sql:this.mapInlineParam(v,o),params:[]};let $=["none"];if(x)$=[x(f.encoder)];return{sql:a(l.value++,v),params:[v],typings:$}}if(z(f,pc))return{sql:a(l.value++,f),params:[f],typings:["none"]};if(z(f,k.Aliased)&&f.fieldAlias!==void 0)return{sql:p(f.fieldAlias),params:[]};if(z(f,fi)){if(f._.isWith)return{sql:p(f._.alias),params:[]};return this.buildQueryFromSourceParams([new pi("("),f._.sql,new pi(") "),new Zx(f._.alias)],o)}if(E1(f)){if(f.schema)return{sql:p(f.schema)+"."+p(f.enumName),params:[]};return{sql:p(f.enumName),params:[]}}if(Kf(f)){if(f.shouldOmitSQLParens?.())return this.buildQueryFromSourceParams([f.getSQL()],o);return this.buildQueryFromSourceParams([new pi("("),f.getSQL(),new pi(")")],o)}if(m)return{sql:this.mapInlineParam(f,o),params:[]};return{sql:a(l.value++,f),params:[f],typings:["none"]}}))}mapInlineParam(n,{escapeString:i}){if(n===null)return"null";if(typeof n==="number"||typeof n==="boolean")return n.toString();if(typeof n==="string")return i(n);if(typeof n==="object"){let o=n.toString();if(o==="[object Object]")return i(JSON.stringify(n));return i(o)}throw new Error("Unexpected param value: "+n)}getSQL(){return this}as(n){if(n===void 0)return this;return new k.Aliased(this,n)}mapWith(n){return this.decoder=typeof n==="function"?{mapFromDriverValue:n}:n,this}inlineParams(){return this.shouldInlineParams=!0,this}if(n){return n?this:void 0}}class Zx{constructor(n){this.value=n}static[J]="Name";brand;getSQL(){return new k([this])}}function y1(n){return typeof n==="object"&&n!==null&&"mapToDriverValue"in n&&typeof n.mapToDriverValue==="function"}var B1={mapFromDriverValue:(n)=>n},L1={mapToDriverValue:(n)=>n},d_={...B1,...L1};class Li{constructor(n,i=L1){this.value=n,this.encoder=i}static[J]="Param";brand;getSQL(){return new k([this])}}function S(n,...i){let o=[];if(i.length>0||n.length>0&&n[0]!=="")o.push(new pi(n[0]));for(let[c,p]of i.entries())o.push(p,new pi(n[c+1]));return new k(o)}((n)=>{function i(){return new k([])}n.empty=i;function o(l){return new k(l)}n.fromList=o;function c(l){return new k([new pi(l)])}n.raw=c;function p(l,f){let v=[];for(let[$,T]of l.entries()){if($>0&&f!==void 0)v.push(f);v.push(T)}return new k(v)}n.join=p;function a(l){return new Zx(l)}n.identifier=a;function x(l){return new pc(l)}n.placeholder=x;function m(l,f){return new Li(l,f)}n.param=m})(S||(S={}));((n)=>{class i{constructor(o,c){this.sql=o,this.fieldAlias=c}static[J]="SQL.Aliased";isSelectionField=!1;getSQL(){return this.sql}clone(){return new i(this.sql,this.fieldAlias)}}n.Aliased=i})(k||(k={}));class pc{constructor(n){this.name=n}static[J]="Placeholder";getSQL(){return new k([this])}}function Xf(n,i){return n.map((o)=>{if(z(o,pc)){if(!(o.name in i))throw new Error(`No value for placeholder "${o.name}" was provided`);return i[o.name]}if(z(o,Li)&&z(o.value,pc)){if(!(o.value.name in i))throw new Error(`No value for placeholder "${o.value.name}" was provided`);return o.encoder.mapToDriverValue(i[o.value.name])}return o})}class Vi{static[J]="View";[hn];constructor({name:n,schema:i,selectedFields:o,query:c}){this[hn]={name:n,originalName:n,schema:i,selectedFields:o,query:c,isExisting:!c,isAlias:!1}}getSQL(){return new k([this])}}bn.prototype.getSQL=function(){return new k([this])};L.prototype.getSQL=function(){return new k([this])};fi.prototype.getSQL=function(){return new k([this])};class Ap{constructor(n){this.table=n}static[J]="ColumnAliasProxyHandler";get(n,i){if(i==="table")return this.table;return n[i]}}class Ha{constructor(n,i){this.alias=n,this.replaceOriginalName=i}static[J]="TableAliasProxyHandler";get(n,i){if(i===L.Symbol.IsAlias)return!0;if(i===L.Symbol.Name)return this.alias;if(this.replaceOriginalName&&i===L.Symbol.OriginalName)return this.alias;if(i===hn)return{...n[hn],name:this.alias,isAlias:!0};if(i===L.Symbol.Columns){let c=n[L.Symbol.Columns];if(!c)return c;let p={};return Object.keys(c).map((a)=>{p[a]=new Proxy(c[a],new Ap(new Proxy(n,this)))}),p}let o=n[i];if(z(o,bn))return new Proxy(o,new Ap(new Proxy(n,this)));return o}}function tx(n,i){return new Proxy(n,new Ha(i,!1))}function Ho(n,i){return new Proxy(n,new Ap(new Proxy(n.table,new Ha(i,!1))))}function Gf(n,i){return new k.Aliased(Ea(n.sql,i),n.fieldAlias)}function Ea(n,i){return S.join(n.queryChunks.map((o)=>{if(z(o,bn))return Ho(o,i);if(z(o,k))return Ea(o,i);if(z(o,k.Aliased))return Gf(o,i);return o}))}class qx extends Error{static[J]="DrizzleError";constructor({message:n,cause:i}){super(n);this.name="DrizzleError",this.cause=i}}class Yf extends qx{static[J]="TransactionRollbackError";constructor(){super({message:"Rollback"})}}function ui(n,i){if(y1(i)&&!Kf(n)&&!z(n,Li)&&!z(n,pc)&&!z(n,bn)&&!z(n,L)&&!z(n,Vi))return new Li(n,i);return n}var Eo=(n,i)=>{return S`${n} = ${ui(i,n)}`},N1=(n,i)=>{return S`${n} <> ${ui(i,n)}`};function Uc(...n){let i=n.filter((o)=>o!==void 0);if(i.length===0)return;if(i.length===1)return new k(i);return new k([new pi("("),S.join(i,new pi(" and ")),new pi(")")])}function D1(...n){let i=n.filter((o)=>o!==void 0);if(i.length===0)return;if(i.length===1)return new k(i);return new k([new pi("("),S.join(i,new pi(" or ")),new pi(")")])}function C1(n){return S`not ${n}`}var Px=(n,i)=>{return S`${n} > ${ui(i,n)}`},h1=(n,i)=>{return S`${n} >= ${ui(i,n)}`},I1=(n,i)=>{return S`${n} < ${ui(i,n)}`},k1=(n,i)=>{return S`${n} <= ${ui(i,n)}`};function s1(n,i){if(Array.isArray(i)){if(i.length===0)return S`false`;return S`${n} in ${i.map((o)=>ui(o,n))}`}return S`${n} in ${ui(i,n)}`}function Z1(n,i){if(Array.isArray(i)){if(i.length===0)return S`true`;return S`${n} not in ${i.map((o)=>ui(o,n))}`}return S`${n} not in ${ui(i,n)}`}function t1(n){return S`${n} is null`}function q1(n){return S`${n} is not null`}function P1(n){return S`exists ${n}`}function r1(n){return S`not exists ${n}`}function g1(n,i,o){return S`${n} between ${ui(i,n)} and ${ui(o,n)}`}function d1(n,i,o){return S`${n} not between ${ui(i,n)} and ${ui(o,n)}`}function e1(n,i){return S`${n} like ${i}`}function nw(n,i){return S`${n} not like ${i}`}function iw(n,i){return S`${n} ilike ${i}`}function ow(n,i){return S`${n} not ilike ${i}`}function cw(n){return S`${n} asc`}function pw(n){return S`${n} desc`}class aw{static[J]="ConsoleLogWriter";write(n){console.log(n)}}class zf{static[J]="DefaultLogger";writer;constructor(n){this.writer=n?.writer??new aw}logQuery(n,i){let o=i.map((p)=>{try{return JSON.stringify(p)}catch{return String(p)}}),c=o.length?` -- params: [${o.join(", ")}]`:"";this.writer.write(`Query: ${n}${c}`)}}class Qf{static[J]="NoopLogger";logQuery(){}}class Qi{static[J]="QueryPromise";[Symbol.toStringTag]="QueryPromise";catch(n){return this.then(void 0,n)}finally(n){return this.then((i)=>{return n?.(),i},(i)=>{throw n?.(),i})}then(n,i){return this.execute().then(n,i)}}function xw(n,i,o){let c={},p=n.reduce((a,{path:x,field:m},l)=>{let f;if(z(m,bn))f=m;else if(z(m,k))f=m.decoder;else f=m.sql.decoder;let v=a;for(let[$,T]of x.entries())if($<x.length-1){if(!(T in v))v[T]={};v=v[T]}else{let F=i[l],M=v[T]=F===null?null:f.mapFromDriverValue(F);if(o&&z(m,bn)&&x.length===2){let A=x[0];if(!(A in c))c[A]=M===null?di(m.table):!1;else if(typeof c[A]==="string"&&c[A]!==di(m.table))c[A]=!1}}return a},{});if(o&&Object.keys(c).length>0){for(let[a,x]of Object.entries(c))if(typeof x==="string"&&!o[x])p[a]=null}return p}function ei(n,i){return Object.entries(n).reduce((o,[c,p])=>{if(typeof c!=="string")return o;let a=i?[...i,c]:[c];if(z(p,bn)||z(p,k)||z(p,k.Aliased))o.push({path:a,field:p});else if(z(p,L))o.push(...ei(p[L.Symbol.Columns],a));else o.push(...ei(p,a));return o},[])}function Hf(n,i){let o=Object.keys(n),c=Object.keys(i);if(o.length!==c.length)return!1;for(let[p,a]of o.entries())if(a!==c[p])return!1;return!0}function rx(n,i){let o=Object.entries(i).filter(([,c])=>c!==void 0).map(([c,p])=>{if(z(p,k))return[c,p];else return[c,new Li(p,n[L.Symbol.Columns][c])]});if(o.length===0)throw new Error("No values to set");return Object.fromEntries(o)}function mw(n,i){for(let o of i)for(let c of Object.getOwnPropertyNames(o.prototype)){if(c==="constructor")continue;Object.defineProperty(n.prototype,c,Object.getOwnPropertyDescriptor(o.prototype,c)||Object.create(null))}}function lw(n){return n[L.Symbol.Columns]}function Ef(n){return z(n,fi)?n._.alias:z(n,Vi)?n[hn].name:z(n,k)?void 0:n[L.Symbol.IsAlias]?n[L.Symbol.Name]:n[L.Symbol.BaseName]}function An(n,i){return{name:typeof n==="string"&&n.length>0?n:"",config:typeof n==="object"?n:i}}function fw(n){if(typeof n!=="object"||n===null)return!1;if(n.constructor.name!=="Object")return!1;if("logger"in n){let i=typeof n.logger;if(i!=="boolean"&&(i!=="object"||typeof n.logger.logQuery!=="function")&&i!=="undefined")return!1;return!0}if("schema"in n){let i=typeof n.logger;if(i!=="object"&&i!=="undefined")return!1;return!0}if("casing"in n){let i=typeof n.logger;if(i!=="string"&&i!=="undefined")return!1;return!0}if("mode"in n){if(n.mode!=="default"||n.mode!=="planetscale"||n.mode!==void 0)return!1;return!0}if("connection"in n){let i=typeof n.connection;if(i!=="string"&&i!=="object"&&i!=="undefined")return!1;return!0}if("client"in n){let i=typeof n.client;if(i!=="object"&&i!=="function"&&i!=="undefined")return!1;return!0}if(Object.keys(n).length===0)return!0;return!1}class ac extends I{static[J]="PgIntColumnBaseBuilder";generatedAlwaysAsIdentity(n){if(n){let{name:i,...o}=n;this.config.generatedIdentity={type:"always",sequenceName:i,sequenceOptions:o}}else this.config.generatedIdentity={type:"always"};return this.config.hasDefault=!0,this.config.notNull=!0,this}generatedByDefaultAsIdentity(n){if(n){let{name:i,...o}=n;this.config.generatedIdentity={type:"byDefault",sequenceName:i,sequenceOptions:o}}else this.config.generatedIdentity={type:"byDefault"};return this.config.hasDefault=!0,this.config.notNull=!0,this}}class vw extends ac{static[J]="PgBigInt53Builder";constructor(n){super(n,"number","PgBigInt53")}build(n){return new $w(n,this.config)}}class $w extends u{static[J]="PgBigInt53";getSQLType(){return"bigint"}mapFromDriverValue(n){if(typeof n==="number")return n;return Number(n)}}class Tw extends ac{static[J]="PgBigInt64Builder";constructor(n){super(n,"bigint","PgBigInt64")}build(n){return new ww(n,this.config)}}class ww extends u{static[J]="PgBigInt64";getSQLType(){return"bigint"}mapFromDriverValue(n){return BigInt(n)}}function Jw(n,i){let{name:o,config:c}=An(n,i);if(c.mode==="number")return new vw(o);return new Tw(o)}class Sw extends I{static[J]="PgBigSerial53Builder";constructor(n){super(n,"number","PgBigSerial53");this.config.hasDefault=!0,this.config.notNull=!0}build(n){return new Aw(n,this.config)}}class Aw extends u{static[J]="PgBigSerial53";getSQLType(){return"bigserial"}mapFromDriverValue(n){if(typeof n==="number")return n;return Number(n)}}class Fw extends I{static[J]="PgBigSerial64Builder";constructor(n){super(n,"bigint","PgBigSerial64");this.config.hasDefault=!0}build(n){return new Mw(n,this.config)}}class Mw extends u{static[J]="PgBigSerial64";getSQLType(){return"bigserial"}mapFromDriverValue(n){return BigInt(n)}}function Rw(n,i){let{name:o,config:c}=An(n,i);if(c.mode==="number")return new Sw(o);return new Fw(o)}class Ww extends I{static[J]="PgBooleanBuilder";constructor(n){super(n,"boolean","PgBoolean")}build(n){return new Kw(n,this.config)}}class Kw extends u{static[J]="PgBoolean";getSQLType(){return"boolean"}}function Oa(n){return new Ww(n??"")}class Xw extends I{static[J]="PgCharBuilder";constructor(n,i){super(n,"string","PgChar");this.config.length=i.length,this.config.enumValues=i.enum}build(n){return new Gw(n,this.config)}}class Gw extends u{static[J]="PgChar";length=this.config.length;enumValues=this.config.enumValues;getSQLType(){return this.length===void 0?"char":`char(${this.length})`}}function Yw(n,i={}){let{name:o,config:c}=An(n,i);return new Xw(o,c)}class zw extends I{static[J]="PgCidrBuilder";constructor(n){super(n,"string","PgCidr")}build(n){return new Qw(n,this.config)}}class Qw extends u{static[J]="PgCidr";getSQLType(){return"cidr"}}function Hw(n){return new zw(n??"")}class Ew extends I{static[J]="PgCustomColumnBuilder";constructor(n,i,o){super(n,"custom","PgCustomColumn");this.config.fieldConfig=i,this.config.customTypeParams=o}build(n){return new Ow(n,this.config)}}class Ow extends u{static[J]="PgCustomColumn";sqlName;mapTo;mapFrom;constructor(n,i){super(n,i);this.sqlName=i.customTypeParams.dataType(i.fieldConfig),this.mapTo=i.customTypeParams.toDriver,this.mapFrom=i.customTypeParams.fromDriver}getSQLType(){return this.sqlName}mapFromDriverValue(n){return typeof this.mapFrom==="function"?this.mapFrom(n):n}mapToDriverValue(n){return typeof this.mapTo==="function"?this.mapTo(n):n}}function Uw(n){return(i,o)=>{let{name:c,config:p}=An(i,o);return new Ew(c,p,n)}}class Bo extends I{static[J]="PgDateColumnBaseBuilder";defaultNow(){return this.default(S`now()`)}}class Vw extends Bo{static[J]="PgDateBuilder";constructor(n){super(n,"date","PgDate")}build(n){return new gx(n,this.config)}}class gx extends u{static[J]="PgDate";getSQLType(){return"date"}mapFromDriverValue(n){return new Date(n)}mapToDriverValue(n){return n.toISOString()}}class uw extends Bo{static[J]="PgDateStringBuilder";constructor(n){super(n,"string","PgDateString")}build(n){return new dx(n,this.config)}}class dx extends u{static[J]="PgDateString";getSQLType(){return"date"}}function _w(n,i){let{name:o,config:c}=An(n,i);if(c?.mode==="date")return new Vw(o);return new uw(o)}class bw extends I{static[J]="PgDoublePrecisionBuilder";constructor(n){super(n,"number","PgDoublePrecision")}build(n){return new jw(n,this.config)}}class jw extends u{static[J]="PgDoublePrecision";getSQLType(){return"double precision"}mapFromDriverValue(n){if(typeof n==="string")return Number.parseFloat(n);return n}}function yw(n){return new bw(n??"")}class Bw extends I{static[J]="PgInetBuilder";constructor(n){super(n,"string","PgInet")}build(n){return new Lw(n,this.config)}}class Lw extends u{static[J]="PgInet";getSQLType(){return"inet"}}function Nw(n){return new Bw(n??"")}class Dw extends ac{static[J]="PgIntegerBuilder";constructor(n){super(n,"number","PgInteger")}build(n){return new Cw(n,this.config)}}class Cw extends u{static[J]="PgInteger";getSQLType(){return"integer"}mapFromDriverValue(n){if(typeof n==="string")return Number.parseInt(n);return n}}function ex(n){return new Dw(n??"")}class hw extends I{static[J]="PgIntervalBuilder";constructor(n,i){super(n,"string","PgInterval");this.config.intervalConfig=i}build(n){return new Iw(n,this.config)}}class Iw extends u{static[J]="PgInterval";fields=this.config.intervalConfig.fields;precision=this.config.intervalConfig.precision;getSQLType(){let n=this.fields?` ${this.fields}`:"",i=this.precision?`(${this.precision})`:"";return`interval${n}${i}`}}function kw(n,i={}){let{name:o,config:c}=An(n,i);return new hw(o,c)}class sw extends I{static[J]="PgJsonBuilder";constructor(n){super(n,"json","PgJson")}build(n){return new nm(n,this.config)}}class nm extends u{static[J]="PgJson";constructor(n,i){super(n,i)}getSQLType(){return"json"}mapToDriverValue(n){return JSON.stringify(n)}mapFromDriverValue(n){if(typeof n==="string")try{return JSON.parse(n)}catch{return n}return n}}function Zw(n){return new sw(n??"")}class tw extends I{static[J]="PgJsonbBuilder";constructor(n){super(n,"json","PgJsonb")}build(n){return new im(n,this.config)}}class im extends u{static[J]="PgJsonb";constructor(n,i){super(n,i)}getSQLType(){return"jsonb"}mapToDriverValue(n){return JSON.stringify(n)}mapFromDriverValue(n){if(typeof n==="string")try{return JSON.parse(n)}catch{return n}return n}}function qw(n){return new tw(n??"")}class Pw extends I{static[J]="PgLineBuilder";constructor(n){super(n,"array","PgLine")}build(n){return new rw(n,this.config)}}class rw extends u{static[J]="PgLine";getSQLType(){return"line"}mapFromDriverValue(n){let[i,o,c]=n.slice(1,-1).split(",");return[Number.parseFloat(i),Number.parseFloat(o),Number.parseFloat(c)]}mapToDriverValue(n){return`{${n[0]},${n[1]},${n[2]}}`}}class gw extends I{static[J]="PgLineABCBuilder";constructor(n){super(n,"json","PgLineABC")}build(n){return new dw(n,this.config)}}class dw extends u{static[J]="PgLineABC";getSQLType(){return"line"}mapFromDriverValue(n){let[i,o,c]=n.slice(1,-1).split(",");return{a:Number.parseFloat(i),b:Number.parseFloat(o),c:Number.parseFloat(c)}}mapToDriverValue(n){return`{${n.a},${n.b},${n.c}}`}}function ew(n,i){let{name:o,config:c}=An(n,i);if(!c?.mode||c.mode==="tuple")return new Pw(o);return new gw(o)}class nJ extends I{static[J]="PgMacaddrBuilder";constructor(n){super(n,"string","PgMacaddr")}build(n){return new iJ(n,this.config)}}class iJ extends u{static[J]="PgMacaddr";getSQLType(){return"macaddr"}}function oJ(n){return new nJ(n??"")}class cJ extends I{static[J]="PgMacaddr8Builder";constructor(n){super(n,"string","PgMacaddr8")}build(n){return new pJ(n,this.config)}}class pJ extends u{static[J]="PgMacaddr8";getSQLType(){return"macaddr8"}}function aJ(n){return new cJ(n??"")}class xJ extends I{static[J]="PgNumericBuilder";constructor(n,i,o){super(n,"string","PgNumeric");this.config.precision=i,this.config.scale=o}build(n){return new om(n,this.config)}}class om extends u{static[J]="PgNumeric";precision;scale;constructor(n,i){super(n,i);this.precision=i.precision,this.scale=i.scale}getSQLType(){if(this.precision!==void 0&&this.scale!==void 0)return`numeric(${this.precision}, ${this.scale})`;else if(this.precision===void 0)return"numeric";else return`numeric(${this.precision})`}}function mJ(n,i){let{name:o,config:c}=An(n,i);return new xJ(o,c?.precision,c?.scale)}class lJ extends I{static[J]="PgPointTupleBuilder";constructor(n){super(n,"array","PgPointTuple")}build(n){return new fJ(n,this.config)}}class fJ extends u{static[J]="PgPointTuple";getSQLType(){return"point"}mapFromDriverValue(n){if(typeof n==="string"){let[i,o]=n.slice(1,-1).split(",");return[Number.parseFloat(i),Number.parseFloat(o)]}return[n.x,n.y]}mapToDriverValue(n){return`(${n[0]},${n[1]})`}}class vJ extends I{static[J]="PgPointObjectBuilder";constructor(n){super(n,"json","PgPointObject")}build(n){return new $J(n,this.config)}}class $J extends u{static[J]="PgPointObject";getSQLType(){return"point"}mapFromDriverValue(n){if(typeof n==="string"){let[i,o]=n.slice(1,-1).split(",");return{x:Number.parseFloat(i),y:Number.parseFloat(o)}}return n}mapToDriverValue(n){return`(${n.x},${n.y})`}}function TJ(n,i){let{name:o,config:c}=An(n,i);if(!c?.mode||c.mode==="tuple")return new lJ(o);return new vJ(o)}function _W(n){let i=[];for(let o=0;o<n.length;o+=2)i.push(Number.parseInt(n.slice(o,o+2),16));return new Uint8Array(i)}function wJ(n,i){let o=new ArrayBuffer(8),c=new DataView(o);for(let p=0;p<8;p++)c.setUint8(p,n[i+p]);return c.getFloat64(0,!0)}function Of(n){let i=_W(n),o=0,c=i[o];o+=1;let p=new DataView(i.buffer),a=p.getUint32(o,c===1);o+=4;let x;if(a&536870912)x=p.getUint32(o,c===1),o+=4;if((a&65535)===1){let m=wJ(i,o);o+=8;let l=wJ(i,o);return o+=8,[m,l]}throw new Error("Unsupported geometry type")}class JJ extends I{static[J]="PgGeometryBuilder";constructor(n){super(n,"array","PgGeometry")}build(n){return new SJ(n,this.config)}}class SJ extends u{static[J]="PgGeometry";getSQLType(){return"geometry(point)"}mapFromDriverValue(n){return Of(n)}mapToDriverValue(n){return`point(${n[0]} ${n[1]})`}}class AJ extends I{static[J]="PgGeometryObjectBuilder";constructor(n){super(n,"json","PgGeometryObject")}build(n){return new FJ(n,this.config)}}class FJ extends u{static[J]="PgGeometryObject";getSQLType(){return"geometry(point)"}mapFromDriverValue(n){let i=Of(n);return{x:i[0],y:i[1]}}mapToDriverValue(n){return`point(${n.x} ${n.y})`}}function MJ(n,i){let{name:o,config:c}=An(n,i);if(!c?.mode||c.mode==="tuple")return new JJ(o);return new AJ(o)}class RJ extends I{static[J]="PgRealBuilder";constructor(n,i){super(n,"number","PgReal");this.config.length=i}build(n){return new WJ(n,this.config)}}class WJ extends u{static[J]="PgReal";constructor(n,i){super(n,i)}getSQLType(){return"real"}mapFromDriverValue=(n)=>{if(typeof n==="string")return Number.parseFloat(n);return n}}function KJ(n){return new RJ(n??"")}class XJ extends I{static[J]="PgSerialBuilder";constructor(n){super(n,"number","PgSerial");this.config.hasDefault=!0,this.config.notNull=!0}build(n){return new GJ(n,this.config)}}class GJ extends u{static[J]="PgSerial";getSQLType(){return"serial"}}function YJ(n){return new XJ(n??"")}class zJ extends ac{static[J]="PgSmallIntBuilder";constructor(n){super(n,"number","PgSmallInt")}build(n){return new QJ(n,this.config)}}class QJ extends u{static[J]="PgSmallInt";getSQLType(){return"smallint"}mapFromDriverValue=(n)=>{if(typeof n==="string")return Number(n);return n}}function HJ(n){return new zJ(n??"")}class EJ extends I{static[J]="PgSmallSerialBuilder";constructor(n){super(n,"number","PgSmallSerial");this.config.hasDefault=!0,this.config.notNull=!0}build(n){return new OJ(n,this.config)}}class OJ extends u{static[J]="PgSmallSerial";getSQLType(){return"smallserial"}}function UJ(n){return new EJ(n??"")}class VJ extends I{static[J]="PgTextBuilder";constructor(n,i){super(n,"string","PgText");this.config.enumValues=i.enum}build(n){return new uJ(n,this.config)}}class uJ extends u{static[J]="PgText";enumValues=this.config.enumValues;getSQLType(){return"text"}}function _J(n,i={}){let{name:o,config:c}=An(n,i);return new VJ(o,c)}class bJ extends Bo{constructor(n,i,o){super(n,"string","PgTime");this.withTimezone=i,this.precision=o,this.config.withTimezone=i,this.config.precision=o}static[J]="PgTimeBuilder";build(n){return new cm(n,this.config)}}class cm extends u{static[J]="PgTime";withTimezone;precision;constructor(n,i){super(n,i);this.withTimezone=i.withTimezone,this.precision=i.precision}getSQLType(){return`time${this.precision===void 0?"":`(${this.precision})`}${this.withTimezone?" with time zone":""}`}}function jJ(n,i={}){let{name:o,config:c}=An(n,i);return new bJ(o,c.withTimezone??!1,c.precision)}class yJ extends Bo{static[J]="PgTimestampBuilder";constructor(n,i,o){super(n,"date","PgTimestamp");this.config.withTimezone=i,this.config.precision=o}build(n){return new pm(n,this.config)}}class pm extends u{static[J]="PgTimestamp";withTimezone;precision;constructor(n,i){super(n,i);this.withTimezone=i.withTimezone,this.precision=i.precision}getSQLType(){return`timestamp${this.precision===void 0?"":` (${this.precision})`}${this.withTimezone?" with time zone":""}`}mapFromDriverValue=(n)=>{return new Date(this.withTimezone?n:n+"+0000")};mapToDriverValue=(n)=>{return n.toISOString()}}class BJ extends Bo{static[J]="PgTimestampStringBuilder";constructor(n,i,o){super(n,"string","PgTimestampString");this.config.withTimezone=i,this.config.precision=o}build(n){return new am(n,this.config)}}class am extends u{static[J]="PgTimestampString";withTimezone;precision;constructor(n,i){super(n,i);this.withTimezone=i.withTimezone,this.precision=i.precision}getSQLType(){return`timestamp${this.precision===void 0?"":`(${this.precision})`}${this.withTimezone?" with time zone":""}`}}function wo(n,i={}){let{name:o,config:c}=An(n,i);if(c?.mode==="string")return new BJ(o,c.withTimezone??!1,c.precision);return new yJ(o,c?.withTimezone??!1,c?.precision)}class LJ extends I{static[J]="PgUUIDBuilder";constructor(n){super(n,"string","PgUUID")}defaultRandom(){return this.default(S`gen_random_uuid()`)}build(n){return new xm(n,this.config)}}class xm extends u{static[J]="PgUUID";getSQLType(){return"uuid"}}function Ni(n){return new LJ(n??"")}class NJ extends I{static[J]="PgVarcharBuilder";constructor(n,i){super(n,"string","PgVarchar");this.config.length=i.length,this.config.enumValues=i.enum}build(n){return new DJ(n,this.config)}}class DJ extends u{static[J]="PgVarchar";length=this.config.length;enumValues=this.config.enumValues;getSQLType(){return this.length===void 0?"varchar":`varchar(${this.length})`}}function vi(n,i={}){let{name:o,config:c}=An(n,i);return new NJ(o,c)}class CJ extends I{static[J]="PgBinaryVectorBuilder";constructor(n,i){super(n,"string","PgBinaryVector");this.config.dimensions=i.dimensions}build(n){return new hJ(n,this.config)}}class hJ extends u{static[J]="PgBinaryVector";dimensions=this.config.dimensions;getSQLType(){return`bit(${this.dimensions})`}}function IJ(n,i){let{name:o,config:c}=An(n,i);return new CJ(o,c)}class kJ extends I{static[J]="PgHalfVectorBuilder";constructor(n,i){super(n,"array","PgHalfVector");this.config.dimensions=i.dimensions}build(n){return new sJ(n,this.config)}}class sJ extends u{static[J]="PgHalfVector";dimensions=this.config.dimensions;getSQLType(){return`halfvec(${this.dimensions})`}mapToDriverValue(n){return JSON.stringify(n)}mapFromDriverValue(n){return n.slice(1,-1).split(",").map((i)=>Number.parseFloat(i))}}function ZJ(n,i){let{name:o,config:c}=An(n,i);return new kJ(o,c)}class tJ extends I{static[J]="PgSparseVectorBuilder";constructor(n,i){super(n,"string","PgSparseVector");this.config.dimensions=i.dimensions}build(n){return new qJ(n,this.config)}}class qJ extends u{static[J]="PgSparseVector";dimensions=this.config.dimensions;getSQLType(){return`sparsevec(${this.dimensions})`}}function PJ(n,i){let{name:o,config:c}=An(n,i);return new tJ(o,c)}class rJ extends I{static[J]="PgVectorBuilder";constructor(n,i){super(n,"array","PgVector");this.config.dimensions=i.dimensions}build(n){return new gJ(n,this.config)}}class gJ extends u{static[J]="PgVector";dimensions=this.config.dimensions;getSQLType(){return`vector(${this.dimensions})`}mapToDriverValue(n){return JSON.stringify(n)}mapFromDriverValue(n){return n.slice(1,-1).split(",").map((i)=>Number.parseFloat(i))}}function dJ(n,i){let{name:o,config:c}=An(n,i);return new rJ(o,c)}function eJ(){return{bigint:Jw,bigserial:Rw,boolean:Oa,char:Yw,cidr:Hw,customType:Uw,date:_w,doublePrecision:yw,inet:Nw,integer:ex,interval:kw,json:Zw,jsonb:qw,line:ew,macaddr:oJ,macaddr8:aJ,numeric:mJ,point:TJ,geometry:MJ,real:KJ,serial:YJ,smallint:HJ,smallserial:UJ,text:_J,time:jJ,timestamp:wo,uuid:Ni,varchar:vi,bit:IJ,halfvec:ZJ,sparsevec:PJ,vector:dJ}}var Uf=Symbol.for("drizzle:PgInlineForeignKeys"),nS=Symbol.for("drizzle:EnableRLS");class no extends L{static[J]="PgTable";static Symbol=Object.assign({},L.Symbol,{InlineForeignKeys:Uf,EnableRLS:nS});[Uf]=[];[nS]=!1;[L.Symbol.ExtraConfigBuilder]=void 0}function bW(n,i,o,c,p=n){let a=new no(n,c,p),x=typeof i==="function"?i(eJ()):i,m=Object.fromEntries(Object.entries(x).map(([v,$])=>{let T=$;T.setName(v);let F=T.build(a);return a[Uf].push(...T.buildForeignKeys(F,a)),[v,F]})),l=Object.fromEntries(Object.entries(x).map(([v,$])=>{let T=$;T.setName(v);let F=T.buildExtraConfigColumn(a);return[v,F]})),f=Object.assign(a,m);if(f[L.Symbol.Columns]=m,f[L.Symbol.ExtraConfigColumns]=l,o)f[no.Symbol.ExtraConfigBuilder]=o;return Object.assign(f,{enableRLS:()=>{return f[no.Symbol.EnableRLS]=!0,f}})}var xc=(n,i,o)=>{return bW(n,i,o,void 0)};function iS(...n){if(n[0].columns)return new Ua(n[0].columns,n[0].name);return new Ua(n)}class Ua{static[J]="PgPrimaryKeyBuilder";columns;name;constructor(n,i){this.columns=n,this.name=i}build(n){return new oS(n,this.columns,this.name)}}class oS{constructor(n,i,o){this.table=n,this.columns=i,this.name=o}static[J]="PgPrimaryKey";columns;name;getName(){return this.name??`${this.table[no.Symbol.Name]}_${this.columns.map((n)=>n.name).join("_")}_pk`}}class Vf{constructor(n,i,o){this.sourceTable=n,this.referencedTable=i,this.relationName=o,this.referencedTableName=i[L.Symbol.Name]}static[J]="Relation";referencedTableName;fieldName}class cS{constructor(n,i){this.table=n,this.config=i}static[J]="Relations"}class mc extends Vf{constructor(n,i,o,c){super(n,i,o?.relationName);this.config=o,this.isNullable=c}static[J]="One";withFieldName(n){let i=new mc(this.sourceTable,this.referencedTable,this.config,this.isNullable);return i.fieldName=n,i}}class Va extends Vf{constructor(n,i,o){super(n,i,o?.relationName);this.config=o}static[J]="Many";withFieldName(n){let i=new Va(this.sourceTable,this.referencedTable,this.config);return i.fieldName=n,i}}function pS(){return{and:Uc,between:g1,eq:Eo,exists:P1,gt:Px,gte:h1,ilike:iw,inArray:s1,isNull:t1,isNotNull:q1,like:e1,lt:I1,lte:k1,ne:N1,not:C1,notBetween:d1,notExists:r1,notLike:nw,notIlike:ow,notInArray:Z1,or:D1,sql:S}}function aS(){return{sql:S,asc:cw,desc:pw}}function xS(n,i){if(Object.keys(n).length===1&&"default"in n&&!z(n.default,L))n=n.default;let o={},c={},p={};for(let[a,x]of Object.entries(n))if(z(x,L)){let m=Oc(x),l=c[m];o[m]=a,p[a]={tsName:a,dbName:x[L.Symbol.Name],schema:x[L.Symbol.Schema],columns:x[L.Symbol.Columns],relations:l?.relations??{},primaryKey:l?.primaryKey??[]};for(let v of Object.values(x[L.Symbol.Columns]))if(v.primary)p[a].primaryKey.push(v);let f=x[L.Symbol.ExtraConfigBuilder]?.(x[L.Symbol.ExtraConfigColumns]);if(f){for(let v of Object.values(f))if(z(v,Ua))p[a].primaryKey.push(...v.columns)}}else if(z(x,cS)){let m=Oc(x.table),l=o[m],f=x.config(i(x.table)),v;for(let[$,T]of Object.entries(f))if(l){let F=p[l];if(F.relations[$]=T,v)F.primaryKey.push(...v)}else{if(!(m in c))c[m]={relations:{},primaryKey:v};c[m].relations[$]=T}}return{tables:p,tableNamesMap:o}}function jW(n){return function i(o,c){return new mc(n,o,c,c?.fields.reduce((p,a)=>p&&a.notNull,!0)??!1)}}function yW(n){return function i(o,c){return new Va(n,o,c)}}function mS(n,i,o){if(z(o,mc)&&o.config)return{fields:o.config.fields,references:o.config.references};let c=i[Oc(o.referencedTable)];if(!c)throw new Error(`Table "${o.referencedTable[L.Symbol.Name]}" not found in schema`);let p=n[c];if(!p)throw new Error(`Table "${c}" not found in schema`);let a=o.sourceTable,x=i[Oc(a)];if(!x)throw new Error(`Table "${a[L.Symbol.Name]}" not found in schema`);let m=[];for(let l of Object.values(p.relations))if(o.relationName&&o!==l&&l.relationName===o.relationName||!o.relationName&&l.referencedTable===o.sourceTable)m.push(l);if(m.length>1)throw o.relationName?new Error(`There are multiple relations with name "${o.relationName}" in table "${c}"`):new Error(`There are multiple relations between "${c}" and "${o.sourceTable[L.Symbol.Name]}". Please specify relation name`);if(m[0]&&z(m[0],mc)&&m[0].config)return{fields:m[0].config.references,references:m[0].config.fields};throw new Error(`There is not enough information to infer relation "${x}.${o.fieldName}"`)}function lS(n){return{one:jW(n),many:yW(n)}}function mm(n,i,o,c,p=(a)=>a){let a={};for(let[x,m]of c.entries())if(m.isJson){let l=i.relations[m.tsKey],f=o[x],v=typeof f==="string"?JSON.parse(f):f;a[m.tsKey]=z(l,mc)?v&&mm(n,n[m.relationTableTsKey],v,m.selection,p):v.map(($)=>mm(n,n[m.relationTableTsKey],$,m.selection,p))}else{let l=p(o[x]),f=m.field,v;if(z(f,bn))v=f;else if(z(f,k))v=f.decoder;else v=f.sql.decoder;a[m.tsKey]=l===null?null:v.mapFromDriverValue(l)}return a}var tM=vl(ZM(),1),{Server:qM,Namespace:eL,Socket:nN}=tM.default;import{readFileSync as lR}from"fs";import{resolve as Vv}from"path";var Wn;(function(n){n.assertEqual=(p)=>p;function i(p){}n.assertIs=i;function o(p){throw new Error}n.assertNever=o,n.arrayToEnum=(p)=>{let a={};for(let x of p)a[x]=x;return a},n.getValidEnumValues=(p)=>{let a=n.objectKeys(p).filter((m)=>typeof p[p[m]]!=="number"),x={};for(let m of a)x[m]=p[m];return n.objectValues(x)},n.objectValues=(p)=>{return n.objectKeys(p).map(function(a){return p[a]})},n.objectKeys=typeof Object.keys==="function"?(p)=>Object.keys(p):(p)=>{let a=[];for(let x in p)if(Object.prototype.hasOwnProperty.call(p,x))a.push(x);return a},n.find=(p,a)=>{for(let x of p)if(a(x))return x;return},n.isInteger=typeof Number.isInteger==="function"?(p)=>Number.isInteger(p):(p)=>typeof p==="number"&&isFinite(p)&&Math.floor(p)===p;function c(p,a=" | "){return p.map((x)=>typeof x==="string"?`'${x}'`:x).join(a)}n.joinValues=c,n.jsonStringifyReplacer=(p,a)=>{if(typeof a==="bigint")return a.toString();return a}})(Wn||(Wn={}));var Hv;(function(n){n.mergeShapes=(i,o)=>{return{...i,...o}}})(Hv||(Hv={}));var N=Wn.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Tc=(n)=>{switch(typeof n){case"undefined":return N.undefined;case"string":return N.string;case"number":return isNaN(n)?N.nan:N.number;case"boolean":return N.boolean;case"function":return N.function;case"bigint":return N.bigint;case"symbol":return N.symbol;case"object":if(Array.isArray(n))return N.array;if(n===null)return N.null;if(n.then&&typeof n.then==="function"&&n.catch&&typeof n.catch==="function")return N.promise;if(typeof Map!=="undefined"&&n instanceof Map)return N.map;if(typeof Set!=="undefined"&&n instanceof Set)return N.set;if(typeof Date!=="undefined"&&n instanceof Date)return N.date;return N.object;default:return N.unknown}},O=Wn.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),z5=(n)=>{return JSON.stringify(n,null,2).replace(/"([^"]+)":/g,"$1:")};class Ii extends Error{constructor(n){super();this.issues=[],this.addIssue=(o)=>{this.issues=[...this.issues,o]},this.addIssues=(o=[])=>{this.issues=[...this.issues,...o]};let i=new.target.prototype;if(Object.setPrototypeOf)Object.setPrototypeOf(this,i);else this.__proto__=i;this.name="ZodError",this.issues=n}get errors(){return this.issues}format(n){let i=n||function(p){return p.message},o={_errors:[]},c=(p)=>{for(let a of p.issues)if(a.code==="invalid_union")a.unionErrors.map(c);else if(a.code==="invalid_return_type")c(a.returnTypeError);else if(a.code==="invalid_arguments")c(a.argumentsError);else if(a.path.length===0)o._errors.push(i(a));else{let x=o,m=0;while(m<a.path.length){let l=a.path[m];if(m!==a.path.length-1)x[l]=x[l]||{_errors:[]};else x[l]=x[l]||{_errors:[]},x[l]._errors.push(i(a));x=x[l],m++}}};return c(this),o}static assert(n){if(!(n instanceof Ii))throw new Error(`Not a ZodError: ${n}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,Wn.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(n=(i)=>i.message){let i={},o=[];for(let c of this.issues)if(c.path.length>0)i[c.path[0]]=i[c.path[0]]||[],i[c.path[0]].push(n(c));else o.push(n(c));return{formErrors:o,fieldErrors:i}}get formErrors(){return this.flatten()}}Ii.create=(n)=>{return new Ii(n)};var jp=(n,i)=>{let o;switch(n.code){case O.invalid_type:if(n.received===N.undefined)o="Required";else o=`Expected ${n.expected}, received ${n.received}`;break;case O.invalid_literal:o=`Invalid literal value, expected ${JSON.stringify(n.expected,Wn.jsonStringifyReplacer)}`;break;case O.unrecognized_keys:o=`Unrecognized key(s) in object: ${Wn.joinValues(n.keys,", ")}`;break;case O.invalid_union:o="Invalid input";break;case O.invalid_union_discriminator:o=`Invalid discriminator value. Expected ${Wn.joinValues(n.options)}`;break;case O.invalid_enum_value:o=`Invalid enum value. Expected ${Wn.joinValues(n.options)}, received '${n.received}'`;break;case O.invalid_arguments:o="Invalid function arguments";break;case O.invalid_return_type:o="Invalid function return type";break;case O.invalid_date:o="Invalid date";break;case O.invalid_string:if(typeof n.validation==="object")if("includes"in n.validation){if(o=`Invalid input: must include "${n.validation.includes}"`,typeof n.validation.position==="number")o=`${o} at one or more positions greater than or equal to ${n.validation.position}`}else if("startsWith"in n.validation)o=`Invalid input: must start with "${n.validation.startsWith}"`;else if("endsWith"in n.validation)o=`Invalid input: must end with "${n.validation.endsWith}"`;else Wn.assertNever(n.validation);else if(n.validation!=="regex")o=`Invalid ${n.validation}`;else o="Invalid";break;case O.too_small:if(n.type==="array")o=`Array must contain ${n.exact?"exactly":n.inclusive?"at least":"more than"} ${n.minimum} element(s)`;else if(n.type==="string")o=`String must contain ${n.exact?"exactly":n.inclusive?"at least":"over"} ${n.minimum} character(s)`;else if(n.type==="number")o=`Number must be ${n.exact?"exactly equal to ":n.inclusive?"greater than or equal to ":"greater than "}${n.minimum}`;else if(n.type==="date")o=`Date must be ${n.exact?"exactly equal to ":n.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(n.minimum))}`;else o="Invalid input";break;case O.too_big:if(n.type==="array")o=`Array must contain ${n.exact?"exactly":n.inclusive?"at most":"less than"} ${n.maximum} element(s)`;else if(n.type==="string")o=`String must contain ${n.exact?"exactly":n.inclusive?"at most":"under"} ${n.maximum} character(s)`;else if(n.type==="number")o=`Number must be ${n.exact?"exactly":n.inclusive?"less than or equal to":"less than"} ${n.maximum}`;else if(n.type==="bigint")o=`BigInt must be ${n.exact?"exactly":n.inclusive?"less than or equal to":"less than"} ${n.maximum}`;else if(n.type==="date")o=`Date must be ${n.exact?"exactly":n.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(n.maximum))}`;else o="Invalid input";break;case O.custom:o="Invalid input";break;case O.invalid_intersection_types:o="Intersection results could not be merged";break;case O.not_multiple_of:o=`Number must be a multiple of ${n.multipleOf}`;break;case O.not_finite:o="Number must be finite";break;default:o=i.defaultError,Wn.assertNever(n)}return{message:o}},gM=jp;function Q5(n){gM=n}function bm(){return gM}var jm=(n)=>{let{data:i,path:o,errorMaps:c,issueData:p}=n,a=[...o,...p.path||[]],x={...p,path:a};if(p.message!==void 0)return{...p,path:a,message:p.message};let m="",l=c.filter((f)=>!!f).slice().reverse();for(let f of l)m=f(x,{data:i,defaultError:m}).message;return{...p,path:a,message:m}},H5=[];function B(n,i){let o=bm(),c=jm({issueData:i,data:n.data,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,o,o===jp?void 0:jp].filter((p)=>!!p)});n.common.issues.push(c)}class Xi{constructor(){this.value="valid"}dirty(){if(this.value==="valid")this.value="dirty"}abort(){if(this.value!=="aborted")this.value="aborted"}static mergeArray(n,i){let o=[];for(let c of i){if(c.status==="aborted")return e;if(c.status==="dirty")n.dirty();o.push(c.value)}return{status:n.value,value:o}}static async mergeObjectAsync(n,i){let o=[];for(let c of i){let p=await c.key,a=await c.value;o.push({key:p,value:a})}return Xi.mergeObjectSync(n,o)}static mergeObjectSync(n,i){let o={};for(let c of i){let{key:p,value:a}=c;if(p.status==="aborted")return e;if(a.status==="aborted")return e;if(p.status==="dirty")n.dirty();if(a.status==="dirty")n.dirty();if(p.value!=="__proto__"&&(typeof a.value!=="undefined"||c.alwaysSet))o[p.value]=a.value}return{status:n.value,value:o}}}var e=Object.freeze({status:"aborted"}),_p=(n)=>({status:"dirty",value:n}),Ei=(n)=>({status:"valid",value:n}),Ev=(n)=>n.status==="aborted",Ov=(n)=>n.status==="dirty",Ca=(n)=>n.status==="valid",ha=(n)=>typeof Promise!=="undefined"&&n instanceof Promise;function ym(n,i,o,c){if(o==="a"&&!c)throw new TypeError("Private accessor was defined without a getter");if(typeof i==="function"?n!==i||!c:!i.has(n))throw new TypeError("Cannot read private member from an object whose class did not declare it");return o==="m"?c:o==="a"?c.call(n):c?c.value:i.get(n)}function dM(n,i,o,c,p){if(c==="m")throw new TypeError("Private method is not writable");if(c==="a"&&!p)throw new TypeError("Private accessor was defined without a setter");if(typeof i==="function"?n!==i||!p:!i.has(n))throw new TypeError("Cannot write private member to an object whose class did not declare it");return c==="a"?p.call(n,o):p?p.value=o:i.set(n,o),o}var t;(function(n){n.errToObj=(i)=>typeof i==="string"?{message:i}:i||{},n.toString=(i)=>typeof i==="string"?i:i===null||i===void 0?void 0:i.message})(t||(t={}));var Na,Da;class Ko{constructor(n,i,o,c){this._cachedPath=[],this.parent=n,this.data=i,this._path=o,this._key=c}get path(){if(!this._cachedPath.length)if(this._key instanceof Array)this._cachedPath.push(...this._path,...this._key);else this._cachedPath.push(...this._path,this._key);return this._cachedPath}}var PM=(n,i)=>{if(Ca(i))return{success:!0,data:i.value};else{if(!n.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let o=new Ii(n.common.issues);return this._error=o,this._error}}}};function fn(n){if(!n)return{};let{errorMap:i,invalid_type_error:o,required_error:c,description:p}=n;if(i&&(o||c))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);if(i)return{errorMap:i,description:p};return{errorMap:(x,m)=>{var l,f;let{message:v}=n;if(x.code==="invalid_enum_value")return{message:v!==null&&v!==void 0?v:m.defaultError};if(typeof m.data==="undefined")return{message:(l=v!==null&&v!==void 0?v:c)!==null&&l!==void 0?l:m.defaultError};if(x.code!=="invalid_type")return{message:m.defaultError};return{message:(f=v!==null&&v!==void 0?v:o)!==null&&f!==void 0?f:m.defaultError}},description:p}}class vn{constructor(n){this.spa=this.safeParseAsync,this._def=n,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this)}get description(){return this._def.description}_getType(n){return Tc(n.data)}_getOrReturnCtx(n,i){return i||{common:n.parent.common,data:n.data,parsedType:Tc(n.data),schemaErrorMap:this._def.errorMap,path:n.path,parent:n.parent}}_processInputParams(n){return{status:new Xi,ctx:{common:n.parent.common,data:n.data,parsedType:Tc(n.data),schemaErrorMap:this._def.errorMap,path:n.path,parent:n.parent}}}_parseSync(n){let i=this._parse(n);if(ha(i))throw new Error("Synchronous parse encountered promise.");return i}_parseAsync(n){let i=this._parse(n);return Promise.resolve(i)}parse(n,i){let o=this.safeParse(n,i);if(o.success)return o.data;throw o.error}safeParse(n,i){var o;let c={common:{issues:[],async:(o=i===null||i===void 0?void 0:i.async)!==null&&o!==void 0?o:!1,contextualErrorMap:i===null||i===void 0?void 0:i.errorMap},path:(i===null||i===void 0?void 0:i.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:n,parsedType:Tc(n)},p=this._parseSync({data:n,path:c.path,parent:c});return PM(c,p)}async parseAsync(n,i){let o=await this.safeParseAsync(n,i);if(o.success)return o.data;throw o.error}async safeParseAsync(n,i){let o={common:{issues:[],contextualErrorMap:i===null||i===void 0?void 0:i.errorMap,async:!0},path:(i===null||i===void 0?void 0:i.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:n,parsedType:Tc(n)},c=this._parse({data:n,path:o.path,parent:o}),p=await(ha(c)?c:Promise.resolve(c));return PM(o,p)}refine(n,i){let o=(c)=>{if(typeof i==="string"||typeof i==="undefined")return{message:i};else if(typeof i==="function")return i(c);else return i};return this._refinement((c,p)=>{let a=n(c),x=()=>p.addIssue({code:O.custom,...o(c)});if(typeof Promise!=="undefined"&&a instanceof Promise)return a.then((m)=>{if(!m)return x(),!1;else return!0});if(!a)return x(),!1;else return!0})}refinement(n,i){return this._refinement((o,c)=>{if(!n(o))return c.addIssue(typeof i==="function"?i(o,c):i),!1;else return!0})}_refinement(n){return new co({schema:this,typeName:g.ZodEffects,effect:{type:"refinement",refinement:n}})}superRefine(n){return this._refinement(n)}optional(){return Wo.create(this,this._def)}nullable(){return ho.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Ro.create(this,this._def)}promise(){return hc.create(this,this._def)}or(n){return Np.create([this,n],this._def)}and(n){return Dp.create(this,n,this._def)}transform(n){return new co({...fn(this._def),schema:this,typeName:g.ZodEffects,effect:{type:"transform",transform:n}})}default(n){let i=typeof n==="function"?n:()=>n;return new kp({...fn(this._def),innerType:this,defaultValue:i,typeName:g.ZodDefault})}brand(){return new Lm({typeName:g.ZodBranded,type:this,...fn(this._def)})}catch(n){let i=typeof n==="function"?n:()=>n;return new sp({...fn(this._def),innerType:this,catchValue:i,typeName:g.ZodCatch})}describe(n){return new this.constructor({...this._def,description:n})}pipe(n){return qa.create(this,n)}readonly(){return Zp.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}var E5=/^c[^\s-]{8,}$/i,O5=/^[0-9a-z]+$/,U5=/^[0-9A-HJKMNP-TV-Z]{26}$/,V5=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,u5=/^[a-z0-9_-]{21}$/i,_5=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,b5=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,j5="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Qv,y5=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,B5=/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,L5=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,eM="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",N5=new RegExp(`^${eM}\$`);function nR(n){let i="([01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d";if(n.precision)i=`${i}\\.\\d{${n.precision}}`;else if(n.precision==null)i=`${i}(\\.\\d+)?`;return i}function D5(n){return new RegExp(`^${nR(n)}\$`)}function iR(n){let i=`${eM}T${nR(n)}`,o=[];if(o.push(n.local?"Z?":"Z"),n.offset)o.push("([+-]\\d{2}:?\\d{2})");return i=`${i}(${o.join("|")})`,new RegExp(`^${i}\$`)}function C5(n,i){if((i==="v4"||!i)&&y5.test(n))return!0;if((i==="v6"||!i)&&B5.test(n))return!0;return!1}class Mo extends vn{_parse(n){if(this._def.coerce)n.data=String(n.data);if(this._getType(n)!==N.string){let p=this._getOrReturnCtx(n);return B(p,{code:O.invalid_type,expected:N.string,received:p.parsedType}),e}let o=new Xi,c=void 0;for(let p of this._def.checks)if(p.kind==="min"){if(n.data.length<p.value)c=this._getOrReturnCtx(n,c),B(c,{code:O.too_small,minimum:p.value,type:"string",inclusive:!0,exact:!1,message:p.message}),o.dirty()}else if(p.kind==="max"){if(n.data.length>p.value)c=this._getOrReturnCtx(n,c),B(c,{code:O.too_big,maximum:p.value,type:"string",inclusive:!0,exact:!1,message:p.message}),o.dirty()}else if(p.kind==="length"){let a=n.data.length>p.value,x=n.data.length<p.value;if(a||x){if(c=this._getOrReturnCtx(n,c),a)B(c,{code:O.too_big,maximum:p.value,type:"string",inclusive:!0,exact:!0,message:p.message});else if(x)B(c,{code:O.too_small,minimum:p.value,type:"string",inclusive:!0,exact:!0,message:p.message});o.dirty()}}else if(p.kind==="email"){if(!b5.test(n.data))c=this._getOrReturnCtx(n,c),B(c,{validation:"email",code:O.invalid_string,message:p.message}),o.dirty()}else if(p.kind==="emoji"){if(!Qv)Qv=new RegExp(j5,"u");if(!Qv.test(n.data))c=this._getOrReturnCtx(n,c),B(c,{validation:"emoji",code:O.invalid_string,message:p.message}),o.dirty()}else if(p.kind==="uuid"){if(!V5.test(n.data))c=this._getOrReturnCtx(n,c),B(c,{validation:"uuid",code:O.invalid_string,message:p.message}),o.dirty()}else if(p.kind==="nanoid"){if(!u5.test(n.data))c=this._getOrReturnCtx(n,c),B(c,{validation:"nanoid",code:O.invalid_string,message:p.message}),o.dirty()}else if(p.kind==="cuid"){if(!E5.test(n.data))c=this._getOrReturnCtx(n,c),B(c,{validation:"cuid",code:O.invalid_string,message:p.message}),o.dirty()}else if(p.kind==="cuid2"){if(!O5.test(n.data))c=this._getOrReturnCtx(n,c),B(c,{validation:"cuid2",code:O.invalid_string,message:p.message}),o.dirty()}else if(p.kind==="ulid"){if(!U5.test(n.data))c=this._getOrReturnCtx(n,c),B(c,{validation:"ulid",code:O.invalid_string,message:p.message}),o.dirty()}else if(p.kind==="url")try{new URL(n.data)}catch(a){c=this._getOrReturnCtx(n,c),B(c,{validation:"url",code:O.invalid_string,message:p.message}),o.dirty()}else if(p.kind==="regex"){if(p.regex.lastIndex=0,!p.regex.test(n.data))c=this._getOrReturnCtx(n,c),B(c,{validation:"regex",code:O.invalid_string,message:p.message}),o.dirty()}else if(p.kind==="trim")n.data=n.data.trim();else if(p.kind==="includes"){if(!n.data.includes(p.value,p.position))c=this._getOrReturnCtx(n,c),B(c,{code:O.invalid_string,validation:{includes:p.value,position:p.position},message:p.message}),o.dirty()}else if(p.kind==="toLowerCase")n.data=n.data.toLowerCase();else if(p.kind==="toUpperCase")n.data=n.data.toUpperCase();else if(p.kind==="startsWith"){if(!n.data.startsWith(p.value))c=this._getOrReturnCtx(n,c),B(c,{code:O.invalid_string,validation:{startsWith:p.value},message:p.message}),o.dirty()}else if(p.kind==="endsWith"){if(!n.data.endsWith(p.value))c=this._getOrReturnCtx(n,c),B(c,{code:O.invalid_string,validation:{endsWith:p.value},message:p.message}),o.dirty()}else if(p.kind==="datetime"){if(!iR(p).test(n.data))c=this._getOrReturnCtx(n,c),B(c,{code:O.invalid_string,validation:"datetime",message:p.message}),o.dirty()}else if(p.kind==="date"){if(!N5.test(n.data))c=this._getOrReturnCtx(n,c),B(c,{code:O.invalid_string,validation:"date",message:p.message}),o.dirty()}else if(p.kind==="time"){if(!D5(p).test(n.data))c=this._getOrReturnCtx(n,c),B(c,{code:O.invalid_string,validation:"time",message:p.message}),o.dirty()}else if(p.kind==="duration"){if(!_5.test(n.data))c=this._getOrReturnCtx(n,c),B(c,{validation:"duration",code:O.invalid_string,message:p.message}),o.dirty()}else if(p.kind==="ip"){if(!C5(n.data,p.version))c=this._getOrReturnCtx(n,c),B(c,{validation:"ip",code:O.invalid_string,message:p.message}),o.dirty()}else if(p.kind==="base64"){if(!L5.test(n.data))c=this._getOrReturnCtx(n,c),B(c,{validation:"base64",code:O.invalid_string,message:p.message}),o.dirty()}else Wn.assertNever(p);return{status:o.value,value:n.data}}_regex(n,i,o){return this.refinement((c)=>n.test(c),{validation:i,code:O.invalid_string,...t.errToObj(o)})}_addCheck(n){return new Mo({...this._def,checks:[...this._def.checks,n]})}email(n){return this._addCheck({kind:"email",...t.errToObj(n)})}url(n){return this._addCheck({kind:"url",...t.errToObj(n)})}emoji(n){return this._addCheck({kind:"emoji",...t.errToObj(n)})}uuid(n){return this._addCheck({kind:"uuid",...t.errToObj(n)})}nanoid(n){return this._addCheck({kind:"nanoid",...t.errToObj(n)})}cuid(n){return this._addCheck({kind:"cuid",...t.errToObj(n)})}cuid2(n){return this._addCheck({kind:"cuid2",...t.errToObj(n)})}ulid(n){return this._addCheck({kind:"ulid",...t.errToObj(n)})}base64(n){return this._addCheck({kind:"base64",...t.errToObj(n)})}ip(n){return this._addCheck({kind:"ip",...t.errToObj(n)})}datetime(n){var i,o;if(typeof n==="string")return this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:n});return this._addCheck({kind:"datetime",precision:typeof(n===null||n===void 0?void 0:n.precision)==="undefined"?null:n===null||n===void 0?void 0:n.precision,offset:(i=n===null||n===void 0?void 0:n.offset)!==null&&i!==void 0?i:!1,local:(o=n===null||n===void 0?void 0:n.local)!==null&&o!==void 0?o:!1,...t.errToObj(n===null||n===void 0?void 0:n.message)})}date(n){return this._addCheck({kind:"date",message:n})}time(n){if(typeof n==="string")return this._addCheck({kind:"time",precision:null,message:n});return this._addCheck({kind:"time",precision:typeof(n===null||n===void 0?void 0:n.precision)==="undefined"?null:n===null||n===void 0?void 0:n.precision,...t.errToObj(n===null||n===void 0?void 0:n.message)})}duration(n){return this._addCheck({kind:"duration",...t.errToObj(n)})}regex(n,i){return this._addCheck({kind:"regex",regex:n,...t.errToObj(i)})}includes(n,i){return this._addCheck({kind:"includes",value:n,position:i===null||i===void 0?void 0:i.position,...t.errToObj(i===null||i===void 0?void 0:i.message)})}startsWith(n,i){return this._addCheck({kind:"startsWith",value:n,...t.errToObj(i)})}endsWith(n,i){return this._addCheck({kind:"endsWith",value:n,...t.errToObj(i)})}min(n,i){return this._addCheck({kind:"min",value:n,...t.errToObj(i)})}max(n,i){return this._addCheck({kind:"max",value:n,...t.errToObj(i)})}length(n,i){return this._addCheck({kind:"length",value:n,...t.errToObj(i)})}nonempty(n){return this.min(1,t.errToObj(n))}trim(){return new Mo({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new Mo({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new Mo({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find((n)=>n.kind==="datetime")}get isDate(){return!!this._def.checks.find((n)=>n.kind==="date")}get isTime(){return!!this._def.checks.find((n)=>n.kind==="time")}get isDuration(){return!!this._def.checks.find((n)=>n.kind==="duration")}get isEmail(){return!!this._def.checks.find((n)=>n.kind==="email")}get isURL(){return!!this._def.checks.find((n)=>n.kind==="url")}get isEmoji(){return!!this._def.checks.find((n)=>n.kind==="emoji")}get isUUID(){return!!this._def.checks.find((n)=>n.kind==="uuid")}get isNANOID(){return!!this._def.checks.find((n)=>n.kind==="nanoid")}get isCUID(){return!!this._def.checks.find((n)=>n.kind==="cuid")}get isCUID2(){return!!this._def.checks.find((n)=>n.kind==="cuid2")}get isULID(){return!!this._def.checks.find((n)=>n.kind==="ulid")}get isIP(){return!!this._def.checks.find((n)=>n.kind==="ip")}get isBase64(){return!!this._def.checks.find((n)=>n.kind==="base64")}get minLength(){let n=null;for(let i of this._def.checks)if(i.kind==="min"){if(n===null||i.value>n)n=i.value}return n}get maxLength(){let n=null;for(let i of this._def.checks)if(i.kind==="max"){if(n===null||i.value<n)n=i.value}return n}}Mo.create=(n)=>{var i;return new Mo({checks:[],typeName:g.ZodString,coerce:(i=n===null||n===void 0?void 0:n.coerce)!==null&&i!==void 0?i:!1,...fn(n)})};function h5(n,i){let o=(n.toString().split(".")[1]||"").length,c=(i.toString().split(".")[1]||"").length,p=o>c?o:c,a=parseInt(n.toFixed(p).replace(".","")),x=parseInt(i.toFixed(p).replace(".",""));return a%x/Math.pow(10,p)}class Jc extends vn{constructor(){super(...arguments);this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(n){if(this._def.coerce)n.data=Number(n.data);if(this._getType(n)!==N.number){let p=this._getOrReturnCtx(n);return B(p,{code:O.invalid_type,expected:N.number,received:p.parsedType}),e}let o=void 0,c=new Xi;for(let p of this._def.checks)if(p.kind==="int"){if(!Wn.isInteger(n.data))o=this._getOrReturnCtx(n,o),B(o,{code:O.invalid_type,expected:"integer",received:"float",message:p.message}),c.dirty()}else if(p.kind==="min"){if(p.inclusive?n.data<p.value:n.data<=p.value)o=this._getOrReturnCtx(n,o),B(o,{code:O.too_small,minimum:p.value,type:"number",inclusive:p.inclusive,exact:!1,message:p.message}),c.dirty()}else if(p.kind==="max"){if(p.inclusive?n.data>p.value:n.data>=p.value)o=this._getOrReturnCtx(n,o),B(o,{code:O.too_big,maximum:p.value,type:"number",inclusive:p.inclusive,exact:!1,message:p.message}),c.dirty()}else if(p.kind==="multipleOf"){if(h5(n.data,p.value)!==0)o=this._getOrReturnCtx(n,o),B(o,{code:O.not_multiple_of,multipleOf:p.value,message:p.message}),c.dirty()}else if(p.kind==="finite"){if(!Number.isFinite(n.data))o=this._getOrReturnCtx(n,o),B(o,{code:O.not_finite,message:p.message}),c.dirty()}else Wn.assertNever(p);return{status:c.value,value:n.data}}gte(n,i){return this.setLimit("min",n,!0,t.toString(i))}gt(n,i){return this.setLimit("min",n,!1,t.toString(i))}lte(n,i){return this.setLimit("max",n,!0,t.toString(i))}lt(n,i){return this.setLimit("max",n,!1,t.toString(i))}setLimit(n,i,o,c){return new Jc({...this._def,checks:[...this._def.checks,{kind:n,value:i,inclusive:o,message:t.toString(c)}]})}_addCheck(n){return new Jc({...this._def,checks:[...this._def.checks,n]})}int(n){return this._addCheck({kind:"int",message:t.toString(n)})}positive(n){return this._addCheck({kind:"min",value:0,inclusive:!1,message:t.toString(n)})}negative(n){return this._addCheck({kind:"max",value:0,inclusive:!1,message:t.toString(n)})}nonpositive(n){return this._addCheck({kind:"max",value:0,inclusive:!0,message:t.toString(n)})}nonnegative(n){return this._addCheck({kind:"min",value:0,inclusive:!0,message:t.toString(n)})}multipleOf(n,i){return this._addCheck({kind:"multipleOf",value:n,message:t.toString(i)})}finite(n){return this._addCheck({kind:"finite",message:t.toString(n)})}safe(n){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:t.toString(n)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:t.toString(n)})}get minValue(){let n=null;for(let i of this._def.checks)if(i.kind==="min"){if(n===null||i.value>n)n=i.value}return n}get maxValue(){let n=null;for(let i of this._def.checks)if(i.kind==="max"){if(n===null||i.value<n)n=i.value}return n}get isInt(){return!!this._def.checks.find((n)=>n.kind==="int"||n.kind==="multipleOf"&&Wn.isInteger(n.value))}get isFinite(){let n=null,i=null;for(let o of this._def.checks)if(o.kind==="finite"||o.kind==="int"||o.kind==="multipleOf")return!0;else if(o.kind==="min"){if(i===null||o.value>i)i=o.value}else if(o.kind==="max"){if(n===null||o.value<n)n=o.value}return Number.isFinite(i)&&Number.isFinite(n)}}Jc.create=(n)=>{return new Jc({checks:[],typeName:g.ZodNumber,coerce:(n===null||n===void 0?void 0:n.coerce)||!1,...fn(n)})};class Sc extends vn{constructor(){super(...arguments);this.min=this.gte,this.max=this.lte}_parse(n){if(this._def.coerce)n.data=BigInt(n.data);if(this._getType(n)!==N.bigint){let p=this._getOrReturnCtx(n);return B(p,{code:O.invalid_type,expected:N.bigint,received:p.parsedType}),e}let o=void 0,c=new Xi;for(let p of this._def.checks)if(p.kind==="min"){if(p.inclusive?n.data<p.value:n.data<=p.value)o=this._getOrReturnCtx(n,o),B(o,{code:O.too_small,type:"bigint",minimum:p.value,inclusive:p.inclusive,message:p.message}),c.dirty()}else if(p.kind==="max"){if(p.inclusive?n.data>p.value:n.data>=p.value)o=this._getOrReturnCtx(n,o),B(o,{code:O.too_big,type:"bigint",maximum:p.value,inclusive:p.inclusive,message:p.message}),c.dirty()}else if(p.kind==="multipleOf"){if(n.data%p.value!==BigInt(0))o=this._getOrReturnCtx(n,o),B(o,{code:O.not_multiple_of,multipleOf:p.value,message:p.message}),c.dirty()}else Wn.assertNever(p);return{status:c.value,value:n.data}}gte(n,i){return this.setLimit("min",n,!0,t.toString(i))}gt(n,i){return this.setLimit("min",n,!1,t.toString(i))}lte(n,i){return this.setLimit("max",n,!0,t.toString(i))}lt(n,i){return this.setLimit("max",n,!1,t.toString(i))}setLimit(n,i,o,c){return new Sc({...this._def,checks:[...this._def.checks,{kind:n,value:i,inclusive:o,message:t.toString(c)}]})}_addCheck(n){return new Sc({...this._def,checks:[...this._def.checks,n]})}positive(n){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:t.toString(n)})}negative(n){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:t.toString(n)})}nonpositive(n){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:t.toString(n)})}nonnegative(n){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:t.toString(n)})}multipleOf(n,i){return this._addCheck({kind:"multipleOf",value:n,message:t.toString(i)})}get minValue(){let n=null;for(let i of this._def.checks)if(i.kind==="min"){if(n===null||i.value>n)n=i.value}return n}get maxValue(){let n=null;for(let i of this._def.checks)if(i.kind==="max"){if(n===null||i.value<n)n=i.value}return n}}Sc.create=(n)=>{var i;return new Sc({checks:[],typeName:g.ZodBigInt,coerce:(i=n===null||n===void 0?void 0:n.coerce)!==null&&i!==void 0?i:!1,...fn(n)})};class yp extends vn{_parse(n){if(this._def.coerce)n.data=Boolean(n.data);if(this._getType(n)!==N.boolean){let o=this._getOrReturnCtx(n);return B(o,{code:O.invalid_type,expected:N.boolean,received:o.parsedType}),e}return Ei(n.data)}}yp.create=(n)=>{return new yp({typeName:g.ZodBoolean,coerce:(n===null||n===void 0?void 0:n.coerce)||!1,...fn(n)})};class Nc extends vn{_parse(n){if(this._def.coerce)n.data=new Date(n.data);if(this._getType(n)!==N.date){let p=this._getOrReturnCtx(n);return B(p,{code:O.invalid_type,expected:N.date,received:p.parsedType}),e}if(isNaN(n.data.getTime())){let p=this._getOrReturnCtx(n);return B(p,{code:O.invalid_date}),e}let o=new Xi,c=void 0;for(let p of this._def.checks)if(p.kind==="min"){if(n.data.getTime()<p.value)c=this._getOrReturnCtx(n,c),B(c,{code:O.too_small,message:p.message,inclusive:!0,exact:!1,minimum:p.value,type:"date"}),o.dirty()}else if(p.kind==="max"){if(n.data.getTime()>p.value)c=this._getOrReturnCtx(n,c),B(c,{code:O.too_big,message:p.message,inclusive:!0,exact:!1,maximum:p.value,type:"date"}),o.dirty()}else Wn.assertNever(p);return{status:o.value,value:new Date(n.data.getTime())}}_addCheck(n){return new Nc({...this._def,checks:[...this._def.checks,n]})}min(n,i){return this._addCheck({kind:"min",value:n.getTime(),message:t.toString(i)})}max(n,i){return this._addCheck({kind:"max",value:n.getTime(),message:t.toString(i)})}get minDate(){let n=null;for(let i of this._def.checks)if(i.kind==="min"){if(n===null||i.value>n)n=i.value}return n!=null?new Date(n):null}get maxDate(){let n=null;for(let i of this._def.checks)if(i.kind==="max"){if(n===null||i.value<n)n=i.value}return n!=null?new Date(n):null}}Nc.create=(n)=>{return new Nc({checks:[],coerce:(n===null||n===void 0?void 0:n.coerce)||!1,typeName:g.ZodDate,...fn(n)})};class Ia extends vn{_parse(n){if(this._getType(n)!==N.symbol){let o=this._getOrReturnCtx(n);return B(o,{code:O.invalid_type,expected:N.symbol,received:o.parsedType}),e}return Ei(n.data)}}Ia.create=(n)=>{return new Ia({typeName:g.ZodSymbol,...fn(n)})};class Bp extends vn{_parse(n){if(this._getType(n)!==N.undefined){let o=this._getOrReturnCtx(n);return B(o,{code:O.invalid_type,expected:N.undefined,received:o.parsedType}),e}return Ei(n.data)}}Bp.create=(n)=>{return new Bp({typeName:g.ZodUndefined,...fn(n)})};class Lp extends vn{_parse(n){if(this._getType(n)!==N.null){let o=this._getOrReturnCtx(n);return B(o,{code:O.invalid_type,expected:N.null,received:o.parsedType}),e}return Ei(n.data)}}Lp.create=(n)=>{return new Lp({typeName:g.ZodNull,...fn(n)})};class Dc extends vn{constructor(){super(...arguments);this._any=!0}_parse(n){return Ei(n.data)}}Dc.create=(n)=>{return new Dc({typeName:g.ZodAny,...fn(n)})};class wc extends vn{constructor(){super(...arguments);this._unknown=!0}_parse(n){return Ei(n.data)}}wc.create=(n)=>{return new wc({typeName:g.ZodUnknown,...fn(n)})};class Uo extends vn{_parse(n){let i=this._getOrReturnCtx(n);return B(i,{code:O.invalid_type,expected:N.never,received:i.parsedType}),e}}Uo.create=(n)=>{return new Uo({typeName:g.ZodNever,...fn(n)})};class ka extends vn{_parse(n){if(this._getType(n)!==N.undefined){let o=this._getOrReturnCtx(n);return B(o,{code:O.invalid_type,expected:N.void,received:o.parsedType}),e}return Ei(n.data)}}ka.create=(n)=>{return new ka({typeName:g.ZodVoid,...fn(n)})};class Ro extends vn{_parse(n){let{ctx:i,status:o}=this._processInputParams(n),c=this._def;if(i.parsedType!==N.array)return B(i,{code:O.invalid_type,expected:N.array,received:i.parsedType}),e;if(c.exactLength!==null){let a=i.data.length>c.exactLength.value,x=i.data.length<c.exactLength.value;if(a||x)B(i,{code:a?O.too_big:O.too_small,minimum:x?c.exactLength.value:void 0,maximum:a?c.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:c.exactLength.message}),o.dirty()}if(c.minLength!==null){if(i.data.length<c.minLength.value)B(i,{code:O.too_small,minimum:c.minLength.value,type:"array",inclusive:!0,exact:!1,message:c.minLength.message}),o.dirty()}if(c.maxLength!==null){if(i.data.length>c.maxLength.value)B(i,{code:O.too_big,maximum:c.maxLength.value,type:"array",inclusive:!0,exact:!1,message:c.maxLength.message}),o.dirty()}if(i.common.async)return Promise.all([...i.data].map((a,x)=>{return c.type._parseAsync(new Ko(i,a,i.path,x))})).then((a)=>{return Xi.mergeArray(o,a)});let p=[...i.data].map((a,x)=>{return c.type._parseSync(new Ko(i,a,i.path,x))});return Xi.mergeArray(o,p)}get element(){return this._def.type}min(n,i){return new Ro({...this._def,minLength:{value:n,message:t.toString(i)}})}max(n,i){return new Ro({...this._def,maxLength:{value:n,message:t.toString(i)}})}length(n,i){return new Ro({...this._def,exactLength:{value:n,message:t.toString(i)}})}nonempty(n){return this.min(1,n)}}Ro.create=(n,i)=>{return new Ro({type:n,minLength:null,maxLength:null,exactLength:null,typeName:g.ZodArray,...fn(i)})};function up(n){if(n instanceof In){let i={};for(let o in n.shape){let c=n.shape[o];i[o]=Wo.create(up(c))}return new In({...n._def,shape:()=>i})}else if(n instanceof Ro)return new Ro({...n._def,type:up(n.element)});else if(n instanceof Wo)return Wo.create(up(n.unwrap()));else if(n instanceof ho)return ho.create(up(n.unwrap()));else if(n instanceof Vo)return Vo.create(n.items.map((i)=>up(i)));else return n}class In extends vn{constructor(){super(...arguments);this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let n=this._def.shape(),i=Wn.objectKeys(n);return this._cached={shape:n,keys:i}}_parse(n){if(this._getType(n)!==N.object){let l=this._getOrReturnCtx(n);return B(l,{code:O.invalid_type,expected:N.object,received:l.parsedType}),e}let{status:o,ctx:c}=this._processInputParams(n),{shape:p,keys:a}=this._getCached(),x=[];if(!(this._def.catchall instanceof Uo&&this._def.unknownKeys==="strip")){for(let l in c.data)if(!a.includes(l))x.push(l)}let m=[];for(let l of a){let f=p[l],v=c.data[l];m.push({key:{status:"valid",value:l},value:f._parse(new Ko(c,v,c.path,l)),alwaysSet:l in c.data})}if(this._def.catchall instanceof Uo){let l=this._def.unknownKeys;if(l==="passthrough")for(let f of x)m.push({key:{status:"valid",value:f},value:{status:"valid",value:c.data[f]}});else if(l==="strict"){if(x.length>0)B(c,{code:O.unrecognized_keys,keys:x}),o.dirty()}else if(l==="strip");else throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let l=this._def.catchall;for(let f of x){let v=c.data[f];m.push({key:{status:"valid",value:f},value:l._parse(new Ko(c,v,c.path,f)),alwaysSet:f in c.data})}}if(c.common.async)return Promise.resolve().then(async()=>{let l=[];for(let f of m){let v=await f.key,$=await f.value;l.push({key:v,value:$,alwaysSet:f.alwaysSet})}return l}).then((l)=>{return Xi.mergeObjectSync(o,l)});else return Xi.mergeObjectSync(o,m)}get shape(){return this._def.shape()}strict(n){return t.errToObj,new In({...this._def,unknownKeys:"strict",...n!==void 0?{errorMap:(i,o)=>{var c,p,a,x;let m=(a=(p=(c=this._def).errorMap)===null||p===void 0?void 0:p.call(c,i,o).message)!==null&&a!==void 0?a:o.defaultError;if(i.code==="unrecognized_keys")return{message:(x=t.errToObj(n).message)!==null&&x!==void 0?x:m};return{message:m}}}:{}})}strip(){return new In({...this._def,unknownKeys:"strip"})}passthrough(){return new In({...this._def,unknownKeys:"passthrough"})}extend(n){return new In({...this._def,shape:()=>({...this._def.shape(),...n})})}merge(n){return new In({unknownKeys:n._def.unknownKeys,catchall:n._def.catchall,shape:()=>({...this._def.shape(),...n._def.shape()}),typeName:g.ZodObject})}setKey(n,i){return this.augment({[n]:i})}catchall(n){return new In({...this._def,catchall:n})}pick(n){let i={};return Wn.objectKeys(n).forEach((o)=>{if(n[o]&&this.shape[o])i[o]=this.shape[o]}),new In({...this._def,shape:()=>i})}omit(n){let i={};return Wn.objectKeys(this.shape).forEach((o)=>{if(!n[o])i[o]=this.shape[o]}),new In({...this._def,shape:()=>i})}deepPartial(){return up(this)}partial(n){let i={};return Wn.objectKeys(this.shape).forEach((o)=>{let c=this.shape[o];if(n&&!n[o])i[o]=c;else i[o]=c.optional()}),new In({...this._def,shape:()=>i})}required(n){let i={};return Wn.objectKeys(this.shape).forEach((o)=>{if(n&&!n[o])i[o]=this.shape[o];else{let p=this.shape[o];while(p instanceof Wo)p=p._def.innerType;i[o]=p}}),new In({...this._def,shape:()=>i})}keyof(){return oR(Wn.objectKeys(this.shape))}}In.create=(n,i)=>{return new In({shape:()=>n,unknownKeys:"strip",catchall:Uo.create(),typeName:g.ZodObject,...fn(i)})};In.strictCreate=(n,i)=>{return new In({shape:()=>n,unknownKeys:"strict",catchall:Uo.create(),typeName:g.ZodObject,...fn(i)})};In.lazycreate=(n,i)=>{return new In({shape:n,unknownKeys:"strip",catchall:Uo.create(),typeName:g.ZodObject,...fn(i)})};class Np extends vn{_parse(n){let{ctx:i}=this._processInputParams(n),o=this._def.options;function c(p){for(let x of p)if(x.result.status==="valid")return x.result;for(let x of p)if(x.result.status==="dirty")return i.common.issues.push(...x.ctx.common.issues),x.result;let a=p.map((x)=>new Ii(x.ctx.common.issues));return B(i,{code:O.invalid_union,unionErrors:a}),e}if(i.common.async)return Promise.all(o.map(async(p)=>{let a={...i,common:{...i.common,issues:[]},parent:null};return{result:await p._parseAsync({data:i.data,path:i.path,parent:a}),ctx:a}})).then(c);else{let p=void 0,a=[];for(let m of o){let l={...i,common:{...i.common,issues:[]},parent:null},f=m._parseSync({data:i.data,path:i.path,parent:l});if(f.status==="valid")return f;else if(f.status==="dirty"&&!p)p={result:f,ctx:l};if(l.common.issues.length)a.push(l.common.issues)}if(p)return i.common.issues.push(...p.ctx.common.issues),p.result;let x=a.map((m)=>new Ii(m));return B(i,{code:O.invalid_union,unionErrors:x}),e}}get options(){return this._def.options}}Np.create=(n,i)=>{return new Np({options:n,typeName:g.ZodUnion,...fn(i)})};var Co=(n)=>{if(n instanceof Cp)return Co(n.schema);else if(n instanceof co)return Co(n.innerType());else if(n instanceof hp)return[n.value];else if(n instanceof Ac)return n.options;else if(n instanceof Ip)return Wn.objectValues(n.enum);else if(n instanceof kp)return Co(n._def.innerType);else if(n instanceof Bp)return[void 0];else if(n instanceof Lp)return[null];else if(n instanceof Wo)return[void 0,...Co(n.unwrap())];else if(n instanceof ho)return[null,...Co(n.unwrap())];else if(n instanceof Lm)return Co(n.unwrap());else if(n instanceof Zp)return Co(n.unwrap());else if(n instanceof sp)return Co(n._def.innerType);else return[]};class Bm extends vn{_parse(n){let{ctx:i}=this._processInputParams(n);if(i.parsedType!==N.object)return B(i,{code:O.invalid_type,expected:N.object,received:i.parsedType}),e;let o=this.discriminator,c=i.data[o],p=this.optionsMap.get(c);if(!p)return B(i,{code:O.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[o]}),e;if(i.common.async)return p._parseAsync({data:i.data,path:i.path,parent:i});else return p._parseSync({data:i.data,path:i.path,parent:i})}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(n,i,o){let c=new Map;for(let p of i){let a=Co(p.shape[n]);if(!a.length)throw new Error(`A discriminator value for key \`${n}\` could not be extracted from all schema options`);for(let x of a){if(c.has(x))throw new Error(`Discriminator property ${String(n)} has duplicate value ${String(x)}`);c.set(x,p)}}return new Bm({typeName:g.ZodDiscriminatedUnion,discriminator:n,options:i,optionsMap:c,...fn(o)})}}function Uv(n,i){let o=Tc(n),c=Tc(i);if(n===i)return{valid:!0,data:n};else if(o===N.object&&c===N.object){let p=Wn.objectKeys(i),a=Wn.objectKeys(n).filter((m)=>p.indexOf(m)!==-1),x={...n,...i};for(let m of a){let l=Uv(n[m],i[m]);if(!l.valid)return{valid:!1};x[m]=l.data}return{valid:!0,data:x}}else if(o===N.array&&c===N.array){if(n.length!==i.length)return{valid:!1};let p=[];for(let a=0;a<n.length;a++){let x=n[a],m=i[a],l=Uv(x,m);if(!l.valid)return{valid:!1};p.push(l.data)}return{valid:!0,data:p}}else if(o===N.date&&c===N.date&&+n===+i)return{valid:!0,data:n};else return{valid:!1}}class Dp extends vn{_parse(n){let{status:i,ctx:o}=this._processInputParams(n),c=(p,a)=>{if(Ev(p)||Ev(a))return e;let x=Uv(p.value,a.value);if(!x.valid)return B(o,{code:O.invalid_intersection_types}),e;if(Ov(p)||Ov(a))i.dirty();return{status:i.value,value:x.data}};if(o.common.async)return Promise.all([this._def.left._parseAsync({data:o.data,path:o.path,parent:o}),this._def.right._parseAsync({data:o.data,path:o.path,parent:o})]).then(([p,a])=>c(p,a));else return c(this._def.left._parseSync({data:o.data,path:o.path,parent:o}),this._def.right._parseSync({data:o.data,path:o.path,parent:o}))}}Dp.create=(n,i,o)=>{return new Dp({left:n,right:i,typeName:g.ZodIntersection,...fn(o)})};class Vo extends vn{_parse(n){let{status:i,ctx:o}=this._processInputParams(n);if(o.parsedType!==N.array)return B(o,{code:O.invalid_type,expected:N.array,received:o.parsedType}),e;if(o.data.length<this._def.items.length)return B(o,{code:O.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),e;if(!this._def.rest&&o.data.length>this._def.items.length)B(o,{code:O.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),i.dirty();let p=[...o.data].map((a,x)=>{let m=this._def.items[x]||this._def.rest;if(!m)return null;return m._parse(new Ko(o,a,o.path,x))}).filter((a)=>!!a);if(o.common.async)return Promise.all(p).then((a)=>{return Xi.mergeArray(i,a)});else return Xi.mergeArray(i,p)}get items(){return this._def.items}rest(n){return new Vo({...this._def,rest:n})}}Vo.create=(n,i)=>{if(!Array.isArray(n))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Vo({items:n,typeName:g.ZodTuple,rest:null,...fn(i)})};class sa extends vn{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(n){let{status:i,ctx:o}=this._processInputParams(n);if(o.parsedType!==N.object)return B(o,{code:O.invalid_type,expected:N.object,received:o.parsedType}),e;let c=[],p=this._def.keyType,a=this._def.valueType;for(let x in o.data)c.push({key:p._parse(new Ko(o,x,o.path,x)),value:a._parse(new Ko(o,o.data[x],o.path,x)),alwaysSet:x in o.data});if(o.common.async)return Xi.mergeObjectAsync(i,c);else return Xi.mergeObjectSync(i,c)}get element(){return this._def.valueType}static create(n,i,o){if(i instanceof vn)return new sa({keyType:n,valueType:i,typeName:g.ZodRecord,...fn(o)});return new sa({keyType:Mo.create(),valueType:n,typeName:g.ZodRecord,...fn(i)})}}class Za extends vn{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(n){let{status:i,ctx:o}=this._processInputParams(n);if(o.parsedType!==N.map)return B(o,{code:O.invalid_type,expected:N.map,received:o.parsedType}),e;let c=this._def.keyType,p=this._def.valueType,a=[...o.data.entries()].map(([x,m],l)=>{return{key:c._parse(new Ko(o,x,o.path,[l,"key"])),value:p._parse(new Ko(o,m,o.path,[l,"value"]))}});if(o.common.async){let x=new Map;return Promise.resolve().then(async()=>{for(let m of a){let l=await m.key,f=await m.value;if(l.status==="aborted"||f.status==="aborted")return e;if(l.status==="dirty"||f.status==="dirty")i.dirty();x.set(l.value,f.value)}return{status:i.value,value:x}})}else{let x=new Map;for(let m of a){let{key:l,value:f}=m;if(l.status==="aborted"||f.status==="aborted")return e;if(l.status==="dirty"||f.status==="dirty")i.dirty();x.set(l.value,f.value)}return{status:i.value,value:x}}}}Za.create=(n,i,o)=>{return new Za({valueType:i,keyType:n,typeName:g.ZodMap,...fn(o)})};class Cc extends vn{_parse(n){let{status:i,ctx:o}=this._processInputParams(n);if(o.parsedType!==N.set)return B(o,{code:O.invalid_type,expected:N.set,received:o.parsedType}),e;let c=this._def;if(c.minSize!==null){if(o.data.size<c.minSize.value)B(o,{code:O.too_small,minimum:c.minSize.value,type:"set",inclusive:!0,exact:!1,message:c.minSize.message}),i.dirty()}if(c.maxSize!==null){if(o.data.size>c.maxSize.value)B(o,{code:O.too_big,maximum:c.maxSize.value,type:"set",inclusive:!0,exact:!1,message:c.maxSize.message}),i.dirty()}let p=this._def.valueType;function a(m){let l=new Set;for(let f of m){if(f.status==="aborted")return e;if(f.status==="dirty")i.dirty();l.add(f.value)}return{status:i.value,value:l}}let x=[...o.data.values()].map((m,l)=>p._parse(new Ko(o,m,o.path,l)));if(o.common.async)return Promise.all(x).then((m)=>a(m));else return a(x)}min(n,i){return new Cc({...this._def,minSize:{value:n,message:t.toString(i)}})}max(n,i){return new Cc({...this._def,maxSize:{value:n,message:t.toString(i)}})}size(n,i){return this.min(n,i).max(n,i)}nonempty(n){return this.min(1,n)}}Cc.create=(n,i)=>{return new Cc({valueType:n,minSize:null,maxSize:null,typeName:g.ZodSet,...fn(i)})};class bp extends vn{constructor(){super(...arguments);this.validate=this.implement}_parse(n){let{ctx:i}=this._processInputParams(n);if(i.parsedType!==N.function)return B(i,{code:O.invalid_type,expected:N.function,received:i.parsedType}),e;function o(x,m){return jm({data:x,path:i.path,errorMaps:[i.common.contextualErrorMap,i.schemaErrorMap,bm(),jp].filter((l)=>!!l),issueData:{code:O.invalid_arguments,argumentsError:m}})}function c(x,m){return jm({data:x,path:i.path,errorMaps:[i.common.contextualErrorMap,i.schemaErrorMap,bm(),jp].filter((l)=>!!l),issueData:{code:O.invalid_return_type,returnTypeError:m}})}let p={errorMap:i.common.contextualErrorMap},a=i.data;if(this._def.returns instanceof hc){let x=this;return Ei(async function(...m){let l=new Ii([]),f=await x._def.args.parseAsync(m,p).catch((T)=>{throw l.addIssue(o(m,T)),l}),v=await Reflect.apply(a,this,f);return await x._def.returns._def.type.parseAsync(v,p).catch((T)=>{throw l.addIssue(c(v,T)),l})})}else{let x=this;return Ei(function(...m){let l=x._def.args.safeParse(m,p);if(!l.success)throw new Ii([o(m,l.error)]);let f=Reflect.apply(a,this,l.data),v=x._def.returns.safeParse(f,p);if(!v.success)throw new Ii([c(f,v.error)]);return v.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...n){return new bp({...this._def,args:Vo.create(n).rest(wc.create())})}returns(n){return new bp({...this._def,returns:n})}implement(n){return this.parse(n)}strictImplement(n){return this.parse(n)}static create(n,i,o){return new bp({args:n?n:Vo.create([]).rest(wc.create()),returns:i||wc.create(),typeName:g.ZodFunction,...fn(o)})}}class Cp extends vn{get schema(){return this._def.getter()}_parse(n){let{ctx:i}=this._processInputParams(n);return this._def.getter()._parse({data:i.data,path:i.path,parent:i})}}Cp.create=(n,i)=>{return new Cp({getter:n,typeName:g.ZodLazy,...fn(i)})};class hp extends vn{_parse(n){if(n.data!==this._def.value){let i=this._getOrReturnCtx(n);return B(i,{received:i.data,code:O.invalid_literal,expected:this._def.value}),e}return{status:"valid",value:n.data}}get value(){return this._def.value}}hp.create=(n,i)=>{return new hp({value:n,typeName:g.ZodLiteral,...fn(i)})};function oR(n,i){return new Ac({values:n,typeName:g.ZodEnum,...fn(i)})}class Ac extends vn{constructor(){super(...arguments);Na.set(this,void 0)}_parse(n){if(typeof n.data!=="string"){let i=this._getOrReturnCtx(n),o=this._def.values;return B(i,{expected:Wn.joinValues(o),received:i.parsedType,code:O.invalid_type}),e}if(!ym(this,Na,"f"))dM(this,Na,new Set(this._def.values),"f");if(!ym(this,Na,"f").has(n.data)){let i=this._getOrReturnCtx(n),o=this._def.values;return B(i,{received:i.data,code:O.invalid_enum_value,options:o}),e}return Ei(n.data)}get options(){return this._def.values}get enum(){let n={};for(let i of this._def.values)n[i]=i;return n}get Values(){let n={};for(let i of this._def.values)n[i]=i;return n}get Enum(){let n={};for(let i of this._def.values)n[i]=i;return n}extract(n,i=this._def){return Ac.create(n,{...this._def,...i})}exclude(n,i=this._def){return Ac.create(this.options.filter((o)=>!n.includes(o)),{...this._def,...i})}}Na=new WeakMap;Ac.create=oR;class Ip extends vn{constructor(){super(...arguments);Da.set(this,void 0)}_parse(n){let i=Wn.getValidEnumValues(this._def.values),o=this._getOrReturnCtx(n);if(o.parsedType!==N.string&&o.parsedType!==N.number){let c=Wn.objectValues(i);return B(o,{expected:Wn.joinValues(c),received:o.parsedType,code:O.invalid_type}),e}if(!ym(this,Da,"f"))dM(this,Da,new Set(Wn.getValidEnumValues(this._def.values)),"f");if(!ym(this,Da,"f").has(n.data)){let c=Wn.objectValues(i);return B(o,{received:o.data,code:O.invalid_enum_value,options:c}),e}return Ei(n.data)}get enum(){return this._def.values}}Da=new WeakMap;Ip.create=(n,i)=>{return new Ip({values:n,typeName:g.ZodNativeEnum,...fn(i)})};class hc extends vn{unwrap(){return this._def.type}_parse(n){let{ctx:i}=this._processInputParams(n);if(i.parsedType!==N.promise&&i.common.async===!1)return B(i,{code:O.invalid_type,expected:N.promise,received:i.parsedType}),e;let o=i.parsedType===N.promise?i.data:Promise.resolve(i.data);return Ei(o.then((c)=>{return this._def.type.parseAsync(c,{path:i.path,errorMap:i.common.contextualErrorMap})}))}}hc.create=(n,i)=>{return new hc({type:n,typeName:g.ZodPromise,...fn(i)})};class co extends vn{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===g.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(n){let{status:i,ctx:o}=this._processInputParams(n),c=this._def.effect||null,p={addIssue:(a)=>{if(B(o,a),a.fatal)i.abort();else i.dirty()},get path(){return o.path}};if(p.addIssue=p.addIssue.bind(p),c.type==="preprocess"){let a=c.transform(o.data,p);if(o.common.async)return Promise.resolve(a).then(async(x)=>{if(i.value==="aborted")return e;let m=await this._def.schema._parseAsync({data:x,path:o.path,parent:o});if(m.status==="aborted")return e;if(m.status==="dirty")return _p(m.value);if(i.value==="dirty")return _p(m.value);return m});else{if(i.value==="aborted")return e;let x=this._def.schema._parseSync({data:a,path:o.path,parent:o});if(x.status==="aborted")return e;if(x.status==="dirty")return _p(x.value);if(i.value==="dirty")return _p(x.value);return x}}if(c.type==="refinement"){let a=(x)=>{let m=c.refinement(x,p);if(o.common.async)return Promise.resolve(m);if(m instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return x};if(o.common.async===!1){let x=this._def.schema._parseSync({data:o.data,path:o.path,parent:o});if(x.status==="aborted")return e;if(x.status==="dirty")i.dirty();return a(x.value),{status:i.value,value:x.value}}else return this._def.schema._parseAsync({data:o.data,path:o.path,parent:o}).then((x)=>{if(x.status==="aborted")return e;if(x.status==="dirty")i.dirty();return a(x.value).then(()=>{return{status:i.value,value:x.value}})})}if(c.type==="transform")if(o.common.async===!1){let a=this._def.schema._parseSync({data:o.data,path:o.path,parent:o});if(!Ca(a))return a;let x=c.transform(a.value,p);if(x instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:i.value,value:x}}else return this._def.schema._parseAsync({data:o.data,path:o.path,parent:o}).then((a)=>{if(!Ca(a))return a;return Promise.resolve(c.transform(a.value,p)).then((x)=>({status:i.value,value:x}))});Wn.assertNever(c)}}co.create=(n,i,o)=>{return new co({schema:n,typeName:g.ZodEffects,effect:i,...fn(o)})};co.createWithPreprocess=(n,i,o)=>{return new co({schema:i,effect:{type:"preprocess",transform:n},typeName:g.ZodEffects,...fn(o)})};class Wo extends vn{_parse(n){if(this._getType(n)===N.undefined)return Ei(void 0);return this._def.innerType._parse(n)}unwrap(){return this._def.innerType}}Wo.create=(n,i)=>{return new Wo({innerType:n,typeName:g.ZodOptional,...fn(i)})};class ho extends vn{_parse(n){if(this._getType(n)===N.null)return Ei(null);return this._def.innerType._parse(n)}unwrap(){return this._def.innerType}}ho.create=(n,i)=>{return new ho({innerType:n,typeName:g.ZodNullable,...fn(i)})};class kp extends vn{_parse(n){let{ctx:i}=this._processInputParams(n),o=i.data;if(i.parsedType===N.undefined)o=this._def.defaultValue();return this._def.innerType._parse({data:o,path:i.path,parent:i})}removeDefault(){return this._def.innerType}}kp.create=(n,i)=>{return new kp({innerType:n,typeName:g.ZodDefault,defaultValue:typeof i.default==="function"?i.default:()=>i.default,...fn(i)})};class sp extends vn{_parse(n){let{ctx:i}=this._processInputParams(n),o={...i,common:{...i.common,issues:[]}},c=this._def.innerType._parse({data:o.data,path:o.path,parent:{...o}});if(ha(c))return c.then((p)=>{return{status:"valid",value:p.status==="valid"?p.value:this._def.catchValue({get error(){return new Ii(o.common.issues)},input:o.data})}});else return{status:"valid",value:c.status==="valid"?c.value:this._def.catchValue({get error(){return new Ii(o.common.issues)},input:o.data})}}removeCatch(){return this._def.innerType}}sp.create=(n,i)=>{return new sp({innerType:n,typeName:g.ZodCatch,catchValue:typeof i.catch==="function"?i.catch:()=>i.catch,...fn(i)})};class ta extends vn{_parse(n){if(this._getType(n)!==N.nan){let o=this._getOrReturnCtx(n);return B(o,{code:O.invalid_type,expected:N.nan,received:o.parsedType}),e}return{status:"valid",value:n.data}}}ta.create=(n)=>{return new ta({typeName:g.ZodNaN,...fn(n)})};var I5=Symbol("zod_brand");class Lm extends vn{_parse(n){let{ctx:i}=this._processInputParams(n),o=i.data;return this._def.type._parse({data:o,path:i.path,parent:i})}unwrap(){return this._def.type}}class qa extends vn{_parse(n){let{status:i,ctx:o}=this._processInputParams(n);if(o.common.async)return(async()=>{let p=await this._def.in._parseAsync({data:o.data,path:o.path,parent:o});if(p.status==="aborted")return e;if(p.status==="dirty")return i.dirty(),_p(p.value);else return this._def.out._parseAsync({data:p.value,path:o.path,parent:o})})();else{let c=this._def.in._parseSync({data:o.data,path:o.path,parent:o});if(c.status==="aborted")return e;if(c.status==="dirty")return i.dirty(),{status:"dirty",value:c.value};else return this._def.out._parseSync({data:c.value,path:o.path,parent:o})}}static create(n,i){return new qa({in:n,out:i,typeName:g.ZodPipeline})}}class Zp extends vn{_parse(n){let i=this._def.innerType._parse(n),o=(c)=>{if(Ca(c))c.value=Object.freeze(c.value);return c};return ha(i)?i.then((c)=>o(c)):o(i)}unwrap(){return this._def.innerType}}Zp.create=(n,i)=>{return new Zp({innerType:n,typeName:g.ZodReadonly,...fn(i)})};function cR(n,i={},o){if(n)return Dc.create().superRefine((c,p)=>{var a,x;if(!n(c)){let m=typeof i==="function"?i(c):typeof i==="string"?{message:i}:i,l=(x=(a=m.fatal)!==null&&a!==void 0?a:o)!==null&&x!==void 0?x:!0,f=typeof m==="string"?{message:m}:m;p.addIssue({code:"custom",...f,fatal:l})}});return Dc.create()}var k5={object:In.lazycreate},g;(function(n){n.ZodString="ZodString",n.ZodNumber="ZodNumber",n.ZodNaN="ZodNaN",n.ZodBigInt="ZodBigInt",n.ZodBoolean="ZodBoolean",n.ZodDate="ZodDate",n.ZodSymbol="ZodSymbol",n.ZodUndefined="ZodUndefined",n.ZodNull="ZodNull",n.ZodAny="ZodAny",n.ZodUnknown="ZodUnknown",n.ZodNever="ZodNever",n.ZodVoid="ZodVoid",n.ZodArray="ZodArray",n.ZodObject="ZodObject",n.ZodUnion="ZodUnion",n.ZodDiscriminatedUnion="ZodDiscriminatedUnion",n.ZodIntersection="ZodIntersection",n.ZodTuple="ZodTuple",n.ZodRecord="ZodRecord",n.ZodMap="ZodMap",n.ZodSet="ZodSet",n.ZodFunction="ZodFunction",n.ZodLazy="ZodLazy",n.ZodLiteral="ZodLiteral",n.ZodEnum="ZodEnum",n.ZodEffects="ZodEffects",n.ZodNativeEnum="ZodNativeEnum",n.ZodOptional="ZodOptional",n.ZodNullable="ZodNullable",n.ZodDefault="ZodDefault",n.ZodCatch="ZodCatch",n.ZodPromise="ZodPromise",n.ZodBranded="ZodBranded",n.ZodPipeline="ZodPipeline",n.ZodReadonly="ZodReadonly"})(g||(g={}));var s5=(n,i={message:`Input not instance of ${n.name}`})=>cR((o)=>o instanceof n,i),pR=Mo.create,aR=Jc.create,Z5=ta.create,t5=Sc.create,xR=yp.create,q5=Nc.create,P5=Ia.create,r5=Bp.create,g5=Lp.create,d5=Dc.create,e5=wc.create,n9=Uo.create,i9=ka.create,o9=Ro.create,Pa=In.create,c9=In.strictCreate,p9=Np.create,a9=Bm.create,x9=Dp.create,m9=Vo.create,l9=sa.create,f9=Za.create,v9=Cc.create,$9=bp.create,T9=Cp.create,w9=hp.create,J9=Ac.create,S9=Ip.create,A9=hc.create,rM=co.create,F9=Wo.create,M9=ho.create,R9=co.createWithPreprocess,W9=qa.create,K9=()=>pR().optional(),X9=()=>aR().optional(),G9=()=>xR().optional(),Y9={string:(n)=>Mo.create({...n,coerce:!0}),number:(n)=>Jc.create({...n,coerce:!0}),boolean:(n)=>yp.create({...n,coerce:!0}),bigint:(n)=>Sc.create({...n,coerce:!0}),date:(n)=>Nc.create({...n,coerce:!0})},z9=e,Gn=Object.freeze({__proto__:null,defaultErrorMap:jp,setErrorMap:Q5,getErrorMap:bm,makeIssue:jm,EMPTY_PATH:H5,addIssueToContext:B,ParseStatus:Xi,INVALID:e,DIRTY:_p,OK:Ei,isAborted:Ev,isDirty:Ov,isValid:Ca,isAsync:ha,get util(){return Wn},get objectUtil(){return Hv},ZodParsedType:N,getParsedType:Tc,ZodType:vn,datetimeRegex:iR,ZodString:Mo,ZodNumber:Jc,ZodBigInt:Sc,ZodBoolean:yp,ZodDate:Nc,ZodSymbol:Ia,ZodUndefined:Bp,ZodNull:Lp,ZodAny:Dc,ZodUnknown:wc,ZodNever:Uo,ZodVoid:ka,ZodArray:Ro,ZodObject:In,ZodUnion:Np,ZodDiscriminatedUnion:Bm,ZodIntersection:Dp,ZodTuple:Vo,ZodRecord:sa,ZodMap:Za,ZodSet:Cc,ZodFunction:bp,ZodLazy:Cp,ZodLiteral:hp,ZodEnum:Ac,ZodNativeEnum:Ip,ZodPromise:hc,ZodEffects:co,ZodTransformer:co,ZodOptional:Wo,ZodNullable:ho,ZodDefault:kp,ZodCatch:sp,ZodNaN:ta,BRAND:I5,ZodBranded:Lm,ZodPipeline:qa,ZodReadonly:Zp,custom:cR,Schema:vn,ZodSchema:vn,late:k5,get ZodFirstPartyTypeKind(){return g},coerce:Y9,any:d5,array:o9,bigint:t5,boolean:xR,date:q5,discriminatedUnion:a9,effect:rM,enum:J9,function:$9,instanceof:s5,intersection:x9,lazy:T9,literal:w9,map:f9,nan:Z5,nativeEnum:S9,never:n9,null:g5,nullable:M9,number:aR,object:Pa,oboolean:G9,onumber:X9,optional:F9,ostring:K9,pipeline:W9,preprocess:R9,promise:A9,record:l9,set:v9,strictObject:c9,string:pR,symbol:P5,transformer:rM,tuple:m9,undefined:r5,union:p9,unknown:e5,void:i9,NEVER:z9,ZodIssueCode:O,quotelessJson:z5,ZodError:Ii});function mR(n){let i=n.runtimeEnvStrict??n.runtimeEnv??process.env;if(n.emptyStringAsUndefined??!1){for(let[K,E]of Object.entries(i))if(E==="")delete i[K]}if(!!n.skipValidation)return i;let p=typeof n.client==="object"?n.client:{},a=typeof n.server==="object"?n.server:{},x=typeof n.shared==="object"?n.shared:{},m=Pa(p),l=Pa(a),f=Pa(x),v=n.isServer??(typeof window==="undefined"||("Deno"in window)),$=m.merge(f),T=l.merge(f).merge(m),F=v?T.safeParse(i):$.safeParse(i),M=n.onValidationError??((K)=>{throw console.error("\u274C Invalid environment variables:",K.flatten().fieldErrors),new Error("Invalid environment variables")}),A=n.onInvalidAccess??((K)=>{throw new Error("\u274C Attempted to access a server-side environment variable on the client")});if(F.success===!1)return M(F.error);let R=(K)=>{if(!n.clientPrefix)return!0;return!K.startsWith(n.clientPrefix)&&!(K in f.shape)},G=(K)=>{return v||!R(K)},Q=(K)=>{return K==="__esModule"||K==="$$typeof"},b=(n.extends??[]).reduce((K,E)=>{return Object.assign(K,E)},{}),D=Object.assign(F.data,b);return new Proxy(D,{get(K,E){if(typeof E!=="string")return;if(Q(E))return;if(!G(E))return A(E);return Reflect.get(K,E)}})}var Q9="__vite_start_time"in globalThis,H9=typeof window!=="undefined",mN="vitest"in globalThis,rn=mR({isServer:!Q9&&!H9,server:{CI:Gn.string().transform((n)=>!0).optional(),POSTGRES_USER:Gn.string(),POSTGRES_PASSWORD:Gn.string(),POSTGRES_DATABASE:Gn.string(),POSTGRES_HOST:Gn.string(),POSTGRES_PORT:Gn.string().transform((n)=>Number.parseInt(n,10)),BACKEND_PORT:Gn.string().transform((n)=>Number.parseInt(n,10)),RUN_WORKERS_FROM_SOURCE:Gn.union([Gn.literal("true"),Gn.literal("false")]).optional().transform((n)=>n==="true"),FRONTEND_PORT:Gn.string().transform((n)=>Number.parseInt(n,10)),FRONTEND_ORIGINS:Gn.string().transform((n)=>JSON.parse(n)).pipe(Gn.array(Gn.string())),OPENAI_API_KEY:Gn.string().optional()},clientPrefix:"VITE_",client:{VITE_BACKEND_ORIGIN:Gn.string(),VITE_USE_SELF_SIGNED_CERTIFICATE:Gn.union([Gn.literal("true"),Gn.literal("false")]).optional().transform((n)=>n==="true")},runtimeEnv:import.meta.env,emptyStringAsUndefined:!0});var fR=Vv(import.meta.dirname,"../dev"),uv=rn.VITE_USE_SELF_SIGNED_CERTIFICATE?{cert:lR(Vv(fR,"./cert.pem"),"utf-8"),key:lR(Vv(fR,"./key.pem"),"utf-8")}:void 0;var Fc=new Vl,Tn=rn.VITE_USE_SELF_SIGNED_CERTIFICATE?console:Fc.logger;nn.STORE.loggers[0]=new Wc("warn",void 0,Tn);if(Tn!==console)Object.assign(console,Tn,{log:Tn.info});import{spawn as E9}from"child_process";import{resolve as O9}from"path";function _v(n,i,o=n.logger){let c=rn.RUN_WORKERS_FROM_SOURCE?"ts":"js",p=i.endsWith(".bun")?"bun":"node",x=[O9(import.meta.dir,`${i}.${c}`)];if(p==="node"&&c==="ts")x.push("--experimental-strip-types");let m=E9(p,x);return new Ja(m,i,o)}var vR=vl($f(),1);var U9=604800000,Nm=(()=>{let{__userSessionMap:n}=globalThis;if(!n){n=globalThis.__userSessionMap=new Map;let i=new vR.CronJob("00 00 03 * * *",()=>{for(let[o,c]of n.entries()){let p=Date.now();for(let[a,x]of c.entries())if(p-x>U9)c.delete(a);if(c.size===0)n.delete(o)}});i.start(),process.on("exit",()=>{i.stop(),Tn.info("\uD83D\uDEEC autoExpiry stopped")})}return n})();import XG from"path";import nG from"os";import iG from"fs";var Dm=new Map,bv=new Map,jv=Symbol("OriginError"),tp={};class po extends Promise{constructor(n,i,o,c,p={}){let a,x;super((m,l)=>{a=m,x=l});this.tagged=Array.isArray(n.raw),this.strings=n,this.args=i,this.handler=o,this.canceller=c,this.options=p,this.state=null,this.statement=null,this.resolve=(m)=>(this.active=!1,a(m)),this.reject=(m)=>(this.active=!1,x(m)),this.active=!1,this.cancelled=null,this.executed=!1,this.signature="",this[jv]=this.handler.debug?new Error:this.tagged&&V9(this.strings)}get origin(){return(this.handler.debug?this[jv].stack:this.tagged&&bv.has(this.strings)?bv.get(this.strings):bv.set(this.strings,this[jv].stack).get(this.strings))||""}static get[Symbol.species](){return Promise}cancel(){return this.canceller&&(this.canceller(this),this.canceller=null)}simple(){return this.options.simple=!0,this.options.prepare=!1,this}async readable(){return this.simple(),this.streaming=!0,this}async writable(){return this.simple(),this.streaming=!0,this}cursor(n=1,i){if(this.options.simple=!1,typeof n==="function")i=n,n=1;if(this.cursorRows=n,typeof i==="function")return this.cursorFn=i,this;let o;return{[Symbol.asyncIterator]:()=>({next:()=>{if(this.executed&&!this.active)return{done:!0};o&&o();let c=new Promise((p,a)=>{this.cursorFn=(x)=>{return p({value:x,done:!1}),new Promise((m)=>o=m)},this.resolve=()=>(this.active=!1,p({done:!0})),this.reject=(x)=>(this.active=!1,a(x))});return this.execute(),c},return(){return o&&o(tp),{done:!0}}})}}describe(){return this.options.simple=!1,this.onlyDescribe=this.options.prepare=!0,this}stream(){throw new Error(".stream has been renamed to .forEach")}forEach(n){return this.forEachFn=n,this.handle(),this}raw(){return this.isRaw=!0,this}values(){return this.isRaw="values",this}async handle(){!this.executed&&(this.executed=!0)&&await 1&&this.handler(this)}execute(){return this.handle(),this}then(){return this.handle(),super.then.apply(this,arguments)}catch(){return this.handle(),super.catch.apply(this,arguments)}finally(){return this.handle(),super.finally.apply(this,arguments)}}function V9(n){if(Dm.has(n))return Dm.get(n);let i=Error.stackTraceLimit;return Error.stackTraceLimit=4,Dm.set(n,new Error),Error.stackTraceLimit=i,Dm.get(n)}class qp extends Error{constructor(n){super(n.message);this.name=this.constructor.name,Object.assign(this,n)}}var en={connection:$R,postgres:TR,generic:wR,notSupported:JR};function $R(n,i,o){let{host:c,port:p}=o||i,a=Object.assign(new Error("write "+n+" "+(i.path||c+":"+p)),{code:n,errno:n,address:i.path||c},i.path?{}:{port:p});return Error.captureStackTrace(a,$R),a}function TR(n){let i=new qp(n);return Error.captureStackTrace(i,TR),i}function wR(n,i){let o=Object.assign(new Error(n+": "+i),{code:n});return Error.captureStackTrace(o,wR),o}function JR(n){let i=Object.assign(new Error(n+" (B) is not supported"),{code:"MESSAGE_NOT_SUPPORTED",name:n});return Error.captureStackTrace(i,JR),i}var u9={string:{to:25,from:null,serialize:(n)=>""+n},number:{to:0,from:[21,23,26,700,701],serialize:(n)=>""+n,parse:(n)=>+n},json:{to:114,from:[114,3802],serialize:(n)=>JSON.stringify(n),parse:(n)=>JSON.parse(n)},boolean:{to:16,from:16,serialize:(n)=>n===!0?"t":"f",parse:(n)=>n==="t"},date:{to:1184,from:[1082,1114,1184],serialize:(n)=>(n instanceof Date?n:new Date(n)).toISOString(),parse:(n)=>new Date(n)},bytea:{to:17,from:17,serialize:(n)=>"\\x"+Buffer.from(n).toString("hex"),parse:(n)=>Buffer.from(n.slice(2),"hex")}};class Im{then(){yv()}catch(){yv()}finally(){yv()}}class ea extends Im{constructor(n){super();this.value=Zm(n)}}class uo extends Im{constructor(n,i,o){super();this.value=n,this.type=i,this.array=o}}class km extends Im{constructor(n,i){super();this.first=n,this.rest=i}build(n,i,o,c){let p=_9.map(([a,x])=>({fn:x,i:n.search(a)})).sort((a,x)=>a.i-x.i).pop();return p.i===-1?Cv(this.first,c):p.fn(this.first,this.rest,i,o,c)}}function sm(n,i,o,c){let p=n instanceof uo?n.value:n;if(p===void 0){if(n instanceof uo?n.value=c.transform.undefined:p=n=c.transform.undefined,p===void 0)throw en.generic("UNDEFINED_VALUE","Undefined values are not allowed")}return"$"+o.push(n instanceof uo?(i.push(n.value),n.array?n.array[n.type||hm(n.value)]||n.type||MR(n.value):n.type):(i.push(n),hm(n)))}var AR=WR(u9);function Nv(n,i,o,c,p,a){for(let x=1;x<n.strings.length;x++)i+=Dv(i,o,c,p,a)+n.strings[x],o=n.args[x];return i}function Dv(n,i,o,c,p){return i instanceof km?i.build(n,o,c,p):i instanceof po?Lv(i,o,c,p):i instanceof ea?i.value:i&&i[0]instanceof po?i.reduce((a,x)=>a+" "+Lv(x,o,c,p),""):sm(i,o,c,p)}function Lv(n,i,o,c){return n.fragment=!0,Nv(n,n.strings[0],n.args[0],i,o,c)}function FR(n,i,o,c,p){return n.map((a)=>"("+c.map((x)=>Dv("values",a[x],i,o,p)).join(",")+")").join(",")}function SR(n,i,o,c,p){let a=Array.isArray(n[0]),x=i.length?i.flat():Object.keys(a?n[0]:n);return FR(a?n:[n],o,c,x,p)}function Cm(n,i,o,c,p){if(typeof n==="string"&&(n=[n].concat(i)),Array.isArray(n))return Cv(n,p);let a;return(i.length?i.flat():Object.keys(n)).map((m)=>{return a=n[m],(a instanceof po?Lv(a,o,c,p):a instanceof ea?a.value:sm(a,o,c,p))+" as "+Zm(p.transform.column.to?p.transform.column.to(m):m)}).join(",")}var _9=Object.entries({values:SR,in:(...n)=>{let i=SR(...n);return i==="()"?"(null)":i},select:Cm,as:Cm,returning:Cm,"\\(":Cm,update(n,i,o,c,p){return(i.length?i.flat():Object.keys(n)).map((a)=>Zm(p.transform.column.to?p.transform.column.to(a):a)+"="+Dv("values",n[a],o,c,p))},insert(n,i,o,c,p){let a=i.length?i.flat():Object.keys(Array.isArray(n)?n[0]:n);return"("+Cv(a,p)+")values"+FR(Array.isArray(n)?n:[n],o,c,a,p)}}).map(([n,i])=>[new RegExp("((?:^|[\\s(])"+n+"(?:$|[\\s(]))(?![\\s\\S]*\\1)","i"),i]);function yv(){throw en.generic("NOT_TAGGED_CALL","Query not called as a tagged template literal")}var{serializers:b9,parsers:j9}=AR;function MR(n){if(Array.isArray(n))return MR(n[0]);return typeof n==="string"?1009:0}var RR=function(n){let i=WR(n||{});return{serializers:Object.assign({},b9,i.serializers),parsers:Object.assign({},j9,i.parsers)}};function WR(n){return Object.keys(n).reduce((i,o)=>{if(n[o].from&&[].concat(n[o].from).forEach((c)=>i.parsers[c]=n[o].parse),n[o].serialize)i.serializers[n[o].to]=n[o].serialize,n[o].from&&[].concat(n[o].from).forEach((c)=>i.serializers[c]=n[o].serialize);return i},{parsers:{},serializers:{}})}function Cv(n,{transform:{column:i}}){return n.map((o)=>Zm(i.to?i.to(o):o)).join(",")}var Zm=function n(i){return'"'+i.replace(/"/g,'""').replace(/\./g,'"."')+'"'},hm=function n(i){return i instanceof uo?i.type:i instanceof Date?1184:i instanceof Uint8Array?17:i===!0||i===!1?16:typeof i==="bigint"?20:Array.isArray(i)?n(i[0]):0},y9=/\\/g,B9=/"/g;function L9(n){return n.replace(y9,"\\\\").replace(B9,'\\"')}var KR=function n(i,o,c,p){if(Array.isArray(i)===!1)return i;if(!i.length)return"{}";let a=i[0],x=p===1020?";":",";if(Array.isArray(a)&&!a.type)return"{"+i.map((m)=>n(m,o,c,p)).join(x)+"}";return"{"+i.map((m)=>{if(m===void 0){if(m=c.transform.undefined,m===void 0)throw en.generic("UNDEFINED_VALUE","Undefined values are not allowed")}return m===null?"null":'"'+L9(o?o(m.type?m.value:m):""+m)+'"'}).join(x)+"}"},Bv={i:0,char:null,str:"",quoted:!1,last:0},XR=function n(i,o,c){return Bv.i=Bv.last=0,GR(Bv,i,o,c)};function GR(n,i,o,c){let p=[],a=c===1020?";":",";for(;n.i<i.length;n.i++){if(n.char=i[n.i],n.quoted)if(n.char==="\\")n.str+=i[++n.i];else if(n.char==='"')p.push(o?o(n.str):n.str),n.str="",n.quoted=i[n.i+1]==='"',n.last=n.i+2;else n.str+=n.char;else if(n.char==='"')n.quoted=!0;else if(n.char==="{")n.last=++n.i,p.push(GR(n,i,o,c));else if(n.char==="}"){n.quoted=!1,n.last<n.i&&p.push(o?o(i.slice(n.last,n.i)):i.slice(n.last,n.i)),n.last=n.i+1;break}else if(n.char===a&&n.p!=="}"&&n.p!=='"')p.push(o?o(i.slice(n.last,n.i)):i.slice(n.last,n.i)),n.last=n.i+1;n.p=n.char}return n.last<n.i&&p.push(o?o(i.slice(n.last,n.i+1)):i.slice(n.last,n.i+1)),p}var Ic=(n)=>{let i=n[0];for(let o=1;o<n.length;o++)i+=n[o]==="_"?n[++o].toUpperCase():n[o];return i},kc=(n)=>{let i=n[0].toUpperCase();for(let o=1;o<n.length;o++)i+=n[o]==="_"?n[++o].toUpperCase():n[o];return i},sc=(n)=>n.replace(/_/g,"-"),ra=(n)=>n.replace(/([A-Z])/g,"_$1").toLowerCase(),ga=(n)=>(n.slice(0,1)+n.slice(1).replace(/([A-Z])/g,"_$1")).toLowerCase(),da=(n)=>n.replace(/-/g,"_");function hv(n){return function i(o,c){return typeof o==="object"&&o!==null&&(c.type===114||c.type===3802)?Array.isArray(o)?o.map((p)=>i(p,c)):Object.entries(o).reduce((p,[a,x])=>Object.assign(p,{[n(a)]:i(x,c)}),{}):o}}Ic.column={from:Ic};Ic.value={from:hv(Ic)};ra.column={to:ra};var Iv={...Ic};Iv.column.to=ra;kc.column={from:kc};kc.value={from:hv(kc)};ga.column={to:ga};var kv={...kc};kv.column.to=ga;sc.column={from:sc};sc.value={from:hv(sc)};da.column={to:da};var sv={...sc};sv.column.to=da;import YR from"net";import h9 from"tls";import nx from"crypto";import Zv from"stream";import{performance as zR}from"perf_hooks";class Zc extends Array{constructor(){super();Object.defineProperties(this,{count:{value:null,writable:!0},state:{value:null,writable:!0},command:{value:null,writable:!0},columns:{value:null,writable:!0},statement:{value:null,writable:!0}})}static get[Symbol.species](){return Array}}var ki=N9;function N9(n=[]){let i=n.slice(),o=0;return{get length(){return i.length-o},remove:(c)=>{let p=i.indexOf(c);return p===-1?null:(i.splice(p,1),c)},push:(c)=>(i.push(c),c),shift:()=>{let c=i[o++];if(o===i.length)o=0,i=[];else i[o-1]=void 0;return c}}}var Gi=Buffer.allocUnsafe(256),D9="BCcDdEFfHPpQSX".split("").reduce((n,i)=>{let o=i.charCodeAt(0);return n[i]=()=>{return Gi[0]=o,On.i=5,On},n},{}),On=Object.assign(C9,D9,{N:String.fromCharCode(0),i:0,inc(n){return On.i+=n,On},str(n){let i=Buffer.byteLength(n);return tm(i),On.i+=Gi.write(n,On.i,i,"utf8"),On},i16(n){return tm(2),Gi.writeUInt16BE(n,On.i),On.i+=2,On},i32(n,i){if(i||i===0)return Gi.writeUInt32BE(n,i),On;return tm(4),Gi.writeUInt32BE(n,On.i),On.i+=4,On},z(n){return tm(n),Gi.fill(0,On.i,On.i+n),On.i+=n,On},raw(n){return Gi=Buffer.concat([Gi.subarray(0,On.i),n]),On.i=Gi.length,On},end(n=1){Gi.writeUInt32BE(On.i-n,n);let i=Gi.subarray(0,On.i);return On.i=0,Gi=Buffer.allocUnsafe(256),i}}),q=On;function tm(n){if(Gi.length-On.i<n){let i=Gi,o=i.length;Gi=Buffer.allocUnsafe(o+(o>>1)+n),i.copy(Gi)}}function C9(){return On.i=0,On}var Pv=ER,I9=1,Mc=q().S().end(),QR=q().H().end(),k9=q().i32(8).i32(80877103).end(8),s9=Buffer.concat([q().E().str(q.N).i32(0).end(),Mc]),Z9=q().D().str("S").str(q.N).end(),Pp=()=>{},t9=new Set(["FetchPreparedStatement","RevalidateCachedQuery","transformAssignedExpr"]),q9={83:"severity_local",86:"severity",67:"code",77:"message",68:"detail",72:"hint",80:"position",112:"internal_position",113:"internal_query",87:"where",115:"schema_name",116:"table_name",99:"column_name",100:"data type_name",110:"constraint_name",70:"file",76:"line",82:"routine"};function ER(n,i={},{onopen:o=Pp,onend:c=Pp,onclose:p=Pp}={}){let{ssl:a,max:x,user:m,host:l,port:f,database:v,parsers:$,transform:T,onnotice:F,onnotify:M,onparameter:A,max_pipeline:R,keep_alive:G,backoff:Q,target_session_attrs:b}=n,D=ki(),Y=I9++,K={pid:null,secret:null},E=qv(ml,n.idle_timeout),y=qv(ml,n.max_lifetime),V=qv(l4,n.connect_timeout),X=null,Z,C=new Zc,on=Buffer.alloc(0),mn=n.fetch_types,ln={},Vn={},ji=Math.random().toString(36).slice(2),H=1,s=0,Jn=0,Yn=0,ni=0,wn=0,un=0,gn=0,Dn=null,jn=null,$i=!1,_n=null,ao=null,Ti=null,Io=null,ii=null,yn=null,xo=null,Go=null,_=null,na=null,wi={queue:i.closed,idleTimer:E,connect(w){Ti=w||!0,X$()},terminate:oa,execute:ia,cancel:p4,end:ml,count:0,id:Y};return i.closed&&i.closed.push(wi),wi;async function c4(){let w;try{w=n.socket?await Promise.resolve(n.socket(n)):new YR.Socket}catch(W){rc(W);return}return w.on("error",rc),w.on("close",G$),w.on("drain",W$),w}async function p4({pid:w,secret:W},P,Kn){try{Z=q().i32(16).i32(80877102).i32(w).i32(W).end(16),await K$(),X.once("error",Kn),X.once("close",P)}catch(kn){Kn(kn)}}function ia(w){if($i)return xx(w,en.connection("CONNECTION_DESTROYED",n));if(w.cancelled)return;try{return w.state=K,_?D.push(w):(_=w,_.active=!0),m4(w),mi(a4(w))&&!w.describeFirst&&!w.cursorFn&&D.length<R&&(!w.options.onexecute||w.options.onexecute(wi))}catch(W){return D.length===0&&mi(Mc),Yo(W),!0}}function a4(w){if(w.parameters.length>=65534)throw en.generic("MAX_PARAMETERS_EXCEEDED","Max number of parameters (65534) exceeded");return w.options.simple?q().Q().str(w.statement.string+q.N).end():w.describeFirst?Buffer.concat([F$(w),QR]):w.prepare?w.prepared?ax(w):Buffer.concat([F$(w),ax(w)]):x4(w)}function F$(w){return Buffer.concat([z$(w.statement.string,w.parameters,w.statement.types,w.statement.name),Z4("S",w.statement.name)])}function ax(w){return Buffer.concat([s4(w.parameters,w.statement.types,w.statement.name,w.cursorName),w.cursorFn?Q$("",w.cursorRows):s9])}function x4(w){return Buffer.concat([z$(w.statement.string,w.parameters,w.statement.types),Z9,ax(w)])}function m4(w){let W=[],P=[],Kn=Nv(w,w.strings[0],w.args[0],W,P,n);!w.tagged&&w.args.forEach((kn)=>sm(kn,W,P,n)),w.prepare=n.prepare&&("prepare"in w.options?w.options.prepare:!0),w.string=Kn,w.signature=w.prepare&&P+Kn,w.onlyDescribe&&delete Vn[w.signature],w.parameters=w.parameters||W,w.prepared=w.prepare&&w.signature in Vn,w.describeFirst=w.onlyDescribe||W.length&&!w.prepared,w.statement=w.prepared?Vn[w.signature]:{string:Kn,types:P,name:w.prepare?ji+H++:""},typeof n.debug==="function"&&n.debug(Y,Kn,W,P)}function mi(w,W){if(yn=yn?Buffer.concat([yn,w]):Buffer.from(w),W||yn.length>=1024)return M$(W);return jn===null&&(jn=setImmediate(M$)),!0}function M$(w){let W=X.write(yn,w);return jn!==null&&clearImmediate(jn),yn=jn=null,W}function l4(){Yo(en.connection("CONNECT_TIMEOUT",n,X)),X.destroy()}async function R$(){if(mi(k9),!await new Promise((W)=>X.once("data",(P)=>W(P[0]===83)))&&a==="prefer")return Pc();X.removeAllListeners(),X=h9.connect({socket:X,servername:YR.isIP(X.host)?void 0:X.host,...a==="require"||a==="allow"||a==="prefer"?{rejectUnauthorized:!1}:a==="verify-full"?{}:typeof a==="object"?a:{}}),X.on("secureConnect",Pc),X.on("error",rc),X.on("close",G$),X.on("drain",W$)}function W$(){!_&&o(wi)}function xl(w){if(_n){if(_n.push(w),Jn-=w.length,Jn>=0)return}on=_n?Buffer.concat(_n,wn-Jn):on.length===0?w:Buffer.concat([on,w],on.length+w.length);while(on.length>4){if(wn=on.readUInt32BE(1),wn>=on.length){Jn=wn-on.length,_n=[on];break}try{f4(on.subarray(0,wn+1))}catch(W){_&&(_.cursorFn||_.describeFirst)&&mi(Mc),Yo(W)}on=on.subarray(wn+1),Jn=0,_n=null}}async function K$(){if($i=!1,ln={},X||(X=await c4()),!X)return;if(V.start(),n.socket)return a?R$():Pc();if(X.on("connect",a?R$:Pc),n.path)return X.connect(n.path);X.ssl=a,X.connect(f[Yn],l[Yn]),X.host=l[Yn],X.port=f[Yn],Yn=(Yn+1)%f.length}function X$(){setTimeout(K$,s?s+un-zR.now():0)}function Pc(){try{Vn={},mn=n.fetch_types,ji=Math.random().toString(36).slice(2),H=1,y.start(),X.on("data",xl),G&&X.setKeepAlive&&X.setKeepAlive(!0,1000*G);let w=q4();mi(w)}catch(w){rc(w)}}function rc(w){if(wi.queue===i.connecting&&n.host[ni+1])return;Yo(w);while(D.length)xx(D.shift(),w)}function Yo(w){ii&&(ii.destroy(w),ii=null),_&&xx(_,w),Ti&&(xx(Ti,w),Ti=null)}function xx(w,W){"query"in W||"parameters"in W||Object.defineProperties(W,{stack:{value:W.stack+w.origin.replace(/.*\n/,"\n"),enumerable:n.debug},query:{value:w.string,enumerable:n.debug},parameters:{value:w.parameters,enumerable:n.debug},args:{value:w.args,enumerable:n.debug},types:{value:w.statement&&w.statement.types,enumerable:n.debug}}),w.reject(W)}function ml(){return Io||(!wi.reserved&&c(wi),!wi.reserved&&!Ti&&!_&&D.length===0?(oa(),new Promise((w)=>X&&X.readyState!=="closed"?X.once("close",w):w())):Io=new Promise((w)=>xo=w))}function oa(){if($i=!0,ii||_||Ti||D.length)rc(en.connection("CONNECTION_DESTROYED",n));if(clearImmediate(jn),X)X.removeListener("data",xl),X.removeListener("connect",Pc),X.readyState==="open"&&X.end(q().X().end());xo&&(xo(),Io=xo=null)}async function G$(w){if(on=Buffer.alloc(0),Jn=0,_n=null,clearImmediate(jn),X.removeListener("data",xl),X.removeListener("connect",Pc),E.cancel(),y.cancel(),V.cancel(),X.removeAllListeners(),X=null,Ti)return X$();!w&&(_||D.length)&&rc(en.connection("CONNECTION_CLOSED",n,X)),s=zR.now(),w&&n.shared.retries++,un=(typeof Q==="function"?Q(n.shared.retries):Q)*1000,p(wi,en.connection("CONNECTION_CLOSED",n,X))}function f4(w,W=w[0]){(W===68?v4:W===100?B4:W===65?V4:W===83?$4:W===90?T4:W===67?w4:W===50?Y$:W===49?J4:W===116?S4:W===84?A4:W===82?F4:W===110?G4:W===75?Y4:W===69?O4:W===115?u4:W===51?_4:W===71?b4:W===78?N4:W===72?j4:W===99?L4:W===73?D4:W===86?C4:W===118?h4:W===87?y4:I4)(w)}function v4(w){let W=7,P,Kn,kn,Ji=_.isRaw?new Array(_.statement.columns.length):{};for(let Yi=0;Yi<_.statement.columns.length;Yi++)Kn=_.statement.columns[Yi],P=w.readInt32BE(W),W+=4,kn=P===-1?null:_.isRaw===!0?w.subarray(W,W+=P):Kn.parser===void 0?w.toString("utf8",W,W+=P):Kn.parser.array===!0?Kn.parser(w.toString("utf8",W+1,W+=P)):Kn.parser(w.toString("utf8",W,W+=P)),_.isRaw?Ji[Yi]=_.isRaw===!0?kn:T.value.from?T.value.from(kn,Kn):kn:Ji[Kn.name]=T.value.from?T.value.from(kn,Kn):kn;_.forEachFn?_.forEachFn(T.row.from?T.row.from(Ji):Ji,C):C[gn++]=T.row.from?T.row.from(Ji):Ji}function $4(w){let[W,P]=w.toString("utf8",5,w.length-1).split(q.N);if(ln[W]=P,n.parameters[W]!==P)n.parameters[W]=P,A&&A(W,P)}function T4(w){if(_&&_.options.simple&&_.resolve(ao||C),_=ao=null,C=new Zc,V.cancel(),Ti){if(b){if(!ln.in_hot_standby||!ln.default_transaction_read_only)return E4();else if(H4(b,ln))return oa()}if(mn)return Ti===!0&&(Ti=null),z4();Ti!==!0&&ia(Ti),n.shared.retries=ni=0,Ti=null;return}while(D.length&&(_=D.shift())&&(_.active=!0,_.cancelled))ER(n).cancel(_.state,_.cancelled.resolve,_.cancelled.reject);if(_)return;wi.reserved?!wi.reserved.release&&w[5]===73?Io?oa():(wi.reserved=null,o(wi)):wi.reserved():Io?oa():o(wi)}function w4(w){gn=0;for(let W=w.length-1;W>0;W--){if(w[W]===32&&w[W+1]<58&&C.count===null)C.count=+w.toString("utf8",W+1,w.length-1);if(w[W-1]>=65){C.command=w.toString("utf8",5,W),C.state=K;break}}if(na&&(na(),na=null),C.command==="BEGIN"&&x!==1&&!wi.reserved)return Yo(en.generic("UNSAFE_TRANSACTION","Only use sql.begin, sql.reserved or max: 1"));if(_.options.simple)return Y$();if(_.cursorFn)C.count&&_.cursorFn(C),mi(Mc);_.resolve(C)}function J4(){_.parsing=!1}function Y$(){!C.statement&&(C.statement=_.statement),C.columns=_.statement.columns}function S4(w){let W=w.readUInt16BE(5);for(let P=0;P<W;++P)!_.statement.types[P]&&(_.statement.types[P]=w.readUInt32BE(7+P*4));_.prepare&&(Vn[_.signature]=_.statement),_.describeFirst&&!_.onlyDescribe&&(mi(ax(_)),_.describeFirst=!1)}function A4(w){if(C.command)ao=ao||[C],ao.push(C=new Zc),C.count=null,_.statement.columns=null;let W=w.readUInt16BE(5),P=7,Kn;_.statement.columns=Array(W);for(let kn=0;kn<W;++kn){Kn=P;while(w[P++]!==0);let Ji=w.readUInt32BE(P),Yi=w.readUInt16BE(P+4),ko=w.readUInt32BE(P+6);_.statement.columns[kn]={name:T.column.from?T.column.from(w.toString("utf8",Kn,P-1)):w.toString("utf8",Kn,P-1),parser:$[ko],table:Ji,number:Yi,type:ko},P+=18}if(C.statement=_.statement,_.onlyDescribe)return _.resolve(_.statement),mi(Mc)}async function F4(w,W=w.readUInt32BE(5)){(W===3?M4:W===5?R4:W===10?W4:W===11?K4:W===12?X4:W!==0?k4:Pp)(w,W)}async function M4(){let w=await ll();mi(q().p().str(w).z(1).end())}async function R4(w){let W="md5"+await HR(Buffer.concat([Buffer.from(await HR(await ll()+m)),w.subarray(9)]));mi(q().p().str(W).z(1).end())}async function W4(){Go=(await nx.randomBytes(18)).toString("base64"),q().p().str("SCRAM-SHA-256"+q.N);let w=q.i;mi(q.inc(4).str("n,,n=*,r="+Go).i32(q.i-w-4,w).end())}async function K4(w){let W=w.toString("utf8",9).split(",").reduce((Yi,ko)=>(Yi[ko[0]]=ko.slice(2),Yi),{}),P=await nx.pbkdf2Sync(await ll(),Buffer.from(W.s,"base64"),parseInt(W.i),32,"sha256"),Kn=await qm(P,"Client Key"),kn="n=*,r="+Go+",r="+W.r+",s="+W.s+",i="+W.i+",c=biws,r="+W.r;Dn=(await qm(await qm(P,"Server Key"),kn)).toString("base64");let Ji="c=biws,r="+W.r+",p="+r9(Kn,Buffer.from(await qm(await P9(Kn),kn))).toString("base64");mi(q().p().str(Ji).end())}function X4(w){if(w.toString("utf8",9).split(q.N,1)[0].slice(2)===Dn)return;Yo(en.generic("SASL_SIGNATURE_MISMATCH","The server did not return the correct signature")),X.destroy()}function ll(){return Promise.resolve(typeof n.pass==="function"?n.pass():n.pass)}function G4(){if(C.statement=_.statement,C.statement.columns=[],_.onlyDescribe)return _.resolve(_.statement),mi(Mc)}function Y4(w){K.pid=w.readUInt32BE(5),K.secret=w.readUInt32BE(9)}async function z4(){mn=!1,(await new po([`
|
|
38
38
|
select b.oid, b.typarray
|
|
39
39
|
from pg_catalog.pg_type a
|
|
40
40
|
left join pg_catalog.pg_type b on b.oid = a.typelem
|
|
@@ -54,10 +54,10 @@ var P4=Object.create;var{getPrototypeOf:r4,defineProperty:fl,getOwnPropertyNames
|
|
|
54
54
|
tell.location
|
|
55
55
|
from (select lo_tell64($1) as location) tell
|
|
56
56
|
) seek
|
|
57
|
-
`};return c(l),new Promise(async($)=>x=$);async function f({highWaterMark:$=16384,start:T=0,end:F=1/0}={}){let M=F-T;return T&&await l.seek(T),new UR.Readable({highWaterMark:$,async read(A){let R=A>M?A-M:A;M-=A;let[{data:G}]=await l.read(R);if(this.push(G),G.length<A)this.push(null)}})}async function v({highWaterMark:$=16384,start:T=0}={}){return T&&await l.seek(T),new UR.Writable({highWaterMark:$,write(F,M,A){l.write(F).then(()=>A(),A)}})}}).catch(p)})}Object.assign(rm,{PostgresError:qp,toPascal:kc,pascal:kv,toCamel:Ic,camel:Iv,toKebab:sc,kebab:sv,fromPascal:ga,fromCamel:ra,fromKebab:da,BigInt:{to:20,from:[20],parse:(n)=>BigInt(n),serialize:(n)=>n.toString()}});var rp=rm;function rm(n,i){let o=oG(n,i),c=o.no_subscribe||rv(rm,{...o}),p=!1,a=ki(),x=ki(),m=ki(),l=ki(),f=ki(),v=ki(),$=ki(),T=ki(),F={connecting:x,reserved:m,closed:l,ended:f,open:v,busy:$,full:T},M=[...Array(o.max)].map(()=>Pv(o,F,{onopen:Vn,onend:ln,onclose:ji})),A=R(y);return Object.assign(A,{get parameters(){return o.parameters},largeObject:gv.bind(null,A),subscribe:c,CLOSE:tp,END:tp,PostgresError:qp,options:o,reserve:b,listen:G,begin:D,close:C,end:Z}),A;function R(H){return H.debug=o.debug,Object.entries(o.types).reduce((Tn,[un,gn])=>{return Tn[un]=(Dn)=>new uo(Dn,gn.to),Tn},s),Object.assign(wn,{types:s,typed:s,unsafe:Yn,notify:Q,array:E,json:K,file:ni}),wn;function s(Tn,un){return new uo(Tn,un)}function wn(Tn,...un){return Tn&&Array.isArray(Tn.raw)?new po(Tn,un,H,X):typeof Tn==="string"&&!un.length?new ea(o.transform.column.to?o.transform.column.to(Tn):Tn):new km(Tn,un)}function Yn(Tn,un=[],gn={}){return arguments.length===2&&!Array.isArray(un)&&(gn=un,un=[]),new po([Tn],un,H,X,{prepare:!1,...gn,simple:"simple"in gn?gn.simple:un.length===0})}function ni(Tn,un=[],gn={}){return arguments.length===2&&!Array.isArray(un)&&(gn=un,un=[]),new po([],un,(jn)=>{iG.readFile(Tn,"utf8",($i,_n)=>{if($i)return jn.reject($i);jn.strings=[_n],H(jn)})},X,{...gn,simple:"simple"in gn?gn.simple:un.length===0})}}async function G(H,s,wn){let Yn={fn:s,onlisten:wn},ni=G.sql||(G.sql=rm({...o,max:1,idle_timeout:null,max_lifetime:null,fetch_types:!1,onclose(){Object.entries(G.channels).forEach(([jn,{listeners:$i}])=>{delete G.channels[jn],Promise.all($i.map((_n)=>G(jn,_n.fn,_n.onlisten).catch(()=>{})))})},onnotify(jn,$i){jn in G.channels&&G.channels[jn].listeners.forEach((_n)=>_n.fn($i))}})),Tn=G.channels||(G.channels={});if(H in Tn){Tn[H].listeners.push(Yn);let jn=await Tn[H].result;return Yn.onlisten&&Yn.onlisten(),{state:jn.state,unlisten:Dn}}Tn[H]={result:ni`listen ${ni.unsafe('"'+H.replace(/"/g,'""')+'"')}`,listeners:[Yn]};let gn=await Tn[H].result;return Yn.onlisten&&Yn.onlisten(),{state:gn.state,unlisten:Dn};async function Dn(){if(H in Tn===!1)return;if(Tn[H].listeners=Tn[H].listeners.filter((jn)=>jn!==Yn),Tn[H].listeners.length)return;return delete Tn[H],ni`unlisten ${ni.unsafe('"'+H.replace(/"/g,'""')+'"')}`}}async function Q(H,s){return await A`select pg_notify(${H}, ${""+s})`}async function b(){let H=ki(),s=v.length?v.shift():await new Promise((ni)=>{a.push({reserve:ni}),l.length&&mn(l.shift())});Y(s,m),s.reserved=()=>H.length?s.execute(H.shift()):Y(s,m),s.reserved.release=!0;let wn=R(Yn);return wn.release=()=>{s.reserved=null,Vn(s)},wn;function Yn(ni){s.queue===T?H.push(ni):s.execute(ni)||Y(s,T)}}async function D(H,s){!s&&(s=H,H="");let wn=ki(),Yn=0,ni,Tn=null;try{return await A.unsafe("begin "+H.replace(/[^a-z ]/ig,""),[],{onexecute:gn}).execute(),await Promise.race([un(ni,s),new Promise((Dn,jn)=>ni.onclose=jn)])}catch(Dn){throw Dn}async function un(Dn,jn,$i){let _n=R(ii);_n.savepoint=Io,_n.prepare=(yn)=>Tn=yn.replace(/[^a-z0-9$-_. ]/gi);let ao,Ti;$i&&await _n`savepoint ${_n($i)}`;try{if(Ti=await new Promise((yn,xo)=>{let Go=jn(_n);Promise.resolve(Array.isArray(Go)?Promise.all(Go):Go).then(yn,xo)}),ao)throw ao}catch(yn){throw await($i?_n`rollback to ${_n($i)}`:_n`rollback`),yn instanceof qp&&yn.code==="25P02"&&ao||yn}if(!$i)Tn?await _n`prepare transaction '${_n.unsafe(Tn)}'`:await _n`commit`;return Ti;function Io(yn,xo){if(yn&&Array.isArray(yn.raw))return Io((Go)=>Go.apply(Go,arguments));return arguments.length===1&&(xo=yn,yn=null),un(Dn,xo,"s"+Yn+++(yn?"_"+yn:""))}function ii(yn){yn.catch((xo)=>ao||(ao=xo)),Dn.queue===T?wn.push(yn):Dn.execute(yn)||Y(Dn,T)}}function gn(Dn){ni=Dn,Y(Dn,m),Dn.reserved=()=>wn.length?Dn.execute(wn.shift()):Y(Dn,m)}}function Y(H,s){return H.queue.remove(H),s.push(H),H.queue=s,s===v?H.idleTimer.start():H.idleTimer.cancel(),H}function K(H){return new uo(H,3802)}function E(H,s){if(!Array.isArray(H))return E(Array.from(arguments));return new uo(H,s||(H.length?hm(H)||25:0),o.shared.typeArrayMap)}function y(H){if(p)return H.reject(en.connection("CONNECTION_ENDED",o,o));if(v.length)return V(v.shift(),H);if(l.length)return mn(l.shift(),H);$.length?V($.shift(),H):a.push(H)}function V(H,s){return H.execute(s)?Y(H,$):Y(H,T)}function X(H){return new Promise((s,wn)=>{H.state?H.active?Pv(o).cancel(H.state,s,wn):H.cancelled={resolve:s,reject:wn}:(a.remove(H),H.cancelled=!0,H.reject(en.generic("57014","canceling statement due to user request")),s())})}async function Z({timeout:H=null}={}){if(p)return p;await 1;let s;return p=Promise.race([new Promise((wn)=>H!==null&&(s=setTimeout(on,H*1000,wn))),Promise.all(M.map((wn)=>wn.end()).concat(G.sql?G.sql.end({timeout:0}):[],c.sql?c.sql.end({timeout:0}):[]))]).then(()=>clearTimeout(s))}async function C(){await Promise.all(M.map((H)=>H.end()))}async function on(H){await Promise.all(M.map((s)=>s.terminate()));while(a.length)a.shift().reject(en.connection("CONNECTION_DESTROYED",o));H()}function mn(H,s){return Y(H,x),H.connect(s),H}function ln(H){Y(H,f)}function Vn(H){if(a.length===0)return Y(H,v);let s=Math.ceil(a.length/(x.length+1)),wn=!0;while(wn&&a.length&&s-- >0){let Yn=a.shift();if(Yn.reserve)return Yn.reserve(H);wn=H.execute(Yn)}wn?Y(H,$):Y(H,T)}function ji(H,s){Y(H,l),H.reserved=null,H.onclose&&(H.onclose(s),H.onclose=null),o.onclose&&o.onclose(H.id),a.length&&mn(H,a.shift())}}function oG(n,i){if(n&&n.shared)return n;let o=process.env,c=(!n||typeof n==="string"?i:n)||{},{url:p,multihost:a}=mG(n),x=[...p.searchParams].reduce((T,[F,M])=>(T[F]=M,T),{}),m=c.hostname||c.host||a||p.hostname||o.PGHOST||"localhost",l=c.port||p.port||o.PGPORT||5432,f=c.user||c.username||p.username||o.PGUSERNAME||o.PGUSER||lG();c.no_prepare&&(c.prepare=!1),x.sslmode&&(x.ssl=x.sslmode,delete x.sslmode),"timeout"in c&&(console.log("The timeout option is deprecated, use idle_timeout instead"),c.idle_timeout=c.timeout),x.sslrootcert==="system"&&(x.ssl="verify-full");let v=["idle_timeout","connect_timeout","max_lifetime","max_pipeline","backoff","keep_alive"],$={max:10,ssl:!1,idle_timeout:null,connect_timeout:30,max_lifetime:aG,max_pipeline:100,backoff:pG,keep_alive:60,prepare:!0,debug:!1,fetch_types:!0,publications:"alltables",target_session_attrs:null};return{host:Array.isArray(m)?m:m.split(",").map((T)=>T.split(":")[0]),port:Array.isArray(l)?l:m.split(",").map((T)=>parseInt(T.split(":")[1]||l)),path:c.path||m.indexOf("/")>-1&&m+"/.s.PGSQL."+l,database:c.database||c.db||(p.pathname||"").slice(1)||o.PGDATABASE||f,user:f,pass:c.pass||c.password||p.password||o.PGPASSWORD||"",...Object.entries($).reduce((T,[F,M])=>{let A=F in c?c[F]:(F in x)?x[F]==="disable"||x[F]==="false"?!1:x[F]:o["PG"+F.toUpperCase()]||M;return T[F]=typeof A==="string"&&v.includes(F)?+A:A,T},{}),connection:{application_name:"postgres.js",...c.connection,...Object.entries(x).reduce((T,[F,M])=>((F in $)||(T[F]=M),T),{})},types:c.types||{},target_session_attrs:cG(c,p,o),onnotice:c.onnotice,onnotify:c.onnotify,onclose:c.onclose,onparameter:c.onparameter,socket:c.socket,transform:xG(c.transform||{undefined:void 0}),parameters:{},shared:{retries:0,typeArrayMap:{}},...RR(c.types)}}function cG(n,i,o){let c=n.target_session_attrs||i.searchParams.get("target_session_attrs")||o.PGTARGETSESSIONATTRS;if(!c||["read-write","read-only","primary","standby","prefer-standby"].includes(c))return c;throw new Error("target_session_attrs "+c+" is not supported")}function pG(n){return(0.5+Math.random()/2)*Math.min(3**n/100,20)}function aG(){return 60*(30+Math.random()*30)}function xG(n){return{undefined:n.undefined,column:{from:typeof n.column==="function"?n.column:n.column&&n.column.from,to:n.column&&n.column.to},value:{from:typeof n.value==="function"?n.value:n.value&&n.value.from,to:n.value&&n.value.to},row:{from:typeof n.row==="function"?n.row:n.row&&n.row.from,to:n.row&&n.row.to}}}function mG(n){if(!n||typeof n!=="string")return{url:{searchParams:new Map}};let i=n;i=i.slice(i.indexOf("://")+3).split(/[?/]/)[0],i=decodeURIComponent(i.slice(i.indexOf("@")+1));let o=new URL(n.replace(i,i.split(",")[0]));return{url:{username:decodeURIComponent(o.username),password:decodeURIComponent(o.password),host:o.host,hostname:o.hostname,port:o.port,pathname:o.pathname,searchParams:o.searchParams},multihost:i.indexOf(",")>-1&&i}}function lG(){try{return nG.userInfo().username}catch(n){return process.env.USERNAME||"runner"}}class gm extends Qi{constructor(n,i,o,c){super();this.session=i,this.dialect=o,this.config={table:n,withList:c}}static[J]="PgDelete";config;where(n){return this.config.where=n,this}returning(n=this.config.table[L.Symbol.Columns]){return this.config.returning=ei(n),this}getSQL(){return this.dialect.buildDeleteQuery(this.config)}toSQL(){let{typings:n,...i}=this.dialect.sqlToQuery(this.getSQL());return i}_prepare(n){return Un.startActiveSpan("drizzle.prepareQuery",()=>{return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,n,!0)})}prepare(n){return this._prepare(n)}execute=(n)=>{return Un.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(n)})};$dynamic(){return this}}class dm{constructor(n,i,o,c){this.table=n,this.session=i,this.dialect=o,this.withList=c}static[J]="PgInsertBuilder";values(n){if(n=Array.isArray(n)?n:[n],n.length===0)throw new Error("values() must be called with at least one value");let i=n.map((o)=>{let c={},p=this.table[L.Symbol.Columns];for(let a of Object.keys(o)){let x=o[a];c[a]=z(x,k)?x:new Li(x,p[a])}return c});return new VR(this.table,i,this.session,this.dialect,this.withList)}}class VR extends Qi{constructor(n,i,o,c,p){super();this.session=o,this.dialect=c,this.config={table:n,values:i,withList:p}}static[J]="PgInsert";config;returning(n=this.config.table[L.Symbol.Columns]){return this.config.returning=ei(n),this}onConflictDoNothing(n={}){if(n.target===void 0)this.config.onConflict=S`do nothing`;else{let i="";i=Array.isArray(n.target)?n.target.map((c)=>this.dialect.escapeName(this.dialect.casing.getColumnCasing(c))).join(","):this.dialect.escapeName(this.dialect.casing.getColumnCasing(n.target));let o=n.where?S` where ${n.where}`:void 0;this.config.onConflict=S`(${S.raw(i)})${o} do nothing`}return this}onConflictDoUpdate(n){if(n.where&&(n.targetWhere||n.setWhere))throw new Error('You cannot use both "where" and "targetWhere"/"setWhere" at the same time - "where" is deprecated, use "targetWhere" or "setWhere" instead.');let i=n.where?S` where ${n.where}`:void 0,o=n.targetWhere?S` where ${n.targetWhere}`:void 0,c=n.setWhere?S` where ${n.setWhere}`:void 0,p=this.dialect.buildUpdateSet(this.config.table,rx(this.config.table,n.set)),a="";return a=Array.isArray(n.target)?n.target.map((x)=>this.dialect.escapeName(this.dialect.casing.getColumnCasing(x))).join(","):this.dialect.escapeName(this.dialect.casing.getColumnCasing(n.target)),this.config.onConflict=S`(${S.raw(a)})${o} do update set ${p}${i}${c}`,this}getSQL(){return this.dialect.buildInsertQuery(this.config)}toSQL(){let{typings:n,...i}=this.dialect.sqlToQuery(this.getSQL());return i}_prepare(n){return Un.startActiveSpan("drizzle.prepareQuery",()=>{return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,n,!0)})}prepare(n){return this._prepare(n)}execute=(n)=>{return Un.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(n)})};$dynamic(){return this}}function fG(n){return(n.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).map((o)=>o.toLowerCase()).join("_")}function vG(n){return(n.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).reduce((o,c,p)=>{let a=p===0?c.toLowerCase():`${c[0].toUpperCase()}${c.slice(1)}`;return o+a},"")}function $G(n){return n}class dv{static[J]="CasingCache";cache={};cachedTables={};convert;constructor(n){this.convert=n==="snake_case"?fG:n==="camelCase"?vG:$G}getColumnCasing(n){if(!n.keyAsName)return n.name;let i=n.table[L.Symbol.Schema]??"public",o=n.table[L.Symbol.OriginalName],c=`${i}.${o}.${n.name}`;if(!this.cache[c])this.cacheTable(n.table);return this.cache[c]}cacheTable(n){let i=n[L.Symbol.Schema]??"public",o=n[L.Symbol.OriginalName],c=`${i}.${o}`;if(!this.cachedTables[c]){for(let p of Object.values(n[L.Symbol.Columns])){let a=`${c}.${p.name}`;this.cache[a]=this.convert(p.name)}this.cachedTables[c]=!0}}clearCache(){this.cache={},this.cachedTables={}}}class ix extends Vi{static[J]="PgViewBase"}class tc{static[J]="PgDialect";casing;constructor(n){this.casing=new dv(n?.casing)}async migrate(n,i,o){let c=typeof o==="string"?"__drizzle_migrations":o.migrationsTable??"__drizzle_migrations",p=typeof o==="string"?"drizzle":o.migrationsSchema??"drizzle",a=S`
|
|
57
|
+
`};return c(l),new Promise(async($)=>x=$);async function f({highWaterMark:$=16384,start:T=0,end:F=1/0}={}){let M=F-T;return T&&await l.seek(T),new UR.Readable({highWaterMark:$,async read(A){let R=A>M?A-M:A;M-=A;let[{data:G}]=await l.read(R);if(this.push(G),G.length<A)this.push(null)}})}async function v({highWaterMark:$=16384,start:T=0}={}){return T&&await l.seek(T),new UR.Writable({highWaterMark:$,write(F,M,A){l.write(F).then(()=>A(),A)}})}}).catch(p)})}Object.assign(rm,{PostgresError:qp,toPascal:kc,pascal:kv,toCamel:Ic,camel:Iv,toKebab:sc,kebab:sv,fromPascal:ga,fromCamel:ra,fromKebab:da,BigInt:{to:20,from:[20],parse:(n)=>BigInt(n),serialize:(n)=>n.toString()}});var rp=rm;function rm(n,i){let o=oG(n,i),c=o.no_subscribe||rv(rm,{...o}),p=!1,a=ki(),x=ki(),m=ki(),l=ki(),f=ki(),v=ki(),$=ki(),T=ki(),F={connecting:x,reserved:m,closed:l,ended:f,open:v,busy:$,full:T},M=[...Array(o.max)].map(()=>Pv(o,F,{onopen:Vn,onend:ln,onclose:ji})),A=R(y);return Object.assign(A,{get parameters(){return o.parameters},largeObject:gv.bind(null,A),subscribe:c,CLOSE:tp,END:tp,PostgresError:qp,options:o,reserve:b,listen:G,begin:D,close:C,end:Z}),A;function R(H){return H.debug=o.debug,Object.entries(o.types).reduce((wn,[un,gn])=>{return wn[un]=(Dn)=>new uo(Dn,gn.to),wn},s),Object.assign(Jn,{types:s,typed:s,unsafe:Yn,notify:Q,array:E,json:K,file:ni}),Jn;function s(wn,un){return new uo(wn,un)}function Jn(wn,...un){return wn&&Array.isArray(wn.raw)?new po(wn,un,H,X):typeof wn==="string"&&!un.length?new ea(o.transform.column.to?o.transform.column.to(wn):wn):new km(wn,un)}function Yn(wn,un=[],gn={}){return arguments.length===2&&!Array.isArray(un)&&(gn=un,un=[]),new po([wn],un,H,X,{prepare:!1,...gn,simple:"simple"in gn?gn.simple:un.length===0})}function ni(wn,un=[],gn={}){return arguments.length===2&&!Array.isArray(un)&&(gn=un,un=[]),new po([],un,(jn)=>{iG.readFile(wn,"utf8",($i,_n)=>{if($i)return jn.reject($i);jn.strings=[_n],H(jn)})},X,{...gn,simple:"simple"in gn?gn.simple:un.length===0})}}async function G(H,s,Jn){let Yn={fn:s,onlisten:Jn},ni=G.sql||(G.sql=rm({...o,max:1,idle_timeout:null,max_lifetime:null,fetch_types:!1,onclose(){Object.entries(G.channels).forEach(([jn,{listeners:$i}])=>{delete G.channels[jn],Promise.all($i.map((_n)=>G(jn,_n.fn,_n.onlisten).catch(()=>{})))})},onnotify(jn,$i){jn in G.channels&&G.channels[jn].listeners.forEach((_n)=>_n.fn($i))}})),wn=G.channels||(G.channels={});if(H in wn){wn[H].listeners.push(Yn);let jn=await wn[H].result;return Yn.onlisten&&Yn.onlisten(),{state:jn.state,unlisten:Dn}}wn[H]={result:ni`listen ${ni.unsafe('"'+H.replace(/"/g,'""')+'"')}`,listeners:[Yn]};let gn=await wn[H].result;return Yn.onlisten&&Yn.onlisten(),{state:gn.state,unlisten:Dn};async function Dn(){if(H in wn===!1)return;if(wn[H].listeners=wn[H].listeners.filter((jn)=>jn!==Yn),wn[H].listeners.length)return;return delete wn[H],ni`unlisten ${ni.unsafe('"'+H.replace(/"/g,'""')+'"')}`}}async function Q(H,s){return await A`select pg_notify(${H}, ${""+s})`}async function b(){let H=ki(),s=v.length?v.shift():await new Promise((ni)=>{a.push({reserve:ni}),l.length&&mn(l.shift())});Y(s,m),s.reserved=()=>H.length?s.execute(H.shift()):Y(s,m),s.reserved.release=!0;let Jn=R(Yn);return Jn.release=()=>{s.reserved=null,Vn(s)},Jn;function Yn(ni){s.queue===T?H.push(ni):s.execute(ni)||Y(s,T)}}async function D(H,s){!s&&(s=H,H="");let Jn=ki(),Yn=0,ni,wn=null;try{return await A.unsafe("begin "+H.replace(/[^a-z ]/ig,""),[],{onexecute:gn}).execute(),await Promise.race([un(ni,s),new Promise((Dn,jn)=>ni.onclose=jn)])}catch(Dn){throw Dn}async function un(Dn,jn,$i){let _n=R(ii);_n.savepoint=Io,_n.prepare=(yn)=>wn=yn.replace(/[^a-z0-9$-_. ]/gi);let ao,Ti;$i&&await _n`savepoint ${_n($i)}`;try{if(Ti=await new Promise((yn,xo)=>{let Go=jn(_n);Promise.resolve(Array.isArray(Go)?Promise.all(Go):Go).then(yn,xo)}),ao)throw ao}catch(yn){throw await($i?_n`rollback to ${_n($i)}`:_n`rollback`),yn instanceof qp&&yn.code==="25P02"&&ao||yn}if(!$i)wn?await _n`prepare transaction '${_n.unsafe(wn)}'`:await _n`commit`;return Ti;function Io(yn,xo){if(yn&&Array.isArray(yn.raw))return Io((Go)=>Go.apply(Go,arguments));return arguments.length===1&&(xo=yn,yn=null),un(Dn,xo,"s"+Yn+++(yn?"_"+yn:""))}function ii(yn){yn.catch((xo)=>ao||(ao=xo)),Dn.queue===T?Jn.push(yn):Dn.execute(yn)||Y(Dn,T)}}function gn(Dn){ni=Dn,Y(Dn,m),Dn.reserved=()=>Jn.length?Dn.execute(Jn.shift()):Y(Dn,m)}}function Y(H,s){return H.queue.remove(H),s.push(H),H.queue=s,s===v?H.idleTimer.start():H.idleTimer.cancel(),H}function K(H){return new uo(H,3802)}function E(H,s){if(!Array.isArray(H))return E(Array.from(arguments));return new uo(H,s||(H.length?hm(H)||25:0),o.shared.typeArrayMap)}function y(H){if(p)return H.reject(en.connection("CONNECTION_ENDED",o,o));if(v.length)return V(v.shift(),H);if(l.length)return mn(l.shift(),H);$.length?V($.shift(),H):a.push(H)}function V(H,s){return H.execute(s)?Y(H,$):Y(H,T)}function X(H){return new Promise((s,Jn)=>{H.state?H.active?Pv(o).cancel(H.state,s,Jn):H.cancelled={resolve:s,reject:Jn}:(a.remove(H),H.cancelled=!0,H.reject(en.generic("57014","canceling statement due to user request")),s())})}async function Z({timeout:H=null}={}){if(p)return p;await 1;let s;return p=Promise.race([new Promise((Jn)=>H!==null&&(s=setTimeout(on,H*1000,Jn))),Promise.all(M.map((Jn)=>Jn.end()).concat(G.sql?G.sql.end({timeout:0}):[],c.sql?c.sql.end({timeout:0}):[]))]).then(()=>clearTimeout(s))}async function C(){await Promise.all(M.map((H)=>H.end()))}async function on(H){await Promise.all(M.map((s)=>s.terminate()));while(a.length)a.shift().reject(en.connection("CONNECTION_DESTROYED",o));H()}function mn(H,s){return Y(H,x),H.connect(s),H}function ln(H){Y(H,f)}function Vn(H){if(a.length===0)return Y(H,v);let s=Math.ceil(a.length/(x.length+1)),Jn=!0;while(Jn&&a.length&&s-- >0){let Yn=a.shift();if(Yn.reserve)return Yn.reserve(H);Jn=H.execute(Yn)}Jn?Y(H,$):Y(H,T)}function ji(H,s){Y(H,l),H.reserved=null,H.onclose&&(H.onclose(s),H.onclose=null),o.onclose&&o.onclose(H.id),a.length&&mn(H,a.shift())}}function oG(n,i){if(n&&n.shared)return n;let o=process.env,c=(!n||typeof n==="string"?i:n)||{},{url:p,multihost:a}=mG(n),x=[...p.searchParams].reduce((T,[F,M])=>(T[F]=M,T),{}),m=c.hostname||c.host||a||p.hostname||o.PGHOST||"localhost",l=c.port||p.port||o.PGPORT||5432,f=c.user||c.username||p.username||o.PGUSERNAME||o.PGUSER||lG();c.no_prepare&&(c.prepare=!1),x.sslmode&&(x.ssl=x.sslmode,delete x.sslmode),"timeout"in c&&(console.log("The timeout option is deprecated, use idle_timeout instead"),c.idle_timeout=c.timeout),x.sslrootcert==="system"&&(x.ssl="verify-full");let v=["idle_timeout","connect_timeout","max_lifetime","max_pipeline","backoff","keep_alive"],$={max:10,ssl:!1,idle_timeout:null,connect_timeout:30,max_lifetime:aG,max_pipeline:100,backoff:pG,keep_alive:60,prepare:!0,debug:!1,fetch_types:!0,publications:"alltables",target_session_attrs:null};return{host:Array.isArray(m)?m:m.split(",").map((T)=>T.split(":")[0]),port:Array.isArray(l)?l:m.split(",").map((T)=>parseInt(T.split(":")[1]||l)),path:c.path||m.indexOf("/")>-1&&m+"/.s.PGSQL."+l,database:c.database||c.db||(p.pathname||"").slice(1)||o.PGDATABASE||f,user:f,pass:c.pass||c.password||p.password||o.PGPASSWORD||"",...Object.entries($).reduce((T,[F,M])=>{let A=F in c?c[F]:(F in x)?x[F]==="disable"||x[F]==="false"?!1:x[F]:o["PG"+F.toUpperCase()]||M;return T[F]=typeof A==="string"&&v.includes(F)?+A:A,T},{}),connection:{application_name:"postgres.js",...c.connection,...Object.entries(x).reduce((T,[F,M])=>((F in $)||(T[F]=M),T),{})},types:c.types||{},target_session_attrs:cG(c,p,o),onnotice:c.onnotice,onnotify:c.onnotify,onclose:c.onclose,onparameter:c.onparameter,socket:c.socket,transform:xG(c.transform||{undefined:void 0}),parameters:{},shared:{retries:0,typeArrayMap:{}},...RR(c.types)}}function cG(n,i,o){let c=n.target_session_attrs||i.searchParams.get("target_session_attrs")||o.PGTARGETSESSIONATTRS;if(!c||["read-write","read-only","primary","standby","prefer-standby"].includes(c))return c;throw new Error("target_session_attrs "+c+" is not supported")}function pG(n){return(0.5+Math.random()/2)*Math.min(3**n/100,20)}function aG(){return 60*(30+Math.random()*30)}function xG(n){return{undefined:n.undefined,column:{from:typeof n.column==="function"?n.column:n.column&&n.column.from,to:n.column&&n.column.to},value:{from:typeof n.value==="function"?n.value:n.value&&n.value.from,to:n.value&&n.value.to},row:{from:typeof n.row==="function"?n.row:n.row&&n.row.from,to:n.row&&n.row.to}}}function mG(n){if(!n||typeof n!=="string")return{url:{searchParams:new Map}};let i=n;i=i.slice(i.indexOf("://")+3).split(/[?/]/)[0],i=decodeURIComponent(i.slice(i.indexOf("@")+1));let o=new URL(n.replace(i,i.split(",")[0]));return{url:{username:decodeURIComponent(o.username),password:decodeURIComponent(o.password),host:o.host,hostname:o.hostname,port:o.port,pathname:o.pathname,searchParams:o.searchParams},multihost:i.indexOf(",")>-1&&i}}function lG(){try{return nG.userInfo().username}catch(n){return process.env.USERNAME||"runner"}}class gm extends Qi{constructor(n,i,o,c){super();this.session=i,this.dialect=o,this.config={table:n,withList:c}}static[J]="PgDelete";config;where(n){return this.config.where=n,this}returning(n=this.config.table[L.Symbol.Columns]){return this.config.returning=ei(n),this}getSQL(){return this.dialect.buildDeleteQuery(this.config)}toSQL(){let{typings:n,...i}=this.dialect.sqlToQuery(this.getSQL());return i}_prepare(n){return Un.startActiveSpan("drizzle.prepareQuery",()=>{return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,n,!0)})}prepare(n){return this._prepare(n)}execute=(n)=>{return Un.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(n)})};$dynamic(){return this}}class dm{constructor(n,i,o,c){this.table=n,this.session=i,this.dialect=o,this.withList=c}static[J]="PgInsertBuilder";values(n){if(n=Array.isArray(n)?n:[n],n.length===0)throw new Error("values() must be called with at least one value");let i=n.map((o)=>{let c={},p=this.table[L.Symbol.Columns];for(let a of Object.keys(o)){let x=o[a];c[a]=z(x,k)?x:new Li(x,p[a])}return c});return new VR(this.table,i,this.session,this.dialect,this.withList)}}class VR extends Qi{constructor(n,i,o,c,p){super();this.session=o,this.dialect=c,this.config={table:n,values:i,withList:p}}static[J]="PgInsert";config;returning(n=this.config.table[L.Symbol.Columns]){return this.config.returning=ei(n),this}onConflictDoNothing(n={}){if(n.target===void 0)this.config.onConflict=S`do nothing`;else{let i="";i=Array.isArray(n.target)?n.target.map((c)=>this.dialect.escapeName(this.dialect.casing.getColumnCasing(c))).join(","):this.dialect.escapeName(this.dialect.casing.getColumnCasing(n.target));let o=n.where?S` where ${n.where}`:void 0;this.config.onConflict=S`(${S.raw(i)})${o} do nothing`}return this}onConflictDoUpdate(n){if(n.where&&(n.targetWhere||n.setWhere))throw new Error('You cannot use both "where" and "targetWhere"/"setWhere" at the same time - "where" is deprecated, use "targetWhere" or "setWhere" instead.');let i=n.where?S` where ${n.where}`:void 0,o=n.targetWhere?S` where ${n.targetWhere}`:void 0,c=n.setWhere?S` where ${n.setWhere}`:void 0,p=this.dialect.buildUpdateSet(this.config.table,rx(this.config.table,n.set)),a="";return a=Array.isArray(n.target)?n.target.map((x)=>this.dialect.escapeName(this.dialect.casing.getColumnCasing(x))).join(","):this.dialect.escapeName(this.dialect.casing.getColumnCasing(n.target)),this.config.onConflict=S`(${S.raw(a)})${o} do update set ${p}${i}${c}`,this}getSQL(){return this.dialect.buildInsertQuery(this.config)}toSQL(){let{typings:n,...i}=this.dialect.sqlToQuery(this.getSQL());return i}_prepare(n){return Un.startActiveSpan("drizzle.prepareQuery",()=>{return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,n,!0)})}prepare(n){return this._prepare(n)}execute=(n)=>{return Un.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(n)})};$dynamic(){return this}}function fG(n){return(n.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).map((o)=>o.toLowerCase()).join("_")}function vG(n){return(n.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).reduce((o,c,p)=>{let a=p===0?c.toLowerCase():`${c[0].toUpperCase()}${c.slice(1)}`;return o+a},"")}function $G(n){return n}class dv{static[J]="CasingCache";cache={};cachedTables={};convert;constructor(n){this.convert=n==="snake_case"?fG:n==="camelCase"?vG:$G}getColumnCasing(n){if(!n.keyAsName)return n.name;let i=n.table[L.Symbol.Schema]??"public",o=n.table[L.Symbol.OriginalName],c=`${i}.${o}.${n.name}`;if(!this.cache[c])this.cacheTable(n.table);return this.cache[c]}cacheTable(n){let i=n[L.Symbol.Schema]??"public",o=n[L.Symbol.OriginalName],c=`${i}.${o}`;if(!this.cachedTables[c]){for(let p of Object.values(n[L.Symbol.Columns])){let a=`${c}.${p.name}`;this.cache[a]=this.convert(p.name)}this.cachedTables[c]=!0}}clearCache(){this.cache={},this.cachedTables={}}}class ix extends Vi{static[J]="PgViewBase"}class tc{static[J]="PgDialect";casing;constructor(n){this.casing=new dv(n?.casing)}async migrate(n,i,o){let c=typeof o==="string"?"__drizzle_migrations":o.migrationsTable??"__drizzle_migrations",p=typeof o==="string"?"drizzle":o.migrationsSchema??"drizzle",a=S`
|
|
58
58
|
CREATE TABLE IF NOT EXISTS ${S.identifier(p)}.${S.identifier(c)} (
|
|
59
59
|
id SERIAL PRIMARY KEY,
|
|
60
60
|
hash text NOT NULL,
|
|
61
61
|
created_at bigint
|
|
62
62
|
)
|
|
63
|
-
`;await i.execute(S`CREATE SCHEMA IF NOT EXISTS ${S.identifier(p)}`),await i.execute(a);let m=(await i.all(S`select id, hash, created_at from ${S.identifier(p)}.${S.identifier(c)} order by created_at desc limit 1`))[0];await i.transaction(async(l)=>{for await(let f of n)if(!m||Number(m.created_at)<f.folderMillis){for(let v of f.sql)await l.execute(S.raw(v));await l.execute(S`insert into ${S.identifier(p)}.${S.identifier(c)} ("hash", "created_at") values(${f.hash}, ${f.folderMillis})`)}})}escapeName(n){return`"${n}"`}escapeParam(n){return`\$${n+1}`}escapeString(n){return`'${n.replace(/'/g,"''")}'`}buildWithCTE(n){if(!n?.length)return;let i=[S`with `];for(let[o,c]of n.entries())if(i.push(S`${S.identifier(c._.alias)} as (${c._.sql})`),o<n.length-1)i.push(S`, `);return i.push(S` `),S.join(i)}buildDeleteQuery({table:n,where:i,returning:o,withList:c}){let p=this.buildWithCTE(c),a=o?S` returning ${this.buildSelection(o,{isSingleTable:!0})}`:void 0,x=i?S` where ${i}`:void 0;return S`${p}delete from ${n}${x}${a}`}buildUpdateSet(n,i){let o=n[L.Symbol.Columns],c=Object.keys(o).filter((a)=>i[a]!==void 0||o[a]?.onUpdateFn!==void 0),p=c.length;return S.join(c.flatMap((a,x)=>{let m=o[a],l=i[a]??S.param(m.onUpdateFn(),m),f=S`${S.identifier(this.casing.getColumnCasing(m))} = ${l}`;if(x<p-1)return[f,S.raw(", ")];return[f]}))}buildUpdateQuery({table:n,set:i,where:o,returning:c,withList:p}){let a=this.buildWithCTE(p),x=this.buildUpdateSet(n,i),m=c?S` returning ${this.buildSelection(c,{isSingleTable:!0})}`:void 0,l=o?S` where ${o}`:void 0;return S`${a}update ${n} set ${x}${l}${m}`}buildSelection(n,{isSingleTable:i=!1}={}){let o=n.length,c=n.flatMap(({field:p},a)=>{let x=[];if(z(p,k.Aliased)&&p.isSelectionField)x.push(S.identifier(p.fieldAlias));else if(z(p,k.Aliased)||z(p,k)){let m=z(p,k.Aliased)?p.sql:p;if(i)x.push(new k(m.queryChunks.map((l)=>{if(z(l,u))return S.identifier(this.casing.getColumnCasing(l));return l})));else x.push(m);if(z(p,k.Aliased))x.push(S` as ${S.identifier(p.fieldAlias)}`)}else if(z(p,bn))if(i)x.push(S.identifier(this.casing.getColumnCasing(p)));else x.push(p);if(a<o-1)x.push(S`, `);return x});return S.join(c)}buildSelectQuery({withList:n,fields:i,fieldsFlat:o,where:c,having:p,table:a,joins:x,orderBy:m,groupBy:l,limit:f,offset:v,lockingClause:$,distinct:T,setOperators:F}){let M=o??ei(i);for(let mn of M)if(z(mn.field,bn)&&di(mn.field.table)!==(z(a,fi)?a._.alias:z(a,ix)?a[hn].name:z(a,k)?void 0:di(a))&&!((ln)=>x?.some(({alias:Vn})=>Vn===(ln[L.Symbol.IsAlias]?di(ln):ln[L.Symbol.BaseName])))(mn.field.table)){let ln=di(mn.field.table);throw new Error(`Your "${mn.path.join("->")}" field references a column "${ln}"."${mn.field.name}", but the table "${ln}" is not part of the query! Did you forget to join it?`)}let A=!x||x.length===0,R=this.buildWithCTE(n),G;if(T)G=T===!0?S` distinct`:S` distinct on (${S.join(T.on,S`, `)})`;let Q=this.buildSelection(M,{isSingleTable:A}),b=(()=>{if(z(a,L)&&a[L.Symbol.OriginalName]!==a[L.Symbol.Name]){let mn=S`${S.identifier(a[L.Symbol.OriginalName])}`;if(a[L.Symbol.Schema])mn=S`${S.identifier(a[L.Symbol.Schema])}.${mn}`;return S`${mn} ${S.identifier(a[L.Symbol.Name])}`}return a})(),D=[];if(x)for(let[mn,ln]of x.entries()){if(mn===0)D.push(S` `);let Vn=ln.table,ji=ln.lateral?S` lateral`:void 0;if(z(Vn,no)){let H=Vn[no.Symbol.Name],s=Vn[no.Symbol.Schema],wn=Vn[no.Symbol.OriginalName],Yn=H===wn?void 0:ln.alias;D.push(S`${S.raw(ln.joinType)} join${ji} ${s?S`${S.identifier(s)}.`:void 0}${S.identifier(wn)}${Yn&&S` ${S.identifier(Yn)}`} on ${ln.on}`)}else if(z(Vn,Vi)){let H=Vn[hn].name,s=Vn[hn].schema,wn=Vn[hn].originalName,Yn=H===wn?void 0:ln.alias;D.push(S`${S.raw(ln.joinType)} join${ji} ${s?S`${S.identifier(s)}.`:void 0}${S.identifier(wn)}${Yn&&S` ${S.identifier(Yn)}`} on ${ln.on}`)}else D.push(S`${S.raw(ln.joinType)} join${ji} ${Vn} on ${ln.on}`);if(mn<x.length-1)D.push(S` `)}let Y=S.join(D),K=c?S` where ${c}`:void 0,E=p?S` having ${p}`:void 0,y;if(m&&m.length>0)y=S` order by ${S.join(m,S`, `)}`;let V;if(l&&l.length>0)V=S` group by ${S.join(l,S`, `)}`;let X=typeof f==="object"||typeof f==="number"&&f>=0?S` limit ${f}`:void 0,Z=v?S` offset ${v}`:void 0,C=S.empty();if($){let mn=S` for ${S.raw($.strength)}`;if($.config.of)mn.append(S` of ${S.join(Array.isArray($.config.of)?$.config.of:[$.config.of],S`, `)}`);if($.config.noWait)mn.append(S` no wait`);else if($.config.skipLocked)mn.append(S` skip locked`);C.append(mn)}let on=S`${R}select${G} ${Q} from ${b}${Y}${K}${V}${E}${y}${X}${Z}${C}`;if(F.length>0)return this.buildSetOperations(on,F);return on}buildSetOperations(n,i){let[o,...c]=i;if(!o)throw new Error("Cannot pass undefined values to any set operator");if(c.length===0)return this.buildSetOperationQuery({leftSelect:n,setOperator:o});return this.buildSetOperations(this.buildSetOperationQuery({leftSelect:n,setOperator:o}),c)}buildSetOperationQuery({leftSelect:n,setOperator:{type:i,isAll:o,rightSelect:c,limit:p,orderBy:a,offset:x}}){let m=S`(${n.getSQL()}) `,l=S`(${c.getSQL()})`,f;if(a&&a.length>0){let F=[];for(let M of a)if(z(M,u))F.push(S.identifier(M.name));else if(z(M,k)){for(let A=0;A<M.queryChunks.length;A++){let R=M.queryChunks[A];if(z(R,u))M.queryChunks[A]=S.identifier(R.name)}F.push(S`${M}`)}else F.push(S`${M}`);f=S` order by ${S.join(F,S`, `)} `}let v=typeof p==="object"||typeof p==="number"&&p>=0?S` limit ${p}`:void 0,$=S.raw(`${i} ${o?"all ":""}`),T=x?S` offset ${x}`:void 0;return S`${m}${$}${l}${f}${v}${T}`}buildInsertQuery({table:n,values:i,onConflict:o,returning:c,withList:p}){let a=[],x=n[L.Symbol.Columns],m=Object.entries(x).filter(([F,M])=>!M.shouldDisableInsert()),l=m.map(([,F])=>S.identifier(this.casing.getColumnCasing(F)));for(let[F,M]of i.entries()){let A=[];for(let[R,G]of m){let Q=M[R];if(Q===void 0||z(Q,Li)&&Q.value===void 0)if(G.defaultFn!==void 0){let b=G.defaultFn(),D=z(b,k)?b:S.param(b,G);A.push(D)}else if(!G.default&&G.onUpdateFn!==void 0){let b=G.onUpdateFn(),D=z(b,k)?b:S.param(b,G);A.push(D)}else A.push(S`default`);else A.push(Q)}if(a.push(A),F<i.length-1)a.push(S`, `)}let f=this.buildWithCTE(p),v=S.join(a),$=c?S` returning ${this.buildSelection(c,{isSingleTable:!0})}`:void 0,T=o?S` on conflict ${o}`:void 0;return S`${f}insert into ${n} ${l} values ${v}${T}${$}`}buildRefreshMaterializedViewQuery({view:n,concurrently:i,withNoData:o}){let c=i?S` concurrently`:void 0,p=o?S` with no data`:void 0;return S`refresh materialized view${c} ${n}${p}`}prepareTyping(n){if(z(n,im)||z(n,nm))return"json";else if(z(n,om))return"decimal";else if(z(n,cm))return"time";else if(z(n,pm)||z(n,am))return"timestamp";else if(z(n,gx)||z(n,dx))return"date";else if(z(n,xm))return"uuid";else return"none"}sqlToQuery(n,i){return n.toQuery({casing:this.casing,escapeName:this.escapeName,escapeParam:this.escapeParam,escapeString:this.escapeString,prepareTyping:this.prepareTyping,invokeSource:i})}buildRelationalQueryWithoutPK({fullSchema:n,schema:i,tableNamesMap:o,table:c,tableConfig:p,queryConfig:a,tableAlias:x,nestedQueryRelation:m,joinOn:l}){let f=[],v,$,T=[],F,M=[];if(a===!0)f=Object.entries(p.columns).map(([G,Q])=>({dbKey:Q.name,tsKey:G,field:Ho(Q,x),relationTableTsKey:void 0,isJson:!1,selection:[]}));else{let R=Object.fromEntries(Object.entries(p.columns).map(([K,E])=>[K,Ho(E,x)]));if(a.where){let K=typeof a.where==="function"?a.where(R,pS()):a.where;F=K&&Ea(K,x)}let G=[],Q=[];if(a.columns){let K=!1;for(let[E,y]of Object.entries(a.columns)){if(y===void 0)continue;if(E in p.columns){if(!K&&y===!0)K=!0;Q.push(E)}}if(Q.length>0)Q=K?Q.filter((E)=>a.columns?.[E]===!0):Object.keys(p.columns).filter((E)=>!Q.includes(E))}else Q=Object.keys(p.columns);for(let K of Q){let E=p.columns[K];G.push({tsKey:K,value:E})}let b=[];if(a.with)b=Object.entries(a.with).filter((K)=>!!K[1]).map(([K,E])=>({tsKey:K,queryConfig:E,relation:p.relations[K]}));let D;if(a.extras){D=typeof a.extras==="function"?a.extras(R,{sql:S}):a.extras;for(let[K,E]of Object.entries(D))G.push({tsKey:K,value:Gf(E,x)})}for(let{tsKey:K,value:E}of G)f.push({dbKey:z(E,k.Aliased)?E.fieldAlias:p.columns[K].name,tsKey:K,field:z(E,bn)?Ho(E,x):E,relationTableTsKey:void 0,isJson:!1,selection:[]});let Y=typeof a.orderBy==="function"?a.orderBy(R,aS()):a.orderBy??[];if(!Array.isArray(Y))Y=[Y];T=Y.map((K)=>{if(z(K,bn))return Ho(K,x);return Ea(K,x)}),v=a.limit,$=a.offset;for(let{tsKey:K,queryConfig:E,relation:y}of b){let V=mS(i,o,y),X=Oc(y.referencedTable),Z=o[X],C=`${x}_${K}`,on=Uc(...V.fields.map((Vn,ji)=>Eo(Ho(V.references[ji],C),Ho(Vn,x)))),mn=this.buildRelationalQueryWithoutPK({fullSchema:n,schema:i,tableNamesMap:o,table:n[Z],tableConfig:i[Z],queryConfig:z(y,mc)?E===!0?{limit:1}:{...E,limit:1}:E,tableAlias:C,joinOn:on,nestedQueryRelation:y}),ln=S`${S.identifier(C)}.${S.identifier("data")}`.as(K);M.push({on:S`true`,table:new fi(mn.sql,{},C),alias:C,joinType:"left",lateral:!0}),f.push({dbKey:K,tsKey:K,field:ln,relationTableTsKey:Z,isJson:!0,selection:mn.selection})}}if(f.length===0)throw new qx({message:`No fields selected for table "${p.tsName}" ("${x}")`});let A;if(F=Uc(l,F),m){let R=S`json_build_array(${S.join(f.map(({field:b,tsKey:D,isJson:Y})=>Y?S`${S.identifier(`${x}_${D}`)}.${S.identifier("data")}`:z(b,k.Aliased)?b.sql:b),S`, `)})`;if(z(m,Va))R=S`coalesce(json_agg(${R}${T.length>0?S` order by ${S.join(T,S`, `)}`:void 0}), '[]'::json)`;let G=[{dbKey:"data",tsKey:"data",field:R.as("data"),isJson:!0,relationTableTsKey:p.tsName,selection:f}];if(v!==void 0||$!==void 0||T.length>0)A=this.buildSelectQuery({table:tx(c,x),fields:{},fieldsFlat:[{path:[],field:S.raw("*")}],where:F,limit:v,offset:$,orderBy:T,setOperators:[]}),F=void 0,v=void 0,$=void 0,T=[];else A=tx(c,x);A=this.buildSelectQuery({table:z(A,no)?A:new fi(A,{},x),fields:{},fieldsFlat:G.map(({field:b})=>({path:[],field:z(b,bn)?Ho(b,x):b})),joins:M,where:F,limit:v,offset:$,orderBy:T,setOperators:[]})}else A=this.buildSelectQuery({table:tx(c,x),fields:{},fieldsFlat:f.map(({field:R})=>({path:[],field:z(R,bn)?Ho(R,x):R})),joins:M,where:F,limit:v,offset:$,orderBy:T,setOperators:[]});return{tableTsKey:p.tsName,sql:A,selection:f}}}class bi{static[J]="SelectionProxyHandler";config;constructor(n){this.config={...n}}get(n,i){if(i==="_")return{...n._,selectedFields:new Proxy(n._.selectedFields,this)};if(i===hn)return{...n[hn],selectedFields:new Proxy(n[hn].selectedFields,this)};if(typeof i==="symbol")return n[i];let c=(z(n,fi)?n._.selectedFields:z(n,Vi)?n[hn].selectedFields:n)[i];if(z(c,k.Aliased)){if(this.config.sqlAliasedBehavior==="sql"&&!c.isSelectionField)return c.sql;let p=c.clone();return p.isSelectionField=!0,p}if(z(c,k)){if(this.config.sqlBehavior==="sql")return c;throw new Error(`You tried to reference "${i}" field from a subquery, which is a raw SQL field, but it doesn't have an alias declared. Please add an alias to the field using ".as('alias')" method.`)}if(z(c,bn)){if(this.config.alias)return new Proxy(c,new Ap(new Proxy(c.table,new Ha(this.config.alias,this.config.replaceOriginalName??!1))));return c}if(typeof c!=="object"||c===null)return c;return new Proxy(c,new bi(this.config))}}class ev{static[J]="TypedQueryBuilder";getSelectedFields(){return this._.selectedFields}}class Oi{static[J]="PgSelectBuilder";fields;session;dialect;withList=[];distinct;constructor(n){if(this.fields=n.fields,this.session=n.session,this.dialect=n.dialect,n.withList)this.withList=n.withList;this.distinct=n.distinct}from(n){let i=!!this.fields,o;if(this.fields)o=this.fields;else if(z(n,fi))o=Object.fromEntries(Object.keys(n._.selectedFields).map((c)=>[c,n[c]]));else if(z(n,ix))o=n[hn].selectedFields;else if(z(n,k))o={};else o=lw(n);return new n$({table:n,fields:o,isPartialSelect:i,session:this.session,dialect:this.dialect,withList:this.withList,distinct:this.distinct})}}class uR extends ev{static[J]="PgSelectQueryBuilder";_;config;joinsNotNullableMap;tableName;isPartialSelect;session;dialect;constructor({table:n,fields:i,isPartialSelect:o,session:c,dialect:p,withList:a,distinct:x}){super();this.config={withList:a,table:n,fields:{...i},distinct:x,setOperators:[]},this.isPartialSelect=o,this.session=c,this.dialect=p,this._={selectedFields:i},this.tableName=Ef(n),this.joinsNotNullableMap=typeof this.tableName==="string"?{[this.tableName]:!0}:{}}createJoin(n){return(i,o)=>{let c=this.tableName,p=Ef(i);if(typeof p==="string"&&this.config.joins?.some((a)=>a.alias===p))throw new Error(`Alias "${p}" is already used in this query`);if(!this.isPartialSelect){if(Object.keys(this.joinsNotNullableMap).length===1&&typeof c==="string")this.config.fields={[c]:this.config.fields};if(typeof p==="string"&&!z(i,k)){let a=z(i,fi)?i._.selectedFields:z(i,Vi)?i[hn].selectedFields:i[L.Symbol.Columns];this.config.fields[p]=a}}if(typeof o==="function")o=o(new Proxy(this.config.fields,new bi({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));if(!this.config.joins)this.config.joins=[];if(this.config.joins.push({on:o,table:i,joinType:n,alias:p}),typeof p==="string")switch(n){case"left":{this.joinsNotNullableMap[p]=!1;break}case"right":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([a])=>[a,!1])),this.joinsNotNullableMap[p]=!0;break}case"inner":{this.joinsNotNullableMap[p]=!0;break}case"full":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([a])=>[a,!1])),this.joinsNotNullableMap[p]=!1;break}}return this}}leftJoin=this.createJoin("left");rightJoin=this.createJoin("right");innerJoin=this.createJoin("inner");fullJoin=this.createJoin("full");createSetOperator(n,i){return(o)=>{let c=typeof o==="function"?o(TG()):o;if(!Hf(this.getSelectedFields(),c.getSelectedFields()))throw new Error("Set operator error (union / intersect / except): selected fields are not the same or are in a different order");return this.config.setOperators.push({type:n,isAll:i,rightSelect:c}),this}}union=this.createSetOperator("union",!1);unionAll=this.createSetOperator("union",!0);intersect=this.createSetOperator("intersect",!1);intersectAll=this.createSetOperator("intersect",!0);except=this.createSetOperator("except",!1);exceptAll=this.createSetOperator("except",!0);addSetOperators(n){return this.config.setOperators.push(...n),this}where(n){if(typeof n==="function")n=n(new Proxy(this.config.fields,new bi({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));return this.config.where=n,this}having(n){if(typeof n==="function")n=n(new Proxy(this.config.fields,new bi({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));return this.config.having=n,this}groupBy(...n){if(typeof n[0]==="function"){let i=n[0](new Proxy(this.config.fields,new bi({sqlAliasedBehavior:"alias",sqlBehavior:"sql"})));this.config.groupBy=Array.isArray(i)?i:[i]}else this.config.groupBy=n;return this}orderBy(...n){if(typeof n[0]==="function"){let i=n[0](new Proxy(this.config.fields,new bi({sqlAliasedBehavior:"alias",sqlBehavior:"sql"}))),o=Array.isArray(i)?i:[i];if(this.config.setOperators.length>0)this.config.setOperators.at(-1).orderBy=o;else this.config.orderBy=o}else{let i=n;if(this.config.setOperators.length>0)this.config.setOperators.at(-1).orderBy=i;else this.config.orderBy=i}return this}limit(n){if(this.config.setOperators.length>0)this.config.setOperators.at(-1).limit=n;else this.config.limit=n;return this}offset(n){if(this.config.setOperators.length>0)this.config.setOperators.at(-1).offset=n;else this.config.offset=n;return this}for(n,i={}){return this.config.lockingClause={strength:n,config:i},this}getSQL(){return this.dialect.buildSelectQuery(this.config)}toSQL(){let{typings:n,...i}=this.dialect.sqlToQuery(this.getSQL());return i}as(n){return new Proxy(new fi(this.getSQL(),this.config.fields,n),new bi({alias:n,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}getSelectedFields(){return new Proxy(this.config.fields,new bi({alias:this.tableName,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}$dynamic(){return this}}class n$ extends uR{static[J]="PgSelect";_prepare(n){let{session:i,config:o,dialect:c,joinsNotNullableMap:p}=this;if(!i)throw new Error("Cannot execute a query on a query builder. Please use a database instance instead.");return Un.startActiveSpan("drizzle.prepareQuery",()=>{let a=ei(o.fields),x=i.prepareQuery(c.sqlToQuery(this.getSQL()),a,n,!0);return x.joinsNotNullableMap=p,x})}prepare(n){return this._prepare(n)}execute=(n)=>{return Un.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(n)})}}mw(n$,[Qi]);function gp(n,i){return(o,c,...p)=>{let a=[c,...p].map((x)=>({type:n,isAll:i,rightSelect:x}));for(let x of a)if(!Hf(o.getSelectedFields(),x.rightSelect.getSelectedFields()))throw new Error("Set operator error (union / intersect / except): selected fields are not the same or are in a different order");return o.addSetOperators(a)}}var TG=()=>({union:wG,unionAll:JG,intersect:SG,intersectAll:AG,except:FG,exceptAll:MG}),wG=gp("union",!1),JG=gp("union",!0),SG=gp("intersect",!1),AG=gp("intersect",!0),FG=gp("except",!1),MG=gp("except",!0);class i${static[J]="PgQueryBuilder";dialect;dialectConfig;constructor(n){this.dialect=z(n,tc)?n:void 0,this.dialectConfig=z(n,tc)?void 0:n}$with(n){let i=this;return{as(o){if(typeof o==="function")o=o(i);return new Proxy(new Qa(o.getSQL(),o.getSelectedFields(),n,!0),new bi({alias:n,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}}with(...n){let i=this;function o(a){return new Oi({fields:a??void 0,session:void 0,dialect:i.getDialect(),withList:n})}function c(a){return new Oi({fields:a??void 0,session:void 0,dialect:i.getDialect(),distinct:!0})}function p(a,x){return new Oi({fields:x??void 0,session:void 0,dialect:i.getDialect(),distinct:{on:a}})}return{select:o,selectDistinct:c,selectDistinctOn:p}}select(n){return new Oi({fields:n??void 0,session:void 0,dialect:this.getDialect()})}selectDistinct(n){return new Oi({fields:n??void 0,session:void 0,dialect:this.getDialect(),distinct:!0})}selectDistinctOn(n,i){return new Oi({fields:i??void 0,session:void 0,dialect:this.getDialect(),distinct:{on:n}})}getDialect(){if(!this.dialect)this.dialect=new tc(this.dialectConfig);return this.dialect}}class o$ extends Qi{constructor(n,i,o){super();this.session=i,this.dialect=o,this.config={view:n}}static[J]="PgRefreshMaterializedView";config;concurrently(){if(this.config.withNoData!==void 0)throw new Error("Cannot use concurrently and withNoData together");return this.config.concurrently=!0,this}withNoData(){if(this.config.concurrently!==void 0)throw new Error("Cannot use concurrently and withNoData together");return this.config.withNoData=!0,this}getSQL(){return this.dialect.buildRefreshMaterializedViewQuery(this.config)}toSQL(){let{typings:n,...i}=this.dialect.sqlToQuery(this.getSQL());return i}_prepare(n){return Un.startActiveSpan("drizzle.prepareQuery",()=>{return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),void 0,n,!0)})}prepare(n){return this._prepare(n)}execute=(n)=>{return Un.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(n)})}}class em{constructor(n,i,o,c){this.table=n,this.session=i,this.dialect=o,this.withList=c}static[J]="PgUpdateBuilder";set(n){return new _R(this.table,rx(this.table,n),this.session,this.dialect,this.withList)}}class _R extends Qi{constructor(n,i,o,c,p){super();this.session=o,this.dialect=c,this.config={set:i,table:n,withList:p}}static[J]="PgUpdate";config;where(n){return this.config.where=n,this}returning(n=this.config.table[L.Symbol.Columns]){return this.config.returning=ei(n),this}getSQL(){return this.dialect.buildUpdateQuery(this.config)}toSQL(){let{typings:n,...i}=this.dialect.sqlToQuery(this.getSQL());return i}_prepare(n){return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,n,!0)}prepare(n){return this._prepare(n)}execute=(n)=>{return this._prepare().execute(n)};$dynamic(){return this}}class ox extends k{constructor(n){super(ox.buildEmbeddedCount(n.source,n.filters).queryChunks);this.params=n,this.mapWith(Number),this.session=n.session,this.sql=ox.buildCount(n.source,n.filters)}sql;static[J]="PgCountBuilder";[Symbol.toStringTag]="PgCountBuilder";session;static buildEmbeddedCount(n,i){return S`(select count(*) from ${n}${S.raw(" where ").if(i)}${i})`}static buildCount(n,i){return S`select count(*) as count from ${n}${S.raw(" where ").if(i)}${i};`}then(n,i){return Promise.resolve(this.session.count(this.sql)).then(n,i)}catch(n){return this.then(void 0,n)}finally(n){return this.then((i)=>{return n?.(),i},(i)=>{throw n?.(),i})}}class p${constructor(n,i,o,c,p,a,x){this.fullSchema=n,this.schema=i,this.tableNamesMap=o,this.table=c,this.tableConfig=p,this.dialect=a,this.session=x}static[J]="PgRelationalQueryBuilder";findMany(n){return new c$(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,n?n:{},"many")}findFirst(n){return new c$(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,n?{...n,limit:1}:{limit:1},"first")}}class c$ extends Qi{constructor(n,i,o,c,p,a,x,m,l){super();this.fullSchema=n,this.schema=i,this.tableNamesMap=o,this.table=c,this.tableConfig=p,this.dialect=a,this.session=x,this.config=m,this.mode=l}static[J]="PgRelationalQuery";_prepare(n){return Un.startActiveSpan("drizzle.prepareQuery",()=>{let{query:i,builtQuery:o}=this._toSQL();return this.session.prepareQuery(o,void 0,n,!0,(c,p)=>{let a=c.map((x)=>mm(this.schema,this.tableConfig,x,i.selection,p));if(this.mode==="first")return a[0];return a})})}prepare(n){return this._prepare(n)}_getQuery(){return this.dialect.buildRelationalQueryWithoutPK({fullSchema:this.fullSchema,schema:this.schema,tableNamesMap:this.tableNamesMap,table:this.table,tableConfig:this.tableConfig,queryConfig:this.config,tableAlias:this.tableConfig.tsName})}getSQL(){return this._getQuery().sql}_toSQL(){let n=this._getQuery(),i=this.dialect.sqlToQuery(n.sql);return{query:n,builtQuery:i}}toSQL(){return this._toSQL().builtQuery}execute(){return Un.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute()})}}class a$ extends Qi{constructor(n,i,o,c){super();this.execute=n,this.sql=i,this.query=o,this.mapBatchResult=c}static[J]="PgRaw";getSQL(){return this.sql}getQuery(){return this.query}mapResult(n,i){return i?this.mapBatchResult(n):n}_prepare(){return this}isResponseInArrayMode(){return!1}}class cx{constructor(n,i,o){if(this.dialect=n,this.session=i,this._=o?{schema:o.schema,fullSchema:o.fullSchema,tableNamesMap:o.tableNamesMap,session:i}:{schema:void 0,fullSchema:{},tableNamesMap:{},session:i},this.query={},this._.schema)for(let[c,p]of Object.entries(this._.schema))this.query[c]=new p$(o.fullSchema,this._.schema,this._.tableNamesMap,o.fullSchema[c],p,n,i)}static[J]="PgDatabase";query;$with(n){let i=this;return{as(o){if(typeof o==="function")o=o(new i$(i.dialect));return new Proxy(new Qa(o.getSQL(),o.getSelectedFields(),n,!0),new bi({alias:n,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}}$count(n,i){return new ox({source:n,filters:i,session:this.session})}with(...n){let i=this;function o(l){return new Oi({fields:l??void 0,session:i.session,dialect:i.dialect,withList:n})}function c(l){return new Oi({fields:l??void 0,session:i.session,dialect:i.dialect,withList:n,distinct:!0})}function p(l,f){return new Oi({fields:f??void 0,session:i.session,dialect:i.dialect,withList:n,distinct:{on:l}})}function a(l){return new em(l,i.session,i.dialect,n)}function x(l){return new dm(l,i.session,i.dialect,n)}function m(l){return new gm(l,i.session,i.dialect,n)}return{select:o,selectDistinct:c,selectDistinctOn:p,update:a,insert:x,delete:m}}select(n){return new Oi({fields:n??void 0,session:this.session,dialect:this.dialect})}selectDistinct(n){return new Oi({fields:n??void 0,session:this.session,dialect:this.dialect,distinct:!0})}selectDistinctOn(n,i){return new Oi({fields:i??void 0,session:this.session,dialect:this.dialect,distinct:{on:n}})}update(n){return new em(n,this.session,this.dialect)}insert(n){return new dm(n,this.session,this.dialect)}delete(n){return new gm(n,this.session,this.dialect)}refreshMaterializedView(n){return new o$(n,this.session,this.dialect)}execute(n){let i=typeof n==="string"?S.raw(n):n.getSQL(),o=this.dialect.sqlToQuery(i),c=this.session.prepareQuery(o,void 0,void 0,!1);return new a$(()=>c.execute(),i,o,(p)=>c.mapResult(p,!0))}transaction(n,i){return this.session.transaction(n,i)}}class bR{constructor(n,i){this.unique=n,this.name=i}static[J]="PgIndexBuilderOn";on(...n){return new nl(n.map((i)=>{if(z(i,k))return i;i=i;let o=new za(i.name,!!i.keyAsName,i.columnType,i.indexConfig);return i.indexConfig=JSON.parse(JSON.stringify(i.defaultConfig)),o}),this.unique,!1,this.name)}onOnly(...n){return new nl(n.map((i)=>{if(z(i,k))return i;i=i;let o=new za(i.name,!!i.keyAsName,i.columnType,i.indexConfig);return i.indexConfig=i.defaultConfig,o}),this.unique,!0,this.name)}using(n,...i){return new nl(i.map((o)=>{if(z(o,k))return o;o=o;let c=new za(o.name,!!o.keyAsName,o.columnType,o.indexConfig);return o.indexConfig=JSON.parse(JSON.stringify(o.defaultConfig)),c}),this.unique,!0,this.name,n)}}class nl{static[J]="PgIndexBuilder";config;constructor(n,i,o,c,p="btree"){this.config={name:c,columns:n,unique:i,only:o,method:p}}concurrently(){return this.config.concurrently=!0,this}with(n){return this.config.with=n,this}where(n){return this.config.where=n,this}build(n){return new jR(this.config,n)}}class jR{static[J]="PgIndex";config;constructor(n,i){this.config={...n,table:i}}}function x$(n){return new bR(!0,n)}class m${constructor(n){this.query=n}getQuery(){return this.query}mapResult(n,i){return n}static[J]="PgPreparedQuery";joinsNotNullableMap}class l${constructor(n){this.dialect=n}static[J]="PgSession";execute(n){return Un.startActiveSpan("drizzle.operation",()=>{return Un.startActiveSpan("drizzle.prepareQuery",()=>{return this.prepareQuery(this.dialect.sqlToQuery(n),void 0,void 0,!1)}).execute()})}all(n){return this.prepareQuery(this.dialect.sqlToQuery(n),void 0,void 0,!1).all()}async count(n){let i=await this.execute(n);return Number(i[0].count)}}class f$ extends cx{constructor(n,i,o,c=0){super(n,i,o);this.schema=o,this.nestedIndex=c}static[J]="PgTransaction";rollback(){throw new Yf}getTransactionConfigSQL(n){let i=[];if(n.isolationLevel)i.push(`isolation level ${n.isolationLevel}`);if(n.accessMode)i.push(n.accessMode);if(typeof n.deferrable==="boolean")i.push(n.deferrable?"deferrable":"not deferrable");return S.raw(i.join(" "))}setTransaction(n){return this.session.execute(S`set transaction ${this.getTransactionConfigSQL(n)}`)}}class yR extends m${constructor(n,i,o,c,p,a,x){super({sql:i,params:o});this.client=n,this.queryString=i,this.params=o,this.logger=c,this.fields=p,this._isResponseInArrayMode=a,this.customResultMapper=x}static[J]="PostgresJsPreparedQuery";async execute(n={}){return Un.startActiveSpan("drizzle.execute",async(i)=>{let o=Xf(this.params,n);i?.setAttributes({"drizzle.query.text":this.queryString,"drizzle.query.params":JSON.stringify(o)}),this.logger.logQuery(this.queryString,o);let{fields:c,queryString:p,client:a,joinsNotNullableMap:x,customResultMapper:m}=this;if(!c&&!m)return Un.startActiveSpan("drizzle.driver.execute",()=>{return a.unsafe(p,o)});let l=await Un.startActiveSpan("drizzle.driver.execute",()=>{return i?.setAttributes({"drizzle.query.text":p,"drizzle.query.params":JSON.stringify(o)}),a.unsafe(p,o).values()});return Un.startActiveSpan("drizzle.mapResponse",()=>{return m?m(l):l.map((f)=>xw(c,f,x))})})}all(n={}){return Un.startActiveSpan("drizzle.execute",async(i)=>{let o=Xf(this.params,n);return i?.setAttributes({"drizzle.query.text":this.queryString,"drizzle.query.params":JSON.stringify(o)}),this.logger.logQuery(this.queryString,o),Un.startActiveSpan("drizzle.driver.execute",()=>{return i?.setAttributes({"drizzle.query.text":this.queryString,"drizzle.query.params":JSON.stringify(o)}),this.client.unsafe(this.queryString,o)})})}isResponseInArrayMode(){return this._isResponseInArrayMode}}class px extends l${constructor(n,i,o,c={}){super(i);this.client=n,this.schema=o,this.options=c,this.logger=c.logger??new Qf}static[J]="PostgresJsSession";logger;prepareQuery(n,i,o,c,p){return new yR(this.client,n.sql,n.params,this.logger,i,c,p)}query(n,i){return this.logger.logQuery(n,i),this.client.unsafe(n,i).values()}queryObjects(n,i){return this.client.unsafe(n,i)}transaction(n,i){return this.client.begin(async(o)=>{let c=new px(o,this.dialect,this.schema,this.options),p=new v$(this.dialect,c,this.schema);if(i)await p.setTransaction(i);return n(p)})}}class v$ extends f${constructor(n,i,o,c=0){super(n,i,o,c);this.session=i}static[J]="PostgresJsTransaction";transaction(n){return this.session.client.savepoint((i)=>{let o=new px(i,this.dialect,this.schema,this.session.options),c=new v$(this.dialect,o,this.schema);return n(c)})}}class BR extends cx{static[J]="PostgresJsDatabase"}function dp(n,i={}){let o=(l)=>l;for(let l of["1184","1082","1083","1114"])n.options.parsers[l]=o,n.options.serializers[l]=o;n.options.serializers["114"]=o,n.options.serializers["3802"]=o;let c=new tc({casing:i.casing}),p;if(i.logger===!0)p=new zf;else if(i.logger!==!1)p=i.logger;let a;if(i.schema){let l=xS(i.schema,lS);a={fullSchema:i.schema,schema:l.tables,tableNamesMap:l.tableNamesMap}}let x=new px(n,c,a,{logger:p}),m=new BR(c,x,a);return m.$client=n,m}function il(...n){if(typeof n[0]==="string"){let i=rp(n[0]);return dp(i,n[1])}if(fw(n[0])){let{connection:i,client:o,...c}=n[0];if(o)return dp(o,c);if(typeof i==="object"&&i.url!==void 0){let{url:a,...x}=i,m=rp(a,x);return dp(m,c)}let p=rp(i);return dp(p,c)}return dp(n[0],n[1])}((n)=>{function i(o){return dp({},o)}n.mock=i})(il||(il={}));var T$={};e4(T$,{users:()=>Xo,userChanges:()=>WG,untrackedUserColumnNames:()=>RG,twoFactorMethod:()=>hR,trackedUserColumnName:()=>CR,trackableUserColumnNames:()=>DR,role:()=>NR,players:()=>$$,passwordResetAttempts:()=>KG,loginHistory:()=>ep,games:()=>ol,banishedIps:()=>cl});function LR(n){return S`lower(${n})`}var NR=kx("role",["admin","user"]),Xo=xc("users",{id:Ni().primaryKey().defaultRandom(),username:vi({length:16}).notNull(),email:vi({length:254}).notNull(),hash:vi({length:64}).notNull(),salt:vi({length:36}).notNull(),createdAt:wo({withTimezone:!0}).notNull().defaultNow(),createdIp:vi({length:45}).notNull(),isActive:Oa().notNull().default(!1),verifiedAt:wo({withTimezone:!0}),userRole:NR().default("user")},(n)=>[x$("usernameUniqueIndex").on(LR(n.username)),x$("emailUniqueIndex").on(LR(n.email))]),RG=["id","createdAt","createdIp","isActive","salt","verifiedAt"],DR=["username","email","hash","userRole"],CR=kx("trackedUserColumnName",DR),WG=xc("userChanges",{id:Ni().primaryKey().defaultRandom(),userId:Ni().notNull().references(()=>Xo.id),changedAt:wo({withTimezone:!0}).notNull().defaultNow(),changedIp:vi({length:45}).notNull(),changedColumn:CR().notNull(),oldValue:vi({length:255}),newValue:vi({length:255})}),ol=xc("games",{id:Ni().primaryKey().defaultRandom()}),$$=xc("players",{userId:Ni().notNull().references(()=>Xo.id),gameId:Ni().notNull().references(()=>ol.id),score:ex().notNull()},(n)=>[iS({name:"players_userId_gameId_pk",columns:[n.userId,n.gameId]})]),ep=xc("loginHistory",{id:Ni().primaryKey().defaultRandom(),userId:Ni().references(()=>Xo.id),loginTime:wo({withTimezone:!0}).notNull().defaultNow(),ipAddress:vi({length:45}).notNull(),userAgent:vi({length:1024}),successful:Oa().notNull().default(!1)}),hR=kx("twoFactorMethod",["email","phone"]),KG=xc("passwordResetAttempts",{id:Ni().primaryKey().defaultRandom(),userId:Ni().notNull().references(()=>Xo.id),requestedIp:vi({length:45}).notNull(),requestedAt:wo({withTimezone:!0}).notNull().defaultNow(),succeededIp:vi({length:45}),succeededAt:wo({withTimezone:!0}),verificationMethod:hR().notNull()}),cl=xc("banishedIps",{ip:vi({length:45}).primaryKey(),reason:vi({length:2048}).notNull(),banishedAt:wo({withTimezone:!0}).notNull().defaultNow(),banishedUntil:wo({withTimezone:!0})});var __dirname="/home/runner/work/wayforge/wayforge/apps/tempest.games/src/database";class w${options;sql;drizzle;observers=new Map;async setupTriggersAndNotifications(){await this.sql.file(XG.resolve(__dirname,"notify_update.sql"));let n=[di(Xo),di(ol),di($$)];await this.sql`SELECT create_notify_triggers(${this.sql.array(n)})`,await this.sql.listen("table_update",(i)=>{let o=i.split(","),c=o[0],p=o[1],a=`${c}("${p}")`;if(this.observers.has(a))this.observers.get(a).next(a)})}constructor(n=!1,i={host:rn.POSTGRES_HOST,port:rn.POSTGRES_PORT,user:rn.POSTGRES_USER,password:rn.POSTGRES_PASSWORD,database:rn.POSTGRES_DATABASE}){this.options=i,this.sql=rp(i),this.drizzle=il(this.sql,{schema:T$,logger:n})}observe(n,i){if(!this.observers.has(n))this.observers.set(n,new xn);this.observers.get(n).subscribe("SINGLETON",i)}}import{createHash as GG}from"crypto";function J$(n){let i=GG("sha256").update(n).digest("hex");return`${i.substring(0,8)}-${i.substring(8,12)}-${i.substring(12,16)}-${i.substring(16,20)}-${i.substring(20,32)}`}var IR=["123","321","abc","admin","adobe","alexander","amanda","andrea","andrew","angel","apple","asdf","ashley","baby","banana","baseball","batman","bear","biteme","blazer","blonde","boston","buster","butterfly","cameron","charlie","cheese","chelsea","chicken","chocolate","chris","compaq","computer","cookie","corvette","cowboys","dakota","dallas","daniel","david","diamond","dolphin","donald","dragon","eagle","flower","football","frank","freedom","friend","gateway","george","ginger","god","golf","hannah","hardcore","harley","heather","hello","hottie","hunter","internet","jasmine","jennifer","jessica","jesus","johnny","jordan","joshua","justin","justme","killer","knight","lakers","letmein","liverpool","login","london","love","lucky","mackenzie","maggie","master","matrix","matthew","maverick","melissa","mercedes","michael","michelle","mickey","miller","money","monkey","morgan","mother","muffin","mustang","natasha","nathan","nicole","ninja","orange","pass","password","patrick","peanut","pepper","phoenix","photoshop","pokemon","princess","purple","qazwsx","qwerty","rainbow","ranger","root","samantha","samsung","scooter","secret","shadow","simpson","smile","soccer","sparkle","starwars","summer","sunflower","sunshine","superman","taylor","temp","test","thomas","tigers","tigger","tinkerbell","trust","turtle","victoria","welcome","whatever","william","winter","yellow","zaq12wsx","zxcvbn"];var YG=3,zG=15,QG=/^[a-zA-Z0-9_-]+$/,ZR=Gn.string().min(YG).max(zG).regex(QG),kR=20,sR={"0":"o","1":"l","3":"e","4":"a","5":"s","7":"t","@":"a",$:"s","!":"i"};function HG(n){let i="";for(let o of n)if(o in sR)i+=sR[o];else i+=o;return i}function EG(n){let i=n.toLocaleLowerCase(),o=HG(i);for(let c of IR){if(o.includes(c))return!0;if(i.includes(c))return!0}return!1}function OG(n){let i=new Set(n).size;return n.length*Math.log2(i)}function UG(n){let i=0,o=100;if(EG(n))i-=o;return i+=OG(n)*0.5,Math.max(i,0)}var tR=Gn.string().refine((n)=>{return UG(n)>=kR},{message:`Password does not meet the minimum complexity of ${kR}.`}).brand("password"),qR=Gn.object({username:ZR,password:tR}).strict(),VG=Gn.string().email().brand("email"),PR=Gn.object({username:ZR,password:tR,email:VG}).strict();var pl={100:"Continue",101:"Switching Protocols",102:"Processing",103:"Early Hints",200:"OK",201:"Created",202:"Accepted",203:"Non-Authoritative Information",204:"No Content",205:"Reset Content",206:"Partial Content",207:"Multi-Status",208:"Already Reported",226:"IM Used",300:"Multiple Choices",301:"Moved Permanently",302:"Found",303:"See Other",304:"Not Modified",305:"Use Proxy",306:"Switch Proxy",307:"Temporary Redirect",308:"Permanent Redirect",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",407:"Proxy Authentication Required",408:"Request Timeout",409:"Conflict",410:"Gone",411:"Length Required",412:"Precondition Failed",413:"Payload Too Large",414:"URI Too Long",415:"Unsupported Media Type",416:"Range Not Satisfiable",417:"Expectation Failed",418:"I'm a teapot",421:"Misdirected Request",422:"Unprocessable Entity",423:"Locked",424:"Failed Dependency",425:"Too Early",426:"Upgrade Required",428:"Precondition Required",429:"Too Many Requests",431:"Request Header Fields Too Large",451:"Unavailable For Legal Reasons",500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout",505:"HTTP Version Not Supported",506:"Variant Also Negotiates",507:"Insufficient Storage",508:"Loop Detected",510:"Not Extended",511:"Network Authentication Required"},S$=H$(pl).map(([n])=>Gn.literal(Number(n))),uG=Gn.union([S$[0],S$[1],...S$]),rR=Gn.tuple([uG,Gn.string()]);var gR=go({key:"count",default:0}),_G=Xc({key:"incrementTX",do:({set:n})=>{n(gR,(i)=>i+1)}}),dR=f0({key:"countContinuity",config:(n)=>n.add(gR).add(_G)});var n4=_v(Fc,"backend.worker.game.bun",Jn),qc=new w$({logQuery(n,i){Jn.info("\uD83D\uDCDD query",n,i)}});nn.STORE.loggers[0]=new Wc("info",void 0,Jn);var pI=(()=>{let{__tribunalDaily:n}=globalThis;if(!n)n=new i4.CronJob("00 15 * * * *",()=>{_v(Fc,"backend.worker.tribunal.bun",Jn)}),n.start(),process.on("exit",()=>{n.stop(),Jn.info("\u231B tribunal daily cronjob stopped")}),Jn.info("\u23F3 tribunal daily cronjob started");return n})();function yG(n){if(uv)return jG(uv,n);return bG({},n)}var o4=yG((n,i)=>{let o;n.on("data",(c)=>(o??=[]).push(c)).on("end",async()=>{let c=n.headers.authorization;try{if(typeof n.url==="undefined")throw[400,"No URL"];let p=n.socket.remoteAddress;if(!p)throw[400,"No IP address"];let a=new Date,x=new URL(n.url,rn.VITE_BACKEND_ORIGIN);Jn.info(a,p,n.method,x.pathname);let m=await qc.drizzle.query.banishedIps.findFirst({columns:{banishedUntil:!0},where:Eo(cl.ip,p)}),l=m?.banishedUntil===null,f=m?.banishedUntil&&m.banishedUntil>a;if(l||f){Jn.info(`\uD83D\uDE45 request from banned ip ${p}`);return}switch(n.method){case"POST":if(!o)throw[400,"No data received"];switch(x.pathname){case`/sign-up-${J$("sign-up")}`:{let v=Buffer.concat(o).toString(),$=JSON.parse(v),T=PR.safeParse($);if(!T.success){Jn.warn("signup parsed",T.error.issues);return}let{username:F,password:M,email:A}=T.data;if(Jn.info(`\uD83D\uDD11 attempting to sign up: ${F}`),await qc.drizzle.query.users.findFirst({columns:{id:!0},where:Eo(Xo.email,A)}))throw[400,"User already exists"];let G=crypto.randomUUID(),Q=eR("sha256").update(M+G).digest("hex");await qc.drizzle.insert(Xo).values({username:F,email:A,hash:Q,salt:G,createdIp:p}),Jn.info(`\uD83D\uDD11 user created: ${F}`),i.writeHead(201,{"Content-Type":"text/plain","Access-Control-Allow-Origin":`${rn.FRONTEND_ORIGINS[0]}`}),i.end(pl[201])}break;case`/login-${J$("login")}`:{let v=!1,$=null;try{let T=new Date(+a-600000);Jn.info("\uD83D\uDD11 ten minutes ago",{tenMinutesAgo:T,now:a});let F=await qc.drizzle.query.loginHistory.findMany({columns:{userId:!0,successful:!0},where:Uc(Eo(ep.ipAddress,p),Eo(ep.successful,!1),Px(ep.loginTime,T)),limit:10});Jn.info(`\uD83D\uDD11 ${F.length}/10 recent failed logins from ${p}`);let M=10-F.length;if(M<1)throw Jn.info(`\uD83D\uDD11 too many recent failed logins from ${p}`),await qc.drizzle.insert(cl).values({ip:p,reason:"Too many recent login attempts.",banishedAt:a,banishedUntil:new Date(+a+86400000)}),[429,"Too many recent login attempts."];let A=Buffer.concat(o).toString(),R=JSON.parse(A),G=qR.safeParse(R);if(!G.success)throw Jn.warn("login parsed",G.error.issues),[400,`${M} attempts remaining.`];let{username:Q,password:b}=G.data,D=await qc.drizzle.query.users.findFirst({columns:{id:!0,hash:!0,salt:!0},where:Eo(Xo.username,Q)});if(Jn.info("\uD83D\uDD11 login attempt as user",Q),!D)throw Jn.info(`\uD83D\uDD11 user ${Q} does not exist`),[400,`${M} attempts remaining.`];let{hash:Y,salt:K}=D;if($=D.id,eR("sha256").update(b+K).digest("hex")===Y){let y=crypto.randomUUID(),V=Nm.get(Q);if(!V)V=new Map,Nm.set(Q,V);V.set(y,Number(a)),v=!0,Jn.info("\uD83D\uDD11 login successful as",Q),i.writeHead(200,{"Content-Type":"text/plain","Access-Control-Allow-Origin":`${rn.FRONTEND_ORIGINS[0]}`}),i.end(`${Q} ${y}`)}}finally{await qc.drizzle.insert(ep).values({userId:$,successful:v,ipAddress:p,userAgent:n.headers["user-agent"]??"Withheld"}),Jn.info(`\uD83D\uDD11 recorded login attempt from ${p}`)}}}}}catch(p){let a=rR.safeParse(p);if(a.success){let[x,m]=a.data,f=`${pl[x]}. ${m}`;Jn.info(`\u274C ${x}: ${f}`),i.writeHead(x,{"Content-Type":"text/plain","Access-Control-Allow-Origin":`${rn.FRONTEND_ORIGINS[0]}`}),i.end(f)}else Jn.error(p),i.writeHead(500,{"Content-Type":"text/plain","Access-Control-Allow-Origin":`${rn.FRONTEND_ORIGINS[0]}`}),i.end("Internal Server Error")}})}),A$=o4.listen(rn.BACKEND_PORT).address(),BG=typeof A$==="string"?null:A$===null?null:A$.port;if(BG===null)throw new Error("Could not determine port for test server");new qM(o4,{cors:{origin:rn.FRONTEND_ORIGINS,methods:["GET","POST"]}}).use((n,i)=>{let{username:o,sessionKey:c}=n.handshake.auth;if(!(o&&c)){i(new Error("No auth header provided"));return}let p=`user::${o}`,a=`socket::${n.id}`;if(Nm.get(o)?.has(c)){let m=Sn(nn.STORE,Xx,a);Qn(nn.STORE,m,n),Rc(Gc,(l)=>{l.set(p,a)},nn.STORE),Qn(nn.STORE,jl,(l)=>l.add(p)),Qn(nn.STORE,bl,(l)=>l.add(a)),Jn.info(`${o} connected on ${n.id}`),i()}else Jn.info(`${o} couldn't authenticate`),i(new Error("Authentication error"))}).on("connection",(n)=>{let o=F0({socket:n,store:nn.STORE})(dR);n.on("disconnect",()=>{let c=`socket::${n.id}`,p=np(Gc,c,nn.STORE).userKeyOfSocket,a=Mn(nn.STORE,p);if(Rc(Gc,(x)=>{x.delete(c)},nn.STORE),a)Qn(nn.STORE,jl,(x)=>(x.delete(a),x));Qn(nn.STORE,bl,(x)=>(x.delete(c),x)),Jn.info(`${n.id} disconnected`),o()})});async function al(){Jn.info("\uD83E\uDDF9 closing workers");let n=new Promise((i)=>n4.process.once("close",i));n4.process.emit("timeToStop"),await n,Jn.info("\uD83D\uDEEC backend server exiting"),process.exit(0)}process.on("SIGINT",async()=>{Jn.info("\u2757 received SIGINT; exiting gracefully"),await al()});process.on("SIGTERM",async()=>{Jn.info("\u2757 received SIGTERM; exiting gracefully"),await al()});process.on("exit",async()=>{Jn.info("\u2757 received exit; exiting gracefully"),await al()});Fc.on("updatesReady",()=>{Jn.info('\u2757 backend server received signal "updatesReady"'),Fc.emit("readyToUpdate"),Jn.info('\u2757 backend server has sent signal "readyToUpdate"; now awaits signal "timeToStop"'),Fc.on("timeToStop",async()=>{Jn.info('\u2757 backend server received signal "timeToStop"; exiting gracefully'),await al()})});Jn.info(`\uD83D\uDEEB backend server ready on port ${rn.BACKEND_PORT}`);Fc.emit("alive");export{pI as tribunalDaily};
|
|
63
|
+
`;await i.execute(S`CREATE SCHEMA IF NOT EXISTS ${S.identifier(p)}`),await i.execute(a);let m=(await i.all(S`select id, hash, created_at from ${S.identifier(p)}.${S.identifier(c)} order by created_at desc limit 1`))[0];await i.transaction(async(l)=>{for await(let f of n)if(!m||Number(m.created_at)<f.folderMillis){for(let v of f.sql)await l.execute(S.raw(v));await l.execute(S`insert into ${S.identifier(p)}.${S.identifier(c)} ("hash", "created_at") values(${f.hash}, ${f.folderMillis})`)}})}escapeName(n){return`"${n}"`}escapeParam(n){return`\$${n+1}`}escapeString(n){return`'${n.replace(/'/g,"''")}'`}buildWithCTE(n){if(!n?.length)return;let i=[S`with `];for(let[o,c]of n.entries())if(i.push(S`${S.identifier(c._.alias)} as (${c._.sql})`),o<n.length-1)i.push(S`, `);return i.push(S` `),S.join(i)}buildDeleteQuery({table:n,where:i,returning:o,withList:c}){let p=this.buildWithCTE(c),a=o?S` returning ${this.buildSelection(o,{isSingleTable:!0})}`:void 0,x=i?S` where ${i}`:void 0;return S`${p}delete from ${n}${x}${a}`}buildUpdateSet(n,i){let o=n[L.Symbol.Columns],c=Object.keys(o).filter((a)=>i[a]!==void 0||o[a]?.onUpdateFn!==void 0),p=c.length;return S.join(c.flatMap((a,x)=>{let m=o[a],l=i[a]??S.param(m.onUpdateFn(),m),f=S`${S.identifier(this.casing.getColumnCasing(m))} = ${l}`;if(x<p-1)return[f,S.raw(", ")];return[f]}))}buildUpdateQuery({table:n,set:i,where:o,returning:c,withList:p}){let a=this.buildWithCTE(p),x=this.buildUpdateSet(n,i),m=c?S` returning ${this.buildSelection(c,{isSingleTable:!0})}`:void 0,l=o?S` where ${o}`:void 0;return S`${a}update ${n} set ${x}${l}${m}`}buildSelection(n,{isSingleTable:i=!1}={}){let o=n.length,c=n.flatMap(({field:p},a)=>{let x=[];if(z(p,k.Aliased)&&p.isSelectionField)x.push(S.identifier(p.fieldAlias));else if(z(p,k.Aliased)||z(p,k)){let m=z(p,k.Aliased)?p.sql:p;if(i)x.push(new k(m.queryChunks.map((l)=>{if(z(l,u))return S.identifier(this.casing.getColumnCasing(l));return l})));else x.push(m);if(z(p,k.Aliased))x.push(S` as ${S.identifier(p.fieldAlias)}`)}else if(z(p,bn))if(i)x.push(S.identifier(this.casing.getColumnCasing(p)));else x.push(p);if(a<o-1)x.push(S`, `);return x});return S.join(c)}buildSelectQuery({withList:n,fields:i,fieldsFlat:o,where:c,having:p,table:a,joins:x,orderBy:m,groupBy:l,limit:f,offset:v,lockingClause:$,distinct:T,setOperators:F}){let M=o??ei(i);for(let mn of M)if(z(mn.field,bn)&&di(mn.field.table)!==(z(a,fi)?a._.alias:z(a,ix)?a[hn].name:z(a,k)?void 0:di(a))&&!((ln)=>x?.some(({alias:Vn})=>Vn===(ln[L.Symbol.IsAlias]?di(ln):ln[L.Symbol.BaseName])))(mn.field.table)){let ln=di(mn.field.table);throw new Error(`Your "${mn.path.join("->")}" field references a column "${ln}"."${mn.field.name}", but the table "${ln}" is not part of the query! Did you forget to join it?`)}let A=!x||x.length===0,R=this.buildWithCTE(n),G;if(T)G=T===!0?S` distinct`:S` distinct on (${S.join(T.on,S`, `)})`;let Q=this.buildSelection(M,{isSingleTable:A}),b=(()=>{if(z(a,L)&&a[L.Symbol.OriginalName]!==a[L.Symbol.Name]){let mn=S`${S.identifier(a[L.Symbol.OriginalName])}`;if(a[L.Symbol.Schema])mn=S`${S.identifier(a[L.Symbol.Schema])}.${mn}`;return S`${mn} ${S.identifier(a[L.Symbol.Name])}`}return a})(),D=[];if(x)for(let[mn,ln]of x.entries()){if(mn===0)D.push(S` `);let Vn=ln.table,ji=ln.lateral?S` lateral`:void 0;if(z(Vn,no)){let H=Vn[no.Symbol.Name],s=Vn[no.Symbol.Schema],Jn=Vn[no.Symbol.OriginalName],Yn=H===Jn?void 0:ln.alias;D.push(S`${S.raw(ln.joinType)} join${ji} ${s?S`${S.identifier(s)}.`:void 0}${S.identifier(Jn)}${Yn&&S` ${S.identifier(Yn)}`} on ${ln.on}`)}else if(z(Vn,Vi)){let H=Vn[hn].name,s=Vn[hn].schema,Jn=Vn[hn].originalName,Yn=H===Jn?void 0:ln.alias;D.push(S`${S.raw(ln.joinType)} join${ji} ${s?S`${S.identifier(s)}.`:void 0}${S.identifier(Jn)}${Yn&&S` ${S.identifier(Yn)}`} on ${ln.on}`)}else D.push(S`${S.raw(ln.joinType)} join${ji} ${Vn} on ${ln.on}`);if(mn<x.length-1)D.push(S` `)}let Y=S.join(D),K=c?S` where ${c}`:void 0,E=p?S` having ${p}`:void 0,y;if(m&&m.length>0)y=S` order by ${S.join(m,S`, `)}`;let V;if(l&&l.length>0)V=S` group by ${S.join(l,S`, `)}`;let X=typeof f==="object"||typeof f==="number"&&f>=0?S` limit ${f}`:void 0,Z=v?S` offset ${v}`:void 0,C=S.empty();if($){let mn=S` for ${S.raw($.strength)}`;if($.config.of)mn.append(S` of ${S.join(Array.isArray($.config.of)?$.config.of:[$.config.of],S`, `)}`);if($.config.noWait)mn.append(S` no wait`);else if($.config.skipLocked)mn.append(S` skip locked`);C.append(mn)}let on=S`${R}select${G} ${Q} from ${b}${Y}${K}${V}${E}${y}${X}${Z}${C}`;if(F.length>0)return this.buildSetOperations(on,F);return on}buildSetOperations(n,i){let[o,...c]=i;if(!o)throw new Error("Cannot pass undefined values to any set operator");if(c.length===0)return this.buildSetOperationQuery({leftSelect:n,setOperator:o});return this.buildSetOperations(this.buildSetOperationQuery({leftSelect:n,setOperator:o}),c)}buildSetOperationQuery({leftSelect:n,setOperator:{type:i,isAll:o,rightSelect:c,limit:p,orderBy:a,offset:x}}){let m=S`(${n.getSQL()}) `,l=S`(${c.getSQL()})`,f;if(a&&a.length>0){let F=[];for(let M of a)if(z(M,u))F.push(S.identifier(M.name));else if(z(M,k)){for(let A=0;A<M.queryChunks.length;A++){let R=M.queryChunks[A];if(z(R,u))M.queryChunks[A]=S.identifier(R.name)}F.push(S`${M}`)}else F.push(S`${M}`);f=S` order by ${S.join(F,S`, `)} `}let v=typeof p==="object"||typeof p==="number"&&p>=0?S` limit ${p}`:void 0,$=S.raw(`${i} ${o?"all ":""}`),T=x?S` offset ${x}`:void 0;return S`${m}${$}${l}${f}${v}${T}`}buildInsertQuery({table:n,values:i,onConflict:o,returning:c,withList:p}){let a=[],x=n[L.Symbol.Columns],m=Object.entries(x).filter(([F,M])=>!M.shouldDisableInsert()),l=m.map(([,F])=>S.identifier(this.casing.getColumnCasing(F)));for(let[F,M]of i.entries()){let A=[];for(let[R,G]of m){let Q=M[R];if(Q===void 0||z(Q,Li)&&Q.value===void 0)if(G.defaultFn!==void 0){let b=G.defaultFn(),D=z(b,k)?b:S.param(b,G);A.push(D)}else if(!G.default&&G.onUpdateFn!==void 0){let b=G.onUpdateFn(),D=z(b,k)?b:S.param(b,G);A.push(D)}else A.push(S`default`);else A.push(Q)}if(a.push(A),F<i.length-1)a.push(S`, `)}let f=this.buildWithCTE(p),v=S.join(a),$=c?S` returning ${this.buildSelection(c,{isSingleTable:!0})}`:void 0,T=o?S` on conflict ${o}`:void 0;return S`${f}insert into ${n} ${l} values ${v}${T}${$}`}buildRefreshMaterializedViewQuery({view:n,concurrently:i,withNoData:o}){let c=i?S` concurrently`:void 0,p=o?S` with no data`:void 0;return S`refresh materialized view${c} ${n}${p}`}prepareTyping(n){if(z(n,im)||z(n,nm))return"json";else if(z(n,om))return"decimal";else if(z(n,cm))return"time";else if(z(n,pm)||z(n,am))return"timestamp";else if(z(n,gx)||z(n,dx))return"date";else if(z(n,xm))return"uuid";else return"none"}sqlToQuery(n,i){return n.toQuery({casing:this.casing,escapeName:this.escapeName,escapeParam:this.escapeParam,escapeString:this.escapeString,prepareTyping:this.prepareTyping,invokeSource:i})}buildRelationalQueryWithoutPK({fullSchema:n,schema:i,tableNamesMap:o,table:c,tableConfig:p,queryConfig:a,tableAlias:x,nestedQueryRelation:m,joinOn:l}){let f=[],v,$,T=[],F,M=[];if(a===!0)f=Object.entries(p.columns).map(([G,Q])=>({dbKey:Q.name,tsKey:G,field:Ho(Q,x),relationTableTsKey:void 0,isJson:!1,selection:[]}));else{let R=Object.fromEntries(Object.entries(p.columns).map(([K,E])=>[K,Ho(E,x)]));if(a.where){let K=typeof a.where==="function"?a.where(R,pS()):a.where;F=K&&Ea(K,x)}let G=[],Q=[];if(a.columns){let K=!1;for(let[E,y]of Object.entries(a.columns)){if(y===void 0)continue;if(E in p.columns){if(!K&&y===!0)K=!0;Q.push(E)}}if(Q.length>0)Q=K?Q.filter((E)=>a.columns?.[E]===!0):Object.keys(p.columns).filter((E)=>!Q.includes(E))}else Q=Object.keys(p.columns);for(let K of Q){let E=p.columns[K];G.push({tsKey:K,value:E})}let b=[];if(a.with)b=Object.entries(a.with).filter((K)=>!!K[1]).map(([K,E])=>({tsKey:K,queryConfig:E,relation:p.relations[K]}));let D;if(a.extras){D=typeof a.extras==="function"?a.extras(R,{sql:S}):a.extras;for(let[K,E]of Object.entries(D))G.push({tsKey:K,value:Gf(E,x)})}for(let{tsKey:K,value:E}of G)f.push({dbKey:z(E,k.Aliased)?E.fieldAlias:p.columns[K].name,tsKey:K,field:z(E,bn)?Ho(E,x):E,relationTableTsKey:void 0,isJson:!1,selection:[]});let Y=typeof a.orderBy==="function"?a.orderBy(R,aS()):a.orderBy??[];if(!Array.isArray(Y))Y=[Y];T=Y.map((K)=>{if(z(K,bn))return Ho(K,x);return Ea(K,x)}),v=a.limit,$=a.offset;for(let{tsKey:K,queryConfig:E,relation:y}of b){let V=mS(i,o,y),X=Oc(y.referencedTable),Z=o[X],C=`${x}_${K}`,on=Uc(...V.fields.map((Vn,ji)=>Eo(Ho(V.references[ji],C),Ho(Vn,x)))),mn=this.buildRelationalQueryWithoutPK({fullSchema:n,schema:i,tableNamesMap:o,table:n[Z],tableConfig:i[Z],queryConfig:z(y,mc)?E===!0?{limit:1}:{...E,limit:1}:E,tableAlias:C,joinOn:on,nestedQueryRelation:y}),ln=S`${S.identifier(C)}.${S.identifier("data")}`.as(K);M.push({on:S`true`,table:new fi(mn.sql,{},C),alias:C,joinType:"left",lateral:!0}),f.push({dbKey:K,tsKey:K,field:ln,relationTableTsKey:Z,isJson:!0,selection:mn.selection})}}if(f.length===0)throw new qx({message:`No fields selected for table "${p.tsName}" ("${x}")`});let A;if(F=Uc(l,F),m){let R=S`json_build_array(${S.join(f.map(({field:b,tsKey:D,isJson:Y})=>Y?S`${S.identifier(`${x}_${D}`)}.${S.identifier("data")}`:z(b,k.Aliased)?b.sql:b),S`, `)})`;if(z(m,Va))R=S`coalesce(json_agg(${R}${T.length>0?S` order by ${S.join(T,S`, `)}`:void 0}), '[]'::json)`;let G=[{dbKey:"data",tsKey:"data",field:R.as("data"),isJson:!0,relationTableTsKey:p.tsName,selection:f}];if(v!==void 0||$!==void 0||T.length>0)A=this.buildSelectQuery({table:tx(c,x),fields:{},fieldsFlat:[{path:[],field:S.raw("*")}],where:F,limit:v,offset:$,orderBy:T,setOperators:[]}),F=void 0,v=void 0,$=void 0,T=[];else A=tx(c,x);A=this.buildSelectQuery({table:z(A,no)?A:new fi(A,{},x),fields:{},fieldsFlat:G.map(({field:b})=>({path:[],field:z(b,bn)?Ho(b,x):b})),joins:M,where:F,limit:v,offset:$,orderBy:T,setOperators:[]})}else A=this.buildSelectQuery({table:tx(c,x),fields:{},fieldsFlat:f.map(({field:R})=>({path:[],field:z(R,bn)?Ho(R,x):R})),joins:M,where:F,limit:v,offset:$,orderBy:T,setOperators:[]});return{tableTsKey:p.tsName,sql:A,selection:f}}}class bi{static[J]="SelectionProxyHandler";config;constructor(n){this.config={...n}}get(n,i){if(i==="_")return{...n._,selectedFields:new Proxy(n._.selectedFields,this)};if(i===hn)return{...n[hn],selectedFields:new Proxy(n[hn].selectedFields,this)};if(typeof i==="symbol")return n[i];let c=(z(n,fi)?n._.selectedFields:z(n,Vi)?n[hn].selectedFields:n)[i];if(z(c,k.Aliased)){if(this.config.sqlAliasedBehavior==="sql"&&!c.isSelectionField)return c.sql;let p=c.clone();return p.isSelectionField=!0,p}if(z(c,k)){if(this.config.sqlBehavior==="sql")return c;throw new Error(`You tried to reference "${i}" field from a subquery, which is a raw SQL field, but it doesn't have an alias declared. Please add an alias to the field using ".as('alias')" method.`)}if(z(c,bn)){if(this.config.alias)return new Proxy(c,new Ap(new Proxy(c.table,new Ha(this.config.alias,this.config.replaceOriginalName??!1))));return c}if(typeof c!=="object"||c===null)return c;return new Proxy(c,new bi(this.config))}}class ev{static[J]="TypedQueryBuilder";getSelectedFields(){return this._.selectedFields}}class Oi{static[J]="PgSelectBuilder";fields;session;dialect;withList=[];distinct;constructor(n){if(this.fields=n.fields,this.session=n.session,this.dialect=n.dialect,n.withList)this.withList=n.withList;this.distinct=n.distinct}from(n){let i=!!this.fields,o;if(this.fields)o=this.fields;else if(z(n,fi))o=Object.fromEntries(Object.keys(n._.selectedFields).map((c)=>[c,n[c]]));else if(z(n,ix))o=n[hn].selectedFields;else if(z(n,k))o={};else o=lw(n);return new n$({table:n,fields:o,isPartialSelect:i,session:this.session,dialect:this.dialect,withList:this.withList,distinct:this.distinct})}}class uR extends ev{static[J]="PgSelectQueryBuilder";_;config;joinsNotNullableMap;tableName;isPartialSelect;session;dialect;constructor({table:n,fields:i,isPartialSelect:o,session:c,dialect:p,withList:a,distinct:x}){super();this.config={withList:a,table:n,fields:{...i},distinct:x,setOperators:[]},this.isPartialSelect=o,this.session=c,this.dialect=p,this._={selectedFields:i},this.tableName=Ef(n),this.joinsNotNullableMap=typeof this.tableName==="string"?{[this.tableName]:!0}:{}}createJoin(n){return(i,o)=>{let c=this.tableName,p=Ef(i);if(typeof p==="string"&&this.config.joins?.some((a)=>a.alias===p))throw new Error(`Alias "${p}" is already used in this query`);if(!this.isPartialSelect){if(Object.keys(this.joinsNotNullableMap).length===1&&typeof c==="string")this.config.fields={[c]:this.config.fields};if(typeof p==="string"&&!z(i,k)){let a=z(i,fi)?i._.selectedFields:z(i,Vi)?i[hn].selectedFields:i[L.Symbol.Columns];this.config.fields[p]=a}}if(typeof o==="function")o=o(new Proxy(this.config.fields,new bi({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));if(!this.config.joins)this.config.joins=[];if(this.config.joins.push({on:o,table:i,joinType:n,alias:p}),typeof p==="string")switch(n){case"left":{this.joinsNotNullableMap[p]=!1;break}case"right":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([a])=>[a,!1])),this.joinsNotNullableMap[p]=!0;break}case"inner":{this.joinsNotNullableMap[p]=!0;break}case"full":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([a])=>[a,!1])),this.joinsNotNullableMap[p]=!1;break}}return this}}leftJoin=this.createJoin("left");rightJoin=this.createJoin("right");innerJoin=this.createJoin("inner");fullJoin=this.createJoin("full");createSetOperator(n,i){return(o)=>{let c=typeof o==="function"?o(TG()):o;if(!Hf(this.getSelectedFields(),c.getSelectedFields()))throw new Error("Set operator error (union / intersect / except): selected fields are not the same or are in a different order");return this.config.setOperators.push({type:n,isAll:i,rightSelect:c}),this}}union=this.createSetOperator("union",!1);unionAll=this.createSetOperator("union",!0);intersect=this.createSetOperator("intersect",!1);intersectAll=this.createSetOperator("intersect",!0);except=this.createSetOperator("except",!1);exceptAll=this.createSetOperator("except",!0);addSetOperators(n){return this.config.setOperators.push(...n),this}where(n){if(typeof n==="function")n=n(new Proxy(this.config.fields,new bi({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));return this.config.where=n,this}having(n){if(typeof n==="function")n=n(new Proxy(this.config.fields,new bi({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));return this.config.having=n,this}groupBy(...n){if(typeof n[0]==="function"){let i=n[0](new Proxy(this.config.fields,new bi({sqlAliasedBehavior:"alias",sqlBehavior:"sql"})));this.config.groupBy=Array.isArray(i)?i:[i]}else this.config.groupBy=n;return this}orderBy(...n){if(typeof n[0]==="function"){let i=n[0](new Proxy(this.config.fields,new bi({sqlAliasedBehavior:"alias",sqlBehavior:"sql"}))),o=Array.isArray(i)?i:[i];if(this.config.setOperators.length>0)this.config.setOperators.at(-1).orderBy=o;else this.config.orderBy=o}else{let i=n;if(this.config.setOperators.length>0)this.config.setOperators.at(-1).orderBy=i;else this.config.orderBy=i}return this}limit(n){if(this.config.setOperators.length>0)this.config.setOperators.at(-1).limit=n;else this.config.limit=n;return this}offset(n){if(this.config.setOperators.length>0)this.config.setOperators.at(-1).offset=n;else this.config.offset=n;return this}for(n,i={}){return this.config.lockingClause={strength:n,config:i},this}getSQL(){return this.dialect.buildSelectQuery(this.config)}toSQL(){let{typings:n,...i}=this.dialect.sqlToQuery(this.getSQL());return i}as(n){return new Proxy(new fi(this.getSQL(),this.config.fields,n),new bi({alias:n,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}getSelectedFields(){return new Proxy(this.config.fields,new bi({alias:this.tableName,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}$dynamic(){return this}}class n$ extends uR{static[J]="PgSelect";_prepare(n){let{session:i,config:o,dialect:c,joinsNotNullableMap:p}=this;if(!i)throw new Error("Cannot execute a query on a query builder. Please use a database instance instead.");return Un.startActiveSpan("drizzle.prepareQuery",()=>{let a=ei(o.fields),x=i.prepareQuery(c.sqlToQuery(this.getSQL()),a,n,!0);return x.joinsNotNullableMap=p,x})}prepare(n){return this._prepare(n)}execute=(n)=>{return Un.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(n)})}}mw(n$,[Qi]);function gp(n,i){return(o,c,...p)=>{let a=[c,...p].map((x)=>({type:n,isAll:i,rightSelect:x}));for(let x of a)if(!Hf(o.getSelectedFields(),x.rightSelect.getSelectedFields()))throw new Error("Set operator error (union / intersect / except): selected fields are not the same or are in a different order");return o.addSetOperators(a)}}var TG=()=>({union:wG,unionAll:JG,intersect:SG,intersectAll:AG,except:FG,exceptAll:MG}),wG=gp("union",!1),JG=gp("union",!0),SG=gp("intersect",!1),AG=gp("intersect",!0),FG=gp("except",!1),MG=gp("except",!0);class i${static[J]="PgQueryBuilder";dialect;dialectConfig;constructor(n){this.dialect=z(n,tc)?n:void 0,this.dialectConfig=z(n,tc)?void 0:n}$with(n){let i=this;return{as(o){if(typeof o==="function")o=o(i);return new Proxy(new Qa(o.getSQL(),o.getSelectedFields(),n,!0),new bi({alias:n,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}}with(...n){let i=this;function o(a){return new Oi({fields:a??void 0,session:void 0,dialect:i.getDialect(),withList:n})}function c(a){return new Oi({fields:a??void 0,session:void 0,dialect:i.getDialect(),distinct:!0})}function p(a,x){return new Oi({fields:x??void 0,session:void 0,dialect:i.getDialect(),distinct:{on:a}})}return{select:o,selectDistinct:c,selectDistinctOn:p}}select(n){return new Oi({fields:n??void 0,session:void 0,dialect:this.getDialect()})}selectDistinct(n){return new Oi({fields:n??void 0,session:void 0,dialect:this.getDialect(),distinct:!0})}selectDistinctOn(n,i){return new Oi({fields:i??void 0,session:void 0,dialect:this.getDialect(),distinct:{on:n}})}getDialect(){if(!this.dialect)this.dialect=new tc(this.dialectConfig);return this.dialect}}class o$ extends Qi{constructor(n,i,o){super();this.session=i,this.dialect=o,this.config={view:n}}static[J]="PgRefreshMaterializedView";config;concurrently(){if(this.config.withNoData!==void 0)throw new Error("Cannot use concurrently and withNoData together");return this.config.concurrently=!0,this}withNoData(){if(this.config.concurrently!==void 0)throw new Error("Cannot use concurrently and withNoData together");return this.config.withNoData=!0,this}getSQL(){return this.dialect.buildRefreshMaterializedViewQuery(this.config)}toSQL(){let{typings:n,...i}=this.dialect.sqlToQuery(this.getSQL());return i}_prepare(n){return Un.startActiveSpan("drizzle.prepareQuery",()=>{return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),void 0,n,!0)})}prepare(n){return this._prepare(n)}execute=(n)=>{return Un.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(n)})}}class em{constructor(n,i,o,c){this.table=n,this.session=i,this.dialect=o,this.withList=c}static[J]="PgUpdateBuilder";set(n){return new _R(this.table,rx(this.table,n),this.session,this.dialect,this.withList)}}class _R extends Qi{constructor(n,i,o,c,p){super();this.session=o,this.dialect=c,this.config={set:i,table:n,withList:p}}static[J]="PgUpdate";config;where(n){return this.config.where=n,this}returning(n=this.config.table[L.Symbol.Columns]){return this.config.returning=ei(n),this}getSQL(){return this.dialect.buildUpdateQuery(this.config)}toSQL(){let{typings:n,...i}=this.dialect.sqlToQuery(this.getSQL());return i}_prepare(n){return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,n,!0)}prepare(n){return this._prepare(n)}execute=(n)=>{return this._prepare().execute(n)};$dynamic(){return this}}class ox extends k{constructor(n){super(ox.buildEmbeddedCount(n.source,n.filters).queryChunks);this.params=n,this.mapWith(Number),this.session=n.session,this.sql=ox.buildCount(n.source,n.filters)}sql;static[J]="PgCountBuilder";[Symbol.toStringTag]="PgCountBuilder";session;static buildEmbeddedCount(n,i){return S`(select count(*) from ${n}${S.raw(" where ").if(i)}${i})`}static buildCount(n,i){return S`select count(*) as count from ${n}${S.raw(" where ").if(i)}${i};`}then(n,i){return Promise.resolve(this.session.count(this.sql)).then(n,i)}catch(n){return this.then(void 0,n)}finally(n){return this.then((i)=>{return n?.(),i},(i)=>{throw n?.(),i})}}class p${constructor(n,i,o,c,p,a,x){this.fullSchema=n,this.schema=i,this.tableNamesMap=o,this.table=c,this.tableConfig=p,this.dialect=a,this.session=x}static[J]="PgRelationalQueryBuilder";findMany(n){return new c$(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,n?n:{},"many")}findFirst(n){return new c$(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,n?{...n,limit:1}:{limit:1},"first")}}class c$ extends Qi{constructor(n,i,o,c,p,a,x,m,l){super();this.fullSchema=n,this.schema=i,this.tableNamesMap=o,this.table=c,this.tableConfig=p,this.dialect=a,this.session=x,this.config=m,this.mode=l}static[J]="PgRelationalQuery";_prepare(n){return Un.startActiveSpan("drizzle.prepareQuery",()=>{let{query:i,builtQuery:o}=this._toSQL();return this.session.prepareQuery(o,void 0,n,!0,(c,p)=>{let a=c.map((x)=>mm(this.schema,this.tableConfig,x,i.selection,p));if(this.mode==="first")return a[0];return a})})}prepare(n){return this._prepare(n)}_getQuery(){return this.dialect.buildRelationalQueryWithoutPK({fullSchema:this.fullSchema,schema:this.schema,tableNamesMap:this.tableNamesMap,table:this.table,tableConfig:this.tableConfig,queryConfig:this.config,tableAlias:this.tableConfig.tsName})}getSQL(){return this._getQuery().sql}_toSQL(){let n=this._getQuery(),i=this.dialect.sqlToQuery(n.sql);return{query:n,builtQuery:i}}toSQL(){return this._toSQL().builtQuery}execute(){return Un.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute()})}}class a$ extends Qi{constructor(n,i,o,c){super();this.execute=n,this.sql=i,this.query=o,this.mapBatchResult=c}static[J]="PgRaw";getSQL(){return this.sql}getQuery(){return this.query}mapResult(n,i){return i?this.mapBatchResult(n):n}_prepare(){return this}isResponseInArrayMode(){return!1}}class cx{constructor(n,i,o){if(this.dialect=n,this.session=i,this._=o?{schema:o.schema,fullSchema:o.fullSchema,tableNamesMap:o.tableNamesMap,session:i}:{schema:void 0,fullSchema:{},tableNamesMap:{},session:i},this.query={},this._.schema)for(let[c,p]of Object.entries(this._.schema))this.query[c]=new p$(o.fullSchema,this._.schema,this._.tableNamesMap,o.fullSchema[c],p,n,i)}static[J]="PgDatabase";query;$with(n){let i=this;return{as(o){if(typeof o==="function")o=o(new i$(i.dialect));return new Proxy(new Qa(o.getSQL(),o.getSelectedFields(),n,!0),new bi({alias:n,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}}$count(n,i){return new ox({source:n,filters:i,session:this.session})}with(...n){let i=this;function o(l){return new Oi({fields:l??void 0,session:i.session,dialect:i.dialect,withList:n})}function c(l){return new Oi({fields:l??void 0,session:i.session,dialect:i.dialect,withList:n,distinct:!0})}function p(l,f){return new Oi({fields:f??void 0,session:i.session,dialect:i.dialect,withList:n,distinct:{on:l}})}function a(l){return new em(l,i.session,i.dialect,n)}function x(l){return new dm(l,i.session,i.dialect,n)}function m(l){return new gm(l,i.session,i.dialect,n)}return{select:o,selectDistinct:c,selectDistinctOn:p,update:a,insert:x,delete:m}}select(n){return new Oi({fields:n??void 0,session:this.session,dialect:this.dialect})}selectDistinct(n){return new Oi({fields:n??void 0,session:this.session,dialect:this.dialect,distinct:!0})}selectDistinctOn(n,i){return new Oi({fields:i??void 0,session:this.session,dialect:this.dialect,distinct:{on:n}})}update(n){return new em(n,this.session,this.dialect)}insert(n){return new dm(n,this.session,this.dialect)}delete(n){return new gm(n,this.session,this.dialect)}refreshMaterializedView(n){return new o$(n,this.session,this.dialect)}execute(n){let i=typeof n==="string"?S.raw(n):n.getSQL(),o=this.dialect.sqlToQuery(i),c=this.session.prepareQuery(o,void 0,void 0,!1);return new a$(()=>c.execute(),i,o,(p)=>c.mapResult(p,!0))}transaction(n,i){return this.session.transaction(n,i)}}class bR{constructor(n,i){this.unique=n,this.name=i}static[J]="PgIndexBuilderOn";on(...n){return new nl(n.map((i)=>{if(z(i,k))return i;i=i;let o=new za(i.name,!!i.keyAsName,i.columnType,i.indexConfig);return i.indexConfig=JSON.parse(JSON.stringify(i.defaultConfig)),o}),this.unique,!1,this.name)}onOnly(...n){return new nl(n.map((i)=>{if(z(i,k))return i;i=i;let o=new za(i.name,!!i.keyAsName,i.columnType,i.indexConfig);return i.indexConfig=i.defaultConfig,o}),this.unique,!0,this.name)}using(n,...i){return new nl(i.map((o)=>{if(z(o,k))return o;o=o;let c=new za(o.name,!!o.keyAsName,o.columnType,o.indexConfig);return o.indexConfig=JSON.parse(JSON.stringify(o.defaultConfig)),c}),this.unique,!0,this.name,n)}}class nl{static[J]="PgIndexBuilder";config;constructor(n,i,o,c,p="btree"){this.config={name:c,columns:n,unique:i,only:o,method:p}}concurrently(){return this.config.concurrently=!0,this}with(n){return this.config.with=n,this}where(n){return this.config.where=n,this}build(n){return new jR(this.config,n)}}class jR{static[J]="PgIndex";config;constructor(n,i){this.config={...n,table:i}}}function x$(n){return new bR(!0,n)}class m${constructor(n){this.query=n}getQuery(){return this.query}mapResult(n,i){return n}static[J]="PgPreparedQuery";joinsNotNullableMap}class l${constructor(n){this.dialect=n}static[J]="PgSession";execute(n){return Un.startActiveSpan("drizzle.operation",()=>{return Un.startActiveSpan("drizzle.prepareQuery",()=>{return this.prepareQuery(this.dialect.sqlToQuery(n),void 0,void 0,!1)}).execute()})}all(n){return this.prepareQuery(this.dialect.sqlToQuery(n),void 0,void 0,!1).all()}async count(n){let i=await this.execute(n);return Number(i[0].count)}}class f$ extends cx{constructor(n,i,o,c=0){super(n,i,o);this.schema=o,this.nestedIndex=c}static[J]="PgTransaction";rollback(){throw new Yf}getTransactionConfigSQL(n){let i=[];if(n.isolationLevel)i.push(`isolation level ${n.isolationLevel}`);if(n.accessMode)i.push(n.accessMode);if(typeof n.deferrable==="boolean")i.push(n.deferrable?"deferrable":"not deferrable");return S.raw(i.join(" "))}setTransaction(n){return this.session.execute(S`set transaction ${this.getTransactionConfigSQL(n)}`)}}class yR extends m${constructor(n,i,o,c,p,a,x){super({sql:i,params:o});this.client=n,this.queryString=i,this.params=o,this.logger=c,this.fields=p,this._isResponseInArrayMode=a,this.customResultMapper=x}static[J]="PostgresJsPreparedQuery";async execute(n={}){return Un.startActiveSpan("drizzle.execute",async(i)=>{let o=Xf(this.params,n);i?.setAttributes({"drizzle.query.text":this.queryString,"drizzle.query.params":JSON.stringify(o)}),this.logger.logQuery(this.queryString,o);let{fields:c,queryString:p,client:a,joinsNotNullableMap:x,customResultMapper:m}=this;if(!c&&!m)return Un.startActiveSpan("drizzle.driver.execute",()=>{return a.unsafe(p,o)});let l=await Un.startActiveSpan("drizzle.driver.execute",()=>{return i?.setAttributes({"drizzle.query.text":p,"drizzle.query.params":JSON.stringify(o)}),a.unsafe(p,o).values()});return Un.startActiveSpan("drizzle.mapResponse",()=>{return m?m(l):l.map((f)=>xw(c,f,x))})})}all(n={}){return Un.startActiveSpan("drizzle.execute",async(i)=>{let o=Xf(this.params,n);return i?.setAttributes({"drizzle.query.text":this.queryString,"drizzle.query.params":JSON.stringify(o)}),this.logger.logQuery(this.queryString,o),Un.startActiveSpan("drizzle.driver.execute",()=>{return i?.setAttributes({"drizzle.query.text":this.queryString,"drizzle.query.params":JSON.stringify(o)}),this.client.unsafe(this.queryString,o)})})}isResponseInArrayMode(){return this._isResponseInArrayMode}}class px extends l${constructor(n,i,o,c={}){super(i);this.client=n,this.schema=o,this.options=c,this.logger=c.logger??new Qf}static[J]="PostgresJsSession";logger;prepareQuery(n,i,o,c,p){return new yR(this.client,n.sql,n.params,this.logger,i,c,p)}query(n,i){return this.logger.logQuery(n,i),this.client.unsafe(n,i).values()}queryObjects(n,i){return this.client.unsafe(n,i)}transaction(n,i){return this.client.begin(async(o)=>{let c=new px(o,this.dialect,this.schema,this.options),p=new v$(this.dialect,c,this.schema);if(i)await p.setTransaction(i);return n(p)})}}class v$ extends f${constructor(n,i,o,c=0){super(n,i,o,c);this.session=i}static[J]="PostgresJsTransaction";transaction(n){return this.session.client.savepoint((i)=>{let o=new px(i,this.dialect,this.schema,this.session.options),c=new v$(this.dialect,o,this.schema);return n(c)})}}class BR extends cx{static[J]="PostgresJsDatabase"}function dp(n,i={}){let o=(l)=>l;for(let l of["1184","1082","1083","1114"])n.options.parsers[l]=o,n.options.serializers[l]=o;n.options.serializers["114"]=o,n.options.serializers["3802"]=o;let c=new tc({casing:i.casing}),p;if(i.logger===!0)p=new zf;else if(i.logger!==!1)p=i.logger;let a;if(i.schema){let l=xS(i.schema,lS);a={fullSchema:i.schema,schema:l.tables,tableNamesMap:l.tableNamesMap}}let x=new px(n,c,a,{logger:p}),m=new BR(c,x,a);return m.$client=n,m}function il(...n){if(typeof n[0]==="string"){let i=rp(n[0]);return dp(i,n[1])}if(fw(n[0])){let{connection:i,client:o,...c}=n[0];if(o)return dp(o,c);if(typeof i==="object"&&i.url!==void 0){let{url:a,...x}=i,m=rp(a,x);return dp(m,c)}let p=rp(i);return dp(p,c)}return dp(n[0],n[1])}((n)=>{function i(o){return dp({},o)}n.mock=i})(il||(il={}));var T$={};e4(T$,{users:()=>Xo,userChanges:()=>WG,untrackedUserColumnNames:()=>RG,twoFactorMethod:()=>hR,trackedUserColumnName:()=>CR,trackableUserColumnNames:()=>DR,role:()=>NR,players:()=>$$,passwordResetAttempts:()=>KG,loginHistory:()=>ep,games:()=>ol,banishedIps:()=>cl});function LR(n){return S`lower(${n})`}var NR=kx("role",["admin","user"]),Xo=xc("users",{id:Ni().primaryKey().defaultRandom(),username:vi({length:16}).notNull(),email:vi({length:254}).notNull(),hash:vi({length:64}).notNull(),salt:vi({length:36}).notNull(),createdAt:wo({withTimezone:!0}).notNull().defaultNow(),createdIp:vi({length:45}).notNull(),isActive:Oa().notNull().default(!1),verifiedAt:wo({withTimezone:!0}),userRole:NR().default("user")},(n)=>[x$("usernameUniqueIndex").on(LR(n.username)),x$("emailUniqueIndex").on(LR(n.email))]),RG=["id","createdAt","createdIp","isActive","salt","verifiedAt"],DR=["username","email","hash","userRole"],CR=kx("trackedUserColumnName",DR),WG=xc("userChanges",{id:Ni().primaryKey().defaultRandom(),userId:Ni().notNull().references(()=>Xo.id),changedAt:wo({withTimezone:!0}).notNull().defaultNow(),changedIp:vi({length:45}).notNull(),changedColumn:CR().notNull(),oldValue:vi({length:255}),newValue:vi({length:255})}),ol=xc("games",{id:Ni().primaryKey().defaultRandom()}),$$=xc("players",{userId:Ni().notNull().references(()=>Xo.id),gameId:Ni().notNull().references(()=>ol.id),score:ex().notNull()},(n)=>[iS({name:"players_userId_gameId_pk",columns:[n.userId,n.gameId]})]),ep=xc("loginHistory",{id:Ni().primaryKey().defaultRandom(),userId:Ni().references(()=>Xo.id),loginTime:wo({withTimezone:!0}).notNull().defaultNow(),ipAddress:vi({length:45}).notNull(),userAgent:vi({length:1024}),successful:Oa().notNull().default(!1)}),hR=kx("twoFactorMethod",["email","phone"]),KG=xc("passwordResetAttempts",{id:Ni().primaryKey().defaultRandom(),userId:Ni().notNull().references(()=>Xo.id),requestedIp:vi({length:45}).notNull(),requestedAt:wo({withTimezone:!0}).notNull().defaultNow(),succeededIp:vi({length:45}),succeededAt:wo({withTimezone:!0}),verificationMethod:hR().notNull()}),cl=xc("banishedIps",{ip:vi({length:45}).primaryKey(),reason:vi({length:2048}).notNull(),banishedAt:wo({withTimezone:!0}).notNull().defaultNow(),banishedUntil:wo({withTimezone:!0})});var __dirname="/home/runner/work/wayforge/wayforge/apps/tempest.games/src/database";class w${options;sql;drizzle;observers=new Map;async setupTriggersAndNotifications(){await this.sql.file(XG.resolve(__dirname,"notify_update.sql"));let n=[di(Xo),di(ol),di($$)];await this.sql`SELECT create_notify_triggers(${this.sql.array(n)})`,await this.sql.listen("table_update",(i)=>{let o=i.split(","),c=o[0],p=o[1],a=`${c}("${p}")`;if(this.observers.has(a))this.observers.get(a).next(a)})}constructor(n=!1,i={host:rn.POSTGRES_HOST,port:rn.POSTGRES_PORT,user:rn.POSTGRES_USER,password:rn.POSTGRES_PASSWORD,database:rn.POSTGRES_DATABASE}){this.options=i,this.sql=rp(i),this.drizzle=il(this.sql,{schema:T$,logger:n})}observe(n,i){if(!this.observers.has(n))this.observers.set(n,new xn);this.observers.get(n).subscribe("SINGLETON",i)}}import{createHash as GG}from"crypto";function J$(n){let i=GG("sha256").update(n).digest("hex");return`${i.substring(0,8)}-${i.substring(8,12)}-${i.substring(12,16)}-${i.substring(16,20)}-${i.substring(20,32)}`}var IR=["123","321","abc","admin","adobe","alexander","amanda","andrea","andrew","angel","apple","asdf","ashley","baby","banana","baseball","batman","bear","biteme","blazer","blonde","boston","buster","butterfly","cameron","charlie","cheese","chelsea","chicken","chocolate","chris","compaq","computer","cookie","corvette","cowboys","dakota","dallas","daniel","david","diamond","dolphin","donald","dragon","eagle","flower","football","frank","freedom","friend","gateway","george","ginger","god","golf","hannah","hardcore","harley","heather","hello","hottie","hunter","internet","jasmine","jennifer","jessica","jesus","johnny","jordan","joshua","justin","justme","killer","knight","lakers","letmein","liverpool","login","london","love","lucky","mackenzie","maggie","master","matrix","matthew","maverick","melissa","mercedes","michael","michelle","mickey","miller","money","monkey","morgan","mother","muffin","mustang","natasha","nathan","nicole","ninja","orange","pass","password","patrick","peanut","pepper","phoenix","photoshop","pokemon","princess","purple","qazwsx","qwerty","rainbow","ranger","root","samantha","samsung","scooter","secret","shadow","simpson","smile","soccer","sparkle","starwars","summer","sunflower","sunshine","superman","taylor","temp","test","thomas","tigers","tigger","tinkerbell","trust","turtle","victoria","welcome","whatever","william","winter","yellow","zaq12wsx","zxcvbn"];var YG=3,zG=15,QG=/^[a-zA-Z0-9_-]+$/,ZR=Gn.string().min(YG).max(zG).regex(QG),kR=20,sR={"0":"o","1":"l","3":"e","4":"a","5":"s","7":"t","@":"a",$:"s","!":"i"};function HG(n){let i="";for(let o of n)if(o in sR)i+=sR[o];else i+=o;return i}function EG(n){let i=n.toLocaleLowerCase(),o=HG(i);for(let c of IR){if(o.includes(c))return!0;if(i.includes(c))return!0}return!1}function OG(n){let i=new Set(n).size;return n.length*Math.log2(i)}function UG(n){let i=0,o=100;if(EG(n))i-=o;return i+=OG(n)*0.5,Math.max(i,0)}var tR=Gn.string().refine((n)=>{return UG(n)>=kR},{message:`Password does not meet the minimum complexity of ${kR}.`}).brand("password"),qR=Gn.object({username:ZR,password:tR}).strict(),VG=Gn.string().email().brand("email"),PR=Gn.object({username:ZR,password:tR,email:VG}).strict();var pl={100:"Continue",101:"Switching Protocols",102:"Processing",103:"Early Hints",200:"OK",201:"Created",202:"Accepted",203:"Non-Authoritative Information",204:"No Content",205:"Reset Content",206:"Partial Content",207:"Multi-Status",208:"Already Reported",226:"IM Used",300:"Multiple Choices",301:"Moved Permanently",302:"Found",303:"See Other",304:"Not Modified",305:"Use Proxy",306:"Switch Proxy",307:"Temporary Redirect",308:"Permanent Redirect",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",407:"Proxy Authentication Required",408:"Request Timeout",409:"Conflict",410:"Gone",411:"Length Required",412:"Precondition Failed",413:"Payload Too Large",414:"URI Too Long",415:"Unsupported Media Type",416:"Range Not Satisfiable",417:"Expectation Failed",418:"I'm a teapot",421:"Misdirected Request",422:"Unprocessable Entity",423:"Locked",424:"Failed Dependency",425:"Too Early",426:"Upgrade Required",428:"Precondition Required",429:"Too Many Requests",431:"Request Header Fields Too Large",451:"Unavailable For Legal Reasons",500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout",505:"HTTP Version Not Supported",506:"Variant Also Negotiates",507:"Insufficient Storage",508:"Loop Detected",510:"Not Extended",511:"Network Authentication Required"},S$=H$(pl).map(([n])=>Gn.literal(Number(n))),uG=Gn.union([S$[0],S$[1],...S$]),rR=Gn.tuple([uG,Gn.string()]);var gR=go({key:"count",default:0}),_G=Xc({key:"incrementTX",do:({set:n})=>{n(gR,(i)=>i+1)}}),dR=f0({key:"countContinuity",config:(n)=>n.add(gR).add(_G)});var n4=_v(Fc,"backend.worker.game.bun",Tn),qc=new w$({logQuery(n,i){Tn.info("\uD83D\uDCDD query",n,i)}});nn.STORE.loggers[0]=new Wc("info",void 0,Tn);var pI=(()=>{let{__tribunalDaily:n}=globalThis;if(!n)n=new i4.CronJob("00 15 * * * *",()=>{_v(Fc,"backend.worker.tribunal.bun",Tn)}),n.start(),process.on("exit",()=>{n.stop(),Tn.info("\u231B tribunal daily cronjob stopped")}),Tn.info("\u23F3 tribunal daily cronjob started");return n})();function yG(n){if(uv)return jG(uv,n);return bG({},n)}var o4=yG((n,i)=>{let o;n.on("data",(c)=>(o??=[]).push(c)).on("end",async()=>{let c=n.headers.authorization;try{if(typeof n.url==="undefined")throw[400,"No URL"];let p=n.socket.remoteAddress;if(!p)throw[400,"No IP address"];let a=new Date,x=new URL(n.url,rn.VITE_BACKEND_ORIGIN);Tn.info(a,p,n.method,x.pathname);let m=await qc.drizzle.query.banishedIps.findFirst({columns:{banishedUntil:!0},where:Eo(cl.ip,p)}),l=m?.banishedUntil===null,f=m?.banishedUntil&&m.banishedUntil>a;if(l||f){Tn.info(`\uD83D\uDE45 request from banned ip ${p}`);return}switch(n.method){case"POST":if(!o)throw[400,"No data received"];switch(x.pathname){case`/sign-up-${J$("sign-up")}`:{let v=Buffer.concat(o).toString(),$=JSON.parse(v),T=PR.safeParse($);if(!T.success){Tn.warn("signup parsed",T.error.issues);return}let{username:F,password:M,email:A}=T.data;if(Tn.info(`\uD83D\uDD11 attempting to sign up: ${F}`),await qc.drizzle.query.users.findFirst({columns:{id:!0},where:Eo(Xo.email,A)}))throw[400,"User already exists"];let G=crypto.randomUUID(),Q=eR("sha256").update(M+G).digest("hex");await qc.drizzle.insert(Xo).values({username:F,email:A,hash:Q,salt:G,createdIp:p}),Tn.info(`\uD83D\uDD11 user created: ${F}`),i.writeHead(201,{"Content-Type":"text/plain","Access-Control-Allow-Origin":`${rn.FRONTEND_ORIGINS[0]}`}),i.end(pl[201])}break;case`/login-${J$("login")}`:{let v=!1,$=null;try{let T=new Date(+a-600000);Tn.info("\uD83D\uDD11 ten minutes ago",{tenMinutesAgo:T,now:a});let F=await qc.drizzle.query.loginHistory.findMany({columns:{userId:!0,successful:!0},where:Uc(Eo(ep.ipAddress,p),Eo(ep.successful,!1),Px(ep.loginTime,T)),limit:10});Tn.info(`\uD83D\uDD11 ${F.length}/10 recent failed logins from ${p}`);let M=10-F.length;if(M<1)throw Tn.info(`\uD83D\uDD11 too many recent failed logins from ${p}`),await qc.drizzle.insert(cl).values({ip:p,reason:"Too many recent login attempts.",banishedAt:a,banishedUntil:new Date(+a+86400000)}),[429,"Too many recent login attempts."];let A=Buffer.concat(o).toString(),R=JSON.parse(A),G=qR.safeParse(R);if(!G.success)throw Tn.warn("login parsed",G.error.issues),[400,`${M} attempts remaining.`];let{username:Q,password:b}=G.data,D=await qc.drizzle.query.users.findFirst({columns:{id:!0,hash:!0,salt:!0},where:Eo(Xo.username,Q)});if(Tn.info("\uD83D\uDD11 login attempt as user",Q),!D)throw Tn.info(`\uD83D\uDD11 user ${Q} does not exist`),[400,`${M} attempts remaining.`];let{hash:Y,salt:K}=D;if($=D.id,eR("sha256").update(b+K).digest("hex")===Y){let y=crypto.randomUUID(),V=Nm.get(Q);if(!V)V=new Map,Nm.set(Q,V);V.set(y,Number(a)),v=!0,Tn.info("\uD83D\uDD11 login successful as",Q),i.writeHead(200,{"Content-Type":"text/plain","Access-Control-Allow-Origin":`${rn.FRONTEND_ORIGINS[0]}`}),i.end(`${Q} ${y}`)}}finally{await qc.drizzle.insert(ep).values({userId:$,successful:v,ipAddress:p,userAgent:n.headers["user-agent"]??"Withheld"}),Tn.info(`\uD83D\uDD11 recorded login attempt from ${p}`)}}}}}catch(p){let a=rR.safeParse(p);if(a.success){let[x,m]=a.data,f=`${pl[x]}. ${m}`;Tn.info(`\u274C ${x}: ${f}`),i.writeHead(x,{"Content-Type":"text/plain","Access-Control-Allow-Origin":`${rn.FRONTEND_ORIGINS[0]}`}),i.end(f)}else Tn.error(p),i.writeHead(500,{"Content-Type":"text/plain","Access-Control-Allow-Origin":`${rn.FRONTEND_ORIGINS[0]}`}),i.end("Internal Server Error")}})}),A$=o4.listen(rn.BACKEND_PORT).address(),BG=typeof A$==="string"?null:A$===null?null:A$.port;if(BG===null)throw new Error("Could not determine port for test server");new qM(o4,{cors:{origin:rn.FRONTEND_ORIGINS,methods:["GET","POST"]}}).use((n,i)=>{let{username:o,sessionKey:c}=n.handshake.auth;if(!(o&&c)){i(new Error("No auth header provided"));return}let p=`user::${o}`,a=`socket::${n.id}`;if(Nm.get(o)?.has(c)){let m=Sn(nn.STORE,Xx,a);Qn(nn.STORE,m,n),Rc(Gc,(l)=>{l.set(p,a)},nn.STORE),Qn(nn.STORE,jl,(l)=>l.add(p)),Qn(nn.STORE,bl,(l)=>l.add(a)),Tn.info(`${o} connected on ${n.id}`),i()}else Tn.info(`${o} couldn't authenticate`),i(new Error("Authentication error"))}).on("connection",(n)=>{let o=F0({socket:n,store:nn.STORE})(dR);n.on("disconnect",()=>{let c=`socket::${n.id}`,p=np(Gc,c,nn.STORE).userKeyOfSocket,a=Mn(nn.STORE,p);if(Rc(Gc,(x)=>{x.delete(c)},nn.STORE),a)Qn(nn.STORE,jl,(x)=>(x.delete(a),x));Qn(nn.STORE,bl,(x)=>(x.delete(c),x)),Tn.info(`${n.id} disconnected`),o()})});async function al(){Tn.info("\uD83E\uDDF9 closing workers");let n=new Promise((i)=>n4.process.once("close",i));n4.process.emit("timeToStop"),await n,Tn.info("\uD83D\uDEEC backend server exiting"),process.exit(0)}process.on("SIGINT",async()=>{Tn.info("\u2757 received SIGINT; exiting gracefully"),await al()});process.on("SIGTERM",async()=>{Tn.info("\u2757 received SIGTERM; exiting gracefully"),await al()});process.on("exit",async()=>{Tn.info("\u2757 received exit; exiting gracefully"),await al()});Fc.on("updatesReady",()=>{Tn.info('\u2757 backend server received signal "updatesReady"'),Fc.emit("readyToUpdate"),Tn.info('\u2757 backend server has sent signal "readyToUpdate"; now awaits signal "timeToStop"'),Fc.on("timeToStop",async()=>{Tn.info('\u2757 backend server received signal "timeToStop"; exiting gracefully'),await al()})});Tn.info(`\uD83D\uDEEB backend server ready on port ${rn.BACKEND_PORT}`);Fc.emit("alive");export{pI as tribunalDaily};
|