tempest.games 0.1.37 → 0.1.39
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/CHANGELOG.md +14 -0
- package/app/assets/index-HtWKEKQB.js +100 -0
- package/app/index.html +1 -1
- package/bin/backend.bun.js +71 -33
- package/bin/backend.worker.game.bun.js +2 -2
- package/bin/backend.worker.tribunal.bun.js +91 -53
- package/bin/frontend.bun.js +55 -17
- package/bin/interactive-db.bun.js +1 -1
- package/bin/setup-db.bun.js +7444 -3714
- package/drizzle.config.ts +22 -17
- package/package.json +18 -19
- package/app/assets/index-i-9D4V9Z.js +0 -62
package/bin/frontend.bun.js
CHANGED
|
@@ -1,32 +1,70 @@
|
|
|
1
1
|
#!/usr/bin/env bun
|
|
2
2
|
// @bun
|
|
3
|
-
var
|
|
4
|
-
|
|
5
|
-
|
|
3
|
+
var SX=Object.create;var{getPrototypeOf:$X,defineProperty:LS,getOwnPropertyNames:JX}=Object;var _X=Object.prototype.hasOwnProperty;var z5=(T,o,y)=>{y=T!=null?SX($X(T)):{};let A=o||!T||!T.__esModule?LS(y,"default",{value:T,enumerable:!0}):y;for(let F of JX(T))if(!_X.call(A,F))LS(A,F,{get:()=>T[F],enumerable:!0});return A};var Q5=(T,o)=>()=>(o||T((o={exports:{}}).exports,o),o.exports);var RX=(T,o)=>{for(var y in o)LS(T,y,{get:o[y],enumerable:!0,configurable:!0,set:(A)=>o[y]=()=>A})};var V5=import.meta.require;import{join as w5,normalize as U5,resolve as M4}from"path";var Ky=(T)=>Array.isArray(T)?T:[T],B0=(T,o)=>{let y=[[],[]];for(let A of T)if(o(A))y[0].push(A);else y[1].push(A);return y},cF=Array,Fy=(T,o)=>T.includes(o),N0=(T,o=0)=>[...new Array(T)].map((y,A)=>A+o),FT=(T,o,y)=>{if(T===void 0)return o===void 0?[]:Array.isArray(o)?o:[o];if(y?.prepend)if(Array.isArray(o))T.unshift(...o);else T.unshift(o);else if(Array.isArray(o))T.push(...o);else T.push(o);return T},fy=(T,o)=>{if(o===void 0||o===null)return T??[];if(T===void 0||T===null)return Ky(o);return T.concat(o)},t0=(...T)=>T.reduce(fy,[]),so=(T,o,y)=>{if(T===void 0)return Array.isArray(o)?o:[o];let A=y?.isEqual??((F,f)=>F===f);return Ky(o).forEach((F)=>{if(!T.some((f)=>A(f,F)))T.push(F)}),T},p0=(T,o)=>T.reduce((y,A)=>{let F=A[o];return y[F]=FT(y[F],A),y},{}),Sy=(T,o,y)=>T.length===o.length&&T.every(y?.isEqual?(A,F)=>y.isEqual(A,o[F]):(A,F)=>A===o[F]);var Yo=(T,o)=>hT(T)===o,hT=(T)=>{let o=typeof T;return o==="object"?T===null?"null":"object":o==="function"?"object":o},Zo={boolean:"boolean",null:"null",undefined:"undefined",bigint:"a bigint",number:"a number",object:"an object",string:"a string",symbol:"a symbol"},b0={...Zo,function:"a function"};class x0 extends Error{}var $T=(T)=>$y(T,x0),$y=(T,o=Error)=>{throw new o(T)};class qA extends Error{name="ParseError"}var E=(T)=>$y(T,qA),Po=(T)=>` ${T}`;var l=(T,o)=>{let y={},A=Array.isArray(T),F=!1;return Object.entries(T).forEach((f,S)=>{let $=A?o(S,f[1]):o(...f,S);F||=typeof $[0]==="number",(Array.isArray($[0])||$.length===0?$:[$]).forEach(([J,R])=>{if(typeof J==="object")y[J.group]=FT(y[J.group],R);else y[J]=R})}),F?Object.values(y):y};var IS=Object.entries;var pT=(T,o)=>(T in o),yA=(T,o)=>(o in T);class kS{constructor(T){Object.assign(this,T)}}var j0=class{};class vA extends j0{}var WX=(T,o)=>{let y={},A={},F;for(F in T)if(F in o)y[F]=T[F];else A[F]=T[F];return[y,A]};var m0=(T,o)=>WX(T,o)[1],ao=(T)=>Object.keys(T).length===0,PA=(T)=>[...Object.entries(T),...Object.getOwnPropertySymbols(T).map((o)=>[o,T[o]])],q0=(T,o)=>Object.defineProperties(T,Object.getOwnPropertyDescriptors(o)),v0=(T)=>{let o=Object.keys(T).sort(),y={};for(let A=0;A<o.length;A++)y[o[A]]=T[o[A]];return y};var Qo=Po("represents an uninitialized value"),P0=(T)=>Object.values(T).filter((o)=>{if(typeof o==="number")return!0;return typeof T[o]!=="number"});var BS={Array,Boolean,Date,Error,Function,Map,Number,Promise,RegExp,Set,String,WeakMap,WeakSet},NS=globalThis.File??Blob,tS={ArrayBuffer,Blob,File:NS,FormData,Headers,Request,Response,URL},OX={Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array},jy={...BS,...tS,...OX,String,Number,Boolean},hA=(T)=>{let o=Object.getPrototypeOf(T);while(o?.constructor&&(!pT(o.constructor.name,jy)||!(T instanceof jy[o.constructor.name])))o=Object.getPrototypeOf(o);let y=o?.constructor?.name;if(y===void 0||y==="Object")return;return y},nA=(T)=>typeof T==="object"&&T!==null?hA(T)??"object":hT(T);var ET=Array.isArray,MX={Array:"an array",Function:"a function",Date:"a Date",RegExp:"a RegExp",Error:"an Error",Map:"a Map",Set:"a Set",String:"a String object",Number:"a Number object",Boolean:"a Boolean object",Promise:"a Promise",WeakMap:"a WeakMap",WeakSet:"a WeakSet"},XX={ArrayBuffer:"an ArrayBuffer instance",Blob:"a Blob instance",File:"a File instance",FormData:"a FormData instance",Headers:"a Headers instance",Request:"a Request instance",Response:"a Response instance",URL:"a URL instance"},YX={Int8Array:"an Int8Array",Uint8Array:"a Uint8Array",Uint8ClampedArray:"a Uint8ClampedArray",Int16Array:"an Int16Array",Uint16Array:"a Uint16Array",Int32Array:"an Int32Array",Uint32Array:"a Uint32Array",Float32Array:"a Float32Array",Float64Array:"a Float64Array",BigInt64Array:"a BigInt64Array",BigUint64Array:"a BigUint64Array"},h0={...MX,...XX,...YX},gA=(T)=>{let o=Object(T).name??null;return o&&pT(o,jy)&&jy[o]===T?o:null};var pS=(T,o)=>{let y=T.prototype;while(y!==null){if(y===o.prototype)return!0;y=Object.getPrototypeOf(y)}return!1};var n0=(T)=>g0(T,new Map),g0=(T,o)=>{if(typeof T!=="object"||T===null)return T;if(o?.has(T))return o.get(T);let y=gA(T.constructor);if(y==="Date")return new Date(T.getTime());if(y&&y!=="Array")return T;let A=Array.isArray(T)?T.slice():Object.create(Object.getPrototypeOf(T)),F=Object.getOwnPropertyDescriptors(T);if(o){o.set(T,A);for(let f in F){let S=F[f];if("get"in S||"set"in S)continue;S.value=g0(S.value,o)}}return Object.defineProperties(A,F),A};var ZX=(T)=>{let o=Qo;return()=>o===Qo?o=T():o},zy=(T)=>typeof T==="function"&&T.length===0;var u0=class extends Function{constructor(...T){let o=T.slice(0,-1),y=T.at(-1);try{super(...o,y)}catch(A){return $T(`Encountered an unexpected error while compiling your definition:
|
|
4
|
+
Message: ${A}
|
|
5
|
+
Source: (${T.slice(0,-1)}) => {
|
|
6
|
+
${T.at(-1)}
|
|
7
|
+
}`)}}};class ho{constructor(T,...[o]){return Object.assign(Object.setPrototypeOf(T.bind(o?.bind??this),this.constructor.prototype),o?.attach)}}var i0=ZX(()=>{try{return new Function("return false")()}catch{return!0}});var i5=Po("brand");var c0=Po("arkInferred");var r5=Po("args");class fo{constructor(){}}var HX=()=>{try{return((new Error().stack?.split(`
|
|
8
|
+
`)[2]?.trim()||"").match(/\(?(.+?)(?::\d+:\d+)?\)?$/)?.[1]||"unknown").replace(/^file:\/\//,"")}catch{return"unknown"}},EX=globalThis.process?.env??{},d0={fileName:HX,env:EX};var r0=(T)=>T[0].toUpperCase()+T.slice(1);var bS=(T)=>new RegExp(GX(T),typeof T==="string"?"":T.flags);var GX=(T)=>{return`^(?:${typeof T==="string"?T:T.source})$`};var Jy={negativeLookahead:(T)=>`(?!${T})`,nonCapturingGroup:(T)=>`(?:${T})`},uA="\\",Qy={" ":1,"\n":1,"\t":1};var wX=/^-0\.?0*$/.source,s0=/[1-9]\d*/.source,UX=/\.\d+/.source,KX=/\.\d*[1-9]/.source,a0=(T)=>bS(Jy.negativeLookahead(wX)+Jy.nonCapturingGroup("-?"+Jy.nonCapturingGroup(Jy.nonCapturingGroup("0|"+s0)+Jy.nonCapturingGroup(T.decimalPattern)+"?")+(T.allowDecimalOnly?"|"+T.decimalPattern:"")+"?")),l0=a0({decimalPattern:KX,allowDecimalOnly:!1}),zX=l0.test.bind(l0),dF=a0({decimalPattern:UX,allowDecimalOnly:!0}),yH=dF.test.bind(dF),QX=/^-?\d*\.?\d*$/,VX=(T)=>T.length!==0&&QX.test(T),iA=bS(Jy.negativeLookahead("^-0$")+"-?"+Jy.nonCapturingGroup(Jy.nonCapturingGroup("0|"+s0))),DX=iA.test.bind(iA),xS=/^-?\d+$/,CX=xS.test.bind(xS),e0={number:"a number",bigint:"a bigint",integer:"an integer"},T_=(T,o)=>`'${T}' was parsed as ${e0[o]} but could not be narrowed to a literal value. Avoid unnecessary leading or trailing zeros and other abnormal notation`,LX=(T,o)=>o==="number"?zX(T):DX(T),IX=(T,o)=>o==="number"?Number(T):Number.parseInt(T),kX=(T,o)=>o==="number"?VX(T):CX(T),o_=(T,o)=>jS(T,"number",o),y_=(T,o)=>jS(T,"number",{...o,strict:!0}),A_=(T,o)=>jS(T,"integer",o),jS=(T,o,y)=>{let A=IX(T,o);if(!Number.isNaN(A)){if(kX(T,o)){if(y?.strict)return LX(T,o)?A:E(T_(T,o));return A}}return y?.errorOnFail?E(y?.errorOnFail===!0?`Failed to parse ${e0[o]} from '${T}'`:y?.errorOnFail):void 0},F_=(T)=>{if(T[T.length-1]!=="n")return;let o=T.slice(0,-1),y;try{y=BigInt(o)}catch{return}if(iA.test(o))return y;if(xS.test(o))return E(T_(T,"bigint"))};var BX="0.45.9",NX={version:BX,filename:d0.fileName(),FileConstructor:NS},my=NX,f_=new WeakMap,mS=Object.create(null),cA=(T)=>{let o=f_.get(T);if(o)return o;let y=tX(T);if(mS[y])y=`${y}${mS[y]++}`;else mS[y]=1;return my[y]=T,f_.set(T,y),y},AA=(T)=>/^[a-zA-Z_$][a-zA-Z_$0-9]*$/.test(T),tX=(T)=>{switch(typeof T){case"object":{if(T===null)break;let o=hA(T)??"object";return o[0].toLowerCase()+o.slice(1)}case"function":return AA(T.name)?T.name:"fn";case"symbol":return T.description&&AA(T.description)?T.description:"symbol"}return $T(`Unexpected attempt to register serializable value of type ${hT(T)}`)};var rF=(T)=>typeof T==="string"?JSON.stringify(T):typeof T==="bigint"?`${T}n`:`${T}`;var S_=(T,o={})=>dA(T,{onUndefined:"$ark.undefined",onBigInt:(y)=>`$ark.bigint-${y}`,...o},[]);var d=(T,o)=>{switch(hT(T)){case"object":let y=T,A=y.constructor.name;return A==="Object"||A==="Array"?JSON.stringify(dA(y,lF,[]),null,o):y instanceof Date?qy(y):typeof y.expression==="string"?y.expression:A;case"symbol":return lF.onSymbol(T);default:return rF(T)}},lF={onCycle:()=>"(cycle)",onSymbol:(T)=>`Symbol(${cA(T)})`,onFunction:(T)=>`Function(${cA(T)})`},dA=(T,o,y)=>{switch(hT(T)){case"object":{let A=T;if("toJSON"in A&&typeof A.toJSON==="function")return A.toJSON();if(typeof A==="function")return lF.onFunction(A);if(y.includes(A))return"(cycle)";let F=[...y,A];if(Array.isArray(A))return A.map((S)=>dA(S,o,F));if(A instanceof Date)return A.toDateString();let f={};for(let S in A)f[S]=dA(A[S],o,F);for(let S of Object.getOwnPropertySymbols(A))f[o.onSymbol?.(S)??S.toString()]=dA(A[S],o,F);return f}case"symbol":return lF.onSymbol(T);case"bigint":return o.onBigInt?.(T)??`${T}n`;case"undefined":return o.onUndefined??"undefined";case"string":return T.replaceAll("\\","\\\\");default:return T}},qy=(T)=>{let o=T.getFullYear(),y=T.getMonth(),A=T.getDate(),F=T.getHours(),f=T.getMinutes(),S=T.getSeconds(),$=T.getMilliseconds();if(y===0&&A===1&&F===0&&f===0&&S===0&&$===0)return`${o}`;let _=`${pX[y]} ${A}, ${o}`;if(F===0&&f===0&&S===0&&$===0)return _;let J=T.toLocaleTimeString(),R=J.endsWith(" AM")||J.endsWith(" PM")?J.slice(-3):"";if(R)J=J.slice(0,-R.length);if($)J+=`.${xX($,3)}`;else if(bX.test(J))J=J.slice(0,-3);return`${J+R}, ${_}`},pX=["January","February","March","April","May","June","July","August","September","October","November","December"],bX=/:\d\d:00$/,xX=(T,o)=>String(T).padStart(o,"0");var $_=(T,o,...[y])=>{let A=y?.stringifySymbol??d,F=T;switch(typeof o){case"string":F=AA(o)?T===""?o:`${T}.${o}`:`${T}[${JSON.stringify(o)}]`;break;case"number":F=`${T}[${o}]`;break;case"symbol":F=`${T}[${A(o)}]`;break;default:if(y?.stringifyNonKey)F=`${T}[${y.stringifyNonKey(o)}]`;else E(`${d(o)} must be a PropertyKey or stringifyNonKey must be passed to options`)}return F},_y=(T,...o)=>T.reduce((y,A)=>$_(y,A,...o),"");class rA extends cF{cache={};constructor(...T){super();this.push(...T)}toJSON(){if(this.cache.json)return this.cache.json;this.cache.json=[];for(let T=0;T<this.length;T++)this.cache.json.push(typeof this[T]==="symbol"?d(this[T]):this[T]);return this.cache.json}stringify(){if(this.cache.stringify)return this.cache.stringify;return this.cache.stringify=_y(this)}stringifyAncestors(){if(this.cache.stringifyAncestors)return this.cache.stringifyAncestors;let T="",o=[T];return this.forEach((y)=>{T=$_(T,y),o.push(T)}),this.cache.stringifyAncestors=o}}class qS{chars;i;def;constructor(T){this.def=T,this.chars=[...T],this.i=0}shift(){return this.chars[this.i++]??""}get lookahead(){return this.chars[this.i]??""}get nextLookahead(){return this.chars[this.i+1]??""}get length(){return this.chars.length}shiftUntil(T){let o="";while(this.lookahead){if(T(this,o))if(o[o.length-1]===uA)o=o.slice(0,-1);else break;o+=this.shift()}return o}shiftUntilLookahead(T){return typeof T==="string"?this.shiftUntil((o)=>o.lookahead===T):this.shiftUntil((o)=>(o.lookahead in T))}shiftUntilNonWhitespace(){return this.shiftUntil(()=>!(this.lookahead in Qy))}jumpToIndex(T){this.i=T<0?this.length+T:T}jumpForward(T){this.i+=T}get location(){return this.i}get unscanned(){return this.chars.slice(this.i,this.length).join("")}get scanned(){return this.chars.slice(0,this.i).join("")}sliceChars(T,o){return this.chars.slice(T,o).join("")}lookaheadIs(T){return this.lookahead===T}lookaheadIsIn(T){return this.lookahead in T}}var DH=Po("implementedTraits");var vS="$ark",jX=2;while(vS in globalThis)vS=`$ark${jX++}`;var J_=vS;globalThis[J_]=my;var U=my,mX=(T)=>`${J_}.${T}`,BT=(T)=>mX(cA(T));class sF extends vA{argNames;body="";constructor(...T){super();this.argNames=T;for(let o of T){if(o in this)throw new Error(`Arg name '${o}' would overwrite an existing property on FunctionBody`);this[o]=o}}indentation=0;indent(){return this.indentation+=4,this}dedent(){return this.indentation-=4,this}prop(T,o=!1){return PS(T,o)}index(T,o=!1){return __(`${T}`,o)}line(T){return this.body+=`${" ".repeat(this.indentation)}${T}
|
|
9
|
+
`,this}const(T,o){return this.line(`const ${T} = ${o}`),this}let(T,o){return this.line(`let ${T} = ${o}`)}set(T,o){return this.line(`${T} = ${o}`)}if(T,o){return this.block(`if (${T})`,o)}elseIf(T,o){return this.block(`else if (${T})`,o)}else(T){return this.block("else",T)}for(T,o,y=0){return this.block(`for (let i = ${y}; ${T}; i++)`,o)}forIn(T,o){return this.block(`for (const k in ${T})`,o)}block(T,o,y=""){return this.line(`${T} {`),this.indent(),o(this),this.dedent(),this.line(`}${y}`)}return(T=""){return this.line(`return ${T}`)}write(T="anonymous",o=0){return`${T}(${this.argNames.join(", ")}) { ${o?this.body.split(`
|
|
10
|
+
`).map((y)=>" ".repeat(o)+`${y}`).join(`
|
|
11
|
+
`):this.body} }`}compile(){return new u0(...this.argNames,this.body)}}var Ry=(T)=>Yo(T,"object")||typeof T==="symbol"?BT(T):rF(T),PS=(T,o=!1)=>{if(typeof T==="string"&&AA(T))return`${o?"?":""}.${T}`;return __(qX(T),o)},qX=(T)=>typeof T==="symbol"?BT(T):JSON.stringify(T),__=(T,o=!1)=>`${o?"?.":""}[${T}]`;class lA extends sF{traversalKind;optimistic;constructor(T){super("data","ctx");this.traversalKind=T.kind,this.optimistic=T.optimistic===!0}invoke(T,o){let y=o?.arg??this.data,A=typeof T==="string"?!0:this.requiresContextFor(T),F=typeof T==="string"?T:T.id;if(A)return`${this.referenceToId(F,o)}(${y}, ${this.ctx})`;return`${this.referenceToId(F,o)}(${y})`}referenceToId(T,o){let y=o?.kind??this.traversalKind,A=`this.${T}${y}`;return o?.bind?`${A}.bind(${o?.bind})`:A}requiresContextFor(T){return this.traversalKind==="Apply"||T.allowsRequiresContext}initializeErrorCount(){return this.const("errorCount","ctx.currentErrorCount")}returnIfFail(){return this.if("ctx.currentErrorCount > errorCount",()=>this.return())}returnIfFailFast(){return this.if("ctx.failFast && ctx.currentErrorCount > errorCount",()=>this.return())}traverseKey(T,o,y){let A=this.requiresContextFor(y);if(A)this.line(`${this.ctx}.path.push(${T})`);if(this.check(y,{arg:o}),A)this.line(`${this.ctx}.path.pop()`);return this}check(T,o){return this.traversalKind==="Allows"?this.if(`!${this.invoke(T,o)}`,()=>this.return(!1)):this.line(this.invoke(T,o))}}var aF=(T)=>l(T,(o,y)=>[o,ET(y)?[...y]:y]),Ro=Po("arkKind"),q=(T,o)=>T?.[Ro]===o,zT=(T)=>q(T,"root")||q(T,"constraint");var R_=["unit","proto","domain"],FA=["required","optional","index","sequence"],hS=["pattern","divisor","exactLength","max","min","maxLength","minLength","before","after"],eF=[...hS,...FA,"structure","predicate"],fA=["alias","union","morph","unit","intersection","proto","domain"],vX=[...fA,...eF],Tf=l(eF,(T,o)=>[o,1]),W_=l([...FA,"undeclared"],(T,o)=>[o,1]),O_=l(vX,(T,o)=>[o,T]),SA=(T)=>typeof T==="string"&&(T in O_);var $A=(T)=>O_[T],of=(T)=>fA.slice($A(T)+1),_E=[...of("union"),"alias"],RE=[...of("morph"),"alias"],ko=(T)=>{if(typeof T==="string"||typeof T==="boolean"||T===null)return T;if(typeof T==="number"){if(Number.isNaN(T))return"NaN";if(T===Number.POSITIVE_INFINITY)return"Infinity";if(T===Number.NEGATIVE_INFINITY)return"-Infinity";return T}return Ry(T)},Vy=(T)=>{let o="{ ";for(let[y,A]of Object.entries(T))o+=`${y}: ${Ry(A)}, `;return o+" }"},r=(T)=>{let o=T;if(o.hasAssociatedError)o.defaults.expected??=(y)=>("description"in y)?y.description:o.defaults.description(y),o.defaults.actual??=(y)=>d(y),o.defaults.problem??=(y)=>`must be ${y.expected}${y.actual?` (was ${y.actual})`:""}`,o.defaults.message??=(y)=>{if(y.path.length===0)return y.problem;let A=`${y.propString} ${y.problem}`;if(A[0]==="[")return`value at ${A}`;return A};return o};U.config??={};var sA=(T,o)=>{if(!o)return T;let y={...T},A;for(A in o){let F={...T.keywords};if(A==="keywords"){for(let f in o[A]){let S=o.keywords[f];if(S===void 0)continue;F[f]=typeof S==="string"?{description:S}:S}y.keywords=F}else y[A]=SA(A)?{...T[A],...o[A]}:o[A]}return y};class Dy extends vA{[Ro]="error";path;data;nodeConfig;input;ctx;constructor({prefixPath:T,relativePath:o,...y},A){super();this.input=y,this.ctx=A,q0(this,y);let F=A.data;if(y.code==="union")y.errors=y.errors.flatMap((S)=>{let $=S.hasCode("union")?S.errors:[S];if(!T&&!o)return $;return $.map((_)=>_.transform((J)=>({...J,path:t0(T,J.path,o)})))});this.nodeConfig=A.config[this.code];let f=[...y.path??A.path];if(o)f.push(...o);if(T)f.unshift(...T);this.path=new rA(...f),this.data="data"in y?y.data:F}transform(T){return new Dy(T({data:this.data,path:this.path,...this.input}),this.ctx)}hasCode(T){return this.code===T}get propString(){return _y(this.path)}get expected(){if(this.input.expected)return this.input.expected;let T=this.meta?.expected??this.nodeConfig.expected;return typeof T==="function"?T(this.input):T}get actual(){if(this.input.actual)return this.input.actual;let T=this.meta?.actual??this.nodeConfig.actual;return typeof T==="function"?T(this.data):T}get problem(){if(this.input.problem)return this.input.problem;let T=this.meta?.problem??this.nodeConfig.problem;return typeof T==="function"?T(this):T}get message(){if(this.input.message)return this.input.message;let T=this.meta?.message??this.nodeConfig.message;return typeof T==="function"?T(this):T}get flat(){return this.hasCode("intersection")?[...this.errors]:[this]}toJSON(){return{data:this.data,path:this.path,...this.input,expected:this.expected,actual:this.actual,problem:this.problem,message:this.message}}toString(){return this.message}throw(){throw this}}class Ho extends cF{[Ro]="errors";ctx;constructor(T){super();this.ctx=T}byPath=Object.create(null);get flatByPath(){return l(this.byPath,(T,o)=>[T,o.flat])}get flatProblemsByPath(){return l(this.byPath,(T,o)=>[T,o.flat.map((y)=>y.problem)])}byAncestorPath=Object.create(null);count=0;mutable=this;throw(){throw this.toTraversalError()}toTraversalError(){return new nS(this)}add(T){if(this.includes(T))return;this._add(T)}transform(T){let o=new Ho(this.ctx);return this.forEach((y)=>o.add(T(y))),o}merge(T){T.forEach((o)=>{if(this.includes(o))return;this._add(new Dy({...o,path:[...this.ctx.path,...o.path]},this.ctx))})}affectsPath(T){if(this.length===0)return!1;return T.stringifyAncestors().some((o)=>(o in this.byPath))||T.stringify()in this.byAncestorPath}get summary(){return this.toString()}get issues(){return this}toJSON(){return[...this.map((T)=>T.toJSON())]}toString(){return this.join(`
|
|
12
|
+
`)}_add(T){let o=this.byPath[T.propString];if(o){if(o.hasCode("union")&&o.errors.length===0)return;let y=T.hasCode("union")&&T.errors.length===0?T:new Dy({code:"intersection",errors:o.hasCode("intersection")?[...o.errors,T]:[o,T]},this.ctx),A=this.indexOf(o);this.mutable[A===-1?this.length:A]=y,this.byPath[T.propString]=y,this.addAncestorPaths(T)}else this.byPath[T.propString]=T,this.addAncestorPaths(T),this.mutable.push(T);this.count++}addAncestorPaths(T){T.path.stringifyAncestors().forEach((o)=>{this.byAncestorPath[o]=FT(this.byAncestorPath[o],T)})}}class nS extends Error{name="TraversalError";constructor(T){if(T.length===1)super(T.summary);else super(`
|
|
13
|
+
`+T.map((o)=>` \u2022 ${PX(o)}`).join(`
|
|
14
|
+
`));Object.defineProperty(this,"arkErrors",{value:T,enumerable:!1})}}var PX=(T)=>T.toString().split(`
|
|
15
|
+
`).join(`
|
|
16
|
+
`);class no{path=[];errors=new Ho(this);root;config;queuedMorphs=[];branches=[];seen={};constructor(T,o){this.root=T,this.config=o}get data(){let T=this.root;for(let o of this.path)T=T?.[o];return T}get propString(){return _y(this.path)}reject(T){return this.error(T),!1}mustBe(T){return this.error(T),!1}error(T){let o=typeof T==="object"?T.code?T:{...T,code:"predicate"}:{code:"predicate",expected:T};return this.errorFromContext(o)}hasError(){return this.currentErrorCount!==0}get currentBranch(){return this.branches.at(-1)}queueMorphs(T){let o={path:new rA(...this.path),morphs:T};if(this.currentBranch)this.currentBranch.queuedMorphs.push(o);else this.queuedMorphs.push(o)}finalize(T){if(this.queuedMorphs.length){if(typeof this.root==="object"&&this.root!==null&&this.config.clone)this.root=this.config.clone(this.root);this.applyQueuedMorphs()}if(this.hasError())return T?T(this.errors):this.errors;return this.root}get currentErrorCount(){return this.currentBranch?this.currentBranch.error?1:0:this.errors.count}get failFast(){return this.branches.length!==0}pushBranch(){this.branches.push({error:void 0,queuedMorphs:[]})}popBranch(){return this.branches.pop()}get external(){return this}errorFromNodeContext(T){return this.errorFromContext(T)}errorFromContext(T){let o=new Dy(T,this);if(this.currentBranch)this.currentBranch.error=o;else this.errors.add(o);return o}applyQueuedMorphs(){while(this.queuedMorphs.length){let T=this.queuedMorphs;this.queuedMorphs=[];for(let{path:o,morphs:y}of T){if(this.errors.affectsPath(o))continue;this.applyMorphsAtPath(o,y)}}}applyMorphsAtPath(T,o){let y=T.at(-1),A;if(y!==void 0){A=this.root;for(let F=0;F<T.length-1;F++)A=A[T[F]]}this.path=[...T];for(let F of o){let f=zT(F),S=F(A===void 0?this.root:A[y],this);if(S instanceof Dy){this.errors.add(S);break}if(S instanceof Ho){if(!f)this.errors.merge(S);break}if(A===void 0)this.root=S;else A[y]=S;this.applyQueuedMorphs()}}}var Eo=(T,o,y)=>{if(!y)return o();y.path.push(T);let A=o();return y.path.pop(),A};class eA extends ho{attachments;$;onFail;includesTransform;includesContextualPredicate;isCyclic;allowsRequiresContext;rootApplyStrategy;contextFreeMorph;rootApply;referencesById;shallowReferences;flatRefs;flatMorphs;allows;get shallowMorphs(){return[]}constructor(T,o){super((A,F,f=this.onFail)=>{if(F)return this.traverseApply(A,F),F.hasError()?F.errors:F.data;return this.rootApply(A,f)},{attach:T});this.attachments=T,this.$=o,this.onFail=this.meta.onFail??this.$.resolvedConfig.onFail,this.includesTransform=this.hasKind("morph")||this.hasKind("structure")&&this.structuralMorph!==void 0,this.includesContextualPredicate=this.hasKind("predicate")&&this.inner.predicate.length!==1,this.isCyclic=this.kind==="alias",this.referencesById={[this.id]:this},this.shallowReferences=this.hasKind("structure")?[this,...this.children]:this.children.reduce((A,F)=>uX(A,F.shallowReferences),[this]);let y=this.isStructural();this.flatRefs=[],this.flatMorphs=[];for(let A=0;A<this.children.length;A++){if(this.includesTransform||=this.children[A].includesTransform,this.includesContextualPredicate||=this.children[A].includesContextualPredicate,this.isCyclic||=this.children[A].isCyclic,!y){let F=this.children[A].flatRefs;for(let f=0;f<F.length;f++){let S=F[f];if(!this.flatRefs.some(($)=>X_($,S))){this.flatRefs.push(S);for(let $ of S.node.branches)if($.hasKind("morph")||$.hasKind("intersection")&&$.structure?.structuralMorph!==void 0)this.flatMorphs.push({path:S.path,propString:S.propString,node:$})}}}Object.assign(this.referencesById,this.children[A].referencesById)}this.flatRefs.sort((A,F)=>A.path.length>F.path.length?1:A.path.length<F.path.length?-1:A.propString>F.propString?1:A.propString<F.propString?-1:A.node.expression<F.node.expression?-1:1),this.allowsRequiresContext=this.includesContextualPredicate||this.isCyclic,this.rootApplyStrategy=!this.allowsRequiresContext&&this.flatMorphs.length===0?this.shallowMorphs.length===0?"allows":this.shallowMorphs.every((A)=>A.length===1||A.name==="$arkStructuralMorph")?this.hasKind("union")?this.branches.some((A)=>A.shallowMorphs.length>1)?"contextual":"branchedOptimistic":this.shallowMorphs.length>1?"contextual":"optimistic":"contextual":"contextual",this.rootApply=this.createRootApply(),this.allows=this.allowsRequiresContext?(A)=>this.traverseAllows(A,new no(A,this.$.resolvedConfig)):(A)=>this.traverseAllows(A)}createRootApply(){switch(this.rootApplyStrategy){case"allows":return(o,y)=>{if(this.allows(o))return o;let A=new no(o,this.$.resolvedConfig);return this.traverseApply(o,A),A.finalize(y)};case"contextual":return(o,y)=>{let A=new no(o,this.$.resolvedConfig);return this.traverseApply(o,A),A.finalize(y)};case"optimistic":this.contextFreeMorph=this.shallowMorphs[0];let T=this.$.resolvedConfig.clone;return(o,y)=>{if(this.allows(o))return this.contextFreeMorph(T&&(typeof o==="object"&&o!==null||typeof o==="function")?T(o):o);let A=new no(o,this.$.resolvedConfig);return this.traverseApply(o,A),A.finalize(y)};case"branchedOptimistic":return this.createBranchedOptimisticRootApply();default:return this.rootApplyStrategy,$T(`Unexpected rootApplyStrategy ${this.rootApplyStrategy}`)}}compiledMeta=gX(this.metaJson);cacheGetter(T,o){return Object.defineProperty(this,T,{value:o}),o}get description(){return this.cacheGetter("description",this.meta?.description??this.$.resolvedConfig[this.kind].description(this))}get references(){return Object.values(this.referencesById)}precedence=$A(this.kind);precompilation;assert=(T,o)=>this(T,o,(y)=>y.throw());traverse(T,o){return this(T,o,null)}get in(){return this.cacheGetter("in",this.getIo("in"))}get out(){return this.cacheGetter("out",this.getIo("out"))}getIo(T){if(!this.includesTransform)return this;let o={};for(let[y,A]of this.innerEntries){let F=this.impl.keys[y];if(F.reduceIo)F.reduceIo(T,o,A);else if(F.child){let f=A;o[y]=ET(f)?f.map((S)=>S[T]):f[T]}else o[y]=A}return this.$.node(this.kind,o)}toJSON(){return this.json}toString(){return`Type<${this.expression}>`}equals(T){let o=zT(T)?T:this.$.parseDefinition(T);return this.innerHash===o.innerHash}ifEquals(T){return this.equals(T)?this:void 0}hasKind(T){return this.kind===T}assertHasKind(T){if(this.kind!==T)$y(`${this.kind} node was not of asserted kind ${T}`);return this}hasKindIn(...T){return T.includes(this.kind)}assertHasKindIn(...T){if(!Fy(T,this.kind))$y(`${this.kind} node was not one of asserted kinds ${T}`);return this}isBasis(){return Fy(R_,this.kind)}isConstraint(){return Fy(eF,this.kind)}isStructural(){return Fy(FA,this.kind)}isRefinement(){return Fy(hS,this.kind)}isRoot(){return Fy(fA,this.kind)}isUnknown(){return this.hasKind("intersection")&&this.children.length===0}isNever(){return this.hasKind("union")&&this.children.length===0}hasUnit(T){return this.hasKind("unit")&&this.allows(T)}hasOpenIntersection(){return this.impl.intersectionIsOpen}get nestableExpression(){return this.expression}select(T){let o=aA.normalize(T);return this._select(o)}_select(T){let o=aA.applyBoundary[T.boundary??"references"](this);if(T.kind)o=o.filter((y)=>y.kind===T.kind);if(T.where)o=o.filter(T.where);return aA.applyMethod[T.method??"filter"](o,this,T)}transform(T,o){return this._transform(T,this._createTransformContext(o))}_createTransformContext(T){return{root:this,selected:void 0,seen:{},path:[],parseOptions:{prereduced:T?.prereduced??!1},undeclaredKeyHandling:void 0,...T}}_transform(T,o){let y=o.bindScope??this.$;if(o.seen[this.id])return this.$.lazilyResolve(o.seen[this.id]);if(o.shouldTransform?.(this,o)===!1)return this;let A;if(o.seen[this.id]=()=>A,this.hasKind("structure")&&this.undeclared!==o.undeclaredKeyHandling)o={...o,undeclaredKeyHandling:this.undeclared};let F=l(this.inner,(J,R)=>{if(!this.impl.keys[J].child)return[J,R];let M=R;if(!ET(M)){let H=M._transform(T,o);return H?[J,H]:[]}if(M.length===0)return[J,R];let Y=M.flatMap((H)=>{return H._transform(T,o)??[]});return Y.length?[J,Y]:[]});delete o.seen[this.id];let f=Object.assign(F,{meta:this.meta}),S=o.selected&&!o.selected.includes(this)?f:T(this.kind,f,o);if(S===null)return null;if(zT(S))return A=S;let $=Object.keys(S);if(($.length===0||$.length===1&&$[0]==="meta")&&!ao(this.inner))return null;if((this.kind==="required"||this.kind==="optional"||this.kind==="index")&&!("value"in S))return o.undeclaredKeyHandling?{...S,value:U.intrinsic.unknown}:null;if(this.kind==="morph")S.in??=U.intrinsic.unknown;return A=y.node(this.kind,S,o.parseOptions)}configureReferences(T,o="references"){let y=aA.normalize(o),A=typeof T==="string"?($,_)=>({..._,meta:{..._.meta,description:T}}):typeof T==="function"?($,_)=>({..._,meta:T(_.meta)}):($,_)=>({..._,meta:{..._.meta,...T}});if(y.boundary==="self")return this.$.node(this.kind,A(this.kind,{...this.inner,meta:this.meta}));let F=this._select(y),f=F&&Ky(F),S=y.boundary==="child"?($,_)=>_.root.children.includes($):y.boundary==="shallow"?($)=>$.kind!=="structure":()=>!0;return this.$.finalize(this.transform(A,{shouldTransform:S,selected:f}))}}var aA={applyBoundary:{self:(T)=>[T],child:(T)=>[...T.children],shallow:(T)=>[...T.shallowReferences],references:(T)=>[...T.references]},applyMethod:{filter:(T)=>T,assertFilter:(T,o,y)=>{if(T.length===0)$y(M_(o,y));return T},find:(T)=>T[0],assertFind:(T,o,y)=>{if(T.length===0)$y(M_(o,y));return T[0]}},normalize:(T)=>typeof T==="function"?{boundary:"references",method:"filter",where:T}:typeof T==="string"?pT(T,aA.applyBoundary)?{method:"filter",boundary:T}:{boundary:"references",method:"filter",kind:T}:{boundary:"references",method:"filter",...T}},M_=(T,o)=>`${T} had no references matching ${d(o)}.`,hX=(T)=>_y(T,{stringifyNonKey:(o)=>o.expression}),nX=/"(\$ark\.[^"]+)"/g,gX=(T)=>JSON.stringify(T).replaceAll(nX,"$1"),go=(T,o)=>({path:T,node:o,propString:hX(T)}),X_=(T,o)=>T.propString===o.propString&&T.node.equals(o.node),gS=(T,o)=>so(T,o,{isEqual:X_}),uX=(T,o)=>so(T,o,{isEqual:(y,A)=>y.equals(A)});class k extends Array{static init(T,o,y,A){return new k({kind:T,l:o,r:y,path:A?.path??[],optional:A?.optional??!1})}add(T,o,y,A){return this.push({kind:T,l:o,r:y,path:A?.path??[],optional:A?.optional??!1}),this}get summary(){return this.describeReasons()}describeReasons(){if(this.length===1){let{path:T,l:o,r:y}=this[0],A=_y(T);return iS(`Intersection${A&&` at ${A}`} of ${Y_(o,y)}`)}return`The following intersections result in unsatisfiable types:
|
|
17
|
+
\u2022 ${this.map(({path:T,l:o,r:y})=>`${T}: ${Y_(o,y)}`).join(`
|
|
18
|
+
\u2022 `)}`}throw(){return E(this.describeReasons())}invert(){let T=this.map((o)=>({...o,l:o.r,r:o.l}));if(!(T instanceof k))return new k(...T);return T}withPrefixKey(T,o){return this.map((y)=>({...y,path:[T,...y.path],optional:y.optional||o==="optional"}))}toNeverIfDisjoint(){return U.intrinsic.never}}var Y_=(T,o)=>`${uS(T)} and ${uS(o)}`,uS=(T)=>zT(T)?T.expression:ET(T)?T.map(uS).join(" | ")||"never":String(T),iS=(T)=>`${T} results in an unsatisfiable type`;var JA={},Go=(T,o,y)=>QT(T,o,{$:y,invert:!1,pipe:!1}),TF=(T,o,y)=>QT(T,o,{$:y,invert:!1,pipe:!0}),QT=(T,o,y)=>{let A=y.pipe?"|>":"&",F=`${T.hash}${A}${o.hash}`;if(JA[F]!==void 0)return JA[F];if(!y.pipe){let $=`${o.hash}${A}${T.hash}`;if(JA[$]!==void 0){let _=JA[$],J=_ instanceof k?_.invert():_;return JA[F]=J,J}}let f=!y.pipe||!T.includesTransform&&!o.includesTransform;if(f&&T.equals(o))return T;let S=f?cS(T,o,y):T.hasKindIn(...fA)?iX(T,o,y):cS(T,o,y);if(zT(S)){if(T.equals(S))S=T;else if(o.equals(S))S=o}return JA[F]=S,S},cS=(T,o,y)=>{let A=T.precedence<o.precedence?T.kind:o.kind,F=T.impl.intersections[o.kind]??o.impl.intersections[T.kind];if(F===void 0)return null;else if(A===T.kind)return F(T,o,y);else{let f=F(o,T,{...y,invert:!y.invert});if(f instanceof k)f=f.invert();return f}},iX=(T,o,y)=>T.includesTransform||o.includesTransform?y.invert?Z_(o,T,y):Z_(T,o,y):cS(T,o,y),Z_=(T,o,y)=>T.distribute((A)=>cX(A,o,y),(A)=>{let F=A.filter(zT);if(F.length===0)return k.init("union",T.branches,o.branches);if(F.length<T.branches.length||!T.branches.every(($,_)=>$.in.equals(F[_].in)))return y.$.parseSchema(F);let f;if(F.length===1){let $=F[0];if(!f)return $;return y.$.node("morph",{...$.inner,in:$.in.configure(f,"self")})}let S={branches:F};if(f)S.meta=f;return y.$.parseSchema(S)}),cX=(T,o,y)=>{if(T.hasKind("morph")){let F=[...T.morphs];if(T.lastMorphIfNode){let f=QT(T.lastMorphIfNode,o,y);if(f instanceof k)return f;F[F.length-1]=f}else F.push(o);return y.$.node("morph",{morphs:F,in:T.inner.in})}if(o.hasKind("morph")){let F=QT(T,o.in,y);if(F instanceof k)return F;return y.$.node("morph",{morphs:[o],in:F})}return y.$.node("morph",{morphs:[o],in:T})};class Bo extends eA{constructor(T,o){super(T,o);Object.defineProperty(this,Ro,{value:"constraint",enumerable:!1})}impliedSiblings;intersect(T){return Go(this,T,this.$)}}class Wy extends Bo{traverseApply=(T,o)=>{if(!this.traverseAllows(T,o))o.errorFromNodeContext(this.errorContext)};compile(T){if(T.traversalKind==="Allows")T.return(this.compiledCondition);else T.if(this.compiledNegation,()=>T.line(`${T.ctx}.errorFromNodeContext(${this.compiledErrorContext})`))}get errorContext(){return{code:this.kind,description:this.description,meta:this.meta,...this.inner}}get compiledErrorContext(){return Vy(this.errorContext)}}var So=(T)=>(o,y)=>{if(ET(o)){if(o.length===0)return;let F=o.map((f)=>y.$.node(T,f));if(T==="predicate")return F;return F.sort((f,S)=>f.hash<S.hash?-1:1)}let A=y.$.node(T,o);return A.hasOpenIntersection()?[A]:A},_A=(T)=>{let o=T.r.shift();if(!o){let A=T.l.length===0&&T.kind==="structure"?U.intrinsic.unknown.internal:T.ctx.$.node(T.kind,Object.assign(T.baseInner,dX(T.l)),{prereduced:!0});for(let F of T.roots){if(A instanceof k)return A;A=QT(F,A,T.ctx)}return A}let y=!1;for(let A=0;A<T.l.length;A++){let F=QT(T.l[A],o,T.ctx);if(F===null)continue;if(F instanceof k)return F;if(!y){if(F.isRoot())return T.roots.push(F),T.l.splice(A),_A(T);T.l[A]=F,y=!0}else if(!T.l.includes(F))return $T(`Unexpectedly encountered multiple distinct intersection results for refinement ${F}`)}if(!y)T.l.push(o);if(T.kind==="intersection")o.impliedSiblings?.forEach((A)=>so(T.r,A));return _A(T)},RA=(T)=>{return Object.entries(T).flatMap(([y,A])=>(y in Tf)?A:[]).sort((y,A)=>y.precedence<A.precedence?-1:y.precedence>A.precedence?1:y.kind==="predicate"&&A.kind==="predicate"?0:y.hash<A.hash?-1:1)},dX=(T)=>{let o={};for(let y of T)if(y.hasOpenIntersection())o[y.kind]=FT(o[y.kind],y);else{if(o[y.kind])return $T(`Unexpected intersection of closed refinements of kind ${y.kind}`);o[y.kind]=y}return o},H_=(...T)=>E(E_(...T)),E_=(T,o,y)=>{let A=y.hasKind("morph")?"a morph":y.isUnknown()?"unknown":y.exclude(o).defaultShortDescription;return`${r0(T)} operand must be ${o.description} (was ${A})`};var G_=(T,o,y)=>new Cy(T,o,y,y,null);class yf extends ho{}class Cy extends ho{[Ro]="generic";paramDefs;bodyDef;$;arg$;baseInstantiation;hkt;description;constructor(T,o,y,A,F){super((...f)=>{let S=l(this.names,($,_)=>{let J=this.arg$.parse(f[$]);if(!J.extends(this.constraints[$]))E(rX(_,this.constraints[$].expression,J.expression));return[_,J]});if(this.defIsLazy()){let $=this.bodyDef(S);return this.$.parse($)}return this.$.parse(o,{args:S})});this.paramDefs=T,this.bodyDef=o,this.$=y,this.arg$=A,this.hkt=F,this.description=F?new F().description??`a generic type for ${F.constructor.name}`:"a generic type",this.baseInstantiation=this(...this.constraints)}defIsLazy(){return this.bodyDef instanceof yf}cacheGetter(T,o){return Object.defineProperty(this,T,{value:o}),o}get json(){return this.cacheGetter("json",{params:this.params.map((T)=>T[1].isUnknown()?T[0]:[T[0],T[1].json]),body:S_(this.bodyDef)})}get params(){return this.cacheGetter("params",this.paramDefs.map((T)=>typeof T==="string"?[T,U.intrinsic.unknown]:[T[0],this.$.parse(T[1])]))}get names(){return this.cacheGetter("names",this.params.map((T)=>T[0]))}get constraints(){return this.cacheGetter("constraints",this.params.map((T)=>T[1]))}get internal(){return this}get referencesById(){return this.baseInstantiation.internal.referencesById}get references(){return this.baseInstantiation.internal.references}}var rX=(T,o,y)=>`${T} must be assignable to ${o} (was ${y})`;var w_={morph:"it represents a transformation, while JSON Schema only allows validation. Consider creating a Schema from one of its endpoints using `.in` or `.out`.",cyclic:"cyclic types are not yet convertible to JSON Schema. If this feature is important to you, please add your feedback at https://github.com/arktypeio/arktype/issues/1087"},U_=(T,o)=>{let y=`${T} is not convertible to JSON Schema`;if(o){let A=pT(o,w_)?w_[o]:o;y+=` because ${A}`}return y},JT={writeUnjsonifiableMessage:U_,UnjsonifiableError:class T extends Error{},throwUnjsonifiableError:(...T)=>$y(U_(...T)),throwInternalOperandError:(T,o)=>$T(`Unexpected JSON Schema input for ${T}: ${d(o)}`)};var lX=r({kind:"predicate",hasAssociatedError:!0,collapsibleKey:"predicate",keys:{predicate:{}},normalize:(T)=>typeof T==="function"?{predicate:T}:T,defaults:{description:(T)=>`valid according to ${T.predicate.name||"an anonymous predicate"}`},intersectionIsOpen:!0,intersections:{predicate:()=>null}});class K_ extends Bo{serializedPredicate=BT(this.predicate);compiledCondition=`${this.serializedPredicate}(data, ctx)`;compiledNegation=`!${this.compiledCondition}`;impliedBasis=null;expression=this.serializedPredicate;traverseAllows=this.predicate;errorContext={code:"predicate",description:this.description,meta:this.meta};compiledErrorContext=Vy(this.errorContext);traverseApply=(T,o)=>{if(!this.predicate(T,o.external)&&!o.hasError())o.errorFromNodeContext(this.errorContext)};compile(T){if(T.traversalKind==="Allows"){T.return(this.compiledCondition);return}T.if(`${this.compiledNegation} && !ctx.hasError()`,()=>T.line(`ctx.errorFromNodeContext(${this.compiledErrorContext})`))}reduceJsonSchema(){return JT.throwUnjsonifiableError(`Predicate ${this.expression}`)}}var dS={implementation:lX,Node:K_};var sX=r({kind:"divisor",collapsibleKey:"rule",keys:{rule:{parse:(T)=>Number.isInteger(T)?T:E(aX(T))}},normalize:(T)=>typeof T==="number"?{rule:T}:T,hasAssociatedError:!0,defaults:{description:(T)=>T.rule===1?"an integer":T.rule===2?"even":`a multiple of ${T.rule}`},intersections:{divisor:(T,o,y)=>y.$.node("divisor",{rule:Math.abs(T.rule*o.rule/eX(T.rule,o.rule))})},obviatesBasisDescription:!0});class z_ extends Wy{traverseAllows=(T)=>T%this.rule===0;compiledCondition=`data % ${this.rule} === 0`;compiledNegation=`data % ${this.rule} !== 0`;impliedBasis=U.intrinsic.number.internal;expression=`% ${this.rule}`;reduceJsonSchema(T){if(T.type="integer",this.rule===1)return T;return T.multipleOf=this.rule,T}}var rS={implementation:sX,Node:z_};var aX=(T)=>`divisor must be an integer (was ${T})`,eX=(T,o)=>{let y,A=T,F=o;while(F!==0)y=F,F=A%F,A=y;return A};class Vo extends Wy{boundOperandKind=A8[this.kind];compiledActual=this.boundOperandKind==="value"?"data":this.boundOperandKind==="length"?"data.length":"data.valueOf()";comparator=F8(this.kind,this.exclusive);numericLimit=this.rule.valueOf();expression=`${this.comparator} ${this.rule}`;compiledCondition=`${this.compiledActual} ${this.comparator} ${this.numericLimit}`;compiledNegation=`${this.compiledActual} ${T8[this.comparator]} ${this.numericLimit}`;stringLimit=this.boundOperandKind==="date"?f8(this.numericLimit):`${this.numericLimit}`;limitKind=this.comparator["0"]==="<"?"upper":"lower";isStricterThan(T){return(this.limitKind==="upper"?this.numericLimit<T.numericLimit:this.numericLimit>T.numericLimit)||this.numericLimit===T.numericLimit&&this.exclusive===!0&&!T.exclusive}overlapsRange(T){if(this.isStricterThan(T))return!1;if(this.numericLimit===T.numericLimit&&(this.exclusive||T.exclusive))return!1;return!0}overlapIsUnit(T){return this.numericLimit===T.numericLimit&&!this.exclusive&&!T.exclusive}}var T8={"<":">=","<=":">",">":"<=",">=":"<"},o8={min:"max",minLength:"maxLength",after:"before"},Af={parse:(T)=>T||void 0},Ff=(T)=>(o)=>{if(typeof o==="number")return{rule:o};let{exclusive:y,...A}=o;return y?{...A,rule:T==="minLength"?A.rule+1:A.rule-1}:A},ff=(T)=>(o)=>{if(typeof o==="number"||typeof o==="string"||o instanceof Date)return{rule:o};let{exclusive:y,...A}=o;if(!y)return A;let F=typeof A.rule==="number"?A.rule:typeof A.rule==="string"?new Date(A.rule).valueOf():A.rule.valueOf();return y?{...A,rule:T==="after"?F+1:F-1}:A},Sf=(T)=>typeof T==="string"||typeof T==="number"?new Date(T):T,y8=(T,o)=>`${T} bound must be a positive integer (was ${o})`,WA=(T)=>(o)=>{if(!Number.isInteger(o)||o<0)E(y8(T,o));return o},A8={min:"value",max:"value",minLength:"length",maxLength:"length",after:"date",before:"date"},F8=(T,o)=>`${pT(T,o8)?">":"<"}${o?"":"="}`,f8=(T)=>typeof T==="string"?T:new Date(T).toLocaleString(),Q_=(T)=>`Bounded expression ${T} must be exactly one of number, string, Array, or Date`;var S8=r({kind:"after",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:Sf,serialize:(T)=>T.toISOString()}},normalize:ff("after"),defaults:{description:(T)=>`${T.collapsibleLimitString} or later`,actual:qy},intersections:{after:(T,o)=>T.isStricterThan(o)?T:o}});class V_ extends Vo{impliedBasis=U.intrinsic.Date.internal;collapsibleLimitString=qy(this.rule);traverseAllows=(T)=>T>=this.rule;reduceJsonSchema(){return JT.throwUnjsonifiableError("Date instance")}}var lS={implementation:S8,Node:V_};var $8=r({kind:"before",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:Sf,serialize:(T)=>T.toISOString()}},normalize:ff("before"),defaults:{description:(T)=>`${T.collapsibleLimitString} or earlier`,actual:qy},intersections:{before:(T,o)=>T.isStricterThan(o)?T:o,after:(T,o,y)=>T.overlapsRange(o)?T.overlapIsUnit(o)?y.$.node("unit",{unit:T.rule}):null:k.init("range",T,o)}});class D_ extends Vo{collapsibleLimitString=qy(this.rule);traverseAllows=(T)=>T<=this.rule;impliedBasis=U.intrinsic.Date.internal;reduceJsonSchema(){return JT.throwUnjsonifiableError("Date instance")}}var sS={implementation:$8,Node:D_};var J8=r({kind:"exactLength",collapsibleKey:"rule",keys:{rule:{parse:WA("exactLength")}},normalize:(T)=>typeof T==="number"?{rule:T}:T,hasAssociatedError:!0,defaults:{description:(T)=>`exactly length ${T.rule}`,actual:(T)=>`${T.length}`},intersections:{exactLength:(T,o,y)=>k.init("unit",y.$.node("unit",{unit:T.rule}),y.$.node("unit",{unit:o.rule}),{path:["length"]}),minLength:(T,o)=>T.rule>=o.rule?T:k.init("range",T,o),maxLength:(T,o)=>T.rule<=o.rule?T:k.init("range",T,o)}});class C_ extends Wy{traverseAllows=(T)=>T.length===this.rule;compiledCondition=`data.length === ${this.rule}`;compiledNegation=`data.length !== ${this.rule}`;impliedBasis=U.intrinsic.lengthBoundable.internal;expression=`== ${this.rule}`;reduceJsonSchema(T){switch(T.type){case"string":return T.minLength=this.rule,T.maxLength=this.rule,T;case"array":return T.minItems=this.rule,T.maxItems=this.rule,T;default:return JT.throwInternalOperandError("exactLength",T)}}}var aS={implementation:J8,Node:C_};var _8=r({kind:"max",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{},exclusive:Af},normalize:(T)=>typeof T==="number"?{rule:T}:T,defaults:{description:(T)=>{if(T.rule===0)return T.exclusive?"negative":"non-positive";return`${T.exclusive?"less than":"at most"} ${T.rule}`}},intersections:{max:(T,o)=>T.isStricterThan(o)?T:o,min:(T,o,y)=>T.overlapsRange(o)?T.overlapIsUnit(o)?y.$.node("unit",{unit:T.rule}):null:k.init("range",T,o)},obviatesBasisDescription:!0});class L_ extends Vo{impliedBasis=U.intrinsic.number.internal;traverseAllows=this.exclusive?(T)=>T<this.rule:(T)=>T<=this.rule;reduceJsonSchema(T){if(this.exclusive)T.exclusiveMaximum=this.rule;else T.maximum=this.rule;return T}}var eS={implementation:_8,Node:L_};var R8=r({kind:"maxLength",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:WA("maxLength")}},reduce:(T,o)=>T.rule===0?o.node("exactLength",T):void 0,normalize:Ff("maxLength"),defaults:{description:(T)=>`at most length ${T.rule}`,actual:(T)=>`${T.length}`},intersections:{maxLength:(T,o)=>T.isStricterThan(o)?T:o,minLength:(T,o,y)=>T.overlapsRange(o)?T.overlapIsUnit(o)?y.$.node("exactLength",{rule:T.rule}):null:k.init("range",T,o)}});class I_ extends Vo{impliedBasis=U.intrinsic.lengthBoundable.internal;traverseAllows=(T)=>T.length<=this.rule;reduceJsonSchema(T){switch(T.type){case"string":return T.maxLength=this.rule,T;case"array":return T.maxItems=this.rule,T;default:return JT.throwInternalOperandError("maxLength",T)}}}var T$={implementation:R8,Node:I_};var W8=r({kind:"min",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{},exclusive:Af},normalize:(T)=>typeof T==="number"?{rule:T}:T,defaults:{description:(T)=>{if(T.rule===0)return T.exclusive?"positive":"non-negative";return`${T.exclusive?"more than":"at least"} ${T.rule}`}},intersections:{min:(T,o)=>T.isStricterThan(o)?T:o},obviatesBasisDescription:!0});class k_ extends Vo{impliedBasis=U.intrinsic.number.internal;traverseAllows=this.exclusive?(T)=>T>this.rule:(T)=>T>=this.rule;reduceJsonSchema(T){if(this.exclusive)T.exclusiveMinimum=this.rule;else T.minimum=this.rule;return T}}var o$={implementation:W8,Node:k_};var O8=r({kind:"minLength",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:WA("minLength")}},reduce:(T)=>T.rule===0?U.intrinsic.unknown:void 0,normalize:Ff("minLength"),defaults:{description:(T)=>T.rule===1?"non-empty":`at least length ${T.rule}`,actual:(T)=>T.length===0?"":`${T.length}`},intersections:{minLength:(T,o)=>T.isStricterThan(o)?T:o}});class B_ extends Vo{impliedBasis=U.intrinsic.lengthBoundable.internal;traverseAllows=(T)=>T.length>=this.rule;reduceJsonSchema(T){switch(T.type){case"string":return T.minLength=this.rule,T;case"array":return T.minItems=this.rule,T;default:return JT.throwInternalOperandError("minLength",T)}}}var y$={implementation:O8,Node:B_};var N_={min:o$.implementation,max:eS.implementation,minLength:y$.implementation,maxLength:T$.implementation,exactLength:aS.implementation,after:lS.implementation,before:sS.implementation},t_={min:o$.Node,max:eS.Node,minLength:y$.Node,maxLength:T$.Node,exactLength:aS.Node,after:lS.Node,before:sS.Node};var M8=r({kind:"pattern",collapsibleKey:"rule",keys:{rule:{},flags:{}},normalize:(T)=>typeof T==="string"?{rule:T}:T instanceof RegExp?T.flags?{rule:T.source,flags:T.flags}:{rule:T.source}:T,obviatesBasisDescription:!0,obviatesBasisExpression:!0,hasAssociatedError:!0,intersectionIsOpen:!0,defaults:{description:(T)=>`matched by ${T.rule}`},intersections:{pattern:()=>null}});class p_ extends Wy{instance=new RegExp(this.rule,this.flags);expression=`${this.instance}`;traverseAllows=this.instance.test.bind(this.instance);compiledCondition=`${this.expression}.test(data)`;compiledNegation=`!${this.compiledCondition}`;impliedBasis=U.intrinsic.string.internal;reduceJsonSchema(T){if(T.pattern)return JT.throwUnjsonifiableError(`Intersection of patterns ${T.pattern} & ${this.rule}`);return T.pattern=this.rule,T}}var A$={implementation:M8,Node:p_};var oF=(T,o)=>{let y=X8(T);if(o&&!o.includes(y))return E(`Root of kind ${y} should be one of ${o}`);return y},X8=(T)=>{if(q(T,"root"))return T.kind;if(typeof T==="string")return T[0]==="$"?"alias":(T in Zo)?"domain":"proto";if(typeof T==="function")return"proto";if(typeof T!=="object"||T===null)return E(b_(T));if("morphs"in T)return"morph";if("branches"in T||ET(T))return"union";if("unit"in T)return"unit";if("reference"in T)return"alias";let o=Object.keys(T);if(o.length===0||o.some((y)=>(y in Tf)))return"intersection";if("proto"in T)return"proto";if("domain"in T)return"domain";return E(b_(T))},b_=(T)=>`${d(T)} is not a valid type schema`,x_={},Y8=(T)=>ET(T)?T.map((o)=>o.collapsibleJson):T.collapsibleJson,Wo={};U.nodesByRegisteredId=Wo;var F$=(T)=>{return x_[T]??=0,`${T}${++x_[T]}`},f$=(T)=>{let o=OA[T.kind],y=o.applyConfig?.(T.def,T.$.resolvedConfig)??T.def,A={},{meta:F,...f}=y,S=F===void 0?{}:typeof F==="string"?{description:F}:F,$=IS(f).sort(([J],[R])=>SA(J)?SA(R)?$A(J)-$A(R):1:SA(R)?-1:J<R?-1:1).filter(([J,R])=>{if(J.startsWith("meta.")){let M=J.slice(5);return S[M]=R,!1}return!0});for(let J of $){let R=J[0],M=o.keys[R];if(!M)return E(`Key ${R} is not valid on ${T.kind} schema`);let Y=M.parse?M.parse(J[1],T):J[1];if(Y!==Qo&&(Y!==void 0||M.preserveUndefined))A[R]=Y}if(o.reduce&&!T.prereduced){let J=o.reduce(A,T.$);if(J){if(J instanceof k)return J.throw();return Z8(J,S)}}return S$({id:T.id,kind:T.kind,inner:A,meta:S,$:T.$})},S$=({id:T,kind:o,inner:y,meta:A,$:F,ignoreCache:f})=>{let S=OA[o],$=IS(y),_=[],J={};if($.forEach(([t,m])=>{let h=S.keys[t],K=h.serialize??(h.child?Y8:ko);if(J[t]=K(m),h.child===!0){let V=m;if(ET(V))_.push(...V);else _.push(V)}else if(typeof h.child==="function")_.push(...h.child(m))}),S.finalizeInnerJson)J=S.finalizeInnerJson(J);let R={...J},M={};if(!ao(A))M=l(A,(t,m)=>[t,t==="examples"?m:ko(m)]),R.meta=$f(M,"description",!0);J=$f(J,S.collapsibleKey,!1);let Y=JSON.stringify({kind:o,...J});R=$f(R,S.collapsibleKey,!1);let H=$f(R,S.collapsibleKey,!0),Q=JSON.stringify({kind:o,...R});if(F.nodesByHash[Q]&&!f)return F.nodesByHash[Q];let w={id:T,kind:o,impl:S,inner:y,innerEntries:$,innerJson:J,innerHash:Y,meta:A,metaJson:M,json:R,hash:Q,collapsibleJson:H,children:_};if(o!=="intersection"){for(let t in y)if(t!=="in"&&t!=="out")w[t]=y[t]}let B=new m_[o](w,F);return F.nodesByHash[Q]=B},j_=(T,o)=>{if(T.id===o)return T;if(zT(Wo[o]))$T(`Unexpected attempt to overwrite node id ${o}`);return S$({id:o,kind:T.kind,inner:T.inner,meta:T.meta,$:T.$,ignoreCache:!0})},Z8=(T,o,y)=>{if(y&&zT(Wo[y]))$T(`Unexpected attempt to overwrite node id ${y}`);return S$({id:y??F$(o.alias??T.kind),kind:T.kind,inner:T.inner,meta:o,$:T.$})},$f=(T,o,y)=>{let A=Object.keys(T);if(A.length===1&&A[0]===o){let F=T[o];if(y)return F;if(Yo(F,"object")&&(Object.keys(F).length===1||Array.isArray(F)))return F}return T};var yF=(T,o,y)=>{if(T.key!==o.key)return null;let A=T.key,F=QT(T.value,o.value,y),f=T.required||o.required?"required":"optional";if(F instanceof k)if(f==="optional")F=U.intrinsic.never.internal;else return F.withPrefixKey(T.key,T.required&&o.required?"required":"optional");if(f==="required")return y.$.node("required",{key:A,value:F});let S=T.hasDefault()?o.hasDefault()?T.default===o.default?T.default:E($$(T.default,o.default)):T.default:o.hasDefault()?o.default:Qo;return y.$.node("optional",{key:A,value:F,default:S})};class AF extends Bo{required=this.kind==="required";optional=this.kind==="optional";impliedBasis=U.intrinsic.object.internal;serializedKey=Ry(this.key);compiledKey=typeof this.key==="string"?this.key:this.serializedKey;flatRefs=FT(this.value.flatRefs.map((T)=>go([this.key,...T.path],T.node)),go([this.key],this.value));_transform(T,o){o.path.push(this.key);let y=super._transform(T,o);return o.path.pop(),y}hasDefault(){return"default"in this.inner}traverseAllows=(T,o)=>{if(this.key in T)return Eo(this.key,()=>this.value.traverseAllows(T[this.key],o),o);return this.optional};traverseApply=(T,o)=>{if(this.key in T)Eo(this.key,()=>this.value.traverseApply(T[this.key],o),o);else if(this.hasKind("required"))o.errorFromNodeContext(this.errorContext)};compile(T){if(T.if(`${this.serializedKey} in data`,()=>T.traverseKey(this.serializedKey,`data${T.prop(this.key)}`,this.value)),this.hasKind("required"))T.else(()=>{if(T.traversalKind==="Apply")return T.line(`ctx.errorFromNodeContext(${this.compiledErrorContext})`);else return T.return(!1)});if(T.traversalKind==="Allows")T.return(!0)}}var $$=(T,o)=>`Invalid intersection of default values ${d(T)} & ${d(o)}`;var H8=r({kind:"optional",hasAssociatedError:!1,intersectionIsOpen:!0,keys:{key:{},value:{child:!0,parse:(T,o)=>o.$.parseSchema(T)},default:{preserveUndefined:!0}},normalize:(T)=>T,reduce:(T,o)=>{if(o.resolvedConfig.exactOptionalPropertyTypes===!1){if(!T.value.allows(void 0))return o.node("optional",{...T,value:T.value.or(g.undefined)},{prereduced:!0})}},defaults:{description:(T)=>`${T.compiledKey}?: ${T.value.description}`},intersections:{optional:yF}});class q_ extends AF{constructor(...T){super(...T);if("default"in this.inner)fF(this.value,this.inner.default,this.key)}get outProp(){if(!this.hasDefault())return this;let{default:T,...o}=this.inner;return this.cacheGetter("outProp",this.$.node("required",o,{prereduced:!0}))}expression=this.hasDefault()?`${this.compiledKey}: ${this.value.expression} = ${d(this.inner.default)}`:`${this.compiledKey}?: ${this.value.expression}`;defaultValueMorph=G8(this);defaultValueMorphRef=this.defaultValueMorph&&BT(this.defaultValueMorph)}var FF={implementation:H8,Node:q_},E8={},G8=(T)=>{if(!T.hasDefault())return;let o=`{${T.compiledKey}: ${T.value.id} = ${ko(T.default)}}`;return E8[o]??=J$(T.key,T.value,T.default)},J$=(T,o,y)=>{if(typeof y==="function")return o.includesTransform?(F,f)=>{return Eo(T,()=>o(F[T]=y(),f),f),F}:(F)=>{return F[T]=y(),F};let A=o.includesTransform?o.assert(y):y;return Yo(A,"object")?(F,f)=>{return Eo(T,()=>o(F[T]=y,f),f),F}:(F)=>{return F[T]=A,F}},fF=(T,o,y)=>{let A=zy(o);if(Yo(o,"object")&&!A)E(w8(y));let F=T.in(A?o():o);if(F instanceof Ho){if(y===null)E(`Default ${F.summary}`);let f=F.transform((S)=>S.transform(($)=>({...$,prefixPath:[y]})));E(`Default for ${f.summary}`)}return o},w8=(T)=>{return`Non-primitive default ${T===null?"":typeof T==="number"?`for value at [${T}] `:`for ${Ry(T)} `}must be specified as a function like () => ({my: 'object'})`};class No extends eA{constructor(T,o){super(T,o);Object.defineProperty(this,Ro,{value:"root",enumerable:!1})}get internal(){return this}get "~standard"(){return{vendor:"arktype",version:1,validate:(T)=>{let o=this(T);if(o instanceof Ho)return o;return{value:o}}}}as(){return this}brand(T){if(T==="")return E(U8);return this}readonly(){return this}branches=this.hasKind("union")?this.inner.branches:[this];distribute(T,o){let y=this.branches.map(T);return o?.(y)??y}get shortDescription(){return this.meta.description??this.defaultShortDescription}toJsonSchema(T={}){let o={dialect:"https://json-schema.org/draft/2020-12/schema",...T},y=this.toJsonSchemaRecurse(o);if(typeof o.dialect==="string")y.$schema=o.dialect;return y}toJsonSchemaRecurse(T){let o=this.innerToJsonSchema(T);return Object.assign(o,this.metaJson)}intersect(T){let o=this.$.parseDefinition(T),y=this.rawIntersect(o);if(y instanceof k)return y;return this.$.finalize(y)}rawIntersect(T){return Go(this,T,this.$)}toNeverIfDisjoint(){return this}and(T){let o=this.intersect(T);return o instanceof k?o.throw():o}rawAnd(T){let o=this.rawIntersect(T);return o instanceof k?o.throw():o}or(T){let o=this.$.parseDefinition(T);return this.$.finalize(this.rawOr(o))}rawOr(T){let o=[...this.branches,...T.branches];return this.$.node("union",o)}map(T){return this.$.schema(this.applyStructuralOperation("map",[T]))}pick(...T){return this.$.schema(this.applyStructuralOperation("pick",T))}omit(...T){return this.$.schema(this.applyStructuralOperation("omit",T))}required(){return this.$.schema(this.applyStructuralOperation("required",[]))}partial(){return this.$.schema(this.applyStructuralOperation("partial",[]))}_keyof;keyof(){if(this._keyof)return this._keyof;let T=this.applyStructuralOperation("keyof",[]).reduce((o,y)=>o.intersect(y).toNeverIfDisjoint(),U.intrinsic.unknown.internal);if(T.branches.length===0)E(iS(`keyof ${this.expression}`));return this._keyof=this.$.finalize(T)}get props(){if(this.branches.length!==1)return E(K8(this.expression));return[...this.applyStructuralOperation("props",[])[0]]}merge(T){let o=this.$.parseDefinition(T);return this.$.schema(o.distribute((y)=>this.applyStructuralOperation("merge",[v_(y)??E(P_("merge",y.expression))])))}applyStructuralOperation(T,o){return this.distribute((y)=>{if(y.equals(U.intrinsic.object)&&T!=="merge")return y;let A=v_(y);if(!A)E(P_(T,y.expression));if(T==="keyof")return A.keyof();if(T==="get")return A.get(...o);if(T==="props")return A.props;let F=T==="required"?"require":T==="partial"?"optionalize":T;return this.$.node("intersection",{...y.inner,structure:A[F](...o)})})}get(...T){if(T[0]===void 0)return this;return this.$.schema(this.applyStructuralOperation("get",T))}extract(T){let o=this.$.parseDefinition(T);return this.$.schema(this.branches.filter((y)=>y.extends(o)))}exclude(T){let o=this.$.parseDefinition(T);return this.$.schema(this.branches.filter((y)=>!y.extends(o)))}array(){return this.$.schema(this.isUnknown()?{proto:Array}:{proto:Array,sequence:this},{prereduced:!0})}overlaps(T){return!(this.intersect(T)instanceof k)}extends(T){let o=this.intersect(T);return!(o instanceof k)&&this.equals(o)}ifExtends(T){return this.extends(T)?this:void 0}subsumes(T){return this.$.parseDefinition(T).extends(this)}configure(T,o="shallow"){return this.configureReferences(T,o)}describe(T,o="shallow"){return this.configure({description:T},o)}optional(){return[this,"?"]}default(T){return fF(this,T,null),[this,"=",T]}from(T){return this.assert(T)}_pipe(...T){let o=T.reduce((y,A)=>y.rawPipeOnce(A),this);return this.$.finalize(o)}tryPipe(...T){let o=T.reduce((y,A)=>y.rawPipeOnce(q(A,"root")?A:(F,f)=>{try{return A(F,f)}catch(S){return f.error({code:"predicate",predicate:A,actual:`aborted due to error:
|
|
19
|
+
${S}
|
|
20
|
+
`})}}),this);return this.$.finalize(o)}pipe=Object.assign(this._pipe.bind(this),{try:this.tryPipe.bind(this)});to(T){return this.$.finalize(this.toNode(this.$.parseDefinition(T)))}toNode(T){let o=TF(this,T,this.$);if(o instanceof k)return o.throw();return o}rawPipeOnce(T){if(q(T,"root"))return this.toNode(T);return this.distribute((o)=>o.hasKind("morph")?this.$.node("morph",{in:o.inner.in,morphs:[...o.morphs,T]}):this.$.node("morph",{in:o,morphs:[T]}),this.$.parseSchema)}narrow(T){return this.constrainOut("predicate",T)}constrain(T,o){return this._constrain("root",T,o)}constrainIn(T,o){return this._constrain("in",T,o)}constrainOut(T,o){return this._constrain("out",T,o)}_constrain(T,o,y){let A=this.$.node(o,y);if(A.isRoot())return A.isUnknown()?this:$T(`Unexpected constraint node ${A}`);let F=T==="root"?this:this[T];if(F.hasKind("morph")||A.impliedBasis&&!F.extends(A.impliedBasis))return H_(o,A.impliedBasis,this);let f=this.$.node("intersection",{[A.kind]:A}),S=T==="out"?TF(this,f,this.$):Go(this,f,this.$);if(S instanceof k)S.throw();return this.$.finalize(S)}onUndeclaredKey(T){let o=typeof T==="string"?T:T.rule,y=typeof T==="string"?!1:T.deep;return this.$.finalize(this.transform((A,F)=>A==="structure"?o==="ignore"?m0(F,{undeclared:1}):{...F,undeclared:o}:F,y?void 0:{shouldTransform:(A)=>!Fy(FA,A.kind)}))}hasEqualMorphs(T){if(!this.includesTransform&&!T.includesTransform)return!0;if(!Sy(this.shallowMorphs,T.shallowMorphs))return!1;if(!Sy(this.flatMorphs,T.flatMorphs,{isEqual:(o,y)=>o.propString===y.propString&&(o.node.hasKind("morph")&&y.node.hasKind("morph")?o.node.hasEqualMorphs(y.node):o.node.hasKind("intersection")&&y.node.hasKind("intersection")?o.node.structure?.structuralMorphRef===y.node.structure?.structuralMorphRef:!1)}))return!1;return!0}onDeepUndeclaredKey(T){return this.onUndeclaredKey({rule:T,deep:!0})}filter(T){return this.constrainIn("predicate",T)}divisibleBy(T){return this.constrain("divisor",T)}matching(T){return this.constrain("pattern",T)}atLeast(T){return this.constrain("min",T)}atMost(T){return this.constrain("max",T)}moreThan(T){return this.constrain("min",MA(T))}lessThan(T){return this.constrain("max",MA(T))}atLeastLength(T){return this.constrain("minLength",T)}atMostLength(T){return this.constrain("maxLength",T)}moreThanLength(T){return this.constrain("minLength",MA(T))}lessThanLength(T){return this.constrain("maxLength",MA(T))}exactlyLength(T){return this.constrain("exactLength",T)}atOrAfter(T){return this.constrain("after",T)}atOrBefore(T){return this.constrain("before",T)}laterThan(T){return this.constrain("after",MA(T))}earlierThan(T){return this.constrain("before",MA(T))}}var U8="Expected a non-empty brand name after #",MA=(T)=>typeof T==="object"&&!(T instanceof Date)?{...T,exclusive:!0}:{rule:T,exclusive:!0},SF=(T,o)=>q(o,"root")?q(T,"root")?T.extends(o):o.allows(T):q(T,"root")?T.hasUnit(o):o===T,v_=(T)=>{if(T.hasKind("morph"))return null;if(T.hasKind("intersection"))return T.inner.structure??(T.basis?.domain==="object"?T.$.bindReference(U.intrinsic.emptyStructure):null);if(T.isBasis()&&T.domain==="object")return T.$.bindReference(U.intrinsic.emptyStructure);return null},K8=(T)=>`Props cannot be extracted from a union. Use .distribute to extract props from each branch instead. Received:
|
|
21
|
+
${T}`,P_=(T,o)=>`${T} operand must be an object (was ${o})`;var eo=(T,o)=>l(of(T),(y,A)=>[A,o]);var z8=(T)=>typeof T==="string"?{reference:T}:T,h_=(T)=>T instanceof k?U.intrinsic.never.internal:T,Q8=r({kind:"alias",hasAssociatedError:!1,collapsibleKey:"reference",keys:{reference:{serialize:(T)=>T.startsWith("$")?T:`$ark.${T}`},resolve:{}},normalize:z8,defaults:{description:(T)=>T.reference},intersections:{alias:(T,o,y)=>y.$.lazilyResolve(()=>h_(QT(T.resolution,o.resolution,y)),`${T.reference}${y.pipe?"=>":"&"}${o.reference}`),...eo("alias",(T,o,y)=>{if(o.isUnknown())return T;if(o.isNever())return o;if(o.isBasis()&&!o.overlaps(U.intrinsic.object))return k.init("assignability",U.intrinsic.object,o);return y.$.lazilyResolve(()=>h_(QT(T.resolution,o,y)),`${T.reference}${y.pipe?"=>":"&"}${o.id}`)})}});class n_ extends No{expression=this.reference;structure=void 0;get resolution(){let T=this._resolve();return Wo[this.id]=T}_resolve(){if(this.resolve)return this.resolve();if(this.reference[0]==="$")return this.$.resolveRoot(this.reference.slice(1));let T=this.reference,o=Wo[T],y=[];while(q(o,"context")){if(y.includes(o.id))return E(V8(o.id,y));y.push(o.id),o=Wo[o.id]}if(!q(o,"root"))return $T(`Unexpected resolution for reference ${this.reference}
|
|
22
|
+
Seen: [${y.join("->")}]
|
|
23
|
+
Resolution: ${d(o)}`);return o}get resolutionId(){if(this.reference.includes("&")||this.reference.includes("=>"))return this.resolution.id;if(this.reference[0]!=="$")return this.reference;let T=this.reference.slice(1),o=this.$.resolutions[T];if(typeof o==="string")return o;if(q(o,"root"))return o.id;return $T(`Unexpected resolution for reference ${this.reference}: ${d(o)}`)}get defaultShortDescription(){return Zo.object}innerToJsonSchema(T){return JT.throwUnjsonifiableError(this.expression,"cyclic")}traverseAllows=(T,o)=>{let y=o.seen[this.reference];if(y?.includes(T))return!0;return o.seen[this.reference]=FT(y,T),this.resolution.traverseAllows(T,o)};traverseApply=(T,o)=>{let y=o.seen[this.reference];if(y?.includes(T))return;o.seen[this.reference]=FT(y,T),this.resolution.traverseApply(T,o)};compile(T){let o=this.resolutionId;T.if(`ctx.seen.${o} && ctx.seen.${o}.includes(data)`,()=>T.return(!0)),T.if(`!ctx.seen.${o}`,()=>T.line(`ctx.seen.${o} = []`)),T.line(`ctx.seen.${o}.push(data)`),T.return(T.invoke(o))}}var V8=(T,o)=>`Alias '${T}' has a shallow resolution cycle: ${[...o,T].join("->")}`,$F={implementation:Q8,Node:n_};class vy extends No{traverseApply=(T,o)=>{if(!this.traverseAllows(T,o))o.errorFromNodeContext(this.errorContext)};get errorContext(){return{code:this.kind,description:this.description,meta:this.meta,...this.inner}}get compiledErrorContext(){return Vy(this.errorContext)}compile(T){if(T.traversalKind==="Allows")T.return(this.compiledCondition);else T.if(this.compiledNegation,()=>T.line(`${T.ctx}.errorFromNodeContext(${this.compiledErrorContext})`))}}var D8=r({kind:"domain",hasAssociatedError:!0,collapsibleKey:"domain",keys:{domain:{},numberAllowsNaN:{}},normalize:(T)=>typeof T==="string"?{domain:T}:yA(T,"numberAllowsNaN")&&T.domain!=="number"?E(Jf.writeBadAllowNanMessage(T.domain)):T,applyConfig:(T,o)=>T.numberAllowsNaN===void 0&&T.domain==="number"&&o.numberAllowsNaN?{...T,numberAllowsNaN:!0}:T,defaults:{description:(T)=>Zo[T.domain],actual:(T)=>Number.isNaN(T)?"NaN":Zo[hT(T)]},intersections:{domain:(T,o)=>T.domain==="number"&&o.domain==="number"?T.numberAllowsNaN?o:T:k.init("domain",T,o)}});class g_ extends vy{requiresNaNCheck=this.domain==="number"&&!this.numberAllowsNaN;traverseAllows=this.requiresNaNCheck?(T)=>typeof T==="number"&&!Number.isNaN(T):(T)=>hT(T)===this.domain;compiledCondition=this.domain==="object"?'((typeof data === "object" && data !== null) || typeof data === "function")':`typeof data === "${this.domain}"${this.requiresNaNCheck?" && !Number.isNaN(data)":""}`;compiledNegation=this.domain==="object"?'((typeof data !== "object" || data === null) && typeof data !== "function")':`typeof data !== "${this.domain}"${this.requiresNaNCheck?" || Number.isNaN(data)":""}`;expression=this.numberAllowsNaN?"number | NaN":this.domain;get nestableExpression(){return this.numberAllowsNaN?`(${this.expression})`:this.expression}get defaultShortDescription(){return Zo[this.domain]}innerToJsonSchema(T){if(this.domain==="bigint"||this.domain==="symbol")return JT.throwUnjsonifiableError(this.domain);return{type:this.domain}}}var Jf={implementation:D8,Node:g_,writeBadAllowNanMessage:(T)=>`numberAllowsNaN may only be specified with domain "number" (was ${T})`};var C8=r({kind:"intersection",hasAssociatedError:!0,normalize:(T)=>{if(zT(T))return T;let{structure:o,...y}=T,A=!!o,F=o??{},f=l(y,(S,$)=>{if(pT(S,W_)){if(A)E(`Flattened structure key ${S} cannot be specified alongside a root 'structure' key.`);return F[S]=$,[]}return[S,$]});if(q(F,"constraint")||!ao(F))f.structure=F;return f},finalizeInnerJson:({structure:T,...o})=>Yo(T,"object")?{...T,...o}:o,keys:{domain:{child:!0,parse:(T,o)=>o.$.node("domain",T)},proto:{child:!0,parse:(T,o)=>o.$.node("proto",T)},structure:{child:!0,parse:(T,o)=>o.$.node("structure",T),serialize:(T)=>{if(!T.sequence?.minLength)return T.collapsibleJson;let{sequence:o,...y}=T.collapsibleJson,{minVariadicLength:A,...F}=o,f=F.variadic&&Object.keys(F).length===1?F.variadic:F;return{...y,sequence:f}}},divisor:{child:!0,parse:So("divisor")},max:{child:!0,parse:So("max")},min:{child:!0,parse:So("min")},maxLength:{child:!0,parse:So("maxLength")},minLength:{child:!0,parse:So("minLength")},exactLength:{child:!0,parse:So("exactLength")},before:{child:!0,parse:So("before")},after:{child:!0,parse:So("after")},pattern:{child:!0,parse:So("pattern")},predicate:{child:!0,parse:So("predicate")}},reduce:(T,o)=>u_({},T,{$:o,invert:!1,pipe:!1}),defaults:{description:(T)=>{if(T.children.length===0)return"unknown";if(T.structure)return T.structure.description;let o=[];if(T.basis&&!T.refinements.some((y)=>y.impl.obviatesBasisDescription))o.push(T.basis.description);if(T.refinements.length){let y=T.refinements.toSorted((A,F)=>A.kind==="min"&&F.kind==="max"?-1:0).map((A)=>A.description);o.push(...y)}if(T.inner.predicate)o.push(...T.inner.predicate.map((y)=>y.description));return o.join(" and ")},expected:(T)=>` \u25E6 ${T.errors.map((o)=>o.expected).join(`
|
|
24
|
+
\u25E6 `)}`,problem:(T)=>`(${T.actual}) must be...
|
|
25
|
+
${T.expected}`},intersections:{intersection:(T,o,y)=>u_(T.inner,o.inner,y),...eo("intersection",(T,o,y)=>{if(T.children.length===0)return o;let{domain:A,proto:F,...f}=T.inner,S=F??A,$=S?QT(S,o,y):o;return $ instanceof k?$:T?.basis?.equals($)?T:T.$.node("intersection",{...f,[$.kind]:$},{prereduced:!0})})}});class i_ extends No{basis=this.inner.domain??this.inner.proto??null;refinements=this.children.filter((T)=>T.isRefinement());structure=this.inner.structure;expression=L8(this);get shallowMorphs(){return this.inner.structure?.structuralMorph?[this.inner.structure.structuralMorph]:[]}get defaultShortDescription(){return this.basis?.defaultShortDescription??"present"}innerToJsonSchema(T){return this.children.reduce((o,y)=>y.isBasis()?y.toJsonSchemaRecurse(T):y.reduceJsonSchema(o,T),{})}traverseAllows=(T,o)=>this.children.every((y)=>y.traverseAllows(T,o));traverseApply=(T,o)=>{let y=o.currentErrorCount;if(this.basis){if(this.basis.traverseApply(T,o),o.currentErrorCount>y)return}if(this.refinements.length){for(let A=0;A<this.refinements.length-1;A++)if(this.refinements[A].traverseApply(T,o),o.failFast&&o.currentErrorCount>y)return;if(this.refinements.at(-1).traverseApply(T,o),o.currentErrorCount>y)return}if(this.structure){if(this.structure.traverseApply(T,o),o.currentErrorCount>y)return}if(this.inner.predicate){for(let A=0;A<this.inner.predicate.length-1;A++)if(this.inner.predicate[A].traverseApply(T,o),o.failFast&&o.currentErrorCount>y)return;this.inner.predicate.at(-1).traverseApply(T,o)}};compile(T){if(T.traversalKind==="Allows"){this.children.forEach((o)=>T.check(o)),T.return(!0);return}if(T.initializeErrorCount(),this.basis){if(T.check(this.basis),this.children.length>1)T.returnIfFail()}if(this.refinements.length){for(let o=0;o<this.refinements.length-1;o++)T.check(this.refinements[o]),T.returnIfFailFast();if(T.check(this.refinements.at(-1)),this.structure||this.inner.predicate)T.returnIfFail()}if(this.structure){if(T.check(this.structure),this.inner.predicate)T.returnIfFail()}if(this.inner.predicate){for(let o=0;o<this.inner.predicate.length-1;o++)T.check(this.inner.predicate[o]),T.returnIfFail();T.check(this.inner.predicate.at(-1))}}}var _$={implementation:C8,Node:i_},L8=(T)=>{let o=T.structure?.expression||`${T.basis&&!T.refinements.some((y)=>y.impl.obviatesBasisExpression)?T.basis.nestableExpression+" ":""}${T.refinements.map((y)=>y.expression).join(" & ")}`||"unknown";if(o==="Array == 0")o="[]";return o},u_=(T,o,y)=>{let A={},F=T.proto??T.domain,f=o.proto??o.domain,S=F?f?QT(F,f,y):F:f;if(S instanceof k)return S;if(S)A[S.kind]=S;return _A({kind:"intersection",baseInner:A,l:RA(T),r:RA(o),roots:[],ctx:y})};var I8=r({kind:"morph",hasAssociatedError:!1,keys:{in:{child:!0,parse:(T,o)=>o.$.parseSchema(T)},morphs:{parse:Ky,serialize:(T)=>T.map((o)=>q(o,"root")?o.json:BT(o))},declaredIn:{child:!1,serialize:(T)=>T.json},declaredOut:{child:!1,serialize:(T)=>T.json}},normalize:(T)=>T,defaults:{description:(T)=>`a morph from ${T.in.description} to ${T.out?.description??"unknown"}`},intersections:{morph:(T,o,y)=>{if(!T.hasEqualMorphs(o))return E(k8(T.expression,o.expression));let A=QT(T.in,o.in,y);if(A instanceof k)return A;let F={morphs:T.morphs};if(T.declaredIn||o.declaredIn){let f=QT(T.in,o.in,y);if(f instanceof k)return f.throw();else F.declaredIn=f}if(T.declaredOut||o.declaredOut){let f=QT(T.out,o.out,y);if(f instanceof k)return f.throw();else F.declaredOut=f}return A.distribute((f)=>y.$.node("morph",{...F,in:f}),y.$.parseSchema)},...eo("morph",(T,o,y)=>{let A=T.inner.in?QT(T.inner.in,o,y):o;return A instanceof k?A:A.equals(T.inner.in)?T:y.$.node("morph",{...T.inner,in:A})})}});class c_ extends No{serializedMorphs=this.morphs.map(BT);compiledMorphs=`[${this.serializedMorphs}]`;lastMorph=this.inner.morphs.at(-1);lastMorphIfNode=q(this.lastMorph,"root")?this.lastMorph:void 0;introspectableIn=this.inner.in;introspectableOut=this.lastMorphIfNode?Object.assign(this.referencesById,this.lastMorphIfNode.referencesById)&&this.lastMorphIfNode.out:void 0;get shallowMorphs(){return Array.isArray(this.inner.in?.shallowMorphs)?[...this.inner.in.shallowMorphs,...this.morphs]:this.morphs}get in(){return this.declaredIn??this.inner.in?.in??U.intrinsic.unknown.internal}get out(){return this.declaredOut??this.introspectableOut??U.intrinsic.unknown.internal}declareIn(T){return this.$.node("morph",{...this.inner,declaredIn:T})}declareOut(T){return this.$.node("morph",{...this.inner,declaredOut:T})}expression=`(In: ${this.in.expression}) => ${this.lastMorphIfNode?"To":"Out"}<${this.out.expression}>`;get defaultShortDescription(){return this.in.meta.description??this.in.defaultShortDescription}innerToJsonSchema(T){return JT.throwUnjsonifiableError(this.expression,"morph")}compile(T){if(T.traversalKind==="Allows"){if(!this.introspectableIn)return;T.return(T.invoke(this.introspectableIn));return}if(this.introspectableIn)T.line(T.invoke(this.introspectableIn));T.line(`ctx.queueMorphs(${this.compiledMorphs})`)}traverseAllows=(T,o)=>!this.introspectableIn||this.introspectableIn.traverseAllows(T,o);traverseApply=(T,o)=>{if(this.introspectableIn)this.introspectableIn.traverseApply(T,o);o.queueMorphs(this.morphs)};hasEqualMorphs(T){return Sy(this.morphs,T.morphs,{isEqual:(o,y)=>o===y||q(o,"root")&&q(y,"root")&&o.equals(y)})}}var R$={implementation:I8,Node:c_},k8=(T,o)=>`The intersection of distinct morphs at a single path is indeterminate:
|
|
26
|
+
Left: ${T}
|
|
27
|
+
Right: ${o}`;var B8=r({kind:"proto",hasAssociatedError:!0,collapsibleKey:"proto",keys:{proto:{serialize:(T)=>gA(T)??ko(T)},dateAllowsInvalid:{}},normalize:(T)=>{let o=typeof T==="string"?{proto:jy[T]}:typeof T==="function"?zT(T)?T:{proto:T}:typeof T.proto==="string"?{...T,proto:jy[T.proto]}:T;if(typeof o.proto!=="function")E(JF.writeInvalidSchemaMessage(o.proto));if(yA(o,"dateAllowsInvalid")&&o.proto!==Date)E(JF.writeBadInvalidDateMessage(o.proto));return o},applyConfig:(T,o)=>{if(T.dateAllowsInvalid===void 0&&T.proto===Date&&o.dateAllowsInvalid)return{...T,dateAllowsInvalid:!0};return T},defaults:{description:(T)=>T.builtinName?h0[T.builtinName]:`an instance of ${T.proto.name}`,actual:(T)=>T instanceof Date&&T.toString()==="Invalid Date"?"an invalid Date":nA(T)},intersections:{proto:(T,o)=>T.proto===Date&&o.proto===Date?T.dateAllowsInvalid?o:T:pS(T.proto,o.proto)?T:pS(o.proto,T.proto)?o:k.init("proto",T,o),domain:(T,o)=>o.domain==="object"?T:k.init("domain",U.intrinsic.object.internal,o)}});class d_ extends vy{builtinName=gA(this.proto);serializedConstructor=this.json.proto;requiresInvalidDateCheck=this.proto===Date&&!this.dateAllowsInvalid;traverseAllows=this.requiresInvalidDateCheck?(T)=>T instanceof Date&&T.toString()!=="Invalid Date":(T)=>T instanceof this.proto;compiledCondition=`data instanceof ${this.serializedConstructor}${this.requiresInvalidDateCheck?' && data.toString() !== "Invalid Date"':""}`;compiledNegation=`!(${this.compiledCondition})`;innerToJsonSchema(T){switch(this.builtinName){case"Array":return{type:"array"};default:return JT.throwUnjsonifiableError(this.description)}}expression=this.dateAllowsInvalid?"Date | InvalidDate":this.proto.name;get nestableExpression(){return this.dateAllowsInvalid?`(${this.expression})`:this.expression}domain="object";get defaultShortDescription(){return this.description}}var JF={implementation:B8,Node:d_,writeBadInvalidDateMessage:(T)=>`dateAllowsInvalid may only be specified with constructor Date (was ${T.name})`,writeInvalidSchemaMessage:(T)=>`instanceOf operand must be a function (was ${hT(T)})`};var N8=r({kind:"union",hasAssociatedError:!0,collapsibleKey:"branches",keys:{ordered:{},branches:{child:!0,parse:(T,o)=>{let y=[];if(T.forEach((A)=>{(q(A,"root")?A.branches:o.$.parseSchema(A).branches).forEach((f)=>{if(f.hasKind("morph")){let S=y.findIndex(($)=>$.hasKind("morph")&&$.hasEqualMorphs(f));if(S===-1)y.push(f);else{let $=y[S];y[S]=o.$.node("morph",{...$.inner,in:$.in.rawOr(f.in)})}}else y.push(f)})}),!o.def.ordered)y.sort((A,F)=>A.hash<F.hash?-1:1);return y}}},normalize:(T)=>ET(T)?{branches:T}:T,reduce:(T,o)=>{let y=h8(T);if(y.length===1)return y[0];if(y.length===T.branches.length)return;return o.node("union",{...T,branches:y},{prereduced:!0})},defaults:{description:(T)=>T.distribute((o)=>o.description,XA),expected:(T)=>{let o=p0(T.errors,"propString"),y=Object.entries(o).map(([A,F])=>{let f=[];F.forEach((_)=>so(f,_.expected));let S=XA(f),$=F.every((_)=>_.actual===F[0].actual)?F[0].actual:d(F[0].data);return`${A&&`${A} `}must be ${S}${$&&` (was ${$})`}`});return XA(y)},problem:(T)=>T.expected,message:(T)=>T.problem},intersections:{union:(T,o,y)=>{if(T.isNever!==o.isNever)return k.init("presence",T,o);let A;if(T.ordered){if(o.ordered)E(g8(T.expression,o.expression));if(A=W$(o.branches,T.branches,y),A instanceof k)A.invert()}else A=W$(T.branches,o.branches,y);if(A instanceof k)return A;return y.$.parseSchema(T.ordered||o.ordered?{branches:A,ordered:!0}:{branches:A})},...eo("union",(T,o,y)=>{let A=W$(T.branches,[o],y);if(A instanceof k)return A;if(A.length===1)return A[0];return y.$.parseSchema(T.ordered?{branches:A,ordered:!0}:{branches:A})})}});class s_ extends No{isBoolean=this.branches.length===2&&this.branches[0].hasUnit(!1)&&this.branches[1].hasUnit(!0);get branchGroups(){let T=[],o=-1;return this.branches.forEach((y)=>{if(y.hasKind("unit")&&y.domain==="boolean"){if(o===-1)o=T.length,T.push(y);else T[o]=U.intrinsic.boolean;return}T.push(y)}),T}unitBranches=this.branches.filter((T)=>T.in.hasKind("unit"));discriminant=this.discriminate();discriminantJson=this.discriminant?q8(this.discriminant):null;expression=this.distribute((T)=>T.nestableExpression,P8);createBranchedOptimisticRootApply(){return(T,o)=>{let y=this.traverseOptimistic(T);if(y!==Qo)return y;let A=new no(T,this.$.resolvedConfig);return this.traverseApply(T,A),A.finalize(o)}}get shallowMorphs(){return this.branches.reduce((T,o)=>so(T,o.shallowMorphs),[])}get defaultShortDescription(){return this.distribute((T)=>T.defaultShortDescription,XA)}innerToJsonSchema(T){if(this.branchGroups.length===1&&this.branchGroups[0].equals(U.intrinsic.boolean))return{type:"boolean"};let o=this.branchGroups.map((y)=>y.toJsonSchemaRecurse(T));if(o.every((y)=>Object.keys(y).length===1&&yA(y,"const")))return{enum:o.map((y)=>y.const)};return{anyOf:o}}traverseAllows=(T,o)=>this.branches.some((y)=>y.traverseAllows(T,o));traverseApply=(T,o)=>{let y=[];for(let A=0;A<this.branches.length;A++){if(o.pushBranch(),this.branches[A].traverseApply(T,o),!o.hasError()){if(this.branches[A].includesTransform)return o.queuedMorphs.push(...o.popBranch().queuedMorphs);return o.popBranch()}y.push(o.popBranch().error)}o.errorFromNodeContext({code:"union",errors:y,meta:this.meta})};traverseOptimistic=(T)=>{for(let o=0;o<this.branches.length;o++){let y=this.branches[o];if(y.traverseAllows(T)){if(y.contextFreeMorph)return y.contextFreeMorph(T);return T}}return Qo};compile(T){if(!this.discriminant||this.unitBranches.length===this.branches.length&&this.branches.length===2)return this.compileIndiscriminable(T);let o=this.discriminant.optionallyChainedPropString;if(this.discriminant.kind==="domain")o=`typeof ${o} === "object" ? ${o} === null ? "null" : "object" : typeof ${o} === "function" ? "object" : typeof ${o}`;let y=this.discriminant.cases,A=Object.keys(y),{optimistic:F}=T;if(T.optimistic=!1,T.block(`switch(${o})`,()=>{for(let J in y){let R=y[J],M=J==="default"?J:`case ${J}`;T.line(`${M}: return ${R===!0?F?T.data:R:F?`${T.invoke(R)} ? ${R.contextFreeMorph?`${BT(R.contextFreeMorph)}(${T.data})`:T.data} : "${Qo}"`:T.invoke(R)}`)}return T}),T.traversalKind==="Allows"){T.return(F?`"${Qo}"`:!1);return}let f=XA(this.discriminant.kind==="domain"?A.map((J)=>{let R=J.slice(1,-1);return R==="function"?Zo.object:Zo[R]}):A),S=this.discriminant.path.map((J)=>typeof J==="symbol"?BT(J):JSON.stringify(J)),$=JSON.stringify(f),_=this.discriminant.kind==="domain"?`${j8}[${o}]`:`${m8}(${o})`;T.line(`ctx.errorFromNodeContext({
|
|
28
|
+
code: "predicate",
|
|
29
|
+
expected: ${$},
|
|
30
|
+
actual: ${_},
|
|
31
|
+
relativePath: [${S}],
|
|
32
|
+
meta: ${this.compiledMeta}
|
|
33
|
+
})`)}compileIndiscriminable(T){if(T.traversalKind==="Apply")T.const("errors","[]"),this.branches.forEach((o)=>T.line("ctx.pushBranch()").line(T.invoke(o)).if("!ctx.hasError()",()=>T.return(o.includesTransform?"ctx.queuedMorphs.push(...ctx.popBranch().queuedMorphs)":"ctx.popBranch()")).line("errors.push(ctx.popBranch().error)")),T.line(`ctx.errorFromNodeContext({ code: "union", errors, meta: ${this.compiledMeta} })`);else{let{optimistic:o}=T;T.optimistic=!1,this.branches.forEach((y)=>T.if(`${T.invoke(y)}`,()=>T.return(o?y.contextFreeMorph?`${BT(y.contextFreeMorph)}(${T.data})`:T.data:!0))),T.return(o?`"${Qo}"`:!1)}}get nestableExpression(){return this.isBoolean?"boolean":`(${this.expression})`}discriminate(){if(this.branches.length<2)return null;if(this.unitBranches.length===this.branches.length){let F=l(this.unitBranches,(f,S)=>[`${S.in.serializedValue}`,S.hasKind("morph")?S:!0]);return{kind:"unit",path:[],optionallyChainedPropString:"data",cases:F}}let T=[];for(let F=0;F<this.branches.length-1;F++){let f=this.branches[F];for(let S=F+1;S<this.branches.length;S++){let $=this.branches[S],_=Go(f.in,$.in,f.$);if(!(_ instanceof k))continue;for(let J of _){if(!J.kind||J.optional)continue;let R,M;if(J.kind==="domain"){let{l:H,r:Q}=J;R=`"${typeof H==="string"?H:H.domain}"`,M=`"${typeof Q==="string"?Q:Q.domain}"`}else if(J.kind==="unit")R=J.l.serializedValue,M=J.r.serializedValue;else continue;let Y=T.find((H)=>Sy(H.path,J.path)&&H.kind===J.kind);if(!Y)T.push({kind:J.kind,cases:{[R]:{branchIndices:[F],condition:J.l},[M]:{branchIndices:[S],condition:J.r}},path:J.path});else{if(Y.cases[R])Y.cases[R].branchIndices=so(Y.cases[R].branchIndices,F);else Y.cases[R]??={branchIndices:[F],condition:J.l};if(Y.cases[M])Y.cases[M].branchIndices=so(Y.cases[M].branchIndices,S);else Y.cases[M]??={branchIndices:[S],condition:J.r}}}}}let o=this.ordered?b8(T,this.branches):T;if(!o.length)return null;let y=t8(o,this),A={};for(let F in y.best.cases){let f=p8(y,F);if(f===null){A[F]=!0;continue}if(f.length===this.branches.length)return null;if(this.ordered)f.sort((_,J)=>_.originalIndex-J.originalIndex);let S=f.map((_)=>_.branch),$=S.length===1?S[0]:this.$.node("union",this.ordered?{branches:S,ordered:!0}:S);Object.assign(this.referencesById,$.referencesById),A[F]=$}if(y.defaultEntries.length){let F=y.defaultEntries.map((f)=>f.branch);A.default=this.$.node("union",this.ordered?{branches:F,ordered:!0}:F,{prereduced:!0}),Object.assign(this.referencesById,A.default.referencesById)}return Object.assign(y.location,{cases:A})}}var t8=(T,o)=>{let y=T.sort((f,S)=>Object.keys(S.cases).length-Object.keys(f.cases).length)[0],A={kind:y.kind,path:y.path,optionallyChainedPropString:a_(y.path)},F=o.branches.map((f,S)=>({originalIndex:S,branch:f}));return{best:y,location:A,defaultEntries:F,node:o}},p8=(T,o)=>{let y=T.best.cases[o],A=x8(y.condition,T.location.path,T.node.$),F=[],f=[];for(let S=0;S<T.defaultEntries.length;S++){let $=T.defaultEntries[S];if(y.branchIndices.includes($.originalIndex)){let _=r_(T.node.branches[$.originalIndex],T.location);if(_===null)F=null;else F?.push({originalIndex:$.originalIndex,branch:_})}else if($.branch.hasKind("alias")&&A.hasKind("domain")&&A.domain==="object")F?.push($);else{if($.branch.in.overlaps(A)){let _=r_($.branch,T.location);F?.push({originalIndex:$.originalIndex,branch:_})}f.push($)}}return T.defaultEntries=f,F},b8=(T,o)=>{return T.filter((A)=>{let F=Object.values(A.cases).map((f)=>f.branchIndices);for(let f=0;f<F.length-1;f++){let S=F[f];for(let $=f+1;$<F.length;$++){let _=F[$];for(let J of S)for(let R of _)if(J>R){if(o[J].overlaps(o[R]))return!1}}}return!0})},x8=(T,o,y)=>{let A=T==="undefined"?y.node("unit",{unit:void 0}):T==="null"?y.node("unit",{unit:null}):T==="boolean"?y.units([!0,!1]):T;for(let F=o.length-1;F>=0;F--){let f=o[F];A=y.node("intersection",typeof f==="number"?{proto:"Array",sequence:[...N0(f).map((S)=>({})),A]}:{domain:"object",required:[{key:f,value:A}]})}return A},a_=(T)=>T.reduce((o,y)=>o+PS(y,!0),"data"),j8=BT(b0),m8=BT(d),O$={implementation:N8,Node:s_},q8=(T)=>({kind:T.kind,path:T.path.map((o)=>typeof o==="string"?o:Ry(o)),cases:l(T.cases,(o,y)=>[o,y===!0?y:y.hasKind("union")&&y.discriminantJson?y.discriminantJson:y.json])}),v8={delimiter:" | ",finalDelimiter:" | "},P8=(T)=>XA(T,v8),XA=(T,o)=>{let y=o?.delimiter??", ",A=o?.finalDelimiter??" or ";if(T.length===0)return"never";if(T.length===1)return T[0];if(T.length===2&&T[0]==="false"&&T[1]==="true"||T[0]==="true"&&T[1]==="false")return"boolean";let F={},f=T.filter(($)=>F[$]?!1:F[$]=!0),S=f.pop();return`${f.join(y)}${f.length?A:""}${S}`},W$=(T,o,y)=>{let A=o.map(()=>[]);for(let f=0;f<T.length;f++){let S={};for(let $=0;$<o.length;$++){if(A[$]===null)continue;if(T[f].equals(o[$])){A[$]=null,S={};break}let _=QT(T[f],o[$],y);if(_ instanceof k)continue;if(_.equals(T[f])){A[$].push(T[f]),S={};break}if(_.equals(o[$]))A[$]=null;else S[$]=_}for(let $ in S)A[$][f]=S[$]}let F=A.flatMap((f,S)=>f?.flatMap(($)=>$.branches)??o[S]);return F.length===0?k.init("union",T,o):F},h8=({branches:T,ordered:o})=>{if(T.length<2)return T;let y=T.map(()=>!0);for(let A=0;A<T.length;A++)for(let F=A+1;F<T.length&&y[A]&&y[F];F++){if(T[A].equals(T[F])){y[F]=!1;continue}let f=Go(T[A].in,T[F].in,T[0].$);if(f instanceof k)continue;if(!o)n8(T[A],T[F]);if(f.equals(T[A].in))y[A]=!!o;else if(f.equals(T[F].in))y[F]=!1}return T.filter((A,F)=>y[F])},n8=(T,o)=>{if(!T.includesTransform&&!o.includesTransform)return;if(!Sy(T.shallowMorphs,o.shallowMorphs))E(l_(T.expression,o.expression));if(!Sy(T.flatMorphs,o.flatMorphs,{isEqual:(y,A)=>y.propString===A.propString&&(y.node.hasKind("morph")&&A.node.hasKind("morph")?y.node.hasEqualMorphs(A.node):y.node.hasKind("intersection")&&A.node.hasKind("intersection")?y.node.structure?.structuralMorphRef===A.node.structure?.structuralMorphRef:!1)}))E(l_(T.expression,o.expression))},r_=(T,o)=>T.transform((y,A)=>{if(y==="domain"||y==="unit")return null;return A},{shouldTransform:(y,A)=>{let F=a_(A.path);if(!o.optionallyChainedPropString.startsWith(F))return!1;if(y.hasKind("domain")&&y.domain==="object")return!0;if((y.hasKind("domain")||o.kind==="unit")&&F===o.optionallyChainedPropString)return!0;return y.children.length!==0&&y.kind!=="index"}}),l_=(T,o)=>`An unordered union of a type including a morph and a type with overlapping input is indeterminate:
|
|
34
|
+
Left: ${T}
|
|
35
|
+
Right: ${o}`,g8=(T,o)=>`The intersection of two ordered unions is indeterminate:
|
|
36
|
+
Left: ${T}
|
|
37
|
+
Right: ${o}`;var u8=r({kind:"unit",hasAssociatedError:!0,keys:{unit:{preserveUndefined:!0,serialize:(T)=>T instanceof Date?T.toISOString():ko(T)}},normalize:(T)=>T,defaults:{description:(T)=>d(T.unit),problem:({expected:T,actual:o})=>`${T===o?`must be reference equal to ${T} (serialized to the same value)`:`must be ${T} (was ${o})`}`},intersections:{unit:(T,o)=>k.init("unit",T,o),...eo("unit",(T,o)=>{if(o.allows(T.unit))return T;let y=o.hasKind("intersection")?o.basis:o;if(y){let A=y.hasKind("domain")?y:U.intrinsic.object;if(T.domain!==A.domain){let F=T.domain==="undefined"||T.domain==="null"||T.domain==="boolean"?T.domain:U.intrinsic[T.domain];return k.init("domain",F,A)}}return k.init("assignability",T,o.hasKind("intersection")?o.children.find((A)=>!A.allows(T.unit)):o)})}});class T1 extends vy{compiledValue=this.json.unit;serializedValue=typeof this.unit==="string"||this.unit instanceof Date?JSON.stringify(this.compiledValue):`${this.compiledValue}`;compiledCondition=e_(this.unit,this.serializedValue);compiledNegation=e_(this.unit,this.serializedValue,"negated");expression=d(this.unit);domain=hT(this.unit);get defaultShortDescription(){return this.domain==="object"?Zo.object:this.description}innerToJsonSchema(T){return this.unit===null?{type:"null"}:U.intrinsic.jsonPrimitive.allows(this.unit)?{const:this.unit}:JT.throwUnjsonifiableError(this.defaultShortDescription)}traverseAllows=this.unit instanceof Date?(T)=>T instanceof Date&&T.toISOString()===this.compiledValue:Number.isNaN(this.unit)?(T)=>Number.isNaN(T):(T)=>T===this.unit}var M$={implementation:u8,Node:T1},e_=(T,o,y)=>{if(T instanceof Date){let A=`data instanceof Date && data.toISOString() === ${o}`;return y?`!(${A})`:A}if(Number.isNaN(T))return`${y?"!":""}Number.isNaN(data)`;return`data ${y?"!":"="}== ${o}`};var i8=r({kind:"index",hasAssociatedError:!1,intersectionIsOpen:!0,keys:{signature:{child:!0,parse:(T,o)=>{let y=o.$.parseSchema(T);if(!y.extends(U.intrinsic.key))return E(d8(y.expression));let A=y.branches.filter((F)=>F.hasKind("unit"));if(A.length)return E(c8(A.map((F)=>d(F.unit))));return y}},value:{child:!0,parse:(T,o)=>o.$.parseSchema(T)}},normalize:(T)=>T,defaults:{description:(T)=>`[${T.signature.expression}]: ${T.value.description}`},intersections:{index:(T,o,y)=>{if(T.signature.equals(o.signature)){let A=QT(T.value,o.value,y),F=A instanceof k?U.intrinsic.never.internal:A;return y.$.node("index",{signature:T.signature,value:F})}if(T.signature.extends(o.signature)&&T.value.subsumes(o.value))return o;if(o.signature.extends(T.signature)&&o.value.subsumes(T.value))return T;return null}}});class o1 extends Bo{impliedBasis=U.intrinsic.object.internal;expression=`[${this.signature.expression}]: ${this.value.expression}`;flatRefs=FT(this.value.flatRefs.map((T)=>go([this.signature,...T.path],T.node)),go([this.signature],this.value));traverseAllows=(T,o)=>PA(T).every((y)=>{if(this.signature.traverseAllows(y[0],o))return Eo(y[0],()=>this.value.traverseAllows(y[1],o),o);return!0});traverseApply=(T,o)=>PA(T).forEach((y)=>{if(this.signature.traverseAllows(y[0],o))Eo(y[0],()=>this.value.traverseApply(y[1],o),o)});_transform(T,o){o.path.push(this.signature);let y=super._transform(T,o);return o.path.pop(),y}compile(){}}var X$={implementation:i8,Node:o1},c8=(T)=>`Index keys ${T.join(", ")} should be specified as named props.`,d8=(T)=>`Indexed key definition '${T}' must be a string or symbol`;var r8=r({kind:"required",hasAssociatedError:!0,intersectionIsOpen:!0,keys:{key:{},value:{child:!0,parse:(T,o)=>o.$.parseSchema(T)}},normalize:(T)=>T,defaults:{description:(T)=>`${T.compiledKey}: ${T.value.description}`,expected:(T)=>T.missingValueDescription,actual:()=>"missing"},intersections:{required:yF,optional:yF}});class y1 extends AF{expression=`${this.compiledKey}: ${this.value.expression}`;errorContext=Object.freeze({code:"required",missingValueDescription:this.value.defaultShortDescription,relativePath:[this.key],meta:this.meta});compiledErrorContext=Vy(this.errorContext)}var Y$={implementation:r8,Node:y1};var l8=r({kind:"sequence",hasAssociatedError:!1,collapsibleKey:"variadic",keys:{prefix:{child:!0,parse:(T,o)=>{if(T.length===0)return;return T.map((y)=>o.$.parseSchema(y))}},optionals:{child:!0,parse:(T,o)=>{if(T.length===0)return;return T.map((y)=>o.$.parseSchema(y))}},defaultables:{child:(T)=>T.map((o)=>o[0]),parse:(T,o)=>{if(T.length===0)return;return T.map((y)=>{let A=o.$.parseSchema(y[0]);return fF(A,y[1],null),[A,y[1]]})},serialize:(T)=>T.map((o)=>[o[0].collapsibleJson,ko(o[1])])},variadic:{child:!0,parse:(T,o)=>o.$.parseSchema(T,o)},minVariadicLength:{parse:(T)=>T===0?void 0:T},postfix:{child:!0,parse:(T,o)=>{if(T.length===0)return;return T.map((y)=>o.$.parseSchema(y))}}},normalize:(T)=>{if(typeof T==="string")return{variadic:T};if("variadic"in T||"prefix"in T||"defaultables"in T||"optionals"in T||"postfix"in T||"minVariadicLength"in T){if(T.postfix?.length){if(!T.variadic)return E(TY);if(T.optionals?.length||T.defaultables?.length)return E(H$)}if(T.minVariadicLength&&!T.variadic)return E("minVariadicLength may not be specified without a variadic element");return T}return{variadic:T}},reduce:(T,o)=>{let y=T.minVariadicLength??0,A=T.prefix?.slice()??[],F=T.defaultables?.slice()??[],f=T.optionals?.slice()??[],S=T.postfix?.slice()??[];if(T.variadic){while(f.at(-1)?.equals(T.variadic))f.pop();if(f.length===0&&F.length===0)while(A.at(-1)?.equals(T.variadic))A.pop(),y++;while(S[0]?.equals(T.variadic))S.shift(),y++}else if(f.length===0&&F.length===0)A.push(...S.splice(0));if(y!==T.minVariadicLength||T.prefix&&T.prefix.length!==A.length)return o.node("sequence",{...T,prefix:A,defaultables:F,optionals:f,postfix:S,minVariadicLength:y},{prereduced:!0})},defaults:{description:(T)=>{if(T.isVariadicOnly)return`${T.variadic.nestableExpression}[]`;return`[${T.tuple.map((y)=>y.kind==="defaultables"?`${y.node.nestableExpression} = ${d(y.default)}`:y.kind==="optionals"?`${y.node.nestableExpression}?`:y.kind==="variadic"?`...${y.node.nestableExpression}[]`:y.node.expression).join(", ")}]`}},intersections:{sequence:(T,o,y)=>{let A=_F({l:T.tuple,r:o.tuple,disjoint:new k,result:[],fixedVariants:[],ctx:y}),F=A.disjoint.length===0?[A,...A.fixedVariants]:A.fixedVariants;return F.length===0?A.disjoint:F.length===1?y.$.node("sequence",A1(F[0].result)):y.$.node("union",F.map((f)=>({proto:Array,sequence:A1(f.result)})))}}});class F1 extends Bo{impliedBasis=U.intrinsic.Array.internal;tuple=e8(this.inner);prefixLength=this.prefix?.length??0;defaultablesLength=this.defaultables?.length??0;optionalsLength=this.optionals?.length??0;postfixLength=this.postfix?.length??0;defaultablesAndOptionals=[];prevariadic=this.tuple.filter((T)=>{if(T.kind==="defaultables"||T.kind==="optionals")return this.defaultablesAndOptionals.push(T.node),!0;return T.kind==="prefix"});variadicOrPostfix=fy(this.variadic&&[this.variadic],this.postfix);flatRefs=this.addFlatRefs();addFlatRefs(){return gS(this.flatRefs,this.prevariadic.flatMap((T,o)=>FT(T.node.flatRefs.map((y)=>go([`${o}`,...y.path],y.node)),go([`${o}`],T.node)))),gS(this.flatRefs,this.variadicOrPostfix.flatMap((T)=>FT(T.flatRefs.map((o)=>go([U.intrinsic.nonNegativeIntegerString.internal,...o.path],o.node)),go([U.intrinsic.nonNegativeIntegerString.internal],T)))),this.flatRefs}isVariadicOnly=this.prevariadic.length+this.postfixLength===0;minVariadicLength=this.inner.minVariadicLength??0;minLength=this.prefixLength+this.minVariadicLength+this.postfixLength;minLengthNode=this.minLength===0?null:this.$.node("minLength",this.minLength);maxLength=this.variadic?null:this.tuple.length;maxLengthNode=this.maxLength===null?null:this.$.node("maxLength",this.maxLength);impliedSiblings=this.minLengthNode?this.maxLengthNode?[this.minLengthNode,this.maxLengthNode]:[this.minLengthNode]:this.maxLengthNode?[this.maxLengthNode]:[];defaultValueMorphs=a8(this);defaultValueMorphsReference=this.defaultValueMorphs.length?BT(this.defaultValueMorphs):void 0;elementAtIndex(T,o){if(o<this.prevariadic.length)return this.tuple[o];let y=T.length-this.postfixLength;if(o>=y)return{kind:"postfix",node:this.postfix[o-y]};return{kind:"variadic",node:this.variadic??$T(`Unexpected attempt to access index ${o} on ${this}`)}}traverseAllows=(T,o)=>{for(let y=0;y<T.length;y++)if(!this.elementAtIndex(T,y).node.traverseAllows(T[y],o))return!1;return!0};traverseApply=(T,o)=>{let y=0;for(;y<T.length;y++)Eo(y,()=>this.elementAtIndex(T,y).node.traverseApply(T[y],o),o)};get element(){return this.cacheGetter("element",this.$.node("union",this.children))}compile(T){if(this.prefix?.forEach((o,y)=>T.traverseKey(`${y}`,`data[${y}]`,o)),this.defaultablesAndOptionals.forEach((o,y)=>{let A=`${y+this.prefixLength}`;T.if(`${A} >= ${T.data}.length`,()=>T.traversalKind==="Allows"?T.return(!0):T.return()),T.traverseKey(A,`data[${A}]`,o)}),this.variadic){if(this.postfix)T.const("firstPostfixIndex",`${T.data}.length${this.postfix?`- ${this.postfix.length}`:""}`);T.for(`i < ${this.postfix?"firstPostfixIndex":"data.length"}`,()=>T.traverseKey("i","data[i]",this.variadic),this.prevariadic.length),this.postfix?.forEach((o,y)=>{let A=`firstPostfixIndex + ${y}`;T.traverseKey(A,`data[${A}]`,o)})}if(T.traversalKind==="Allows")T.return(!0)}_transform(T,o){o.path.push(U.intrinsic.nonNegativeIntegerString.internal);let y=super._transform(T,o);return o.path.pop(),y}expression=this.description;reduceJsonSchema(T,o){if(this.prevariadic.length)T.prefixItems=this.prevariadic.map((y)=>{let A=y.node.toJsonSchemaRecurse(o);if(y.kind==="defaultables"){let F=typeof y.default==="function"?y.default():y.default;A.default=F}return A});if(this.minLength)T.minItems=this.minLength;if(this.variadic){if(T.items=this.variadic?.toJsonSchemaRecurse(o),this.maxLength)T.maxItems=this.maxLength}else T.items=!1,delete T.maxItems;if(this.postfix)return JT.throwUnjsonifiableError(`Postfix tuple element${this.postfixLength>1?"s":""} ${this.postfix.join(", ")}`);return T}}var s8={},a8=(T)=>{if(!T.defaultables)return[];let o=[],y="[",A=T.prefixLength+T.defaultablesLength-1;for(let F=T.prefixLength;F<=A;F++){let[f,S]=T.defaultables[F-T.prefixLength];o.push(J$(F,f,S)),y+=`${F}: ${f.id} = ${ko(S)}, `}return y+="]",s8[y]??=o},Z$={implementation:l8,Node:F1},e8=(T)=>{let o=[];if(T.prefix?.forEach((y)=>o.push({kind:"prefix",node:y})),T.defaultables?.forEach(([y,A])=>o.push({kind:"defaultables",node:y,default:A})),T.optionals?.forEach((y)=>o.push({kind:"optionals",node:y})),T.variadic)o.push({kind:"variadic",node:T.variadic});return T.postfix?.forEach((y)=>o.push({kind:"postfix",node:y})),o},A1=(T)=>T.reduce((o,y)=>{if(y.kind==="variadic")o.variadic=y.node;else if(y.kind==="defaultables")o.defaultables=FT(o.defaultables,[[y.node,y.default]]);else o[y.kind]=FT(o[y.kind],y.node);return o},{}),H$="A postfix required element cannot follow an optional or defaultable element",TY="A postfix element requires a variadic element",_F=(T)=>{let[o,...y]=T.l,[A,...F]=T.r;if(!o||!A)return T;let f=y.at(-1)?.kind==="postfix",S=F.at(-1)?.kind==="postfix",$=o.kind==="prefix"||A.kind==="prefix"?"prefix":o.kind==="postfix"||A.kind==="postfix"?"postfix":o.kind==="variadic"&&A.kind==="variadic"?"variadic":f||S?"prefix":o.kind==="defaultables"||A.kind==="defaultables"?"defaultables":"optionals";if(o.kind==="prefix"&&A.kind==="variadic"&&S){let M=_F({...T,fixedVariants:[],r:F.map((Y)=>({...Y,kind:"prefix"}))});if(M.disjoint.length===0)T.fixedVariants.push(M)}else if(A.kind==="prefix"&&o.kind==="variadic"&&f){let M=_F({...T,fixedVariants:[],l:y.map((Y)=>({...Y,kind:"prefix"}))});if(M.disjoint.length===0)T.fixedVariants.push(M)}let _=QT(o.node,A.node,T.ctx);if(_ instanceof k)if($==="prefix"||$==="postfix")T.disjoint.push(..._.withPrefixKey($==="prefix"?T.result.length:`-${y.length+1}`,"required")),T.result=[...T.result,{kind:$,node:U.intrinsic.never.internal}];else if($==="optionals"||$==="defaultables")return T;else return _F({...T,fixedVariants:[],l:y.map((M)=>({...M,kind:"prefix"})),r:y.map((M)=>({...M,kind:"prefix"}))});else if($==="defaultables"){if(o.kind==="defaultables"&&A.kind==="defaultables"&&o.default!==A.default)E($$(o.default,A.default));T.result=[...T.result,{kind:$,node:_,default:o.kind==="defaultables"?o.default:A.kind==="defaultables"?A.default:$T(`Unexpected defaultable intersection from ${o.kind} and ${A.kind} elements.`)}]}else T.result=[...T.result,{kind:$,node:_}];let J=T.l.length,R=T.r.length;if(o.kind!=="variadic"||J>=R&&(A.kind==="variadic"||R===1))T.l=y;if(A.kind!=="variadic"||R>=J&&(o.kind==="variadic"||J===1))T.r=F;return _F(T)};var $1=(T)=>(o)=>{if(o.props.length||o.index){let y=o.index?.map((F)=>F[T])??[];if(o.props.forEach((F)=>y.push(F[T])),o.undeclared)y.push(`+ (undeclared): ${o.undeclared}`);let A=`{ ${y.join(", ")} }`;return o.sequence?`${A} & ${o.sequence.description}`:A}return o.sequence?.description??"{}"},oY=$1("description"),yY=$1("expression"),f1=(T,o,y)=>{let A=T.required?"required":"optional";if(!o.signature.allows(T.key))return null;let F=Go(T.value,o.value,y);if(F instanceof k)if(A==="optional")return y.node("optional",{key:T.key,value:U.intrinsic.never.internal});else return F.withPrefixKey(T.key,T.kind);return null},AY=r({kind:"structure",hasAssociatedError:!1,normalize:(T)=>T,applyConfig:(T,o)=>{if(!T.undeclared&&o.onUndeclaredKey!=="ignore")return{...T,undeclared:o.onUndeclaredKey};return T},keys:{required:{child:!0,parse:So("required"),reduceIo:(T,o,y)=>{o.required=FT(o.required,y.map((A)=>A[T]));return}},optional:{child:!0,parse:So("optional"),reduceIo:(T,o,y)=>{if(T==="in"){o.optional=y.map((A)=>A.in);return}y.forEach((A)=>o[A.outProp.kind]=FT(o[A.outProp.kind],A.outProp.out))}},index:{child:!0,parse:So("index")},sequence:{child:!0,parse:So("sequence")},undeclared:{parse:(T)=>T==="ignore"?void 0:T,reduceIo:(T,o,y)=>{if(y!=="delete")return;if(T==="in")delete o.undeclared;else o.undeclared="reject"}}},defaults:{description:oY},intersections:{structure:(T,o,y)=>{let A={...T.inner},F={...o.inner},f=new k;if(T.undeclared){let _=T.keyof();if(o.requiredKeys.forEach((J)=>{if(!_.allows(J))f.add("presence",U.intrinsic.never.internal,o.propsByKey[J].value,{path:[J]})}),F.optional)F.optional=F.optional.filter((J)=>_.allows(J.key));if(F.index)F.index=F.index.flatMap((J)=>{if(J.signature.extends(_))return J;let R=Go(_,J.signature,y.$);if(R instanceof k)return[];let M=_f(R,J.value,y.$);if(M.required)F.required=fy(F.required,M.required);if(M.optional)F.optional=fy(F.optional,M.optional);return M.index??[]})}if(o.undeclared){let _=o.keyof();if(T.requiredKeys.forEach((J)=>{if(!_.allows(J))f.add("presence",T.propsByKey[J].value,U.intrinsic.never.internal,{path:[J]})}),A.optional)A.optional=A.optional.filter((J)=>_.allows(J.key));if(A.index)A.index=A.index.flatMap((J)=>{if(J.signature.extends(_))return J;let R=Go(_,J.signature,y.$);if(R instanceof k)return[];let M=_f(R,J.value,y.$);if(M.required)A.required=fy(A.required,M.required);if(M.optional)A.optional=fy(A.optional,M.optional);return M.index??[]})}let S={};if(T.undeclared||o.undeclared)S.undeclared=T.undeclared==="reject"||o.undeclared==="reject"?"reject":"delete";let $=_A({kind:"structure",baseInner:S,l:RA(A),r:RA(F),roots:[],ctx:y});if($ instanceof k)f.push(...$);if(f.length)return f;return $}},reduce:(T,o)=>{if(T.index){if(!(T.required||T.optional))return;let y=!1,A=T.required??[],F=T.optional??[],f=[...F];for(let S of T.index){for(let $ of A){let _=f1($,S,o);if(_ instanceof k)return _}for(let[$,_]of F.entries()){let J=f1(_,S,o);if(J instanceof k)return J;if(J===null)continue;f[$]=J,y=!0}}if(y)return o.node("structure",{...T,optional:f},{prereduced:!0})}}});class J1 extends Bo{impliedBasis=U.intrinsic.object.internal;impliedSiblings=this.children.flatMap((T)=>T.impliedSiblings??[]);props=fy(this.required,this.optional);propsByKey=l(this.props,(T,o)=>[o.key,o]);propsByKeyReference=BT(this.propsByKey);expression=yY(this);requiredKeys=this.required?.map((T)=>T.key)??[];optionalKeys=this.optional?.map((T)=>T.key)??[];literalKeys=[...this.requiredKeys,...this.optionalKeys];_keyof;keyof(){if(this._keyof)return this._keyof;let T=this.$.units(this.literalKeys).branches;return this.index?.forEach(({signature:o})=>{T=T.concat(o.branches)}),this._keyof=this.$.node("union",T)}map(T){return this.$.node("structure",this.props.flatMap(T).reduce((o,y)=>{let A=this.propsByKey[y.key];if(zT(y)){if(y.kind!=="required"&&y.kind!=="optional")return E(`Map result must have kind "required" or "optional" (was ${y.kind})`);return o[y.kind]=FT(o[y.kind],y),o}let F=y.kind??A?.kind??"required",f=l(y,(S,$)=>(S in FF.implementation.keys)?[S,$]:[]);return o[F]=FT(o[F],this.$.node(F,f)),o},{}))}assertHasKeys(T){let o=T.filter((y)=>!SF(y,this.keyof()));if(o.length)return E(S1(this.expression,o))}get(T,...o){let y,A=!1,F=$Y(T);if((typeof F==="string"||typeof F==="symbol")&&this.propsByKey[F])y=this.propsByKey[F].value,A=this.propsByKey[F].required;if(this.index?.forEach((S)=>{if(SF(F,S.signature))y=y?.and(S.value)??S.value}),this.sequence&&SF(F,U.intrinsic.nonNegativeIntegerString))if(q(F,"root")){if(this.sequence.variadic)y=y?.and(this.sequence.element)??this.sequence.element}else{let S=Number.parseInt(F);if(S<this.sequence.prevariadic.length){let $=this.sequence.prevariadic[S].node;y=y?.and($)??$,A||=S<this.sequence.prefixLength}else if(this.sequence.variadic){let $=this.$.node("union",this.sequence.variadicOrPostfix);y=y?.and($)??$}}if(!y){if(this.sequence?.variadic&&q(F,"root")&&F.extends(U.intrinsic.number))return E(JY(F.expression,this.sequence.expression));return E(S1(this.expression,[F]))}let f=y.get(...o);return A?f:f.or(U.intrinsic.undefined)}pick(...T){return this.assertHasKeys(T),this.$.node("structure",this.filterKeys("pick",T))}omit(...T){return this.assertHasKeys(T),this.$.node("structure",this.filterKeys("omit",T))}optionalize(){let{required:T,...o}=this.inner;return this.$.node("structure",{...o,optional:this.props.map((y)=>y.hasKind("required")?this.$.node("optional",y.inner):y)})}require(){let{optional:T,...o}=this.inner;return this.$.node("structure",{...o,required:this.props.map((y)=>y.hasKind("optional")?{key:y.key,value:y.value}:y)})}merge(T){let o=this.filterKeys("omit",[T.keyof()]);if(T.required)o.required=FT(o.required,T.required);if(T.optional)o.optional=FT(o.optional,T.optional);if(T.index)o.index=FT(o.index,T.index);if(T.sequence)o.sequence=T.sequence;if(T.undeclared)o.undeclared=T.undeclared;else delete o.undeclared;return this.$.node("structure",o)}filterKeys(T,o){let y=aF(this.inner),A=(F)=>{let f=o.some((S)=>SF(F,S));return T==="pick"?f:!f};if(y.required)y.required=y.required.filter((F)=>A(F.key));if(y.optional)y.optional=y.optional.filter((F)=>A(F.key));if(y.index)y.index=y.index.filter((F)=>A(F.signature));return y}traverseAllows=(T,o)=>this._traverse("Allows",T,o);traverseApply=(T,o)=>this._traverse("Apply",T,o);_traverse=(T,o,y)=>{let A=y?.currentErrorCount??0;for(let F=0;F<this.props.length;F++)if(T==="Allows"){if(!this.props[F].traverseAllows(o,y))return!1}else if(this.props[F].traverseApply(o,y),y.failFast&&y.currentErrorCount>A)return!1;if(this.sequence){if(T==="Allows"){if(!this.sequence.traverseAllows(o,y))return!1}else if(this.sequence.traverseApply(o,y),y.failFast&&y.currentErrorCount>A)return!1}if(this.index||this.undeclared==="reject"){let F=Object.keys(o);F.push(...Object.getOwnPropertySymbols(o));for(let f=0;f<F.length;f++){let S=F[f];if(this.index){for(let $ of this.index)if($.signature.traverseAllows(S,y)){if(T==="Allows"){if(!Eo(S,()=>$.value.traverseAllows(o[S],y),y))return!1}else if(Eo(S,()=>$.value.traverseApply(o[S],y),y),y.failFast&&y.currentErrorCount>A)return!1}}if(this.undeclared==="reject"&&!this.declaresKey(S)){if(T==="Allows")return!1;if(y.errorFromNodeContext({code:"predicate",expected:"removed",actual:"",relativePath:[S],meta:this.meta}),y.failFast)return!1}}}if(this.structuralMorph&&y&&!y.hasError())y.queueMorphs([this.structuralMorph]);return!0};get defaultable(){return this.cacheGetter("defaultable",this.optional?.filter((T)=>T.hasDefault())??[])}declaresKey=(T)=>(T in this.propsByKey)||this.index?.some((o)=>o.signature.allows(T))||this.sequence!==void 0&&U.intrinsic.nonNegativeIntegerString.allows(T);_compileDeclaresKey(T){let o=[];if(this.props.length)o.push(`k in ${this.propsByKeyReference}`);if(this.index?.forEach((y)=>o.push(T.invoke(y.signature,{kind:"Allows",arg:"k"}))),this.sequence)o.push("$ark.intrinsic.nonNegativeIntegerString.allows(k)");return o.join(" || ")||"false"}get structuralMorph(){return this.cacheGetter("structuralMorph",fY(this))}structuralMorphRef=this.structuralMorph&&BT(this.structuralMorph);compile(T){if(T.traversalKind==="Apply")T.initializeErrorCount();if(this.props.forEach((o)=>{if(T.check(o),T.traversalKind==="Apply")T.returnIfFailFast()}),this.sequence){if(T.check(this.sequence),T.traversalKind==="Apply")T.returnIfFailFast()}if(this.index||this.undeclared==="reject")T.const("keys","Object.keys(data)"),T.line("keys.push(...Object.getOwnPropertySymbols(data))"),T.for("i < keys.length",()=>this.compileExhaustiveEntry(T));if(T.traversalKind==="Allows")return T.return(!0);if(this.structuralMorphRef)T.if("ctx && !ctx.hasError()",()=>{return T.line("ctx.queueMorphs(["),SY(T,this),T.line("])")})}compileExhaustiveEntry(T){if(T.const("k","keys[i]"),this.index?.forEach((o)=>{T.if(`${T.invoke(o.signature,{arg:"k",kind:"Allows"})}`,()=>T.traverseKey("k","data[k]",o.value))}),this.undeclared==="reject")T.if(`!(${this._compileDeclaresKey(T)})`,()=>{if(T.traversalKind==="Allows")return T.return(!1);return T.line(`ctx.errorFromNodeContext({ code: "predicate", expected: "removed", actual: "", relativePath: [k], meta: ${this.compiledMeta} })`).if("ctx.failFast",()=>T.return())});return T}reduceJsonSchema(T,o){switch(T.type){case"object":return this.reduceObjectJsonSchema(T,o);case"array":if(this.props.length||this.index)return JT.throwUnjsonifiableError(`Additional properties on array ${this.expression}`);return this.sequence?.reduceJsonSchema(T,o)??T;default:return JT.throwInternalOperandError("structure",T)}}reduceObjectJsonSchema(T,o){if(this.props.length){if(T.properties={},this.props.forEach((y)=>{if(typeof y.key==="symbol")return JT.throwUnjsonifiableError(`Symbolic key ${y.serializedKey}`);let A=y.value.toJsonSchemaRecurse(o);if(y.hasDefault()){let F=typeof y.default==="function"?y.default():y.default;A.default=F}T.properties[y.key]=A}),this.requiredKeys.length)T.required=this.requiredKeys}if(this.index?.forEach((y)=>{if(y.signature.equals(U.intrinsic.string))return T.additionalProperties=y.value.toJsonSchemaRecurse(o);if(!y.signature.extends(U.intrinsic.string))return JT.throwUnjsonifiableError(`Symbolic index signature ${y.signature.exclude(U.intrinsic.string)}`);y.signature.branches.forEach((A)=>{if(!A.hasKind("intersection")||A.inner.pattern?.length!==1)return JT.throwUnjsonifiableError(`Index signature ${A}`);T.patternProperties??={},T.patternProperties[A.inner.pattern[0].rule]=y.value.toJsonSchemaRecurse(o)})}),this.undeclared&&!T.additionalProperties)T.additionalProperties=!1;return T}}var E$={},FY=(T)=>{let o="";for(let y=0;y<T.defaultable.length;y++)o+=T.defaultable[y].defaultValueMorphRef;if(T.sequence?.defaultValueMorphsReference)o+=T.sequence?.defaultValueMorphsReference;if(T.undeclared==="delete"){if(o+="delete !(",T.required?.forEach((y)=>o+=y.compiledKey+" | "),T.optional?.forEach((y)=>o+=y.compiledKey+" | "),T.index?.forEach((y)=>o+=y.signature.id+" | "),T.sequence)if(T.sequence.maxLength===null)o+=g.nonNegativeIntegerString.id;else o+=T.sequence.tuple.forEach((y,A)=>o+=A+" | ");o+=")"}return o},fY=(T)=>{let o=FY(T);if(!o)return;if(E$[o])return E$[o];let y=(A,F)=>{for(let f=0;f<T.defaultable.length;f++)if(!(T.defaultable[f].key in A))T.defaultable[f].defaultValueMorph(A,F);if(T.sequence?.defaultables)for(let f=A.length-T.sequence.prefixLength;f<T.sequence.defaultables.length;f++)T.sequence.defaultValueMorphs[f](A,F);if(T.undeclared==="delete"){for(let f in A)if(!T.declaresKey(f))delete A[f]}return A};return E$[o]=y},SY=(T,o)=>{let A=`(data${o.defaultable.some((F)=>F.defaultValueMorph.length===2)||o.sequence?.defaultValueMorphs.some((F)=>F.length===2)?", ctx":""})`;return T.block(`${A} => `,(F)=>{for(let f=0;f<o.defaultable.length;f++){let{serializedKey:S,defaultValueMorphRef:$}=o.defaultable[f];F.if(`!(${S} in data)`,(_)=>_.line(`${$}${A}`))}if(o.sequence?.defaultables)F.for(`i < ${o.sequence.defaultables.length}`,(f)=>f.set("data[i]",5),`data.length - ${o.sequence.prefixLength}`);if(o.undeclared==="delete")F.forIn("data",(f)=>f.if(`!(${o._compileDeclaresKey(f)})`,(S)=>S.line("delete data[k]")));return F.return("data")})},G$={implementation:AY,Node:J1},$Y=(T)=>{if(q(T,"root")&&T.hasKind("unit"))T=T.unit;if(typeof T==="number")T=`${T}`;return T},JY=(T,o)=>`${T} is not allowed as an array index on ${o}. Use the 'nonNegativeIntegerString' keyword instead.`,_f=(T,o,y)=>{let[A,F]=B0(T.branches,(S)=>S.hasKind("unit"));if(!A.length)return{index:y.node("index",{signature:T,value:o})};let f={};if(A.forEach((S)=>{let $=y.node("required",{key:S.unit,value:o});f[$.kind]=FT(f[$.kind],$)}),F.length)f.index=y.node("index",{signature:F,value:o});return f},_Y=(T)=>q(T,"root")?T.expression:d(T),S1=(T,o)=>`Key${o.length===1?"":"s"} ${o.map(_Y).join(", ")} ${o.length===1?"does":"do"} not exist on ${T}`;var OA={...N_,alias:$F.implementation,domain:Jf.implementation,unit:M$.implementation,proto:JF.implementation,union:O$.implementation,morph:R$.implementation,intersection:_$.implementation,divisor:rS.implementation,pattern:A$.implementation,predicate:dS.implementation,required:Y$.implementation,optional:FF.implementation,index:X$.implementation,sequence:Z$.implementation,structure:G$.implementation};U.defaultConfig=v0(Object.assign(l(OA,(T,o)=>[T,o.defaults]),{jitless:i0(),clone:n0,onUndeclaredKey:"ignore",exactOptionalPropertyTypes:!0,numberAllowsNaN:!1,dateAllowsInvalid:!1,onFail:null,keywords:{}}));U.resolvedConfig=sA(U.defaultConfig,U.config);var m_={...t_,alias:$F.Node,domain:Jf.Node,unit:M$.Node,proto:JF.Node,union:O$.Node,morph:R$.Node,intersection:_$.Node,divisor:rS.Node,pattern:A$.Node,predicate:dS.Node,required:Y$.Node,optional:FF.Node,index:X$.Node,sequence:Z$.Node,structure:G$.Node};class YA extends kS{get[Ro](){return"module"}}var w$=(T,o)=>new YA(l(T,(y,A)=>[y,q(A,"module")?w$(A,o):o.bindReference(A)]));var RY=(T)=>ET(T)?T:("branches"in T)&&ET(T.branches)?T.branches:void 0,WY=(T,o)=>E(`Node of kind ${o} is not valid as a ${T} definition`),_1=(T)=>`#${T} duplicates public alias ${T}`,U$={};U.ambient??={};var R1,O1="function $",OY=(T)=>M1(T,X1(T)),M1=(T,o)=>{let y=o.write(O1,4),A=o.compile()();for(let F of T){if(F.precompilation)continue;if(F.traverseAllows=A[`${F.id}Allows`].bind(A),F.isRoot()&&!F.allowsRequiresContext)F.allows=F.traverseAllows;if(F.traverseApply=A[`${F.id}Apply`].bind(A),A[`${F.id}Optimistic`])F.traverseOptimistic=A[`${F.id}Optimistic`].bind(A);F.precompilation=y}},X1=(T)=>new sF().return(T.reduce((o,y)=>{let A=new lA({kind:"Allows"}).indent();y.compile(A);let F=A.write(`${y.id}Allows`),f=new lA({kind:"Apply"}).indent();y.compile(f);let S=f.write(`${y.id}Apply`),$=`${o}${F},
|
|
38
|
+
${S},
|
|
39
|
+
`;if(!y.hasKind("union"))return $;let _=new lA({kind:"Allows",optimistic:!0}).indent();y.compile(_);let J=_.write(`${y.id}Optimistic`);return`${$}${J},
|
|
40
|
+
`},`{
|
|
41
|
+
`)+"}");class Rf{config;resolvedConfig;name;get[Ro](){return"scope"}referencesById={};references=[];resolutions={};exportedNames=[];aliases={};resolved=!1;nodesByHash={};intrinsic;constructor(T,o){if(this.config=sA(U.config,o),this.resolvedConfig=sA(U.resolvedConfig,o),this.name=this.resolvedConfig.name??`anonymousScope${Object.keys(U$).length}`,this.name in U$)E(`A Scope already named ${this.name} already exists`);U$[this.name]=this,Object.entries(T).map((A)=>this.preparseOwnAliasEntry(...A)).forEach(([A,F])=>{let f=A;if(A[0]==="#"){if(f=A.slice(1),f in this.aliases)E(_1(f));this.aliases[f]=F}else{if(f in this.aliases)E(_1(A));this.aliases[f]=F,this.exportedNames.push(f)}if(!q(F,"module")&&!q(F,"generic")&&!zy(F)){let S=this.preparseOwnDefinitionFormat(F,{alias:f});if(q(S,"root"))this.resolutions[f]=this.bindReference(S);else this.resolutions[f]=this.createParseContext(S).id}}),R1??=this.node("union",{branches:["string","number","object","bigint","symbol",{unit:!0},{unit:!1},{unit:void 0},{unit:null}]},{prereduced:!0}),this.nodesByHash[R1.hash]=this.node("intersection",{},{prereduced:!0}),this.intrinsic=U.intrinsic?l(U.intrinsic,(A,F)=>A.startsWith("json")?[]:[A,this.bindReference(F)]):{}}cacheGetter(T,o){return Object.defineProperty(this,T,{value:o}),o}get internal(){return this}_json;get json(){if(!this._json)this.export();return this._json}defineSchema(T){return T}generic=(...T)=>{let o=this;return(y,A)=>new Cy(T,A?new yf(y):y,o,o,A??null)};units=(T,o)=>{let y=[];for(let F of T)if(!y.includes(F))y.push(F);let A=y.map((F)=>this.node("unit",{unit:F},o));return this.node("union",A,{...o,prereduced:!0})};lazyResolutions=[];lazilyResolve(T,o){let y=this.node("alias",{reference:o??"synthetic",resolve:T},{prereduced:!0});if(!this.resolved)this.lazyResolutions.push(y);return y}schema=(T,o)=>this.finalize(this.parseSchema(T,o));parseSchema=(T,o)=>this.node(oF(T),T,o);preparseNode(T,o,y){let A=typeof T==="string"?T:oF(o,T);if(zT(o)&&o.kind===A)return o;if(A==="alias"&&!y?.prereduced){let{reference:S}=$F.implementation.normalize(o,this);if(S.startsWith("$")){let $=this.resolveRoot(S.slice(1));o=$,A=$.kind}}else if(A==="union"&&Yo(o,"object")){let S=RY(o);if(S?.length===1)o=S[0],A=oF(o)}if(zT(o)&&o.kind===A)return o;let f=OA[A].normalize?.(o,this)??o;if(zT(f))return f.kind===A?f:WY(A,f.kind);return{...y,$:this,kind:A,def:f,prefix:y.alias??A}}bindReference(T){let o;if(zT(T))o=T.$===this?T:new T.constructor(T.attachments,this);else o=T.$===this?T:new Cy(T.params,T.bodyDef,T.$,this,T.hkt);if(!this.resolved)Object.assign(this.referencesById,o.referencesById);return o}resolveRoot(T){return this.maybeResolveRoot(T)??E(Q$(T))}maybeResolveRoot(T){let o=this.maybeResolve(T);if(q(o,"generic"))return;return o}maybeResolveSubalias(T){return K$(this.aliases,T)??K$(this.ambient,T)}get ambient(){return U.ambient}maybeResolve(T){let o=this.resolutions[T];if(o){if(typeof o!=="string")return this.bindReference(o);let A=Wo[o];if(q(A,"root"))return this.resolutions[T]=A;if(q(A,"context")){if(A.phase==="resolving")return this.node("alias",{reference:`$${T}`},{prereduced:!0});if(A.phase==="resolved")return $T(`Unexpected resolved context for was uncached by its scope: ${d(A)}`);A.phase="resolving";let F=this.bindReference(this.parseOwnDefinitionFormat(A.def,A));return A.phase="resolved",Wo[F.id]=F,Wo[A.id]=F,this.resolutions[T]=F}return $T(`Unexpected nodesById entry for ${o}: ${d(A)}`)}let y=this.aliases[T]??this.ambient?.[T];if(!y)return this.maybeResolveSubalias(T);if(y=this.normalizeRootScopeValue(y),q(y,"generic"))return this.resolutions[T]=this.bindReference(y);if(q(y,"module"))if(y.root)return this.resolutions[T]=this.bindReference(y.root);else return E(H1(T));return this.resolutions[T]=this.parse(y,{alias:T})}createParseContext(T){let o=T.id??F$(T.prefix);return Wo[o]=Object.assign(T,{[Ro]:"context",$:this,id:o,phase:"unresolved"})}traversal(T){return new no(T,this.resolvedConfig)}import(...T){return new YA(l(this.export(...T),(o,y)=>[`#${o}`,y]))}precompilation;_exportedResolutions;_exports;export(...T){if(!this._exports){this._exports={};for(let y of this.exportedNames){let A=this.aliases[y];this._exports[y]=q(A,"module")?w$(A,this):W1(this.maybeResolve(y))}if(this.lazyResolutions.forEach((y)=>y.resolution),this._exportedResolutions=Z1(this,this._exports),this._json=Y1(this._exportedResolutions),Object.assign(this.resolutions,this._exportedResolutions),this.references=Object.values(this.referencesById),!this.resolvedConfig.jitless){let y=X1(this.references);this.precompilation=y.write(O1,4),M1(this.references,y)}this.resolved=!0}let o=T.length?T:this.exportedNames;return new YA(l(o,(y,A)=>[A,this._exports[A]]))}resolve(T){return this.export()[T]}node=(T,o,y={})=>{let A=this.preparseNode(T,o,y);if(zT(A))return this.bindReference(A);let F=this.createParseContext(A),f=f$(F),S=this.bindReference(f);return Wo[F.id]=S};parse=(T,o={})=>this.finalize(this.parseDefinition(T,o));parseDefinition(T,o={}){if(q(T,"root"))return this.bindReference(T);let y=this.preparseOwnDefinitionFormat(T,o);if(q(y,"root"))return this.bindReference(y);let A=this.createParseContext(y);Wo[A.id]=A;let F=this.bindReference(this.parseOwnDefinitionFormat(T,A));if(F.isCyclic)F=j_(F,A.id);return Wo[A.id]=F,F}finalize(T){if(W1(T),!T.precompilation&&!this.resolvedConfig.jitless)OY(T.references);return T}}class z$ extends Rf{parseOwnDefinitionFormat(T,o){return f$(o)}preparseOwnDefinitionFormat(T,o){return this.preparseNode(oF(T),T,o)}preparseOwnAliasEntry(T,o){return[T,o]}normalizeRootScopeValue(T){return T}}var W1=(T)=>{return T.references.filter((o)=>o.hasKind("alias")).forEach((o)=>{Object.assign(o.referencesById,o.resolution.referencesById),T.references.forEach((y)=>{if(o.id in y.referencesById)Object.assign(y.referencesById,o.referencesById)})}),T},Y1=(T)=>l(T,(o,y)=>[o,q(y,"root")||q(y,"generic")?y.json:q(y,"module")?Y1(y):$T(`Unexpected resolution ${d(y)}`)]),K$=(T,o)=>{let y=o.indexOf(".");if(y===-1)return;let A=o.slice(0,y),F=T[A];if(F===void 0)return;if(!q(F,"module"))return E(MY(A));let f=o.slice(y+1),S=F[f];if(S===void 0)return K$(F,f);if(q(S,"root")||q(S,"generic"))return S;if(q(S,"module"))return S.root??E(H1(o));$T(`Unexpected resolution for alias '${o}': ${d(S)}`)},Wf=(T,o)=>new z$(T,o),RF=new z$({});var Z1=(T,o)=>{let y={};for(let A in o){let F=o[A];if(q(F,"module")){let f=Z1(T,F),S=l(f,($,_)=>[`${A}.${$}`,_]);Object.assign(y,S)}else if(q(F,"root")||q(F,"generic"))y[A]=F;else $T(`Unexpected scope resolution ${d(F)}`)}return y},Q$=(T)=>`'${T}' is unresolvable`,MY=(T)=>`'${T}' must reference a module to be accessed using dot syntax`,H1=(T)=>`Reference to submodule '${T}' must specify an alias`;RF.export();var{schema:MT,node:ZA,defineSchema:KU,generic:to}=RF;var V$="^(?:0|[1-9]\\d*)$",XY=new RegExp(V$),VU=BT(XY);var E1=Wf({bigint:"bigint",boolean:[{unit:!1},{unit:!0}],false:{unit:!1},never:[],null:{unit:null},number:"number",object:"object",string:"string",symbol:"symbol",true:{unit:!0},unknown:{},undefined:{unit:void 0},Array,Date},{prereducedAliases:!0}).export();U.intrinsic={...E1};var G1=Wf({integer:{domain:"number",divisor:1},lengthBoundable:["string",Array],key:["string","symbol"],nonNegativeIntegerString:{domain:"string",pattern:V$}},{prereducedAliases:!0}).export();Object.assign(U.intrinsic,G1);var YY=Wf({jsonPrimitive:["string","number",{unit:!0},{unit:!1},{unit:null}],jsonObject:{domain:"object",index:{signature:"string",value:"$jsonData"}},jsonData:["$jsonPrimitive","$jsonObject"]},{prereducedAliases:!0}).export(),g={...E1,...G1,...YY,emptyStructure:ZA("structure",{},{prereduced:!0})};U.intrinsic={...g};var U1=(T)=>typeof T==="string"&&T[0]==="d"&&(T[1]==="'"||T[1]==='"')&&T.at(-1)===T[1],w1=(T)=>T.toString()!=="Invalid Date",K1=(T)=>T.slice(2,-1),D$=(T)=>`'${T}' could not be parsed by the Date constructor`,z1=(T,o)=>ZY(T,o),ZY=(T,o)=>{let y=new Date(T);if(w1(y))return y;let A=o_(T);if(A!==void 0){let F=new Date(A);if(w1(F))return F}return o?E(o===!0?D$(T):o):void 0};var C$=(T,o)=>{let y=T.scanner.shiftUntil(HY[V1[o]]);if(T.scanner.lookahead==="")return T.error(GY(y,o));if(T.scanner.shift(),o==="/"){try{new RegExp(y)}catch(A){E(String(A))}T.root=T.ctx.$.node("intersection",{domain:"string",pattern:y},{prereduced:!0})}else if(pT(o,L$))T.root=T.ctx.$.node("unit",{unit:y});else{let A=z1(y,D$(y));T.root=T.ctx.$.node("unit",{meta:y,unit:A})}},L$={"'":1,'"':1},Q1={"/":1,"'":1,'"':1},V1={"d'":"'",'d"':'"',"'":"'",'"':'"',"/":"/"},HY={"'":(T)=>T.lookahead==="'",'"':(T)=>T.lookahead==='"',"/":(T)=>T.lookahead==="/"},EY={'"':"double-quote","'":"single-quote","/":"forward slash"},GY=(T,o)=>`${o}${T} requires a closing ${EY[V1[o]]}`;var D1=(T)=>`Private type references should not include '#'. Use '${T}' instead.`,Of="Optional definitions like 'string?' are only valid as properties in an object or tuple",Mf="Defaultable definitions like 'number = 0' are only valid as properties in an object or tuple";var C1={">":!0,">=":!0},L1={"<":!0,"<=":!0};var HA={"<":">",">":"<","<=":">=",">=":"<=","==":"=="},I1=(T)=>`Unmatched )${T===""?"":` before ${T}`}`,Xf=(T)=>`Missing ${T}`,k1=(T,o)=>`Left bounds are only valid when paired with right bounds (try ...${o}${T})`,Yf=(T)=>`Left-bounded expressions must specify their limits using < or <= (was ${T})`,B1=(T,o,y,A)=>`An expression may have at most one left bound (parsed ${T}${HA[o]}, ${y}${HA[A]})`;var N1=(T,o,y)=>t1(T,o,y,[]),t1=(T,o,y,A)=>{let F=y.parseUntilFinalizer();if(A.push(F.root),F.finalizer===">"){if(A.length!==o.params.length)return y.error(I$(T,o.names,A.map((f)=>f.expression)));return A}if(F.finalizer===",")return t1(T,o,y,A);return F.error(Xf(">"))},I$=(T,o,y)=>`${T}<${o.join(", ")}> requires exactly ${o.length} args (got ${y.length}${y.length===0?"":`: ${y.join(", ")}`})`;var k$=(T)=>{let o=T.scanner.shiftUntilNextTerminator();if(o==="keyof")T.addPrefix("keyof");else T.root=UY(T,o)},wY=(T,o,y)=>{if(y.scanner.shiftUntilNonWhitespace(),y.scanner.shift()!=="<")return y.error(I$(T,o.names,[]));let F=N1(T,o,y);return o(...F)},UY=(T,o)=>KY(T,o)??zY(T,o)??T.error(o===""?T.scanner.lookahead==="#"?D1(T.shiftedByOne().scanner.shiftUntilNextTerminator()):B$(T):Q$(o)),KY=(T,o)=>{if(T.ctx.args?.[o]){let A=T.ctx.args[o];if(typeof A!=="string")return A;return T.ctx.$.node("alias",{reference:A},{prereduced:!0})}let y=T.ctx.$.maybeResolve(o);if(q(y,"root"))return y;if(y===void 0)return;if(q(y,"generic"))return wY(o,y,T);return E(`Unexpected resolution ${d(y)}`)},zY=(T,o)=>{let y=y_(o);if(y!==void 0)return T.ctx.$.node("unit",{unit:y});let A=F_(o);if(A!==void 0)return T.ctx.$.node("unit",{unit:A})},B$=(T)=>{let o=T.previousOperator();return o?N$(o,T.scanner.unscanned):QY(T.scanner.unscanned)},N$=(T,o="")=>`Token '${T}' requires a right operand${o?` before '${o}'`:""}`,QY=(T)=>`Expected an expression${T?` before '${T}'`:""}`;var t$=(T)=>T.scanner.lookahead===""?T.error(B$(T)):T.scanner.lookahead==="("?T.shiftedByOne().reduceGroupOpen():T.scanner.lookaheadIsIn(Q1)?C$(T,T.scanner.shift()):T.scanner.lookaheadIsIn(Qy)?t$(T.shiftedByOne()):T.scanner.lookahead==="d"?T.scanner.nextLookahead in L$?C$(T,`${T.scanner.shift()}${T.scanner.shift()}`):k$(T):k$(T);class Oy extends qS{shiftUntilNextTerminator(){return this.shiftUntilNonWhitespace(),this.shiftUntil(()=>(this.lookahead in Oy.terminatingChars))}static terminatingChars={"<":1,">":1,"=":1,"|":1,"&":1,")":1,"[":1,"%":1,",":1,":":1,"?":1,"#":1,...Qy};static finalizingLookaheads={">":1,",":1,"":1,"=":1,"?":1};static lookaheadIsFinalizing=(T,o)=>T===">"?o[0]==="="?o[1]==="=":o.trimStart()===""||pT(o.trimStart()[0],Oy.terminatingChars):T==="="?o[0]!=="=":T===","||T==="?"}var b1=(T,o)=>{let y=VY(T,o);if(T.root.hasKind("unit")){if(typeof T.root.unit==="number"){T.reduceLeftBound(T.root.unit,y),T.unsetRoot();return}if(T.root.unit instanceof Date){let A=`d'${T.root.description??T.root.unit.toISOString()}'`;T.unsetRoot(),T.reduceLeftBound(A,y);return}}return CY(T,y)},x1={"<":1,">":1,"=":1},VY=(T,o)=>T.scanner.lookaheadIs("=")?`${o}${T.scanner.shift()}`:o;var p1=(T,o,y,A)=>{if(y.extends(U.intrinsic.number)){if(typeof o!=="number")return E(p$(T,o,A));return T==="=="?["min","max"]:T[0]===">"?["min"]:["max"]}if(y.extends(U.intrinsic.lengthBoundable)){if(typeof o!=="number")return E(p$(T,o,A));return T==="=="?["exactLength"]:T[0]===">"?["minLength"]:["maxLength"]}if(y.extends(U.intrinsic.Date))return T==="=="?["after","before"]:T[0]===">"?["after"]:["before"];return E(Q_(y.expression))},DY=(T)=>({rule:U1(T.limit)?K1(T.limit):T.limit,exclusive:T.comparator.length===1}),CY=(T,o)=>{let y=T.unsetRoot(),A=T.scanner.location;T.parseOperand();let F=T.unsetRoot(),f=T.scanner.sliceChars(A,T.scanner.location);if(T.root=y,!F.hasKind("unit")||typeof F.unit!=="number"&&!(F.unit instanceof Date))return T.error(p$(o,f,"right"));let S=F.unit,$=o.length===1,_=p1(o,typeof S==="number"?S:f,y,"right");for(let R of _)T.constrainRoot(R,o==="=="?{rule:S}:{rule:S,exclusive:$});if(!T.branches.leftBound)return;if(!pT(o,L1))return T.error(Yf(o));let J=p1(T.branches.leftBound.comparator,T.branches.leftBound.limit,y,"left");T.constrainRoot(J[0],DY(T.branches.leftBound)),T.branches.leftBound=null},p$=(T,o,y)=>`Comparator ${y==="left"?HA[T]:T} must be ${y==="left"?"preceded":"followed"} by a corresponding literal (was ${o})`;var j1=(T)=>{T.scanner.shiftUntilNonWhitespace();let o=T.scanner.shiftUntilNextTerminator();T.root=T.root.brand(o)};var q1=(T)=>{let o=T.scanner.shiftUntilNextTerminator(),y=A_(o,{errorOnFail:m1(o)});if(y===0)T.error(m1(0));T.root=T.root.constrain("divisor",y)},m1=(T)=>`% operator must be followed by a non-zero integer literal (was ${T})`;var b$=(T)=>{let o=T.scanner.shift();return o===""?T.finalize(""):o==="["?T.scanner.shift()==="]"?T.setRoot(T.root.array()):T.error(LY):o==="|"?T.scanner.lookahead===">"?T.shiftedByOne().pushRootToBranch("|>"):T.pushRootToBranch(o):o==="&"?T.pushRootToBranch(o):o===")"?T.finalizeGroup():Oy.lookaheadIsFinalizing(o,T.scanner.unscanned)?T.finalize(o):pT(o,x1)?b1(T,o):o==="%"?q1(T):o==="#"?j1(T):(o in Qy)?b$(T):T.error(Zf(o))},Zf=(T,o="")=>`'${T}' is not allowed here${o&&` (should be ${o})`}`,LY="Missing expected ']'";var v1=(T)=>{let o=T.unsetRoot();T.parseOperand();let y=T.unsetRoot();if(!y.hasKind("unit"))return T.error(IY(y.expression));let A=y.unit instanceof Date?()=>new Date(y.unit):y.unit;return[o,"=",A]},IY=(T)=>`Default value '${T}' must a literal value`;var x$=(T,o)=>{let y=o.$.maybeResolveRoot(T);if(y)return y;if(T.endsWith("[]")){let f=o.$.maybeResolveRoot(T.slice(0,-2));if(f)return f.array()}let A=new EA(new Oy(T),o),F=kY(A);if(A.finalizer===">")E(Zf(">"));return F},kY=(T)=>{T.parseOperand();let o=WF(T).root;if(!o)return $T(`Root was unexpectedly unset after parsing string '${T.scanner.scanned}'`);if(T.finalizer==="=")o=v1(T);else if(T.finalizer==="?")o=[o,"?"];if(T.scanner.shiftUntilNonWhitespace(),T.scanner.lookahead)E(Zf(T.scanner.lookahead));return o},WF=(T)=>{while(T.finalizer===void 0)BY(T);return T},BY=(T)=>T.hasRoot()?T.parseOperator():T.parseOperand();class EA{root;branches={prefixes:[],leftBound:null,intersection:null,union:null,pipe:null};finalizer;groups=[];scanner;ctx;constructor(T,o){this.scanner=T,this.ctx=o}error(T){return E(T)}hasRoot(){return this.root!==void 0}setRoot(T){this.root=T}unsetRoot(){let T=this.root;return this.root=void 0,T}constrainRoot(...T){this.root=this.root.constrain(T[0],T[1])}finalize(T){if(this.groups.length)return this.error(Xf(")"));this.finalizeBranches(),this.finalizer=T}reduceLeftBound(T,o){let y=HA[o];if(!pT(y,C1))return this.error(Yf(o));if(this.branches.leftBound)return this.error(B1(this.branches.leftBound.limit,this.branches.leftBound.comparator,T,y));this.branches.leftBound={comparator:y,limit:T}}finalizeBranches(){if(this.assertRangeUnset(),this.branches.pipe){this.pushRootToBranch("|>"),this.root=this.branches.pipe;return}if(this.branches.union){this.pushRootToBranch("|"),this.root=this.branches.union;return}if(this.branches.intersection){this.pushRootToBranch("&"),this.root=this.branches.intersection;return}this.applyPrefixes()}finalizeGroup(){this.finalizeBranches();let T=this.groups.pop();if(!T)return this.error(I1(this.scanner.unscanned));this.branches=T}addPrefix(T){this.branches.prefixes.push(T)}applyPrefixes(){while(this.branches.prefixes.length){let T=this.branches.prefixes.pop();this.root=T==="keyof"?this.root.keyof():$T(`Unexpected prefix '${T}'`)}}pushRootToBranch(T){this.assertRangeUnset(),this.applyPrefixes();let o=this.root;if(this.root=void 0,this.branches.intersection=this.branches.intersection?.rawAnd(o)??o,T==="&")return;if(this.branches.union=this.branches.union?.rawOr(this.branches.intersection)??this.branches.intersection,this.branches.intersection=null,T==="|")return;this.branches.pipe=this.branches.pipe?.rawPipeOnce(this.branches.union)??this.branches.union,this.branches.union=null}parseUntilFinalizer(){return WF(new EA(this.scanner,this.ctx))}parseOperator(){return b$(this)}parseOperand(){return t$(this)}assertRangeUnset(){if(this.branches.leftBound)return this.error(k1(this.branches.leftBound.limit,this.branches.leftBound.comparator))}reduceGroupOpen(){this.groups.push(this.branches),this.branches={prefixes:[],leftBound:null,union:null,intersection:null,pipe:null}}previousOperator(){return this.branches.leftBound?.comparator??this.branches.prefixes.at(-1)??(this.branches.intersection?"&":this.branches.union?"|":this.branches.pipe?"|>":void 0)}shiftedByOne(){return this.scanner.shift(),this}}var NY="An empty string is not a valid generic parameter name",Hf=(T,o,y)=>{T.shiftUntilNonWhitespace();let A=T.shiftUntilNextTerminator();if(A===""){if(T.lookahead===""&&o.length)return o;return E(NY)}return T.shiftUntilNonWhitespace(),tY(T,A,o,y)},P1="extends ",tY=(T,o,y,A)=>{if(T.shiftUntilNonWhitespace(),T.unscanned.startsWith(P1))T.jumpForward(P1.length);else{if(T.lookahead===",")T.shift();return y.push(o),Hf(T,y,A)}let F=WF(new EA(T,A));return y.push([o,F.root]),Hf(T,y,A)};class j$ extends ho{$;constructor(T){super((...o)=>new OF(T)(...o),{bind:T});this.$=T}in(T){return new OF(this.$,T===void 0?void 0:this.$.parse(T))}at(T,o){return new OF(this.$).at(T,o)}case(T,o){return new OF(this.$).case(T,o)}}class OF extends ho{$;in;key;branches=[];constructor(T,o){super((y)=>this.caseEntries(Object.entries(y).map(([A,F])=>A==="default"?[A,F]:[this.$.parse(A),F])));this.$=T,this.in=o}at(T,o){if(this.key)E(bY);if(this.branches.length)E(pY);return this.key=T,o?this.match(o):this}case(T,o){return this.caseEntry(this.$.parse(T),o)}caseEntry(T,o){let A=(this.key?this.$.parse({[this.key]:T}):T).pipe(o);return this.branches.push(A),this}match(T){return this(T)}strings(T){return this.caseEntries(Object.entries(T).map(([o,y])=>o==="default"?[o,y]:[this.$.node("unit",{unit:o}),y]))}caseEntries(T){for(let o=0;o<T.length;o++){let[y,A]=T[o];if(y==="default"){if(o!==T.length-1)E("default may only be specified as the last key of a switch definition");return this.default(A)}if(typeof A!=="function")return E(`Value for case "${y}" must be a function (was ${hT(A)})`);this.caseEntry(y,A)}return this}default(T){if(typeof T==="function")this.case(g.unknown,T);let o={branches:this.branches,ordered:!0};if(T==="never"||T==="assert")o.meta={onFail:h1};let y=this.$.node("union",o);if(!this.in)return this.$.finalize(y);let A=this.in.pipe(y);if(T==="never"||T==="assert")A=A.configureReferences({onFail:h1},"self");return this.$.finalize(A)}}var h1=(T)=>T.throw(),pY="A key matcher must be specified before the first case i.e. match.at('foo') or match.in<object>().at('bar')",bY="At most one key matcher may be specified per expression";var Ef=(T,o)=>{if(ET(T)){if(T[1]==="=")return[o.$.parseOwnDefinitionFormat(T[0],o),"=",T[2]];if(T[1]==="?")return[o.$.parseOwnDefinitionFormat(T[0],o),"?"]}return Gf(T,o)},n1="Only required keys may make their values optional, e.g. { [mySymbol]: ['number', '?'] }",g1="Only required keys may specify default values, e.g. { value: 'number = 0' }";var u1=(T,o)=>{let y,A={},F=PA(T);for(let[S,$]of F){let _=mY(S);if(_.kind==="spread"){if(!ao(A))return E(jY);let H=o.$.parseOwnDefinitionFormat($,o);if(H.equals(g.object))continue;if(!H.hasKind("intersection")||!H.basis?.equals(g.object))return E(qY(H.expression));y=H.structure;continue}if(_.kind==="undeclared"){if($!=="reject"&&$!=="delete"&&$!=="ignore")E(xY($));A.undeclared=$;continue}let J=Ef($,o),R=_;if(_.kind==="required"){if(!ET(J))m$(A,"required",{key:_.normalized,value:J},o);else m$(A,"optional",J[1]==="="?{key:_.normalized,value:J[0],default:J[2]}:{key:_.normalized,value:J[0]},o);continue}if(ET(J)){if(J[1]==="?")E(n1);if(J[1]==="=")E(g1)}if(_.kind==="optional"){m$(A,"optional",{key:_.normalized,value:J},o);continue}let M=o.$.parseOwnDefinitionFormat(R.normalized,o),Y=_f(M,J,o.$);if(Y.index)A.index=FT(A.index,Y.index);if(Y.required)A.required=FT(A.required,Y.required)}let f=o.$.node("structure",A);return o.$.parseSchema({domain:"object",structure:y?.merge(f)??f})},m$=(T,o,y,A)=>{T[o]=FT(T[o],A.$.node(o,y))},xY=(T)=>`Value of '+' key must be 'reject', 'delete', or 'ignore' (was ${d(T)})`,jY="Spread operator may only be used as the first key in an object",mY=(T)=>typeof T==="symbol"?{kind:"required",normalized:T}:T.at(-1)==="?"?T.at(-2)===uA?{kind:"required",normalized:`${T.slice(0,-2)}?`}:{kind:"optional",normalized:T.slice(0,-1)}:T[0]==="["&&T.at(-1)==="]"?{kind:"index",normalized:T.slice(1,-1)}:T[0]===uA&&T[1]==="["&&T.at(-1)==="]"?{kind:"required",normalized:T.slice(1)}:T==="..."?{kind:"spread"}:T==="+"?{kind:"undeclared"}:{kind:"required",normalized:T==="\\..."?"...":T==="\\+"?"+":T},qY=(T)=>`Spread operand must resolve to an object literal type (was ${T})`;var c1=(T,o)=>rY(T)?s1[T[0]](T,o):cY(T)?l1[T[1]](T,o):null,vY=(T,o)=>o.$.parseOwnDefinitionFormat(T[1],o).keyof(),q$=(T,o)=>{if(T[2]===void 0)return E(N$(T[1],""));let y=o.$.parseOwnDefinitionFormat(T[0],o),A=o.$.parseOwnDefinitionFormat(T[2],o);if(T[1]==="|")return o.$.node("union",{branches:[y,A]});let F=T[1]==="&"?Go(y,A,o.$):TF(y,A,o.$);if(F instanceof k)return F.throw();return F},PY=(T,o)=>o.$.parseOwnDefinitionFormat(T[0],o).array(),hY=(T,o)=>{if(typeof T[2]!=="function")return E(d1("=>",T[2]));return o.$.parseOwnDefinitionFormat(T[0],o).pipe(T[2])},d1=(T,o)=>`${T===":"?"Narrow":"Morph"} expression requires a function following '${T}' (was ${typeof o})`,nY=(T,o)=>{if(typeof T[2]!=="function")return E(d1(":",T[2]));return o.$.parseOwnDefinitionFormat(T[0],o).constrain("predicate",T[2])},gY=(T,o)=>o.$.parseOwnDefinitionFormat(T[0],o).configureReferences(T[2],"shallow"),r1=(T)=>T,uY=r1({"[]":PY,"?":()=>E(Of)}),iY=r1({"|":q$,"&":q$,":":nY,"=>":hY,"|>":q$,"@":gY,"=":()=>E(Mf)}),l1={...uY,...iY},cY=(T)=>l1[T[1]]!==void 0,dY=(T)=>T,s1=dY({keyof:vY,instanceof:(T,o)=>{if(typeof T[1]!=="function")return E(i1(nA(T[1])));let y=T.slice(1).map((A)=>typeof A==="function"?o.$.node("proto",{proto:A}):E(i1(nA(A))));return y.length===1?y[0]:o.$.node("union",{branches:y})},"===":(T,o)=>o.$.units(T.slice(1))}),rY=(T)=>s1[T[0]]!==void 0,i1=(T)=>`Expected a constructor following 'instanceof' operator (was ${T})`;var TR=(T,o)=>{let y=[{}],A=0;while(A<T.length){let F=!1;if(T[A]==="..."&&A<T.length-1)F=!0,A++;let f=Ef(T[A],o),[S,$,_]=!ET(f)?[f]:f;if(A++,F){if(!S.extends(U.intrinsic.Array))return E(aY(S.expression));y=y.flatMap((J)=>S.distribute((R)=>sY(aF(J),R)))}else y=y.map((J)=>{if($==="?")return oR(J,S);if($==="=")return lY(J,S,_);return v$(J,S)})}return o.$.parseSchema(y.map((F)=>ao(F)?{proto:Array,exactLength:0}:{proto:Array,sequence:F}))},v$=(T,o)=>{if(T.defaultables||T.optionals)return E(T.variadic?H$:eY);if(T.variadic)T.postfix=FT(T.postfix,o);else T.prefix=FT(T.prefix,o);return T},oR=(T,o)=>{if(T.variadic)return E(yR);return T.optionals=FT(T.optionals,o),T},lY=(T,o,y)=>{if(T.variadic)return E(yR);if(T.optionals)return E(T6);return T.defaultables=FT(T.defaultables,[[o,y]]),T},a1=(T,o)=>{if(T.postfix)E(e1);if(T.variadic){if(!T.variadic.equals(o))E(e1)}else T.variadic=o.internal;return T},sY=(T,o)=>{let y=o.select({method:"find",kind:"sequence"});if(!y)return a1(T,U.intrinsic.unknown);if(y.prefix?.forEach((A)=>v$(T,A)),y.optionals?.forEach((A)=>oR(T,A)),y.variadic)a1(T,y.variadic);return y.postfix?.forEach((A)=>v$(T,A)),T},aY=(T)=>`Spread element must be an array (was ${T})`,e1="A tuple may have at most one variadic element",eY="A required element may not follow an optional element",yR="An optional element may not follow a variadic element";var T6="A defaultable element may not follow an optional element without a default";var o6={},Gf=(T,o)=>{if(typeof T==="string"){if(o.args&&Object.keys(o.args).some((A)=>T.includes(A)))return x$(T,o);let y=o6[o.$.name]??={};return y[T]??=x$(T,o)}return Yo(T,"object")?y6(T,o):E(P$(hT(T)))},y6=(T,o)=>{let y=hA(T);switch(y){case void 0:if(q(T,"root"))return T;return u1(T,o);case"Array":return A6(T,o);case"RegExp":return o.$.node("intersection",{domain:"string",pattern:T},{prereduced:!0});case"Function":{let A=zy(T)?T():T;if(q(A,"root"))return A;return E(P$("Function"))}default:return E(P$(y??d(T)))}},A6=(T,o)=>c1(T,o)??TR(T,o),P$=(T)=>`Type definitions must be strings or objects (was ${T})`;class h$ extends ho{constructor(T){let o=Object.assign({errors:Ho,hkt:fo,$:T,raw:T.parse,module:T.constructor.module,scope:T.constructor.scope,define:T.define,match:T.match,generic:T.generic,schema:T.schema,keywords:T.ambient,unit:T.unit,enumerated:T.enumerated,instanceOf:T.instanceOf,valueOf:T.valueOf,or:T.or,and:T.and,merge:T.merge,pipe:T.pipe},T.ambientAttachments);super((...y)=>{if(y.length===1)return T.parse(y[0]);if(y.length===2&&typeof y[0]==="string"&&y[0][0]==="<"&&y[0].at(-1)===">"){let A=y[0].slice(1,-1),F=T.parseGenericParams(A,{});return new Cy(F,y[1],T,T,null)}return T.parse(y)},{bind:T,attach:o})}}var GA=U;class wf extends Rf{get ambientAttachments(){if(!GA.typeAttachments)return;return this.cacheGetter("ambientAttachments",l(GA.typeAttachments,(T,o)=>[T,this.bindReference(o)]))}preparseOwnAliasEntry(T,o){let y=T.indexOf("<");if(y===-1){if(q(o,"module")||q(o,"generic"))return[T,o];let f=this.name==="ark"?T:T==="root"?this.name:`${this.name}.${T}`,S=this.resolvedConfig.keywords?.[f];if(S)o=[o,"@",S];return[T,o]}if(T.at(-1)!==">")E("'>' must be the last character of a generic declaration in a scope");let A=T.slice(0,y),F=T.slice(y+1,-1);return[A,()=>{let f=this.parseGenericParams(F,{alias:A});return G_(f,o,this)}]}parseGenericParams(T,o){return Hf(new Oy(T),[],this.createParseContext({...o,def:T,prefix:"generic"}))}normalizeRootScopeValue(T){if(zy(T)&&!q(T,"generic"))return T();return T}preparseOwnDefinitionFormat(T,o){return{...o,def:T,prefix:o.alias??"type"}}parseOwnDefinitionFormat(T,o){if(!(o.alias&&(o.alias in this.aliases))&&!o.args)o.args={this:o.id};let A=Gf(T,o);if(ET(A)){if(A[1]==="=")return E(Mf);if(A[1]==="?")return E(Of)}return A}unit=(T)=>this.units([T]);valueOf=(T)=>this.units(P0(T));enumerated=(...T)=>this.units(T);instanceOf=(T)=>this.node("proto",{proto:T},{prereduced:!0});or=(...T)=>this.schema(T.map((o)=>this.parse(o)));and=(...T)=>T.reduce((o,y)=>o.and(this.parse(y)),this.intrinsic.unknown);merge=(...T)=>T.reduce((o,y)=>o.merge(this.parse(y)),this.intrinsic.object);pipe=(...T)=>this.intrinsic.unknown.pipe(...T);match=new j$(this);declare=()=>({type:this.type});define(T){return T}type=new h$(this);static scope=(T,o={})=>new wf(T,o);static module=(T,o={})=>this.scope(T,o).export()}var n$=Object.assign(wf.scope,{define:(T)=>T}),TT=wf;class AR extends fo{description='merge an object\'s properties onto another like `Merge(User, { isAdmin: "true" })`'}var F6=to(["base",g.object],["props",g.object])((T)=>T.base.merge(T.props),AR),FR=TT.module({Key:g.key,Merge:F6});class fR extends fo{}var f6=to("element")((T)=>{let o=T.element.exclude(g.Array),y=o.array();return o.rawOr(y).pipe(Ky).distribute((A)=>A.assertHasKind("morph").declareOut(y),MT)},fR),SR=TT.module({root:g.Array,readonly:"root",index:g.nonNegativeIntegerString,liftFrom:f6},{name:"Array"});var g$=MT(["string",my.FileConstructor]),S6=g$.rawOr(g$.array()),$R=MT({meta:"an object representing parsed form data",domain:"object",index:{signature:"string",value:S6}}),JR=TT.module({root:["instanceof",FormData],value:g$,parsed:$R,parse:MT({in:FormData,morphs:(T)=>{let o={};for(let[y,A]of T)if(y in o){let F=o[y];if(typeof F==="string"||F instanceof my.FileConstructor)o[y]=[F,A];else F.push(A)}else o[y]=A;return o},declaredOut:$R})},{name:"FormData"});var _R=TT.module({Int8:["instanceof",Int8Array],Uint8:["instanceof",Uint8Array],Uint8Clamped:["instanceof",Uint8ClampedArray],Int16:["instanceof",Int16Array],Uint16:["instanceof",Uint16Array],Int32:["instanceof",Int32Array],Uint32:["instanceof",Uint32Array],Float32:["instanceof",Float32Array],Float64:["instanceof",Float64Array],BigInt64:["instanceof",BigInt64Array],BigUint64:["instanceof",BigUint64Array]},{name:"TypedArray"});var $6={Boolean:1,Number:1,String:1},RR=TT.module({...l({...BS,...tS},(T,o)=>(T in $6)?[]:[T,["instanceof",o]]),Array:SR,TypedArray:_R,FormData:JR});var J6=MT({domain:{domain:"number",meta:"a number representing a Unix timestamp"},divisor:{rule:1,meta:"an integer representing a Unix timestamp"},min:{rule:-8640000000000000,meta:"a Unix timestamp after -8640000000000000"},max:{rule:8640000000000000,meta:"a Unix timestamp before 8640000000000000"},meta:"an integer representing a safe Unix timestamp"}),_6=MT({domain:"number",divisor:1}),Uf=TT.module({root:g.number,integer:_6,epoch:J6,safe:MT({domain:{domain:"number",numberAllowsNaN:!1},min:Number.MIN_SAFE_INTEGER,max:Number.MAX_SAFE_INTEGER}),NaN:["===",Number.NaN],Infinity:["===",Number.POSITIVE_INFINITY],NegativeInfinity:["===",Number.NEGATIVE_INFINITY]},{name:"number"});var LT=(T,o)=>ZA("intersection",{domain:"string",pattern:{rule:T.source,flags:T.flags,meta:o}}),WR=LT(iA,"a well-formed integer string"),KR=TT.module({root:WR,parse:MT({in:WR,morphs:(T,o)=>{let y=Number.parseInt(T);return Number.isSafeInteger(y)?y:o.error("an integer in the range Number.MIN_SAFE_INTEGER to Number.MAX_SAFE_INTEGER")},declaredOut:g.integer})},{name:"string.integer"}),R6=LT(/^[0-9a-fA-F]+$/,"hex characters only"),W6=TT.module({root:LT(/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,"base64-encoded"),url:LT(/^(?:[A-Za-z0-9_-]{4})*(?:[A-Za-z0-9_-]{2}(?:==|%3D%3D)?|[A-Za-z0-9_-]{3}(?:=|%3D)?)?$/,"base64url-encoded")},{name:"string.base64"}),OR=LT(/^[A-Z].*$/,"capitalized"),O6=TT.module({root:MT({in:"string",morphs:(T)=>T.charAt(0).toUpperCase()+T.slice(1),declaredOut:OR}),preformatted:OR},{name:"string.capitalize"}),M6=(T)=>{let o=T.replace(/[- ]+/g,""),y=0,A,F,f=!1;for(let S=o.length-1;S>=0;S--){if(A=o.substring(S,S+1),F=Number.parseInt(A,10),f)if(F*=2,F>=10)y+=F%10+1;else y+=F;else y+=F;f=!f}return!!(y%10===0?o:!1)},X6=/^(?:4[0-9]{12}(?:[0-9]{3,6})?|5[1-5][0-9]{14}|(222[1-9]|22[3-9][0-9]|2[3-6][0-9]{2}|27[01][0-9]|2720)[0-9]{12}|6(?:011|5[0-9][0-9])[0-9]{12,15}|3[47][0-9]{13}|3(?:0[0-5]|[68][0-9])[0-9]{11}|(?:2131|1800|35\d{3})\d{11}|6[27][0-9]{14}|^(81[0-9]{14,17}))$/,Y6=MT({domain:"string",pattern:{meta:"a credit card number",rule:X6.source},predicate:{meta:"a credit card number",predicate:M6}});var Z6=/^([+-]?\d{4}(?!\d{2}\b))((-?)((0[1-9]|1[0-2])(\3([12]\d|0[1-9]|3[01]))?|W([0-4]\d|5[0-3])(-?[1-7])?|(00[1-9]|0[1-9]\d|[12]\d{2}|3([0-5]\d|6[1-6])))([T]((([01]\d|2[0-3])((:?)[0-5]\d)?|24:?00)([.,]\d+(?!:))?)?(\17[0-5]\d([.,]\d+)?)?([zZ]|([+-])([01]\d|2[0-3]):?([0-5]\d)?)?)?)?$/;var H6=(T)=>!Number.isNaN(new Date(T).valueOf()),MR=MT({domain:"string",predicate:{meta:"a parsable date",predicate:H6}}).assertHasKind("intersection"),XR=KR.root.internal.narrow((T,o)=>{let y=Number.parseInt(T),A=Uf.epoch(y);if(A instanceof Ho)return o.errors.merge(A),!1;return!0}).configure({description:"an integer string representing a safe Unix timestamp"},"self").assertHasKind("intersection"),E6=TT.module({root:XR,parse:MT({in:XR,morphs:(T)=>new Date(T),declaredOut:g.Date})},{name:"string.date.epoch"}),YR=LT(Z6,"an ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) date").internal.assertHasKind("intersection"),G6=TT.module({root:YR,parse:MT({in:YR,morphs:(T)=>new Date(T),declaredOut:g.Date})},{name:"string.date.iso"}),w6=TT.module({root:MR,parse:MT({declaredIn:MR,in:"string",morphs:(T,o)=>{let y=new Date(T);if(Number.isNaN(y.valueOf()))return o.error("a parsable date");return y},declaredOut:g.Date}),iso:G6,epoch:E6},{name:"string.date"}),U6=LT(/^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$/,"an email address"),ZR="(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])",Ly=`(${ZR}[.]){3}${ZR}`,K6=new RegExp(`^${Ly}$`),jT="(?:[0-9a-fA-F]{1,4})",z6=new RegExp(`^((?:${jT}:){7}(?:${jT}|:)|(?:${jT}:){6}(?:${Ly}|:${jT}|:)|(?:${jT}:){5}(?::${Ly}|(:${jT}){1,2}|:)|(?:${jT}:){4}(?:(:${jT}){0,1}:${Ly}|(:${jT}){1,3}|:)|(?:${jT}:){3}(?:(:${jT}){0,2}:${Ly}|(:${jT}){1,4}|:)|(?:${jT}:){2}(?:(:${jT}){0,3}:${Ly}|(:${jT}){1,5}|:)|(?:${jT}:){1}(?:(:${jT}){0,4}:${Ly}|(:${jT}){1,6}|:)|(?::((?::${jT}){0,5}:${Ly}|(?::${jT}){1,7}|:)))(%[0-9a-zA-Z.]{1,})?$`),Q6=TT.module({root:["v4 | v6","@","an IP address"],v4:LT(K6,"an IPv4 address"),v6:LT(z6,"an IPv6 address")},{name:"string.ip"}),wA="a JSON string",zR=(T)=>{if(!(T instanceof SyntaxError))throw T;return`must be ${wA} (${T})`},V6=MT({meta:wA,domain:"string",predicate:{meta:wA,predicate:(T,o)=>{try{return JSON.parse(T),!0}catch(y){return o.reject({code:"predicate",expected:wA,problem:zR(y)})}}}}),D6=(T,o)=>{if(T.length===0)return o.error({code:"predicate",expected:wA,actual:"empty"});try{return JSON.parse(T)}catch(y){return o.error({code:"predicate",expected:wA,problem:zR(y)})}},C6=TT.module({root:V6,parse:MT({meta:"safe JSON string parser",in:"string",morphs:D6,declaredOut:g.jsonObject})},{name:"string.json"}),HR=LT(/^[a-z]*$/,"only lowercase letters"),L6=TT.module({root:MT({in:"string",morphs:(T)=>T.toLowerCase(),declaredOut:HR}),preformatted:HR},{name:"string.lower"}),QR=["NFC","NFD","NFKC","NFKD"],MF=l(QR,(T,o)=>[o,MT({domain:"string",predicate:(y)=>y.normalize(o)===y,meta:`${o}-normalized unicode`})]),Kf=l(QR,(T,o)=>[o,MT({in:"string",morphs:(y)=>y.normalize(o),declaredOut:MF[o]})]),I6=TT.module({root:Kf.NFC,preformatted:MF.NFC},{name:"string.normalize.NFC"}),k6=TT.module({root:Kf.NFD,preformatted:MF.NFD},{name:"string.normalize.NFD"}),B6=TT.module({root:Kf.NFKC,preformatted:MF.NFKC},{name:"string.normalize.NFKC"}),N6=TT.module({root:Kf.NFKD,preformatted:MF.NFKD},{name:"string.normalize.NFKD"}),t6=TT.module({root:"NFC",NFC:I6,NFD:k6,NFKC:B6,NFKD:N6},{name:"string.normalize"}),ER=LT(dF,"a well-formed numeric string"),p6=TT.module({root:ER,parse:MT({in:ER,morphs:(T)=>Number.parseFloat(T),declaredOut:g.number})},{name:"string.numeric"}),b6=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$/,x6=LT(b6,"a semantic version (see https://semver.org/)"),GR=LT(/^\S.*\S$|^\S?$/,"trimmed"),j6=TT.module({root:MT({in:"string",morphs:(T)=>T.trim(),declaredOut:GR}),preformatted:GR},{name:"string.trim"}),wR=LT(/^[A-Z]*$/,"only uppercase letters"),m6=TT.module({root:MT({in:"string",morphs:(T)=>T.toUpperCase(),declaredOut:wR}),preformatted:wR},{name:"string.upper"}),q6=(T)=>{if(URL.canParse)return URL.canParse(T);try{return new URL(T),!0}catch{return!1}},UR=MT({domain:"string",predicate:{meta:"a URL string",predicate:q6}}),v6=TT.module({root:UR,parse:MT({declaredIn:UR,in:"string",morphs:(T,o)=>{try{return new URL(T)}catch{return o.error("a URL string")}},declaredOut:MT(URL)})},{name:"string.url"}),P6=TT.module({root:["versioned | nil | max","@","a UUID"],"#nil":"'00000000-0000-0000-0000-000000000000'","#max":"'ffffffff-ffff-ffff-ffff-ffffffffffff'","#versioned":/[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}/i,v1:LT(/^[0-9a-f]{8}-[0-9a-f]{4}-1[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,"a UUIDv1"),v2:LT(/^[0-9a-f]{8}-[0-9a-f]{4}-2[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,"a UUIDv2"),v3:LT(/^[0-9a-f]{8}-[0-9a-f]{4}-3[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,"a UUIDv3"),v4:LT(/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,"a UUIDv4"),v5:LT(/^[0-9a-f]{8}-[0-9a-f]{4}-5[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,"a UUIDv5"),v6:LT(/^[0-9a-f]{8}-[0-9a-f]{4}-6[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,"a UUIDv6"),v7:LT(/^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,"a UUIDv7"),v8:LT(/^[0-9a-f]{8}-[0-9a-f]{4}-8[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,"a UUIDv8")},{name:"string.uuid"}),VR=TT.module({root:g.string,alpha:LT(/^[A-Za-z]*$/,"only letters"),alphanumeric:LT(/^[A-Za-z\d]*$/,"only letters and digits 0-9"),hex:R6,base64:W6,capitalize:O6,creditCard:Y6,date:w6,digits:LT(/^\d*$/,"only digits 0-9"),email:U6,integer:KR,ip:Q6,json:C6,lower:L6,normalize:t6,numeric:p6,semver:x6,trim:j6,upper:m6,url:v6,uuid:P6},{name:"string"});var DR=TT.module({bigint:g.bigint,boolean:g.boolean,false:g.false,never:g.never,null:g.null,number:g.number,object:g.object,string:g.string,symbol:g.symbol,true:g.true,unknown:g.unknown,undefined:g.undefined}),CR=TT.module({root:g.unknown,any:g.unknown},{name:"unknown"}),h6=TT.module({root:g.jsonObject,stringify:ZA("morph",{in:g.jsonObject,morphs:(T)=>JSON.stringify(T),declaredOut:g.string})},{name:"object.json"}),LR=TT.module({root:g.object,json:h6},{name:"object"});class IR extends fo{description='instantiate an object from an index signature and corresponding value type like `Record("string", "number")`'}var n6=to(["K",g.key],"V")((T)=>({domain:"object",index:{signature:T.K,value:T.V}}),IR);class kR extends fo{description='pick a set of properties from an object like `Pick(User, "name | age")`'}var g6=to(["T",g.object],["K",g.key])((T)=>T.T.pick(T.K),kR);class BR extends fo{description='omit a set of properties from an object like `Omit(User, "age")`'}var u6=to(["T",g.object],["K",g.key])((T)=>T.T.omit(T.K),BR);class NR extends fo{description="make all named properties of an object optional like `Partial(User)`"}var i6=to(["T",g.object])((T)=>T.T.partial(),NR);class tR extends fo{description="make all named properties of an object required like `Required(User)`"}var c6=to(["T",g.object])((T)=>T.T.required(),tR);class pR extends fo{description='exclude branches of a union like `Exclude("boolean", "true")`'}var d6=to("T","U")((T)=>T.T.exclude(T.U),pR);class bR extends fo{description='extract branches of a union like `Extract("0 | false | 1", "number")`'}var r6=to("T","U")((T)=>T.T.extract(T.U),bR),xR=TT.module({Exclude:d6,Extract:r6,Omit:u6,Partial:i6,Pick:g6,Record:n6,Required:c6});var Iy=n$({...DR,...xR,...RR,...FR,string:VR,number:Uf,object:LR,unknown:CR},{prereducedAliases:!0,name:"ark"}),nT=Iy.export();Object.assign(GA.ambient,nT);GA.typeAttachments={string:nT.string.root,number:nT.number.root,bigint:nT.bigint,boolean:nT.boolean,symbol:nT.symbol,undefined:nT.undefined,null:nT.null,object:nT.object.root,unknown:nT.unknown.root,false:nT.false,true:nT.true,never:nT.never,arrayIndex:nT.Array.index,Key:nT.Key,Record:nT.Record,Array:nT.Array.root,Date:nT.Date};var po=Object.assign(Iy.type,GA.typeAttachments),l6=Iy.match,s6=Iy.generic,iz=Iy.schema,a6=Iy.define,e6=Iy.declare;function zf(T=Math.random){return T().toString(36).slice(2)}class XF extends Promise{fate;resolve;reject;done=!1;constructor(T){let o,y;super((A,F)=>{o=A,y=F});this.resolve=o,this.reject=y,this.use(T instanceof Promise?T:new Promise(T))}pass(T,o){if(T===this.fate)this.resolve(o),this.done=!0}fail(T,o){if(T===this.fate)this.reject(o),this.done=!0}use(T){if(T instanceof Promise){let o=T;this.fate=o,o.then((y)=>{this.pass(o,y)},(y)=>{this.fail(o,y)})}else this.resolve(T),this.fate=void 0}}var jR=(T,o,y=fT.STORE)=>{return My(y,{key:`${T.key}:JSON`,get:({get:A})=>o.toJson(A(T)),set:({set:A},F)=>{A(T,o.fromJson(F))}})};function p(T){while(T.child!==null)T=T.child;return T}class oT{Subscriber;subscribers=new Map;subscribe(T,o){return this.subscribers.set(T,o),()=>{this.unsubscribe(T)}}unsubscribe(T){this.subscribers.delete(T)}next(T){let o=this.subscribers.values();for(let y of o)y(T)}}class u$ extends oT{state;constructor(T){super();this.state=T}next(T){this.state=T,super.next(T)}}function Xy(T,o,y){let A={key:o.key,type:"atom_family"},F=T.families.get(o.key);if(F)T.logger.error("\u2757","atom_family",o.key,`Overwriting an existing ${Ty(F)} "${F.key}" in store "${T.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);let f=new oT,$=Object.assign((_)=>{let J=AT(_),R={key:o.key,subKey:J},M=`${o.key}(${J})`,Y=p(T),H=o.default,Q={key:M,default:H instanceof Function?H(_):H};if(o.effects)Q.effects=o.effects(_);let w=Do(Y,Q,R);return f.next({type:"state_creation",token:w}),w},A,{subject:f,install:(_)=>Xy(_,o),internalRoles:y});return T.families.set(o.key,$),T.defaults.set(o.key,o.default),A}function mR(T,o){if("mutable"in o)return YF(T,o);return Xy(T,o)}function Yy(T,o,y){let A={key:o.key,type:"readonly_selector_family"},F=T.families.get(o.key);if(F)T.logger.error("\u2757","readonly_selector_family",o.key,`Overwriting an existing ${Ty(F)} "${F.key}" in store "${T.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);let f=new oT,$=Object.assign((_)=>{let J=AT(_),R={key:o.key,subKey:J},M=`${o.key}(${J})`,Y=p(T),H=ZF(Y,{key:M,get:o.get(_)},R);return f.next({type:"state_creation",token:H}),H},A,{internalRoles:y,subject:f,install:(_)=>Yy(_,o),default:(_)=>{return o.get(_)({get:(...R)=>OT(T,...R),find:(...R)=>c(T,...R),json:(R)=>gT(T,R)})}});return T.families.set(o.key,$),A}function Qf(T,o){if("set"in o)return HF(T,o);return Yy(T,o)}class Vf{_buffer;_index=0;constructor(T){let o;if(typeof T==="number")o=T;else o=T.length;this._buffer=Array.from({length:o})}get buffer(){return this._buffer}get index(){return this._index}add(T){this._buffer[this._index]=T,this._index=(this._index+1)%this._buffer.length}copy(){let T=new Vf([...this._buffer]);return T._index=this._index,T}}var TZ={atom_family:"atom",mutable_atom_family:"mutable_atom",selector_family:"selector",readonly_selector_family:"readonly_selector",molecule_family:"molecule"};function qR(T,o){let y=AT(o),A=`${T.key}(${y})`,F=TZ[T.type],f={key:A,type:F};return Object.assign(f,{family:{key:T.key,subKey:y}}),Object.assign(f,{counterfeit:!0}),f}function wo(T){let o={key:T.key,type:T.type};if("family"in T)o.family=T.family;return o}function UA(T){return vR(fT.STORE,T)}function Py(T){return mR(fT.STORE,T)}function i$(...T){if(T.length===2)return OT(fT.STORE,...T);return OT(fT.STORE,...T)}function Df(T,o,y=fT.STORE){return y.joins.set(T.key,new EF(T,o,y)),{key:T.key,type:"join",a:T.between[0],b:T.between[1],cardinality:T.cardinality}}function hR(T){return nR(T,fT.STORE)}var c$=(T)=>(o,y,A,F,...f)=>{console[T](`${o} ${y} "${A}" ${F}`,...f)},oZ={error:c$("error"),info:c$("info"),warn:c$("warn")};class d${logLevel;filter;logger;constructor(T,o,y=oZ){this.logLevel=T,this.filter=o,this.logger=y}error=(...T)=>{if((this.filter?.(...T)??!0)&&this.logLevel!==null)this.logger.error(...T)};info=(...T)=>{if((this.filter?.(...T)??!0)&&this.logLevel==="info")this.logger.info(...T)};warn=(...T)=>{if((this.filter?.(...T)??!0)&&this.logLevel!=="error"&&this.logLevel!==null)this.logger.warn(...T)}}var gQ=Symbol("claim");class gR{store;constructor(T=fT.STORE){this.store=T,uR("root",T)}allocate(T,o,y){return hy(this.store,T,o,y)}fuse(T,o,y){return iR(this.store,T,o,y)}deallocate(T){ny(this.store,T)}claim(T,o,y){return KA(this.store,T,o,y)}}class r${store;realm;constructor(T=fT.STORE){this.store=T,this.realm=new gR(T)}allocate(T,o,y){hy(this.store,T,o,y)}deallocate(T){ny(this.store,T)}claim(T,o,y){KA(this.store,T,o,y)}}function Lf(T){return Qf(fT.STORE,T)}function aT(T){return"epoch"in T.transactionMeta}function XT(T){return"phase"in T.transactionMeta}var cR=(T)=>{let o=p(T);if(!XT(o)){T.logger.warn("\uD83D\uDC1E","transaction","???","abortTransaction called outside of a transaction. This is probably a bug in AtomIO.");return}T.logger.info("\uD83E\uDE82","transaction",o.transactionMeta.update.key,"Aborting transaction"),o.parent.child=null};function YT(T){return T[0].toUpperCase()+T.slice(1)}function Ty(T){return T.type.split("_").map(YT).join(" ")}class gy extends Error{constructor(T,o){super(`${Ty(T)} ${AT(T.key)} not found in store "${o.config.name}".`)}}function zA(T,o,y){return(...A)=>{let F=_T(T,o);if(F)return F.run(A,y);throw new gy(o,T)}}var If=(T)=>(o)=>T instanceof Function?T(o):T;var ky=(T,o)=>{if(T.valueMap.has(o.key))return T.logger.info("\uD83D\uDCD6",o.type,o.key,"reading cached value"),dR(o,T);switch(o.type){case"selector":case"readonly_selector":return T.logger.info("\uD83E\uDDEE",o.type,o.key,"computing value"),o.get();case"atom":case"mutable_atom":{let y=o.default,A;if(y instanceof Function)A=y();else A=y;return T.logger.info("\uD83D\uDC81","atom",o.key,"could not find cached value; using default",A),A}}};var rR=(T,o)=>{if(T.operation.open){let y=performance.now();return T.logger.info("\u2757",o.type,o.key,`deferring setState at T-${y} until setState for "${T.operation.token.key}" is done`),y}T.operation={open:!0,done:new Set,prev:new Map,time:Date.now(),token:o},T.logger.info("\u2B55",o.type,o.key,`operation start in store "${T.config.name}"${!XT(T)?"":` ${T.transactionMeta.phase} "${T.transactionMeta.update.key}"`}`)},lR=(T)=>{if(T.operation.open)T.logger.info("\uD83D\uDD34",T.operation.token.type,T.operation.token.key,`operation done in store "${T.config.name}"`);T.operation={open:!1},T.on.operationClose.next(T.operation)},sR=(T,o)=>{if(!T.operation.open)return T.logger.error("\uD83D\uDC1E","unknown",o,"isDone called outside of an operation. This is probably a bug in AtomIO."),!0;return T.operation.done.has(o)},QA=(T,o)=>{if(!T.operation.open){T.logger.error("\uD83D\uDC1E","unknown",o,"markDone called outside of an operation. This is probably a bug in AtomIO.");return}T.operation.done.add(o)};var aR=(T,o,y)=>{switch(o.type){case"mutable_atom":T.logger.info("\uD83D\uDCE2",o.type,o.key,"is now (",y.newValue,") subscribers:",o.subject.subscribers);break;case"atom":case"selector":case"readonly_selector":T.logger.info("\uD83D\uDCE2",o.type,o.key,"went (",y.oldValue,"->",y.newValue,") subscribers:",o.subject.subscribers)}o.subject.next(y)};var l$=(T,o)=>{let y=p(T),A=y.selectorAtoms.getRelatedKeys(o.key);if(y.logger.info("\uD83E\uDDF9",o.type,o.key,A?`evicting ${A.size} states downstream:`:"no downstream states",A??"to evict"),A){if(y.operation.open)y.logger.info("\uD83E\uDDF9",o.type,o.key,`[ ${[...y.operation.done].join(", ")} ] already done`);for(let F of A){if(sR(y,F))continue;eR(F,y),QA(y,F)}}};var TW=(T,o,y)=>{let A=ky(T,o),F=A;if(o.type==="mutable_atom"&&XT(T)){let{parent:S}=T;F=wF(T,o,S)}if(F=If(y)(F),T.logger.info("\uD83D\uDCDD","atom",o.key,"set to",F),F=bo(T,o.key,F,o.subject),yW(T,o.key))AW(T,o.key);QA(T,o.key),l$(T,o);let f={oldValue:A,newValue:F};if(!XT(T)){aR(T,o,f);return}if(T.on.transactionApplying.state===null){let{key:S}=o;if(oW(f.newValue))return;let $={type:"atom_update",key:S,...f};if(o.family)$.family=o.family;T.transactionMeta.update.updates.push($),T.logger.info("\uD83D\uDCC1","atom",S,"stowed (",f.oldValue,"->",f.newValue,")")}else if(o.key.startsWith("*")){let S=o.key.slice(1),$=T.atoms.get(S),_=T.valueMap.get(S);if($.type==="mutable_atom"&&XT(T)){let{parent:R}=T;_=wF(T,$,R)}if(_.do(f.newValue)===null)l$(T,$)}};var kf=(T,o,y)=>{switch(o.type){case"atom":case"mutable_atom":TW(T,o,y);break;case"selector":o.set(y);break}};function FW(T,o){if(o.family){let y=T.families.get(o.family.key);if(y)return y}}function bT(T,...o){let y,A,F,f;if(o.length===2){if(y=o[0],f=o[1],A=FW(T,y)??null,A)F=y.family?rT(y.family.subKey):null,y=c(T,A,F)}else A=o[0],F=o[1],f=o[2],y=c(T,A,F);if("counterfeit"in y&&"family"in y){let _=y.family.subKey,J=T.disposalTraces.buffer.find((R)=>R?.key===_);T.logger.error("\u274C",y.type,y.key,`could not be set because it was not found in the store "${T.config.name}".`,J?`This state was previously disposed:
|
|
42
|
+
${J.trace}`:"No previous disposal trace was found.");return}let S=rR(T,y);if(S){let _=T.on.operationClose.subscribe(`waiting to set "${y.key}" at T-${S}`,()=>{_(),T.logger.info("\uD83D\uDFE2",y.type,y.key,`resuming deferred setState from T-${S}`),bT(T,y,f)});return}let $=_T(T,y);kf(T,$,f),lR(T)}function Bf(T,o,y){let{key:A,newValue:F,oldValue:f}=o,S=T==="newValue"?F:f,$={key:A,type:"atom"};if(o.family)Object.assign($,{family:o.family});bT(y,$,S)}function fW(T){let{stack:o}=T;if(o)return`
|
|
43
|
+
`+o.split(`
|
|
6
44
|
`)?.slice(1)?.join(`
|
|
7
|
-
`);return""}function
|
|
45
|
+
`);return""}function uR(T,o=fT.STORE){let y={key:T,stringKey:AT(T),dependsOn:"any"};return o.molecules.set(AT(T),y),T}function hy(T,o,y,A="any"){let F=o,f=AT(y),S=[],$=p(T);if(Array.isArray(F))for(let R of F){let M=AT(R);if($.molecules.get(M))T.moleculeGraph.set(M,f,{source:M});else S.push(M)}else{let R=AT(F);if($.molecules.get(R))T.moleculeGraph.set(R,f,{source:R});else S.push(R)}if(S.length===0)$.molecules.set(f,{key:y,stringKey:f,dependsOn:A});let _={type:"molecule_creation",key:y,provenance:F};if(XT($)&&$.transactionMeta.phase==="building")$.transactionMeta.update.updates.push(_);else $.on.moleculeCreation.next(_);for(let R of S){let M=T.disposalTraces.buffer.find((Y)=>Y?.key===R);T.logger.error("\u274C","molecule",y,"allocation failed:",`Could not allocate to ${R} in store "${T.config.name}".`,M?`
|
|
8
46
|
${R} was most recently disposed
|
|
9
|
-
${
|
|
47
|
+
${M.trace}`:`No previous disposal trace for ${R} was found.`)}return y}function iR(T,o,y,A){let F=`T$--${o}==${y}++${A}`;return hy(T,[y,A],F,"all"),F}function ny(T,o){let y=AT(o),A=T.molecules.get(y);if(!A){let H=T.disposalTraces.buffer.find((Q)=>Q?.key===y);T.logger.error("\u274C","molecule",o,"deallocation failed:",`Could not find allocation for ${y} in store "${T.config.name}".`,H?`
|
|
10
48
|
This state was most recently deallocated
|
|
11
|
-
${
|
|
12
|
-
${S} was most recently disposed
|
|
13
|
-
${O.trace}`:`No previous disposal trace for ${S} was found.`),n}let F=no(T),J=A.molecules.get(F);if(!J){let O=o.disposalTraces.buffer.find((_)=>_?.key===F);return o.logger.error("\u274C","molecule",n,"claim failed:",`Could not allocate to ${F} in store "${o.config.name}".`,O?`
|
|
49
|
+
${H.trace}`:`No previous disposal trace for ${y} was found.`);return}let F=T.moleculeJoins.getRelatedKeys(A.key);if(F)for(let H of F){let Q=T.joins.get(H);if(Q)Q.relations.delete(A.key),Q.molecules.delete(A.stringKey)}T.moleculeJoins.delete(A.stringKey);let f=[],S=[],$={type:"molecule_disposal",key:A.key,values:S,provenance:f},_=p(T);_.molecules.delete(y);let J=XT(_)&&_.transactionMeta.phase==="building";if(J)_.transactionMeta.update.updates.push($);let R=T.moleculeGraph.getRelationEntries({downstreamMoleculeKey:A.stringKey});if(R)for(let[H,{source:Q}]of R)if(Q===A.stringKey){let w=rT(H);ny(T,w)}else f.push(Q);let M=_.moleculeData.getRelatedKeys(A.stringKey);if(M)for(let H of M){let Q=_.families.get(H),w=c(T,Q,A.key);S.push([Q.key,w]),uy(T,w)}if(_.moleculeGraph.delete(A.stringKey),_.moleculeJoins.delete(A.stringKey),_.moleculeData.delete(A.stringKey),!J)_.on.moleculeDisposal.next($);_.molecules.delete(A.stringKey);let Y=fW(new Error);T.disposalTraces.add({key:y,trace:Y})}function KA(T,o,y,A){let F=AT(y),f=p(T),S=f.molecules.get(F);if(!S){let Y=T.disposalTraces.buffer.find((H)=>H?.key===F);return T.logger.error("\u274C","molecule",y,"claim failed:",`Could not allocate to ${F} in store "${T.config.name}".`,Y?`
|
|
14
50
|
${F} was most recently disposed
|
|
15
|
-
${
|
|
16
|
-
${$.trace}`:"No previous disposal trace was found."),f.type){case"atom_family":case"mutable_atom_family":return o.defaults.get(f.key);case"selector_family":case"readonly_selector_family":{if(o.defaults.has(f.key))return o.defaults.get(n.family.key);let F=$o(o,f).default(A);return o.defaults.set(f.key,F),F}}}return PT(o,$o(o,n))}class jo{a;b;cardinality;relations=new Map;contents=new Map;isAType;isBType;isContent;makeContentKey=(o,T)=>`${o}:${T}`;warn;getRelatedKeys(o){return this.relations.get(o)}addRelation(o,T){let n=this.relations.get(o),f=this.relations.get(T);if(n)n.add(T);else n=new Set([T]),this.relations.set(o,n);if(f)f.add(o);else f=new Set([o]),this.relations.set(T,f)}deleteRelation(o,T){let n=this.relations.get(o);if(n){if(n.delete(T),n.size===0)this.relations.delete(o);let f=this.relations.get(T);if(f){if(f.delete(o),f.size===0)this.relations.delete(T)}}}replaceRelationsUnsafely(o,T){this.relations.set(o,new Set(T));for(let n of T){let f=new Set().add(o);this.relations.set(n,f)}}replaceRelationsSafely(o,T){let n=this.relations.get(o),f=this.isAType?.(o)?o:void 0,S=f===void 0?o:void 0;if(n)for(let A of n){f??=A,S??=A;let $=this.relations.get(A);if($){if($.size===1)this.relations.delete(A);else $.delete(o);this.contents.delete(this.makeContentKey(f,S))}}this.relations.set(o,new Set(T));for(let A of T){let $=this.relations.get(A);if($)$.add(o);else $=new Set().add(o),this.relations.set(A,$)}}getContentInternal(o){return this.contents.get(o)}setContent(o,T){this.contents.set(o,T)}deleteContent(o){this.contents.delete(o)}constructor(o,T){if(this.a=o.between[0],this.b=o.between[1],this.cardinality=o.cardinality,!T?.externalStore)this.relations=new Map(o.relations?.map(([n,f])=>[n,new Set(f)])),this.contents=new Map(o.contents);if(this.isAType=T?.isAType??null,this.isBType=T?.isBType??null,this.isContent=T?.isContent??null,T?.makeContentKey)this.makeContentKey=T.makeContentKey;if(T?.externalStore){let n=T.externalStore;if(this.has=(f,S)=>n.has(f,S),this.addRelation=(f,S)=>{n.addRelation(f,S)},this.deleteRelation=(f,S)=>{n.deleteRelation(f,S)},this.replaceRelationsSafely=(f,S)=>{n.replaceRelationsSafely(f,S)},this.replaceRelationsUnsafely=(f,S)=>{n.replaceRelationsUnsafely(f,S)},this.getRelatedKeys=(f)=>n.getRelatedKeys(f),n.getContent)this.getContentInternal=(f)=>{return n.getContent(f)},this.setContent=(f,S)=>{n.setContent(f,S)},this.deleteContent=(f)=>{n.deleteContent(f)};for(let[f,S]of o.relations??[]){let A=this.isAType?.(f)?f:void 0,$=A===void 0?f:void 0;for(let F of S)A??=F,$??=F,this.addRelation(A,$)}for(let[f,S]of o.contents??[])this.setContent(f,S)}if(T?.warn)this.warn=T.warn}toJSON(){return{between:[this.a,this.b],cardinality:this.cardinality,relations:[...this.relations.entries()].map(([o,T])=>[o,[...T]]),contents:[...this.contents.entries()]}}set(...o){let T,n,f;switch(o.length){case 1:{let S=o[0];T=S[this.a],n=S[this.b],f=void 0;break}case 2:{let S=o[0];if(typeof S==="string")[T,n]=o;else T=S[this.a],n=S[this.b],f=o[1];break}default:{T=o[0],n=o[1],f=o[2];break}}switch(this.cardinality){case"1:1":{let S=this.getRelatedKey(T);if(S&&S!==n)this.delete(T,S)}case"1:n":{let S=this.getRelatedKey(n);if(S&&S!==T)this.delete(S,n)}break;case"n:n":}if(f){let S=this.makeContentKey(T,n);this.setContent(S,f)}return this.addRelation(T,n),this}delete(o,T){T=typeof T==="string"?T:o[this.b];let n=typeof o==="string"?o:o[this.a];if(n===void 0&&typeof T==="string"){let f=this.getRelatedKeys(T);if(f)for(let S of f)this.delete(S,T)}if(typeof n==="string"&&T===void 0){let f=this.getRelatedKeys(n);if(f)for(let S of f)this.delete(n,S)}if(typeof n==="string"&&typeof T==="string"){this.deleteRelation(n,T);let f=this.makeContentKey(n,T);this.deleteContent(f)}return this}getRelatedKey(o){let T=this.getRelatedKeys(o);if(T){if(T.size>1)this.warn?.(`${T.size} related keys were found for key "${o}": (${[...T].map((f)=>`"${f}"`).join(", ")}). Only one related key was expected.`);let n;for(let f of T){n=f;break}return n}}replaceRelations(o,T,n){let f=!Array.isArray(T),S=f?Object.keys(T):T;if(n?.reckless)this.replaceRelationsUnsafely(o,S);else this.replaceRelationsSafely(o,S);if(f)for(let A of S){let $=this.makeContentKey(o,A),F=T[A];this.setContent($,F)}return this}getContent(o,T){let n=this.makeContentKey(o,T);return this.getContentInternal(n)}getRelationEntries(o){let T=o[this.a],n=o[this.b];if(T!==void 0&&n===void 0){let f=this.getRelatedKeys(T);if(f)return[...f].map((S)=>{return[S,this.getContent(T,S)]})}if(T===void 0&&n!==void 0){let f=this.getRelatedKeys(n);if(f)return[...f].map((S)=>{return[S,this.getContent(S,n)]})}return[]}has(o,T){if(T)return this.getRelatedKeys(o)?.has(T)??!1;return this.relations.has(o)}}class kT extends Map{deleted=new Set;source;constructor(o){super();this.source=o}get(o){if(super.has(o))return super.get(o);if(!this.deleted.has(o)&&this.source.has(o))return this.source.get(o);return}set(o,T){return this.deleted.delete(o),super.set(o,T)}hasOwn(o){return super.has(o)}has(o){return!this.deleted.has(o)&&(super.has(o)||this.source.has(o))}delete(o){return this.deleted.add(o),super.delete(o)}}var UF=(o,T,n,f)=>{let S=C(o),A={parent:S,child:null,on:S.on,loggers:S.loggers,logger:S.logger,config:S.config,atoms:new kT(S.atoms),atomsThatAreDefault:new Set(S.atomsThatAreDefault),families:new kT(S.families),joins:new kT(S.joins),operation:{open:!1},readonlySelectors:new kT(S.readonlySelectors),timelines:new kT(S.timelines),timelineTopics:new jo(S.timelineTopics.toJSON()),trackers:new Map,transactions:new kT(S.transactions),selectorAtoms:new jo(S.selectorAtoms.toJSON()),selectorGraph:new jo(S.selectorGraph.toJSON(),{makeContentKey:(...t)=>t.sort().join(":")}),selectors:new kT(S.selectors),valueMap:new kT(S.valueMap),defaults:S.defaults,disposalTraces:o.disposalTraces.copy(),molecules:new kT(S.molecules),moleculeGraph:new jo(S.moleculeGraph.toJSON(),{makeContentKey:S.moleculeGraph.makeContentKey}),moleculeData:new jo(S.moleculeData.toJSON(),{makeContentKey:S.moleculeData.makeContentKey}),moleculeJoins:new jo(S.moleculeJoins.toJSON(),{makeContentKey:S.moleculeJoins.makeContentKey}),miscResources:new kT(S.miscResources)},$=EF(o,T),F={phase:"building",update:{type:"transaction_update",key:T,id:f,epoch:$===void 0?Number.NaN:$+1,updates:[],params:n,output:void 0},toolkit:{get:(...t)=>to(J,...t),set:(...t)=>{Uo(J,...t)},run:(t,R=Zf())=>zn(J,t,R),find:(t,R)=>i(J,t,R),json:(t)=>Io(J,t),dispose:(...t)=>{$n(J,...t)},env:()=>QF(J)}},J=Object.assign(A,{transactionMeta:F});return S.child=J,o.logger.info("\uD83D\uDEEB","transaction",T,"Building transaction with params:",n),J};function RA(o,T){let n={key:T.key,type:"transaction",run:(A,$)=>{let F=UF(o,T.key,A,$);try{let J=C(o),{toolkit:t}=F.transactionMeta,R=T.do(t,...A);return zF(R,J),R}catch(J){throw SF(f),o.logger.warn("\uD83D\uDCA5","transaction",T.key,"caught:",J),J}},install:(A)=>RA(A,T),subject:new oo},f=C(o);f.transactions.set(n.key,n);let S=fT(n);return o.on.transactionCreation.next(S),S}function tf(o){return RA(fo.STORE,o)}class VF{parent=null;child=null;valueMap=new Map;defaults=new Map;atoms=new Map;selectors=new Map;readonlySelectors=new Map;atomsThatAreDefault=new Set;selectorAtoms=new jo({between:["selectorKey","atomKey"],cardinality:"n:n"});selectorGraph=new jo({between:["upstreamSelectorKey","downstreamSelectorKey"],cardinality:"n:n"},{makeContentKey:(...o)=>o.sort().join(":")});trackers=new Map;families=new Map;joins=new Map;transactions=new Map;transactionMeta={epoch:new Map,actionContinuities:new jo({between:["continuity","action"],cardinality:"1:n"})};timelines=new Map;timelineTopics=new jo({between:["timelineKey","topicKey"],cardinality:"1:n"});disposalTraces=new gf(100);molecules=new Map;moleculeJoins=new jo({between:["moleculeKey","joinKey"],cardinality:"n:n"},{makeContentKey:(...o)=>o.sort().join(":")});moleculeGraph=new jo({between:["upstreamMoleculeKey","downstreamMoleculeKey"],cardinality:"n:n"},{makeContentKey:(...o)=>o.sort().join(":")});moleculeData=new jo({between:["moleculeKey","stateFamilyKey"],cardinality:"n:n"},{makeContentKey:(...o)=>o.sort().join(":")});miscResources=new Map;on={atomCreation:new oo,atomDisposal:new oo,selectorCreation:new oo,selectorDisposal:new oo,timelineCreation:new oo,transactionCreation:new oo,transactionApplying:new TA(null),operationClose:new oo,moleculeCreation:new oo,moleculeDisposal:new oo};operation={open:!1};config={name:"IMPLICIT_STORE",lifespan:"ephemeral"};loggers=[new SA("warn",(o,T,n)=>!iT(n))];logger={error:(...o)=>{for(let T of this.loggers)T.error(...o)},info:(...o)=>{for(let T of this.loggers)T.info(...o)},warn:(...o)=>{for(let T of this.loggers)T.warn(...o)}};constructor(o,T=null){if(this.config={...T?.config,...o},T!==null){if(this.valueMap=new Map(T?.valueMap),this.operation={...T?.operation},qo(T))this.transactionMeta={epoch:new Map(T?.transactionMeta.epoch),actionContinuities:new jo(T?.transactionMeta.actionContinuities.toJSON())};for(let[,f]of T.families){if(f.internalRoles?.includes("mutable")||f.internalRoles?.includes("join"))continue;f.install(this)}let n=new Set;for(let[,f]of T.atoms){if(n.has(f.key))continue;if(f.install(this),f.type==="mutable_atom"){let S=Io(T,f),A=bT(f);n.add(S.key),n.add(A.key)}}for(let[,f]of T.readonlySelectors)f.install(this);for(let[,f]of T.selectors){if(n.has(f.key))continue;f.install(this)}for(let[,f]of T.transactions)f.install(this);for(let[,f]of T.timelines)f.install(this)}}}var fo={get STORE(){return globalThis.ATOM_IO_IMPLICIT_STORE??=new VF({name:"IMPLICIT_STORE",lifespan:"ephemeral"}),globalThis.ATOM_IO_IMPLICIT_STORE}};function $o(o,T){let n,f=o;while(f!==null){switch(T.type){case"atom":case"mutable_atom":n=f.atoms.get(T.key);break;case"selector":n=f.selectors.get(T.key);break;case"readonly_selector":n=f.readonlySelectors.get(T.key);break;case"atom_family":case"mutable_atom_family":case"selector_family":case"readonly_selector_family":n=f.families.get(T.key);break;case"timeline":n=f.timelines.get(T.key);break;case"transaction":n=f.transactions.get(T.key);break}if(n)return n;f=f.child}throw new An(T,o)}function BF(o,T,n){let f=o.families.get(T.key);if(f===void 0)throw new An(T,o);let S=f(n),A=C(o);if(S.family){if(qo(A))switch(S.type){case"atom":case"mutable_atom":o.on.atomCreation.next(S);break;case"selector":case"readonly_selector":o.on.selectorCreation.next(S);break}else if(Ro(A)&&A.on.transactionApplying.state===null)A.transactionMeta.update.updates.push({type:"state_creation",token:S})}return S}function mF(o,T,n){let f=no(n),S=`${T.key}(${f})`,A=C(o),$;switch(T.type){case"atom_family":case"mutable_atom_family":$=A.atoms.get(S);break;case"selector_family":$=A.selectors.get(S);break;case"readonly_selector_family":$=A.readonlySelectors.get(S);break}if($)return fT($);return $}function i(o,T,n){let f=mF(o,T,n);if(f)return f;let S=no(n),A=o.molecules.get(S);if(!A&&o.config.lifespan==="immortal"){let $=u$(T,n);return o.logger.error("\u274C",$.type,$.key,`was not found in store "${o.config.name}"; returned a counterfeit token.`),$}if(f=BF(o,T,n),A)C(o).moleculeData.set(S,T.key);return f}function $n(o,...T){let n;if(T.length===1)n=T[0];else{let f=T[0],S=T[1];n=i(o,f,S)}try{$o(o,n)}catch(f){o.logger.error("\u274C",n.type,n.key,`could not be disposed because it was not found in the store "${o.config.name}".`);return}switch(n.type){case"atom":case"mutable_atom":MA(o,n);break;case"selector":case"readonly_selector":LF(o,n);break}}var TS=(o,T)=>C(o).atoms.has(T),bM=(o,T)=>C(o).selectors.has(T),xM=(o,T)=>C(o).readonlySelectors.has(T),CF=(o,T)=>TS(o,T)||bM(o,T)||xM(o,T);var nS=(o,T)=>{return C(T).selectorGraph.getRelationEntries({downstreamSelectorKey:o}).filter(([f,{source:S}])=>S!==o).map(([f,{source:S}])=>S).filter((f)=>CF(T,f))};var yA=(o,T,n)=>{let f=[],S=nS(o,n);while(S.length>0){let A=S.shift();if(T.has(A))continue;if(T.add(A),!TS(n,A))S.push(...nS(A,n));else if(!f.includes(A))f.push(A)}return f},IF=(o,T)=>{let n=o.key,f=nS(n,T),S=new Set;return f.flatMap((A)=>TS(T,A)?A:yA(A,S,T))};var jF=(o,T,n,f)=>{let S=C(f);if(T.type==="atom"||T.type==="mutable_atom")S.selectorAtoms.set({selectorKey:o,atomKey:T.key}),f.logger.info("\uD83D\uDD0D","selector",o,`discovers root atom "${T.key}"`);else{let A=yA(T.key,n,f);f.logger.info("\uD83D\uDD0D","selector",o,`discovers root atoms: [ ${A.map(($)=>`"${$}"`).join(", ")} ]`);for(let $ of A)S.selectorAtoms=S.selectorAtoms.set({selectorKey:o,atomKey:$})}n.add(T.key)};var fS=(o,T,n)=>({get:(...f)=>{let S=C(n),A;if(f.length===2){let[J,t]=f;A=i(n,J,t)}else[A]=f;let $=$o(n,A),F=PT(n,$);return n.logger.info("\uD83D\uDD0C","selector",o,`registers dependency ( "${A.key}" =`,F,")"),S.selectorGraph.set({upstreamSelectorKey:A.key,downstreamSelectorKey:o},{source:A.key}),jF(o,A,T,n),F},set:(...f)=>{let S,A;if(f.length===2)S=f[0],A=f[1];else{let J=f[0],t=f[1];A=f[2],S=i(n,J,t)}let $=C(n),F=$o($,S);sf($,F,A)},find:(f,S)=>i(n,f,S),json:(f)=>Io(n,f)});var Sf=(o,T,n)=>{let f=C(o),S=new oo,A=new Set,{get:$,find:F,json:J}=fS(T.key,A,f),t=()=>{let _=T.get({get:$,find:F,json:J});return yT(C(o),T.key,_,S),A.clear(),_},R={...T,subject:S,install:(_)=>Sf(_,T,n),get:t,type:"readonly_selector",...n&&{family:n}};f.readonlySelectors.set(T.key,R);let W=t();o.logger.info("\u2728",R.type,R.key,"=",W);let O={key:T.key,type:"readonly_selector"};if(n)O.family=n;return O};var Rf=(o,T,n)=>{let f=C(o),S=new oo,A=new Set,$=fS(T.key,A,f),{find:F,get:J,json:t}=$,R={find:F,get:J,json:t},W=(m=T.get,b=C(o))=>{let r=m(R);return yT(b,T.key,r,S),A.clear(),r},_={...T,subject:S,install:(m)=>Rf(m,T,n),get:W,set:(m)=>{let b=C(o),r=W(T.get,b),P=ef(m)(r);if(o.logger.info("\uD83D\uDCDD","selector",T.key,"set (",r,"->",P,")"),yT(b,T.key,P,S),Dn(b,T.key),qo(b))S.next({newValue:P,oldValue:r});T.set($,P)},type:"selector",...n&&{family:n}};f.selectors.set(T.key,_);let Q=W();o.logger.info("\u2728",_.type,_.key,"=",Q);let H={key:T.key,type:"selector"};if(n)H.family=n;return H};function jT(o,T){if("set"in T){let S=Rf(o,T,void 0);return o.on.selectorCreation.next(S),S}let f=Sf(o,T,void 0);return o.on.selectorCreation.next(f),f}function LF(o,T){let n=C(o),{key:f}=T,S=$o(n,T);if(!S.family)o.logger.error("\u274C","selector",f,"Standalone selectors cannot be disposed.");else{if(n.molecules.get(S.family.subKey))n.moleculeData.delete(S.family.subKey,S.family.key);let $;switch(T.type){case"selector":n.selectors.delete(f),$={key:S.family.key,type:"selector_family"},$o(o,$).subject.next({type:"state_disposal",subType:"selector",token:T});break;case"readonly_selector":n.readonlySelectors.delete(f),$={key:S.family.key,type:"readonly_selector_family"},$o(o,$).subject.next({type:"state_disposal",subType:"selector",token:T});break}if(n.valueMap.delete(f),n.selectorAtoms.delete(f),n.selectorGraph.delete(f),o.logger.info("\uD83D\uDD25",T.type,f,"deleted"),Ro(n)&&n.transactionMeta.phase==="building")n.transactionMeta.update.updates.push({type:"state_disposal",subType:"selector",token:T});else o.on.selectorDisposal.next(T)}}function Af(o,T,n){let f={key:T.key,type:"selector_family"},S=o.families.get(T.key);if(S)o.logger.error("\u2757","selector_family",T.key,`Overwriting an existing ${VT(S)} "${S.key}" in store "${o.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);let A=new oo,F=Object.assign((J)=>{let t=no(J),R={key:T.key,subKey:t},W=`${T.key}(${t})`,O=C(o),_=Rf(O,{key:W,get:T.get(J),set:T.set(J)},R);return A.next({type:"state_creation",token:_}),_},f,{internalRoles:n,subject:A,install:(J)=>Af(J,T),default:(J)=>{return T.get(J)({get:(...R)=>to(o,...R),find:(R,W)=>i(o,R,W),json:(R)=>Io(o,R)})}});return o.families.set(T.key,F),f}function hF(o,T,n){return Af(o,{key:`${T.key}:JSON`,get:(S)=>({get:A})=>{let $=A(T,S);return n.toJson($)},set:(S)=>({set:A},$)=>{A(T,S,n.fromJson($))}},["mutable","json"])}var xo=(o)=>JSON.parse(o),no=(o)=>JSON.stringify(o),F2=[Array.prototype,Boolean.prototype,Number.prototype,Object.prototype,String.prototype];var NF=(o,T)=>{let n=C(o);if(n.operation.open)return n.operation.prev.get(T.key);return n.valueMap.get(T.key)};var OA=(o,T)=>{let n=C(o);return IF(T,o).map((S)=>{let A=n.atoms.get(S);if(A===void 0)throw new Error(`Atom "${S}", a dependency of selector "${T.key}", not found in store "${o.config.name}".`);return A.subject.subscribe(`${T.type}:${T.key}`,($)=>{o.logger.info("\uD83D\uDCE2",T.type,T.key,"root",S,"went",$.oldValue,"->",$.newValue);let F=NF(n,T),J=PT(n,T);o.logger.info("\u2728",T.type,T.key,"went",F,"->",J),T.subject.next({newValue:J,oldValue:F})})})};function lo(o,T,n,f){function S(W){if(o.operation.open){let O=o.on.operationClose.subscribe(`state subscription ${n}`,()=>{O(),f(W)})}else f(W)}let A=$o(o,T);o.logger.info("\uD83D\uDC40",A.type,A.key,`Adding subscription "${n}"`);let $=A.type==="selector"||A.type==="readonly_selector",F=null,J=S;if($)F=OA(o,A),J=(W)=>{if(F)F.length=0,F.push(...OA(o,A));S(W)};let t=A.subject.subscribe(n,J);return()=>{if(o.logger.info("\uD83D\uDE48",A.type,A.key,`Removing subscription "${n}"`),t(),F)for(let W of F)W()}}var kA=(o,T,n,f)=>{let S=$o(o,T);o.logger.info("\uD83D\uDC40","timeline",T.key,`Adding subscription "${n}"`);let A=S.subject.subscribe(n,f);return()=>{o.logger.info("\uD83D\uDE48","timeline",T.key,`Removing subscription "${n}" from timeline`),A()}};var WA=(o,T,n,f)=>{let S=$o(o,T);o.logger.info("\uD83D\uDC40","transaction",T.key,`Adding subscription "${n}"`);let A=S.subject.subscribe(n,f);return()=>{o.logger.info("\uD83D\uDE48","transaction",T.key,`Removing subscription "${n}"`),A()}};class Fn{Update;initializeState(o,T){let n=`*${o.key}`;T.atoms.delete(n),T.valueMap.delete(n);let f=o.family?{key:`*${o.family.key}`,subKey:o.family.subKey}:void 0,S=FT(T,{key:n,default:null},f);if(T.parent?.valueMap.has(n)){let A=T.parent.valueMap.get(n);T.valueMap.set(n,A)}return S}unsubscribeFromInnerValue;unsubscribeFromState;observeCore(o,T,n){let f=`tracker:${n.config.name}:${Ro(n)?n.transactionMeta.update.key:"main"}:${o.key}`,S=to(n,o);this.unsubscribeFromInnerValue=S.subscribe(f,(A)=>{Uo(n,T,A)}),this.unsubscribeFromState=lo(n,o,f,(A)=>{if(A.newValue!==A.oldValue)this.unsubscribeFromInnerValue(),this.unsubscribeFromInnerValue=A.newValue.subscribe(f,($)=>{Uo(n,T,$)})})}updateCore(o,T,n){let f=`tracker:${n.config.name}:${Ro(n)?n.transactionMeta.update.key:"main"}:${o.key}`;lo(n,T,f,({newValue:S,oldValue:A})=>{let $=n.timelineTopics.getRelatedKey(T.key);if($){if(n.timelines.get($)?.timeTraveling){let t=kA(n,{key:$,type:"timeline"},f,(R)=>{t(),Uo(n,o,(W)=>{if(R==="redo"&&S)W.do(S);else if(R==="undo"&&A)W.undo(A);return W})});return}}let F=n.on.operationClose.subscribe(f,()=>{F();let J=to(n,o),t=S===null?-1:J.getUpdateNumber(S),R=t-J.cacheUpdateNumber;if(S&&R===1)Uo(n,o,(W)=>(W.do(S),W));else n.logger.info("\u274C","mutable_atom",o.key,`could not be updated. Expected update number ${J.cacheUpdateNumber+1}, but got ${t}`)})})}mutableState;latestUpdateState;[Symbol.dispose];constructor(o,T){this.mutableState=o;let n=C(T);this.latestUpdateState=this.initializeState(o,n),this.observeCore(o,this.latestUpdateState,n),this.updateCore(o,this.latestUpdateState,n),n.trackers.set(o.key,this),this[Symbol.dispose]=()=>{this.unsubscribeFromInnerValue(),this.unsubscribeFromState(),n.trackers.delete(o.key)}}}function Mf(o,T,n){o.logger.info("\uD83D\uDD28","atom",T.key,`creating in store "${o.config.name}"`);let f=C(o),S=f.atoms.get(T.key);if(S&&S.type==="mutable_atom")return o.logger.error("\u274C","atom",T.key,"Tried to create atom, but it already exists in the store."),fT(S);let A=new oo,$={...T,type:"mutable_atom",install:(t)=>{return t.logger.info("\uD83D\uDEE0\uFE0F","atom",T.key,`installing in store "${t.config.name}"`),Mf(t,T,n)},subject:A};if(n)$.family=n;let F=T.default();f.atoms.set($.key,$),SS(o,T.key),yT(f,T.key,F,A);let J=fT($);if(T.effects){let t=0,R=[];for(let W of T.effects){let O=W({setSelf:(_)=>{Uo(o,J,_)},onSet:(_)=>lo(o,J,`effect[${t}]`,_)});if(O)R.push(O);++t}$.cleanup=()=>{for(let W of R)W()}}if(new Fn(J,o),!n)d$(J,T,o);return J}class wA{trackers=new Map;Update;latestUpdateAtoms;mutableAtoms;constructor(o,T){let n=hT(T,{key:`*${o.key}`,default:null},["mutable","updates"]);this.latestUpdateAtoms=$o(T,n),this.mutableAtoms=o,this.mutableAtoms.subject.subscribe(`store=${T.config.name}::tracker-atom-family`,(f)=>{let{type:S,token:A}=f;if(A.family){let $=xo(A.family.subKey);switch(S){case"state_creation":this.trackers.set($,new Fn(A,T));break;case"state_disposal":{let F=this.trackers.get($);if(F)F[Symbol.dispose](),this.trackers.delete($)}break}}})}}function ff(o,T,n){let f={key:T.key,type:"mutable_atom_family"},S=o.families.get(T.key);if(S)o.logger.error("\u2757","mutable_atom_family",T.key,`Overwriting an existing ${VT(S)} "${S.key}" in store "${o.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);let A=new oo,F=Object.assign((J)=>{let t=no(J),R={key:T.key,subKey:t},W=`${T.key}(${t})`,O=C(o),_={key:W,default:()=>T.default(J),toJson:T.toJson,fromJson:T.fromJson,mutable:!0};if(T.effects)_.effects=T.effects(J);let Q=Mf(O,_,R);return A.next({type:"state_creation",token:Q}),Q},f,{subject:A,install:(J)=>ff(J,T),toJson:T.toJson,fromJson:T.fromJson,internalRoles:n});return o.families.set(T.key,F),hF(o,F,T),new wA(F,o),f}var _A=(o,T)=>{let n=C(T),f=`${o.key}:JSON`;return n.families.get(f)};var Io=(o,T)=>{if(T.family){let f=C(o),A={key:`${T.family.key}:JSON`,type:"selector_family"},$=$o(f,A),F=JSON.parse(T.family.subKey);return i(o,$,F)}return{type:"selector",key:`${T.key}:JSON`}};var bT=(o)=>{let n={type:"atom",key:`*${o.key}`};if(o.family)n.family={key:`*${o.family.key}`,subKey:o.family.subKey};return n};function yF(o){return typeof o==="object"&&o!==null&&"do"in o&&"undo"in o&&"subscribe"in o}function Jf(o,T,n){let f=n.valueMap.get(T.key),S=o.valueMap.get(T.key);if(f!==S)return S;if(f===void 0)return T.default();n.logger.info("\uD83D\uDCC3","atom",T.key,"copying");let A=T.toJson(f),$=T.fromJson(A);return o.valueMap.set(T.key,$),new Fn(T,n),$}function yT(o,T,n,f){let S=o.valueMap.get(T);if(S instanceof nf)S.use(n);if(n instanceof Promise){let A=new nf(n);return o.valueMap.set(T,A),A.then(($)=>{yT(o,T,$,f),f.next({newValue:$,oldValue:A})}).catch(($)=>{o.logger.error("\uD83D\uDCA5","state",T,"rejected:",$)}),A}return o.valueMap.set(T,n),n}var AF=(o,T)=>{let n=T.valueMap.get(o.key);if(o.type==="mutable_atom"&&Ro(T)){let{parent:f}=T;n=Jf(T,o,f)}return n},RF=(o,T)=>{let n=T.valueMap.get(o);if(n instanceof nf){let f=n,S=T.selectors.get(o)??T.readonlySelectors.get(o);if(S)f.use(S.get());return}if(T.operation.open)T.operation.prev.set(o,n);T.valueMap.delete(o),T.logger.info("\uD83D\uDDD1","state",o,"evicted")};var kF=(o,T)=>{return C(o).atomsThatAreDefault.has(T)},SS=(o,T)=>{let n=C(o);n.atomsThatAreDefault=new Set(n.atomsThatAreDefault).add(T)},WF=(o,T)=>{let n=C(o);n.atomsThatAreDefault=new Set(C(o).atomsThatAreDefault),n.atomsThatAreDefault.delete(T)};function FT(o,T,n){o.logger.info("\uD83D\uDD28","atom",T.key,`creating in store "${o.config.name}"`);let f=C(o),S=f.atoms.get(T.key);if(S&&S.type==="atom")return o.logger.error("\u274C","atom",T.key,"Tried to create atom, but it already exists in the store."),fT(S);let A=new oo,$={...T,type:"atom",install:(t)=>{return t.logger.info("\uD83D\uDEE0\uFE0F","atom",T.key,`installing in store "${t.config.name}"`),FT(t,T,n)},subject:A};if(n)$.family=n;let F=T.default;if(T.default instanceof Function)F=T.default();f.atoms.set($.key,$),SS(o,T.key),yT(f,T.key,F,A);let J=fT($);if(T.effects){let t=0,R=[];for(let W of T.effects){let O=W({setSelf:(_)=>{Uo(o,J,_)},onSet:(_)=>lo(o,J,`effect[${t}]`,_)});if(O)R.push(O);++t}$.cleanup=()=>{for(let W of R)W()}}return J}function e$(o,T){if("mutable"in T){let S=Mf(o,T,void 0);return o.on.atomCreation.next(S),S}let f=FT(o,T,void 0);return o.on.atomCreation.next(f),f}function MA(o,T){let n=C(o),{key:f,family:S}=T,A=$o(n,T);if(!S)o.logger.error("\u274C","atom",f,"Standalone atoms cannot be disposed.");else{A.cleanup?.();let $=o.valueMap.get(A.key),F=$o(o,{key:S.key,type:"atom_family"}),J={type:"state_disposal",subType:"atom",token:T,value:$};F.subject.next(J);let t=Ro(n);if(n.atoms.delete(f),n.valueMap.delete(f),n.selectorAtoms.delete(f),n.atomsThatAreDefault.delete(f),o.timelineTopics.delete(f),T.type==="mutable_atom"){let R=bT(T);MA(o,R),o.trackers.delete(f)}if(o.logger.info("\uD83D\uDD25","atom",f,"deleted"),t&&n.transactionMeta.phase==="building"){let R=n.transactionMeta.update.updates.at(-1);if(!(R?.type==="molecule_disposal"&&R.values.some(([_])=>_===A.family?.key)))n.transactionMeta.update.updates.push(J)}else o.on.atomDisposal.next(T)}}class ho extends Set{mode="record";subject=new oo;cacheLimit=0;cache=[];cacheIdx=-1;cacheUpdateNumber=-1;constructor(o,T=0){super(o);if(o instanceof ho)this.parent=o,this.cacheUpdateNumber=o.cacheUpdateNumber;if(T)this.cacheLimit=T,this.cache=new Array(T),this.subscribe("auto cache",(n)=>{this.cacheIdx++,this.cacheIdx%=this.cacheLimit,this.cache[this.cacheIdx]=n})}toJSON(){return{members:[...this],cache:this.cache,cacheLimit:this.cacheLimit,cacheIdx:this.cacheIdx,cacheUpdateNumber:this.cacheUpdateNumber}}static fromJSON(o){let T=new ho(o.members,o.cacheLimit);return T.cache=o.cache,T.cacheIdx=o.cacheIdx,T.cacheUpdateNumber=o.cacheUpdateNumber,T}add(o){let T=super.add(o);if(this.mode==="record")this.cacheUpdateNumber++,this.emit(`add:${no(o)}`);return T}clear(){let o=this.mode==="record"?[...this]:null;if(super.clear(),o)this.cacheUpdateNumber++,this.emit(`clear:${JSON.stringify(o)}`)}delete(o){let T=super.delete(o);if(this.mode==="record")this.cacheUpdateNumber++,this.emit(`del:${no(o)}`);return T}parent;child=null;transactionUpdates=null;transaction(o){this.mode="transaction",this.transactionUpdates=[],this.child=new ho(this);let T=this.child._subscribe("transaction",(n)=>{this.transactionUpdates?.push(n)});try{if(o(this.child)){for(let f of this.transactionUpdates)this.doStep(f);this.cacheUpdateNumber++,this.emit(`tx:${this.transactionUpdates.join(";")}`)}}catch(n){throw console.warn("Did not apply transaction to SetRTX; this error was thrown:",n),n}finally{T(),this.child=null,this.transactionUpdates=null,this.mode="record"}}_subscribe(o,T){return this.subject.subscribe(o,T)}subscribe(o,T){return this.subject.subscribe(o,(n)=>{T(`${this.cacheUpdateNumber}=${n}`)})}emit(o){this.subject.next(o)}doStep(o){let T=o.indexOf(":"),n=o.substring(0,T),f=o.substring(T+1);switch(n){case"add":this.add(JSON.parse(f));break;case"clear":this.clear();break;case"del":this.delete(JSON.parse(f));break;case"tx":for(let S of f.split(";"))this.doStep(S)}}getUpdateNumber(o){let T=o.indexOf("=");return Number(o.substring(0,T))}do(o){let T=o.indexOf("="),n=Number(o.substring(0,T)),f=n-this.cacheUpdateNumber;if(f>0){if(f===1){this.mode="playback";let A=o.substring(T+1);return this.doStep(A),this.mode="record",this.cacheUpdateNumber=n,null}return this.cacheUpdateNumber+1}if(Math.abs(f)<this.cacheLimit){let A=this.cacheIdx+f;if(this.cache[A]===o)return null;this.mode="playback";let F=!1;while(!F){this.cacheIdx%=this.cacheLimit;let t=this.cache[this.cacheIdx];if(this.cacheIdx--,!t)return"OUT_OF_RANGE";this.undo(t),F=this.cacheIdx===A-1}let J=o.substring(T+1);return this.doStep(J),this.mode="record",this.cacheUpdateNumber=n,null}return"OUT_OF_RANGE"}undoStep(o){let T=o.indexOf(":"),n=o.substring(0,T),f=o.substring(T+1);switch(n){case"add":this.delete(JSON.parse(f));break;case"del":this.add(JSON.parse(f));break;case"clear":{let S=JSON.parse(f);for(let A of S)this.add(A);break}case"tx":{let S=f.split(";");for(let A=S.length-1;A>=0;A--)this.undoStep(S[A])}}}undo(o){let T=o.indexOf("=");if(Number(o.substring(0,T))===this.cacheUpdateNumber){this.mode="playback";let f=o.substring(T+1);return this.undoStep(f),this.mode="record",this.cacheUpdateNumber--,null}return this.cacheUpdateNumber}}class $f{toolkit;options;defaultContent;molecules=new Map;relations;states;core;transact(o,T){let n=this.toolkit;this.toolkit=o,T(this),this.toolkit=n}store;realm;[Symbol.dispose](){}constructor(o,T,n=fo.STORE){this.store=n,this.realm=new AA(n),this.options=o,this.defaultContent=T,this.store.miscResources.set(`join:${o.key}`,this),this.realm.allocate("root",o.key),this.toolkit={get:(...E)=>to(n,...E),set:(...E)=>{Uo(n,...E)},find:(...E)=>i(n,...E),json:(E)=>Io(n,E)};let f=o.between[0],S=o.between[1],A=ff(n,{key:`${o.key}/relatedKeys`,default:()=>new ho,mutable:!0,fromJson:(E)=>ho.fromJSON(E),toJson:(E)=>E.toJSON()},["join","relations"]);this.core={relatedKeysAtoms:A};let $=({get:E},z)=>E(A,z),F=({set:E},z,U)=>{if(!this.store.molecules.has(no(z)))this.realm.allocate(o.key,z);E(A,z,(D)=>D.add(U)),E(A,U,(D)=>D.add(z))},J=({set:E},z,U)=>{E(A,z,(D)=>{return D.delete(U),D}),E(A,U,(D)=>{return D.delete(z),D})},t=(E,z,U)=>{let{find:D,get:v,set:l}=E,K=D(A,z),s=v(K);for(let q of s){if(U.includes(q))continue;l(A,q,(ko)=>{return ko.delete(z),ko})}l(K,(q)=>{return q.transaction((a)=>{a.clear();for(let ko of U){let mo=$(E,ko),nT=mo.has(z);if(this.relations.cardinality==="1:n"){let IT=[];for(let G of mo){if(G===z)continue;let p=$(E,G);if(p.delete(ko),p.size===0)IT.push(G)}if(!nT&&mo.size>0)mo.clear();for(let G of IT){let p=[ko,G].sort(),Fo=`"${p[0]}:${p[1]}"`;this.molecules.delete(Fo)}}if(!nT)mo.add(z);a.add(ko)}return!0}),q})},R=(E,z,U)=>{let{set:D}=E;D(A,z,(v)=>{return v.transaction((l)=>{for(let K of U)l.add(K);return!0}),v});for(let v of U)D(A,v,(l)=>{return l.add(z),l});return!0},W=(E,z,U)=>{let D=$(E,z);return U?D.has(U):D.size>0},O={getRelatedKeys:(E)=>$(this.toolkit,E),addRelation:(E,z)=>{this.store.moleculeJoins.set(E,o.key),this.store.moleculeJoins.set(z,o.key),F(this.toolkit,E,z)},deleteRelation:(E,z)=>{J(this.toolkit,E,z)},replaceRelationsSafely:(E,z)=>{t(this.toolkit,E,z)},replaceRelationsUnsafely:(E,z)=>{R(this.toolkit,E,z)},has:(E,z)=>W(this.toolkit,E,z)},_,Q;if(T){Q=hT(n,{key:`${o.key}/content`,default:T},["join","content"]);let E=({get:D},v)=>D(Q,v),z=({set:D},v,l)=>{D(Q,v,l)};_=Object.assign(O,{getContent:(D)=>{return E(this.toolkit,D)},setContent:(D,v)=>{z(this.toolkit,D,v)},deleteContent:(D)=>{this.realm.deallocate(D)}})}else _=O;let H=new jo(o,{externalStore:_,isAType:o.isAType,isBType:o.isBType,makeContentKey:(...E)=>{let[z,U]=E,D=E.sort(),v=`${D[0]}:${D[1]}`,l=n.molecules.get(no(z)),K=n.molecules.get(no(U));if(!l)this.realm.allocate(o.key,z);if(!K)this.realm.allocate(o.key,U);return this.realm.allocate(z,v,"all"),this.realm.claim(U,v),this.store.moleculeJoins.set(v,o.key),v}}),m=()=>NT(n,{key:`${o.key}/singleRelatedKey`,get:(E)=>({get:z})=>{let U=z(A,E);for(let D of U)return D;return null}},["join","keys"]),b=()=>{return NT(n,{key:`${o.key}/multipleRelatedKeys`,get:(E)=>({get:z})=>{let U=_A(A,n);return z(U,E).members}},["join","keys"])},r=()=>NT(n,{key:`${o.key}/singleRelatedEntry`,get:(E)=>({get:z})=>{let U=z(A,E);for(let D of U){let v=H.isAType?.(E)?E:void 0,l=v===void 0?E:void 0;v??=D,l??=D;let K=H.makeContentKey(v,l),s=z(Q,K);return[D,s]}return null}},["join","entries"]),P=()=>NT(n,{key:`${o.key}/multipleRelatedEntries`,get:(E)=>({get:z})=>{let U=_A(A,n);return z(U,E).members.map((v)=>{let l=H.isAType?.(E)?E:void 0,K=l===void 0?E:void 0;l??=v,K??=v;let s=H.makeContentKey(l,K),q=z(Q,s);return[v,q]})}},["join","entries"]);switch(o.cardinality){case"1:1":{let E=m(),z=`${f}KeyOf${Mo(S)}`,U=`${S}KeyOf${Mo(f)}`,D={[z]:E,[U]:E},v;if(T){let l=r(),K=`${f}EntryOf${Mo(S)}`,s=`${S}EntryOf${Mo(f)}`,q={[K]:l,[s]:l};v=Object.assign(D,q)}else v=D;this.relations=H,this.states=v;break}case"1:n":{let E=m(),z=b(),U=`${f}KeyOf${Mo(S)}`,D=`${S}KeysOf${Mo(f)}`,v={[U]:E,[D]:z},l;if(T){let K=r(),s=P(),q=`${f}EntryOf${Mo(S)}`,a=`${S}EntriesOf${Mo(f)}`,ko={[q]:K,[a]:s};l=Object.assign(v,ko)}else l=v;this.relations=H,this.states=l;break}case"n:n":{let E=b(),z=`${f}KeysOf${Mo(S)}`,U=`${S}KeysOf${Mo(f)}`,D={[z]:E,[U]:E},v;if(T){let l=P(),K=`${f}EntriesOf${Mo(S)}`,s=`${S}EntriesOf${Mo(f)}`,q={[K]:l,[s]:l};v=Object.assign(D,q)}else v=D;this.relations=H,this.states=v}}}}function Qn(o,T){let n=T.joins.get(o.key);if(n===void 0){let S=fo.STORE.joins.get(o.key);if(S===void 0)throw new Error(`Join "${o.key}" not found in store "${T.config.name}"`);n=new $f(S.options,S.defaultContent,T),T.joins.set(o.key,n)}return n}function Ff(o,T,n){let f=Qn(o,n),S=C(n);if(Ro(S)){let{toolkit:A}=S.transactionMeta;f.transact(A,({relations:$})=>{T($)})}else T(f.relations)}function lf(o,T,n){let f=Qn(o,n),S;switch(o.cardinality){case"1:1":{let A=`${o.a}KeyOf${Mo(o.b)}`,$=`${o.b}KeyOf${Mo(o.a)}`;S={get[A](){let J=f.states[A];return i(n,J,T)},get[$](){let J=f.states[$];return i(n,J,T)}};let F=`${o.a}EntryOf${Mo(o.b)}`;if(F in f.states){let J=`${o.b}EntryOf${Mo(o.a)}`;Object.assign(S,{get[F](){let t=f.states[F];return i(n,t,T)},get[J](){let t=f.states[J];return i(n,t,T)}})}break}case"1:n":{let A=`${o.a}KeyOf${Mo(o.b)}`,$=`${o.b}KeysOf${Mo(o.a)}`;S={get[A](){let J=f.states[A];return i(n,J,T)},get[$](){let J=f.states[$];return i(n,J,T)}};let F=`${o.a}EntryOf${Mo(o.b)}`;if(F in f.states){let J=`${o.b}EntriesOf${Mo(o.a)}`;Object.assign(S,{get[F](){let t=f.states[F];return i(n,t,T)},get[J](){let t=f.states[J];return i(n,t,T)}})}break}case"n:n":{let A=`${o.a}KeysOf${Mo(o.b)}`,$=`${o.b}KeysOf${Mo(o.a)}`;S={get[A](){let J=f.states[A];return i(n,J,T)},get[$](){let J=f.states[$];return i(n,J,T)}};let F=`${o.a}EntriesOf${Mo(o.b)}`;if(F in f.states){let J=`${o.b}EntriesOf${Mo(o.a)}`;Object.assign(S,{get[F](){let t=f.states[F];return i(n,t,T)},get[J](){let t=f.states[J];return i(n,t,T)}})}}}return S}function oF(o,T){return Qn(o,T).core.relatedKeysAtoms}function iT(o){return o.startsWith("\uD83D\uDD0D ")}var XA=(o)=>{let T=FT(o,{key:"\uD83D\uDD0D Atom Token Index (Internal)",default:()=>{let n=new Map;for(let[f,S]of o.atoms){if(iT(f))continue;let A=fT(S);if(S.family){let $=n.get(S.family.key);if(!$||!("familyMembers"in $))$={key:S.family.key,familyMembers:new Map},n.set(S.family.key,$);$.familyMembers.set(S.family.subKey,A)}else n.set(f,A)}return n},effects:[({setSelf:n})=>{o.on.atomCreation.subscribe("introspection",(f)=>{if(iT(f.key))return;n((S)=>{if(f.family){let{key:A,subKey:$}=f.family,F=S.get(A);if(F===void 0||!("familyMembers"in F))F={key:A,familyMembers:new Map},S.set(A,F);F.familyMembers.set($,f)}else S.set(f.key,f);return S})}),o.on.atomDisposal.subscribe("introspection",(f)=>{n((S)=>{if(f.family){let{key:A,subKey:$}=f.family,F=S.get(A);if(F&&"familyMembers"in F){if(F.familyMembers.delete($),F.familyMembers.size===0)S.delete(A)}}else S.delete(f.key);return S})})}]},void 0);return jT(o,{key:"\uD83D\uDD0D Atom Token Index",get:({get:n})=>n(T)})};var HA=(o)=>{let T=FT(o,{key:"\uD83D\uDD0D Selector Token Index (Internal)",default:()=>{let n=new Map;for(let f of[o.readonlySelectors,o.selectors])for(let[S,A]of f){if(iT(S))continue;let $=fT(A);if(A.family){let F=n.get(A.family.key);if(!F||!("familyMembers"in F))F={key:A.family.key,familyMembers:new Map},n.set(A.family.key,F);F.familyMembers.set(A.family.subKey,$)}else n.set(S,$)}return n},effects:[({setSelf:n})=>{o.on.selectorCreation.subscribe("introspection",(f)=>{if(iT(f.key))return;n((S)=>{if(f.family){let{key:A,subKey:$}=f.family,F=S.get(A);if(F===void 0||!("familyMembers"in F))F={key:A,familyMembers:new Map},S.set(A,F);F.familyMembers.set($,f)}else S.set(f.key,f);return S})}),o.on.selectorDisposal.subscribe("introspection",(f)=>{n((S)=>{if(f.family){let{key:A,subKey:$}=f.family,F=S.get(A);if(F&&"familyMembers"in F){if(F.familyMembers.delete($),F.familyMembers.size===0)S.delete(A)}}else S.delete(f.key);return S})})}]},void 0);return jT(o,{key:"\uD83D\uDD0D Selector Token Index",get:({get:n})=>n(T)})};class AS{supported;constructor(o){this.supported=o}refine(o){for(let[T,n]of Object.entries(this.supported))try{if(n(o)===!0&&n!==Boolean)return{type:T,data:o}}catch(f){try{if(o instanceof n)return{type:T,data:o}}catch(S){}}return null}}var KA=new AS({number:(o)=>typeof o==="number",string:(o)=>typeof o==="string",boolean:(o)=>typeof o==="boolean",null:(o)=>o===null});function EA(o){if(!o)return!1;return Object.getPrototypeOf(o)===Object.prototype}var GA=new AS({object:EA,array:(o)=>Array.isArray(o)}),vM=new AS({...KA.supported,...GA.supported}),Un=(o)=>{if(o===void 0)return"undefined";let T=vM.refine(o);if(T)return T.type;return Object.getPrototypeOf(o).constructor.name};class bF{store;auditorCreatedAt=performance.now();statesCreatedAt=new Map;atomIndex;selectorIndex;disposed=!1;unsubscribeFromAtomCreation;unsubscribeFromAtomDisposal;unsubscribeFromSelectorCreation;unsubscribeFromSelectorDisposal;constructor(o=fo.STORE){this.store=o,this.atomIndex=XA(this.store),this.selectorIndex=HA(this.store),this.unsubscribeFromAtomCreation=this.store.on.atomCreation.subscribe(`auditor-${this.auditorCreatedAt}`,({key:T})=>{this.statesCreatedAt.set(T,performance.now()-this.auditorCreatedAt)}),this.unsubscribeFromAtomDisposal=this.store.on.atomDisposal.subscribe(`auditor-${this.auditorCreatedAt}`,({key:T})=>{this.statesCreatedAt.delete(T)}),this.unsubscribeFromSelectorCreation=this.store.on.selectorCreation.subscribe(`auditor-${this.auditorCreatedAt}`,({key:T})=>{this.statesCreatedAt.set(T,performance.now()-this.auditorCreatedAt)}),this.unsubscribeFromSelectorDisposal=this.store.on.selectorDisposal.subscribe(`auditor-${this.auditorCreatedAt}`,({key:T})=>{this.statesCreatedAt.delete(T)})}static DEFAULT_LIST_RESOURCES_PARAM={atomFamilies:!0,selectorFamilies:!0};listResources(o=bF.DEFAULT_LIST_RESOURCES_PARAM){if(this.disposed)throw new Error("This Auditor has been disposed");let T=nA(this.atomIndex),n=nA(this.selectorIndex),f=[...T.values()].filter((F)=>("familyMembers"in F)),S=[...n.values()].filter((F)=>("familyMembers"in F)),A=performance.now(),$=[];if(o.atomFamilies)for(let F of f){let J=F.familyMembers.values();for(let t of J){let W=this.statesCreatedAt.get(t.key)??this.auditorCreatedAt,O=A-W;$.push([t,O])}}if(o.selectorFamilies)for(let F of S){let J=F.familyMembers.values();for(let t of J){let W=this.statesCreatedAt.get(t.key)??this.auditorCreatedAt,O=A-W;$.push([t,O])}}return $}[Symbol.dispose](){this.unsubscribeFromAtomCreation(),this.unsubscribeFromAtomDisposal(),this.unsubscribeFromSelectorCreation(),this.unsubscribeFromSelectorDisposal(),this.disposed=!0}}var YA=(o,T)=>{let n=(f,S)=>{let $=((J,t)=>{let R=T(J,t);if(R)return R;return null})(f,S);if($?.jobComplete??$?.pathComplete)return $;let F=Array.isArray(S)?S.map((J,t)=>[t,J]):EA(S)?Object.entries(S):[];for(let[J,t]of F){let R=n([...f,J],t);if(R?.jobComplete)return R}return{}};n([],o)};function rM(o,T){return{summary:`${o<T?"+":"-"}${Math.abs(o-T)} (${o} \u2192 ${T})`}}function qM(o,T){return{summary:`${o.length<T.length?"+":"-"}${Math.abs(o.length-T.length)} ("${o}" \u2192 "${T}")`}}function pM(o,T){return{summary:`${o} \u2192 ${T}`}}function xF(o,T,n){let f="",S=[],A=[],$=[];return YA(o,(F,J)=>{let t;for(t of F){let R=T[t];if(R===void 0)A.push([t,JSON.stringify(J)]);else{let W=n(J,R);if(W.summary!=="No Change")$.push([t,W])}}}),YA(T,(F,J)=>{let t;for(t of F)if(o[t]===void 0)S.push([t,JSON.stringify(J)])}),f=`\uFF5E${$.length} \uFF0B${S.length} \uFF0D${A.length}`,{summary:f,added:S,removed:A,changed:$}}function cM(o,T,n){return xF(o,T,n)}class vF{leafRefinery;treeRefinery;leafDiffers;treeDiffers;constructor(o,T,n){this.leafRefinery=o,this.treeRefinery=T,this.leafDiffers={},this.treeDiffers={};for(let f of Object.keys(o.supported)){let S=n[f];this.leafDiffers[f]=S}for(let f of Object.keys(T.supported)){let S=n[f];this.treeDiffers[f]=S}}diff(o,T){if(o===T)return{summary:"No Change"};let n=this.leafRefinery.refine(o)??this.treeRefinery.refine(o),f=this.leafRefinery.refine(T)??this.treeRefinery.refine(T);if(n!==null&&f!==null){if(n.type===f.type){if(n.type in this.leafDiffers)return this.leafDiffers[n.type](n.data,f.data);if(n.type in this.treeDiffers)return this.treeDiffers[n.type](n.data,f.data,(F,J)=>this.diff(F,J))}}let S=Un(o),A=Un(T);if(S===A)return{summary:`${S} \u2192 ${A}`};return{summary:`Type change: ${S} \u2192 ${A}`}}}var A8=new vF(KA,GA,{number:rM,string:qM,boolean:pM,null:()=>({summary:"No Change"}),object:xF,array:cM});class rF extends Map{set(o,T){if(this.has(o))return console.warn("Tried to set a key that already exists in an InvariantMap",{key:o,value:T}),this;return super.set(o,T)}clear(){throw new Error("Cannot clear an InvariantMap")}}class $S{type="continuity";globals=[];actions=[];perspectives=[];key;constructor(o){this.key=o}static existing=new rF;static create(o,T){let n=new $S(o),{type:f,globals:S,actions:A,perspectives:$}=T(n),F={type:f,key:o,globals:S,actions:A,perspectives:$};return $S.existing.set(o,F),F}add(...o){switch(o[0].type){case"atom":case"mutable_atom":this.globals.push(...o);break;case"transaction":this.actions.push(...o);break;case"atom_family":case"mutable_atom_family":{let[n,f]=o;this.perspectives.push({type:"realtime_perspective",resourceAtoms:n,viewAtoms:f})}break}return this}}function W8(o){let{key:T,config:n}=o,f=$S.create(T,n),{actions:S}=f;for(let A of S)DF(fo.STORE,T,A.key);return GF(fo.STORE,T,-1),f}var X8=Gn({key:"usersInRoomIndex",mutable:!0,default:()=>new ho,toJson:(o)=>o.toJSON(),fromJson:(o)=>ho.fromJSON(o)}),zA=Gn({key:"roomIndex",default:()=>new ho,mutable:!0,toJson:(o)=>o.toJSON(),fromJson:(o)=>ho.fromJSON(o)}),ZM={enteredAtEpoch:0},yf=df({key:"usersInRooms",between:["room","user"],cardinality:"1:n",isAType:(o)=>typeof o==="string",isBType:(o)=>typeof o==="string"},ZM),H8=uf({key:"usersInMyRoomView",get:(o)=>({find:T})=>{let n=a$(yf);return[T(n,o)]}});import{spawn as PM}from"node:child_process";class Vn{listeners;globalListeners;handleEvent(o,...T){for(let f of this.globalListeners)f(o,...T);let n=this.listeners.get(o);if(n)for(let f of n)f(...T)}id="no_id_retrieved";emit;constructor(o){this.emit=o,this.listeners=new Map,this.globalListeners=new Set}on(o,T){let n=this.listeners.get(o);if(n)n.add(T);else this.listeners.set(o,new Set([T]));return this}onAny(o){return this.globalListeners.add(o),this}off(o,T){let n=this.listeners.get(o);if(n)if(T)n.delete(T);else this.listeners.delete(o);return this}offAny(o){return this.globalListeners.delete(o),this}}class DA extends Vn{incompleteData="";unprocessedEvents=[];incompleteLog="";unprocessedLogs=[];id="#####";process;key;logger;handleLog(o){if(Array.isArray(o)){let[T,...n]=o;switch(T){case"i":this.logger.info(...n);break;case"w":this.logger.warn(...n);break;case"e":this.logger.error(...n);break;default:return}}}constructor(o,T,n){super((f,...S)=>{let A=JSON.stringify([f,...S])+"\x03",$=(F)=>{if(F.code==="EPIPE")console.error("EPIPE error during write",this.process.stdin);this.process.stdin.removeListener("error",$)};return this.process.stdin.once("error",$),this.process.stdin.write(A),this});if(this.process=o,this.key=T,this.logger=n??{info:(...f)=>{console.info(this.id,this.key,...f)},warn:(...f)=>{console.warn(this.id,this.key,...f)},error:(...f)=>{console.error(this.id,this.key,...f)}},this.process.stdout.on("data",(f)=>{let S=f.toString();if(S==="ALIVE")return;this.unprocessedEvents.push(...S.split("\x03"));let A=this.unprocessedEvents.shift();this.incompleteData+=A??"";try{if(this.incompleteData.startsWith("error"))console.log("\u2757",this.incompleteData);let $=xo(this.incompleteData);this.handleEvent(...$);while(this.unprocessedEvents.length>0){let F=this.unprocessedEvents.shift();if(F){if(this.unprocessedEvents.length===0)this.incompleteData=F;$=xo(F),this.handleEvent(...$)}}this.incompleteData=""}catch($){console.warn("\u26A0\uFE0F----------------\u26A0\uFE0F"),console.warn(this.incompleteData),console.warn("\u26A0\uFE0F----------------\u26A0\uFE0F"),console.error($)}}),this.process.stderr.on("data",(f)=>{let S=f.toString();this.unprocessedLogs.push(...S.split("\x03"));let A=this.unprocessedLogs.shift();this.incompleteLog+=A??"";try{let $=xo(this.incompleteLog);this.handleLog($);while(this.unprocessedLogs.length>0)if(this.incompleteLog=this.unprocessedLogs.shift()??"",this.incompleteLog)$=xo(this.incompleteLog),this.handleLog($)}catch($){console.error("\u274C\u274C\u274C"),console.error(this.incompleteLog),console.error($),console.error("\u274C\u274C\u274C\uFE0F")}}),o.pid)this.id=o.pid.toString()}}class qF extends Vn{in;out;id="no_id_retrieved";disposalFunctions=[];constructor(o){super((...T)=>{return this.out.next(T),this});this.id=o,this.in=new oo,this.out=new oo,this.in.subscribe("socket",(T)=>{this.handleEvent(...T)})}dispose(){for(let o of this.disposalFunctions)o()}}class QA extends Vn{incompleteData="";unprocessedEvents=[];relays;relayServices;process;id="#####";log(...o){this.process.stderr.write(no(o.map((T)=>T instanceof ho?`{ ${T.toJSON().members.join(" | ")} }`:T))+"\x03")}logger={info:(...o)=>{this.log("i",...o)},warn:(...o)=>{this.log("w",...o)},error:(...o)=>{this.log("e",...o)}};constructor(){super((o,...T)=>{let n=JSON.stringify([o,...T]);return this.process.stdout.write(n+"\x03"),this});if(this.process=process,this.process.stdin.resume(),this.relays=new Map,this.relayServices=[],this.process.stdin.on("data",(o)=>{let T=o.toString();this.unprocessedEvents.push(...T.split("\x03"));let n=this.unprocessedEvents.shift();this.incompleteData+=n??"";try{let f=xo(this.incompleteData);this.logger.info("\uD83C\uDFB0","received",f),this.handleEvent(...f);while(this.unprocessedEvents.length>0){let S=this.unprocessedEvents.shift();if(S){if(this.unprocessedEvents.length===0)this.incompleteData=S;let A=xo(S);this.handleEvent(...A)}}this.incompleteData=""}catch(f){if(f instanceof Error)this.logger.error("\u2757",f.message,f.cause,f.stack)}}),this.on("exit",()=>{this.logger.info("\uD83D\uDD25",this.id,'received "exit"'),process.exit(0)}),process.on("exit",(o)=>{this.logger.info("\uD83D\uDD25",this.id,`exited with code ${o}`)}),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",(o)=>{this.logger.info("\uD83D\uDC64","user",o,"joined");let T=new qF(`user:${o}`);this.relays.set(o,T),this.logger.info("\uD83D\uDD17","attaching services:",`[${[...this.relayServices.keys()].join(", ")}]`);for(let n of this.relayServices){let f=n(T);if(f)T.disposalFunctions.push(f)}this.on(`user:${o}`,(...n)=>{T.in.next(n)}),T.out.subscribe("socket",(n)=>{this.emit(...n)})}),this.on("user-leaves",(o)=>{let T=this.relays.get(o);if(this.off(`relay:${o}`),T)T.dispose(),this.relays.delete(o)}),process.stdout.write("ALIVE")}relay(o){this.logger.info("\uD83D\uDD17","running relay method"),this.relayServices.push(o)}}var UA=nn({key:"roomArguments",default:["echo",["Hello World!"]]}),pF=uf({key:"room",get:(o)=>async({get:T,find:n})=>{let f=n(UA,o),S=T(f),[A,$]=S,F=await new Promise((J)=>{let t=PM(A,$,{env:process.env}),R=(W)=>{if(W.toString()==="ALIVE")t.stdout.off("data",R),J(t)};t.stdout.on("data",R)});return new DA(F,o)}});var i8=tf({key:"createRoom",do:({get:o,set:T,find:n},f,S,A)=>{let $=A?[S,A]:[S],F=n(UA,f);T(F,$),T(zA,(R)=>R.add(f));let J=n(pF,f);return o(J)}}),g8=tf({key:"joinRoom",do:(o,T,n,f)=>{let S={enteredAtEpoch:f};return Ff(yf,(A)=>{A.set({room:T,user:n},S)},o.env().store),S}}),d8=tf({key:"leaveRoom",do:(o,T,n)=>{Ff(yf,(f)=>{f.delete({room:T,user:n})},o.env().store)}}),l8=tf({key:"destroyRoom",do:(o,T)=>{Ff(yf,(n)=>{n.delete({room:T})},o.env().store),o.set(zA,(n)=>(n.delete(T),n))}});function VA(o,T){return T.map((n)=>{switch(n.type){case"transaction_update":{let f=VA(o,n.updates);return{...n,updates:f}}case"atom_update":case"selector_update":case"molecule_creation":case"molecule_disposal":case"molecule_transfer":case"state_creation":case"state_disposal":return n}}).filter((n)=>{switch(n.type){case"atom_update":case"selector_update":return o.includes(n.key);case"state_creation":case"state_disposal":return o.includes(n.token.key);case"molecule_creation":case"transaction_update":case"molecule_disposal":case"molecule_transfer":return!0}})}var s8=nn({key:"redactor",default:{occlude:(o)=>o}}),Bn=nn({key:"unacknowledgedUpdates",default:()=>[]});var cF=nn({key:"sockets",default:null}),nK=Gn({key:"socketsIndex",mutable:!0,default:()=>new ho,toJson:(o)=>o.toJSON(),fromJson:(o)=>ho.fromJSON(o)}),fK=Gn({key:"usersIndex",mutable:!0,default:()=>new ho,toJson:(o)=>o.toJSON(),fromJson:(o)=>ho.fromJSON(o)}),BA=df({key:"usersOfSockets",between:["user","socket"],cardinality:"1:1",isAType:(o)=>o.startsWith("user::"),isBType:(o)=>o.startsWith("socket::")});function ZF(o,T,n,f){let S=T.key;return function A(){let $=[];for(let J of T.globals){let t=J.type==="mutable_atom"?Io(o,J):J,R=to(o,t);$.push(t,R)}for(let J of T.perspectives){let{viewAtoms:t,resourceAtoms:R}=J,W=i(o,t,n),O=to(o,W);o.logger.info("\uD83D\uDC41","atom",R.key,`${n} can see`,{viewAtoms:t,resourceAtoms:R,userView:O});for(let _ of O){let Q=_.type==="mutable_atom"?Io(o,_):_,H=to(o,Q);$.push(Q,H)}}let F=qo(o)?o.transactionMeta.epoch.get(S)??null:null;f?.emit(`continuity-init:${S}`,F,$)}}function PF(o,T,n){let f=T.key;return function S(A){o.logger.info("\uD83D\uDECE\uFE0F","continuity",f,"received",A);let{key:$,id:F}=A,J=`tx-run:${$}:${F}`,t=`${J}:start`,R=`${J}:end`;performance.mark(t);try{zn(o,{type:"transaction",key:$},F)(...A.params)}catch(O){if(O instanceof Error)o.logger.error("\u274C","continuity",f,`failed to run transaction ${$} from ${n} with update ${F}`,O.message)}performance.mark(R);let W=performance.measure(J,t,R);o?.logger.info("\uD83D\uDE80","transaction",$,F,n,W.duration)}}function iF(o,T,n,f){let S=T.key;return function A($){if(o.logger.info("\uD83D\uDC4D","continuity",S,`${n} acknowledged epoch ${$}`),f[0]?.epoch===$)Uo(o,Bn,n,(J)=>{return J.shift(),o.logger.info("\uD83D\uDC4D","continuity",S,`${n} unacknowledged update queue now has`,J.length,"items"),J})}}function gF(o,T,n,f){let S=T.key,A=[];for(let $ of T.actions){let F=WA(o,$,`sync-continuity:${S}:${n}`,(J)=>{try{let t=T.globals.map((O)=>{if(O.type==="atom")return O.key;return bT(O).key}).concat(T.perspectives.flatMap((O)=>{let{viewAtoms:_}=O,Q=i(o,_,n);return to(o,Q).map((m)=>{return m.type==="mutable_atom"?"*"+m.key:m.key})})),R=VA(t,J.updates),W={...J,updates:R};Uo(o,Bn,n,(O)=>{if(W)O.push(W),O.sort((_,Q)=>_.epoch-Q.epoch),o.logger.info("\uD83D\uDC4D","continuity",S,`${n} unacknowledged update queue now has`,O.length,"items");return O}),f?.emit(`tx-new:${S}`,W)}catch(t){if(t instanceof Error)o.logger.error("\u274C","continuity",S,`${n} failed to send update from transaction ${$.key} to ${n}`,t.message)}});A.push(F)}return A}function dF(o,T,n,f){let S=T.key,A=[];for(let $ of T.perspectives){let{viewAtoms:F}=$,J=i(o,F,n),t=lo(o,J,`sync-continuity:${S}:${n}:perspective:${$.resourceAtoms.key}`,({oldValue:R,newValue:W})=>{let O=R.map((m)=>m.key),_=W.map((m)=>m.key),Q=R.filter((m)=>!_.includes(m.key)),H=W.filter((m)=>!O.includes(m.key)).flatMap((m)=>{let b=m.type==="mutable_atom"?Io(o,m):m,r=to(o,b);return[b,r]});if(o.logger.info("\uD83D\uDC41","atom",$.resourceAtoms.key,`${n} has a new perspective`,{oldKeys:O,newKeys:_,revealed:H,concealed:Q}),H.length>0)f?.emit(`reveal:${S}`,H);if(Q.length>0)f?.emit(`conceal:${S}`,Q)});A.push(t)}return A}function CK({socket:o,store:T=fo.STORE}){return function n(f){let S=o,A=f.key,$=lf(BA,`socket::${S.id}`,T).userKeyOfSocket,F=to(T,$);if(!F)return T.logger.error("\u274C","continuity",A,`Tried to create a synchronizer for a socket (${S.id}) that is not connected to a user.`),()=>{};let J=lf(BA,F,T).socketKeyOfUser,t=lo(T,J,`sync-continuity:${A}:${F}`,({newValue:b})=>{if(T.logger.info("\uD83D\uDC4B","continuity",A,`seeing ${F} on new socket ${b}`),b===null){T.logger.warn("\u274C","continuity",A,`User (${F}) is not connected to a socket, waiting for them to reappear.`);return}let r=i(T,cF,b);S=to(T,r);for(let E of R)S?.emit(`tx-new:${A}`,E)}),R=to(T,Bn,F),W=[],O=dF(T,f,F,S),_=gF(T,f,F,S);W.push(...O,..._);let Q=ZF(T,f,F,o);S.off(`get:${A}`,Q),S.on(`get:${A}`,Q);let H=PF(T,f,F);S.off(`tx-run:${A}`,H),S.on(`tx-run:${A}`,H);let m=iF(T,f,F,R);return S?.on(`ack:${A}`,m),()=>{for(let b of W)b();S?.off(`ack:${A}`,m),S?.off(`get:${A}`,Q),S?.off(`tx-run:${A}`,H)}}}var{file:h0,serve:Jk}=globalThis.Bun;import{readFileSync as tJ}from"node:fs";import{resolve as hA}from"node:path";function iM(o,T){let n={},f=[];for(let S in o){let A=o[S],$=T[S],F=A["~standard"].validate($);if(F instanceof Promise)throw new Error(`Validation must be synchronous, but ${S} returned a Promise.`);if(F.issues){f.push(...F.issues.map((J)=>({...J,path:[S,...J.path??[]]})));continue}n[S]=F.value}if(f.length)return{issues:f};return{value:n}}function lF(o){let T=o.runtimeEnvStrict??o.runtimeEnv??process.env;if(o.emptyStringAsUndefined??!1){for(let[r,P]of Object.entries(T))if(P==="")delete T[r]}if(!!o.skipValidation)return T;let S=typeof o.client==="object"?o.client:{},A=typeof o.server==="object"?o.server:{},$=typeof o.shared==="object"?o.shared:{},F=o.isServer??(typeof window==="undefined"||("Deno"in window)),J=F?{...A,...$,...S}:{...S,...$},t=iM(J,T),R=o.onValidationError??((r)=>{throw console.error("\u274C Invalid environment variables:",r),new Error("Invalid environment variables")}),W=o.onInvalidAccess??(()=>{throw new Error("\u274C Attempted to access a server-side environment variable on the client")});if(t.issues)return R(t.issues);let O=(r)=>{if(!o.clientPrefix)return!0;return!r.startsWith(o.clientPrefix)&&!(r in $)},_=(r)=>{return F||!O(r)},Q=(r)=>{return r==="__esModule"||r==="$$typeof"},H=(o.extends??[]).reduce((r,P)=>{return Object.assign(r,P)},{}),m=Object.assign(t.value,H);return new Proxy(m,{get(r,P){if(typeof P!=="string")return;if(Q(P))return;if(!_(P))return W(P);return Reflect.get(r,P)}})}var Ao;(function(o){o.assertEqual=(S)=>S;function T(S){}o.assertIs=T;function n(S){throw new Error}o.assertNever=n,o.arrayToEnum=(S)=>{let A={};for(let $ of S)A[$]=$;return A},o.getValidEnumValues=(S)=>{let A=o.objectKeys(S).filter((F)=>typeof S[S[F]]!=="number"),$={};for(let F of A)$[F]=S[F];return o.objectValues($)},o.objectValues=(S)=>{return o.objectKeys(S).map(function(A){return S[A]})},o.objectKeys=typeof Object.keys==="function"?(S)=>Object.keys(S):(S)=>{let A=[];for(let $ in S)if(Object.prototype.hasOwnProperty.call(S,$))A.push($);return A},o.find=(S,A)=>{for(let $ of S)if(A($))return $;return},o.isInteger=typeof Number.isInteger==="function"?(S)=>Number.isInteger(S):(S)=>typeof S==="number"&&isFinite(S)&&Math.floor(S)===S;function f(S,A=" | "){return S.map(($)=>typeof $==="string"?`'${$}'`:$).join(A)}o.joinValues=f,o.jsonStringifyReplacer=(S,A)=>{if(typeof A==="bigint")return A.toString();return A}})(Ao||(Ao={}));var LA;(function(o){o.mergeShapes=(T,n)=>{return{...T,...n}}})(LA||(LA={}));var h=Ao.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),vT=(o)=>{switch(typeof o){case"undefined":return h.undefined;case"string":return h.string;case"number":return isNaN(o)?h.nan:h.number;case"boolean":return h.boolean;case"function":return h.function;case"bigint":return h.bigint;case"symbol":return h.symbol;case"object":if(Array.isArray(o))return h.array;if(o===null)return h.null;if(o.then&&typeof o.then==="function"&&o.catch&&typeof o.catch==="function")return h.promise;if(typeof Map!=="undefined"&&o instanceof Map)return h.map;if(typeof Set!=="undefined"&&o instanceof Set)return h.set;if(typeof Date!=="undefined"&&o instanceof Date)return h.date;return h.object;default:return h.unknown}},Y=Ao.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"]),gM=(o)=>{return JSON.stringify(o,null,2).replace(/"([^"]+)":/g,"$1:")};class JT extends Error{get errors(){return this.issues}constructor(o){super();this.issues=[],this.addIssue=(n)=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};let T=new.target.prototype;if(Object.setPrototypeOf)Object.setPrototypeOf(this,T);else this.__proto__=T;this.name="ZodError",this.issues=o}format(o){let T=o||function(S){return S.message},n={_errors:[]},f=(S)=>{for(let A of S.issues)if(A.code==="invalid_union")A.unionErrors.map(f);else if(A.code==="invalid_return_type")f(A.returnTypeError);else if(A.code==="invalid_arguments")f(A.argumentsError);else if(A.path.length===0)n._errors.push(T(A));else{let $=n,F=0;while(F<A.path.length){let J=A.path[F];if(F!==A.path.length-1)$[J]=$[J]||{_errors:[]};else $[J]=$[J]||{_errors:[]},$[J]._errors.push(T(A));$=$[J],F++}}};return f(this),n}static assert(o){if(!(o instanceof JT))throw new Error(`Not a ZodError: ${o}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,Ao.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(o=(T)=>T.message){let T={},n=[];for(let f of this.issues)if(f.path.length>0)T[f.path[0]]=T[f.path[0]]||[],T[f.path[0]].push(o(f));else n.push(o(f));return{formErrors:n,fieldErrors:T}}get formErrors(){return this.flatten()}}JT.create=(o)=>{return new JT(o)};var In=(o,T)=>{let n;switch(o.code){case Y.invalid_type:if(o.received===h.undefined)n="Required";else n=`Expected ${o.expected}, received ${o.received}`;break;case Y.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(o.expected,Ao.jsonStringifyReplacer)}`;break;case Y.unrecognized_keys:n=`Unrecognized key(s) in object: ${Ao.joinValues(o.keys,", ")}`;break;case Y.invalid_union:n="Invalid input";break;case Y.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${Ao.joinValues(o.options)}`;break;case Y.invalid_enum_value:n=`Invalid enum value. Expected ${Ao.joinValues(o.options)}, received '${o.received}'`;break;case Y.invalid_arguments:n="Invalid function arguments";break;case Y.invalid_return_type:n="Invalid function return type";break;case Y.invalid_date:n="Invalid date";break;case Y.invalid_string:if(typeof o.validation==="object")if("includes"in o.validation){if(n=`Invalid input: must include "${o.validation.includes}"`,typeof o.validation.position==="number")n=`${n} at one or more positions greater than or equal to ${o.validation.position}`}else if("startsWith"in o.validation)n=`Invalid input: must start with "${o.validation.startsWith}"`;else if("endsWith"in o.validation)n=`Invalid input: must end with "${o.validation.endsWith}"`;else Ao.assertNever(o.validation);else if(o.validation!=="regex")n=`Invalid ${o.validation}`;else n="Invalid";break;case Y.too_small:if(o.type==="array")n=`Array must contain ${o.exact?"exactly":o.inclusive?"at least":"more than"} ${o.minimum} element(s)`;else if(o.type==="string")n=`String must contain ${o.exact?"exactly":o.inclusive?"at least":"over"} ${o.minimum} character(s)`;else if(o.type==="number")n=`Number must be ${o.exact?"exactly equal to ":o.inclusive?"greater than or equal to ":"greater than "}${o.minimum}`;else if(o.type==="date")n=`Date must be ${o.exact?"exactly equal to ":o.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(o.minimum))}`;else n="Invalid input";break;case Y.too_big:if(o.type==="array")n=`Array must contain ${o.exact?"exactly":o.inclusive?"at most":"less than"} ${o.maximum} element(s)`;else if(o.type==="string")n=`String must contain ${o.exact?"exactly":o.inclusive?"at most":"under"} ${o.maximum} character(s)`;else if(o.type==="number")n=`Number must be ${o.exact?"exactly":o.inclusive?"less than or equal to":"less than"} ${o.maximum}`;else if(o.type==="bigint")n=`BigInt must be ${o.exact?"exactly":o.inclusive?"less than or equal to":"less than"} ${o.maximum}`;else if(o.type==="date")n=`Date must be ${o.exact?"exactly":o.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(o.maximum))}`;else n="Invalid input";break;case Y.custom:n="Invalid input";break;case Y.invalid_intersection_types:n="Intersection results could not be merged";break;case Y.not_multiple_of:n=`Number must be a multiple of ${o.multipleOf}`;break;case Y.not_finite:n="Number must be finite";break;default:n=T.defaultError,Ao.assertNever(o)}return{message:n}},aF=In;function dM(o){aF=o}function FS(){return aF}var JS=(o)=>{let{data:T,path:n,errorMaps:f,issueData:S}=o,A=[...n,...S.path||[]],$={...S,path:A};if(S.message!==void 0)return{...S,path:A,message:S.message};let F="",J=f.filter((t)=>!!t).slice().reverse();for(let t of J)F=t($,{data:T,defaultError:F}).message;return{...S,path:A,message:F}},lM=[];function L(o,T){let n=FS(),f=JS({issueData:T,data:o.data,path:o.path,errorMaps:[o.common.contextualErrorMap,o.schemaErrorMap,n,n===In?void 0:In].filter((S)=>!!S)});o.common.issues.push(f)}class uo{constructor(){this.value="valid"}dirty(){if(this.value==="valid")this.value="dirty"}abort(){if(this.value!=="aborted")this.value="aborted"}static mergeArray(o,T){let n=[];for(let f of T){if(f.status==="aborted")return d;if(f.status==="dirty")o.dirty();n.push(f.value)}return{status:o.value,value:n}}static async mergeObjectAsync(o,T){let n=[];for(let f of T){let S=await f.key,A=await f.value;n.push({key:S,value:A})}return uo.mergeObjectSync(o,n)}static mergeObjectSync(o,T){let n={};for(let f of T){let{key:S,value:A}=f;if(S.status==="aborted")return d;if(A.status==="aborted")return d;if(S.status==="dirty")o.dirty();if(A.status==="dirty")o.dirty();if(S.value!=="__proto__"&&(typeof A.value!=="undefined"||f.alwaysSet))n[S.value]=A.value}return{status:o.value,value:n}}}var d=Object.freeze({status:"aborted"}),Ln=(o)=>({status:"dirty",value:o}),ao=(o)=>({status:"valid",value:o}),CA=(o)=>o.status==="aborted",IA=(o)=>o.status==="dirty",Jn=(o)=>o.status==="valid",Of=(o)=>typeof Promise!=="undefined"&&o instanceof Promise;function tS(o,T,n,f){if(n==="a"&&!f)throw new TypeError("Private accessor was defined without a getter");if(typeof T==="function"?o!==T||!f:!T.has(o))throw new TypeError("Cannot read private member from an object whose class did not declare it");return n==="m"?f:n==="a"?f.call(o):f?f.value:T.get(o)}function oJ(o,T,n,f,S){if(f==="m")throw new TypeError("Private method is not writable");if(f==="a"&&!S)throw new TypeError("Private accessor was defined without a setter");if(typeof T==="function"?o!==T||!S:!T.has(o))throw new TypeError("Cannot write private member to an object whose class did not declare it");return f==="a"?S.call(o,n):S?S.value=n:T.set(o,n),n}var x;(function(o){o.errToObj=(T)=>typeof T==="string"?{message:T}:T||{},o.toString=(T)=>typeof T==="string"?T:T===null||T===void 0?void 0:T.message})(x||(x={}));var kf,Wf;class GT{constructor(o,T,n,f){this._cachedPath=[],this.parent=o,this.data=T,this._path=n,this._key=f}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 uF=(o,T)=>{if(Jn(T))return{success:!0,data:T.value};else{if(!o.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let n=new JT(o.common.issues);return this._error=n,this._error}}}};function u(o){if(!o)return{};let{errorMap:T,invalid_type_error:n,required_error:f,description:S}=o;if(T&&(n||f))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);if(T)return{errorMap:T,description:S};return{errorMap:($,F)=>{var J,t;let{message:R}=o;if($.code==="invalid_enum_value")return{message:R!==null&&R!==void 0?R:F.defaultError};if(typeof F.data==="undefined")return{message:(J=R!==null&&R!==void 0?R:f)!==null&&J!==void 0?J:F.defaultError};if($.code!=="invalid_type")return{message:F.defaultError};return{message:(t=R!==null&&R!==void 0?R:n)!==null&&t!==void 0?t:F.defaultError}},description:S}}class e{get description(){return this._def.description}_getType(o){return vT(o.data)}_getOrReturnCtx(o,T){return T||{common:o.parent.common,data:o.data,parsedType:vT(o.data),schemaErrorMap:this._def.errorMap,path:o.path,parent:o.parent}}_processInputParams(o){return{status:new uo,ctx:{common:o.parent.common,data:o.data,parsedType:vT(o.data),schemaErrorMap:this._def.errorMap,path:o.path,parent:o.parent}}}_parseSync(o){let T=this._parse(o);if(Of(T))throw new Error("Synchronous parse encountered promise.");return T}_parseAsync(o){let T=this._parse(o);return Promise.resolve(T)}parse(o,T){let n=this.safeParse(o,T);if(n.success)return n.data;throw n.error}safeParse(o,T){var n;let f={common:{issues:[],async:(n=T===null||T===void 0?void 0:T.async)!==null&&n!==void 0?n:!1,contextualErrorMap:T===null||T===void 0?void 0:T.errorMap},path:(T===null||T===void 0?void 0:T.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:o,parsedType:vT(o)},S=this._parseSync({data:o,path:f.path,parent:f});return uF(f,S)}"~validate"(o){var T,n;let f={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:o,parsedType:vT(o)};if(!this["~standard"].async)try{let S=this._parseSync({data:o,path:[],parent:f});return Jn(S)?{value:S.value}:{issues:f.common.issues}}catch(S){if((n=(T=S===null||S===void 0?void 0:S.message)===null||T===void 0?void 0:T.toLowerCase())===null||n===void 0?void 0:n.includes("encountered"))this["~standard"].async=!0;f.common={issues:[],async:!0}}return this._parseAsync({data:o,path:[],parent:f}).then((S)=>Jn(S)?{value:S.value}:{issues:f.common.issues})}async parseAsync(o,T){let n=await this.safeParseAsync(o,T);if(n.success)return n.data;throw n.error}async safeParseAsync(o,T){let n={common:{issues:[],contextualErrorMap:T===null||T===void 0?void 0:T.errorMap,async:!0},path:(T===null||T===void 0?void 0:T.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:o,parsedType:vT(o)},f=this._parse({data:o,path:n.path,parent:n}),S=await(Of(f)?f:Promise.resolve(f));return uF(n,S)}refine(o,T){let n=(f)=>{if(typeof T==="string"||typeof T==="undefined")return{message:T};else if(typeof T==="function")return T(f);else return T};return this._refinement((f,S)=>{let A=o(f),$=()=>S.addIssue({code:Y.custom,...n(f)});if(typeof Promise!=="undefined"&&A instanceof Promise)return A.then((F)=>{if(!F)return $(),!1;else return!0});if(!A)return $(),!1;else return!0})}refinement(o,T){return this._refinement((n,f)=>{if(!o(n))return f.addIssue(typeof T==="function"?T(n,f):T),!1;else return!0})}_refinement(o){return new WT({schema:this,typeName:g.ZodEffects,effect:{type:"refinement",refinement:o}})}superRefine(o){return this._refinement(o)}constructor(o){this.spa=this.safeParseAsync,this._def=o,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),this["~standard"]={version:1,vendor:"zod",validate:(T)=>this["~validate"](T)}}optional(){return ET.create(this,this._def)}nullable(){return rT.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return KT.create(this)}promise(){return yn.create(this,this._def)}or(o){return bn.create([this,o],this._def)}and(o){return xn.create(this,o,this._def)}transform(o){return new WT({...u(this._def),schema:this,typeName:g.ZodEffects,effect:{type:"transform",transform:o}})}default(o){let T=typeof o==="function"?o:()=>o;return new pn({...u(this._def),innerType:this,defaultValue:T,typeName:g.ZodDefault})}brand(){return new MS({typeName:g.ZodBranded,type:this,...u(this._def)})}catch(o){let T=typeof o==="function"?o:()=>o;return new cn({...u(this._def),innerType:this,catchValue:T,typeName:g.ZodCatch})}describe(o){return new this.constructor({...this._def,description:o})}pipe(o){return Ef.create(this,o)}readonly(){return Zn.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}var uM=/^c[^\s-]{8,}$/i,eM=/^[0-9a-z]+$/,sM=/^[0-9A-HJKMNP-TV-Z]{26}$/i,aM=/^[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,o1=/^[a-z0-9_-]{21}$/i,T1=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,n1=/^[-+]?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)?)??$/,f1=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,S1="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",mA,A1=/^(?:(?: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])$/,$1=/^(?:(?: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])\/(3[0-2]|[12]?[0-9])$/,F1=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,J1=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,t1=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,R1=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,TJ="((\\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])))",M1=new RegExp(`^${TJ}$`);function nJ(o){let T="([01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d";if(o.precision)T=`${T}\\.\\d{${o.precision}}`;else if(o.precision==null)T=`${T}(\\.\\d+)?`;return T}function y1(o){return new RegExp(`^${nJ(o)}$`)}function fJ(o){let T=`${TJ}T${nJ(o)}`,n=[];if(n.push(o.local?"Z?":"Z"),o.offset)n.push("([+-]\\d{2}:?\\d{2})");return T=`${T}(${n.join("|")})`,new RegExp(`^${T}$`)}function k1(o,T){if((T==="v4"||!T)&&A1.test(o))return!0;if((T==="v6"||!T)&&F1.test(o))return!0;return!1}function W1(o,T){if(!T1.test(o))return!1;try{let[n]=o.split("."),f=n.replace(/-/g,"+").replace(/_/g,"/").padEnd(n.length+(4-n.length%4)%4,"="),S=JSON.parse(atob(f));if(typeof S!=="object"||S===null)return!1;if(!S.typ||!S.alg)return!1;if(T&&S.alg!==T)return!1;return!0}catch(n){return!1}}function O1(o,T){if((T==="v4"||!T)&&$1.test(o))return!0;if((T==="v6"||!T)&&J1.test(o))return!0;return!1}class HT extends e{_parse(o){if(this._def.coerce)o.data=String(o.data);if(this._getType(o)!==h.string){let S=this._getOrReturnCtx(o);return L(S,{code:Y.invalid_type,expected:h.string,received:S.parsedType}),d}let n=new uo,f=void 0;for(let S of this._def.checks)if(S.kind==="min"){if(o.data.length<S.value)f=this._getOrReturnCtx(o,f),L(f,{code:Y.too_small,minimum:S.value,type:"string",inclusive:!0,exact:!1,message:S.message}),n.dirty()}else if(S.kind==="max"){if(o.data.length>S.value)f=this._getOrReturnCtx(o,f),L(f,{code:Y.too_big,maximum:S.value,type:"string",inclusive:!0,exact:!1,message:S.message}),n.dirty()}else if(S.kind==="length"){let A=o.data.length>S.value,$=o.data.length<S.value;if(A||$){if(f=this._getOrReturnCtx(o,f),A)L(f,{code:Y.too_big,maximum:S.value,type:"string",inclusive:!0,exact:!0,message:S.message});else if($)L(f,{code:Y.too_small,minimum:S.value,type:"string",inclusive:!0,exact:!0,message:S.message});n.dirty()}}else if(S.kind==="email"){if(!f1.test(o.data))f=this._getOrReturnCtx(o,f),L(f,{validation:"email",code:Y.invalid_string,message:S.message}),n.dirty()}else if(S.kind==="emoji"){if(!mA)mA=new RegExp(S1,"u");if(!mA.test(o.data))f=this._getOrReturnCtx(o,f),L(f,{validation:"emoji",code:Y.invalid_string,message:S.message}),n.dirty()}else if(S.kind==="uuid"){if(!aM.test(o.data))f=this._getOrReturnCtx(o,f),L(f,{validation:"uuid",code:Y.invalid_string,message:S.message}),n.dirty()}else if(S.kind==="nanoid"){if(!o1.test(o.data))f=this._getOrReturnCtx(o,f),L(f,{validation:"nanoid",code:Y.invalid_string,message:S.message}),n.dirty()}else if(S.kind==="cuid"){if(!uM.test(o.data))f=this._getOrReturnCtx(o,f),L(f,{validation:"cuid",code:Y.invalid_string,message:S.message}),n.dirty()}else if(S.kind==="cuid2"){if(!eM.test(o.data))f=this._getOrReturnCtx(o,f),L(f,{validation:"cuid2",code:Y.invalid_string,message:S.message}),n.dirty()}else if(S.kind==="ulid"){if(!sM.test(o.data))f=this._getOrReturnCtx(o,f),L(f,{validation:"ulid",code:Y.invalid_string,message:S.message}),n.dirty()}else if(S.kind==="url")try{new URL(o.data)}catch(A){f=this._getOrReturnCtx(o,f),L(f,{validation:"url",code:Y.invalid_string,message:S.message}),n.dirty()}else if(S.kind==="regex"){if(S.regex.lastIndex=0,!S.regex.test(o.data))f=this._getOrReturnCtx(o,f),L(f,{validation:"regex",code:Y.invalid_string,message:S.message}),n.dirty()}else if(S.kind==="trim")o.data=o.data.trim();else if(S.kind==="includes"){if(!o.data.includes(S.value,S.position))f=this._getOrReturnCtx(o,f),L(f,{code:Y.invalid_string,validation:{includes:S.value,position:S.position},message:S.message}),n.dirty()}else if(S.kind==="toLowerCase")o.data=o.data.toLowerCase();else if(S.kind==="toUpperCase")o.data=o.data.toUpperCase();else if(S.kind==="startsWith"){if(!o.data.startsWith(S.value))f=this._getOrReturnCtx(o,f),L(f,{code:Y.invalid_string,validation:{startsWith:S.value},message:S.message}),n.dirty()}else if(S.kind==="endsWith"){if(!o.data.endsWith(S.value))f=this._getOrReturnCtx(o,f),L(f,{code:Y.invalid_string,validation:{endsWith:S.value},message:S.message}),n.dirty()}else if(S.kind==="datetime"){if(!fJ(S).test(o.data))f=this._getOrReturnCtx(o,f),L(f,{code:Y.invalid_string,validation:"datetime",message:S.message}),n.dirty()}else if(S.kind==="date"){if(!M1.test(o.data))f=this._getOrReturnCtx(o,f),L(f,{code:Y.invalid_string,validation:"date",message:S.message}),n.dirty()}else if(S.kind==="time"){if(!y1(S).test(o.data))f=this._getOrReturnCtx(o,f),L(f,{code:Y.invalid_string,validation:"time",message:S.message}),n.dirty()}else if(S.kind==="duration"){if(!n1.test(o.data))f=this._getOrReturnCtx(o,f),L(f,{validation:"duration",code:Y.invalid_string,message:S.message}),n.dirty()}else if(S.kind==="ip"){if(!k1(o.data,S.version))f=this._getOrReturnCtx(o,f),L(f,{validation:"ip",code:Y.invalid_string,message:S.message}),n.dirty()}else if(S.kind==="jwt"){if(!W1(o.data,S.alg))f=this._getOrReturnCtx(o,f),L(f,{validation:"jwt",code:Y.invalid_string,message:S.message}),n.dirty()}else if(S.kind==="cidr"){if(!O1(o.data,S.version))f=this._getOrReturnCtx(o,f),L(f,{validation:"cidr",code:Y.invalid_string,message:S.message}),n.dirty()}else if(S.kind==="base64"){if(!t1.test(o.data))f=this._getOrReturnCtx(o,f),L(f,{validation:"base64",code:Y.invalid_string,message:S.message}),n.dirty()}else if(S.kind==="base64url"){if(!R1.test(o.data))f=this._getOrReturnCtx(o,f),L(f,{validation:"base64url",code:Y.invalid_string,message:S.message}),n.dirty()}else Ao.assertNever(S);return{status:n.value,value:o.data}}_regex(o,T,n){return this.refinement((f)=>o.test(f),{validation:T,code:Y.invalid_string,...x.errToObj(n)})}_addCheck(o){return new HT({...this._def,checks:[...this._def.checks,o]})}email(o){return this._addCheck({kind:"email",...x.errToObj(o)})}url(o){return this._addCheck({kind:"url",...x.errToObj(o)})}emoji(o){return this._addCheck({kind:"emoji",...x.errToObj(o)})}uuid(o){return this._addCheck({kind:"uuid",...x.errToObj(o)})}nanoid(o){return this._addCheck({kind:"nanoid",...x.errToObj(o)})}cuid(o){return this._addCheck({kind:"cuid",...x.errToObj(o)})}cuid2(o){return this._addCheck({kind:"cuid2",...x.errToObj(o)})}ulid(o){return this._addCheck({kind:"ulid",...x.errToObj(o)})}base64(o){return this._addCheck({kind:"base64",...x.errToObj(o)})}base64url(o){return this._addCheck({kind:"base64url",...x.errToObj(o)})}jwt(o){return this._addCheck({kind:"jwt",...x.errToObj(o)})}ip(o){return this._addCheck({kind:"ip",...x.errToObj(o)})}cidr(o){return this._addCheck({kind:"cidr",...x.errToObj(o)})}datetime(o){var T,n;if(typeof o==="string")return this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:o});return this._addCheck({kind:"datetime",precision:typeof(o===null||o===void 0?void 0:o.precision)==="undefined"?null:o===null||o===void 0?void 0:o.precision,offset:(T=o===null||o===void 0?void 0:o.offset)!==null&&T!==void 0?T:!1,local:(n=o===null||o===void 0?void 0:o.local)!==null&&n!==void 0?n:!1,...x.errToObj(o===null||o===void 0?void 0:o.message)})}date(o){return this._addCheck({kind:"date",message:o})}time(o){if(typeof o==="string")return this._addCheck({kind:"time",precision:null,message:o});return this._addCheck({kind:"time",precision:typeof(o===null||o===void 0?void 0:o.precision)==="undefined"?null:o===null||o===void 0?void 0:o.precision,...x.errToObj(o===null||o===void 0?void 0:o.message)})}duration(o){return this._addCheck({kind:"duration",...x.errToObj(o)})}regex(o,T){return this._addCheck({kind:"regex",regex:o,...x.errToObj(T)})}includes(o,T){return this._addCheck({kind:"includes",value:o,position:T===null||T===void 0?void 0:T.position,...x.errToObj(T===null||T===void 0?void 0:T.message)})}startsWith(o,T){return this._addCheck({kind:"startsWith",value:o,...x.errToObj(T)})}endsWith(o,T){return this._addCheck({kind:"endsWith",value:o,...x.errToObj(T)})}min(o,T){return this._addCheck({kind:"min",value:o,...x.errToObj(T)})}max(o,T){return this._addCheck({kind:"max",value:o,...x.errToObj(T)})}length(o,T){return this._addCheck({kind:"length",value:o,...x.errToObj(T)})}nonempty(o){return this.min(1,x.errToObj(o))}trim(){return new HT({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new HT({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new HT({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find((o)=>o.kind==="datetime")}get isDate(){return!!this._def.checks.find((o)=>o.kind==="date")}get isTime(){return!!this._def.checks.find((o)=>o.kind==="time")}get isDuration(){return!!this._def.checks.find((o)=>o.kind==="duration")}get isEmail(){return!!this._def.checks.find((o)=>o.kind==="email")}get isURL(){return!!this._def.checks.find((o)=>o.kind==="url")}get isEmoji(){return!!this._def.checks.find((o)=>o.kind==="emoji")}get isUUID(){return!!this._def.checks.find((o)=>o.kind==="uuid")}get isNANOID(){return!!this._def.checks.find((o)=>o.kind==="nanoid")}get isCUID(){return!!this._def.checks.find((o)=>o.kind==="cuid")}get isCUID2(){return!!this._def.checks.find((o)=>o.kind==="cuid2")}get isULID(){return!!this._def.checks.find((o)=>o.kind==="ulid")}get isIP(){return!!this._def.checks.find((o)=>o.kind==="ip")}get isCIDR(){return!!this._def.checks.find((o)=>o.kind==="cidr")}get isBase64(){return!!this._def.checks.find((o)=>o.kind==="base64")}get isBase64url(){return!!this._def.checks.find((o)=>o.kind==="base64url")}get minLength(){let o=null;for(let T of this._def.checks)if(T.kind==="min"){if(o===null||T.value>o)o=T.value}return o}get maxLength(){let o=null;for(let T of this._def.checks)if(T.kind==="max"){if(o===null||T.value<o)o=T.value}return o}}HT.create=(o)=>{var T;return new HT({checks:[],typeName:g.ZodString,coerce:(T=o===null||o===void 0?void 0:o.coerce)!==null&&T!==void 0?T:!1,...u(o)})};function w1(o,T){let n=(o.toString().split(".")[1]||"").length,f=(T.toString().split(".")[1]||"").length,S=n>f?n:f,A=parseInt(o.toFixed(S).replace(".","")),$=parseInt(T.toFixed(S).replace(".",""));return A%$/Math.pow(10,S)}class dT extends e{constructor(){super(...arguments);this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(o){if(this._def.coerce)o.data=Number(o.data);if(this._getType(o)!==h.number){let S=this._getOrReturnCtx(o);return L(S,{code:Y.invalid_type,expected:h.number,received:S.parsedType}),d}let n=void 0,f=new uo;for(let S of this._def.checks)if(S.kind==="int"){if(!Ao.isInteger(o.data))n=this._getOrReturnCtx(o,n),L(n,{code:Y.invalid_type,expected:"integer",received:"float",message:S.message}),f.dirty()}else if(S.kind==="min"){if(S.inclusive?o.data<S.value:o.data<=S.value)n=this._getOrReturnCtx(o,n),L(n,{code:Y.too_small,minimum:S.value,type:"number",inclusive:S.inclusive,exact:!1,message:S.message}),f.dirty()}else if(S.kind==="max"){if(S.inclusive?o.data>S.value:o.data>=S.value)n=this._getOrReturnCtx(o,n),L(n,{code:Y.too_big,maximum:S.value,type:"number",inclusive:S.inclusive,exact:!1,message:S.message}),f.dirty()}else if(S.kind==="multipleOf"){if(w1(o.data,S.value)!==0)n=this._getOrReturnCtx(o,n),L(n,{code:Y.not_multiple_of,multipleOf:S.value,message:S.message}),f.dirty()}else if(S.kind==="finite"){if(!Number.isFinite(o.data))n=this._getOrReturnCtx(o,n),L(n,{code:Y.not_finite,message:S.message}),f.dirty()}else Ao.assertNever(S);return{status:f.value,value:o.data}}gte(o,T){return this.setLimit("min",o,!0,x.toString(T))}gt(o,T){return this.setLimit("min",o,!1,x.toString(T))}lte(o,T){return this.setLimit("max",o,!0,x.toString(T))}lt(o,T){return this.setLimit("max",o,!1,x.toString(T))}setLimit(o,T,n,f){return new dT({...this._def,checks:[...this._def.checks,{kind:o,value:T,inclusive:n,message:x.toString(f)}]})}_addCheck(o){return new dT({...this._def,checks:[...this._def.checks,o]})}int(o){return this._addCheck({kind:"int",message:x.toString(o)})}positive(o){return this._addCheck({kind:"min",value:0,inclusive:!1,message:x.toString(o)})}negative(o){return this._addCheck({kind:"max",value:0,inclusive:!1,message:x.toString(o)})}nonpositive(o){return this._addCheck({kind:"max",value:0,inclusive:!0,message:x.toString(o)})}nonnegative(o){return this._addCheck({kind:"min",value:0,inclusive:!0,message:x.toString(o)})}multipleOf(o,T){return this._addCheck({kind:"multipleOf",value:o,message:x.toString(T)})}finite(o){return this._addCheck({kind:"finite",message:x.toString(o)})}safe(o){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:x.toString(o)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:x.toString(o)})}get minValue(){let o=null;for(let T of this._def.checks)if(T.kind==="min"){if(o===null||T.value>o)o=T.value}return o}get maxValue(){let o=null;for(let T of this._def.checks)if(T.kind==="max"){if(o===null||T.value<o)o=T.value}return o}get isInt(){return!!this._def.checks.find((o)=>o.kind==="int"||o.kind==="multipleOf"&&Ao.isInteger(o.value))}get isFinite(){let o=null,T=null;for(let n of this._def.checks)if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;else if(n.kind==="min"){if(T===null||n.value>T)T=n.value}else if(n.kind==="max"){if(o===null||n.value<o)o=n.value}return Number.isFinite(T)&&Number.isFinite(o)}}dT.create=(o)=>{return new dT({checks:[],typeName:g.ZodNumber,coerce:(o===null||o===void 0?void 0:o.coerce)||!1,...u(o)})};class lT extends e{constructor(){super(...arguments);this.min=this.gte,this.max=this.lte}_parse(o){if(this._def.coerce)try{o.data=BigInt(o.data)}catch(S){return this._getInvalidInput(o)}if(this._getType(o)!==h.bigint)return this._getInvalidInput(o);let n=void 0,f=new uo;for(let S of this._def.checks)if(S.kind==="min"){if(S.inclusive?o.data<S.value:o.data<=S.value)n=this._getOrReturnCtx(o,n),L(n,{code:Y.too_small,type:"bigint",minimum:S.value,inclusive:S.inclusive,message:S.message}),f.dirty()}else if(S.kind==="max"){if(S.inclusive?o.data>S.value:o.data>=S.value)n=this._getOrReturnCtx(o,n),L(n,{code:Y.too_big,type:"bigint",maximum:S.value,inclusive:S.inclusive,message:S.message}),f.dirty()}else if(S.kind==="multipleOf"){if(o.data%S.value!==BigInt(0))n=this._getOrReturnCtx(o,n),L(n,{code:Y.not_multiple_of,multipleOf:S.value,message:S.message}),f.dirty()}else Ao.assertNever(S);return{status:f.value,value:o.data}}_getInvalidInput(o){let T=this._getOrReturnCtx(o);return L(T,{code:Y.invalid_type,expected:h.bigint,received:T.parsedType}),d}gte(o,T){return this.setLimit("min",o,!0,x.toString(T))}gt(o,T){return this.setLimit("min",o,!1,x.toString(T))}lte(o,T){return this.setLimit("max",o,!0,x.toString(T))}lt(o,T){return this.setLimit("max",o,!1,x.toString(T))}setLimit(o,T,n,f){return new lT({...this._def,checks:[...this._def.checks,{kind:o,value:T,inclusive:n,message:x.toString(f)}]})}_addCheck(o){return new lT({...this._def,checks:[...this._def.checks,o]})}positive(o){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:x.toString(o)})}negative(o){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:x.toString(o)})}nonpositive(o){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:x.toString(o)})}nonnegative(o){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:x.toString(o)})}multipleOf(o,T){return this._addCheck({kind:"multipleOf",value:o,message:x.toString(T)})}get minValue(){let o=null;for(let T of this._def.checks)if(T.kind==="min"){if(o===null||T.value>o)o=T.value}return o}get maxValue(){let o=null;for(let T of this._def.checks)if(T.kind==="max"){if(o===null||T.value<o)o=T.value}return o}}lT.create=(o)=>{var T;return new lT({checks:[],typeName:g.ZodBigInt,coerce:(T=o===null||o===void 0?void 0:o.coerce)!==null&&T!==void 0?T:!1,...u(o)})};class jn extends e{_parse(o){if(this._def.coerce)o.data=Boolean(o.data);if(this._getType(o)!==h.boolean){let n=this._getOrReturnCtx(o);return L(n,{code:Y.invalid_type,expected:h.boolean,received:n.parsedType}),d}return ao(o.data)}}jn.create=(o)=>{return new jn({typeName:g.ZodBoolean,coerce:(o===null||o===void 0?void 0:o.coerce)||!1,...u(o)})};class tn extends e{_parse(o){if(this._def.coerce)o.data=new Date(o.data);if(this._getType(o)!==h.date){let S=this._getOrReturnCtx(o);return L(S,{code:Y.invalid_type,expected:h.date,received:S.parsedType}),d}if(isNaN(o.data.getTime())){let S=this._getOrReturnCtx(o);return L(S,{code:Y.invalid_date}),d}let n=new uo,f=void 0;for(let S of this._def.checks)if(S.kind==="min"){if(o.data.getTime()<S.value)f=this._getOrReturnCtx(o,f),L(f,{code:Y.too_small,message:S.message,inclusive:!0,exact:!1,minimum:S.value,type:"date"}),n.dirty()}else if(S.kind==="max"){if(o.data.getTime()>S.value)f=this._getOrReturnCtx(o,f),L(f,{code:Y.too_big,message:S.message,inclusive:!0,exact:!1,maximum:S.value,type:"date"}),n.dirty()}else Ao.assertNever(S);return{status:n.value,value:new Date(o.data.getTime())}}_addCheck(o){return new tn({...this._def,checks:[...this._def.checks,o]})}min(o,T){return this._addCheck({kind:"min",value:o.getTime(),message:x.toString(T)})}max(o,T){return this._addCheck({kind:"max",value:o.getTime(),message:x.toString(T)})}get minDate(){let o=null;for(let T of this._def.checks)if(T.kind==="min"){if(o===null||T.value>o)o=T.value}return o!=null?new Date(o):null}get maxDate(){let o=null;for(let T of this._def.checks)if(T.kind==="max"){if(o===null||T.value<o)o=T.value}return o!=null?new Date(o):null}}tn.create=(o)=>{return new tn({checks:[],coerce:(o===null||o===void 0?void 0:o.coerce)||!1,typeName:g.ZodDate,...u(o)})};class wf extends e{_parse(o){if(this._getType(o)!==h.symbol){let n=this._getOrReturnCtx(o);return L(n,{code:Y.invalid_type,expected:h.symbol,received:n.parsedType}),d}return ao(o.data)}}wf.create=(o)=>{return new wf({typeName:g.ZodSymbol,...u(o)})};class hn extends e{_parse(o){if(this._getType(o)!==h.undefined){let n=this._getOrReturnCtx(o);return L(n,{code:Y.invalid_type,expected:h.undefined,received:n.parsedType}),d}return ao(o.data)}}hn.create=(o)=>{return new hn({typeName:g.ZodUndefined,...u(o)})};class Nn extends e{_parse(o){if(this._getType(o)!==h.null){let n=this._getOrReturnCtx(o);return L(n,{code:Y.invalid_type,expected:h.null,received:n.parsedType}),d}return ao(o.data)}}Nn.create=(o)=>{return new Nn({typeName:g.ZodNull,...u(o)})};class Rn extends e{constructor(){super(...arguments);this._any=!0}_parse(o){return ao(o.data)}}Rn.create=(o)=>{return new Rn({typeName:g.ZodAny,...u(o)})};class gT extends e{constructor(){super(...arguments);this._unknown=!0}_parse(o){return ao(o.data)}}gT.create=(o)=>{return new gT({typeName:g.ZodUnknown,...u(o)})};class BT extends e{_parse(o){let T=this._getOrReturnCtx(o);return L(T,{code:Y.invalid_type,expected:h.never,received:T.parsedType}),d}}BT.create=(o)=>{return new BT({typeName:g.ZodNever,...u(o)})};class _f extends e{_parse(o){if(this._getType(o)!==h.undefined){let n=this._getOrReturnCtx(o);return L(n,{code:Y.invalid_type,expected:h.void,received:n.parsedType}),d}return ao(o.data)}}_f.create=(o)=>{return new _f({typeName:g.ZodVoid,...u(o)})};class KT extends e{_parse(o){let{ctx:T,status:n}=this._processInputParams(o),f=this._def;if(T.parsedType!==h.array)return L(T,{code:Y.invalid_type,expected:h.array,received:T.parsedType}),d;if(f.exactLength!==null){let A=T.data.length>f.exactLength.value,$=T.data.length<f.exactLength.value;if(A||$)L(T,{code:A?Y.too_big:Y.too_small,minimum:$?f.exactLength.value:void 0,maximum:A?f.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:f.exactLength.message}),n.dirty()}if(f.minLength!==null){if(T.data.length<f.minLength.value)L(T,{code:Y.too_small,minimum:f.minLength.value,type:"array",inclusive:!0,exact:!1,message:f.minLength.message}),n.dirty()}if(f.maxLength!==null){if(T.data.length>f.maxLength.value)L(T,{code:Y.too_big,maximum:f.maxLength.value,type:"array",inclusive:!0,exact:!1,message:f.maxLength.message}),n.dirty()}if(T.common.async)return Promise.all([...T.data].map((A,$)=>{return f.type._parseAsync(new GT(T,A,T.path,$))})).then((A)=>{return uo.mergeArray(n,A)});let S=[...T.data].map((A,$)=>{return f.type._parseSync(new GT(T,A,T.path,$))});return uo.mergeArray(n,S)}get element(){return this._def.type}min(o,T){return new KT({...this._def,minLength:{value:o,message:x.toString(T)}})}max(o,T){return new KT({...this._def,maxLength:{value:o,message:x.toString(T)}})}length(o,T){return new KT({...this._def,exactLength:{value:o,message:x.toString(T)}})}nonempty(o){return this.min(1,o)}}KT.create=(o,T)=>{return new KT({type:o,minLength:null,maxLength:null,exactLength:null,typeName:g.ZodArray,...u(T)})};function mn(o){if(o instanceof zo){let T={};for(let n in o.shape){let f=o.shape[n];T[n]=ET.create(mn(f))}return new zo({...o._def,shape:()=>T})}else if(o instanceof KT)return new KT({...o._def,type:mn(o.element)});else if(o instanceof ET)return ET.create(mn(o.unwrap()));else if(o instanceof rT)return rT.create(mn(o.unwrap()));else if(o instanceof mT)return mT.create(o.items.map((T)=>mn(T)));else return o}class zo extends e{constructor(){super(...arguments);this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let o=this._def.shape(),T=Ao.objectKeys(o);return this._cached={shape:o,keys:T}}_parse(o){if(this._getType(o)!==h.object){let J=this._getOrReturnCtx(o);return L(J,{code:Y.invalid_type,expected:h.object,received:J.parsedType}),d}let{status:n,ctx:f}=this._processInputParams(o),{shape:S,keys:A}=this._getCached(),$=[];if(!(this._def.catchall instanceof BT&&this._def.unknownKeys==="strip")){for(let J in f.data)if(!A.includes(J))$.push(J)}let F=[];for(let J of A){let t=S[J],R=f.data[J];F.push({key:{status:"valid",value:J},value:t._parse(new GT(f,R,f.path,J)),alwaysSet:J in f.data})}if(this._def.catchall instanceof BT){let J=this._def.unknownKeys;if(J==="passthrough")for(let t of $)F.push({key:{status:"valid",value:t},value:{status:"valid",value:f.data[t]}});else if(J==="strict"){if($.length>0)L(f,{code:Y.unrecognized_keys,keys:$}),n.dirty()}else if(J==="strip");else throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let J=this._def.catchall;for(let t of $){let R=f.data[t];F.push({key:{status:"valid",value:t},value:J._parse(new GT(f,R,f.path,t)),alwaysSet:t in f.data})}}if(f.common.async)return Promise.resolve().then(async()=>{let J=[];for(let t of F){let R=await t.key,W=await t.value;J.push({key:R,value:W,alwaysSet:t.alwaysSet})}return J}).then((J)=>{return uo.mergeObjectSync(n,J)});else return uo.mergeObjectSync(n,F)}get shape(){return this._def.shape()}strict(o){return x.errToObj,new zo({...this._def,unknownKeys:"strict",...o!==void 0?{errorMap:(T,n)=>{var f,S,A,$;let F=(A=(S=(f=this._def).errorMap)===null||S===void 0?void 0:S.call(f,T,n).message)!==null&&A!==void 0?A:n.defaultError;if(T.code==="unrecognized_keys")return{message:($=x.errToObj(o).message)!==null&&$!==void 0?$:F};return{message:F}}}:{}})}strip(){return new zo({...this._def,unknownKeys:"strip"})}passthrough(){return new zo({...this._def,unknownKeys:"passthrough"})}extend(o){return new zo({...this._def,shape:()=>({...this._def.shape(),...o})})}merge(o){return new zo({unknownKeys:o._def.unknownKeys,catchall:o._def.catchall,shape:()=>({...this._def.shape(),...o._def.shape()}),typeName:g.ZodObject})}setKey(o,T){return this.augment({[o]:T})}catchall(o){return new zo({...this._def,catchall:o})}pick(o){let T={};return Ao.objectKeys(o).forEach((n)=>{if(o[n]&&this.shape[n])T[n]=this.shape[n]}),new zo({...this._def,shape:()=>T})}omit(o){let T={};return Ao.objectKeys(this.shape).forEach((n)=>{if(!o[n])T[n]=this.shape[n]}),new zo({...this._def,shape:()=>T})}deepPartial(){return mn(this)}partial(o){let T={};return Ao.objectKeys(this.shape).forEach((n)=>{let f=this.shape[n];if(o&&!o[n])T[n]=f;else T[n]=f.optional()}),new zo({...this._def,shape:()=>T})}required(o){let T={};return Ao.objectKeys(this.shape).forEach((n)=>{if(o&&!o[n])T[n]=this.shape[n];else{let S=this.shape[n];while(S instanceof ET)S=S._def.innerType;T[n]=S}}),new zo({...this._def,shape:()=>T})}keyof(){return SJ(Ao.objectKeys(this.shape))}}zo.create=(o,T)=>{return new zo({shape:()=>o,unknownKeys:"strip",catchall:BT.create(),typeName:g.ZodObject,...u(T)})};zo.strictCreate=(o,T)=>{return new zo({shape:()=>o,unknownKeys:"strict",catchall:BT.create(),typeName:g.ZodObject,...u(T)})};zo.lazycreate=(o,T)=>{return new zo({shape:o,unknownKeys:"strip",catchall:BT.create(),typeName:g.ZodObject,...u(T)})};class bn extends e{_parse(o){let{ctx:T}=this._processInputParams(o),n=this._def.options;function f(S){for(let $ of S)if($.result.status==="valid")return $.result;for(let $ of S)if($.result.status==="dirty")return T.common.issues.push(...$.ctx.common.issues),$.result;let A=S.map(($)=>new JT($.ctx.common.issues));return L(T,{code:Y.invalid_union,unionErrors:A}),d}if(T.common.async)return Promise.all(n.map(async(S)=>{let A={...T,common:{...T.common,issues:[]},parent:null};return{result:await S._parseAsync({data:T.data,path:T.path,parent:A}),ctx:A}})).then(f);else{let S=void 0,A=[];for(let F of n){let J={...T,common:{...T.common,issues:[]},parent:null},t=F._parseSync({data:T.data,path:T.path,parent:J});if(t.status==="valid")return t;else if(t.status==="dirty"&&!S)S={result:t,ctx:J};if(J.common.issues.length)A.push(J.common.issues)}if(S)return T.common.issues.push(...S.ctx.common.issues),S.result;let $=A.map((F)=>new JT(F));return L(T,{code:Y.invalid_union,unionErrors:$}),d}}get options(){return this._def.options}}bn.create=(o,T)=>{return new bn({options:o,typeName:g.ZodUnion,...u(T)})};var xT=(o)=>{if(o instanceof vn)return xT(o.schema);else if(o instanceof WT)return xT(o.innerType());else if(o instanceof rn)return[o.value];else if(o instanceof uT)return o.options;else if(o instanceof qn)return Ao.objectValues(o.enum);else if(o instanceof pn)return xT(o._def.innerType);else if(o instanceof hn)return[void 0];else if(o instanceof Nn)return[null];else if(o instanceof ET)return[void 0,...xT(o.unwrap())];else if(o instanceof rT)return[null,...xT(o.unwrap())];else if(o instanceof MS)return xT(o.unwrap());else if(o instanceof Zn)return xT(o.unwrap());else if(o instanceof cn)return xT(o._def.innerType);else return[]};class RS extends e{_parse(o){let{ctx:T}=this._processInputParams(o);if(T.parsedType!==h.object)return L(T,{code:Y.invalid_type,expected:h.object,received:T.parsedType}),d;let n=this.discriminator,f=T.data[n],S=this.optionsMap.get(f);if(!S)return L(T,{code:Y.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),d;if(T.common.async)return S._parseAsync({data:T.data,path:T.path,parent:T});else return S._parseSync({data:T.data,path:T.path,parent:T})}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(o,T,n){let f=new Map;for(let S of T){let A=xT(S.shape[o]);if(!A.length)throw new Error(`A discriminator value for key \`${o}\` could not be extracted from all schema options`);for(let $ of A){if(f.has($))throw new Error(`Discriminator property ${String(o)} has duplicate value ${String($)}`);f.set($,S)}}return new RS({typeName:g.ZodDiscriminatedUnion,discriminator:o,options:T,optionsMap:f,...u(n)})}}function jA(o,T){let n=vT(o),f=vT(T);if(o===T)return{valid:!0,data:o};else if(n===h.object&&f===h.object){let S=Ao.objectKeys(T),A=Ao.objectKeys(o).filter((F)=>S.indexOf(F)!==-1),$={...o,...T};for(let F of A){let J=jA(o[F],T[F]);if(!J.valid)return{valid:!1};$[F]=J.data}return{valid:!0,data:$}}else if(n===h.array&&f===h.array){if(o.length!==T.length)return{valid:!1};let S=[];for(let A=0;A<o.length;A++){let $=o[A],F=T[A],J=jA($,F);if(!J.valid)return{valid:!1};S.push(J.data)}return{valid:!0,data:S}}else if(n===h.date&&f===h.date&&+o===+T)return{valid:!0,data:o};else return{valid:!1}}class xn extends e{_parse(o){let{status:T,ctx:n}=this._processInputParams(o),f=(S,A)=>{if(CA(S)||CA(A))return d;let $=jA(S.value,A.value);if(!$.valid)return L(n,{code:Y.invalid_intersection_types}),d;if(IA(S)||IA(A))T.dirty();return{status:T.value,value:$.data}};if(n.common.async)return Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([S,A])=>f(S,A));else return f(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}}xn.create=(o,T,n)=>{return new xn({left:o,right:T,typeName:g.ZodIntersection,...u(n)})};class mT extends e{_parse(o){let{status:T,ctx:n}=this._processInputParams(o);if(n.parsedType!==h.array)return L(n,{code:Y.invalid_type,expected:h.array,received:n.parsedType}),d;if(n.data.length<this._def.items.length)return L(n,{code:Y.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),d;if(!this._def.rest&&n.data.length>this._def.items.length)L(n,{code:Y.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),T.dirty();let S=[...n.data].map((A,$)=>{let F=this._def.items[$]||this._def.rest;if(!F)return null;return F._parse(new GT(n,A,n.path,$))}).filter((A)=>!!A);if(n.common.async)return Promise.all(S).then((A)=>{return uo.mergeArray(T,A)});else return uo.mergeArray(T,S)}get items(){return this._def.items}rest(o){return new mT({...this._def,rest:o})}}mT.create=(o,T)=>{if(!Array.isArray(o))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new mT({items:o,typeName:g.ZodTuple,rest:null,...u(T)})};class Xf extends e{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(o){let{status:T,ctx:n}=this._processInputParams(o);if(n.parsedType!==h.object)return L(n,{code:Y.invalid_type,expected:h.object,received:n.parsedType}),d;let f=[],S=this._def.keyType,A=this._def.valueType;for(let $ in n.data)f.push({key:S._parse(new GT(n,$,n.path,$)),value:A._parse(new GT(n,n.data[$],n.path,$)),alwaysSet:$ in n.data});if(n.common.async)return uo.mergeObjectAsync(T,f);else return uo.mergeObjectSync(T,f)}get element(){return this._def.valueType}static create(o,T,n){if(T instanceof e)return new Xf({keyType:o,valueType:T,typeName:g.ZodRecord,...u(n)});return new Xf({keyType:HT.create(),valueType:o,typeName:g.ZodRecord,...u(T)})}}class Hf extends e{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(o){let{status:T,ctx:n}=this._processInputParams(o);if(n.parsedType!==h.map)return L(n,{code:Y.invalid_type,expected:h.map,received:n.parsedType}),d;let f=this._def.keyType,S=this._def.valueType,A=[...n.data.entries()].map(([$,F],J)=>{return{key:f._parse(new GT(n,$,n.path,[J,"key"])),value:S._parse(new GT(n,F,n.path,[J,"value"]))}});if(n.common.async){let $=new Map;return Promise.resolve().then(async()=>{for(let F of A){let J=await F.key,t=await F.value;if(J.status==="aborted"||t.status==="aborted")return d;if(J.status==="dirty"||t.status==="dirty")T.dirty();$.set(J.value,t.value)}return{status:T.value,value:$}})}else{let $=new Map;for(let F of A){let{key:J,value:t}=F;if(J.status==="aborted"||t.status==="aborted")return d;if(J.status==="dirty"||t.status==="dirty")T.dirty();$.set(J.value,t.value)}return{status:T.value,value:$}}}}Hf.create=(o,T,n)=>{return new Hf({valueType:T,keyType:o,typeName:g.ZodMap,...u(n)})};class Mn extends e{_parse(o){let{status:T,ctx:n}=this._processInputParams(o);if(n.parsedType!==h.set)return L(n,{code:Y.invalid_type,expected:h.set,received:n.parsedType}),d;let f=this._def;if(f.minSize!==null){if(n.data.size<f.minSize.value)L(n,{code:Y.too_small,minimum:f.minSize.value,type:"set",inclusive:!0,exact:!1,message:f.minSize.message}),T.dirty()}if(f.maxSize!==null){if(n.data.size>f.maxSize.value)L(n,{code:Y.too_big,maximum:f.maxSize.value,type:"set",inclusive:!0,exact:!1,message:f.maxSize.message}),T.dirty()}let S=this._def.valueType;function A(F){let J=new Set;for(let t of F){if(t.status==="aborted")return d;if(t.status==="dirty")T.dirty();J.add(t.value)}return{status:T.value,value:J}}let $=[...n.data.values()].map((F,J)=>S._parse(new GT(n,F,n.path,J)));if(n.common.async)return Promise.all($).then((F)=>A(F));else return A($)}min(o,T){return new Mn({...this._def,minSize:{value:o,message:x.toString(T)}})}max(o,T){return new Mn({...this._def,maxSize:{value:o,message:x.toString(T)}})}size(o,T){return this.min(o,T).max(o,T)}nonempty(o){return this.min(1,o)}}Mn.create=(o,T)=>{return new Mn({valueType:o,minSize:null,maxSize:null,typeName:g.ZodSet,...u(T)})};class Cn extends e{constructor(){super(...arguments);this.validate=this.implement}_parse(o){let{ctx:T}=this._processInputParams(o);if(T.parsedType!==h.function)return L(T,{code:Y.invalid_type,expected:h.function,received:T.parsedType}),d;function n($,F){return JS({data:$,path:T.path,errorMaps:[T.common.contextualErrorMap,T.schemaErrorMap,FS(),In].filter((J)=>!!J),issueData:{code:Y.invalid_arguments,argumentsError:F}})}function f($,F){return JS({data:$,path:T.path,errorMaps:[T.common.contextualErrorMap,T.schemaErrorMap,FS(),In].filter((J)=>!!J),issueData:{code:Y.invalid_return_type,returnTypeError:F}})}let S={errorMap:T.common.contextualErrorMap},A=T.data;if(this._def.returns instanceof yn){let $=this;return ao(async function(...F){let J=new JT([]),t=await $._def.args.parseAsync(F,S).catch((O)=>{throw J.addIssue(n(F,O)),J}),R=await Reflect.apply(A,this,t);return await $._def.returns._def.type.parseAsync(R,S).catch((O)=>{throw J.addIssue(f(R,O)),J})})}else{let $=this;return ao(function(...F){let J=$._def.args.safeParse(F,S);if(!J.success)throw new JT([n(F,J.error)]);let t=Reflect.apply(A,this,J.data),R=$._def.returns.safeParse(t,S);if(!R.success)throw new JT([f(t,R.error)]);return R.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...o){return new Cn({...this._def,args:mT.create(o).rest(gT.create())})}returns(o){return new Cn({...this._def,returns:o})}implement(o){return this.parse(o)}strictImplement(o){return this.parse(o)}static create(o,T,n){return new Cn({args:o?o:mT.create([]).rest(gT.create()),returns:T||gT.create(),typeName:g.ZodFunction,...u(n)})}}class vn extends e{get schema(){return this._def.getter()}_parse(o){let{ctx:T}=this._processInputParams(o);return this._def.getter()._parse({data:T.data,path:T.path,parent:T})}}vn.create=(o,T)=>{return new vn({getter:o,typeName:g.ZodLazy,...u(T)})};class rn extends e{_parse(o){if(o.data!==this._def.value){let T=this._getOrReturnCtx(o);return L(T,{received:T.data,code:Y.invalid_literal,expected:this._def.value}),d}return{status:"valid",value:o.data}}get value(){return this._def.value}}rn.create=(o,T)=>{return new rn({value:o,typeName:g.ZodLiteral,...u(T)})};function SJ(o,T){return new uT({values:o,typeName:g.ZodEnum,...u(T)})}class uT extends e{constructor(){super(...arguments);kf.set(this,void 0)}_parse(o){if(typeof o.data!=="string"){let T=this._getOrReturnCtx(o),n=this._def.values;return L(T,{expected:Ao.joinValues(n),received:T.parsedType,code:Y.invalid_type}),d}if(!tS(this,kf,"f"))oJ(this,kf,new Set(this._def.values),"f");if(!tS(this,kf,"f").has(o.data)){let T=this._getOrReturnCtx(o),n=this._def.values;return L(T,{received:T.data,code:Y.invalid_enum_value,options:n}),d}return ao(o.data)}get options(){return this._def.values}get enum(){let o={};for(let T of this._def.values)o[T]=T;return o}get Values(){let o={};for(let T of this._def.values)o[T]=T;return o}get Enum(){let o={};for(let T of this._def.values)o[T]=T;return o}extract(o,T=this._def){return uT.create(o,{...this._def,...T})}exclude(o,T=this._def){return uT.create(this.options.filter((n)=>!o.includes(n)),{...this._def,...T})}}kf=new WeakMap;uT.create=SJ;class qn extends e{constructor(){super(...arguments);Wf.set(this,void 0)}_parse(o){let T=Ao.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(o);if(n.parsedType!==h.string&&n.parsedType!==h.number){let f=Ao.objectValues(T);return L(n,{expected:Ao.joinValues(f),received:n.parsedType,code:Y.invalid_type}),d}if(!tS(this,Wf,"f"))oJ(this,Wf,new Set(Ao.getValidEnumValues(this._def.values)),"f");if(!tS(this,Wf,"f").has(o.data)){let f=Ao.objectValues(T);return L(n,{received:n.data,code:Y.invalid_enum_value,options:f}),d}return ao(o.data)}get enum(){return this._def.values}}Wf=new WeakMap;qn.create=(o,T)=>{return new qn({values:o,typeName:g.ZodNativeEnum,...u(T)})};class yn extends e{unwrap(){return this._def.type}_parse(o){let{ctx:T}=this._processInputParams(o);if(T.parsedType!==h.promise&&T.common.async===!1)return L(T,{code:Y.invalid_type,expected:h.promise,received:T.parsedType}),d;let n=T.parsedType===h.promise?T.data:Promise.resolve(T.data);return ao(n.then((f)=>{return this._def.type.parseAsync(f,{path:T.path,errorMap:T.common.contextualErrorMap})}))}}yn.create=(o,T)=>{return new yn({type:o,typeName:g.ZodPromise,...u(T)})};class WT extends e{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===g.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(o){let{status:T,ctx:n}=this._processInputParams(o),f=this._def.effect||null,S={addIssue:(A)=>{if(L(n,A),A.fatal)T.abort();else T.dirty()},get path(){return n.path}};if(S.addIssue=S.addIssue.bind(S),f.type==="preprocess"){let A=f.transform(n.data,S);if(n.common.async)return Promise.resolve(A).then(async($)=>{if(T.value==="aborted")return d;let F=await this._def.schema._parseAsync({data:$,path:n.path,parent:n});if(F.status==="aborted")return d;if(F.status==="dirty")return Ln(F.value);if(T.value==="dirty")return Ln(F.value);return F});else{if(T.value==="aborted")return d;let $=this._def.schema._parseSync({data:A,path:n.path,parent:n});if($.status==="aborted")return d;if($.status==="dirty")return Ln($.value);if(T.value==="dirty")return Ln($.value);return $}}if(f.type==="refinement"){let A=($)=>{let F=f.refinement($,S);if(n.common.async)return Promise.resolve(F);if(F instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return $};if(n.common.async===!1){let $=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if($.status==="aborted")return d;if($.status==="dirty")T.dirty();return A($.value),{status:T.value,value:$.value}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(($)=>{if($.status==="aborted")return d;if($.status==="dirty")T.dirty();return A($.value).then(()=>{return{status:T.value,value:$.value}})})}if(f.type==="transform")if(n.common.async===!1){let A=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!Jn(A))return A;let $=f.transform(A.value,S);if($ instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:T.value,value:$}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then((A)=>{if(!Jn(A))return A;return Promise.resolve(f.transform(A.value,S)).then(($)=>({status:T.value,value:$}))});Ao.assertNever(f)}}WT.create=(o,T,n)=>{return new WT({schema:o,typeName:g.ZodEffects,effect:T,...u(n)})};WT.createWithPreprocess=(o,T,n)=>{return new WT({schema:T,effect:{type:"preprocess",transform:o},typeName:g.ZodEffects,...u(n)})};class ET extends e{_parse(o){if(this._getType(o)===h.undefined)return ao(void 0);return this._def.innerType._parse(o)}unwrap(){return this._def.innerType}}ET.create=(o,T)=>{return new ET({innerType:o,typeName:g.ZodOptional,...u(T)})};class rT extends e{_parse(o){if(this._getType(o)===h.null)return ao(null);return this._def.innerType._parse(o)}unwrap(){return this._def.innerType}}rT.create=(o,T)=>{return new rT({innerType:o,typeName:g.ZodNullable,...u(T)})};class pn extends e{_parse(o){let{ctx:T}=this._processInputParams(o),n=T.data;if(T.parsedType===h.undefined)n=this._def.defaultValue();return this._def.innerType._parse({data:n,path:T.path,parent:T})}removeDefault(){return this._def.innerType}}pn.create=(o,T)=>{return new pn({innerType:o,typeName:g.ZodDefault,defaultValue:typeof T.default==="function"?T.default:()=>T.default,...u(T)})};class cn extends e{_parse(o){let{ctx:T}=this._processInputParams(o),n={...T,common:{...T.common,issues:[]}},f=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});if(Of(f))return f.then((S)=>{return{status:"valid",value:S.status==="valid"?S.value:this._def.catchValue({get error(){return new JT(n.common.issues)},input:n.data})}});else return{status:"valid",value:f.status==="valid"?f.value:this._def.catchValue({get error(){return new JT(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}}cn.create=(o,T)=>{return new cn({innerType:o,typeName:g.ZodCatch,catchValue:typeof T.catch==="function"?T.catch:()=>T.catch,...u(T)})};class Kf extends e{_parse(o){if(this._getType(o)!==h.nan){let n=this._getOrReturnCtx(o);return L(n,{code:Y.invalid_type,expected:h.nan,received:n.parsedType}),d}return{status:"valid",value:o.data}}}Kf.create=(o)=>{return new Kf({typeName:g.ZodNaN,...u(o)})};var _1=Symbol("zod_brand");class MS extends e{_parse(o){let{ctx:T}=this._processInputParams(o),n=T.data;return this._def.type._parse({data:n,path:T.path,parent:T})}unwrap(){return this._def.type}}class Ef extends e{_parse(o){let{status:T,ctx:n}=this._processInputParams(o);if(n.common.async)return(async()=>{let S=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});if(S.status==="aborted")return d;if(S.status==="dirty")return T.dirty(),Ln(S.value);else return this._def.out._parseAsync({data:S.value,path:n.path,parent:n})})();else{let f=this._def.in._parseSync({data:n.data,path:n.path,parent:n});if(f.status==="aborted")return d;if(f.status==="dirty")return T.dirty(),{status:"dirty",value:f.value};else return this._def.out._parseSync({data:f.value,path:n.path,parent:n})}}static create(o,T){return new Ef({in:o,out:T,typeName:g.ZodPipeline})}}class Zn extends e{_parse(o){let T=this._def.innerType._parse(o),n=(f)=>{if(Jn(f))f.value=Object.freeze(f.value);return f};return Of(T)?T.then((f)=>n(f)):n(T)}unwrap(){return this._def.innerType}}Zn.create=(o,T)=>{return new Zn({innerType:o,typeName:g.ZodReadonly,...u(T)})};function eF(o,T){let n=typeof o==="function"?o(T):typeof o==="string"?{message:o}:o;return typeof n==="string"?{message:n}:n}function AJ(o,T={},n){if(o)return Rn.create().superRefine((f,S)=>{var A,$;let F=o(f);if(F instanceof Promise)return F.then((J)=>{var t,R;if(!J){let W=eF(T,f),O=(R=(t=W.fatal)!==null&&t!==void 0?t:n)!==null&&R!==void 0?R:!0;S.addIssue({code:"custom",...W,fatal:O})}});if(!F){let J=eF(T,f),t=($=(A=J.fatal)!==null&&A!==void 0?A:n)!==null&&$!==void 0?$:!0;S.addIssue({code:"custom",...J,fatal:t})}return});return Rn.create()}var X1={object:zo.lazycreate},g;(function(o){o.ZodString="ZodString",o.ZodNumber="ZodNumber",o.ZodNaN="ZodNaN",o.ZodBigInt="ZodBigInt",o.ZodBoolean="ZodBoolean",o.ZodDate="ZodDate",o.ZodSymbol="ZodSymbol",o.ZodUndefined="ZodUndefined",o.ZodNull="ZodNull",o.ZodAny="ZodAny",o.ZodUnknown="ZodUnknown",o.ZodNever="ZodNever",o.ZodVoid="ZodVoid",o.ZodArray="ZodArray",o.ZodObject="ZodObject",o.ZodUnion="ZodUnion",o.ZodDiscriminatedUnion="ZodDiscriminatedUnion",o.ZodIntersection="ZodIntersection",o.ZodTuple="ZodTuple",o.ZodRecord="ZodRecord",o.ZodMap="ZodMap",o.ZodSet="ZodSet",o.ZodFunction="ZodFunction",o.ZodLazy="ZodLazy",o.ZodLiteral="ZodLiteral",o.ZodEnum="ZodEnum",o.ZodEffects="ZodEffects",o.ZodNativeEnum="ZodNativeEnum",o.ZodOptional="ZodOptional",o.ZodNullable="ZodNullable",o.ZodDefault="ZodDefault",o.ZodCatch="ZodCatch",o.ZodPromise="ZodPromise",o.ZodBranded="ZodBranded",o.ZodPipeline="ZodPipeline",o.ZodReadonly="ZodReadonly"})(g||(g={}));var H1=(o,T={message:`Input not instance of ${o.name}`})=>AJ((n)=>n instanceof o,T),$J=HT.create,FJ=dT.create,K1=Kf.create,E1=lT.create,JJ=jn.create,G1=tn.create,Y1=wf.create,z1=hn.create,D1=Nn.create,Q1=Rn.create,U1=gT.create,V1=BT.create,B1=_f.create,m1=KT.create,L1=zo.create,C1=zo.strictCreate,I1=bn.create,j1=RS.create,h1=xn.create,N1=mT.create,b1=Xf.create,x1=Hf.create,v1=Mn.create,r1=Cn.create,q1=vn.create,p1=rn.create,c1=uT.create,Z1=qn.create,P1=yn.create,sF=WT.create,i1=ET.create,g1=rT.create,d1=WT.createWithPreprocess,l1=Ef.create,u1=()=>$J().optional(),e1=()=>FJ().optional(),s1=()=>JJ().optional(),a1={string:(o)=>HT.create({...o,coerce:!0}),number:(o)=>dT.create({...o,coerce:!0}),boolean:(o)=>jn.create({...o,coerce:!0}),bigint:(o)=>lT.create({...o,coerce:!0}),date:(o)=>tn.create({...o,coerce:!0})},oy=d,Eo=Object.freeze({__proto__:null,defaultErrorMap:In,setErrorMap:dM,getErrorMap:FS,makeIssue:JS,EMPTY_PATH:lM,addIssueToContext:L,ParseStatus:uo,INVALID:d,DIRTY:Ln,OK:ao,isAborted:CA,isDirty:IA,isValid:Jn,isAsync:Of,get util(){return Ao},get objectUtil(){return LA},ZodParsedType:h,getParsedType:vT,ZodType:e,datetimeRegex:fJ,ZodString:HT,ZodNumber:dT,ZodBigInt:lT,ZodBoolean:jn,ZodDate:tn,ZodSymbol:wf,ZodUndefined:hn,ZodNull:Nn,ZodAny:Rn,ZodUnknown:gT,ZodNever:BT,ZodVoid:_f,ZodArray:KT,ZodObject:zo,ZodUnion:bn,ZodDiscriminatedUnion:RS,ZodIntersection:xn,ZodTuple:mT,ZodRecord:Xf,ZodMap:Hf,ZodSet:Mn,ZodFunction:Cn,ZodLazy:vn,ZodLiteral:rn,ZodEnum:uT,ZodNativeEnum:qn,ZodPromise:yn,ZodEffects:WT,ZodTransformer:WT,ZodOptional:ET,ZodNullable:rT,ZodDefault:pn,ZodCatch:cn,ZodNaN:Kf,BRAND:_1,ZodBranded:MS,ZodPipeline:Ef,ZodReadonly:Zn,custom:AJ,Schema:e,ZodSchema:e,late:X1,get ZodFirstPartyTypeKind(){return g},coerce:a1,any:Q1,array:m1,bigint:E1,boolean:JJ,date:G1,discriminatedUnion:j1,effect:sF,enum:c1,function:r1,instanceof:H1,intersection:h1,lazy:q1,literal:p1,map:x1,nan:K1,nativeEnum:Z1,never:V1,null:D1,nullable:g1,number:FJ,object:L1,oboolean:s1,onumber:e1,optional:i1,ostring:u1,pipeline:l1,preprocess:d1,promise:P1,record:b1,set:v1,strictObject:C1,string:$J,symbol:Y1,transformer:sF,tuple:N1,undefined:z1,union:I1,unknown:U1,void:B1,NEVER:oy,ZodIssueCode:Y,quotelessJson:gM,ZodError:JT});var Ty="__vite_start_time"in globalThis,ny=typeof window!=="undefined",JE="vitest"in globalThis,YT=lF({isServer:!Ty&&!ny,server:{CI:Eo.string().transform((o)=>!0).optional(),POSTGRES_USER:Eo.string(),POSTGRES_PASSWORD:Eo.string(),POSTGRES_DATABASE:Eo.string(),POSTGRES_HOST:Eo.string(),POSTGRES_PORT:Eo.string().transform((o)=>Number.parseInt(o,10)),BACKEND_PORT:Eo.string().transform((o)=>Number.parseInt(o,10)),RUN_WORKERS_FROM_SOURCE:Eo.union([Eo.literal("true"),Eo.literal("false")]).optional().transform((o)=>o==="true"),FRONTEND_PORT:Eo.string().transform((o)=>Number.parseInt(o,10)),FRONTEND_ORIGINS:Eo.string().transform((o)=>JSON.parse(o)).pipe(Eo.array(Eo.string())),OPENAI_API_KEY:Eo.string().optional()},clientPrefix:"VITE_",client:{VITE_BACKEND_ORIGIN:Eo.string(),VITE_USE_SELF_SIGNED_CERTIFICATE:Eo.union([Eo.literal("true"),Eo.literal("false")]).optional().transform((o)=>o==="true")},runtimeEnv:import.meta.env,emptyStringAsUndefined:!0});var RJ=hA(import.meta.dirname,"../dev"),MJ=YT.VITE_USE_SELF_SIGNED_CERTIFICATE?{cert:tJ(hA(RJ,"./cert.pem"),"utf-8"),key:tJ(hA(RJ,"./key.pem"),"utf-8")}:void 0;import Sk from"node:path";var y=Symbol.for("drizzle:entityKind"),WE=Symbol.for("drizzle:hasOwnEntityKind");function X(o,T){if(!o||typeof o!=="object")return!1;if(o instanceof T)return!0;if(!Object.prototype.hasOwnProperty.call(T,y))throw new Error(`Class "${T.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 n=Object.getPrototypeOf(o).constructor;if(n)while(n){if(y in n&&n[y]===T[y])return!0;n=Object.getPrototypeOf(n)}return!1}class Wo{constructor(o,T){this.table=o,this.config=T,this.name=T.name,this.keyAsName=T.keyAsName,this.notNull=T.notNull,this.default=T.default,this.defaultFn=T.defaultFn,this.onUpdateFn=T.onUpdateFn,this.hasDefault=T.hasDefault,this.primary=T.primaryKey,this.isUnique=T.isUnique,this.uniqueName=T.uniqueName,this.uniqueType=T.uniqueType,this.dataType=T.dataType,this.columnType=T.columnType,this.generated=T.generated,this.generatedIdentity=T.generatedIdentity}static[y]="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(o){return o}mapToDriverValue(o){return o}shouldDisableInsert(){return this.config.generated!==void 0&&this.config.generated.type!=="byDefault"}}class NA{static[y]="ColumnBuilder";config;constructor(o,T,n){this.config={name:o,keyAsName:o==="",notNull:!1,default:void 0,hasDefault:!1,primaryKey:!1,isUnique:!1,uniqueName:void 0,uniqueType:void 0,dataType:T,columnType:n,generated:void 0}}$type(){return this}notNull(){return this.config.notNull=!0,this}default(o){return this.config.default=o,this.config.hasDefault=!0,this}$defaultFn(o){return this.config.defaultFn=o,this.config.hasDefault=!0,this}$default=this.$defaultFn;$onUpdateFn(o){return this.config.onUpdateFn=o,this.config.hasDefault=!0,this}$onUpdate=this.$onUpdateFn;primaryKey(){return this.config.primaryKey=!0,this.config.notNull=!0,this}setName(o){if(this.config.name!=="")return;this.config.name=o}}var zT=Symbol.for("drizzle:Name");class bA{static[y]="PgForeignKeyBuilder";reference;_onUpdate="no action";_onDelete="no action";constructor(o,T){if(this.reference=()=>{let{name:n,columns:f,foreignColumns:S}=o();return{name:n,columns:f,foreignTable:S[0].table,foreignColumns:S}},T)this._onUpdate=T.onUpdate,this._onDelete=T.onDelete}onUpdate(o){return this._onUpdate=o===void 0?"no action":o,this}onDelete(o){return this._onDelete=o===void 0?"no action":o,this}build(o){return new yJ(o,this)}}class yJ{constructor(o,T){this.table=o,this.reference=T.reference,this.onUpdate=T._onUpdate,this.onDelete=T._onDelete}static[y]="PgForeignKey";reference;onUpdate;onDelete;getName(){let{name:o,columns:T,foreignColumns:n}=this.reference(),f=T.map(($)=>$.name),S=n.map(($)=>$.name),A=[this.table[zT],...f,n[0].table[zT],...S];return o??`${A.join("_")}_fk`}}function yS(o,...T){return o(...T)}function kJ(o,T){return`${o[zT]}_${T.join("_")}_unique`}function WJ(o,T,n){for(let f=T;f<o.length;f++){let S=o[f];if(S==="\\"){f++;continue}if(S==='"')return[o.slice(T,f).replace(/\\/g,""),f+1];if(n)continue;if(S===","||S==="}")return[o.slice(T,f).replace(/\\/g,""),f]}return[o.slice(T).replace(/\\/g,""),o.length]}function OJ(o,T=0){let n=[],f=T,S=!1;while(f<o.length){let A=o[f];if(A===","){if(S||f===T)n.push("");S=!0,f++;continue}if(S=!1,A==="\\"){f+=2;continue}if(A==='"'){let[J,t]=WJ(o,f+1,!0);n.push(J),f=t;continue}if(A==="}")return[n,f+1];if(A==="{"){let[J,t]=OJ(o,f+1);n.push(J),f=t;continue}let[$,F]=WJ(o,f,!1);n.push($),f=F}return[n,f]}function wJ(o){let[T]=OJ(o,1);return T}function xA(o){return`{${o.map((T)=>{if(Array.isArray(T))return xA(T);if(typeof T==="string")return`"${T.replace(/\\/g,"\\\\").replace(/"/g,"\\\"")}"`;return`${T}`}).join(",")}}`}class N extends NA{foreignKeyConfigs=[];static[y]="PgColumnBuilder";array(o){return new XJ(this.config.name,this,o)}references(o,T={}){return this.foreignKeyConfigs.push({ref:o,actions:T}),this}unique(o,T){return this.config.isUnique=!0,this.config.uniqueName=o,this.config.uniqueType=T?.nulls,this}generatedAlwaysAs(o){return this.config.generated={as:o,type:"always",mode:"stored"},this}buildForeignKeys(o,T){return this.foreignKeyConfigs.map(({ref:n,actions:f})=>{return yS((S,A)=>{let $=new bA(()=>{let F=S();return{columns:[o],foreignColumns:[F]}});if(A.onUpdate)$.onUpdate(A.onUpdate);if(A.onDelete)$.onDelete(A.onDelete);return $.build(T)},n,f)})}buildExtraConfigColumn(o){return new _J(o,this.config)}}class V extends Wo{constructor(o,T){if(!T.uniqueName)T.uniqueName=kJ(o,[T.name]);super(o,T);this.table=o}static[y]="PgColumn"}class _J extends V{static[y]="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(o){return this.indexConfig.opClass=o,this}}class Gf{static[y]="IndexedColumn";constructor(o,T,n,f){this.name=o,this.keyAsName=T,this.type=n,this.indexConfig=f}name;keyAsName;type;indexConfig}class XJ extends N{static[y]="PgArrayBuilder";constructor(o,T,n){super(o,"array","PgArray");this.config.baseBuilder=T,this.config.size=n}build(o){let T=this.config.baseBuilder.build(o);return new vA(o,this.config,T)}}class vA extends V{constructor(o,T,n,f){super(o,T);this.baseColumn=n,this.range=f,this.size=T.size}size;static[y]="PgArray";getSQLType(){return`${this.baseColumn.getSQLType()}[${typeof this.size==="number"?this.size:""}]`}mapFromDriverValue(o){if(typeof o==="string")o=wJ(o);return o.map((T)=>this.baseColumn.mapFromDriverValue(T))}mapToDriverValue(o,T=!1){let n=o.map((f)=>f===null?null:X(this.baseColumn,vA)?this.baseColumn.mapToDriverValue(f,!0):this.baseColumn.mapToDriverValue(f));if(T)return n;return xA(n)}}var rA=Symbol.for("drizzle:isPgEnum");function HJ(o){return!!o&&typeof o==="function"&&rA in o&&o[rA]===!0}class KJ extends N{static[y]="PgEnumColumnBuilder";constructor(o,T){super(o,"string","PgEnumColumn");this.config.enum=T}build(o){return new EJ(o,this.config)}}class EJ extends V{static[y]="PgEnumColumn";enum=this.config.enum;enumValues=this.config.enum.enumValues;constructor(o,T){super(o,T);this.enum=T.enum}getSQLType(){return this.enum.enumName}}function kS(o,T){return fy(o,T,void 0)}function fy(o,T,n){let f=Object.assign((S)=>new KJ(S??"",f),{enumName:o,enumValues:T,schema:n,[rA]:!0});return f}class No{static[y]="Subquery";constructor(o,T,n,f=!1){this._={brand:"Subquery",sql:o,selectedFields:T,alias:n,isWith:f}}}class Yf extends No{static[y]="WithSubquery"}var GJ="0.41.0";var qA,pA,Oo={startActiveSpan(o,T){if(!qA)return T();if(!pA)pA=qA.trace.getTracer("drizzle-orm",GJ);return yS((n,f)=>f.startActiveSpan(o,(S)=>{try{return T(S)}catch(A){throw S.setStatus({code:n.SpanStatusCode.ERROR,message:A instanceof Error?A.message:"Unknown error"}),A}finally{S.end()}}),qA,pA)}};var Xo=Symbol.for("drizzle:ViewBaseConfig");var WS=Symbol.for("drizzle:Schema"),OS=Symbol.for("drizzle:Columns"),YJ=Symbol.for("drizzle:ExtraConfigColumns"),cA=Symbol.for("drizzle:OriginalName"),ZA=Symbol.for("drizzle:BaseName"),zf=Symbol.for("drizzle:IsAlias"),zJ=Symbol.for("drizzle:ExtraConfigBuilder"),Sy=Symbol.for("drizzle:IsDrizzleTable");class I{static[y]="Table";static Symbol={Name:zT,Schema:WS,OriginalName:cA,Columns:OS,ExtraConfigColumns:YJ,BaseName:ZA,IsAlias:zf,ExtraConfigBuilder:zJ};[zT];[cA];[WS];[OS];[YJ];[ZA];[zf]=!1;[Sy]=!0;[zJ]=void 0;constructor(o,T,n){this[zT]=this[cA]=o,this[WS]=T,this[ZA]=n}}function vo(o){return o[zT]}function kn(o){return`${o[WS]??"public"}.${o[zT]}`}function PA(o){return o!==null&&o!==void 0&&typeof o.getSQL==="function"}function Ay(o){let T={sql:"",params:[]};for(let n of o)if(T.sql+=n.sql,T.params.push(...n.params),n.typings?.length){if(!T.typings)T.typings=[];T.typings.push(...n.typings)}return T}class bo{static[y]="StringChunk";value;constructor(o){this.value=Array.isArray(o)?o:[o]}getSQL(){return new j([this])}}class j{constructor(o){this.queryChunks=o}static[y]="SQL";decoder=QJ;shouldInlineParams=!1;append(o){return this.queryChunks.push(...o.queryChunks),this}toQuery(o){return Oo.startActiveSpan("drizzle.buildSQL",(T)=>{let n=this.buildQueryFromSourceParams(this.queryChunks,o);return T?.setAttributes({"drizzle.query.text":n.sql,"drizzle.query.params":JSON.stringify(n.params)}),n})}buildQueryFromSourceParams(o,T){let n=Object.assign({},T,{inlineParams:T.inlineParams||this.shouldInlineParams,paramStartIndex:T.paramStartIndex||{value:0}}),{casing:f,escapeName:S,escapeParam:A,prepareTyping:$,inlineParams:F,paramStartIndex:J}=n;return Ay(o.map((t)=>{if(X(t,bo))return{sql:t.value.join(""),params:[]};if(X(t,wS))return{sql:S(t.value),params:[]};if(t===void 0)return{sql:"",params:[]};if(Array.isArray(t)){let R=[new bo("(")];for(let[W,O]of t.entries())if(R.push(O),W<t.length-1)R.push(new bo(", "));return R.push(new bo(")")),this.buildQueryFromSourceParams(R,n)}if(X(t,j))return this.buildQueryFromSourceParams(t.queryChunks,{...n,inlineParams:F||t.shouldInlineParams});if(X(t,I)){let R=t[I.Symbol.Schema],W=t[I.Symbol.Name];return{sql:R===void 0||t[zf]?S(W):S(R)+"."+S(W),params:[]}}if(X(t,Wo)){let R=f.getColumnCasing(t);if(T.invokeSource==="indexes")return{sql:S(R),params:[]};let W=t.table[I.Symbol.Schema];return{sql:t.table[zf]||W===void 0?S(t.table[I.Symbol.Name])+"."+S(R):S(W)+"."+S(t.table[I.Symbol.Name])+"."+S(R),params:[]}}if(X(t,ST)){let R=t[Xo].schema,W=t[Xo].name;return{sql:R===void 0||t[Xo].isAlias?S(W):S(R)+"."+S(W),params:[]}}if(X(t,tT)){if(X(t.value,eT))return{sql:A(J.value++,t),params:[t],typings:["none"]};let R=t.value===null?null:t.encoder.mapToDriverValue(t.value);if(X(R,j))return this.buildQueryFromSourceParams([R],n);if(F)return{sql:this.mapInlineParam(R,n),params:[]};let W=["none"];if($)W=[$(t.encoder)];return{sql:A(J.value++,R),params:[R],typings:W}}if(X(t,eT))return{sql:A(J.value++,t),params:[t],typings:["none"]};if(X(t,j.Aliased)&&t.fieldAlias!==void 0)return{sql:S(t.fieldAlias),params:[]};if(X(t,No)){if(t._.isWith)return{sql:S(t._.alias),params:[]};return this.buildQueryFromSourceParams([new bo("("),t._.sql,new bo(") "),new wS(t._.alias)],n)}if(HJ(t)){if(t.schema)return{sql:S(t.schema)+"."+S(t.enumName),params:[]};return{sql:S(t.enumName),params:[]}}if(PA(t)){if(t.shouldOmitSQLParens?.())return this.buildQueryFromSourceParams([t.getSQL()],n);return this.buildQueryFromSourceParams([new bo("("),t.getSQL(),new bo(")")],n)}if(F)return{sql:this.mapInlineParam(t,n),params:[]};return{sql:A(J.value++,t),params:[t],typings:["none"]}}))}mapInlineParam(o,{escapeString:T}){if(o===null)return"null";if(typeof o==="number"||typeof o==="boolean")return o.toString();if(typeof o==="string")return T(o);if(typeof o==="object"){let n=o.toString();if(n==="[object Object]")return T(JSON.stringify(o));return T(n)}throw new Error("Unexpected param value: "+o)}getSQL(){return this}as(o){if(o===void 0)return this;return new j.Aliased(this,o)}mapWith(o){return this.decoder=typeof o==="function"?{mapFromDriverValue:o}:o,this}inlineParams(){return this.shouldInlineParams=!0,this}if(o){return o?this:void 0}}class wS{constructor(o){this.value=o}static[y]="Name";brand;getSQL(){return new j([this])}}function DJ(o){return typeof o==="object"&&o!==null&&"mapToDriverValue"in o&&typeof o.mapToDriverValue==="function"}var QJ={mapFromDriverValue:(o)=>o},UJ={mapToDriverValue:(o)=>o},n5={...QJ,...UJ};class tT{constructor(o,T=UJ){this.value=o,this.encoder=T}static[y]="Param";brand;getSQL(){return new j([this])}}function k(o,...T){let n=[];if(T.length>0||o.length>0&&o[0]!=="")n.push(new bo(o[0]));for(let[f,S]of T.entries())n.push(S,new bo(o[f+1]));return new j(n)}((o)=>{function T(){return new j([])}o.empty=T;function n(J){return new j(J)}o.fromList=n;function f(J){return new j([new bo(J)])}o.raw=f;function S(J,t){let R=[];for(let[W,O]of J.entries()){if(W>0&&t!==void 0)R.push(t);R.push(O)}return new j(R)}o.join=S;function A(J){return new wS(J)}o.identifier=A;function $(J){return new eT(J)}o.placeholder=$;function F(J,t){return new tT(J,t)}o.param=F})(k||(k={}));((o)=>{class T{constructor(n,f){this.sql=n,this.fieldAlias=f}static[y]="SQL.Aliased";isSelectionField=!1;getSQL(){return this.sql}clone(){return new T(this.sql,this.fieldAlias)}}o.Aliased=T})(j||(j={}));class eT{constructor(o){this.name=o}static[y]="Placeholder";getSQL(){return new j([this])}}function iA(o,T){return o.map((n)=>{if(X(n,eT)){if(!(n.name in T))throw new Error(`No value for placeholder "${n.name}" was provided`);return T[n.name]}if(X(n,tT)&&X(n.value,eT)){if(!(n.value.name in T))throw new Error(`No value for placeholder "${n.value.name}" was provided`);return n.encoder.mapToDriverValue(T[n.value.name])}return n})}var $y=Symbol.for("drizzle:IsDrizzleView");class ST{static[y]="View";[Xo];[$y]=!0;constructor({name:o,schema:T,selectedFields:n,query:f}){this[Xo]={name:o,originalName:o,schema:T,selectedFields:n,query:f,isExisting:!f,isAlias:!1}}getSQL(){return new j([this])}}Wo.prototype.getSQL=function(){return new j([this])};I.prototype.getSQL=function(){return new j([this])};No.prototype.getSQL=function(){return new j([this])};class Pn{constructor(o){this.table=o}static[y]="ColumnAliasProxyHandler";get(o,T){if(T==="table")return this.table;return o[T]}}class Df{constructor(o,T){this.alias=o,this.replaceOriginalName=T}static[y]="TableAliasProxyHandler";get(o,T){if(T===I.Symbol.IsAlias)return!0;if(T===I.Symbol.Name)return this.alias;if(this.replaceOriginalName&&T===I.Symbol.OriginalName)return this.alias;if(T===Xo)return{...o[Xo],name:this.alias,isAlias:!0};if(T===I.Symbol.Columns){let f=o[I.Symbol.Columns];if(!f)return f;let S={};return Object.keys(f).map((A)=>{S[A]=new Proxy(f[A],new Pn(new Proxy(o,this)))}),S}let n=o[T];if(X(n,Wo))return new Proxy(n,new Pn(new Proxy(o,this)));return n}}function _S(o,T){return new Proxy(o,new Df(T,!1))}function LT(o,T){return new Proxy(o,new Pn(new Proxy(o.table,new Df(T,!1))))}function gA(o,T){return new j.Aliased(Qf(o.sql,T),o.fieldAlias)}function Qf(o,T){return k.join(o.queryChunks.map((n)=>{if(X(n,Wo))return LT(n,T);if(X(n,j))return Qf(n,T);if(X(n,j.Aliased))return gA(n,T);return n}))}class XS extends Error{static[y]="DrizzleError";constructor({message:o,cause:T}){super(o);this.name="DrizzleError",this.cause=T}}class dA extends XS{static[y]="TransactionRollbackError";constructor(){super({message:"Rollback"})}}function AT(o,T){if(DJ(T)&&!PA(o)&&!X(o,tT)&&!X(o,eT)&&!X(o,Wo)&&!X(o,I)&&!X(o,ST))return new tT(o,T);return o}var HS=(o,T)=>{return k`${o} = ${AT(T,o)}`},VJ=(o,T)=>{return k`${o} <> ${AT(T,o)}`};function Uf(...o){let T=o.filter((n)=>n!==void 0);if(T.length===0)return;if(T.length===1)return new j(T);return new j([new bo("("),k.join(T,new bo(" and ")),new bo(")")])}function BJ(...o){let T=o.filter((n)=>n!==void 0);if(T.length===0)return;if(T.length===1)return new j(T);return new j([new bo("("),k.join(T,new bo(" or ")),new bo(")")])}function mJ(o){return k`not ${o}`}var LJ=(o,T)=>{return k`${o} > ${AT(T,o)}`},CJ=(o,T)=>{return k`${o} >= ${AT(T,o)}`},IJ=(o,T)=>{return k`${o} < ${AT(T,o)}`},jJ=(o,T)=>{return k`${o} <= ${AT(T,o)}`};function hJ(o,T){if(Array.isArray(T)){if(T.length===0)return k`false`;return k`${o} in ${T.map((n)=>AT(n,o))}`}return k`${o} in ${AT(T,o)}`}function NJ(o,T){if(Array.isArray(T)){if(T.length===0)return k`true`;return k`${o} not in ${T.map((n)=>AT(n,o))}`}return k`${o} not in ${AT(T,o)}`}function bJ(o){return k`${o} is null`}function xJ(o){return k`${o} is not null`}function vJ(o){return k`exists ${o}`}function rJ(o){return k`not exists ${o}`}function qJ(o,T,n){return k`${o} between ${AT(T,o)} and ${AT(n,o)}`}function pJ(o,T,n){return k`${o} not between ${AT(T,o)} and ${AT(n,o)}`}function cJ(o,T){return k`${o} like ${T}`}function ZJ(o,T){return k`${o} not like ${T}`}function PJ(o,T){return k`${o} ilike ${T}`}function iJ(o,T){return k`${o} not ilike ${T}`}function gJ(o){return k`${o} asc`}function dJ(o){return k`${o} desc`}class lJ{static[y]="ConsoleLogWriter";write(o){console.log(o)}}class lA{static[y]="DefaultLogger";writer;constructor(o){this.writer=o?.writer??new lJ}logQuery(o,T){let n=T.map((S)=>{try{return JSON.stringify(S)}catch{return String(S)}}),f=n.length?` -- params: [${n.join(", ")}]`:"";this.writer.write(`Query: ${o}${f}`)}}class uA{static[y]="NoopLogger";logQuery(){}}class oT{static[y]="QueryPromise";[Symbol.toStringTag]="QueryPromise";catch(o){return this.then(void 0,o)}finally(o){return this.then((T)=>{return o?.(),T},(T)=>{throw o?.(),T})}then(o,T){return this.execute().then(o,T)}}function uJ(o,T,n){let f={},S=o.reduce((A,{path:$,field:F},J)=>{let t;if(X(F,Wo))t=F;else if(X(F,j))t=F.decoder;else t=F.sql.decoder;let R=A;for(let[W,O]of $.entries())if(W<$.length-1){if(!(O in R))R[O]={};R=R[O]}else{let _=T[J],Q=R[O]=_===null?null:t.mapFromDriverValue(_);if(n&&X(F,Wo)&&$.length===2){let H=$[0];if(!(H in f))f[H]=Q===null?vo(F.table):!1;else if(typeof f[H]==="string"&&f[H]!==vo(F.table))f[H]=!1}}return A},{});if(n&&Object.keys(f).length>0){for(let[A,$]of Object.entries(f))if(typeof $==="string"&&!n[$])S[A]=null}return S}function OT(o,T){return Object.entries(o).reduce((n,[f,S])=>{if(typeof f!=="string")return n;let A=T?[...T,f]:[f];if(X(S,Wo)||X(S,j)||X(S,j.Aliased))n.push({path:A,field:S});else if(X(S,I))n.push(...OT(S[I.Symbol.Columns],A));else n.push(...OT(S,A));return n},[])}function Vf(o,T){let n=Object.keys(o),f=Object.keys(T);if(n.length!==f.length)return!1;for(let[S,A]of n.entries())if(A!==f[S])return!1;return!0}function KS(o,T){let n=Object.entries(T).filter(([,f])=>f!==void 0).map(([f,S])=>{if(X(S,j)||X(S,Wo))return[f,S];else return[f,new tT(S,o[I.Symbol.Columns][f])]});if(n.length===0)throw new Error("No values to set");return Object.fromEntries(n)}function eJ(o,T){for(let n of T)for(let f of Object.getOwnPropertyNames(n.prototype)){if(f==="constructor")continue;Object.defineProperty(o.prototype,f,Object.getOwnPropertyDescriptor(n.prototype,f)||Object.create(null))}}function sJ(o){return o[I.Symbol.Columns]}function qT(o){return X(o,No)?o._.alias:X(o,ST)?o[Xo].name:X(o,j)?void 0:o[I.Symbol.IsAlias]?o[I.Symbol.Name]:o[I.Symbol.BaseName]}function So(o,T){return{name:typeof o==="string"&&o.length>0?o:"",config:typeof o==="object"?o:T}}function aJ(o){if(typeof o!=="object"||o===null)return!1;if(o.constructor.name!=="Object")return!1;if("logger"in o){let T=typeof o.logger;if(T!=="boolean"&&(T!=="object"||typeof o.logger.logQuery!=="function")&&T!=="undefined")return!1;return!0}if("schema"in o){let T=typeof o.schema;if(T!=="object"&&T!=="undefined")return!1;return!0}if("casing"in o){let T=typeof o.casing;if(T!=="string"&&T!=="undefined")return!1;return!0}if("mode"in o){if(o.mode!=="default"||o.mode!=="planetscale"||o.mode!==void 0)return!1;return!0}if("connection"in o){let T=typeof o.connection;if(T!=="string"&&T!=="object"&&T!=="undefined")return!1;return!0}if("client"in o){let T=typeof o.client;if(T!=="object"&&T!=="function"&&T!=="undefined")return!1;return!0}if(Object.keys(o).length===0)return!0;return!1}class sT extends N{static[y]="PgIntColumnBaseBuilder";generatedAlwaysAsIdentity(o){if(o){let{name:T,...n}=o;this.config.generatedIdentity={type:"always",sequenceName:T,sequenceOptions:n}}else this.config.generatedIdentity={type:"always"};return this.config.hasDefault=!0,this.config.notNull=!0,this}generatedByDefaultAsIdentity(o){if(o){let{name:T,...n}=o;this.config.generatedIdentity={type:"byDefault",sequenceName:T,sequenceOptions:n}}else this.config.generatedIdentity={type:"byDefault"};return this.config.hasDefault=!0,this.config.notNull=!0,this}}class ot extends sT{static[y]="PgBigInt53Builder";constructor(o){super(o,"number","PgBigInt53")}build(o){return new Tt(o,this.config)}}class Tt extends V{static[y]="PgBigInt53";getSQLType(){return"bigint"}mapFromDriverValue(o){if(typeof o==="number")return o;return Number(o)}}class nt extends sT{static[y]="PgBigInt64Builder";constructor(o){super(o,"bigint","PgBigInt64")}build(o){return new ft(o,this.config)}}class ft extends V{static[y]="PgBigInt64";getSQLType(){return"bigint"}mapFromDriverValue(o){return BigInt(o)}}function St(o,T){let{name:n,config:f}=So(o,T);if(f.mode==="number")return new ot(n);return new nt(n)}class At extends N{static[y]="PgBigSerial53Builder";constructor(o){super(o,"number","PgBigSerial53");this.config.hasDefault=!0,this.config.notNull=!0}build(o){return new $t(o,this.config)}}class $t extends V{static[y]="PgBigSerial53";getSQLType(){return"bigserial"}mapFromDriverValue(o){if(typeof o==="number")return o;return Number(o)}}class Ft extends N{static[y]="PgBigSerial64Builder";constructor(o){super(o,"bigint","PgBigSerial64");this.config.hasDefault=!0}build(o){return new Jt(o,this.config)}}class Jt extends V{static[y]="PgBigSerial64";getSQLType(){return"bigserial"}mapFromDriverValue(o){return BigInt(o)}}function tt(o,T){let{name:n,config:f}=So(o,T);if(f.mode==="number")return new At(n);return new Ft(n)}class Rt extends N{static[y]="PgBooleanBuilder";constructor(o){super(o,"boolean","PgBoolean")}build(o){return new Mt(o,this.config)}}class Mt extends V{static[y]="PgBoolean";getSQLType(){return"boolean"}}function Bf(o){return new Rt(o??"")}class yt extends N{static[y]="PgCharBuilder";constructor(o,T){super(o,"string","PgChar");this.config.length=T.length,this.config.enumValues=T.enum}build(o){return new kt(o,this.config)}}class kt extends V{static[y]="PgChar";length=this.config.length;enumValues=this.config.enumValues;getSQLType(){return this.length===void 0?"char":`char(${this.length})`}}function Wt(o,T={}){let{name:n,config:f}=So(o,T);return new yt(n,f)}class Ot extends N{static[y]="PgCidrBuilder";constructor(o){super(o,"string","PgCidr")}build(o){return new wt(o,this.config)}}class wt extends V{static[y]="PgCidr";getSQLType(){return"cidr"}}function _t(o){return new Ot(o??"")}class Xt extends N{static[y]="PgCustomColumnBuilder";constructor(o,T,n){super(o,"custom","PgCustomColumn");this.config.fieldConfig=T,this.config.customTypeParams=n}build(o){return new Ht(o,this.config)}}class Ht extends V{static[y]="PgCustomColumn";sqlName;mapTo;mapFrom;constructor(o,T){super(o,T);this.sqlName=T.customTypeParams.dataType(T.fieldConfig),this.mapTo=T.customTypeParams.toDriver,this.mapFrom=T.customTypeParams.fromDriver}getSQLType(){return this.sqlName}mapFromDriverValue(o){return typeof this.mapFrom==="function"?this.mapFrom(o):o}mapToDriverValue(o){return typeof this.mapTo==="function"?this.mapTo(o):o}}function Kt(o){return(T,n)=>{let{name:f,config:S}=So(T,n);return new Xt(f,S,o)}}class pT extends N{static[y]="PgDateColumnBaseBuilder";defaultNow(){return this.default(k`now()`)}}class Et extends pT{static[y]="PgDateBuilder";constructor(o){super(o,"date","PgDate")}build(o){return new ES(o,this.config)}}class ES extends V{static[y]="PgDate";getSQLType(){return"date"}mapFromDriverValue(o){return new Date(o)}mapToDriverValue(o){return o.toISOString()}}class Gt extends pT{static[y]="PgDateStringBuilder";constructor(o){super(o,"string","PgDateString")}build(o){return new GS(o,this.config)}}class GS extends V{static[y]="PgDateString";getSQLType(){return"date"}}function Yt(o,T){let{name:n,config:f}=So(o,T);if(f?.mode==="date")return new Et(n);return new Gt(n)}class zt extends N{static[y]="PgDoublePrecisionBuilder";constructor(o){super(o,"number","PgDoublePrecision")}build(o){return new Dt(o,this.config)}}class Dt extends V{static[y]="PgDoublePrecision";getSQLType(){return"double precision"}mapFromDriverValue(o){if(typeof o==="string")return Number.parseFloat(o);return o}}function Qt(o){return new zt(o??"")}class Ut extends N{static[y]="PgInetBuilder";constructor(o){super(o,"string","PgInet")}build(o){return new Vt(o,this.config)}}class Vt extends V{static[y]="PgInet";getSQLType(){return"inet"}}function Bt(o){return new Ut(o??"")}class mt extends sT{static[y]="PgIntegerBuilder";constructor(o){super(o,"number","PgInteger")}build(o){return new Lt(o,this.config)}}class Lt extends V{static[y]="PgInteger";getSQLType(){return"integer"}mapFromDriverValue(o){if(typeof o==="string")return Number.parseInt(o);return o}}function YS(o){return new mt(o??"")}class Ct extends N{static[y]="PgIntervalBuilder";constructor(o,T){super(o,"string","PgInterval");this.config.intervalConfig=T}build(o){return new It(o,this.config)}}class It extends V{static[y]="PgInterval";fields=this.config.intervalConfig.fields;precision=this.config.intervalConfig.precision;getSQLType(){let o=this.fields?` ${this.fields}`:"",T=this.precision?`(${this.precision})`:"";return`interval${o}${T}`}}function jt(o,T={}){let{name:n,config:f}=So(o,T);return new Ct(n,f)}class ht extends N{static[y]="PgJsonBuilder";constructor(o){super(o,"json","PgJson")}build(o){return new zS(o,this.config)}}class zS extends V{static[y]="PgJson";constructor(o,T){super(o,T)}getSQLType(){return"json"}mapToDriverValue(o){return JSON.stringify(o)}mapFromDriverValue(o){if(typeof o==="string")try{return JSON.parse(o)}catch{return o}return o}}function Nt(o){return new ht(o??"")}class bt extends N{static[y]="PgJsonbBuilder";constructor(o){super(o,"json","PgJsonb")}build(o){return new DS(o,this.config)}}class DS extends V{static[y]="PgJsonb";constructor(o,T){super(o,T)}getSQLType(){return"jsonb"}mapToDriverValue(o){return JSON.stringify(o)}mapFromDriverValue(o){if(typeof o==="string")try{return JSON.parse(o)}catch{return o}return o}}function xt(o){return new bt(o??"")}class vt extends N{static[y]="PgLineBuilder";constructor(o){super(o,"array","PgLine")}build(o){return new rt(o,this.config)}}class rt extends V{static[y]="PgLine";getSQLType(){return"line"}mapFromDriverValue(o){let[T,n,f]=o.slice(1,-1).split(",");return[Number.parseFloat(T),Number.parseFloat(n),Number.parseFloat(f)]}mapToDriverValue(o){return`{${o[0]},${o[1]},${o[2]}}`}}class qt extends N{static[y]="PgLineABCBuilder";constructor(o){super(o,"json","PgLineABC")}build(o){return new pt(o,this.config)}}class pt extends V{static[y]="PgLineABC";getSQLType(){return"line"}mapFromDriverValue(o){let[T,n,f]=o.slice(1,-1).split(",");return{a:Number.parseFloat(T),b:Number.parseFloat(n),c:Number.parseFloat(f)}}mapToDriverValue(o){return`{${o.a},${o.b},${o.c}}`}}function ct(o,T){let{name:n,config:f}=So(o,T);if(!f?.mode||f.mode==="tuple")return new vt(n);return new qt(n)}class Zt extends N{static[y]="PgMacaddrBuilder";constructor(o){super(o,"string","PgMacaddr")}build(o){return new Pt(o,this.config)}}class Pt extends V{static[y]="PgMacaddr";getSQLType(){return"macaddr"}}function it(o){return new Zt(o??"")}class gt extends N{static[y]="PgMacaddr8Builder";constructor(o){super(o,"string","PgMacaddr8")}build(o){return new dt(o,this.config)}}class dt extends V{static[y]="PgMacaddr8";getSQLType(){return"macaddr8"}}function lt(o){return new gt(o??"")}class ut extends N{static[y]="PgNumericBuilder";constructor(o,T,n){super(o,"string","PgNumeric");this.config.precision=T,this.config.scale=n}build(o){return new QS(o,this.config)}}class QS extends V{static[y]="PgNumeric";precision;scale;constructor(o,T){super(o,T);this.precision=T.precision,this.scale=T.scale}mapFromDriverValue(o){if(typeof o==="string")return o;return String(o)}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})`}}class et extends N{static[y]="PgNumericNumberBuilder";constructor(o,T,n){super(o,"number","PgNumericNumber");this.config.precision=T,this.config.scale=n}build(o){return new st(o,this.config)}}class st extends V{static[y]="PgNumericNumber";precision;scale;constructor(o,T){super(o,T);this.precision=T.precision,this.scale=T.scale}mapFromDriverValue(o){if(typeof o==="number")return o;return Number(o)}mapToDriverValue=String;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})`}}class at extends N{static[y]="PgNumericBigIntBuilder";constructor(o,T,n){super(o,"bigint","PgNumericBigInt");this.config.precision=T,this.config.scale=n}build(o){return new oR(o,this.config)}}class oR extends V{static[y]="PgNumericBigInt";precision;scale;constructor(o,T){super(o,T);this.precision=T.precision,this.scale=T.scale}mapFromDriverValue=BigInt;mapToDriverValue=String;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 TR(o,T){let{name:n,config:f}=So(o,T),S=f?.mode;return S==="number"?new et(n,f?.precision,f?.scale):S==="bigint"?new at(n,f?.precision,f?.scale):new ut(n,f?.precision,f?.scale)}class nR extends N{static[y]="PgPointTupleBuilder";constructor(o){super(o,"array","PgPointTuple")}build(o){return new fR(o,this.config)}}class fR extends V{static[y]="PgPointTuple";getSQLType(){return"point"}mapFromDriverValue(o){if(typeof o==="string"){let[T,n]=o.slice(1,-1).split(",");return[Number.parseFloat(T),Number.parseFloat(n)]}return[o.x,o.y]}mapToDriverValue(o){return`(${o[0]},${o[1]})`}}class SR extends N{static[y]="PgPointObjectBuilder";constructor(o){super(o,"json","PgPointObject")}build(o){return new AR(o,this.config)}}class AR extends V{static[y]="PgPointObject";getSQLType(){return"point"}mapFromDriverValue(o){if(typeof o==="string"){let[T,n]=o.slice(1,-1).split(",");return{x:Number.parseFloat(T),y:Number.parseFloat(n)}}return o}mapToDriverValue(o){return`(${o.x},${o.y})`}}function $R(o,T){let{name:n,config:f}=So(o,T);if(!f?.mode||f.mode==="tuple")return new nR(n);return new SR(n)}function Fy(o){let T=[];for(let n=0;n<o.length;n+=2)T.push(Number.parseInt(o.slice(n,n+2),16));return new Uint8Array(T)}function FR(o,T){let n=new ArrayBuffer(8),f=new DataView(n);for(let S=0;S<8;S++)f.setUint8(S,o[T+S]);return f.getFloat64(0,!0)}function eA(o){let T=Fy(o),n=0,f=T[n];n+=1;let S=new DataView(T.buffer),A=S.getUint32(n,f===1);n+=4;let $;if(A&536870912)$=S.getUint32(n,f===1),n+=4;if((A&65535)===1){let F=FR(T,n);n+=8;let J=FR(T,n);return n+=8,[F,J]}throw new Error("Unsupported geometry type")}class JR extends N{static[y]="PgGeometryBuilder";constructor(o){super(o,"array","PgGeometry")}build(o){return new tR(o,this.config)}}class tR extends V{static[y]="PgGeometry";getSQLType(){return"geometry(point)"}mapFromDriverValue(o){return eA(o)}mapToDriverValue(o){return`point(${o[0]} ${o[1]})`}}class RR extends N{static[y]="PgGeometryObjectBuilder";constructor(o){super(o,"json","PgGeometryObject")}build(o){return new MR(o,this.config)}}class MR extends V{static[y]="PgGeometryObject";getSQLType(){return"geometry(point)"}mapFromDriverValue(o){let T=eA(o);return{x:T[0],y:T[1]}}mapToDriverValue(o){return`point(${o.x} ${o.y})`}}function yR(o,T){let{name:n,config:f}=So(o,T);if(!f?.mode||f.mode==="tuple")return new JR(n);return new RR(n)}class kR extends N{static[y]="PgRealBuilder";constructor(o,T){super(o,"number","PgReal");this.config.length=T}build(o){return new WR(o,this.config)}}class WR extends V{static[y]="PgReal";constructor(o,T){super(o,T)}getSQLType(){return"real"}mapFromDriverValue=(o)=>{if(typeof o==="string")return Number.parseFloat(o);return o}}function OR(o){return new kR(o??"")}class wR extends N{static[y]="PgSerialBuilder";constructor(o){super(o,"number","PgSerial");this.config.hasDefault=!0,this.config.notNull=!0}build(o){return new _R(o,this.config)}}class _R extends V{static[y]="PgSerial";getSQLType(){return"serial"}}function XR(o){return new wR(o??"")}class HR extends sT{static[y]="PgSmallIntBuilder";constructor(o){super(o,"number","PgSmallInt")}build(o){return new KR(o,this.config)}}class KR extends V{static[y]="PgSmallInt";getSQLType(){return"smallint"}mapFromDriverValue=(o)=>{if(typeof o==="string")return Number(o);return o}}function ER(o){return new HR(o??"")}class GR extends N{static[y]="PgSmallSerialBuilder";constructor(o){super(o,"number","PgSmallSerial");this.config.hasDefault=!0,this.config.notNull=!0}build(o){return new YR(o,this.config)}}class YR extends V{static[y]="PgSmallSerial";getSQLType(){return"smallserial"}}function zR(o){return new GR(o??"")}class DR extends N{static[y]="PgTextBuilder";constructor(o,T){super(o,"string","PgText");this.config.enumValues=T.enum}build(o){return new QR(o,this.config)}}class QR extends V{static[y]="PgText";enumValues=this.config.enumValues;getSQLType(){return"text"}}function UR(o,T={}){let{name:n,config:f}=So(o,T);return new DR(n,f)}class VR extends pT{constructor(o,T,n){super(o,"string","PgTime");this.withTimezone=T,this.precision=n,this.config.withTimezone=T,this.config.precision=n}static[y]="PgTimeBuilder";build(o){return new US(o,this.config)}}class US extends V{static[y]="PgTime";withTimezone;precision;constructor(o,T){super(o,T);this.withTimezone=T.withTimezone,this.precision=T.precision}getSQLType(){return`time${this.precision===void 0?"":`(${this.precision})`}${this.withTimezone?" with time zone":""}`}}function BR(o,T={}){let{name:n,config:f}=So(o,T);return new VR(n,f.withTimezone??!1,f.precision)}class mR extends pT{static[y]="PgTimestampBuilder";constructor(o,T,n){super(o,"date","PgTimestamp");this.config.withTimezone=T,this.config.precision=n}build(o){return new VS(o,this.config)}}class VS extends V{static[y]="PgTimestamp";withTimezone;precision;constructor(o,T){super(o,T);this.withTimezone=T.withTimezone,this.precision=T.precision}getSQLType(){return`timestamp${this.precision===void 0?"":` (${this.precision})`}${this.withTimezone?" with time zone":""}`}mapFromDriverValue=(o)=>{return new Date(this.withTimezone?o:o+"+0000")};mapToDriverValue=(o)=>{return o.toISOString()}}class LR extends pT{static[y]="PgTimestampStringBuilder";constructor(o,T,n){super(o,"string","PgTimestampString");this.config.withTimezone=T,this.config.precision=n}build(o){return new BS(o,this.config)}}class BS extends V{static[y]="PgTimestampString";withTimezone;precision;constructor(o,T){super(o,T);this.withTimezone=T.withTimezone,this.precision=T.precision}getSQLType(){return`timestamp${this.precision===void 0?"":`(${this.precision})`}${this.withTimezone?" with time zone":""}`}}function DT(o,T={}){let{name:n,config:f}=So(o,T);if(f?.mode==="string")return new LR(n,f.withTimezone??!1,f.precision);return new mR(n,f?.withTimezone??!1,f?.precision)}class CR extends N{static[y]="PgUUIDBuilder";constructor(o){super(o,"string","PgUUID")}defaultRandom(){return this.default(k`gen_random_uuid()`)}build(o){return new mS(o,this.config)}}class mS extends V{static[y]="PgUUID";getSQLType(){return"uuid"}}function RT(o){return new CR(o??"")}class IR extends N{static[y]="PgVarcharBuilder";constructor(o,T){super(o,"string","PgVarchar");this.config.length=T.length,this.config.enumValues=T.enum}build(o){return new jR(o,this.config)}}class jR extends V{static[y]="PgVarchar";length=this.config.length;enumValues=this.config.enumValues;getSQLType(){return this.length===void 0?"varchar":`varchar(${this.length})`}}function po(o,T={}){let{name:n,config:f}=So(o,T);return new IR(n,f)}class hR extends N{static[y]="PgBinaryVectorBuilder";constructor(o,T){super(o,"string","PgBinaryVector");this.config.dimensions=T.dimensions}build(o){return new NR(o,this.config)}}class NR extends V{static[y]="PgBinaryVector";dimensions=this.config.dimensions;getSQLType(){return`bit(${this.dimensions})`}}function bR(o,T){let{name:n,config:f}=So(o,T);return new hR(n,f)}class xR extends N{static[y]="PgHalfVectorBuilder";constructor(o,T){super(o,"array","PgHalfVector");this.config.dimensions=T.dimensions}build(o){return new vR(o,this.config)}}class vR extends V{static[y]="PgHalfVector";dimensions=this.config.dimensions;getSQLType(){return`halfvec(${this.dimensions})`}mapToDriverValue(o){return JSON.stringify(o)}mapFromDriverValue(o){return o.slice(1,-1).split(",").map((T)=>Number.parseFloat(T))}}function rR(o,T){let{name:n,config:f}=So(o,T);return new xR(n,f)}class qR extends N{static[y]="PgSparseVectorBuilder";constructor(o,T){super(o,"string","PgSparseVector");this.config.dimensions=T.dimensions}build(o){return new pR(o,this.config)}}class pR extends V{static[y]="PgSparseVector";dimensions=this.config.dimensions;getSQLType(){return`sparsevec(${this.dimensions})`}}function cR(o,T){let{name:n,config:f}=So(o,T);return new qR(n,f)}class ZR extends N{static[y]="PgVectorBuilder";constructor(o,T){super(o,"array","PgVector");this.config.dimensions=T.dimensions}build(o){return new PR(o,this.config)}}class PR extends V{static[y]="PgVector";dimensions=this.config.dimensions;getSQLType(){return`vector(${this.dimensions})`}mapToDriverValue(o){return JSON.stringify(o)}mapFromDriverValue(o){return o.slice(1,-1).split(",").map((T)=>Number.parseFloat(T))}}function iR(o,T){let{name:n,config:f}=So(o,T);return new ZR(n,f)}function gR(){return{bigint:St,bigserial:tt,boolean:Bf,char:Wt,cidr:_t,customType:Kt,date:Yt,doublePrecision:Qt,inet:Bt,integer:YS,interval:jt,json:Nt,jsonb:xt,line:ct,macaddr:it,macaddr8:lt,numeric:TR,point:$R,geometry:yR,real:OR,serial:XR,smallint:ER,smallserial:zR,text:UR,time:BR,timestamp:DT,uuid:RT,varchar:po,bit:bR,halfvec:rR,sparsevec:cR,vector:iR}}var sA=Symbol.for("drizzle:PgInlineForeignKeys"),dR=Symbol.for("drizzle:EnableRLS");class co extends I{static[y]="PgTable";static Symbol=Object.assign({},I.Symbol,{InlineForeignKeys:sA,EnableRLS:dR});[sA]=[];[dR]=!1;[I.Symbol.ExtraConfigBuilder]=void 0;[I.Symbol.ExtraConfigColumns]={}}function Jy(o,T,n,f,S=o){let A=new co(o,f,S),$=typeof T==="function"?T(gR()):T,F=Object.fromEntries(Object.entries($).map(([R,W])=>{let O=W;O.setName(R);let _=O.build(A);return A[sA].push(...O.buildForeignKeys(_,A)),[R,_]})),J=Object.fromEntries(Object.entries($).map(([R,W])=>{let O=W;O.setName(R);let _=O.buildExtraConfigColumn(A);return[R,_]})),t=Object.assign(A,F);if(t[I.Symbol.Columns]=F,t[I.Symbol.ExtraConfigColumns]=J,n)t[co.Symbol.ExtraConfigBuilder]=n;return Object.assign(t,{enableRLS:()=>{return t[co.Symbol.EnableRLS]=!0,t}})}var aT=(o,T,n)=>{return Jy(o,T,n,void 0)};function lR(...o){if(o[0].columns)return new mf(o[0].columns,o[0].name);return new mf(o)}class mf{static[y]="PgPrimaryKeyBuilder";columns;name;constructor(o,T){this.columns=o,this.name=T}build(o){return new uR(o,this.columns,this.name)}}class uR{constructor(o,T,n){this.table=o,this.columns=T,this.name=n}static[y]="PgPrimaryKey";columns;name;getName(){return this.name??`${this.table[co.Symbol.Name]}_${this.columns.map((o)=>o.name).join("_")}_pk`}}class aA{constructor(o,T,n){this.sourceTable=o,this.referencedTable=T,this.relationName=n,this.referencedTableName=T[I.Symbol.Name]}static[y]="Relation";referencedTableName;fieldName}class eR{constructor(o,T){this.table=o,this.config=T}static[y]="Relations"}class on extends aA{constructor(o,T,n,f){super(o,T,n?.relationName);this.config=n,this.isNullable=f}static[y]="One";withFieldName(o){let T=new on(this.sourceTable,this.referencedTable,this.config,this.isNullable);return T.fieldName=o,T}}class Lf extends aA{constructor(o,T,n){super(o,T,n?.relationName);this.config=n}static[y]="Many";withFieldName(o){let T=new Lf(this.sourceTable,this.referencedTable,this.config);return T.fieldName=o,T}}function sR(){return{and:Uf,between:qJ,eq:HS,exists:vJ,gt:LJ,gte:CJ,ilike:PJ,inArray:hJ,isNull:bJ,isNotNull:xJ,like:cJ,lt:IJ,lte:jJ,ne:VJ,not:mJ,notBetween:pJ,notExists:rJ,notLike:ZJ,notIlike:iJ,notInArray:NJ,or:BJ,sql:k}}function aR(){return{sql:k,asc:gJ,desc:dJ}}function o0(o,T){if(Object.keys(o).length===1&&"default"in o&&!X(o.default,I))o=o.default;let n={},f={},S={};for(let[A,$]of Object.entries(o))if(X($,I)){let F=kn($),J=f[F];n[F]=A,S[A]={tsName:A,dbName:$[I.Symbol.Name],schema:$[I.Symbol.Schema],columns:$[I.Symbol.Columns],relations:J?.relations??{},primaryKey:J?.primaryKey??[]};for(let R of Object.values($[I.Symbol.Columns]))if(R.primary)S[A].primaryKey.push(R);let t=$[I.Symbol.ExtraConfigBuilder]?.($[I.Symbol.ExtraConfigColumns]);if(t){for(let R of Object.values(t))if(X(R,mf))S[A].primaryKey.push(...R.columns)}}else if(X($,eR)){let F=kn($.table),J=n[F],t=$.config(T($.table)),R;for(let[W,O]of Object.entries(t))if(J){let _=S[J];if(_.relations[W]=O,R)_.primaryKey.push(...R)}else{if(!(F in f))f[F]={relations:{},primaryKey:R};f[F].relations[W]=O}}return{tables:S,tableNamesMap:n}}function ty(o){return function T(n,f){return new on(o,n,f,f?.fields.reduce((S,A)=>S&&A.notNull,!0)??!1)}}function Ry(o){return function T(n,f){return new Lf(o,n,f)}}function T0(o,T,n){if(X(n,on)&&n.config)return{fields:n.config.fields,references:n.config.references};let f=T[kn(n.referencedTable)];if(!f)throw new Error(`Table "${n.referencedTable[I.Symbol.Name]}" not found in schema`);let S=o[f];if(!S)throw new Error(`Table "${f}" not found in schema`);let A=n.sourceTable,$=T[kn(A)];if(!$)throw new Error(`Table "${A[I.Symbol.Name]}" not found in schema`);let F=[];for(let J of Object.values(S.relations))if(n.relationName&&n!==J&&J.relationName===n.relationName||!n.relationName&&J.referencedTable===n.sourceTable)F.push(J);if(F.length>1)throw n.relationName?new Error(`There are multiple relations with name "${n.relationName}" in table "${f}"`):new Error(`There are multiple relations between "${f}" and "${n.sourceTable[I.Symbol.Name]}". Please specify relation name`);if(F[0]&&X(F[0],on)&&F[0].config)return{fields:F[0].config.references,references:F[0].config.fields};throw new Error(`There is not enough information to infer relation "${$}.${n.fieldName}"`)}function n0(o){return{one:ty(o),many:Ry(o)}}function LS(o,T,n,f,S=(A)=>A){let A={};for(let[$,F]of f.entries())if(F.isJson){let J=T.relations[F.tsKey],t=n[$],R=typeof t==="string"?JSON.parse(t):t;A[F.tsKey]=X(J,on)?R&&LS(o,o[F.relationTableTsKey],R,F.selection,S):R.map((W)=>LS(o,o[F.relationTableTsKey],W,F.selection,S))}else{let J=S(n[$]),t=F.field,R;if(X(t,Wo))R=t;else if(X(t,j))R=t.decoder;else R=t.sql.decoder;A[F.tsKey]=J===null?null:R.mapFromDriverValue(J)}return A}import jy from"node:os";import hy from"node:fs";var CS=new Map,o$=new Map,T$=Symbol("OriginError"),gn={};class wT extends Promise{constructor(o,T,n,f,S={}){let A,$;super((F,J)=>{A=F,$=J});this.tagged=Array.isArray(o.raw),this.strings=o,this.args=T,this.handler=n,this.canceller=f,this.options=S,this.state=null,this.statement=null,this.resolve=(F)=>(this.active=!1,A(F)),this.reject=(F)=>(this.active=!1,$(F)),this.active=!1,this.cancelled=null,this.executed=!1,this.signature="",this[T$]=this.handler.debug?new Error:this.tagged&&My(this.strings)}get origin(){return(this.handler.debug?this[T$].stack:this.tagged&&o$.has(this.strings)?o$.get(this.strings):o$.set(this.strings,this[T$].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(o=1,T){if(this.options.simple=!1,typeof o==="function")T=o,o=1;if(this.cursorRows=o,typeof T==="function")return this.cursorFn=T,this;let n;return{[Symbol.asyncIterator]:()=>({next:()=>{if(this.executed&&!this.active)return{done:!0};n&&n();let f=new Promise((S,A)=>{this.cursorFn=($)=>{return S({value:$,done:!1}),new Promise((F)=>n=F)},this.resolve=()=>(this.active=!1,S({done:!0})),this.reject=($)=>(this.active=!1,A($))});return this.execute(),f},return(){return n&&n(gn),{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(o){return this.forEachFn=o,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 My(o){if(CS.has(o))return CS.get(o);let T=Error.stackTraceLimit;return Error.stackTraceLimit=4,CS.set(o,new Error),Error.stackTraceLimit=T,CS.get(o)}class dn extends Error{constructor(o){super(o.message);this.name=this.constructor.name,Object.assign(this,o)}}var Bo={connection:f0,postgres:S0,generic:A0,notSupported:$0};function f0(o,T,n){let{host:f,port:S}=n||T,A=Object.assign(new Error("write "+o+" "+(T.path||f+":"+S)),{code:o,errno:o,address:T.path||f},T.path?{}:{port:S});return Error.captureStackTrace(A,f0),A}function S0(o){let T=new dn(o);return Error.captureStackTrace(T,S0),T}function A0(o,T){let n=Object.assign(new Error(o+": "+T),{code:o});return Error.captureStackTrace(n,A0),n}function $0(o){let T=Object.assign(new Error(o+" (B) is not supported"),{code:"MESSAGE_NOT_SUPPORTED",name:o});return Error.captureStackTrace(T,$0),T}var yy={string:{to:25,from:null,serialize:(o)=>""+o},number:{to:0,from:[21,23,26,700,701],serialize:(o)=>""+o,parse:(o)=>+o},json:{to:114,from:[114,3802],serialize:(o)=>JSON.stringify(o),parse:(o)=>JSON.parse(o)},boolean:{to:16,from:16,serialize:(o)=>o===!0?"t":"f",parse:(o)=>o==="t"},date:{to:1184,from:[1082,1114,1184],serialize:(o)=>(o instanceof Date?o:new Date(o)).toISOString(),parse:(o)=>new Date(o)},bytea:{to:17,from:17,serialize:(o)=>"\\x"+Buffer.from(o).toString("hex"),parse:(o)=>Buffer.from(o.slice(2),"hex")}};class hS{then(){n$()}catch(){n$()}finally(){n$()}}class hf extends hS{constructor(o){super();this.value=xS(o)}}class CT extends hS{constructor(o,T,n){super();this.value=o,this.type=T,this.array=n}}class NS extends hS{constructor(o,T){super();this.first=o,this.rest=T}build(o,T,n,f){let S=ky.map(([A,$])=>({fn:$,i:o.search(A)})).sort((A,$)=>A.i-$.i).pop();return S.i===-1?F$(this.first,f):S.fn(this.first,this.rest,T,n,f)}}function bS(o,T,n,f){let S=o instanceof CT?o.value:o;if(S===void 0){if(o instanceof CT?o.value=f.transform.undefined:S=o=f.transform.undefined,S===void 0)throw Bo.generic("UNDEFINED_VALUE","Undefined values are not allowed")}return"$"+n.push(o instanceof CT?(T.push(o.value),o.array?o.array[o.type||jS(o.value)]||o.type||R0(o.value):o.type):(T.push(o),jS(o)))}var J0=y0(yy);function A$(o,T,n,f,S,A){for(let $=1;$<o.strings.length;$++)T+=$$(T,n,f,S,A)+o.strings[$],n=o.args[$];return T}function $$(o,T,n,f,S){return T instanceof NS?T.build(o,n,f,S):T instanceof wT?S$(T,n,f,S):T instanceof hf?T.value:T&&T[0]instanceof wT?T.reduce((A,$)=>A+" "+S$($,n,f,S),""):bS(T,n,f,S)}function S$(o,T,n,f){return o.fragment=!0,A$(o,o.strings[0],o.args[0],T,n,f)}function t0(o,T,n,f,S){return o.map((A)=>"("+f.map(($)=>$$("values",A[$],T,n,S)).join(",")+")").join(",")}function F0(o,T,n,f,S){let A=Array.isArray(o[0]),$=T.length?T.flat():Object.keys(A?o[0]:o);return t0(A?o:[o],n,f,$,S)}function IS(o,T,n,f,S){if(typeof o==="string"&&(o=[o].concat(T)),Array.isArray(o))return F$(o,S);let A;return(T.length?T.flat():Object.keys(o)).map((F)=>{return A=o[F],(A instanceof wT?S$(A,n,f,S):A instanceof hf?A.value:bS(A,n,f,S))+" as "+xS(S.transform.column.to?S.transform.column.to(F):F)}).join(",")}var ky=Object.entries({values:F0,in:(...o)=>{let T=F0(...o);return T==="()"?"(null)":T},select:IS,as:IS,returning:IS,"\\(":IS,update(o,T,n,f,S){return(T.length?T.flat():Object.keys(o)).map((A)=>xS(S.transform.column.to?S.transform.column.to(A):A)+"="+$$("values",o[A],n,f,S))},insert(o,T,n,f,S){let A=T.length?T.flat():Object.keys(Array.isArray(o)?o[0]:o);return"("+F$(A,S)+")values"+t0(Array.isArray(o)?o:[o],n,f,A,S)}}).map(([o,T])=>[new RegExp("((?:^|[\\s(])"+o+"(?:$|[\\s(]))(?![\\s\\S]*\\1)","i"),T]);function n$(){throw Bo.generic("NOT_TAGGED_CALL","Query not called as a tagged template literal")}var{serializers:Wy,parsers:Oy}=J0;function R0(o){if(Array.isArray(o))return R0(o[0]);return typeof o==="string"?1009:0}var M0=function(o){let T=y0(o||{});return{serializers:Object.assign({},Wy,T.serializers),parsers:Object.assign({},Oy,T.parsers)}};function y0(o){return Object.keys(o).reduce((T,n)=>{if(o[n].from&&[].concat(o[n].from).forEach((f)=>T.parsers[f]=o[n].parse),o[n].serialize)T.serializers[o[n].to]=o[n].serialize,o[n].from&&[].concat(o[n].from).forEach((f)=>T.serializers[f]=o[n].serialize);return T},{parsers:{},serializers:{}})}function F$(o,{transform:{column:T}}){return o.map((n)=>xS(T.to?T.to(n):n)).join(",")}var xS=function o(T){return'"'+T.replace(/"/g,'""').replace(/\./g,'"."')+'"'},jS=function o(T){return T instanceof CT?T.type:T instanceof Date?1184:T instanceof Uint8Array?17:T===!0||T===!1?16:typeof T==="bigint"?20:Array.isArray(T)?o(T[0]):0},wy=/\\/g,_y=/"/g;function Xy(o){return o.replace(wy,"\\\\").replace(_y,"\\\"")}var k0=function o(T,n,f,S){if(Array.isArray(T)===!1)return T;if(!T.length)return"{}";let A=T[0],$=S===1020?";":",";if(Array.isArray(A)&&!A.type)return"{"+T.map((F)=>o(F,n,f,S)).join($)+"}";return"{"+T.map((F)=>{if(F===void 0){if(F=f.transform.undefined,F===void 0)throw Bo.generic("UNDEFINED_VALUE","Undefined values are not allowed")}return F===null?"null":'"'+Xy(n?n(F.type?F.value:F):""+F)+'"'}).join($)+"}"},f$={i:0,char:null,str:"",quoted:!1,last:0},W0=function o(T,n,f){return f$.i=f$.last=0,O0(f$,T,n,f)};function O0(o,T,n,f){let S=[],A=f===1020?";":",";for(;o.i<T.length;o.i++){if(o.char=T[o.i],o.quoted)if(o.char==="\\")o.str+=T[++o.i];else if(o.char==='"')S.push(n?n(o.str):o.str),o.str="",o.quoted=T[o.i+1]==='"',o.last=o.i+2;else o.str+=o.char;else if(o.char==='"')o.quoted=!0;else if(o.char==="{")o.last=++o.i,S.push(O0(o,T,n,f));else if(o.char==="}"){o.quoted=!1,o.last<o.i&&S.push(n?n(T.slice(o.last,o.i)):T.slice(o.last,o.i)),o.last=o.i+1;break}else if(o.char===A&&o.p!=="}"&&o.p!=='"')S.push(n?n(T.slice(o.last,o.i)):T.slice(o.last,o.i)),o.last=o.i+1;o.p=o.char}return o.last<o.i&&S.push(n?n(T.slice(o.last,o.i+1)):T.slice(o.last,o.i+1)),S}var Wn=(o)=>{let T=o[0];for(let n=1;n<o.length;n++)T+=o[n]==="_"?o[++n].toUpperCase():o[n];return T},On=(o)=>{let T=o[0].toUpperCase();for(let n=1;n<o.length;n++)T+=o[n]==="_"?o[++n].toUpperCase():o[n];return T},wn=(o)=>o.replace(/_/g,"-"),Cf=(o)=>o.replace(/([A-Z])/g,"_$1").toLowerCase(),If=(o)=>(o.slice(0,1)+o.slice(1).replace(/([A-Z])/g,"_$1")).toLowerCase(),jf=(o)=>o.replace(/-/g,"_");function J$(o){return function T(n,f){return typeof n==="object"&&n!==null&&(f.type===114||f.type===3802)?Array.isArray(n)?n.map((S)=>T(S,f)):Object.entries(n).reduce((S,[A,$])=>Object.assign(S,{[o(A)]:T($,f)}),{}):n}}Wn.column={from:Wn};Wn.value={from:J$(Wn)};Cf.column={to:Cf};var t$={...Wn};t$.column.to=Cf;On.column={from:On};On.value={from:J$(On)};If.column={to:If};var R$={...On};R$.column.to=If;wn.column={from:wn};wn.value={from:J$(wn)};jf.column={to:jf};var M$={...wn};M$.column.to=jf;import w0 from"node:net";import Gy from"node:tls";import Nf from"node:crypto";import y$ from"node:stream";import{performance as _0}from"node:perf_hooks";class _n 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 MT=Hy;function Hy(o=[]){let T=o.slice(),n=0;return{get length(){return T.length-n},remove:(f)=>{let S=T.indexOf(f);return S===-1?null:(T.splice(S,1),f)},push:(f)=>(T.push(f),f),shift:()=>{let f=T[n++];if(n===T.length)n=0,T=[];else T[n-1]=void 0;return f}}}var eo=Buffer.allocUnsafe(256),Ky="BCcDdEFfHPpQSX".split("").reduce((o,T)=>{let n=T.charCodeAt(0);return o[T]=()=>{return eo[0]=n,yo.i=5,yo},o},{}),yo=Object.assign(Ey,Ky,{N:String.fromCharCode(0),i:0,inc(o){return yo.i+=o,yo},str(o){let T=Buffer.byteLength(o);return vS(T),yo.i+=eo.write(o,yo.i,T,"utf8"),yo},i16(o){return vS(2),eo.writeUInt16BE(o,yo.i),yo.i+=2,yo},i32(o,T){if(T||T===0)return eo.writeUInt32BE(o,T),yo;return vS(4),eo.writeUInt32BE(o,yo.i),yo.i+=4,yo},z(o){return vS(o),eo.fill(0,yo.i,yo.i+o),yo.i+=o,yo},raw(o){return eo=Buffer.concat([eo.subarray(0,yo.i),o]),yo.i=eo.length,yo},end(o=1){eo.writeUInt32BE(yo.i-o,o);let T=eo.subarray(0,yo.i);return yo.i=0,eo=Buffer.allocUnsafe(256),T}}),c=yo;function vS(o){if(eo.length-yo.i<o){let T=eo,n=T.length;eo=Buffer.allocUnsafe(n+(n>>1)+o),T.copy(eo)}}function Ey(){return yo.i=0,yo}var O$=K0,Yy=1,Tn=c().S().end(),X0=c().H().end(),zy=c().i32(8).i32(80877103).end(8),Dy=Buffer.concat([c().E().str(c.N).i32(0).end(),Tn]),Qy=c().D().str("S").str(c.N).end(),ln=()=>{},Uy=new Set(["FetchPreparedStatement","RevalidateCachedQuery","transformAssignedExpr"]),Vy={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 K0(o,T={},{onopen:n=ln,onend:f=ln,onclose:S=ln}={}){let{ssl:A,max:$,user:F,host:J,port:t,database:R,parsers:W,transform:O,onnotice:_,onnotify:Q,onparameter:H,max_pipeline:m,keep_alive:b,backoff:r,target_session_attrs:P}=o,E=MT(),z=Yy++,U={pid:null,secret:null},D=W$(sS,o.idle_timeout),v=W$(sS,o.max_lifetime),l=W$(p0,o.connect_timeout),K=null,s,q=new _n,a=Buffer.alloc(0),ko=o.fetch_types,mo={},nT={},IT=Math.random().toString(36).slice(2),G=1,p=0,Fo=0,Go=0,Lo=0,To=0,wo=0,Vo=0,Yo=null,Ho=null,Zo=!1,_o=null,_T=null,Po=null,cT=null,Co=null,Ko=null,XT=null,QT=null,B=null,an=null,io={queue:T.closed,idleTimer:D,connect(M){Po=M||!0,p$()},terminate:Tf,execute:of,cancel:x0,end:sS,count:0,id:z};return T.closed&&T.closed.push(io),io;async function b0(){let M;try{M=o.socket?await Promise.resolve(o.socket(o)):new w0.Socket}catch(w){En(w);return}return M.on("error",En),M.on("close",c$),M.on("drain",r$),M}async function x0({pid:M,secret:w},Z,Jo){try{s=c().i32(16).i32(80877102).i32(M).i32(w).end(16),await q$(),K.once("error",Jo),K.once("close",Z)}catch(Do){Jo(Do)}}function of(M){if(Zo)return cf(M,Bo.connection("CONNECTION_DESTROYED",o));if(M.cancelled)return;try{return M.state=U,B?E.push(M):(B=M,B.active=!0),q0(M),ro(v0(M))&&!M.describeFirst&&!M.cursorFn&&E.length<m&&(!M.options.onexecute||M.options.onexecute(io))}catch(w){return E.length===0&&ro(Tn),UT(w),!0}}function v0(M){if(M.parameters.length>=65534)throw Bo.generic("MAX_PARAMETERS_EXCEEDED","Max number of parameters (65534) exceeded");return M.options.simple?c().Q().str(M.statement.string+c.N).end():M.describeFirst?Buffer.concat([b$(M),X0]):M.prepare?M.prepared?pf(M):Buffer.concat([b$(M),pf(M)]):r0(M)}function b$(M){return Buffer.concat([P$(M.statement.string,M.parameters,M.statement.types,M.statement.name),QM("S",M.statement.name)])}function pf(M){return Buffer.concat([DM(M.parameters,M.statement.types,M.statement.name,M.cursorName),M.cursorFn?i$("",M.cursorRows):Dy])}function r0(M){return Buffer.concat([P$(M.statement.string,M.parameters,M.statement.types),Qy,pf(M)])}function q0(M){let w=[],Z=[],Jo=A$(M,M.strings[0],M.args[0],w,Z,o);!M.tagged&&M.args.forEach((Do)=>bS(Do,w,Z,o)),M.prepare=o.prepare&&("prepare"in M.options?M.options.prepare:!0),M.string=Jo,M.signature=M.prepare&&Z+Jo,M.onlyDescribe&&delete nT[M.signature],M.parameters=M.parameters||w,M.prepared=M.prepare&&M.signature in nT,M.describeFirst=M.onlyDescribe||w.length&&!M.prepared,M.statement=M.prepared?nT[M.signature]:{string:Jo,types:Z,name:M.prepare?IT+G++:""},typeof o.debug==="function"&&o.debug(z,Jo,w,Z)}function ro(M,w){if(Ko=Ko?Buffer.concat([Ko,M]):Buffer.from(M),w||Ko.length>=1024)return x$(w);return Ho===null&&(Ho=setImmediate(x$)),!0}function x$(M){let w=K.write(Ko,M);return Ho!==null&&clearImmediate(Ho),Ko=Ho=null,w}function p0(){UT(Bo.connection("CONNECT_TIMEOUT",o,K)),K.destroy()}async function v$(){if(ro(zy),!await new Promise((w)=>K.once("data",(Z)=>w(Z[0]===83)))&&A==="prefer")return Kn();K.removeAllListeners(),K=Gy.connect({socket:K,servername:w0.isIP(K.host)?void 0:K.host,...A==="require"||A==="allow"||A==="prefer"?{rejectUnauthorized:!1}:A==="verify-full"?{}:typeof A==="object"?A:{}}),K.on("secureConnect",Kn),K.on("error",En),K.on("close",c$),K.on("drain",r$)}function r$(){!B&&n(io)}function eS(M){if(_o){if(_o.push(M),Fo-=M.length,Fo>=0)return}a=_o?Buffer.concat(_o,To-Fo):a.length===0?M:Buffer.concat([a,M],a.length+M.length);while(a.length>4){if(To=a.readUInt32BE(1),To>=a.length){Fo=To-a.length,_o=[a];break}try{c0(a.subarray(0,To+1))}catch(w){B&&(B.cursorFn||B.describeFirst)&&ro(Tn),UT(w)}a=a.subarray(To+1),Fo=0,_o=null}}async function q$(){if(Zo=!1,mo={},K||(K=await b0()),!K)return;if(l.start(),o.socket)return A?v$():Kn();if(K.on("connect",A?v$:Kn),o.path)return K.connect(o.path);K.ssl=A,K.connect(t[Go],J[Go]),K.host=J[Go],K.port=t[Go],Go=(Go+1)%t.length}function p$(){setTimeout(q$,p?p+wo-_0.now():0)}function Kn(){try{nT={},ko=o.fetch_types,IT=Math.random().toString(36).slice(2),G=1,v.start(),K.on("data",eS),b&&K.setKeepAlive&&K.setKeepAlive(!0,1000*b);let M=VM();ro(M)}catch(M){En(M)}}function En(M){if(io.queue===T.connecting&&o.host[Lo+1])return;UT(M);while(E.length)cf(E.shift(),M)}function UT(M){Co&&(Co.destroy(M),Co=null),B&&cf(B,M),Po&&(cf(Po,M),Po=null)}function cf(M,w){"query"in w||"parameters"in w||Object.defineProperties(w,{stack:{value:w.stack+M.origin.replace(/.*\n/,`
|
|
17
|
-
|
|
51
|
+
${Y.trace}`:`No previous disposal trace for ${F} was found.`),y}let $=AT(o),_=f.molecules.get($);if(!_){let Y=T.disposalTraces.buffer.find((H)=>H?.key===$);return T.logger.error("\u274C","molecule",y,"claim failed:",`Could not allocate to ${$} in store "${T.config.name}".`,Y?`
|
|
52
|
+
${$} was most recently disposed
|
|
53
|
+
${Y.trace}`:`No previous disposal trace for ${$} was found.`),y}let J=T.moleculeGraph.getRelationEntries({downstreamMoleculeKey:S.stringKey}).filter(([,{source:Y}])=>Y!==F).map(([Y])=>rT(Y));if(A)f.moleculeGraph.delete(F);f.moleculeGraph.set({upstreamMoleculeKey:_.stringKey,downstreamMoleculeKey:S.stringKey},{source:_.stringKey});let R={type:"molecule_transfer",key:S.key,from:J,to:[_.key]};if(XT(f)&&f.transactionMeta.phase==="building")f.transactionMeta.update.updates.push(R);return y}function s$(T,o,y){switch(o){case"newValue":{SW(T,y);break}case"oldValue":{uy(y,T.token);break}}}function a$(T,o,y){switch(o){case"newValue":{uy(y,T.token);break}case"oldValue":{if(SW(T,y),T.subType==="atom")y.valueMap.set(T.token.key,T.value);break}}}function SW(T,o){let{family:y}=T.token;if(y){let A=o.families.get(y.key);if(A)c(o,A,rT(y.subKey))}}function $W(T,o,y){switch(o){case"newValue":hy(y,T.provenance,T.key);break;case"oldValue":ny(y,T.key);break}}function JW(T,o,y){switch(o){case"newValue":ny(y,T.key);break;case"oldValue":{let A=T.provenance.map(rT);hy(y,A,T.key);for(let[F,f]of T.values){let S=y.families.get(F);if(S){c(y,S,T.key);let $=`${F}(${AT(T.key)})`;y.valueMap.set($,f)}}}break}}function _W(T,o,y){switch(o){case"newValue":{let A=T.to.length===1?T.to[0]:T.to;KA(y,A,T.key,"exclusive")}break;case"oldValue":{let A=T.from.length===1?T.from[0]:T.from;KA(y,A,T.key,"exclusive")}break}}function Nf(T,o,y){let A=T==="newValue"?o.updates:[...o.updates].reverse();for(let F of A)switch(F.type){case"atom_update":case"selector_update":Bf(T,F,y);break;case"state_creation":s$(F,T,y);break;case"state_disposal":a$(F,T,y);break;case"molecule_creation":$W(F,T,y);break;case"molecule_disposal":JW(F,T,y);break;case"molecule_transfer":_W(F,T,y);break;case"transaction_update":Nf(T,F,y);break}}function e$(T,o){return T.transactionMeta.actionContinuities.getRelatedKey(o)}function yZ(T,o){return T.transactionMeta.epoch.get(o)}function RW(T,o){if(!aT(T))return;let A=e$(T,o);if(A===void 0)return;return yZ(T,A)}function WW(T,o,y){if(aT(T)&&o)T.transactionMeta.epoch.set(o,y)}function OW(T,o,y){if(!aT(T))return;let F=e$(T,o);if(F!==void 0)T.transactionMeta.epoch.set(F,y)}var MW=(T,o)=>{let y=p(o),{parent:A}=y;if(A===null||!XT(y)||y.transactionMeta?.phase!=="building"){o.logger.warn("\uD83D\uDC1E","transaction","???","applyTransaction called outside of a transaction. This is probably a bug in AtomIO.");return}y.transactionMeta.phase="applying",y.transactionMeta.update.output=T,A.child=null,A.on.transactionApplying.next(y.transactionMeta);let{updates:F}=y.transactionMeta.update;if(o.logger.info("\uD83D\uDEC4","transaction",y.transactionMeta.update.key,`Applying transaction with ${F.length} updates:`,F),Nf("newValue",y.transactionMeta.update,A),aT(A))OW(A,y.transactionMeta.update.key,y.transactionMeta.update.epoch),_T(o,{key:y.transactionMeta.update.key,type:"transaction"})?.subject.next(y.transactionMeta.update),o.logger.info("\uD83D\uDEEC","transaction",y.transactionMeta.update.key,"Finished applying transaction.");else if(XT(A))A.transactionMeta.update.updates.push(y.transactionMeta.update);A.on.transactionApplying.next(null)};function XW(T,o,y){if(!aT(T))return;let{epoch:F,actionContinuities:f}=T.transactionMeta;if(f.set(o,y),!F.has(o))F.set(o,-1)}function YW(T){return{store:T}}function OT(T,...o){let y,A,F;if(o.length===1)y=o[0];else A=o[0],F=o[1],y=c(T,A,F);if("counterfeit"in y&&"family"in y){A=T.families.get(y.family.key);let f=y.family.subKey,S=T.disposalTraces.buffer.find(($)=>$?.key===f);switch(T.logger.error("\u274C",y.type,y.key,`could not be retrieved because it was not found in the store "${T.config.name}".`,S?`This state was previously disposed:
|
|
54
|
+
${S.trace}`:"No previous disposal trace was found."),A.type){case"atom_family":case"mutable_atom_family":return T.defaults.get(A.key);case"selector_family":case"readonly_selector_family":{if(T.defaults.has(A.key))return T.defaults.get(y.family.key);let $=_T(T,A).default(f);return T.defaults.set(A.key,$),$}}}return ky(T,_T(T,y))}class uT{a;b;cardinality;relations=new Map;contents=new Map;isAType;isBType;isContent;makeContentKey=(T,o)=>`${T}:${o}`;warn;getRelatedKeys(T){return this.relations.get(T)}addRelation(T,o){let y=this.relations.get(T),A=this.relations.get(o);if(y)y.add(o);else y=new Set([o]),this.relations.set(T,y);if(A)A.add(T);else A=new Set([T]),this.relations.set(o,A)}deleteRelation(T,o){let y=this.relations.get(T);if(y){if(y.delete(o),y.size===0)this.relations.delete(T);let A=this.relations.get(o);if(A){if(A.delete(T),A.size===0)this.relations.delete(o)}}}replaceRelationsUnsafely(T,o){this.relations.set(T,new Set(o));for(let y of o){let A=new Set().add(T);this.relations.set(y,A)}}replaceRelationsSafely(T,o){let y=this.relations.get(T),A=this.isAType?.(T)?T:void 0,F=A===void 0?T:void 0;if(y)for(let f of y){A??=f,F??=f;let S=this.relations.get(f);if(S){if(S.size===1)this.relations.delete(f);else S.delete(T);this.contents.delete(this.makeContentKey(A,F))}}this.relations.set(T,new Set(o));for(let f of o){let S=this.relations.get(f);if(S)S.add(T);else S=new Set().add(T),this.relations.set(f,S)}}getContentInternal(T){return this.contents.get(T)}setContent(T,o){this.contents.set(T,o)}deleteContent(T){this.contents.delete(T)}constructor(T,o){if(this.a=T.between[0],this.b=T.between[1],this.cardinality=T.cardinality,!o?.externalStore)this.relations=new Map(T.relations?.map(([y,A])=>[y,new Set(A)])),this.contents=new Map(T.contents);if(this.isAType=o?.isAType??null,this.isBType=o?.isBType??null,this.isContent=o?.isContent??null,o?.makeContentKey)this.makeContentKey=o.makeContentKey;if(o?.externalStore){let y=o.externalStore;if(this.has=(A,F)=>y.has(A,F),this.addRelation=(A,F)=>{y.addRelation(A,F)},this.deleteRelation=(A,F)=>{y.deleteRelation(A,F)},this.replaceRelationsSafely=(A,F)=>{y.replaceRelationsSafely(A,F)},this.replaceRelationsUnsafely=(A,F)=>{y.replaceRelationsUnsafely(A,F)},this.getRelatedKeys=(A)=>y.getRelatedKeys(A),y.getContent)this.getContentInternal=(A)=>{return y.getContent(A)},this.setContent=(A,F)=>{y.setContent(A,F)},this.deleteContent=(A)=>{y.deleteContent(A)};for(let[A,F]of T.relations??[]){let f=this.isAType?.(A)?A:void 0,S=f===void 0?A:void 0;for(let $ of F)f??=$,S??=$,this.addRelation(f,S)}for(let[A,F]of T.contents??[])this.setContent(A,F)}if(o?.warn)this.warn=o.warn}toJSON(){return{between:[this.a,this.b],cardinality:this.cardinality,relations:[...this.relations.entries()].map(([T,o])=>[T,[...o]]),contents:[...this.contents.entries()]}}set(...T){let o,y,A;switch(T.length){case 1:{let F=T[0];o=F[this.a],y=F[this.b],A=void 0;break}case 2:{let F=T[0];if(typeof F==="string")[o,y]=T;else o=F[this.a],y=F[this.b],A=T[1];break}default:{o=T[0],y=T[1],A=T[2];break}}switch(this.cardinality){case"1:1":{let F=this.getRelatedKey(o);if(F&&F!==y)this.delete(o,F)}case"1:n":{let F=this.getRelatedKey(y);if(F&&F!==o)this.delete(F,y)}break;case"n:n":}if(A){let F=this.makeContentKey(o,y);this.setContent(F,A)}return this.addRelation(o,y),this}delete(T,o){o=typeof o==="string"?o:T[this.b];let y=typeof T==="string"?T:T[this.a];if(y===void 0&&typeof o==="string"){let A=this.getRelatedKeys(o);if(A)for(let F of A)this.delete(F,o)}if(typeof y==="string"&&o===void 0){let A=this.getRelatedKeys(y);if(A)for(let F of A)this.delete(y,F)}if(typeof y==="string"&&typeof o==="string"){this.deleteRelation(y,o);let A=this.makeContentKey(y,o);this.deleteContent(A)}return this}getRelatedKey(T){let o=this.getRelatedKeys(T);if(o){if(o.size>1)this.warn?.(`${o.size} related keys were found for key "${T}": (${[...o].map((A)=>`"${A}"`).join(", ")}). Only one related key was expected.`);let y;for(let A of o){y=A;break}return y}}replaceRelations(T,o,y){let A=!Array.isArray(o),F=A?Object.keys(o):o;if(y?.reckless)this.replaceRelationsUnsafely(T,F);else this.replaceRelationsSafely(T,F);if(A)for(let f of F){let S=this.makeContentKey(T,f),$=o[f];this.setContent(S,$)}return this}getContent(T,o){let y=this.makeContentKey(T,o);return this.getContentInternal(y)}getRelationEntries(T){let o=T[this.a],y=T[this.b];if(o!==void 0&&y===void 0){let A=this.getRelatedKeys(o);if(A)return[...A].map((F)=>{return[F,this.getContent(o,F)]})}if(o===void 0&&y!==void 0){let A=this.getRelatedKeys(y);if(A)return[...A].map((F)=>{return[F,this.getContent(F,y)]})}return[]}has(T,o){if(o)return this.getRelatedKeys(T)?.has(o)??!1;return this.relations.has(T)}}class xo extends Map{deleted=new Set;source;constructor(T){super();this.source=T}get(T){if(super.has(T))return super.get(T);if(!this.deleted.has(T)&&this.source.has(T))return this.source.get(T);return}set(T,o){return this.deleted.delete(T),super.set(T,o)}hasOwn(T){return super.has(T)}has(T){return!this.deleted.has(T)&&(super.has(T)||this.source.has(T))}delete(T){return this.deleted.add(T),super.delete(T)}}var ZW=(T,o,y,A)=>{let F=p(T),f={parent:F,child:null,on:F.on,loggers:F.loggers,logger:F.logger,config:F.config,atoms:new xo(F.atoms),atomsThatAreDefault:new Set(F.atomsThatAreDefault),families:new xo(F.families),joins:new xo(F.joins),operation:{open:!1},readonlySelectors:new xo(F.readonlySelectors),timelines:new xo(F.timelines),timelineTopics:new uT(F.timelineTopics.toJSON()),trackers:new Map,transactions:new xo(F.transactions),selectorAtoms:new uT(F.selectorAtoms.toJSON()),selectorGraph:new uT(F.selectorGraph.toJSON(),{makeContentKey:(...J)=>J.sort().join(":")}),selectors:new xo(F.selectors),valueMap:new xo(F.valueMap),defaults:F.defaults,disposalTraces:T.disposalTraces.copy(),molecules:new xo(F.molecules),moleculeGraph:new uT(F.moleculeGraph.toJSON(),{makeContentKey:F.moleculeGraph.makeContentKey}),moleculeData:new uT(F.moleculeData.toJSON(),{makeContentKey:F.moleculeData.makeContentKey}),moleculeJoins:new uT(F.moleculeJoins.toJSON(),{makeContentKey:F.moleculeJoins.makeContentKey}),miscResources:new xo(F.miscResources)},S=RW(T,o),$={phase:"building",update:{type:"transaction_update",key:o,id:A,epoch:S===void 0?Number.NaN:S+1,updates:[],params:y,output:void 0},toolkit:{get:(...J)=>OT(_,...J),set:(...J)=>{bT(_,...J)},run:(J,R=zf())=>zA(_,J,R),find:(J,R)=>c(_,J,R),json:(J)=>gT(_,J),dispose:(...J)=>{uy(_,...J)},env:()=>YW(_)}},_=Object.assign(f,{transactionMeta:$});return F.child=_,T.logger.info("\uD83D\uDEEB","transaction",o,"Building transaction with params:",y),_};function TJ(T,o){let y={key:o.key,type:"transaction",run:(f,S)=>{let $=ZW(T,o.key,f,S);try{let _=p(T),{toolkit:J}=$.transactionMeta,R=o.do(J,...f);return MW(R,_),R}catch(_){throw cR(A),T.logger.warn("\uD83D\uDCA5","transaction",o.key,"caught:",_),_}},install:(f)=>TJ(f,o),subject:new oT},A=p(T);A.transactions.set(y.key,y);let F=wo(y);return T.on.transactionCreation.next(F),F}function UF(T){return TJ(fT.STORE,T)}class HW{parent=null;child=null;valueMap=new Map;defaults=new Map;atoms=new Map;selectors=new Map;readonlySelectors=new Map;atomsThatAreDefault=new Set;selectorAtoms=new uT({between:["selectorKey","atomKey"],cardinality:"n:n"});selectorGraph=new uT({between:["upstreamSelectorKey","downstreamSelectorKey"],cardinality:"n:n"},{makeContentKey:(...T)=>T.sort().join(":")});trackers=new Map;families=new Map;joins=new Map;transactions=new Map;transactionMeta={epoch:new Map,actionContinuities:new uT({between:["continuity","action"],cardinality:"1:n"})};timelines=new Map;timelineTopics=new uT({between:["timelineKey","topicKey"],cardinality:"1:n"});disposalTraces=new Vf(100);molecules=new Map;moleculeJoins=new uT({between:["moleculeKey","joinKey"],cardinality:"n:n"},{makeContentKey:(...T)=>T.sort().join(":")});moleculeGraph=new uT({between:["upstreamMoleculeKey","downstreamMoleculeKey"],cardinality:"n:n"},{makeContentKey:(...T)=>T.sort().join(":")});moleculeData=new uT({between:["moleculeKey","stateFamilyKey"],cardinality:"n:n"},{makeContentKey:(...T)=>T.sort().join(":")});miscResources=new Map;on={atomCreation:new oT,atomDisposal:new oT,selectorCreation:new oT,selectorDisposal:new oT,timelineCreation:new oT,transactionCreation:new oT,transactionApplying:new u$(null),operationClose:new oT,moleculeCreation:new oT,moleculeDisposal:new oT};operation={open:!1};config={name:"IMPLICIT_STORE",lifespan:"ephemeral"};loggers=[new d$("warn",(T,o,y)=>!By(y))];logger={error:(...T)=>{for(let o of this.loggers)o.error(...T)},info:(...T)=>{for(let o of this.loggers)o.info(...T)},warn:(...T)=>{for(let o of this.loggers)o.warn(...T)}};constructor(T,o=null){if(this.config={...o?.config,...T},o!==null){if(this.valueMap=new Map(o?.valueMap),this.operation={...o?.operation},aT(o))this.transactionMeta={epoch:new Map(o?.transactionMeta.epoch),actionContinuities:new uT(o?.transactionMeta.actionContinuities.toJSON())};for(let[,A]of o.families){if(A.internalRoles?.includes("mutable")||A.internalRoles?.includes("join"))continue;A.install(this)}let y=new Set;for(let[,A]of o.atoms){if(y.has(A.key))continue;if(A.install(this),A.type==="mutable_atom"){let F=gT(o,A),f=Zy(A);y.add(F.key),y.add(f.key)}}for(let[,A]of o.readonlySelectors)A.install(this);for(let[,A]of o.selectors){if(y.has(A.key))continue;A.install(this)}for(let[,A]of o.transactions)A.install(this);for(let[,A]of o.timelines)A.install(this)}}}var fT={get STORE(){return globalThis.ATOM_IO_IMPLICIT_STORE??=new HW({name:"IMPLICIT_STORE",lifespan:"ephemeral"}),globalThis.ATOM_IO_IMPLICIT_STORE}};function _T(T,o){let y,A=T;while(A!==null){switch(o.type){case"atom":case"mutable_atom":y=A.atoms.get(o.key);break;case"selector":y=A.selectors.get(o.key);break;case"readonly_selector":y=A.readonlySelectors.get(o.key);break;case"atom_family":case"mutable_atom_family":case"selector_family":case"readonly_selector_family":y=A.families.get(o.key);break;case"timeline":y=A.timelines.get(o.key);break;case"transaction":y=A.transactions.get(o.key);break}if(y)return y;A=A.child}throw new gy(o,T)}function EW(T,o,y){let A=T.families.get(o.key);if(A===void 0)throw new gy(o,T);let F=A(y),f=p(T);if(F.family){if(aT(f))switch(F.type){case"atom":case"mutable_atom":T.on.atomCreation.next(F);break;case"selector":case"readonly_selector":T.on.selectorCreation.next(F);break}else if(XT(f)&&f.on.transactionApplying.state===null)f.transactionMeta.update.updates.push({type:"state_creation",token:F})}return F}function GW(T,o,y){let A=AT(y),F=`${o.key}(${A})`,f=p(T),S;switch(o.type){case"atom_family":case"mutable_atom_family":S=f.atoms.get(F);break;case"selector_family":S=f.selectors.get(F);break;case"readonly_selector_family":S=f.readonlySelectors.get(F);break}if(S)return wo(S);return S}function c(T,o,y){let A=GW(T,o,y);if(A)return A;let F=AT(y),f=T.molecules.get(F);if(!f&&T.config.lifespan==="immortal"){let S=qR(o,y);return T.logger.error("\u274C",S.type,S.key,`was not found in store "${T.config.name}"; returned a counterfeit token.`),S}if(A=EW(T,o,y),f)p(T).moleculeData.set(F,o.key);return A}function uy(T,...o){let y;if(o.length===1)y=o[0];else{let A=o[0],F=o[1];y=c(T,A,F)}try{_T(T,y)}catch(A){T.logger.error("\u274C",y.type,y.key,`could not be disposed because it was not found in the store "${T.config.name}".`);return}switch(y.type){case"atom":case"mutable_atom":oJ(T,y);break;case"selector":case"readonly_selector":wW(T,y);break}}var tf=(T,o)=>p(T).atoms.has(o),AZ=(T,o)=>p(T).selectors.has(o),FZ=(T,o)=>p(T).readonlySelectors.has(o),UW=(T,o)=>tf(T,o)||AZ(T,o)||FZ(T,o);var pf=(T,o)=>{return p(o).selectorGraph.getRelationEntries({downstreamSelectorKey:T}).filter(([A,{source:F}])=>F!==T).map(([A,{source:F}])=>F).filter((A)=>UW(o,A))};var yJ=(T,o,y)=>{let A=[],F=pf(T,y);while(F.length>0){let f=F.shift();if(o.has(f))continue;if(o.add(f),!tf(y,f))F.push(...pf(f,y));else if(!A.includes(f))A.push(f)}return A},KW=(T,o)=>{let y=T.key,A=pf(y,o),F=new Set;return A.flatMap((f)=>tf(o,f)?f:yJ(f,F,o))};var zW=(T,o,y,A)=>{let F=p(A);if(o.type==="atom"||o.type==="mutable_atom")F.selectorAtoms.set({selectorKey:T,atomKey:o.key}),A.logger.info("\uD83D\uDD0D","selector",T,`discovers root atom "${o.key}"`);else{let f=yJ(o.key,y,A);A.logger.info("\uD83D\uDD0D","selector",T,`discovers root atoms: [ ${f.map((S)=>`"${S}"`).join(", ")} ]`);for(let S of f)F.selectorAtoms=F.selectorAtoms.set({selectorKey:T,atomKey:S})}y.add(o.key)};var bf=(T,o,y)=>({get:(...A)=>{let F=p(y),f;if(A.length===2){let[_,J]=A;f=c(y,_,J)}else[f]=A;let S=_T(y,f),$=ky(y,S);return y.logger.info("\uD83D\uDD0C","selector",T,`registers dependency ( "${f.key}" =`,$,")"),F.selectorGraph.set({upstreamSelectorKey:f.key,downstreamSelectorKey:T},{source:f.key}),zW(T,f,o,y),$},set:(...A)=>{let F,f;if(A.length===2)F=A[0],f=A[1];else{let _=A[0],J=A[1];f=A[2],F=c(y,_,J)}let S=p(y),$=_T(S,F);kf(S,$,f)},find:(A,F)=>c(y,A,F),json:(A)=>gT(y,A)});var ZF=(T,o,y)=>{let A=p(T),F=new oT,f=new Set,{get:S,find:$,json:_}=bf(o.key,f,A),J=()=>{let H=o.get({get:S,find:$,json:_});return bo(p(T),o.key,H,F),f.clear(),H},R={...o,subject:F,install:(H)=>ZF(H,o,y),get:J,type:"readonly_selector",...y&&{family:y}};A.readonlySelectors.set(o.key,R);let M=J();T.logger.info("\u2728",R.type,R.key,"=",M);let Y={key:o.key,type:"readonly_selector"};if(y)Y.family=y;return Y};var KF=(T,o,y)=>{let A=p(T),F=new oT,f=new Set,S=bf(o.key,f,A),{find:$,get:_,json:J}=S,R={find:$,get:_,json:J},M=(B=o.get,t=p(T))=>{let m=B(R);return bo(t,o.key,m,F),f.clear(),m},H={...o,subject:F,install:(B)=>KF(B,o,y),get:M,set:(B)=>{let t=p(T),m=M(o.get,t),h=If(B)(m);if(T.logger.info("\uD83D\uDCDD","selector",o.key,"set (",m,"->",h,")"),bo(t,o.key,h,F),QA(t,o.key),aT(t))F.next({newValue:h,oldValue:m});o.set(S,h)},type:"selector",...y&&{family:y}};A.selectors.set(o.key,H);let Q=M();T.logger.info("\u2728",H.type,H.key,"=",Q);let w={key:o.key,type:"selector"};if(y)w.family=y;return w};function My(T,o){if("set"in o){let F=KF(T,o,void 0);return T.on.selectorCreation.next(F),F}let A=ZF(T,o,void 0);return T.on.selectorCreation.next(A),A}function wW(T,o){let y=p(T),{key:A}=o,F=_T(y,o);if(!F.family)T.logger.error("\u274C","selector",A,"Standalone selectors cannot be disposed.");else{if(y.molecules.get(F.family.subKey))y.moleculeData.delete(F.family.subKey,F.family.key);let S;switch(o.type){case"selector":y.selectors.delete(A),S={key:F.family.key,type:"selector_family"},_T(T,S).subject.next({type:"state_disposal",subType:"selector",token:o});break;case"readonly_selector":y.readonlySelectors.delete(A),S={key:F.family.key,type:"readonly_selector_family"},_T(T,S).subject.next({type:"state_disposal",subType:"selector",token:o});break}if(y.valueMap.delete(A),y.selectorAtoms.delete(A),y.selectorGraph.delete(A),T.logger.info("\uD83D\uDD25",o.type,A,"deleted"),XT(y)&&y.transactionMeta.phase==="building")y.transactionMeta.update.updates.push({type:"state_disposal",subType:"selector",token:o});else T.on.selectorDisposal.next(o)}}function HF(T,o,y){let A={key:o.key,type:"selector_family"},F=T.families.get(o.key);if(F)T.logger.error("\u2757","selector_family",o.key,`Overwriting an existing ${Ty(F)} "${F.key}" in store "${T.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);let f=new oT,$=Object.assign((_)=>{let J=AT(_),R={key:o.key,subKey:J},M=`${o.key}(${J})`,Y=p(T),H=KF(Y,{key:M,get:o.get(_),set:o.set(_)},R);return f.next({type:"state_creation",token:H}),H},A,{internalRoles:y,subject:f,install:(_)=>HF(_,o),default:(_)=>{return o.get(_)({get:(...R)=>OT(T,...R),find:(R,M)=>c(T,R,M),json:(R)=>gT(T,R)})}});return T.families.set(o.key,$),A}function QW(T,o,y){return HF(T,{key:`${o.key}:JSON`,get:(F)=>({get:f})=>{let S=f(o,F);return y.toJson(S)},set:(F)=>({set:f},S)=>{f(o,F,y.fromJson(S))}},["mutable","json"])}var rT=(T)=>JSON.parse(T),AT=(T)=>JSON.stringify(T),yI=[Array.prototype,Boolean.prototype,Number.prototype,Object.prototype,String.prototype];var VW=(T,o)=>{let y=p(T);if(y.operation.open)return y.operation.prev.get(o.key);return y.valueMap.get(o.key)};var fJ=(T,o)=>{let y=p(T);return KW(o,T).map((F)=>{let f=y.atoms.get(F);if(f===void 0)throw new Error(`Atom "${F}", a dependency of selector "${o.key}", not found in store "${T.config.name}".`);return f.subject.subscribe(`${o.type}:${o.key}`,(S)=>{T.logger.info("\uD83D\uDCE2",o.type,o.key,"root",F,"went",S.oldValue,"->",S.newValue);let $=VW(y,o),_=ky(y,o);T.logger.info("\u2728",o.type,o.key,"went",$,"->",_),o.subject.next({newValue:_,oldValue:$})})})};function $o(T,o,y,A){function F(M){if(T.operation.open){let Y=T.on.operationClose.subscribe(`state subscription ${y}`,()=>{Y(),A(M)})}else A(M)}let f=_T(T,o);T.logger.info("\uD83D\uDC40",f.type,f.key,`Adding subscription "${y}"`);let S=f.type==="selector"||f.type==="readonly_selector",$=null,_=F;if(S)$=fJ(T,f),_=(M)=>{if($)$.length=0,$.push(...fJ(T,f));F(M)};let J=f.subject.subscribe(y,_);return()=>{if(T.logger.info("\uD83D\uDE48",f.type,f.key,`Removing subscription "${y}"`),J(),$)for(let M of $)M()}}var AJ=(T,o,y,A)=>{let F=_T(T,o);T.logger.info("\uD83D\uDC40","timeline",o.key,`Adding subscription "${y}"`);let f=F.subject.subscribe(y,A);return()=>{T.logger.info("\uD83D\uDE48","timeline",o.key,`Removing subscription "${y}" from timeline`),f()}};var FJ=(T,o,y,A)=>{let F=_T(T,o);T.logger.info("\uD83D\uDC40","transaction",o.key,`Adding subscription "${y}"`);let f=F.subject.subscribe(y,A);return()=>{T.logger.info("\uD83D\uDE48","transaction",o.key,`Removing subscription "${y}"`),f()}};class iy{Update;initializeState(T,o){let y=`*${T.key}`;o.atoms.delete(y),o.valueMap.delete(y);let A=T.family?{key:`*${T.family.key}`,subKey:T.family.subKey}:void 0,F=Do(o,{key:y,default:null},A);if(o.parent?.valueMap.has(y)){let f=o.parent.valueMap.get(y);o.valueMap.set(y,f)}return F}unsubscribeFromInnerValue;unsubscribeFromState;observeCore(T,o,y){let A=`tracker:${y.config.name}:${XT(y)?y.transactionMeta.update.key:"main"}:${T.key}`,F=OT(y,T);this.unsubscribeFromInnerValue=F.subscribe(A,(f)=>{bT(y,o,f)}),this.unsubscribeFromState=$o(y,T,A,(f)=>{if(f.newValue!==f.oldValue)this.unsubscribeFromInnerValue(),this.unsubscribeFromInnerValue=f.newValue.subscribe(A,(S)=>{bT(y,o,S)})})}updateCore(T,o,y){let A=`tracker:${y.config.name}:${XT(y)?y.transactionMeta.update.key:"main"}:${T.key}`;$o(y,o,A,({newValue:F,oldValue:f})=>{let S=y.timelineTopics.getRelatedKey(o.key);if(S){if(y.timelines.get(S)?.timeTraveling){let J=AJ(y,{key:S,type:"timeline"},A,(R)=>{J(),bT(y,T,(M)=>{if(R==="redo"&&F)M.do(F);else if(R==="undo"&&f)M.undo(f);return M})});return}}let $=y.on.operationClose.subscribe(A,()=>{$();let _=OT(y,T),J=F===null?-1:_.getUpdateNumber(F),R=J-_.cacheUpdateNumber;if(F&&R===1)bT(y,T,(M)=>(M.do(F),M));else y.logger.info("\u274C","mutable_atom",T.key,`could not be updated. Expected update number ${_.cacheUpdateNumber+1}, but got ${J}`)})})}mutableState;latestUpdateState;[Symbol.dispose];constructor(T,o){this.mutableState=T;let y=p(o);this.latestUpdateState=this.initializeState(T,y),this.observeCore(T,this.latestUpdateState,y),this.updateCore(T,this.latestUpdateState,y),y.trackers.set(T.key,this),this[Symbol.dispose]=()=>{this.unsubscribeFromInnerValue(),this.unsubscribeFromState(),y.trackers.delete(T.key)}}}function zF(T,o,y){T.logger.info("\uD83D\uDD28","atom",o.key,`creating in store "${T.config.name}"`);let A=p(T),F=A.atoms.get(o.key);if(F&&F.type==="mutable_atom")return T.logger.error("\u274C","atom",o.key,"Tried to create atom, but it already exists in the store."),wo(F);let f=new oT,S={...o,type:"mutable_atom",install:(J)=>{return J.logger.info("\uD83D\uDEE0\uFE0F","atom",o.key,`installing in store "${J.config.name}"`),zF(J,o,y)},subject:f};if(y)S.family=y;let $=o.default();A.atoms.set(S.key,S),xf(T,o.key),bo(A,o.key,$,f);let _=wo(S);if(o.effects){let J=0,R=[];for(let M of o.effects){let Y=M({setSelf:(H)=>{bT(T,_,H)},onSet:(H)=>$o(T,_,`effect[${J}]`,H)});if(Y)R.push(Y);++J}S.cleanup=()=>{for(let M of R)M()}}if(new iy(_,T),!y)jR(_,o,T);return _}class SJ{trackers=new Map;Update;latestUpdateAtoms;mutableAtoms;constructor(T,o){let y=Xy(o,{key:`*${T.key}`,default:null},["mutable","updates"]);this.latestUpdateAtoms=_T(o,y),this.mutableAtoms=T,this.mutableAtoms.subject.subscribe(`store=${o.config.name}::tracker-atom-family`,(A)=>{let{type:F,token:f}=A;if(f.family){let S=rT(f.family.subKey);switch(F){case"state_creation":this.trackers.set(S,new iy(f,o));break;case"state_disposal":{let $=this.trackers.get(S);if($)$[Symbol.dispose](),this.trackers.delete(S)}break}}})}}function YF(T,o,y){let A={key:o.key,type:"mutable_atom_family"},F=T.families.get(o.key);if(F)T.logger.error("\u2757","mutable_atom_family",o.key,`Overwriting an existing ${Ty(F)} "${F.key}" in store "${T.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);let f=new oT,$=Object.assign((_)=>{let J=AT(_),R={key:o.key,subKey:J},M=`${o.key}(${J})`,Y=p(T),H={key:M,default:()=>o.default(_),toJson:o.toJson,fromJson:o.fromJson,mutable:!0};if(o.effects)H.effects=o.effects(_);let Q=zF(Y,H,R);return f.next({type:"state_creation",token:Q}),Q},A,{subject:f,install:(_)=>YF(_,o),toJson:o.toJson,fromJson:o.fromJson,internalRoles:y});return T.families.set(o.key,$),QW(T,$,o),new SJ($,T),A}var $J=(T,o)=>{let y=p(o),A=`${T.key}:JSON`;return y.families.get(A)};var gT=(T,o)=>{if(o.family){let A=p(T),f={key:`${o.family.key}:JSON`,type:"selector_family"},S=_T(A,f),$=JSON.parse(o.family.subKey);return c(T,S,$)}return{type:"selector",key:`${o.key}:JSON`}};var Zy=(T)=>{let y={type:"atom",key:`*${T.key}`};if(T.family)y.family={key:`*${T.family.key}`,subKey:T.family.subKey};return y};function oW(T){return typeof T==="object"&&T!==null&&"do"in T&&"undo"in T&&"subscribe"in T}function wF(T,o,y){let A=y.valueMap.get(o.key),F=T.valueMap.get(o.key);if(A!==F)return F;if(A===void 0)return o.default();y.logger.info("\uD83D\uDCC3","atom",o.key,"copying");let f=o.toJson(A),S=o.fromJson(f);return T.valueMap.set(o.key,S),new iy(o,y),S}function bo(T,o,y,A){let F=T.valueMap.get(o);if(F instanceof XF)F.use(y);if(y instanceof Promise){let f=new XF(y);return T.valueMap.set(o,f),f.then((S)=>{bo(T,o,S,A),A.next({newValue:S,oldValue:f})}).catch((S)=>{T.logger.error("\uD83D\uDCA5","state",o,"rejected:",S)}),f}return T.valueMap.set(o,y),y}var dR=(T,o)=>{let y=o.valueMap.get(T.key);if(T.type==="mutable_atom"&&XT(o)){let{parent:A}=o;y=wF(o,T,A)}return y},eR=(T,o)=>{let y=o.valueMap.get(T);if(y instanceof XF){let A=y,F=o.selectors.get(T)??o.readonlySelectors.get(T);if(F)A.use(F.get());return}if(o.operation.open)o.operation.prev.set(T,y);o.valueMap.delete(T),o.logger.info("\uD83D\uDDD1","state",T,"evicted")};var yW=(T,o)=>{return p(T).atomsThatAreDefault.has(o)},xf=(T,o)=>{let y=p(T);y.atomsThatAreDefault=new Set(y.atomsThatAreDefault).add(o)},AW=(T,o)=>{let y=p(T);y.atomsThatAreDefault=new Set(p(T).atomsThatAreDefault),y.atomsThatAreDefault.delete(o)};function Do(T,o,y){T.logger.info("\uD83D\uDD28","atom",o.key,`creating in store "${T.config.name}"`);let A=p(T),F=A.atoms.get(o.key);if(F&&F.type==="atom")return T.logger.error("\u274C","atom",o.key,"Tried to create atom, but it already exists in the store."),wo(F);let f=new oT,S={...o,type:"atom",install:(J)=>{return J.logger.info("\uD83D\uDEE0\uFE0F","atom",o.key,`installing in store "${J.config.name}"`),Do(J,o,y)},subject:f};if(y)S.family=y;let $=o.default;if(o.default instanceof Function)$=o.default();A.atoms.set(S.key,S),xf(T,o.key),bo(A,o.key,$,f);let _=wo(S);if(o.effects){let J=0,R=[];for(let M of o.effects){let Y=M({setSelf:(H)=>{bT(T,_,H)},onSet:(H)=>$o(T,_,`effect[${J}]`,H)});if(Y)R.push(Y);++J}S.cleanup=()=>{for(let M of R)M()}}return _}function vR(T,o){if("mutable"in o){let F=zF(T,o,void 0);return T.on.atomCreation.next(F),F}let A=Do(T,o,void 0);return T.on.atomCreation.next(A),A}function oJ(T,o){let y=p(T),{key:A,family:F}=o,f=_T(y,o);if(!F)T.logger.error("\u274C","atom",A,"Standalone atoms cannot be disposed.");else{f.cleanup?.();let S=T.valueMap.get(f.key),$=_T(T,{key:F.key,type:"atom_family"}),_={type:"state_disposal",subType:"atom",token:o,value:S};$.subject.next(_);let J=XT(y);if(y.atoms.delete(A),y.valueMap.delete(A),y.selectorAtoms.delete(A),y.atomsThatAreDefault.delete(A),T.timelineTopics.delete(A),o.type==="mutable_atom"){let R=Zy(o);oJ(T,R),T.trackers.delete(A)}if(T.logger.info("\uD83D\uDD25","atom",A,"deleted"),J&&y.transactionMeta.phase==="building"){let R=y.transactionMeta.update.updates.at(-1);if(!(R?.type==="molecule_disposal"&&R.values.some(([H])=>H===f.family?.key)))y.transactionMeta.update.updates.push(_)}else T.on.atomDisposal.next(o)}}class iT extends Set{mode="record";subject=new oT;cacheLimit=0;cache=[];cacheIdx=-1;cacheUpdateNumber=-1;constructor(T,o=0){super(T);if(T instanceof iT)this.parent=T,this.cacheUpdateNumber=T.cacheUpdateNumber;if(o)this.cacheLimit=o,this.cache=new Array(o),this.subscribe("auto cache",(y)=>{this.cacheIdx++,this.cacheIdx%=this.cacheLimit,this.cache[this.cacheIdx]=y})}toJSON(){return{members:[...this],cache:this.cache,cacheLimit:this.cacheLimit,cacheIdx:this.cacheIdx,cacheUpdateNumber:this.cacheUpdateNumber}}static fromJSON(T){let o=new iT(T.members,T.cacheLimit);return o.cache=T.cache,o.cacheIdx=T.cacheIdx,o.cacheUpdateNumber=T.cacheUpdateNumber,o}add(T){let o=super.add(T);if(this.mode==="record")this.cacheUpdateNumber++,this.emit(`add:${AT(T)}`);return o}clear(){let T=this.mode==="record"?[...this]:null;if(super.clear(),T)this.cacheUpdateNumber++,this.emit(`clear:${JSON.stringify(T)}`)}delete(T){let o=super.delete(T);if(this.mode==="record")this.cacheUpdateNumber++,this.emit(`del:${AT(T)}`);return o}parent;child=null;transactionUpdates=null;transaction(T){this.mode="transaction",this.transactionUpdates=[],this.child=new iT(this);let o=this.child._subscribe("transaction",(y)=>{this.transactionUpdates?.push(y)});try{if(T(this.child)){for(let A of this.transactionUpdates)this.doStep(A);this.cacheUpdateNumber++,this.emit(`tx:${this.transactionUpdates.join(";")}`)}}catch(y){throw console.warn("Did not apply transaction to SetRTX; this error was thrown:",y),y}finally{o(),this.child=null,this.transactionUpdates=null,this.mode="record"}}_subscribe(T,o){return this.subject.subscribe(T,o)}subscribe(T,o){return this.subject.subscribe(T,(y)=>{o(`${this.cacheUpdateNumber}=${y}`)})}emit(T){this.subject.next(T)}doStep(T){let o=T.indexOf(":"),y=T.substring(0,o),A=T.substring(o+1);switch(y){case"add":this.add(JSON.parse(A));break;case"clear":this.clear();break;case"del":this.delete(JSON.parse(A));break;case"tx":for(let F of A.split(";"))this.doStep(F)}}getUpdateNumber(T){let o=T.indexOf("=");return Number(T.substring(0,o))}do(T){let o=T.indexOf("="),y=Number(T.substring(0,o)),A=y-this.cacheUpdateNumber;if(A>0){if(A===1){this.mode="playback";let f=T.substring(o+1);return this.doStep(f),this.mode="record",this.cacheUpdateNumber=y,null}return this.cacheUpdateNumber+1}if(Math.abs(A)<this.cacheLimit){let f=this.cacheIdx+A;if(this.cache[f]===T)return null;this.mode="playback";let $=!1;while(!$){this.cacheIdx%=this.cacheLimit;let J=this.cache[this.cacheIdx];if(this.cacheIdx--,!J)return"OUT_OF_RANGE";this.undo(J),$=this.cacheIdx===f-1}let _=T.substring(o+1);return this.doStep(_),this.mode="record",this.cacheUpdateNumber=y,null}return"OUT_OF_RANGE"}undoStep(T){let o=T.indexOf(":"),y=T.substring(0,o),A=T.substring(o+1);switch(y){case"add":this.delete(JSON.parse(A));break;case"del":this.add(JSON.parse(A));break;case"clear":{let F=JSON.parse(A);for(let f of F)this.add(f);break}case"tx":{let F=A.split(";");for(let f=F.length-1;f>=0;f--)this.undoStep(F[f])}}}undo(T){let o=T.indexOf("=");if(Number(T.substring(0,o))===this.cacheUpdateNumber){this.mode="playback";let A=T.substring(o+1);return this.undoStep(A),this.mode="record",this.cacheUpdateNumber--,null}return this.cacheUpdateNumber}}class EF{toolkit;options;defaultContent;molecules=new Map;relations;states;core;transact(T,o){let y=this.toolkit;this.toolkit=T,o(this),this.toolkit=y}store;realm;[Symbol.dispose](){}constructor(T,o,y=fT.STORE){this.store=y,this.realm=new r$(y),this.options=T,this.defaultContent=o,this.store.miscResources.set(`join:${T.key}`,this),this.realm.allocate("root",T.key),this.toolkit={get:(...K)=>OT(y,...K),set:(...K)=>{bT(y,...K)},find:(...K)=>c(y,...K),json:(K)=>gT(y,K)};let A=T.between[0],F=T.between[1],f=YF(y,{key:`${T.key}/relatedKeys`,default:()=>new iT,mutable:!0,fromJson:(K)=>iT.fromJSON(K),toJson:(K)=>K.toJSON()},["join","relations"]);this.core={relatedKeysAtoms:f};let S=({get:K},V)=>K(f,V),$=({set:K},V,L)=>{if(!this.store.molecules.has(AT(V)))this.realm.allocate(T.key,V);K(f,V,(C)=>C.add(L)),K(f,L,(C)=>C.add(V))},_=({set:K},V,L)=>{K(f,V,(C)=>{return C.delete(L),C}),K(f,L,(C)=>{return C.delete(V),C})},J=(K,V,L)=>{let{find:C,get:v,set:s}=K,z=C(f,V),a=v(z);for(let P of a){if(L.includes(P))continue;s(f,P,(HT)=>{return HT.delete(V),HT})}s(z,(P)=>{return P.transaction((e)=>{e.clear();for(let HT of L){let qT=S(K,HT),Xo=qT.has(V);if(this.relations.cardinality==="1:n"){let Ay=[];for(let D of qT){if(D===V)continue;let n=S(K,D);if(n.delete(HT),n.size===0)Ay.push(D)}if(!Xo&&qT.size>0)qT.clear();for(let D of Ay){let n=[HT,D].sort(),RT=`"${n[0]}:${n[1]}"`;this.molecules.delete(RT)}}if(!Xo)qT.add(V);e.add(HT)}return!0}),P})},R=(K,V,L)=>{let{set:C}=K;C(f,V,(v)=>{return v.transaction((s)=>{for(let z of L)s.add(z);return!0}),v});for(let v of L)C(f,v,(s)=>{return s.add(V),s});return!0},M=(K,V,L)=>{let C=S(K,V);return L?C.has(L):C.size>0},Y={getRelatedKeys:(K)=>S(this.toolkit,K),addRelation:(K,V)=>{this.store.moleculeJoins.set(K,T.key),this.store.moleculeJoins.set(V,T.key),$(this.toolkit,K,V)},deleteRelation:(K,V)=>{_(this.toolkit,K,V)},replaceRelationsSafely:(K,V)=>{J(this.toolkit,K,V)},replaceRelationsUnsafely:(K,V)=>{R(this.toolkit,K,V)},has:(K,V)=>M(this.toolkit,K,V)},H,Q;if(o){Q=Xy(y,{key:`${T.key}/content`,default:o},["join","content"]);let K=({get:C},v)=>C(Q,v),V=({set:C},v,s)=>{C(Q,v,s)};H=Object.assign(Y,{getContent:(C)=>{return K(this.toolkit,C)},setContent:(C,v)=>{V(this.toolkit,C,v)},deleteContent:(C)=>{this.realm.deallocate(C)}})}else H=Y;let w=new uT(T,{externalStore:H,isAType:T.isAType,isBType:T.isBType,makeContentKey:(...K)=>{let[V,L]=K,C=K.sort(),v=`${C[0]}:${C[1]}`,s=y.molecules.get(AT(V)),z=y.molecules.get(AT(L));if(!s)this.realm.allocate(T.key,V);if(!z)this.realm.allocate(T.key,L);return this.realm.allocate(V,v,"all"),this.realm.claim(L,v),this.store.moleculeJoins.set(v,T.key),v}}),B=()=>Yy(y,{key:`${T.key}/singleRelatedKey`,get:(K)=>({get:V})=>{let L=V(f,K);for(let C of L)return C;return null}},["join","keys"]),t=()=>{return Yy(y,{key:`${T.key}/multipleRelatedKeys`,get:(K)=>({get:V})=>{let L=$J(f,y);return V(L,K).members}},["join","keys"])},m=()=>Yy(y,{key:`${T.key}/singleRelatedEntry`,get:(K)=>({get:V})=>{let L=V(f,K);for(let C of L){let v=w.isAType?.(K)?K:void 0,s=v===void 0?K:void 0;v??=C,s??=C;let z=w.makeContentKey(v,s),a=V(Q,z);return[C,a]}return null}},["join","entries"]),h=()=>Yy(y,{key:`${T.key}/multipleRelatedEntries`,get:(K)=>({get:V})=>{let L=$J(f,y);return V(L,K).members.map((v)=>{let s=w.isAType?.(K)?K:void 0,z=s===void 0?K:void 0;s??=v,z??=v;let a=w.makeContentKey(s,z),P=V(Q,a);return[v,P]})}},["join","entries"]);switch(T.cardinality){case"1:1":{let K=B(),V=`${A}KeyOf${YT(F)}`,L=`${F}KeyOf${YT(A)}`,C={[V]:K,[L]:K},v;if(o){let s=m(),z=`${A}EntryOf${YT(F)}`,a=`${F}EntryOf${YT(A)}`,P={[z]:s,[a]:s};v=Object.assign(C,P)}else v=C;this.relations=w,this.states=v;break}case"1:n":{let K=B(),V=t(),L=`${A}KeyOf${YT(F)}`,C=`${F}KeysOf${YT(A)}`,v={[L]:K,[C]:V},s;if(o){let z=m(),a=h(),P=`${A}EntryOf${YT(F)}`,e=`${F}EntriesOf${YT(A)}`,HT={[P]:z,[e]:a};s=Object.assign(v,HT)}else s=v;this.relations=w,this.states=s;break}case"n:n":{let K=t(),V=`${A}KeysOf${YT(F)}`,L=`${F}KeysOf${YT(A)}`,C={[V]:K,[L]:K},v;if(o){let s=h(),z=`${A}EntriesOf${YT(F)}`,a=`${F}EntriesOf${YT(A)}`,P={[z]:s,[a]:s};v=Object.assign(C,P)}else v=C;this.relations=w,this.states=v}}}}function VA(T,o){let y=o.joins.get(T.key);if(y===void 0){let F=fT.STORE.joins.get(T.key);if(F===void 0)throw new Error(`Join "${T.key}" not found in store "${o.config.name}"`);y=new EF(F.options,F.defaultContent,o),o.joins.set(T.key,y)}return y}function GF(T,o,y){let A=VA(T,y),F=p(y);if(XT(F)){let{toolkit:f}=F.transactionMeta;A.transact(f,({relations:S})=>{o(S)})}else o(A.relations)}function Cf(T,o,y){let A=VA(T,y),F;switch(T.cardinality){case"1:1":{let f=`${T.a}KeyOf${YT(T.b)}`,S=`${T.b}KeyOf${YT(T.a)}`;F={get[f](){let _=A.states[f];return c(y,_,o)},get[S](){let _=A.states[S];return c(y,_,o)}};let $=`${T.a}EntryOf${YT(T.b)}`;if($ in A.states){let _=`${T.b}EntryOf${YT(T.a)}`;Object.assign(F,{get[$](){let J=A.states[$];return c(y,J,o)},get[_](){let J=A.states[_];return c(y,J,o)}})}break}case"1:n":{let f=`${T.a}KeyOf${YT(T.b)}`,S=`${T.b}KeysOf${YT(T.a)}`;F={get[f](){let _=A.states[f];return c(y,_,o)},get[S](){let _=A.states[S];return c(y,_,o)}};let $=`${T.a}EntryOf${YT(T.b)}`;if($ in A.states){let _=`${T.b}EntriesOf${YT(T.a)}`;Object.assign(F,{get[$](){let J=A.states[$];return c(y,J,o)},get[_](){let J=A.states[_];return c(y,J,o)}})}break}case"n:n":{let f=`${T.a}KeysOf${YT(T.b)}`,S=`${T.b}KeysOf${YT(T.a)}`;F={get[f](){let _=A.states[f];return c(y,_,o)},get[S](){let _=A.states[S];return c(y,_,o)}};let $=`${T.a}EntriesOf${YT(T.b)}`;if($ in A.states){let _=`${T.b}EntriesOf${YT(T.a)}`;Object.assign(F,{get[$](){let J=A.states[$];return c(y,J,o)},get[_](){let J=A.states[_];return c(y,J,o)}})}}}return F}function nR(T,o){return VA(T,o).core.relatedKeysAtoms}function By(T){return T.startsWith("\uD83D\uDD0D ")}var JJ=(T)=>{let o=Do(T,{key:"\uD83D\uDD0D Atom Token Index (Internal)",default:()=>{let y=new Map;for(let[A,F]of T.atoms){if(By(A))continue;let f=wo(F);if(F.family){let S=y.get(F.family.key);if(!S||!("familyMembers"in S))S={key:F.family.key,familyMembers:new Map},y.set(F.family.key,S);S.familyMembers.set(F.family.subKey,f)}else y.set(A,f)}return y},effects:[({setSelf:y})=>{T.on.atomCreation.subscribe("introspection",(A)=>{if(By(A.key))return;y((F)=>{if(A.family){let{key:f,subKey:S}=A.family,$=F.get(f);if($===void 0||!("familyMembers"in $))$={key:f,familyMembers:new Map},F.set(f,$);$.familyMembers.set(S,A)}else F.set(A.key,A);return F})}),T.on.atomDisposal.subscribe("introspection",(A)=>{y((F)=>{if(A.family){let{key:f,subKey:S}=A.family,$=F.get(f);if($&&"familyMembers"in $){if($.familyMembers.delete(S),$.familyMembers.size===0)F.delete(f)}}else F.delete(A.key);return F})})}]},void 0);return My(T,{key:"\uD83D\uDD0D Atom Token Index",get:({get:y})=>y(o)})};var _J=(T)=>{let o=Do(T,{key:"\uD83D\uDD0D Selector Token Index (Internal)",default:()=>{let y=new Map;for(let A of[T.readonlySelectors,T.selectors])for(let[F,f]of A){if(By(F))continue;let S=wo(f);if(f.family){let $=y.get(f.family.key);if(!$||!("familyMembers"in $))$={key:f.family.key,familyMembers:new Map},y.set(f.family.key,$);$.familyMembers.set(f.family.subKey,S)}else y.set(F,S)}return y},effects:[({setSelf:y})=>{T.on.selectorCreation.subscribe("introspection",(A)=>{if(By(A.key))return;y((F)=>{if(A.family){let{key:f,subKey:S}=A.family,$=F.get(f);if($===void 0||!("familyMembers"in $))$={key:f,familyMembers:new Map},F.set(f,$);$.familyMembers.set(S,A)}else F.set(A.key,A);return F})}),T.on.selectorDisposal.subscribe("introspection",(A)=>{y((F)=>{if(A.family){let{key:f,subKey:S}=A.family,$=F.get(f);if($&&"familyMembers"in $){if($.familyMembers.delete(S),$.familyMembers.size===0)F.delete(f)}}else F.delete(A.key);return F})})}]},void 0);return My(T,{key:"\uD83D\uDD0D Selector Token Index",get:({get:y})=>y(o)})};class jf{supported;constructor(T){this.supported=T}refine(T){for(let[o,y]of Object.entries(this.supported))try{if(y(T)===!0&&y!==Boolean)return{type:o,data:T}}catch(A){try{if(T instanceof y)return{type:o,data:T}}catch(F){}}return null}}var RJ=new jf({number:(T)=>typeof T==="number",string:(T)=>typeof T==="string",boolean:(T)=>typeof T==="boolean",null:(T)=>T===null});function WJ(T){if(!T)return!1;return Object.getPrototypeOf(T)===Object.prototype}var OJ=new jf({object:WJ,array:(T)=>Array.isArray(T)}),fZ=new jf({...RJ.supported,...OJ.supported}),DA=(T)=>{if(T===void 0)return"undefined";let o=fZ.refine(T);if(o)return o.type;return Object.getPrototypeOf(T).constructor.name};class DW{store;auditorCreatedAt=performance.now();statesCreatedAt=new Map;atomIndex;selectorIndex;disposed=!1;unsubscribeFromAtomCreation;unsubscribeFromAtomDisposal;unsubscribeFromSelectorCreation;unsubscribeFromSelectorDisposal;constructor(T=fT.STORE){this.store=T,this.atomIndex=JJ(this.store),this.selectorIndex=_J(this.store),this.unsubscribeFromAtomCreation=this.store.on.atomCreation.subscribe(`auditor-${this.auditorCreatedAt}`,({key:o})=>{this.statesCreatedAt.set(o,performance.now()-this.auditorCreatedAt)}),this.unsubscribeFromAtomDisposal=this.store.on.atomDisposal.subscribe(`auditor-${this.auditorCreatedAt}`,({key:o})=>{this.statesCreatedAt.delete(o)}),this.unsubscribeFromSelectorCreation=this.store.on.selectorCreation.subscribe(`auditor-${this.auditorCreatedAt}`,({key:o})=>{this.statesCreatedAt.set(o,performance.now()-this.auditorCreatedAt)}),this.unsubscribeFromSelectorDisposal=this.store.on.selectorDisposal.subscribe(`auditor-${this.auditorCreatedAt}`,({key:o})=>{this.statesCreatedAt.delete(o)})}static DEFAULT_LIST_RESOURCES_PARAM={atomFamilies:!0,selectorFamilies:!0};listResources(T=DW.DEFAULT_LIST_RESOURCES_PARAM){if(this.disposed)throw new Error("This Auditor has been disposed");let o=i$(this.atomIndex),y=i$(this.selectorIndex),A=[...o.values()].filter(($)=>("familyMembers"in $)),F=[...y.values()].filter(($)=>("familyMembers"in $)),f=performance.now(),S=[];if(T.atomFamilies)for(let $ of A){let _=$.familyMembers.values();for(let J of _){let M=this.statesCreatedAt.get(J.key)??this.auditorCreatedAt,Y=f-M;S.push([J,Y])}}if(T.selectorFamilies)for(let $ of F){let _=$.familyMembers.values();for(let J of _){let M=this.statesCreatedAt.get(J.key)??this.auditorCreatedAt,Y=f-M;S.push([J,Y])}}return S}[Symbol.dispose](){this.unsubscribeFromAtomCreation(),this.unsubscribeFromAtomDisposal(),this.unsubscribeFromSelectorCreation(),this.unsubscribeFromSelectorDisposal(),this.disposed=!0}}var MJ=(T,o)=>{let y=(A,F)=>{let S=((_,J)=>{let R=o(_,J);if(R)return R;return null})(A,F);if(S?.jobComplete??S?.pathComplete)return S;let $=Array.isArray(F)?F.map((_,J)=>[J,_]):WJ(F)?Object.entries(F):[];for(let[_,J]of $){let R=y([...A,_],J);if(R?.jobComplete)return R}return{}};y([],T)};function SZ(T,o){return{summary:`${T<o?"+":"-"}${Math.abs(T-o)} (${T} \u2192 ${o})`}}function $Z(T,o){return{summary:`${T.length<o.length?"+":"-"}${Math.abs(T.length-o.length)} ("${T}" \u2192 "${o}")`}}function JZ(T,o){return{summary:`${T} \u2192 ${o}`}}function CW(T,o,y){let A="",F=[],f=[],S=[];return MJ(T,($,_)=>{let J;for(J of $){let R=o[J];if(R===void 0)f.push([J,JSON.stringify(_)]);else{let M=y(_,R);if(M.summary!=="No Change")S.push([J,M])}}}),MJ(o,($,_)=>{let J;for(J of $)if(T[J]===void 0)F.push([J,JSON.stringify(_)])}),A=`\uFF5E${S.length} \uFF0B${F.length} \uFF0D${f.length}`,{summary:A,added:F,removed:f,changed:S}}function _Z(T,o,y){return CW(T,o,y)}class LW{leafRefinery;treeRefinery;leafDiffers;treeDiffers;constructor(T,o,y){this.leafRefinery=T,this.treeRefinery=o,this.leafDiffers={},this.treeDiffers={};for(let A of Object.keys(T.supported)){let F=y[A];this.leafDiffers[A]=F}for(let A of Object.keys(o.supported)){let F=y[A];this.treeDiffers[A]=F}}diff(T,o){if(T===o)return{summary:"No Change"};let y=this.leafRefinery.refine(T)??this.treeRefinery.refine(T),A=this.leafRefinery.refine(o)??this.treeRefinery.refine(o);if(y!==null&&A!==null){if(y.type===A.type){if(y.type in this.leafDiffers)return this.leafDiffers[y.type](y.data,A.data);if(y.type in this.treeDiffers)return this.treeDiffers[y.type](y.data,A.data,($,_)=>this.diff($,_))}}let F=DA(T),f=DA(o);if(F===f)return{summary:`${F} \u2192 ${f}`};return{summary:`Type change: ${F} \u2192 ${f}`}}}var Tt=new LW(RJ,OJ,{number:SZ,string:$Z,boolean:JZ,null:()=>({summary:"No Change"}),object:CW,array:_Z});class IW extends Map{set(T,o){if(this.has(T))return console.warn("Tried to set a key that already exists in an InvariantMap",{key:T,value:o}),this;return super.set(T,o)}clear(){throw new Error("Cannot clear an InvariantMap")}}class mf{type="continuity";globals=[];actions=[];perspectives=[];key;constructor(T){this.key=T}static existing=new IW;static create(T,o){let y=new mf(T),{type:A,globals:F,actions:f,perspectives:S}=o(y),$={type:A,key:T,globals:F,actions:f,perspectives:S};return mf.existing.set(T,$),$}add(...T){switch(T[0].type){case"atom":case"mutable_atom":this.globals.push(...T);break;case"transaction":this.actions.push(...T);break;case"atom_family":case"mutable_atom_family":{let[y,A]=T;this.perspectives.push({type:"realtime_perspective",resourceAtoms:y,viewAtoms:A})}break}return this}}function _t(T){let{key:o,config:y}=T,A=mf.create(o,y),{actions:F}=A;for(let f of F)XW(fT.STORE,o,f.key);return WW(fT.STORE,o,-1),A}var Mt=UA({key:"usersInRoomIndex",mutable:!0,default:()=>new iT,toJson:(T)=>T.toJSON(),fromJson:(T)=>iT.fromJSON(T)}),XJ=UA({key:"roomIndex",default:()=>new iT,mutable:!0,toJson:(T)=>T.toJSON(),fromJson:(T)=>iT.fromJSON(T)}),RZ={enteredAtEpoch:0},QF=Df({key:"usersInRooms",between:["room","user"],cardinality:"1:n",isAType:(T)=>typeof T==="string",isBType:(T)=>typeof T==="string"},RZ),Xt=Lf({key:"usersInMyRoomView",get:(T)=>({find:o})=>{let y=hR(QF);return[o(y,T)]}});import{spawn as WZ}from"child_process";class CA{listeners;globalListeners;handleEvent(T,...o){for(let A of this.globalListeners)A(T,...o);let y=this.listeners.get(T);if(y)for(let A of y)A(...o)}id="no_id_retrieved";emit;constructor(T){this.emit=T,this.listeners=new Map,this.globalListeners=new Set}on(T,o){let y=this.listeners.get(T);if(y)y.add(o);else this.listeners.set(T,new Set([o]));return this}onAny(T){return this.globalListeners.add(T),this}off(T,o){let y=this.listeners.get(T);if(y)if(o)y.delete(o);else this.listeners.delete(T);return this}offAny(T){return this.globalListeners.delete(T),this}}class YJ extends CA{incompleteData="";unprocessedEvents=[];incompleteLog="";unprocessedLogs=[];id="#####";process;key;logger;handleLog(T){if(Array.isArray(T)){let[o,...y]=T;switch(o){case"i":this.logger.info(...y);break;case"w":this.logger.warn(...y);break;case"e":this.logger.error(...y);break;default:return}}}constructor(T,o,y){super((A,...F)=>{let f=JSON.stringify([A,...F])+"\x03",S=($)=>{if($.code==="EPIPE")console.error("EPIPE error during write",this.process.stdin);this.process.stdin.removeListener("error",S)};return this.process.stdin.once("error",S),this.process.stdin.write(f),this});if(this.process=T,this.key=o,this.logger=y??{info:(...A)=>{console.info(this.id,this.key,...A)},warn:(...A)=>{console.warn(this.id,this.key,...A)},error:(...A)=>{console.error(this.id,this.key,...A)}},this.process.stdout.on("data",(A)=>{let F=A.toString();if(F==="ALIVE")return;this.unprocessedEvents.push(...F.split("\x03"));let f=this.unprocessedEvents.shift();this.incompleteData+=f??"";try{if(this.incompleteData.startsWith("error"))console.log("\u2757",this.incompleteData);let S=rT(this.incompleteData);this.handleEvent(...S);while(this.unprocessedEvents.length>0){let $=this.unprocessedEvents.shift();if($){if(this.unprocessedEvents.length===0)this.incompleteData=$;S=rT($),this.handleEvent(...S)}}this.incompleteData=""}catch(S){console.warn("\u26A0\uFE0F----------------\u26A0\uFE0F"),console.warn(this.incompleteData),console.warn("\u26A0\uFE0F----------------\u26A0\uFE0F"),console.error(S)}}),this.process.stderr.on("data",(A)=>{let F=A.toString();this.unprocessedLogs.push(...F.split("\x03"));let f=this.unprocessedLogs.shift();this.incompleteLog+=f??"";try{let S=rT(this.incompleteLog);this.handleLog(S);while(this.unprocessedLogs.length>0)if(this.incompleteLog=this.unprocessedLogs.shift()??"",this.incompleteLog)S=rT(this.incompleteLog),this.handleLog(S)}catch(S){console.error("\u274C\u274C\u274C"),console.error(this.incompleteLog),console.error(S),console.error("\u274C\u274C\u274C\uFE0F")}}),T.pid)this.id=T.pid.toString()}}class kW extends CA{in;out;id="no_id_retrieved";disposalFunctions=[];constructor(T){super((...o)=>{return this.out.next(o),this});this.id=T,this.in=new oT,this.out=new oT,this.in.subscribe("socket",(o)=>{this.handleEvent(...o)})}dispose(){for(let T of this.disposalFunctions)T()}}class ZJ extends CA{incompleteData="";unprocessedEvents=[];relays;relayServices;process;id="#####";log(...T){this.process.stderr.write(AT(T.map((o)=>o instanceof iT?`{ ${o.toJSON().members.join(" | ")} }`:o))+"\x03")}logger={info:(...T)=>{this.log("i",...T)},warn:(...T)=>{this.log("w",...T)},error:(...T)=>{this.log("e",...T)}};constructor(){super((T,...o)=>{let y=JSON.stringify([T,...o]);return this.process.stdout.write(y+"\x03"),this});if(this.process=process,this.process.stdin.resume(),this.relays=new Map,this.relayServices=[],this.process.stdin.on("data",(T)=>{let o=T.toString();this.unprocessedEvents.push(...o.split("\x03"));let y=this.unprocessedEvents.shift();this.incompleteData+=y??"";try{let A=rT(this.incompleteData);this.logger.info("\uD83C\uDFB0","received",A),this.handleEvent(...A);while(this.unprocessedEvents.length>0){let F=this.unprocessedEvents.shift();if(F){if(this.unprocessedEvents.length===0)this.incompleteData=F;let f=rT(F);this.handleEvent(...f)}}this.incompleteData=""}catch(A){if(A instanceof Error)this.logger.error("\u2757",A.message,A.cause,A.stack)}}),this.on("exit",()=>{this.logger.info("\uD83D\uDD25",this.id,'received "exit"'),process.exit(0)}),process.on("exit",(T)=>{this.logger.info("\uD83D\uDD25",this.id,`exited with code ${T}`)}),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",(T)=>{this.logger.info("\uD83D\uDC64","user",T,"joined");let o=new kW(`user:${T}`);this.relays.set(T,o),this.logger.info("\uD83D\uDD17","attaching services:",`[${[...this.relayServices.keys()].join(", ")}]`);for(let y of this.relayServices){let A=y(o);if(A)o.disposalFunctions.push(A)}this.on(`user:${T}`,(...y)=>{o.in.next(y)}),o.out.subscribe("socket",(y)=>{this.emit(...y)})}),this.on("user-leaves",(T)=>{let o=this.relays.get(T);if(this.off(`relay:${T}`),o)o.dispose(),this.relays.delete(T)}),process.stdout.write("ALIVE")}relay(T){this.logger.info("\uD83D\uDD17","running relay method"),this.relayServices.push(T)}}var HJ=Py({key:"roomArguments",default:["echo",["Hello World!"]]}),BW=Lf({key:"room",get:(T)=>async({get:o,find:y})=>{let A=y(HJ,T),F=o(A),[f,S]=F,$=await new Promise((_)=>{let J=WZ(f,S,{env:process.env}),R=(M)=>{if(M.toString()==="ALIVE")J.stdout.off("data",R),_(J)};J.stdout.on("data",R)});return new YJ($,T)}});var Pt=UF({key:"createRoom",do:({get:T,set:o,find:y},A,F,f)=>{let S=f?[F,f]:[F],$=y(HJ,A);o($,S),o(XJ,(R)=>R.add(A));let _=y(BW,A);return T(_)}}),ht=UF({key:"joinRoom",do:(T,o,y,A)=>{let F={enteredAtEpoch:A};return GF(QF,(f)=>{f.set({room:o,user:y},F)},T.env().store),F}}),nt=UF({key:"leaveRoom",do:(T,o,y)=>{GF(QF,(A)=>{A.delete({room:o,user:y})},T.env().store)}}),gt=UF({key:"destroyRoom",do:(T,o)=>{GF(QF,(y)=>{y.delete({room:o})},T.env().store),T.set(XJ,(y)=>(y.delete(o),y))}});function EJ(T,o){return o.map((y)=>{switch(y.type){case"transaction_update":{let A=EJ(T,y.updates);return{...y,updates:A}}case"atom_update":case"selector_update":case"molecule_creation":case"molecule_disposal":case"molecule_transfer":case"state_creation":case"state_disposal":return y}}).filter((y)=>{switch(y.type){case"atom_update":case"selector_update":return T.includes(y.key);case"state_creation":case"state_disposal":return T.includes(y.token.key);case"molecule_creation":case"transaction_update":case"molecule_disposal":case"molecule_transfer":return!0}})}var ct=Py({key:"redactor",default:{occlude:(T)=>T}}),LA=Py({key:"unacknowledgedUpdates",default:()=>[]});var NW=Py({key:"sockets",default:null}),st=UA({key:"socketsIndex",mutable:!0,default:()=>new iT,toJson:(T)=>T.toJSON(),fromJson:(T)=>iT.fromJSON(T)}),at=UA({key:"usersIndex",mutable:!0,default:()=>new iT,toJson:(T)=>T.toJSON(),fromJson:(T)=>iT.fromJSON(T)}),GJ=Df({key:"usersOfSockets",between:["user","socket"],cardinality:"1:1",isAType:(T)=>T.startsWith("user::"),isBType:(T)=>T.startsWith("socket::")});function tW(T,o,y,A){let F=o.key;return function f(){let S=[];for(let _ of o.globals){let J=_.type==="mutable_atom"?gT(T,_):_,R=OT(T,J);S.push(J,R)}for(let _ of o.perspectives){let{viewAtoms:J,resourceAtoms:R}=_,M=c(T,J,y),Y=OT(T,M);T.logger.info("\uD83D\uDC41","atom",R.key,`${y} can see`,{viewAtoms:J,resourceAtoms:R,userView:Y});for(let H of Y){let Q=H.type==="mutable_atom"?gT(T,H):H,w=OT(T,Q);S.push(Q,w)}}let $=aT(T)?T.transactionMeta.epoch.get(F)??null:null;A?.emit(`continuity-init:${F}`,$,S)}}function pW(T,o,y){let A=o.key;return function F(f){T.logger.info("\uD83D\uDECE\uFE0F","continuity",A,"received",f);let{key:S,id:$}=f,_=`tx-run:${S}:${$}`,J=`${_}:start`,R=`${_}:end`;performance.mark(J);try{zA(T,{type:"transaction",key:S},$)(...f.params)}catch(Y){if(Y instanceof Error)T.logger.error("\u274C","continuity",A,`failed to run transaction ${S} from ${y} with update ${$}`,Y.message)}performance.mark(R);let M=performance.measure(_,J,R);T?.logger.info("\uD83D\uDE80","transaction",S,$,y,M.duration)}}function bW(T,o,y,A){let F=o.key;return function f(S){if(T.logger.info("\uD83D\uDC4D","continuity",F,`${y} acknowledged epoch ${S}`),A[0]?.epoch===S)bT(T,LA,y,(_)=>{return _.shift(),T.logger.info("\uD83D\uDC4D","continuity",F,`${y} unacknowledged update queue now has`,_.length,"items"),_})}}function xW(T,o,y,A){let F=o.key,f=[];for(let S of o.actions){let $=FJ(T,S,`sync-continuity:${F}:${y}`,(_)=>{try{let J=o.globals.map((Y)=>{if(Y.type==="atom")return Y.key;return Zy(Y).key}).concat(o.perspectives.flatMap((Y)=>{let{viewAtoms:H}=Y,Q=c(T,H,y);return OT(T,Q).map((B)=>{return B.type==="mutable_atom"?"*"+B.key:B.key})})),R=EJ(J,_.updates),M={..._,updates:R};bT(T,LA,y,(Y)=>{if(M)Y.push(M),Y.sort((H,Q)=>H.epoch-Q.epoch),T.logger.info("\uD83D\uDC4D","continuity",F,`${y} unacknowledged update queue now has`,Y.length,"items");return Y}),A?.emit(`tx-new:${F}`,M)}catch(J){if(J instanceof Error)T.logger.error("\u274C","continuity",F,`${y} failed to send update from transaction ${S.key} to ${y}`,J.message)}});f.push($)}return f}function jW(T,o,y,A){let F=o.key,f=[];for(let S of o.perspectives){let{viewAtoms:$}=S,_=c(T,$,y),J=$o(T,_,`sync-continuity:${F}:${y}:perspective:${S.resourceAtoms.key}`,({oldValue:R,newValue:M})=>{let Y=R.map((B)=>B.key),H=M.map((B)=>B.key),Q=R.filter((B)=>!H.includes(B.key)),w=M.filter((B)=>!Y.includes(B.key)).flatMap((B)=>{let t=B.type==="mutable_atom"?gT(T,B):B,m=OT(T,t);return[t,m]});if(T.logger.info("\uD83D\uDC41","atom",S.resourceAtoms.key,`${y} has a new perspective`,{oldKeys:Y,newKeys:H,revealed:w,concealed:Q}),w.length>0)A?.emit(`reveal:${F}`,w);if(Q.length>0)A?.emit(`conceal:${F}`,Q)});f.push(J)}return f}function Cp({socket:T,store:o=fT.STORE}){return function y(A){let F=T,f=A.key,S=Cf(GJ,`socket::${F.id}`,o).userKeyOfSocket,$=OT(o,S);if(!$)return o.logger.error("\u274C","continuity",f,`Tried to create a synchronizer for a socket (${F.id}) that is not connected to a user.`),()=>{};let _=Cf(GJ,$,o).socketKeyOfUser,J=$o(o,_,`sync-continuity:${f}:${$}`,({newValue:t})=>{if(o.logger.info("\uD83D\uDC4B","continuity",f,`seeing ${$} on new socket ${t}`),t===null){o.logger.warn("\u274C","continuity",f,`User (${$}) is not connected to a socket, waiting for them to reappear.`);return}let m=c(o,NW,t);F=OT(o,m);for(let K of R)F?.emit(`tx-new:${f}`,K)}),R=OT(o,LA,$),M=[],Y=jW(o,A,$,F),H=xW(o,A,$,F);M.push(...Y,...H);let Q=tW(o,A,$,T);F.off(`get:${f}`,Q),F.on(`get:${f}`,Q);let w=pW(o,A,$);F.off(`tx-run:${f}`,w),F.on(`tx-run:${f}`,w);let B=bW(o,A,$,R);return F?.on(`ack:${f}`,B),()=>{for(let t of M)t();F?.off(`ack:${f}`,B),F?.off(`get:${f}`,Q),F?.off(`tx-run:${f}`,w)}}}var{file:O4,serve:K5}=globalThis.Bun;import{readFileSync as vW}from"fs";import{resolve as wJ}from"path";function OZ(T,o){let y={},A=[];for(let F in T){let f=T[F],S=o[F],$=f["~standard"].validate(S);if($ instanceof Promise)throw new Error(`Validation must be synchronous, but ${F} returned a Promise.`);if($.issues){A.push(...$.issues.map((_)=>({..._,path:[F,..._.path??[]]})));continue}y[F]=$.value}if(A.length)return{issues:A};return{value:y}}function mW(T){let o=T.runtimeEnvStrict??T.runtimeEnv??process.env;if(T.emptyStringAsUndefined??!1){for(let[m,h]of Object.entries(o))if(h==="")delete o[m]}if(!!T.skipValidation)return o;let F=typeof T.client==="object"?T.client:{},f=typeof T.server==="object"?T.server:{},S=typeof T.shared==="object"?T.shared:{},$=T.isServer??(typeof window==="undefined"||("Deno"in window)),_=$?{...f,...S,...F}:{...F,...S},J=OZ(_,o),R=T.onValidationError??((m)=>{throw console.error("\u274C Invalid environment variables:",m),new Error("Invalid environment variables")}),M=T.onInvalidAccess??(()=>{throw new Error("\u274C Attempted to access a server-side environment variable on the client")});if(J.issues)return R(J.issues);let Y=(m)=>{if(!T.clientPrefix)return!0;return!m.startsWith(T.clientPrefix)&&!(m in S)},H=(m)=>{return $||!Y(m)},Q=(m)=>{return m==="__esModule"||m==="$$typeof"},w=(T.extends??[]).reduce((m,h)=>{return Object.assign(m,h)},{}),B=Object.assign(J.value,w);return new Proxy(B,{get(m,h){if(typeof h!=="string")return;if(Q(h))return;if(!H(h))return M(h);return Reflect.get(m,h)}})}var MZ="__vite_start_time"in globalThis,XZ=typeof window!=="undefined",yb="vitest"in globalThis,Hy=po("string"),qW=po('"true" | "false" | undefined'),uo=mW({isServer:!MZ&&!XZ,server:{CI:po("string | undefined").pipe(Boolean),POSTGRES_USER:Hy,POSTGRES_PASSWORD:Hy,POSTGRES_DATABASE:Hy,POSTGRES_HOST:Hy,POSTGRES_PORT:Hy.pipe((T)=>Number.parseInt(T,10)),BACKEND_PORT:Hy.pipe((T)=>Number.parseInt(T,10)),RUN_WORKERS_FROM_SOURCE:qW.pipe((T)=>T==="true"),FRONTEND_PORT:Hy.pipe((T)=>Number.parseInt(T,10)),FRONTEND_ORIGINS:Hy.pipe.try((T)=>JSON.parse(T),po("string[]")),OPENAI_API_KEY:po("string | undefined")},clientPrefix:"VITE_",client:{VITE_BACKEND_ORIGIN:Hy,VITE_USE_SELF_SIGNED_CERTIFICATE:qW.pipe((T)=>T==="true")},runtimeEnv:import.meta.env,emptyStringAsUndefined:!0});var PW=wJ(import.meta.dirname,"../dev"),hW=uo.VITE_USE_SELF_SIGNED_CERTIFICATE?{cert:vW(wJ(PW,"./cert.pem"),"utf-8"),key:vW(wJ(PW,"./key.pem"),"utf-8")}:void 0;import Z5 from"path";var O=Symbol.for("drizzle:entityKind"),Jb=Symbol.for("drizzle:hasOwnEntityKind");function G(T,o){if(!T||typeof T!=="object")return!1;if(T instanceof o)return!0;if(!Object.prototype.hasOwnProperty.call(o,O))throw new Error(`Class "${o.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 y=Object.getPrototypeOf(T).constructor;if(y)while(y){if(O in y&&y[O]===o[O])return!0;y=Object.getPrototypeOf(y)}return!1}class GT{constructor(T,o){this.table=T,this.config=o,this.name=o.name,this.keyAsName=o.keyAsName,this.notNull=o.notNull,this.default=o.default,this.defaultFn=o.defaultFn,this.onUpdateFn=o.onUpdateFn,this.hasDefault=o.hasDefault,this.primary=o.primaryKey,this.isUnique=o.isUnique,this.uniqueName=o.uniqueName,this.uniqueType=o.uniqueType,this.dataType=o.dataType,this.columnType=o.columnType,this.generated=o.generated,this.generatedIdentity=o.generatedIdentity}static[O]="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(T){return T}mapToDriverValue(T){return T}shouldDisableInsert(){return this.config.generated!==void 0&&this.config.generated.type!=="byDefault"}}class UJ{static[O]="ColumnBuilder";config;constructor(T,o,y){this.config={name:T,keyAsName:T==="",notNull:!1,default:void 0,hasDefault:!1,primaryKey:!1,isUnique:!1,uniqueName:void 0,uniqueType:void 0,dataType:o,columnType:y,generated:void 0}}$type(){return this}notNull(){return this.config.notNull=!0,this}default(T){return this.config.default=T,this.config.hasDefault=!0,this}$defaultFn(T){return this.config.defaultFn=T,this.config.hasDefault=!0,this}$default=this.$defaultFn;$onUpdateFn(T){return this.config.onUpdateFn=T,this.config.hasDefault=!0,this}$onUpdate=this.$onUpdateFn;primaryKey(){return this.config.primaryKey=!0,this.config.notNull=!0,this}setName(T){if(this.config.name!=="")return;this.config.name=T}}var io=Symbol.for("drizzle:Name");class KJ{static[O]="PgForeignKeyBuilder";reference;_onUpdate="no action";_onDelete="no action";constructor(T,o){if(this.reference=()=>{let{name:y,columns:A,foreignColumns:F}=T();return{name:y,columns:A,foreignTable:F[0].table,foreignColumns:F}},o)this._onUpdate=o.onUpdate,this._onDelete=o.onDelete}onUpdate(T){return this._onUpdate=T===void 0?"no action":T,this}onDelete(T){return this._onDelete=T===void 0?"no action":T,this}build(T){return new nW(T,this)}}class nW{constructor(T,o){this.table=T,this.reference=o.reference,this.onUpdate=o._onUpdate,this.onDelete=o._onDelete}static[O]="PgForeignKey";reference;onUpdate;onDelete;getName(){let{name:T,columns:o,foreignColumns:y}=this.reference(),A=o.map((S)=>S.name),F=y.map((S)=>S.name),f=[this.table[io],...A,y[0].table[io],...F];return T??`${f.join("_")}_fk`}}function qf(T,...o){return T(...o)}function gW(T,o){return`${T[io]}_${o.join("_")}_unique`}function uW(T,o,y){for(let A=o;A<T.length;A++){let F=T[A];if(F==="\\"){A++;continue}if(F==='"')return[T.slice(o,A).replace(/\\/g,""),A+1];if(y)continue;if(F===","||F==="}")return[T.slice(o,A).replace(/\\/g,""),A]}return[T.slice(o).replace(/\\/g,""),T.length]}function iW(T,o=0){let y=[],A=o,F=!1;while(A<T.length){let f=T[A];if(f===","){if(F||A===o)y.push("");F=!0,A++;continue}if(F=!1,f==="\\"){A+=2;continue}if(f==='"'){let[_,J]=uW(T,A+1,!0);y.push(_),A=J;continue}if(f==="}")return[y,A+1];if(f==="{"){let[_,J]=iW(T,A+1);y.push(_),A=J;continue}let[S,$]=uW(T,A,!1);y.push(S),A=$}return[y,A]}function cW(T){let[o]=iW(T,1);return o}function zJ(T){return`{${T.map((o)=>{if(Array.isArray(o))return zJ(o);if(typeof o==="string")return`"${o.replace(/\\/g,"\\\\").replace(/"/g,"\\\"")}"`;return`${o}`}).join(",")}}`}class j extends UJ{foreignKeyConfigs=[];static[O]="PgColumnBuilder";array(T){return new rW(this.config.name,this,T)}references(T,o={}){return this.foreignKeyConfigs.push({ref:T,actions:o}),this}unique(T,o){return this.config.isUnique=!0,this.config.uniqueName=T,this.config.uniqueType=o?.nulls,this}generatedAlwaysAs(T){return this.config.generated={as:T,type:"always",mode:"stored"},this}buildForeignKeys(T,o){return this.foreignKeyConfigs.map(({ref:y,actions:A})=>{return qf((F,f)=>{let S=new KJ(()=>{let $=F();return{columns:[T],foreignColumns:[$]}});if(f.onUpdate)S.onUpdate(f.onUpdate);if(f.onDelete)S.onDelete(f.onDelete);return S.build(o)},y,A)})}buildExtraConfigColumn(T){return new dW(T,this.config)}}class I extends GT{constructor(T,o){if(!o.uniqueName)o.uniqueName=gW(T,[o.name]);super(T,o);this.table=T}static[O]="PgColumn"}class dW extends I{static[O]="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(T){return this.indexConfig.opClass=T,this}}class VF{static[O]="IndexedColumn";constructor(T,o,y,A){this.name=T,this.keyAsName=o,this.type=y,this.indexConfig=A}name;keyAsName;type;indexConfig}class rW extends j{static[O]="PgArrayBuilder";constructor(T,o,y){super(T,"array","PgArray");this.config.baseBuilder=o,this.config.size=y}build(T){let o=this.config.baseBuilder.build(T);return new QJ(T,this.config,o)}}class QJ extends I{constructor(T,o,y,A){super(T,o);this.baseColumn=y,this.range=A,this.size=o.size}size;static[O]="PgArray";getSQLType(){return`${this.baseColumn.getSQLType()}[${typeof this.size==="number"?this.size:""}]`}mapFromDriverValue(T){if(typeof T==="string")T=cW(T);return T.map((o)=>this.baseColumn.mapFromDriverValue(o))}mapToDriverValue(T,o=!1){let y=T.map((A)=>A===null?null:G(this.baseColumn,QJ)?this.baseColumn.mapToDriverValue(A,!0):this.baseColumn.mapToDriverValue(A));if(o)return y;return zJ(y)}}var VJ=Symbol.for("drizzle:isPgEnum");function lW(T){return!!T&&typeof T==="function"&&VJ in T&&T[VJ]===!0}class sW extends j{static[O]="PgEnumColumnBuilder";constructor(T,o){super(T,"string","PgEnumColumn");this.config.enum=o}build(T){return new aW(T,this.config)}}class aW extends I{static[O]="PgEnumColumn";enum=this.config.enum;enumValues=this.config.enum.enumValues;constructor(T,o){super(T,o);this.enum=o.enum}getSQLType(){return this.enum.enumName}}function vf(T,o){return YZ(T,o,void 0)}function YZ(T,o,y){let A=Object.assign((F)=>new sW(F??"",A),{enumName:T,enumValues:o,schema:y,[VJ]:!0});return A}class cT{static[O]="Subquery";constructor(T,o,y,A=!1){this._={brand:"Subquery",sql:T,selectedFields:o,alias:y,isWith:A}}}class DF extends cT{static[O]="WithSubquery"}var eW="0.41.0";var DJ,CJ,wT={startActiveSpan(T,o){if(!DJ)return o();if(!CJ)CJ=DJ.trace.getTracer("drizzle-orm",eW);return qf((y,A)=>A.startActiveSpan(T,(F)=>{try{return o(F)}catch(f){throw F.setStatus({code:y.SpanStatusCode.ERROR,message:f instanceof Error?f.message:"Unknown error"}),f}finally{F.end()}}),DJ,CJ)}};var VT=Symbol.for("drizzle:ViewBaseConfig");var Pf=Symbol.for("drizzle:Schema"),hf=Symbol.for("drizzle:Columns"),TO=Symbol.for("drizzle:ExtraConfigColumns"),LJ=Symbol.for("drizzle:OriginalName"),IJ=Symbol.for("drizzle:BaseName"),CF=Symbol.for("drizzle:IsAlias"),oO=Symbol.for("drizzle:ExtraConfigBuilder"),ZZ=Symbol.for("drizzle:IsDrizzleTable");class b{static[O]="Table";static Symbol={Name:io,Schema:Pf,OriginalName:LJ,Columns:hf,ExtraConfigColumns:TO,BaseName:IJ,IsAlias:CF,ExtraConfigBuilder:oO};[io];[LJ];[Pf];[hf];[TO];[IJ];[CF]=!1;[ZZ]=!0;[oO]=void 0;constructor(T,o,y){this[io]=this[LJ]=T,this[Pf]=o,this[IJ]=y}}function lT(T){return T[io]}function cy(T){return`${T[Pf]??"public"}.${T[io]}`}function kJ(T){return T!==null&&T!==void 0&&typeof T.getSQL==="function"}function HZ(T){let o={sql:"",params:[]};for(let y of T)if(o.sql+=y.sql,o.params.push(...y.params),y.typings?.length){if(!o.typings)o.typings=[];o.typings.push(...y.typings)}return o}class dT{static[O]="StringChunk";value;constructor(T){this.value=Array.isArray(T)?T:[T]}getSQL(){return new x([this])}}class x{constructor(T){this.queryChunks=T}static[O]="SQL";decoder=AO;shouldInlineParams=!1;append(T){return this.queryChunks.push(...T.queryChunks),this}toQuery(T){return wT.startActiveSpan("drizzle.buildSQL",(o)=>{let y=this.buildQueryFromSourceParams(this.queryChunks,T);return o?.setAttributes({"drizzle.query.text":y.sql,"drizzle.query.params":JSON.stringify(y.params)}),y})}buildQueryFromSourceParams(T,o){let y=Object.assign({},o,{inlineParams:o.inlineParams||this.shouldInlineParams,paramStartIndex:o.paramStartIndex||{value:0}}),{casing:A,escapeName:F,escapeParam:f,prepareTyping:S,inlineParams:$,paramStartIndex:_}=y;return HZ(T.map((J)=>{if(G(J,dT))return{sql:J.value.join(""),params:[]};if(G(J,nf))return{sql:F(J.value),params:[]};if(J===void 0)return{sql:"",params:[]};if(Array.isArray(J)){let R=[new dT("(")];for(let[M,Y]of J.entries())if(R.push(Y),M<J.length-1)R.push(new dT(", "));return R.push(new dT(")")),this.buildQueryFromSourceParams(R,y)}if(G(J,x))return this.buildQueryFromSourceParams(J.queryChunks,{...y,inlineParams:$||J.shouldInlineParams});if(G(J,b)){let R=J[b.Symbol.Schema],M=J[b.Symbol.Name];return{sql:R===void 0||J[CF]?F(M):F(R)+"."+F(M),params:[]}}if(G(J,GT)){let R=A.getColumnCasing(J);if(o.invokeSource==="indexes")return{sql:F(R),params:[]};let M=J.table[b.Symbol.Schema];return{sql:J.table[CF]||M===void 0?F(J.table[b.Symbol.Name])+"."+F(R):F(M)+"."+F(J.table[b.Symbol.Name])+"."+F(R),params:[]}}if(G(J,Uo)){let R=J[VT].schema,M=J[VT].name;return{sql:R===void 0||J[VT].isAlias?F(M):F(R)+"."+F(M),params:[]}}if(G(J,Co)){if(G(J.value,Ny))return{sql:f(_.value++,J),params:[J],typings:["none"]};let R=J.value===null?null:J.encoder.mapToDriverValue(J.value);if(G(R,x))return this.buildQueryFromSourceParams([R],y);if($)return{sql:this.mapInlineParam(R,y),params:[]};let M=["none"];if(S)M=[S(J.encoder)];return{sql:f(_.value++,R),params:[R],typings:M}}if(G(J,Ny))return{sql:f(_.value++,J),params:[J],typings:["none"]};if(G(J,x.Aliased)&&J.fieldAlias!==void 0)return{sql:F(J.fieldAlias),params:[]};if(G(J,cT)){if(J._.isWith)return{sql:F(J._.alias),params:[]};return this.buildQueryFromSourceParams([new dT("("),J._.sql,new dT(") "),new nf(J._.alias)],y)}if(lW(J)){if(J.schema)return{sql:F(J.schema)+"."+F(J.enumName),params:[]};return{sql:F(J.enumName),params:[]}}if(kJ(J)){if(J.shouldOmitSQLParens?.())return this.buildQueryFromSourceParams([J.getSQL()],y);return this.buildQueryFromSourceParams([new dT("("),J.getSQL(),new dT(")")],y)}if($)return{sql:this.mapInlineParam(J,y),params:[]};return{sql:f(_.value++,J),params:[J],typings:["none"]}}))}mapInlineParam(T,{escapeString:o}){if(T===null)return"null";if(typeof T==="number"||typeof T==="boolean")return T.toString();if(typeof T==="string")return o(T);if(typeof T==="object"){let y=T.toString();if(y==="[object Object]")return o(JSON.stringify(T));return o(y)}throw new Error("Unexpected param value: "+T)}getSQL(){return this}as(T){if(T===void 0)return this;return new x.Aliased(this,T)}mapWith(T){return this.decoder=typeof T==="function"?{mapFromDriverValue:T}:T,this}inlineParams(){return this.shouldInlineParams=!0,this}if(T){return T?this:void 0}}class nf{constructor(T){this.value=T}static[O]="Name";brand;getSQL(){return new x([this])}}function yO(T){return typeof T==="object"&&T!==null&&"mapToDriverValue"in T&&typeof T.mapToDriverValue==="function"}var AO={mapFromDriverValue:(T)=>T},FO={mapToDriverValue:(T)=>T},lb={...AO,...FO};class Co{constructor(T,o=FO){this.value=T,this.encoder=o}static[O]="Param";brand;getSQL(){return new x([this])}}function X(T,...o){let y=[];if(o.length>0||T.length>0&&T[0]!=="")y.push(new dT(T[0]));for(let[A,F]of o.entries())y.push(F,new dT(T[A+1]));return new x(y)}((T)=>{function o(){return new x([])}T.empty=o;function y(_){return new x(_)}T.fromList=y;function A(_){return new x([new dT(_)])}T.raw=A;function F(_,J){let R=[];for(let[M,Y]of _.entries()){if(M>0&&J!==void 0)R.push(J);R.push(Y)}return new x(R)}T.join=F;function f(_){return new nf(_)}T.identifier=f;function S(_){return new Ny(_)}T.placeholder=S;function $(_,J){return new Co(_,J)}T.param=$})(X||(X={}));((T)=>{class o{constructor(y,A){this.sql=y,this.fieldAlias=A}static[O]="SQL.Aliased";isSelectionField=!1;getSQL(){return this.sql}clone(){return new o(this.sql,this.fieldAlias)}}T.Aliased=o})(x||(x={}));class Ny{constructor(T){this.name=T}static[O]="Placeholder";getSQL(){return new x([this])}}function BJ(T,o){return T.map((y)=>{if(G(y,Ny)){if(!(y.name in o))throw new Error(`No value for placeholder "${y.name}" was provided`);return o[y.name]}if(G(y,Co)&&G(y.value,Ny)){if(!(y.value.name in o))throw new Error(`No value for placeholder "${y.value.name}" was provided`);return y.encoder.mapToDriverValue(o[y.value.name])}return y})}var EZ=Symbol.for("drizzle:IsDrizzleView");class Uo{static[O]="View";[VT];[EZ]=!0;constructor({name:T,schema:o,selectedFields:y,query:A}){this[VT]={name:T,originalName:T,schema:o,selectedFields:y,query:A,isExisting:!A,isAlias:!1}}getSQL(){return new x([this])}}GT.prototype.getSQL=function(){return new x([this])};b.prototype.getSQL=function(){return new x([this])};cT.prototype.getSQL=function(){return new x([this])};class IA{constructor(T){this.table=T}static[O]="ColumnAliasProxyHandler";get(T,o){if(o==="table")return this.table;return T[o]}}class LF{constructor(T,o){this.alias=T,this.replaceOriginalName=o}static[O]="TableAliasProxyHandler";get(T,o){if(o===b.Symbol.IsAlias)return!0;if(o===b.Symbol.Name)return this.alias;if(this.replaceOriginalName&&o===b.Symbol.OriginalName)return this.alias;if(o===VT)return{...T[VT],name:this.alias,isAlias:!0};if(o===b.Symbol.Columns){let A=T[b.Symbol.Columns];if(!A)return A;let F={};return Object.keys(A).map((f)=>{F[f]=new Proxy(A[f],new IA(new Proxy(T,this)))}),F}let y=T[o];if(G(y,GT))return new Proxy(y,new IA(new Proxy(T,this)));return y}}function gf(T,o){return new Proxy(T,new LF(o,!1))}function oy(T,o){return new Proxy(T,new IA(new Proxy(T.table,new LF(o,!1))))}function NJ(T,o){return new x.Aliased(IF(T.sql,o),T.fieldAlias)}function IF(T,o){return X.join(T.queryChunks.map((y)=>{if(G(y,GT))return oy(y,o);if(G(y,x))return IF(y,o);if(G(y,x.Aliased))return NJ(y,o);return y}))}class uf extends Error{static[O]="DrizzleError";constructor({message:T,cause:o}){super(T);this.name="DrizzleError",this.cause=o}}class tJ extends uf{static[O]="TransactionRollbackError";constructor(){super({message:"Rollback"})}}function Ko(T,o){if(yO(o)&&!kJ(T)&&!G(T,Co)&&!G(T,Ny)&&!G(T,GT)&&!G(T,b)&&!G(T,Uo))return new Co(T,o);return T}var cf=(T,o)=>{return X`${T} = ${Ko(o,T)}`},fO=(T,o)=>{return X`${T} <> ${Ko(o,T)}`};function kF(...T){let o=T.filter((y)=>y!==void 0);if(o.length===0)return;if(o.length===1)return new x(o);return new x([new dT("("),X.join(o,new dT(" and ")),new dT(")")])}function SO(...T){let o=T.filter((y)=>y!==void 0);if(o.length===0)return;if(o.length===1)return new x(o);return new x([new dT("("),X.join(o,new dT(" or ")),new dT(")")])}function $O(T){return X`not ${T}`}var JO=(T,o)=>{return X`${T} > ${Ko(o,T)}`},_O=(T,o)=>{return X`${T} >= ${Ko(o,T)}`},RO=(T,o)=>{return X`${T} < ${Ko(o,T)}`},WO=(T,o)=>{return X`${T} <= ${Ko(o,T)}`};function OO(T,o){if(Array.isArray(o)){if(o.length===0)return X`false`;return X`${T} in ${o.map((y)=>Ko(y,T))}`}return X`${T} in ${Ko(o,T)}`}function MO(T,o){if(Array.isArray(o)){if(o.length===0)return X`true`;return X`${T} not in ${o.map((y)=>Ko(y,T))}`}return X`${T} not in ${Ko(o,T)}`}function XO(T){return X`${T} is null`}function YO(T){return X`${T} is not null`}function ZO(T){return X`exists ${T}`}function HO(T){return X`not exists ${T}`}function EO(T,o,y){return X`${T} between ${Ko(o,T)} and ${Ko(y,T)}`}function GO(T,o,y){return X`${T} not between ${Ko(o,T)} and ${Ko(y,T)}`}function wO(T,o){return X`${T} like ${o}`}function UO(T,o){return X`${T} not like ${o}`}function KO(T,o){return X`${T} ilike ${o}`}function zO(T,o){return X`${T} not ilike ${o}`}function QO(T){return X`${T} asc`}function VO(T){return X`${T} desc`}class DO{static[O]="ConsoleLogWriter";write(T){console.log(T)}}class pJ{static[O]="DefaultLogger";writer;constructor(T){this.writer=T?.writer??new DO}logQuery(T,o){let y=o.map((F)=>{try{return JSON.stringify(F)}catch{return String(F)}}),A=y.length?` -- params: [${y.join(", ")}]`:"";this.writer.write(`Query: ${T}${A}`)}}class bJ{static[O]="NoopLogger";logQuery(){}}class Oo{static[O]="QueryPromise";[Symbol.toStringTag]="QueryPromise";catch(T){return this.then(void 0,T)}finally(T){return this.then((o)=>{return T?.(),o},(o)=>{throw T?.(),o})}then(T,o){return this.execute().then(T,o)}}function CO(T,o,y){let A={},F=T.reduce((f,{path:S,field:$},_)=>{let J;if(G($,GT))J=$;else if(G($,x))J=$.decoder;else J=$.sql.decoder;let R=f;for(let[M,Y]of S.entries())if(M<S.length-1){if(!(Y in R))R[Y]={};R=R[Y]}else{let H=o[_],Q=R[Y]=H===null?null:J.mapFromDriverValue(H);if(y&&G($,GT)&&S.length===2){let w=S[0];if(!(w in A))A[w]=Q===null?lT($.table):!1;else if(typeof A[w]==="string"&&A[w]!==lT($.table))A[w]=!1}}return f},{});if(y&&Object.keys(A).length>0){for(let[f,S]of Object.entries(A))if(typeof S==="string"&&!y[S])F[f]=null}return F}function jo(T,o){return Object.entries(T).reduce((y,[A,F])=>{if(typeof A!=="string")return y;let f=o?[...o,A]:[A];if(G(F,GT)||G(F,x)||G(F,x.Aliased))y.push({path:f,field:F});else if(G(F,b))y.push(...jo(F[b.Symbol.Columns],f));else y.push(...jo(F,f));return y},[])}function BF(T,o){let y=Object.keys(T),A=Object.keys(o);if(y.length!==A.length)return!1;for(let[F,f]of y.entries())if(f!==A[F])return!1;return!0}function df(T,o){let y=Object.entries(o).filter(([,A])=>A!==void 0).map(([A,F])=>{if(G(F,x)||G(F,GT))return[A,F];else return[A,new Co(F,T[b.Symbol.Columns][A])]});if(y.length===0)throw new Error("No values to set");return Object.fromEntries(y)}function LO(T,o){for(let y of o)for(let A of Object.getOwnPropertyNames(y.prototype)){if(A==="constructor")continue;Object.defineProperty(T.prototype,A,Object.getOwnPropertyDescriptor(y.prototype,A)||Object.create(null))}}function IO(T){return T[b.Symbol.Columns]}function Ey(T){return G(T,cT)?T._.alias:G(T,Uo)?T[VT].name:G(T,x)?void 0:T[b.Symbol.IsAlias]?T[b.Symbol.Name]:T[b.Symbol.BaseName]}function ST(T,o){return{name:typeof T==="string"&&T.length>0?T:"",config:typeof T==="object"?T:o}}function kO(T){if(typeof T!=="object"||T===null)return!1;if(T.constructor.name!=="Object")return!1;if("logger"in T){let o=typeof T.logger;if(o!=="boolean"&&(o!=="object"||typeof T.logger.logQuery!=="function")&&o!=="undefined")return!1;return!0}if("schema"in T){let o=typeof T.schema;if(o!=="object"&&o!=="undefined")return!1;return!0}if("casing"in T){let o=typeof T.casing;if(o!=="string"&&o!=="undefined")return!1;return!0}if("mode"in T){if(T.mode!=="default"||T.mode!=="planetscale"||T.mode!==void 0)return!1;return!0}if("connection"in T){let o=typeof T.connection;if(o!=="string"&&o!=="object"&&o!=="undefined")return!1;return!0}if("client"in T){let o=typeof T.client;if(o!=="object"&&o!=="function"&&o!=="undefined")return!1;return!0}if(Object.keys(T).length===0)return!0;return!1}class ty extends j{static[O]="PgIntColumnBaseBuilder";generatedAlwaysAsIdentity(T){if(T){let{name:o,...y}=T;this.config.generatedIdentity={type:"always",sequenceName:o,sequenceOptions:y}}else this.config.generatedIdentity={type:"always"};return this.config.hasDefault=!0,this.config.notNull=!0,this}generatedByDefaultAsIdentity(T){if(T){let{name:o,...y}=T;this.config.generatedIdentity={type:"byDefault",sequenceName:o,sequenceOptions:y}}else this.config.generatedIdentity={type:"byDefault"};return this.config.hasDefault=!0,this.config.notNull=!0,this}}class BO extends ty{static[O]="PgBigInt53Builder";constructor(T){super(T,"number","PgBigInt53")}build(T){return new NO(T,this.config)}}class NO extends I{static[O]="PgBigInt53";getSQLType(){return"bigint"}mapFromDriverValue(T){if(typeof T==="number")return T;return Number(T)}}class tO extends ty{static[O]="PgBigInt64Builder";constructor(T){super(T,"bigint","PgBigInt64")}build(T){return new pO(T,this.config)}}class pO extends I{static[O]="PgBigInt64";getSQLType(){return"bigint"}mapFromDriverValue(T){return BigInt(T)}}function bO(T,o){let{name:y,config:A}=ST(T,o);if(A.mode==="number")return new BO(y);return new tO(y)}class xO extends j{static[O]="PgBigSerial53Builder";constructor(T){super(T,"number","PgBigSerial53");this.config.hasDefault=!0,this.config.notNull=!0}build(T){return new jO(T,this.config)}}class jO extends I{static[O]="PgBigSerial53";getSQLType(){return"bigserial"}mapFromDriverValue(T){if(typeof T==="number")return T;return Number(T)}}class mO extends j{static[O]="PgBigSerial64Builder";constructor(T){super(T,"bigint","PgBigSerial64");this.config.hasDefault=!0}build(T){return new qO(T,this.config)}}class qO extends I{static[O]="PgBigSerial64";getSQLType(){return"bigserial"}mapFromDriverValue(T){return BigInt(T)}}function vO(T,o){let{name:y,config:A}=ST(T,o);if(A.mode==="number")return new xO(y);return new mO(y)}class PO extends j{static[O]="PgBooleanBuilder";constructor(T){super(T,"boolean","PgBoolean")}build(T){return new hO(T,this.config)}}class hO extends I{static[O]="PgBoolean";getSQLType(){return"boolean"}}function NF(T){return new PO(T??"")}class nO extends j{static[O]="PgCharBuilder";constructor(T,o){super(T,"string","PgChar");this.config.length=o.length,this.config.enumValues=o.enum}build(T){return new gO(T,this.config)}}class gO extends I{static[O]="PgChar";length=this.config.length;enumValues=this.config.enumValues;getSQLType(){return this.length===void 0?"char":`char(${this.length})`}}function uO(T,o={}){let{name:y,config:A}=ST(T,o);return new nO(y,A)}class iO extends j{static[O]="PgCidrBuilder";constructor(T){super(T,"string","PgCidr")}build(T){return new cO(T,this.config)}}class cO extends I{static[O]="PgCidr";getSQLType(){return"cidr"}}function dO(T){return new iO(T??"")}class rO extends j{static[O]="PgCustomColumnBuilder";constructor(T,o,y){super(T,"custom","PgCustomColumn");this.config.fieldConfig=o,this.config.customTypeParams=y}build(T){return new lO(T,this.config)}}class lO extends I{static[O]="PgCustomColumn";sqlName;mapTo;mapFrom;constructor(T,o){super(T,o);this.sqlName=o.customTypeParams.dataType(o.fieldConfig),this.mapTo=o.customTypeParams.toDriver,this.mapFrom=o.customTypeParams.fromDriver}getSQLType(){return this.sqlName}mapFromDriverValue(T){return typeof this.mapFrom==="function"?this.mapFrom(T):T}mapToDriverValue(T){return typeof this.mapTo==="function"?this.mapTo(T):T}}function sO(T){return(o,y)=>{let{name:A,config:F}=ST(o,y);return new rO(A,F,T)}}class Gy extends j{static[O]="PgDateColumnBaseBuilder";defaultNow(){return this.default(X`now()`)}}class aO extends Gy{static[O]="PgDateBuilder";constructor(T){super(T,"date","PgDate")}build(T){return new rf(T,this.config)}}class rf extends I{static[O]="PgDate";getSQLType(){return"date"}mapFromDriverValue(T){return new Date(T)}mapToDriverValue(T){return T.toISOString()}}class eO extends Gy{static[O]="PgDateStringBuilder";constructor(T){super(T,"string","PgDateString")}build(T){return new lf(T,this.config)}}class lf extends I{static[O]="PgDateString";getSQLType(){return"date"}}function TM(T,o){let{name:y,config:A}=ST(T,o);if(A?.mode==="date")return new aO(y);return new eO(y)}class oM extends j{static[O]="PgDoublePrecisionBuilder";constructor(T){super(T,"number","PgDoublePrecision")}build(T){return new yM(T,this.config)}}class yM extends I{static[O]="PgDoublePrecision";getSQLType(){return"double precision"}mapFromDriverValue(T){if(typeof T==="string")return Number.parseFloat(T);return T}}function AM(T){return new oM(T??"")}class FM extends j{static[O]="PgInetBuilder";constructor(T){super(T,"string","PgInet")}build(T){return new fM(T,this.config)}}class fM extends I{static[O]="PgInet";getSQLType(){return"inet"}}function SM(T){return new FM(T??"")}class $M extends ty{static[O]="PgIntegerBuilder";constructor(T){super(T,"number","PgInteger")}build(T){return new JM(T,this.config)}}class JM extends I{static[O]="PgInteger";getSQLType(){return"integer"}mapFromDriverValue(T){if(typeof T==="string")return Number.parseInt(T);return T}}function sf(T){return new $M(T??"")}class _M extends j{static[O]="PgIntervalBuilder";constructor(T,o){super(T,"string","PgInterval");this.config.intervalConfig=o}build(T){return new RM(T,this.config)}}class RM extends I{static[O]="PgInterval";fields=this.config.intervalConfig.fields;precision=this.config.intervalConfig.precision;getSQLType(){let T=this.fields?` ${this.fields}`:"",o=this.precision?`(${this.precision})`:"";return`interval${T}${o}`}}function WM(T,o={}){let{name:y,config:A}=ST(T,o);return new _M(y,A)}class OM extends j{static[O]="PgJsonBuilder";constructor(T){super(T,"json","PgJson")}build(T){return new af(T,this.config)}}class af extends I{static[O]="PgJson";constructor(T,o){super(T,o)}getSQLType(){return"json"}mapToDriverValue(T){return JSON.stringify(T)}mapFromDriverValue(T){if(typeof T==="string")try{return JSON.parse(T)}catch{return T}return T}}function MM(T){return new OM(T??"")}class XM extends j{static[O]="PgJsonbBuilder";constructor(T){super(T,"json","PgJsonb")}build(T){return new ef(T,this.config)}}class ef extends I{static[O]="PgJsonb";constructor(T,o){super(T,o)}getSQLType(){return"jsonb"}mapToDriverValue(T){return JSON.stringify(T)}mapFromDriverValue(T){if(typeof T==="string")try{return JSON.parse(T)}catch{return T}return T}}function YM(T){return new XM(T??"")}class ZM extends j{static[O]="PgLineBuilder";constructor(T){super(T,"array","PgLine")}build(T){return new HM(T,this.config)}}class HM extends I{static[O]="PgLine";getSQLType(){return"line"}mapFromDriverValue(T){let[o,y,A]=T.slice(1,-1).split(",");return[Number.parseFloat(o),Number.parseFloat(y),Number.parseFloat(A)]}mapToDriverValue(T){return`{${T[0]},${T[1]},${T[2]}}`}}class EM extends j{static[O]="PgLineABCBuilder";constructor(T){super(T,"json","PgLineABC")}build(T){return new GM(T,this.config)}}class GM extends I{static[O]="PgLineABC";getSQLType(){return"line"}mapFromDriverValue(T){let[o,y,A]=T.slice(1,-1).split(",");return{a:Number.parseFloat(o),b:Number.parseFloat(y),c:Number.parseFloat(A)}}mapToDriverValue(T){return`{${T.a},${T.b},${T.c}}`}}function wM(T,o){let{name:y,config:A}=ST(T,o);if(!A?.mode||A.mode==="tuple")return new ZM(y);return new EM(y)}class UM extends j{static[O]="PgMacaddrBuilder";constructor(T){super(T,"string","PgMacaddr")}build(T){return new KM(T,this.config)}}class KM extends I{static[O]="PgMacaddr";getSQLType(){return"macaddr"}}function zM(T){return new UM(T??"")}class QM extends j{static[O]="PgMacaddr8Builder";constructor(T){super(T,"string","PgMacaddr8")}build(T){return new VM(T,this.config)}}class VM extends I{static[O]="PgMacaddr8";getSQLType(){return"macaddr8"}}function DM(T){return new QM(T??"")}class CM extends j{static[O]="PgNumericBuilder";constructor(T,o,y){super(T,"string","PgNumeric");this.config.precision=o,this.config.scale=y}build(T){return new TS(T,this.config)}}class TS extends I{static[O]="PgNumeric";precision;scale;constructor(T,o){super(T,o);this.precision=o.precision,this.scale=o.scale}mapFromDriverValue(T){if(typeof T==="string")return T;return String(T)}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})`}}class LM extends j{static[O]="PgNumericNumberBuilder";constructor(T,o,y){super(T,"number","PgNumericNumber");this.config.precision=o,this.config.scale=y}build(T){return new IM(T,this.config)}}class IM extends I{static[O]="PgNumericNumber";precision;scale;constructor(T,o){super(T,o);this.precision=o.precision,this.scale=o.scale}mapFromDriverValue(T){if(typeof T==="number")return T;return Number(T)}mapToDriverValue=String;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})`}}class kM extends j{static[O]="PgNumericBigIntBuilder";constructor(T,o,y){super(T,"bigint","PgNumericBigInt");this.config.precision=o,this.config.scale=y}build(T){return new BM(T,this.config)}}class BM extends I{static[O]="PgNumericBigInt";precision;scale;constructor(T,o){super(T,o);this.precision=o.precision,this.scale=o.scale}mapFromDriverValue=BigInt;mapToDriverValue=String;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 NM(T,o){let{name:y,config:A}=ST(T,o),F=A?.mode;return F==="number"?new LM(y,A?.precision,A?.scale):F==="bigint"?new kM(y,A?.precision,A?.scale):new CM(y,A?.precision,A?.scale)}class tM extends j{static[O]="PgPointTupleBuilder";constructor(T){super(T,"array","PgPointTuple")}build(T){return new pM(T,this.config)}}class pM extends I{static[O]="PgPointTuple";getSQLType(){return"point"}mapFromDriverValue(T){if(typeof T==="string"){let[o,y]=T.slice(1,-1).split(",");return[Number.parseFloat(o),Number.parseFloat(y)]}return[T.x,T.y]}mapToDriverValue(T){return`(${T[0]},${T[1]})`}}class bM extends j{static[O]="PgPointObjectBuilder";constructor(T){super(T,"json","PgPointObject")}build(T){return new xM(T,this.config)}}class xM extends I{static[O]="PgPointObject";getSQLType(){return"point"}mapFromDriverValue(T){if(typeof T==="string"){let[o,y]=T.slice(1,-1).split(",");return{x:Number.parseFloat(o),y:Number.parseFloat(y)}}return T}mapToDriverValue(T){return`(${T.x},${T.y})`}}function jM(T,o){let{name:y,config:A}=ST(T,o);if(!A?.mode||A.mode==="tuple")return new tM(y);return new bM(y)}function GZ(T){let o=[];for(let y=0;y<T.length;y+=2)o.push(Number.parseInt(T.slice(y,y+2),16));return new Uint8Array(o)}function mM(T,o){let y=new ArrayBuffer(8),A=new DataView(y);for(let F=0;F<8;F++)A.setUint8(F,T[o+F]);return A.getFloat64(0,!0)}function xJ(T){let o=GZ(T),y=0,A=o[y];y+=1;let F=new DataView(o.buffer),f=F.getUint32(y,A===1);y+=4;let S;if(f&536870912)S=F.getUint32(y,A===1),y+=4;if((f&65535)===1){let $=mM(o,y);y+=8;let _=mM(o,y);return y+=8,[$,_]}throw new Error("Unsupported geometry type")}class qM extends j{static[O]="PgGeometryBuilder";constructor(T){super(T,"array","PgGeometry")}build(T){return new vM(T,this.config)}}class vM extends I{static[O]="PgGeometry";getSQLType(){return"geometry(point)"}mapFromDriverValue(T){return xJ(T)}mapToDriverValue(T){return`point(${T[0]} ${T[1]})`}}class PM extends j{static[O]="PgGeometryObjectBuilder";constructor(T){super(T,"json","PgGeometryObject")}build(T){return new hM(T,this.config)}}class hM extends I{static[O]="PgGeometryObject";getSQLType(){return"geometry(point)"}mapFromDriverValue(T){let o=xJ(T);return{x:o[0],y:o[1]}}mapToDriverValue(T){return`point(${T.x} ${T.y})`}}function nM(T,o){let{name:y,config:A}=ST(T,o);if(!A?.mode||A.mode==="tuple")return new qM(y);return new PM(y)}class gM extends j{static[O]="PgRealBuilder";constructor(T,o){super(T,"number","PgReal");this.config.length=o}build(T){return new uM(T,this.config)}}class uM extends I{static[O]="PgReal";constructor(T,o){super(T,o)}getSQLType(){return"real"}mapFromDriverValue=(T)=>{if(typeof T==="string")return Number.parseFloat(T);return T}}function iM(T){return new gM(T??"")}class cM extends j{static[O]="PgSerialBuilder";constructor(T){super(T,"number","PgSerial");this.config.hasDefault=!0,this.config.notNull=!0}build(T){return new dM(T,this.config)}}class dM extends I{static[O]="PgSerial";getSQLType(){return"serial"}}function rM(T){return new cM(T??"")}class lM extends ty{static[O]="PgSmallIntBuilder";constructor(T){super(T,"number","PgSmallInt")}build(T){return new sM(T,this.config)}}class sM extends I{static[O]="PgSmallInt";getSQLType(){return"smallint"}mapFromDriverValue=(T)=>{if(typeof T==="string")return Number(T);return T}}function aM(T){return new lM(T??"")}class eM extends j{static[O]="PgSmallSerialBuilder";constructor(T){super(T,"number","PgSmallSerial");this.config.hasDefault=!0,this.config.notNull=!0}build(T){return new T2(T,this.config)}}class T2 extends I{static[O]="PgSmallSerial";getSQLType(){return"smallserial"}}function o2(T){return new eM(T??"")}class y2 extends j{static[O]="PgTextBuilder";constructor(T,o){super(T,"string","PgText");this.config.enumValues=o.enum}build(T){return new A2(T,this.config)}}class A2 extends I{static[O]="PgText";enumValues=this.config.enumValues;getSQLType(){return"text"}}function F2(T,o={}){let{name:y,config:A}=ST(T,o);return new y2(y,A)}class f2 extends Gy{constructor(T,o,y){super(T,"string","PgTime");this.withTimezone=o,this.precision=y,this.config.withTimezone=o,this.config.precision=y}static[O]="PgTimeBuilder";build(T){return new oS(T,this.config)}}class oS extends I{static[O]="PgTime";withTimezone;precision;constructor(T,o){super(T,o);this.withTimezone=o.withTimezone,this.precision=o.precision}getSQLType(){return`time${this.precision===void 0?"":`(${this.precision})`}${this.withTimezone?" with time zone":""}`}}function S2(T,o={}){let{name:y,config:A}=ST(T,o);return new f2(y,A.withTimezone??!1,A.precision)}class $2 extends Gy{static[O]="PgTimestampBuilder";constructor(T,o,y){super(T,"date","PgTimestamp");this.config.withTimezone=o,this.config.precision=y}build(T){return new yS(T,this.config)}}class yS extends I{static[O]="PgTimestamp";withTimezone;precision;constructor(T,o){super(T,o);this.withTimezone=o.withTimezone,this.precision=o.precision}getSQLType(){return`timestamp${this.precision===void 0?"":` (${this.precision})`}${this.withTimezone?" with time zone":""}`}mapFromDriverValue=(T)=>{return new Date(this.withTimezone?T:T+"+0000")};mapToDriverValue=(T)=>{return T.toISOString()}}class J2 extends Gy{static[O]="PgTimestampStringBuilder";constructor(T,o,y){super(T,"string","PgTimestampString");this.config.withTimezone=o,this.config.precision=y}build(T){return new AS(T,this.config)}}class AS extends I{static[O]="PgTimestampString";withTimezone;precision;constructor(T,o){super(T,o);this.withTimezone=o.withTimezone,this.precision=o.precision}getSQLType(){return`timestamp${this.precision===void 0?"":`(${this.precision})`}${this.withTimezone?" with time zone":""}`}}function co(T,o={}){let{name:y,config:A}=ST(T,o);if(A?.mode==="string")return new J2(y,A.withTimezone??!1,A.precision);return new $2(y,A?.withTimezone??!1,A?.precision)}class _2 extends j{static[O]="PgUUIDBuilder";constructor(T){super(T,"string","PgUUID")}defaultRandom(){return this.default(X`gen_random_uuid()`)}build(T){return new FS(T,this.config)}}class FS extends I{static[O]="PgUUID";getSQLType(){return"uuid"}}function Lo(T){return new _2(T??"")}class R2 extends j{static[O]="PgVarcharBuilder";constructor(T,o){super(T,"string","PgVarchar");this.config.length=o.length,this.config.enumValues=o.enum}build(T){return new W2(T,this.config)}}class W2 extends I{static[O]="PgVarchar";length=this.config.length;enumValues=this.config.enumValues;getSQLType(){return this.length===void 0?"varchar":`varchar(${this.length})`}}function eT(T,o={}){let{name:y,config:A}=ST(T,o);return new R2(y,A)}class O2 extends j{static[O]="PgBinaryVectorBuilder";constructor(T,o){super(T,"string","PgBinaryVector");this.config.dimensions=o.dimensions}build(T){return new M2(T,this.config)}}class M2 extends I{static[O]="PgBinaryVector";dimensions=this.config.dimensions;getSQLType(){return`bit(${this.dimensions})`}}function X2(T,o){let{name:y,config:A}=ST(T,o);return new O2(y,A)}class Y2 extends j{static[O]="PgHalfVectorBuilder";constructor(T,o){super(T,"array","PgHalfVector");this.config.dimensions=o.dimensions}build(T){return new Z2(T,this.config)}}class Z2 extends I{static[O]="PgHalfVector";dimensions=this.config.dimensions;getSQLType(){return`halfvec(${this.dimensions})`}mapToDriverValue(T){return JSON.stringify(T)}mapFromDriverValue(T){return T.slice(1,-1).split(",").map((o)=>Number.parseFloat(o))}}function H2(T,o){let{name:y,config:A}=ST(T,o);return new Y2(y,A)}class E2 extends j{static[O]="PgSparseVectorBuilder";constructor(T,o){super(T,"string","PgSparseVector");this.config.dimensions=o.dimensions}build(T){return new G2(T,this.config)}}class G2 extends I{static[O]="PgSparseVector";dimensions=this.config.dimensions;getSQLType(){return`sparsevec(${this.dimensions})`}}function w2(T,o){let{name:y,config:A}=ST(T,o);return new E2(y,A)}class U2 extends j{static[O]="PgVectorBuilder";constructor(T,o){super(T,"array","PgVector");this.config.dimensions=o.dimensions}build(T){return new K2(T,this.config)}}class K2 extends I{static[O]="PgVector";dimensions=this.config.dimensions;getSQLType(){return`vector(${this.dimensions})`}mapToDriverValue(T){return JSON.stringify(T)}mapFromDriverValue(T){return T.slice(1,-1).split(",").map((o)=>Number.parseFloat(o))}}function z2(T,o){let{name:y,config:A}=ST(T,o);return new U2(y,A)}function Q2(){return{bigint:bO,bigserial:vO,boolean:NF,char:uO,cidr:dO,customType:sO,date:TM,doublePrecision:AM,inet:SM,integer:sf,interval:WM,json:MM,jsonb:YM,line:wM,macaddr:zM,macaddr8:DM,numeric:NM,point:jM,geometry:nM,real:iM,serial:rM,smallint:aM,smallserial:o2,text:F2,time:S2,timestamp:co,uuid:Lo,varchar:eT,bit:X2,halfvec:H2,sparsevec:w2,vector:z2}}var jJ=Symbol.for("drizzle:PgInlineForeignKeys"),V2=Symbol.for("drizzle:EnableRLS");class To extends b{static[O]="PgTable";static Symbol=Object.assign({},b.Symbol,{InlineForeignKeys:jJ,EnableRLS:V2});[jJ]=[];[V2]=!1;[b.Symbol.ExtraConfigBuilder]=void 0;[b.Symbol.ExtraConfigColumns]={}}function wZ(T,o,y,A,F=T){let f=new To(T,A,F),S=typeof o==="function"?o(Q2()):o,$=Object.fromEntries(Object.entries(S).map(([R,M])=>{let Y=M;Y.setName(R);let H=Y.build(f);return f[jJ].push(...Y.buildForeignKeys(H,f)),[R,H]})),_=Object.fromEntries(Object.entries(S).map(([R,M])=>{let Y=M;Y.setName(R);let H=Y.buildExtraConfigColumn(f);return[R,H]})),J=Object.assign(f,$);if(J[b.Symbol.Columns]=$,J[b.Symbol.ExtraConfigColumns]=_,y)J[To.Symbol.ExtraConfigBuilder]=y;return Object.assign(J,{enableRLS:()=>{return J[To.Symbol.EnableRLS]=!0,J}})}var py=(T,o,y)=>{return wZ(T,o,y,void 0)};function D2(...T){if(T[0].columns)return new tF(T[0].columns,T[0].name);return new tF(T)}class tF{static[O]="PgPrimaryKeyBuilder";columns;name;constructor(T,o){this.columns=T,this.name=o}build(T){return new C2(T,this.columns,this.name)}}class C2{constructor(T,o,y){this.table=T,this.columns=o,this.name=y}static[O]="PgPrimaryKey";columns;name;getName(){return this.name??`${this.table[To.Symbol.Name]}_${this.columns.map((T)=>T.name).join("_")}_pk`}}class mJ{constructor(T,o,y){this.sourceTable=T,this.referencedTable=o,this.relationName=y,this.referencedTableName=o[b.Symbol.Name]}static[O]="Relation";referencedTableName;fieldName}class L2{constructor(T,o){this.table=T,this.config=o}static[O]="Relations"}class by extends mJ{constructor(T,o,y,A){super(T,o,y?.relationName);this.config=y,this.isNullable=A}static[O]="One";withFieldName(T){let o=new by(this.sourceTable,this.referencedTable,this.config,this.isNullable);return o.fieldName=T,o}}class pF extends mJ{constructor(T,o,y){super(T,o,y?.relationName);this.config=y}static[O]="Many";withFieldName(T){let o=new pF(this.sourceTable,this.referencedTable,this.config);return o.fieldName=T,o}}function I2(){return{and:kF,between:EO,eq:cf,exists:ZO,gt:JO,gte:_O,ilike:KO,inArray:OO,isNull:XO,isNotNull:YO,like:wO,lt:RO,lte:WO,ne:fO,not:$O,notBetween:GO,notExists:HO,notLike:UO,notIlike:zO,notInArray:MO,or:SO,sql:X}}function k2(){return{sql:X,asc:QO,desc:VO}}function B2(T,o){if(Object.keys(T).length===1&&"default"in T&&!G(T.default,b))T=T.default;let y={},A={},F={};for(let[f,S]of Object.entries(T))if(G(S,b)){let $=cy(S),_=A[$];y[$]=f,F[f]={tsName:f,dbName:S[b.Symbol.Name],schema:S[b.Symbol.Schema],columns:S[b.Symbol.Columns],relations:_?.relations??{},primaryKey:_?.primaryKey??[]};for(let R of Object.values(S[b.Symbol.Columns]))if(R.primary)F[f].primaryKey.push(R);let J=S[b.Symbol.ExtraConfigBuilder]?.(S[b.Symbol.ExtraConfigColumns]);if(J){for(let R of Object.values(J))if(G(R,tF))F[f].primaryKey.push(...R.columns)}}else if(G(S,L2)){let $=cy(S.table),_=y[$],J=S.config(o(S.table)),R;for(let[M,Y]of Object.entries(J))if(_){let H=F[_];if(H.relations[M]=Y,R)H.primaryKey.push(...R)}else{if(!($ in A))A[$]={relations:{},primaryKey:R};A[$].relations[M]=Y}}return{tables:F,tableNamesMap:y}}function UZ(T){return function o(y,A){return new by(T,y,A,A?.fields.reduce((F,f)=>F&&f.notNull,!0)??!1)}}function KZ(T){return function o(y,A){return new pF(T,y,A)}}function N2(T,o,y){if(G(y,by)&&y.config)return{fields:y.config.fields,references:y.config.references};let A=o[cy(y.referencedTable)];if(!A)throw new Error(`Table "${y.referencedTable[b.Symbol.Name]}" not found in schema`);let F=T[A];if(!F)throw new Error(`Table "${A}" not found in schema`);let f=y.sourceTable,S=o[cy(f)];if(!S)throw new Error(`Table "${f[b.Symbol.Name]}" not found in schema`);let $=[];for(let _ of Object.values(F.relations))if(y.relationName&&y!==_&&_.relationName===y.relationName||!y.relationName&&_.referencedTable===y.sourceTable)$.push(_);if($.length>1)throw y.relationName?new Error(`There are multiple relations with name "${y.relationName}" in table "${A}"`):new Error(`There are multiple relations between "${A}" and "${y.sourceTable[b.Symbol.Name]}". Please specify relation name`);if($[0]&&G($[0],by)&&$[0].config)return{fields:$[0].config.references,references:$[0].config.fields};throw new Error(`There is not enough information to infer relation "${S}.${y.fieldName}"`)}function t2(T){return{one:UZ(T),many:KZ(T)}}function fS(T,o,y,A,F=(f)=>f){let f={};for(let[S,$]of A.entries())if($.isJson){let _=o.relations[$.tsKey],J=y[S],R=typeof J==="string"?JSON.parse(J):J;f[$.tsKey]=G(_,by)?R&&fS(T,T[$.relationTableTsKey],R,$.selection,F):R.map((M)=>fS(T,T[$.relationTableTsKey],M,$.selection,F))}else{let _=F(y[S]),J=$.field,R;if(G(J,GT))R=J;else if(G(J,x))R=J.decoder;else R=J.sql.decoder;f[$.tsKey]=_===null?null:R.mapFromDriverValue(_)}return f}import iZ from"os";import cZ from"fs";var SS=new Map,qJ=new Map,vJ=Symbol("OriginError"),kA={};class mo extends Promise{constructor(T,o,y,A,F={}){let f,S;super(($,_)=>{f=$,S=_});this.tagged=Array.isArray(T.raw),this.strings=T,this.args=o,this.handler=y,this.canceller=A,this.options=F,this.state=null,this.statement=null,this.resolve=($)=>(this.active=!1,f($)),this.reject=($)=>(this.active=!1,S($)),this.active=!1,this.cancelled=null,this.executed=!1,this.signature="",this[vJ]=this.handler.debug?new Error:this.tagged&&zZ(this.strings)}get origin(){return(this.handler.debug?this[vJ].stack:this.tagged&&qJ.has(this.strings)?qJ.get(this.strings):qJ.set(this.strings,this[vJ].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(T=1,o){if(this.options.simple=!1,typeof T==="function")o=T,T=1;if(this.cursorRows=T,typeof o==="function")return this.cursorFn=o,this;let y;return{[Symbol.asyncIterator]:()=>({next:()=>{if(this.executed&&!this.active)return{done:!0};y&&y();let A=new Promise((F,f)=>{this.cursorFn=(S)=>{return F({value:S,done:!1}),new Promise(($)=>y=$)},this.resolve=()=>(this.active=!1,F({done:!0})),this.reject=(S)=>(this.active=!1,f(S))});return this.execute(),A},return(){return y&&y(kA),{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(T){return this.forEachFn=T,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 zZ(T){if(SS.has(T))return SS.get(T);let o=Error.stackTraceLimit;return Error.stackTraceLimit=4,SS.set(T,new Error),Error.stackTraceLimit=o,SS.get(T)}class BA extends Error{constructor(T){super(T.message);this.name=this.constructor.name,Object.assign(this,T)}}var mT={connection:p2,postgres:b2,generic:x2,notSupported:j2};function p2(T,o,y){let{host:A,port:F}=y||o,f=Object.assign(new Error("write "+T+" "+(o.path||A+":"+F)),{code:T,errno:T,address:o.path||A},o.path?{}:{port:F});return Error.captureStackTrace(f,p2),f}function b2(T){let o=new BA(T);return Error.captureStackTrace(o,b2),o}function x2(T,o){let y=Object.assign(new Error(T+": "+o),{code:T});return Error.captureStackTrace(y,x2),y}function j2(T){let o=Object.assign(new Error(T+" (B) is not supported"),{code:"MESSAGE_NOT_SUPPORTED",name:T});return Error.captureStackTrace(o,j2),o}var QZ={string:{to:25,from:null,serialize:(T)=>""+T},number:{to:0,from:[21,23,26,700,701],serialize:(T)=>""+T,parse:(T)=>+T},json:{to:114,from:[114,3802],serialize:(T)=>JSON.stringify(T),parse:(T)=>JSON.parse(T)},boolean:{to:16,from:16,serialize:(T)=>T===!0?"t":"f",parse:(T)=>T==="t"},date:{to:1184,from:[1082,1114,1184],serialize:(T)=>(T instanceof Date?T:new Date(T)).toISOString(),parse:(T)=>new Date(T)},bytea:{to:17,from:17,serialize:(T)=>"\\x"+Buffer.from(T).toString("hex"),parse:(T)=>Buffer.from(T.slice(2),"hex")}};class _S{then(){PJ()}catch(){PJ()}finally(){PJ()}}class mF extends _S{constructor(T){super();this.value=OS(T)}}class yy extends _S{constructor(T,o,y){super();this.value=T,this.type=o,this.array=y}}class RS extends _S{constructor(T,o){super();this.first=T,this.rest=o}build(T,o,y,A){let F=VZ.map(([f,S])=>({fn:S,i:T.search(f)})).sort((f,S)=>f.i-S.i).pop();return F.i===-1?iJ(this.first,A):F.fn(this.first,this.rest,o,y,A)}}function WS(T,o,y,A){let F=T instanceof yy?T.value:T;if(F===void 0){if(T instanceof yy?T.value=A.transform.undefined:F=T=A.transform.undefined,F===void 0)throw mT.generic("UNDEFINED_VALUE","Undefined values are not allowed")}return"$"+y.push(T instanceof yy?(o.push(T.value),T.array?T.array[T.type||JS(T.value)]||T.type||P2(T.value):T.type):(o.push(T),JS(T)))}var q2=n2(QZ);function gJ(T,o,y,A,F,f){for(let S=1;S<T.strings.length;S++)o+=uJ(o,y,A,F,f)+T.strings[S],y=T.args[S];return o}function uJ(T,o,y,A,F){return o instanceof RS?o.build(T,y,A,F):o instanceof mo?nJ(o,y,A,F):o instanceof mF?o.value:o&&o[0]instanceof mo?o.reduce((f,S)=>f+" "+nJ(S,y,A,F),""):WS(o,y,A,F)}function nJ(T,o,y,A){return T.fragment=!0,gJ(T,T.strings[0],T.args[0],o,y,A)}function v2(T,o,y,A,F){return T.map((f)=>"("+A.map((S)=>uJ("values",f[S],o,y,F)).join(",")+")").join(",")}function m2(T,o,y,A,F){let f=Array.isArray(T[0]),S=o.length?o.flat():Object.keys(f?T[0]:T);return v2(f?T:[T],y,A,S,F)}function $S(T,o,y,A,F){if(typeof T==="string"&&(T=[T].concat(o)),Array.isArray(T))return iJ(T,F);let f;return(o.length?o.flat():Object.keys(T)).map(($)=>{return f=T[$],(f instanceof mo?nJ(f,y,A,F):f instanceof mF?f.value:WS(f,y,A,F))+" as "+OS(F.transform.column.to?F.transform.column.to($):$)}).join(",")}var VZ=Object.entries({values:m2,in:(...T)=>{let o=m2(...T);return o==="()"?"(null)":o},select:$S,as:$S,returning:$S,"\\(":$S,update(T,o,y,A,F){return(o.length?o.flat():Object.keys(T)).map((f)=>OS(F.transform.column.to?F.transform.column.to(f):f)+"="+uJ("values",T[f],y,A,F))},insert(T,o,y,A,F){let f=o.length?o.flat():Object.keys(Array.isArray(T)?T[0]:T);return"("+iJ(f,F)+")values"+v2(Array.isArray(T)?T:[T],y,A,f,F)}}).map(([T,o])=>[new RegExp("((?:^|[\\s(])"+T+"(?:$|[\\s(]))(?![\\s\\S]*\\1)","i"),o]);function PJ(){throw mT.generic("NOT_TAGGED_CALL","Query not called as a tagged template literal")}var{serializers:DZ,parsers:CZ}=q2;function P2(T){if(Array.isArray(T))return P2(T[0]);return typeof T==="string"?1009:0}var h2=function(T){let o=n2(T||{});return{serializers:Object.assign({},DZ,o.serializers),parsers:Object.assign({},CZ,o.parsers)}};function n2(T){return Object.keys(T).reduce((o,y)=>{if(T[y].from&&[].concat(T[y].from).forEach((A)=>o.parsers[A]=T[y].parse),T[y].serialize)o.serializers[T[y].to]=T[y].serialize,T[y].from&&[].concat(T[y].from).forEach((A)=>o.serializers[A]=T[y].serialize);return o},{parsers:{},serializers:{}})}function iJ(T,{transform:{column:o}}){return T.map((y)=>OS(o.to?o.to(y):y)).join(",")}var OS=function T(o){return'"'+o.replace(/"/g,'""').replace(/\./g,'"."')+'"'},JS=function T(o){return o instanceof yy?o.type:o instanceof Date?1184:o instanceof Uint8Array?17:o===!0||o===!1?16:typeof o==="bigint"?20:Array.isArray(o)?T(o[0]):0},LZ=/\\/g,IZ=/"/g;function kZ(T){return T.replace(LZ,"\\\\").replace(IZ,"\\\"")}var g2=function T(o,y,A,F){if(Array.isArray(o)===!1)return o;if(!o.length)return"{}";let f=o[0],S=F===1020?";":",";if(Array.isArray(f)&&!f.type)return"{"+o.map(($)=>T($,y,A,F)).join(S)+"}";return"{"+o.map(($)=>{if($===void 0){if($=A.transform.undefined,$===void 0)throw mT.generic("UNDEFINED_VALUE","Undefined values are not allowed")}return $===null?"null":'"'+kZ(y?y($.type?$.value:$):""+$)+'"'}).join(S)+"}"},hJ={i:0,char:null,str:"",quoted:!1,last:0},u2=function T(o,y,A){return hJ.i=hJ.last=0,i2(hJ,o,y,A)};function i2(T,o,y,A){let F=[],f=A===1020?";":",";for(;T.i<o.length;T.i++){if(T.char=o[T.i],T.quoted)if(T.char==="\\")T.str+=o[++T.i];else if(T.char==='"')F.push(y?y(T.str):T.str),T.str="",T.quoted=o[T.i+1]==='"',T.last=T.i+2;else T.str+=T.char;else if(T.char==='"')T.quoted=!0;else if(T.char==="{")T.last=++T.i,F.push(i2(T,o,y,A));else if(T.char==="}"){T.quoted=!1,T.last<T.i&&F.push(y?y(o.slice(T.last,T.i)):o.slice(T.last,T.i)),T.last=T.i+1;break}else if(T.char===f&&T.p!=="}"&&T.p!=='"')F.push(y?y(o.slice(T.last,T.i)):o.slice(T.last,T.i)),T.last=T.i+1;T.p=T.char}return T.last<T.i&&F.push(y?y(o.slice(T.last,T.i+1)):o.slice(T.last,T.i+1)),F}var dy=(T)=>{let o=T[0];for(let y=1;y<T.length;y++)o+=T[y]==="_"?T[++y].toUpperCase():T[y];return o},ry=(T)=>{let o=T[0].toUpperCase();for(let y=1;y<T.length;y++)o+=T[y]==="_"?T[++y].toUpperCase():T[y];return o},ly=(T)=>T.replace(/_/g,"-"),bF=(T)=>T.replace(/([A-Z])/g,"_$1").toLowerCase(),xF=(T)=>(T.slice(0,1)+T.slice(1).replace(/([A-Z])/g,"_$1")).toLowerCase(),jF=(T)=>T.replace(/-/g,"_");function cJ(T){return function o(y,A){return typeof y==="object"&&y!==null&&(A.type===114||A.type===3802)?Array.isArray(y)?y.map((F)=>o(F,A)):Object.entries(y).reduce((F,[f,S])=>Object.assign(F,{[T(f)]:o(S,A)}),{}):y}}dy.column={from:dy};dy.value={from:cJ(dy)};bF.column={to:bF};var dJ={...dy};dJ.column.to=bF;ry.column={from:ry};ry.value={from:cJ(ry)};xF.column={to:xF};var rJ={...ry};rJ.column.to=xF;ly.column={from:ly};ly.value={from:cJ(ly)};jF.column={to:jF};var lJ={...ly};lJ.column.to=jF;import c2 from"net";import pZ from"tls";import qF from"crypto";import sJ from"stream";import{performance as d2}from"perf_hooks";class sy 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 Io=BZ;function BZ(T=[]){let o=T.slice(),y=0;return{get length(){return o.length-y},remove:(A)=>{let F=o.indexOf(A);return F===-1?null:(o.splice(F,1),A)},push:(A)=>(o.push(A),A),shift:()=>{let A=o[y++];if(y===o.length)y=0,o=[];else o[y-1]=void 0;return A}}}var Jo=Buffer.allocUnsafe(256),NZ="BCcDdEFfHPpQSX".split("").reduce((T,o)=>{let y=o.charCodeAt(0);return T[o]=()=>{return Jo[0]=y,ZT.i=5,ZT},T},{}),ZT=Object.assign(tZ,NZ,{N:String.fromCharCode(0),i:0,inc(T){return ZT.i+=T,ZT},str(T){let o=Buffer.byteLength(T);return MS(o),ZT.i+=Jo.write(T,ZT.i,o,"utf8"),ZT},i16(T){return MS(2),Jo.writeUInt16BE(T,ZT.i),ZT.i+=2,ZT},i32(T,o){if(o||o===0)return Jo.writeUInt32BE(T,o),ZT;return MS(4),Jo.writeUInt32BE(T,ZT.i),ZT.i+=4,ZT},z(T){return MS(T),Jo.fill(0,ZT.i,ZT.i+T),ZT.i+=T,ZT},raw(T){return Jo=Buffer.concat([Jo.subarray(0,ZT.i),T]),ZT.i=Jo.length,ZT},end(T=1){Jo.writeUInt32BE(ZT.i-T,T);let o=Jo.subarray(0,ZT.i);return ZT.i=0,Jo=Buffer.allocUnsafe(256),o}}),u=ZT;function MS(T){if(Jo.length-ZT.i<T){let o=Jo,y=o.length;Jo=Buffer.allocUnsafe(y+(y>>1)+T),o.copy(Jo)}}function tZ(){return ZT.i=0,ZT}var T0=s2,bZ=1,xy=u().S().end(),r2=u().H().end(),xZ=u().i32(8).i32(80877103).end(8),jZ=Buffer.concat([u().E().str(u.N).i32(0).end(),xy]),mZ=u().D().str("S").str(u.N).end(),NA=()=>{},qZ=new Set(["FetchPreparedStatement","RevalidateCachedQuery","transformAssignedExpr"]),vZ={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 s2(T,o={},{onopen:y=NA,onend:A=NA,onclose:F=NA}={}){let{ssl:f,max:S,user:$,host:_,port:J,database:R,parsers:M,transform:Y,onnotice:H,onnotify:Q,onparameter:w,max_pipeline:B,keep_alive:t,backoff:m,target_session_attrs:h}=T,K=Io(),V=bZ++,L={pid:null,secret:null},C=eJ(DS,T.idle_timeout),v=eJ(DS,T.max_lifetime),s=eJ(G4,T.connect_timeout),z=null,a,P=new sy,e=Buffer.alloc(0),HT=T.fetch_types,qT={},Xo={},Ay=Math.random().toString(36).slice(2),D=1,n=0,RT=0,IT=0,vT=0,yT=0,UT=0,xT=0,kT=null,DT=null,oo=!1,KT=null,qo=null,yo=null,wy=null,PT=null,CT=null,vo=null,ro=null,N=null,xA=null,Ao={queue:o.closed,idleTimer:C,connect(W){yo=W||!0,D0()},terminate:mA,execute:jA,cancel:Y4,end:DS,count:0,id:V};return o.closed&&o.closed.push(Ao),Ao;async function X4(){let W;try{W=T.socket?await Promise.resolve(T.socket(T)):new c2.Socket}catch(Z){oA(Z);return}return W.on("error",oA),W.on("close",C0),W.on("drain",Q0),W}async function Y4({pid:W,secret:Z},i,WT){try{a=u().i32(16).i32(80877102).i32(W).i32(Z).end(16),await V0(),z.once("error",WT),z.once("close",i)}catch(NT){WT(NT)}}function jA(W){if(oo)return iF(W,mT.connection("CONNECTION_DESTROYED",T));if(W.cancelled)return;try{return W.state=L,N?K.push(W):(N=W,N.active=!0),E4(W),sT(Z4(W))&&!W.describeFirst&&!W.cursorFn&&K.length<B&&(!W.options.onexecute||W.options.onexecute(Ao))}catch(Z){return K.length===0&&sT(xy),lo(Z),!0}}function Z4(W){if(W.parameters.length>=65534)throw mT.generic("MAX_PARAMETERS_EXCEEDED","Max number of parameters (65534) exceeded");return W.options.simple?u().Q().str(W.statement.string+u.N).end():W.describeFirst?Buffer.concat([U0(W),r2]):W.prepare?W.prepared?uF(W):Buffer.concat([U0(W),uF(W)]):H4(W)}function U0(W){return Buffer.concat([I0(W.statement.string,W.parameters,W.statement.types,W.statement.name),AX("S",W.statement.name)])}function uF(W){return Buffer.concat([yX(W.parameters,W.statement.types,W.statement.name,W.cursorName),W.cursorFn?k0("",W.cursorRows):jZ])}function H4(W){return Buffer.concat([I0(W.statement.string,W.parameters,W.statement.types),mZ,uF(W)])}function E4(W){let Z=[],i=[],WT=gJ(W,W.strings[0],W.args[0],Z,i,T);!W.tagged&&W.args.forEach((NT)=>WS(NT,Z,i,T)),W.prepare=T.prepare&&("prepare"in W.options?W.options.prepare:!0),W.string=WT,W.signature=W.prepare&&i+WT,W.onlyDescribe&&delete Xo[W.signature],W.parameters=W.parameters||Z,W.prepared=W.prepare&&W.signature in Xo,W.describeFirst=W.onlyDescribe||Z.length&&!W.prepared,W.statement=W.prepared?Xo[W.signature]:{string:WT,types:i,name:W.prepare?Ay+D++:""},typeof T.debug==="function"&&T.debug(V,WT,Z,i)}function sT(W,Z){if(CT=CT?Buffer.concat([CT,W]):Buffer.from(W),Z||CT.length>=1024)return K0(Z);return DT===null&&(DT=setImmediate(K0)),!0}function K0(W){let Z=z.write(CT,W);return DT!==null&&clearImmediate(DT),CT=DT=null,Z}function G4(){lo(mT.connection("CONNECT_TIMEOUT",T,z)),z.destroy()}async function z0(){if(sT(xZ),!await new Promise((Z)=>z.once("data",(i)=>Z(i[0]===83)))&&f==="prefer")return TA();z.removeAllListeners(),z=pZ.connect({socket:z,servername:c2.isIP(z.host)?void 0:z.host,...f==="require"||f==="allow"||f==="prefer"?{rejectUnauthorized:!1}:f==="verify-full"?{}:typeof f==="object"?f:{}}),z.on("secureConnect",TA),z.on("error",oA),z.on("close",C0),z.on("drain",Q0)}function Q0(){!N&&y(Ao)}function VS(W){if(KT){if(KT.push(W),RT-=W.length,RT>=0)return}e=KT?Buffer.concat(KT,yT-RT):e.length===0?W:Buffer.concat([e,W],e.length+W.length);while(e.length>4){if(yT=e.readUInt32BE(1),yT>=e.length){RT=yT-e.length,KT=[e];break}try{w4(e.subarray(0,yT+1))}catch(Z){N&&(N.cursorFn||N.describeFirst)&&sT(xy),lo(Z)}e=e.subarray(yT+1),RT=0,KT=null}}async function V0(){if(oo=!1,qT={},z||(z=await X4()),!z)return;if(s.start(),T.socket)return f?z0():TA();if(z.on("connect",f?z0:TA),T.path)return z.connect(T.path);z.ssl=f,z.connect(J[IT],_[IT]),z.host=_[IT],z.port=J[IT],IT=(IT+1)%J.length}function D0(){setTimeout(V0,n?n+UT-d2.now():0)}function TA(){try{Xo={},HT=T.fetch_types,Ay=Math.random().toString(36).slice(2),D=1,v.start(),z.on("data",VS),t&&z.setKeepAlive&&z.setKeepAlive(!0,1000*t);let W=fX();sT(W)}catch(W){oA(W)}}function oA(W){if(Ao.queue===o.connecting&&T.host[vT+1])return;lo(W);while(K.length)iF(K.shift(),W)}function lo(W){PT&&(PT.destroy(W),PT=null),N&&iF(N,W),yo&&(iF(yo,W),yo=null)}function iF(W,Z){"query"in Z||"parameters"in Z||Object.defineProperties(Z,{stack:{value:Z.stack+W.origin.replace(/.*\n/,`
|
|
55
|
+
`),enumerable:T.debug},query:{value:W.string,enumerable:T.debug},parameters:{value:W.parameters,enumerable:T.debug},args:{value:W.args,enumerable:T.debug},types:{value:W.statement&&W.statement.types,enumerable:T.debug}}),W.reject(Z)}function DS(){return wy||(!Ao.reserved&&A(Ao),!Ao.reserved&&!yo&&!N&&K.length===0?(mA(),new Promise((W)=>z&&z.readyState!=="closed"?z.once("close",W):W())):wy=new Promise((W)=>vo=W))}function mA(){if(oo=!0,PT||N||yo||K.length)oA(mT.connection("CONNECTION_DESTROYED",T));if(clearImmediate(DT),z)z.removeListener("data",VS),z.removeListener("connect",TA),z.readyState==="open"&&z.end(u().X().end());vo&&(vo(),wy=vo=null)}async function C0(W){if(e=Buffer.alloc(0),RT=0,KT=null,clearImmediate(DT),z.removeListener("data",VS),z.removeListener("connect",TA),C.cancel(),v.cancel(),s.cancel(),z.removeAllListeners(),z=null,yo)return D0();!W&&(N||K.length)&&oA(mT.connection("CONNECTION_CLOSED",T,z)),n=d2.now(),W&&T.shared.retries++,UT=(typeof m==="function"?m(T.shared.retries):m)*1000,F(Ao,mT.connection("CONNECTION_CLOSED",T,z))}function w4(W,Z=W[0]){(Z===68?U4:Z===100?d4:Z===65?h4:Z===83?K4:Z===90?z4:Z===67?Q4:Z===50?L0:Z===49?V4:Z===116?D4:Z===84?C4:Z===82?L4:Z===110?p4:Z===75?b4:Z===69?v4:Z===115?n4:Z===51?g4:Z===71?u4:Z===78?l4:Z===72?i4:Z===99?r4:Z===73?s4:Z===86?a4:Z===118?e4:Z===87?c4:TX)(W)}function U4(W){let Z=7,i,WT,NT,Fo=N.isRaw?new Array(N.statement.columns.length):{};for(let _o=0;_o<N.statement.columns.length;_o++)WT=N.statement.columns[_o],i=W.readInt32BE(Z),Z+=4,NT=i===-1?null:N.isRaw===!0?W.subarray(Z,Z+=i):WT.parser===void 0?W.toString("utf8",Z,Z+=i):WT.parser.array===!0?WT.parser(W.toString("utf8",Z+1,Z+=i)):WT.parser(W.toString("utf8",Z,Z+=i)),N.isRaw?Fo[_o]=N.isRaw===!0?NT:Y.value.from?Y.value.from(NT,WT):NT:Fo[WT.name]=Y.value.from?Y.value.from(NT,WT):NT;N.forEachFn?N.forEachFn(Y.row.from?Y.row.from(Fo):Fo,P):P[xT++]=Y.row.from?Y.row.from(Fo):Fo}function K4(W){let[Z,i]=W.toString("utf8",5,W.length-1).split(u.N);if(qT[Z]=i,T.parameters[Z]!==i)T.parameters[Z]=i,w&&w(Z,i)}function z4(W){if(N&&N.options.simple&&N.resolve(qo||P),N=qo=null,P=new sy,s.cancel(),yo){if(h){if(!qT.in_hot_standby||!qT.default_transaction_read_only)return q4();else if(m4(h,qT))return mA()}if(HT)return yo===!0&&(yo=null),x4();yo!==!0&&jA(yo),T.shared.retries=vT=0,yo=null;return}while(K.length&&(N=K.shift())&&(N.active=!0,N.cancelled))s2(T).cancel(N.state,N.cancelled.resolve,N.cancelled.reject);if(N)return;Ao.reserved?!Ao.reserved.release&&W[5]===73?wy?mA():(Ao.reserved=null,y(Ao)):Ao.reserved():wy?mA():y(Ao)}function Q4(W){xT=0;for(let Z=W.length-1;Z>0;Z--){if(W[Z]===32&&W[Z+1]<58&&P.count===null)P.count=+W.toString("utf8",Z+1,W.length-1);if(W[Z-1]>=65){P.command=W.toString("utf8",5,Z),P.state=L;break}}if(xA&&(xA(),xA=null),P.command==="BEGIN"&&S!==1&&!Ao.reserved)return lo(mT.generic("UNSAFE_TRANSACTION","Only use sql.begin, sql.reserved or max: 1"));if(N.options.simple)return L0();if(N.cursorFn)P.count&&N.cursorFn(P),sT(xy);N.resolve(P)}function V4(){N.parsing=!1}function L0(){!P.statement&&(P.statement=N.statement),P.columns=N.statement.columns}function D4(W){let Z=W.readUInt16BE(5);for(let i=0;i<Z;++i)!N.statement.types[i]&&(N.statement.types[i]=W.readUInt32BE(7+i*4));N.prepare&&(Xo[N.signature]=N.statement),N.describeFirst&&!N.onlyDescribe&&(sT(uF(N)),N.describeFirst=!1)}function C4(W){if(P.command)qo=qo||[P],qo.push(P=new sy),P.count=null,N.statement.columns=null;let Z=W.readUInt16BE(5),i=7,WT;N.statement.columns=Array(Z);for(let NT=0;NT<Z;++NT){WT=i;while(W[i++]!==0);let Fo=W.readUInt32BE(i),_o=W.readUInt16BE(i+4),Uy=W.readUInt32BE(i+6);N.statement.columns[NT]={name:Y.column.from?Y.column.from(W.toString("utf8",WT,i-1)):W.toString("utf8",WT,i-1),parser:M[Uy],table:Fo,number:_o,type:Uy},i+=18}if(P.statement=N.statement,N.onlyDescribe)return N.resolve(N.statement),sT(xy)}async function L4(W,Z=W.readUInt32BE(5)){(Z===3?I4:Z===5?k4:Z===10?B4:Z===11?N4:Z===12?t4:Z!==0?oX:NA)(W,Z)}async function I4(){let W=await CS();sT(u().p().str(W).z(1).end())}async function k4(W){let Z="md5"+await l2(Buffer.concat([Buffer.from(await l2(await CS()+$)),W.subarray(9)]));sT(u().p().str(Z).z(1).end())}async function B4(){ro=(await qF.randomBytes(18)).toString("base64"),u().p().str("SCRAM-SHA-256"+u.N);let W=u.i;sT(u.inc(4).str("n,,n=*,r="+ro).i32(u.i-W-4,W).end())}async function N4(W){let Z=W.toString("utf8",9).split(",").reduce((_o,Uy)=>(_o[Uy[0]]=Uy.slice(2),_o),{}),i=await qF.pbkdf2Sync(await CS(),Buffer.from(Z.s,"base64"),parseInt(Z.i),32,"sha256"),WT=await XS(i,"Client Key"),NT="n=*,r="+ro+",r="+Z.r+",s="+Z.s+",i="+Z.i+",c=biws,r="+Z.r;kT=(await XS(await XS(i,"Server Key"),NT)).toString("base64");let Fo="c=biws,r="+Z.r+",p="+hZ(WT,Buffer.from(await XS(await PZ(WT),NT))).toString("base64");sT(u().p().str(Fo).end())}function t4(W){if(W.toString("utf8",9).split(u.N,1)[0].slice(2)===kT)return;lo(mT.generic("SASL_SIGNATURE_MISMATCH","The server did not return the correct signature")),z.destroy()}function CS(){return Promise.resolve(typeof T.pass==="function"?T.pass():T.pass)}function p4(){if(P.statement=N.statement,P.statement.columns=[],N.onlyDescribe)return N.resolve(N.statement),sT(xy)}function b4(W){L.pid=W.readUInt32BE(5),L.secret=W.readUInt32BE(9)}async function x4(){HT=!1,(await new mo([`
|
|
18
56
|
select b.oid, b.typarray
|
|
19
57
|
from pg_catalog.pg_type a
|
|
20
58
|
left join pg_catalog.pg_type b on b.oid = a.typelem
|
|
21
59
|
where a.typcategory = 'A'
|
|
22
60
|
group by b.oid, b.typarray
|
|
23
61
|
order by b.oid
|
|
24
|
-
`],[],
|
|
62
|
+
`],[],jA)).forEach(({oid:Z,typarray:i})=>j4(Z,i))}function j4(W,Z){if(!!T.parsers[Z]&&!!T.serializers[Z])return;let i=T.parsers[W];T.shared.typeArrayMap[W]=Z,T.parsers[Z]=(WT)=>u2(WT,i,Z),T.parsers[Z].array=!0,T.serializers[Z]=(WT)=>g2(WT,T.serializers[W],T,Z)}function m4(W,Z){return W==="read-write"&&Z.default_transaction_read_only==="on"||W==="read-only"&&Z.default_transaction_read_only==="off"||W==="primary"&&Z.in_hot_standby==="on"||W==="standby"&&Z.in_hot_standby==="off"||W==="prefer-standby"&&Z.in_hot_standby==="off"&&T.host[vT]}function q4(){let W=new mo([`
|
|
25
63
|
show transaction_read_only;
|
|
26
64
|
select pg_catalog.pg_is_in_recovery()
|
|
27
|
-
`],[],
|
|
65
|
+
`],[],jA,null,{simple:!0});W.resolve=([[Z],[i]])=>{qT.default_transaction_read_only=Z.transaction_read_only,qT.in_hot_standby=i.pg_is_in_recovery?"on":"off"},W.execute()}function v4(W){N&&(N.cursorFn||N.describeFirst)&&sT(xy);let Z=mT.postgres(aJ(W));N&&N.retried?lo(N.retried):N&&N.prepared&&qZ.has(Z.routine)?P4(N,Z):lo(Z)}function P4(W,Z){delete Xo[W.signature],W.retried=Z,jA(W)}function h4(W){if(!Q)return;let Z=9;while(W[Z++]!==0);Q(W.toString("utf8",9,Z-1),W.toString("utf8",Z,W.length-1))}async function n4(){try{let W=await Promise.resolve(N.cursorFn(P));xT=0,W===kA?sT(FX(N.portal)):(P=new sy,sT(k0("",N.cursorRows)))}catch(W){sT(xy),N.reject(W)}}function g4(){P.count&&N.cursorFn(P),N.resolve(P)}function u4(){PT=new sJ.Writable({autoDestroy:!0,write(W,Z,i){z.write(u().d().raw(W).end(),i)},destroy(W,Z){Z(W),z.write(u().f().str(W+u.N).end()),PT=null},final(W){z.write(u().c().end()),xA=W}}),N.resolve(PT)}function i4(){PT=new sJ.Readable({read(){z.resume()}}),N.resolve(PT)}function c4(){PT=new sJ.Duplex({autoDestroy:!0,read(){z.resume()},write(W,Z,i){z.write(u().d().raw(W).end(),i)},destroy(W,Z){Z(W),z.write(u().f().str(W+u.N).end()),PT=null},final(W){z.write(u().c().end()),xA=W}}),N.resolve(PT)}function d4(W){PT&&(PT.push(W.subarray(5))||z.pause())}function r4(){PT&&PT.push(null),PT=null}function l4(W){H?H(aJ(W)):console.log(aJ(W))}function s4(){}function a4(){lo(mT.notSupported("FunctionCallResponse"))}function e4(){lo(mT.notSupported("NegotiateProtocolVersion"))}function TX(W){console.error("Postgres.js : Unknown Message:",W[0])}function oX(W,Z){console.error("Postgres.js : Unknown Auth:",Z)}function yX(W,Z,i="",WT=""){let NT,Fo;return u().B().str(WT+u.N).str(i+u.N).i16(0).i16(W.length),W.forEach((_o,Uy)=>{if(_o===null)return u.i32(4294967295);Fo=Z[Uy],W[Uy]=_o=Fo in T.serializers?T.serializers[Fo](_o):""+_o,NT=u.i,u.inc(4).str(_o).i32(u.i-NT-4,NT)}),u.i16(0),u.end()}function I0(W,Z,i,WT=""){return u().P().str(WT+u.N).str(W+u.N).i16(Z.length),Z.forEach((NT,Fo)=>u.i32(i[Fo]||0)),u.end()}function AX(W,Z=""){return u().D().str(W).str(Z+u.N).end()}function k0(W="",Z=0){return Buffer.concat([u().E().str(W+u.N).i32(Z).end(),r2])}function FX(W=""){return Buffer.concat([u().C().str("P").str(W+u.N).end(),u().S().end()])}function fX(){return a||u().inc(4).i16(3).z(2).str(Object.entries(Object.assign({user:$,database:R,client_encoding:"UTF8"},T.connection)).filter(([,W])=>W).map(([W,Z])=>W+u.N+Z).join(u.N)).z(2).end(0)}}function aJ(T){let o={},y=5;for(let A=5;A<T.length-1;A++)if(T[A]===0)o[vZ[T[y]]]=T.toString("utf8",y+1,A),y=A+1;return o}function l2(T){return qF.createHash("md5").update(T).digest("hex")}function XS(T,o){return qF.createHmac("sha256",T).update(o).digest()}function PZ(T){return qF.createHash("sha256").update(T).digest()}function hZ(T,o){let y=Math.max(T.length,o.length),A=Buffer.allocUnsafe(y);for(let F=0;F<y;F++)A[F]=T[F]^o[F];return A}function eJ(T,o){if(o=typeof o==="function"?o():o,!o)return{cancel:NA,start:NA};let y;return{cancel(){y&&(clearTimeout(y),y=null)},start(){y&&clearTimeout(y),y=setTimeout(A,o*1000,arguments)}};function A(F){T.apply(null,F),y=null}}var a2=()=>{};function o0(T,o){let y=new Map,A="postgresjs_"+Math.random().toString(36).slice(2),F={},f,S,$=!1,_=M.sql=T({...o,transform:{column:{},value:{},row:{}},max:1,fetch_types:!1,idle_timeout:null,max_lifetime:null,connection:{...o.connection,replication:"database"},onclose:async function(){if($)return;S=null,F.pid=F.secret=void 0,Y(await H(_,A,o.publications)),y.forEach((w)=>w.forEach(({onsubscribe:B})=>B()))},no_subscribe:!0}),J=_.end,R=_.close;return _.end=async()=>{return $=!0,S&&await new Promise((w)=>(S.once("close",w),S.end())),J()},_.close=async()=>{return S&&await new Promise((w)=>(S.once("close",w),S.end())),R()},M;async function M(w,B,t=a2,m=a2){if(w=uZ(w),!f)f=H(_,A,o.publications);let h={fn:B,onsubscribe:t},K=y.has(w)?y.get(w).add(h):y.set(w,new Set([h])).get(w),V=()=>{K.delete(h),K.size===0&&y.delete(w)};return f.then((L)=>{return Y(L),t(),S&&S.on("error",m),{unsubscribe:V,state:F,sql:_}})}function Y(w){S=w.stream,F.pid=w.state.pid,F.secret=w.state.secret}async function H(w,B,t){if(!t)throw new Error("Missing publication names");let m=await w.unsafe(`CREATE_REPLICATION_SLOT ${B} TEMPORARY LOGICAL pgoutput NOEXPORT_SNAPSHOT`),[h]=m,K=await w.unsafe(`START_REPLICATION SLOT ${B} LOGICAL ${h.consistent_point} (proto_version '1', publication_names '${t}')`).writable(),V={lsn:Buffer.concat(h.consistent_point.split("/").map((z)=>Buffer.from(("00000000"+z).slice(-8),"hex")))};return K.on("data",C),K.on("error",L),K.on("close",w.close),{stream:K,state:m.state};function L(z){console.error("Unexpected error during logical streaming - reconnecting",z)}function C(z){if(z[0]===119)gZ(z.subarray(25),V,w.options.parsers,v,o.transform);else if(z[0]===107&&z[17])V.lsn=z.subarray(1,9),s()}function v(z,a){let P=a.relation.schema+"."+a.relation.table;Q("*",z,a),Q("*:"+P,z,a),a.relation.keys.length&&Q("*:"+P+"="+a.relation.keys.map((e)=>z[e.name]),z,a),Q(a.command,z,a),Q(a.command+":"+P,z,a),a.relation.keys.length&&Q(a.command+":"+P+"="+a.relation.keys.map((e)=>z[e.name]),z,a)}function s(){let z=Buffer.alloc(34);z[0]=114,z.fill(V.lsn,1),z.writeBigInt64BE(BigInt(Date.now()-Date.UTC(2000,0,1))*BigInt(1000),25),K.write(z)}}function Q(w,B,t){y.has(w)&&y.get(w).forEach(({fn:m})=>m(B,t,w))}}function nZ(T){return new Date(Date.UTC(2000,0,1)+Number(T/BigInt(1000)))}function gZ(T,o,y,A,F){let f=(S,[$,_])=>(S[$.charCodeAt(0)]=_,S);Object.entries({R:(S)=>{let $=1,_=o[S.readUInt32BE($)]={schema:S.toString("utf8",$+=4,$=S.indexOf(0,$))||"pg_catalog",table:S.toString("utf8",$+1,$=S.indexOf(0,$+1)),columns:Array(S.readUInt16BE($+=2)),keys:[]};$+=2;let J=0,R;while($<S.length)R=_.columns[J++]={key:S[$++],name:F.column.from?F.column.from(S.toString("utf8",$,$=S.indexOf(0,$))):S.toString("utf8",$,$=S.indexOf(0,$)),type:S.readUInt32BE($+=1),parser:y[S.readUInt32BE($)],atttypmod:S.readUInt32BE($+=4)},R.key&&_.keys.push(R),$+=4},Y:()=>{},O:()=>{},B:(S)=>{o.date=nZ(S.readBigInt64BE(9)),o.lsn=S.subarray(1,9)},I:(S)=>{let $=1,_=o[S.readUInt32BE($)],{row:J}=YS(S,_.columns,$+=7,F);A(J,{command:"insert",relation:_})},D:(S)=>{let $=1,_=o[S.readUInt32BE($)];$+=4;let J=S[$]===75;A(J||S[$]===79?YS(S,_.columns,$+=3,F).row:null,{command:"delete",relation:_,key:J})},U:(S)=>{let $=1,_=o[S.readUInt32BE($)];$+=4;let J=S[$]===75,R=J||S[$]===79?YS(S,_.columns,$+=3,F):null;R&&($=R.i);let{row:M}=YS(S,_.columns,$+3,F);A(M,{command:"update",relation:_,key:J,old:R&&R.row})},T:()=>{},C:()=>{}}).reduce(f,{})[T[0]](T)}function YS(T,o,y,A){let F,f,S,$=A.raw?new Array(o.length):{};for(let _=0;_<o.length;_++)F=T[y++],f=o[_],S=F===110?null:F===117?void 0:f.parser===void 0?T.toString("utf8",y+4,y+=4+T.readUInt32BE(y)):f.parser.array===!0?f.parser(T.toString("utf8",y+5,y+=4+T.readUInt32BE(y))):f.parser(T.toString("utf8",y+4,y+=4+T.readUInt32BE(y))),A.raw?$[_]=A.raw===!0?S:A.value.from?A.value.from(S,f):S:$[f.name]=A.value.from?A.value.from(S,f):S;return{i:y,row:A.row.from?A.row.from($):$}}function uZ(T){let o=T.match(/^(\*|insert|update|delete)?:?([^.]+?\.?[^=]+)?=?(.+)?/i)||[];if(!o)throw new Error("Malformed subscribe pattern: "+T);let[,y,A,F]=o;return(y||"*")+(A?":"+(A.indexOf(".")===-1?"public."+A:A):"")+(F?"="+F:"")}import e2 from"stream";function y0(T,o,y=393216){return new Promise(async(A,F)=>{await T.begin(async(f)=>{let S;!o&&([{oid:o}]=await f`select lo_creat(-1) as oid`);let[{fd:$}]=await f`select lo_open(${o}, ${y}) as fd`,_={writable:R,readable:J,close:()=>f`select lo_close(${$})`.then(S),tell:()=>f`select lo_tell64(${$})`,read:(M)=>f`select loread(${$}, ${M}) as data`,write:(M)=>f`select lowrite(${$}, ${M})`,truncate:(M)=>f`select lo_truncate64(${$}, ${M})`,seek:(M,Y=0)=>f`select lo_lseek64(${$}, ${M}, ${Y})`,size:()=>f`
|
|
28
66
|
select
|
|
29
|
-
lo_lseek64(${
|
|
67
|
+
lo_lseek64(${$}, location, 0) as position,
|
|
30
68
|
seek.size
|
|
31
69
|
from (
|
|
32
70
|
select
|
|
@@ -34,10 +72,10 @@ ${$.trace}`:"No previous disposal trace was found."),f.type){case"atom_family":c
|
|
|
34
72
|
tell.location
|
|
35
73
|
from (select lo_tell64($1) as location) tell
|
|
36
74
|
) seek
|
|
37
|
-
`};return f(J),new Promise(async(W)=>$=W);async function t({highWaterMark:W=16384,start:O=0,end:_=1/0}={}){let Q=_-O;return O&&await J.seek(O),new G0.Readable({highWaterMark:W,async read(H){let m=H>Q?H-Q:H;Q-=H;let[{data:b}]=await J.read(m);if(this.push(b),b.length<H)this.push(null)}})}async function R({highWaterMark:W=16384,start:O=0}={}){return O&&await J.seek(O),new G0.Writable({highWaterMark:W,write(_,Q,H){J.write(_).then(()=>H(),H)}})}}).catch(S)})}Object.assign(pS,{PostgresError:dn,toPascal:On,pascal:R$,toCamel:Wn,camel:t$,toKebab:wn,kebab:M$,fromPascal:If,fromCamel:Cf,fromKebab:jf,BigInt:{to:20,from:[20],parse:(o)=>BigInt(o),serialize:(o)=>o.toString()}});var un=pS;function pS(o,T){let n=Ny(o,T),f=n.no_subscribe||w$(pS,{...n}),S=!1,A=MT(),$=MT(),F=MT(),J=MT(),t=MT(),R=MT(),W=MT(),O=MT(),_={connecting:$,reserved:F,closed:J,ended:t,open:R,busy:W,full:O},Q=[...Array(n.max)].map(()=>O$(n,_,{onopen:nT,onend:mo,onclose:IT})),H=m(v);return Object.assign(H,{get parameters(){return n.parameters},largeObject:_$.bind(null,H),subscribe:f,CLOSE:gn,END:gn,PostgresError:dn,options:n,reserve:P,listen:b,begin:E,close:q,end:s}),H;function m(G){return G.debug=n.debug,Object.entries(n.types).reduce((To,[wo,Vo])=>{return To[wo]=(Yo)=>new CT(Yo,Vo.to),To},p),Object.assign(Fo,{types:p,typed:p,unsafe:Go,notify:r,array:D,json:U,file:Lo}),Fo;function p(To,wo){return new CT(To,wo)}function Fo(To,...wo){return To&&Array.isArray(To.raw)?new wT(To,wo,G,K):typeof To==="string"&&!wo.length?new hf(n.transform.column.to?n.transform.column.to(To):To):new NS(To,wo)}function Go(To,wo=[],Vo={}){return arguments.length===2&&!Array.isArray(wo)&&(Vo=wo,wo=[]),new wT([To],wo,G,K,{prepare:!1,...Vo,simple:"simple"in Vo?Vo.simple:wo.length===0})}function Lo(To,wo=[],Vo={}){return arguments.length===2&&!Array.isArray(wo)&&(Vo=wo,wo=[]),new wT([],wo,(Ho)=>{hy.readFile(To,"utf8",(Zo,_o)=>{if(Zo)return Ho.reject(Zo);Ho.strings=[_o],G(Ho)})},K,{...Vo,simple:"simple"in Vo?Vo.simple:wo.length===0})}}async function b(G,p,Fo){let Go={fn:p,onlisten:Fo},Lo=b.sql||(b.sql=pS({...n,max:1,idle_timeout:null,max_lifetime:null,fetch_types:!1,onclose(){Object.entries(b.channels).forEach(([Ho,{listeners:Zo}])=>{delete b.channels[Ho],Promise.all(Zo.map((_o)=>b(Ho,_o.fn,_o.onlisten).catch(()=>{})))})},onnotify(Ho,Zo){Ho in b.channels&&b.channels[Ho].listeners.forEach((_o)=>_o.fn(Zo))}})),To=b.channels||(b.channels={});if(G in To){To[G].listeners.push(Go);let Ho=await To[G].result;return Go.onlisten&&Go.onlisten(),{state:Ho.state,unlisten:Yo}}To[G]={result:Lo`listen ${Lo.unsafe('"'+G.replace(/"/g,'""')+'"')}`,listeners:[Go]};let Vo=await To[G].result;return Go.onlisten&&Go.onlisten(),{state:Vo.state,unlisten:Yo};async function Yo(){if(G in To===!1)return;if(To[G].listeners=To[G].listeners.filter((Ho)=>Ho!==Go),To[G].listeners.length)return;return delete To[G],Lo`unlisten ${Lo.unsafe('"'+G.replace(/"/g,'""')+'"')}`}}async function r(G,p){return await H`select pg_notify(${G}, ${""+p})`}async function P(){let G=MT(),p=R.length?R.shift():await new Promise((Lo)=>{A.push({reserve:Lo}),J.length&&ko(J.shift())});z(p,F),p.reserved=()=>G.length?p.execute(G.shift()):z(p,F),p.reserved.release=!0;let Fo=m(Go);return Fo.release=()=>{p.reserved=null,nT(p)},Fo;function Go(Lo){p.queue===O?G.push(Lo):p.execute(Lo)||z(p,O)}}async function E(G,p){!p&&(p=G,G="");let Fo=MT(),Go=0,Lo,To=null;try{return await H.unsafe("begin "+G.replace(/[^a-z ]/ig,""),[],{onexecute:Vo}).execute(),await Promise.race([wo(Lo,p),new Promise((Yo,Ho)=>Lo.onclose=Ho)])}catch(Yo){throw Yo}async function wo(Yo,Ho,Zo){let _o=m(Co);_o.savepoint=cT,_o.prepare=(Ko)=>To=Ko.replace(/[^a-z0-9$-_. ]/gi);let _T,Po;Zo&&await _o`savepoint ${_o(Zo)}`;try{if(Po=await new Promise((Ko,XT)=>{let QT=Ho(_o);Promise.resolve(Array.isArray(QT)?Promise.all(QT):QT).then(Ko,XT)}),_T)throw _T}catch(Ko){throw await(Zo?_o`rollback to ${_o(Zo)}`:_o`rollback`),Ko instanceof dn&&Ko.code==="25P02"&&_T||Ko}if(!Zo)To?await _o`prepare transaction '${_o.unsafe(To)}'`:await _o`commit`;return Po;function cT(Ko,XT){if(Ko&&Array.isArray(Ko.raw))return cT((QT)=>QT.apply(QT,arguments));return arguments.length===1&&(XT=Ko,Ko=null),wo(Yo,XT,"s"+Go+++(Ko?"_"+Ko:""))}function Co(Ko){Ko.catch((XT)=>_T||(_T=XT)),Yo.queue===O?Fo.push(Ko):Yo.execute(Ko)||z(Yo,O)}}function Vo(Yo){Lo=Yo,z(Yo,F),Yo.reserved=()=>Fo.length?Yo.execute(Fo.shift()):z(Yo,F)}}function z(G,p){return G.queue.remove(G),p.push(G),G.queue=p,p===R?G.idleTimer.start():G.idleTimer.cancel(),G}function U(G){return new CT(G,3802)}function D(G,p){if(!Array.isArray(G))return D(Array.from(arguments));return new CT(G,p||(G.length?jS(G)||25:0),n.shared.typeArrayMap)}function v(G){if(S)return G.reject(Bo.connection("CONNECTION_ENDED",n,n));if(R.length)return l(R.shift(),G);if(J.length)return ko(J.shift(),G);W.length?l(W.shift(),G):A.push(G)}function l(G,p){return G.execute(p)?z(G,W):z(G,O)}function K(G){return new Promise((p,Fo)=>{G.state?G.active?O$(n).cancel(G.state,p,Fo):G.cancelled={resolve:p,reject:Fo}:(A.remove(G),G.cancelled=!0,G.reject(Bo.generic("57014","canceling statement due to user request")),p())})}async function s({timeout:G=null}={}){if(S)return S;await 1;let p;return S=Promise.race([new Promise((Fo)=>G!==null&&(p=setTimeout(a,G*1000,Fo))),Promise.all(Q.map((Fo)=>Fo.end()).concat(b.sql?b.sql.end({timeout:0}):[],f.sql?f.sql.end({timeout:0}):[]))]).then(()=>clearTimeout(p))}async function q(){await Promise.all(Q.map((G)=>G.end()))}async function a(G){await Promise.all(Q.map((p)=>p.terminate()));while(A.length)A.shift().reject(Bo.connection("CONNECTION_DESTROYED",n));G()}function ko(G,p){return z(G,$),G.connect(p),G}function mo(G){z(G,t)}function nT(G){if(A.length===0)return z(G,R);let p=Math.ceil(A.length/($.length+1)),Fo=!0;while(Fo&&A.length&&p-- >0){let Go=A.shift();if(Go.reserve)return Go.reserve(G);Fo=G.execute(Go)}Fo?z(G,W):z(G,O)}function IT(G,p){z(G,J),G.reserved=null,G.onclose&&(G.onclose(p),G.onclose=null),n.onclose&&n.onclose(G.id),A.length&&ko(G,A.shift())}}function Ny(o,T){if(o&&o.shared)return o;let n=process.env,f=(!o||typeof o==="string"?T:o)||{},{url:S,multihost:A}=qy(o),$=[...S.searchParams].reduce((O,[_,Q])=>(O[_]=Q,O),{}),F=f.hostname||f.host||A||S.hostname||n.PGHOST||"localhost",J=f.port||S.port||n.PGPORT||5432,t=f.user||f.username||S.username||n.PGUSERNAME||n.PGUSER||py();f.no_prepare&&(f.prepare=!1),$.sslmode&&($.ssl=$.sslmode,delete $.sslmode),"timeout"in f&&(console.log("The timeout option is deprecated, use idle_timeout instead"),f.idle_timeout=f.timeout),$.sslrootcert==="system"&&($.ssl="verify-full");let R=["idle_timeout","connect_timeout","max_lifetime","max_pipeline","backoff","keep_alive"],W={max:10,ssl:!1,idle_timeout:null,connect_timeout:30,max_lifetime:vy,max_pipeline:100,backoff:xy,keep_alive:60,prepare:!0,debug:!1,fetch_types:!0,publications:"alltables",target_session_attrs:null};return{host:Array.isArray(F)?F:F.split(",").map((O)=>O.split(":")[0]),port:Array.isArray(J)?J:F.split(",").map((O)=>parseInt(O.split(":")[1]||J)),path:f.path||F.indexOf("/")>-1&&F+"/.s.PGSQL."+J,database:f.database||f.db||(S.pathname||"").slice(1)||n.PGDATABASE||t,user:t,pass:f.pass||f.password||S.password||n.PGPASSWORD||"",...Object.entries(W).reduce((O,[_,Q])=>{let H=_ in f?f[_]:(_ in $)?$[_]==="disable"||$[_]==="false"?!1:$[_]:n["PG"+_.toUpperCase()]||Q;return O[_]=typeof H==="string"&&R.includes(_)?+H:H,O},{}),connection:{application_name:"postgres.js",...f.connection,...Object.entries($).reduce((O,[_,Q])=>((_ in W)||(O[_]=Q),O),{})},types:f.types||{},target_session_attrs:by(f,S,n),onnotice:f.onnotice,onnotify:f.onnotify,onclose:f.onclose,onparameter:f.onparameter,socket:f.socket,transform:ry(f.transform||{undefined:void 0}),parameters:{},shared:{retries:0,typeArrayMap:{}},...M0(f.types)}}function by(o,T,n){let f=o.target_session_attrs||T.searchParams.get("target_session_attrs")||n.PGTARGETSESSIONATTRS;if(!f||["read-write","read-only","primary","standby","prefer-standby"].includes(f))return f;throw new Error("target_session_attrs "+f+" is not supported")}function xy(o){return(0.5+Math.random()/2)*Math.min(3**o/100,20)}function vy(){return 60*(30+Math.random()*30)}function ry(o){return{undefined:o.undefined,column:{from:typeof o.column==="function"?o.column:o.column&&o.column.from,to:o.column&&o.column.to},value:{from:typeof o.value==="function"?o.value:o.value&&o.value.from,to:o.value&&o.value.to},row:{from:typeof o.row==="function"?o.row:o.row&&o.row.from,to:o.row&&o.row.to}}}function qy(o){if(!o||typeof o!=="string")return{url:{searchParams:new Map}};let T=o;T=T.slice(T.indexOf("://")+3).split(/[?/]/)[0],T=decodeURIComponent(T.slice(T.indexOf("@")+1));let n=new URL(o.replace(T,T.split(",")[0]));return{url:{username:decodeURIComponent(n.username),password:decodeURIComponent(n.password),host:n.host,hostname:n.hostname,port:n.port,pathname:n.pathname,searchParams:n.searchParams},multihost:T.indexOf(",")>-1&&T}}function py(){try{return jy.userInfo().username}catch(o){return process.env.USERNAME||process.env.USER||process.env.LOGNAME}}class Qo{static[y]="SelectionProxyHandler";config;constructor(o){this.config={...o}}get(o,T){if(T==="_")return{...o._,selectedFields:new Proxy(o._.selectedFields,this)};if(T===Xo)return{...o[Xo],selectedFields:new Proxy(o[Xo].selectedFields,this)};if(typeof T==="symbol")return o[T];let f=(X(o,No)?o._.selectedFields:X(o,ST)?o[Xo].selectedFields:o)[T];if(X(f,j.Aliased)){if(this.config.sqlAliasedBehavior==="sql"&&!f.isSelectionField)return f.sql;let S=f.clone();return S.isSelectionField=!0,S}if(X(f,j)){if(this.config.sqlBehavior==="sql")return f;throw new Error(`You tried to reference "${T}" 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(X(f,Wo)){if(this.config.alias)return new Proxy(f,new Pn(new Proxy(f.table,new Df(this.config.alias,this.config.replaceOriginalName??!1))));return f}if(typeof f!=="object"||f===null)return f;return new Proxy(f,new Qo(this.config))}}class cS extends oT{constructor(o,T,n,f){super();this.session=T,this.dialect=n,this.config={table:o,withList:f}}static[y]="PgDelete";config;where(o){return this.config.where=o,this}returning(o=this.config.table[I.Symbol.Columns]){return this.config.returningFields=o,this.config.returning=OT(o),this}getSQL(){return this.dialect.buildDeleteQuery(this.config)}toSQL(){let{typings:o,...T}=this.dialect.sqlToQuery(this.getSQL());return T}_prepare(o){return Oo.startActiveSpan("drizzle.prepareQuery",()=>{return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,o,!0)})}prepare(o){return this._prepare(o)}authToken;setToken(o){return this.authToken=o,this}execute=(o)=>{return Oo.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(o,this.authToken)})};getSelectedFields(){return this.config.returningFields?new Proxy(this.config.returningFields,new Qo({alias:vo(this.config.table),sqlAliasedBehavior:"alias",sqlBehavior:"error"})):void 0}$dynamic(){return this}}function cy(o){return(o.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).map((n)=>n.toLowerCase()).join("_")}function Zy(o){return(o.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).reduce((n,f,S)=>{let A=S===0?f.toLowerCase():`${f[0].toUpperCase()}${f.slice(1)}`;return n+A},"")}function Py(o){return o}class X${static[y]="CasingCache";cache={};cachedTables={};convert;constructor(o){this.convert=o==="snake_case"?cy:o==="camelCase"?Zy:Py}getColumnCasing(o){if(!o.keyAsName)return o.name;let T=o.table[I.Symbol.Schema]??"public",n=o.table[I.Symbol.OriginalName],f=`${T}.${n}.${o.name}`;if(!this.cache[f])this.cacheTable(o.table);return this.cache[f]}cacheTable(o){let T=o[I.Symbol.Schema]??"public",n=o[I.Symbol.OriginalName],f=`${T}.${n}`;if(!this.cachedTables[f]){for(let S of Object.values(o[I.Symbol.Columns])){let A=`${f}.${S.name}`;this.cache[A]=this.convert(S.name)}this.cachedTables[f]=!0}}clearCache(){this.cache={},this.cachedTables={}}}class bf extends ST{static[y]="PgViewBase"}class Xn{static[y]="PgDialect";casing;constructor(o){this.casing=new X$(o?.casing)}async migrate(o,T,n){let f=typeof n==="string"?"__drizzle_migrations":n.migrationsTable??"__drizzle_migrations",S=typeof n==="string"?"drizzle":n.migrationsSchema??"drizzle",A=k`
|
|
38
|
-
CREATE TABLE IF NOT EXISTS ${
|
|
75
|
+
`};return A(_),new Promise(async(M)=>S=M);async function J({highWaterMark:M=16384,start:Y=0,end:H=1/0}={}){let Q=H-Y;return Y&&await _.seek(Y),new e2.Readable({highWaterMark:M,async read(w){let B=w>Q?w-Q:w;Q-=w;let[{data:t}]=await _.read(B);if(this.push(t),t.length<w)this.push(null)}})}async function R({highWaterMark:M=16384,start:Y=0}={}){return Y&&await _.seek(Y),new e2.Writable({highWaterMark:M,write(H,Q,w){_.write(H).then(()=>w(),w)}})}}).catch(F)})}Object.assign(ZS,{PostgresError:BA,toPascal:ry,pascal:rJ,toCamel:dy,camel:dJ,toKebab:ly,kebab:lJ,fromPascal:xF,fromCamel:bF,fromKebab:jF,BigInt:{to:20,from:[20],parse:(T)=>BigInt(T),serialize:(T)=>T.toString()}});var tA=ZS;function ZS(T,o){let y=dZ(T,o),A=y.no_subscribe||o0(ZS,{...y}),F=!1,f=Io(),S=Io(),$=Io(),_=Io(),J=Io(),R=Io(),M=Io(),Y=Io(),H={connecting:S,reserved:$,closed:_,ended:J,open:R,busy:M,full:Y},Q=[...Array(y.max)].map(()=>T0(y,H,{onopen:Xo,onend:qT,onclose:Ay})),w=B(v);return Object.assign(w,{get parameters(){return y.parameters},largeObject:y0.bind(null,w),subscribe:A,CLOSE:kA,END:kA,PostgresError:BA,options:y,reserve:h,listen:t,begin:K,close:P,end:a}),w;function B(D){return D.debug=y.debug,Object.entries(y.types).reduce((yT,[UT,xT])=>{return yT[UT]=(kT)=>new yy(kT,xT.to),yT},n),Object.assign(RT,{types:n,typed:n,unsafe:IT,notify:m,array:C,json:L,file:vT}),RT;function n(yT,UT){return new yy(yT,UT)}function RT(yT,...UT){return yT&&Array.isArray(yT.raw)?new mo(yT,UT,D,z):typeof yT==="string"&&!UT.length?new mF(y.transform.column.to?y.transform.column.to(yT):yT):new RS(yT,UT)}function IT(yT,UT=[],xT={}){return arguments.length===2&&!Array.isArray(UT)&&(xT=UT,UT=[]),new mo([yT],UT,D,z,{prepare:!1,...xT,simple:"simple"in xT?xT.simple:UT.length===0})}function vT(yT,UT=[],xT={}){return arguments.length===2&&!Array.isArray(UT)&&(xT=UT,UT=[]),new mo([],UT,(DT)=>{cZ.readFile(yT,"utf8",(oo,KT)=>{if(oo)return DT.reject(oo);DT.strings=[KT],D(DT)})},z,{...xT,simple:"simple"in xT?xT.simple:UT.length===0})}}async function t(D,n,RT){let IT={fn:n,onlisten:RT},vT=t.sql||(t.sql=ZS({...y,max:1,idle_timeout:null,max_lifetime:null,fetch_types:!1,onclose(){Object.entries(t.channels).forEach(([DT,{listeners:oo}])=>{delete t.channels[DT],Promise.all(oo.map((KT)=>t(DT,KT.fn,KT.onlisten).catch(()=>{})))})},onnotify(DT,oo){DT in t.channels&&t.channels[DT].listeners.forEach((KT)=>KT.fn(oo))}})),yT=t.channels||(t.channels={});if(D in yT){yT[D].listeners.push(IT);let DT=await yT[D].result;return IT.onlisten&&IT.onlisten(),{state:DT.state,unlisten:kT}}yT[D]={result:vT`listen ${vT.unsafe('"'+D.replace(/"/g,'""')+'"')}`,listeners:[IT]};let xT=await yT[D].result;return IT.onlisten&&IT.onlisten(),{state:xT.state,unlisten:kT};async function kT(){if(D in yT===!1)return;if(yT[D].listeners=yT[D].listeners.filter((DT)=>DT!==IT),yT[D].listeners.length)return;return delete yT[D],vT`unlisten ${vT.unsafe('"'+D.replace(/"/g,'""')+'"')}`}}async function m(D,n){return await w`select pg_notify(${D}, ${""+n})`}async function h(){let D=Io(),n=R.length?R.shift():await new Promise((vT)=>{f.push({reserve:vT}),_.length&&HT(_.shift())});V(n,$),n.reserved=()=>D.length?n.execute(D.shift()):V(n,$),n.reserved.release=!0;let RT=B(IT);return RT.release=()=>{n.reserved=null,Xo(n)},RT;function IT(vT){n.queue===Y?D.push(vT):n.execute(vT)||V(n,Y)}}async function K(D,n){!n&&(n=D,D="");let RT=Io(),IT=0,vT,yT=null;try{return await w.unsafe("begin "+D.replace(/[^a-z ]/ig,""),[],{onexecute:xT}).execute(),await Promise.race([UT(vT,n),new Promise((kT,DT)=>vT.onclose=DT)])}catch(kT){throw kT}async function UT(kT,DT,oo){let KT=B(PT);KT.savepoint=wy,KT.prepare=(CT)=>yT=CT.replace(/[^a-z0-9$-_. ]/gi);let qo,yo;oo&&await KT`savepoint ${KT(oo)}`;try{if(yo=await new Promise((CT,vo)=>{let ro=DT(KT);Promise.resolve(Array.isArray(ro)?Promise.all(ro):ro).then(CT,vo)}),qo)throw qo}catch(CT){throw await(oo?KT`rollback to ${KT(oo)}`:KT`rollback`),CT instanceof BA&&CT.code==="25P02"&&qo||CT}if(!oo)yT?await KT`prepare transaction '${KT.unsafe(yT)}'`:await KT`commit`;return yo;function wy(CT,vo){if(CT&&Array.isArray(CT.raw))return wy((ro)=>ro.apply(ro,arguments));return arguments.length===1&&(vo=CT,CT=null),UT(kT,vo,"s"+IT+++(CT?"_"+CT:""))}function PT(CT){CT.catch((vo)=>qo||(qo=vo)),kT.queue===Y?RT.push(CT):kT.execute(CT)||V(kT,Y)}}function xT(kT){vT=kT,V(kT,$),kT.reserved=()=>RT.length?kT.execute(RT.shift()):V(kT,$)}}function V(D,n){return D.queue.remove(D),n.push(D),D.queue=n,n===R?D.idleTimer.start():D.idleTimer.cancel(),D}function L(D){return new yy(D,3802)}function C(D,n){if(!Array.isArray(D))return C(Array.from(arguments));return new yy(D,n||(D.length?JS(D)||25:0),y.shared.typeArrayMap)}function v(D){if(F)return D.reject(mT.connection("CONNECTION_ENDED",y,y));if(R.length)return s(R.shift(),D);if(_.length)return HT(_.shift(),D);M.length?s(M.shift(),D):f.push(D)}function s(D,n){return D.execute(n)?V(D,M):V(D,Y)}function z(D){return new Promise((n,RT)=>{D.state?D.active?T0(y).cancel(D.state,n,RT):D.cancelled={resolve:n,reject:RT}:(f.remove(D),D.cancelled=!0,D.reject(mT.generic("57014","canceling statement due to user request")),n())})}async function a({timeout:D=null}={}){if(F)return F;await 1;let n;return F=Promise.race([new Promise((RT)=>D!==null&&(n=setTimeout(e,D*1000,RT))),Promise.all(Q.map((RT)=>RT.end()).concat(t.sql?t.sql.end({timeout:0}):[],A.sql?A.sql.end({timeout:0}):[]))]).then(()=>clearTimeout(n))}async function P(){await Promise.all(Q.map((D)=>D.end()))}async function e(D){await Promise.all(Q.map((n)=>n.terminate()));while(f.length)f.shift().reject(mT.connection("CONNECTION_DESTROYED",y));D()}function HT(D,n){return V(D,S),D.connect(n),D}function qT(D){V(D,J)}function Xo(D){if(f.length===0)return V(D,R);let n=Math.ceil(f.length/(S.length+1)),RT=!0;while(RT&&f.length&&n-- >0){let IT=f.shift();if(IT.reserve)return IT.reserve(D);RT=D.execute(IT)}RT?V(D,M):V(D,Y)}function Ay(D,n){V(D,_),D.reserved=null,D.onclose&&(D.onclose(n),D.onclose=null),y.onclose&&y.onclose(D.id),f.length&&HT(D,f.shift())}}function dZ(T,o){if(T&&T.shared)return T;let y=process.env,A=(!T||typeof T==="string"?o:T)||{},{url:F,multihost:f}=eZ(T),S=[...F.searchParams].reduce((Y,[H,Q])=>(Y[H]=Q,Y),{}),$=A.hostname||A.host||f||F.hostname||y.PGHOST||"localhost",_=A.port||F.port||y.PGPORT||5432,J=A.user||A.username||F.username||y.PGUSERNAME||y.PGUSER||T5();A.no_prepare&&(A.prepare=!1),S.sslmode&&(S.ssl=S.sslmode,delete S.sslmode),"timeout"in A&&(console.log("The timeout option is deprecated, use idle_timeout instead"),A.idle_timeout=A.timeout),S.sslrootcert==="system"&&(S.ssl="verify-full");let R=["idle_timeout","connect_timeout","max_lifetime","max_pipeline","backoff","keep_alive"],M={max:10,ssl:!1,idle_timeout:null,connect_timeout:30,max_lifetime:sZ,max_pipeline:100,backoff:lZ,keep_alive:60,prepare:!0,debug:!1,fetch_types:!0,publications:"alltables",target_session_attrs:null};return{host:Array.isArray($)?$:$.split(",").map((Y)=>Y.split(":")[0]),port:Array.isArray(_)?_:$.split(",").map((Y)=>parseInt(Y.split(":")[1]||_)),path:A.path||$.indexOf("/")>-1&&$+"/.s.PGSQL."+_,database:A.database||A.db||(F.pathname||"").slice(1)||y.PGDATABASE||J,user:J,pass:A.pass||A.password||F.password||y.PGPASSWORD||"",...Object.entries(M).reduce((Y,[H,Q])=>{let w=H in A?A[H]:(H in S)?S[H]==="disable"||S[H]==="false"?!1:S[H]:y["PG"+H.toUpperCase()]||Q;return Y[H]=typeof w==="string"&&R.includes(H)?+w:w,Y},{}),connection:{application_name:"postgres.js",...A.connection,...Object.entries(S).reduce((Y,[H,Q])=>((H in M)||(Y[H]=Q),Y),{})},types:A.types||{},target_session_attrs:rZ(A,F,y),onnotice:A.onnotice,onnotify:A.onnotify,onclose:A.onclose,onparameter:A.onparameter,socket:A.socket,transform:aZ(A.transform||{undefined:void 0}),parameters:{},shared:{retries:0,typeArrayMap:{}},...h2(A.types)}}function rZ(T,o,y){let A=T.target_session_attrs||o.searchParams.get("target_session_attrs")||y.PGTARGETSESSIONATTRS;if(!A||["read-write","read-only","primary","standby","prefer-standby"].includes(A))return A;throw new Error("target_session_attrs "+A+" is not supported")}function lZ(T){return(0.5+Math.random()/2)*Math.min(3**T/100,20)}function sZ(){return 60*(30+Math.random()*30)}function aZ(T){return{undefined:T.undefined,column:{from:typeof T.column==="function"?T.column:T.column&&T.column.from,to:T.column&&T.column.to},value:{from:typeof T.value==="function"?T.value:T.value&&T.value.from,to:T.value&&T.value.to},row:{from:typeof T.row==="function"?T.row:T.row&&T.row.from,to:T.row&&T.row.to}}}function eZ(T){if(!T||typeof T!=="string")return{url:{searchParams:new Map}};let o=T;o=o.slice(o.indexOf("://")+3).split(/[?/]/)[0],o=decodeURIComponent(o.slice(o.indexOf("@")+1));let y=new URL(T.replace(o,o.split(",")[0]));return{url:{username:decodeURIComponent(y.username),password:decodeURIComponent(y.password),host:y.host,hostname:y.hostname,port:y.port,pathname:y.pathname,searchParams:y.searchParams},multihost:o.indexOf(",")>-1&&o}}function T5(){try{return iZ.userInfo().username}catch(T){return process.env.USERNAME||process.env.USER||process.env.LOGNAME}}class tT{static[O]="SelectionProxyHandler";config;constructor(T){this.config={...T}}get(T,o){if(o==="_")return{...T._,selectedFields:new Proxy(T._.selectedFields,this)};if(o===VT)return{...T[VT],selectedFields:new Proxy(T[VT].selectedFields,this)};if(typeof o==="symbol")return T[o];let A=(G(T,cT)?T._.selectedFields:G(T,Uo)?T[VT].selectedFields:T)[o];if(G(A,x.Aliased)){if(this.config.sqlAliasedBehavior==="sql"&&!A.isSelectionField)return A.sql;let F=A.clone();return F.isSelectionField=!0,F}if(G(A,x)){if(this.config.sqlBehavior==="sql")return A;throw new Error(`You tried to reference "${o}" 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(G(A,GT)){if(this.config.alias)return new Proxy(A,new IA(new Proxy(A.table,new LF(this.config.alias,this.config.replaceOriginalName??!1))));return A}if(typeof A!=="object"||A===null)return A;return new Proxy(A,new tT(this.config))}}class HS extends Oo{constructor(T,o,y,A){super();this.session=o,this.dialect=y,this.config={table:T,withList:A}}static[O]="PgDelete";config;where(T){return this.config.where=T,this}returning(T=this.config.table[b.Symbol.Columns]){return this.config.returningFields=T,this.config.returning=jo(T),this}getSQL(){return this.dialect.buildDeleteQuery(this.config)}toSQL(){let{typings:T,...o}=this.dialect.sqlToQuery(this.getSQL());return o}_prepare(T){return wT.startActiveSpan("drizzle.prepareQuery",()=>{return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,T,!0)})}prepare(T){return this._prepare(T)}authToken;setToken(T){return this.authToken=T,this}execute=(T)=>{return wT.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(T,this.authToken)})};getSelectedFields(){return this.config.returningFields?new Proxy(this.config.returningFields,new tT({alias:lT(this.config.table),sqlAliasedBehavior:"alias",sqlBehavior:"error"})):void 0}$dynamic(){return this}}function o5(T){return(T.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).map((y)=>y.toLowerCase()).join("_")}function y5(T){return(T.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).reduce((y,A,F)=>{let f=F===0?A.toLowerCase():`${A[0].toUpperCase()}${A.slice(1)}`;return y+f},"")}function A5(T){return T}class A0{static[O]="CasingCache";cache={};cachedTables={};convert;constructor(T){this.convert=T==="snake_case"?o5:T==="camelCase"?y5:A5}getColumnCasing(T){if(!T.keyAsName)return T.name;let o=T.table[b.Symbol.Schema]??"public",y=T.table[b.Symbol.OriginalName],A=`${o}.${y}.${T.name}`;if(!this.cache[A])this.cacheTable(T.table);return this.cache[A]}cacheTable(T){let o=T[b.Symbol.Schema]??"public",y=T[b.Symbol.OriginalName],A=`${o}.${y}`;if(!this.cachedTables[A]){for(let F of Object.values(T[b.Symbol.Columns])){let f=`${A}.${F.name}`;this.cache[f]=this.convert(F.name)}this.cachedTables[A]=!0}}clearCache(){this.cache={},this.cachedTables={}}}class vF extends Uo{static[O]="PgViewBase"}class ay{static[O]="PgDialect";casing;constructor(T){this.casing=new A0(T?.casing)}async migrate(T,o,y){let A=typeof y==="string"?"__drizzle_migrations":y.migrationsTable??"__drizzle_migrations",F=typeof y==="string"?"drizzle":y.migrationsSchema??"drizzle",f=X`
|
|
76
|
+
CREATE TABLE IF NOT EXISTS ${X.identifier(F)}.${X.identifier(A)} (
|
|
39
77
|
id SERIAL PRIMARY KEY,
|
|
40
78
|
hash text NOT NULL,
|
|
41
79
|
created_at bigint
|
|
42
80
|
)
|
|
43
|
-
`;await T.execute(k`CREATE SCHEMA IF NOT EXISTS ${k.identifier(S)}`),await T.execute(A);let F=(await T.all(k`select id, hash, created_at from ${k.identifier(S)}.${k.identifier(f)} order by created_at desc limit 1`))[0];await T.transaction(async(J)=>{for await(let t of o)if(!F||Number(F.created_at)<t.folderMillis){for(let R of t.sql)await J.execute(k.raw(R));await J.execute(k`insert into ${k.identifier(S)}.${k.identifier(f)} ("hash", "created_at") values(${t.hash}, ${t.folderMillis})`)}})}escapeName(o){return`"${o}"`}escapeParam(o){return`$${o+1}`}escapeString(o){return`'${o.replace(/'/g,"''")}'`}buildWithCTE(o){if(!o?.length)return;let T=[k`with `];for(let[n,f]of o.entries())if(T.push(k`${k.identifier(f._.alias)} as (${f._.sql})`),n<o.length-1)T.push(k`, `);return T.push(k` `),k.join(T)}buildDeleteQuery({table:o,where:T,returning:n,withList:f}){let S=this.buildWithCTE(f),A=n?k` returning ${this.buildSelection(n,{isSingleTable:!0})}`:void 0,$=T?k` where ${T}`:void 0;return k`${S}delete from ${o}${$}${A}`}buildUpdateSet(o,T){let n=o[I.Symbol.Columns],f=Object.keys(n).filter((A)=>T[A]!==void 0||n[A]?.onUpdateFn!==void 0),S=f.length;return k.join(f.flatMap((A,$)=>{let F=n[A],J=T[A]??k.param(F.onUpdateFn(),F),t=k`${k.identifier(this.casing.getColumnCasing(F))} = ${J}`;if($<S-1)return[t,k.raw(", ")];return[t]}))}buildUpdateQuery({table:o,set:T,where:n,returning:f,withList:S,from:A,joins:$}){let F=this.buildWithCTE(S),J=o[co.Symbol.Name],t=o[co.Symbol.Schema],R=o[co.Symbol.OriginalName],W=J===R?void 0:J,O=k`${t?k`${k.identifier(t)}.`:void 0}${k.identifier(R)}${W&&k` ${k.identifier(W)}`}`,_=this.buildUpdateSet(o,T),Q=A&&k.join([k.raw(" from "),this.buildFromTable(A)]),H=this.buildJoins($),m=f?k` returning ${this.buildSelection(f,{isSingleTable:!A})}`:void 0,b=n?k` where ${n}`:void 0;return k`${F}update ${O} set ${_}${Q}${H}${b}${m}`}buildSelection(o,{isSingleTable:T=!1}={}){let n=o.length,f=o.flatMap(({field:S},A)=>{let $=[];if(X(S,j.Aliased)&&S.isSelectionField)$.push(k.identifier(S.fieldAlias));else if(X(S,j.Aliased)||X(S,j)){let F=X(S,j.Aliased)?S.sql:S;if(T)$.push(new j(F.queryChunks.map((J)=>{if(X(J,V))return k.identifier(this.casing.getColumnCasing(J));return J})));else $.push(F);if(X(S,j.Aliased))$.push(k` as ${k.identifier(S.fieldAlias)}`)}else if(X(S,Wo))if(T)$.push(k.identifier(this.casing.getColumnCasing(S)));else $.push(S);if(A<n-1)$.push(k`, `);return $});return k.join(f)}buildJoins(o){if(!o||o.length===0)return;let T=[];for(let[n,f]of o.entries()){if(n===0)T.push(k` `);let S=f.table,A=f.lateral?k` lateral`:void 0;if(X(S,co)){let $=S[co.Symbol.Name],F=S[co.Symbol.Schema],J=S[co.Symbol.OriginalName],t=$===J?void 0:f.alias;T.push(k`${k.raw(f.joinType)} join${A} ${F?k`${k.identifier(F)}.`:void 0}${k.identifier(J)}${t&&k` ${k.identifier(t)}`} on ${f.on}`)}else if(X(S,ST)){let $=S[Xo].name,F=S[Xo].schema,J=S[Xo].originalName,t=$===J?void 0:f.alias;T.push(k`${k.raw(f.joinType)} join${A} ${F?k`${k.identifier(F)}.`:void 0}${k.identifier(J)}${t&&k` ${k.identifier(t)}`} on ${f.on}`)}else T.push(k`${k.raw(f.joinType)} join${A} ${S} on ${f.on}`);if(n<o.length-1)T.push(k` `)}return k.join(T)}buildFromTable(o){if(X(o,I)&&o[I.Symbol.IsAlias]){let T=k`${k.identifier(o[I.Symbol.OriginalName])}`;if(o[I.Symbol.Schema])T=k`${k.identifier(o[I.Symbol.Schema])}.${T}`;return k`${T} ${k.identifier(o[I.Symbol.Name])}`}return o}buildSelectQuery({withList:o,fields:T,fieldsFlat:n,where:f,having:S,table:A,joins:$,orderBy:F,groupBy:J,limit:t,offset:R,lockingClause:W,distinct:O,setOperators:_}){let Q=n??OT(T);for(let a of Q)if(X(a.field,Wo)&&vo(a.field.table)!==(X(A,No)?A._.alias:X(A,bf)?A[Xo].name:X(A,j)?void 0:vo(A))&&!((ko)=>$?.some(({alias:mo})=>mo===(ko[I.Symbol.IsAlias]?vo(ko):ko[I.Symbol.BaseName])))(a.field.table)){let ko=vo(a.field.table);throw new Error(`Your "${a.path.join("->")}" field references a column "${ko}"."${a.field.name}", but the table "${ko}" is not part of the query! Did you forget to join it?`)}let H=!$||$.length===0,m=this.buildWithCTE(o),b;if(O)b=O===!0?k` distinct`:k` distinct on (${k.join(O.on,k`, `)})`;let r=this.buildSelection(Q,{isSingleTable:H}),P=this.buildFromTable(A),E=this.buildJoins($),z=f?k` where ${f}`:void 0,U=S?k` having ${S}`:void 0,D;if(F&&F.length>0)D=k` order by ${k.join(F,k`, `)}`;let v;if(J&&J.length>0)v=k` group by ${k.join(J,k`, `)}`;let l=typeof t==="object"||typeof t==="number"&&t>=0?k` limit ${t}`:void 0,K=R?k` offset ${R}`:void 0,s=k.empty();if(W){let a=k` for ${k.raw(W.strength)}`;if(W.config.of)a.append(k` of ${k.join(Array.isArray(W.config.of)?W.config.of:[W.config.of],k`, `)}`);if(W.config.noWait)a.append(k` no wait`);else if(W.config.skipLocked)a.append(k` skip locked`);s.append(a)}let q=k`${m}select${b} ${r} from ${P}${E}${z}${v}${U}${D}${l}${K}${s}`;if(_.length>0)return this.buildSetOperations(q,_);return q}buildSetOperations(o,T){let[n,...f]=T;if(!n)throw new Error("Cannot pass undefined values to any set operator");if(f.length===0)return this.buildSetOperationQuery({leftSelect:o,setOperator:n});return this.buildSetOperations(this.buildSetOperationQuery({leftSelect:o,setOperator:n}),f)}buildSetOperationQuery({leftSelect:o,setOperator:{type:T,isAll:n,rightSelect:f,limit:S,orderBy:A,offset:$}}){let F=k`(${o.getSQL()}) `,J=k`(${f.getSQL()})`,t;if(A&&A.length>0){let _=[];for(let Q of A)if(X(Q,V))_.push(k.identifier(Q.name));else if(X(Q,j)){for(let H=0;H<Q.queryChunks.length;H++){let m=Q.queryChunks[H];if(X(m,V))Q.queryChunks[H]=k.identifier(m.name)}_.push(k`${Q}`)}else _.push(k`${Q}`);t=k` order by ${k.join(_,k`, `)} `}let R=typeof S==="object"||typeof S==="number"&&S>=0?k` limit ${S}`:void 0,W=k.raw(`${T} ${n?"all ":""}`),O=$?k` offset ${$}`:void 0;return k`${F}${W}${J}${t}${R}${O}`}buildInsertQuery({table:o,values:T,onConflict:n,returning:f,withList:S,select:A,overridingSystemValue_:$}){let F=[],J=o[I.Symbol.Columns],t=Object.entries(J).filter(([m,b])=>!b.shouldDisableInsert()),R=t.map(([,m])=>k.identifier(this.casing.getColumnCasing(m)));if(A){let m=T;if(X(m,j))F.push(m);else F.push(m.getSQL())}else{let m=T;F.push(k.raw("values "));for(let[b,r]of m.entries()){let P=[];for(let[E,z]of t){let U=r[E];if(U===void 0||X(U,tT)&&U.value===void 0)if(z.defaultFn!==void 0){let D=z.defaultFn(),v=X(D,j)?D:k.param(D,z);P.push(v)}else if(!z.default&&z.onUpdateFn!==void 0){let D=z.onUpdateFn(),v=X(D,j)?D:k.param(D,z);P.push(v)}else P.push(k`default`);else P.push(U)}if(F.push(P),b<m.length-1)F.push(k`, `)}}let W=this.buildWithCTE(S),O=k.join(F),_=f?k` returning ${this.buildSelection(f,{isSingleTable:!0})}`:void 0,Q=n?k` on conflict ${n}`:void 0,H=$===!0?k`overriding system value `:void 0;return k`${W}insert into ${o} ${R} ${H}${O}${Q}${_}`}buildRefreshMaterializedViewQuery({view:o,concurrently:T,withNoData:n}){let f=T?k` concurrently`:void 0,S=n?k` with no data`:void 0;return k`refresh materialized view${f} ${o}${S}`}prepareTyping(o){if(X(o,DS)||X(o,zS))return"json";else if(X(o,QS))return"decimal";else if(X(o,US))return"time";else if(X(o,VS)||X(o,BS))return"timestamp";else if(X(o,ES)||X(o,GS))return"date";else if(X(o,mS))return"uuid";else return"none"}sqlToQuery(o,T){return o.toQuery({casing:this.casing,escapeName:this.escapeName,escapeParam:this.escapeParam,escapeString:this.escapeString,prepareTyping:this.prepareTyping,invokeSource:T})}buildRelationalQueryWithoutPK({fullSchema:o,schema:T,tableNamesMap:n,table:f,tableConfig:S,queryConfig:A,tableAlias:$,nestedQueryRelation:F,joinOn:J}){let t=[],R,W,O=[],_,Q=[];if(A===!0)t=Object.entries(S.columns).map(([b,r])=>({dbKey:r.name,tsKey:b,field:LT(r,$),relationTableTsKey:void 0,isJson:!1,selection:[]}));else{let m=Object.fromEntries(Object.entries(S.columns).map(([U,D])=>[U,LT(D,$)]));if(A.where){let U=typeof A.where==="function"?A.where(m,sR()):A.where;_=U&&Qf(U,$)}let b=[],r=[];if(A.columns){let U=!1;for(let[D,v]of Object.entries(A.columns)){if(v===void 0)continue;if(D in S.columns){if(!U&&v===!0)U=!0;r.push(D)}}if(r.length>0)r=U?r.filter((D)=>A.columns?.[D]===!0):Object.keys(S.columns).filter((D)=>!r.includes(D))}else r=Object.keys(S.columns);for(let U of r){let D=S.columns[U];b.push({tsKey:U,value:D})}let P=[];if(A.with)P=Object.entries(A.with).filter((U)=>!!U[1]).map(([U,D])=>({tsKey:U,queryConfig:D,relation:S.relations[U]}));let E;if(A.extras){E=typeof A.extras==="function"?A.extras(m,{sql:k}):A.extras;for(let[U,D]of Object.entries(E))b.push({tsKey:U,value:gA(D,$)})}for(let{tsKey:U,value:D}of b)t.push({dbKey:X(D,j.Aliased)?D.fieldAlias:S.columns[U].name,tsKey:U,field:X(D,Wo)?LT(D,$):D,relationTableTsKey:void 0,isJson:!1,selection:[]});let z=typeof A.orderBy==="function"?A.orderBy(m,aR()):A.orderBy??[];if(!Array.isArray(z))z=[z];O=z.map((U)=>{if(X(U,Wo))return LT(U,$);return Qf(U,$)}),R=A.limit,W=A.offset;for(let{tsKey:U,queryConfig:D,relation:v}of P){let l=T0(T,n,v),K=kn(v.referencedTable),s=n[K],q=`${$}_${U}`,a=Uf(...l.fields.map((nT,IT)=>HS(LT(l.references[IT],q),LT(nT,$)))),ko=this.buildRelationalQueryWithoutPK({fullSchema:o,schema:T,tableNamesMap:n,table:o[s],tableConfig:T[s],queryConfig:X(v,on)?D===!0?{limit:1}:{...D,limit:1}:D,tableAlias:q,joinOn:a,nestedQueryRelation:v}),mo=k`${k.identifier(q)}.${k.identifier("data")}`.as(U);Q.push({on:k`true`,table:new No(ko.sql,{},q),alias:q,joinType:"left",lateral:!0}),t.push({dbKey:U,tsKey:U,field:mo,relationTableTsKey:s,isJson:!0,selection:ko.selection})}}if(t.length===0)throw new XS({message:`No fields selected for table "${S.tsName}" ("${$}")`});let H;if(_=Uf(J,_),F){let m=k`json_build_array(${k.join(t.map(({field:P,tsKey:E,isJson:z})=>z?k`${k.identifier(`${$}_${E}`)}.${k.identifier("data")}`:X(P,j.Aliased)?P.sql:P),k`, `)})`;if(X(F,Lf))m=k`coalesce(json_agg(${m}${O.length>0?k` order by ${k.join(O,k`, `)}`:void 0}), '[]'::json)`;let b=[{dbKey:"data",tsKey:"data",field:m.as("data"),isJson:!0,relationTableTsKey:S.tsName,selection:t}];if(R!==void 0||W!==void 0||O.length>0)H=this.buildSelectQuery({table:_S(f,$),fields:{},fieldsFlat:[{path:[],field:k.raw("*")}],where:_,limit:R,offset:W,orderBy:O,setOperators:[]}),_=void 0,R=void 0,W=void 0,O=[];else H=_S(f,$);H=this.buildSelectQuery({table:X(H,co)?H:new No(H,{},$),fields:{},fieldsFlat:b.map(({field:P})=>({path:[],field:X(P,Wo)?LT(P,$):P})),joins:Q,where:_,limit:R,offset:W,orderBy:O,setOperators:[]})}else H=this.buildSelectQuery({table:_S(f,$),fields:{},fieldsFlat:t.map(({field:m})=>({path:[],field:X(m,Wo)?LT(m,$):m})),joins:Q,where:_,limit:R,offset:W,orderBy:O,setOperators:[]});return{tableTsKey:S.tsName,sql:H,selection:t}}}class H${static[y]="TypedQueryBuilder";getSelectedFields(){return this._.selectedFields}}class TT{static[y]="PgSelectBuilder";fields;session;dialect;withList=[];distinct;constructor(o){if(this.fields=o.fields,this.session=o.session,this.dialect=o.dialect,o.withList)this.withList=o.withList;this.distinct=o.distinct}authToken;setToken(o){return this.authToken=o,this}from(o){let T=!!this.fields,n=o,f;if(this.fields)f=this.fields;else if(X(n,No))f=Object.fromEntries(Object.keys(n._.selectedFields).map((S)=>[S,n[S]]));else if(X(n,bf))f=n[Xo].selectedFields;else if(X(n,j))f={};else f=sJ(n);return new K$({table:n,fields:f,isPartialSelect:T,session:this.session,dialect:this.dialect,withList:this.withList,distinct:this.distinct}).setToken(this.authToken)}}class Y0 extends H${static[y]="PgSelectQueryBuilder";_;config;joinsNotNullableMap;tableName;isPartialSelect;session;dialect;constructor({table:o,fields:T,isPartialSelect:n,session:f,dialect:S,withList:A,distinct:$}){super();this.config={withList:A,table:o,fields:{...T},distinct:$,setOperators:[]},this.isPartialSelect=n,this.session=f,this.dialect=S,this._={selectedFields:T},this.tableName=qT(o),this.joinsNotNullableMap=typeof this.tableName==="string"?{[this.tableName]:!0}:{}}createJoin(o){return(T,n)=>{let f=this.tableName,S=qT(T);if(typeof S==="string"&&this.config.joins?.some((A)=>A.alias===S))throw new Error(`Alias "${S}" is already used in this query`);if(!this.isPartialSelect){if(Object.keys(this.joinsNotNullableMap).length===1&&typeof f==="string")this.config.fields={[f]:this.config.fields};if(typeof S==="string"&&!X(T,j)){let A=X(T,No)?T._.selectedFields:X(T,ST)?T[Xo].selectedFields:T[I.Symbol.Columns];this.config.fields[S]=A}}if(typeof n==="function")n=n(new Proxy(this.config.fields,new Qo({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));if(!this.config.joins)this.config.joins=[];if(this.config.joins.push({on:n,table:T,joinType:o,alias:S}),typeof S==="string")switch(o){case"left":{this.joinsNotNullableMap[S]=!1;break}case"right":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([A])=>[A,!1])),this.joinsNotNullableMap[S]=!0;break}case"inner":{this.joinsNotNullableMap[S]=!0;break}case"full":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([A])=>[A,!1])),this.joinsNotNullableMap[S]=!1;break}}return this}}leftJoin=this.createJoin("left");rightJoin=this.createJoin("right");innerJoin=this.createJoin("inner");fullJoin=this.createJoin("full");createSetOperator(o,T){return(n)=>{let f=typeof n==="function"?n(iy()):n;if(!Vf(this.getSelectedFields(),f.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:o,isAll:T,rightSelect:f}),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(o){return this.config.setOperators.push(...o),this}where(o){if(typeof o==="function")o=o(new Proxy(this.config.fields,new Qo({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));return this.config.where=o,this}having(o){if(typeof o==="function")o=o(new Proxy(this.config.fields,new Qo({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));return this.config.having=o,this}groupBy(...o){if(typeof o[0]==="function"){let T=o[0](new Proxy(this.config.fields,new Qo({sqlAliasedBehavior:"alias",sqlBehavior:"sql"})));this.config.groupBy=Array.isArray(T)?T:[T]}else this.config.groupBy=o;return this}orderBy(...o){if(typeof o[0]==="function"){let T=o[0](new Proxy(this.config.fields,new Qo({sqlAliasedBehavior:"alias",sqlBehavior:"sql"}))),n=Array.isArray(T)?T:[T];if(this.config.setOperators.length>0)this.config.setOperators.at(-1).orderBy=n;else this.config.orderBy=n}else{let T=o;if(this.config.setOperators.length>0)this.config.setOperators.at(-1).orderBy=T;else this.config.orderBy=T}return this}limit(o){if(this.config.setOperators.length>0)this.config.setOperators.at(-1).limit=o;else this.config.limit=o;return this}offset(o){if(this.config.setOperators.length>0)this.config.setOperators.at(-1).offset=o;else this.config.offset=o;return this}for(o,T={}){return this.config.lockingClause={strength:o,config:T},this}getSQL(){return this.dialect.buildSelectQuery(this.config)}toSQL(){let{typings:o,...T}=this.dialect.sqlToQuery(this.getSQL());return T}as(o){return new Proxy(new No(this.getSQL(),this.config.fields,o),new Qo({alias:o,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}getSelectedFields(){return new Proxy(this.config.fields,new Qo({alias:this.tableName,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}$dynamic(){return this}}class K$ extends Y0{static[y]="PgSelect";_prepare(o){let{session:T,config:n,dialect:f,joinsNotNullableMap:S,authToken:A}=this;if(!T)throw new Error("Cannot execute a query on a query builder. Please use a database instance instead.");return Oo.startActiveSpan("drizzle.prepareQuery",()=>{let $=OT(n.fields),F=T.prepareQuery(f.sqlToQuery(this.getSQL()),$,o,!0);return F.joinsNotNullableMap=S,F.setToken(A)})}prepare(o){return this._prepare(o)}authToken;setToken(o){return this.authToken=o,this}execute=(o)=>{return Oo.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(o,this.authToken)})}}eJ(K$,[oT]);function en(o,T){return(n,f,...S)=>{let A=[f,...S].map(($)=>({type:o,isAll:T,rightSelect:$}));for(let $ of A)if(!Vf(n.getSelectedFields(),$.rightSelect.getSelectedFields()))throw new Error("Set operator error (union / intersect / except): selected fields are not the same or are in a different order");return n.addSetOperators(A)}}var iy=()=>({union:gy,unionAll:dy,intersect:ly,intersectAll:uy,except:ey,exceptAll:sy}),gy=en("union",!1),dy=en("union",!0),ly=en("intersect",!1),uy=en("intersect",!0),ey=en("except",!1),sy=en("except",!0);class xf{static[y]="PgQueryBuilder";dialect;dialectConfig;constructor(o){this.dialect=X(o,Xn)?o:void 0,this.dialectConfig=X(o,Xn)?void 0:o}$with=(o,T)=>{let n=this;return{as:(S)=>{if(typeof S==="function")S=S(n);return new Proxy(new Yf(S.getSQL(),T??("getSelectedFields"in S?S.getSelectedFields()??{}:{}),o,!0),new Qo({alias:o,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}};with(...o){let T=this;function n(A){return new TT({fields:A??void 0,session:void 0,dialect:T.getDialect(),withList:o})}function f(A){return new TT({fields:A??void 0,session:void 0,dialect:T.getDialect(),distinct:!0})}function S(A,$){return new TT({fields:$??void 0,session:void 0,dialect:T.getDialect(),distinct:{on:A}})}return{select:n,selectDistinct:f,selectDistinctOn:S}}select(o){return new TT({fields:o??void 0,session:void 0,dialect:this.getDialect()})}selectDistinct(o){return new TT({fields:o??void 0,session:void 0,dialect:this.getDialect(),distinct:!0})}selectDistinctOn(o,T){return new TT({fields:T??void 0,session:void 0,dialect:this.getDialect(),distinct:{on:o}})}getDialect(){if(!this.dialect)this.dialect=new Xn(this.dialectConfig);return this.dialect}}class ZS{constructor(o,T,n,f,S){this.table=o,this.session=T,this.dialect=n,this.withList=f,this.overridingSystemValue_=S}static[y]="PgInsertBuilder";authToken;setToken(o){return this.authToken=o,this}overridingSystemValue(){return this.overridingSystemValue_=!0,this}values(o){if(o=Array.isArray(o)?o:[o],o.length===0)throw new Error("values() must be called with at least one value");let T=o.map((n)=>{let f={},S=this.table[I.Symbol.Columns];for(let A of Object.keys(n)){let $=n[A];f[A]=X($,j)?$:new tT($,S[A])}return f});return new E$(this.table,T,this.session,this.dialect,this.withList,!1,this.overridingSystemValue_).setToken(this.authToken)}select(o){let T=typeof o==="function"?o(new xf):o;if(!X(T,j)&&!Vf(this.table[OS],T._.selectedFields))throw new Error("Insert select error: selected fields are not the same or are in a different order compared to the table definition");return new E$(this.table,T,this.session,this.dialect,this.withList,!0)}}class E$ extends oT{constructor(o,T,n,f,S,A,$){super();this.session=n,this.dialect=f,this.config={table:o,values:T,withList:S,select:A,overridingSystemValue_:$}}static[y]="PgInsert";config;returning(o=this.config.table[I.Symbol.Columns]){return this.config.returningFields=o,this.config.returning=OT(o),this}onConflictDoNothing(o={}){if(o.target===void 0)this.config.onConflict=k`do nothing`;else{let T="";T=Array.isArray(o.target)?o.target.map((f)=>this.dialect.escapeName(this.dialect.casing.getColumnCasing(f))).join(","):this.dialect.escapeName(this.dialect.casing.getColumnCasing(o.target));let n=o.where?k` where ${o.where}`:void 0;this.config.onConflict=k`(${k.raw(T)})${n} do nothing`}return this}onConflictDoUpdate(o){if(o.where&&(o.targetWhere||o.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 T=o.where?k` where ${o.where}`:void 0,n=o.targetWhere?k` where ${o.targetWhere}`:void 0,f=o.setWhere?k` where ${o.setWhere}`:void 0,S=this.dialect.buildUpdateSet(this.config.table,KS(this.config.table,o.set)),A="";return A=Array.isArray(o.target)?o.target.map(($)=>this.dialect.escapeName(this.dialect.casing.getColumnCasing($))).join(","):this.dialect.escapeName(this.dialect.casing.getColumnCasing(o.target)),this.config.onConflict=k`(${k.raw(A)})${n} do update set ${S}${T}${f}`,this}getSQL(){return this.dialect.buildInsertQuery(this.config)}toSQL(){let{typings:o,...T}=this.dialect.sqlToQuery(this.getSQL());return T}_prepare(o){return Oo.startActiveSpan("drizzle.prepareQuery",()=>{return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,o,!0)})}prepare(o){return this._prepare(o)}authToken;setToken(o){return this.authToken=o,this}execute=(o)=>{return Oo.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(o,this.authToken)})};getSelectedFields(){return this.config.returningFields?new Proxy(this.config.returningFields,new Qo({alias:vo(this.config.table),sqlAliasedBehavior:"alias",sqlBehavior:"error"})):void 0}$dynamic(){return this}}class G$ extends oT{constructor(o,T,n){super();this.session=T,this.dialect=n,this.config={view:o}}static[y]="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:o,...T}=this.dialect.sqlToQuery(this.getSQL());return T}_prepare(o){return Oo.startActiveSpan("drizzle.prepareQuery",()=>{return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),void 0,o,!0)})}prepare(o){return this._prepare(o)}authToken;setToken(o){return this.authToken=o,this}execute=(o)=>{return Oo.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(o,this.authToken)})}}class PS{constructor(o,T,n,f){this.table=o,this.session=T,this.dialect=n,this.withList=f}static[y]="PgUpdateBuilder";authToken;setToken(o){return this.authToken=o,this}set(o){return new z0(this.table,KS(this.table,o),this.session,this.dialect,this.withList).setToken(this.authToken)}}class z0 extends oT{constructor(o,T,n,f,S){super();this.session=n,this.dialect=f,this.config={set:T,table:o,withList:S,joins:[]},this.tableName=qT(o),this.joinsNotNullableMap=typeof this.tableName==="string"?{[this.tableName]:!0}:{}}static[y]="PgUpdate";config;tableName;joinsNotNullableMap;from(o){let T=o,n=qT(T);if(typeof n==="string")this.joinsNotNullableMap[n]=!0;return this.config.from=T,this}getTableLikeFields(o){if(X(o,co))return o[I.Symbol.Columns];else if(X(o,No))return o._.selectedFields;return o[Xo].selectedFields}createJoin(o){return(T,n)=>{let f=qT(T);if(typeof f==="string"&&this.config.joins.some((S)=>S.alias===f))throw new Error(`Alias "${f}" is already used in this query`);if(typeof n==="function"){let S=this.config.from&&!X(this.config.from,j)?this.getTableLikeFields(this.config.from):void 0;n=n(new Proxy(this.config.table[I.Symbol.Columns],new Qo({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})),S&&new Proxy(S,new Qo({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})))}if(this.config.joins.push({on:n,table:T,joinType:o,alias:f}),typeof f==="string")switch(o){case"left":{this.joinsNotNullableMap[f]=!1;break}case"right":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([S])=>[S,!1])),this.joinsNotNullableMap[f]=!0;break}case"inner":{this.joinsNotNullableMap[f]=!0;break}case"full":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([S])=>[S,!1])),this.joinsNotNullableMap[f]=!1;break}}return this}}leftJoin=this.createJoin("left");rightJoin=this.createJoin("right");innerJoin=this.createJoin("inner");fullJoin=this.createJoin("full");where(o){return this.config.where=o,this}returning(o){if(!o){if(o=Object.assign({},this.config.table[I.Symbol.Columns]),this.config.from){let T=qT(this.config.from);if(typeof T==="string"&&this.config.from&&!X(this.config.from,j)){let n=this.getTableLikeFields(this.config.from);o[T]=n}for(let n of this.config.joins){let f=qT(n.table);if(typeof f==="string"&&!X(n.table,j)){let S=this.getTableLikeFields(n.table);o[f]=S}}}}return this.config.returningFields=o,this.config.returning=OT(o),this}getSQL(){return this.dialect.buildUpdateQuery(this.config)}toSQL(){let{typings:o,...T}=this.dialect.sqlToQuery(this.getSQL());return T}_prepare(o){let T=this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,o,!0);return T.joinsNotNullableMap=this.joinsNotNullableMap,T}prepare(o){return this._prepare(o)}authToken;setToken(o){return this.authToken=o,this}execute=(o)=>{return this._prepare().execute(o,this.authToken)};getSelectedFields(){return this.config.returningFields?new Proxy(this.config.returningFields,new Qo({alias:vo(this.config.table),sqlAliasedBehavior:"alias",sqlBehavior:"error"})):void 0}$dynamic(){return this}}class vf extends j{constructor(o){super(vf.buildEmbeddedCount(o.source,o.filters).queryChunks);this.params=o,this.mapWith(Number),this.session=o.session,this.sql=vf.buildCount(o.source,o.filters)}sql;token;static[y]="PgCountBuilder";[Symbol.toStringTag]="PgCountBuilder";session;static buildEmbeddedCount(o,T){return k`(select count(*) from ${o}${k.raw(" where ").if(T)}${T})`}static buildCount(o,T){return k`select count(*) as count from ${o}${k.raw(" where ").if(T)}${T};`}setToken(o){return this.token=o,this}then(o,T){return Promise.resolve(this.session.count(this.sql,this.token)).then(o,T)}catch(o){return this.then(void 0,o)}finally(o){return this.then((T)=>{return o?.(),T},(T)=>{throw o?.(),T})}}class z${constructor(o,T,n,f,S,A,$){this.fullSchema=o,this.schema=T,this.tableNamesMap=n,this.table=f,this.tableConfig=S,this.dialect=A,this.session=$}static[y]="PgRelationalQueryBuilder";findMany(o){return new Y$(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,o?o:{},"many")}findFirst(o){return new Y$(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,o?{...o,limit:1}:{limit:1},"first")}}class Y$ extends oT{constructor(o,T,n,f,S,A,$,F,J){super();this.fullSchema=o,this.schema=T,this.tableNamesMap=n,this.table=f,this.tableConfig=S,this.dialect=A,this.session=$,this.config=F,this.mode=J}static[y]="PgRelationalQuery";_prepare(o){return Oo.startActiveSpan("drizzle.prepareQuery",()=>{let{query:T,builtQuery:n}=this._toSQL();return this.session.prepareQuery(n,void 0,o,!0,(f,S)=>{let A=f.map(($)=>LS(this.schema,this.tableConfig,$,T.selection,S));if(this.mode==="first")return A[0];return A})})}prepare(o){return this._prepare(o)}_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 o=this._getQuery(),T=this.dialect.sqlToQuery(o.sql);return{query:o,builtQuery:T}}toSQL(){return this._toSQL().builtQuery}authToken;setToken(o){return this.authToken=o,this}execute(){return Oo.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(void 0,this.authToken)})}}class D$ extends oT{constructor(o,T,n,f){super();this.execute=o,this.sql=T,this.query=n,this.mapBatchResult=f}static[y]="PgRaw";getSQL(){return this.sql}getQuery(){return this.query}mapResult(o,T){return T?this.mapBatchResult(o):o}_prepare(){return this}isResponseInArrayMode(){return!1}}class rf{constructor(o,T,n){if(this.dialect=o,this.session=T,this._=n?{schema:n.schema,fullSchema:n.fullSchema,tableNamesMap:n.tableNamesMap,session:T}:{schema:void 0,fullSchema:{},tableNamesMap:{},session:T},this.query={},this._.schema)for(let[f,S]of Object.entries(this._.schema))this.query[f]=new z$(n.fullSchema,this._.schema,this._.tableNamesMap,n.fullSchema[f],S,o,T)}static[y]="PgDatabase";query;$with=(o,T)=>{let n=this;return{as:(S)=>{if(typeof S==="function")S=S(new xf(n.dialect));return new Proxy(new Yf(S.getSQL(),T??("getSelectedFields"in S?S.getSelectedFields()??{}:{}),o,!0),new Qo({alias:o,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}};$count(o,T){return new vf({source:o,filters:T,session:this.session})}with(...o){let T=this;function n(J){return new TT({fields:J??void 0,session:T.session,dialect:T.dialect,withList:o})}function f(J){return new TT({fields:J??void 0,session:T.session,dialect:T.dialect,withList:o,distinct:!0})}function S(J,t){return new TT({fields:t??void 0,session:T.session,dialect:T.dialect,withList:o,distinct:{on:J}})}function A(J){return new PS(J,T.session,T.dialect,o)}function $(J){return new ZS(J,T.session,T.dialect,o)}function F(J){return new cS(J,T.session,T.dialect,o)}return{select:n,selectDistinct:f,selectDistinctOn:S,update:A,insert:$,delete:F}}select(o){return new TT({fields:o??void 0,session:this.session,dialect:this.dialect})}selectDistinct(o){return new TT({fields:o??void 0,session:this.session,dialect:this.dialect,distinct:!0})}selectDistinctOn(o,T){return new TT({fields:T??void 0,session:this.session,dialect:this.dialect,distinct:{on:o}})}update(o){return new PS(o,this.session,this.dialect)}insert(o){return new ZS(o,this.session,this.dialect)}delete(o){return new cS(o,this.session,this.dialect)}refreshMaterializedView(o){return new G$(o,this.session,this.dialect)}authToken;execute(o){let T=typeof o==="string"?k.raw(o):o.getSQL(),n=this.dialect.sqlToQuery(T),f=this.session.prepareQuery(n,void 0,void 0,!1);return new D$(()=>f.execute(void 0,this.authToken),T,n,(S)=>f.mapResult(S,!0))}transaction(o,T){return this.session.transaction(o,T)}}class D0{constructor(o,T){this.unique=o,this.name=T}static[y]="PgIndexBuilderOn";on(...o){return new iS(o.map((T)=>{if(X(T,j))return T;T=T;let n=new Gf(T.name,!!T.keyAsName,T.columnType,T.indexConfig);return T.indexConfig=JSON.parse(JSON.stringify(T.defaultConfig)),n}),this.unique,!1,this.name)}onOnly(...o){return new iS(o.map((T)=>{if(X(T,j))return T;T=T;let n=new Gf(T.name,!!T.keyAsName,T.columnType,T.indexConfig);return T.indexConfig=T.defaultConfig,n}),this.unique,!0,this.name)}using(o,...T){return new iS(T.map((n)=>{if(X(n,j))return n;n=n;let f=new Gf(n.name,!!n.keyAsName,n.columnType,n.indexConfig);return n.indexConfig=JSON.parse(JSON.stringify(n.defaultConfig)),f}),this.unique,!0,this.name,o)}}class iS{static[y]="PgIndexBuilder";config;constructor(o,T,n,f,S="btree"){this.config={name:f,columns:o,unique:T,only:n,method:S}}concurrently(){return this.config.concurrently=!0,this}with(o){return this.config.with=o,this}where(o){return this.config.where=o,this}build(o){return new Q0(this.config,o)}}class Q0{static[y]="PgIndex";config;constructor(o,T){this.config={...o,table:T}}}function Q$(o){return new D0(!0,o)}class U${constructor(o){this.query=o}authToken;getQuery(){return this.query}mapResult(o,T){return o}setToken(o){return this.authToken=o,this}static[y]="PgPreparedQuery";joinsNotNullableMap}class V${constructor(o){this.dialect=o}static[y]="PgSession";execute(o,T){return Oo.startActiveSpan("drizzle.operation",()=>{return Oo.startActiveSpan("drizzle.prepareQuery",()=>{return this.prepareQuery(this.dialect.sqlToQuery(o),void 0,void 0,!1)}).setToken(T).execute(void 0,T)})}all(o){return this.prepareQuery(this.dialect.sqlToQuery(o),void 0,void 0,!1).all()}async count(o,T){let n=await this.execute(o,T);return Number(n[0].count)}}class B$ extends rf{constructor(o,T,n,f=0){super(o,T,n);this.schema=n,this.nestedIndex=f}static[y]="PgTransaction";rollback(){throw new dA}getTransactionConfigSQL(o){let T=[];if(o.isolationLevel)T.push(`isolation level ${o.isolationLevel}`);if(o.accessMode)T.push(o.accessMode);if(typeof o.deferrable==="boolean")T.push(o.deferrable?"deferrable":"not deferrable");return k.raw(T.join(" "))}setTransaction(o){return this.session.execute(k`set transaction ${this.getTransactionConfigSQL(o)}`)}}class U0 extends U${constructor(o,T,n,f,S,A,$){super({sql:T,params:n});this.client=o,this.queryString=T,this.params=n,this.logger=f,this.fields=S,this._isResponseInArrayMode=A,this.customResultMapper=$}static[y]="PostgresJsPreparedQuery";async execute(o={}){return Oo.startActiveSpan("drizzle.execute",async(T)=>{let n=iA(this.params,o);T?.setAttributes({"drizzle.query.text":this.queryString,"drizzle.query.params":JSON.stringify(n)}),this.logger.logQuery(this.queryString,n);let{fields:f,queryString:S,client:A,joinsNotNullableMap:$,customResultMapper:F}=this;if(!f&&!F)return Oo.startActiveSpan("drizzle.driver.execute",()=>{return A.unsafe(S,n)});let J=await Oo.startActiveSpan("drizzle.driver.execute",()=>{return T?.setAttributes({"drizzle.query.text":S,"drizzle.query.params":JSON.stringify(n)}),A.unsafe(S,n).values()});return Oo.startActiveSpan("drizzle.mapResponse",()=>{return F?F(J):J.map((t)=>uJ(f,t,$))})})}all(o={}){return Oo.startActiveSpan("drizzle.execute",async(T)=>{let n=iA(this.params,o);return T?.setAttributes({"drizzle.query.text":this.queryString,"drizzle.query.params":JSON.stringify(n)}),this.logger.logQuery(this.queryString,n),Oo.startActiveSpan("drizzle.driver.execute",()=>{return T?.setAttributes({"drizzle.query.text":this.queryString,"drizzle.query.params":JSON.stringify(n)}),this.client.unsafe(this.queryString,n)})})}isResponseInArrayMode(){return this._isResponseInArrayMode}}class qf extends V${constructor(o,T,n,f={}){super(T);this.client=o,this.schema=n,this.options=f,this.logger=f.logger??new uA}static[y]="PostgresJsSession";logger;prepareQuery(o,T,n,f,S){return new U0(this.client,o.sql,o.params,this.logger,T,f,S)}query(o,T){return this.logger.logQuery(o,T),this.client.unsafe(o,T).values()}queryObjects(o,T){return this.client.unsafe(o,T)}transaction(o,T){return this.client.begin(async(n)=>{let f=new qf(n,this.dialect,this.schema,this.options),S=new m$(this.dialect,f,this.schema);if(T)await S.setTransaction(T);return o(S)})}}class m$ extends B${constructor(o,T,n,f=0){super(o,T,n,f);this.session=T}static[y]="PostgresJsTransaction";transaction(o){return this.session.client.savepoint((T)=>{let n=new qf(T,this.dialect,this.schema,this.session.options),f=new m$(this.dialect,n,this.schema);return o(f)})}}class V0 extends rf{static[y]="PostgresJsDatabase"}function sn(o,T={}){let n=(J)=>J;for(let J of["1184","1082","1083","1114","1182","1185","1115","1231"])o.options.parsers[J]=n,o.options.serializers[J]=n;o.options.serializers["114"]=n,o.options.serializers["3802"]=n;let f=new Xn({casing:T.casing}),S;if(T.logger===!0)S=new lA;else if(T.logger!==!1)S=T.logger;let A;if(T.schema){let J=o0(T.schema,n0);A={fullSchema:T.schema,schema:J.tables,tableNamesMap:J.tableNamesMap}}let $=new qf(o,f,A,{logger:S}),F=new V0(f,$,A);return F.$client=o,F}function gS(...o){if(typeof o[0]==="string"){let T=un(o[0]);return sn(T,o[1])}if(aJ(o[0])){let{connection:T,client:n,...f}=o[0];if(n)return sn(n,f);if(typeof T==="object"&&T.url!==void 0){let{url:A,...$}=T,F=un(A,$);return sn(F,f)}let S=un(T);return sn(S,f)}return sn(o[0],o[1])}((o)=>{function T(n){return sn({options:{parsers:{},serializers:{}}},n)}o.mock=T})(gS||(gS={}));var C$={};IM(C$,{users:()=>Hn,userChanges:()=>ok,untrackedUserColumnNames:()=>ay,twoFactorMethod:()=>I0,trackedUserColumnName:()=>C0,trackableUserColumnNames:()=>L0,role:()=>m0,players:()=>L$,passwordResetAttempts:()=>nk,loginHistory:()=>Tk,games:()=>dS,banishedIps:()=>fk});function B0(o){return k`lower(${o})`}var m0=kS("role",["admin","user"]),Hn=aT("users",{id:RT().primaryKey().defaultRandom(),username:po({length:16}).notNull(),email:po({length:254}).notNull(),hash:po({length:64}).notNull(),salt:po({length:36}).notNull(),createdAt:DT({withTimezone:!0}).notNull().defaultNow(),createdIp:po({length:45}).notNull(),isActive:Bf().notNull().default(!1),verifiedAt:DT({withTimezone:!0}),userRole:m0().default("user")},(o)=>[Q$("usernameUniqueIndex").on(B0(o.username)),Q$("emailUniqueIndex").on(B0(o.email))]),ay=["id","createdAt","createdIp","isActive","salt","verifiedAt"],L0=["username","email","hash","userRole"],C0=kS("trackedUserColumnName",L0),ok=aT("userChanges",{id:RT().primaryKey().defaultRandom(),userId:RT().notNull().references(()=>Hn.id),changedAt:DT({withTimezone:!0}).notNull().defaultNow(),changedIp:po({length:45}).notNull(),changedColumn:C0().notNull(),oldValue:po({length:255}),newValue:po({length:255})}),dS=aT("games",{id:RT().primaryKey().defaultRandom()}),L$=aT("players",{userId:RT().notNull().references(()=>Hn.id),gameId:RT().notNull().references(()=>dS.id),score:YS().notNull()},(o)=>[lR({name:"players_userId_gameId_pk",columns:[o.userId,o.gameId]})]),Tk=aT("loginHistory",{id:RT().primaryKey().defaultRandom(),userId:RT().references(()=>Hn.id),loginTime:DT({withTimezone:!0}).notNull().defaultNow(),ipAddress:po({length:45}).notNull(),userAgent:po({length:1024}),successful:Bf().notNull().default(!1)}),I0=kS("twoFactorMethod",["email","phone"]),nk=aT("passwordResetAttempts",{id:RT().primaryKey().defaultRandom(),userId:RT().notNull().references(()=>Hn.id),requestedIp:po({length:45}).notNull(),requestedAt:DT({withTimezone:!0}).notNull().defaultNow(),succeededIp:po({length:45}),succeededAt:DT({withTimezone:!0}),verificationMethod:I0().notNull()}),fk=aT("banishedIps",{ip:po({length:45}).primaryKey(),reason:po({length:2048}).notNull(),banishedAt:DT({withTimezone:!0}).notNull().defaultNow(),banishedUntil:DT({withTimezone:!0})});var __dirname="/home/runner/work/wayforge/wayforge/apps/tempest.games/src/database";class I${options;sql;drizzle;observers=new Map;async setupTriggersAndNotifications(){await this.sql.file(Sk.resolve(__dirname,"notify_update.sql"));let o=[vo(Hn),vo(dS),vo(L$)];await this.sql`SELECT create_notify_triggers(${this.sql.array(o)})`,await this.sql.listen("table_update",(T)=>{let n=T.split(","),f=n[0],S=n[1],A=`${f}("${S}")`;if(this.observers.has(A))this.observers.get(A).next(A)})}constructor(o=!1,T={host:YT.POSTGRES_HOST,port:YT.POSTGRES_PORT,user:YT.POSTGRES_USER,password:YT.POSTGRES_PASSWORD,database:YT.POSTGRES_DATABASE}){this.options=T,this.sql=un(T),this.drizzle=gS(this.sql,{schema:C$,logger:o})}observe(o,T){if(!this.observers.has(o))this.observers.set(o,new oo);this.observers.get(o).subscribe("SINGLETON",T)}}var lS={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"},j$=g$(lS).map(([o])=>Eo.literal(Number(o))),Ak=Eo.union([j$[0],j$[1],...j$]),j0=Eo.tuple([Ak,Eo.string()]);var N$=new QA,{logger:$T}=N$;Object.assign(console,$T,{log:$T.info});$T.info("ready");var h$=N0(import.meta.dir,"..","app"),Mz=new I$({logQuery(o,T){$T.info("\uD83D\uDCDD query",o,T)}});Jk({hostname:"0.0.0.0",port:YT.FRONTEND_PORT??3333,...MJ??void 0,async fetch(o){try{let T=new Date,n=new URL(o.url);if($T.info(o.method,n.pathname),n.pathname==="/")return new Response(Bun.file(N0(h$,"index.html")));if(n.pathname==="/index.html")return Response.redirect("/");let f=$k(h$,n.pathname),S=Fk(f);if(!S.startsWith(h$))throw[403,"Access Denied"];if(!await h0(S).exists())return Response.redirect("/");return new Response(h0(S))}catch(T){let n=j0.safeParse(T);if(n.success){let[f,S]=n.data,$=`${lS[f]}. ${S}`;return $T.info(`\u274C ${f}: ${$}`),new Response($,{status:f})}if(T instanceof Error)$T.error(T.message);else{let f=Un(T);$T.error("frontend server threw",f)}return new Response(lS[500],{status:500})}}});function uS(){$T.info("\uD83D\uDEEC frontend server exiting"),process.exit(0)}process.on("SIGINT",()=>{$T.info("\u2757 received SIGINT; exiting gracefully"),uS()});process.on("SIGTERM",()=>{$T.info("\u2757 received SIGTERM; exiting gracefully"),uS()});process.on("exit",()=>{$T.info("\u2757 received exit; exiting gracefully"),uS()});N$.on("timeToStop",()=>{$T.info('\u2757 backend server received signal "timeToStop"; exiting gracefully'),uS()});$T.info(`\uD83D\uDEEB frontend server running at http://localhost:${YT.FRONTEND_PORT}/`);N$.emit("alive");
|
|
81
|
+
`;await o.execute(X`CREATE SCHEMA IF NOT EXISTS ${X.identifier(F)}`),await o.execute(f);let $=(await o.all(X`select id, hash, created_at from ${X.identifier(F)}.${X.identifier(A)} order by created_at desc limit 1`))[0];await o.transaction(async(_)=>{for await(let J of T)if(!$||Number($.created_at)<J.folderMillis){for(let R of J.sql)await _.execute(X.raw(R));await _.execute(X`insert into ${X.identifier(F)}.${X.identifier(A)} ("hash", "created_at") values(${J.hash}, ${J.folderMillis})`)}})}escapeName(T){return`"${T}"`}escapeParam(T){return`$${T+1}`}escapeString(T){return`'${T.replace(/'/g,"''")}'`}buildWithCTE(T){if(!T?.length)return;let o=[X`with `];for(let[y,A]of T.entries())if(o.push(X`${X.identifier(A._.alias)} as (${A._.sql})`),y<T.length-1)o.push(X`, `);return o.push(X` `),X.join(o)}buildDeleteQuery({table:T,where:o,returning:y,withList:A}){let F=this.buildWithCTE(A),f=y?X` returning ${this.buildSelection(y,{isSingleTable:!0})}`:void 0,S=o?X` where ${o}`:void 0;return X`${F}delete from ${T}${S}${f}`}buildUpdateSet(T,o){let y=T[b.Symbol.Columns],A=Object.keys(y).filter((f)=>o[f]!==void 0||y[f]?.onUpdateFn!==void 0),F=A.length;return X.join(A.flatMap((f,S)=>{let $=y[f],_=o[f]??X.param($.onUpdateFn(),$),J=X`${X.identifier(this.casing.getColumnCasing($))} = ${_}`;if(S<F-1)return[J,X.raw(", ")];return[J]}))}buildUpdateQuery({table:T,set:o,where:y,returning:A,withList:F,from:f,joins:S}){let $=this.buildWithCTE(F),_=T[To.Symbol.Name],J=T[To.Symbol.Schema],R=T[To.Symbol.OriginalName],M=_===R?void 0:_,Y=X`${J?X`${X.identifier(J)}.`:void 0}${X.identifier(R)}${M&&X` ${X.identifier(M)}`}`,H=this.buildUpdateSet(T,o),Q=f&&X.join([X.raw(" from "),this.buildFromTable(f)]),w=this.buildJoins(S),B=A?X` returning ${this.buildSelection(A,{isSingleTable:!f})}`:void 0,t=y?X` where ${y}`:void 0;return X`${$}update ${Y} set ${H}${Q}${w}${t}${B}`}buildSelection(T,{isSingleTable:o=!1}={}){let y=T.length,A=T.flatMap(({field:F},f)=>{let S=[];if(G(F,x.Aliased)&&F.isSelectionField)S.push(X.identifier(F.fieldAlias));else if(G(F,x.Aliased)||G(F,x)){let $=G(F,x.Aliased)?F.sql:F;if(o)S.push(new x($.queryChunks.map((_)=>{if(G(_,I))return X.identifier(this.casing.getColumnCasing(_));return _})));else S.push($);if(G(F,x.Aliased))S.push(X` as ${X.identifier(F.fieldAlias)}`)}else if(G(F,GT))if(o)S.push(X.identifier(this.casing.getColumnCasing(F)));else S.push(F);if(f<y-1)S.push(X`, `);return S});return X.join(A)}buildJoins(T){if(!T||T.length===0)return;let o=[];for(let[y,A]of T.entries()){if(y===0)o.push(X` `);let F=A.table,f=A.lateral?X` lateral`:void 0;if(G(F,To)){let S=F[To.Symbol.Name],$=F[To.Symbol.Schema],_=F[To.Symbol.OriginalName],J=S===_?void 0:A.alias;o.push(X`${X.raw(A.joinType)} join${f} ${$?X`${X.identifier($)}.`:void 0}${X.identifier(_)}${J&&X` ${X.identifier(J)}`} on ${A.on}`)}else if(G(F,Uo)){let S=F[VT].name,$=F[VT].schema,_=F[VT].originalName,J=S===_?void 0:A.alias;o.push(X`${X.raw(A.joinType)} join${f} ${$?X`${X.identifier($)}.`:void 0}${X.identifier(_)}${J&&X` ${X.identifier(J)}`} on ${A.on}`)}else o.push(X`${X.raw(A.joinType)} join${f} ${F} on ${A.on}`);if(y<T.length-1)o.push(X` `)}return X.join(o)}buildFromTable(T){if(G(T,b)&&T[b.Symbol.IsAlias]){let o=X`${X.identifier(T[b.Symbol.OriginalName])}`;if(T[b.Symbol.Schema])o=X`${X.identifier(T[b.Symbol.Schema])}.${o}`;return X`${o} ${X.identifier(T[b.Symbol.Name])}`}return T}buildSelectQuery({withList:T,fields:o,fieldsFlat:y,where:A,having:F,table:f,joins:S,orderBy:$,groupBy:_,limit:J,offset:R,lockingClause:M,distinct:Y,setOperators:H}){let Q=y??jo(o);for(let e of Q)if(G(e.field,GT)&&lT(e.field.table)!==(G(f,cT)?f._.alias:G(f,vF)?f[VT].name:G(f,x)?void 0:lT(f))&&!((HT)=>S?.some(({alias:qT})=>qT===(HT[b.Symbol.IsAlias]?lT(HT):HT[b.Symbol.BaseName])))(e.field.table)){let HT=lT(e.field.table);throw new Error(`Your "${e.path.join("->")}" field references a column "${HT}"."${e.field.name}", but the table "${HT}" is not part of the query! Did you forget to join it?`)}let w=!S||S.length===0,B=this.buildWithCTE(T),t;if(Y)t=Y===!0?X` distinct`:X` distinct on (${X.join(Y.on,X`, `)})`;let m=this.buildSelection(Q,{isSingleTable:w}),h=this.buildFromTable(f),K=this.buildJoins(S),V=A?X` where ${A}`:void 0,L=F?X` having ${F}`:void 0,C;if($&&$.length>0)C=X` order by ${X.join($,X`, `)}`;let v;if(_&&_.length>0)v=X` group by ${X.join(_,X`, `)}`;let s=typeof J==="object"||typeof J==="number"&&J>=0?X` limit ${J}`:void 0,z=R?X` offset ${R}`:void 0,a=X.empty();if(M){let e=X` for ${X.raw(M.strength)}`;if(M.config.of)e.append(X` of ${X.join(Array.isArray(M.config.of)?M.config.of:[M.config.of],X`, `)}`);if(M.config.noWait)e.append(X` no wait`);else if(M.config.skipLocked)e.append(X` skip locked`);a.append(e)}let P=X`${B}select${t} ${m} from ${h}${K}${V}${v}${L}${C}${s}${z}${a}`;if(H.length>0)return this.buildSetOperations(P,H);return P}buildSetOperations(T,o){let[y,...A]=o;if(!y)throw new Error("Cannot pass undefined values to any set operator");if(A.length===0)return this.buildSetOperationQuery({leftSelect:T,setOperator:y});return this.buildSetOperations(this.buildSetOperationQuery({leftSelect:T,setOperator:y}),A)}buildSetOperationQuery({leftSelect:T,setOperator:{type:o,isAll:y,rightSelect:A,limit:F,orderBy:f,offset:S}}){let $=X`(${T.getSQL()}) `,_=X`(${A.getSQL()})`,J;if(f&&f.length>0){let H=[];for(let Q of f)if(G(Q,I))H.push(X.identifier(Q.name));else if(G(Q,x)){for(let w=0;w<Q.queryChunks.length;w++){let B=Q.queryChunks[w];if(G(B,I))Q.queryChunks[w]=X.identifier(B.name)}H.push(X`${Q}`)}else H.push(X`${Q}`);J=X` order by ${X.join(H,X`, `)} `}let R=typeof F==="object"||typeof F==="number"&&F>=0?X` limit ${F}`:void 0,M=X.raw(`${o} ${y?"all ":""}`),Y=S?X` offset ${S}`:void 0;return X`${$}${M}${_}${J}${R}${Y}`}buildInsertQuery({table:T,values:o,onConflict:y,returning:A,withList:F,select:f,overridingSystemValue_:S}){let $=[],_=T[b.Symbol.Columns],J=Object.entries(_).filter(([B,t])=>!t.shouldDisableInsert()),R=J.map(([,B])=>X.identifier(this.casing.getColumnCasing(B)));if(f){let B=o;if(G(B,x))$.push(B);else $.push(B.getSQL())}else{let B=o;$.push(X.raw("values "));for(let[t,m]of B.entries()){let h=[];for(let[K,V]of J){let L=m[K];if(L===void 0||G(L,Co)&&L.value===void 0)if(V.defaultFn!==void 0){let C=V.defaultFn(),v=G(C,x)?C:X.param(C,V);h.push(v)}else if(!V.default&&V.onUpdateFn!==void 0){let C=V.onUpdateFn(),v=G(C,x)?C:X.param(C,V);h.push(v)}else h.push(X`default`);else h.push(L)}if($.push(h),t<B.length-1)$.push(X`, `)}}let M=this.buildWithCTE(F),Y=X.join($),H=A?X` returning ${this.buildSelection(A,{isSingleTable:!0})}`:void 0,Q=y?X` on conflict ${y}`:void 0,w=S===!0?X`overriding system value `:void 0;return X`${M}insert into ${T} ${R} ${w}${Y}${Q}${H}`}buildRefreshMaterializedViewQuery({view:T,concurrently:o,withNoData:y}){let A=o?X` concurrently`:void 0,F=y?X` with no data`:void 0;return X`refresh materialized view${A} ${T}${F}`}prepareTyping(T){if(G(T,ef)||G(T,af))return"json";else if(G(T,TS))return"decimal";else if(G(T,oS))return"time";else if(G(T,yS)||G(T,AS))return"timestamp";else if(G(T,rf)||G(T,lf))return"date";else if(G(T,FS))return"uuid";else return"none"}sqlToQuery(T,o){return T.toQuery({casing:this.casing,escapeName:this.escapeName,escapeParam:this.escapeParam,escapeString:this.escapeString,prepareTyping:this.prepareTyping,invokeSource:o})}buildRelationalQueryWithoutPK({fullSchema:T,schema:o,tableNamesMap:y,table:A,tableConfig:F,queryConfig:f,tableAlias:S,nestedQueryRelation:$,joinOn:_}){let J=[],R,M,Y=[],H,Q=[];if(f===!0)J=Object.entries(F.columns).map(([t,m])=>({dbKey:m.name,tsKey:t,field:oy(m,S),relationTableTsKey:void 0,isJson:!1,selection:[]}));else{let B=Object.fromEntries(Object.entries(F.columns).map(([L,C])=>[L,oy(C,S)]));if(f.where){let L=typeof f.where==="function"?f.where(B,I2()):f.where;H=L&&IF(L,S)}let t=[],m=[];if(f.columns){let L=!1;for(let[C,v]of Object.entries(f.columns)){if(v===void 0)continue;if(C in F.columns){if(!L&&v===!0)L=!0;m.push(C)}}if(m.length>0)m=L?m.filter((C)=>f.columns?.[C]===!0):Object.keys(F.columns).filter((C)=>!m.includes(C))}else m=Object.keys(F.columns);for(let L of m){let C=F.columns[L];t.push({tsKey:L,value:C})}let h=[];if(f.with)h=Object.entries(f.with).filter((L)=>!!L[1]).map(([L,C])=>({tsKey:L,queryConfig:C,relation:F.relations[L]}));let K;if(f.extras){K=typeof f.extras==="function"?f.extras(B,{sql:X}):f.extras;for(let[L,C]of Object.entries(K))t.push({tsKey:L,value:NJ(C,S)})}for(let{tsKey:L,value:C}of t)J.push({dbKey:G(C,x.Aliased)?C.fieldAlias:F.columns[L].name,tsKey:L,field:G(C,GT)?oy(C,S):C,relationTableTsKey:void 0,isJson:!1,selection:[]});let V=typeof f.orderBy==="function"?f.orderBy(B,k2()):f.orderBy??[];if(!Array.isArray(V))V=[V];Y=V.map((L)=>{if(G(L,GT))return oy(L,S);return IF(L,S)}),R=f.limit,M=f.offset;for(let{tsKey:L,queryConfig:C,relation:v}of h){let s=N2(o,y,v),z=cy(v.referencedTable),a=y[z],P=`${S}_${L}`,e=kF(...s.fields.map((Xo,Ay)=>cf(oy(s.references[Ay],P),oy(Xo,S)))),HT=this.buildRelationalQueryWithoutPK({fullSchema:T,schema:o,tableNamesMap:y,table:T[a],tableConfig:o[a],queryConfig:G(v,by)?C===!0?{limit:1}:{...C,limit:1}:C,tableAlias:P,joinOn:e,nestedQueryRelation:v}),qT=X`${X.identifier(P)}.${X.identifier("data")}`.as(L);Q.push({on:X`true`,table:new cT(HT.sql,{},P),alias:P,joinType:"left",lateral:!0}),J.push({dbKey:L,tsKey:L,field:qT,relationTableTsKey:a,isJson:!0,selection:HT.selection})}}if(J.length===0)throw new uf({message:`No fields selected for table "${F.tsName}" ("${S}")`});let w;if(H=kF(_,H),$){let B=X`json_build_array(${X.join(J.map(({field:h,tsKey:K,isJson:V})=>V?X`${X.identifier(`${S}_${K}`)}.${X.identifier("data")}`:G(h,x.Aliased)?h.sql:h),X`, `)})`;if(G($,pF))B=X`coalesce(json_agg(${B}${Y.length>0?X` order by ${X.join(Y,X`, `)}`:void 0}), '[]'::json)`;let t=[{dbKey:"data",tsKey:"data",field:B.as("data"),isJson:!0,relationTableTsKey:F.tsName,selection:J}];if(R!==void 0||M!==void 0||Y.length>0)w=this.buildSelectQuery({table:gf(A,S),fields:{},fieldsFlat:[{path:[],field:X.raw("*")}],where:H,limit:R,offset:M,orderBy:Y,setOperators:[]}),H=void 0,R=void 0,M=void 0,Y=[];else w=gf(A,S);w=this.buildSelectQuery({table:G(w,To)?w:new cT(w,{},S),fields:{},fieldsFlat:t.map(({field:h})=>({path:[],field:G(h,GT)?oy(h,S):h})),joins:Q,where:H,limit:R,offset:M,orderBy:Y,setOperators:[]})}else w=this.buildSelectQuery({table:gf(A,S),fields:{},fieldsFlat:J.map(({field:B})=>({path:[],field:G(B,GT)?oy(B,S):B})),joins:Q,where:H,limit:R,offset:M,orderBy:Y,setOperators:[]});return{tableTsKey:F.tsName,sql:w,selection:J}}}class F0{static[O]="TypedQueryBuilder";getSelectedFields(){return this._.selectedFields}}class Mo{static[O]="PgSelectBuilder";fields;session;dialect;withList=[];distinct;constructor(T){if(this.fields=T.fields,this.session=T.session,this.dialect=T.dialect,T.withList)this.withList=T.withList;this.distinct=T.distinct}authToken;setToken(T){return this.authToken=T,this}from(T){let o=!!this.fields,y=T,A;if(this.fields)A=this.fields;else if(G(y,cT))A=Object.fromEntries(Object.keys(y._.selectedFields).map((F)=>[F,y[F]]));else if(G(y,vF))A=y[VT].selectedFields;else if(G(y,x))A={};else A=IO(y);return new f0({table:y,fields:A,isPartialSelect:o,session:this.session,dialect:this.dialect,withList:this.withList,distinct:this.distinct}).setToken(this.authToken)}}class T4 extends F0{static[O]="PgSelectQueryBuilder";_;config;joinsNotNullableMap;tableName;isPartialSelect;session;dialect;constructor({table:T,fields:o,isPartialSelect:y,session:A,dialect:F,withList:f,distinct:S}){super();this.config={withList:f,table:T,fields:{...o},distinct:S,setOperators:[]},this.isPartialSelect=y,this.session=A,this.dialect=F,this._={selectedFields:o},this.tableName=Ey(T),this.joinsNotNullableMap=typeof this.tableName==="string"?{[this.tableName]:!0}:{}}createJoin(T){return(o,y)=>{let A=this.tableName,F=Ey(o);if(typeof F==="string"&&this.config.joins?.some((f)=>f.alias===F))throw new Error(`Alias "${F}" is already used in this query`);if(!this.isPartialSelect){if(Object.keys(this.joinsNotNullableMap).length===1&&typeof A==="string")this.config.fields={[A]:this.config.fields};if(typeof F==="string"&&!G(o,x)){let f=G(o,cT)?o._.selectedFields:G(o,Uo)?o[VT].selectedFields:o[b.Symbol.Columns];this.config.fields[F]=f}}if(typeof y==="function")y=y(new Proxy(this.config.fields,new tT({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));if(!this.config.joins)this.config.joins=[];if(this.config.joins.push({on:y,table:o,joinType:T,alias:F}),typeof F==="string")switch(T){case"left":{this.joinsNotNullableMap[F]=!1;break}case"right":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([f])=>[f,!1])),this.joinsNotNullableMap[F]=!0;break}case"inner":{this.joinsNotNullableMap[F]=!0;break}case"full":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([f])=>[f,!1])),this.joinsNotNullableMap[F]=!1;break}}return this}}leftJoin=this.createJoin("left");rightJoin=this.createJoin("right");innerJoin=this.createJoin("inner");fullJoin=this.createJoin("full");createSetOperator(T,o){return(y)=>{let A=typeof y==="function"?y(F5()):y;if(!BF(this.getSelectedFields(),A.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:T,isAll:o,rightSelect:A}),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(T){return this.config.setOperators.push(...T),this}where(T){if(typeof T==="function")T=T(new Proxy(this.config.fields,new tT({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));return this.config.where=T,this}having(T){if(typeof T==="function")T=T(new Proxy(this.config.fields,new tT({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));return this.config.having=T,this}groupBy(...T){if(typeof T[0]==="function"){let o=T[0](new Proxy(this.config.fields,new tT({sqlAliasedBehavior:"alias",sqlBehavior:"sql"})));this.config.groupBy=Array.isArray(o)?o:[o]}else this.config.groupBy=T;return this}orderBy(...T){if(typeof T[0]==="function"){let o=T[0](new Proxy(this.config.fields,new tT({sqlAliasedBehavior:"alias",sqlBehavior:"sql"}))),y=Array.isArray(o)?o:[o];if(this.config.setOperators.length>0)this.config.setOperators.at(-1).orderBy=y;else this.config.orderBy=y}else{let o=T;if(this.config.setOperators.length>0)this.config.setOperators.at(-1).orderBy=o;else this.config.orderBy=o}return this}limit(T){if(this.config.setOperators.length>0)this.config.setOperators.at(-1).limit=T;else this.config.limit=T;return this}offset(T){if(this.config.setOperators.length>0)this.config.setOperators.at(-1).offset=T;else this.config.offset=T;return this}for(T,o={}){return this.config.lockingClause={strength:T,config:o},this}getSQL(){return this.dialect.buildSelectQuery(this.config)}toSQL(){let{typings:T,...o}=this.dialect.sqlToQuery(this.getSQL());return o}as(T){return new Proxy(new cT(this.getSQL(),this.config.fields,T),new tT({alias:T,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}getSelectedFields(){return new Proxy(this.config.fields,new tT({alias:this.tableName,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}$dynamic(){return this}}class f0 extends T4{static[O]="PgSelect";_prepare(T){let{session:o,config:y,dialect:A,joinsNotNullableMap:F,authToken:f}=this;if(!o)throw new Error("Cannot execute a query on a query builder. Please use a database instance instead.");return wT.startActiveSpan("drizzle.prepareQuery",()=>{let S=jo(y.fields),$=o.prepareQuery(A.sqlToQuery(this.getSQL()),S,T,!0);return $.joinsNotNullableMap=F,$.setToken(f)})}prepare(T){return this._prepare(T)}authToken;setToken(T){return this.authToken=T,this}execute=(T)=>{return wT.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(T,this.authToken)})}}LO(f0,[Oo]);function pA(T,o){return(y,A,...F)=>{let f=[A,...F].map((S)=>({type:T,isAll:o,rightSelect:S}));for(let S of f)if(!BF(y.getSelectedFields(),S.rightSelect.getSelectedFields()))throw new Error("Set operator error (union / intersect / except): selected fields are not the same or are in a different order");return y.addSetOperators(f)}}var F5=()=>({union:f5,unionAll:S5,intersect:$5,intersectAll:J5,except:_5,exceptAll:R5}),f5=pA("union",!1),S5=pA("union",!0),$5=pA("intersect",!1),J5=pA("intersect",!0),_5=pA("except",!1),R5=pA("except",!0);class PF{static[O]="PgQueryBuilder";dialect;dialectConfig;constructor(T){this.dialect=G(T,ay)?T:void 0,this.dialectConfig=G(T,ay)?void 0:T}$with=(T,o)=>{let y=this;return{as:(F)=>{if(typeof F==="function")F=F(y);return new Proxy(new DF(F.getSQL(),o??("getSelectedFields"in F?F.getSelectedFields()??{}:{}),T,!0),new tT({alias:T,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}};with(...T){let o=this;function y(f){return new Mo({fields:f??void 0,session:void 0,dialect:o.getDialect(),withList:T})}function A(f){return new Mo({fields:f??void 0,session:void 0,dialect:o.getDialect(),distinct:!0})}function F(f,S){return new Mo({fields:S??void 0,session:void 0,dialect:o.getDialect(),distinct:{on:f}})}return{select:y,selectDistinct:A,selectDistinctOn:F}}select(T){return new Mo({fields:T??void 0,session:void 0,dialect:this.getDialect()})}selectDistinct(T){return new Mo({fields:T??void 0,session:void 0,dialect:this.getDialect(),distinct:!0})}selectDistinctOn(T,o){return new Mo({fields:o??void 0,session:void 0,dialect:this.getDialect(),distinct:{on:T}})}getDialect(){if(!this.dialect)this.dialect=new ay(this.dialectConfig);return this.dialect}}class ES{constructor(T,o,y,A,F){this.table=T,this.session=o,this.dialect=y,this.withList=A,this.overridingSystemValue_=F}static[O]="PgInsertBuilder";authToken;setToken(T){return this.authToken=T,this}overridingSystemValue(){return this.overridingSystemValue_=!0,this}values(T){if(T=Array.isArray(T)?T:[T],T.length===0)throw new Error("values() must be called with at least one value");let o=T.map((y)=>{let A={},F=this.table[b.Symbol.Columns];for(let f of Object.keys(y)){let S=y[f];A[f]=G(S,x)?S:new Co(S,F[f])}return A});return new S0(this.table,o,this.session,this.dialect,this.withList,!1,this.overridingSystemValue_).setToken(this.authToken)}select(T){let o=typeof T==="function"?T(new PF):T;if(!G(o,x)&&!BF(this.table[hf],o._.selectedFields))throw new Error("Insert select error: selected fields are not the same or are in a different order compared to the table definition");return new S0(this.table,o,this.session,this.dialect,this.withList,!0)}}class S0 extends Oo{constructor(T,o,y,A,F,f,S){super();this.session=y,this.dialect=A,this.config={table:T,values:o,withList:F,select:f,overridingSystemValue_:S}}static[O]="PgInsert";config;returning(T=this.config.table[b.Symbol.Columns]){return this.config.returningFields=T,this.config.returning=jo(T),this}onConflictDoNothing(T={}){if(T.target===void 0)this.config.onConflict=X`do nothing`;else{let o="";o=Array.isArray(T.target)?T.target.map((A)=>this.dialect.escapeName(this.dialect.casing.getColumnCasing(A))).join(","):this.dialect.escapeName(this.dialect.casing.getColumnCasing(T.target));let y=T.where?X` where ${T.where}`:void 0;this.config.onConflict=X`(${X.raw(o)})${y} do nothing`}return this}onConflictDoUpdate(T){if(T.where&&(T.targetWhere||T.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 o=T.where?X` where ${T.where}`:void 0,y=T.targetWhere?X` where ${T.targetWhere}`:void 0,A=T.setWhere?X` where ${T.setWhere}`:void 0,F=this.dialect.buildUpdateSet(this.config.table,df(this.config.table,T.set)),f="";return f=Array.isArray(T.target)?T.target.map((S)=>this.dialect.escapeName(this.dialect.casing.getColumnCasing(S))).join(","):this.dialect.escapeName(this.dialect.casing.getColumnCasing(T.target)),this.config.onConflict=X`(${X.raw(f)})${y} do update set ${F}${o}${A}`,this}getSQL(){return this.dialect.buildInsertQuery(this.config)}toSQL(){let{typings:T,...o}=this.dialect.sqlToQuery(this.getSQL());return o}_prepare(T){return wT.startActiveSpan("drizzle.prepareQuery",()=>{return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,T,!0)})}prepare(T){return this._prepare(T)}authToken;setToken(T){return this.authToken=T,this}execute=(T)=>{return wT.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(T,this.authToken)})};getSelectedFields(){return this.config.returningFields?new Proxy(this.config.returningFields,new tT({alias:lT(this.config.table),sqlAliasedBehavior:"alias",sqlBehavior:"error"})):void 0}$dynamic(){return this}}class $0 extends Oo{constructor(T,o,y){super();this.session=o,this.dialect=y,this.config={view:T}}static[O]="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:T,...o}=this.dialect.sqlToQuery(this.getSQL());return o}_prepare(T){return wT.startActiveSpan("drizzle.prepareQuery",()=>{return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),void 0,T,!0)})}prepare(T){return this._prepare(T)}authToken;setToken(T){return this.authToken=T,this}execute=(T)=>{return wT.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(T,this.authToken)})}}class GS{constructor(T,o,y,A){this.table=T,this.session=o,this.dialect=y,this.withList=A}static[O]="PgUpdateBuilder";authToken;setToken(T){return this.authToken=T,this}set(T){return new o4(this.table,df(this.table,T),this.session,this.dialect,this.withList).setToken(this.authToken)}}class o4 extends Oo{constructor(T,o,y,A,F){super();this.session=y,this.dialect=A,this.config={set:o,table:T,withList:F,joins:[]},this.tableName=Ey(T),this.joinsNotNullableMap=typeof this.tableName==="string"?{[this.tableName]:!0}:{}}static[O]="PgUpdate";config;tableName;joinsNotNullableMap;from(T){let o=T,y=Ey(o);if(typeof y==="string")this.joinsNotNullableMap[y]=!0;return this.config.from=o,this}getTableLikeFields(T){if(G(T,To))return T[b.Symbol.Columns];else if(G(T,cT))return T._.selectedFields;return T[VT].selectedFields}createJoin(T){return(o,y)=>{let A=Ey(o);if(typeof A==="string"&&this.config.joins.some((F)=>F.alias===A))throw new Error(`Alias "${A}" is already used in this query`);if(typeof y==="function"){let F=this.config.from&&!G(this.config.from,x)?this.getTableLikeFields(this.config.from):void 0;y=y(new Proxy(this.config.table[b.Symbol.Columns],new tT({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})),F&&new Proxy(F,new tT({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})))}if(this.config.joins.push({on:y,table:o,joinType:T,alias:A}),typeof A==="string")switch(T){case"left":{this.joinsNotNullableMap[A]=!1;break}case"right":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([F])=>[F,!1])),this.joinsNotNullableMap[A]=!0;break}case"inner":{this.joinsNotNullableMap[A]=!0;break}case"full":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([F])=>[F,!1])),this.joinsNotNullableMap[A]=!1;break}}return this}}leftJoin=this.createJoin("left");rightJoin=this.createJoin("right");innerJoin=this.createJoin("inner");fullJoin=this.createJoin("full");where(T){return this.config.where=T,this}returning(T){if(!T){if(T=Object.assign({},this.config.table[b.Symbol.Columns]),this.config.from){let o=Ey(this.config.from);if(typeof o==="string"&&this.config.from&&!G(this.config.from,x)){let y=this.getTableLikeFields(this.config.from);T[o]=y}for(let y of this.config.joins){let A=Ey(y.table);if(typeof A==="string"&&!G(y.table,x)){let F=this.getTableLikeFields(y.table);T[A]=F}}}}return this.config.returningFields=T,this.config.returning=jo(T),this}getSQL(){return this.dialect.buildUpdateQuery(this.config)}toSQL(){let{typings:T,...o}=this.dialect.sqlToQuery(this.getSQL());return o}_prepare(T){let o=this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,T,!0);return o.joinsNotNullableMap=this.joinsNotNullableMap,o}prepare(T){return this._prepare(T)}authToken;setToken(T){return this.authToken=T,this}execute=(T)=>{return this._prepare().execute(T,this.authToken)};getSelectedFields(){return this.config.returningFields?new Proxy(this.config.returningFields,new tT({alias:lT(this.config.table),sqlAliasedBehavior:"alias",sqlBehavior:"error"})):void 0}$dynamic(){return this}}class hF extends x{constructor(T){super(hF.buildEmbeddedCount(T.source,T.filters).queryChunks);this.params=T,this.mapWith(Number),this.session=T.session,this.sql=hF.buildCount(T.source,T.filters)}sql;token;static[O]="PgCountBuilder";[Symbol.toStringTag]="PgCountBuilder";session;static buildEmbeddedCount(T,o){return X`(select count(*) from ${T}${X.raw(" where ").if(o)}${o})`}static buildCount(T,o){return X`select count(*) as count from ${T}${X.raw(" where ").if(o)}${o};`}setToken(T){return this.token=T,this}then(T,o){return Promise.resolve(this.session.count(this.sql,this.token)).then(T,o)}catch(T){return this.then(void 0,T)}finally(T){return this.then((o)=>{return T?.(),o},(o)=>{throw T?.(),o})}}class _0{constructor(T,o,y,A,F,f,S){this.fullSchema=T,this.schema=o,this.tableNamesMap=y,this.table=A,this.tableConfig=F,this.dialect=f,this.session=S}static[O]="PgRelationalQueryBuilder";findMany(T){return new J0(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,T?T:{},"many")}findFirst(T){return new J0(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,T?{...T,limit:1}:{limit:1},"first")}}class J0 extends Oo{constructor(T,o,y,A,F,f,S,$,_){super();this.fullSchema=T,this.schema=o,this.tableNamesMap=y,this.table=A,this.tableConfig=F,this.dialect=f,this.session=S,this.config=$,this.mode=_}static[O]="PgRelationalQuery";_prepare(T){return wT.startActiveSpan("drizzle.prepareQuery",()=>{let{query:o,builtQuery:y}=this._toSQL();return this.session.prepareQuery(y,void 0,T,!0,(A,F)=>{let f=A.map((S)=>fS(this.schema,this.tableConfig,S,o.selection,F));if(this.mode==="first")return f[0];return f})})}prepare(T){return this._prepare(T)}_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 T=this._getQuery(),o=this.dialect.sqlToQuery(T.sql);return{query:T,builtQuery:o}}toSQL(){return this._toSQL().builtQuery}authToken;setToken(T){return this.authToken=T,this}execute(){return wT.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(void 0,this.authToken)})}}class R0 extends Oo{constructor(T,o,y,A){super();this.execute=T,this.sql=o,this.query=y,this.mapBatchResult=A}static[O]="PgRaw";getSQL(){return this.sql}getQuery(){return this.query}mapResult(T,o){return o?this.mapBatchResult(T):T}_prepare(){return this}isResponseInArrayMode(){return!1}}class nF{constructor(T,o,y){if(this.dialect=T,this.session=o,this._=y?{schema:y.schema,fullSchema:y.fullSchema,tableNamesMap:y.tableNamesMap,session:o}:{schema:void 0,fullSchema:{},tableNamesMap:{},session:o},this.query={},this._.schema)for(let[A,F]of Object.entries(this._.schema))this.query[A]=new _0(y.fullSchema,this._.schema,this._.tableNamesMap,y.fullSchema[A],F,T,o)}static[O]="PgDatabase";query;$with=(T,o)=>{let y=this;return{as:(F)=>{if(typeof F==="function")F=F(new PF(y.dialect));return new Proxy(new DF(F.getSQL(),o??("getSelectedFields"in F?F.getSelectedFields()??{}:{}),T,!0),new tT({alias:T,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}};$count(T,o){return new hF({source:T,filters:o,session:this.session})}with(...T){let o=this;function y(_){return new Mo({fields:_??void 0,session:o.session,dialect:o.dialect,withList:T})}function A(_){return new Mo({fields:_??void 0,session:o.session,dialect:o.dialect,withList:T,distinct:!0})}function F(_,J){return new Mo({fields:J??void 0,session:o.session,dialect:o.dialect,withList:T,distinct:{on:_}})}function f(_){return new GS(_,o.session,o.dialect,T)}function S(_){return new ES(_,o.session,o.dialect,T)}function $(_){return new HS(_,o.session,o.dialect,T)}return{select:y,selectDistinct:A,selectDistinctOn:F,update:f,insert:S,delete:$}}select(T){return new Mo({fields:T??void 0,session:this.session,dialect:this.dialect})}selectDistinct(T){return new Mo({fields:T??void 0,session:this.session,dialect:this.dialect,distinct:!0})}selectDistinctOn(T,o){return new Mo({fields:o??void 0,session:this.session,dialect:this.dialect,distinct:{on:T}})}update(T){return new GS(T,this.session,this.dialect)}insert(T){return new ES(T,this.session,this.dialect)}delete(T){return new HS(T,this.session,this.dialect)}refreshMaterializedView(T){return new $0(T,this.session,this.dialect)}authToken;execute(T){let o=typeof T==="string"?X.raw(T):T.getSQL(),y=this.dialect.sqlToQuery(o),A=this.session.prepareQuery(y,void 0,void 0,!1);return new R0(()=>A.execute(void 0,this.authToken),o,y,(F)=>A.mapResult(F,!0))}transaction(T,o){return this.session.transaction(T,o)}}class y4{constructor(T,o){this.unique=T,this.name=o}static[O]="PgIndexBuilderOn";on(...T){return new wS(T.map((o)=>{if(G(o,x))return o;o=o;let y=new VF(o.name,!!o.keyAsName,o.columnType,o.indexConfig);return o.indexConfig=JSON.parse(JSON.stringify(o.defaultConfig)),y}),this.unique,!1,this.name)}onOnly(...T){return new wS(T.map((o)=>{if(G(o,x))return o;o=o;let y=new VF(o.name,!!o.keyAsName,o.columnType,o.indexConfig);return o.indexConfig=o.defaultConfig,y}),this.unique,!0,this.name)}using(T,...o){return new wS(o.map((y)=>{if(G(y,x))return y;y=y;let A=new VF(y.name,!!y.keyAsName,y.columnType,y.indexConfig);return y.indexConfig=JSON.parse(JSON.stringify(y.defaultConfig)),A}),this.unique,!0,this.name,T)}}class wS{static[O]="PgIndexBuilder";config;constructor(T,o,y,A,F="btree"){this.config={name:A,columns:T,unique:o,only:y,method:F}}concurrently(){return this.config.concurrently=!0,this}with(T){return this.config.with=T,this}where(T){return this.config.where=T,this}build(T){return new A4(this.config,T)}}class A4{static[O]="PgIndex";config;constructor(T,o){this.config={...T,table:o}}}function W0(T){return new y4(!0,T)}class O0{constructor(T){this.query=T}authToken;getQuery(){return this.query}mapResult(T,o){return T}setToken(T){return this.authToken=T,this}static[O]="PgPreparedQuery";joinsNotNullableMap}class M0{constructor(T){this.dialect=T}static[O]="PgSession";execute(T,o){return wT.startActiveSpan("drizzle.operation",()=>{return wT.startActiveSpan("drizzle.prepareQuery",()=>{return this.prepareQuery(this.dialect.sqlToQuery(T),void 0,void 0,!1)}).setToken(o).execute(void 0,o)})}all(T){return this.prepareQuery(this.dialect.sqlToQuery(T),void 0,void 0,!1).all()}async count(T,o){let y=await this.execute(T,o);return Number(y[0].count)}}class X0 extends nF{constructor(T,o,y,A=0){super(T,o,y);this.schema=y,this.nestedIndex=A}static[O]="PgTransaction";rollback(){throw new tJ}getTransactionConfigSQL(T){let o=[];if(T.isolationLevel)o.push(`isolation level ${T.isolationLevel}`);if(T.accessMode)o.push(T.accessMode);if(typeof T.deferrable==="boolean")o.push(T.deferrable?"deferrable":"not deferrable");return X.raw(o.join(" "))}setTransaction(T){return this.session.execute(X`set transaction ${this.getTransactionConfigSQL(T)}`)}}class F4 extends O0{constructor(T,o,y,A,F,f,S){super({sql:o,params:y});this.client=T,this.queryString=o,this.params=y,this.logger=A,this.fields=F,this._isResponseInArrayMode=f,this.customResultMapper=S}static[O]="PostgresJsPreparedQuery";async execute(T={}){return wT.startActiveSpan("drizzle.execute",async(o)=>{let y=BJ(this.params,T);o?.setAttributes({"drizzle.query.text":this.queryString,"drizzle.query.params":JSON.stringify(y)}),this.logger.logQuery(this.queryString,y);let{fields:A,queryString:F,client:f,joinsNotNullableMap:S,customResultMapper:$}=this;if(!A&&!$)return wT.startActiveSpan("drizzle.driver.execute",()=>{return f.unsafe(F,y)});let _=await wT.startActiveSpan("drizzle.driver.execute",()=>{return o?.setAttributes({"drizzle.query.text":F,"drizzle.query.params":JSON.stringify(y)}),f.unsafe(F,y).values()});return wT.startActiveSpan("drizzle.mapResponse",()=>{return $?$(_):_.map((J)=>CO(A,J,S))})})}all(T={}){return wT.startActiveSpan("drizzle.execute",async(o)=>{let y=BJ(this.params,T);return o?.setAttributes({"drizzle.query.text":this.queryString,"drizzle.query.params":JSON.stringify(y)}),this.logger.logQuery(this.queryString,y),wT.startActiveSpan("drizzle.driver.execute",()=>{return o?.setAttributes({"drizzle.query.text":this.queryString,"drizzle.query.params":JSON.stringify(y)}),this.client.unsafe(this.queryString,y)})})}isResponseInArrayMode(){return this._isResponseInArrayMode}}class gF extends M0{constructor(T,o,y,A={}){super(o);this.client=T,this.schema=y,this.options=A,this.logger=A.logger??new bJ}static[O]="PostgresJsSession";logger;prepareQuery(T,o,y,A,F){return new F4(this.client,T.sql,T.params,this.logger,o,A,F)}query(T,o){return this.logger.logQuery(T,o),this.client.unsafe(T,o).values()}queryObjects(T,o){return this.client.unsafe(T,o)}transaction(T,o){return this.client.begin(async(y)=>{let A=new gF(y,this.dialect,this.schema,this.options),F=new Y0(this.dialect,A,this.schema);if(o)await F.setTransaction(o);return T(F)})}}class Y0 extends X0{constructor(T,o,y,A=0){super(T,o,y,A);this.session=o}static[O]="PostgresJsTransaction";transaction(T){return this.session.client.savepoint((o)=>{let y=new gF(o,this.dialect,this.schema,this.session.options),A=new Y0(this.dialect,y,this.schema);return T(A)})}}class f4 extends nF{static[O]="PostgresJsDatabase"}function bA(T,o={}){let y=(_)=>_;for(let _ of["1184","1082","1083","1114","1182","1185","1115","1231"])T.options.parsers[_]=y,T.options.serializers[_]=y;T.options.serializers["114"]=y,T.options.serializers["3802"]=y;let A=new ay({casing:o.casing}),F;if(o.logger===!0)F=new pJ;else if(o.logger!==!1)F=o.logger;let f;if(o.schema){let _=B2(o.schema,t2);f={fullSchema:o.schema,schema:_.tables,tableNamesMap:_.tableNamesMap}}let S=new gF(T,A,f,{logger:F}),$=new f4(A,S,f);return $.$client=T,$}function US(...T){if(typeof T[0]==="string"){let o=tA(T[0]);return bA(o,T[1])}if(kO(T[0])){let{connection:o,client:y,...A}=T[0];if(y)return bA(y,A);if(typeof o==="object"&&o.url!==void 0){let{url:f,...S}=o,$=tA(f,S);return bA($,A)}let F=tA(o);return bA(F,A)}return bA(T[0],T[1])}((T)=>{function o(y){return bA({options:{parsers:{},serializers:{}}},y)}T.mock=o})(US||(US={}));var H0={};RX(H0,{users:()=>ey,userChanges:()=>O5,untrackedUserColumnNames:()=>W5,twoFactorMethod:()=>R4,trackedUserColumnName:()=>_4,trackableUserColumnNames:()=>J4,role:()=>$4,players:()=>Z0,passwordResetAttempts:()=>X5,loginHistory:()=>M5,games:()=>KS,banishedIps:()=>Y5});function S4(T){return X`lower(${T})`}var $4=vf("role",["admin","user"]),ey=py("users",{id:Lo().primaryKey().defaultRandom(),username:eT({length:16}).notNull(),email:eT({length:254}).notNull(),hash:eT({length:64}).notNull(),salt:eT({length:36}).notNull(),createdAt:co({withTimezone:!0}).notNull().defaultNow(),createdIp:eT({length:45}).notNull(),isActive:NF().notNull().default(!1),verifiedAt:co({withTimezone:!0}),userRole:$4().default("user")},(T)=>[W0("usernameUniqueIndex").on(S4(T.username)),W0("emailUniqueIndex").on(S4(T.email))]),W5=["id","createdAt","createdIp","isActive","salt","verifiedAt"],J4=["username","email","hash","userRole"],_4=vf("trackedUserColumnName",J4),O5=py("userChanges",{id:Lo().primaryKey().defaultRandom(),userId:Lo().notNull().references(()=>ey.id),changedAt:co({withTimezone:!0}).notNull().defaultNow(),changedIp:eT({length:45}).notNull(),changedColumn:_4().notNull(),oldValue:eT({length:255}),newValue:eT({length:255})}),KS=py("games",{id:Lo().primaryKey().defaultRandom()}),Z0=py("players",{userId:Lo().notNull().references(()=>ey.id),gameId:Lo().notNull().references(()=>KS.id),score:sf().notNull()},(T)=>[D2({name:"players_userId_gameId_pk",columns:[T.userId,T.gameId]})]),M5=py("loginHistory",{id:Lo().primaryKey().defaultRandom(),userId:Lo().references(()=>ey.id),loginTime:co({withTimezone:!0}).notNull().defaultNow(),ipAddress:eT({length:45}).notNull(),userAgent:eT({length:1024}),successful:NF().notNull().default(!1)}),R4=vf("twoFactorMethod",["email","phone"]),X5=py("passwordResetAttempts",{id:Lo().primaryKey().defaultRandom(),userId:Lo().notNull().references(()=>ey.id),requestedIp:eT({length:45}).notNull(),requestedAt:co({withTimezone:!0}).notNull().defaultNow(),succeededIp:eT({length:45}),succeededAt:co({withTimezone:!0}),verificationMethod:R4().notNull()}),Y5=py("banishedIps",{ip:eT({length:45}).primaryKey(),reason:eT({length:2048}).notNull(),banishedAt:co({withTimezone:!0}).notNull().defaultNow(),banishedUntil:co({withTimezone:!0})});var __dirname="/home/runner/work/wayforge/wayforge/apps/tempest.games/src/database";class E0{options;sql;drizzle;observers=new Map;async setupTriggersAndNotifications(){await this.sql.file(Z5.resolve(__dirname,"notify_update.sql"));let T=[lT(ey),lT(KS),lT(Z0)];await this.sql`SELECT create_notify_triggers(${this.sql.array(T)})`,await this.sql.listen("table_update",(o)=>{let y=o.split(","),A=y[0],F=y[1],f=`${A}("${F}")`;if(this.observers.has(f))this.observers.get(f).next(f)})}constructor(T=!1,o={host:uo.POSTGRES_HOST,port:uo.POSTGRES_PORT,user:uo.POSTGRES_USER,password:uo.POSTGRES_PASSWORD,database:uo.POSTGRES_DATABASE}){this.options=o,this.sql=tA(o),this.drizzle=US(this.sql,{schema:H0,logger:T})}observe(T,o){if(!this.observers.has(T))this.observers.set(T,new oT);this.observers.get(T).subscribe("SINGLETON",o)}}var zS={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"'};function H5(T){return Number.parseInt(T,10)}var E5=po(zS),G5=E5.keyof().pipe((T)=>H5(T)),W4=po([G5,"string"]);var w0=new ZJ,{logger:zo}=w0;Object.assign(console,zo,{log:zo.info});zo.info("ready");var G0=M4(import.meta.dir,"..","app"),fn=new E0({logQuery(T,o){zo.info("\uD83D\uDCDD query",T,o)}});K5({hostname:"0.0.0.0",port:uo.FRONTEND_PORT??3333,...hW??void 0,async fetch(T){try{let o=new Date,y=new URL(T.url);if(zo.info(T.method,y.pathname),y.pathname==="/")return new Response(Bun.file(M4(G0,"index.html")));if(y.pathname==="/index.html")return Response.redirect("/");let A=w5(G0,y.pathname),F=U5(A);if(!F.startsWith(G0))throw[403,"Access Denied"];if(!await O4(F).exists())return Response.redirect("/");return new Response(O4(F))}catch(o){let y=W4(o);if(y instanceof po.errors===!1){let[A,F]=y,S=`${zS[A]}. ${F}`;return zo.info(`\u274C ${A}: ${S}`),new Response(S,{status:A})}if(o instanceof Error)zo.error(o.message);else{let A=DA(o);zo.error("frontend server threw",A)}return new Response(zS[500],{status:500})}}});function QS(){zo.info("\uD83D\uDEEC frontend server exiting"),process.exit(0)}process.on("SIGINT",()=>{zo.info("\u2757 received SIGINT; exiting gracefully"),QS()});process.on("SIGTERM",()=>{zo.info("\u2757 received SIGTERM; exiting gracefully"),QS()});process.on("exit",()=>{zo.info("\u2757 received exit; exiting gracefully"),QS()});w0.on("timeToStop",()=>{zo.info('\u2757 backend server received signal "timeToStop"; exiting gracefully'),QS()});zo.info(`\uD83D\uDEEB frontend server running at http://localhost:${uo.FRONTEND_PORT}/`);w0.emit("alive");
|