tempest.games 0.1.45 → 0.1.46
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 +9 -0
- package/app/assets/index-BAZ8dbVE.js +106 -0
- package/app/index.html +1 -1
- package/bin/backend.bun.js +53 -47
- package/bin/backend.worker.tribunal.bun.js +64 -58
- package/bin/frontend.bun.js +41 -35
- package/bin/setup-db.bun.js +654 -398
- package/package.json +21 -21
- package/app/assets/index-CiuqjTCl.js +0 -100
package/bin/frontend.bun.js
CHANGED
|
@@ -1,68 +1,74 @@
|
|
|
1
1
|
#!/usr/bin/env bun
|
|
2
2
|
// @bun
|
|
3
|
-
var
|
|
4
|
-
Message: ${
|
|
3
|
+
var MX=Object.create;var{getPrototypeOf:OX,defineProperty:If,getOwnPropertyNames:XX}=Object;var YX=Object.prototype.hasOwnProperty;var p5=(T,o,F)=>{F=T!=null?MX(OX(T)):{};let A=o||!T||!T.__esModule?If(F,"default",{value:T,enumerable:!0}):F;for(let y of XX(T))if(!YX.call(A,y))If(A,y,{get:()=>T[y],enumerable:!0});return A};var j5=(T,o)=>()=>(o||T((o={exports:{}}).exports,o),o.exports);var ZX=(T,o)=>{for(var F in o)If(T,F,{get:o[F],enumerable:!0,configurable:!0,set:(A)=>o[F]=()=>A})};var x5=import.meta.require;import{join as k5,normalize as B5,resolve as w4}from"path";var KF=(T)=>Array.isArray(T)?T:[T],p_=(T,o)=>{let F=[[],[]];for(let A of T)if(o(A))F[0].push(A);else F[1].push(A);return F},ry=Array,yF=(T,o)=>T.includes(o),j_=(T,o=0)=>[...new Array(T)].map((F,A)=>A+o),yT=(T,o,F)=>{if(T===void 0)return o===void 0?[]:Array.isArray(o)?o:[o];if(F?.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},SF=(T,o)=>{if(o===void 0||o===null)return T??[];if(T===void 0||T===null)return KF(o);return T.concat(o)},x_=(...T)=>T.reduce(SF,[]),so=(T,o,F)=>{if(T===void 0)return Array.isArray(o)?o:[o];let A=F?.isEqual??((y,S)=>y===S);for(let y of KF(o))if(!T.some((S)=>A(S,y)))T.push(y);return T},b_=(T,o)=>T.reduce((F,A)=>{let y=A[o];return F[y]=yT(F[y],A),F},{}),fF=(T,o,F)=>T.length===o.length&&T.every(F?.isEqual?(A,y)=>F.isEqual(A,o[y]):(A,y)=>A===o[y]);var Yo=(T,o)=>tT(T)===o,tT=(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"},q_={...Zo,function:"a function"};class v_ extends Error{}var $T=(T)=>qF(T,v_),qF=(T,o=Error)=>{throw new o(T)};class tA extends Error{name="ParseError"}var G=(T)=>qF(T,tA),to=(T)=>` ${T}`;var d=(T,o)=>{let F={},A=Array.isArray(T),y=!1;for(let[S,f]of Object.entries(T).entries()){let $=A?o(S,f[1]):o(...f,S);y||=typeof $[0]==="number";let _=Array.isArray($[0])||$.length===0?$:[$];for(let[J,R]of _)if(typeof J==="object")F[J.group]=yT(F[J.group],R);else F[J]=R}return y?Object.values(F):F};var kf=Object.entries;var hT=(T,o)=>(T in o),yA=(T,o)=>(o in T);class Bf{constructor(T){Object.assign(this,T)}}var P_=class{};class hA extends P_{}var HX=(T,o)=>{let F={},A={},y;for(y in T)if(y in o)F[y]=T[y];else A[y]=T[y];return[F,A]};var m_=(T,o)=>HX(T,o)[1],ao=(T)=>Object.keys(T).length===0,vF=(T)=>[...Object.entries(T),...Object.getOwnPropertySymbols(T).map((o)=>[o,T[o]])],t_=(T,o)=>Object.defineProperties(T,Object.getOwnPropertyDescriptors(o)),h_=(T)=>{let o=Object.keys(T).sort(),F={};for(let A=0;A<o.length;A++)F[o[A]]=T[o[A]];return F};var Qo=to("represents an uninitialized value"),g_=(T)=>Object.values(T).filter((o)=>{if(typeof o==="number")return!0;return typeof T[o]!=="number"});var Nf={Array,Boolean,Date,Error,Function,Map,Number,Promise,RegExp,Set,String,WeakMap,WeakSet},pf=globalThis.File??Blob,jf={ArrayBuffer,Blob,File:pf,FormData,Headers,Request,Response,URL},GX={Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array},PF={...Nf,...jf,...GX,String,Number,Boolean},gA=(T)=>{let o=Object.getPrototypeOf(T);while(o?.constructor&&(!hT(o.constructor.name,PF)||!(T instanceof PF[o.constructor.name])))o=Object.getPrototypeOf(o);let F=o?.constructor?.name;if(F===void 0||F==="Object")return;return F},nA=(T)=>typeof T==="object"&&T!==null?gA(T)??"object":tT(T);var HT=Array.isArray,wX={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"},EX={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"},KX={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"},n_={...wX,...EX,...KX},uA=(T)=>{let o=Object(T).name??null;return o&&hT(o,PF)&&PF[o]===T?o:null};var xf=(T,o)=>{let F=T.prototype;while(F!==null){if(F===o.prototype)return!0;F=Object.getPrototypeOf(F)}return!1};var u_=(T)=>c_(T,new Map),c_=(T,o)=>{if(typeof T!=="object"||T===null)return T;if(o?.has(T))return o.get(T);let F=uA(T.constructor);if(F==="Date")return new Date(T.getTime());if(F&&F!=="Array")return T;let A=Array.isArray(T)?T.slice():Object.create(Object.getPrototypeOf(T)),y=Object.getOwnPropertyDescriptors(T);if(o){o.set(T,A);for(let S in y){let f=y[S];if("get"in f||"set"in f)continue;f.value=c_(f.value,o)}}return Object.defineProperties(A,y),A};var UX=(T)=>{let o=Qo;return()=>o===Qo?o=T():o},UF=(T)=>typeof T==="function"&&T.length===0;var i_=class extends Function{constructor(...T){let o=T.slice(0,-1),F=T.at(-1);try{super(...o,F)}catch(A){return $T(`Encountered an unexpected error while compiling your definition:
|
|
4
|
+
Message: ${A}
|
|
5
5
|
Source: (${T.slice(0,-1)}) => {
|
|
6
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
|
|
8
|
-
`)[2]?.trim()||"").match(/\(?(.+?)(?::\d+:\d+)?\)?$/)?.[1]||"unknown").replace(/^file:\/\//,"")}catch{return"unknown"}},
|
|
7
|
+
}`)}}};class ho{constructor(T,...[o]){return Object.assign(Object.setPrototypeOf(T.bind(o?.bind??this),this.constructor.prototype),o?.attach)}}var d_=UX(()=>{try{return new Function("return false")()}catch{return!0}});var FH=to("brand");var r_=to("arkInferred");var SH=to("args");class yo{constructor(){}}var zX=()=>{try{return((new Error().stack?.split(`
|
|
8
|
+
`)[2]?.trim()||"").match(/\(?(.+?)(?::\d+:\d+)?\)?$/)?.[1]||"unknown").replace(/^file:\/\//,"")}catch{return"unknown"}},QX=globalThis.process?.env??{},l_={fileName:zX,env:QX};var s_=(T)=>T[0].toUpperCase()+T.slice(1);var bf=(T)=>new RegExp(VX(T),typeof T==="string"?"":T.flags);var VX=(T)=>{return`^(?:${typeof T==="string"?T:T.source})$`};var $F={negativeLookahead:(T)=>`(?!${T})`,nonCapturingGroup:(T)=>`(?:${T})`},cA="\\",zF={" ":1,"\n":1,"\t":1};var DX=/^-0\.?0*$/.source,e_=/[1-9]\d*/.source,LX=/\.\d+/.source,CX=/\.\d*[1-9]/.source,T0=(T)=>bf($F.negativeLookahead(DX)+$F.nonCapturingGroup("-?"+$F.nonCapturingGroup($F.nonCapturingGroup("0|"+e_)+$F.nonCapturingGroup(T.decimalPattern)+"?")+(T.allowDecimalOnly?"|"+T.decimalPattern:"")+"?")),a_=T0({decimalPattern:CX,allowDecimalOnly:!1}),IX=a_.test.bind(a_),ly=T0({decimalPattern:LX,allowDecimalOnly:!0}),MH=ly.test.bind(ly),kX=/^-?\d*\.?\d*$/,BX=(T)=>T.length!==0&&kX.test(T),iA=bf($F.negativeLookahead("^-0$")+"-?"+$F.nonCapturingGroup($F.nonCapturingGroup("0|"+e_))),NX=iA.test.bind(iA),qf=/^-?\d+$/,pX=qf.test.bind(qf),o0={number:"a number",bigint:"a bigint",integer:"an integer"},F0=(T,o)=>`'${T}' was parsed as ${o0[o]} but could not be narrowed to a literal value. Avoid unnecessary leading or trailing zeros and other abnormal notation`,jX=(T,o)=>o==="number"?IX(T):NX(T),xX=(T,o)=>o==="number"?Number(T):Number.parseInt(T),bX=(T,o)=>o==="number"?BX(T):pX(T),A0=(T,o)=>vf(T,"number",o),y0=(T,o)=>vf(T,"number",{...o,strict:!0}),S0=(T,o)=>vf(T,"integer",o),vf=(T,o,F)=>{let A=xX(T,o);if(!Number.isNaN(A)){if(bX(T,o)){if(F?.strict)return jX(T,o)?A:G(F0(T,o));return A}}return F?.errorOnFail?G(F?.errorOnFail===!0?`Failed to parse ${o0[o]} from '${T}'`:F?.errorOnFail):void 0},f0=(T)=>{if(T[T.length-1]!=="n")return;let o=T.slice(0,-1),F;try{F=BigInt(o)}catch{return}if(iA.test(o))return F;if(qf.test(o))return G(F0(T,"bigint"))};var qX="0.46.0",vX={version:qX,filename:l_.fileName(),FileConstructor:pf},mF=vX,$0=new Map,Pf=Object.create(null),dA=(T)=>{let o=$0.get(T);if(o)return o;let F=PX(T);if(Pf[F])F=`${F}${Pf[F]++}`;else Pf[F]=1;return mF[F]=T,$0.set(T,F),F},QF=(T)=>/^[$A-Z_a-z][\w$]*$/.test(T),PX=(T)=>{switch(typeof T){case"object":{if(T===null)break;let o=gA(T)??"object";return o[0].toLowerCase()+o.slice(1)}case"function":return QF(T.name)?T.name:"fn";case"symbol":return T.description&&QF(T.description)?T.description:"symbol"}return $T(`Unexpected attempt to register serializable value of type ${tT(T)}`)};var rA=(T)=>typeof T==="string"?JSON.stringify(T):typeof T==="bigint"?`${T}n`:`${T}`;var J0=(T,o={})=>lA(T,{onUndefined:"$ark.undefined",onBigInt:(F)=>`$ark.bigint-${F}`,...o},[]);var r=(T,o)=>{switch(tT(T)){case"object":let F=T,A=F.constructor.name;return A==="Object"||A==="Array"?o?.quoteKeys===!1?sy(F,o?.indent??0,""):JSON.stringify(lA(F,SA,[]),null,o?.indent):sy(F,o?.indent??0,"");case"symbol":return SA.onSymbol(T);default:return rA(T)}},sy=(T,o,F)=>{if(typeof T==="function")return SA.onFunction(T);if(typeof T!=="object"||T===null)return rA(T);let A=F+" ".repeat(o);if(Array.isArray(T)){if(T.length===0)return"[]";let S=T.map((f)=>sy(f,o,A)).join(`,
|
|
9
|
+
`+A);return o?`[
|
|
10
|
+
${A}${S}
|
|
11
|
+
${F}]`:`[${S}]`}let y=T.constructor.name;if(y==="Object"){let S=vF(T).map(([f,$])=>{let _=typeof f==="symbol"?SA.onSymbol(f):QF(f)?f:JSON.stringify(f),J=sy($,o,A);return`${A}${_}: ${J}`});if(S.length===0)return"{}";return o?`{
|
|
12
|
+
${S.join(`,
|
|
13
|
+
`)}
|
|
14
|
+
${F}}`:`{${S.join(", ")}}`}if(T instanceof Date)return tF(T);if("expression"in T&&typeof T.expression==="string")return T.expression;return y},SA={onCycle:()=>"(cycle)",onSymbol:(T)=>`Symbol(${dA(T)})`,onFunction:(T)=>`Function(${dA(T)})`},lA=(T,o,F)=>{switch(tT(T)){case"object":{let A=T;if("toJSON"in A&&typeof A.toJSON==="function")return A.toJSON();if(typeof A==="function")return SA.onFunction(A);if(F.includes(A))return"(cycle)";let y=[...F,A];if(Array.isArray(A))return A.map((f)=>lA(f,o,y));if(A instanceof Date)return A.toDateString();let S={};for(let f in A)S[f]=lA(A[f],o,y);for(let f of Object.getOwnPropertySymbols(A))S[o.onSymbol?.(f)??f.toString()]=lA(A[f],o,y);return S}case"symbol":return SA.onSymbol(T);case"bigint":return o.onBigInt?.(T)??`${T}n`;case"undefined":return o.onUndefined??"undefined";case"string":return T.replaceAll("\\","\\\\");default:return T}},tF=(T)=>{let o=T.getFullYear(),F=T.getMonth(),A=T.getDate(),y=T.getHours(),S=T.getMinutes(),f=T.getSeconds(),$=T.getMilliseconds();if(F===0&&A===1&&y===0&&S===0&&f===0&&$===0)return`${o}`;let _=`${mX[F]} ${A}, ${o}`;if(y===0&&S===0&&f===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+=`.${hX($,3)}`;else if(tX.test(J))J=J.slice(0,-3);return`${J+R}, ${_}`},mX=["January","February","March","April","May","June","July","August","September","October","November","December"],tX=/:\d\d:00$/,hX=(T,o)=>String(T).padStart(o,"0");var _0=(T,o,...[F])=>{let A=F?.stringifySymbol??r,y=T;switch(typeof o){case"string":y=QF(o)?T===""?o:`${T}.${o}`:`${T}[${JSON.stringify(o)}]`;break;case"number":y=`${T}[${o}]`;break;case"symbol":y=`${T}[${A(o)}]`;break;default:if(F?.stringifyNonKey)y=`${T}[${F.stringifyNonKey(o)}]`;else G(`${r(o)} must be a PropertyKey or stringifyNonKey must be passed to options`)}return y},JF=(T,...o)=>T.reduce((F,A)=>_0(F,A,...o),"");class sA extends ry{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"?r(this[T]):this[T]);return this.cache.json}stringify(){if(this.cache.stringify)return this.cache.stringify;return this.cache.stringify=JF(this)}stringifyAncestors(){if(this.cache.stringifyAncestors)return this.cache.stringifyAncestors;let T="",o=[T];for(let F of this)T=_0(T,F),o.push(T);return this.cache.stringifyAncestors=o}}class mf{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]===cA)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 zF))}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 qH=to("implementedTraits");var tf="$ark",gX=2;while(tf in globalThis)tf=`$ark${gX++}`;var R0=tf;globalThis[R0]=mF;var K=mF,nX=(T)=>`${R0}.${T}`,BT=(T)=>nX(dA(T));class ay extends hA{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 hf(T,o)}index(T,o=!1){return W0(`${T}`,o)}line(T){return this.body+=`${" ".repeat(this.indentation)}${T}
|
|
9
15
|
`,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,F=0){return this.block(`for (let i = ${F}; ${T}; i++)`,o)}forIn(T,o){return this.block(`for (const k in ${T})`,o)}block(T,o,F=""){return this.line(`${T} {`),this.indent(),o(this),this.dedent(),this.line(`}${F}`)}return(T=""){return this.line(`return ${T}`)}write(T="anonymous",o=0){return`${T}(${this.argNames.join(", ")}) { ${o?this.body.split(`
|
|
10
16
|
`).map((F)=>" ".repeat(o)+`${F}`).join(`
|
|
11
|
-
`):this.body} }`}compile(){return new
|
|
12
|
-
`)}_add(T){let o=this.byPath[T.propString];if(o){if(o.hasCode("union")&&o.errors.length===0)return;let F=T.hasCode("union")&&T.errors.length===0?T:new DF({code:"intersection",errors:o.hasCode("intersection")?[...o.errors,T]:[o,T]},this.ctx),
|
|
13
|
-
`+T.map((o)=>` \u2022 ${
|
|
14
|
-
`));Object.defineProperty(this,"arkErrors",{value:T,enumerable:!1})}}var
|
|
17
|
+
`):this.body} }`}compile(){return new i_(...this.argNames,this.body)}}var _F=(T)=>Yo(T,"object")||typeof T==="symbol"?BT(T):rA(T),hf=(T,o=!1)=>{if(typeof T==="string"&&QF(T))return`${o?"?":""}.${T}`;return W0(uX(T),o)},uX=(T)=>typeof T==="symbol"?BT(T):JSON.stringify(T),W0=(T,o=!1)=>`${o?"?.":""}[${T}]`;class aA extends ay{traversalKind;optimistic;constructor(T){super("data","ctx");this.traversalKind=T.kind,this.optimistic=T.optimistic===!0}invoke(T,o){let F=o?.arg??this.data,A=typeof T==="string"?!0:this.requiresContextFor(T),y=typeof T==="string"?T:T.id;if(A)return`${this.referenceToId(y,o)}(${F}, ${this.ctx})`;return`${this.referenceToId(y,o)}(${F})`}referenceToId(T,o){let F=o?.kind??this.traversalKind,A=`this.${T}${F}`;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,F){let A=this.requiresContextFor(F);if(A)this.line(`${this.ctx}.path.push(${T})`);if(this.check(F,{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 ey=(T)=>d(T,(o,F)=>[o,HT(F)?[...F]:F]),Ro=to("arkKind"),P=(T,o)=>T?.[Ro]===o,UT=(T)=>P(T,"root")||P(T,"constraint");var M0=["unit","proto","domain"],fA=["required","optional","index","sequence"],gf=["pattern","divisor","exactLength","max","min","maxLength","minLength","before","after"],TS=[...gf,...fA,"structure","predicate"],$A=["alias","union","morph","unit","intersection","proto","domain"],cX=[...$A,...TS],oS=d(TS,(T,o)=>[o,1]),O0=d([...fA,"undeclared"],(T,o)=>[o,1]),X0=d(cX,(T,o)=>[o,T]),JA=(T)=>typeof T==="string"&&(T in X0);var _A=(T)=>X0[T],FS=(T)=>$A.slice(_A(T)+1),EG=[...FS("union"),"alias"],KG=[...FS("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 _F(T)},VF=(T)=>{let o="{ ";for(let[F,A]of Object.entries(T))o+=`${F}: ${_F(A)}, `;return o+" }"},l=(T)=>{let o=T;if(o.hasAssociatedError)o.defaults.expected??=(F)=>("description"in F)?F.description:o.defaults.description(F),o.defaults.actual??=(F)=>r(F),o.defaults.problem??=(F)=>`must be ${F.expected}${F.actual?` (was ${F.actual})`:""}`,o.defaults.message??=(F)=>{if(F.path.length===0)return F.problem;let A=`${F.propString} ${F.problem}`;if(A[0]==="[")return`value at ${A}`;return A};return o};class Y0 extends Error{name="ToJsonSchemaError";code;context;constructor(T,o){super(r(o,{quoteKeys:!1,indent:4}));this.code=T,this.context=o}hasCode(T){return this.code===T}}var iX={dialect:"https://json-schema.org/draft/2020-12/schema",useRefs:!1,fallback:{arrayObject:(T)=>LT.throw("arrayObject",T),arrayPostfix:(T)=>LT.throw("arrayPostfix",T),defaultValue:(T)=>LT.throw("defaultValue",T),domain:(T)=>LT.throw("domain",T),morph:(T)=>LT.throw("morph",T),patternIntersection:(T)=>LT.throw("patternIntersection",T),predicate:(T)=>LT.throw("predicate",T),proto:(T)=>LT.throw("proto",T),symbolKey:(T)=>LT.throw("symbolKey",T),unit:(T)=>LT.throw("unit",T),date:(T)=>LT.throw("date",T)}},LT={Error:Y0,throw:(...T)=>{throw new LT.Error(...T)},throwInternalOperandError:(T,o)=>$T(`Unexpected JSON Schema input for ${T}: ${r(o)}`),defaultConfig:iX};K.config??={};var eA=(T,o)=>{if(!o)return T;let F={...T},A;for(A in o){let y={...T.keywords};if(A==="keywords"){for(let S in o[A]){let f=o.keywords[S];if(f===void 0)continue;y[S]=typeof f==="string"?{description:f}:f}F.keywords=y}else if(A==="toJsonSchema")F[A]=nf(T.toJsonSchema,o.toJsonSchema);else if(JA(A))F[A]={...T[A],...o[A]};else F[A]=o[A]}return F},nf=(T,o)=>{if(!T)return o??{};if(!o)return T;let F={...T},A;for(A in o)if(A==="fallback")F.fallback=dX(T.fallback,o.fallback);else F[A]=o[A];return F},dX=(T,o)=>{T=Z0(T),o=Z0(o);let F={},A;for(A in LT.defaultConfig.fallback)F[A]=o[A]??o.default??T[A]??T.default??LT.defaultConfig.fallback[A];return F},Z0=(T)=>typeof T==="function"?{default:T}:T??{};class DF extends hA{[Ro]="error";path;data;nodeConfig;input;ctx;constructor({prefixPath:T,relativePath:o,...F},A){super();this.input=F,this.ctx=A,t_(this,F);let y=A.data;if(F.code==="union")F.errors=F.errors.flatMap((f)=>{let $=f.hasCode("union")?f.errors:[f];if(!T&&!o)return $;return $.map((_)=>_.transform((J)=>({...J,path:x_(T,J.path,o)})))});this.nodeConfig=A.config[this.code];let S=[...F.path??A.path];if(o)S.push(...o);if(T)S.unshift(...T);this.path=new sA(...S),this.data="data"in F?F.data:y}transform(T){return new DF(T({data:this.data,path:this.path,...this.input}),this.ctx)}hasCode(T){return this.code===T}get propString(){return JF(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 ry{[Ro]="errors";ctx;constructor(T){super();this.ctx=T}byPath=Object.create(null);get flatByPath(){return d(this.byPath,(T,o)=>[T,o.flat])}get flatProblemsByPath(){return d(this.byPath,(T,o)=>[T,o.flat.map((F)=>F.problem)])}byAncestorPath=Object.create(null);count=0;mutable=this;throw(){throw this.toTraversalError()}toTraversalError(){return new uf(this)}add(T){if(this.includes(T))return;this._add(T)}transform(T){let o=new Ho(this.ctx);for(let F of this)o.add(T(F));return o}merge(T){for(let o of T){if(this.includes(o))continue;this._add(new DF({...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(`
|
|
18
|
+
`)}_add(T){let o=this.byPath[T.propString];if(o){if(o.hasCode("union")&&o.errors.length===0)return;let F=T.hasCode("union")&&T.errors.length===0?T:new DF({code:"intersection",errors:o.hasCode("intersection")?[...o.errors,T]:[o,T]},this.ctx),A=this.indexOf(o);this.mutable[A===-1?this.length:A]=F,this.byPath[T.propString]=F,this.addAncestorPaths(T)}else this.byPath[T.propString]=T,this.addAncestorPaths(T),this.mutable.push(T);this.count++}addAncestorPaths(T){for(let o of T.path.stringifyAncestors())this.byAncestorPath[o]=yT(this.byAncestorPath[o],T)}}class uf extends Error{name="TraversalError";constructor(T){if(T.length===1)super(T.summary);else super(`
|
|
19
|
+
`+T.map((o)=>` \u2022 ${rX(o)}`).join(`
|
|
20
|
+
`));Object.defineProperty(this,"arkErrors",{value:T,enumerable:!1})}}var rX=(T)=>T.toString().split(`
|
|
15
21
|
`).join(`
|
|
16
|
-
`);class go{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 _F(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 ry(...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 DF(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:F}of T){if(this.errors.affectsPath(o))continue;this.applyMorphsAtPath(o,F)}}}applyMorphsAtPath(T,o){let F=T.at(-1),y;if(F!==void 0){y=this.root;for(let A=0;A<T.length-1;A++)y=y[T[A]]}this.path=[...T];for(let A of o){let S=zT(A),f=A(y===void 0?this.root:y[F],this);if(f instanceof DF){this.errors.add(f);break}if(f instanceof Ho){if(!S)this.errors.merge(f);break}if(y===void 0)this.root=f;else y[F]=f;this.applyQueuedMorphs()}}}var Go=(T,o,F)=>{if(!F)return o();F.path.push(T);let y=o();return F.path.pop(),y};class ey extends ho{attachments;$;onFail;includesTransform;includesContextualPredicate;isCyclic;allowsRequiresContext;rootApplyStrategy;contextFreeMorph;rootApply;referencesById;shallowReferences;flatRefs;flatMorphs;allows;get shallowMorphs(){return[]}constructor(T,o){super((y,A,S=this.onFail)=>{if(A)return this.traverseApply(y,A),A.hasError()?A.errors:A.data;return this.rootApply(y,S)},{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((y,A)=>uX(y,A.shallowReferences),[this]);let F=this.isStructural();this.flatRefs=[],this.flatMorphs=[];for(let y=0;y<this.children.length;y++){if(this.includesTransform||=this.children[y].includesTransform,this.includesContextualPredicate||=this.children[y].includesContextualPredicate,this.isCyclic||=this.children[y].isCyclic,!F){let A=this.children[y].flatRefs;for(let S=0;S<A.length;S++){let f=A[S];if(!this.flatRefs.some(($)=>X0($,f))){this.flatRefs.push(f);for(let $ of f.node.branches)if($.hasKind("morph")||$.hasKind("intersection")&&$.structure?.structuralMorph!==void 0)this.flatMorphs.push({path:f.path,propString:f.propString,node:$})}}}Object.assign(this.referencesById,this.children[y].referencesById)}this.flatRefs.sort((y,A)=>y.path.length>A.path.length?1:y.path.length<A.path.length?-1:y.propString>A.propString?1:y.propString<A.propString?-1:y.node.expression<A.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((y)=>y.length===1||y.name==="$arkStructuralMorph")?this.hasKind("union")?this.branches.some((y)=>y.shallowMorphs.length>1)?"contextual":"branchedOptimistic":this.shallowMorphs.length>1?"contextual":"optimistic":"contextual":"contextual",this.rootApply=this.createRootApply(),this.allows=this.allowsRequiresContext?(y)=>this.traverseAllows(y,new go(y,this.$.resolvedConfig)):(y)=>this.traverseAllows(y)}createRootApply(){switch(this.rootApplyStrategy){case"allows":return(o,F)=>{if(this.allows(o))return o;let y=new go(o,this.$.resolvedConfig);return this.traverseApply(o,y),y.finalize(F)};case"contextual":return(o,F)=>{let y=new go(o,this.$.resolvedConfig);return this.traverseApply(o,y),y.finalize(F)};case"optimistic":this.contextFreeMorph=this.shallowMorphs[0];let T=this.$.resolvedConfig.clone;return(o,F)=>{if(this.allows(o))return this.contextFreeMorph(T&&(typeof o==="object"&&o!==null||typeof o==="function")?T(o):o);let y=new go(o,this.$.resolvedConfig);return this.traverseApply(o,y),y.finalize(F)};case"branchedOptimistic":return this.createBranchedOptimisticRootApply();default:return this.rootApplyStrategy,$T(`Unexpected rootApplyStrategy ${this.rootApplyStrategy}`)}}compiledMeta=nX(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=$y(this.kind);precompilation;assert=(T,o)=>this(T,o,(F)=>F.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[F,y]of this.innerEntries){let A=this.impl.keys[F];if(A.reduceIo)A.reduceIo(T,o,y);else if(A.child){let S=y;o[F]=GT(S)?S.map((f)=>f[T]):S[T]}else o[F]=y}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)$F(`${this.kind} node was not of asserted kind ${T}`);return this}hasKindIn(...T){return T.includes(this.kind)}assertHasKindIn(...T){if(!AF(T,this.kind))$F(`${this.kind} node was not one of asserted kinds ${T}`);return this}isBasis(){return AF(R0,this.kind)}isConstraint(){return AF(eA,this.kind)}isStructural(){return AF(Ay,this.kind)}isRefinement(){return AF(Pf,this.kind)}isRoot(){return AF(Sy,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=ay.normalize(T);return this._select(o)}_select(T){let o=ay.applyBoundary[T.boundary??"references"](this);if(T.kind)o=o.filter((F)=>F.kind===T.kind);if(T.where)o=o.filter(T.where);return ay.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 F=o.bindScope??this.$;if(o.seen[this.id])return this.$.lazilyResolve(o.seen[this.id]);if(o.shouldTransform?.(this,o)===!1)return this;let y;if(o.seen[this.id]=()=>y,this.hasKind("structure")&&this.undeclared!==o.undeclaredKeyHandling)o={...o,undeclaredKeyHandling:this.undeclared};let A=l(this.inner,(J,R)=>{if(!this.impl.keys[J].child)return[J,R];let M=R;if(!GT(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 S=Object.assign(A,{meta:this.meta}),f=o.selected&&!o.selected.includes(this)?S:T(this.kind,S,o);if(f===null)return null;if(zT(f))return y=f;let $=Object.keys(f);if(($.length===0||$.length===1&&$[0]==="meta")&&!ao(this.inner))return null;if((this.kind==="required"||this.kind==="optional"||this.kind==="index")&&!("value"in f))return o.undeclaredKeyHandling?{...f,value:U.intrinsic.unknown}:null;if(this.kind==="morph")f.in??=U.intrinsic.unknown;return y=F.node(this.kind,f,o.parseOptions)}configureReferences(T,o="references"){let F=ay.normalize(o),y=typeof T==="string"?($,_)=>({..._,meta:{..._.meta,description:T}}):typeof T==="function"?($,_)=>({..._,meta:T(_.meta)}):($,_)=>({..._,meta:{..._.meta,...T}});if(F.boundary==="self")return this.$.node(this.kind,y(this.kind,{...this.inner,meta:this.meta}));let A=this._select(F),S=A&&KF(A),f=F.boundary==="child"?($,_)=>_.root.children.includes($):F.boundary==="shallow"?($)=>$.kind!=="structure":()=>!0;return this.$.finalize(this.transform(y,{shouldTransform:f,selected:S}))}}var ay={applyBoundary:{self:(T)=>[T],child:(T)=>[...T.children],shallow:(T)=>[...T.shallowReferences],references:(T)=>[...T.references]},applyMethod:{filter:(T)=>T,assertFilter:(T,o,F)=>{if(T.length===0)$F(M0(o,F));return T},find:(T)=>T[0],assertFind:(T,o,F)=>{if(T.length===0)$F(M0(o,F));return T[0]}},normalize:(T)=>typeof T==="function"?{boundary:"references",method:"filter",where:T}:typeof T==="string"?xT(T,ay.applyBoundary)?{method:"filter",boundary:T}:{boundary:"references",method:"filter",kind:T}:{boundary:"references",method:"filter",...T}},M0=(T,o)=>`${T} had no references matching ${d(o)}.`,hX=(T)=>_F(T,{stringifyNonKey:(o)=>o.expression}),gX=/"(\$ark\.[^"]+)"/g,nX=(T)=>JSON.stringify(T).replaceAll(gX,"$1"),no=(T,o)=>({path:T,node:o,propString:hX(T)}),X0=(T,o)=>T.propString===o.propString&&T.node.equals(o.node),gf=(T,o)=>so(T,o,{isEqual:X0}),uX=(T,o)=>so(T,o,{isEqual:(F,y)=>F.equals(y)});class k extends Array{static init(T,o,F,y){return new k({kind:T,l:o,r:F,path:y?.path??[],optional:y?.optional??!1})}add(T,o,F,y){return this.push({kind:T,l:o,r:F,path:y?.path??[],optional:y?.optional??!1}),this}get summary(){return this.describeReasons()}describeReasons(){if(this.length===1){let{path:T,l:o,r:F}=this[0],y=_F(T);return uf(`Intersection${y&&` at ${y}`} of ${Y0(o,F)}`)}return`The following intersections result in unsatisfiable types:
|
|
17
|
-
\u2022 ${this.map(({path:T,l:o,r:F})=>`${T}: ${
|
|
18
|
-
\u2022 `)}`}throw(){return G(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((F)=>({...F,path:[T,...F.path],optional:F.optional||o==="optional"}))}toNeverIfDisjoint(){return U.intrinsic.never}}var Y0=(T,o)=>`${nf(T)} and ${nf(o)}`,nf=(T)=>zT(T)?T.expression:GT(T)?T.map(nf).join(" | ")||"never":String(T),uf=(T)=>`${T} results in an unsatisfiable type`;var Jy={},Eo=(T,o,F)=>QT(T,o,{$:F,invert:!1,pipe:!1}),TA=(T,o,F)=>QT(T,o,{$:F,invert:!1,pipe:!0}),QT=(T,o,F)=>{let y=F.pipe?"|>":"&",A=`${T.hash}${y}${o.hash}`;if(Jy[A]!==void 0)return Jy[A];if(!F.pipe){let $=`${o.hash}${y}${T.hash}`;if(Jy[$]!==void 0){let _=Jy[$],J=_ instanceof k?_.invert():_;return Jy[A]=J,J}}let S=!F.pipe||!T.includesTransform&&!o.includesTransform;if(S&&T.equals(o))return T;let f=S?cf(T,o,F):T.hasKindIn(...Sy)?cX(T,o,F):cf(T,o,F);if(zT(f)){if(T.equals(f))f=T;else if(o.equals(f))f=o}return Jy[A]=f,f},cf=(T,o,F)=>{let y=T.precedence<o.precedence?T.kind:o.kind,A=T.impl.intersections[o.kind]??o.impl.intersections[T.kind];if(A===void 0)return null;else if(y===T.kind)return A(T,o,F);else{let S=A(o,T,{...F,invert:!F.invert});if(S instanceof k)S=S.invert();return S}},cX=(T,o,F)=>T.includesTransform||o.includesTransform?F.invert?Z0(o,T,F):Z0(T,o,F):cf(T,o,F),Z0=(T,o,F)=>T.distribute((y)=>iX(y,o,F),(y)=>{let A=y.filter(zT);if(A.length===0)return k.init("union",T.branches,o.branches);if(A.length<T.branches.length||!T.branches.every(($,_)=>$.in.equals(A[_].in)))return F.$.parseSchema(A);let S;if(A.length===1){let $=A[0];if(!S)return $;return F.$.node("morph",{...$.inner,in:$.in.configure(S,"self")})}let f={branches:A};if(S)f.meta=S;return F.$.parseSchema(f)}),iX=(T,o,F)=>{if(T.hasKind("morph")){let A=[...T.morphs];if(T.lastMorphIfNode){let S=QT(T.lastMorphIfNode,o,F);if(S instanceof k)return S;A[A.length-1]=S}else A.push(o);return F.$.node("morph",{morphs:A,in:T.inner.in})}if(o.hasKind("morph")){let A=QT(T,o.in,F);if(A instanceof k)return A;return F.$.node("morph",{morphs:[o],in:A})}return F.$.node("morph",{morphs:[o],in:T})};class Bo extends ey{constructor(T,o){super(T,o);Object.defineProperty(this,Ro,{value:"constraint",enumerable:!1})}impliedSiblings;intersect(T){return Eo(this,T,this.$)}}class WF 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 VF(this.errorContext)}}var So=(T)=>(o,F)=>{if(GT(o)){if(o.length===0)return;let A=o.map((S)=>F.$.node(T,S));if(T==="predicate")return A;return A.sort((S,f)=>S.hash<f.hash?-1:1)}let y=F.$.node(T,o);return y.hasOpenIntersection()?[y]:y},_y=(T)=>{let o=T.r.shift();if(!o){let y=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 A of T.roots){if(y instanceof k)return y;y=QT(A,y,T.ctx)}return y}let F=!1;for(let y=0;y<T.l.length;y++){let A=QT(T.l[y],o,T.ctx);if(A===null)continue;if(A instanceof k)return A;if(!F){if(A.isRoot())return T.roots.push(A),T.l.splice(y),_y(T);T.l[y]=A,F=!0}else if(!T.l.includes(A))return $T(`Unexpectedly encountered multiple distinct intersection results for refinement ${A}`)}if(!F)T.l.push(o);if(T.kind==="intersection")o.impliedSiblings?.forEach((y)=>so(T.r,y));return _y(T)},Ry=(T)=>{return Object.entries(T).flatMap(([F,y])=>(F in TS)?y:[]).sort((F,y)=>F.precedence<y.precedence?-1:F.precedence>y.precedence?1:F.kind==="predicate"&&y.kind==="predicate"?0:F.hash<y.hash?-1:1)},dX=(T)=>{let o={};for(let F of T)if(F.hasOpenIntersection())o[F.kind]=AT(o[F.kind],F);else{if(o[F.kind])return $T(`Unexpected intersection of closed refinements of kind ${F.kind}`);o[F.kind]=F}return o},H0=(...T)=>G(G0(...T)),G0=(T,o,F)=>{let y=F.hasKind("morph")?"a morph":F.isUnknown()?"unknown":F.exclude(o).defaultShortDescription;return`${r_(T)} operand must be ${o.description} (was ${y})`};var E0=(T,o,F)=>new CF(T,o,F,F,null);class FS extends ho{}class CF extends ho{[Ro]="generic";paramDefs;bodyDef;$;arg$;baseInstantiation;hkt;description;constructor(T,o,F,y,A){super((...S)=>{let f=l(this.names,($,_)=>{let J=this.arg$.parse(S[$]);if(!J.extends(this.constraints[$]))G(rX(_,this.constraints[$].expression,J.expression));return[_,J]});if(this.defIsLazy()){let $=this.bodyDef(f);return this.$.parse($)}return this.$.parse(o,{args:f})});this.paramDefs=T,this.bodyDef=o,this.$=F,this.arg$=y,this.hkt=A,this.description=A?new A().description??`a generic type for ${A.constructor.name}`:"a generic type",this.baseInstantiation=this(...this.constraints)}defIsLazy(){return this.bodyDef instanceof FS}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:f0(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,F)=>`${T} must be assignable to ${o} (was ${F})`;var w0={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"},U0=(T,o)=>{let F=`${T} is not convertible to JSON Schema`;if(o){let y=xT(o,w0)?w0[o]:o;F+=` because ${y}`}return F},JT={writeUnjsonifiableMessage:U0,UnjsonifiableError:class T extends Error{},throwUnjsonifiableError:(...T)=>$F(U0(...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 K0 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=VF(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 df={implementation:lX,Node:K0};var sX=r({kind:"divisor",collapsibleKey:"rule",keys:{rule:{parse:(T)=>Number.isInteger(T)?T:G(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,F)=>F.$.node("divisor",{rule:Math.abs(T.rule*o.rule/eX(T.rule,o.rule))})},obviatesBasisDescription:!0});class z0 extends WF{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 rf={implementation:sX,Node:z0};var aX=(T)=>`divisor must be an integer (was ${T})`,eX=(T,o)=>{let F,y=T,A=o;while(A!==0)F=A,A=y%A,y=F;return y};class Vo extends WF{boundOperandKind=y8[this.kind];compiledActual=this.boundOperandKind==="value"?"data":this.boundOperandKind==="length"?"data.length":"data.valueOf()";comparator=A8(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"?S8(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"},yS={parse:(T)=>T||void 0},AS=(T)=>(o)=>{if(typeof o==="number")return{rule:o};let{exclusive:F,...y}=o;return F?{...y,rule:T==="minLength"?y.rule+1:y.rule-1}:y},SS=(T)=>(o)=>{if(typeof o==="number"||typeof o==="string"||o instanceof Date)return{rule:o};let{exclusive:F,...y}=o;if(!F)return y;let A=typeof y.rule==="number"?y.rule:typeof y.rule==="string"?new Date(y.rule).valueOf():y.rule.valueOf();return F?{...y,rule:T==="after"?A+1:A-1}:y},fS=(T)=>typeof T==="string"||typeof T==="number"?new Date(T):T,F8=(T,o)=>`${T} bound must be a positive integer (was ${o})`,Wy=(T)=>(o)=>{if(!Number.isInteger(o)||o<0)G(F8(T,o));return o},y8={min:"value",max:"value",minLength:"length",maxLength:"length",after:"date",before:"date"},A8=(T,o)=>`${xT(T,o8)?">":"<"}${o?"":"="}`,S8=(T)=>typeof T==="string"?T:new Date(T).toLocaleString(),Q0=(T)=>`Bounded expression ${T} must be exactly one of number, string, Array, or Date`;var f8=r({kind:"after",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:fS,serialize:(T)=>T.toISOString()}},normalize:SS("after"),defaults:{description:(T)=>`${T.collapsibleLimitString} or later`,actual:vF},intersections:{after:(T,o)=>T.isStricterThan(o)?T:o}});class V0 extends Vo{impliedBasis=U.intrinsic.Date.internal;collapsibleLimitString=vF(this.rule);traverseAllows=(T)=>T>=this.rule;reduceJsonSchema(){return JT.throwUnjsonifiableError("Date instance")}}var lf={implementation:f8,Node:V0};var $8=r({kind:"before",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:fS,serialize:(T)=>T.toISOString()}},normalize:SS("before"),defaults:{description:(T)=>`${T.collapsibleLimitString} or earlier`,actual:vF},intersections:{before:(T,o)=>T.isStricterThan(o)?T:o,after:(T,o,F)=>T.overlapsRange(o)?T.overlapIsUnit(o)?F.$.node("unit",{unit:T.rule}):null:k.init("range",T,o)}});class D0 extends Vo{collapsibleLimitString=vF(this.rule);traverseAllows=(T)=>T<=this.rule;impliedBasis=U.intrinsic.Date.internal;reduceJsonSchema(){return JT.throwUnjsonifiableError("Date instance")}}var sf={implementation:$8,Node:D0};var J8=r({kind:"exactLength",collapsibleKey:"rule",keys:{rule:{parse:Wy("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,F)=>k.init("unit",F.$.node("unit",{unit:T.rule}),F.$.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 C0 extends WF{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 af={implementation:J8,Node:C0};var _8=r({kind:"max",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{},exclusive:yS},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,F)=>T.overlapsRange(o)?T.overlapIsUnit(o)?F.$.node("unit",{unit:T.rule}):null:k.init("range",T,o)},obviatesBasisDescription:!0});class L0 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 ef={implementation:_8,Node:L0};var R8=r({kind:"maxLength",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:Wy("maxLength")}},reduce:(T,o)=>T.rule===0?o.node("exactLength",T):void 0,normalize:AS("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,F)=>T.overlapsRange(o)?T.overlapIsUnit(o)?F.$.node("exactLength",{rule:T.rule}):null:k.init("range",T,o)}});class I0 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:I0};var W8=r({kind:"min",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{},exclusive:yS},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 k0 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:k0};var O8=r({kind:"minLength",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:Wy("minLength")}},reduce:(T)=>T.rule===0?U.intrinsic.unknown:void 0,normalize:AS("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 B0 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 F$={implementation:O8,Node:B0};var N0={min:o$.implementation,max:ef.implementation,minLength:F$.implementation,maxLength:T$.implementation,exactLength:af.implementation,after:lf.implementation,before:sf.implementation},p0={min:o$.Node,max:ef.Node,minLength:F$.Node,maxLength:T$.Node,exactLength:af.Node,after:lf.Node,before:sf.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 x0 extends WF{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 y$={implementation:M8,Node:x0};var oA=(T,o)=>{let F=X8(T);if(o&&!o.includes(F))return G(`Root of kind ${F} should be one of ${o}`);return F},X8=(T)=>{if(v(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 G(b0(T));if("morphs"in T)return"morph";if("branches"in T||GT(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((F)=>(F in TS)))return"intersection";if("proto"in T)return"proto";if("domain"in T)return"domain";return G(b0(T))},b0=(T)=>`${d(T)} is not a valid type schema`,j0={},Y8=(T)=>GT(T)?T.map((o)=>o.collapsibleJson):T.collapsibleJson,Wo={};U.nodesByRegisteredId=Wo;var A$=(T)=>{return j0[T]??=0,`${T}${++j0[T]}`},S$=(T)=>{let o=Oy[T.kind],F=o.applyConfig?.(T.def,T.$.resolvedConfig)??T.def,y={},{meta:A,...S}=F,f=A===void 0?{}:typeof A==="string"?{description:A}:A,$=Lf(S).sort(([J],[R])=>fy(J)?fy(R)?$y(J)-$y(R):1:fy(R)?-1:J<R?-1:1).filter(([J,R])=>{if(J.startsWith("meta.")){let M=J.slice(5);return f[M]=R,!1}return!0});for(let J of $){let R=J[0],M=o.keys[R];if(!M)return G(`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))y[R]=Y}if(o.reduce&&!T.prereduced){let J=o.reduce(y,T.$);if(J){if(J instanceof k)return J.throw();return Z8(J,f)}}return f$({id:T.id,kind:T.kind,inner:y,meta:f,$:T.$})},f$=({id:T,kind:o,inner:F,meta:y,$:A,ignoreCache:S})=>{let f=Oy[o],$=Lf(F),_=[],J={};if($.forEach(([p,q])=>{let h=f.keys[p],K=h.serialize??(h.child?Y8:ko);if(J[p]=K(q),h.child===!0){let V=q;if(GT(V))_.push(...V);else _.push(V)}else if(typeof h.child==="function")_.push(...h.child(q))}),f.finalizeInnerJson)J=f.finalizeInnerJson(J);let R={...J},M={};if(!ao(y))M=l(y,(p,q)=>[p,p==="examples"?q:ko(q)]),R.meta=$S(M,"description",!0);J=$S(J,f.collapsibleKey,!1);let Y=JSON.stringify({kind:o,...J});R=$S(R,f.collapsibleKey,!1);let H=$S(R,f.collapsibleKey,!0),Q=JSON.stringify({kind:o,...R});if(A.nodesByHash[Q]&&!S)return A.nodesByHash[Q];let w={id:T,kind:o,impl:f,inner:F,innerEntries:$,innerJson:J,innerHash:Y,meta:y,metaJson:M,json:R,hash:Q,collapsibleJson:H,children:_};if(o!=="intersection"){for(let p in F)if(p!=="in"&&p!=="out")w[p]=F[p]}let B=new q0[o](w,A);return A.nodesByHash[Q]=B},t0=(T,o)=>{if(T.id===o)return T;if(zT(Wo[o]))$T(`Unexpected attempt to overwrite node id ${o}`);return f$({id:o,kind:T.kind,inner:T.inner,meta:T.meta,$:T.$,ignoreCache:!0})},Z8=(T,o,F)=>{if(F&&zT(Wo[F]))$T(`Unexpected attempt to overwrite node id ${F}`);return f$({id:F??A$(o.alias??T.kind),kind:T.kind,inner:T.inner,meta:o,$:T.$})},$S=(T,o,F)=>{let y=Object.keys(T);if(y.length===1&&y[0]===o){let A=T[o];if(F)return A;if(Yo(A,"object")&&(Object.keys(A).length===1||Array.isArray(A)))return A}return T};var FA=(T,o,F)=>{if(T.key!==o.key)return null;let y=T.key,A=QT(T.value,o.value,F),S=T.required||o.required?"required":"optional";if(A instanceof k)if(S==="optional")A=U.intrinsic.never.internal;else return A.withPrefixKey(T.key,T.required&&o.required?"required":"optional");if(S==="required")return F.$.node("required",{key:y,value:A});let f=T.hasDefault()?o.hasDefault()?T.default===o.default?T.default:G($$(T.default,o.default)):T.default:o.hasDefault()?o.default:Qo;return F.$.node("optional",{key:y,value:A,default:f})};class yA extends Bo{required=this.kind==="required";optional=this.kind==="optional";impliedBasis=U.intrinsic.object.internal;serializedKey=RF(this.key);compiledKey=typeof this.key==="string"?this.key:this.serializedKey;flatRefs=AT(this.value.flatRefs.map((T)=>no([this.key,...T.path],T.node)),no([this.key],this.value));_transform(T,o){o.path.push(this.key);let F=super._transform(T,o);return o.path.pop(),F}hasDefault(){return"default"in this.inner}traverseAllows=(T,o)=>{if(this.key in T)return Go(this.key,()=>this.value.traverseAllows(T[this.key],o),o);return this.optional};traverseApply=(T,o)=>{if(this.key in T)Go(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(n.undefined)},{prereduced:!0})}},defaults:{description:(T)=>`${T.compiledKey}?: ${T.value.description}`},intersections:{optional:FA}});class v0 extends yA{constructor(...T){super(...T);if("default"in this.inner)SA(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=E8(this);defaultValueMorphRef=this.defaultValueMorph&&BT(this.defaultValueMorph)}var AA={implementation:H8,Node:v0},G8={},E8=(T)=>{if(!T.hasDefault())return;let o=`{${T.compiledKey}: ${T.value.id} = ${ko(T.default)}}`;return G8[o]??=J$(T.key,T.value,T.default)},J$=(T,o,F)=>{if(typeof F==="function")return o.includesTransform?(A,S)=>{return Go(T,()=>o(A[T]=F(),S),S),A}:(A)=>{return A[T]=F(),A};let y=o.includesTransform?o.assert(F):F;return Yo(y,"object")?(A,S)=>{return Go(T,()=>o(A[T]=F,S),S),A}:(A)=>{return A[T]=y,A}},SA=(T,o,F)=>{let y=zF(o);if(Yo(o,"object")&&!y)G(w8(F));let A=T.in(y?o():o);if(A instanceof Ho){if(F===null)G(`Default ${A.summary}`);let S=A.transform((f)=>f.transform(($)=>({...$,prefixPath:[F]})));G(`Default for ${S.summary}`)}return o},w8=(T)=>{return`Non-primitive default ${T===null?"":typeof T==="number"?`for value at [${T}] `:`for ${RF(T)} `}must be specified as a function like () => ({my: 'object'})`};class No extends ey{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 G(U8);return this}readonly(){return this}branches=this.hasKind("union")?this.inner.branches:[this];distribute(T,o){let F=this.branches.map(T);return o?.(F)??F}get shortDescription(){return this.meta.description??this.defaultShortDescription}toJsonSchema(T={}){let o={dialect:"https://json-schema.org/draft/2020-12/schema",...T},F=this.toJsonSchemaRecurse(o);if(typeof o.dialect==="string")F.$schema=o.dialect;return F}toJsonSchemaRecurse(T){let o=this.innerToJsonSchema(T);return Object.assign(o,this.metaJson)}intersect(T){let o=this.$.parseDefinition(T),F=this.rawIntersect(o);if(F instanceof k)return F;return this.$.finalize(F)}rawIntersect(T){return Eo(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,F)=>o.intersect(F).toNeverIfDisjoint(),U.intrinsic.unknown.internal);if(T.branches.length===0)G(uf(`keyof ${this.expression}`));return this._keyof=this.$.finalize(T)}get props(){if(this.branches.length!==1)return G(K8(this.expression));return[...this.applyStructuralOperation("props",[])[0]]}merge(T){let o=this.$.parseDefinition(T);return this.$.schema(o.distribute((F)=>this.applyStructuralOperation("merge",[m0(F)??G(P0("merge",F.expression))])))}applyStructuralOperation(T,o){return this.distribute((F)=>{if(F.equals(U.intrinsic.object)&&T!=="merge")return F;let y=m0(F);if(!y)G(P0(T,F.expression));if(T==="keyof")return y.keyof();if(T==="get")return y.get(...o);if(T==="props")return y.props;let A=T==="required"?"require":T==="partial"?"optionalize":T;return this.$.node("intersection",{...F.inner,structure:y[A](...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((F)=>F.extends(o)))}exclude(T){let o=this.$.parseDefinition(T);return this.$.schema(this.branches.filter((F)=>!F.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 SA(this,T,null),[this,"=",T]}from(T){return this.assert(T)}_pipe(...T){let o=T.reduce((F,y)=>F.rawPipeOnce(y),this);return this.$.finalize(o)}tryPipe(...T){let o=T.reduce((F,y)=>F.rawPipeOnce(v(y,"root")?y:(A,S)=>{try{return y(A,S)}catch(f){return S.error({code:"predicate",predicate:y,actual:`aborted due to error:
|
|
22
|
+
`);class go{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 JF(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 sA(...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 DF(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:F}of T){if(this.errors.affectsPath(o))continue;this.applyMorphsAtPath(o,F)}}}applyMorphsAtPath(T,o){let F=T.at(-1),A;if(F!==void 0){A=this.root;for(let y=0;y<T.length-1;y++)A=A[T[y]]}this.path=[...T];for(let y of o){let S=UT(y),f=y(A===void 0?this.root:A[F],this);if(f instanceof DF){this.errors.add(f);break}if(f instanceof Ho){if(!S)this.errors.merge(f);break}if(A===void 0)this.root=f;else A[F]=f;this.applyQueuedMorphs()}}}var Go=(T,o,F)=>{if(!F)return o();F.path.push(T);let A=o();return F.path.pop(),A};class oy extends ho{attachments;$;onFail;includesTransform;includesContextualPredicate;isCyclic;allowsRequiresContext;rootApplyStrategy;contextFreeMorph;rootApply;referencesById;shallowReferences;flatRefs;flatMorphs;allows;get shallowMorphs(){return[]}constructor(T,o){super((A,y,S=this.onFail)=>{if(y)return this.traverseApply(A,y),y.hasError()?y.errors:y.data;return this.rootApply(A,S)},{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,y)=>eX(A,y.shallowReferences),[this]);let F=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,!F){let y=this.children[A].flatRefs;for(let S=0;S<y.length;S++){let f=y[S];if(!this.flatRefs.some(($)=>G0($,f))){this.flatRefs.push(f);for(let $ of f.node.branches)if($.hasKind("morph")||$.hasKind("intersection")&&$.structure?.structuralMorph!==void 0)this.flatMorphs.push({path:f.path,propString:f.propString,node:$})}}}Object.assign(this.referencesById,this.children[A].referencesById)}this.flatRefs.sort((A,y)=>A.path.length>y.path.length?1:A.path.length<y.path.length?-1:A.propString>y.propString?1:A.propString<y.propString?-1:A.node.expression<y.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 go(A,this.$.resolvedConfig)):(A)=>this.traverseAllows(A)}createRootApply(){switch(this.rootApplyStrategy){case"allows":return(o,F)=>{if(this.allows(o))return o;let A=new go(o,this.$.resolvedConfig);return this.traverseApply(o,A),A.finalize(F)};case"contextual":return(o,F)=>{let A=new go(o,this.$.resolvedConfig);return this.traverseApply(o,A),A.finalize(F)};case"optimistic":this.contextFreeMorph=this.shallowMorphs[0];let T=this.$.resolvedConfig.clone;return(o,F)=>{if(this.allows(o))return this.contextFreeMorph(T&&(typeof o==="object"&&o!==null||typeof o==="function")?T(o):o);let A=new go(o,this.$.resolvedConfig);return this.traverseApply(o,A),A.finalize(F)};case"branchedOptimistic":return this.createBranchedOptimisticRootApply();default:return this.rootApplyStrategy,$T(`Unexpected rootApplyStrategy ${this.rootApplyStrategy}`)}}compiledMeta=aX(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,(F)=>F.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[F,A]of this.innerEntries){let y=this.impl.keys[F];if(y.reduceIo)y.reduceIo(T,o,A);else if(y.child){let S=A;o[F]=HT(S)?S.map((f)=>f[T]):S[T]}else o[F]=A}return this.$.node(this.kind,o)}toJSON(){return this.json}toString(){return`Type<${this.expression}>`}equals(T){let o=UT(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)qF(`${this.kind} node was not of asserted kind ${T}`);return this}hasKindIn(...T){return T.includes(this.kind)}assertHasKindIn(...T){if(!yF(T,this.kind))qF(`${this.kind} node was not one of asserted kinds ${T}`);return this}isBasis(){return yF(M0,this.kind)}isConstraint(){return yF(TS,this.kind)}isStructural(){return yF(fA,this.kind)}isRefinement(){return yF(gf,this.kind)}isRoot(){return yF($A,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=Ty.normalize(T);return this._select(o)}_select(T){let o=Ty.applyBoundary[T.boundary??"references"](this);if(T.kind)o=o.filter((F)=>F.kind===T.kind);if(T.where)o=o.filter(T.where);return Ty.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 F=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 y=d(this.inner,(J,R)=>{if(!this.impl.keys[J].child)return[J,R];let O=R;if(!HT(O)){let H=O._transform(T,o);return H?[J,H]:[]}if(O.length===0)return[J,R];let Y=O.flatMap((H)=>{return H._transform(T,o)??[]});return Y.length?[J,Y]:[]});delete o.seen[this.id];let S=Object.assign(y,{meta:this.meta}),f=o.selected&&!o.selected.includes(this)?S:T(this.kind,S,o);if(f===null)return null;if(UT(f))return A=f;let $=Object.keys(f);if(($.length===0||$.length===1&&$[0]==="meta")&&!ao(this.inner))return null;if((this.kind==="required"||this.kind==="optional"||this.kind==="index")&&!("value"in f))return o.undeclaredKeyHandling?{...f,value:K.intrinsic.unknown}:null;if(this.kind==="morph")f.in??=K.intrinsic.unknown;return A=F.node(this.kind,f,o.parseOptions)}configureReferences(T,o="references"){let F=Ty.normalize(o),A=typeof T==="string"?($,_)=>({..._,meta:{..._.meta,description:T}}):typeof T==="function"?($,_)=>({..._,meta:T(_.meta)}):($,_)=>({..._,meta:{..._.meta,...T}});if(F.boundary==="self")return this.$.node(this.kind,A(this.kind,{...this.inner,meta:this.meta}));let y=this._select(F),S=y&&KF(y),f=F.boundary==="child"?($,_)=>_.root.children.includes($):F.boundary==="shallow"?($)=>$.kind!=="structure":()=>!0;return this.$.finalize(this.transform(A,{shouldTransform:f,selected:S}))}}var Ty={applyBoundary:{self:(T)=>[T],child:(T)=>[...T.children],shallow:(T)=>[...T.shallowReferences],references:(T)=>[...T.references]},applyMethod:{filter:(T)=>T,assertFilter:(T,o,F)=>{if(T.length===0)qF(H0(o,F));return T},find:(T)=>T[0],assertFind:(T,o,F)=>{if(T.length===0)qF(H0(o,F));return T[0]}},normalize:(T)=>typeof T==="function"?{boundary:"references",method:"filter",where:T}:typeof T==="string"?hT(T,Ty.applyBoundary)?{method:"filter",boundary:T}:{boundary:"references",method:"filter",kind:T}:{boundary:"references",method:"filter",...T}},H0=(T,o)=>`${T} had no references matching ${r(o)}.`,lX=(T)=>JF(T,{stringifyNonKey:(o)=>o.expression}),sX=/"(\$ark\.[^"]+)"/g,aX=(T)=>JSON.stringify(T).replaceAll(sX,"$1"),no=(T,o)=>({path:T,node:o,propString:lX(T)}),G0=(T,o)=>T.propString===o.propString&&T.node.equals(o.node),cf=(T,o)=>so(T,o,{isEqual:G0}),eX=(T,o)=>so(T,o,{isEqual:(F,A)=>F.equals(A)});class k extends Array{static init(T,o,F,A){return new k({kind:T,l:o,r:F,path:A?.path??[],optional:A?.optional??!1})}add(T,o,F,A){return this.push({kind:T,l:o,r:F,path:A?.path??[],optional:A?.optional??!1}),this}get summary(){return this.describeReasons()}describeReasons(){if(this.length===1){let{path:T,l:o,r:F}=this[0],A=JF(T);return rf(`Intersection${A&&` at ${A}`} of ${w0(o,F)}`)}return`The following intersections result in unsatisfiable types:
|
|
23
|
+
\u2022 ${this.map(({path:T,l:o,r:F})=>`${T}: ${w0(o,F)}`).join(`
|
|
24
|
+
\u2022 `)}`}throw(){return G(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((F)=>({...F,path:[T,...F.path],optional:F.optional||o==="optional"}))}toNeverIfDisjoint(){return K.intrinsic.never}}var w0=(T,o)=>`${df(T)} and ${df(o)}`,df=(T)=>UT(T)?T.expression:HT(T)?T.map(df).join(" | ")||"never":String(T),rf=(T)=>`${T} results in an unsatisfiable type`;var RA={},wo=(T,o,F)=>zT(T,o,{$:F,invert:!1,pipe:!1}),Fy=(T,o,F)=>zT(T,o,{$:F,invert:!1,pipe:!0}),zT=(T,o,F)=>{let A=F.pipe?"|>":"&",y=`${T.hash}${A}${o.hash}`;if(RA[y]!==void 0)return RA[y];if(!F.pipe){let $=`${o.hash}${A}${T.hash}`;if(RA[$]!==void 0){let _=RA[$],J=_ instanceof k?_.invert():_;return RA[y]=J,J}}let S=!F.pipe||!T.includesTransform&&!o.includesTransform;if(S&&T.equals(o))return T;let f=S?lf(T,o,F):T.hasKindIn(...$A)?T8(T,o,F):lf(T,o,F);if(UT(f)){if(T.equals(f))f=T;else if(o.equals(f))f=o}return RA[y]=f,f},lf=(T,o,F)=>{let A=T.precedence<o.precedence?T.kind:o.kind,y=T.impl.intersections[o.kind]??o.impl.intersections[T.kind];if(y===void 0)return null;else if(A===T.kind)return y(T,o,F);else{let S=y(o,T,{...F,invert:!F.invert});if(S instanceof k)S=S.invert();return S}},T8=(T,o,F)=>T.includesTransform||o.includesTransform?F.invert?E0(o,T,F):E0(T,o,F):lf(T,o,F),E0=(T,o,F)=>T.distribute((A)=>o8(A,o,F),(A)=>{let y=A.filter(UT);if(y.length===0)return k.init("union",T.branches,o.branches);if(y.length<T.branches.length||!T.branches.every(($,_)=>$.in.equals(y[_].in)))return F.$.parseSchema(y);let S;if(y.length===1){let $=y[0];if(!S)return $;return F.$.node("morph",{...$.inner,in:$.in.configure(S,"self")})}let f={branches:y};if(S)f.meta=S;return F.$.parseSchema(f)}),o8=(T,o,F)=>{if(T.hasKind("morph")){let y=[...T.morphs];if(T.lastMorphIfNode){let S=zT(T.lastMorphIfNode,o,F);if(S instanceof k)return S;y[y.length-1]=S}else y.push(o);return F.$.node("morph",{morphs:y,in:T.inner.in})}if(o.hasKind("morph")){let y=zT(T,o.in,F);if(y instanceof k)return y;return F.$.node("morph",{morphs:[o],in:y})}return F.$.node("morph",{morphs:[o],in:T})};class Bo extends oy{constructor(T,o){super(T,o);Object.defineProperty(this,Ro,{value:"constraint",enumerable:!1})}impliedSiblings;intersect(T){return wo(this,T,this.$)}}class RF 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 VF(this.errorContext)}}var So=(T)=>(o,F)=>{if(HT(o)){if(o.length===0)return;let y=o.map((S)=>F.$.node(T,S));if(T==="predicate")return y;return y.sort((S,f)=>S.hash<f.hash?-1:1)}let A=F.$.node(T,o);return A.hasOpenIntersection()?[A]:A},WA=(T)=>{let o=T.r.shift();if(!o){let A=T.l.length===0&&T.kind==="structure"?K.intrinsic.unknown.internal:T.ctx.$.node(T.kind,Object.assign(T.baseInner,F8(T.l)),{prereduced:!0});for(let y of T.roots){if(A instanceof k)return A;A=zT(y,A,T.ctx)}return A}let F=!1;for(let A=0;A<T.l.length;A++){let y=zT(T.l[A],o,T.ctx);if(y===null)continue;if(y instanceof k)return y;if(!F){if(y.isRoot())return T.roots.push(y),T.l.splice(A),WA(T);T.l[A]=y,F=!0}else if(!T.l.includes(y))return $T(`Unexpectedly encountered multiple distinct intersection results for refinement ${y}`)}if(!F)T.l.push(o);if(T.kind==="intersection"){if(o.impliedSiblings)for(let A of o.impliedSiblings)so(T.r,A)}return WA(T)},MA=(T)=>{return Object.entries(T).flatMap(([F,A])=>(F in oS)?A:[]).sort((F,A)=>F.precedence<A.precedence?-1:F.precedence>A.precedence?1:F.kind==="predicate"&&A.kind==="predicate"?0:F.hash<A.hash?-1:1)},F8=(T)=>{let o={};for(let F of T)if(F.hasOpenIntersection())o[F.kind]=yT(o[F.kind],F);else{if(o[F.kind])return $T(`Unexpected intersection of closed refinements of kind ${F.kind}`);o[F.kind]=F}return o},K0=(...T)=>G(U0(...T)),U0=(T,o,F)=>{let A=F.hasKind("morph")?"a morph":F.isUnknown()?"unknown":F.exclude(o).defaultShortDescription;return`${s_(T)} operand must be ${o.description} (was ${A})`};var z0=(T,o,F)=>new LF(T,o,F,F,null);class AS extends ho{}class LF extends ho{[Ro]="generic";paramDefs;bodyDef;$;arg$;baseInstantiation;hkt;description;constructor(T,o,F,A,y){super((...S)=>{let f=d(this.names,($,_)=>{let J=this.arg$.parse(S[$]);if(!J.extends(this.constraints[$]))G(A8(_,this.constraints[$].expression,J.expression));return[_,J]});if(this.defIsLazy()){let $=this.bodyDef(f);return this.$.parse($)}return this.$.parse(o,{args:f})});this.paramDefs=T,this.bodyDef=o,this.$=F,this.arg$=A,this.hkt=y,this.description=y?new y().description??`a generic type for ${y.constructor.name}`:"a generic type",this.baseInstantiation=this(...this.constraints)}defIsLazy(){return this.bodyDef instanceof AS}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:J0(this.bodyDef)})}get params(){return this.cacheGetter("params",this.paramDefs.map((T)=>typeof T==="string"?[T,K.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 A8=(T,o,F)=>`${T} must be assignable to ${o} (was ${F})`;var y8=l({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 Q0 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=VF(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(T,o){return o.fallback.predicate({code:"predicate",base:T,predicate:this.predicate})}}var sf={implementation:y8,Node:Q0};var S8=l({kind:"divisor",collapsibleKey:"rule",keys:{rule:{parse:(T)=>Number.isInteger(T)?T:G(f8(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,F)=>F.$.node("divisor",{rule:Math.abs(T.rule*o.rule/$8(T.rule,o.rule))})},obviatesBasisDescription:!0});class V0 extends RF{traverseAllows=(T)=>T%this.rule===0;compiledCondition=`data % ${this.rule} === 0`;compiledNegation=`data % ${this.rule} !== 0`;impliedBasis=K.intrinsic.number.internal;expression=`% ${this.rule}`;reduceJsonSchema(T){if(T.type="integer",this.rule===1)return T;return T.multipleOf=this.rule,T}}var af={implementation:S8,Node:V0};var f8=(T)=>`divisor must be an integer (was ${T})`,$8=(T,o)=>{let F,A=T,y=o;while(y!==0)F=y,y=A%y,A=F;return A};class Vo extends RF{boundOperandKind=W8[this.kind];compiledActual=this.boundOperandKind==="value"?"data":this.boundOperandKind==="length"?"data.length":"data.valueOf()";comparator=M8(this.kind,this.exclusive);numericLimit=this.rule.valueOf();expression=`${this.comparator} ${this.rule}`;compiledCondition=`${this.compiledActual} ${this.comparator} ${this.numericLimit}`;compiledNegation=`${this.compiledActual} ${J8[this.comparator]} ${this.numericLimit}`;stringLimit=this.boundOperandKind==="date"?O8(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 J8={"<":">=","<=":">",">":"<=",">=":"<"},_8={min:"max",minLength:"maxLength",after:"before"},yS={parse:(T)=>T||void 0},SS=(T)=>(o)=>{if(typeof o==="number")return{rule:o};let{exclusive:F,...A}=o;return F?{...A,rule:T==="minLength"?A.rule+1:A.rule-1}:A},fS=(T)=>(o)=>{if(typeof o==="number"||typeof o==="string"||o instanceof Date)return{rule:o};let{exclusive:F,...A}=o;if(!F)return A;let y=typeof A.rule==="number"?A.rule:typeof A.rule==="string"?new Date(A.rule).valueOf():A.rule.valueOf();return F?{...A,rule:T==="after"?y+1:y-1}:A},$S=(T)=>typeof T==="string"||typeof T==="number"?new Date(T):T,R8=(T,o)=>`${T} bound must be a positive integer (was ${o})`,OA=(T)=>(o)=>{if(!Number.isInteger(o)||o<0)G(R8(T,o));return o},W8={min:"value",max:"value",minLength:"length",maxLength:"length",after:"date",before:"date"},M8=(T,o)=>`${hT(T,_8)?">":"<"}${o?"":"="}`,O8=(T)=>typeof T==="string"?T:new Date(T).toLocaleString(),D0=(T)=>`Bounded expression ${T} must be exactly one of number, string, Array, or Date`;var X8=l({kind:"after",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:$S,serialize:(T)=>T.toISOString()}},normalize:fS("after"),defaults:{description:(T)=>`${T.collapsibleLimitString} or later`,actual:tF},intersections:{after:(T,o)=>T.isStricterThan(o)?T:o}});class L0 extends Vo{impliedBasis=K.intrinsic.Date.internal;collapsibleLimitString=tF(this.rule);traverseAllows=(T)=>T>=this.rule;reduceJsonSchema(T,o){return o.fallback.date({code:"date",base:T,after:this.rule})}}var ef={implementation:X8,Node:L0};var Y8=l({kind:"before",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:$S,serialize:(T)=>T.toISOString()}},normalize:fS("before"),defaults:{description:(T)=>`${T.collapsibleLimitString} or earlier`,actual:tF},intersections:{before:(T,o)=>T.isStricterThan(o)?T:o,after:(T,o,F)=>T.overlapsRange(o)?T.overlapIsUnit(o)?F.$.node("unit",{unit:T.rule}):null:k.init("range",T,o)}});class C0 extends Vo{collapsibleLimitString=tF(this.rule);traverseAllows=(T)=>T<=this.rule;impliedBasis=K.intrinsic.Date.internal;reduceJsonSchema(T,o){return o.fallback.date({code:"date",base:T,before:this.rule})}}var T$={implementation:Y8,Node:C0};var Z8=l({kind:"exactLength",collapsibleKey:"rule",keys:{rule:{parse:OA("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,F)=>k.init("unit",F.$.node("unit",{unit:T.rule}),F.$.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 I0 extends RF{traverseAllows=(T)=>T.length===this.rule;compiledCondition=`data.length === ${this.rule}`;compiledNegation=`data.length !== ${this.rule}`;impliedBasis=K.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 LT.throwInternalOperandError("exactLength",T)}}}var o$={implementation:Z8,Node:I0};var H8=l({kind:"max",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{},exclusive:yS},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,F)=>T.overlapsRange(o)?T.overlapIsUnit(o)?F.$.node("unit",{unit:T.rule}):null:k.init("range",T,o)},obviatesBasisDescription:!0});class k0 extends Vo{impliedBasis=K.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 F$={implementation:H8,Node:k0};var G8=l({kind:"maxLength",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:OA("maxLength")}},reduce:(T,o)=>T.rule===0?o.node("exactLength",T):void 0,normalize:SS("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,F)=>T.overlapsRange(o)?T.overlapIsUnit(o)?F.$.node("exactLength",{rule:T.rule}):null:k.init("range",T,o)}});class B0 extends Vo{impliedBasis=K.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 LT.throwInternalOperandError("maxLength",T)}}}var A$={implementation:G8,Node:B0};var w8=l({kind:"min",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{},exclusive:yS},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 N0 extends Vo{impliedBasis=K.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 y$={implementation:w8,Node:N0};var E8=l({kind:"minLength",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:OA("minLength")}},reduce:(T)=>T.rule===0?K.intrinsic.unknown:void 0,normalize:SS("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 p0 extends Vo{impliedBasis=K.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 LT.throwInternalOperandError("minLength",T)}}}var S$={implementation:E8,Node:p0};var j0={min:y$.implementation,max:F$.implementation,minLength:S$.implementation,maxLength:A$.implementation,exactLength:o$.implementation,after:ef.implementation,before:T$.implementation},x0={min:y$.Node,max:F$.Node,minLength:S$.Node,maxLength:A$.Node,exactLength:o$.Node,after:ef.Node,before:T$.Node};var K8=l({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 b0 extends RF{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=K.intrinsic.string.internal;reduceJsonSchema(T,o){if(T.pattern)return o.fallback.patternIntersection({code:"patternIntersection",base:T,pattern:this.rule});return T.pattern=this.rule,T}}var f$={implementation:K8,Node:b0};var Ay=(T,o)=>{let F=U8(T);if(o&&!o.includes(F))return G(`Root of kind ${F} should be one of ${o}`);return F},U8=(T)=>{if(P(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 G(q0(T));if("morphs"in T)return"morph";if("branches"in T||HT(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((F)=>(F in oS)))return"intersection";if("proto"in T)return"proto";if("domain"in T)return"domain";return G(q0(T))},q0=(T)=>`${r(T)} is not a valid type schema`,v0={},z8=(T)=>HT(T)?T.map((o)=>o.collapsibleJson):T.collapsibleJson,Wo={};K.nodesByRegisteredId=Wo;var $$=(T)=>{return v0[T]??=0,`${T}${++v0[T]}`},J$=(T)=>{let o=XA[T.kind],F=o.applyConfig?.(T.def,T.$.resolvedConfig)??T.def,A={},{meta:y,...S}=F,f=y===void 0?{}:typeof y==="string"?{description:y}:y,$=kf(S).sort(([J],[R])=>JA(J)?JA(R)?_A(J)-_A(R):1:JA(R)?-1:J<R?-1:1).filter(([J,R])=>{if(J.startsWith("meta.")){let O=J.slice(5);return f[O]=R,!1}return!0});for(let J of $){let R=J[0],O=o.keys[R];if(!O)return G(`Key ${R} is not valid on ${T.kind} schema`);let Y=O.parse?O.parse(J[1],T):J[1];if(Y!==Qo&&(Y!==void 0||O.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 Q8(J,f)}}return _$({id:T.id,kind:T.kind,inner:A,meta:f,$:T.$})},_$=({id:T,kind:o,inner:F,meta:A,$:y,ignoreCache:S})=>{let f=XA[o],$=kf(F),_=[],J={};for(let[p,v]of $){let h=f.keys[p],U=h.serialize??(h.child?z8:ko);if(J[p]=U(v),h.child===!0){let V=v;if(HT(V))_.push(...V);else _.push(V)}else if(typeof h.child==="function")_.push(...h.child(v))}if(f.finalizeInnerJson)J=f.finalizeInnerJson(J);let R={...J},O={};if(!ao(A))O=d(A,(p,v)=>[p,p==="examples"?v:ko(v)]),R.meta=JS(O,"description",!0);J=JS(J,f.collapsibleKey,!1);let Y=JSON.stringify({kind:o,...J});R=JS(R,f.collapsibleKey,!1);let H=JS(R,f.collapsibleKey,!0),Q=JSON.stringify({kind:o,...R});if(y.nodesByHash[Q]&&!S)return y.nodesByHash[Q];let E={id:T,kind:o,impl:f,inner:F,innerEntries:$,innerJson:J,innerHash:Y,meta:A,metaJson:O,json:R,hash:Q,collapsibleJson:H,children:_};if(o!=="intersection"){for(let p in F)if(p!=="in"&&p!=="out")E[p]=F[p]}let B=new m0[o](E,y);return y.nodesByHash[Q]=B},P0=(T,o)=>{if(T.id===o)return T;if(UT(Wo[o]))$T(`Unexpected attempt to overwrite node id ${o}`);return _$({id:o,kind:T.kind,inner:T.inner,meta:T.meta,$:T.$,ignoreCache:!0})},Q8=(T,o,F)=>{if(F&&UT(Wo[F]))$T(`Unexpected attempt to overwrite node id ${F}`);return _$({id:F??$$(o.alias??T.kind),kind:T.kind,inner:T.inner,meta:o,$:T.$})},JS=(T,o,F)=>{let A=Object.keys(T);if(A.length===1&&A[0]===o){let y=T[o];if(F)return y;if(Yo(y,"object")&&(Object.keys(y).length===1||Array.isArray(y)))return y}return T};var yy=(T,o,F)=>{if(T.key!==o.key)return null;let A=T.key,y=zT(T.value,o.value,F),S=T.required||o.required?"required":"optional";if(y instanceof k)if(S==="optional")y=K.intrinsic.never.internal;else return y.withPrefixKey(T.key,T.required&&o.required?"required":"optional");if(S==="required")return F.$.node("required",{key:A,value:y});let f=T.hasDefault()?o.hasDefault()?T.default===o.default?T.default:G(R$(T.default,o.default)):T.default:o.hasDefault()?o.default:Qo;return F.$.node("optional",{key:A,value:y,default:f})};class Sy extends Bo{required=this.kind==="required";optional=this.kind==="optional";impliedBasis=K.intrinsic.object.internal;serializedKey=_F(this.key);compiledKey=typeof this.key==="string"?this.key:this.serializedKey;flatRefs=yT(this.value.flatRefs.map((T)=>no([this.key,...T.path],T.node)),no([this.key],this.value));_transform(T,o){o.path.push(this.key);let F=super._transform(T,o);return o.path.pop(),F}hasDefault(){return"default"in this.inner}traverseAllows=(T,o)=>{if(this.key in T)return Go(this.key,()=>this.value.traverseAllows(T[this.key],o),o);return this.optional};traverseApply=(T,o)=>{if(this.key in T)Go(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(()=>T.traversalKind==="Apply"?T.line(`ctx.errorFromNodeContext(${this.compiledErrorContext})`):T.return(!1));if(T.traversalKind==="Allows")T.return(!0)}}var R$=(T,o)=>`Invalid intersection of default values ${r(T)} & ${r(o)}`;var V8=l({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(n.undefined)},{prereduced:!0})}},defaults:{description:(T)=>`${T.compiledKey}?: ${T.value.description}`},intersections:{optional:yy}});class t0 extends Sy{constructor(...T){super(...T);if("default"in this.inner)$y(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} = ${r(this.inner.default)}`:`${this.compiledKey}?: ${this.value.expression}`;defaultValueMorph=L8(this);defaultValueMorphRef=this.defaultValueMorph&&BT(this.defaultValueMorph)}var fy={implementation:V8,Node:t0},D8={},L8=(T)=>{if(!T.hasDefault())return;let o=`{${T.compiledKey}: ${T.value.id} = ${ko(T.default)}}`;return D8[o]??=W$(T.key,T.value,T.default)},W$=(T,o,F)=>{if(typeof F==="function")return o.includesTransform?(y,S)=>{return Go(T,()=>o(y[T]=F(),S),S),y}:(y)=>{return y[T]=F(),y};let A=o.includesTransform?o.assert(F):F;return Yo(A,"object")?(y,S)=>{return Go(T,()=>o(y[T]=F,S),S),y}:(y)=>{return y[T]=A,y}},$y=(T,o,F)=>{let A=UF(o);if(Yo(o,"object")&&!A)G(C8(F));let y=T.in(A?o():o);if(y instanceof Ho){if(F===null)G(`Default ${y.summary}`);let S=y.transform((f)=>f.transform(($)=>({...$,prefixPath:[F]})));G(`Default for ${S.summary}`)}return o},C8=(T)=>{return`Non-primitive default ${T===null?"":typeof T==="number"?`for value at [${T}] `:`for ${_F(T)} `}must be specified as a function like () => ({my: 'object'})`};class No extends oy{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 G(I8);return this}readonly(){return this}branches=this.hasKind("union")?this.inner.branches:[this];distribute(T,o){let F=this.branches.map(T);return o?.(F)??F}get shortDescription(){return this.meta.description??this.defaultShortDescription}toJsonSchema(T={}){let o=nf(this.$.resolvedConfig.toJsonSchema,T);o.useRefs||=this.isCyclic;let F=typeof o.dialect==="string"?{$schema:o.dialect}:{};if(Object.assign(F,this.toJsonSchemaRecurse(o)),o.useRefs)F.$defs=d(this.references,(A,y)=>y.isRoot()&&!y.alwaysExpandJsonSchema?[y.id,y.toResolvedJsonSchema(o)]:[]);return F}toJsonSchemaRecurse(T){if(T.useRefs&&!this.alwaysExpandJsonSchema)return{$ref:`#/$defs/${this.id}`};return this.toResolvedJsonSchema(T)}get alwaysExpandJsonSchema(){return this.isBasis()||this.kind==="alias"||this.hasKind("union")&&this.isBoolean}toResolvedJsonSchema(T){let o=this.innerToJsonSchema(T);return Object.assign(o,this.metaJson)}intersect(T){let o=this.$.parseDefinition(T),F=this.rawIntersect(o);if(F instanceof k)return F;return this.$.finalize(F)}rawIntersect(T){return wo(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,F)=>o.intersect(F).toNeverIfDisjoint(),K.intrinsic.unknown.internal);if(T.branches.length===0)G(rf(`keyof ${this.expression}`));return this._keyof=this.$.finalize(T)}get props(){if(this.branches.length!==1)return G(k8(this.expression));return[...this.applyStructuralOperation("props",[])[0]]}merge(T){let o=this.$.parseDefinition(T);return this.$.schema(o.distribute((F)=>this.applyStructuralOperation("merge",[h0(F)??G(g0("merge",F.expression))])))}applyStructuralOperation(T,o){return this.distribute((F)=>{if(F.equals(K.intrinsic.object)&&T!=="merge")return F;let A=h0(F);if(!A)G(g0(T,F.expression));if(T==="keyof")return A.keyof();if(T==="get")return A.get(...o);if(T==="props")return A.props;let y=T==="required"?"require":T==="partial"?"optionalize":T;return this.$.node("intersection",{...F.inner,structure:A[y](...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((F)=>F.extends(o)))}exclude(T){let o=this.$.parseDefinition(T);return this.$.schema(this.branches.filter((F)=>!F.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 $y(this,T,null),[this,"=",T]}from(T){return this.assert(T)}_pipe(...T){let o=T.reduce((F,A)=>F.rawPipeOnce(A),this);return this.$.finalize(o)}tryPipe(...T){let o=T.reduce((F,A)=>F.rawPipeOnce(P(A,"root")?A:(y,S)=>{try{return A(y,S)}catch(f){return S.error({code:"predicate",predicate:A,actual:`aborted due to error:
|
|
19
25
|
${f}
|
|
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=
|
|
21
|
-
${T}`,
|
|
26
|
+
`})}}),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=Fy(this,T,this.$);if(o instanceof k)return o.throw();return o}rawPipeOnce(T){if(P(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,F){let A=this.$.node(o,F);if(A.isRoot())return A.isUnknown()?this:$T(`Unexpected constraint node ${A}`);let y=T==="root"?this:this[T];if(y.hasKind("morph")||A.impliedBasis&&!y.extends(A.impliedBasis))return K0(o,A.impliedBasis,this);let S=this.$.node("intersection",{[A.kind]:A}),f=T==="out"?Fy(this,S,this.$):wo(this,S,this.$);if(f instanceof k)f.throw();return this.$.finalize(f)}onUndeclaredKey(T){let o=typeof T==="string"?T:T.rule,F=typeof T==="string"?!1:T.deep;return this.$.finalize(this.transform((A,y)=>A==="structure"?o==="ignore"?m_(y,{undeclared:1}):{...y,undeclared:o}:y,F?void 0:{shouldTransform:(A)=>!yF(fA,A.kind)}))}hasEqualMorphs(T){if(!this.includesTransform&&!T.includesTransform)return!0;if(!fF(this.shallowMorphs,T.shallowMorphs))return!1;if(!fF(this.flatMorphs,T.flatMorphs,{isEqual:(o,F)=>o.propString===F.propString&&(o.node.hasKind("morph")&&F.node.hasKind("morph")?o.node.hasEqualMorphs(F.node):o.node.hasKind("intersection")&&F.node.hasKind("intersection")?o.node.structure?.structuralMorphRef===F.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",YA(T))}lessThan(T){return this.constrain("max",YA(T))}atLeastLength(T){return this.constrain("minLength",T)}atMostLength(T){return this.constrain("maxLength",T)}moreThanLength(T){return this.constrain("minLength",YA(T))}lessThanLength(T){return this.constrain("maxLength",YA(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",YA(T))}earlierThan(T){return this.constrain("before",YA(T))}}var I8="Expected a non-empty brand name after #",YA=(T)=>typeof T==="object"&&!(T instanceof Date)?{...T,exclusive:!0}:{rule:T,exclusive:!0},Jy=(T,o)=>P(o,"root")?P(T,"root")?T.extends(o):o.allows(T):P(T,"root")?T.hasUnit(o):o===T,h0=(T)=>{if(T.hasKind("morph"))return null;if(T.hasKind("intersection"))return T.inner.structure??(T.basis?.domain==="object"?T.$.bindReference(K.intrinsic.emptyStructure):null);if(T.isBasis()&&T.domain==="object")return T.$.bindReference(K.intrinsic.emptyStructure);return null},k8=(T)=>`Props cannot be extracted from a union. Use .distribute to extract props from each branch instead. Received:
|
|
27
|
+
${T}`,g0=(T,o)=>`${T} operand must be an object (was ${o})`;var eo=(T,o)=>d(FS(T),(F,A)=>[A,o]);var B8=(T)=>typeof T==="string"?{reference:T}:T,n0=(T)=>T instanceof k?K.intrinsic.never.internal:T,N8=l({kind:"alias",hasAssociatedError:!1,collapsibleKey:"reference",keys:{reference:{serialize:(T)=>T.startsWith("$")?T:`$ark.${T}`},resolve:{}},normalize:B8,defaults:{description:(T)=>T.reference},intersections:{alias:(T,o,F)=>F.$.lazilyResolve(()=>n0(zT(T.resolution,o.resolution,F)),`${T.reference}${F.pipe?"=>":"&"}${o.reference}`),...eo("alias",(T,o,F)=>{if(o.isUnknown())return T;if(o.isNever())return o;if(o.isBasis()&&!o.overlaps(K.intrinsic.object))return k.init("assignability",K.intrinsic.object,o);return F.$.lazilyResolve(()=>n0(zT(T.resolution,o,F)),`${T.reference}${F.pipe?"=>":"&"}${o.id}`)})}});class u0 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],F=[];while(P(o,"context")){if(F.includes(o.id))return G(p8(o.id,F));F.push(o.id),o=Wo[o.id]}if(!P(o,"root"))return $T(`Unexpected resolution for reference ${this.reference}
|
|
22
28
|
Seen: [${F.join("->")}]
|
|
23
|
-
Resolution: ${
|
|
29
|
+
Resolution: ${r(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(P(o,"root"))return o.id;return $T(`Unexpected resolution for reference ${this.reference}: ${r(o)}`)}get defaultShortDescription(){return Zo.object}innerToJsonSchema(T){return this.resolution.toJsonSchemaRecurse(T)}traverseAllows=(T,o)=>{let F=o.seen[this.reference];if(F?.includes(T))return!0;return o.seen[this.reference]=yT(F,T),this.resolution.traverseAllows(T,o)};traverseApply=(T,o)=>{let F=o.seen[this.reference];if(F?.includes(T))return;o.seen[this.reference]=yT(F,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 p8=(T,o)=>`Alias '${T}' has a shallow resolution cycle: ${[...o,T].join("->")}`,_y={implementation:N8,Node:u0};class hF 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 VF(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 j8=l({kind:"domain",hasAssociatedError:!0,collapsibleKey:"domain",keys:{domain:{},numberAllowsNaN:{}},normalize:(T)=>typeof T==="string"?{domain:T}:yA(T,"numberAllowsNaN")&&T.domain!=="number"?G(_S.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[tT(T)]},intersections:{domain:(T,o)=>T.domain==="number"&&o.domain==="number"?T.numberAllowsNaN?o:T:k.init("domain",T,o)}});class c0 extends hF{requiresNaNCheck=this.domain==="number"&&!this.numberAllowsNaN;traverseAllows=this.requiresNaNCheck?(T)=>typeof T==="number"&&!Number.isNaN(T):(T)=>tT(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 T.fallback.domain({code:"domain",base:{},domain:this.domain});return{type:this.domain}}}var _S={implementation:j8,Node:c0,writeBadAllowNanMessage:(T)=>`numberAllowsNaN may only be specified with domain "number" (was ${T})`};var x8=l({kind:"intersection",hasAssociatedError:!0,normalize:(T)=>{if(UT(T))return T;let{structure:o,...F}=T,A=!!o,y=o??{},S=d(F,(f,$)=>{if(hT(f,O0)){if(A)G(`Flattened structure key ${f} cannot be specified alongside a root 'structure' key.`);return y[f]=$,[]}return[f,$]});if(P(y,"constraint")||!ao(y))S.structure=y;return S},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,...F}=T.collapsibleJson,{minVariadicLength:A,...y}=o,S=y.variadic&&Object.keys(y).length===1?y.variadic:y;return{...F,sequence:S}}},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)=>i0({},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((F)=>F.impl.obviatesBasisDescription))o.push(T.basis.description);if(T.refinements.length){let F=T.refinements.toSorted((A,y)=>A.kind==="min"&&y.kind==="max"?-1:0).map((A)=>A.description);o.push(...F)}if(T.inner.predicate)o.push(...T.inner.predicate.map((F)=>F.description));return o.join(" and ")},expected:(T)=>` \u25E6 ${T.errors.map((o)=>o.expected).join(`
|
|
24
30
|
\u25E6 `)}`,problem:(T)=>`(${T.actual}) must be...
|
|
25
|
-
${T.expected}`},intersections:{intersection:(T,o,F)=>
|
|
31
|
+
${T.expected}`},intersections:{intersection:(T,o,F)=>i0(T.inner,o.inner,F),...eo("intersection",(T,o,F)=>{if(T.children.length===0)return o;let{domain:A,proto:y,...S}=T.inner,f=y??A,$=f?zT(f,o,F):o;return $ instanceof k?$:T?.basis?.equals($)?T:T.$.node("intersection",{...S,[$.kind]:$},{prereduced:!0})})}});class d0 extends No{basis=this.inner.domain??this.inner.proto??null;refinements=this.children.filter((T)=>T.isRefinement());structure=this.inner.structure;expression=b8(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,F)=>F.isBasis()?F.toJsonSchemaRecurse(T):F.reduceJsonSchema(o,T),{})}traverseAllows=(T,o)=>this.children.every((F)=>F.traverseAllows(T,o));traverseApply=(T,o)=>{let F=o.currentErrorCount;if(this.basis){if(this.basis.traverseApply(T,o),o.currentErrorCount>F)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>F)return;if(this.refinements.at(-1).traverseApply(T,o),o.currentErrorCount>F)return}if(this.structure){if(this.structure.traverseApply(T,o),o.currentErrorCount>F)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>F)return;this.inner.predicate.at(-1).traverseApply(T,o)}};compile(T){if(T.traversalKind==="Allows"){for(let o of this.children)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 M$={implementation:x8,Node:d0},b8=(T)=>{let o=T.structure?.expression||`${T.basis&&!T.refinements.some((F)=>F.impl.obviatesBasisExpression)?T.basis.nestableExpression+" ":""}${T.refinements.map((F)=>F.expression).join(" & ")}`||"unknown";if(o==="Array == 0")o="[]";return o},i0=(T,o,F)=>{let A={},y=T.proto??T.domain,S=o.proto??o.domain,f=y?S?zT(y,S,F):y:S;if(f instanceof k)return f;if(f)A[f.kind]=f;return WA({kind:"intersection",baseInner:A,l:MA(T),r:MA(o),roots:[],ctx:F})};var q8=l({kind:"morph",hasAssociatedError:!1,keys:{in:{child:!0,parse:(T,o)=>o.$.parseSchema(T)},morphs:{parse:KF,serialize:(T)=>T.map((o)=>P(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,F)=>{if(!T.hasEqualMorphs(o))return G(v8(T.expression,o.expression));let A=zT(T.in,o.in,F);if(A instanceof k)return A;let y={morphs:T.morphs};if(T.declaredIn||o.declaredIn){let S=zT(T.in,o.in,F);if(S instanceof k)return S.throw();else y.declaredIn=S}if(T.declaredOut||o.declaredOut){let S=zT(T.out,o.out,F);if(S instanceof k)return S.throw();else y.declaredOut=S}return A.distribute((S)=>F.$.node("morph",{...y,in:S}),F.$.parseSchema)},...eo("morph",(T,o,F)=>{let A=T.inner.in?zT(T.inner.in,o,F):o;return A instanceof k?A:A.equals(T.inner.in)?T:F.$.node("morph",{...T.inner,in:A})})}});class r0 extends No{serializedMorphs=this.morphs.map(BT);compiledMorphs=`[${this.serializedMorphs}]`;lastMorph=this.inner.morphs.at(-1);lastMorphIfNode=P(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??K.intrinsic.unknown.internal}get out(){return this.declaredOut??this.introspectableOut??K.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 T.fallback.morph({code:"morph",base:this.in.toJsonSchemaRecurse(T),out:this.introspectableOut?.toJsonSchemaRecurse(T)??null})}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 fF(this.morphs,T.morphs,{isEqual:(o,F)=>o===F||P(o,"root")&&P(F,"root")&&o.equals(F)})}}var O$={implementation:q8,Node:r0},v8=(T,o)=>`The intersection of distinct morphs at a single path is indeterminate:
|
|
26
32
|
Left: ${T}
|
|
27
|
-
Right: ${o}`;var
|
|
33
|
+
Right: ${o}`;var P8=l({kind:"proto",hasAssociatedError:!0,collapsibleKey:"proto",keys:{proto:{serialize:(T)=>uA(T)??ko(T)},dateAllowsInvalid:{}},normalize:(T)=>{let o=typeof T==="string"?{proto:PF[T]}:typeof T==="function"?UT(T)?T:{proto:T}:typeof T.proto==="string"?{...T,proto:PF[T.proto]}:T;if(typeof o.proto!=="function")G(Ry.writeInvalidSchemaMessage(o.proto));if(yA(o,"dateAllowsInvalid")&&o.proto!==Date)G(Ry.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?n_[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:xf(T.proto,o.proto)?T:xf(o.proto,T.proto)?o:k.init("proto",T,o),domain:(T,o)=>o.domain==="object"?T:k.init("domain",K.intrinsic.object.internal,o)}});class l0 extends hF{builtinName=uA(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"};case"Date":return T.fallback.date?.({code:"date",base:{}})??T.fallback.proto({code:"proto",base:{},proto:this.proto});default:return T.fallback.proto({code:"proto",base:{},proto:this.proto})}}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 Ry={implementation:P8,Node:l0,writeBadInvalidDateMessage:(T)=>`dateAllowsInvalid may only be specified with constructor Date (was ${T.name})`,writeInvalidSchemaMessage:(T)=>`instanceOf operand must be a function (was ${tT(T)})`};var m8=l({kind:"union",hasAssociatedError:!0,collapsibleKey:"branches",keys:{ordered:{},branches:{child:!0,parse:(T,o)=>{let F=[];for(let A of T){let y=P(A,"root")?A.branches:o.$.parseSchema(A).branches;for(let S of y)if(S.hasKind("morph")){let f=F.findIndex(($)=>$.hasKind("morph")&&$.hasEqualMorphs(S));if(f===-1)F.push(S);else{let $=F[f];F[f]=o.$.node("morph",{...$.inner,in:$.in.rawOr(S.in)})}}else F.push(S)}if(!o.def.ordered)F.sort((A,y)=>A.hash<y.hash?-1:1);return F}}},normalize:(T)=>HT(T)?{branches:T}:T,reduce:(T,o)=>{let F=l8(T);if(F.length===1)return F[0];if(F.length===T.branches.length)return;return o.node("union",{...T,branches:F},{prereduced:!0})},defaults:{description:(T)=>T.distribute((o)=>o.description,ZA),expected:(T)=>{let o=b_(T.errors,"propString"),F=Object.entries(o).map(([A,y])=>{let S=[];for(let _ of y)so(S,_.expected);let f=ZA(S),$=y.every((_)=>_.actual===y[0].actual)?y[0].actual:r(y[0].data);return`${A&&`${A} `}must be ${f}${$&&` (was ${$})`}`});return ZA(F)},problem:(T)=>T.expected,message:(T)=>T.problem},intersections:{union:(T,o,F)=>{if(T.isNever!==o.isNever)return k.init("presence",T,o);let A;if(T.ordered){if(o.ordered)G(a8(T.expression,o.expression));if(A=X$(o.branches,T.branches,F),A instanceof k)A.invert()}else A=X$(T.branches,o.branches,F);if(A instanceof k)return A;return F.$.parseSchema(T.ordered||o.ordered?{branches:A,ordered:!0}:{branches:A})},...eo("union",(T,o,F)=>{let A=X$(T.branches,[o],F);if(A instanceof k)return A;if(A.length===1)return A[0];return F.$.parseSchema(T.ordered?{branches:A,ordered:!0}:{branches:A})})}});class e0 extends No{isBoolean=this.branches.length===2&&this.branches[0].hasUnit(!1)&&this.branches[1].hasUnit(!0);get branchGroups(){let T=[],o=-1;for(let F of this.branches){if(F.hasKind("unit")&&F.domain==="boolean"){if(o===-1)o=T.length,T.push(F);else T[o]=K.intrinsic.boolean;continue}T.push(F)}return T}unitBranches=this.branches.filter((T)=>T.in.hasKind("unit"));discriminant=this.discriminate();discriminantJson=this.discriminant?i8(this.discriminant):null;expression=this.distribute((T)=>T.nestableExpression,r8);createBranchedOptimisticRootApply(){return(T,o)=>{let F=this.traverseOptimistic(T);if(F!==Qo)return F;let A=new go(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,ZA)}innerToJsonSchema(T){if(this.branchGroups.length===1&&this.branchGroups[0].equals(K.intrinsic.boolean))return{type:"boolean"};let o=this.branchGroups.map((F)=>F.toJsonSchemaRecurse(T));if(o.every((F)=>Object.keys(F).length===1&&yA(F,"const")))return{enum:o.map((F)=>F.const)};return{anyOf:o}}traverseAllows=(T,o)=>this.branches.some((F)=>F.traverseAllows(T,o));traverseApply=(T,o)=>{let F=[];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()}F.push(o.popBranch().error)}o.errorFromNodeContext({code:"union",errors:F,meta:this.meta})};traverseOptimistic=(T)=>{for(let o=0;o<this.branches.length;o++){let F=this.branches[o];if(F.traverseAllows(T)){if(F.contextFreeMorph)return F.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 F=this.discriminant.cases,A=Object.keys(F),{optimistic:y}=T;if(T.optimistic=!1,T.block(`switch(${o})`,()=>{for(let J in F){let R=F[J],O=J==="default"?J:`case ${J}`;T.line(`${O}: return ${R===!0?y?T.data:R:y?`${T.invoke(R)} ? ${R.contextFreeMorph?`${BT(R.contextFreeMorph)}(${T.data})`:T.data} : "${Qo}"`:T.invoke(R)}`)}return T}),T.traversalKind==="Allows"){T.return(y?`"${Qo}"`:!1);return}let S=ZA(this.discriminant.kind==="domain"?A.map((J)=>{let R=J.slice(1,-1);return R==="function"?Zo.object:Zo[R]}):A),f=this.discriminant.path.map((J)=>typeof J==="symbol"?BT(J):JSON.stringify(J)),$=JSON.stringify(S),_=this.discriminant.kind==="domain"?`${u8}[${o}]`:`${c8}(${o})`;T.line(`ctx.errorFromNodeContext({
|
|
28
34
|
code: "predicate",
|
|
29
35
|
expected: ${$},
|
|
30
36
|
actual: ${_},
|
|
31
37
|
relativePath: [${f}],
|
|
32
38
|
meta: ${this.compiledMeta}
|
|
33
|
-
})`)}compileIndiscriminable(T){if(T.traversalKind==="Apply")T.const("errors","[]")
|
|
39
|
+
})`)}compileIndiscriminable(T){if(T.traversalKind==="Apply"){T.const("errors","[]");for(let o of this.branches)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;for(let F of this.branches)T.if(`${T.invoke(F)}`,()=>T.return(o?F.contextFreeMorph?`${BT(F.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||this.isCyclic)return null;if(this.unitBranches.length===this.branches.length){let y=d(this.unitBranches,(S,f)=>[`${f.in.serializedValue}`,f.hasKind("morph")?f:!0]);return{kind:"unit",path:[],optionallyChainedPropString:"data",cases:y}}let T=[];for(let y=0;y<this.branches.length-1;y++){let S=this.branches[y];for(let f=y+1;f<this.branches.length;f++){let $=this.branches[f],_=wo(S.in,$.in,S.$);if(!(_ instanceof k))continue;for(let J of _){if(!J.kind||J.optional)continue;let R,O;if(J.kind==="domain"){let{l:H,r:Q}=J;R=`"${typeof H==="string"?H:H.domain}"`,O=`"${typeof Q==="string"?Q:Q.domain}"`}else if(J.kind==="unit")R=J.l.serializedValue,O=J.r.serializedValue;else continue;let Y=T.find((H)=>fF(H.path,J.path)&&H.kind===J.kind);if(!Y)T.push({kind:J.kind,cases:{[R]:{branchIndices:[y],condition:J.l},[O]:{branchIndices:[f],condition:J.r}},path:J.path});else{if(Y.cases[R])Y.cases[R].branchIndices=so(Y.cases[R].branchIndices,y);else Y.cases[R]??={branchIndices:[y],condition:J.l};if(Y.cases[O])Y.cases[O].branchIndices=so(Y.cases[O].branchIndices,f);else Y.cases[O]??={branchIndices:[f],condition:J.r}}}}}let o=this.ordered?g8(T,this.branches):T;if(!o.length)return null;let F=t8(o,this),A={};for(let y in F.best.cases){let S=h8(F,y);if(S===null){A[y]=!0;continue}if(S.length===this.branches.length)return null;if(this.ordered)S.sort((_,J)=>_.originalIndex-J.originalIndex);let f=S.map((_)=>_.branch),$=f.length===1?f[0]:this.$.node("union",this.ordered?{branches:f,ordered:!0}:f);Object.assign(this.referencesById,$.referencesById),A[y]=$}if(F.defaultEntries.length){let y=F.defaultEntries.map((S)=>S.branch);A.default=this.$.node("union",this.ordered?{branches:y,ordered:!0}:y,{prereduced:!0}),Object.assign(this.referencesById,A.default.referencesById)}return Object.assign(F.location,{cases:A})}}var t8=(T,o)=>{let F=T.sort((S,f)=>Object.keys(f.cases).length-Object.keys(S.cases).length)[0],A={kind:F.kind,path:F.path,optionallyChainedPropString:T1(F.path)},y=o.branches.map((S,f)=>({originalIndex:f,branch:S}));return{best:F,location:A,defaultEntries:y,node:o}},h8=(T,o)=>{let F=T.best.cases[o],A=n8(F.condition,T.location.path,T.node.$),y=[],S=[];for(let f=0;f<T.defaultEntries.length;f++){let $=T.defaultEntries[f];if(F.branchIndices.includes($.originalIndex)){let _=s0(T.node.branches[$.originalIndex],T.location);if(_===null)y=null;else y?.push({originalIndex:$.originalIndex,branch:_})}else if($.branch.hasKind("alias")&&A.hasKind("domain")&&A.domain==="object")y?.push($);else{if($.branch.in.overlaps(A)){let _=s0($.branch,T.location);y?.push({originalIndex:$.originalIndex,branch:_})}S.push($)}}return T.defaultEntries=S,y},g8=(T,o)=>{return T.filter((A)=>{let y=Object.values(A.cases).map((S)=>S.branchIndices);for(let S=0;S<y.length-1;S++){let f=y[S];for(let $=S+1;$<y.length;$++){let _=y[$];for(let J of f)for(let R of _)if(J>R){if(o[J].overlaps(o[R]))return!1}}}return!0})},n8=(T,o,F)=>{let A=T==="undefined"?F.node("unit",{unit:void 0}):T==="null"?F.node("unit",{unit:null}):T==="boolean"?F.units([!0,!1]):T;for(let y=o.length-1;y>=0;y--){let S=o[y];A=F.node("intersection",typeof S==="number"?{proto:"Array",sequence:[...j_(S).map((f)=>({})),A]}:{domain:"object",required:[{key:S,value:A}]})}return A},T1=(T)=>T.reduce((o,F)=>o+hf(F,!0),"data"),u8=BT(q_),c8=BT(r),Y$={implementation:m8,Node:e0},i8=(T)=>({kind:T.kind,path:T.path.map((o)=>typeof o==="string"?o:_F(o)),cases:d(T.cases,(o,F)=>[o,F===!0?F:F.hasKind("union")&&F.discriminantJson?F.discriminantJson:F.json])}),d8={delimiter:" | ",finalDelimiter:" | "},r8=(T)=>ZA(T,d8),ZA=(T,o)=>{let F=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 y={},S=T.filter(($)=>y[$]?!1:y[$]=!0),f=S.pop();return`${S.join(F)}${S.length?A:""}${f}`},X$=(T,o,F)=>{let A=o.map(()=>[]);for(let S=0;S<T.length;S++){let f={};for(let $=0;$<o.length;$++){if(A[$]===null)continue;if(T[S].equals(o[$])){A[$]=null,f={};break}let _=zT(T[S],o[$],F);if(_ instanceof k)continue;if(_.equals(T[S])){A[$].push(T[S]),f={};break}if(_.equals(o[$]))A[$]=null;else f[$]=_}for(let $ in f)A[$][S]=f[$]}let y=A.flatMap((S,f)=>S?.flatMap(($)=>$.branches)??o[f]);return y.length===0?k.init("union",T,o):y},l8=({branches:T,ordered:o})=>{if(T.length<2)return T;let F=T.map(()=>!0);for(let A=0;A<T.length;A++)for(let y=A+1;y<T.length&&F[A]&&F[y];y++){if(T[A].equals(T[y])){F[y]=!1;continue}let S=wo(T[A].in,T[y].in,T[0].$);if(S instanceof k)continue;if(!o)s8(T[A],T[y]);if(S.equals(T[A].in))F[A]=!!o;else if(S.equals(T[y].in))F[y]=!1}return T.filter((A,y)=>F[y])},s8=(T,o)=>{if(!T.includesTransform&&!o.includesTransform)return;if(!fF(T.shallowMorphs,o.shallowMorphs))G(a0(T.expression,o.expression));if(!fF(T.flatMorphs,o.flatMorphs,{isEqual:(F,A)=>F.propString===A.propString&&(F.node.hasKind("morph")&&A.node.hasKind("morph")?F.node.hasEqualMorphs(A.node):F.node.hasKind("intersection")&&A.node.hasKind("intersection")?F.node.structure?.structuralMorphRef===A.node.structure?.structuralMorphRef:!1)}))G(a0(T.expression,o.expression))},s0=(T,o)=>T.transform((F,A)=>{if(F==="domain"||F==="unit")return null;return A},{shouldTransform:(F,A)=>{let y=T1(A.path);if(!o.optionallyChainedPropString.startsWith(y))return!1;if(F.hasKind("domain")&&F.domain==="object")return!0;if((F.hasKind("domain")||o.kind==="unit")&&y===o.optionallyChainedPropString)return!0;return F.children.length!==0&&F.kind!=="index"}}),a0=(T,o)=>`An unordered union of a type including a morph and a type with overlapping input is indeterminate:
|
|
34
40
|
Left: ${T}
|
|
35
|
-
Right: ${o}`,
|
|
41
|
+
Right: ${o}`,a8=(T,o)=>`The intersection of two ordered unions is indeterminate:
|
|
36
42
|
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 F=o.hasKind("intersection")?o.basis:o;if(F){let y=F.hasKind("domain")?F:U.intrinsic.object;if(T.domain!==y.domain){let A=T.domain==="undefined"||T.domain==="null"||T.domain==="boolean"?T.domain:U.intrinsic[T.domain];return k.init("domain",A,y)}}return k.init("assignability",T,o.hasKind("intersection")?o.children.find((y)=>!y.allows(T.unit)):o)})}});class T1 extends mF{compiledValue=this.json.unit;serializedValue=typeof this.unit==="string"||this.unit instanceof Date?JSON.stringify(this.compiledValue):`${this.compiledValue}`;compiledCondition=e0(this.unit,this.serializedValue);compiledNegation=e0(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},e0=(T,o,F)=>{if(T instanceof Date){let y=`data instanceof Date && data.toISOString() === ${o}`;return F?`!(${y})`:y}if(Number.isNaN(T))return`${F?"!":""}Number.isNaN(data)`;return`data ${F?"!":"="}== ${o}`};var c8=r({kind:"index",hasAssociatedError:!1,intersectionIsOpen:!0,keys:{signature:{child:!0,parse:(T,o)=>{let F=o.$.parseSchema(T);if(!F.extends(U.intrinsic.key))return G(d8(F.expression));let y=F.branches.filter((A)=>A.hasKind("unit"));if(y.length)return G(i8(y.map((A)=>d(A.unit))));return F}},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,F)=>{if(T.signature.equals(o.signature)){let y=QT(T.value,o.value,F),A=y instanceof k?U.intrinsic.never.internal:y;return F.$.node("index",{signature:T.signature,value:A})}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=AT(this.value.flatRefs.map((T)=>no([this.signature,...T.path],T.node)),no([this.signature],this.value));traverseAllows=(T,o)=>Py(T).every((F)=>{if(this.signature.traverseAllows(F[0],o))return Go(F[0],()=>this.value.traverseAllows(F[1],o),o);return!0});traverseApply=(T,o)=>Py(T).forEach((F)=>{if(this.signature.traverseAllows(F[0],o))Go(F[0],()=>this.value.traverseApply(F[1],o),o)});_transform(T,o){o.path.push(this.signature);let F=super._transform(T,o);return o.path.pop(),F}compile(){}}var X$={implementation:c8,Node:o1},i8=(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:FA,optional:FA}});class F1 extends yA{expression=`${this.compiledKey}: ${this.value.expression}`;errorContext=Object.freeze({code:"required",missingValueDescription:this.value.defaultShortDescription,relativePath:[this.key],meta:this.meta});compiledErrorContext=VF(this.errorContext)}var Y$={implementation:r8,Node:F1};var l8=r({kind:"sequence",hasAssociatedError:!1,collapsibleKey:"variadic",keys:{prefix:{child:!0,parse:(T,o)=>{if(T.length===0)return;return T.map((F)=>o.$.parseSchema(F))}},optionals:{child:!0,parse:(T,o)=>{if(T.length===0)return;return T.map((F)=>o.$.parseSchema(F))}},defaultables:{child:(T)=>T.map((o)=>o[0]),parse:(T,o)=>{if(T.length===0)return;return T.map((F)=>{let y=o.$.parseSchema(F[0]);return SA(y,F[1],null),[y,F[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((F)=>o.$.parseSchema(F))}}},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 G(TY);if(T.optionals?.length||T.defaultables?.length)return G(H$)}if(T.minVariadicLength&&!T.variadic)return G("minVariadicLength may not be specified without a variadic element");return T}return{variadic:T}},reduce:(T,o)=>{let F=T.minVariadicLength??0,y=T.prefix?.slice()??[],A=T.defaultables?.slice()??[],S=T.optionals?.slice()??[],f=T.postfix?.slice()??[];if(T.variadic){while(S.at(-1)?.equals(T.variadic))S.pop();if(S.length===0&&A.length===0)while(y.at(-1)?.equals(T.variadic))y.pop(),F++;while(f[0]?.equals(T.variadic))f.shift(),F++}else if(S.length===0&&A.length===0)y.push(...f.splice(0));if(F!==T.minVariadicLength||T.prefix&&T.prefix.length!==y.length)return o.node("sequence",{...T,prefix:y,defaultables:A,optionals:S,postfix:f,minVariadicLength:F},{prereduced:!0})},defaults:{description:(T)=>{if(T.isVariadicOnly)return`${T.variadic.nestableExpression}[]`;return`[${T.tuple.map((F)=>F.kind==="defaultables"?`${F.node.nestableExpression} = ${d(F.default)}`:F.kind==="optionals"?`${F.node.nestableExpression}?`:F.kind==="variadic"?`...${F.node.nestableExpression}[]`:F.node.expression).join(", ")}]`}},intersections:{sequence:(T,o,F)=>{let y=_A({l:T.tuple,r:o.tuple,disjoint:new k,result:[],fixedVariants:[],ctx:F}),A=y.disjoint.length===0?[y,...y.fixedVariants]:y.fixedVariants;return A.length===0?y.disjoint:A.length===1?F.$.node("sequence",y1(A[0].result)):F.$.node("union",A.map((S)=>({proto:Array,sequence:y1(S.result)})))}}});class A1 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=SF(this.variadic&&[this.variadic],this.postfix);flatRefs=this.addFlatRefs();addFlatRefs(){return gf(this.flatRefs,this.prevariadic.flatMap((T,o)=>AT(T.node.flatRefs.map((F)=>no([`${o}`,...F.path],F.node)),no([`${o}`],T.node)))),gf(this.flatRefs,this.variadicOrPostfix.flatMap((T)=>AT(T.flatRefs.map((o)=>no([U.intrinsic.nonNegativeIntegerString.internal,...o.path],o.node)),no([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 F=T.length-this.postfixLength;if(o>=F)return{kind:"postfix",node:this.postfix[o-F]};return{kind:"variadic",node:this.variadic??$T(`Unexpected attempt to access index ${o} on ${this}`)}}traverseAllows=(T,o)=>{for(let F=0;F<T.length;F++)if(!this.elementAtIndex(T,F).node.traverseAllows(T[F],o))return!1;return!0};traverseApply=(T,o)=>{let F=0;for(;F<T.length;F++)Go(F,()=>this.elementAtIndex(T,F).node.traverseApply(T[F],o),o)};get element(){return this.cacheGetter("element",this.$.node("union",this.children))}compile(T){if(this.prefix?.forEach((o,F)=>T.traverseKey(`${F}`,`data[${F}]`,o)),this.defaultablesAndOptionals.forEach((o,F)=>{let y=`${F+this.prefixLength}`;T.if(`${y} >= ${T.data}.length`,()=>T.traversalKind==="Allows"?T.return(!0):T.return()),T.traverseKey(y,`data[${y}]`,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,F)=>{let y=`firstPostfixIndex + ${F}`;T.traverseKey(y,`data[${y}]`,o)})}if(T.traversalKind==="Allows")T.return(!0)}_transform(T,o){o.path.push(U.intrinsic.nonNegativeIntegerString.internal);let F=super._transform(T,o);return o.path.pop(),F}expression=this.description;reduceJsonSchema(T,o){if(this.prevariadic.length)T.prefixItems=this.prevariadic.map((F)=>{let y=F.node.toJsonSchemaRecurse(o);if(F.kind==="defaultables"){let A=typeof F.default==="function"?F.default():F.default;y.default=A}return y});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=[],F="[",y=T.prefixLength+T.defaultablesLength-1;for(let A=T.prefixLength;A<=y;A++){let[S,f]=T.defaultables[A-T.prefixLength];o.push(J$(A,S,f)),F+=`${A}: ${S.id} = ${ko(f)}, `}return F+="]",s8[F]??=o},Z$={implementation:l8,Node:A1},e8=(T)=>{let o=[];if(T.prefix?.forEach((F)=>o.push({kind:"prefix",node:F})),T.defaultables?.forEach(([F,y])=>o.push({kind:"defaultables",node:F,default:y})),T.optionals?.forEach((F)=>o.push({kind:"optionals",node:F})),T.variadic)o.push({kind:"variadic",node:T.variadic});return T.postfix?.forEach((F)=>o.push({kind:"postfix",node:F})),o},y1=(T)=>T.reduce((o,F)=>{if(F.kind==="variadic")o.variadic=F.node;else if(F.kind==="defaultables")o.defaultables=AT(o.defaultables,[[F.node,F.default]]);else o[F.kind]=AT(o[F.kind],F.node);return o},{}),H$="A postfix required element cannot follow an optional or defaultable element",TY="A postfix element requires a variadic element",_A=(T)=>{let[o,...F]=T.l,[y,...A]=T.r;if(!o||!y)return T;let S=F.at(-1)?.kind==="postfix",f=A.at(-1)?.kind==="postfix",$=o.kind==="prefix"||y.kind==="prefix"?"prefix":o.kind==="postfix"||y.kind==="postfix"?"postfix":o.kind==="variadic"&&y.kind==="variadic"?"variadic":S||f?"prefix":o.kind==="defaultables"||y.kind==="defaultables"?"defaultables":"optionals";if(o.kind==="prefix"&&y.kind==="variadic"&&f){let M=_A({...T,fixedVariants:[],r:A.map((Y)=>({...Y,kind:"prefix"}))});if(M.disjoint.length===0)T.fixedVariants.push(M)}else if(y.kind==="prefix"&&o.kind==="variadic"&&S){let M=_A({...T,fixedVariants:[],l:F.map((Y)=>({...Y,kind:"prefix"}))});if(M.disjoint.length===0)T.fixedVariants.push(M)}let _=QT(o.node,y.node,T.ctx);if(_ instanceof k)if($==="prefix"||$==="postfix")T.disjoint.push(..._.withPrefixKey($==="prefix"?T.result.length:`-${F.length+1}`,"required")),T.result=[...T.result,{kind:$,node:U.intrinsic.never.internal}];else if($==="optionals"||$==="defaultables")return T;else return _A({...T,fixedVariants:[],l:F.map((M)=>({...M,kind:"prefix"})),r:F.map((M)=>({...M,kind:"prefix"}))});else if($==="defaultables"){if(o.kind==="defaultables"&&y.kind==="defaultables"&&o.default!==y.default)G($$(o.default,y.default));T.result=[...T.result,{kind:$,node:_,default:o.kind==="defaultables"?o.default:y.kind==="defaultables"?y.default:$T(`Unexpected defaultable intersection from ${o.kind} and ${y.kind} elements.`)}]}else T.result=[...T.result,{kind:$,node:_}];let J=T.l.length,R=T.r.length;if(o.kind!=="variadic"||J>=R&&(y.kind==="variadic"||R===1))T.l=F;if(y.kind!=="variadic"||R>=J&&(o.kind==="variadic"||J===1))T.r=A;return _A(T)};var $1=(T)=>(o)=>{if(o.props.length||o.index){let F=o.index?.map((A)=>A[T])??[];if(o.props.forEach((A)=>F.push(A[T])),o.undeclared)F.push(`+ (undeclared): ${o.undeclared}`);let y=`{ ${F.join(", ")} }`;return o.sequence?`${y} & ${o.sequence.description}`:y}return o.sequence?.description??"{}"},oY=$1("description"),FY=$1("expression"),S1=(T,o,F)=>{let y=T.required?"required":"optional";if(!o.signature.allows(T.key))return null;let A=Eo(T.value,o.value,F);if(A instanceof k)if(y==="optional")return F.node("optional",{key:T.key,value:U.intrinsic.never.internal});else return A.withPrefixKey(T.key,T.kind);return null},yY=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,F)=>{o.required=AT(o.required,F.map((y)=>y[T]));return}},optional:{child:!0,parse:So("optional"),reduceIo:(T,o,F)=>{if(T==="in"){o.optional=F.map((y)=>y.in);return}F.forEach((y)=>o[y.outProp.kind]=AT(o[y.outProp.kind],y.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,F)=>{if(F!=="delete")return;if(T==="in")delete o.undeclared;else o.undeclared="reject"}}},defaults:{description:oY},intersections:{structure:(T,o,F)=>{let y={...T.inner},A={...o.inner},S=new k;if(T.undeclared){let _=T.keyof();if(o.requiredKeys.forEach((J)=>{if(!_.allows(J))S.add("presence",U.intrinsic.never.internal,o.propsByKey[J].value,{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=Eo(_,J.signature,F.$);if(R instanceof k)return[];let M=_S(R,J.value,F.$);if(M.required)A.required=SF(A.required,M.required);if(M.optional)A.optional=SF(A.optional,M.optional);return M.index??[]})}if(o.undeclared){let _=o.keyof();if(T.requiredKeys.forEach((J)=>{if(!_.allows(J))S.add("presence",T.propsByKey[J].value,U.intrinsic.never.internal,{path:[J]})}),y.optional)y.optional=y.optional.filter((J)=>_.allows(J.key));if(y.index)y.index=y.index.flatMap((J)=>{if(J.signature.extends(_))return J;let R=Eo(_,J.signature,F.$);if(R instanceof k)return[];let M=_S(R,J.value,F.$);if(M.required)y.required=SF(y.required,M.required);if(M.optional)y.optional=SF(y.optional,M.optional);return M.index??[]})}let f={};if(T.undeclared||o.undeclared)f.undeclared=T.undeclared==="reject"||o.undeclared==="reject"?"reject":"delete";let $=_y({kind:"structure",baseInner:f,l:Ry(y),r:Ry(A),roots:[],ctx:F});if($ instanceof k)S.push(...$);if(S.length)return S;return $}},reduce:(T,o)=>{if(T.index){if(!(T.required||T.optional))return;let F=!1,y=T.required??[],A=T.optional??[],S=[...A];for(let f of T.index){for(let $ of y){let _=S1($,f,o);if(_ instanceof k)return _}for(let[$,_]of A.entries()){let J=S1(_,f,o);if(J instanceof k)return J;if(J===null)continue;S[$]=J,F=!0}}if(F)return o.node("structure",{...T,optional:S},{prereduced:!0})}}});class J1 extends Bo{impliedBasis=U.intrinsic.object.internal;impliedSiblings=this.children.flatMap((T)=>T.impliedSiblings??[]);props=SF(this.required,this.optional);propsByKey=l(this.props,(T,o)=>[o.key,o]);propsByKeyReference=BT(this.propsByKey);expression=FY(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,F)=>{let y=this.propsByKey[F.key];if(zT(F)){if(F.kind!=="required"&&F.kind!=="optional")return G(`Map result must have kind "required" or "optional" (was ${F.kind})`);return o[F.kind]=AT(o[F.kind],F),o}let A=F.kind??y?.kind??"required",S=l(F,(f,$)=>(f in AA.implementation.keys)?[f,$]:[]);return o[A]=AT(o[A],this.$.node(A,S)),o},{}))}assertHasKeys(T){let o=T.filter((F)=>!fA(F,this.keyof()));if(o.length)return G(f1(this.expression,o))}get(T,...o){let F,y=!1,A=$Y(T);if((typeof A==="string"||typeof A==="symbol")&&this.propsByKey[A])F=this.propsByKey[A].value,y=this.propsByKey[A].required;if(this.index?.forEach((f)=>{if(fA(A,f.signature))F=F?.and(f.value)??f.value}),this.sequence&&fA(A,U.intrinsic.nonNegativeIntegerString))if(v(A,"root")){if(this.sequence.variadic)F=F?.and(this.sequence.element)??this.sequence.element}else{let f=Number.parseInt(A);if(f<this.sequence.prevariadic.length){let $=this.sequence.prevariadic[f].node;F=F?.and($)??$,y||=f<this.sequence.prefixLength}else if(this.sequence.variadic){let $=this.$.node("union",this.sequence.variadicOrPostfix);F=F?.and($)??$}}if(!F){if(this.sequence?.variadic&&v(A,"root")&&A.extends(U.intrinsic.number))return G(JY(A.expression,this.sequence.expression));return G(f1(this.expression,[A]))}let S=F.get(...o);return y?S:S.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((F)=>F.hasKind("required")?this.$.node("optional",F.inner):F)})}require(){let{optional:T,...o}=this.inner;return this.$.node("structure",{...o,required:this.props.map((F)=>F.hasKind("optional")?{key:F.key,value:F.value}:F)})}merge(T){let o=this.filterKeys("omit",[T.keyof()]);if(T.required)o.required=AT(o.required,T.required);if(T.optional)o.optional=AT(o.optional,T.optional);if(T.index)o.index=AT(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 F=aA(this.inner),y=(A)=>{let S=o.some((f)=>fA(A,f));return T==="pick"?S:!S};if(F.required)F.required=F.required.filter((A)=>y(A.key));if(F.optional)F.optional=F.optional.filter((A)=>y(A.key));if(F.index)F.index=F.index.filter((A)=>y(A.signature));return F}traverseAllows=(T,o)=>this._traverse("Allows",T,o);traverseApply=(T,o)=>this._traverse("Apply",T,o);_traverse=(T,o,F)=>{let y=F?.currentErrorCount??0;for(let A=0;A<this.props.length;A++)if(T==="Allows"){if(!this.props[A].traverseAllows(o,F))return!1}else if(this.props[A].traverseApply(o,F),F.failFast&&F.currentErrorCount>y)return!1;if(this.sequence){if(T==="Allows"){if(!this.sequence.traverseAllows(o,F))return!1}else if(this.sequence.traverseApply(o,F),F.failFast&&F.currentErrorCount>y)return!1}if(this.index||this.undeclared==="reject"){let A=Object.keys(o);A.push(...Object.getOwnPropertySymbols(o));for(let S=0;S<A.length;S++){let f=A[S];if(this.index){for(let $ of this.index)if($.signature.traverseAllows(f,F)){if(T==="Allows"){if(!Go(f,()=>$.value.traverseAllows(o[f],F),F))return!1}else if(Go(f,()=>$.value.traverseApply(o[f],F),F),F.failFast&&F.currentErrorCount>y)return!1}}if(this.undeclared==="reject"&&!this.declaresKey(f)){if(T==="Allows")return!1;if(F.errorFromNodeContext({code:"predicate",expected:"removed",actual:"",relativePath:[f],meta:this.meta}),F.failFast)return!1}}}if(this.structuralMorph&&F&&!F.hasError())F.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((F)=>o.push(T.invoke(F.signature,{kind:"Allows",arg:"k"}))),this.sequence)o.push("$ark.intrinsic.nonNegativeIntegerString.allows(k)");return o.join(" || ")||"false"}get structuralMorph(){return this.cacheGetter("structuralMorph",SY(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(["),fY(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((F)=>{if(typeof F.key==="symbol")return JT.throwUnjsonifiableError(`Symbolic key ${F.serializedKey}`);let y=F.value.toJsonSchemaRecurse(o);if(F.hasDefault()){let A=typeof F.default==="function"?F.default():F.default;y.default=A}T.properties[F.key]=y}),this.requiredKeys.length)T.required=this.requiredKeys}if(this.index?.forEach((F)=>{if(F.signature.equals(U.intrinsic.string))return T.additionalProperties=F.value.toJsonSchemaRecurse(o);if(!F.signature.extends(U.intrinsic.string))return JT.throwUnjsonifiableError(`Symbolic index signature ${F.signature.exclude(U.intrinsic.string)}`);F.signature.branches.forEach((y)=>{if(!y.hasKind("intersection")||y.inner.pattern?.length!==1)return JT.throwUnjsonifiableError(`Index signature ${y}`);T.patternProperties??={},T.patternProperties[y.inner.pattern[0].rule]=F.value.toJsonSchemaRecurse(o)})}),this.undeclared&&!T.additionalProperties)T.additionalProperties=!1;return T}}var G$={},AY=(T)=>{let o="";for(let F=0;F<T.defaultable.length;F++)o+=T.defaultable[F].defaultValueMorphRef;if(T.sequence?.defaultValueMorphsReference)o+=T.sequence?.defaultValueMorphsReference;if(T.undeclared==="delete"){if(o+="delete !(",T.required?.forEach((F)=>o+=F.compiledKey+" | "),T.optional?.forEach((F)=>o+=F.compiledKey+" | "),T.index?.forEach((F)=>o+=F.signature.id+" | "),T.sequence)if(T.sequence.maxLength===null)o+=n.nonNegativeIntegerString.id;else o+=T.sequence.tuple.forEach((F,y)=>o+=y+" | ");o+=")"}return o},SY=(T)=>{let o=AY(T);if(!o)return;if(G$[o])return G$[o];let F=(y,A)=>{for(let S=0;S<T.defaultable.length;S++)if(!(T.defaultable[S].key in y))T.defaultable[S].defaultValueMorph(y,A);if(T.sequence?.defaultables)for(let S=y.length-T.sequence.prefixLength;S<T.sequence.defaultables.length;S++)T.sequence.defaultValueMorphs[S](y,A);if(T.undeclared==="delete"){for(let S in y)if(!T.declaresKey(S))delete y[S]}return y};return G$[o]=F},fY=(T,o)=>{let y=`(data${o.defaultable.some((A)=>A.defaultValueMorph.length===2)||o.sequence?.defaultValueMorphs.some((A)=>A.length===2)?", ctx":""})`;return T.block(`${y} => `,(A)=>{for(let S=0;S<o.defaultable.length;S++){let{serializedKey:f,defaultValueMorphRef:$}=o.defaultable[S];A.if(`!(${f} in data)`,(_)=>_.line(`${$}${y}`))}if(o.sequence?.defaultables)A.for(`i < ${o.sequence.defaultables.length}`,(S)=>S.set("data[i]",5),`data.length - ${o.sequence.prefixLength}`);if(o.undeclared==="delete")A.forIn("data",(S)=>S.if(`!(${o._compileDeclaresKey(S)})`,(f)=>f.line("delete data[k]")));return A.return("data")})},E$={implementation:yY,Node:J1},$Y=(T)=>{if(v(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.`,_S=(T,o,F)=>{let[y,A]=B_(T.branches,(f)=>f.hasKind("unit"));if(!y.length)return{index:F.node("index",{signature:T,value:o})};let S={};if(y.forEach((f)=>{let $=F.node("required",{key:f.unit,value:o});S[$.kind]=AT(S[$.kind],$)}),A.length)S.index=F.node("index",{signature:A,value:o});return S},_Y=(T)=>v(T,"root")?T.expression:d(T),f1=(T,o)=>`Key${o.length===1?"":"s"} ${o.map(_Y).join(", ")} ${o.length===1?"does":"do"} not exist on ${T}`;var Oy={...N0,alias:$A.implementation,domain:JS.implementation,unit:M$.implementation,proto:JA.implementation,union:O$.implementation,morph:R$.implementation,intersection:_$.implementation,divisor:rf.implementation,pattern:y$.implementation,predicate:df.implementation,required:Y$.implementation,optional:AA.implementation,index:X$.implementation,sequence:Z$.implementation,structure:E$.implementation};U.defaultConfig=m_(Object.assign(l(Oy,(T,o)=>[T,o.defaults]),{jitless:c_(),clone:g_,onUndeclaredKey:"ignore",exactOptionalPropertyTypes:!0,numberAllowsNaN:!1,dateAllowsInvalid:!1,onFail:null,keywords:{}}));U.resolvedConfig=sy(U.defaultConfig,U.config);var q0={...p0,alias:$A.Node,domain:JS.Node,unit:M$.Node,proto:JA.Node,union:O$.Node,morph:R$.Node,intersection:_$.Node,divisor:rf.Node,pattern:y$.Node,predicate:df.Node,required:Y$.Node,optional:AA.Node,index:X$.Node,sequence:Z$.Node,structure:E$.Node};class Yy extends If{get[Ro](){return"module"}}var w$=(T,o)=>new Yy(l(T,(F,y)=>[F,v(y,"module")?w$(y,o):o.bindReference(y)]));var RY=(T)=>GT(T)?T:("branches"in T)&>(T.branches)?T.branches:void 0,WY=(T,o)=>G(`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 F=o.write(O1,4),y=o.compile()();for(let A of T){if(A.precompilation)continue;if(A.traverseAllows=y[`${A.id}Allows`].bind(y),A.isRoot()&&!A.allowsRequiresContext)A.allows=A.traverseAllows;if(A.traverseApply=y[`${A.id}Apply`].bind(y),y[`${A.id}Optimistic`])A.traverseOptimistic=y[`${A.id}Optimistic`].bind(y);A.precompilation=F}},X1=(T)=>new sA().return(T.reduce((o,F)=>{let y=new ly({kind:"Allows"}).indent();F.compile(y);let A=y.write(`${F.id}Allows`),S=new ly({kind:"Apply"}).indent();F.compile(S);let f=S.write(`${F.id}Apply`),$=`${o}${A},
|
|
43
|
+
Right: ${o}`;var e8=l({kind:"unit",hasAssociatedError:!0,keys:{unit:{preserveUndefined:!0,serialize:(T)=>T instanceof Date?T.toISOString():ko(T)}},normalize:(T)=>T,defaults:{description:(T)=>r(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 F=o.hasKind("intersection")?o.basis:o;if(F){let A=F.hasKind("domain")?F:K.intrinsic.object;if(T.domain!==A.domain){let y=T.domain==="undefined"||T.domain==="null"||T.domain==="boolean"?T.domain:K.intrinsic[T.domain];return k.init("domain",y,A)}}return k.init("assignability",T,o.hasKind("intersection")?o.children.find((A)=>!A.allows(T.unit)):o)})}});class F1 extends hF{compiledValue=this.json.unit;serializedValue=typeof this.unit==="string"||this.unit instanceof Date?JSON.stringify(this.compiledValue):`${this.compiledValue}`;compiledCondition=o1(this.unit,this.serializedValue);compiledNegation=o1(this.unit,this.serializedValue,"negated");expression=r(this.unit);domain=tT(this.unit);get defaultShortDescription(){return this.domain==="object"?Zo.object:this.description}innerToJsonSchema(T){return this.unit===null?{type:"null"}:K.intrinsic.jsonPrimitive.allows(this.unit)?{const:this.unit}:T.fallback.unit({code:"unit",base:{},unit:this.unit})}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 Z$={implementation:e8,Node:F1},o1=(T,o,F)=>{if(T instanceof Date){let A=`data instanceof Date && data.toISOString() === ${o}`;return F?`!(${A})`:A}if(Number.isNaN(T))return`${F?"!":""}Number.isNaN(data)`;return`data ${F?"!":"="}== ${o}`};var TY=l({kind:"index",hasAssociatedError:!1,intersectionIsOpen:!0,keys:{signature:{child:!0,parse:(T,o)=>{let F=o.$.parseSchema(T);if(!F.extends(K.intrinsic.key))return G(FY(F.expression));let A=F.branches.filter((y)=>y.hasKind("unit"));if(A.length)return G(oY(A.map((y)=>r(y.unit))));return F}},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,F)=>{if(T.signature.equals(o.signature)){let A=zT(T.value,o.value,F),y=A instanceof k?K.intrinsic.never.internal:A;return F.$.node("index",{signature:T.signature,value:y})}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 A1 extends Bo{impliedBasis=K.intrinsic.object.internal;expression=`[${this.signature.expression}]: ${this.value.expression}`;flatRefs=yT(this.value.flatRefs.map((T)=>no([this.signature,...T.path],T.node)),no([this.signature],this.value));traverseAllows=(T,o)=>vF(T).every((F)=>{if(this.signature.traverseAllows(F[0],o))return Go(F[0],()=>this.value.traverseAllows(F[1],o),o);return!0});traverseApply=(T,o)=>{for(let F of vF(T))if(this.signature.traverseAllows(F[0],o))Go(F[0],()=>this.value.traverseApply(F[1],o),o)};_transform(T,o){o.path.push(this.signature);let F=super._transform(T,o);return o.path.pop(),F}compile(){}}var H$={implementation:TY,Node:A1},oY=(T)=>`Index keys ${T.join(", ")} should be specified as named props.`,FY=(T)=>`Indexed key definition '${T}' must be a string or symbol`;var AY=l({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:yy,optional:yy}});class y1 extends Sy{expression=`${this.compiledKey}: ${this.value.expression}`;errorContext=Object.freeze({code:"required",missingValueDescription:this.value.defaultShortDescription,relativePath:[this.key],meta:this.meta});compiledErrorContext=VF(this.errorContext)}var G$={implementation:AY,Node:y1};var yY=l({kind:"sequence",hasAssociatedError:!1,collapsibleKey:"variadic",keys:{prefix:{child:!0,parse:(T,o)=>{if(T.length===0)return;return T.map((F)=>o.$.parseSchema(F))}},optionals:{child:!0,parse:(T,o)=>{if(T.length===0)return;return T.map((F)=>o.$.parseSchema(F))}},defaultables:{child:(T)=>T.map((o)=>o[0]),parse:(T,o)=>{if(T.length===0)return;return T.map((F)=>{let A=o.$.parseSchema(F[0]);return $y(A,F[1],null),[A,F[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((F)=>o.$.parseSchema(F))}}},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 G(JY);if(T.optionals?.length||T.defaultables?.length)return G(E$)}if(T.minVariadicLength&&!T.variadic)return G("minVariadicLength may not be specified without a variadic element");return T}return{variadic:T}},reduce:(T,o)=>{let F=T.minVariadicLength??0,A=T.prefix?.slice()??[],y=T.defaultables?.slice()??[],S=T.optionals?.slice()??[],f=T.postfix?.slice()??[];if(T.variadic){while(S.at(-1)?.equals(T.variadic))S.pop();if(S.length===0&&y.length===0)while(A.at(-1)?.equals(T.variadic))A.pop(),F++;while(f[0]?.equals(T.variadic))f.shift(),F++}else if(S.length===0&&y.length===0)A.push(...f.splice(0));if(F!==T.minVariadicLength||T.prefix&&T.prefix.length!==A.length)return o.node("sequence",{...T,prefix:A,defaultables:y,optionals:S,postfix:f,minVariadicLength:F},{prereduced:!0})},defaults:{description:(T)=>{if(T.isVariadicOnly)return`${T.variadic.nestableExpression}[]`;return`[${T.tuple.map((F)=>F.kind==="defaultables"?`${F.node.nestableExpression} = ${r(F.default)}`:F.kind==="optionals"?`${F.node.nestableExpression}?`:F.kind==="variadic"?`...${F.node.nestableExpression}[]`:F.node.expression).join(", ")}]`}},intersections:{sequence:(T,o,F)=>{let A=Wy({l:T.tuple,r:o.tuple,disjoint:new k,result:[],fixedVariants:[],ctx:F}),y=A.disjoint.length===0?[A,...A.fixedVariants]:A.fixedVariants;return y.length===0?A.disjoint:y.length===1?F.$.node("sequence",S1(y[0].result)):F.$.node("union",y.map((S)=>({proto:Array,sequence:S1(S.result)})))}}});class f1 extends Bo{impliedBasis=K.intrinsic.Array.internal;tuple=$Y(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=SF(this.variadic&&[this.variadic],this.postfix);flatRefs=this.addFlatRefs();addFlatRefs(){return cf(this.flatRefs,this.prevariadic.flatMap((T,o)=>yT(T.node.flatRefs.map((F)=>no([`${o}`,...F.path],F.node)),no([`${o}`],T.node)))),cf(this.flatRefs,this.variadicOrPostfix.flatMap((T)=>yT(T.flatRefs.map((o)=>no([K.intrinsic.nonNegativeIntegerString.internal,...o.path],o.node)),no([K.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=fY(this);defaultValueMorphsReference=this.defaultValueMorphs.length?BT(this.defaultValueMorphs):void 0;elementAtIndex(T,o){if(o<this.prevariadic.length)return this.tuple[o];let F=T.length-this.postfixLength;if(o>=F)return{kind:"postfix",node:this.postfix[o-F]};return{kind:"variadic",node:this.variadic??$T(`Unexpected attempt to access index ${o} on ${this}`)}}traverseAllows=(T,o)=>{for(let F=0;F<T.length;F++)if(!this.elementAtIndex(T,F).node.traverseAllows(T[F],o))return!1;return!0};traverseApply=(T,o)=>{let F=0;for(;F<T.length;F++)Go(F,()=>this.elementAtIndex(T,F).node.traverseApply(T[F],o),o)};get element(){return this.cacheGetter("element",this.$.node("union",this.children))}compile(T){if(this.prefix)for(let[o,F]of this.prefix.entries())T.traverseKey(`${o}`,`data[${o}]`,F);for(let[o,F]of this.defaultablesAndOptionals.entries()){let A=`${o+this.prefixLength}`;T.if(`${A} >= ${T.data}.length`,()=>T.traversalKind==="Allows"?T.return(!0):T.return()),T.traverseKey(A,`data[${A}]`,F)}if(this.variadic){if(this.postfix)T.const("firstPostfixIndex",`${T.data}.length${this.postfix?`- ${this.postfix.length}`:""}`);if(T.for(`i < ${this.postfix?"firstPostfixIndex":"data.length"}`,()=>T.traverseKey("i","data[i]",this.variadic),this.prevariadic.length),this.postfix)for(let[o,F]of this.postfix.entries()){let A=`firstPostfixIndex + ${o}`;T.traverseKey(A,`data[${A}]`,F)}}if(T.traversalKind==="Allows")T.return(!0)}_transform(T,o){o.path.push(K.intrinsic.nonNegativeIntegerString.internal);let F=super._transform(T,o);return o.path.pop(),F}expression=this.description;reduceJsonSchema(T,o){if(this.prevariadic.length)T.prefixItems=this.prevariadic.map((F)=>{let A=F.node.toJsonSchemaRecurse(o);if(F.kind==="defaultables"){let y=typeof F.default==="function"?F.default():F.default;A.default=K.intrinsic.jsonData.allows(y)?y:o.fallback.defaultValue({code:"defaultValue",base:A,value:y})}return A});if(this.minLength)T.minItems=this.minLength;if(this.variadic){let F=Object.assign(T,{items:this.variadic.toJsonSchemaRecurse(o)});if(this.maxLength)F.maxItems=this.maxLength;if(this.postfix){let A=this.postfix.map((y)=>y.toJsonSchemaRecurse(o));T=o.fallback.arrayPostfix({code:"arrayPostfix",base:F,elements:A})}}else T.items=!1,delete T.maxItems;return T}}var SY={},fY=(T)=>{if(!T.defaultables)return[];let o=[],F="[",A=T.prefixLength+T.defaultablesLength-1;for(let y=T.prefixLength;y<=A;y++){let[S,f]=T.defaultables[y-T.prefixLength];o.push(W$(y,S,f)),F+=`${y}: ${S.id} = ${ko(f)}, `}return F+="]",SY[F]??=o},w$={implementation:yY,Node:f1},$Y=(T)=>{let o=[];if(T.prefix)for(let F of T.prefix)o.push({kind:"prefix",node:F});if(T.defaultables)for(let[F,A]of T.defaultables)o.push({kind:"defaultables",node:F,default:A});if(T.optionals)for(let F of T.optionals)o.push({kind:"optionals",node:F});if(T.variadic)o.push({kind:"variadic",node:T.variadic});if(T.postfix)for(let F of T.postfix)o.push({kind:"postfix",node:F});return o},S1=(T)=>T.reduce((o,F)=>{if(F.kind==="variadic")o.variadic=F.node;else if(F.kind==="defaultables")o.defaultables=yT(o.defaultables,[[F.node,F.default]]);else o[F.kind]=yT(o[F.kind],F.node);return o},{}),E$="A postfix required element cannot follow an optional or defaultable element",JY="A postfix element requires a variadic element",Wy=(T)=>{let[o,...F]=T.l,[A,...y]=T.r;if(!o||!A)return T;let S=F.at(-1)?.kind==="postfix",f=y.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":S||f?"prefix":o.kind==="defaultables"||A.kind==="defaultables"?"defaultables":"optionals";if(o.kind==="prefix"&&A.kind==="variadic"&&f){let O=Wy({...T,fixedVariants:[],r:y.map((Y)=>({...Y,kind:"prefix"}))});if(O.disjoint.length===0)T.fixedVariants.push(O)}else if(A.kind==="prefix"&&o.kind==="variadic"&&S){let O=Wy({...T,fixedVariants:[],l:F.map((Y)=>({...Y,kind:"prefix"}))});if(O.disjoint.length===0)T.fixedVariants.push(O)}let _=zT(o.node,A.node,T.ctx);if(_ instanceof k)if($==="prefix"||$==="postfix")T.disjoint.push(..._.withPrefixKey($==="prefix"?T.result.length:`-${F.length+1}`,"required")),T.result=[...T.result,{kind:$,node:K.intrinsic.never.internal}];else if($==="optionals"||$==="defaultables")return T;else return Wy({...T,fixedVariants:[],l:F.map((O)=>({...O,kind:"prefix"})),r:F.map((O)=>({...O,kind:"prefix"}))});else if($==="defaultables"){if(o.kind==="defaultables"&&A.kind==="defaultables"&&o.default!==A.default)G(R$(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=F;if(A.kind!=="variadic"||R>=J&&(o.kind==="variadic"||J===1))T.r=y;return Wy(T)};var _1=(T)=>(o)=>{if(o.props.length||o.index){let F=o.index?.map((y)=>y[T])??[];for(let y of o.props)F.push(y[T]);if(o.undeclared)F.push(`+ (undeclared): ${o.undeclared}`);let A=`{ ${F.join(", ")} }`;return o.sequence?`${A} & ${o.sequence.description}`:A}return o.sequence?.description??"{}"},_Y=_1("description"),RY=_1("expression"),$1=(T,o,F)=>{let A=T.required?"required":"optional";if(!o.signature.allows(T.key))return null;let y=wo(T.value,o.value,F);if(y instanceof k)return A==="optional"?F.node("optional",{key:T.key,value:K.intrinsic.never.internal}):y.withPrefixKey(T.key,T.kind);return null},WY=l({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,F)=>{o.required=yT(o.required,F.map((A)=>A[T]));return}},optional:{child:!0,parse:So("optional"),reduceIo:(T,o,F)=>{if(T==="in"){o.optional=F.map((A)=>A.in);return}for(let A of F)o[A.outProp.kind]=yT(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,F)=>{if(F!=="delete")return;if(T==="in")delete o.undeclared;else o.undeclared="reject"}}},defaults:{description:_Y},intersections:{structure:(T,o,F)=>{let A={...T.inner},y={...o.inner},S=new k;if(T.undeclared){let _=T.keyof();for(let J of o.requiredKeys)if(!_.allows(J))S.add("presence",K.intrinsic.never.internal,o.propsByKey[J].value,{path:[J]});if(y.optional)y.optional=y.optional.filter((J)=>_.allows(J.key));if(y.index)y.index=y.index.flatMap((J)=>{if(J.signature.extends(_))return J;let R=wo(_,J.signature,F.$);if(R instanceof k)return[];let O=RS(R,J.value,F.$);if(O.required)y.required=SF(y.required,O.required);if(O.optional)y.optional=SF(y.optional,O.optional);return O.index??[]})}if(o.undeclared){let _=o.keyof();for(let J of T.requiredKeys)if(!_.allows(J))S.add("presence",T.propsByKey[J].value,K.intrinsic.never.internal,{path:[J]});if(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=wo(_,J.signature,F.$);if(R instanceof k)return[];let O=RS(R,J.value,F.$);if(O.required)A.required=SF(A.required,O.required);if(O.optional)A.optional=SF(A.optional,O.optional);return O.index??[]})}let f={};if(T.undeclared||o.undeclared)f.undeclared=T.undeclared==="reject"||o.undeclared==="reject"?"reject":"delete";let $=WA({kind:"structure",baseInner:f,l:MA(A),r:MA(y),roots:[],ctx:F});if($ instanceof k)S.push(...$);if(S.length)return S;return $}},reduce:(T,o)=>{if(T.index){if(!(T.required||T.optional))return;let F=!1,A=T.required??[],y=T.optional??[],S=[...y];for(let f of T.index){for(let $ of A){let _=$1($,f,o);if(_ instanceof k)return _}for(let[$,_]of y.entries()){let J=$1(_,f,o);if(J instanceof k)return J;if(J===null)continue;S[$]=J,F=!0}}if(F)return o.node("structure",{...T,optional:S},{prereduced:!0})}}});class R1 extends Bo{impliedBasis=K.intrinsic.object.internal;impliedSiblings=this.children.flatMap((T)=>T.impliedSiblings??[]);props=SF(this.required,this.optional);propsByKey=d(this.props,(T,o)=>[o.key,o]);propsByKeyReference=BT(this.propsByKey);expression=RY(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;if(this.index)for(let{signature:o}of this.index)T=T.concat(o.branches);return this._keyof=this.$.node("union",T)}map(T){return this.$.node("structure",this.props.flatMap(T).reduce((o,F)=>{let A=this.propsByKey[F.key];if(UT(F)){if(F.kind!=="required"&&F.kind!=="optional")return G(`Map result must have kind "required" or "optional" (was ${F.kind})`);return o[F.kind]=yT(o[F.kind],F),o}let y=F.kind??A?.kind??"required",S=d(F,(f,$)=>(f in fy.implementation.keys)?[f,$]:[]);return o[y]=yT(o[y],this.$.node(y,S)),o},{}))}assertHasKeys(T){let o=T.filter((F)=>!Jy(F,this.keyof()));if(o.length)return G(J1(this.expression,o))}get(T,...o){let F,A=!1,y=YY(T);if((typeof y==="string"||typeof y==="symbol")&&this.propsByKey[y])F=this.propsByKey[y].value,A=this.propsByKey[y].required;if(this.index){for(let f of this.index)if(Jy(y,f.signature))F=F?.and(f.value)??f.value}if(this.sequence&&Jy(y,K.intrinsic.nonNegativeIntegerString))if(P(y,"root")){if(this.sequence.variadic)F=F?.and(this.sequence.element)??this.sequence.element}else{let f=Number.parseInt(y);if(f<this.sequence.prevariadic.length){let $=this.sequence.prevariadic[f].node;F=F?.and($)??$,A||=f<this.sequence.prefixLength}else if(this.sequence.variadic){let $=this.$.node("union",this.sequence.variadicOrPostfix);F=F?.and($)??$}}if(!F){if(this.sequence?.variadic&&P(y,"root")&&y.extends(K.intrinsic.number))return G(ZY(y.expression,this.sequence.expression));return G(J1(this.expression,[y]))}let S=F.get(...o);return A?S:S.or(K.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((F)=>F.hasKind("required")?this.$.node("optional",F.inner):F)})}require(){let{optional:T,...o}=this.inner;return this.$.node("structure",{...o,required:this.props.map((F)=>F.hasKind("optional")?{key:F.key,value:F.value}:F)})}merge(T){let o=this.filterKeys("omit",[T.keyof()]);if(T.required)o.required=yT(o.required,T.required);if(T.optional)o.optional=yT(o.optional,T.optional);if(T.index)o.index=yT(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 F=ey(this.inner),A=(y)=>{let S=o.some((f)=>Jy(y,f));return T==="pick"?S:!S};if(F.required)F.required=F.required.filter((y)=>A(y.key));if(F.optional)F.optional=F.optional.filter((y)=>A(y.key));if(F.index)F.index=F.index.filter((y)=>A(y.signature));return F}traverseAllows=(T,o)=>this._traverse("Allows",T,o);traverseApply=(T,o)=>this._traverse("Apply",T,o);_traverse=(T,o,F)=>{let A=F?.currentErrorCount??0;for(let y=0;y<this.props.length;y++)if(T==="Allows"){if(!this.props[y].traverseAllows(o,F))return!1}else if(this.props[y].traverseApply(o,F),F.failFast&&F.currentErrorCount>A)return!1;if(this.sequence){if(T==="Allows"){if(!this.sequence.traverseAllows(o,F))return!1}else if(this.sequence.traverseApply(o,F),F.failFast&&F.currentErrorCount>A)return!1}if(this.index||this.undeclared==="reject"){let y=Object.keys(o);y.push(...Object.getOwnPropertySymbols(o));for(let S=0;S<y.length;S++){let f=y[S];if(this.index){for(let $ of this.index)if($.signature.traverseAllows(f,F)){if(T==="Allows"){if(!Go(f,()=>$.value.traverseAllows(o[f],F),F))return!1}else if(Go(f,()=>$.value.traverseApply(o[f],F),F),F.failFast&&F.currentErrorCount>A)return!1}}if(this.undeclared==="reject"&&!this.declaresKey(f)){if(T==="Allows")return!1;if(F.errorFromNodeContext({code:"predicate",expected:"removed",actual:"",relativePath:[f],meta:this.meta}),F.failFast)return!1}}}if(this.structuralMorph&&F&&!F.hasError())F.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&&K.intrinsic.nonNegativeIntegerString.allows(T);_compileDeclaresKey(T){let o=[];if(this.props.length)o.push(`k in ${this.propsByKeyReference}`);if(this.index)for(let F of this.index)o.push(T.invoke(F.signature,{kind:"Allows",arg:"k"}));if(this.sequence)o.push("$ark.intrinsic.nonNegativeIntegerString.allows(k)");return o.join(" || ")||"false"}get structuralMorph(){return this.cacheGetter("structuralMorph",OY(this))}structuralMorphRef=this.structuralMorph&&BT(this.structuralMorph);compile(T){if(T.traversalKind==="Apply")T.initializeErrorCount();for(let o of this.props)if(T.check(o),T.traversalKind==="Apply")T.returnIfFailFast();if(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(["),XY(T,this),T.line("])")})}compileExhaustiveEntry(T){if(T.const("k","keys[i]"),this.index)for(let o of this.index)T.if(`${T.invoke(o.signature,{arg:"k",kind:"Allows"})}`,()=>T.traverseKey("k","data[k]",o.value));if(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":let F=this.sequence?.reduceJsonSchema(T,o)??T;if(this.props.length||this.index)return o.fallback.arrayObject({code:"arrayObject",base:F,object:this.reduceObjectJsonSchema({type:"object"},o)});return F;default:return LT.throwInternalOperandError("structure",T)}}reduceObjectJsonSchema(T,o){if(this.props.length){T.properties={};for(let F of this.props){let A=F.value.toJsonSchemaRecurse(o);if(typeof F.key==="symbol"){o.fallback.symbolKey({code:"symbolKey",base:T,key:F.key,value:A,optional:F.optional});continue}if(F.hasDefault()){let y=typeof F.default==="function"?F.default():F.default;A.default=K.intrinsic.jsonData.allows(y)?y:o.fallback.defaultValue({code:"defaultValue",base:A,value:y})}T.properties[F.key]=A}if(this.requiredKeys.length&&T.properties)T.required=this.requiredKeys.filter((F)=>typeof F==="string"&&(F in T.properties))}if(this.index)for(let F of this.index){let A=F.value.toJsonSchemaRecurse(o);if(F.signature.equals(K.intrinsic.string)){T.additionalProperties=A;continue}for(let y of F.signature.branches){if(!y.extends(K.intrinsic.string)){T=o.fallback.symbolKey({code:"symbolKey",base:T,key:null,value:A,optional:!1});continue}let S={type:"string"};if(y.hasKind("morph"))S=o.fallback.morph({code:"morph",base:y.in.toJsonSchemaRecurse(o),out:y.out.toJsonSchemaRecurse(o)});if(!y.hasKind("intersection"))return $T(`Unexpected index branch kind ${y.kind}.`);let{pattern:f}=y.inner;if(f){let $=Object.assign(S,{pattern:f[0].rule});for(let _=1;_<f.length;_++)S=o.fallback.patternIntersection({code:"patternIntersection",base:$,pattern:f[_].rule});T.patternProperties??={},T.patternProperties[$.pattern]=A}}}if(this.undeclared&&!T.additionalProperties)T.additionalProperties=!1;return T}}var K$={},MY=(T)=>{let o="";for(let F=0;F<T.defaultable.length;F++)o+=T.defaultable[F].defaultValueMorphRef;if(T.sequence?.defaultValueMorphsReference)o+=T.sequence?.defaultValueMorphsReference;if(T.undeclared==="delete"){if(o+="delete !(",T.required)for(let F of T.required)o+=F.compiledKey+" | ";if(T.optional)for(let F of T.optional)o+=F.compiledKey+" | ";if(T.index)for(let F of T.index)o+=F.signature.id+" | ";if(T.sequence)if(T.sequence.maxLength===null)o+=n.nonNegativeIntegerString.id;else for(let F=0;F<T.sequence.tuple.length;F++)o+=F+" | ";o+=")"}return o},OY=(T)=>{let o=MY(T);if(!o)return;if(K$[o])return K$[o];let F=(A,y)=>{for(let S=0;S<T.defaultable.length;S++)if(!(T.defaultable[S].key in A))T.defaultable[S].defaultValueMorph(A,y);if(T.sequence?.defaultables)for(let S=A.length-T.sequence.prefixLength;S<T.sequence.defaultables.length;S++)T.sequence.defaultValueMorphs[S](A,y);if(T.undeclared==="delete"){for(let S in A)if(!T.declaresKey(S))delete A[S]}return A};return K$[o]=F},XY=(T,o)=>{let A=`(data${o.defaultable.some((y)=>y.defaultValueMorph.length===2)||o.sequence?.defaultValueMorphs.some((y)=>y.length===2)?", ctx":""})`;return T.block(`${A} => `,(y)=>{for(let S=0;S<o.defaultable.length;S++){let{serializedKey:f,defaultValueMorphRef:$}=o.defaultable[S];y.if(`!(${f} in data)`,(_)=>_.line(`${$}${A}`))}if(o.sequence?.defaultables)y.for(`i < ${o.sequence.defaultables.length}`,(S)=>S.set("data[i]",5),`data.length - ${o.sequence.prefixLength}`);if(o.undeclared==="delete")y.forIn("data",(S)=>S.if(`!(${o._compileDeclaresKey(S)})`,(f)=>f.line("delete data[k]")));return y.return("data")})},U$={implementation:WY,Node:R1},YY=(T)=>{if(P(T,"root")&&T.hasKind("unit"))T=T.unit;if(typeof T==="number")T=`${T}`;return T},ZY=(T,o)=>`${T} is not allowed as an array index on ${o}. Use the 'nonNegativeIntegerString' keyword instead.`,RS=(T,o,F)=>{let[A,y]=p_(T.branches,(f)=>f.hasKind("unit"));if(!A.length)return{index:F.node("index",{signature:T,value:o})};let S={};for(let f of A){let $=F.node("required",{key:f.unit,value:o});S[$.kind]=yT(S[$.kind],$)}if(y.length)S.index=F.node("index",{signature:y,value:o});return S},HY=(T)=>P(T,"root")?T.expression:r(T),J1=(T,o)=>`Key${o.length===1?"":"s"} ${o.map(HY).join(", ")} ${o.length===1?"does":"do"} not exist on ${T}`;var XA={...j0,alias:_y.implementation,domain:_S.implementation,unit:Z$.implementation,proto:Ry.implementation,union:Y$.implementation,morph:O$.implementation,intersection:M$.implementation,divisor:af.implementation,pattern:f$.implementation,predicate:sf.implementation,required:G$.implementation,optional:fy.implementation,index:H$.implementation,sequence:w$.implementation,structure:U$.implementation};K.defaultConfig=h_(Object.assign(d(XA,(T,o)=>[T,o.defaults]),{jitless:d_(),clone:u_,onUndeclaredKey:"ignore",exactOptionalPropertyTypes:!0,numberAllowsNaN:!1,dateAllowsInvalid:!1,onFail:null,keywords:{},toJsonSchema:LT.defaultConfig}));K.resolvedConfig=eA(K.defaultConfig,K.config);var m0={...x0,alias:_y.Node,domain:_S.Node,unit:Z$.Node,proto:Ry.Node,union:Y$.Node,morph:O$.Node,intersection:M$.Node,divisor:af.Node,pattern:f$.Node,predicate:sf.Node,required:G$.Node,optional:fy.Node,index:H$.Node,sequence:w$.Node,structure:U$.Node};class HA extends Bf{get[Ro](){return"module"}}var z$=(T,o)=>new HA(d(T,(F,A)=>[F,P(A,"module")?z$(A,o):o.bindReference(A)]));var GY=(T)=>HT(T)?T:("branches"in T)&&HT(T.branches)?T.branches:void 0,wY=(T,o)=>G(`Node of kind ${o} is not valid as a ${T} definition`),W1=(T)=>`#${T} duplicates public alias ${T}`,Q$={};K.ambient??={};var M1,X1="function $",EY=(T)=>Y1(T,Z1(T)),Y1=(T,o)=>{let F=o.write(X1,4),A=o.compile()();for(let y of T){if(y.precompilation)continue;if(y.traverseAllows=A[`${y.id}Allows`].bind(A),y.isRoot()&&!y.allowsRequiresContext)y.allows=y.traverseAllows;if(y.traverseApply=A[`${y.id}Apply`].bind(A),A[`${y.id}Optimistic`])y.traverseOptimistic=A[`${y.id}Optimistic`].bind(A);y.precompilation=F}},Z1=(T)=>new ay().return(T.reduce((o,F)=>{let A=new aA({kind:"Allows"}).indent();F.compile(A);let y=A.write(`${F.id}Allows`),S=new aA({kind:"Apply"}).indent();F.compile(S);let f=S.write(`${F.id}Apply`),$=`${o}${y},
|
|
38
44
|
${f},
|
|
39
|
-
`;if(!F.hasKind("union"))return $;let _=new
|
|
45
|
+
`;if(!F.hasKind("union"))return $;let _=new aA({kind:"Allows",optimistic:!0}).indent();F.compile(_);let J=_.write(`${F.id}Optimistic`);return`${$}${J},
|
|
40
46
|
`},`{
|
|
41
|
-
`)+"}");class RS{config;resolvedConfig;name;get[Ro](){return"scope"}referencesById={};references=[];resolutions={};exportedNames=[];aliases={};resolved=!1;nodesByHash={};intrinsic;constructor(T,o){if(this.config=sy(U.config,o),this.resolvedConfig=sy(U.resolvedConfig,o),this.name=this.resolvedConfig.name??`anonymousScope${Object.keys(U$).length}`,this.name in U$)G(`A Scope already named ${this.name} already exists`);U$[this.name]=this,Object.entries(T).map((y)=>this.preparseOwnAliasEntry(...y)).forEach(([y,A])=>{let S=y;if(y[0]==="#"){if(S=y.slice(1),S in this.aliases)G(_1(S));this.aliases[S]=A}else{if(S in this.aliases)G(_1(y));this.aliases[S]=A,this.exportedNames.push(S)}if(!v(A,"module")&&!v(A,"generic")&&!zF(A)){let f=this.preparseOwnDefinitionFormat(A,{alias:S});if(v(f,"root"))this.resolutions[S]=this.bindReference(f);else this.resolutions[S]=this.createParseContext(f).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,(y,A)=>y.startsWith("json")?[]:[y,this.bindReference(A)]):{}}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(F,y)=>new CF(T,y?new FS(F):F,o,o,y??null)};units=(T,o)=>{let F=[];for(let A of T)if(!F.includes(A))F.push(A);let y=F.map((A)=>this.node("unit",{unit:A},o));return this.node("union",y,{...o,prereduced:!0})};lazyResolutions=[];lazilyResolve(T,o){let F=this.node("alias",{reference:o??"synthetic",resolve:T},{prereduced:!0});if(!this.resolved)this.lazyResolutions.push(F);return F}schema=(T,o)=>this.finalize(this.parseSchema(T,o));parseSchema=(T,o)=>this.node(oA(T),T,o);preparseNode(T,o,F){let y=typeof T==="string"?T:oA(o,T);if(zT(o)&&o.kind===y)return o;if(y==="alias"&&!F?.prereduced){let{reference:f}=$A.implementation.normalize(o,this);if(f.startsWith("$")){let $=this.resolveRoot(f.slice(1));o=$,y=$.kind}}else if(y==="union"&&Yo(o,"object")){let f=RY(o);if(f?.length===1)o=f[0],y=oA(o)}if(zT(o)&&o.kind===y)return o;let S=Oy[y].normalize?.(o,this)??o;if(zT(S))return S.kind===y?S:WY(y,S.kind);return{...F,$:this,kind:y,def:S,prefix:F.alias??y}}bindReference(T){let o;if(zT(T))o=T.$===this?T:new T.constructor(T.attachments,this);else o=T.$===this?T:new CF(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)??G(Q$(T))}maybeResolveRoot(T){let o=this.maybeResolve(T);if(v(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 y=Wo[o];if(v(y,"root"))return this.resolutions[T]=y;if(v(y,"context")){if(y.phase==="resolving")return this.node("alias",{reference:`$${T}`},{prereduced:!0});if(y.phase==="resolved")return $T(`Unexpected resolved context for was uncached by its scope: ${d(y)}`);y.phase="resolving";let A=this.bindReference(this.parseOwnDefinitionFormat(y.def,y));return y.phase="resolved",Wo[A.id]=A,Wo[y.id]=A,this.resolutions[T]=A}return $T(`Unexpected nodesById entry for ${o}: ${d(y)}`)}let F=this.aliases[T]??this.ambient?.[T];if(!F)return this.maybeResolveSubalias(T);if(F=this.normalizeRootScopeValue(F),v(F,"generic"))return this.resolutions[T]=this.bindReference(F);if(v(F,"module"))if(F.root)return this.resolutions[T]=this.bindReference(F.root);else return G(H1(T));return this.resolutions[T]=this.parse(F,{alias:T})}createParseContext(T){let o=T.id??A$(T.prefix);return Wo[o]=Object.assign(T,{[Ro]:"context",$:this,id:o,phase:"unresolved"})}traversal(T){return new go(T,this.resolvedConfig)}import(...T){return new Yy(l(this.export(...T),(o,F)=>[`#${o}`,F]))}precompilation;_exportedResolutions;_exports;export(...T){if(!this._exports){this._exports={};for(let F of this.exportedNames){let y=this.aliases[F];this._exports[F]=v(y,"module")?w$(y,this):W1(this.maybeResolve(F))}if(this.lazyResolutions.forEach((F)=>F.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 F=X1(this.references);this.precompilation=F.write(O1,4),M1(this.references,F)}this.resolved=!0}let o=T.length?T:this.exportedNames;return new Yy(l(o,(F,y)=>[y,this._exports[y]]))}resolve(T){return this.export()[T]}node=(T,o,F={})=>{let y=this.preparseNode(T,o,F);if(zT(y))return this.bindReference(y);let A=this.createParseContext(y),S=S$(A),f=this.bindReference(S);return Wo[A.id]=f};parse=(T,o={})=>this.finalize(this.parseDefinition(T,o));parseDefinition(T,o={}){if(v(T,"root"))return this.bindReference(T);let F=this.preparseOwnDefinitionFormat(T,o);if(v(F,"root"))return this.bindReference(F);let y=this.createParseContext(F);Wo[y.id]=y;let A=this.bindReference(this.parseOwnDefinitionFormat(T,y));if(A.isCyclic)A=t0(A,y.id);return Wo[y.id]=A,A}finalize(T){if(W1(T),!T.precompilation&&!this.resolvedConfig.jitless)OY(T.references);return T}}class z$ extends RS{parseOwnDefinitionFormat(T,o){return S$(o)}preparseOwnDefinitionFormat(T,o){return this.preparseNode(oA(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((F)=>{if(o.id in F.referencesById)Object.assign(F.referencesById,o.referencesById)})}),T},Y1=(T)=>l(T,(o,F)=>[o,v(F,"root")||v(F,"generic")?F.json:v(F,"module")?Y1(F):$T(`Unexpected resolution ${d(F)}`)]),K$=(T,o)=>{let F=o.indexOf(".");if(F===-1)return;let y=o.slice(0,F),A=T[y];if(A===void 0)return;if(!v(A,"module"))return G(MY(y));let S=o.slice(F+1),f=A[S];if(f===void 0)return K$(A,S);if(v(f,"root")||v(f,"generic"))return f;if(v(f,"module"))return f.root??G(H1(o));$T(`Unexpected resolution for alias '${o}': ${d(f)}`)},WS=(T,o)=>new z$(T,o),RA=new z$({});var Z1=(T,o)=>{let F={};for(let y in o){let A=o[y];if(v(A,"module")){let S=Z1(T,A),f=l(S,($,_)=>[`${y}.${$}`,_]);Object.assign(F,f)}else if(v(A,"root")||v(A,"generic"))F[y]=A;else $T(`Unexpected scope resolution ${d(A)}`)}return F},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`;RA.export();var{schema:MT,node:Zy,defineSchema:KU,generic:po}=RA;var V$="^(?:0|[1-9]\\d*)$",XY=new RegExp(V$),VU=BT(XY);var G1=WS({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={...G1};var E1=WS({integer:{domain:"number",divisor:1},lengthBoundable:["string",Array],key:["string","symbol"],nonNegativeIntegerString:{domain:"string",pattern:V$}},{prereducedAliases:!0}).export();Object.assign(U.intrinsic,E1);var YY=WS({jsonPrimitive:["string","number",{unit:!0},{unit:!1},{unit:null}],jsonObject:{domain:"object",index:{signature:"string",value:"$jsonData"}},jsonData:["$jsonPrimitive","$jsonObject"]},{prereducedAliases:!0}).export(),n={...G1,...E1,...YY,emptyStructure:Zy("structure",{},{prereduced:!0})};U.intrinsic={...n};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 F=new Date(T);if(w1(F))return F;let y=o0(T);if(y!==void 0){let A=new Date(y);if(w1(A))return A}return o?G(o===!0?D$(T):o):void 0};var C$=(T,o)=>{let F=T.scanner.shiftUntil(HY[V1[o]]);if(T.scanner.lookahead==="")return T.error(EY(F,o));if(T.scanner.shift(),o==="/"){try{new RegExp(F)}catch(y){G(String(y))}T.root=T.ctx.$.node("intersection",{domain:"string",pattern:F},{prereduced:!0})}else if(xT(o,L$))T.root=T.ctx.$.node("unit",{unit:F});else{let y=z1(F,D$(F));T.root=T.ctx.$.node("unit",{meta:F,unit:y})}},L$={"'":1,'"':1},Q1={"/":1,"'":1,'"':1},V1={"d'":"'",'d"':'"',"'":"'",'"':'"',"/":"/"},HY={"'":(T)=>T.lookahead==="'",'"':(T)=>T.lookahead==='"',"/":(T)=>T.lookahead==="/"},GY={'"':"double-quote","'":"single-quote","/":"forward slash"},EY=(T,o)=>`${o}${T} requires a closing ${GY[V1[o]]}`;var D1=(T)=>`Private type references should not include '#'. Use '${T}' instead.`,OS="Optional definitions like 'string?' are only valid as properties in an object or tuple",MS="Defaultable definitions like 'number = 0' are only valid as properties in an object or tuple";var C1={">":!0,">=":!0},L1={"<":!0,"<=":!0};var Hy={"<":">",">":"<","<=":">=",">=":"<=","==":"=="},I1=(T)=>`Unmatched )${T===""?"":` before ${T}`}`,XS=(T)=>`Missing ${T}`,k1=(T,o)=>`Left bounds are only valid when paired with right bounds (try ...${o}${T})`,YS=(T)=>`Left-bounded expressions must specify their limits using < or <= (was ${T})`,B1=(T,o,F,y)=>`An expression may have at most one left bound (parsed ${T}${Hy[o]}, ${F}${Hy[y]})`;var N1=(T,o,F)=>p1(T,o,F,[]),p1=(T,o,F,y)=>{let A=F.parseUntilFinalizer();if(y.push(A.root),A.finalizer===">"){if(y.length!==o.params.length)return F.error(I$(T,o.names,y.map((S)=>S.expression)));return y}if(A.finalizer===",")return p1(T,o,F,y);return A.error(XS(">"))},I$=(T,o,F)=>`${T}<${o.join(", ")}> requires exactly ${o.length} args (got ${F.length}${F.length===0?"":`: ${F.join(", ")}`})`;var k$=(T)=>{let o=T.scanner.shiftUntilNextTerminator();if(o==="keyof")T.addPrefix("keyof");else T.root=UY(T,o)},wY=(T,o,F)=>{if(F.scanner.shiftUntilNonWhitespace(),F.scanner.shift()!=="<")return F.error(I$(T,o.names,[]));let A=N1(T,o,F);return o(...A)},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 y=T.ctx.args[o];if(typeof y!=="string")return y;return T.ctx.$.node("alias",{reference:y},{prereduced:!0})}let F=T.ctx.$.maybeResolve(o);if(v(F,"root"))return F;if(F===void 0)return;if(v(F,"generic"))return wY(o,F,T);return G(`Unexpected resolution ${d(F)}`)},zY=(T,o)=>{let F=F0(o);if(F!==void 0)return T.ctx.$.node("unit",{unit:F});let y=A0(o);if(y!==void 0)return T.ctx.$.node("unit",{unit:y})},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 p$=(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(QF)?p$(T.shiftedByOne()):T.scanner.lookahead==="d"?T.scanner.nextLookahead in L$?C$(T,`${T.scanner.shift()}${T.scanner.shift()}`):k$(T):k$(T);class OF extends qf{shiftUntilNextTerminator(){return this.shiftUntilNonWhitespace(),this.shiftUntil(()=>(this.lookahead in OF.terminatingChars))}static terminatingChars={"<":1,">":1,"=":1,"|":1,"&":1,")":1,"[":1,"%":1,",":1,":":1,"?":1,"#":1,...QF};static finalizingLookaheads={">":1,",":1,"":1,"=":1,"?":1};static lookaheadIsFinalizing=(T,o)=>T===">"?o[0]==="="?o[1]==="=":o.trimStart()===""||xT(o.trimStart()[0],OF.terminatingChars):T==="="?o[0]!=="=":T===","||T==="?"}var b1=(T,o)=>{let F=VY(T,o);if(T.root.hasKind("unit")){if(typeof T.root.unit==="number"){T.reduceLeftBound(T.root.unit,F),T.unsetRoot();return}if(T.root.unit instanceof Date){let y=`d'${T.root.description??T.root.unit.toISOString()}'`;T.unsetRoot(),T.reduceLeftBound(y,F);return}}return CY(T,F)},j1={"<":1,">":1,"=":1},VY=(T,o)=>T.scanner.lookaheadIs("=")?`${o}${T.scanner.shift()}`:o;var x1=(T,o,F,y)=>{if(F.extends(U.intrinsic.number)){if(typeof o!=="number")return G(x$(T,o,y));return T==="=="?["min","max"]:T[0]===">"?["min"]:["max"]}if(F.extends(U.intrinsic.lengthBoundable)){if(typeof o!=="number")return G(x$(T,o,y));return T==="=="?["exactLength"]:T[0]===">"?["minLength"]:["maxLength"]}if(F.extends(U.intrinsic.Date))return T==="=="?["after","before"]:T[0]===">"?["after"]:["before"];return G(Q0(F.expression))},DY=(T)=>({rule:U1(T.limit)?K1(T.limit):T.limit,exclusive:T.comparator.length===1}),CY=(T,o)=>{let F=T.unsetRoot(),y=T.scanner.location;T.parseOperand();let A=T.unsetRoot(),S=T.scanner.sliceChars(y,T.scanner.location);if(T.root=F,!A.hasKind("unit")||typeof A.unit!=="number"&&!(A.unit instanceof Date))return T.error(x$(o,S,"right"));let f=A.unit,$=o.length===1,_=x1(o,typeof f==="number"?f:S,F,"right");for(let R of _)T.constrainRoot(R,o==="=="?{rule:f}:{rule:f,exclusive:$});if(!T.branches.leftBound)return;if(!xT(o,L1))return T.error(YS(o));let J=x1(T.branches.leftBound.comparator,T.branches.leftBound.limit,F,"left");T.constrainRoot(J[0],DY(T.branches.leftBound)),T.branches.leftBound=null},x$=(T,o,F)=>`Comparator ${F==="left"?Hy[T]:T} must be ${F==="left"?"preceded":"followed"} by a corresponding literal (was ${o})`;var t1=(T)=>{T.scanner.shiftUntilNonWhitespace();let o=T.scanner.shiftUntilNextTerminator();T.root=T.root.brand(o)};var v1=(T)=>{let o=T.scanner.shiftUntilNextTerminator(),F=y0(o,{errorOnFail:q1(o)});if(F===0)T.error(q1(0));T.root=T.root.constrain("divisor",F)},q1=(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():OF.lookaheadIsFinalizing(o,T.scanner.unscanned)?T.finalize(o):xT(o,j1)?b1(T,o):o==="%"?v1(T):o==="#"?t1(T):(o in QF)?b$(T):T.error(ZS(o))},ZS=(T,o="")=>`'${T}' is not allowed here${o&&` (should be ${o})`}`,LY="Missing expected ']'";var m1=(T)=>{let o=T.unsetRoot();T.parseOperand();let F=T.unsetRoot();if(!F.hasKind("unit"))return T.error(IY(F.expression));let y=F.unit instanceof Date?()=>new Date(F.unit):F.unit;return[o,"=",y]},IY=(T)=>`Default value '${T}' must a literal value`;var j$=(T,o)=>{let F=o.$.maybeResolveRoot(T);if(F)return F;if(T.endsWith("[]")){let S=o.$.maybeResolveRoot(T.slice(0,-2));if(S)return S.array()}let y=new Gy(new OF(T),o),A=kY(y);if(y.finalizer===">")G(ZS(">"));return A},kY=(T)=>{T.parseOperand();let o=WA(T).root;if(!o)return $T(`Root was unexpectedly unset after parsing string '${T.scanner.scanned}'`);if(T.finalizer==="=")o=m1(T);else if(T.finalizer==="?")o=[o,"?"];if(T.scanner.shiftUntilNonWhitespace(),T.scanner.lookahead)G(ZS(T.scanner.lookahead));return o},WA=(T)=>{while(T.finalizer===void 0)BY(T);return T},BY=(T)=>T.hasRoot()?T.parseOperator():T.parseOperand();class Gy{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 G(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(XS(")"));this.finalizeBranches(),this.finalizer=T}reduceLeftBound(T,o){let F=Hy[o];if(!xT(F,C1))return this.error(YS(o));if(this.branches.leftBound)return this.error(B1(this.branches.leftBound.limit,this.branches.leftBound.comparator,T,F));this.branches.leftBound={comparator:F,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 WA(new Gy(this.scanner,this.ctx))}parseOperator(){return b$(this)}parseOperand(){return p$(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",HS=(T,o,F)=>{T.shiftUntilNonWhitespace();let y=T.shiftUntilNextTerminator();if(y===""){if(T.lookahead===""&&o.length)return o;return G(NY)}return T.shiftUntilNonWhitespace(),pY(T,y,o,F)},P1="extends ",pY=(T,o,F,y)=>{if(T.shiftUntilNonWhitespace(),T.unscanned.startsWith(P1))T.jumpForward(P1.length);else{if(T.lookahead===",")T.shift();return F.push(o),HS(T,F,y)}let A=WA(new Gy(T,y));return F.push([o,A.root]),HS(T,F,y)};class t$ extends ho{$;constructor(T){super((...o)=>new OA(T)(...o),{bind:T});this.$=T}in(T){return new OA(this.$,T===void 0?void 0:this.$.parse(T))}at(T,o){return new OA(this.$).at(T,o)}case(T,o){return new OA(this.$).case(T,o)}}class OA extends ho{$;in;key;branches=[];constructor(T,o){super((F)=>this.caseEntries(Object.entries(F).map(([y,A])=>y==="default"?[y,A]:[this.$.parse(y),A])));this.$=T,this.in=o}at(T,o){if(this.key)G(bY);if(this.branches.length)G(xY);return this.key=T,o?this.match(o):this}case(T,o){return this.caseEntry(this.$.parse(T),o)}caseEntry(T,o){let y=(this.key?this.$.parse({[this.key]:T}):T).pipe(o);return this.branches.push(y),this}match(T){return this(T)}strings(T){return this.caseEntries(Object.entries(T).map(([o,F])=>o==="default"?[o,F]:[this.$.node("unit",{unit:o}),F]))}caseEntries(T){for(let o=0;o<T.length;o++){let[F,y]=T[o];if(F==="default"){if(o!==T.length-1)G("default may only be specified as the last key of a switch definition");return this.default(y)}if(typeof y!=="function")return G(`Value for case "${F}" must be a function (was ${hT(y)})`);this.caseEntry(F,y)}return this}default(T){if(typeof T==="function")this.case(n.unknown,T);let o={branches:this.branches,ordered:!0};if(T==="never"||T==="assert")o.meta={onFail:h1};let F=this.$.node("union",o);if(!this.in)return this.$.finalize(F);let y=this.in.pipe(F);if(T==="never"||T==="assert")y=y.configureReferences({onFail:h1},"self");return this.$.finalize(y)}}var h1=(T)=>T.throw(),xY="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 GS=(T,o)=>{if(GT(T)){if(T[1]==="=")return[o.$.parseOwnDefinitionFormat(T[0],o),"=",T[2]];if(T[1]==="?")return[o.$.parseOwnDefinitionFormat(T[0],o),"?"]}return ES(T,o)},g1="Only required keys may make their values optional, e.g. { [mySymbol]: ['number', '?'] }",n1="Only required keys may specify default values, e.g. { value: 'number = 0' }";var u1=(T,o)=>{let F,y={},A=Py(T);for(let[f,$]of A){let _=qY(f);if(_.kind==="spread"){if(!ao(y))return G(tY);let H=o.$.parseOwnDefinitionFormat($,o);if(H.equals(n.object))continue;if(!H.hasKind("intersection")||!H.basis?.equals(n.object))return G(vY(H.expression));F=H.structure;continue}if(_.kind==="undeclared"){if($!=="reject"&&$!=="delete"&&$!=="ignore")G(jY($));y.undeclared=$;continue}let J=GS($,o),R=_;if(_.kind==="required"){if(!GT(J))q$(y,"required",{key:_.normalized,value:J},o);else q$(y,"optional",J[1]==="="?{key:_.normalized,value:J[0],default:J[2]}:{key:_.normalized,value:J[0]},o);continue}if(GT(J)){if(J[1]==="?")G(g1);if(J[1]==="=")G(n1)}if(_.kind==="optional"){q$(y,"optional",{key:_.normalized,value:J},o);continue}let M=o.$.parseOwnDefinitionFormat(R.normalized,o),Y=_S(M,J,o.$);if(Y.index)y.index=AT(y.index,Y.index);if(Y.required)y.required=AT(y.required,Y.required)}let S=o.$.node("structure",y);return o.$.parseSchema({domain:"object",structure:F?.merge(S)??S})},q$=(T,o,F,y)=>{T[o]=AT(T[o],y.$.node(o,F))},jY=(T)=>`Value of '+' key must be 'reject', 'delete', or 'ignore' (was ${d(T)})`,tY="Spread operator may only be used as the first key in an object",qY=(T)=>typeof T==="symbol"?{kind:"required",normalized:T}:T.at(-1)==="?"?T.at(-2)===uy?{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]===uy&&T[1]==="["&&T.at(-1)==="]"?{kind:"required",normalized:T.slice(1)}:T==="..."?{kind:"spread"}:T==="+"?{kind:"undeclared"}:{kind:"required",normalized:T==="\\..."?"...":T==="\\+"?"+":T},vY=(T)=>`Spread operand must resolve to an object literal type (was ${T})`;var i1=(T,o)=>rY(T)?s1[T[0]](T,o):iY(T)?l1[T[1]](T,o):null,mY=(T,o)=>o.$.parseOwnDefinitionFormat(T[1],o).keyof(),v$=(T,o)=>{if(T[2]===void 0)return G(N$(T[1],""));let F=o.$.parseOwnDefinitionFormat(T[0],o),y=o.$.parseOwnDefinitionFormat(T[2],o);if(T[1]==="|")return o.$.node("union",{branches:[F,y]});let A=T[1]==="&"?Eo(F,y,o.$):TA(F,y,o.$);if(A instanceof k)return A.throw();return A},PY=(T,o)=>o.$.parseOwnDefinitionFormat(T[0],o).array(),hY=(T,o)=>{if(typeof T[2]!=="function")return G(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})`,gY=(T,o)=>{if(typeof T[2]!=="function")return G(d1(":",T[2]));return o.$.parseOwnDefinitionFormat(T[0],o).constrain("predicate",T[2])},nY=(T,o)=>o.$.parseOwnDefinitionFormat(T[0],o).configureReferences(T[2],"shallow"),r1=(T)=>T,uY=r1({"[]":PY,"?":()=>G(OS)}),cY=r1({"|":v$,"&":v$,":":gY,"=>":hY,"|>":v$,"@":nY,"=":()=>G(MS)}),l1={...uY,...cY},iY=(T)=>l1[T[1]]!==void 0,dY=(T)=>T,s1=dY({keyof:mY,instanceof:(T,o)=>{if(typeof T[1]!=="function")return G(c1(gy(T[1])));let F=T.slice(1).map((y)=>typeof y==="function"?o.$.node("proto",{proto:y}):G(c1(gy(y))));return F.length===1?F[0]:o.$.node("union",{branches:F})},"===":(T,o)=>o.$.units(T.slice(1))}),rY=(T)=>s1[T[0]]!==void 0,c1=(T)=>`Expected a constructor following 'instanceof' operator (was ${T})`;var TR=(T,o)=>{let F=[{}],y=0;while(y<T.length){let A=!1;if(T[y]==="..."&&y<T.length-1)A=!0,y++;let S=GS(T[y],o),[f,$,_]=!GT(S)?[S]:S;if(y++,A){if(!f.extends(U.intrinsic.Array))return G(aY(f.expression));F=F.flatMap((J)=>f.distribute((R)=>sY(aA(J),R)))}else F=F.map((J)=>{if($==="?")return oR(J,f);if($==="=")return lY(J,f,_);return m$(J,f)})}return o.$.parseSchema(F.map((A)=>ao(A)?{proto:Array,exactLength:0}:{proto:Array,sequence:A}))},m$=(T,o)=>{if(T.defaultables||T.optionals)return G(T.variadic?H$:eY);if(T.variadic)T.postfix=AT(T.postfix,o);else T.prefix=AT(T.prefix,o);return T},oR=(T,o)=>{if(T.variadic)return G(FR);return T.optionals=AT(T.optionals,o),T},lY=(T,o,F)=>{if(T.variadic)return G(FR);if(T.optionals)return G(T6);return T.defaultables=AT(T.defaultables,[[o,F]]),T},a1=(T,o)=>{if(T.postfix)G(e1);if(T.variadic){if(!T.variadic.equals(o))G(e1)}else T.variadic=o.internal;return T},sY=(T,o)=>{let F=o.select({method:"find",kind:"sequence"});if(!F)return a1(T,U.intrinsic.unknown);if(F.prefix?.forEach((y)=>m$(T,y)),F.optionals?.forEach((y)=>oR(T,y)),F.variadic)a1(T,F.variadic);return F.postfix?.forEach((y)=>m$(T,y)),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",FR="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={},ES=(T,o)=>{if(typeof T==="string"){if(o.args&&Object.keys(o.args).some((y)=>T.includes(y)))return j$(T,o);let F=o6[o.$.name]??={};return F[T]??=j$(T,o)}return Yo(T,"object")?F6(T,o):G(P$(hT(T)))},F6=(T,o)=>{let F=hy(T);switch(F){case void 0:if(v(T,"root"))return T;return u1(T,o);case"Array":return y6(T,o);case"RegExp":return o.$.node("intersection",{domain:"string",pattern:T},{prereduced:!0});case"Function":{let y=zF(T)?T():T;if(v(y,"root"))return y;return G(P$("Function"))}default:return G(P$(F??d(T)))}},y6=(T,o)=>i1(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:Ao,$: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((...F)=>{if(F.length===1)return T.parse(F[0]);if(F.length===2&&typeof F[0]==="string"&&F[0][0]==="<"&&F[0].at(-1)===">"){let y=F[0].slice(1,-1),A=T.parseGenericParams(y,{});return new CF(A,F[1],T,T,null)}return T.parse(F)},{bind:T,attach:o})}}var Ey=U;class wS extends RS{get ambientAttachments(){if(!Ey.typeAttachments)return;return this.cacheGetter("ambientAttachments",l(Ey.typeAttachments,(T,o)=>[T,this.bindReference(o)]))}preparseOwnAliasEntry(T,o){let F=T.indexOf("<");if(F===-1){if(v(o,"module")||v(o,"generic"))return[T,o];let S=this.name==="ark"?T:T==="root"?this.name:`${this.name}.${T}`,f=this.resolvedConfig.keywords?.[S];if(f)o=[o,"@",f];return[T,o]}if(T.at(-1)!==">")G("'>' must be the last character of a generic declaration in a scope");let y=T.slice(0,F),A=T.slice(F+1,-1);return[y,()=>{let S=this.parseGenericParams(A,{alias:y});return E0(S,o,this)}]}parseGenericParams(T,o){return HS(new OF(T),[],this.createParseContext({...o,def:T,prefix:"generic"}))}normalizeRootScopeValue(T){if(zF(T)&&!v(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 y=ES(T,o);if(GT(y)){if(y[1]==="=")return G(MS);if(y[1]==="?")return G(OS)}return y}unit=(T)=>this.units([T]);valueOf=(T)=>this.units(P_(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,F)=>o.and(this.parse(F)),this.intrinsic.unknown);merge=(...T)=>T.reduce((o,F)=>o.merge(this.parse(F)),this.intrinsic.object);pipe=(...T)=>this.intrinsic.unknown.pipe(...T);match=new t$(this);declare=()=>({type:this.type});define(T){return T}type=new h$(this);static scope=(T,o={})=>new wS(T,o);static module=(T,o={})=>this.scope(T,o).export()}var g$=Object.assign(wS.scope,{define:(T)=>T}),TT=wS;class yR extends Ao{description='merge an object\'s properties onto another like `Merge(User, { isAdmin: "true" })`'}var A6=po(["base",n.object],["props",n.object])((T)=>T.base.merge(T.props),yR),AR=TT.module({Key:n.key,Merge:A6});class SR extends Ao{}var S6=po("element")((T)=>{let o=T.element.exclude(n.Array),F=o.array();return o.rawOr(F).pipe(KF).distribute((y)=>y.assertHasKind("morph").declareOut(F),MT)},SR),fR=TT.module({root:n.Array,readonly:"root",index:n.nonNegativeIntegerString,liftFrom:S6},{name:"Array"});var n$=MT(["string",qF.FileConstructor]),f6=n$.rawOr(n$.array()),$R=MT({meta:"an object representing parsed form data",domain:"object",index:{signature:"string",value:f6}}),JR=TT.module({root:["instanceof",FormData],value:n$,parsed:$R,parse:MT({in:FormData,morphs:(T)=>{let o={};for(let[F,y]of T)if(F in o){let A=o[F];if(typeof A==="string"||A instanceof qF.FileConstructor)o[F]=[A,y];else A.push(y)}else o[F]=y;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({...kf,...Nf},(T,o)=>(T in $6)?[]:[T,["instanceof",o]]),Array:fR,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}),US=TT.module({root:n.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)=>Zy("intersection",{domain:"string",pattern:{rule:T.source,flags:T.flags,meta:o}}),WR=LT(cy,"a well-formed integer string"),KR=TT.module({root:WR,parse:MT({in:WR,morphs:(T,o)=>{let F=Number.parseInt(T);return Number.isSafeInteger(F)?F:o.error("an integer in the range Number.MIN_SAFE_INTEGER to Number.MAX_SAFE_INTEGER")},declaredOut:n.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,""),F=0,y,A,S=!1;for(let f=o.length-1;f>=0;f--){if(y=o.substring(f,f+1),A=Number.parseInt(y,10),S)if(A*=2,A>=10)F+=A%10+1;else F+=A;else F+=A;S=!S}return!!(F%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 F=Number.parseInt(T),y=US.epoch(F);if(y instanceof Ho)return o.errors.merge(y),!1;return!0}).configure({description:"an integer string representing a safe Unix timestamp"},"self").assertHasKind("intersection"),G6=TT.module({root:XR,parse:MT({in:XR,morphs:(T)=>new Date(T),declaredOut:n.Date})},{name:"string.date.epoch"}),YR=LT(Z6,"an ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) date").internal.assertHasKind("intersection"),E6=TT.module({root:YR,parse:MT({in:YR,morphs:(T)=>new Date(T),declaredOut:n.Date})},{name:"string.date.iso"}),w6=TT.module({root:MR,parse:MT({declaredIn:MR,in:"string",morphs:(T,o)=>{let F=new Date(T);if(Number.isNaN(F.valueOf()))return o.error("a parsable date");return F},declaredOut:n.Date}),iso:E6,epoch:G6},{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])",LF=`(${ZR}[.]){3}${ZR}`,K6=new RegExp(`^${LF}$`),tT="(?:[0-9a-fA-F]{1,4})",z6=new RegExp(`^((?:${tT}:){7}(?:${tT}|:)|(?:${tT}:){6}(?:${LF}|:${tT}|:)|(?:${tT}:){5}(?::${LF}|(:${tT}){1,2}|:)|(?:${tT}:){4}(?:(:${tT}){0,1}:${LF}|(:${tT}){1,3}|:)|(?:${tT}:){3}(?:(:${tT}){0,2}:${LF}|(:${tT}){1,4}|:)|(?:${tT}:){2}(?:(:${tT}){0,3}:${LF}|(:${tT}){1,5}|:)|(?:${tT}:){1}(?:(:${tT}){0,4}:${LF}|(:${tT}){1,6}|:)|(?::((?::${tT}){0,5}:${LF}|(?::${tT}){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"}),wy="a JSON string",zR=(T)=>{if(!(T instanceof SyntaxError))throw T;return`must be ${wy} (${T})`},V6=MT({meta:wy,domain:"string",predicate:{meta:wy,predicate:(T,o)=>{try{return JSON.parse(T),!0}catch(F){return o.reject({code:"predicate",expected:wy,problem:zR(F)})}}}}),D6=(T,o)=>{if(T.length===0)return o.error({code:"predicate",expected:wy,actual:"empty"});try{return JSON.parse(T)}catch(F){return o.error({code:"predicate",expected:wy,problem:zR(F)})}},C6=TT.module({root:V6,parse:MT({meta:"safe JSON string parser",in:"string",morphs:D6,declaredOut:n.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"],MA=l(QR,(T,o)=>[o,MT({domain:"string",predicate:(F)=>F.normalize(o)===F,meta:`${o}-normalized unicode`})]),KS=l(QR,(T,o)=>[o,MT({in:"string",morphs:(F)=>F.normalize(o),declaredOut:MA[o]})]),I6=TT.module({root:KS.NFC,preformatted:MA.NFC},{name:"string.normalize.NFC"}),k6=TT.module({root:KS.NFD,preformatted:MA.NFD},{name:"string.normalize.NFD"}),B6=TT.module({root:KS.NFKC,preformatted:MA.NFKC},{name:"string.normalize.NFKC"}),N6=TT.module({root:KS.NFKD,preformatted:MA.NFKD},{name:"string.normalize.NFKD"}),p6=TT.module({root:"NFC",NFC:I6,NFD:k6,NFKC:B6,NFKD:N6},{name:"string.normalize"}),GR=LT(dA,"a well-formed numeric string"),x6=TT.module({root:GR,parse:MT({in:GR,morphs:(T)=>Number.parseFloat(T),declaredOut:n.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-]+)*))?$/,j6=LT(b6,"a semantic version (see https://semver.org/)"),ER=LT(/^\S.*\S$|^\S?$/,"trimmed"),t6=TT.module({root:MT({in:"string",morphs:(T)=>T.trim(),declaredOut:ER}),preformatted:ER},{name:"string.trim"}),wR=LT(/^[A-Z]*$/,"only uppercase letters"),q6=TT.module({root:MT({in:"string",morphs:(T)=>T.toUpperCase(),declaredOut:wR}),preformatted:wR},{name:"string.upper"}),v6=(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:v6}}),m6=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:n.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:p6,numeric:x6,semver:j6,trim:t6,upper:q6,url:m6,uuid:P6},{name:"string"});var DR=TT.module({bigint:n.bigint,boolean:n.boolean,false:n.false,never:n.never,null:n.null,number:n.number,object:n.object,string:n.string,symbol:n.symbol,true:n.true,unknown:n.unknown,undefined:n.undefined}),CR=TT.module({root:n.unknown,any:n.unknown},{name:"unknown"}),h6=TT.module({root:n.jsonObject,stringify:Zy("morph",{in:n.jsonObject,morphs:(T)=>JSON.stringify(T),declaredOut:n.string})},{name:"object.json"}),LR=TT.module({root:n.object,json:h6},{name:"object"});class IR extends Ao{description='instantiate an object from an index signature and corresponding value type like `Record("string", "number")`'}var g6=po(["K",n.key],"V")((T)=>({domain:"object",index:{signature:T.K,value:T.V}}),IR);class kR extends Ao{description='pick a set of properties from an object like `Pick(User, "name | age")`'}var n6=po(["T",n.object],["K",n.key])((T)=>T.T.pick(T.K),kR);class BR extends Ao{description='omit a set of properties from an object like `Omit(User, "age")`'}var u6=po(["T",n.object],["K",n.key])((T)=>T.T.omit(T.K),BR);class NR extends Ao{description="make all named properties of an object optional like `Partial(User)`"}var c6=po(["T",n.object])((T)=>T.T.partial(),NR);class pR extends Ao{description="make all named properties of an object required like `Required(User)`"}var i6=po(["T",n.object])((T)=>T.T.required(),pR);class xR extends Ao{description='exclude branches of a union like `Exclude("boolean", "true")`'}var d6=po("T","U")((T)=>T.T.exclude(T.U),xR);class bR extends Ao{description='extract branches of a union like `Extract("0 | false | 1", "number")`'}var r6=po("T","U")((T)=>T.T.extract(T.U),bR),jR=TT.module({Exclude:d6,Extract:r6,Omit:u6,Partial:c6,Pick:n6,Record:g6,Required:i6});var IF=g$({...DR,...jR,...RR,...AR,string:VR,number:US,object:LR,unknown:CR},{prereducedAliases:!0,name:"ark"}),gT=IF.export();Object.assign(Ey.ambient,gT);Ey.typeAttachments={string:gT.string.root,number:gT.number.root,bigint:gT.bigint,boolean:gT.boolean,symbol:gT.symbol,undefined:gT.undefined,null:gT.null,object:gT.object.root,unknown:gT.unknown.root,false:gT.false,true:gT.true,never:gT.never,arrayIndex:gT.Array.index,Key:gT.Key,Record:gT.Record,Array:gT.Array.root,Date:gT.Date};var xo=Object.assign(IF.type,Ey.typeAttachments),l6=IF.match,s6=IF.generic,cz=IF.schema,a6=IF.define,e6=IF.declare;function zS(T=Math.random){return T().toString(36).slice(2)}class XA extends Promise{fate;resolve;reject;done=!1;constructor(T){let o,F;super((y,A)=>{o=y,F=A});this.resolve=o,this.reject=F,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((F)=>{this.pass(o,F)},(F)=>{this.fail(o,F)})}else this.resolve(T),this.fate=void 0}}var tR=(T,o,F=ST.STORE)=>{return MF(F,{key:`${T.key}:JSON`,get:({get:y})=>o.toJson(y(T)),set:({set:y},A)=>{y(T,o.fromJson(A))}})};function x(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 F of o)F(T)}}class u$ extends oT{state;constructor(T){super();this.state=T}next(T){this.state=T,super.next(T)}}function XF(T,o,F){let y={key:o.key,type:"atom_family"},A=T.families.get(o.key);if(A)T.logger.error("\u2757","atom_family",o.key,`Overwriting an existing ${TF(A)} "${A.key}" in store "${T.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);let S=new oT,$=Object.assign((_)=>{let J=yT(_),R={key:o.key,subKey:J},M=`${o.key}(${J})`,Y=x(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 S.next({type:"state_creation",token:w}),w},y,{subject:S,install:(_)=>XF(_,o),internalRoles:F});return T.families.set(o.key,$),T.defaults.set(o.key,o.default),y}function qR(T,o){if("mutable"in o)return YA(T,o);return XF(T,o)}function YF(T,o,F){let y={key:o.key,type:"readonly_selector_family"},A=T.families.get(o.key);if(A)T.logger.error("\u2757","readonly_selector_family",o.key,`Overwriting an existing ${TF(A)} "${A.key}" in store "${T.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);let S=new oT,$=Object.assign((_)=>{let J=yT(_),R={key:o.key,subKey:J},M=`${o.key}(${J})`,Y=x(T),H=ZA(Y,{key:M,get:o.get(_)},R);return S.next({type:"state_creation",token:H}),H},y,{internalRoles:F,subject:S,install:(_)=>YF(_,o),default:(_)=>{return o.get(_)({get:(...R)=>OT(T,...R),find:(...R)=>i(T,...R),json:(R)=>nT(T,R)})}});return T.families.set(o.key,$),y}function QS(T,o){if("set"in o)return HA(T,o);return YF(T,o)}class VS{_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 VS([...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 vR(T,o){let F=yT(o),y=`${T.key}(${F})`,A=TZ[T.type],S={key:y,type:A};return Object.assign(S,{family:{key:T.key,subKey:F}}),Object.assign(S,{counterfeit:!0}),S}function wo(T){let o={key:T.key,type:T.type};if("family"in T)o.family=T.family;return o}function Uy(T){return mR(ST.STORE,T)}function PF(T){return qR(ST.STORE,T)}function c$(...T){if(T.length===2)return OT(ST.STORE,...T);return OT(ST.STORE,...T)}function DS(T,o,F=ST.STORE){return F.joins.set(T.key,new GA(T,o,F)),{key:T.key,type:"join",a:T.between[0],b:T.between[1],cardinality:T.cardinality}}function hR(T){return gR(T,ST.STORE)}var i$=(T)=>(o,F,y,A,...S)=>{console[T](`${o} ${F} "${y}" ${A}`,...S)},oZ={error:i$("error"),info:i$("info"),warn:i$("warn")};class d${logLevel;filter;logger;constructor(T,o,F=oZ){this.logLevel=T,this.filter=o,this.logger=F}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 nQ=Symbol("claim");class nR{store;constructor(T=ST.STORE){this.store=T,uR("root",T)}allocate(T,o,F){return hF(this.store,T,o,F)}fuse(T,o,F){return cR(this.store,T,o,F)}deallocate(T){gF(this.store,T)}claim(T,o,F){return Ky(this.store,T,o,F)}}class r${store;realm;constructor(T=ST.STORE){this.store=T,this.realm=new nR(T)}allocate(T,o,F){hF(this.store,T,o,F)}deallocate(T){gF(this.store,T)}claim(T,o,F){Ky(this.store,T,o,F)}}function LS(T){return QS(ST.STORE,T)}function aT(T){return"epoch"in T.transactionMeta}function XT(T){return"phase"in T.transactionMeta}var iR=(T)=>{let o=x(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 TF(T){return T.type.split("_").map(YT).join(" ")}class nF extends Error{constructor(T,o){super(`${TF(T)} ${yT(T.key)} not found in store "${o.config.name}".`)}}function zy(T,o,F){return(...y)=>{let A=_T(T,o);if(A)return A.run(y,F);throw new nF(o,T)}}var IS=(T)=>(o)=>T instanceof Function?T(o):T;var kF=(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 F=o.default,y;if(F instanceof Function)y=F();else y=F;return T.logger.info("\uD83D\uDC81","atom",o.key,"could not find cached value; using default",y),y}}};var rR=(T,o)=>{if(T.operation.open){let F=performance.now();return T.logger.info("\u2757",o.type,o.key,`deferring setState at T-${F} until setState for "${T.operation.token.key}" is done`),F}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)},Qy=(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,F)=>{switch(o.type){case"mutable_atom":T.logger.info("\uD83D\uDCE2",o.type,o.key,"is now (",F.newValue,") subscribers:",o.subject.subscribers);break;case"atom":case"selector":case"readonly_selector":T.logger.info("\uD83D\uDCE2",o.type,o.key,"went (",F.oldValue,"->",F.newValue,") subscribers:",o.subject.subscribers)}o.subject.next(F)};var l$=(T,o)=>{let F=x(T),y=F.selectorAtoms.getRelatedKeys(o.key);if(F.logger.info("\uD83E\uDDF9",o.type,o.key,y?`evicting ${y.size} states downstream:`:"no downstream states",y??"to evict"),y){if(F.operation.open)F.logger.info("\uD83E\uDDF9",o.type,o.key,`[ ${[...F.operation.done].join(", ")} ] already done`);for(let A of y){if(sR(F,A))continue;eR(A,F),Qy(F,A)}}};var TW=(T,o,F)=>{let y=kF(T,o),A=y;if(o.type==="mutable_atom"&&XT(T)){let{parent:f}=T;A=wA(T,o,f)}if(A=IS(F)(A),T.logger.info("\uD83D\uDCDD","atom",o.key,"set to",A),A=bo(T,o.key,A,o.subject),FW(T,o.key))yW(T,o.key);Qy(T,o.key),l$(T,o);let S={oldValue:y,newValue:A};if(!XT(T)){aR(T,o,S);return}if(T.on.transactionApplying.state===null){let{key:f}=o;if(oW(S.newValue))return;let $={type:"atom_update",key:f,...S};if(o.family)$.family=o.family;T.transactionMeta.update.updates.push($),T.logger.info("\uD83D\uDCC1","atom",f,"stowed (",S.oldValue,"->",S.newValue,")")}else if(o.key.startsWith("*")){let f=o.key.slice(1),$=T.atoms.get(f),_=T.valueMap.get(f);if($.type==="mutable_atom"&&XT(T)){let{parent:R}=T;_=wA(T,$,R)}if(_.do(S.newValue)===null)l$(T,$)}};var kS=(T,o,F)=>{switch(o.type){case"atom":case"mutable_atom":TW(T,o,F);break;case"selector":o.set(F);break}};function AW(T,o){if(o.family){let F=T.families.get(o.family.key);if(F)return F}}function bT(T,...o){let F,y,A,S;if(o.length===2){if(F=o[0],S=o[1],y=AW(T,F)??null,y)A=F.family?rT(F.family.subKey):null,F=i(T,y,A)}else y=o[0],A=o[1],S=o[2],F=i(T,y,A);if("counterfeit"in F&&"family"in F){let _=F.family.subKey,J=T.disposalTraces.buffer.find((R)=>R?.key===_);T.logger.error("\u274C",F.type,F.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 f=
|
|
47
|
+
`)+"}");class WS{config;resolvedConfig;name;get[Ro](){return"scope"}referencesById={};references=[];resolutions={};exportedNames=[];aliases={};resolved=!1;nodesByHash={};intrinsic;constructor(T,o){if(this.config=eA(K.config,o),this.resolvedConfig=eA(K.resolvedConfig,o),this.name=this.resolvedConfig.name??`anonymousScope${Object.keys(Q$).length}`,this.name in Q$)G(`A Scope already named ${this.name} already exists`);Q$[this.name]=this;let F=Object.entries(T).map((A)=>this.preparseOwnAliasEntry(...A));for(let[A,y]of F){let S=A;if(A[0]==="#"){if(S=A.slice(1),S in this.aliases)G(W1(S));this.aliases[S]=y}else{if(S in this.aliases)G(W1(A));this.aliases[S]=y,this.exportedNames.push(S)}if(!P(y,"module")&&!P(y,"generic")&&!UF(y)){let f=this.preparseOwnDefinitionFormat(y,{alias:S});this.resolutions[S]=P(f,"root")?this.bindReference(f):this.createParseContext(f).id}}M1??=this.node("union",{branches:["string","number","object","bigint","symbol",{unit:!0},{unit:!1},{unit:void 0},{unit:null}]},{prereduced:!0}),this.nodesByHash[M1.hash]=this.node("intersection",{},{prereduced:!0}),this.intrinsic=K.intrinsic?d(K.intrinsic,(A,y)=>A.startsWith("json")?[]:[A,this.bindReference(y)]):{}}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(F,A)=>new LF(T,A?new AS(F):F,o,o,A??null)};units=(T,o)=>{let F=[];for(let y of T)if(!F.includes(y))F.push(y);let A=F.map((y)=>this.node("unit",{unit:y},o));return this.node("union",A,{...o,prereduced:!0})};lazyResolutions=[];lazilyResolve(T,o){let F=this.node("alias",{reference:o??"synthetic",resolve:T},{prereduced:!0});if(!this.resolved)this.lazyResolutions.push(F);return F}schema=(T,o)=>this.finalize(this.parseSchema(T,o));parseSchema=(T,o)=>this.node(Ay(T),T,o);preparseNode(T,o,F){let A=typeof T==="string"?T:Ay(o,T);if(UT(o)&&o.kind===A)return o;if(A==="alias"&&!F?.prereduced){let{reference:f}=_y.implementation.normalize(o,this);if(f.startsWith("$")){let $=this.resolveRoot(f.slice(1));o=$,A=$.kind}}else if(A==="union"&&Yo(o,"object")){let f=GY(o);if(f?.length===1)o=f[0],A=Ay(o)}if(UT(o)&&o.kind===A)return o;let S=XA[A].normalize?.(o,this)??o;if(UT(S))return S.kind===A?S:wY(A,S.kind);return{...F,$:this,kind:A,def:S,prefix:F.alias??A}}bindReference(T){let o;if(UT(T))o=T.$===this?T:new T.constructor(T.attachments,this);else o=T.$===this?T:new LF(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)??G(L$(T))}maybeResolveRoot(T){let o=this.maybeResolve(T);if(P(o,"generic"))return;return o}maybeResolveSubalias(T){return V$(this.aliases,T)??V$(this.ambient,T)}get ambient(){return K.ambient}maybeResolve(T){let o=this.resolutions[T];if(o){if(typeof o!=="string")return this.bindReference(o);let A=Wo[o];if(P(A,"root"))return this.resolutions[T]=A;if(P(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: ${r(A)}`);A.phase="resolving";let y=this.bindReference(this.parseOwnDefinitionFormat(A.def,A));return A.phase="resolved",Wo[y.id]=y,Wo[A.id]=y,this.resolutions[T]=y}return $T(`Unexpected nodesById entry for ${o}: ${r(A)}`)}let F=this.aliases[T]??this.ambient?.[T];if(!F)return this.maybeResolveSubalias(T);if(F=this.normalizeRootScopeValue(F),P(F,"generic"))return this.resolutions[T]=this.bindReference(F);if(P(F,"module")){if(!F.root)G(w1(T));return this.resolutions[T]=this.bindReference(F.root)}return this.resolutions[T]=this.parse(F,{alias:T})}createParseContext(T){let o=T.id??$$(T.prefix);return Wo[o]=Object.assign(T,{[Ro]:"context",$:this,id:o,phase:"unresolved"})}traversal(T){return new go(T,this.resolvedConfig)}import(...T){return new HA(d(this.export(...T),(o,F)=>[`#${o}`,F]))}precompilation;_exportedResolutions;_exports;export(...T){if(!this._exports){this._exports={};for(let F of this.exportedNames){let A=this.aliases[F];this._exports[F]=P(A,"module")?z$(A,this):O1(this.maybeResolve(F))}for(let F of this.lazyResolutions)F.resolution;if(this._exportedResolutions=G1(this,this._exports),this._json=H1(this._exportedResolutions),Object.assign(this.resolutions,this._exportedResolutions),this.references=Object.values(this.referencesById),!this.resolvedConfig.jitless){let F=Z1(this.references);this.precompilation=F.write(X1,4),Y1(this.references,F)}this.resolved=!0}let o=T.length?T:this.exportedNames;return new HA(d(o,(F,A)=>[A,this._exports[A]]))}resolve(T){return this.export()[T]}node=(T,o,F={})=>{let A=this.preparseNode(T,o,F);if(UT(A))return this.bindReference(A);let y=this.createParseContext(A),S=J$(y),f=this.bindReference(S);return Wo[y.id]=f};parse=(T,o={})=>this.finalize(this.parseDefinition(T,o));parseDefinition(T,o={}){if(P(T,"root"))return this.bindReference(T);let F=this.preparseOwnDefinitionFormat(T,o);if(P(F,"root"))return this.bindReference(F);let A=this.createParseContext(F);Wo[A.id]=A;let y=this.bindReference(this.parseOwnDefinitionFormat(T,A));if(y.isCyclic)y=P0(y,A.id);return Wo[A.id]=y,y}finalize(T){if(O1(T),!T.precompilation&&!this.resolvedConfig.jitless)EY(T.references);return T}}class D$ extends WS{parseOwnDefinitionFormat(T,o){return J$(o)}preparseOwnDefinitionFormat(T,o){return this.preparseNode(Ay(T),T,o)}preparseOwnAliasEntry(T,o){return[T,o]}normalizeRootScopeValue(T){return T}}var O1=(T)=>{let o=T.references.filter((F)=>F.hasKind("alias"));for(let F of o){Object.assign(F.referencesById,F.resolution.referencesById);for(let A of T.references)if(F.id in A.referencesById)Object.assign(A.referencesById,F.referencesById)}return T},H1=(T)=>d(T,(o,F)=>[o,P(F,"root")||P(F,"generic")?F.json:P(F,"module")?H1(F):$T(`Unexpected resolution ${r(F)}`)]),V$=(T,o)=>{let F=o.indexOf(".");if(F===-1)return;let A=o.slice(0,F),y=T[A];if(y===void 0)return;if(!P(y,"module"))return G(KY(A));let S=o.slice(F+1),f=y[S];if(f===void 0)return V$(y,S);if(P(f,"root")||P(f,"generic"))return f;if(P(f,"module"))return f.root??G(w1(o));$T(`Unexpected resolution for alias '${o}': ${r(f)}`)},MS=(T,o)=>new D$(T,o),My=new D$({});var G1=(T,o)=>{let F={};for(let A in o){let y=o[A];if(P(y,"module")){let S=G1(T,y),f=d(S,($,_)=>[`${A}.${$}`,_]);Object.assign(F,f)}else if(P(y,"root")||P(y,"generic"))F[A]=y;else $T(`Unexpected scope resolution ${r(y)}`)}return F},L$=(T)=>`'${T}' is unresolvable`,KY=(T)=>`'${T}' must reference a module to be accessed using dot syntax`,w1=(T)=>`Reference to submodule '${T}' must specify an alias`;My.export();var{schema:WT,node:GA,defineSchema:DK,generic:po}=My;var C$="^(?:0|[1-9]\\d*)$",UY=new RegExp(C$),IK=BT(UY);var E1=MS({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();K.intrinsic={...E1};var K1=MS({integer:{domain:"number",divisor:1},lengthBoundable:["string",Array],key:["string","symbol"],nonNegativeIntegerString:{domain:"string",pattern:C$}},{prereducedAliases:!0}).export();Object.assign(K.intrinsic,K1);var zY=MS({jsonPrimitive:["string","number",{unit:!0},{unit:!1},{unit:null}],jsonObject:{domain:"object",index:{signature:"string",value:"$jsonData"}},jsonData:["$jsonPrimitive","$jsonObject"]},{prereducedAliases:!0}).export(),n={...E1,...K1,...zY,emptyStructure:GA("structure",{},{prereduced:!0})};K.intrinsic={...n};var z1=(T)=>typeof T==="string"&&T[0]==="d"&&(T[1]==="'"||T[1]==='"')&&T.at(-1)===T[1],U1=(T)=>T.toString()!=="Invalid Date",Q1=(T)=>T.slice(2,-1),I$=(T)=>`'${T}' could not be parsed by the Date constructor`,V1=(T,o)=>QY(T,o),QY=(T,o)=>{let F=new Date(T);if(U1(F))return F;let A=A0(T);if(A!==void 0){let y=new Date(A);if(U1(y))return y}return o?G(o===!0?I$(T):o):void 0};var k$=(T,o)=>{let F=T.scanner.shiftUntil(VY[L1[o]]);if(T.scanner.lookahead==="")return T.error(LY(F,o));if(T.scanner.shift(),o==="/"){try{new RegExp(F)}catch(A){G(String(A))}T.root=T.ctx.$.node("intersection",{domain:"string",pattern:F},{prereduced:!0})}else if(hT(o,B$))T.root=T.ctx.$.node("unit",{unit:F});else{let A=V1(F,I$(F));T.root=T.ctx.$.node("unit",{meta:F,unit:A})}},B$={"'":1,'"':1},D1={"/":1,"'":1,'"':1},L1={"d'":"'",'d"':'"',"'":"'",'"':'"',"/":"/"},VY={"'":(T)=>T.lookahead==="'",'"':(T)=>T.lookahead==='"',"/":(T)=>T.lookahead==="/"},DY={'"':"double-quote","'":"single-quote","/":"forward slash"},LY=(T,o)=>`${o}${T} requires a closing ${DY[L1[o]]}`;var C1=(T)=>`Private type references should not include '#'. Use '${T}' instead.`,OS="Optional definitions like 'string?' are only valid as properties in an object or tuple",XS="Defaultable definitions like 'number = 0' are only valid as properties in an object or tuple";var I1={">":!0,">=":!0},k1={"<":!0,"<=":!0};var wA={"<":">",">":"<","<=":">=",">=":"<=","==":"=="},B1=(T)=>`Unmatched )${T===""?"":` before ${T}`}`,YS=(T)=>`Missing ${T}`,N1=(T,o)=>`Left bounds are only valid when paired with right bounds (try ...${o}${T})`,ZS=(T)=>`Left-bounded expressions must specify their limits using < or <= (was ${T})`,p1=(T,o,F,A)=>`An expression may have at most one left bound (parsed ${T}${wA[o]}, ${F}${wA[A]})`;var j1=(T,o,F)=>x1(T,o,F,[]),x1=(T,o,F,A)=>{let y=F.parseUntilFinalizer();if(A.push(y.root),y.finalizer===">"){if(A.length!==o.params.length)return F.error(N$(T,o.names,A.map((S)=>S.expression)));return A}if(y.finalizer===",")return x1(T,o,F,A);return y.error(YS(">"))},N$=(T,o,F)=>`${T}<${o.join(", ")}> requires exactly ${o.length} args (got ${F.length}${F.length===0?"":`: ${F.join(", ")}`})`;var p$=(T)=>{let o=T.scanner.shiftUntilNextTerminator();if(o==="keyof")T.addPrefix("keyof");else T.root=IY(T,o)},CY=(T,o,F)=>{if(F.scanner.shiftUntilNonWhitespace(),F.scanner.shift()!=="<")return F.error(N$(T,o.names,[]));let y=j1(T,o,F);return o(...y)},IY=(T,o)=>kY(T,o)??BY(T,o)??T.error(o===""?T.scanner.lookahead==="#"?C1(T.shiftedByOne().scanner.shiftUntilNextTerminator()):j$(T):L$(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 F=T.ctx.$.maybeResolve(o);if(P(F,"root"))return F;if(F===void 0)return;if(P(F,"generic"))return CY(o,F,T);return G(`Unexpected resolution ${r(F)}`)},BY=(T,o)=>{let F=y0(o);if(F!==void 0)return T.ctx.$.node("unit",{unit:F});let A=f0(o);if(A!==void 0)return T.ctx.$.node("unit",{unit:A})},j$=(T)=>{let o=T.previousOperator();return o?x$(o,T.scanner.unscanned):NY(T.scanner.unscanned)},x$=(T,o="")=>`Token '${T}' requires a right operand${o?` before '${o}'`:""}`,NY=(T)=>`Expected an expression${T?` before '${T}'`:""}`;var b$=(T)=>T.scanner.lookahead===""?T.error(j$(T)):T.scanner.lookahead==="("?T.shiftedByOne().reduceGroupOpen():T.scanner.lookaheadIsIn(D1)?k$(T,T.scanner.shift()):T.scanner.lookaheadIsIn(zF)?b$(T.shiftedByOne()):T.scanner.lookahead==="d"?T.scanner.nextLookahead in B$?k$(T,`${T.scanner.shift()}${T.scanner.shift()}`):p$(T):p$(T);class WF extends mf{shiftUntilNextTerminator(){return this.shiftUntilNonWhitespace(),this.shiftUntil(()=>(this.lookahead in WF.terminatingChars))}static terminatingChars={"<":1,">":1,"=":1,"|":1,"&":1,")":1,"[":1,"%":1,",":1,":":1,"?":1,"#":1,...zF};static finalizingLookaheads={">":1,",":1,"":1,"=":1,"?":1};static lookaheadIsFinalizing=(T,o)=>T===">"?o[0]==="="?o[1]==="=":o.trimStart()===""||hT(o.trimStart()[0],WF.terminatingChars):T==="="?o[0]!=="=":T===","||T==="?"}var q1=(T,o)=>{let F=pY(T,o);if(T.root.hasKind("unit")){if(typeof T.root.unit==="number"){T.reduceLeftBound(T.root.unit,F),T.unsetRoot();return}if(T.root.unit instanceof Date){let A=`d'${T.root.description??T.root.unit.toISOString()}'`;T.unsetRoot(),T.reduceLeftBound(A,F);return}}return xY(T,F)},v1={"<":1,">":1,"=":1},pY=(T,o)=>T.scanner.lookaheadIs("=")?`${o}${T.scanner.shift()}`:o;var b1=(T,o,F,A)=>{if(F.extends(K.intrinsic.number)){if(typeof o!=="number")return G(q$(T,o,A));return T==="=="?["min","max"]:T[0]===">"?["min"]:["max"]}if(F.extends(K.intrinsic.lengthBoundable)){if(typeof o!=="number")return G(q$(T,o,A));return T==="=="?["exactLength"]:T[0]===">"?["minLength"]:["maxLength"]}if(F.extends(K.intrinsic.Date))return T==="=="?["after","before"]:T[0]===">"?["after"]:["before"];return G(D0(F.expression))},jY=(T)=>({rule:z1(T.limit)?Q1(T.limit):T.limit,exclusive:T.comparator.length===1}),xY=(T,o)=>{let F=T.unsetRoot(),A=T.scanner.location;T.parseOperand();let y=T.unsetRoot(),S=T.scanner.sliceChars(A,T.scanner.location);if(T.root=F,!y.hasKind("unit")||typeof y.unit!=="number"&&!(y.unit instanceof Date))return T.error(q$(o,S,"right"));let f=y.unit,$=o.length===1,_=b1(o,typeof f==="number"?f:S,F,"right");for(let R of _)T.constrainRoot(R,o==="=="?{rule:f}:{rule:f,exclusive:$});if(!T.branches.leftBound)return;if(!hT(o,k1))return T.error(ZS(o));let J=b1(T.branches.leftBound.comparator,T.branches.leftBound.limit,F,"left");T.constrainRoot(J[0],jY(T.branches.leftBound)),T.branches.leftBound=null},q$=(T,o,F)=>`Comparator ${F==="left"?wA[T]:T} must be ${F==="left"?"preceded":"followed"} by a corresponding literal (was ${o})`;var P1=(T)=>{T.scanner.shiftUntilNonWhitespace();let o=T.scanner.shiftUntilNextTerminator();T.root=T.root.brand(o)};var t1=(T)=>{let o=T.scanner.shiftUntilNextTerminator(),F=S0(o,{errorOnFail:m1(o)});if(F===0)T.error(m1(0));T.root=T.root.constrain("divisor",F)},m1=(T)=>`% operator must be followed by a non-zero integer literal (was ${T})`;var v$=(T)=>{let o=T.scanner.shift();return o===""?T.finalize(""):o==="["?T.scanner.shift()==="]"?T.setRoot(T.root.array()):T.error(bY):o==="|"?T.scanner.lookahead===">"?T.shiftedByOne().pushRootToBranch("|>"):T.pushRootToBranch(o):o==="&"?T.pushRootToBranch(o):o===")"?T.finalizeGroup():WF.lookaheadIsFinalizing(o,T.scanner.unscanned)?T.finalize(o):hT(o,v1)?q1(T,o):o==="%"?t1(T):o==="#"?P1(T):(o in zF)?v$(T):T.error(HS(o))},HS=(T,o="")=>`'${T}' is not allowed here${o&&` (should be ${o})`}`,bY="Missing expected ']'";var h1=(T)=>{let o=T.unsetRoot();T.parseOperand();let F=T.unsetRoot();if(!F.hasKind("unit"))return T.error(qY(F.expression));let A=F.unit instanceof Date?()=>new Date(F.unit):F.unit;return[o,"=",A]},qY=(T)=>`Default value '${T}' must a literal value`;var P$=(T,o)=>{let F=o.$.maybeResolveRoot(T);if(F)return F;if(T.endsWith("[]")){let S=o.$.maybeResolveRoot(T.slice(0,-2));if(S)return S.array()}let A=new EA(new WF(T),o),y=vY(A);if(A.finalizer===">")G(HS(">"));return y},vY=(T)=>{T.parseOperand();let o=Oy(T).root;if(!o)return $T(`Root was unexpectedly unset after parsing string '${T.scanner.scanned}'`);if(T.finalizer==="=")o=h1(T);else if(T.finalizer==="?")o=[o,"?"];if(T.scanner.shiftUntilNonWhitespace(),T.scanner.lookahead)G(HS(T.scanner.lookahead));return o},Oy=(T)=>{while(T.finalizer===void 0)PY(T);return T},PY=(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 G(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(YS(")"));this.finalizeBranches(),this.finalizer=T}reduceLeftBound(T,o){let F=wA[o];if(!hT(F,I1))return this.error(ZS(o));if(this.branches.leftBound)return this.error(p1(this.branches.leftBound.limit,this.branches.leftBound.comparator,T,F));this.branches.leftBound={comparator:F,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(B1(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 Oy(new EA(this.scanner,this.ctx))}parseOperator(){return v$(this)}parseOperand(){return b$(this)}assertRangeUnset(){if(this.branches.leftBound)return this.error(N1(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 mY="An empty string is not a valid generic parameter name",GS=(T,o,F)=>{T.shiftUntilNonWhitespace();let A=T.shiftUntilNextTerminator();if(A===""){if(T.lookahead===""&&o.length)return o;return G(mY)}return T.shiftUntilNonWhitespace(),tY(T,A,o,F)},g1="extends ",tY=(T,o,F,A)=>{if(T.shiftUntilNonWhitespace(),T.unscanned.startsWith(g1))T.jumpForward(g1.length);else{if(T.lookahead===",")T.shift();return F.push(o),GS(T,F,A)}let y=Oy(new EA(T,A));return F.push([o,y.root]),GS(T,F,A)};class m$ extends ho{$;constructor(T){super((...o)=>new Xy(T)(...o),{bind:T});this.$=T}in(T){return new Xy(this.$,T===void 0?void 0:this.$.parse(T))}at(T,o){return new Xy(this.$).at(T,o)}case(T,o){return new Xy(this.$).case(T,o)}}class Xy extends ho{$;in;key;branches=[];constructor(T,o){super((F)=>this.caseEntries(Object.entries(F).map(([A,y])=>A==="default"?[A,y]:[this.$.parse(A),y])));this.$=T,this.in=o}at(T,o){if(this.key)G(gY);if(this.branches.length)G(hY);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,F])=>o==="default"?[o,F]:[this.$.node("unit",{unit:o}),F]))}caseEntries(T){for(let o=0;o<T.length;o++){let[F,A]=T[o];if(F==="default"){if(o!==T.length-1)G("default may only be specified as the last key of a switch definition");return this.default(A)}if(typeof A!=="function")return G(`Value for case "${F}" must be a function (was ${tT(A)})`);this.caseEntry(F,A)}return this}default(T){if(typeof T==="function")this.case(n.unknown,T);let o={branches:this.branches,ordered:!0};if(T==="never"||T==="assert")o.meta={onFail:n1};let F=this.$.node("union",o);if(!this.in)return this.$.finalize(F);let A=this.in.pipe(F);if(T==="never"||T==="assert")A=A.configureReferences({onFail:n1},"self");return this.$.finalize(A)}}var n1=(T)=>T.throw(),hY="A key matcher must be specified before the first case i.e. match.at('foo') or match.in<object>().at('bar')",gY="At most one key matcher may be specified per expression";var wS=(T,o)=>{if(HT(T)){if(T[1]==="=")return[o.$.parseOwnDefinitionFormat(T[0],o),"=",T[2]];if(T[1]==="?")return[o.$.parseOwnDefinitionFormat(T[0],o),"?"]}return ES(T,o)},u1="Only required keys may make their values optional, e.g. { [mySymbol]: ['number', '?'] }",c1="Only required keys may specify default values, e.g. { value: 'number = 0' }";var i1=(T,o)=>{let F,A={},y=vF(T);for(let[f,$]of y){let _=cY(f);if(_.kind==="spread"){if(!ao(A))return G(uY);let H=o.$.parseOwnDefinitionFormat($,o);if(H.equals(n.object))continue;if(!H.hasKind("intersection")||!H.basis?.equals(n.object))return G(iY(H.expression));F=H.structure;continue}if(_.kind==="undeclared"){if($!=="reject"&&$!=="delete"&&$!=="ignore")G(nY($));A.undeclared=$;continue}let J=wS($,o),R=_;if(_.kind==="required"){if(!HT(J))t$(A,"required",{key:_.normalized,value:J},o);else t$(A,"optional",J[1]==="="?{key:_.normalized,value:J[0],default:J[2]}:{key:_.normalized,value:J[0]},o);continue}if(HT(J)){if(J[1]==="?")G(u1);if(J[1]==="=")G(c1)}if(_.kind==="optional"){t$(A,"optional",{key:_.normalized,value:J},o);continue}let O=o.$.parseOwnDefinitionFormat(R.normalized,o),Y=RS(O,J,o.$);if(Y.index)A.index=yT(A.index,Y.index);if(Y.required)A.required=yT(A.required,Y.required)}let S=o.$.node("structure",A);return o.$.parseSchema({domain:"object",structure:F?.merge(S)??S})},t$=(T,o,F,A)=>{T[o]=yT(T[o],A.$.node(o,F))},nY=(T)=>`Value of '+' key must be 'reject', 'delete', or 'ignore' (was ${r(T)})`,uY="Spread operator may only be used as the first key in an object",cY=(T)=>typeof T==="symbol"?{kind:"required",normalized:T}:T.at(-1)==="?"?T.at(-2)===cA?{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]===cA&&T[1]==="["&&T.at(-1)==="]"?{kind:"required",normalized:T.slice(1)}:T==="..."?{kind:"spread"}:T==="+"?{kind:"undeclared"}:{kind:"required",normalized:T==="\\..."?"...":T==="\\+"?"+":T},iY=(T)=>`Spread operand must resolve to an object literal type (was ${T})`;var r1=(T,o)=>A6(T)?e1[T[0]](T,o):o6(T)?a1[T[1]](T,o):null,dY=(T,o)=>o.$.parseOwnDefinitionFormat(T[1],o).keyof(),h$=(T,o)=>{if(T[2]===void 0)return G(x$(T[1],""));let F=o.$.parseOwnDefinitionFormat(T[0],o),A=o.$.parseOwnDefinitionFormat(T[2],o);if(T[1]==="|")return o.$.node("union",{branches:[F,A]});let y=T[1]==="&"?wo(F,A,o.$):Fy(F,A,o.$);if(y instanceof k)return y.throw();return y},rY=(T,o)=>o.$.parseOwnDefinitionFormat(T[0],o).array(),lY=(T,o)=>{if(typeof T[2]!=="function")return G(l1("=>",T[2]));return o.$.parseOwnDefinitionFormat(T[0],o).pipe(T[2])},l1=(T,o)=>`${T===":"?"Narrow":"Morph"} expression requires a function following '${T}' (was ${typeof o})`,sY=(T,o)=>{if(typeof T[2]!=="function")return G(l1(":",T[2]));return o.$.parseOwnDefinitionFormat(T[0],o).constrain("predicate",T[2])},aY=(T,o)=>o.$.parseOwnDefinitionFormat(T[0],o).configureReferences(T[2],"shallow"),s1=(T)=>T,eY=s1({"[]":rY,"?":()=>G(OS)}),T6=s1({"|":h$,"&":h$,":":sY,"=>":lY,"|>":h$,"@":aY,"=":()=>G(XS)}),a1={...eY,...T6},o6=(T)=>a1[T[1]]!==void 0,F6=(T)=>T,e1=F6({keyof:dY,instanceof:(T,o)=>{if(typeof T[1]!=="function")return G(d1(nA(T[1])));let F=T.slice(1).map((A)=>typeof A==="function"?o.$.node("proto",{proto:A}):G(d1(nA(A))));return F.length===1?F[0]:o.$.node("union",{branches:F})},"===":(T,o)=>o.$.units(T.slice(1))}),A6=(T)=>e1[T[0]]!==void 0,d1=(T)=>`Expected a constructor following 'instanceof' operator (was ${T})`;var FR=(T,o)=>{let F=[{}],A=0;while(A<T.length){let y=!1;if(T[A]==="..."&&A<T.length-1)y=!0,A++;let S=wS(T[A],o),[f,$,_]=!HT(S)?[S]:S;if(A++,y){if(!f.extends(K.intrinsic.Array))return G(f6(f.expression));F=F.flatMap((J)=>f.distribute((R)=>S6(ey(J),R)))}else F=F.map((J)=>{if($==="?")return AR(J,f);if($==="=")return y6(J,f,_);return g$(J,f)})}return o.$.parseSchema(F.map((y)=>ao(y)?{proto:Array,exactLength:0}:{proto:Array,sequence:y}))},g$=(T,o)=>{if(T.defaultables||T.optionals)return G(T.variadic?E$:$6);if(T.variadic)T.postfix=yT(T.postfix,o);else T.prefix=yT(T.prefix,o);return T},AR=(T,o)=>{if(T.variadic)return G(yR);return T.optionals=yT(T.optionals,o),T},y6=(T,o,F)=>{if(T.variadic)return G(yR);if(T.optionals)return G(J6);return T.defaultables=yT(T.defaultables,[[o,F]]),T},TR=(T,o)=>{if(T.postfix)G(oR);if(T.variadic){if(!T.variadic.equals(o))G(oR)}else T.variadic=o.internal;return T},S6=(T,o)=>{let F=o.select({method:"find",kind:"sequence"});if(!F)return TR(T,K.intrinsic.unknown);if(F.prefix)for(let A of F.prefix)g$(T,A);if(F.optionals)for(let A of F.optionals)AR(T,A);if(F.variadic)TR(T,F.variadic);if(F.postfix)for(let A of F.postfix)g$(T,A);return T},f6=(T)=>`Spread element must be an array (was ${T})`,oR="A tuple may have at most one variadic element",$6="A required element may not follow an optional element",yR="An optional element may not follow a variadic element";var J6="A defaultable element may not follow an optional element without a default";var _6={},ES=(T,o)=>{if(typeof T==="string"){if(o.args&&Object.keys(o.args).some((A)=>T.includes(A)))return P$(T,o);let F=_6[o.$.name]??={};return F[T]??=P$(T,o)}return Yo(T,"object")?R6(T,o):G(n$(tT(T)))},R6=(T,o)=>{let F=gA(T);switch(F){case void 0:if(P(T,"root"))return T;return i1(T,o);case"Array":return W6(T,o);case"RegExp":return o.$.node("intersection",{domain:"string",pattern:T},{prereduced:!0});case"Function":{let A=UF(T)?T():T;if(P(A,"root"))return A;return G(n$("Function"))}default:return G(n$(F??r(T)))}},W6=(T,o)=>r1(T,o)??FR(T,o),n$=(T)=>`Type definitions must be strings or objects (was ${T})`;class u$ extends ho{constructor(T){let o=Object.assign({errors:Ho,hkt:yo,$: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((...F)=>{if(F.length===1)return T.parse(F[0]);if(F.length===2&&typeof F[0]==="string"&&F[0][0]==="<"&&F[0].at(-1)===">"){let A=F[0].slice(1,-1),y=T.parseGenericParams(A,{});return new LF(y,F[1],T,T,null)}return T.parse(F)},{bind:T,attach:o})}}var KA=K;class KS extends WS{get ambientAttachments(){if(!KA.typeAttachments)return;return this.cacheGetter("ambientAttachments",d(KA.typeAttachments,(T,o)=>[T,this.bindReference(o)]))}preparseOwnAliasEntry(T,o){let F=T.indexOf("<");if(F===-1){if(P(o,"module")||P(o,"generic"))return[T,o];let S=this.name==="ark"?T:T==="root"?this.name:`${this.name}.${T}`,f=this.resolvedConfig.keywords?.[S];if(f)o=[o,"@",f];return[T,o]}if(T.at(-1)!==">")G("'>' must be the last character of a generic declaration in a scope");let A=T.slice(0,F),y=T.slice(F+1,-1);return[A,()=>{let S=this.parseGenericParams(y,{alias:A});return z0(S,o,this)}]}parseGenericParams(T,o){return GS(new WF(T),[],this.createParseContext({...o,def:T,prefix:"generic"}))}normalizeRootScopeValue(T){if(UF(T)&&!P(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=ES(T,o);if(HT(A)){if(A[1]==="=")return G(XS);if(A[1]==="?")return G(OS)}return A}unit=(T)=>this.units([T]);valueOf=(T)=>this.units(g_(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,F)=>o.and(this.parse(F)),this.intrinsic.unknown);merge=(...T)=>T.reduce((o,F)=>o.merge(this.parse(F)),this.intrinsic.object);pipe=(...T)=>this.intrinsic.unknown.pipe(...T);match=new m$(this);declare=()=>({type:this.type});define(T){return T}type=new u$(this);static scope=(T,o={})=>new KS(T,o);static module=(T,o={})=>this.scope(T,o).export()}var c$=Object.assign(KS.scope,{define:(T)=>T}),TT=KS;class SR extends yo{description='merge an object\'s properties onto another like `Merge(User, { isAdmin: "true" })`'}var M6=po(["base",n.object],["props",n.object])((T)=>T.base.merge(T.props),SR),fR=TT.module({Key:n.key,Merge:M6});class $R extends yo{}var O6=po("element")((T)=>{let o=T.element.exclude(n.Array),F=o.array();return o.rawOr(F).pipe(KF).distribute((A)=>A.assertHasKind("morph").declareOut(F),WT)},$R),JR=TT.module({root:n.Array,readonly:"root",index:n.nonNegativeIntegerString,liftFrom:O6},{name:"Array"});var i$=WT(["string",mF.FileConstructor]),X6=i$.rawOr(i$.array()),_R=WT({meta:"an object representing parsed form data",domain:"object",index:{signature:"string",value:X6}}),RR=TT.module({root:["instanceof",FormData],value:i$,parsed:_R,parse:WT({in:FormData,morphs:(T)=>{let o={};for(let[F,A]of T)if(F in o){let y=o[F];if(typeof y==="string"||y instanceof mF.FileConstructor)o[F]=[y,A];else y.push(A)}else o[F]=A;return o},declaredOut:_R})},{name:"FormData"});var WR=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 Y6={Boolean:1,Number:1,String:1},MR=TT.module({...d({...Nf,...jf},(T,o)=>(T in Y6)?[]:[T,["instanceof",o]]),Array:JR,TypedArray:WR,FormData:RR});var Z6=WT({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"}),H6=WT({domain:"number",divisor:1}),US=TT.module({root:n.number,integer:H6,epoch:Z6,safe:WT({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 CT=(T,o,F)=>{let A={domain:"string",pattern:{rule:T.source,flags:T.flags,meta:o}};if(F)A.meta={format:F};return GA("intersection",A)},OR=CT(iA,"a well-formed integer string"),VR=TT.module({root:OR,parse:WT({in:OR,morphs:(T,o)=>{let F=Number.parseInt(T);return Number.isSafeInteger(F)?F:o.error("an integer in the range Number.MIN_SAFE_INTEGER to Number.MAX_SAFE_INTEGER")},declaredOut:n.integer})},{name:"string.integer"}),G6=CT(/^[\dA-Fa-f]+$/,"hex characters only"),w6=TT.module({root:CT(/^(?:[\d+/A-Za-z]{4})*(?:[\d+/A-Za-z]{2}==|[\d+/A-Za-z]{3}=)?$/,"base64-encoded"),url:CT(/^(?:[\w-]{4})*(?:[\w-]{2}(?:==|%3D%3D)?|[\w-]{3}(?:=|%3D)?)?$/,"base64url-encoded")},{name:"string.base64"}),XR=CT(/^[A-Z].*$/,"capitalized"),E6=TT.module({root:WT({in:"string",morphs:(T)=>T.charAt(0).toUpperCase()+T.slice(1),declaredOut:XR}),preformatted:XR},{name:"string.capitalize"}),K6=(T)=>{let o=T.replaceAll(/[ -]+/g,""),F=0,A,y,S=!1;for(let f=o.length-1;f>=0;f--){if(A=o.substring(f,f+1),y=Number.parseInt(A,10),S)y*=2,F+=y>=10?y%10+1:y;else F+=y;S=!S}return!!(F%10===0?o:!1)},U6=/^(?:4\d{12}(?:\d{3,6})?|5[1-5]\d{14}|(222[1-9]|22[3-9]\d|2[3-6]\d{2}|27[01]\d|2720)\d{12}|6(?:011|5\d\d)\d{12,15}|3[47]\d{13}|3(?:0[0-5]|[68]\d)\d{11}|(?:2131|1800|35\d{3})\d{11}|6[27]\d{14}|^(81\d{14,17}))$/,z6=WT({domain:"string",pattern:{meta:"a credit card number",rule:U6.source},predicate:{meta:"a credit card number",predicate:K6}});var Q6=/^([+-]?\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 V6=(T)=>!Number.isNaN(new Date(T).valueOf()),YR=WT({domain:"string",predicate:{meta:"a parsable date",predicate:V6}}).assertHasKind("intersection"),ZR=VR.root.internal.narrow((T,o)=>{let F=Number.parseInt(T),A=US.epoch(F);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"),D6=TT.module({root:ZR,parse:WT({in:ZR,morphs:(T)=>new Date(T),declaredOut:n.Date})},{name:"string.date.epoch"}),HR=CT(Q6,"an ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) date").internal.assertHasKind("intersection"),L6=TT.module({root:HR,parse:WT({in:HR,morphs:(T)=>new Date(T),declaredOut:n.Date})},{name:"string.date.iso"}),C6=TT.module({root:YR,parse:WT({declaredIn:YR,in:"string",morphs:(T,o)=>{let F=new Date(T);if(Number.isNaN(F.valueOf()))return o.error("a parsable date");return F},declaredOut:n.Date}),iso:L6,epoch:D6},{name:"string.date"}),I6=CT(/^[\w%+.-]+@[\d.A-Za-z-]+\.[A-Za-z]{2,}$/,"an email address","email"),GR="(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])",CF=`(${GR}[.]){3}${GR}`,k6=new RegExp(`^${CF}$`),bT="(?:[0-9a-fA-F]{1,4})",B6=new RegExp(`^((?:${bT}:){7}(?:${bT}|:)|(?:${bT}:){6}(?:${CF}|:${bT}|:)|(?:${bT}:){5}(?::${CF}|(:${bT}){1,2}|:)|(?:${bT}:){4}(?:(:${bT}){0,1}:${CF}|(:${bT}){1,3}|:)|(?:${bT}:){3}(?:(:${bT}){0,2}:${CF}|(:${bT}){1,4}|:)|(?:${bT}:){2}(?:(:${bT}){0,3}:${CF}|(:${bT}){1,5}|:)|(?:${bT}:){1}(?:(:${bT}){0,4}:${CF}|(:${bT}){1,6}|:)|(?::((?::${bT}){0,5}:${CF}|(?::${bT}){1,7}|:)))(%[0-9a-zA-Z.]{1,})?$`),N6=TT.module({root:["v4 | v6","@","an IP address"],v4:CT(k6,"an IPv4 address","ipv4"),v6:CT(B6,"an IPv6 address","ipv6")},{name:"string.ip"}),UA="a JSON string",DR=(T)=>{if(!(T instanceof SyntaxError))throw T;return`must be ${UA} (${T})`},p6=WT({meta:UA,domain:"string",predicate:{meta:UA,predicate:(T,o)=>{try{return JSON.parse(T),!0}catch(F){return o.reject({code:"predicate",expected:UA,problem:DR(F)})}}}}),j6=(T,o)=>{if(T.length===0)return o.error({code:"predicate",expected:UA,actual:"empty"});try{return JSON.parse(T)}catch(F){return o.error({code:"predicate",expected:UA,problem:DR(F)})}},x6=TT.module({root:p6,parse:WT({meta:"safe JSON string parser",in:"string",morphs:j6,declaredOut:n.jsonObject})},{name:"string.json"}),wR=CT(/^[a-z]*$/,"only lowercase letters"),b6=TT.module({root:WT({in:"string",morphs:(T)=>T.toLowerCase(),declaredOut:wR}),preformatted:wR},{name:"string.lower"}),LR=["NFC","NFD","NFKC","NFKD"],Yy=d(LR,(T,o)=>[o,WT({domain:"string",predicate:(F)=>F.normalize(o)===F,meta:`${o}-normalized unicode`})]),zS=d(LR,(T,o)=>[o,WT({in:"string",morphs:(F)=>F.normalize(o),declaredOut:Yy[o]})]),q6=TT.module({root:zS.NFC,preformatted:Yy.NFC},{name:"string.normalize.NFC"}),v6=TT.module({root:zS.NFD,preformatted:Yy.NFD},{name:"string.normalize.NFD"}),P6=TT.module({root:zS.NFKC,preformatted:Yy.NFKC},{name:"string.normalize.NFKC"}),m6=TT.module({root:zS.NFKD,preformatted:Yy.NFKD},{name:"string.normalize.NFKD"}),t6=TT.module({root:"NFC",NFC:q6,NFD:v6,NFKC:P6,NFKD:m6},{name:"string.normalize"}),ER=CT(ly,"a well-formed numeric string"),h6=TT.module({root:ER,parse:WT({in:ER,morphs:(T)=>Number.parseFloat(T),declaredOut:n.number})},{name:"string.numeric"}),KR="a regex pattern",g6=WT({domain:"string",predicate:{meta:KR,predicate:(T,o)=>{try{return new RegExp(T),!0}catch(F){return o.reject({code:"predicate",expected:KR,problem:String(F)})}}},meta:{format:"regex"}}),n6=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[A-Za-z-][\dA-Za-z-]*)(?:\.(?:0|[1-9]\d*|\d*[A-Za-z-][\dA-Za-z-]*))*))?(?:\+([\dA-Za-z-]+(?:\.[\dA-Za-z-]+)*))?$/,u6=CT(n6,"a semantic version (see https://semver.org/)"),UR=CT(/^\S.*\S$|^\S?$/,"trimmed"),c6=TT.module({root:WT({in:"string",morphs:(T)=>T.trim(),declaredOut:UR}),preformatted:UR},{name:"string.trim"}),zR=CT(/^[A-Z]*$/,"only uppercase letters"),i6=TT.module({root:WT({in:"string",morphs:(T)=>T.toUpperCase(),declaredOut:zR}),preformatted:zR},{name:"string.upper"}),d6=(T)=>{if(URL.canParse)return URL.canParse(T);try{return new URL(T),!0}catch{return!1}},QR=WT({domain:"string",predicate:{meta:"a URL string",predicate:d6},meta:{format:"uri"}}),r6=TT.module({root:QR,parse:WT({declaredIn:QR,in:"string",morphs:(T,o)=>{try{return new URL(T)}catch{return o.error("a URL string")}},declaredOut:WT(URL)})},{name:"string.url"}),l6=TT.module({root:["versioned | nil | max","@",{description:"a UUID",format:"uuid"}],"#nil":"'00000000-0000-0000-0000-000000000000'","#max":"'ffffffff-ffff-ffff-ffff-ffffffffffff'","#versioned":/[\da-f]{8}-[\da-f]{4}-[1-8][\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}/i,v1:CT(/^[\da-f]{8}-[\da-f]{4}-1[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv1"),v2:CT(/^[\da-f]{8}-[\da-f]{4}-2[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv2"),v3:CT(/^[\da-f]{8}-[\da-f]{4}-3[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv3"),v4:CT(/^[\da-f]{8}-[\da-f]{4}-4[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv4"),v5:CT(/^[\da-f]{8}-[\da-f]{4}-5[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv5"),v6:CT(/^[\da-f]{8}-[\da-f]{4}-6[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv6"),v7:CT(/^[\da-f]{8}-[\da-f]{4}-7[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv7"),v8:CT(/^[\da-f]{8}-[\da-f]{4}-8[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv8")},{name:"string.uuid"}),CR=TT.module({root:n.string,alpha:CT(/^[A-Za-z]*$/,"only letters"),alphanumeric:CT(/^[\dA-Za-z]*$/,"only letters and digits 0-9"),hex:G6,base64:w6,capitalize:E6,creditCard:z6,date:C6,digits:CT(/^\d*$/,"only digits 0-9"),email:I6,integer:VR,ip:N6,json:x6,lower:b6,normalize:t6,numeric:h6,regex:g6,semver:u6,trim:c6,upper:i6,url:r6,uuid:l6},{name:"string"});var IR=TT.module({bigint:n.bigint,boolean:n.boolean,false:n.false,never:n.never,null:n.null,number:n.number,object:n.object,string:n.string,symbol:n.symbol,true:n.true,unknown:n.unknown,undefined:n.undefined}),kR=TT.module({root:n.unknown,any:n.unknown},{name:"unknown"}),s6=TT.module({root:n.jsonObject,stringify:GA("morph",{in:n.jsonObject,morphs:(T)=>JSON.stringify(T),declaredOut:n.string})},{name:"object.json"}),BR=TT.module({root:n.object,json:s6},{name:"object"});class NR extends yo{description='instantiate an object from an index signature and corresponding value type like `Record("string", "number")`'}var a6=po(["K",n.key],"V")((T)=>({domain:"object",index:{signature:T.K,value:T.V}}),NR);class pR extends yo{description='pick a set of properties from an object like `Pick(User, "name | age")`'}var e6=po(["T",n.object],["K",n.key])((T)=>T.T.pick(T.K),pR);class jR extends yo{description='omit a set of properties from an object like `Omit(User, "age")`'}var TZ=po(["T",n.object],["K",n.key])((T)=>T.T.omit(T.K),jR);class xR extends yo{description="make all named properties of an object optional like `Partial(User)`"}var oZ=po(["T",n.object])((T)=>T.T.partial(),xR);class bR extends yo{description="make all named properties of an object required like `Required(User)`"}var FZ=po(["T",n.object])((T)=>T.T.required(),bR);class qR extends yo{description='exclude branches of a union like `Exclude("boolean", "true")`'}var AZ=po("T","U")((T)=>T.T.exclude(T.U),qR);class vR extends yo{description='extract branches of a union like `Extract("0 | false | 1", "number")`'}var yZ=po("T","U")((T)=>T.T.extract(T.U),vR),PR=TT.module({Exclude:AZ,Extract:yZ,Omit:TZ,Partial:oZ,Pick:e6,Record:a6,Required:FZ});var IF=c$({...IR,...PR,...MR,...fR,string:CR,number:US,object:BR,unknown:kR},{prereducedAliases:!0,name:"ark"}),gT=IF.export();Object.assign(KA.ambient,gT);KA.typeAttachments={string:gT.string.root,number:gT.number.root,bigint:gT.bigint,boolean:gT.boolean,symbol:gT.symbol,undefined:gT.undefined,null:gT.null,object:gT.object.root,unknown:gT.unknown.root,false:gT.false,true:gT.true,never:gT.never,arrayIndex:gT.Array.index,Key:gT.Key,Record:gT.Record,Array:gT.Array.root,Date:gT.Date};var jo=Object.assign(IF.type,KA.typeAttachments),SZ=IF.match,fZ=IF.generic,sz=IF.schema,$Z=IF.define,JZ=IF.declare;function QS(T=Math.random){return T().toString(36).slice(2)}class Zy extends Promise{fate;resolve;reject;done=!1;constructor(T){let o,F;super((A,y)=>{o=A,F=y});this.resolve=o,this.reject=F,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((F)=>{this.pass(o,F)},(F)=>{this.fail(o,F)})}else this.resolve(T),this.fate=void 0}}var mR=(T,o,F=ST.STORE)=>{return MF(F,{key:`${T.key}:JSON`,get:({get:A})=>o.toJson(A(T)),set:({set:A},y)=>{A(T,o.fromJson(y))}})};function j(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 F of o)F(T)}}class d$ extends oT{state;constructor(T){super();this.state=T}next(T){this.state=T,super.next(T)}}function OF(T,o,F){let A={key:o.key,type:"atom_family"},y=T.families.get(o.key);if(y)T.logger.error("\u2757","atom_family",o.key,`Overwriting an existing ${TF(y)} "${y.key}" in store "${T.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);let S=new oT,$=Object.assign((_)=>{let J=AT(_),R={key:o.key,subKey:J},O=`${o.key}(${J})`,Y=j(T),H=o.default,Q={key:O,default:H instanceof Function?H(_):H};if(o.effects)Q.effects=o.effects(_);let E=Do(Y,Q,R);return S.next({type:"state_creation",token:E}),E},A,{subject:S,install:(_)=>OF(_,o),internalRoles:F});return T.families.set(o.key,$),T.defaults.set(o.key,o.default),A}function tR(T,o){if("mutable"in o)return Hy(T,o);return OF(T,o)}function XF(T,o,F){let A={key:o.key,type:"readonly_selector_family"},y=T.families.get(o.key);if(y)T.logger.error("\u2757","readonly_selector_family",o.key,`Overwriting an existing ${TF(y)} "${y.key}" in store "${T.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);let S=new oT,$=Object.assign((_)=>{let J=AT(_),R={key:o.key,subKey:J},O=`${o.key}(${J})`,Y=j(T),H=Gy(Y,{key:O,get:o.get(_)},R);return S.next({type:"state_creation",token:H}),H},A,{internalRoles:F,subject:S,install:(_)=>XF(_,o),default:(_)=>{return o.get(_)({get:(...R)=>MT(T,...R),find:(...R)=>i(T,...R),json:(R)=>nT(T,R)})}});return T.families.set(o.key,$),A}function VS(T,o){if("set"in o)return wy(T,o);return XF(T,o)}class DS{_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 DS([...this._buffer]);return T._index=this._index,T}}var _Z={atom_family:"atom",mutable_atom_family:"mutable_atom",selector_family:"selector",readonly_selector_family:"readonly_selector",molecule_family:"molecule"};function hR(T,o){let F=AT(o),A=`${T.key}(${F})`,y=_Z[T.type],S={key:A,type:y};return Object.assign(S,{family:{key:T.key,subKey:F}}),Object.assign(S,{counterfeit:!0}),S}function Eo(T){let o={key:T.key,type:T.type};if("family"in T)o.family=T.family;return o}function zA(T){return gR(ST.STORE,T)}function gF(T){return tR(ST.STORE,T)}function r$(...T){if(T.length===2)return MT(ST.STORE,...T);return MT(ST.STORE,...T)}function LS(T,o,F=ST.STORE){return F.joins.set(T.key,new Ey(T,o,F)),{key:T.key,type:"join",a:T.between[0],b:T.between[1],cardinality:T.cardinality}}function uR(T){return cR(T,ST.STORE)}var l$=(T)=>(o,F,A,y,...S)=>{console[T](`${o} ${F} "${A}" ${y}`,...S)},RZ={error:l$("error"),info:l$("info"),warn:l$("warn")};class s${logLevel;filter;logger;constructor(T,o,F=RZ){this.logLevel=T,this.filter=o,this.logger=F}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 rQ=Symbol("claim");class iR{store;constructor(T=ST.STORE){this.store=T,dR("root",T)}allocate(T,o,F){return nF(this.store,T,o,F)}fuse(T,o,F){return rR(this.store,T,o,F)}deallocate(T){uF(this.store,T)}claim(T,o,F){return QA(this.store,T,o,F)}}class a${store;realm;constructor(T=ST.STORE){this.store=T,this.realm=new iR(T)}allocate(T,o,F){nF(this.store,T,o,F)}deallocate(T){uF(this.store,T)}claim(T,o,F){QA(this.store,T,o,F)}}function IS(T){return VS(ST.STORE,T)}function aT(T){return"epoch"in T.transactionMeta}function OT(T){return"phase"in T.transactionMeta}var lR=(T)=>{let o=j(T);if(!OT(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 XT(T){return T[0].toUpperCase()+T.slice(1)}function TF(T){return T.type.split("_").map(XT).join(" ")}class cF extends Error{constructor(T,o){super(`${TF(T)} ${AT(T.key)} not found in store "${o.config.name}".`)}}function VA(T,o,F){return(...A)=>{let y=JT(T,o);if(y)return y.run(A,F);throw new cF(o,T)}}var kS=(T)=>(o)=>T instanceof Function?T(o):T;var kF=(T,o)=>{if(T.valueMap.has(o.key))return T.logger.info("\uD83D\uDCD6",o.type,o.key,"reading cached value"),sR(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 F=o.default,A;if(F instanceof Function)A=F();else A=F;return T.logger.info("\uD83D\uDC81","atom",o.key,"could not find cached value; using default",A),A}}};var aR=(T,o)=>{if(T.operation.open){let F=performance.now();return T.logger.info("\u2757",o.type,o.key,`deferring setState at T-${F} until setState for "${T.operation.token.key}" is done`),F}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}"${!OT(T)?"":` ${T.transactionMeta.phase} "${T.transactionMeta.update.key}"`}`)},eR=(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)},TW=(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)},DA=(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 oW=(T,o,F)=>{switch(o.type){case"mutable_atom":T.logger.info("\uD83D\uDCE2",o.type,o.key,"is now (",F.newValue,") subscribers:",o.subject.subscribers);break;case"atom":case"selector":case"readonly_selector":T.logger.info("\uD83D\uDCE2",o.type,o.key,"went (",F.oldValue,"->",F.newValue,") subscribers:",o.subject.subscribers)}o.subject.next(F)};var e$=(T,o)=>{let F=j(T),A=F.selectorAtoms.getRelatedKeys(o.key);if(F.logger.info("\uD83E\uDDF9",o.type,o.key,A?`evicting ${A.size} states downstream:`:"no downstream states",A??"to evict"),A){if(F.operation.open)F.logger.info("\uD83E\uDDF9",o.type,o.key,`[ ${[...F.operation.done].join(", ")} ] already done`);for(let y of A){if(TW(F,y))continue;FW(y,F),DA(F,y)}}};var AW=(T,o,F)=>{let A=kF(T,o),y=A;if(o.type==="mutable_atom"&&OT(T)){let{parent:f}=T;y=Uy(T,o,f)}if(y=kS(F)(y),T.logger.info("\uD83D\uDCDD","atom",o.key,"set to",y),y=xo(T,o.key,y,o.subject),SW(T,o.key))fW(T,o.key);DA(T,o.key),e$(T,o);let S={oldValue:A,newValue:y};if(!OT(T)){oW(T,o,S);return}if(T.on.transactionApplying.state===null){let{key:f}=o;if(yW(S.newValue))return;let $={type:"atom_update",key:f,...S};if(o.family)$.family=o.family;T.transactionMeta.update.updates.push($),T.logger.info("\uD83D\uDCC1","atom",f,"stowed (",S.oldValue,"->",S.newValue,")")}else if(o.key.startsWith("*")){let f=o.key.slice(1),$=T.atoms.get(f),_=T.valueMap.get(f);if($.type==="mutable_atom"&&OT(T)){let{parent:R}=T;_=Uy(T,$,R)}if(_.do(S.newValue)===null)e$(T,$)}};var BS=(T,o,F)=>{switch(o.type){case"atom":case"mutable_atom":AW(T,o,F);break;case"selector":o.set(F);break}};function $W(T,o){if(o.family){let F=T.families.get(o.family.key);if(F)return F}}function jT(T,...o){let F,A,y,S;if(o.length===2){if(F=o[0],S=o[1],A=$W(T,F)??null,A)y=F.family?rT(F.family.subKey):null,F=i(T,A,y)}else A=o[0],y=o[1],S=o[2],F=i(T,A,y);if("counterfeit"in F&&"family"in F){let _=F.family.subKey,J=T.disposalTraces.buffer.find((R)=>R?.key===_);T.logger.error("\u274C",F.type,F.key,`could not be set because it was not found in the store "${T.config.name}".`,J?`This state was previously disposed:
|
|
48
|
+
${J.trace}`:"No previous disposal trace was found.");return}let f=aR(T,F);if(f){let _=T.on.operationClose.subscribe(`waiting to set "${F.key}" at T-${f}`,()=>{_(),T.logger.info("\uD83D\uDFE2",F.type,F.key,`resuming deferred setState from T-${f}`),jT(T,F,S)});return}let $=JT(T,F);BS(T,$,S),eR(T)}function NS(T,o,F){let{key:A,newValue:y,oldValue:S}=o,f=T==="newValue"?y:S,$={key:A,type:"atom"};if(o.family)Object.assign($,{family:o.family});jT(F,$,f)}function JW(T){let{stack:o}=T;if(o)return`
|
|
43
49
|
`+o.split(`
|
|
44
50
|
`)?.slice(1)?.join(`
|
|
45
|
-
`);return""}function
|
|
51
|
+
`);return""}function dR(T,o=ST.STORE){let F={key:T,stringKey:AT(T),dependsOn:"any"};return o.molecules.set(AT(T),F),T}function nF(T,o,F,A="any"){let y=o,S=AT(F),f=[],$=j(T);if(Array.isArray(y))for(let R of y){let O=AT(R);if($.molecules.get(O))T.moleculeGraph.set(O,S,{source:O});else f.push(O)}else{let R=AT(y);if($.molecules.get(R))T.moleculeGraph.set(R,S,{source:R});else f.push(R)}if(f.length===0)$.molecules.set(S,{key:F,stringKey:S,dependsOn:A});let _={type:"molecule_creation",key:F,provenance:y};if(OT($)&&$.transactionMeta.phase==="building")$.transactionMeta.update.updates.push(_);else $.on.moleculeCreation.next(_);for(let R of f){let O=T.disposalTraces.buffer.find((Y)=>Y?.key===R);T.logger.error("\u274C","molecule",F,"allocation failed:",`Could not allocate to ${R} in store "${T.config.name}".`,O?`
|
|
46
52
|
${R} was most recently disposed
|
|
47
|
-
${
|
|
53
|
+
${O.trace}`:`No previous disposal trace for ${R} was found.`)}return F}function rR(T,o,F,A){let y=`T$--${o}==${F}++${A}`;return nF(T,[F,A],y,"all"),y}function uF(T,o){let F=AT(o),A=T.molecules.get(F);if(!A){let H=T.disposalTraces.buffer.find((Q)=>Q?.key===F);T.logger.error("\u274C","molecule",o,"deallocation failed:",`Could not find allocation for ${F} in store "${T.config.name}".`,H?`
|
|
48
54
|
This state was most recently deallocated
|
|
49
|
-
${H.trace}`:`No previous disposal trace for ${F} was found.`);return}let
|
|
50
|
-
${
|
|
51
|
-
${Y.trace}`:`No previous disposal trace for ${
|
|
55
|
+
${H.trace}`:`No previous disposal trace for ${F} was found.`);return}let y=T.moleculeJoins.getRelatedKeys(A.key);if(y)for(let H of y){let Q=T.joins.get(H);if(Q)Q.relations.delete(A.key),Q.molecules.delete(A.stringKey)}T.moleculeJoins.delete(A.stringKey);let S=[],f=[],$={type:"molecule_disposal",key:A.key,values:f,provenance:S},_=j(T);_.molecules.delete(F);let J=OT(_)&&_.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 E=rT(H);uF(T,E)}else S.push(Q);let O=_.moleculeData.getRelatedKeys(A.stringKey);if(O)for(let H of O){let Q=_.families.get(H),E=i(T,Q,A.key);f.push([Q.key,E]),iF(T,E)}if(_.moleculeGraph.delete(A.stringKey),_.moleculeJoins.delete(A.stringKey),_.moleculeData.delete(A.stringKey),!J)_.on.moleculeDisposal.next($);_.molecules.delete(A.stringKey);let Y=JW(new Error);T.disposalTraces.add({key:F,trace:Y})}function QA(T,o,F,A){let y=AT(F),S=j(T),f=S.molecules.get(y);if(!f){let Y=T.disposalTraces.buffer.find((H)=>H?.key===y);return T.logger.error("\u274C","molecule",F,"claim failed:",`Could not allocate to ${y} in store "${T.config.name}".`,Y?`
|
|
56
|
+
${y} was most recently disposed
|
|
57
|
+
${Y.trace}`:`No previous disposal trace for ${y} was found.`),F}let $=AT(o),_=S.molecules.get($);if(!_){let Y=T.disposalTraces.buffer.find((H)=>H?.key===$);return T.logger.error("\u274C","molecule",F,"claim failed:",`Could not allocate to ${$} in store "${T.config.name}".`,Y?`
|
|
52
58
|
${$} was most recently disposed
|
|
53
|
-
${Y.trace}`:`No previous disposal trace for ${$} was found.`),F}let J=T.moleculeGraph.getRelationEntries({downstreamMoleculeKey:f.stringKey}).filter(([,{source:Y}])=>Y!==
|
|
54
|
-
${f.trace}`:"No previous disposal trace was found."),y.type){case"atom_family":case"mutable_atom_family":return T.defaults.get(y.key);case"selector_family":case"readonly_selector_family":{if(T.defaults.has(y.key))return T.defaults.get(F.family.key);let $=_T(T,y).default(S);return T.defaults.set(y.key,$),$}}}return kF(T,_T(T,F))}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 F=this.relations.get(T),y=this.relations.get(o);if(F)F.add(o);else F=new Set([o]),this.relations.set(T,F);if(y)y.add(T);else y=new Set([T]),this.relations.set(o,y)}deleteRelation(T,o){let F=this.relations.get(T);if(F){if(F.delete(o),F.size===0)this.relations.delete(T);let y=this.relations.get(o);if(y){if(y.delete(T),y.size===0)this.relations.delete(o)}}}replaceRelationsUnsafely(T,o){this.relations.set(T,new Set(o));for(let F of o){let y=new Set().add(T);this.relations.set(F,y)}}replaceRelationsSafely(T,o){let F=this.relations.get(T),y=this.isAType?.(T)?T:void 0,A=y===void 0?T:void 0;if(F)for(let S of F){y??=S,A??=S;let f=this.relations.get(S);if(f){if(f.size===1)this.relations.delete(S);else f.delete(T);this.contents.delete(this.makeContentKey(y,A))}}this.relations.set(T,new Set(o));for(let S of o){let f=this.relations.get(S);if(f)f.add(T);else f=new Set().add(T),this.relations.set(S,f)}}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(([F,y])=>[F,new Set(y)])),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 F=o.externalStore;if(this.has=(y,A)=>F.has(y,A),this.addRelation=(y,A)=>{F.addRelation(y,A)},this.deleteRelation=(y,A)=>{F.deleteRelation(y,A)},this.replaceRelationsSafely=(y,A)=>{F.replaceRelationsSafely(y,A)},this.replaceRelationsUnsafely=(y,A)=>{F.replaceRelationsUnsafely(y,A)},this.getRelatedKeys=(y)=>F.getRelatedKeys(y),F.getContent)this.getContentInternal=(y)=>{return F.getContent(y)},this.setContent=(y,A)=>{F.setContent(y,A)},this.deleteContent=(y)=>{F.deleteContent(y)};for(let[y,A]of T.relations??[]){let S=this.isAType?.(y)?y:void 0,f=S===void 0?y:void 0;for(let $ of A)S??=$,f??=$,this.addRelation(S,f)}for(let[y,A]of T.contents??[])this.setContent(y,A)}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,F,y;switch(T.length){case 1:{let A=T[0];o=A[this.a],F=A[this.b],y=void 0;break}case 2:{let A=T[0];if(typeof A==="string")[o,F]=T;else o=A[this.a],F=A[this.b],y=T[1];break}default:{o=T[0],F=T[1],y=T[2];break}}switch(this.cardinality){case"1:1":{let A=this.getRelatedKey(o);if(A&&A!==F)this.delete(o,A)}case"1:n":{let A=this.getRelatedKey(F);if(A&&A!==o)this.delete(A,F)}break;case"n:n":}if(y){let A=this.makeContentKey(o,F);this.setContent(A,y)}return this.addRelation(o,F),this}delete(T,o){o=typeof o==="string"?o:T[this.b];let F=typeof T==="string"?T:T[this.a];if(F===void 0&&typeof o==="string"){let y=this.getRelatedKeys(o);if(y)for(let A of y)this.delete(A,o)}if(typeof F==="string"&&o===void 0){let y=this.getRelatedKeys(F);if(y)for(let A of y)this.delete(F,A)}if(typeof F==="string"&&typeof o==="string"){this.deleteRelation(F,o);let y=this.makeContentKey(F,o);this.deleteContent(y)}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((y)=>`"${y}"`).join(", ")}). Only one related key was expected.`);let F;for(let y of o){F=y;break}return F}}replaceRelations(T,o,F){let y=!Array.isArray(o),A=y?Object.keys(o):o;if(F?.reckless)this.replaceRelationsUnsafely(T,A);else this.replaceRelationsSafely(T,A);if(y)for(let S of A){let f=this.makeContentKey(T,S),$=o[S];this.setContent(f,$)}return this}getContent(T,o){let F=this.makeContentKey(T,o);return this.getContentInternal(F)}getRelationEntries(T){let o=T[this.a],F=T[this.b];if(o!==void 0&&F===void 0){let y=this.getRelatedKeys(o);if(y)return[...y].map((A)=>{return[A,this.getContent(o,A)]})}if(o===void 0&&F!==void 0){let y=this.getRelatedKeys(F);if(y)return[...y].map((A)=>{return[A,this.getContent(A,F)]})}return[]}has(T,o){if(o)return this.getRelatedKeys(T)?.has(o)??!1;return this.relations.has(T)}}class jo 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,F,y)=>{let A=x(T),S={parent:A,child:null,on:A.on,loggers:A.loggers,logger:A.logger,config:A.config,atoms:new jo(A.atoms),atomsThatAreDefault:new Set(A.atomsThatAreDefault),families:new jo(A.families),joins:new jo(A.joins),operation:{open:!1},readonlySelectors:new jo(A.readonlySelectors),timelines:new jo(A.timelines),timelineTopics:new uT(A.timelineTopics.toJSON()),trackers:new Map,transactions:new jo(A.transactions),selectorAtoms:new uT(A.selectorAtoms.toJSON()),selectorGraph:new uT(A.selectorGraph.toJSON(),{makeContentKey:(...J)=>J.sort().join(":")}),selectors:new jo(A.selectors),valueMap:new jo(A.valueMap),defaults:A.defaults,disposalTraces:T.disposalTraces.copy(),molecules:new jo(A.molecules),moleculeGraph:new uT(A.moleculeGraph.toJSON(),{makeContentKey:A.moleculeGraph.makeContentKey}),moleculeData:new uT(A.moleculeData.toJSON(),{makeContentKey:A.moleculeData.makeContentKey}),moleculeJoins:new uT(A.moleculeJoins.toJSON(),{makeContentKey:A.moleculeJoins.makeContentKey}),miscResources:new jo(A.miscResources)},f=RW(T,o),$={phase:"building",update:{type:"transaction_update",key:o,id:y,epoch:f===void 0?Number.NaN:f+1,updates:[],params:F,output:void 0},toolkit:{get:(...J)=>OT(_,...J),set:(...J)=>{bT(_,...J)},run:(J,R=zS())=>zy(_,J,R),find:(...J)=>i(T,...J),json:(J)=>nT(_,J),dispose:(...J)=>{uF(_,...J)},env:()=>YW(_)}},_=Object.assign(S,{transactionMeta:$});return A.child=_,T.logger.info("\uD83D\uDEEB","transaction",o,"Building transaction with params:",F),_};function TJ(T,o){let F={key:o.key,type:"transaction",run:(S,f)=>{let $=ZW(T,o.key,S,f);try{let _=x(T),{toolkit:J}=$.transactionMeta,R=o.do(J,...S);return MW(R,_),R}catch(_){throw iR(y),T.logger.warn("\uD83D\uDCA5","transaction",o.key,"caught:",_),_}},install:(S)=>TJ(S,o),subject:new oT},y=x(T);y.transactions.set(F.key,F);let A=wo(F);return T.on.transactionCreation.next(A),A}function UA(T){return TJ(ST.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 VS(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,F)=>!BF(F))];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[,y]of o.families){if(y.internalRoles?.includes("mutable")||y.internalRoles?.includes("join"))continue;y.install(this)}let F=new Set;for(let[,y]of o.atoms){if(F.has(y.key))continue;if(y.install(this),y.type==="mutable_atom"){let A=nT(o,y),S=ZF(y);F.add(A.key),F.add(S.key)}}for(let[,y]of o.readonlySelectors)y.install(this);for(let[,y]of o.selectors){if(F.has(y.key))continue;y.install(this)}for(let[,y]of o.transactions)y.install(this);for(let[,y]of o.timelines)y.install(this)}}}var ST={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 F,y=T;while(y!==null){switch(o.type){case"atom":case"mutable_atom":F=y.atoms.get(o.key);break;case"selector":F=y.selectors.get(o.key);break;case"readonly_selector":F=y.readonlySelectors.get(o.key);break;case"atom_family":case"mutable_atom_family":case"selector_family":case"readonly_selector_family":F=y.families.get(o.key);break;case"timeline":F=y.timelines.get(o.key);break;case"transaction":F=y.transactions.get(o.key);break}if(F)return F;y=y.child}throw new nF(o,T)}function GW(T,o,F){let y=T.families.get(o.key);if(y===void 0)throw new nF(o,T);let A=y(F),S=x(T);if(A.family){if(aT(S))switch(A.type){case"atom":case"mutable_atom":T.on.atomCreation.next(A);break;case"selector":case"readonly_selector":T.on.selectorCreation.next(A);break}else if(XT(S)&&S.on.transactionApplying.state===null)S.transactionMeta.update.updates.push({type:"state_creation",token:A})}return A}function EW(T,o,F){let y=yT(F),A=`${o.key}(${y})`,S=x(T),f;switch(o.type){case"atom_family":case"mutable_atom_family":f=S.atoms.get(A);break;case"selector_family":f=S.selectors.get(A);break;case"readonly_selector_family":f=S.readonlySelectors.get(A);break}if(f)return wo(f);return f}function i(T,o,F){let y=EW(T,o,F);if(y)return y;let A=yT(F),S=T.molecules.get(A);if(!S&&T.config.lifespan==="immortal"){let f=vR(o,F);return T.logger.error("\u274C",f.type,f.key,`was not found in store "${T.config.name}"; returned a counterfeit token.`),f}if(y=GW(T,o,F),S)x(T).moleculeData.set(A,o.key);return y}function uF(T,...o){let F;if(o.length===1)F=o[0];else{let y=o[0],A=o[1];F=i(T,y,A)}try{_T(T,F)}catch(y){T.logger.error("\u274C",F.type,F.key,`could not be disposed because it was not found in the store "${T.config.name}".`);return}switch(F.type){case"atom":case"mutable_atom":oJ(T,F);break;case"selector":case"readonly_selector":wW(T,F);break}}var pS=(T,o)=>x(T).atoms.has(o),yZ=(T,o)=>x(T).selectors.has(o),AZ=(T,o)=>x(T).readonlySelectors.has(o),UW=(T,o)=>pS(T,o)||yZ(T,o)||AZ(T,o);var xS=(T,o)=>{return x(o).selectorGraph.getRelationEntries({downstreamSelectorKey:T}).filter(([y,{source:A}])=>A!==T).map(([y,{source:A}])=>A).filter((y)=>UW(o,y))};var FJ=(T,o,F)=>{let y=[],A=xS(T,F);while(A.length>0){let S=A.shift();if(o.has(S))continue;if(o.add(S),!pS(F,S))A.push(...xS(S,F));else if(!y.includes(S))y.push(S)}return y},KW=(T,o)=>{let F=T.key,y=xS(F,o),A=new Set;return y.flatMap((S)=>pS(o,S)?S:FJ(S,A,o))};var zW=(T,o,F,y)=>{let A=x(y);if(o.type==="atom"||o.type==="mutable_atom")A.selectorAtoms.set({selectorKey:T,atomKey:o.key}),y.logger.info("\uD83D\uDD0D","selector",T,`discovers root atom "${o.key}"`);else{let S=FJ(o.key,F,y);y.logger.info("\uD83D\uDD0D","selector",T,`discovers root atoms: [ ${S.map((f)=>`"${f}"`).join(", ")} ]`);for(let f of S)A.selectorAtoms=A.selectorAtoms.set({selectorKey:T,atomKey:f})}F.add(o.key)};var bS=(T,o,F)=>({get:(...y)=>{let A=x(F),S;if(y.length===2){let[_,J]=y;S=i(F,_,J)}else[S]=y;let f=_T(F,S),$=kF(F,f);return F.logger.info("\uD83D\uDD0C","selector",T,`registers dependency ( "${S.key}" =`,$,")"),A.selectorGraph.set({upstreamSelectorKey:S.key,downstreamSelectorKey:T},{source:S.key}),zW(T,S,o,F),$},set:(...y)=>{let A,S;if(y.length===2)A=y[0],S=y[1];else{let _=y[0],J=y[1];S=y[2],A=i(F,_,J)}let f=x(F),$=_T(f,A);kS(f,$,S)},find:(...y)=>i(F,...y),json:(y)=>nT(F,y)});var ZA=(T,o,F)=>{let y=x(T),A=new oT,S=new Set,{get:f,find:$,json:_}=bS(o.key,S,y),J=()=>{let H=o.get({get:f,find:$,json:_});return bo(x(T),o.key,H,A),S.clear(),H},R={...o,subject:A,install:(H)=>ZA(H,o,F),get:J,type:"readonly_selector",...F&&{family:F}};y.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(F)Y.family=F;return Y};var KA=(T,o,F)=>{let y=x(T),A=new oT,S=new Set,f=bS(o.key,S,y),{find:$,get:_,json:J}=f,R={find:$,get:_,json:J},M=(B=o.get,p=x(T))=>{let q=B(R);return bo(p,o.key,q,A),S.clear(),q},H={...o,subject:A,install:(B)=>KA(B,o,F),get:M,set:(B)=>{let p=x(T),q=M(o.get,p),h=IS(B)(q);if(T.logger.info("\uD83D\uDCDD","selector",o.key,"set (",q,"->",h,")"),bo(p,o.key,h,A),Qy(p,o.key),aT(p))A.next({newValue:h,oldValue:q});o.set(f,h)},type:"selector",...F&&{family:F}};y.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(F)w.family=F;return w};function MF(T,o){if("set"in o){let A=KA(T,o,void 0);return T.on.selectorCreation.next(A),A}let y=ZA(T,o,void 0);return T.on.selectorCreation.next(y),y}function wW(T,o){let F=x(T),{key:y}=o,A=_T(F,o);if(!A.family)T.logger.error("\u274C","selector",y,"Standalone selectors cannot be disposed.");else{if(F.molecules.get(A.family.subKey))F.moleculeData.delete(A.family.subKey,A.family.key);let f;switch(o.type){case"selector":F.selectors.delete(y),f={key:A.family.key,type:"selector_family"},_T(T,f).subject.next({type:"state_disposal",subType:"selector",token:o});break;case"readonly_selector":F.readonlySelectors.delete(y),f={key:A.family.key,type:"readonly_selector_family"},_T(T,f).subject.next({type:"state_disposal",subType:"selector",token:o});break}if(F.valueMap.delete(y),F.selectorAtoms.delete(y),F.selectorGraph.delete(y),T.logger.info("\uD83D\uDD25",o.type,y,"deleted"),XT(F)&&F.transactionMeta.phase==="building")F.transactionMeta.update.updates.push({type:"state_disposal",subType:"selector",token:o});else T.on.selectorDisposal.next(o)}}function HA(T,o,F){let y={key:o.key,type:"selector_family"},A=T.families.get(o.key);if(A)T.logger.error("\u2757","selector_family",o.key,`Overwriting an existing ${TF(A)} "${A.key}" in store "${T.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);let S=new oT,$=Object.assign((_)=>{let J=yT(_),R={key:o.key,subKey:J},M=`${o.key}(${J})`,Y=x(T),H=KA(Y,{key:M,get:o.get(_),set:o.set(_)},R);return S.next({type:"state_creation",token:H}),H},y,{internalRoles:F,subject:S,install:(_)=>HA(_,o),default:(_)=>{return o.get(_)({get:(...R)=>OT(T,...R),find:(...R)=>i(T,...R),json:(R)=>nT(T,R)})}});return T.families.set(o.key,$),y}function QW(T,o,F){return HA(T,{key:`${o.key}:JSON`,get:(A)=>({get:S})=>{let f=S(o,A);return F.toJson(f)},set:(A)=>({set:S},f)=>{S(o,A,F.fromJson(f))}},["mutable","json"])}var rT=(T)=>JSON.parse(T),yT=(T)=>JSON.stringify(T),FI=[Array.prototype,Boolean.prototype,Number.prototype,Object.prototype,String.prototype];var VW=(T,o)=>{let F=x(T);if(F.operation.open)return F.operation.prev.get(o.key);return F.valueMap.get(o.key)};var SJ=(T,o)=>{let F=x(T);return KW(o,T).map((A)=>{let S=F.atoms.get(A);if(S===void 0)throw new Error(`Atom "${A}", a dependency of selector "${o.key}", not found in store "${T.config.name}".`);return S.subject.subscribe(`${o.type}:${o.key}`,(f)=>{T.logger.info("\uD83D\uDCE2",o.type,o.key,"root",A,"went",f.oldValue,"->",f.newValue);let $=VW(F,o),_=kF(F,o);T.logger.info("\u2728",o.type,o.key,"went",$,"->",_),o.subject.next({newValue:_,oldValue:$})})})};function fo(T,o,F,y){function A(M){if(T.operation.open){let Y=T.on.operationClose.subscribe(`state subscription ${F}`,()=>{Y(),y(M)})}else y(M)}let S=_T(T,o);T.logger.info("\uD83D\uDC40",S.type,S.key,`Adding subscription "${F}"`);let f=S.type==="selector"||S.type==="readonly_selector",$=null,_=A;if(f)$=SJ(T,S),_=(M)=>{if($)$.length=0,$.push(...SJ(T,S));A(M)};let J=S.subject.subscribe(F,_);return()=>{if(T.logger.info("\uD83D\uDE48",S.type,S.key,`Removing subscription "${F}"`),J(),$)for(let M of $)M()}}var yJ=(T,o,F,y)=>{let A=_T(T,o);T.logger.info("\uD83D\uDC40","timeline",o.key,`Adding subscription "${F}"`);let S=A.subject.subscribe(F,y);return()=>{T.logger.info("\uD83D\uDE48","timeline",o.key,`Removing subscription "${F}" from timeline`),S()}};var AJ=(T,o,F,y)=>{let A=_T(T,o);T.logger.info("\uD83D\uDC40","transaction",o.key,`Adding subscription "${F}"`);let S=A.subject.subscribe(F,y);return()=>{T.logger.info("\uD83D\uDE48","transaction",o.key,`Removing subscription "${F}"`),S()}};class cF{Update;initializeState(T,o){let F=`*${T.key}`;o.atoms.delete(F),o.valueMap.delete(F);let y=T.family?{key:`*${T.family.key}`,subKey:T.family.subKey}:void 0,A=Do(o,{key:F,default:null},y);if(o.parent?.valueMap.has(F)){let S=o.parent.valueMap.get(F);o.valueMap.set(F,S)}return A}unsubscribeFromInnerValue;unsubscribeFromState;observeCore(T,o,F){let y=`tracker:${F.config.name}:${XT(F)?F.transactionMeta.update.key:"main"}:${T.key}`,A=OT(F,T);this.unsubscribeFromInnerValue=A.subscribe(y,(S)=>{bT(F,o,S)}),this.unsubscribeFromState=fo(F,T,y,(S)=>{if(S.newValue!==S.oldValue)this.unsubscribeFromInnerValue(),this.unsubscribeFromInnerValue=S.newValue.subscribe(y,(f)=>{bT(F,o,f)})})}updateCore(T,o,F){let y=`tracker:${F.config.name}:${XT(F)?F.transactionMeta.update.key:"main"}:${T.key}`;fo(F,o,y,({newValue:A,oldValue:S})=>{let f=F.timelineTopics.getRelatedKey(o.key);if(f){if(F.timelines.get(f)?.timeTraveling){let J=yJ(F,{key:f,type:"timeline"},y,(R)=>{J(),bT(F,T,(M)=>{if(R==="redo"&&A)M.do(A);else if(R==="undo"&&S)M.undo(S);return M})});return}}let $=F.on.operationClose.subscribe(y,()=>{$();let _=OT(F,T),J=A===null?-1:_.getUpdateNumber(A),R=J-_.cacheUpdateNumber;if(A&&R===1)bT(F,T,(M)=>(M.do(A),M));else F.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 F=x(o);this.latestUpdateState=this.initializeState(T,F),this.observeCore(T,this.latestUpdateState,F),this.updateCore(T,this.latestUpdateState,F),F.trackers.set(T.key,this),this[Symbol.dispose]=()=>{this.unsubscribeFromInnerValue(),this.unsubscribeFromState(),F.trackers.delete(T.key)}}}function zA(T,o,F){T.logger.info("\uD83D\uDD28","atom",o.key,`creating in store "${T.config.name}"`);let y=x(T),A=y.atoms.get(o.key);if(A&&A.type==="mutable_atom")return T.logger.error("\u274C","atom",o.key,"Tried to create atom, but it already exists in the store."),wo(A);let S=new oT,f={...o,type:"mutable_atom",install:(J)=>{return J.logger.info("\uD83D\uDEE0\uFE0F","atom",o.key,`installing in store "${J.config.name}"`),zA(J,o,F)},subject:S};if(F)f.family=F;let $=o.default();y.atoms.set(f.key,f),jS(T,o.key),bo(y,o.key,$,S);let _=wo(f);if(o.effects){let J=0,R=[];for(let M of o.effects){let Y=M({setSelf:(H)=>{bT(T,_,H)},onSet:(H)=>fo(T,_,`effect[${J}]`,H)});if(Y)R.push(Y);++J}f.cleanup=()=>{for(let M of R)M()}}if(new cF(_,T),!F)tR(_,o,T);return _}class fJ{trackers=new Map;Update;latestUpdateAtoms;mutableAtoms;constructor(T,o){let F=XF(o,{key:`*${T.key}`,default:null},["mutable","updates"]);this.latestUpdateAtoms=_T(o,F),this.mutableAtoms=T,this.mutableAtoms.subject.subscribe(`store=${o.config.name}::tracker-atom-family`,(y)=>{let{type:A,token:S}=y;if(S.family){let f=rT(S.family.subKey);switch(A){case"state_creation":this.trackers.set(f,new cF(S,o));break;case"state_disposal":{let $=this.trackers.get(f);if($)$[Symbol.dispose](),this.trackers.delete(f)}break}}})}}function YA(T,o,F){let y={key:o.key,type:"mutable_atom_family"},A=T.families.get(o.key);if(A)T.logger.error("\u2757","mutable_atom_family",o.key,`Overwriting an existing ${TF(A)} "${A.key}" in store "${T.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);let S=new oT,$=Object.assign((_)=>{let J=yT(_),R={key:o.key,subKey:J},M=`${o.key}(${J})`,Y=x(T),H={key:M,default:()=>o.default(_),toJson:o.toJson,fromJson:o.fromJson,mutable:!0};if(o.effects)H.effects=o.effects(_);let Q=zA(Y,H,R);return S.next({type:"state_creation",token:Q}),Q},y,{subject:S,install:(_)=>YA(_,o),toJson:o.toJson,fromJson:o.fromJson,internalRoles:F});return T.families.set(o.key,$),QW(T,$,o),new fJ($,T),y}var $J=(T,o)=>{let F=x(o),y=`${T.key}:JSON`;return F.families.get(y)};var nT=(T,o)=>{if(o.family){let y=x(T),S={key:`${o.family.key}:JSON`,type:"selector_family"},f=_T(y,S),$=JSON.parse(o.family.subKey);return i(T,f,$)}return{type:"selector",key:`${o.key}:JSON`}};var ZF=(T)=>{let F={type:"atom",key:`*${T.key}`};if(T.family)F.family={key:`*${T.family.key}`,subKey:T.family.subKey};return F};function oW(T){return typeof T==="object"&&T!==null&&"do"in T&&"undo"in T&&"subscribe"in T}function wA(T,o,F){let y=F.valueMap.get(o.key),A=T.valueMap.get(o.key);if(y!==A)return A;if(y===void 0)return o.default();F.logger.info("\uD83D\uDCC3","atom",o.key,"copying");let S=o.toJson(y),f=o.fromJson(S);return T.valueMap.set(o.key,f),new cF(o,F),f}function bo(T,o,F,y){let A=T.valueMap.get(o);if(A instanceof XA)A.use(F);if(F instanceof Promise){let S=new XA(F);return T.valueMap.set(o,S),S.then((f)=>{bo(T,o,f,y),y.next({newValue:f,oldValue:S})}).catch((f)=>{T.logger.error("\uD83D\uDCA5","state",o,"rejected:",f)}),S}return T.valueMap.set(o,F),F}var dR=(T,o)=>{let F=o.valueMap.get(T.key);if(T.type==="mutable_atom"&&XT(o)){let{parent:y}=o;F=wA(o,T,y)}return F},eR=(T,o)=>{let F=o.valueMap.get(T);if(F instanceof XA){let y=F,A=o.selectors.get(T)??o.readonlySelectors.get(T);if(A)y.use(A.get());return}if(o.operation.open)o.operation.prev.set(T,F);o.valueMap.delete(T),o.logger.info("\uD83D\uDDD1","state",T,"evicted")};var FW=(T,o)=>{return x(T).atomsThatAreDefault.has(o)},jS=(T,o)=>{let F=x(T);F.atomsThatAreDefault=new Set(F.atomsThatAreDefault).add(o)},yW=(T,o)=>{let F=x(T);F.atomsThatAreDefault=new Set(x(T).atomsThatAreDefault),F.atomsThatAreDefault.delete(o)};function Do(T,o,F){T.logger.info("\uD83D\uDD28","atom",o.key,`creating in store "${T.config.name}"`);let y=x(T),A=y.atoms.get(o.key);if(A&&A.type==="atom")return T.logger.error("\u274C","atom",o.key,"Tried to create atom, but it already exists in the store."),wo(A);let S=new oT,f={...o,type:"atom",install:(J)=>{return J.logger.info("\uD83D\uDEE0\uFE0F","atom",o.key,`installing in store "${J.config.name}"`),Do(J,o,F)},subject:S};if(F)f.family=F;let $=o.default;if(o.default instanceof Function)$=o.default();y.atoms.set(f.key,f),jS(T,o.key),bo(y,o.key,$,S);let _=wo(f);if(o.effects){let J=0,R=[];for(let M of o.effects){let Y=M({setSelf:(H)=>{bT(T,_,H)},onSet:(H)=>fo(T,_,`effect[${J}]`,H)});if(Y)R.push(Y);++J}f.cleanup=()=>{for(let M of R)M()}}return _}function mR(T,o){if("mutable"in o){let A=zA(T,o,void 0);return T.on.atomCreation.next(A),A}let y=Do(T,o,void 0);return T.on.atomCreation.next(y),y}function oJ(T,o){let F=x(T),{key:y,family:A}=o,S=_T(F,o);if(!A)T.logger.error("\u274C","atom",y,"Standalone atoms cannot be disposed.");else{S.cleanup?.();let f=T.valueMap.get(S.key),$=_T(T,{key:A.key,type:"atom_family"}),_={type:"state_disposal",subType:"atom",token:o,value:f};$.subject.next(_);let J=XT(F);if(F.atoms.delete(y),F.valueMap.delete(y),F.selectorAtoms.delete(y),F.atomsThatAreDefault.delete(y),T.timelineTopics.delete(y),o.type==="mutable_atom"){let R=ZF(o);oJ(T,R),T.trackers.delete(y)}if(T.logger.info("\uD83D\uDD25","atom",y,"deleted"),J&&F.transactionMeta.phase==="building"){let R=F.transactionMeta.update.updates.at(-1);if(!(R?.type==="molecule_disposal"&&R.values.some(([H])=>H===S.family?.key)))F.transactionMeta.update.updates.push(_)}else T.on.atomDisposal.next(o)}}class cT extends Set{mode="record";subject=new oT;cacheLimit=0;cache=[];cacheIdx=-1;cacheUpdateNumber=-1;constructor(T,o=0){super(T);if(T instanceof cT)this.parent=T,this.cacheUpdateNumber=T.cacheUpdateNumber;if(o)this.cacheLimit=o,this.cache=new Array(o),this.subscribe("auto cache",(F)=>{this.cacheIdx++,this.cacheIdx%=this.cacheLimit,this.cache[this.cacheIdx]=F})}toJSON(){return{members:[...this],cache:this.cache,cacheLimit:this.cacheLimit,cacheIdx:this.cacheIdx,cacheUpdateNumber:this.cacheUpdateNumber}}static fromJSON(T){let o=new cT(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:${yT(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:${yT(T)}`);return o}parent;child=null;transactionUpdates=null;transaction(T){this.mode="transaction",this.transactionUpdates=[],this.child=new cT(this);let o=this.child._subscribe("transaction",(F)=>{this.transactionUpdates?.push(F)});try{if(T(this.child)){for(let y of this.transactionUpdates)this.doStep(y);this.cacheUpdateNumber++,this.emit(`tx:${this.transactionUpdates.join(";")}`)}}catch(F){throw console.warn("Did not apply transaction to SetRTX; this error was thrown:",F),F}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,(F)=>{o(`${this.cacheUpdateNumber}=${F}`)})}emit(T){this.subject.next(T)}doStep(T){let o=T.indexOf(":"),F=T.substring(0,o),y=T.substring(o+1);switch(F){case"add":this.add(JSON.parse(y));break;case"clear":this.clear();break;case"del":this.delete(JSON.parse(y));break;case"tx":for(let A of y.split(";"))this.doStep(A)}}getUpdateNumber(T){let o=T.indexOf("=");return Number(T.substring(0,o))}do(T){let o=T.indexOf("="),F=Number(T.substring(0,o)),y=F-this.cacheUpdateNumber;if(y>0){if(y===1){this.mode="playback";let S=T.substring(o+1);return this.doStep(S),this.mode="record",this.cacheUpdateNumber=F,null}return this.cacheUpdateNumber+1}if(Math.abs(y)<this.cacheLimit){let S=this.cacheIdx+y;if(this.cache[S]===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===S-1}let _=T.substring(o+1);return this.doStep(_),this.mode="record",this.cacheUpdateNumber=F,null}return"OUT_OF_RANGE"}undoStep(T){let o=T.indexOf(":"),F=T.substring(0,o),y=T.substring(o+1);switch(F){case"add":this.delete(JSON.parse(y));break;case"del":this.add(JSON.parse(y));break;case"clear":{let A=JSON.parse(y);for(let S of A)this.add(S);break}case"tx":{let A=y.split(";");for(let S=A.length-1;S>=0;S--)this.undoStep(A[S])}}}undo(T){let o=T.indexOf("=");if(Number(T.substring(0,o))===this.cacheUpdateNumber){this.mode="playback";let y=T.substring(o+1);return this.undoStep(y),this.mode="record",this.cacheUpdateNumber--,null}return this.cacheUpdateNumber}}class GA{toolkit;options;defaultContent;molecules=new Map;relations;states;core;transact(T,o){let F=this.toolkit;this.toolkit=T,o(this),this.toolkit=F}store;realm;[Symbol.dispose](){}constructor(T,o,F=ST.STORE){this.store=F,this.realm=new r$(F),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(F,...K),set:(...K)=>{bT(F,...K)},find:(...K)=>i(F,...K),json:(K)=>nT(F,K)};let y=T.between[0],A=T.between[1],S=YA(F,{key:`${T.key}/relatedKeys`,default:()=>new cT,mutable:!0,fromJson:(K)=>cT.fromJSON(K),toJson:(K)=>K.toJSON()},["join","relations"]);this.core={relatedKeysAtoms:S};let f=({get:K},V)=>K(S,V),$=({set:K},V,L)=>{if(!this.store.molecules.has(yT(V)))this.realm.allocate(T.key,V);K(S,V,(C)=>C.add(L)),K(S,L,(C)=>C.add(V))},_=({set:K},V,L)=>{K(S,V,(C)=>{return C.delete(L),C}),K(S,L,(C)=>{return C.delete(V),C})},J=(K,V,L)=>{let{find:C,get:m,set:s}=K,z=C(S,V),a=m(z);for(let P of a){if(L.includes(P))continue;s(S,P,(HT)=>{return HT.delete(V),HT})}s(z,(P)=>{return P.transaction((e)=>{e.clear();for(let HT of L){let vT=f(K,HT),Xo=vT.has(V);if(this.relations.cardinality==="1:n"){let yF=[];for(let D of vT){if(D===V)continue;let g=f(K,D);if(g.delete(HT),g.size===0)yF.push(D)}if(!Xo&&vT.size>0)vT.clear();for(let D of yF){let g=[HT,D].sort(),RT=`"${g[0]}:${g[1]}"`;this.molecules.delete(RT)}}if(!Xo)vT.add(V);e.add(HT)}return!0}),P})},R=(K,V,L)=>{let{set:C}=K;C(S,V,(m)=>{return m.transaction((s)=>{for(let z of L)s.add(z);return!0}),m});for(let m of L)C(S,m,(s)=>{return s.add(V),s});return!0},M=(K,V,L)=>{let C=f(K,V);return L?C.has(L):C.size>0},Y={getRelatedKeys:(K)=>f(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=XF(F,{key:`${T.key}/content`,default:o},["join","content"]);let K=({get:C},m)=>C(Q,m),V=({set:C},m,s)=>{C(Q,m,s)};H=Object.assign(Y,{getContent:(C)=>{return K(this.toolkit,C)},setContent:(C,m)=>{V(this.toolkit,C,m)},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(),m=`${C[0]}:${C[1]}`,s=F.molecules.get(yT(V)),z=F.molecules.get(yT(L));if(!s)this.realm.allocate(T.key,V);if(!z)this.realm.allocate(T.key,L);return this.realm.allocate(V,m,"all"),this.realm.claim(L,m),this.store.moleculeJoins.set(m,T.key),m}}),B=()=>YF(F,{key:`${T.key}/singleRelatedKey`,get:(K)=>({get:V})=>{let L=V(S,K);for(let C of L)return C;return null}},["join","keys"]),p=()=>{return YF(F,{key:`${T.key}/multipleRelatedKeys`,get:(K)=>({get:V})=>{let L=$J(S,F);return V(L,K).members}},["join","keys"])},q=()=>YF(F,{key:`${T.key}/singleRelatedEntry`,get:(K)=>({get:V})=>{let L=V(S,K);for(let C of L){let m=w.isAType?.(K)?K:void 0,s=m===void 0?K:void 0;m??=C,s??=C;let z=w.makeContentKey(m,s),a=V(Q,z);return[C,a]}return null}},["join","entries"]),h=()=>YF(F,{key:`${T.key}/multipleRelatedEntries`,get:(K)=>({get:V})=>{let L=$J(S,F);return V(L,K).members.map((m)=>{let s=w.isAType?.(K)?K:void 0,z=s===void 0?K:void 0;s??=m,z??=m;let a=w.makeContentKey(s,z),P=V(Q,a);return[m,P]})}},["join","entries"]);switch(T.cardinality){case"1:1":{let K=B(),V=`${y}KeyOf${YT(A)}`,L=`${A}KeyOf${YT(y)}`,C={[V]:K,[L]:K},m;if(o){let s=q(),z=`${y}EntryOf${YT(A)}`,a=`${A}EntryOf${YT(y)}`,P={[z]:s,[a]:s};m=Object.assign(C,P)}else m=C;this.relations=w,this.states=m;break}case"1:n":{let K=B(),V=p(),L=`${y}KeyOf${YT(A)}`,C=`${A}KeysOf${YT(y)}`,m={[L]:K,[C]:V},s;if(o){let z=q(),a=h(),P=`${y}EntryOf${YT(A)}`,e=`${A}EntriesOf${YT(y)}`,HT={[P]:z,[e]:a};s=Object.assign(m,HT)}else s=m;this.relations=w,this.states=s;break}case"n:n":{let K=p(),V=`${y}KeysOf${YT(A)}`,L=`${A}KeysOf${YT(y)}`,C={[V]:K,[L]:K},m;if(o){let s=h(),z=`${y}EntriesOf${YT(A)}`,a=`${A}EntriesOf${YT(y)}`,P={[z]:s,[a]:s};m=Object.assign(C,P)}else m=C;this.relations=w,this.states=m}}}}function Vy(T,o){let F=o.joins.get(T.key);if(F===void 0){let A=ST.STORE.joins.get(T.key);if(A===void 0)throw new Error(`Join "${T.key}" not found in store "${o.config.name}"`);F=new GA(A.options,A.defaultContent,o),o.joins.set(T.key,F)}return F}function EA(T,o,F){let y=Vy(T,F),A=x(F);if(XT(A)){let{toolkit:S}=A.transactionMeta;y.transact(S,({relations:f})=>{o(f)})}else o(y.relations)}function CS(T,o,F){let y=Vy(T,F),A;switch(T.cardinality){case"1:1":{let S=`${T.a}KeyOf${YT(T.b)}`,f=`${T.b}KeyOf${YT(T.a)}`;A={get[S](){let _=y.states[S];return i(F,_,o)},get[f](){let _=y.states[f];return i(F,_,o)}};let $=`${T.a}EntryOf${YT(T.b)}`;if($ in y.states){let _=`${T.b}EntryOf${YT(T.a)}`;Object.assign(A,{get[$](){let J=y.states[$];return i(F,J,o)},get[_](){let J=y.states[_];return i(F,J,o)}})}break}case"1:n":{let S=`${T.a}KeyOf${YT(T.b)}`,f=`${T.b}KeysOf${YT(T.a)}`;A={get[S](){let _=y.states[S];return i(F,_,o)},get[f](){let _=y.states[f];return i(F,_,o)}};let $=`${T.a}EntryOf${YT(T.b)}`;if($ in y.states){let _=`${T.b}EntriesOf${YT(T.a)}`;Object.assign(A,{get[$](){let J=y.states[$];return i(F,J,o)},get[_](){let J=y.states[_];return i(F,J,o)}})}break}case"n:n":{let S=`${T.a}KeysOf${YT(T.b)}`,f=`${T.b}KeysOf${YT(T.a)}`;A={get[S](){let _=y.states[S];return i(F,_,o)},get[f](){let _=y.states[f];return i(F,_,o)}};let $=`${T.a}EntriesOf${YT(T.b)}`;if($ in y.states){let _=`${T.b}EntriesOf${YT(T.a)}`;Object.assign(A,{get[$](){let J=y.states[$];return i(F,J,o)},get[_](){let J=y.states[_];return i(F,J,o)}})}}}return A}function gR(T,o){return Vy(T,o).core.relatedKeysAtoms}function BF(T){return T.startsWith("\uD83D\uDD0D ")}var JJ=(T)=>{let o=Do(T,{key:"\uD83D\uDD0D Atom Token Index (Internal)",default:()=>{let F=new Map;for(let[y,A]of T.atoms){if(BF(y))continue;let S=wo(A);if(A.family){let f=F.get(A.family.key);if(!f||!("familyMembers"in f))f={key:A.family.key,familyMembers:new Map},F.set(A.family.key,f);f.familyMembers.set(A.family.subKey,S)}else F.set(y,S)}return F},effects:[({setSelf:F})=>{T.on.atomCreation.subscribe("introspection",(y)=>{if(BF(y.key))return;F((A)=>{if(y.family){let{key:S,subKey:f}=y.family,$=A.get(S);if($===void 0||!("familyMembers"in $))$={key:S,familyMembers:new Map},A.set(S,$);$.familyMembers.set(f,y)}else A.set(y.key,y);return A})}),T.on.atomDisposal.subscribe("introspection",(y)=>{F((A)=>{if(y.family){let{key:S,subKey:f}=y.family,$=A.get(S);if($&&"familyMembers"in $){if($.familyMembers.delete(f),$.familyMembers.size===0)A.delete(S)}}else A.delete(y.key);return A})})}]},void 0);return MF(T,{key:"\uD83D\uDD0D Atom Token Index",get:({get:F})=>F(o)})};var _J=(T)=>{let o=Do(T,{key:"\uD83D\uDD0D Selector Token Index (Internal)",default:()=>{let F=new Map;for(let y of[T.readonlySelectors,T.selectors])for(let[A,S]of y){if(BF(A))continue;let f=wo(S);if(S.family){let $=F.get(S.family.key);if(!$||!("familyMembers"in $))$={key:S.family.key,familyMembers:new Map},F.set(S.family.key,$);$.familyMembers.set(S.family.subKey,f)}else F.set(A,f)}return F},effects:[({setSelf:F})=>{T.on.selectorCreation.subscribe("introspection",(y)=>{if(BF(y.key))return;F((A)=>{if(y.family){let{key:S,subKey:f}=y.family,$=A.get(S);if($===void 0||!("familyMembers"in $))$={key:S,familyMembers:new Map},A.set(S,$);$.familyMembers.set(f,y)}else A.set(y.key,y);return A})}),T.on.selectorDisposal.subscribe("introspection",(y)=>{F((A)=>{if(y.family){let{key:S,subKey:f}=y.family,$=A.get(S);if($&&"familyMembers"in $){if($.familyMembers.delete(f),$.familyMembers.size===0)A.delete(S)}}else A.delete(y.key);return A})})}]},void 0);return MF(T,{key:"\uD83D\uDD0D Selector Token Index",get:({get:F})=>F(o)})};class tS{supported;constructor(T){this.supported=T}refine(T){for(let[o,F]of Object.entries(this.supported))try{if(F(T)===!0&&F!==Boolean)return{type:o,data:T}}catch(y){try{if(T instanceof F)return{type:o,data:T}}catch(A){}}return null}}var RJ=new tS({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 tS({object:WJ,array:(T)=>Array.isArray(T)}),SZ=new tS({...RJ.supported,...OJ.supported}),Dy=(T)=>{if(T===void 0)return"undefined";let o=SZ.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=ST.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=c$(this.atomIndex),F=c$(this.selectorIndex),y=[...o.values()].filter(($)=>("familyMembers"in $)),A=[...F.values()].filter(($)=>("familyMembers"in $)),S=performance.now(),f=[];if(T.atomFamilies)for(let $ of y){let _=$.familyMembers.values();for(let J of _){let M=this.statesCreatedAt.get(J.key)??this.auditorCreatedAt,Y=S-M;f.push([J,Y])}}if(T.selectorFamilies)for(let $ of A){let _=$.familyMembers.values();for(let J of _){let M=this.statesCreatedAt.get(J.key)??this.auditorCreatedAt,Y=S-M;f.push([J,Y])}}return f}[Symbol.dispose](){this.unsubscribeFromAtomCreation(),this.unsubscribeFromAtomDisposal(),this.unsubscribeFromSelectorCreation(),this.unsubscribeFromSelectorDisposal(),this.disposed=!0}}var MJ=(T,o)=>{let F=(y,A)=>{let f=((_,J)=>{let R=o(_,J);if(R)return R;return null})(y,A);if(f?.jobComplete??f?.pathComplete)return f;let $=Array.isArray(A)?A.map((_,J)=>[J,_]):WJ(A)?Object.entries(A):[];for(let[_,J]of $){let R=F([...y,_],J);if(R?.jobComplete)return R}return{}};F([],T)};function fZ(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,F){let y="",A=[],S=[],f=[];return MJ(T,($,_)=>{let J;for(J of $){let R=o[J];if(R===void 0)S.push([J,JSON.stringify(_)]);else{let M=F(_,R);if(M.summary!=="No Change")f.push([J,M])}}}),MJ(o,($,_)=>{let J;for(J of $)if(T[J]===void 0)A.push([J,JSON.stringify(_)])}),y=`\uFF5E${f.length} \uFF0B${A.length} \uFF0D${S.length}`,{summary:y,added:A,removed:S,changed:f}}function _Z(T,o,F){return CW(T,o,F)}class LW{leafRefinery;treeRefinery;leafDiffers;treeDiffers;constructor(T,o,F){this.leafRefinery=T,this.treeRefinery=o,this.leafDiffers={},this.treeDiffers={};for(let y of Object.keys(T.supported)){let A=F[y];this.leafDiffers[y]=A}for(let y of Object.keys(o.supported)){let A=F[y];this.treeDiffers[y]=A}}diff(T,o){if(T===o)return{summary:"No Change"};let F=this.leafRefinery.refine(T)??this.treeRefinery.refine(T),y=this.leafRefinery.refine(o)??this.treeRefinery.refine(o);if(F!==null&&y!==null){if(F.type===y.type){if(F.type in this.leafDiffers)return this.leafDiffers[F.type](F.data,y.data);if(F.type in this.treeDiffers)return this.treeDiffers[F.type](F.data,y.data,($,_)=>this.diff($,_))}}let A=Dy(T),S=Dy(o);if(A===S)return{summary:`${A} \u2192 ${S}`};return{summary:`Type change: ${A} \u2192 ${S}`}}}var Tp=new LW(RJ,OJ,{number:fZ,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 qS{type="continuity";globals=[];actions=[];perspectives=[];key;constructor(T){this.key=T}static existing=new IW;static create(T,o){let F=new qS(T),{type:y,globals:A,actions:S,perspectives:f}=o(F),$={type:y,key:T,globals:A,actions:S,perspectives:f};return qS.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[F,y]=T;this.perspectives.push({type:"realtime_perspective",resourceAtoms:F,viewAtoms:y})}break}return this}}function _p(T){let{key:o,config:F}=T,y=qS.create(o,F),{actions:A}=y;for(let S of A)XW(ST.STORE,o,S.key);return WW(ST.STORE,o,-1),y}var Mp=Uy({key:"usersInRoomIndex",mutable:!0,default:()=>new cT,toJson:(T)=>T.toJSON(),fromJson:(T)=>cT.fromJSON(T)}),XJ=Uy({key:"roomIndex",default:()=>new cT,mutable:!0,toJson:(T)=>T.toJSON(),fromJson:(T)=>cT.fromJSON(T)}),RZ={enteredAtEpoch:0},QA=DS({key:"usersInRooms",between:["room","user"],cardinality:"1:n",isAType:(T)=>typeof T==="string",isBType:(T)=>typeof T==="string"},RZ),Xp=LS({key:"usersInMyRoomView",get:(T)=>({find:o})=>{let F=hR(QA);return[o(F,T)]}});import{spawn as WZ}from"child_process";class Cy{listeners;globalListeners;handleEvent(T,...o){for(let y of this.globalListeners)y(T,...o);let F=this.listeners.get(T);if(F)for(let y of F)y(...o)}id="no_id_retrieved";emit;constructor(T){this.emit=T,this.listeners=new Map,this.globalListeners=new Set}on(T,o){let F=this.listeners.get(T);if(F)F.add(o);else this.listeners.set(T,new Set([o]));return this}onAny(T){return this.globalListeners.add(T),this}off(T,o){let F=this.listeners.get(T);if(F)if(o)F.delete(o);else this.listeners.delete(T);return this}offAny(T){return this.globalListeners.delete(T),this}}class YJ extends Cy{incompleteData="";unprocessedEvents=[];incompleteLog="";unprocessedLogs=[];id="#####";process;key;logger;handleLog(T){if(Array.isArray(T)){let[o,...F]=T;switch(o){case"i":this.logger.info(...F);break;case"w":this.logger.warn(...F);break;case"e":this.logger.error(...F);break;default:return}}}constructor(T,o,F){super((y,...A)=>{let S=JSON.stringify([y,...A])+"\x03",f=($)=>{if($.code==="EPIPE")console.error("EPIPE error during write",this.process.stdin);this.process.stdin.removeListener("error",f)};return this.process.stdin.once("error",f),this.process.stdin.write(S),this});if(this.process=T,this.key=o,this.logger=F??{info:(...y)=>{console.info(this.id,this.key,...y)},warn:(...y)=>{console.warn(this.id,this.key,...y)},error:(...y)=>{console.error(this.id,this.key,...y)}},this.process.stdout.on("data",(y)=>{let A=y.toString();if(A==="ALIVE")return;this.unprocessedEvents.push(...A.split("\x03"));let S=this.unprocessedEvents.shift();this.incompleteData+=S??"";try{if(this.incompleteData.startsWith("error"))console.log("\u2757",this.incompleteData);let f=rT(this.incompleteData);this.handleEvent(...f);while(this.unprocessedEvents.length>0){let $=this.unprocessedEvents.shift();if($){if(this.unprocessedEvents.length===0)this.incompleteData=$;f=rT($),this.handleEvent(...f)}}this.incompleteData=""}catch(f){console.warn("\u26A0\uFE0F----------------\u26A0\uFE0F"),console.warn(this.incompleteData),console.warn("\u26A0\uFE0F----------------\u26A0\uFE0F"),console.error(f)}}),this.process.stderr.on("data",(y)=>{let A=y.toString();this.unprocessedLogs.push(...A.split("\x03"));let S=this.unprocessedLogs.shift();this.incompleteLog+=S??"";try{let f=rT(this.incompleteLog);this.handleLog(f);while(this.unprocessedLogs.length>0)if(this.incompleteLog=this.unprocessedLogs.shift()??"",this.incompleteLog)f=rT(this.incompleteLog),this.handleLog(f)}catch(f){console.error("\u274C\u274C\u274C"),console.error(this.incompleteLog),console.error(f),console.error("\u274C\u274C\u274C\uFE0F")}}),T.pid)this.id=T.pid.toString()}}class kW extends Cy{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 Cy{incompleteData="";unprocessedEvents=[];relays;relayServices;process;id="#####";log(...T){this.process.stderr.write(yT(T.map((o)=>o instanceof cT?`{ ${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 F=JSON.stringify([T,...o]);return this.process.stdout.write(F+"\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 F=this.unprocessedEvents.shift();this.incompleteData+=F??"";try{let y=rT(this.incompleteData);this.logger.info("\uD83C\uDFB0","received",y),this.handleEvent(...y);while(this.unprocessedEvents.length>0){let A=this.unprocessedEvents.shift();if(A){if(this.unprocessedEvents.length===0)this.incompleteData=A;let S=rT(A);this.handleEvent(...S)}}this.incompleteData=""}catch(y){if(y instanceof Error)this.logger.error("\u2757",y.message,y.cause,y.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 F of this.relayServices){let y=F(o);if(y)o.disposalFunctions.push(y)}this.on(`user:${T}`,(...F)=>{o.in.next(F)}),o.out.subscribe("socket",(F)=>{this.emit(...F)})}),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=PF({key:"roomArguments",default:["echo",["Hello World!"]]}),BW=LS({key:"room",get:(T)=>async({get:o,find:F})=>{let y=F(HJ,T),A=o(y),[S,f]=A,$=await new Promise((_)=>{let J=WZ(S,f,{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 Pp=UA({key:"createRoom",do:({get:T,set:o,find:F},y,A,S)=>{let f=S?[A,S]:[A],$=F(HJ,y);o($,f),o(XJ,(R)=>R.add(y));let _=F(BW,y);return T(_)}}),hp=UA({key:"joinRoom",do:(T,o,F,y)=>{let A={enteredAtEpoch:y};return EA(QA,(S)=>{S.set({room:o,user:F},A)},T.env().store),A}}),gp=UA({key:"leaveRoom",do:(T,o,F)=>{EA(QA,(y)=>{y.delete({room:o,user:F})},T.env().store)}}),np=UA({key:"destroyRoom",do:(T,o)=>{EA(QA,(F)=>{F.delete({room:o})},T.env().store),T.set(XJ,(F)=>(F.delete(o),F))}});function GJ(T,o){return o.map((F)=>{switch(F.type){case"transaction_update":{let y=GJ(T,F.updates);return{...F,updates:y}}case"atom_update":case"selector_update":case"molecule_creation":case"molecule_disposal":case"molecule_transfer":case"state_creation":case"state_disposal":return F}}).filter((F)=>{switch(F.type){case"atom_update":case"selector_update":return T.includes(F.key);case"state_creation":case"state_disposal":return T.includes(F.token.key);case"molecule_creation":case"transaction_update":case"molecule_disposal":case"molecule_transfer":return!0}})}var ip=PF({key:"redactor",default:{occlude:(T)=>T}}),Ly=PF({key:"unacknowledgedUpdates",default:()=>[]});var NW=PF({key:"sockets",default:null}),sp=Uy({key:"socketsIndex",mutable:!0,default:()=>new cT,toJson:(T)=>T.toJSON(),fromJson:(T)=>cT.fromJSON(T)}),ap=Uy({key:"usersIndex",mutable:!0,default:()=>new cT,toJson:(T)=>T.toJSON(),fromJson:(T)=>cT.fromJSON(T)}),EJ=DS({key:"usersOfSockets",between:["user","socket"],cardinality:"1:1",isAType:(T)=>T.startsWith("user::"),isBType:(T)=>T.startsWith("socket::")});function pW(T,o,F,y){let A=o.key;return function S(){let f=[];for(let _ of o.globals){let J=_.type==="mutable_atom"?nT(T,_):_,R=OT(T,J);f.push(J,R)}for(let _ of o.perspectives){let{viewAtoms:J,resourceAtoms:R}=_,M=i(T,J,F),Y=OT(T,M);T.logger.info("\uD83D\uDC41","atom",R.key,`${F} can see`,{viewAtoms:J,resourceAtoms:R,userView:Y});for(let H of Y){let Q=H.type==="mutable_atom"?nT(T,H):H,w=OT(T,Q);f.push(Q,w)}}let $=aT(T)?T.transactionMeta.epoch.get(A)??null:null;y?.emit(`continuity-init:${A}`,$,f)}}function xW(T,o,F){let y=o.key;return function A(S){T.logger.info("\uD83D\uDECE\uFE0F","continuity",y,"received",S);let{key:f,id:$}=S,_=`tx-run:${f}:${$}`,J=`${_}:start`,R=`${_}:end`;performance.mark(J);try{zy(T,{type:"transaction",key:f},$)(...S.params)}catch(Y){if(Y instanceof Error)T.logger.error("\u274C","continuity",y,`failed to run transaction ${f} from ${F} with update ${$}`,Y.message)}performance.mark(R);let M=performance.measure(_,J,R);T?.logger.info("\uD83D\uDE80","transaction",f,$,F,M.duration)}}function bW(T,o,F,y){let A=o.key;return function S(f){if(T.logger.info("\uD83D\uDC4D","continuity",A,`${F} acknowledged epoch ${f}`),y[0]?.epoch===f)bT(T,Ly,F,(_)=>{return _.shift(),T.logger.info("\uD83D\uDC4D","continuity",A,`${F} unacknowledged update queue now has`,_.length,"items"),_})}}function jW(T,o,F,y){let A=o.key,S=[];for(let f of o.actions){let $=AJ(T,f,`sync-continuity:${A}:${F}`,(_)=>{try{let J=o.globals.map((Y)=>{if(Y.type==="atom")return Y.key;return ZF(Y).key}).concat(o.perspectives.flatMap((Y)=>{let{viewAtoms:H}=Y,Q=i(T,H,F);return OT(T,Q).map((B)=>{return B.type==="mutable_atom"?"*"+B.key:B.key})})),R=GJ(J,_.updates),M={..._,updates:R};bT(T,Ly,F,(Y)=>{if(M)Y.push(M),Y.sort((H,Q)=>H.epoch-Q.epoch),T.logger.info("\uD83D\uDC4D","continuity",A,`${F} unacknowledged update queue now has`,Y.length,"items");return Y}),y?.emit(`tx-new:${A}`,M)}catch(J){if(J instanceof Error)T.logger.error("\u274C","continuity",A,`${F} failed to send update from transaction ${f.key} to ${F}`,J.message)}});S.push($)}return S}function tW(T,o,F,y){let A=o.key,S=[];for(let f of o.perspectives){let{viewAtoms:$}=f,_=i(T,$,F),J=fo(T,_,`sync-continuity:${A}:${F}:perspective:${f.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 p=B.type==="mutable_atom"?nT(T,B):B,q=OT(T,p);return[p,q]});if(T.logger.info("\uD83D\uDC41","atom",f.resourceAtoms.key,`${F} has a new perspective`,{oldKeys:Y,newKeys:H,revealed:w,concealed:Q}),w.length>0)y?.emit(`reveal:${A}`,w);if(Q.length>0)y?.emit(`conceal:${A}`,Q)});S.push(J)}return S}function Cx({socket:T,store:o=ST.STORE}){return function F(y){let A=T,S=y.key,f=CS(EJ,`socket::${A.id}`,o).userKeyOfSocket,$=OT(o,f);if(!$)return o.logger.error("\u274C","continuity",S,`Tried to create a synchronizer for a socket (${A.id}) that is not connected to a user.`),()=>{};let _=CS(EJ,$,o).socketKeyOfUser,J=fo(o,_,`sync-continuity:${S}:${$}`,({newValue:p})=>{if(o.logger.info("\uD83D\uDC4B","continuity",S,`seeing ${$} on new socket ${p}`),p===null){o.logger.warn("\u274C","continuity",S,`User (${$}) is not connected to a socket, waiting for them to reappear.`);return}let q=i(o,NW,p);A=OT(o,q);for(let K of R)A?.emit(`tx-new:${S}`,K)}),R=OT(o,Ly,$),M=[],Y=tW(o,y,$,A),H=jW(o,y,$,A);M.push(...Y,...H);let Q=pW(o,y,$,T);A.off(`get:${S}`,Q),A.on(`get:${S}`,Q);let w=xW(o,y,$);A.off(`tx-run:${S}`,w),A.on(`tx-run:${S}`,w);let B=bW(o,y,$,R);return A?.on(`ack:${S}`,B),()=>{for(let p of M)p();A?.off(`ack:${S}`,B),A?.off(`get:${S}`,Q),A?.off(`tx-run:${S}`,w)}}}var{file:O4,serve:K5}=globalThis.Bun;import{readFileSync as mW}from"fs";import{resolve as wJ}from"path";function OZ(T,o){let F={},y=[];for(let A in T){let S=T[A],f=o[A],$=S["~standard"].validate(f);if($ instanceof Promise)throw new Error(`Validation must be synchronous, but ${A} returned a Promise.`);if($.issues){y.push(...$.issues.map((_)=>({..._,path:[A,..._.path??[]]})));continue}F[A]=$.value}if(y.length)return{issues:y};return{value:F}}function qW(T){let o=T.runtimeEnvStrict??T.runtimeEnv??process.env;if(T.emptyStringAsUndefined??!1){for(let[q,h]of Object.entries(o))if(h==="")delete o[q]}if(!!T.skipValidation)return o;let A=typeof T.client==="object"?T.client:{},S=typeof T.server==="object"?T.server:{},f=typeof T.shared==="object"?T.shared:{},$=T.isServer??(typeof window==="undefined"||("Deno"in window)),_=$?{...S,...f,...A}:{...A,...f},J=OZ(_,o),R=T.onValidationError??((q)=>{throw console.error("\u274C Invalid environment variables:",q),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=(q)=>{if(!T.clientPrefix)return!0;return!q.startsWith(T.clientPrefix)&&!(q in f)},H=(q)=>{return $||!Y(q)},Q=(q)=>{return q==="__esModule"||q==="$$typeof"},w=(T.extends??[]).reduce((q,h)=>{return Object.assign(q,h)},{}),B=Object.assign(J.value,w);return new Proxy(B,{get(q,h){if(typeof h!=="string")return;if(Q(h))return;if(!H(h))return M(h);return Reflect.get(q,h)}})}var MZ="__vite_start_time"in globalThis,XZ=typeof window!=="undefined",Fb="vitest"in globalThis,HF=xo("string"),vW=xo('"true" | "false" | undefined'),uo=qW({isServer:!MZ&&!XZ,server:{CI:xo("string | undefined").pipe(Boolean),POSTGRES_USER:HF,POSTGRES_PASSWORD:HF,POSTGRES_DATABASE:HF,POSTGRES_HOST:HF,POSTGRES_PORT:HF.pipe((T)=>Number.parseInt(T,10)),BACKEND_PORT:HF.pipe((T)=>Number.parseInt(T,10)),RUN_WORKERS_FROM_SOURCE:vW.pipe((T)=>T==="true"),FRONTEND_PORT:HF.pipe((T)=>Number.parseInt(T,10)),FRONTEND_ORIGINS:HF.pipe.try((T)=>JSON.parse(T),xo("string[]")),OPENAI_API_KEY:xo("string | undefined")},clientPrefix:"VITE_",client:{VITE_BACKEND_ORIGIN:HF,VITE_USE_SELF_SIGNED_CERTIFICATE:vW.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:mW(wJ(PW,"./cert.pem"),"utf-8"),key:mW(wJ(PW,"./key.pem"),"utf-8")}:void 0;import Z5 from"path";var O=Symbol.for("drizzle:entityKind"),Jb=Symbol.for("drizzle:hasOwnEntityKind");function E(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 F=Object.getPrototypeOf(T).constructor;if(F)while(F){if(O in F&&F[O]===o[O])return!0;F=Object.getPrototypeOf(F)}return!1}class ET{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,F){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:F,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 co=Symbol.for("drizzle:Name");class KJ{static[O]="PgForeignKeyBuilder";reference;_onUpdate="no action";_onDelete="no action";constructor(T,o){if(this.reference=()=>{let{name:F,columns:y,foreignColumns:A}=T();return{name:F,columns:y,foreignTable:A[0].table,foreignColumns:A}},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 gW(T,this)}}class gW{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:F}=this.reference(),y=o.map((f)=>f.name),A=F.map((f)=>f.name),S=[this.table[co],...y,F[0].table[co],...A];return T??`${S.join("_")}_fk`}}function vS(T,...o){return T(...o)}function nW(T,o){return`${T[co]}_${o.join("_")}_unique`}function uW(T,o,F){for(let y=o;y<T.length;y++){let A=T[y];if(A==="\\"){y++;continue}if(A==='"')return[T.slice(o,y).replace(/\\/g,""),y+1];if(F)continue;if(A===","||A==="}")return[T.slice(o,y).replace(/\\/g,""),y]}return[T.slice(o).replace(/\\/g,""),T.length]}function cW(T,o=0){let F=[],y=o,A=!1;while(y<T.length){let S=T[y];if(S===","){if(A||y===o)F.push("");A=!0,y++;continue}if(A=!1,S==="\\"){y+=2;continue}if(S==='"'){let[_,J]=uW(T,y+1,!0);F.push(_),y=J;continue}if(S==="}")return[F,y+1];if(S==="{"){let[_,J]=cW(T,y+1);F.push(_),y=J;continue}let[f,$]=uW(T,y,!1);F.push(f),y=$}return[F,y]}function iW(T){let[o]=cW(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 t 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:F,actions:y})=>{return vS((A,S)=>{let f=new KJ(()=>{let $=A();return{columns:[T],foreignColumns:[$]}});if(S.onUpdate)f.onUpdate(S.onUpdate);if(S.onDelete)f.onDelete(S.onDelete);return f.build(o)},F,y)})}buildExtraConfigColumn(T){return new dW(T,this.config)}}class I extends ET{constructor(T,o){if(!o.uniqueName)o.uniqueName=nW(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 VA{static[O]="IndexedColumn";constructor(T,o,F,y){this.name=T,this.keyAsName=o,this.type=F,this.indexConfig=y}name;keyAsName;type;indexConfig}class rW extends t{static[O]="PgArrayBuilder";constructor(T,o,F){super(T,"array","PgArray");this.config.baseBuilder=o,this.config.size=F}build(T){let o=this.config.baseBuilder.build(T);return new QJ(T,this.config,o)}}class QJ extends I{constructor(T,o,F,y){super(T,o);this.baseColumn=F,this.range=y,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=iW(T);return T.map((o)=>this.baseColumn.mapFromDriverValue(o))}mapToDriverValue(T,o=!1){let F=T.map((y)=>y===null?null:E(this.baseColumn,QJ)?this.baseColumn.mapToDriverValue(y,!0):this.baseColumn.mapToDriverValue(y));if(o)return F;return zJ(F)}}var VJ=Symbol.for("drizzle:isPgEnum");function lW(T){return!!T&&typeof T==="function"&&VJ in T&&T[VJ]===!0}class sW extends t{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 mS(T,o){return YZ(T,o,void 0)}function YZ(T,o,F){let y=Object.assign((A)=>new sW(A??"",y),{enumName:T,enumValues:o,schema:F,[VJ]:!0});return y}class iT{static[O]="Subquery";constructor(T,o,F,y=!1){this._={brand:"Subquery",sql:T,selectedFields:o,alias:F,isWith:y}}}class DA extends iT{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 vS((F,y)=>y.startActiveSpan(T,(A)=>{try{return o(A)}catch(S){throw A.setStatus({code:F.SpanStatusCode.ERROR,message:S instanceof Error?S.message:"Unknown error"}),S}finally{A.end()}}),DJ,CJ)}};var VT=Symbol.for("drizzle:ViewBaseConfig");var PS=Symbol.for("drizzle:Schema"),hS=Symbol.for("drizzle:Columns"),TO=Symbol.for("drizzle:ExtraConfigColumns"),LJ=Symbol.for("drizzle:OriginalName"),IJ=Symbol.for("drizzle:BaseName"),CA=Symbol.for("drizzle:IsAlias"),oO=Symbol.for("drizzle:ExtraConfigBuilder"),ZZ=Symbol.for("drizzle:IsDrizzleTable");class b{static[O]="Table";static Symbol={Name:co,Schema:PS,OriginalName:LJ,Columns:hS,ExtraConfigColumns:TO,BaseName:IJ,IsAlias:CA,ExtraConfigBuilder:oO};[co];[LJ];[PS];[hS];[TO];[IJ];[CA]=!1;[ZZ]=!0;[oO]=void 0;constructor(T,o,F){this[co]=this[LJ]=T,this[PS]=o,this[IJ]=F}}function lT(T){return T[co]}function iF(T){return`${T[PS]??"public"}.${T[co]}`}function kJ(T){return T!==null&&T!==void 0&&typeof T.getSQL==="function"}function HZ(T){let o={sql:"",params:[]};for(let F of T)if(o.sql+=F.sql,o.params.push(...F.params),F.typings?.length){if(!o.typings)o.typings=[];o.typings.push(...F.typings)}return o}class dT{static[O]="StringChunk";value;constructor(T){this.value=Array.isArray(T)?T:[T]}getSQL(){return new j([this])}}class j{constructor(T){this.queryChunks=T}static[O]="SQL";decoder=yO;shouldInlineParams=!1;append(T){return this.queryChunks.push(...T.queryChunks),this}toQuery(T){return wT.startActiveSpan("drizzle.buildSQL",(o)=>{let F=this.buildQueryFromSourceParams(this.queryChunks,T);return o?.setAttributes({"drizzle.query.text":F.sql,"drizzle.query.params":JSON.stringify(F.params)}),F})}buildQueryFromSourceParams(T,o){let F=Object.assign({},o,{inlineParams:o.inlineParams||this.shouldInlineParams,paramStartIndex:o.paramStartIndex||{value:0}}),{casing:y,escapeName:A,escapeParam:S,prepareTyping:f,inlineParams:$,paramStartIndex:_}=F;return HZ(T.map((J)=>{if(E(J,dT))return{sql:J.value.join(""),params:[]};if(E(J,gS))return{sql:A(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,F)}if(E(J,j))return this.buildQueryFromSourceParams(J.queryChunks,{...F,inlineParams:$||J.shouldInlineParams});if(E(J,b)){let R=J[b.Symbol.Schema],M=J[b.Symbol.Name];return{sql:R===void 0||J[CA]?A(M):A(R)+"."+A(M),params:[]}}if(E(J,ET)){let R=y.getColumnCasing(J);if(o.invokeSource==="indexes")return{sql:A(R),params:[]};let M=J.table[b.Symbol.Schema];return{sql:J.table[CA]||M===void 0?A(J.table[b.Symbol.Name])+"."+A(R):A(M)+"."+A(J.table[b.Symbol.Name])+"."+A(R),params:[]}}if(E(J,Uo)){let R=J[VT].schema,M=J[VT].name;return{sql:R===void 0||J[VT].isAlias?A(M):A(R)+"."+A(M),params:[]}}if(E(J,Co)){if(E(J.value,NF))return{sql:S(_.value++,J),params:[J],typings:["none"]};let R=J.value===null?null:J.encoder.mapToDriverValue(J.value);if(E(R,j))return this.buildQueryFromSourceParams([R],F);if($)return{sql:this.mapInlineParam(R,F),params:[]};let M=["none"];if(f)M=[f(J.encoder)];return{sql:S(_.value++,R),params:[R],typings:M}}if(E(J,NF))return{sql:S(_.value++,J),params:[J],typings:["none"]};if(E(J,j.Aliased)&&J.fieldAlias!==void 0)return{sql:A(J.fieldAlias),params:[]};if(E(J,iT)){if(J._.isWith)return{sql:A(J._.alias),params:[]};return this.buildQueryFromSourceParams([new dT("("),J._.sql,new dT(") "),new gS(J._.alias)],F)}if(lW(J)){if(J.schema)return{sql:A(J.schema)+"."+A(J.enumName),params:[]};return{sql:A(J.enumName),params:[]}}if(kJ(J)){if(J.shouldOmitSQLParens?.())return this.buildQueryFromSourceParams([J.getSQL()],F);return this.buildQueryFromSourceParams([new dT("("),J.getSQL(),new dT(")")],F)}if($)return{sql:this.mapInlineParam(J,F),params:[]};return{sql:S(_.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 F=T.toString();if(F==="[object Object]")return o(JSON.stringify(T));return o(F)}throw new Error("Unexpected param value: "+T)}getSQL(){return this}as(T){if(T===void 0)return this;return new j.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 gS{constructor(T){this.value=T}static[O]="Name";brand;getSQL(){return new j([this])}}function FO(T){return typeof T==="object"&&T!==null&&"mapToDriverValue"in T&&typeof T.mapToDriverValue==="function"}var yO={mapFromDriverValue:(T)=>T},AO={mapToDriverValue:(T)=>T},lb={...yO,...AO};class Co{constructor(T,o=AO){this.value=T,this.encoder=o}static[O]="Param";brand;getSQL(){return new j([this])}}function X(T,...o){let F=[];if(o.length>0||T.length>0&&T[0]!=="")F.push(new dT(T[0]));for(let[y,A]of o.entries())F.push(A,new dT(T[y+1]));return new j(F)}((T)=>{function o(){return new j([])}T.empty=o;function F(_){return new j(_)}T.fromList=F;function y(_){return new j([new dT(_)])}T.raw=y;function A(_,J){let R=[];for(let[M,Y]of _.entries()){if(M>0&&J!==void 0)R.push(J);R.push(Y)}return new j(R)}T.join=A;function S(_){return new gS(_)}T.identifier=S;function f(_){return new NF(_)}T.placeholder=f;function $(_,J){return new Co(_,J)}T.param=$})(X||(X={}));((T)=>{class o{constructor(F,y){this.sql=F,this.fieldAlias=y}static[O]="SQL.Aliased";isSelectionField=!1;getSQL(){return this.sql}clone(){return new o(this.sql,this.fieldAlias)}}T.Aliased=o})(j||(j={}));class NF{constructor(T){this.name=T}static[O]="Placeholder";getSQL(){return new j([this])}}function BJ(T,o){return T.map((F)=>{if(E(F,NF)){if(!(F.name in o))throw new Error(`No value for placeholder "${F.name}" was provided`);return o[F.name]}if(E(F,Co)&&E(F.value,NF)){if(!(F.value.name in o))throw new Error(`No value for placeholder "${F.value.name}" was provided`);return F.encoder.mapToDriverValue(o[F.value.name])}return F})}var GZ=Symbol.for("drizzle:IsDrizzleView");class Uo{static[O]="View";[VT];[GZ]=!0;constructor({name:T,schema:o,selectedFields:F,query:y}){this[VT]={name:T,originalName:T,schema:o,selectedFields:F,query:y,isExisting:!y,isAlias:!1}}getSQL(){return new j([this])}}ET.prototype.getSQL=function(){return new j([this])};b.prototype.getSQL=function(){return new j([this])};iT.prototype.getSQL=function(){return new j([this])};class Iy{constructor(T){this.table=T}static[O]="ColumnAliasProxyHandler";get(T,o){if(o==="table")return this.table;return T[o]}}class LA{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 y=T[b.Symbol.Columns];if(!y)return y;let A={};return Object.keys(y).map((S)=>{A[S]=new Proxy(y[S],new Iy(new Proxy(T,this)))}),A}let F=T[o];if(E(F,ET))return new Proxy(F,new Iy(new Proxy(T,this)));return F}}function nS(T,o){return new Proxy(T,new LA(o,!1))}function oF(T,o){return new Proxy(T,new Iy(new Proxy(T.table,new LA(o,!1))))}function NJ(T,o){return new j.Aliased(IA(T.sql,o),T.fieldAlias)}function IA(T,o){return X.join(T.queryChunks.map((F)=>{if(E(F,ET))return oF(F,o);if(E(F,j))return IA(F,o);if(E(F,j.Aliased))return NJ(F,o);return F}))}class uS extends Error{static[O]="DrizzleError";constructor({message:T,cause:o}){super(T);this.name="DrizzleError",this.cause=o}}class pJ extends uS{static[O]="TransactionRollbackError";constructor(){super({message:"Rollback"})}}function Ko(T,o){if(FO(o)&&!kJ(T)&&!E(T,Co)&&!E(T,NF)&&!E(T,ET)&&!E(T,b)&&!E(T,Uo))return new Co(T,o);return T}var cS=(T,o)=>{return X`${T} = ${Ko(o,T)}`},SO=(T,o)=>{return X`${T} <> ${Ko(o,T)}`};function kA(...T){let o=T.filter((F)=>F!==void 0);if(o.length===0)return;if(o.length===1)return new j(o);return new j([new dT("("),X.join(o,new dT(" and ")),new dT(")")])}function fO(...T){let o=T.filter((F)=>F!==void 0);if(o.length===0)return;if(o.length===1)return new j(o);return new j([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((F)=>Ko(F,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((F)=>Ko(F,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 GO(T,o,F){return X`${T} between ${Ko(o,T)} and ${Ko(F,T)}`}function EO(T,o,F){return X`${T} not between ${Ko(o,T)} and ${Ko(F,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 xJ{static[O]="DefaultLogger";writer;constructor(T){this.writer=T?.writer??new DO}logQuery(T,o){let F=o.map((A)=>{try{return JSON.stringify(A)}catch{return String(A)}}),y=F.length?` -- params: [${F.join(", ")}]`:"";this.writer.write(`Query: ${T}${y}`)}}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,F){let y={},A=T.reduce((S,{path:f,field:$},_)=>{let J;if(E($,ET))J=$;else if(E($,j))J=$.decoder;else J=$.sql.decoder;let R=S;for(let[M,Y]of f.entries())if(M<f.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(F&&E($,ET)&&f.length===2){let w=f[0];if(!(w in y))y[w]=Q===null?lT($.table):!1;else if(typeof y[w]==="string"&&y[w]!==lT($.table))y[w]=!1}}return S},{});if(F&&Object.keys(y).length>0){for(let[S,f]of Object.entries(y))if(typeof f==="string"&&!F[f])A[S]=null}return A}function to(T,o){return Object.entries(T).reduce((F,[y,A])=>{if(typeof y!=="string")return F;let S=o?[...o,y]:[y];if(E(A,ET)||E(A,j)||E(A,j.Aliased))F.push({path:S,field:A});else if(E(A,b))F.push(...to(A[b.Symbol.Columns],S));else F.push(...to(A,S));return F},[])}function BA(T,o){let F=Object.keys(T),y=Object.keys(o);if(F.length!==y.length)return!1;for(let[A,S]of F.entries())if(S!==y[A])return!1;return!0}function iS(T,o){let F=Object.entries(o).filter(([,y])=>y!==void 0).map(([y,A])=>{if(E(A,j)||E(A,ET))return[y,A];else return[y,new Co(A,T[b.Symbol.Columns][y])]});if(F.length===0)throw new Error("No values to set");return Object.fromEntries(F)}function LO(T,o){for(let F of o)for(let y of Object.getOwnPropertyNames(F.prototype)){if(y==="constructor")continue;Object.defineProperty(T.prototype,y,Object.getOwnPropertyDescriptor(F.prototype,y)||Object.create(null))}}function IO(T){return T[b.Symbol.Columns]}function GF(T){return E(T,iT)?T._.alias:E(T,Uo)?T[VT].name:E(T,j)?void 0:T[b.Symbol.IsAlias]?T[b.Symbol.Name]:T[b.Symbol.BaseName]}function fT(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 pF extends t{static[O]="PgIntColumnBaseBuilder";generatedAlwaysAsIdentity(T){if(T){let{name:o,...F}=T;this.config.generatedIdentity={type:"always",sequenceName:o,sequenceOptions:F}}else this.config.generatedIdentity={type:"always"};return this.config.hasDefault=!0,this.config.notNull=!0,this}generatedByDefaultAsIdentity(T){if(T){let{name:o,...F}=T;this.config.generatedIdentity={type:"byDefault",sequenceName:o,sequenceOptions:F}}else this.config.generatedIdentity={type:"byDefault"};return this.config.hasDefault=!0,this.config.notNull=!0,this}}class BO extends pF{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 pO extends pF{static[O]="PgBigInt64Builder";constructor(T){super(T,"bigint","PgBigInt64")}build(T){return new xO(T,this.config)}}class xO extends I{static[O]="PgBigInt64";getSQLType(){return"bigint"}mapFromDriverValue(T){return BigInt(T)}}function bO(T,o){let{name:F,config:y}=fT(T,o);if(y.mode==="number")return new BO(F);return new pO(F)}class jO extends t{static[O]="PgBigSerial53Builder";constructor(T){super(T,"number","PgBigSerial53");this.config.hasDefault=!0,this.config.notNull=!0}build(T){return new tO(T,this.config)}}class tO extends I{static[O]="PgBigSerial53";getSQLType(){return"bigserial"}mapFromDriverValue(T){if(typeof T==="number")return T;return Number(T)}}class qO extends t{static[O]="PgBigSerial64Builder";constructor(T){super(T,"bigint","PgBigSerial64");this.config.hasDefault=!0}build(T){return new vO(T,this.config)}}class vO extends I{static[O]="PgBigSerial64";getSQLType(){return"bigserial"}mapFromDriverValue(T){return BigInt(T)}}function mO(T,o){let{name:F,config:y}=fT(T,o);if(y.mode==="number")return new jO(F);return new qO(F)}class PO extends t{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 NA(T){return new PO(T??"")}class gO extends t{static[O]="PgCharBuilder";constructor(T,o){super(T,"string","PgChar");this.config.length=o.length,this.config.enumValues=o.enum}build(T){return new nO(T,this.config)}}class nO 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:F,config:y}=fT(T,o);return new gO(F,y)}class cO extends t{static[O]="PgCidrBuilder";constructor(T){super(T,"string","PgCidr")}build(T){return new iO(T,this.config)}}class iO extends I{static[O]="PgCidr";getSQLType(){return"cidr"}}function dO(T){return new cO(T??"")}class rO extends t{static[O]="PgCustomColumnBuilder";constructor(T,o,F){super(T,"custom","PgCustomColumn");this.config.fieldConfig=o,this.config.customTypeParams=F}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,F)=>{let{name:y,config:A}=fT(o,F);return new rO(y,A,T)}}class EF extends t{static[O]="PgDateColumnBaseBuilder";defaultNow(){return this.default(X`now()`)}}class aO extends EF{static[O]="PgDateBuilder";constructor(T){super(T,"date","PgDate")}build(T){return new dS(T,this.config)}}class dS extends I{static[O]="PgDate";getSQLType(){return"date"}mapFromDriverValue(T){return new Date(T)}mapToDriverValue(T){return T.toISOString()}}class eO extends EF{static[O]="PgDateStringBuilder";constructor(T){super(T,"string","PgDateString")}build(T){return new rS(T,this.config)}}class rS extends I{static[O]="PgDateString";getSQLType(){return"date"}}function TM(T,o){let{name:F,config:y}=fT(T,o);if(y?.mode==="date")return new aO(F);return new eO(F)}class oM extends t{static[O]="PgDoublePrecisionBuilder";constructor(T){super(T,"number","PgDoublePrecision")}build(T){return new FM(T,this.config)}}class FM extends I{static[O]="PgDoublePrecision";getSQLType(){return"double precision"}mapFromDriverValue(T){if(typeof T==="string")return Number.parseFloat(T);return T}}function yM(T){return new oM(T??"")}class AM extends t{static[O]="PgInetBuilder";constructor(T){super(T,"string","PgInet")}build(T){return new SM(T,this.config)}}class SM extends I{static[O]="PgInet";getSQLType(){return"inet"}}function fM(T){return new AM(T??"")}class $M extends pF{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 lS(T){return new $M(T??"")}class _M extends t{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:F,config:y}=fT(T,o);return new _M(F,y)}class OM extends t{static[O]="PgJsonBuilder";constructor(T){super(T,"json","PgJson")}build(T){return new sS(T,this.config)}}class sS 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 t{static[O]="PgJsonbBuilder";constructor(T){super(T,"json","PgJsonb")}build(T){return new aS(T,this.config)}}class aS 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 t{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,F,y]=T.slice(1,-1).split(",");return[Number.parseFloat(o),Number.parseFloat(F),Number.parseFloat(y)]}mapToDriverValue(T){return`{${T[0]},${T[1]},${T[2]}}`}}class GM extends t{static[O]="PgLineABCBuilder";constructor(T){super(T,"json","PgLineABC")}build(T){return new EM(T,this.config)}}class EM extends I{static[O]="PgLineABC";getSQLType(){return"line"}mapFromDriverValue(T){let[o,F,y]=T.slice(1,-1).split(",");return{a:Number.parseFloat(o),b:Number.parseFloat(F),c:Number.parseFloat(y)}}mapToDriverValue(T){return`{${T.a},${T.b},${T.c}}`}}function wM(T,o){let{name:F,config:y}=fT(T,o);if(!y?.mode||y.mode==="tuple")return new ZM(F);return new GM(F)}class UM extends t{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 t{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 t{static[O]="PgNumericBuilder";constructor(T,o,F){super(T,"string","PgNumeric");this.config.precision=o,this.config.scale=F}build(T){return new eS(T,this.config)}}class eS 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 t{static[O]="PgNumericNumberBuilder";constructor(T,o,F){super(T,"number","PgNumericNumber");this.config.precision=o,this.config.scale=F}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 t{static[O]="PgNumericBigIntBuilder";constructor(T,o,F){super(T,"bigint","PgNumericBigInt");this.config.precision=o,this.config.scale=F}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:F,config:y}=fT(T,o),A=y?.mode;return A==="number"?new LM(F,y?.precision,y?.scale):A==="bigint"?new kM(F,y?.precision,y?.scale):new CM(F,y?.precision,y?.scale)}class pM extends t{static[O]="PgPointTupleBuilder";constructor(T){super(T,"array","PgPointTuple")}build(T){return new xM(T,this.config)}}class xM extends I{static[O]="PgPointTuple";getSQLType(){return"point"}mapFromDriverValue(T){if(typeof T==="string"){let[o,F]=T.slice(1,-1).split(",");return[Number.parseFloat(o),Number.parseFloat(F)]}return[T.x,T.y]}mapToDriverValue(T){return`(${T[0]},${T[1]})`}}class bM extends t{static[O]="PgPointObjectBuilder";constructor(T){super(T,"json","PgPointObject")}build(T){return new jM(T,this.config)}}class jM extends I{static[O]="PgPointObject";getSQLType(){return"point"}mapFromDriverValue(T){if(typeof T==="string"){let[o,F]=T.slice(1,-1).split(",");return{x:Number.parseFloat(o),y:Number.parseFloat(F)}}return T}mapToDriverValue(T){return`(${T.x},${T.y})`}}function tM(T,o){let{name:F,config:y}=fT(T,o);if(!y?.mode||y.mode==="tuple")return new pM(F);return new bM(F)}function EZ(T){let o=[];for(let F=0;F<T.length;F+=2)o.push(Number.parseInt(T.slice(F,F+2),16));return new Uint8Array(o)}function qM(T,o){let F=new ArrayBuffer(8),y=new DataView(F);for(let A=0;A<8;A++)y.setUint8(A,T[o+A]);return y.getFloat64(0,!0)}function jJ(T){let o=EZ(T),F=0,y=o[F];F+=1;let A=new DataView(o.buffer),S=A.getUint32(F,y===1);F+=4;let f;if(S&536870912)f=A.getUint32(F,y===1),F+=4;if((S&65535)===1){let $=qM(o,F);F+=8;let _=qM(o,F);return F+=8,[$,_]}throw new Error("Unsupported geometry type")}class vM extends t{static[O]="PgGeometryBuilder";constructor(T){super(T,"array","PgGeometry")}build(T){return new mM(T,this.config)}}class mM extends I{static[O]="PgGeometry";getSQLType(){return"geometry(point)"}mapFromDriverValue(T){return jJ(T)}mapToDriverValue(T){return`point(${T[0]} ${T[1]})`}}class PM extends t{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=jJ(T);return{x:o[0],y:o[1]}}mapToDriverValue(T){return`point(${T.x} ${T.y})`}}function gM(T,o){let{name:F,config:y}=fT(T,o);if(!y?.mode||y.mode==="tuple")return new vM(F);return new PM(F)}class nM extends t{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 cM(T){return new nM(T??"")}class iM extends t{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 iM(T??"")}class lM extends pF{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 t{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 F2 extends t{static[O]="PgTextBuilder";constructor(T,o){super(T,"string","PgText");this.config.enumValues=o.enum}build(T){return new y2(T,this.config)}}class y2 extends I{static[O]="PgText";enumValues=this.config.enumValues;getSQLType(){return"text"}}function A2(T,o={}){let{name:F,config:y}=fT(T,o);return new F2(F,y)}class S2 extends EF{constructor(T,o,F){super(T,"string","PgTime");this.withTimezone=o,this.precision=F,this.config.withTimezone=o,this.config.precision=F}static[O]="PgTimeBuilder";build(T){return new Tf(T,this.config)}}class Tf 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 f2(T,o={}){let{name:F,config:y}=fT(T,o);return new S2(F,y.withTimezone??!1,y.precision)}class $2 extends EF{static[O]="PgTimestampBuilder";constructor(T,o,F){super(T,"date","PgTimestamp");this.config.withTimezone=o,this.config.precision=F}build(T){return new of(T,this.config)}}class of 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 EF{static[O]="PgTimestampStringBuilder";constructor(T,o,F){super(T,"string","PgTimestampString");this.config.withTimezone=o,this.config.precision=F}build(T){return new Ff(T,this.config)}}class Ff 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 io(T,o={}){let{name:F,config:y}=fT(T,o);if(y?.mode==="string")return new J2(F,y.withTimezone??!1,y.precision);return new $2(F,y?.withTimezone??!1,y?.precision)}class _2 extends t{static[O]="PgUUIDBuilder";constructor(T){super(T,"string","PgUUID")}defaultRandom(){return this.default(X`gen_random_uuid()`)}build(T){return new yf(T,this.config)}}class yf extends I{static[O]="PgUUID";getSQLType(){return"uuid"}}function Lo(T){return new _2(T??"")}class R2 extends t{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 $o(T,o={}){let{name:F,config:y}=fT(T,o);return new R2(F,y)}class O2 extends t{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:F,config:y}=fT(T,o);return new O2(F,y)}class Y2 extends t{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:F,config:y}=fT(T,o);return new Y2(F,y)}class G2 extends t{static[O]="PgSparseVectorBuilder";constructor(T,o){super(T,"string","PgSparseVector");this.config.dimensions=o.dimensions}build(T){return new E2(T,this.config)}}class E2 extends I{static[O]="PgSparseVector";dimensions=this.config.dimensions;getSQLType(){return`sparsevec(${this.dimensions})`}}function w2(T,o){let{name:F,config:y}=fT(T,o);return new G2(F,y)}class U2 extends t{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:F,config:y}=fT(T,o);return new U2(F,y)}function Q2(){return{bigint:bO,bigserial:mO,boolean:NA,char:uO,cidr:dO,customType:sO,date:TM,doublePrecision:yM,inet:fM,integer:lS,interval:WM,json:MM,jsonb:YM,line:wM,macaddr:zM,macaddr8:DM,numeric:NM,point:tM,geometry:gM,real:cM,serial:rM,smallint:aM,smallserial:o2,text:A2,time:f2,timestamp:io,uuid:Lo,varchar:$o,bit:X2,halfvec:H2,sparsevec:w2,vector:z2}}var tJ=Symbol.for("drizzle:PgInlineForeignKeys"),V2=Symbol.for("drizzle:EnableRLS");class eT extends b{static[O]="PgTable";static Symbol=Object.assign({},b.Symbol,{InlineForeignKeys:tJ,EnableRLS:V2});[tJ]=[];[V2]=!1;[b.Symbol.ExtraConfigBuilder]=void 0;[b.Symbol.ExtraConfigColumns]={}}function wZ(T,o,F,y,A=T){let S=new eT(T,y,A),f=typeof o==="function"?o(Q2()):o,$=Object.fromEntries(Object.entries(f).map(([R,M])=>{let Y=M;Y.setName(R);let H=Y.build(S);return S[tJ].push(...Y.buildForeignKeys(H,S)),[R,H]})),_=Object.fromEntries(Object.entries(f).map(([R,M])=>{let Y=M;Y.setName(R);let H=Y.buildExtraConfigColumn(S);return[R,H]})),J=Object.assign(S,$);if(J[b.Symbol.Columns]=$,J[b.Symbol.ExtraConfigColumns]=_,F)J[eT.Symbol.ExtraConfigBuilder]=F;return Object.assign(J,{enableRLS:()=>{return J[eT.Symbol.EnableRLS]=!0,J}})}var xF=(T,o,F)=>{return wZ(T,o,F,void 0)};function D2(...T){if(T[0].columns)return new pA(T[0].columns,T[0].name);return new pA(T)}class pA{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,F){this.table=T,this.columns=o,this.name=F}static[O]="PgPrimaryKey";columns;name;getName(){return this.name??`${this.table[eT.Symbol.Name]}_${this.columns.map((T)=>T.name).join("_")}_pk`}}class qJ{constructor(T,o,F){this.sourceTable=T,this.referencedTable=o,this.relationName=F,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 bF extends qJ{constructor(T,o,F,y){super(T,o,F?.relationName);this.config=F,this.isNullable=y}static[O]="One";withFieldName(T){let o=new bF(this.sourceTable,this.referencedTable,this.config,this.isNullable);return o.fieldName=T,o}}class xA extends qJ{constructor(T,o,F){super(T,o,F?.relationName);this.config=F}static[O]="Many";withFieldName(T){let o=new xA(this.sourceTable,this.referencedTable,this.config);return o.fieldName=T,o}}function I2(){return{and:kA,between:GO,eq:cS,exists:ZO,gt:JO,gte:_O,ilike:KO,inArray:OO,isNull:XO,isNotNull:YO,like:wO,lt:RO,lte:WO,ne:SO,not:$O,notBetween:EO,notExists:HO,notLike:UO,notIlike:zO,notInArray:MO,or:fO,sql:X}}function k2(){return{sql:X,asc:QO,desc:VO}}function B2(T,o){if(Object.keys(T).length===1&&"default"in T&&!E(T.default,b))T=T.default;let F={},y={},A={};for(let[S,f]of Object.entries(T))if(E(f,b)){let $=iF(f),_=y[$];F[$]=S,A[S]={tsName:S,dbName:f[b.Symbol.Name],schema:f[b.Symbol.Schema],columns:f[b.Symbol.Columns],relations:_?.relations??{},primaryKey:_?.primaryKey??[]};for(let R of Object.values(f[b.Symbol.Columns]))if(R.primary)A[S].primaryKey.push(R);let J=f[b.Symbol.ExtraConfigBuilder]?.(f[b.Symbol.ExtraConfigColumns]);if(J){for(let R of Object.values(J))if(E(R,pA))A[S].primaryKey.push(...R.columns)}}else if(E(f,L2)){let $=iF(f.table),_=F[$],J=f.config(o(f.table)),R;for(let[M,Y]of Object.entries(J))if(_){let H=A[_];if(H.relations[M]=Y,R)H.primaryKey.push(...R)}else{if(!($ in y))y[$]={relations:{},primaryKey:R};y[$].relations[M]=Y}}return{tables:A,tableNamesMap:F}}function UZ(T){return function o(F,y){return new bF(T,F,y,y?.fields.reduce((A,S)=>A&&S.notNull,!0)??!1)}}function KZ(T){return function o(F,y){return new xA(T,F,y)}}function N2(T,o,F){if(E(F,bF)&&F.config)return{fields:F.config.fields,references:F.config.references};let y=o[iF(F.referencedTable)];if(!y)throw new Error(`Table "${F.referencedTable[b.Symbol.Name]}" not found in schema`);let A=T[y];if(!A)throw new Error(`Table "${y}" not found in schema`);let S=F.sourceTable,f=o[iF(S)];if(!f)throw new Error(`Table "${S[b.Symbol.Name]}" not found in schema`);let $=[];for(let _ of Object.values(A.relations))if(F.relationName&&F!==_&&_.relationName===F.relationName||!F.relationName&&_.referencedTable===F.sourceTable)$.push(_);if($.length>1)throw F.relationName?new Error(`There are multiple relations with name "${F.relationName}" in table "${y}"`):new Error(`There are multiple relations between "${y}" and "${F.sourceTable[b.Symbol.Name]}". Please specify relation name`);if($[0]&&E($[0],bF)&&$[0].config)return{fields:$[0].config.references,references:$[0].config.fields};throw new Error(`There is not enough information to infer relation "${f}.${F.fieldName}"`)}function p2(T){return{one:UZ(T),many:KZ(T)}}function Af(T,o,F,y,A=(S)=>S){let S={};for(let[f,$]of y.entries())if($.isJson){let _=o.relations[$.tsKey],J=F[f],R=typeof J==="string"?JSON.parse(J):J;S[$.tsKey]=E(_,bF)?R&&Af(T,T[$.relationTableTsKey],R,$.selection,A):R.map((M)=>Af(T,T[$.relationTableTsKey],M,$.selection,A))}else{let _=A(F[f]),J=$.field,R;if(E(J,ET))R=J;else if(E(J,j))R=J.decoder;else R=J.sql.decoder;S[$.tsKey]=_===null?null:R.mapFromDriverValue(_)}return S}import cZ from"os";import iZ from"fs";var Sf=new Map,vJ=new Map,mJ=Symbol("OriginError"),ky={};class qo extends Promise{constructor(T,o,F,y,A={}){let S,f;super(($,_)=>{S=$,f=_});this.tagged=Array.isArray(T.raw),this.strings=T,this.args=o,this.handler=F,this.canceller=y,this.options=A,this.state=null,this.statement=null,this.resolve=($)=>(this.active=!1,S($)),this.reject=($)=>(this.active=!1,f($)),this.active=!1,this.cancelled=null,this.executed=!1,this.signature="",this[mJ]=this.handler.debug?new Error:this.tagged&&zZ(this.strings)}get origin(){return(this.handler.debug?this[mJ].stack:this.tagged&&vJ.has(this.strings)?vJ.get(this.strings):vJ.set(this.strings,this[mJ].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 F;return{[Symbol.asyncIterator]:()=>({next:()=>{if(this.executed&&!this.active)return{done:!0};F&&F();let y=new Promise((A,S)=>{this.cursorFn=(f)=>{return A({value:f,done:!1}),new Promise(($)=>F=$)},this.resolve=()=>(this.active=!1,A({done:!0})),this.reject=(f)=>(this.active=!1,S(f))});return this.execute(),y},return(){return F&&F(ky),{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(Sf.has(T))return Sf.get(T);let o=Error.stackTraceLimit;return Error.stackTraceLimit=4,Sf.set(T,new Error),Error.stackTraceLimit=o,Sf.get(T)}class By extends Error{constructor(T){super(T.message);this.name=this.constructor.name,Object.assign(this,T)}}var qT={connection:x2,postgres:b2,generic:j2,notSupported:t2};function x2(T,o,F){let{host:y,port:A}=F||o,S=Object.assign(new Error("write "+T+" "+(o.path||y+":"+A)),{code:T,errno:T,address:o.path||y},o.path?{}:{port:A});return Error.captureStackTrace(S,x2),S}function b2(T){let o=new By(T);return Error.captureStackTrace(o,b2),o}function j2(T,o){let F=Object.assign(new Error(T+": "+o),{code:T});return Error.captureStackTrace(F,j2),F}function t2(T){let o=Object.assign(new Error(T+" (B) is not supported"),{code:"MESSAGE_NOT_SUPPORTED",name:T});return Error.captureStackTrace(o,t2),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 Jf{then(){PJ()}catch(){PJ()}finally(){PJ()}}class qA extends Jf{constructor(T){super();this.value=Wf(T)}}class FF extends Jf{constructor(T,o,F){super();this.value=T,this.type=o,this.array=F}}class _f extends Jf{constructor(T,o){super();this.first=T,this.rest=o}build(T,o,F,y){let A=VZ.map(([S,f])=>({fn:f,i:T.search(S)})).sort((S,f)=>S.i-f.i).pop();return A.i===-1?cJ(this.first,y):A.fn(this.first,this.rest,o,F,y)}}function Rf(T,o,F,y){let A=T instanceof FF?T.value:T;if(A===void 0){if(T instanceof FF?T.value=y.transform.undefined:A=T=y.transform.undefined,A===void 0)throw qT.generic("UNDEFINED_VALUE","Undefined values are not allowed")}return"$"+F.push(T instanceof FF?(o.push(T.value),T.array?T.array[T.type||$f(T.value)]||T.type||P2(T.value):T.type):(o.push(T),$f(T)))}var v2=g2(QZ);function nJ(T,o,F,y,A,S){for(let f=1;f<T.strings.length;f++)o+=uJ(o,F,y,A,S)+T.strings[f],F=T.args[f];return o}function uJ(T,o,F,y,A){return o instanceof _f?o.build(T,F,y,A):o instanceof qo?gJ(o,F,y,A):o instanceof qA?o.value:o&&o[0]instanceof qo?o.reduce((S,f)=>S+" "+gJ(f,F,y,A),""):Rf(o,F,y,A)}function gJ(T,o,F,y){return T.fragment=!0,nJ(T,T.strings[0],T.args[0],o,F,y)}function m2(T,o,F,y,A){return T.map((S)=>"("+y.map((f)=>uJ("values",S[f],o,F,A)).join(",")+")").join(",")}function q2(T,o,F,y,A){let S=Array.isArray(T[0]),f=o.length?o.flat():Object.keys(S?T[0]:T);return m2(S?T:[T],F,y,f,A)}function ff(T,o,F,y,A){if(typeof T==="string"&&(T=[T].concat(o)),Array.isArray(T))return cJ(T,A);let S;return(o.length?o.flat():Object.keys(T)).map(($)=>{return S=T[$],(S instanceof qo?gJ(S,F,y,A):S instanceof qA?S.value:Rf(S,F,y,A))+" as "+Wf(A.transform.column.to?A.transform.column.to($):$)}).join(",")}var VZ=Object.entries({values:q2,in:(...T)=>{let o=q2(...T);return o==="()"?"(null)":o},select:ff,as:ff,returning:ff,"\\(":ff,update(T,o,F,y,A){return(o.length?o.flat():Object.keys(T)).map((S)=>Wf(A.transform.column.to?A.transform.column.to(S):S)+"="+uJ("values",T[S],F,y,A))},insert(T,o,F,y,A){let S=o.length?o.flat():Object.keys(Array.isArray(T)?T[0]:T);return"("+cJ(S,A)+")values"+m2(Array.isArray(T)?T:[T],F,y,S,A)}}).map(([T,o])=>[new RegExp("((?:^|[\\s(])"+T+"(?:$|[\\s(]))(?![\\s\\S]*\\1)","i"),o]);function PJ(){throw qT.generic("NOT_TAGGED_CALL","Query not called as a tagged template literal")}var{serializers:DZ,parsers:CZ}=v2;function P2(T){if(Array.isArray(T))return P2(T[0]);return typeof T==="string"?1009:0}var h2=function(T){let o=g2(T||{});return{serializers:Object.assign({},DZ,o.serializers),parsers:Object.assign({},CZ,o.parsers)}};function g2(T){return Object.keys(T).reduce((o,F)=>{if(T[F].from&&[].concat(T[F].from).forEach((y)=>o.parsers[y]=T[F].parse),T[F].serialize)o.serializers[T[F].to]=T[F].serialize,T[F].from&&[].concat(T[F].from).forEach((y)=>o.serializers[y]=T[F].serialize);return o},{parsers:{},serializers:{}})}function cJ(T,{transform:{column:o}}){return T.map((F)=>Wf(o.to?o.to(F):F)).join(",")}var Wf=function T(o){return'"'+o.replace(/"/g,'""').replace(/\./g,'"."')+'"'},$f=function T(o){return o instanceof FF?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 n2=function T(o,F,y,A){if(Array.isArray(o)===!1)return o;if(!o.length)return"{}";let S=o[0],f=A===1020?";":",";if(Array.isArray(S)&&!S.type)return"{"+o.map(($)=>T($,F,y,A)).join(f)+"}";return"{"+o.map(($)=>{if($===void 0){if($=y.transform.undefined,$===void 0)throw qT.generic("UNDEFINED_VALUE","Undefined values are not allowed")}return $===null?"null":'"'+kZ(F?F($.type?$.value:$):""+$)+'"'}).join(f)+"}"},hJ={i:0,char:null,str:"",quoted:!1,last:0},u2=function T(o,F,y){return hJ.i=hJ.last=0,c2(hJ,o,F,y)};function c2(T,o,F,y){let A=[],S=y===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==='"')A.push(F?F(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,A.push(c2(T,o,F,y));else if(T.char==="}"){T.quoted=!1,T.last<T.i&&A.push(F?F(o.slice(T.last,T.i)):o.slice(T.last,T.i)),T.last=T.i+1;break}else if(T.char===S&&T.p!=="}"&&T.p!=='"')A.push(F?F(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&&A.push(F?F(o.slice(T.last,T.i+1)):o.slice(T.last,T.i+1)),A}var dF=(T)=>{let o=T[0];for(let F=1;F<T.length;F++)o+=T[F]==="_"?T[++F].toUpperCase():T[F];return o},rF=(T)=>{let o=T[0].toUpperCase();for(let F=1;F<T.length;F++)o+=T[F]==="_"?T[++F].toUpperCase():T[F];return o},lF=(T)=>T.replace(/_/g,"-"),bA=(T)=>T.replace(/([A-Z])/g,"_$1").toLowerCase(),jA=(T)=>(T.slice(0,1)+T.slice(1).replace(/([A-Z])/g,"_$1")).toLowerCase(),tA=(T)=>T.replace(/-/g,"_");function iJ(T){return function o(F,y){return typeof F==="object"&&F!==null&&(y.type===114||y.type===3802)?Array.isArray(F)?F.map((A)=>o(A,y)):Object.entries(F).reduce((A,[S,f])=>Object.assign(A,{[T(S)]:o(f,y)}),{}):F}}dF.column={from:dF};dF.value={from:iJ(dF)};bA.column={to:bA};var dJ={...dF};dJ.column.to=bA;rF.column={from:rF};rF.value={from:iJ(rF)};jA.column={to:jA};var rJ={...rF};rJ.column.to=jA;lF.column={from:lF};lF.value={from:iJ(lF)};tA.column={to:tA};var lJ={...lF};lJ.column.to=tA;import i2 from"net";import xZ from"tls";import vA from"crypto";import sJ from"stream";import{performance as d2}from"perf_hooks";class sF 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(),F=0;return{get length(){return o.length-F},remove:(y)=>{let A=o.indexOf(y);return A===-1?null:(o.splice(A,1),y)},push:(y)=>(o.push(y),y),shift:()=>{let y=o[F++];if(F===o.length)F=0,o=[];else o[F-1]=void 0;return y}}}var Jo=Buffer.allocUnsafe(256),NZ="BCcDdEFfHPpQSX".split("").reduce((T,o)=>{let F=o.charCodeAt(0);return T[o]=()=>{return Jo[0]=F,ZT.i=5,ZT},T},{}),ZT=Object.assign(pZ,NZ,{N:String.fromCharCode(0),i:0,inc(T){return ZT.i+=T,ZT},str(T){let o=Buffer.byteLength(T);return Of(o),ZT.i+=Jo.write(T,ZT.i,o,"utf8"),ZT},i16(T){return Of(2),Jo.writeUInt16BE(T,ZT.i),ZT.i+=2,ZT},i32(T,o){if(o||o===0)return Jo.writeUInt32BE(T,o),ZT;return Of(4),Jo.writeUInt32BE(T,ZT.i),ZT.i+=4,ZT},z(T){return Of(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 Of(T){if(Jo.length-ZT.i<T){let o=Jo,F=o.length;Jo=Buffer.allocUnsafe(F+(F>>1)+T),o.copy(Jo)}}function pZ(){return ZT.i=0,ZT}var T_=s2,bZ=1,jF=u().S().end(),r2=u().H().end(),jZ=u().i32(8).i32(80877103).end(8),tZ=Buffer.concat([u().E().str(u.N).i32(0).end(),jF]),qZ=u().D().str("S").str(u.N).end(),Ny=()=>{},vZ=new Set(["FetchPreparedStatement","RevalidateCachedQuery","transformAssignedExpr"]),mZ={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:F=Ny,onend:y=Ny,onclose:A=Ny}={}){let{ssl:S,max:f,user:$,host:_,port:J,database:R,parsers:M,transform:Y,onnotice:H,onnotify:Q,onparameter:w,max_pipeline:B,keep_alive:p,backoff:q,target_session_attrs:h}=T,K=Io(),V=bZ++,L={pid:null,secret:null},C=eJ(Vf,T.idle_timeout),m=eJ(Vf,T.max_lifetime),s=eJ(E4,T.connect_timeout),z=null,a,P=new sF,e=Buffer.alloc(0),HT=T.fetch_types,vT={},Xo={},yF=Math.random().toString(36).slice(2),D=1,g=0,RT=0,IT=0,mT=0,FT=0,UT=0,jT=0,kT=null,DT=null,To=!1,KT=null,vo=null,oo=null,wF=null,PT=null,CT=null,mo=null,ro=null,N=null,jy=null,Fo={queue:o.closed,idleTimer:C,connect(W){oo=W||!0,D_()},terminate:qy,execute:ty,cancel:Y4,end:Vf,count:0,id:V};return o.closed&&o.closed.push(Fo),Fo;async function X4(){let W;try{W=T.socket?await Promise.resolve(T.socket(T)):new i2.Socket}catch(Z){oy(Z);return}return W.on("error",oy),W.on("close",C_),W.on("drain",Q_),W}async function Y4({pid:W,secret:Z},c,WT){try{a=u().i32(16).i32(80877102).i32(W).i32(Z).end(16),await V_(),z.once("error",WT),z.once("close",c)}catch(NT){WT(NT)}}function ty(W){if(To)return cA(W,qT.connection("CONNECTION_DESTROYED",T));if(W.cancelled)return;try{return W.state=L,N?K.push(W):(N=W,N.active=!0),G4(W),sT(Z4(W))&&!W.describeFirst&&!W.cursorFn&&K.length<B&&(!W.options.onexecute||W.options.onexecute(Fo))}catch(Z){return K.length===0&&sT(jF),lo(Z),!0}}function Z4(W){if(W.parameters.length>=65534)throw qT.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([U_(W),r2]):W.prepare?W.prepared?uA(W):Buffer.concat([U_(W),uA(W)]):H4(W)}function U_(W){return Buffer.concat([I_(W.statement.string,W.parameters,W.statement.types,W.statement.name),yX("S",W.statement.name)])}function uA(W){return Buffer.concat([FX(W.parameters,W.statement.types,W.statement.name,W.cursorName),W.cursorFn?k_("",W.cursorRows):tZ])}function H4(W){return Buffer.concat([I_(W.statement.string,W.parameters,W.statement.types),qZ,uA(W)])}function G4(W){let Z=[],c=[],WT=nJ(W,W.strings[0],W.args[0],Z,c,T);!W.tagged&&W.args.forEach((NT)=>Rf(NT,Z,c,T)),W.prepare=T.prepare&&("prepare"in W.options?W.options.prepare:!0),W.string=WT,W.signature=W.prepare&&c+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:c,name:W.prepare?yF+D++:""},typeof T.debug==="function"&&T.debug(V,WT,Z,c)}function sT(W,Z){if(CT=CT?Buffer.concat([CT,W]):Buffer.from(W),Z||CT.length>=1024)return K_(Z);return DT===null&&(DT=setImmediate(K_)),!0}function K_(W){let Z=z.write(CT,W);return DT!==null&&clearImmediate(DT),CT=DT=null,Z}function E4(){lo(qT.connection("CONNECT_TIMEOUT",T,z)),z.destroy()}async function z_(){if(sT(jZ),!await new Promise((Z)=>z.once("data",(c)=>Z(c[0]===83)))&&S==="prefer")return Ty();z.removeAllListeners(),z=xZ.connect({socket:z,servername:i2.isIP(z.host)?void 0:z.host,...S==="require"||S==="allow"||S==="prefer"?{rejectUnauthorized:!1}:S==="verify-full"?{}:typeof S==="object"?S:{}}),z.on("secureConnect",Ty),z.on("error",oy),z.on("close",C_),z.on("drain",Q_)}function Q_(){!N&&F(Fo)}function Qf(W){if(KT){if(KT.push(W),RT-=W.length,RT>=0)return}e=KT?Buffer.concat(KT,FT-RT):e.length===0?W:Buffer.concat([e,W],e.length+W.length);while(e.length>4){if(FT=e.readUInt32BE(1),FT>=e.length){RT=FT-e.length,KT=[e];break}try{w4(e.subarray(0,FT+1))}catch(Z){N&&(N.cursorFn||N.describeFirst)&&sT(jF),lo(Z)}e=e.subarray(FT+1),RT=0,KT=null}}async function V_(){if(To=!1,vT={},z||(z=await X4()),!z)return;if(s.start(),T.socket)return S?z_():Ty();if(z.on("connect",S?z_:Ty),T.path)return z.connect(T.path);z.ssl=S,z.connect(J[IT],_[IT]),z.host=_[IT],z.port=J[IT],IT=(IT+1)%J.length}function D_(){setTimeout(V_,g?g+UT-d2.now():0)}function Ty(){try{Xo={},HT=T.fetch_types,yF=Math.random().toString(36).slice(2),D=1,m.start(),z.on("data",Qf),p&&z.setKeepAlive&&z.setKeepAlive(!0,1000*p);let W=SX();sT(W)}catch(W){oy(W)}}function oy(W){if(Fo.queue===o.connecting&&T.host[mT+1])return;lo(W);while(K.length)cA(K.shift(),W)}function lo(W){PT&&(PT.destroy(W),PT=null),N&&cA(N,W),oo&&(cA(oo,W),oo=null)}function cA(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
|
|
59
|
+
${Y.trace}`:`No previous disposal trace for ${$} was found.`),F}let J=T.moleculeGraph.getRelationEntries({downstreamMoleculeKey:f.stringKey}).filter(([,{source:Y}])=>Y!==y).map(([Y])=>rT(Y));if(A)S.moleculeGraph.delete(y);S.moleculeGraph.set({upstreamMoleculeKey:_.stringKey,downstreamMoleculeKey:f.stringKey},{source:_.stringKey});let R={type:"molecule_transfer",key:f.key,from:J,to:[_.key]};if(OT(S)&&S.transactionMeta.phase==="building")S.transactionMeta.update.updates.push(R);return F}function TJ(T,o,F){switch(o){case"newValue":{_W(T,F);break}case"oldValue":{iF(F,T.token);break}}}function oJ(T,o,F){switch(o){case"newValue":{iF(F,T.token);break}case"oldValue":{if(_W(T,F),T.subType==="atom")F.valueMap.set(T.token.key,T.value);break}}}function _W(T,o){let{family:F}=T.token;if(F){let A=o.families.get(F.key);if(A)i(o,A,rT(F.subKey))}}function RW(T,o,F){switch(o){case"newValue":nF(F,T.provenance,T.key);break;case"oldValue":uF(F,T.key);break}}function WW(T,o,F){switch(o){case"newValue":uF(F,T.key);break;case"oldValue":{let A=T.provenance.map(rT);nF(F,A,T.key);for(let[y,S]of T.values){let f=F.families.get(y);if(f){i(F,f,T.key);let $=`${y}(${AT(T.key)})`;F.valueMap.set($,S)}}}break}}function MW(T,o,F){switch(o){case"newValue":{let A=T.to.length===1?T.to[0]:T.to;QA(F,A,T.key,"exclusive")}break;case"oldValue":{let A=T.from.length===1?T.from[0]:T.from;QA(F,A,T.key,"exclusive")}break}}function pS(T,o,F){let A=T==="newValue"?o.updates:[...o.updates].reverse();for(let y of A)switch(y.type){case"atom_update":case"selector_update":NS(T,y,F);break;case"state_creation":TJ(y,T,F);break;case"state_disposal":oJ(y,T,F);break;case"molecule_creation":RW(y,T,F);break;case"molecule_disposal":WW(y,T,F);break;case"molecule_transfer":MW(y,T,F);break;case"transaction_update":pS(T,y,F);break}}function FJ(T,o){return T.transactionMeta.actionContinuities.getRelatedKey(o)}function WZ(T,o){return T.transactionMeta.epoch.get(o)}function OW(T,o){if(!aT(T))return;let A=FJ(T,o);if(A===void 0)return;return WZ(T,A)}function XW(T,o,F){if(aT(T)&&o)T.transactionMeta.epoch.set(o,F)}function YW(T,o,F){if(!aT(T))return;let y=FJ(T,o);if(y!==void 0)T.transactionMeta.epoch.set(y,F)}var ZW=(T,o)=>{let F=j(o),{parent:A}=F;if(A===null||!OT(F)||F.transactionMeta?.phase!=="building"){o.logger.warn("\uD83D\uDC1E","transaction","???","applyTransaction called outside of a transaction. This is probably a bug in AtomIO.");return}F.transactionMeta.phase="applying",F.transactionMeta.update.output=T,A.child=null,A.on.transactionApplying.next(F.transactionMeta);let{updates:y}=F.transactionMeta.update;if(o.logger.info("\uD83D\uDEC4","transaction",F.transactionMeta.update.key,`Applying transaction with ${y.length} updates:`,y),pS("newValue",F.transactionMeta.update,A),aT(A))YW(A,F.transactionMeta.update.key,F.transactionMeta.update.epoch),JT(o,{key:F.transactionMeta.update.key,type:"transaction"})?.subject.next(F.transactionMeta.update),o.logger.info("\uD83D\uDEEC","transaction",F.transactionMeta.update.key,"Finished applying transaction.");else if(OT(A))A.transactionMeta.update.updates.push(F.transactionMeta.update);A.on.transactionApplying.next(null)};function HW(T,o,F){if(!aT(T))return;let{epoch:y,actionContinuities:S}=T.transactionMeta;if(S.set(o,F),!y.has(o))y.set(o,-1)}function GW(T){return{store:T}}function MT(T,...o){let F,A,y;if(o.length===1)F=o[0];else A=o[0],y=o[1],F=i(T,A,y);if("counterfeit"in F&&"family"in F){A=T.families.get(F.family.key);let S=F.family.subKey,f=T.disposalTraces.buffer.find(($)=>$?.key===S);switch(T.logger.error("\u274C",F.type,F.key,`could not be retrieved because it was not found in the store "${T.config.name}".`,f?`This state was previously disposed:
|
|
60
|
+
${f.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(F.family.key);let $=JT(T,A).default(S);return T.defaults.set(A.key,$),$}}}return kF(T,JT(T,F))}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 F=this.relations.get(T),A=this.relations.get(o);if(F)F.add(o);else F=new Set([o]),this.relations.set(T,F);if(A)A.add(T);else A=new Set([T]),this.relations.set(o,A)}deleteRelation(T,o){let F=this.relations.get(T);if(F){if(F.delete(o),F.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 F of o){let A=new Set().add(T);this.relations.set(F,A)}}replaceRelationsSafely(T,o){let F=this.relations.get(T),A=this.isAType?.(T)?T:void 0,y=A===void 0?T:void 0;if(F)for(let S of F){A??=S,y??=S;let f=this.relations.get(S);if(f){if(f.size===1)this.relations.delete(S);else f.delete(T);this.contents.delete(this.makeContentKey(A,y))}}this.relations.set(T,new Set(o));for(let S of o){let f=this.relations.get(S);if(f)f.add(T);else f=new Set().add(T),this.relations.set(S,f)}}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(([F,A])=>[F,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 F=o.externalStore;if(this.has=(A,y)=>F.has(A,y),this.addRelation=(A,y)=>{F.addRelation(A,y)},this.deleteRelation=(A,y)=>{F.deleteRelation(A,y)},this.replaceRelationsSafely=(A,y)=>{F.replaceRelationsSafely(A,y)},this.replaceRelationsUnsafely=(A,y)=>{F.replaceRelationsUnsafely(A,y)},this.getRelatedKeys=(A)=>F.getRelatedKeys(A),F.getContent)this.getContentInternal=(A)=>{return F.getContent(A)},this.setContent=(A,y)=>{F.setContent(A,y)},this.deleteContent=(A)=>{F.deleteContent(A)};for(let[A,y]of T.relations??[]){let S=this.isAType?.(A)?A:void 0,f=S===void 0?A:void 0;for(let $ of y)S??=$,f??=$,this.addRelation(S,f)}for(let[A,y]of T.contents??[])this.setContent(A,y)}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,F,A;switch(T.length){case 1:{let y=T[0];o=y[this.a],F=y[this.b],A=void 0;break}case 2:{let y=T[0];if(typeof y==="string")[o,F]=T;else o=y[this.a],F=y[this.b],A=T[1];break}default:{o=T[0],F=T[1],A=T[2];break}}switch(this.cardinality){case"1:1":{let y=this.getRelatedKey(o);if(y&&y!==F)this.delete(o,y)}case"1:n":{let y=this.getRelatedKey(F);if(y&&y!==o)this.delete(y,F)}break;case"n:n":}if(A){let y=this.makeContentKey(o,F);this.setContent(y,A)}return this.addRelation(o,F),this}delete(T,o){o=typeof o==="string"?o:T[this.b];let F=typeof T==="string"?T:T[this.a];if(F===void 0&&typeof o==="string"){let A=this.getRelatedKeys(o);if(A)for(let y of A)this.delete(y,o)}if(typeof F==="string"&&o===void 0){let A=this.getRelatedKeys(F);if(A)for(let y of A)this.delete(F,y)}if(typeof F==="string"&&typeof o==="string"){this.deleteRelation(F,o);let A=this.makeContentKey(F,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 F;for(let A of o){F=A;break}return F}}replaceRelations(T,o,F){let A=!Array.isArray(o),y=A?Object.keys(o):o;if(F?.reckless)this.replaceRelationsUnsafely(T,y);else this.replaceRelationsSafely(T,y);if(A)for(let S of y){let f=this.makeContentKey(T,S),$=o[S];this.setContent(f,$)}return this}getContent(T,o){let F=this.makeContentKey(T,o);return this.getContentInternal(F)}getRelationEntries(T){let o=T[this.a],F=T[this.b];if(o!==void 0&&F===void 0){let A=this.getRelatedKeys(o);if(A)return[...A].map((y)=>{return[y,this.getContent(o,y)]})}if(o===void 0&&F!==void 0){let A=this.getRelatedKeys(F);if(A)return[...A].map((y)=>{return[y,this.getContent(y,F)]})}return[]}has(T,o){if(o)return this.getRelatedKeys(T)?.has(o)??!1;return this.relations.has(T)}}class bo 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 wW=(T,o,F,A)=>{let y=j(T),S={parent:y,child:null,on:y.on,loggers:y.loggers,logger:y.logger,config:y.config,atoms:new bo(y.atoms),atomsThatAreDefault:new Set(y.atomsThatAreDefault),families:new bo(y.families),joins:new bo(y.joins),operation:{open:!1},readonlySelectors:new bo(y.readonlySelectors),timelines:new bo(y.timelines),timelineTopics:new uT(y.timelineTopics.toJSON()),trackers:new Map,transactions:new bo(y.transactions),selectorAtoms:new uT(y.selectorAtoms.toJSON()),selectorGraph:new uT(y.selectorGraph.toJSON(),{makeContentKey:(...J)=>J.sort().join(":")}),selectors:new bo(y.selectors),valueMap:new bo(y.valueMap),defaults:y.defaults,disposalTraces:T.disposalTraces.copy(),molecules:new bo(y.molecules),moleculeGraph:new uT(y.moleculeGraph.toJSON(),{makeContentKey:y.moleculeGraph.makeContentKey}),moleculeData:new uT(y.moleculeData.toJSON(),{makeContentKey:y.moleculeData.makeContentKey}),moleculeJoins:new uT(y.moleculeJoins.toJSON(),{makeContentKey:y.moleculeJoins.makeContentKey}),miscResources:new bo(y.miscResources)},f=OW(T,o),$={phase:"building",update:{type:"transaction_update",key:o,id:A,epoch:f===void 0?Number.NaN:f+1,updates:[],params:F,output:void 0},toolkit:{get:(...J)=>MT(_,...J),set:(...J)=>{jT(_,...J)},run:(J,R=QS())=>VA(_,J,R),find:(...J)=>i(T,...J),json:(J)=>nT(_,J),dispose:(...J)=>{iF(_,...J)},env:()=>GW(_)}},_=Object.assign(S,{transactionMeta:$});return y.child=_,T.logger.info("\uD83D\uDEEB","transaction",o,"Building transaction with params:",F),_};function AJ(T,o){let F={key:o.key,type:"transaction",run:(S,f)=>{let $=wW(T,o.key,S,f);try{let _=j(T),{toolkit:J}=$.transactionMeta,R=o.do(J,...S);return ZW(R,_),R}catch(_){throw lR(A),T.logger.warn("\uD83D\uDCA5","transaction",o.key,"caught:",_),_}},install:(S)=>AJ(S,o),subject:new oT},A=j(T);A.transactions.set(F.key,F);let y=Eo(F);return T.on.transactionCreation.next(y),y}function zy(T){return AJ(ST.STORE,T)}class EW{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 DS(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 d$(null),operationClose:new oT,moleculeCreation:new oT,moleculeDisposal:new oT};operation={open:!1};config={name:"IMPLICIT_STORE",lifespan:"ephemeral"};loggers=[new s$("warn",(T,o,F)=>!BF(F))];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 F=new Set;for(let[,A]of o.atoms){if(F.has(A.key))continue;if(A.install(this),A.type==="mutable_atom"){let y=nT(o,A),S=YF(A);F.add(y.key),F.add(S.key)}}for(let[,A]of o.readonlySelectors)A.install(this);for(let[,A]of o.selectors){if(F.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 ST={get STORE(){return globalThis.ATOM_IO_IMPLICIT_STORE??=new EW({name:"IMPLICIT_STORE",lifespan:"ephemeral"}),globalThis.ATOM_IO_IMPLICIT_STORE}};function JT(T,o){let F,A=T;while(A!==null){switch(o.type){case"atom":case"mutable_atom":F=A.atoms.get(o.key);break;case"selector":F=A.selectors.get(o.key);break;case"readonly_selector":F=A.readonlySelectors.get(o.key);break;case"atom_family":case"mutable_atom_family":case"selector_family":case"readonly_selector_family":F=A.families.get(o.key);break;case"timeline":F=A.timelines.get(o.key);break;case"transaction":F=A.transactions.get(o.key);break}if(F)return F;A=A.child}throw new cF(o,T)}function KW(T,o,F){let A=T.families.get(o.key);if(A===void 0)throw new cF(o,T);let y=A(F),S=j(T);if(y.family){if(aT(S))switch(y.type){case"atom":case"mutable_atom":T.on.atomCreation.next(y);break;case"selector":case"readonly_selector":T.on.selectorCreation.next(y);break}else if(OT(S)&&S.on.transactionApplying.state===null)S.transactionMeta.update.updates.push({type:"state_creation",token:y})}return y}function UW(T,o,F){let A=AT(F),y=`${o.key}(${A})`,S=j(T),f;switch(o.type){case"atom_family":case"mutable_atom_family":f=S.atoms.get(y);break;case"selector_family":f=S.selectors.get(y);break;case"readonly_selector_family":f=S.readonlySelectors.get(y);break}if(f)return Eo(f);return f}function i(T,o,F){let A=UW(T,o,F);if(A)return A;let y=AT(F),S=T.molecules.get(y);if(!S&&T.config.lifespan==="immortal"){let f=hR(o,F);return T.logger.error("\u274C",f.type,f.key,`was not found in store "${T.config.name}"; returned a counterfeit token.`),f}if(A=KW(T,o,F),S)j(T).moleculeData.set(y,o.key);return A}function iF(T,...o){let F;if(o.length===1)F=o[0];else{let A=o[0],y=o[1];F=i(T,A,y)}try{JT(T,F)}catch(A){T.logger.error("\u274C",F.type,F.key,`could not be disposed because it was not found in the store "${T.config.name}".`);return}switch(F.type){case"atom":case"mutable_atom":yJ(T,F);break;case"selector":case"readonly_selector":zW(T,F);break}}var jS=(T,o)=>j(T).atoms.has(o),MZ=(T,o)=>j(T).selectors.has(o),OZ=(T,o)=>j(T).readonlySelectors.has(o),QW=(T,o)=>jS(T,o)||MZ(T,o)||OZ(T,o);var xS=(T,o)=>{return j(o).selectorGraph.getRelationEntries({downstreamSelectorKey:T}).filter(([A,{source:y}])=>y!==T).map(([A,{source:y}])=>y).filter((A)=>QW(o,A))};var SJ=(T,o,F)=>{let A=[],y=xS(T,F);while(y.length>0){let S=y.shift();if(o.has(S))continue;if(o.add(S),!jS(F,S))y.push(...xS(S,F));else if(!A.includes(S))A.push(S)}return A},VW=(T,o)=>{let F=T.key,A=xS(F,o),y=new Set;return A.flatMap((S)=>jS(o,S)?S:SJ(S,y,o))};var DW=(T,o,F,A)=>{let y=j(A);if(o.type==="atom"||o.type==="mutable_atom")y.selectorAtoms.set({selectorKey:T,atomKey:o.key}),A.logger.info("\uD83D\uDD0D","selector",T,`discovers root atom "${o.key}"`);else{let S=SJ(o.key,F,A);A.logger.info("\uD83D\uDD0D","selector",T,`discovers root atoms: [ ${S.map((f)=>`"${f}"`).join(", ")} ]`);for(let f of S)y.selectorAtoms=y.selectorAtoms.set({selectorKey:T,atomKey:f})}F.add(o.key)};var bS=(T,o,F)=>({get:(...A)=>{let y=j(F),S;if(A.length===2){let[_,J]=A;S=i(F,_,J)}else[S]=A;let f=JT(F,S),$=kF(F,f);return F.logger.info("\uD83D\uDD0C","selector",T,`registers dependency ( "${S.key}" =`,$,")"),y.selectorGraph.set({upstreamSelectorKey:S.key,downstreamSelectorKey:T},{source:S.key}),DW(T,S,o,F),$},set:(...A)=>{let y,S;if(A.length===2)y=A[0],S=A[1];else{let _=A[0],J=A[1];S=A[2],y=i(F,_,J)}let f=j(F),$=JT(f,y);BS(f,$,S)},find:(...A)=>i(F,...A),json:(A)=>nT(F,A)});var Gy=(T,o,F)=>{let A=j(T),y=new oT,S=new Set,{get:f,find:$,json:_}=bS(o.key,S,A),J=()=>{let H=o.get({get:f,find:$,json:_});return xo(j(T),o.key,H,y),S.clear(),H},R={...o,subject:y,install:(H)=>Gy(H,o,F),get:J,type:"readonly_selector",...F&&{family:F}};A.readonlySelectors.set(o.key,R);let O=J();T.logger.info("\u2728",R.type,R.key,"=",O);let Y={key:o.key,type:"readonly_selector"};if(F)Y.family=F;return Y};var Qy=(T,o,F)=>{let A=j(T),y=new oT,S=new Set,f=bS(o.key,S,A),{find:$,get:_,json:J}=f,R={find:$,get:_,json:J},O=(B=o.get,p=j(T))=>{let v=B(R);return xo(p,o.key,v,y),S.clear(),v},H={...o,subject:y,install:(B)=>Qy(B,o,F),get:O,set:(B)=>{let p=j(T),v=O(o.get,p),h=kS(B)(v);if(T.logger.info("\uD83D\uDCDD","selector",o.key,"set (",v,"->",h,")"),xo(p,o.key,h,y),DA(p,o.key),aT(p))y.next({newValue:h,oldValue:v});o.set(f,h)},type:"selector",...F&&{family:F}};A.selectors.set(o.key,H);let Q=O();T.logger.info("\u2728",H.type,H.key,"=",Q);let E={key:o.key,type:"selector"};if(F)E.family=F;return E};function MF(T,o){if("set"in o){let y=Qy(T,o,void 0);return T.on.selectorCreation.next(y),y}let A=Gy(T,o,void 0);return T.on.selectorCreation.next(A),A}function zW(T,o){let F=j(T),{key:A}=o,y=JT(F,o);if(!y.family)T.logger.error("\u274C","selector",A,"Standalone selectors cannot be disposed.");else{if(F.molecules.get(y.family.subKey))F.moleculeData.delete(y.family.subKey,y.family.key);let f;switch(o.type){case"selector":F.selectors.delete(A),f={key:y.family.key,type:"selector_family"},JT(T,f).subject.next({type:"state_disposal",subType:"selector",token:o});break;case"readonly_selector":F.readonlySelectors.delete(A),f={key:y.family.key,type:"readonly_selector_family"},JT(T,f).subject.next({type:"state_disposal",subType:"selector",token:o});break}if(F.valueMap.delete(A),F.selectorAtoms.delete(A),F.selectorGraph.delete(A),T.logger.info("\uD83D\uDD25",o.type,A,"deleted"),OT(F)&&F.transactionMeta.phase==="building")F.transactionMeta.update.updates.push({type:"state_disposal",subType:"selector",token:o});else T.on.selectorDisposal.next(o)}}function wy(T,o,F){let A={key:o.key,type:"selector_family"},y=T.families.get(o.key);if(y)T.logger.error("\u2757","selector_family",o.key,`Overwriting an existing ${TF(y)} "${y.key}" in store "${T.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);let S=new oT,$=Object.assign((_)=>{let J=AT(_),R={key:o.key,subKey:J},O=`${o.key}(${J})`,Y=j(T),H=Qy(Y,{key:O,get:o.get(_),set:o.set(_)},R);return S.next({type:"state_creation",token:H}),H},A,{internalRoles:F,subject:S,install:(_)=>wy(_,o),default:(_)=>{return o.get(_)({get:(...R)=>MT(T,...R),find:(...R)=>i(T,...R),json:(R)=>nT(T,R)})}});return T.families.set(o.key,$),A}function LW(T,o,F){return wy(T,{key:`${o.key}:JSON`,get:(y)=>({get:S})=>{let f=S(o,y);return F.toJson(f)},set:(y)=>({set:S},f)=>{S(o,y,F.fromJson(f))}},["mutable","json"])}var rT=(T)=>JSON.parse(T),AT=(T)=>JSON.stringify(T),$I=[Array.prototype,Boolean.prototype,Number.prototype,Object.prototype,String.prototype];var CW=(T,o)=>{let F=j(T);if(F.operation.open)return F.operation.prev.get(o.key);return F.valueMap.get(o.key)};var JJ=(T,o)=>{let F=j(T);return VW(o,T).map((y)=>{let S=F.atoms.get(y);if(S===void 0)throw new Error(`Atom "${y}", a dependency of selector "${o.key}", not found in store "${T.config.name}".`);return S.subject.subscribe(`${o.type}:${o.key}`,(f)=>{T.logger.info("\uD83D\uDCE2",o.type,o.key,"root",y,"went",f.oldValue,"->",f.newValue);let $=CW(F,o),_=kF(F,o);T.logger.info("\u2728",o.type,o.key,"went",$,"->",_),o.subject.next({newValue:_,oldValue:$})})})};function fo(T,o,F,A){function y(O){if(T.operation.open){let Y=T.on.operationClose.subscribe(`state subscription ${F}`,()=>{Y(),A(O)})}else A(O)}let S=JT(T,o);T.logger.info("\uD83D\uDC40",S.type,S.key,`Adding subscription "${F}"`);let f=S.type==="selector"||S.type==="readonly_selector",$=null,_=y;if(f)$=JJ(T,S),_=(O)=>{if($)$.length=0,$.push(...JJ(T,S));y(O)};let J=S.subject.subscribe(F,_);return()=>{if(T.logger.info("\uD83D\uDE48",S.type,S.key,`Removing subscription "${F}"`),J(),$)for(let O of $)O()}}var fJ=(T,o,F,A)=>{let y=JT(T,o);T.logger.info("\uD83D\uDC40","timeline",o.key,`Adding subscription "${F}"`);let S=y.subject.subscribe(F,A);return()=>{T.logger.info("\uD83D\uDE48","timeline",o.key,`Removing subscription "${F}" from timeline`),S()}};var $J=(T,o,F,A)=>{let y=JT(T,o);T.logger.info("\uD83D\uDC40","transaction",o.key,`Adding subscription "${F}"`);let S=y.subject.subscribe(F,A);return()=>{T.logger.info("\uD83D\uDE48","transaction",o.key,`Removing subscription "${F}"`),S()}};class dF{Update;initializeState(T,o){let F=`*${T.key}`;o.atoms.delete(F),o.valueMap.delete(F);let A=T.family?{key:`*${T.family.key}`,subKey:T.family.subKey}:void 0,y=Do(o,{key:F,default:null},A);if(o.parent?.valueMap.has(F)){let S=o.parent.valueMap.get(F);o.valueMap.set(F,S)}return y}unsubscribeFromInnerValue;unsubscribeFromState;observeCore(T,o,F){let A=`tracker:${F.config.name}:${OT(F)?F.transactionMeta.update.key:"main"}:${T.key}`,y=MT(F,T);this.unsubscribeFromInnerValue=y.subscribe(A,(S)=>{jT(F,o,S)}),this.unsubscribeFromState=fo(F,T,A,(S)=>{if(S.newValue!==S.oldValue)this.unsubscribeFromInnerValue(),this.unsubscribeFromInnerValue=S.newValue.subscribe(A,(f)=>{jT(F,o,f)})})}updateCore(T,o,F){let A=`tracker:${F.config.name}:${OT(F)?F.transactionMeta.update.key:"main"}:${T.key}`;fo(F,o,A,({newValue:y,oldValue:S})=>{let f=F.timelineTopics.getRelatedKey(o.key);if(f){if(F.timelines.get(f)?.timeTraveling){let J=fJ(F,{key:f,type:"timeline"},A,(R)=>{J(),jT(F,T,(O)=>{if(R==="redo"&&y)O.do(y);else if(R==="undo"&&S)O.undo(S);return O})});return}}let $=F.on.operationClose.subscribe(A,()=>{$();let _=MT(F,T),J=y===null?-1:_.getUpdateNumber(y),R=J-_.cacheUpdateNumber;if(y&&R===1)jT(F,T,(O)=>(O.do(y),O));else F.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 F=j(o);this.latestUpdateState=this.initializeState(T,F),this.observeCore(T,this.latestUpdateState,F),this.updateCore(T,this.latestUpdateState,F),F.trackers.set(T.key,this),this[Symbol.dispose]=()=>{this.unsubscribeFromInnerValue(),this.unsubscribeFromState(),F.trackers.delete(T.key)}}}function Vy(T,o,F){T.logger.info("\uD83D\uDD28","atom",o.key,`creating in store "${T.config.name}"`);let A=j(T),y=A.atoms.get(o.key);if(y&&y.type==="mutable_atom")return T.logger.error("\u274C","atom",o.key,"Tried to create atom, but it already exists in the store."),Eo(y);let S=new oT,f={...o,type:"mutable_atom",install:(J)=>{return J.logger.info("\uD83D\uDEE0\uFE0F","atom",o.key,`installing in store "${J.config.name}"`),Vy(J,o,F)},subject:S};if(F)f.family=F;let $=o.default();A.atoms.set(f.key,f),qS(T,o.key),xo(A,o.key,$,S);let _=Eo(f);if(o.effects){let J=0,R=[];for(let O of o.effects){let Y=O({setSelf:(H)=>{jT(T,_,H)},onSet:(H)=>fo(T,_,`effect[${J}]`,H)});if(Y)R.push(Y);++J}f.cleanup=()=>{for(let O of R)O()}}if(new dF(_,T),!F)mR(_,o,T);return _}class _J{trackers=new Map;Update;latestUpdateAtoms;mutableAtoms;constructor(T,o){let F=OF(o,{key:`*${T.key}`,default:null},["mutable","updates"]);this.latestUpdateAtoms=JT(o,F),this.mutableAtoms=T,this.mutableAtoms.subject.subscribe(`store=${o.config.name}::tracker-atom-family`,(A)=>{let{type:y,token:S}=A;if(S.family){let f=rT(S.family.subKey);switch(y){case"state_creation":this.trackers.set(f,new dF(S,o));break;case"state_disposal":{let $=this.trackers.get(f);if($)$[Symbol.dispose](),this.trackers.delete(f)}break}}})}}function Hy(T,o,F){let A={key:o.key,type:"mutable_atom_family"},y=T.families.get(o.key);if(y)T.logger.error("\u2757","mutable_atom_family",o.key,`Overwriting an existing ${TF(y)} "${y.key}" in store "${T.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);let S=new oT,$=Object.assign((_)=>{let J=AT(_),R={key:o.key,subKey:J},O=`${o.key}(${J})`,Y=j(T),H={key:O,default:()=>o.default(_),toJson:o.toJson,fromJson:o.fromJson,mutable:!0};if(o.effects)H.effects=o.effects(_);let Q=Vy(Y,H,R);return S.next({type:"state_creation",token:Q}),Q},A,{subject:S,install:(_)=>Hy(_,o),toJson:o.toJson,fromJson:o.fromJson,internalRoles:F});return T.families.set(o.key,$),LW(T,$,o),new _J($,T),A}var RJ=(T,o)=>{let F=j(o),A=`${T.key}:JSON`;return F.families.get(A)};var nT=(T,o)=>{if(o.family){let A=j(T),S={key:`${o.family.key}:JSON`,type:"selector_family"},f=JT(A,S),$=JSON.parse(o.family.subKey);return i(T,f,$)}return{type:"selector",key:`${o.key}:JSON`}};var YF=(T)=>{let F={type:"atom",key:`*${T.key}`};if(T.family)F.family={key:`*${T.family.key}`,subKey:T.family.subKey};return F};function yW(T){return typeof T==="object"&&T!==null&&"do"in T&&"undo"in T&&"subscribe"in T}function Uy(T,o,F){let A=F.valueMap.get(o.key),y=T.valueMap.get(o.key);if(A!==y)return y;if(A===void 0)return o.default();F.logger.info("\uD83D\uDCC3","atom",o.key,"copying");let S=o.toJson(A),f=o.fromJson(S);return T.valueMap.set(o.key,f),new dF(o,F),f}function xo(T,o,F,A){let y=T.valueMap.get(o);if(y instanceof Zy)y.use(F);if(F instanceof Promise){let S=new Zy(F);return T.valueMap.set(o,S),S.then((f)=>{xo(T,o,f,A),A.next({newValue:f,oldValue:S})}).catch((f)=>{T.logger.error("\uD83D\uDCA5","state",o,"rejected:",f)}),S}return T.valueMap.set(o,F),F}var sR=(T,o)=>{let F=o.valueMap.get(T.key);if(T.type==="mutable_atom"&&OT(o)){let{parent:A}=o;F=Uy(o,T,A)}return F},FW=(T,o)=>{let F=o.valueMap.get(T);if(F instanceof Zy){let A=F,y=o.selectors.get(T)??o.readonlySelectors.get(T);if(y)A.use(y.get());return}if(o.operation.open)o.operation.prev.set(T,F);o.valueMap.delete(T),o.logger.info("\uD83D\uDDD1","state",T,"evicted")};var SW=(T,o)=>{return j(T).atomsThatAreDefault.has(o)},qS=(T,o)=>{let F=j(T);F.atomsThatAreDefault=new Set(F.atomsThatAreDefault).add(o)},fW=(T,o)=>{let F=j(T);F.atomsThatAreDefault=new Set(j(T).atomsThatAreDefault),F.atomsThatAreDefault.delete(o)};function Do(T,o,F){T.logger.info("\uD83D\uDD28","atom",o.key,`creating in store "${T.config.name}"`);let A=j(T),y=A.atoms.get(o.key);if(y&&y.type==="atom")return T.logger.error("\u274C","atom",o.key,"Tried to create atom, but it already exists in the store."),Eo(y);let S=new oT,f={...o,type:"atom",install:(J)=>{return J.logger.info("\uD83D\uDEE0\uFE0F","atom",o.key,`installing in store "${J.config.name}"`),Do(J,o,F)},subject:S};if(F)f.family=F;let $=o.default;if(o.default instanceof Function)$=o.default();A.atoms.set(f.key,f),qS(T,o.key),xo(A,o.key,$,S);let _=Eo(f);if(o.effects){let J=0,R=[];for(let O of o.effects){let Y=O({setSelf:(H)=>{jT(T,_,H)},onSet:(H)=>fo(T,_,`effect[${J}]`,H)});if(Y)R.push(Y);++J}f.cleanup=()=>{for(let O of R)O()}}return _}function gR(T,o){if("mutable"in o){let y=Vy(T,o,void 0);return T.on.atomCreation.next(y),y}let A=Do(T,o,void 0);return T.on.atomCreation.next(A),A}function yJ(T,o){let F=j(T),{key:A,family:y}=o,S=JT(F,o);if(!y)T.logger.error("\u274C","atom",A,"Standalone atoms cannot be disposed.");else{S.cleanup?.();let f=T.valueMap.get(S.key),$=JT(T,{key:y.key,type:"atom_family"}),_={type:"state_disposal",subType:"atom",token:o,value:f};$.subject.next(_);let J=OT(F);if(F.atoms.delete(A),F.valueMap.delete(A),F.selectorAtoms.delete(A),F.atomsThatAreDefault.delete(A),T.timelineTopics.delete(A),o.type==="mutable_atom"){let R=YF(o);yJ(T,R),T.trackers.delete(A)}if(T.logger.info("\uD83D\uDD25","atom",A,"deleted"),J&&F.transactionMeta.phase==="building"){let R=F.transactionMeta.update.updates.at(-1);if(!(R?.type==="molecule_disposal"&&R.values.some(([H])=>H===S.family?.key)))F.transactionMeta.update.updates.push(_)}else T.on.atomDisposal.next(o)}}class cT extends Set{mode="record";subject=new oT;cacheLimit=0;cache=[];cacheIdx=-1;cacheUpdateNumber=-1;constructor(T,o=0){super(T);if(T instanceof cT)this.parent=T,this.cacheUpdateNumber=T.cacheUpdateNumber;if(o)this.cacheLimit=o,this.cache=new Array(o),this.subscribe("auto cache",(F)=>{this.cacheIdx++,this.cacheIdx%=this.cacheLimit,this.cache[this.cacheIdx]=F})}toJSON(){return{members:[...this],cache:this.cache,cacheLimit:this.cacheLimit,cacheIdx:this.cacheIdx,cacheUpdateNumber:this.cacheUpdateNumber}}static fromJSON(T){let o=new cT(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 cT(this);let o=this.child._subscribe("transaction",(F)=>{this.transactionUpdates?.push(F)});try{if(T(this.child)){for(let A of this.transactionUpdates)this.doStep(A);this.cacheUpdateNumber++,this.emit(`tx:${this.transactionUpdates.join(";")}`)}}catch(F){throw console.warn("Did not apply transaction to SetRTX; this error was thrown:",F),F}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,(F)=>{o(`${this.cacheUpdateNumber}=${F}`)})}emit(T){this.subject.next(T)}doStep(T){let o=T.indexOf(":"),F=T.substring(0,o),A=T.substring(o+1);switch(F){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 y of A.split(";"))this.doStep(y)}}getUpdateNumber(T){let o=T.indexOf("=");return Number(T.substring(0,o))}do(T){let o=T.indexOf("="),F=Number(T.substring(0,o)),A=F-this.cacheUpdateNumber;if(A>0){if(A===1){this.mode="playback";let S=T.substring(o+1);return this.doStep(S),this.mode="record",this.cacheUpdateNumber=F,null}return this.cacheUpdateNumber+1}if(Math.abs(A)<this.cacheLimit){let S=this.cacheIdx+A;if(this.cache[S]===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===S-1}let _=T.substring(o+1);return this.doStep(_),this.mode="record",this.cacheUpdateNumber=F,null}return"OUT_OF_RANGE"}undoStep(T){let o=T.indexOf(":"),F=T.substring(0,o),A=T.substring(o+1);switch(F){case"add":this.delete(JSON.parse(A));break;case"del":this.add(JSON.parse(A));break;case"clear":{let y=JSON.parse(A);for(let S of y)this.add(S);break}case"tx":{let y=A.split(";");for(let S=y.length-1;S>=0;S--)this.undoStep(y[S])}}}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 Ey{toolkit;options;defaultContent;molecules=new Map;relations;states;core;transact(T,o){let F=this.toolkit;this.toolkit=T,o(this),this.toolkit=F}store;realm;[Symbol.dispose](){}constructor(T,o,F=ST.STORE){this.store=F,this.realm=new a$(F),this.options=T,this.defaultContent=o,this.store.miscResources.set(`join:${T.key}`,this),this.realm.allocate("root",T.key),this.toolkit={get:(...U)=>MT(F,...U),set:(...U)=>{jT(F,...U)},find:(...U)=>i(F,...U),json:(U)=>nT(F,U)};let A=T.between[0],y=T.between[1],S=Hy(F,{key:`${T.key}/relatedKeys`,default:()=>new cT,mutable:!0,fromJson:(U)=>cT.fromJSON(U),toJson:(U)=>U.toJSON()},["join","relations"]);this.core={relatedKeysAtoms:S};let f=({get:U},V)=>U(S,V),$=({set:U},V,I)=>{if(!this.store.molecules.has(AT(V)))this.realm.allocate(T.key,V);U(S,V,(L)=>L.add(I)),U(S,I,(L)=>L.add(V))},_=({set:U},V,I)=>{U(S,V,(L)=>{return L.delete(I),L}),U(S,I,(L)=>{return L.delete(V),L})},J=(U,V,I)=>{let{find:L,get:m,set:s}=U,z=L(S,V),a=m(z);for(let t of a){if(I.includes(t))continue;s(S,t,(ZT)=>{return ZT.delete(V),ZT})}s(z,(t)=>{return t.transaction((e)=>{e.clear();for(let ZT of I){let vT=f(U,ZT),Xo=vT.has(V);if(this.relations.cardinality==="1:n"){let AF=[];for(let D of vT){if(D===V)continue;let g=f(U,D);if(g.delete(ZT),g.size===0)AF.push(D)}if(!Xo&&vT.size>0)vT.clear();for(let D of AF){let g=[ZT,D].sort(),_T=`"${g[0]}:${g[1]}"`;this.molecules.delete(_T)}}if(!Xo)vT.add(V);e.add(ZT)}return!0}),t})},R=(U,V,I)=>{let{set:L}=U;L(S,V,(m)=>{return m.transaction((s)=>{for(let z of I)s.add(z);return!0}),m});for(let m of I)L(S,m,(s)=>{return s.add(V),s});return!0},O=(U,V,I)=>{let L=f(U,V);return I?L.has(I):L.size>0},Y={getRelatedKeys:(U)=>f(this.toolkit,U),addRelation:(U,V)=>{this.store.moleculeJoins.set(U,T.key),this.store.moleculeJoins.set(V,T.key),$(this.toolkit,U,V)},deleteRelation:(U,V)=>{_(this.toolkit,U,V)},replaceRelationsSafely:(U,V)=>{J(this.toolkit,U,V)},replaceRelationsUnsafely:(U,V)=>{R(this.toolkit,U,V)},has:(U,V)=>O(this.toolkit,U,V)},H,Q;if(o){Q=OF(F,{key:`${T.key}/content`,default:o},["join","content"]);let U=({get:L},m)=>L(Q,m),V=({set:L},m,s)=>{L(Q,m,s)};H=Object.assign(Y,{getContent:(L)=>{return U(this.toolkit,L)},setContent:(L,m)=>{V(this.toolkit,L,m)},deleteContent:(L)=>{this.realm.deallocate(L)}})}else H=Y;let E=new uT(T,{externalStore:H,isAType:T.isAType,isBType:T.isBType,makeContentKey:(...U)=>{let[V,I]=U,L=U.sort(),m=`${L[0]}:${L[1]}`,s=F.molecules.get(AT(V)),z=F.molecules.get(AT(I));if(!s)this.realm.allocate(T.key,V);if(!z)this.realm.allocate(T.key,I);return this.realm.allocate(V,m,"all"),this.realm.claim(I,m),this.store.moleculeJoins.set(m,T.key),m}}),B=()=>XF(F,{key:`${T.key}/singleRelatedKey`,get:(U)=>({get:V})=>{let I=V(S,U);for(let L of I)return L;return null}},["join","keys"]),p=()=>{return XF(F,{key:`${T.key}/multipleRelatedKeys`,get:(U)=>({get:V})=>{let I=RJ(S,F);return V(I,U).members}},["join","keys"])},v=()=>XF(F,{key:`${T.key}/singleRelatedEntry`,get:(U)=>({get:V})=>{let I=V(S,U);for(let L of I){let m=E.isAType?.(U)?U:void 0,s=m===void 0?U:void 0;m??=L,s??=L;let z=E.makeContentKey(m,s),a=V(Q,z);return[L,a]}return null}},["join","entries"]),h=()=>XF(F,{key:`${T.key}/multipleRelatedEntries`,get:(U)=>({get:V})=>{let I=RJ(S,F);return V(I,U).members.map((m)=>{let s=E.isAType?.(U)?U:void 0,z=s===void 0?U:void 0;s??=m,z??=m;let a=E.makeContentKey(s,z),t=V(Q,a);return[m,t]})}},["join","entries"]);switch(T.cardinality){case"1:1":{let U=B(),V=`${A}KeyOf${XT(y)}`,I=`${y}KeyOf${XT(A)}`,L={[V]:U,[I]:U},m;if(o){let s=v(),z=`${A}EntryOf${XT(y)}`,a=`${y}EntryOf${XT(A)}`,t={[z]:s,[a]:s};m=Object.assign(L,t)}else m=L;this.relations=E,this.states=m;break}case"1:n":{let U=B(),V=p(),I=`${A}KeyOf${XT(y)}`,L=`${y}KeysOf${XT(A)}`,m={[I]:U,[L]:V},s;if(o){let z=v(),a=h(),t=`${A}EntryOf${XT(y)}`,e=`${y}EntriesOf${XT(A)}`,ZT={[t]:z,[e]:a};s=Object.assign(m,ZT)}else s=m;this.relations=E,this.states=s;break}case"n:n":{let U=p(),V=`${A}KeysOf${XT(y)}`,I=`${y}KeysOf${XT(A)}`,L={[V]:U,[I]:U},m;if(o){let s=h(),z=`${A}EntriesOf${XT(y)}`,a=`${y}EntriesOf${XT(A)}`,t={[z]:s,[a]:s};m=Object.assign(L,t)}else m=L;this.relations=E,this.states=m}}}}function LA(T,o){let F=o.joins.get(T.key);if(F===void 0){let y=ST.STORE.joins.get(T.key);if(y===void 0)throw new Error(`Join "${T.key}" not found in store "${o.config.name}"`);F=new Ey(y.options,y.defaultContent,o),o.joins.set(T.key,F)}return F}function Ky(T,o,F){let A=LA(T,F),y=j(F);if(OT(y)){let{toolkit:S}=y.transactionMeta;A.transact(S,({relations:f})=>{o(f)})}else o(A.relations)}function CS(T,o,F){let A=LA(T,F),y;switch(T.cardinality){case"1:1":{let S=`${T.a}KeyOf${XT(T.b)}`,f=`${T.b}KeyOf${XT(T.a)}`;y={get[S](){let _=A.states[S];return i(F,_,o)},get[f](){let _=A.states[f];return i(F,_,o)}};let $=`${T.a}EntryOf${XT(T.b)}`;if($ in A.states){let _=`${T.b}EntryOf${XT(T.a)}`;Object.assign(y,{get[$](){let J=A.states[$];return i(F,J,o)},get[_](){let J=A.states[_];return i(F,J,o)}})}break}case"1:n":{let S=`${T.a}KeyOf${XT(T.b)}`,f=`${T.b}KeysOf${XT(T.a)}`;y={get[S](){let _=A.states[S];return i(F,_,o)},get[f](){let _=A.states[f];return i(F,_,o)}};let $=`${T.a}EntryOf${XT(T.b)}`;if($ in A.states){let _=`${T.b}EntriesOf${XT(T.a)}`;Object.assign(y,{get[$](){let J=A.states[$];return i(F,J,o)},get[_](){let J=A.states[_];return i(F,J,o)}})}break}case"n:n":{let S=`${T.a}KeysOf${XT(T.b)}`,f=`${T.b}KeysOf${XT(T.a)}`;y={get[S](){let _=A.states[S];return i(F,_,o)},get[f](){let _=A.states[f];return i(F,_,o)}};let $=`${T.a}EntriesOf${XT(T.b)}`;if($ in A.states){let _=`${T.b}EntriesOf${XT(T.a)}`;Object.assign(y,{get[$](){let J=A.states[$];return i(F,J,o)},get[_](){let J=A.states[_];return i(F,J,o)}})}}}return y}function cR(T,o){return LA(T,o).core.relatedKeysAtoms}function BF(T){return T.startsWith("\uD83D\uDD0D ")}var WJ=(T)=>{let o=Do(T,{key:"\uD83D\uDD0D Atom Token Index (Internal)",default:()=>{let F=new Map;for(let[A,y]of T.atoms){if(BF(A))continue;let S=Eo(y);if(y.family){let f=F.get(y.family.key);if(!f||!("familyMembers"in f))f={key:y.family.key,familyMembers:new Map},F.set(y.family.key,f);f.familyMembers.set(y.family.subKey,S)}else F.set(A,S)}return F},effects:[({setSelf:F})=>{T.on.atomCreation.subscribe("introspection",(A)=>{if(BF(A.key))return;F((y)=>{if(A.family){let{key:S,subKey:f}=A.family,$=y.get(S);if($===void 0||!("familyMembers"in $))$={key:S,familyMembers:new Map},y.set(S,$);$.familyMembers.set(f,A)}else y.set(A.key,A);return y})}),T.on.atomDisposal.subscribe("introspection",(A)=>{F((y)=>{if(A.family){let{key:S,subKey:f}=A.family,$=y.get(S);if($&&"familyMembers"in $){if($.familyMembers.delete(f),$.familyMembers.size===0)y.delete(S)}}else y.delete(A.key);return y})})}]},void 0);return MF(T,{key:"\uD83D\uDD0D Atom Token Index",get:({get:F})=>F(o)})};var MJ=(T)=>{let o=Do(T,{key:"\uD83D\uDD0D Selector Token Index (Internal)",default:()=>{let F=new Map;for(let A of[T.readonlySelectors,T.selectors])for(let[y,S]of A){if(BF(y))continue;let f=Eo(S);if(S.family){let $=F.get(S.family.key);if(!$||!("familyMembers"in $))$={key:S.family.key,familyMembers:new Map},F.set(S.family.key,$);$.familyMembers.set(S.family.subKey,f)}else F.set(y,f)}return F},effects:[({setSelf:F})=>{T.on.selectorCreation.subscribe("introspection",(A)=>{if(BF(A.key))return;F((y)=>{if(A.family){let{key:S,subKey:f}=A.family,$=y.get(S);if($===void 0||!("familyMembers"in $))$={key:S,familyMembers:new Map},y.set(S,$);$.familyMembers.set(f,A)}else y.set(A.key,A);return y})}),T.on.selectorDisposal.subscribe("introspection",(A)=>{F((y)=>{if(A.family){let{key:S,subKey:f}=A.family,$=y.get(S);if($&&"familyMembers"in $){if($.familyMembers.delete(f),$.familyMembers.size===0)y.delete(S)}}else y.delete(A.key);return y})})}]},void 0);return MF(T,{key:"\uD83D\uDD0D Selector Token Index",get:({get:F})=>F(o)})};class vS{supported;constructor(T){this.supported=T}refine(T){for(let[o,F]of Object.entries(this.supported))try{if(F(T)===!0&&F!==Boolean)return{type:o,data:T}}catch(A){try{if(T instanceof F)return{type:o,data:T}}catch(y){}}return null}}var OJ=new vS({number:(T)=>typeof T==="number",string:(T)=>typeof T==="string",boolean:(T)=>typeof T==="boolean",null:(T)=>T===null});function XJ(T){if(!T)return!1;return Object.getPrototypeOf(T)===Object.prototype}var YJ=new vS({object:XJ,array:(T)=>Array.isArray(T)}),XZ=new vS({...OJ.supported,...YJ.supported}),CA=(T)=>{if(T===void 0)return"undefined";let o=XZ.refine(T);if(o)return o.type;return Object.getPrototypeOf(T).constructor.name};class IW{store;auditorCreatedAt=performance.now();statesCreatedAt=new Map;atomIndex;selectorIndex;disposed=!1;unsubscribeFromAtomCreation;unsubscribeFromAtomDisposal;unsubscribeFromSelectorCreation;unsubscribeFromSelectorDisposal;constructor(T=ST.STORE){this.store=T,this.atomIndex=WJ(this.store),this.selectorIndex=MJ(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=IW.DEFAULT_LIST_RESOURCES_PARAM){if(this.disposed)throw new Error("This Auditor has been disposed");let o=r$(this.atomIndex),F=r$(this.selectorIndex),A=[...o.values()].filter(($)=>("familyMembers"in $)),y=[...F.values()].filter(($)=>("familyMembers"in $)),S=performance.now(),f=[];if(T.atomFamilies)for(let $ of A){let _=$.familyMembers.values();for(let J of _){let O=this.statesCreatedAt.get(J.key)??this.auditorCreatedAt,Y=S-O;f.push([J,Y])}}if(T.selectorFamilies)for(let $ of y){let _=$.familyMembers.values();for(let J of _){let O=this.statesCreatedAt.get(J.key)??this.auditorCreatedAt,Y=S-O;f.push([J,Y])}}return f}[Symbol.dispose](){this.unsubscribeFromAtomCreation(),this.unsubscribeFromAtomDisposal(),this.unsubscribeFromSelectorCreation(),this.unsubscribeFromSelectorDisposal(),this.disposed=!0}}var ZJ=(T,o)=>{let F=(A,y)=>{let f=((_,J)=>{let R=o(_,J);if(R)return R;return null})(A,y);if(f?.jobComplete??f?.pathComplete)return f;let $=Array.isArray(y)?y.map((_,J)=>[J,_]):XJ(y)?Object.entries(y):[];for(let[_,J]of $){let R=F([...A,_],J);if(R?.jobComplete)return R}return{}};F([],T)};function YZ(T,o){return{summary:`${T<o?"+":"-"}${Math.abs(T-o)} (${T} \u2192 ${o})`}}function ZZ(T,o){return{summary:`${T.length<o.length?"+":"-"}${Math.abs(T.length-o.length)} ("${T}" \u2192 "${o}")`}}function HZ(T,o){return{summary:`${T} \u2192 ${o}`}}function kW(T,o,F){let A="",y=[],S=[],f=[];return ZJ(T,($,_)=>{let J;for(J of $){let R=o[J];if(R===void 0)S.push([J,JSON.stringify(_)]);else{let O=F(_,R);if(O.summary!=="No Change")f.push([J,O])}}}),ZJ(o,($,_)=>{let J;for(J of $)if(T[J]===void 0)y.push([J,JSON.stringify(_)])}),A=`\uFF5E${f.length} \uFF0B${y.length} \uFF0D${S.length}`,{summary:A,added:y,removed:S,changed:f}}function GZ(T,o,F){return kW(T,o,F)}class BW{leafRefinery;treeRefinery;leafDiffers;treeDiffers;constructor(T,o,F){this.leafRefinery=T,this.treeRefinery=o,this.leafDiffers={},this.treeDiffers={};for(let A of Object.keys(T.supported)){let y=F[A];this.leafDiffers[A]=y}for(let A of Object.keys(o.supported)){let y=F[A];this.treeDiffers[A]=y}}diff(T,o){if(T===o)return{summary:"No Change"};let F=this.leafRefinery.refine(T)??this.treeRefinery.refine(T),A=this.leafRefinery.refine(o)??this.treeRefinery.refine(o);if(F!==null&&A!==null){if(F.type===A.type){if(F.type in this.leafDiffers)return this.leafDiffers[F.type](F.data,A.data);if(F.type in this.treeDiffers)return this.treeDiffers[F.type](F.data,A.data,($,_)=>this.diff($,_))}}let y=CA(T),S=CA(o);if(y===S)return{summary:`${y} \u2192 ${S}`};return{summary:`Type change: ${y} \u2192 ${S}`}}}var Sp=new BW(OJ,YJ,{number:YZ,string:ZZ,boolean:HZ,null:()=>({summary:"No Change"}),object:kW,array:GZ});class NW 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 PS{type="continuity";globals=[];actions=[];perspectives=[];key;constructor(T){this.key=T}static existing=new NW;static create(T,o){let F=new PS(T),{type:A,globals:y,actions:S,perspectives:f}=o(F),$={type:A,key:T,globals:y,actions:S,perspectives:f};return PS.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[F,A]=T;this.perspectives.push({type:"realtime_perspective",resourceAtoms:F,viewAtoms:A})}break}return this}}function Xp(T){let{key:o,config:F}=T,A=PS.create(o,F),{actions:y}=A;for(let S of y)HW(ST.STORE,o,S.key);return XW(ST.STORE,o,-1),A}var Gp=zA({key:"usersInRoomIndex",mutable:!0,default:()=>new cT,toJson:(T)=>T.toJSON(),fromJson:(T)=>cT.fromJSON(T)}),HJ=zA({key:"roomIndex",default:()=>new cT,mutable:!0,toJson:(T)=>T.toJSON(),fromJson:(T)=>cT.fromJSON(T)}),wZ={enteredAtEpoch:0},Dy=LS({key:"usersInRooms",between:["room","user"],cardinality:"1:n",isAType:(T)=>typeof T==="string",isBType:(T)=>typeof T==="string"},wZ),wp=IS({key:"usersInMyRoomView",get:(T)=>({find:o})=>{let F=uR(Dy);return[o(F,T)]}});import{spawn as EZ}from"child_process";class IA{listeners;globalListeners;handleEvent(T,...o){for(let A of this.globalListeners)A(T,...o);let F=this.listeners.get(T);if(F)for(let A of F)A(...o)}id="no_id_retrieved";emit;constructor(T){this.emit=T,this.listeners=new Map,this.globalListeners=new Set}on(T,o){let F=this.listeners.get(T);if(F)F.add(o);else this.listeners.set(T,new Set([o]));return this}onAny(T){return this.globalListeners.add(T),this}off(T,o){let F=this.listeners.get(T);if(F)if(o)F.delete(o);else this.listeners.delete(T);return this}offAny(T){return this.globalListeners.delete(T),this}}class GJ extends IA{incompleteData="";unprocessedEvents=[];incompleteLog="";unprocessedLogs=[];id="#####";process;key;logger;handleLog(T){if(Array.isArray(T)){let[o,...F]=T;switch(o){case"i":this.logger.info(...F);break;case"w":this.logger.warn(...F);break;case"e":this.logger.error(...F);break;default:return}}}constructor(T,o,F){super((A,...y)=>{let S=JSON.stringify([A,...y])+"\x03",f=($)=>{if($.code==="EPIPE")console.error("EPIPE error during write",this.process.stdin);this.process.stdin.removeListener("error",f)};return this.process.stdin.once("error",f),this.process.stdin.write(S),this});if(this.process=T,this.key=o,this.logger=F??{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 y=A.toString();if(y==="ALIVE")return;this.unprocessedEvents.push(...y.split("\x03"));let S=this.unprocessedEvents.shift();this.incompleteData+=S??"";try{if(this.incompleteData.startsWith("error"))console.log("\u2757",this.incompleteData);let f=rT(this.incompleteData);this.handleEvent(...f);while(this.unprocessedEvents.length>0){let $=this.unprocessedEvents.shift();if($){if(this.unprocessedEvents.length===0)this.incompleteData=$;f=rT($),this.handleEvent(...f)}}this.incompleteData=""}catch(f){console.warn("\u26A0\uFE0F----------------\u26A0\uFE0F"),console.warn(this.incompleteData),console.warn("\u26A0\uFE0F----------------\u26A0\uFE0F"),console.error(f)}}),this.process.stderr.on("data",(A)=>{let y=A.toString();this.unprocessedLogs.push(...y.split("\x03"));let S=this.unprocessedLogs.shift();this.incompleteLog+=S??"";try{let f=rT(this.incompleteLog);this.handleLog(f);while(this.unprocessedLogs.length>0)if(this.incompleteLog=this.unprocessedLogs.shift()??"",this.incompleteLog)f=rT(this.incompleteLog),this.handleLog(f)}catch(f){console.error("\u274C\u274C\u274C"),console.error(this.incompleteLog),console.error(f),console.error("\u274C\u274C\u274C\uFE0F")}}),T.pid)this.id=T.pid.toString()}}class pW extends IA{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 wJ extends IA{incompleteData="";unprocessedEvents=[];relays;relayServices;process;id="#####";log(...T){this.process.stderr.write(AT(T.map((o)=>o instanceof cT?`{ ${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 F=JSON.stringify([T,...o]);return this.process.stdout.write(F+"\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 F=this.unprocessedEvents.shift();this.incompleteData+=F??"";try{let A=rT(this.incompleteData);this.logger.info("\uD83C\uDFB0","received",A),this.handleEvent(...A);while(this.unprocessedEvents.length>0){let y=this.unprocessedEvents.shift();if(y){if(this.unprocessedEvents.length===0)this.incompleteData=y;let S=rT(y);this.handleEvent(...S)}}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 pW(`user:${T}`);this.relays.set(T,o),this.logger.info("\uD83D\uDD17","attaching services:",`[${[...this.relayServices.keys()].join(", ")}]`);for(let F of this.relayServices){let A=F(o);if(A)o.disposalFunctions.push(A)}this.on(`user:${T}`,(...F)=>{o.in.next(F)}),o.out.subscribe("socket",(F)=>{this.emit(...F)})}),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 EJ=gF({key:"roomArguments",default:["echo",["Hello World!"]]}),jW=IS({key:"room",get:(T)=>async({get:o,find:F})=>{let A=F(EJ,T),y=o(A),[S,f]=y,$=await new Promise((_)=>{let J=EZ(S,f,{env:process.env}),R=(O)=>{if(O.toString()==="ALIVE")J.stdout.off("data",R),_(J)};J.stdout.on("data",R)});return new GJ($,T)}});var cp=zy({key:"createRoom",do:({get:T,set:o,find:F},A,y,S)=>{let f=S?[y,S]:[y],$=F(EJ,A);o($,f),o(HJ,(R)=>R.add(A));let _=F(jW,A);return T(_)}}),ip=zy({key:"joinRoom",do:(T,o,F,A)=>{let y={enteredAtEpoch:A};return Ky(Dy,(S)=>{S.set({room:o,user:F},y)},T.env().store),y}}),dp=zy({key:"leaveRoom",do:(T,o,F)=>{Ky(Dy,(A)=>{A.delete({room:o,user:F})},T.env().store)}}),rp=zy({key:"destroyRoom",do:(T,o)=>{Ky(Dy,(F)=>{F.delete({room:o})},T.env().store),T.set(HJ,(F)=>(F.delete(o),F))}});function KJ(T,o){return o.map((F)=>{switch(F.type){case"transaction_update":{let A=KJ(T,F.updates);return{...F,updates:A}}case"atom_update":case"selector_update":case"molecule_creation":case"molecule_disposal":case"molecule_transfer":case"state_creation":case"state_disposal":return F}}).filter((F)=>{switch(F.type){case"atom_update":case"selector_update":return T.includes(F.key);case"state_creation":case"state_disposal":return T.includes(F.token.key);case"molecule_creation":case"transaction_update":case"molecule_disposal":case"molecule_transfer":return!0}})}var ap=gF({key:"redactor",default:{occlude:(T)=>T}}),kA=gF({key:"unacknowledgedUpdates",default:()=>[]});var xW=gF({key:"sockets",default:null}),Fj=zA({key:"socketsIndex",mutable:!0,default:()=>new cT,toJson:(T)=>T.toJSON(),fromJson:(T)=>cT.fromJSON(T)}),Aj=zA({key:"usersIndex",mutable:!0,default:()=>new cT,toJson:(T)=>T.toJSON(),fromJson:(T)=>cT.fromJSON(T)}),UJ=LS({key:"usersOfSockets",between:["user","socket"],cardinality:"1:1",isAType:(T)=>T.startsWith("user::"),isBType:(T)=>T.startsWith("socket::")});function bW(T,o,F,A){let y=o.key;return function S(){let f=[];for(let _ of o.globals){let J=_.type==="mutable_atom"?nT(T,_):_,R=MT(T,J);f.push(J,R)}for(let _ of o.perspectives){let{viewAtoms:J,resourceAtoms:R}=_,O=i(T,J,F),Y=MT(T,O);T.logger.info("\uD83D\uDC41","atom",R.key,`${F} can see`,{viewAtoms:J,resourceAtoms:R,userView:Y});for(let H of Y){let Q=H.type==="mutable_atom"?nT(T,H):H,E=MT(T,Q);f.push(Q,E)}}let $=aT(T)?T.transactionMeta.epoch.get(y)??null:null;A?.emit(`continuity-init:${y}`,$,f)}}function qW(T,o,F){let A=o.key;return function y(S){T.logger.info("\uD83D\uDECE\uFE0F","continuity",A,"received",S);let{key:f,id:$}=S,_=`tx-run:${f}:${$}`,J=`${_}:start`,R=`${_}:end`;performance.mark(J);try{VA(T,{type:"transaction",key:f},$)(...S.params)}catch(Y){if(Y instanceof Error)T.logger.error("\u274C","continuity",A,`failed to run transaction ${f} from ${F} with update ${$}`,Y.message)}performance.mark(R);let O=performance.measure(_,J,R);T?.logger.info("\uD83D\uDE80","transaction",f,$,F,O.duration)}}function vW(T,o,F,A){let y=o.key;return function S(f){if(T.logger.info("\uD83D\uDC4D","continuity",y,`${F} acknowledged epoch ${f}`),A[0]?.epoch===f)jT(T,kA,F,(_)=>{return _.shift(),T.logger.info("\uD83D\uDC4D","continuity",y,`${F} unacknowledged update queue now has`,_.length,"items"),_})}}function PW(T,o,F,A){let y=o.key,S=[];for(let f of o.actions){let $=$J(T,f,`sync-continuity:${y}:${F}`,(_)=>{try{let J=o.globals.map((Y)=>{if(Y.type==="atom")return Y.key;return YF(Y).key}).concat(o.perspectives.flatMap((Y)=>{let{viewAtoms:H}=Y,Q=i(T,H,F);return MT(T,Q).map((B)=>{return B.type==="mutable_atom"?"*"+B.key:B.key})})),R=KJ(J,_.updates),O={..._,updates:R};jT(T,kA,F,(Y)=>{if(O)Y.push(O),Y.sort((H,Q)=>H.epoch-Q.epoch),T.logger.info("\uD83D\uDC4D","continuity",y,`${F} unacknowledged update queue now has`,Y.length,"items");return Y}),A?.emit(`tx-new:${y}`,O)}catch(J){if(J instanceof Error)T.logger.error("\u274C","continuity",y,`${F} failed to send update from transaction ${f.key} to ${F}`,J.message)}});S.push($)}return S}function mW(T,o,F,A){let y=o.key,S=[];for(let f of o.perspectives){let{viewAtoms:$}=f,_=i(T,$,F),J=fo(T,_,`sync-continuity:${y}:${F}:perspective:${f.resourceAtoms.key}`,({oldValue:R,newValue:O})=>{let Y=R.map((B)=>B.key),H=O.map((B)=>B.key),Q=R.filter((B)=>!H.includes(B.key)),E=O.filter((B)=>!Y.includes(B.key)).flatMap((B)=>{let p=B.type==="mutable_atom"?nT(T,B):B,v=MT(T,p);return[p,v]});if(T.logger.info("\uD83D\uDC41","atom",f.resourceAtoms.key,`${F} has a new perspective`,{oldKeys:Y,newKeys:H,revealed:E,concealed:Q}),E.length>0)A?.emit(`reveal:${y}`,E);if(Q.length>0)A?.emit(`conceal:${y}`,Q)});S.push(J)}return S}function Nj({socket:T,store:o=ST.STORE}){return function F(A){let y=T,S=A.key,f=CS(UJ,`socket::${y.id}`,o).userKeyOfSocket,$=MT(o,f);if(!$)return o.logger.error("\u274C","continuity",S,`Tried to create a synchronizer for a socket (${y.id}) that is not connected to a user.`),()=>{};let _=CS(UJ,$,o).socketKeyOfUser,J=fo(o,_,`sync-continuity:${S}:${$}`,({newValue:p})=>{if(o.logger.info("\uD83D\uDC4B","continuity",S,`seeing ${$} on new socket ${p}`),p===null){o.logger.warn("\u274C","continuity",S,`User (${$}) is not connected to a socket, waiting for them to reappear.`);return}let v=i(o,xW,p);y=MT(o,v);for(let U of R)y?.emit(`tx-new:${S}`,U)}),R=MT(o,kA,$),O=[],Y=mW(o,A,$,y),H=PW(o,A,$,y);O.push(...Y,...H);let Q=bW(o,A,$,T);y.off(`get:${S}`,Q),y.on(`get:${S}`,Q);let E=qW(o,A,$);y.off(`tx-run:${S}`,E),y.on(`tx-run:${S}`,E);let B=vW(o,A,$,R);return y?.on(`ack:${S}`,B),()=>{for(let p of O)p();y?.off(`ack:${S}`,B),y?.off(`get:${S}`,Q),y?.off(`tx-run:${S}`,E)}}}var{file:G4,serve:N5}=globalThis.Bun;import{readFileSync as nW}from"fs";import{resolve as zJ}from"path";function tW(T,o){if(T instanceof Promise)throw new Error(o)}function KZ(T,o){let F={},A=[];for(let y in T){let S=T[y]["~standard"].validate(o[y]);if(tW(S,`Validation must be synchronous, but ${y} returned a Promise.`),S.issues){A.push(...S.issues.map((f)=>({...f,path:[y,...f.path??[]]})));continue}F[y]=S.value}if(A.length)return{issues:A};return{value:F}}function hW(T){let o=T.runtimeEnvStrict??T.runtimeEnv??process.env;if(T.emptyStringAsUndefined??!1){for(let[v,h]of Object.entries(o))if(h==="")delete o[v]}if(!!T.skipValidation)return o;let y=typeof T.client==="object"?T.client:{},S=typeof T.server==="object"?T.server:{},f=typeof T.shared==="object"?T.shared:{},$=T.isServer??(typeof window==="undefined"||("Deno"in window)),_=$?{...S,...f,...y}:{...y,...f},J=T.createFinalSchema?.(_,$)["~standard"].validate(o)??KZ(_,o);tW(J,"Validation must be synchronous");let R=T.onValidationError??((v)=>{throw console.error("\u274C Invalid environment variables:",v),new Error("Invalid environment variables")}),O=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=(v)=>{if(!T.clientPrefix)return!0;return!v.startsWith(T.clientPrefix)&&!(v in f)},H=(v)=>{return $||!Y(v)},Q=(v)=>{return v==="__esModule"||v==="$$typeof"},E=(T.extends??[]).reduce((v,h)=>{return Object.assign(v,h)},{}),B=Object.assign(E,J.value);return new Proxy(B,{get(v,h){if(typeof h!=="string")return;if(Q(h))return;if(!H(h))return O(h);return Reflect.get(v,h)}})}var UZ="__vite_start_time"in globalThis,zZ=typeof window!=="undefined",$x="vitest"in globalThis,ZF=jo("string"),gW=jo('"true" | "false" | undefined'),uo=hW({isServer:!UZ&&!zZ,server:{CI:jo("string | undefined").pipe(Boolean),POSTGRES_USER:ZF,POSTGRES_PASSWORD:ZF,POSTGRES_DATABASE:ZF,POSTGRES_HOST:ZF,POSTGRES_PORT:ZF.pipe((T)=>Number.parseInt(T,10)),BACKEND_PORT:ZF.pipe((T)=>Number.parseInt(T,10)),RUN_WORKERS_FROM_SOURCE:gW.pipe((T)=>T==="true"),FRONTEND_PORT:ZF.pipe((T)=>Number.parseInt(T,10)),FRONTEND_ORIGINS:ZF.pipe.try((T)=>JSON.parse(T),jo("string[]")),OPENAI_API_KEY:jo("string | undefined")},clientPrefix:"VITE_",client:{VITE_BACKEND_ORIGIN:ZF,VITE_USE_SELF_SIGNED_CERTIFICATE:gW.pipe((T)=>T==="true")},runtimeEnv:import.meta.env,emptyStringAsUndefined:!0});var uW=zJ(import.meta.dirname,"../dev"),cW=uo.VITE_USE_SELF_SIGNED_CERTIFICATE?{cert:nW(zJ(uW,"./cert.pem"),"utf-8"),key:nW(zJ(uW,"./key.pem"),"utf-8")}:void 0;import D5 from"path";var M=Symbol.for("drizzle:entityKind"),Ox=Symbol.for("drizzle:hasOwnEntityKind");function w(T,o){if(!T||typeof T!=="object")return!1;if(T instanceof o)return!0;if(!Object.prototype.hasOwnProperty.call(o,M))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 F=Object.getPrototypeOf(T).constructor;if(F)while(F){if(M in F&&F[M]===o[M])return!0;F=Object.getPrototypeOf(F)}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[M]="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 QJ{static[M]="ColumnBuilder";config;constructor(T,o,F){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:F,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 co=Symbol.for("drizzle:Name");class VJ{static[M]="PgForeignKeyBuilder";reference;_onUpdate="no action";_onDelete="no action";constructor(T,o){if(this.reference=()=>{let{name:F,columns:A,foreignColumns:y}=T();return{name:F,columns:A,foreignTable:y[0].table,foreignColumns:y}},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 iW(T,this)}}class iW{constructor(T,o){this.table=T,this.reference=o.reference,this.onUpdate=o._onUpdate,this.onDelete=o._onDelete}static[M]="PgForeignKey";reference;onUpdate;onDelete;getName(){let{name:T,columns:o,foreignColumns:F}=this.reference(),A=o.map((f)=>f.name),y=F.map((f)=>f.name),S=[this.table[co],...A,F[0].table[co],...y];return T??`${S.join("_")}_fk`}}function mS(T,...o){return T(...o)}function dW(T,o){return`${T[co]}_${o.join("_")}_unique`}function rW(T,o,F){for(let A=o;A<T.length;A++){let y=T[A];if(y==="\\"){A++;continue}if(y==='"')return[T.slice(o,A).replace(/\\/g,""),A+1];if(F)continue;if(y===","||y==="}")return[T.slice(o,A).replace(/\\/g,""),A]}return[T.slice(o).replace(/\\/g,""),T.length]}function lW(T,o=0){let F=[],A=o,y=!1;while(A<T.length){let S=T[A];if(S===","){if(y||A===o)F.push("");y=!0,A++;continue}if(y=!1,S==="\\"){A+=2;continue}if(S==='"'){let[_,J]=rW(T,A+1,!0);F.push(_),A=J;continue}if(S==="}")return[F,A+1];if(S==="{"){let[_,J]=lW(T,A+1);F.push(_),A=J;continue}let[f,$]=rW(T,A,!1);F.push(f),A=$}return[F,A]}function sW(T){let[o]=lW(T,1);return o}function DJ(T){return`{${T.map((o)=>{if(Array.isArray(o))return DJ(o);if(typeof o==="string")return`"${o.replace(/\\/g,"\\\\").replace(/"/g,"\\\"")}"`;return`${o}`}).join(",")}}`}class q extends QJ{foreignKeyConfigs=[];static[M]="PgColumnBuilder";array(T){return new eW(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:F,actions:A})=>{return mS((y,S)=>{let f=new VJ(()=>{let $=y();return{columns:[T],foreignColumns:[$]}});if(S.onUpdate)f.onUpdate(S.onUpdate);if(S.onDelete)f.onDelete(S.onDelete);return f.build(o)},F,A)})}buildExtraConfigColumn(T){return new aW(T,this.config)}}class C extends GT{constructor(T,o){if(!o.uniqueName)o.uniqueName=dW(T,[o.name]);super(T,o);this.table=T}static[M]="PgColumn"}class aW extends C{static[M]="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 Ly{static[M]="IndexedColumn";constructor(T,o,F,A){this.name=T,this.keyAsName=o,this.type=F,this.indexConfig=A}name;keyAsName;type;indexConfig}class eW extends q{static[M]="PgArrayBuilder";constructor(T,o,F){super(T,"array","PgArray");this.config.baseBuilder=o,this.config.size=F}build(T){let o=this.config.baseBuilder.build(T);return new LJ(T,this.config,o)}}class LJ extends C{constructor(T,o,F,A){super(T,o);this.baseColumn=F,this.range=A,this.size=o.size}size;static[M]="PgArray";getSQLType(){return`${this.baseColumn.getSQLType()}[${typeof this.size==="number"?this.size:""}]`}mapFromDriverValue(T){if(typeof T==="string")T=sW(T);return T.map((o)=>this.baseColumn.mapFromDriverValue(o))}mapToDriverValue(T,o=!1){let F=T.map((A)=>A===null?null:w(this.baseColumn,LJ)?this.baseColumn.mapToDriverValue(A,!0):this.baseColumn.mapToDriverValue(A));if(o)return F;return DJ(F)}}class TM extends q{static[M]="PgEnumObjectColumnBuilder";constructor(T,o){super(T,"string","PgEnumObjectColumn");this.config.enum=o}build(T){return new oM(T,this.config)}}class oM extends C{static[M]="PgEnumObjectColumn";enum;enumValues=this.config.enum.enumValues;constructor(T,o){super(T,o);this.enum=o.enum}getSQLType(){return this.enum.enumName}}var tS=Symbol.for("drizzle:isPgEnum");function FM(T){return!!T&&typeof T==="function"&&tS in T&&T[tS]===!0}class AM extends q{static[M]="PgEnumColumnBuilder";constructor(T,o){super(T,"string","PgEnumColumn");this.config.enum=o}build(T){return new yM(T,this.config)}}class yM extends C{static[M]="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 hS(T,o){return Array.isArray(o)?QZ(T,[...o],void 0):VZ(T,o,void 0)}function QZ(T,o,F){let A=Object.assign((y)=>new AM(y??"",A),{enumName:T,enumValues:o,schema:F,[tS]:!0});return A}function VZ(T,o,F){let A=Object.assign((y)=>new TM(y??"",A),{enumName:T,enumValues:Object.values(o),schema:F,[tS]:!0});return A}class iT{static[M]="Subquery";constructor(T,o,F,A=!1){this._={brand:"Subquery",sql:T,selectedFields:o,alias:F,isWith:A}}}class Cy extends iT{static[M]="WithSubquery"}var SM="0.42.0";var CJ,IJ,wT={startActiveSpan(T,o){if(!CJ)return o();if(!IJ)IJ=CJ.trace.getTracer("drizzle-orm",SM);return mS((F,A)=>A.startActiveSpan(T,(y)=>{try{return o(y)}catch(S){throw y.setStatus({code:F.SpanStatusCode.ERROR,message:S instanceof Error?S.message:"Unknown error"}),S}finally{y.end()}}),CJ,IJ)}};var QT=Symbol.for("drizzle:ViewBaseConfig");var gS=Symbol.for("drizzle:Schema"),nS=Symbol.for("drizzle:Columns"),fM=Symbol.for("drizzle:ExtraConfigColumns"),kJ=Symbol.for("drizzle:OriginalName"),BJ=Symbol.for("drizzle:BaseName"),Iy=Symbol.for("drizzle:IsAlias"),$M=Symbol.for("drizzle:ExtraConfigBuilder"),DZ=Symbol.for("drizzle:IsDrizzleTable");class x{static[M]="Table";static Symbol={Name:co,Schema:gS,OriginalName:kJ,Columns:nS,ExtraConfigColumns:fM,BaseName:BJ,IsAlias:Iy,ExtraConfigBuilder:$M};[co];[kJ];[gS];[nS];[fM];[BJ];[Iy]=!1;[DZ]=!0;[$M]=void 0;constructor(T,o,F){this[co]=this[kJ]=T,this[gS]=o,this[BJ]=F}}function lT(T){return T[co]}function rF(T){return`${T[gS]??"public"}.${T[co]}`}function NJ(T){return T!==null&&T!==void 0&&typeof T.getSQL==="function"}function LZ(T){let o={sql:"",params:[]};for(let F of T)if(o.sql+=F.sql,o.params.push(...F.params),F.typings?.length){if(!o.typings)o.typings=[];o.typings.push(...F.typings)}return o}class dT{static[M]="StringChunk";value;constructor(T){this.value=Array.isArray(T)?T:[T]}getSQL(){return new b([this])}}class b{constructor(T){this.queryChunks=T}static[M]="SQL";decoder=_M;shouldInlineParams=!1;append(T){return this.queryChunks.push(...T.queryChunks),this}toQuery(T){return wT.startActiveSpan("drizzle.buildSQL",(o)=>{let F=this.buildQueryFromSourceParams(this.queryChunks,T);return o?.setAttributes({"drizzle.query.text":F.sql,"drizzle.query.params":JSON.stringify(F.params)}),F})}buildQueryFromSourceParams(T,o){let F=Object.assign({},o,{inlineParams:o.inlineParams||this.shouldInlineParams,paramStartIndex:o.paramStartIndex||{value:0}}),{casing:A,escapeName:y,escapeParam:S,prepareTyping:f,inlineParams:$,paramStartIndex:_}=F;return LZ(T.map((J)=>{if(w(J,dT))return{sql:J.value.join(""),params:[]};if(w(J,uS))return{sql:y(J.value),params:[]};if(J===void 0)return{sql:"",params:[]};if(Array.isArray(J)){let R=[new dT("(")];for(let[O,Y]of J.entries())if(R.push(Y),O<J.length-1)R.push(new dT(", "));return R.push(new dT(")")),this.buildQueryFromSourceParams(R,F)}if(w(J,b))return this.buildQueryFromSourceParams(J.queryChunks,{...F,inlineParams:$||J.shouldInlineParams});if(w(J,x)){let R=J[x.Symbol.Schema],O=J[x.Symbol.Name];return{sql:R===void 0||J[Iy]?y(O):y(R)+"."+y(O),params:[]}}if(w(J,GT)){let R=A.getColumnCasing(J);if(o.invokeSource==="indexes")return{sql:y(R),params:[]};let O=J.table[x.Symbol.Schema];return{sql:J.table[Iy]||O===void 0?y(J.table[x.Symbol.Name])+"."+y(R):y(O)+"."+y(J.table[x.Symbol.Name])+"."+y(R),params:[]}}if(w(J,Ko)){let R=J[QT].schema,O=J[QT].name;return{sql:R===void 0||J[QT].isAlias?y(O):y(R)+"."+y(O),params:[]}}if(w(J,Lo)){if(w(J.value,NF))return{sql:S(_.value++,J),params:[J],typings:["none"]};let R=J.value===null?null:J.encoder.mapToDriverValue(J.value);if(w(R,b))return this.buildQueryFromSourceParams([R],F);if($)return{sql:this.mapInlineParam(R,F),params:[]};let O=["none"];if(f)O=[f(J.encoder)];return{sql:S(_.value++,R),params:[R],typings:O}}if(w(J,NF))return{sql:S(_.value++,J),params:[J],typings:["none"]};if(w(J,b.Aliased)&&J.fieldAlias!==void 0)return{sql:y(J.fieldAlias),params:[]};if(w(J,iT)){if(J._.isWith)return{sql:y(J._.alias),params:[]};return this.buildQueryFromSourceParams([new dT("("),J._.sql,new dT(") "),new uS(J._.alias)],F)}if(FM(J)){if(J.schema)return{sql:y(J.schema)+"."+y(J.enumName),params:[]};return{sql:y(J.enumName),params:[]}}if(NJ(J)){if(J.shouldOmitSQLParens?.())return this.buildQueryFromSourceParams([J.getSQL()],F);return this.buildQueryFromSourceParams([new dT("("),J.getSQL(),new dT(")")],F)}if($)return{sql:this.mapInlineParam(J,F),params:[]};return{sql:S(_.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 F=T.toString();if(F==="[object Object]")return o(JSON.stringify(T));return o(F)}throw new Error("Unexpected param value: "+T)}getSQL(){return this}as(T){if(T===void 0)return this;return new b.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 uS{constructor(T){this.value=T}static[M]="Name";brand;getSQL(){return new b([this])}}function JM(T){return typeof T==="object"&&T!==null&&"mapToDriverValue"in T&&typeof T.mapToDriverValue==="function"}var _M={mapFromDriverValue:(T)=>T},RM={mapToDriverValue:(T)=>T},ob={..._M,...RM};class Lo{constructor(T,o=RM){this.value=T,this.encoder=o}static[M]="Param";brand;getSQL(){return new b([this])}}function X(T,...o){let F=[];if(o.length>0||T.length>0&&T[0]!=="")F.push(new dT(T[0]));for(let[A,y]of o.entries())F.push(y,new dT(T[A+1]));return new b(F)}((T)=>{function o(){return new b([])}T.empty=o;function F(_){return new b(_)}T.fromList=F;function A(_){return new b([new dT(_)])}T.raw=A;function y(_,J){let R=[];for(let[O,Y]of _.entries()){if(O>0&&J!==void 0)R.push(J);R.push(Y)}return new b(R)}T.join=y;function S(_){return new uS(_)}T.identifier=S;function f(_){return new NF(_)}T.placeholder=f;function $(_,J){return new Lo(_,J)}T.param=$})(X||(X={}));((T)=>{class o{constructor(F,A){this.sql=F,this.fieldAlias=A}static[M]="SQL.Aliased";isSelectionField=!1;getSQL(){return this.sql}clone(){return new o(this.sql,this.fieldAlias)}}T.Aliased=o})(b||(b={}));class NF{constructor(T){this.name=T}static[M]="Placeholder";getSQL(){return new b([this])}}function pJ(T,o){return T.map((F)=>{if(w(F,NF)){if(!(F.name in o))throw new Error(`No value for placeholder "${F.name}" was provided`);return o[F.name]}if(w(F,Lo)&&w(F.value,NF)){if(!(F.value.name in o))throw new Error(`No value for placeholder "${F.value.name}" was provided`);return F.encoder.mapToDriverValue(o[F.value.name])}return F})}var CZ=Symbol.for("drizzle:IsDrizzleView");class Ko{static[M]="View";[QT];[CZ]=!0;constructor({name:T,schema:o,selectedFields:F,query:A}){this[QT]={name:T,originalName:T,schema:o,selectedFields:F,query:A,isExisting:!A,isAlias:!1}}getSQL(){return new b([this])}}GT.prototype.getSQL=function(){return new b([this])};x.prototype.getSQL=function(){return new b([this])};iT.prototype.getSQL=function(){return new b([this])};class BA{constructor(T){this.table=T}static[M]="ColumnAliasProxyHandler";get(T,o){if(o==="table")return this.table;return T[o]}}class ky{constructor(T,o){this.alias=T,this.replaceOriginalName=o}static[M]="TableAliasProxyHandler";get(T,o){if(o===x.Symbol.IsAlias)return!0;if(o===x.Symbol.Name)return this.alias;if(this.replaceOriginalName&&o===x.Symbol.OriginalName)return this.alias;if(o===QT)return{...T[QT],name:this.alias,isAlias:!0};if(o===x.Symbol.Columns){let A=T[x.Symbol.Columns];if(!A)return A;let y={};return Object.keys(A).map((S)=>{y[S]=new Proxy(A[S],new BA(new Proxy(T,this)))}),y}let F=T[o];if(w(F,GT))return new Proxy(F,new BA(new Proxy(T,this)));return F}}function cS(T,o){return new Proxy(T,new ky(o,!1))}function oF(T,o){return new Proxy(T,new BA(new Proxy(T.table,new ky(o,!1))))}function jJ(T,o){return new b.Aliased(By(T.sql,o),T.fieldAlias)}function By(T,o){return X.join(T.queryChunks.map((F)=>{if(w(F,GT))return oF(F,o);if(w(F,b))return By(F,o);if(w(F,b.Aliased))return jJ(F,o);return F}))}class iS extends Error{static[M]="DrizzleError";constructor({message:T,cause:o}){super(T);this.name="DrizzleError",this.cause=o}}class xJ extends iS{static[M]="TransactionRollbackError";constructor(){super({message:"Rollback"})}}class WM{static[M]="ConsoleLogWriter";write(T){console.log(T)}}class bJ{static[M]="DefaultLogger";writer;constructor(T){this.writer=T?.writer??new WM}logQuery(T,o){let F=o.map((y)=>{try{return JSON.stringify(y)}catch{return String(y)}}),A=F.length?` -- params: [${F.join(", ")}]`:"";this.writer.write(`Query: ${T}${A}`)}}class qJ{static[M]="NoopLogger";logQuery(){}}class Mo{static[M]="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 MM(T,o,F){let A={},y=T.reduce((S,{path:f,field:$},_)=>{let J;if(w($,GT))J=$;else if(w($,b))J=$.decoder;else J=$.sql.decoder;let R=S;for(let[O,Y]of f.entries())if(O<f.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(F&&w($,GT)&&f.length===2){let E=f[0];if(!(E in A))A[E]=Q===null?lT($.table):!1;else if(typeof A[E]==="string"&&A[E]!==lT($.table))A[E]=!1}}return S},{});if(F&&Object.keys(A).length>0){for(let[S,f]of Object.entries(A))if(typeof f==="string"&&!F[f])y[S]=null}return y}function qo(T,o){return Object.entries(T).reduce((F,[A,y])=>{if(typeof A!=="string")return F;let S=o?[...o,A]:[A];if(w(y,GT)||w(y,b)||w(y,b.Aliased))F.push({path:S,field:y});else if(w(y,x))F.push(...qo(y[x.Symbol.Columns],S));else F.push(...qo(y,S));return F},[])}function Ny(T,o){let F=Object.keys(T),A=Object.keys(o);if(F.length!==A.length)return!1;for(let[y,S]of F.entries())if(S!==A[y])return!1;return!0}function dS(T,o){let F=Object.entries(o).filter(([,A])=>A!==void 0).map(([A,y])=>{if(w(y,b)||w(y,GT))return[A,y];else return[A,new Lo(y,T[x.Symbol.Columns][A])]});if(F.length===0)throw new Error("No values to set");return Object.fromEntries(F)}function OM(T,o){for(let F of o)for(let A of Object.getOwnPropertyNames(F.prototype)){if(A==="constructor")continue;Object.defineProperty(T.prototype,A,Object.getOwnPropertyDescriptor(F.prototype,A)||Object.create(null))}}function XM(T){return T[x.Symbol.Columns]}function HF(T){return w(T,iT)?T._.alias:w(T,Ko)?T[QT].name:w(T,b)?void 0:T[x.Symbol.IsAlias]?T[x.Symbol.Name]:T[x.Symbol.BaseName]}function fT(T,o){return{name:typeof T==="string"&&T.length>0?T:"",config:typeof T==="object"?T:o}}function YM(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 pF extends q{static[M]="PgIntColumnBaseBuilder";generatedAlwaysAsIdentity(T){if(T){let{name:o,...F}=T;this.config.generatedIdentity={type:"always",sequenceName:o,sequenceOptions:F}}else this.config.generatedIdentity={type:"always"};return this.config.hasDefault=!0,this.config.notNull=!0,this}generatedByDefaultAsIdentity(T){if(T){let{name:o,...F}=T;this.config.generatedIdentity={type:"byDefault",sequenceName:o,sequenceOptions:F}}else this.config.generatedIdentity={type:"byDefault"};return this.config.hasDefault=!0,this.config.notNull=!0,this}}class ZM extends pF{static[M]="PgBigInt53Builder";constructor(T){super(T,"number","PgBigInt53")}build(T){return new HM(T,this.config)}}class HM extends C{static[M]="PgBigInt53";getSQLType(){return"bigint"}mapFromDriverValue(T){if(typeof T==="number")return T;return Number(T)}}class GM extends pF{static[M]="PgBigInt64Builder";constructor(T){super(T,"bigint","PgBigInt64")}build(T){return new wM(T,this.config)}}class wM extends C{static[M]="PgBigInt64";getSQLType(){return"bigint"}mapFromDriverValue(T){return BigInt(T)}}function EM(T,o){let{name:F,config:A}=fT(T,o);if(A.mode==="number")return new ZM(F);return new GM(F)}class KM extends q{static[M]="PgBigSerial53Builder";constructor(T){super(T,"number","PgBigSerial53");this.config.hasDefault=!0,this.config.notNull=!0}build(T){return new UM(T,this.config)}}class UM extends C{static[M]="PgBigSerial53";getSQLType(){return"bigserial"}mapFromDriverValue(T){if(typeof T==="number")return T;return Number(T)}}class zM extends q{static[M]="PgBigSerial64Builder";constructor(T){super(T,"bigint","PgBigSerial64");this.config.hasDefault=!0}build(T){return new QM(T,this.config)}}class QM extends C{static[M]="PgBigSerial64";getSQLType(){return"bigserial"}mapFromDriverValue(T){return BigInt(T)}}function VM(T,o){let{name:F,config:A}=fT(T,o);if(A.mode==="number")return new KM(F);return new zM(F)}class DM extends q{static[M]="PgBooleanBuilder";constructor(T){super(T,"boolean","PgBoolean")}build(T){return new LM(T,this.config)}}class LM extends C{static[M]="PgBoolean";getSQLType(){return"boolean"}}function py(T){return new DM(T??"")}class CM extends q{static[M]="PgCharBuilder";constructor(T,o){super(T,"string","PgChar");this.config.length=o.length,this.config.enumValues=o.enum}build(T){return new IM(T,this.config)}}class IM extends C{static[M]="PgChar";length=this.config.length;enumValues=this.config.enumValues;getSQLType(){return this.length===void 0?"char":`char(${this.length})`}}function kM(T,o={}){let{name:F,config:A}=fT(T,o);return new CM(F,A)}class BM extends q{static[M]="PgCidrBuilder";constructor(T){super(T,"string","PgCidr")}build(T){return new NM(T,this.config)}}class NM extends C{static[M]="PgCidr";getSQLType(){return"cidr"}}function pM(T){return new BM(T??"")}class jM extends q{static[M]="PgCustomColumnBuilder";constructor(T,o,F){super(T,"custom","PgCustomColumn");this.config.fieldConfig=o,this.config.customTypeParams=F}build(T){return new xM(T,this.config)}}class xM extends C{static[M]="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 bM(T){return(o,F)=>{let{name:A,config:y}=fT(o,F);return new jM(A,y,T)}}class GF extends q{static[M]="PgDateColumnBaseBuilder";defaultNow(){return this.default(X`now()`)}}class qM extends GF{static[M]="PgDateBuilder";constructor(T){super(T,"date","PgDate")}build(T){return new rS(T,this.config)}}class rS extends C{static[M]="PgDate";getSQLType(){return"date"}mapFromDriverValue(T){return new Date(T)}mapToDriverValue(T){return T.toISOString()}}class vM extends GF{static[M]="PgDateStringBuilder";constructor(T){super(T,"string","PgDateString")}build(T){return new lS(T,this.config)}}class lS extends C{static[M]="PgDateString";getSQLType(){return"date"}}function PM(T,o){let{name:F,config:A}=fT(T,o);if(A?.mode==="date")return new qM(F);return new vM(F)}class mM extends q{static[M]="PgDoublePrecisionBuilder";constructor(T){super(T,"number","PgDoublePrecision")}build(T){return new tM(T,this.config)}}class tM extends C{static[M]="PgDoublePrecision";getSQLType(){return"double precision"}mapFromDriverValue(T){if(typeof T==="string")return Number.parseFloat(T);return T}}function hM(T){return new mM(T??"")}class gM extends q{static[M]="PgInetBuilder";constructor(T){super(T,"string","PgInet")}build(T){return new nM(T,this.config)}}class nM extends C{static[M]="PgInet";getSQLType(){return"inet"}}function uM(T){return new gM(T??"")}class cM extends pF{static[M]="PgIntegerBuilder";constructor(T){super(T,"number","PgInteger")}build(T){return new iM(T,this.config)}}class iM extends C{static[M]="PgInteger";getSQLType(){return"integer"}mapFromDriverValue(T){if(typeof T==="string")return Number.parseInt(T);return T}}function sS(T){return new cM(T??"")}class dM extends q{static[M]="PgIntervalBuilder";constructor(T,o){super(T,"string","PgInterval");this.config.intervalConfig=o}build(T){return new rM(T,this.config)}}class rM extends C{static[M]="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 lM(T,o={}){let{name:F,config:A}=fT(T,o);return new dM(F,A)}class sM extends q{static[M]="PgJsonBuilder";constructor(T){super(T,"json","PgJson")}build(T){return new aS(T,this.config)}}class aS extends C{static[M]="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 aM(T){return new sM(T??"")}class eM extends q{static[M]="PgJsonbBuilder";constructor(T){super(T,"json","PgJsonb")}build(T){return new eS(T,this.config)}}class eS extends C{static[M]="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 TO(T){return new eM(T??"")}class oO extends q{static[M]="PgLineBuilder";constructor(T){super(T,"array","PgLine")}build(T){return new FO(T,this.config)}}class FO extends C{static[M]="PgLine";getSQLType(){return"line"}mapFromDriverValue(T){let[o,F,A]=T.slice(1,-1).split(",");return[Number.parseFloat(o),Number.parseFloat(F),Number.parseFloat(A)]}mapToDriverValue(T){return`{${T[0]},${T[1]},${T[2]}}`}}class AO extends q{static[M]="PgLineABCBuilder";constructor(T){super(T,"json","PgLineABC")}build(T){return new yO(T,this.config)}}class yO extends C{static[M]="PgLineABC";getSQLType(){return"line"}mapFromDriverValue(T){let[o,F,A]=T.slice(1,-1).split(",");return{a:Number.parseFloat(o),b:Number.parseFloat(F),c:Number.parseFloat(A)}}mapToDriverValue(T){return`{${T.a},${T.b},${T.c}}`}}function SO(T,o){let{name:F,config:A}=fT(T,o);if(!A?.mode||A.mode==="tuple")return new oO(F);return new AO(F)}class fO extends q{static[M]="PgMacaddrBuilder";constructor(T){super(T,"string","PgMacaddr")}build(T){return new $O(T,this.config)}}class $O extends C{static[M]="PgMacaddr";getSQLType(){return"macaddr"}}function JO(T){return new fO(T??"")}class _O extends q{static[M]="PgMacaddr8Builder";constructor(T){super(T,"string","PgMacaddr8")}build(T){return new RO(T,this.config)}}class RO extends C{static[M]="PgMacaddr8";getSQLType(){return"macaddr8"}}function WO(T){return new _O(T??"")}class MO extends q{static[M]="PgNumericBuilder";constructor(T,o,F){super(T,"string","PgNumeric");this.config.precision=o,this.config.scale=F}build(T){return new Tf(T,this.config)}}class Tf extends C{static[M]="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 OO extends q{static[M]="PgNumericNumberBuilder";constructor(T,o,F){super(T,"number","PgNumericNumber");this.config.precision=o,this.config.scale=F}build(T){return new XO(T,this.config)}}class XO extends C{static[M]="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 YO extends q{static[M]="PgNumericBigIntBuilder";constructor(T,o,F){super(T,"bigint","PgNumericBigInt");this.config.precision=o,this.config.scale=F}build(T){return new ZO(T,this.config)}}class ZO extends C{static[M]="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 HO(T,o){let{name:F,config:A}=fT(T,o),y=A?.mode;return y==="number"?new OO(F,A?.precision,A?.scale):y==="bigint"?new YO(F,A?.precision,A?.scale):new MO(F,A?.precision,A?.scale)}class GO extends q{static[M]="PgPointTupleBuilder";constructor(T){super(T,"array","PgPointTuple")}build(T){return new wO(T,this.config)}}class wO extends C{static[M]="PgPointTuple";getSQLType(){return"point"}mapFromDriverValue(T){if(typeof T==="string"){let[o,F]=T.slice(1,-1).split(",");return[Number.parseFloat(o),Number.parseFloat(F)]}return[T.x,T.y]}mapToDriverValue(T){return`(${T[0]},${T[1]})`}}class EO extends q{static[M]="PgPointObjectBuilder";constructor(T){super(T,"json","PgPointObject")}build(T){return new KO(T,this.config)}}class KO extends C{static[M]="PgPointObject";getSQLType(){return"point"}mapFromDriverValue(T){if(typeof T==="string"){let[o,F]=T.slice(1,-1).split(",");return{x:Number.parseFloat(o),y:Number.parseFloat(F)}}return T}mapToDriverValue(T){return`(${T.x},${T.y})`}}function UO(T,o){let{name:F,config:A}=fT(T,o);if(!A?.mode||A.mode==="tuple")return new GO(F);return new EO(F)}function IZ(T){let o=[];for(let F=0;F<T.length;F+=2)o.push(Number.parseInt(T.slice(F,F+2),16));return new Uint8Array(o)}function zO(T,o){let F=new ArrayBuffer(8),A=new DataView(F);for(let y=0;y<8;y++)A.setUint8(y,T[o+y]);return A.getFloat64(0,!0)}function vJ(T){let o=IZ(T),F=0,A=o[F];F+=1;let y=new DataView(o.buffer),S=y.getUint32(F,A===1);F+=4;let f;if(S&536870912)f=y.getUint32(F,A===1),F+=4;if((S&65535)===1){let $=zO(o,F);F+=8;let _=zO(o,F);return F+=8,[$,_]}throw new Error("Unsupported geometry type")}class QO extends q{static[M]="PgGeometryBuilder";constructor(T){super(T,"array","PgGeometry")}build(T){return new VO(T,this.config)}}class VO extends C{static[M]="PgGeometry";getSQLType(){return"geometry(point)"}mapFromDriverValue(T){return vJ(T)}mapToDriverValue(T){return`point(${T[0]} ${T[1]})`}}class DO extends q{static[M]="PgGeometryObjectBuilder";constructor(T){super(T,"json","PgGeometryObject")}build(T){return new LO(T,this.config)}}class LO extends C{static[M]="PgGeometryObject";getSQLType(){return"geometry(point)"}mapFromDriverValue(T){let o=vJ(T);return{x:o[0],y:o[1]}}mapToDriverValue(T){return`point(${T.x} ${T.y})`}}function CO(T,o){let{name:F,config:A}=fT(T,o);if(!A?.mode||A.mode==="tuple")return new QO(F);return new DO(F)}class IO extends q{static[M]="PgRealBuilder";constructor(T,o){super(T,"number","PgReal");this.config.length=o}build(T){return new kO(T,this.config)}}class kO extends C{static[M]="PgReal";constructor(T,o){super(T,o)}getSQLType(){return"real"}mapFromDriverValue=(T)=>{if(typeof T==="string")return Number.parseFloat(T);return T}}function BO(T){return new IO(T??"")}class NO extends q{static[M]="PgSerialBuilder";constructor(T){super(T,"number","PgSerial");this.config.hasDefault=!0,this.config.notNull=!0}build(T){return new pO(T,this.config)}}class pO extends C{static[M]="PgSerial";getSQLType(){return"serial"}}function jO(T){return new NO(T??"")}class xO extends pF{static[M]="PgSmallIntBuilder";constructor(T){super(T,"number","PgSmallInt")}build(T){return new bO(T,this.config)}}class bO extends C{static[M]="PgSmallInt";getSQLType(){return"smallint"}mapFromDriverValue=(T)=>{if(typeof T==="string")return Number(T);return T}}function qO(T){return new xO(T??"")}class vO extends q{static[M]="PgSmallSerialBuilder";constructor(T){super(T,"number","PgSmallSerial");this.config.hasDefault=!0,this.config.notNull=!0}build(T){return new PO(T,this.config)}}class PO extends C{static[M]="PgSmallSerial";getSQLType(){return"smallserial"}}function mO(T){return new vO(T??"")}class tO extends q{static[M]="PgTextBuilder";constructor(T,o){super(T,"string","PgText");this.config.enumValues=o.enum}build(T){return new hO(T,this.config)}}class hO extends C{static[M]="PgText";enumValues=this.config.enumValues;getSQLType(){return"text"}}function gO(T,o={}){let{name:F,config:A}=fT(T,o);return new tO(F,A)}class nO extends GF{constructor(T,o,F){super(T,"string","PgTime");this.withTimezone=o,this.precision=F,this.config.withTimezone=o,this.config.precision=F}static[M]="PgTimeBuilder";build(T){return new of(T,this.config)}}class of extends C{static[M]="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 uO(T,o={}){let{name:F,config:A}=fT(T,o);return new nO(F,A.withTimezone??!1,A.precision)}class cO extends GF{static[M]="PgTimestampBuilder";constructor(T,o,F){super(T,"date","PgTimestamp");this.config.withTimezone=o,this.config.precision=F}build(T){return new Ff(T,this.config)}}class Ff extends C{static[M]="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 iO extends GF{static[M]="PgTimestampStringBuilder";constructor(T,o,F){super(T,"string","PgTimestampString");this.config.withTimezone=o,this.config.precision=F}build(T){return new Af(T,this.config)}}class Af extends C{static[M]="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 io(T,o={}){let{name:F,config:A}=fT(T,o);if(A?.mode==="string")return new iO(F,A.withTimezone??!1,A.precision);return new cO(F,A?.withTimezone??!1,A?.precision)}class dO extends q{static[M]="PgUUIDBuilder";constructor(T){super(T,"string","PgUUID")}defaultRandom(){return this.default(X`gen_random_uuid()`)}build(T){return new yf(T,this.config)}}class yf extends C{static[M]="PgUUID";getSQLType(){return"uuid"}}function Co(T){return new dO(T??"")}class rO extends q{static[M]="PgVarcharBuilder";constructor(T,o){super(T,"string","PgVarchar");this.config.length=o.length,this.config.enumValues=o.enum}build(T){return new lO(T,this.config)}}class lO extends C{static[M]="PgVarchar";length=this.config.length;enumValues=this.config.enumValues;getSQLType(){return this.length===void 0?"varchar":`varchar(${this.length})`}}function $o(T,o={}){let{name:F,config:A}=fT(T,o);return new rO(F,A)}class sO extends q{static[M]="PgBinaryVectorBuilder";constructor(T,o){super(T,"string","PgBinaryVector");this.config.dimensions=o.dimensions}build(T){return new aO(T,this.config)}}class aO extends C{static[M]="PgBinaryVector";dimensions=this.config.dimensions;getSQLType(){return`bit(${this.dimensions})`}}function eO(T,o){let{name:F,config:A}=fT(T,o);return new sO(F,A)}class T2 extends q{static[M]="PgHalfVectorBuilder";constructor(T,o){super(T,"array","PgHalfVector");this.config.dimensions=o.dimensions}build(T){return new o2(T,this.config)}}class o2 extends C{static[M]="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 F2(T,o){let{name:F,config:A}=fT(T,o);return new T2(F,A)}class A2 extends q{static[M]="PgSparseVectorBuilder";constructor(T,o){super(T,"string","PgSparseVector");this.config.dimensions=o.dimensions}build(T){return new y2(T,this.config)}}class y2 extends C{static[M]="PgSparseVector";dimensions=this.config.dimensions;getSQLType(){return`sparsevec(${this.dimensions})`}}function S2(T,o){let{name:F,config:A}=fT(T,o);return new A2(F,A)}class f2 extends q{static[M]="PgVectorBuilder";constructor(T,o){super(T,"array","PgVector");this.config.dimensions=o.dimensions}build(T){return new $2(T,this.config)}}class $2 extends C{static[M]="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 J2(T,o){let{name:F,config:A}=fT(T,o);return new f2(F,A)}function _2(){return{bigint:EM,bigserial:VM,boolean:py,char:kM,cidr:pM,customType:bM,date:PM,doublePrecision:hM,inet:uM,integer:sS,interval:lM,json:aM,jsonb:TO,line:SO,macaddr:JO,macaddr8:WO,numeric:HO,point:UO,geometry:CO,real:BO,serial:jO,smallint:qO,smallserial:mO,text:gO,time:uO,timestamp:io,uuid:Co,varchar:$o,bit:eO,halfvec:F2,sparsevec:S2,vector:J2}}var PJ=Symbol.for("drizzle:PgInlineForeignKeys"),R2=Symbol.for("drizzle:EnableRLS");class eT extends x{static[M]="PgTable";static Symbol=Object.assign({},x.Symbol,{InlineForeignKeys:PJ,EnableRLS:R2});[PJ]=[];[R2]=!1;[x.Symbol.ExtraConfigBuilder]=void 0;[x.Symbol.ExtraConfigColumns]={}}function kZ(T,o,F,A,y=T){let S=new eT(T,A,y),f=typeof o==="function"?o(_2()):o,$=Object.fromEntries(Object.entries(f).map(([R,O])=>{let Y=O;Y.setName(R);let H=Y.build(S);return S[PJ].push(...Y.buildForeignKeys(H,S)),[R,H]})),_=Object.fromEntries(Object.entries(f).map(([R,O])=>{let Y=O;Y.setName(R);let H=Y.buildExtraConfigColumn(S);return[R,H]})),J=Object.assign(S,$);if(J[x.Symbol.Columns]=$,J[x.Symbol.ExtraConfigColumns]=_,F)J[eT.Symbol.ExtraConfigBuilder]=F;return Object.assign(J,{enableRLS:()=>{return J[eT.Symbol.EnableRLS]=!0,J}})}var jF=(T,o,F)=>{return kZ(T,o,F,void 0)};function W2(...T){if(T[0].columns)return new jy(T[0].columns,T[0].name);return new jy(T)}class jy{static[M]="PgPrimaryKeyBuilder";columns;name;constructor(T,o){this.columns=T,this.name=o}build(T){return new M2(T,this.columns,this.name)}}class M2{constructor(T,o,F){this.table=T,this.columns=o,this.name=F}static[M]="PgPrimaryKey";columns;name;getName(){return this.name??`${this.table[eT.Symbol.Name]}_${this.columns.map((T)=>T.name).join("_")}_pk`}}function Uo(T,o){if(JM(o)&&!NJ(T)&&!w(T,Lo)&&!w(T,NF)&&!w(T,GT)&&!w(T,x)&&!w(T,Ko))return new Lo(T,o);return T}var Sf=(T,o)=>{return X`${T} = ${Uo(o,T)}`},O2=(T,o)=>{return X`${T} <> ${Uo(o,T)}`};function xy(...T){let o=T.filter((F)=>F!==void 0);if(o.length===0)return;if(o.length===1)return new b(o);return new b([new dT("("),X.join(o,new dT(" and ")),new dT(")")])}function X2(...T){let o=T.filter((F)=>F!==void 0);if(o.length===0)return;if(o.length===1)return new b(o);return new b([new dT("("),X.join(o,new dT(" or ")),new dT(")")])}function Y2(T){return X`not ${T}`}var Z2=(T,o)=>{return X`${T} > ${Uo(o,T)}`},H2=(T,o)=>{return X`${T} >= ${Uo(o,T)}`},G2=(T,o)=>{return X`${T} < ${Uo(o,T)}`},w2=(T,o)=>{return X`${T} <= ${Uo(o,T)}`};function E2(T,o){if(Array.isArray(o)){if(o.length===0)return X`false`;return X`${T} in ${o.map((F)=>Uo(F,T))}`}return X`${T} in ${Uo(o,T)}`}function K2(T,o){if(Array.isArray(o)){if(o.length===0)return X`true`;return X`${T} not in ${o.map((F)=>Uo(F,T))}`}return X`${T} not in ${Uo(o,T)}`}function U2(T){return X`${T} is null`}function z2(T){return X`${T} is not null`}function Q2(T){return X`exists ${T}`}function V2(T){return X`not exists ${T}`}function D2(T,o,F){return X`${T} between ${Uo(o,T)} and ${Uo(F,T)}`}function L2(T,o,F){return X`${T} not between ${Uo(o,T)} and ${Uo(F,T)}`}function C2(T,o){return X`${T} like ${o}`}function I2(T,o){return X`${T} not like ${o}`}function k2(T,o){return X`${T} ilike ${o}`}function B2(T,o){return X`${T} not ilike ${o}`}function N2(T){return X`${T} asc`}function p2(T){return X`${T} desc`}class mJ{constructor(T,o,F){this.sourceTable=T,this.referencedTable=o,this.relationName=F,this.referencedTableName=o[x.Symbol.Name]}static[M]="Relation";referencedTableName;fieldName}class j2{constructor(T,o){this.table=T,this.config=o}static[M]="Relations"}class xF extends mJ{constructor(T,o,F,A){super(T,o,F?.relationName);this.config=F,this.isNullable=A}static[M]="One";withFieldName(T){let o=new xF(this.sourceTable,this.referencedTable,this.config,this.isNullable);return o.fieldName=T,o}}class by extends mJ{constructor(T,o,F){super(T,o,F?.relationName);this.config=F}static[M]="Many";withFieldName(T){let o=new by(this.sourceTable,this.referencedTable,this.config);return o.fieldName=T,o}}function x2(){return{and:xy,between:D2,eq:Sf,exists:Q2,gt:Z2,gte:H2,ilike:k2,inArray:E2,isNull:U2,isNotNull:z2,like:C2,lt:G2,lte:w2,ne:O2,not:Y2,notBetween:L2,notExists:V2,notLike:I2,notIlike:B2,notInArray:K2,or:X2,sql:X}}function b2(){return{sql:X,asc:N2,desc:p2}}function q2(T,o){if(Object.keys(T).length===1&&"default"in T&&!w(T.default,x))T=T.default;let F={},A={},y={};for(let[S,f]of Object.entries(T))if(w(f,x)){let $=rF(f),_=A[$];F[$]=S,y[S]={tsName:S,dbName:f[x.Symbol.Name],schema:f[x.Symbol.Schema],columns:f[x.Symbol.Columns],relations:_?.relations??{},primaryKey:_?.primaryKey??[]};for(let R of Object.values(f[x.Symbol.Columns]))if(R.primary)y[S].primaryKey.push(R);let J=f[x.Symbol.ExtraConfigBuilder]?.(f[x.Symbol.ExtraConfigColumns]);if(J){for(let R of Object.values(J))if(w(R,jy))y[S].primaryKey.push(...R.columns)}}else if(w(f,j2)){let $=rF(f.table),_=F[$],J=f.config(o(f.table)),R;for(let[O,Y]of Object.entries(J))if(_){let H=y[_];if(H.relations[O]=Y,R)H.primaryKey.push(...R)}else{if(!($ in A))A[$]={relations:{},primaryKey:R};A[$].relations[O]=Y}}return{tables:y,tableNamesMap:F}}function BZ(T){return function o(F,A){return new xF(T,F,A,A?.fields.reduce((y,S)=>y&&S.notNull,!0)??!1)}}function NZ(T){return function o(F,A){return new by(T,F,A)}}function v2(T,o,F){if(w(F,xF)&&F.config)return{fields:F.config.fields,references:F.config.references};let A=o[rF(F.referencedTable)];if(!A)throw new Error(`Table "${F.referencedTable[x.Symbol.Name]}" not found in schema`);let y=T[A];if(!y)throw new Error(`Table "${A}" not found in schema`);let S=F.sourceTable,f=o[rF(S)];if(!f)throw new Error(`Table "${S[x.Symbol.Name]}" not found in schema`);let $=[];for(let _ of Object.values(y.relations))if(F.relationName&&F!==_&&_.relationName===F.relationName||!F.relationName&&_.referencedTable===F.sourceTable)$.push(_);if($.length>1)throw F.relationName?new Error(`There are multiple relations with name "${F.relationName}" in table "${A}"`):new Error(`There are multiple relations between "${A}" and "${F.sourceTable[x.Symbol.Name]}". Please specify relation name`);if($[0]&&w($[0],xF)&&$[0].config)return{fields:$[0].config.references,references:$[0].config.fields};throw new Error(`There is not enough information to infer relation "${f}.${F.fieldName}"`)}function P2(T){return{one:BZ(T),many:NZ(T)}}function ff(T,o,F,A,y=(S)=>S){let S={};for(let[f,$]of A.entries())if($.isJson){let _=o.relations[$.tsKey],J=F[f],R=typeof J==="string"?JSON.parse(J):J;S[$.tsKey]=w(_,xF)?R&&ff(T,T[$.relationTableTsKey],R,$.selection,y):R.map((O)=>ff(T,T[$.relationTableTsKey],O,$.selection,y))}else{let _=y(F[f]),J=$.field,R;if(w(J,GT))R=J;else if(w(J,b))R=J.decoder;else R=J.sql.decoder;S[$.tsKey]=_===null?null:R.mapFromDriverValue(_)}return S}import F5 from"os";import A5 from"fs";var $f=new Map,tJ=new Map,hJ=Symbol("OriginError"),NA={};class vo extends Promise{constructor(T,o,F,A,y={}){let S,f;super(($,_)=>{S=$,f=_});this.tagged=Array.isArray(T.raw),this.strings=T,this.args=o,this.handler=F,this.canceller=A,this.options=y,this.state=null,this.statement=null,this.resolve=($)=>(this.active=!1,S($)),this.reject=($)=>(this.active=!1,f($)),this.active=!1,this.cancelled=null,this.executed=!1,this.signature="",this[hJ]=this.handler.debug?new Error:this.tagged&&pZ(this.strings)}get origin(){return(this.handler.debug?this[hJ].stack:this.tagged&&tJ.has(this.strings)?tJ.get(this.strings):tJ.set(this.strings,this[hJ].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 F;return{[Symbol.asyncIterator]:()=>({next:()=>{if(this.executed&&!this.active)return{done:!0};F&&F();let A=new Promise((y,S)=>{this.cursorFn=(f)=>{return y({value:f,done:!1}),new Promise(($)=>F=$)},this.resolve=()=>(this.active=!1,y({done:!0})),this.reject=(f)=>(this.active=!1,S(f))});return this.execute(),A},return(){return F&&F(NA),{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 pZ(T){if($f.has(T))return $f.get(T);let o=Error.stackTraceLimit;return Error.stackTraceLimit=4,$f.set(T,new Error),Error.stackTraceLimit=o,$f.get(T)}class pA extends Error{constructor(T){super(T.message);this.name=this.constructor.name,Object.assign(this,T)}}var qT={connection:m2,postgres:t2,generic:h2,notSupported:g2};function m2(T,o,F){let{host:A,port:y}=F||o,S=Object.assign(new Error("write "+T+" "+(o.path||A+":"+y)),{code:T,errno:T,address:o.path||A},o.path?{}:{port:y});return Error.captureStackTrace(S,m2),S}function t2(T){let o=new pA(T);return Error.captureStackTrace(o,t2),o}function h2(T,o){let F=Object.assign(new Error(T+": "+o),{code:T});return Error.captureStackTrace(F,h2),F}function g2(T){let o=Object.assign(new Error(T+" (B) is not supported"),{code:"MESSAGE_NOT_SUPPORTED",name:T});return Error.captureStackTrace(o,g2),o}var jZ={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 Rf{then(){gJ()}catch(){gJ()}finally(){gJ()}}class my extends Rf{constructor(T){super();this.value=Of(T)}}class FF extends Rf{constructor(T,o,F){super();this.value=T,this.type=o,this.array=F}}class Wf extends Rf{constructor(T,o){super();this.first=T,this.rest=o}build(T,o,F,A){let y=xZ.map(([S,f])=>({fn:f,i:T.search(S)})).sort((S,f)=>S.i-f.i).pop();return y.i===-1?dJ(this.first,A):y.fn(this.first,this.rest,o,F,A)}}function Mf(T,o,F,A){let y=T instanceof FF?T.value:T;if(y===void 0){if(T instanceof FF?T.value=A.transform.undefined:y=T=A.transform.undefined,y===void 0)throw qT.generic("UNDEFINED_VALUE","Undefined values are not allowed")}return"$"+F.push(T instanceof FF?(o.push(T.value),T.array?T.array[T.type||_f(T.value)]||T.type||i2(T.value):T.type):(o.push(T),_f(T)))}var u2=r2(jZ);function cJ(T,o,F,A,y,S){for(let f=1;f<T.strings.length;f++)o+=iJ(o,F,A,y,S)+T.strings[f],F=T.args[f];return o}function iJ(T,o,F,A,y){return o instanceof Wf?o.build(T,F,A,y):o instanceof vo?uJ(o,F,A,y):o instanceof my?o.value:o&&o[0]instanceof vo?o.reduce((S,f)=>S+" "+uJ(f,F,A,y),""):Mf(o,F,A,y)}function uJ(T,o,F,A){return T.fragment=!0,cJ(T,T.strings[0],T.args[0],o,F,A)}function c2(T,o,F,A,y){return T.map((S)=>"("+A.map((f)=>iJ("values",S[f],o,F,y)).join(",")+")").join(",")}function n2(T,o,F,A,y){let S=Array.isArray(T[0]),f=o.length?o.flat():Object.keys(S?T[0]:T);return c2(S?T:[T],F,A,f,y)}function Jf(T,o,F,A,y){if(typeof T==="string"&&(T=[T].concat(o)),Array.isArray(T))return dJ(T,y);let S;return(o.length?o.flat():Object.keys(T)).map(($)=>{return S=T[$],(S instanceof vo?uJ(S,F,A,y):S instanceof my?S.value:Mf(S,F,A,y))+" as "+Of(y.transform.column.to?y.transform.column.to($):$)}).join(",")}var xZ=Object.entries({values:n2,in:(...T)=>{let o=n2(...T);return o==="()"?"(null)":o},select:Jf,as:Jf,returning:Jf,"\\(":Jf,update(T,o,F,A,y){return(o.length?o.flat():Object.keys(T)).map((S)=>Of(y.transform.column.to?y.transform.column.to(S):S)+"="+iJ("values",T[S],F,A,y))},insert(T,o,F,A,y){let S=o.length?o.flat():Object.keys(Array.isArray(T)?T[0]:T);return"("+dJ(S,y)+")values"+c2(Array.isArray(T)?T:[T],F,A,S,y)}}).map(([T,o])=>[new RegExp("((?:^|[\\s(])"+T+"(?:$|[\\s(]))(?![\\s\\S]*\\1)","i"),o]);function gJ(){throw qT.generic("NOT_TAGGED_CALL","Query not called as a tagged template literal")}var{serializers:bZ,parsers:qZ}=u2;function i2(T){if(Array.isArray(T))return i2(T[0]);return typeof T==="string"?1009:0}var d2=function(T){let o=r2(T||{});return{serializers:Object.assign({},bZ,o.serializers),parsers:Object.assign({},qZ,o.parsers)}};function r2(T){return Object.keys(T).reduce((o,F)=>{if(T[F].from&&[].concat(T[F].from).forEach((A)=>o.parsers[A]=T[F].parse),T[F].serialize)o.serializers[T[F].to]=T[F].serialize,T[F].from&&[].concat(T[F].from).forEach((A)=>o.serializers[A]=T[F].serialize);return o},{parsers:{},serializers:{}})}function dJ(T,{transform:{column:o}}){return T.map((F)=>Of(o.to?o.to(F):F)).join(",")}var Of=function T(o){return'"'+o.replace(/"/g,'""').replace(/\./g,'"."')+'"'},_f=function T(o){return o instanceof FF?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},vZ=/\\/g,PZ=/"/g;function mZ(T){return T.replace(vZ,"\\\\").replace(PZ,"\\\"")}var l2=function T(o,F,A,y){if(Array.isArray(o)===!1)return o;if(!o.length)return"{}";let S=o[0],f=y===1020?";":",";if(Array.isArray(S)&&!S.type)return"{"+o.map(($)=>T($,F,A,y)).join(f)+"}";return"{"+o.map(($)=>{if($===void 0){if($=A.transform.undefined,$===void 0)throw qT.generic("UNDEFINED_VALUE","Undefined values are not allowed")}return $===null?"null":'"'+mZ(F?F($.type?$.value:$):""+$)+'"'}).join(f)+"}"},nJ={i:0,char:null,str:"",quoted:!1,last:0},s2=function T(o,F,A){return nJ.i=nJ.last=0,a2(nJ,o,F,A)};function a2(T,o,F,A){let y=[],S=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==='"')y.push(F?F(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,y.push(a2(T,o,F,A));else if(T.char==="}"){T.quoted=!1,T.last<T.i&&y.push(F?F(o.slice(T.last,T.i)):o.slice(T.last,T.i)),T.last=T.i+1;break}else if(T.char===S&&T.p!=="}"&&T.p!=='"')y.push(F?F(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&&y.push(F?F(o.slice(T.last,T.i+1)):o.slice(T.last,T.i+1)),y}var lF=(T)=>{let o=T[0];for(let F=1;F<T.length;F++)o+=T[F]==="_"?T[++F].toUpperCase():T[F];return o},sF=(T)=>{let o=T[0].toUpperCase();for(let F=1;F<T.length;F++)o+=T[F]==="_"?T[++F].toUpperCase():T[F];return o},aF=(T)=>T.replace(/_/g,"-"),qy=(T)=>T.replace(/([A-Z])/g,"_$1").toLowerCase(),vy=(T)=>(T.slice(0,1)+T.slice(1).replace(/([A-Z])/g,"_$1")).toLowerCase(),Py=(T)=>T.replace(/-/g,"_");function rJ(T){return function o(F,A){return typeof F==="object"&&F!==null&&(A.type===114||A.type===3802)?Array.isArray(F)?F.map((y)=>o(y,A)):Object.entries(F).reduce((y,[S,f])=>Object.assign(y,{[T(S)]:o(f,A)}),{}):F}}lF.column={from:lF};lF.value={from:rJ(lF)};qy.column={to:qy};var lJ={...lF};lJ.column.to=qy;sF.column={from:sF};sF.value={from:rJ(sF)};vy.column={to:vy};var sJ={...sF};sJ.column.to=vy;aF.column={from:aF};aF.value={from:rJ(aF)};Py.column={to:Py};var aJ={...aF};aJ.column.to=Py;import e2 from"net";import nZ from"tls";import ty from"crypto";import eJ from"stream";import{performance as T4}from"perf_hooks";class eF 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=tZ;function tZ(T=[]){let o=T.slice(),F=0;return{get length(){return o.length-F},remove:(A)=>{let y=o.indexOf(A);return y===-1?null:(o.splice(y,1),A)},push:(A)=>(o.push(A),A),shift:()=>{let A=o[F++];if(F===o.length)F=0,o=[];else o[F-1]=void 0;return A}}}var Jo=Buffer.allocUnsafe(256),hZ="BCcDdEFfHPpQSX".split("").reduce((T,o)=>{let F=o.charCodeAt(0);return T[o]=()=>{return Jo[0]=F,YT.i=5,YT},T},{}),YT=Object.assign(gZ,hZ,{N:String.fromCharCode(0),i:0,inc(T){return YT.i+=T,YT},str(T){let o=Buffer.byteLength(T);return Xf(o),YT.i+=Jo.write(T,YT.i,o,"utf8"),YT},i16(T){return Xf(2),Jo.writeUInt16BE(T,YT.i),YT.i+=2,YT},i32(T,o){if(o||o===0)return Jo.writeUInt32BE(T,o),YT;return Xf(4),Jo.writeUInt32BE(T,YT.i),YT.i+=4,YT},z(T){return Xf(T),Jo.fill(0,YT.i,YT.i+T),YT.i+=T,YT},raw(T){return Jo=Buffer.concat([Jo.subarray(0,YT.i),T]),YT.i=Jo.length,YT},end(T=1){Jo.writeUInt32BE(YT.i-T,T);let o=Jo.subarray(0,YT.i);return YT.i=0,Jo=Buffer.allocUnsafe(256),o}}),u=YT;function Xf(T){if(Jo.length-YT.i<T){let o=Jo,F=o.length;Jo=Buffer.allocUnsafe(F+(F>>1)+T),o.copy(Jo)}}function gZ(){return YT.i=0,YT}var F_=A4,uZ=1,bF=u().S().end(),o4=u().H().end(),cZ=u().i32(8).i32(80877103).end(8),iZ=Buffer.concat([u().E().str(u.N).i32(0).end(),bF]),dZ=u().D().str("S").str(u.N).end(),jA=()=>{},rZ=new Set(["FetchPreparedStatement","RevalidateCachedQuery","transformAssignedExpr"]),lZ={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 A4(T,o={},{onopen:F=jA,onend:A=jA,onclose:y=jA}={}){let{ssl:S,max:f,user:$,host:_,port:J,database:R,parsers:O,transform:Y,onnotice:H,onnotify:Q,onparameter:E,max_pipeline:B,keep_alive:p,backoff:v,target_session_attrs:h}=T,U=Io(),V=uZ++,I={pid:null,secret:null},L=o_(Lf,T.idle_timeout),m=o_(Lf,T.max_lifetime),s=o_(V4,T.connect_timeout),z=null,a,t=new eF,e=Buffer.alloc(0),ZT=T.fetch_types,vT={},Xo={},AF=Math.random().toString(36).slice(2),D=1,g=0,_T=0,IT=0,PT=0,FT=0,ET=0,xT=0,kT=null,VT=null,To=!1,KT=null,Po=null,oo=null,wF=null,mT=null,DT=null,mo=null,ro=null,N=null,vA=null,Fo={queue:o.closed,idleTimer:L,connect(W){oo=W||!0,C_()},terminate:mA,execute:PA,cancel:K4,end:Lf,count:0,id:V};return o.closed&&o.closed.push(Fo),Fo;async function E4(){let W;try{W=T.socket?await Promise.resolve(T.socket(T)):new e2.Socket}catch(Z){AA(Z);return}return W.on("error",AA),W.on("close",I_),W.on("drain",D_),W}async function K4({pid:W,secret:Z},c,RT){try{a=u().i32(16).i32(80877102).i32(W).i32(Z).end(16),await L_(),z.once("error",RT),z.once("close",c)}catch(NT){RT(NT)}}function PA(W){if(To)return dy(W,qT.connection("CONNECTION_DESTROYED",T));if(W.cancelled)return;try{return W.state=I,N?U.push(W):(N=W,N.active=!0),Q4(W),sT(U4(W))&&!W.describeFirst&&!W.cursorFn&&U.length<B&&(!W.options.onexecute||W.options.onexecute(Fo))}catch(Z){return U.length===0&&sT(bF),lo(Z),!0}}function U4(W){if(W.parameters.length>=65534)throw qT.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([z_(W),o4]):W.prepare?W.prepared?iy(W):Buffer.concat([z_(W),iy(W)]):z4(W)}function z_(W){return Buffer.concat([B_(W.statement.string,W.parameters,W.statement.types,W.statement.name),_X("S",W.statement.name)])}function iy(W){return Buffer.concat([JX(W.parameters,W.statement.types,W.statement.name,W.cursorName),W.cursorFn?N_("",W.cursorRows):iZ])}function z4(W){return Buffer.concat([B_(W.statement.string,W.parameters,W.statement.types),dZ,iy(W)])}function Q4(W){let Z=[],c=[],RT=cJ(W,W.strings[0],W.args[0],Z,c,T);!W.tagged&&W.args.forEach((NT)=>Mf(NT,Z,c,T)),W.prepare=T.prepare&&("prepare"in W.options?W.options.prepare:!0),W.string=RT,W.signature=W.prepare&&c+RT,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:RT,types:c,name:W.prepare?AF+D++:""},typeof T.debug==="function"&&T.debug(V,RT,Z,c)}function sT(W,Z){if(DT=DT?Buffer.concat([DT,W]):Buffer.from(W),Z||DT.length>=1024)return Q_(Z);return VT===null&&(VT=setImmediate(Q_)),!0}function Q_(W){let Z=z.write(DT,W);return VT!==null&&clearImmediate(VT),DT=VT=null,Z}function V4(){lo(qT.connection("CONNECT_TIMEOUT",T,z)),z.destroy()}async function V_(){if(sT(cZ),!await new Promise((Z)=>z.once("data",(c)=>Z(c[0]===83)))&&S==="prefer")return FA();z.removeAllListeners(),z=nZ.connect({socket:z,servername:e2.isIP(z.host)?void 0:z.host,...S==="require"||S==="allow"||S==="prefer"?{rejectUnauthorized:!1}:S==="verify-full"?{}:typeof S==="object"?S:{}}),z.on("secureConnect",FA),z.on("error",AA),z.on("close",I_),z.on("drain",D_)}function D_(){!N&&F(Fo)}function Df(W){if(KT){if(KT.push(W),_T-=W.length,_T>=0)return}e=KT?Buffer.concat(KT,FT-_T):e.length===0?W:Buffer.concat([e,W],e.length+W.length);while(e.length>4){if(FT=e.readUInt32BE(1),FT>=e.length){_T=FT-e.length,KT=[e];break}try{D4(e.subarray(0,FT+1))}catch(Z){N&&(N.cursorFn||N.describeFirst)&&sT(bF),lo(Z)}e=e.subarray(FT+1),_T=0,KT=null}}async function L_(){if(To=!1,vT={},z||(z=await E4()),!z)return;if(s.start(),T.socket)return S?V_():FA();if(z.on("connect",S?V_:FA),T.path)return z.connect(T.path);z.ssl=S,z.connect(J[IT],_[IT]),z.host=_[IT],z.port=J[IT],IT=(IT+1)%J.length}function C_(){setTimeout(L_,g?g+ET-T4.now():0)}function FA(){try{Xo={},ZT=T.fetch_types,AF=Math.random().toString(36).slice(2),D=1,m.start(),z.on("data",Df),p&&z.setKeepAlive&&z.setKeepAlive(!0,1000*p);let W=WX();sT(W)}catch(W){AA(W)}}function AA(W){if(Fo.queue===o.connecting&&T.host[PT+1])return;lo(W);while(U.length)dy(U.shift(),W)}function lo(W){mT&&(mT.destroy(W),mT=null),N&&dy(N,W),oo&&(dy(oo,W),oo=null)}function dy(W,Z){"query"in Z||"parameters"in Z||Object.defineProperties(Z,{stack:{value:Z.stack+W.origin.replace(/.*\n/,`
|
|
61
|
+
`),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 Lf(){return wF||(!Fo.reserved&&A(Fo),!Fo.reserved&&!oo&&!N&&U.length===0?(mA(),new Promise((W)=>z&&z.readyState!=="closed"?z.once("close",W):W())):wF=new Promise((W)=>mo=W))}function mA(){if(To=!0,mT||N||oo||U.length)AA(qT.connection("CONNECTION_DESTROYED",T));if(clearImmediate(VT),z)z.removeListener("data",Df),z.removeListener("connect",FA),z.readyState==="open"&&z.end(u().X().end());mo&&(mo(),wF=mo=null)}async function I_(W){if(e=Buffer.alloc(0),_T=0,KT=null,clearImmediate(VT),z.removeListener("data",Df),z.removeListener("connect",FA),L.cancel(),m.cancel(),s.cancel(),z.removeAllListeners(),z=null,oo)return C_();!W&&(N||U.length)&&AA(qT.connection("CONNECTION_CLOSED",T,z)),g=T4.now(),W&&T.shared.retries++,ET=(typeof v==="function"?v(T.shared.retries):v)*1000,y(Fo,qT.connection("CONNECTION_CLOSED",T,z))}function D4(W,Z=W[0]){(Z===68?L4:Z===100?TX:Z===65?d4:Z===83?C4:Z===90?I4:Z===67?k4:Z===50?k_:Z===49?B4:Z===116?N4:Z===84?p4:Z===82?j4:Z===110?m4:Z===75?t4:Z===69?c4:Z===115?r4:Z===51?l4:Z===71?s4:Z===78?FX:Z===72?a4:Z===99?oX:Z===73?AX:Z===86?yX:Z===118?SX:Z===87?e4:fX)(W)}function L4(W){let Z=7,c,RT,NT,Ao=N.isRaw?new Array(N.statement.columns.length):{};for(let _o=0;_o<N.statement.columns.length;_o++)RT=N.statement.columns[_o],c=W.readInt32BE(Z),Z+=4,NT=c===-1?null:N.isRaw===!0?W.subarray(Z,Z+=c):RT.parser===void 0?W.toString("utf8",Z,Z+=c):RT.parser.array===!0?RT.parser(W.toString("utf8",Z+1,Z+=c)):RT.parser(W.toString("utf8",Z,Z+=c)),N.isRaw?Ao[_o]=N.isRaw===!0?NT:Y.value.from?Y.value.from(NT,RT):NT:Ao[RT.name]=Y.value.from?Y.value.from(NT,RT):NT;N.forEachFn?N.forEachFn(Y.row.from?Y.row.from(Ao):Ao,t):t[xT++]=Y.row.from?Y.row.from(Ao):Ao}function C4(W){let[Z,c]=W.toString("utf8",5,W.length-1).split(u.N);if(vT[Z]=c,T.parameters[Z]!==c)T.parameters[Z]=c,E&&E(Z,c)}function I4(W){if(N&&N.options.simple&&N.resolve(Po||t),N=Po=null,t=new eF,s.cancel(),oo){if(h){if(!vT.in_hot_standby||!vT.default_transaction_read_only)return u4();else if(n4(h,vT))return mA()}if(ZT)return oo===!0&&(oo=null),h4();oo!==!0&&PA(oo),T.shared.retries=PT=0,oo=null;return}while(U.length&&(N=U.shift())&&(N.active=!0,N.cancelled))A4(T).cancel(N.state,N.cancelled.resolve,N.cancelled.reject);if(N)return;Fo.reserved?!Fo.reserved.release&&W[5]===73?wF?mA():(Fo.reserved=null,F(Fo)):Fo.reserved():wF?mA():F(Fo)}function k4(W){xT=0;for(let Z=W.length-1;Z>0;Z--){if(W[Z]===32&&W[Z+1]<58&&t.count===null)t.count=+W.toString("utf8",Z+1,W.length-1);if(W[Z-1]>=65){t.command=W.toString("utf8",5,Z),t.state=I;break}}if(vA&&(vA(),vA=null),t.command==="BEGIN"&&f!==1&&!Fo.reserved)return lo(qT.generic("UNSAFE_TRANSACTION","Only use sql.begin, sql.reserved or max: 1"));if(N.options.simple)return k_();if(N.cursorFn)t.count&&N.cursorFn(t),sT(bF);N.resolve(t)}function B4(){N.parsing=!1}function k_(){!t.statement&&(t.statement=N.statement),t.columns=N.statement.columns}function N4(W){let Z=W.readUInt16BE(5);for(let c=0;c<Z;++c)!N.statement.types[c]&&(N.statement.types[c]=W.readUInt32BE(7+c*4));N.prepare&&(Xo[N.signature]=N.statement),N.describeFirst&&!N.onlyDescribe&&(sT(iy(N)),N.describeFirst=!1)}function p4(W){if(t.command)Po=Po||[t],Po.push(t=new eF),t.count=null,N.statement.columns=null;let Z=W.readUInt16BE(5),c=7,RT;N.statement.columns=Array(Z);for(let NT=0;NT<Z;++NT){RT=c;while(W[c++]!==0);let Ao=W.readUInt32BE(c),_o=W.readUInt16BE(c+4),EF=W.readUInt32BE(c+6);N.statement.columns[NT]={name:Y.column.from?Y.column.from(W.toString("utf8",RT,c-1)):W.toString("utf8",RT,c-1),parser:O[EF],table:Ao,number:_o,type:EF},c+=18}if(t.statement=N.statement,N.onlyDescribe)return N.resolve(N.statement),sT(bF)}async function j4(W,Z=W.readUInt32BE(5)){(Z===3?x4:Z===5?b4:Z===10?q4:Z===11?v4:Z===12?P4:Z!==0?$X:jA)(W,Z)}async function x4(){let W=await Cf();sT(u().p().str(W).z(1).end())}async function b4(W){let Z="md5"+await F4(Buffer.concat([Buffer.from(await F4(await Cf()+$)),W.subarray(9)]));sT(u().p().str(Z).z(1).end())}async function q4(){ro=(await ty.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 v4(W){let Z=W.toString("utf8",9).split(",").reduce((_o,EF)=>(_o[EF[0]]=EF.slice(2),_o),{}),c=await ty.pbkdf2Sync(await Cf(),Buffer.from(Z.s,"base64"),parseInt(Z.i),32,"sha256"),RT=await Yf(c,"Client Key"),NT="n=*,r="+ro+",r="+Z.r+",s="+Z.s+",i="+Z.i+",c=biws,r="+Z.r;kT=(await Yf(await Yf(c,"Server Key"),NT)).toString("base64");let Ao="c=biws,r="+Z.r+",p="+aZ(RT,Buffer.from(await Yf(await sZ(RT),NT))).toString("base64");sT(u().p().str(Ao).end())}function P4(W){if(W.toString("utf8",9).split(u.N,1)[0].slice(2)===kT)return;lo(qT.generic("SASL_SIGNATURE_MISMATCH","The server did not return the correct signature")),z.destroy()}function Cf(){return Promise.resolve(typeof T.pass==="function"?T.pass():T.pass)}function m4(){if(t.statement=N.statement,t.statement.columns=[],N.onlyDescribe)return N.resolve(N.statement),sT(bF)}function t4(W){I.pid=W.readUInt32BE(5),I.secret=W.readUInt32BE(9)}async function h4(){ZT=!1,(await new vo([`
|
|
56
62
|
select b.oid, b.typarray
|
|
57
63
|
from pg_catalog.pg_type a
|
|
58
64
|
left join pg_catalog.pg_type b on b.oid = a.typelem
|
|
59
65
|
where a.typcategory = 'A'
|
|
60
66
|
group by b.oid, b.typarray
|
|
61
67
|
order by b.oid
|
|
62
|
-
`],[],
|
|
68
|
+
`],[],PA)).forEach(({oid:Z,typarray:c})=>g4(Z,c))}function g4(W,Z){if(!!T.parsers[Z]&&!!T.serializers[Z])return;let c=T.parsers[W];T.shared.typeArrayMap[W]=Z,T.parsers[Z]=(RT)=>s2(RT,c,Z),T.parsers[Z].array=!0,T.serializers[Z]=(RT)=>l2(RT,T.serializers[W],T,Z)}function n4(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[PT]}function u4(){let W=new vo([`
|
|
63
69
|
show transaction_read_only;
|
|
64
70
|
select pg_catalog.pg_is_in_recovery()
|
|
65
|
-
`],[],
|
|
71
|
+
`],[],PA,null,{simple:!0});W.resolve=([[Z],[c]])=>{vT.default_transaction_read_only=Z.transaction_read_only,vT.in_hot_standby=c.pg_is_in_recovery?"on":"off"},W.execute()}function c4(W){N&&(N.cursorFn||N.describeFirst)&&sT(bF);let Z=qT.postgres(T_(W));N&&N.retried?lo(N.retried):N&&N.prepared&&rZ.has(Z.routine)?i4(N,Z):lo(Z)}function i4(W,Z){delete Xo[W.signature],W.retried=Z,PA(W)}function d4(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 r4(){try{let W=await Promise.resolve(N.cursorFn(t));xT=0,W===NA?sT(RX(N.portal)):(t=new eF,sT(N_("",N.cursorRows)))}catch(W){sT(bF),N.reject(W)}}function l4(){t.count&&N.cursorFn(t),N.resolve(t)}function s4(){mT=new eJ.Writable({autoDestroy:!0,write(W,Z,c){z.write(u().d().raw(W).end(),c)},destroy(W,Z){Z(W),z.write(u().f().str(W+u.N).end()),mT=null},final(W){z.write(u().c().end()),vA=W}}),N.resolve(mT)}function a4(){mT=new eJ.Readable({read(){z.resume()}}),N.resolve(mT)}function e4(){mT=new eJ.Duplex({autoDestroy:!0,read(){z.resume()},write(W,Z,c){z.write(u().d().raw(W).end(),c)},destroy(W,Z){Z(W),z.write(u().f().str(W+u.N).end()),mT=null},final(W){z.write(u().c().end()),vA=W}}),N.resolve(mT)}function TX(W){mT&&(mT.push(W.subarray(5))||z.pause())}function oX(){mT&&mT.push(null),mT=null}function FX(W){H?H(T_(W)):console.log(T_(W))}function AX(){}function yX(){lo(qT.notSupported("FunctionCallResponse"))}function SX(){lo(qT.notSupported("NegotiateProtocolVersion"))}function fX(W){console.error("Postgres.js : Unknown Message:",W[0])}function $X(W,Z){console.error("Postgres.js : Unknown Auth:",Z)}function JX(W,Z,c="",RT=""){let NT,Ao;return u().B().str(RT+u.N).str(c+u.N).i16(0).i16(W.length),W.forEach((_o,EF)=>{if(_o===null)return u.i32(4294967295);Ao=Z[EF],W[EF]=_o=Ao in T.serializers?T.serializers[Ao](_o):""+_o,NT=u.i,u.inc(4).str(_o).i32(u.i-NT-4,NT)}),u.i16(0),u.end()}function B_(W,Z,c,RT=""){return u().P().str(RT+u.N).str(W+u.N).i16(Z.length),Z.forEach((NT,Ao)=>u.i32(c[Ao]||0)),u.end()}function _X(W,Z=""){return u().D().str(W).str(Z+u.N).end()}function N_(W="",Z=0){return Buffer.concat([u().E().str(W+u.N).i32(Z).end(),o4])}function RX(W=""){return Buffer.concat([u().C().str("P").str(W+u.N).end(),u().S().end()])}function WX(){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 T_(T){let o={},F=5;for(let A=5;A<T.length-1;A++)if(T[A]===0)o[lZ[T[F]]]=T.toString("utf8",F+1,A),F=A+1;return o}function F4(T){return ty.createHash("md5").update(T).digest("hex")}function Yf(T,o){return ty.createHmac("sha256",T).update(o).digest()}function sZ(T){return ty.createHash("sha256").update(T).digest()}function aZ(T,o){let F=Math.max(T.length,o.length),A=Buffer.allocUnsafe(F);for(let y=0;y<F;y++)A[y]=T[y]^o[y];return A}function o_(T,o){if(o=typeof o==="function"?o():o,!o)return{cancel:jA,start:jA};let F;return{cancel(){F&&(clearTimeout(F),F=null)},start(){F&&clearTimeout(F),F=setTimeout(A,o*1000,arguments)}};function A(y){T.apply(null,y),F=null}}var y4=()=>{};function A_(T,o){let F=new Map,A="postgresjs_"+Math.random().toString(36).slice(2),y={},S,f,$=!1,_=O.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;f=null,y.pid=y.secret=void 0,Y(await H(_,A,o.publications)),F.forEach((E)=>E.forEach(({onsubscribe:B})=>B()))},no_subscribe:!0}),J=_.end,R=_.close;return _.end=async()=>{return $=!0,f&&await new Promise((E)=>(f.once("close",E),f.end())),J()},_.close=async()=>{return f&&await new Promise((E)=>(f.once("close",E),f.end())),R()},O;async function O(E,B,p=y4,v=y4){if(E=o5(E),!S)S=H(_,A,o.publications);let h={fn:B,onsubscribe:p},U=F.has(E)?F.get(E).add(h):F.set(E,new Set([h])).get(E),V=()=>{U.delete(h),U.size===0&&F.delete(E)};return S.then((I)=>{return Y(I),p(),f&&f.on("error",v),{unsubscribe:V,state:y,sql:_}})}function Y(E){f=E.stream,y.pid=E.state.pid,y.secret=E.state.secret}async function H(E,B,p){if(!p)throw new Error("Missing publication names");let v=await E.unsafe(`CREATE_REPLICATION_SLOT ${B} TEMPORARY LOGICAL pgoutput NOEXPORT_SNAPSHOT`),[h]=v,U=await E.unsafe(`START_REPLICATION SLOT ${B} LOGICAL ${h.consistent_point} (proto_version '1', publication_names '${p}')`).writable(),V={lsn:Buffer.concat(h.consistent_point.split("/").map((z)=>Buffer.from(("00000000"+z).slice(-8),"hex")))};return U.on("data",L),U.on("error",I),U.on("close",E.close),{stream:U,state:v.state};function I(z){console.error("Unexpected error during logical streaming - reconnecting",z)}function L(z){if(z[0]===119)T5(z.subarray(25),V,E.options.parsers,m,o.transform);else if(z[0]===107&&z[17])V.lsn=z.subarray(1,9),s()}function m(z,a){let t=a.relation.schema+"."+a.relation.table;Q("*",z,a),Q("*:"+t,z,a),a.relation.keys.length&&Q("*:"+t+"="+a.relation.keys.map((e)=>z[e.name]),z,a),Q(a.command,z,a),Q(a.command+":"+t,z,a),a.relation.keys.length&&Q(a.command+":"+t+"="+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),U.write(z)}}function Q(E,B,p){F.has(E)&&F.get(E).forEach(({fn:v})=>v(B,p,E))}}function eZ(T){return new Date(Date.UTC(2000,0,1)+Number(T/BigInt(1000)))}function T5(T,o,F,A,y){let S=(f,[$,_])=>(f[$.charCodeAt(0)]=_,f);Object.entries({R:(f)=>{let $=1,_=o[f.readUInt32BE($)]={schema:f.toString("utf8",$+=4,$=f.indexOf(0,$))||"pg_catalog",table:f.toString("utf8",$+1,$=f.indexOf(0,$+1)),columns:Array(f.readUInt16BE($+=2)),keys:[]};$+=2;let J=0,R;while($<f.length)R=_.columns[J++]={key:f[$++],name:y.column.from?y.column.from(f.toString("utf8",$,$=f.indexOf(0,$))):f.toString("utf8",$,$=f.indexOf(0,$)),type:f.readUInt32BE($+=1),parser:F[f.readUInt32BE($)],atttypmod:f.readUInt32BE($+=4)},R.key&&_.keys.push(R),$+=4},Y:()=>{},O:()=>{},B:(f)=>{o.date=eZ(f.readBigInt64BE(9)),o.lsn=f.subarray(1,9)},I:(f)=>{let $=1,_=o[f.readUInt32BE($)],{row:J}=Zf(f,_.columns,$+=7,y);A(J,{command:"insert",relation:_})},D:(f)=>{let $=1,_=o[f.readUInt32BE($)];$+=4;let J=f[$]===75;A(J||f[$]===79?Zf(f,_.columns,$+=3,y).row:null,{command:"delete",relation:_,key:J})},U:(f)=>{let $=1,_=o[f.readUInt32BE($)];$+=4;let J=f[$]===75,R=J||f[$]===79?Zf(f,_.columns,$+=3,y):null;R&&($=R.i);let{row:O}=Zf(f,_.columns,$+3,y);A(O,{command:"update",relation:_,key:J,old:R&&R.row})},T:()=>{},C:()=>{}}).reduce(S,{})[T[0]](T)}function Zf(T,o,F,A){let y,S,f,$=A.raw?new Array(o.length):{};for(let _=0;_<o.length;_++)y=T[F++],S=o[_],f=y===110?null:y===117?void 0:S.parser===void 0?T.toString("utf8",F+4,F+=4+T.readUInt32BE(F)):S.parser.array===!0?S.parser(T.toString("utf8",F+5,F+=4+T.readUInt32BE(F))):S.parser(T.toString("utf8",F+4,F+=4+T.readUInt32BE(F))),A.raw?$[_]=A.raw===!0?f:A.value.from?A.value.from(f,S):f:$[S.name]=A.value.from?A.value.from(f,S):f;return{i:F,row:A.row.from?A.row.from($):$}}function o5(T){let o=T.match(/^(\*|insert|update|delete)?:?([^.]+?\.?[^=]+)?=?(.+)?/i)||[];if(!o)throw new Error("Malformed subscribe pattern: "+T);let[,F,A,y]=o;return(F||"*")+(A?":"+(A.indexOf(".")===-1?"public."+A:A):"")+(y?"="+y:"")}import S4 from"stream";function y_(T,o,F=393216){return new Promise(async(A,y)=>{await T.begin(async(S)=>{let f;!o&&([{oid:o}]=await S`select lo_creat(-1) as oid`);let[{fd:$}]=await S`select lo_open(${o}, ${F}) as fd`,_={writable:R,readable:J,close:()=>S`select lo_close(${$})`.then(f),tell:()=>S`select lo_tell64(${$})`,read:(O)=>S`select loread(${$}, ${O}) as data`,write:(O)=>S`select lowrite(${$}, ${O})`,truncate:(O)=>S`select lo_truncate64(${$}, ${O})`,seek:(O,Y=0)=>S`select lo_lseek64(${$}, ${O}, ${Y})`,size:()=>S`
|
|
66
72
|
select
|
|
67
73
|
lo_lseek64(${$}, location, 0) as position,
|
|
68
74
|
seek.size
|
|
@@ -72,10 +78,10 @@ ${f.trace}`:"No previous disposal trace was found."),y.type){case"atom_family":c
|
|
|
72
78
|
tell.location
|
|
73
79
|
from (select lo_tell64($1) as location) tell
|
|
74
80
|
) seek
|
|
75
|
-
`};return y(_),new Promise(async(M)=>f=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:p}]=await _.read(B);if(this.push(p),p.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(A)})}Object.assign(Yf,{PostgresError:By,toPascal:rF,pascal:rJ,toCamel:dF,camel:dJ,toKebab:lF,kebab:lJ,fromPascal:jA,fromCamel:bA,fromKebab:tA,BigInt:{to:20,from:[20],parse:(T)=>BigInt(T),serialize:(T)=>T.toString()}});var py=Yf;function Yf(T,o){let F=dZ(T,o),y=F.no_subscribe||o_(Yf,{...F}),A=!1,S=Io(),f=Io(),$=Io(),_=Io(),J=Io(),R=Io(),M=Io(),Y=Io(),H={connecting:f,reserved:$,closed:_,ended:J,open:R,busy:M,full:Y},Q=[...Array(F.max)].map(()=>T_(F,H,{onopen:Xo,onend:vT,onclose:yF})),w=B(m);return Object.assign(w,{get parameters(){return F.parameters},largeObject:F_.bind(null,w),subscribe:y,CLOSE:ky,END:ky,PostgresError:By,options:F,reserve:h,listen:p,begin:K,close:P,end:a}),w;function B(D){return D.debug=F.debug,Object.entries(F.types).reduce((FT,[UT,jT])=>{return FT[UT]=(kT)=>new FF(kT,jT.to),FT},g),Object.assign(RT,{types:g,typed:g,unsafe:IT,notify:q,array:C,json:L,file:mT}),RT;function g(FT,UT){return new FF(FT,UT)}function RT(FT,...UT){return FT&&Array.isArray(FT.raw)?new qo(FT,UT,D,z):typeof FT==="string"&&!UT.length?new qA(F.transform.column.to?F.transform.column.to(FT):FT):new _f(FT,UT)}function IT(FT,UT=[],jT={}){return arguments.length===2&&!Array.isArray(UT)&&(jT=UT,UT=[]),new qo([FT],UT,D,z,{prepare:!1,...jT,simple:"simple"in jT?jT.simple:UT.length===0})}function mT(FT,UT=[],jT={}){return arguments.length===2&&!Array.isArray(UT)&&(jT=UT,UT=[]),new qo([],UT,(DT)=>{iZ.readFile(FT,"utf8",(To,KT)=>{if(To)return DT.reject(To);DT.strings=[KT],D(DT)})},z,{...jT,simple:"simple"in jT?jT.simple:UT.length===0})}}async function p(D,g,RT){let IT={fn:g,onlisten:RT},mT=p.sql||(p.sql=Yf({...F,max:1,idle_timeout:null,max_lifetime:null,fetch_types:!1,onclose(){Object.entries(p.channels).forEach(([DT,{listeners:To}])=>{delete p.channels[DT],Promise.all(To.map((KT)=>p(DT,KT.fn,KT.onlisten).catch(()=>{})))})},onnotify(DT,To){DT in p.channels&&p.channels[DT].listeners.forEach((KT)=>KT.fn(To))}})),FT=p.channels||(p.channels={});if(D in FT){FT[D].listeners.push(IT);let DT=await FT[D].result;return IT.onlisten&&IT.onlisten(),{state:DT.state,unlisten:kT}}FT[D]={result:mT`listen ${mT.unsafe('"'+D.replace(/"/g,'""')+'"')}`,listeners:[IT]};let jT=await FT[D].result;return IT.onlisten&&IT.onlisten(),{state:jT.state,unlisten:kT};async function kT(){if(D in FT===!1)return;if(FT[D].listeners=FT[D].listeners.filter((DT)=>DT!==IT),FT[D].listeners.length)return;return delete FT[D],mT`unlisten ${mT.unsafe('"'+D.replace(/"/g,'""')+'"')}`}}async function q(D,g){return await w`select pg_notify(${D}, ${""+g})`}async function h(){let D=Io(),g=R.length?R.shift():await new Promise((mT)=>{S.push({reserve:mT}),_.length&&HT(_.shift())});V(g,$),g.reserved=()=>D.length?g.execute(D.shift()):V(g,$),g.reserved.release=!0;let RT=B(IT);return RT.release=()=>{g.reserved=null,Xo(g)},RT;function IT(mT){g.queue===Y?D.push(mT):g.execute(mT)||V(g,Y)}}async function K(D,g){!g&&(g=D,D="");let RT=Io(),IT=0,mT,FT=null;try{return await w.unsafe("begin "+D.replace(/[^a-z ]/ig,""),[],{onexecute:jT}).execute(),await Promise.race([UT(mT,g),new Promise((kT,DT)=>mT.onclose=DT)])}catch(kT){throw kT}async function UT(kT,DT,To){let KT=B(PT);KT.savepoint=wF,KT.prepare=(CT)=>FT=CT.replace(/[^a-z0-9$-_. ]/gi);let vo,oo;To&&await KT`savepoint ${KT(To)}`;try{if(oo=await new Promise((CT,mo)=>{let ro=DT(KT);Promise.resolve(Array.isArray(ro)?Promise.all(ro):ro).then(CT,mo)}),vo)throw vo}catch(CT){throw await(To?KT`rollback to ${KT(To)}`:KT`rollback`),CT instanceof By&&CT.code==="25P02"&&vo||CT}if(!To)FT?await KT`prepare transaction '${KT.unsafe(FT)}'`:await KT`commit`;return oo;function wF(CT,mo){if(CT&&Array.isArray(CT.raw))return wF((ro)=>ro.apply(ro,arguments));return arguments.length===1&&(mo=CT,CT=null),UT(kT,mo,"s"+IT+++(CT?"_"+CT:""))}function PT(CT){CT.catch((mo)=>vo||(vo=mo)),kT.queue===Y?RT.push(CT):kT.execute(CT)||V(kT,Y)}}function jT(kT){mT=kT,V(kT,$),kT.reserved=()=>RT.length?kT.execute(RT.shift()):V(kT,$)}}function V(D,g){return D.queue.remove(D),g.push(D),D.queue=g,g===R?D.idleTimer.start():D.idleTimer.cancel(),D}function L(D){return new FF(D,3802)}function C(D,g){if(!Array.isArray(D))return C(Array.from(arguments));return new FF(D,g||(D.length?$f(D)||25:0),F.shared.typeArrayMap)}function m(D){if(A)return D.reject(qT.connection("CONNECTION_ENDED",F,F));if(R.length)return s(R.shift(),D);if(_.length)return HT(_.shift(),D);M.length?s(M.shift(),D):S.push(D)}function s(D,g){return D.execute(g)?V(D,M):V(D,Y)}function z(D){return new Promise((g,RT)=>{D.state?D.active?T_(F).cancel(D.state,g,RT):D.cancelled={resolve:g,reject:RT}:(S.remove(D),D.cancelled=!0,D.reject(qT.generic("57014","canceling statement due to user request")),g())})}async function a({timeout:D=null}={}){if(A)return A;await 1;let g;return A=Promise.race([new Promise((RT)=>D!==null&&(g=setTimeout(e,D*1000,RT))),Promise.all(Q.map((RT)=>RT.end()).concat(p.sql?p.sql.end({timeout:0}):[],y.sql?y.sql.end({timeout:0}):[]))]).then(()=>clearTimeout(g))}async function P(){await Promise.all(Q.map((D)=>D.end()))}async function e(D){await Promise.all(Q.map((g)=>g.terminate()));while(S.length)S.shift().reject(qT.connection("CONNECTION_DESTROYED",F));D()}function HT(D,g){return V(D,f),D.connect(g),D}function vT(D){V(D,J)}function Xo(D){if(S.length===0)return V(D,R);let g=Math.ceil(S.length/(f.length+1)),RT=!0;while(RT&&S.length&&g-- >0){let IT=S.shift();if(IT.reserve)return IT.reserve(D);RT=D.execute(IT)}RT?V(D,M):V(D,Y)}function yF(D,g){V(D,_),D.reserved=null,D.onclose&&(D.onclose(g),D.onclose=null),F.onclose&&F.onclose(D.id),S.length&&HT(D,S.shift())}}function dZ(T,o){if(T&&T.shared)return T;let F=process.env,y=(!T||typeof T==="string"?o:T)||{},{url:A,multihost:S}=eZ(T),f=[...A.searchParams].reduce((Y,[H,Q])=>(Y[H]=Q,Y),{}),$=y.hostname||y.host||S||A.hostname||F.PGHOST||"localhost",_=y.port||A.port||F.PGPORT||5432,J=y.user||y.username||A.username||F.PGUSERNAME||F.PGUSER||T5();y.no_prepare&&(y.prepare=!1),f.sslmode&&(f.ssl=f.sslmode,delete f.sslmode),"timeout"in y&&(console.log("The timeout option is deprecated, use idle_timeout instead"),y.idle_timeout=y.timeout),f.sslrootcert==="system"&&(f.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:y.path||$.indexOf("/")>-1&&$+"/.s.PGSQL."+_,database:y.database||y.db||(A.pathname||"").slice(1)||F.PGDATABASE||J,user:J,pass:y.pass||y.password||A.password||F.PGPASSWORD||"",...Object.entries(M).reduce((Y,[H,Q])=>{let w=H in y?y[H]:(H in f)?f[H]==="disable"||f[H]==="false"?!1:f[H]:F["PG"+H.toUpperCase()]||Q;return Y[H]=typeof w==="string"&&R.includes(H)?+w:w,Y},{}),connection:{application_name:"postgres.js",...y.connection,...Object.entries(f).reduce((Y,[H,Q])=>((H in M)||(Y[H]=Q),Y),{})},types:y.types||{},target_session_attrs:rZ(y,A,F),onnotice:y.onnotice,onnotify:y.onnotify,onclose:y.onclose,onparameter:y.onparameter,socket:y.socket,transform:aZ(y.transform||{undefined:void 0}),parameters:{},shared:{retries:0,typeArrayMap:{}},...h2(y.types)}}function rZ(T,o,F){let y=T.target_session_attrs||o.searchParams.get("target_session_attrs")||F.PGTARGETSESSIONATTRS;if(!y||["read-write","read-only","primary","standby","prefer-standby"].includes(y))return y;throw new Error("target_session_attrs "+y+" 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 F=new URL(T.replace(o,o.split(",")[0]));return{url:{username:decodeURIComponent(F.username),password:decodeURIComponent(F.password),host:F.host,hostname:F.hostname,port:F.port,pathname:F.pathname,searchParams:F.searchParams},multihost:o.indexOf(",")>-1&&o}}function T5(){try{return cZ.userInfo().username}catch(T){return process.env.USERNAME||process.env.USER||process.env.LOGNAME}}class pT{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 y=(E(T,iT)?T._.selectedFields:E(T,Uo)?T[VT].selectedFields:T)[o];if(E(y,j.Aliased)){if(this.config.sqlAliasedBehavior==="sql"&&!y.isSelectionField)return y.sql;let A=y.clone();return A.isSelectionField=!0,A}if(E(y,j)){if(this.config.sqlBehavior==="sql")return y;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(E(y,ET)){if(this.config.alias)return new Proxy(y,new Iy(new Proxy(y.table,new LA(this.config.alias,this.config.replaceOriginalName??!1))));return y}if(typeof y!=="object"||y===null)return y;return new Proxy(y,new pT(this.config))}}class Zf extends Oo{constructor(T,o,F,y){super();this.session=o,this.dialect=F,this.config={table:T,withList:y}}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=to(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 pT({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((F)=>F.toLowerCase()).join("_")}function F5(T){return(T.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).reduce((F,y,A)=>{let S=A===0?y.toLowerCase():`${y[0].toUpperCase()}${y.slice(1)}`;return F+S},"")}function y5(T){return T}class y_{static[O]="CasingCache";cache={};cachedTables={};convert;constructor(T){this.convert=T==="snake_case"?o5:T==="camelCase"?F5:y5}getColumnCasing(T){if(!T.keyAsName)return T.name;let o=T.table[b.Symbol.Schema]??"public",F=T.table[b.Symbol.OriginalName],y=`${o}.${F}.${T.name}`;if(!this.cache[y])this.cacheTable(T.table);return this.cache[y]}cacheTable(T){let o=T[b.Symbol.Schema]??"public",F=T[b.Symbol.OriginalName],y=`${o}.${F}`;if(!this.cachedTables[y]){for(let A of Object.values(T[b.Symbol.Columns])){let S=`${y}.${A.name}`;this.cache[S]=this.convert(A.name)}this.cachedTables[y]=!0}}clearCache(){this.cache={},this.cachedTables={}}}class mA extends Uo{static[O]="PgViewBase"}class aF{static[O]="PgDialect";casing;constructor(T){this.casing=new y_(T?.casing)}async migrate(T,o,F){let y=typeof F==="string"?"__drizzle_migrations":F.migrationsTable??"__drizzle_migrations",A=typeof F==="string"?"drizzle":F.migrationsSchema??"drizzle",S=X`
|
|
76
|
-
CREATE TABLE IF NOT EXISTS ${X.identifier(
|
|
81
|
+
`};return A(_),new Promise(async(O)=>f=O);async function J({highWaterMark:O=16384,start:Y=0,end:H=1/0}={}){let Q=H-Y;return Y&&await _.seek(Y),new S4.Readable({highWaterMark:O,async read(E){let B=E>Q?E-Q:E;Q-=E;let[{data:p}]=await _.read(B);if(this.push(p),p.length<E)this.push(null)}})}async function R({highWaterMark:O=16384,start:Y=0}={}){return Y&&await _.seek(Y),new S4.Writable({highWaterMark:O,write(H,Q,E){_.write(H).then(()=>E(),E)}})}}).catch(y)})}Object.assign(Hf,{PostgresError:pA,toPascal:sF,pascal:sJ,toCamel:lF,camel:lJ,toKebab:aF,kebab:aJ,fromPascal:vy,fromCamel:qy,fromKebab:Py,BigInt:{to:20,from:[20],parse:(T)=>BigInt(T),serialize:(T)=>T.toString()}});var xA=Hf;function Hf(T,o){let F=y5(T,o),A=F.no_subscribe||A_(Hf,{...F}),y=!1,S=Io(),f=Io(),$=Io(),_=Io(),J=Io(),R=Io(),O=Io(),Y=Io(),H={connecting:f,reserved:$,closed:_,ended:J,open:R,busy:O,full:Y},Q=[...Array(F.max)].map(()=>F_(F,H,{onopen:Xo,onend:vT,onclose:AF})),E=B(m);return Object.assign(E,{get parameters(){return F.parameters},largeObject:y_.bind(null,E),subscribe:A,CLOSE:NA,END:NA,PostgresError:pA,options:F,reserve:h,listen:p,begin:U,close:t,end:a}),E;function B(D){return D.debug=F.debug,Object.entries(F.types).reduce((FT,[ET,xT])=>{return FT[ET]=(kT)=>new FF(kT,xT.to),FT},g),Object.assign(_T,{types:g,typed:g,unsafe:IT,notify:v,array:L,json:I,file:PT}),_T;function g(FT,ET){return new FF(FT,ET)}function _T(FT,...ET){return FT&&Array.isArray(FT.raw)?new vo(FT,ET,D,z):typeof FT==="string"&&!ET.length?new my(F.transform.column.to?F.transform.column.to(FT):FT):new Wf(FT,ET)}function IT(FT,ET=[],xT={}){return arguments.length===2&&!Array.isArray(ET)&&(xT=ET,ET=[]),new vo([FT],ET,D,z,{prepare:!1,...xT,simple:"simple"in xT?xT.simple:ET.length===0})}function PT(FT,ET=[],xT={}){return arguments.length===2&&!Array.isArray(ET)&&(xT=ET,ET=[]),new vo([],ET,(VT)=>{A5.readFile(FT,"utf8",(To,KT)=>{if(To)return VT.reject(To);VT.strings=[KT],D(VT)})},z,{...xT,simple:"simple"in xT?xT.simple:ET.length===0})}}async function p(D,g,_T){let IT={fn:g,onlisten:_T},PT=p.sql||(p.sql=Hf({...F,max:1,idle_timeout:null,max_lifetime:null,fetch_types:!1,onclose(){Object.entries(p.channels).forEach(([VT,{listeners:To}])=>{delete p.channels[VT],Promise.all(To.map((KT)=>p(VT,KT.fn,KT.onlisten).catch(()=>{})))})},onnotify(VT,To){VT in p.channels&&p.channels[VT].listeners.forEach((KT)=>KT.fn(To))}})),FT=p.channels||(p.channels={});if(D in FT){FT[D].listeners.push(IT);let VT=await FT[D].result;return IT.onlisten&&IT.onlisten(),{state:VT.state,unlisten:kT}}FT[D]={result:PT`listen ${PT.unsafe('"'+D.replace(/"/g,'""')+'"')}`,listeners:[IT]};let xT=await FT[D].result;return IT.onlisten&&IT.onlisten(),{state:xT.state,unlisten:kT};async function kT(){if(D in FT===!1)return;if(FT[D].listeners=FT[D].listeners.filter((VT)=>VT!==IT),FT[D].listeners.length)return;return delete FT[D],PT`unlisten ${PT.unsafe('"'+D.replace(/"/g,'""')+'"')}`}}async function v(D,g){return await E`select pg_notify(${D}, ${""+g})`}async function h(){let D=Io(),g=R.length?R.shift():await new Promise((PT)=>{S.push({reserve:PT}),_.length&&ZT(_.shift())});V(g,$),g.reserved=()=>D.length?g.execute(D.shift()):V(g,$),g.reserved.release=!0;let _T=B(IT);return _T.release=()=>{g.reserved=null,Xo(g)},_T;function IT(PT){g.queue===Y?D.push(PT):g.execute(PT)||V(g,Y)}}async function U(D,g){!g&&(g=D,D="");let _T=Io(),IT=0,PT,FT=null;try{return await E.unsafe("begin "+D.replace(/[^a-z ]/ig,""),[],{onexecute:xT}).execute(),await Promise.race([ET(PT,g),new Promise((kT,VT)=>PT.onclose=VT)])}catch(kT){throw kT}async function ET(kT,VT,To){let KT=B(mT);KT.savepoint=wF,KT.prepare=(DT)=>FT=DT.replace(/[^a-z0-9$-_. ]/gi);let Po,oo;To&&await KT`savepoint ${KT(To)}`;try{if(oo=await new Promise((DT,mo)=>{let ro=VT(KT);Promise.resolve(Array.isArray(ro)?Promise.all(ro):ro).then(DT,mo)}),Po)throw Po}catch(DT){throw await(To?KT`rollback to ${KT(To)}`:KT`rollback`),DT instanceof pA&&DT.code==="25P02"&&Po||DT}if(!To)FT?await KT`prepare transaction '${KT.unsafe(FT)}'`:await KT`commit`;return oo;function wF(DT,mo){if(DT&&Array.isArray(DT.raw))return wF((ro)=>ro.apply(ro,arguments));return arguments.length===1&&(mo=DT,DT=null),ET(kT,mo,"s"+IT+++(DT?"_"+DT:""))}function mT(DT){DT.catch((mo)=>Po||(Po=mo)),kT.queue===Y?_T.push(DT):kT.execute(DT)||V(kT,Y)}}function xT(kT){PT=kT,V(kT,$),kT.reserved=()=>_T.length?kT.execute(_T.shift()):V(kT,$)}}function V(D,g){return D.queue.remove(D),g.push(D),D.queue=g,g===R?D.idleTimer.start():D.idleTimer.cancel(),D}function I(D){return new FF(D,3802)}function L(D,g){if(!Array.isArray(D))return L(Array.from(arguments));return new FF(D,g||(D.length?_f(D)||25:0),F.shared.typeArrayMap)}function m(D){if(y)return D.reject(qT.connection("CONNECTION_ENDED",F,F));if(R.length)return s(R.shift(),D);if(_.length)return ZT(_.shift(),D);O.length?s(O.shift(),D):S.push(D)}function s(D,g){return D.execute(g)?V(D,O):V(D,Y)}function z(D){return new Promise((g,_T)=>{D.state?D.active?F_(F).cancel(D.state,g,_T):D.cancelled={resolve:g,reject:_T}:(S.remove(D),D.cancelled=!0,D.reject(qT.generic("57014","canceling statement due to user request")),g())})}async function a({timeout:D=null}={}){if(y)return y;await 1;let g;return y=Promise.race([new Promise((_T)=>D!==null&&(g=setTimeout(e,D*1000,_T))),Promise.all(Q.map((_T)=>_T.end()).concat(p.sql?p.sql.end({timeout:0}):[],A.sql?A.sql.end({timeout:0}):[]))]).then(()=>clearTimeout(g))}async function t(){await Promise.all(Q.map((D)=>D.end()))}async function e(D){await Promise.all(Q.map((g)=>g.terminate()));while(S.length)S.shift().reject(qT.connection("CONNECTION_DESTROYED",F));D()}function ZT(D,g){return V(D,f),D.connect(g),D}function vT(D){V(D,J)}function Xo(D){if(S.length===0)return V(D,R);let g=Math.ceil(S.length/(f.length+1)),_T=!0;while(_T&&S.length&&g-- >0){let IT=S.shift();if(IT.reserve)return IT.reserve(D);_T=D.execute(IT)}_T?V(D,O):V(D,Y)}function AF(D,g){V(D,_),D.reserved=null,D.onclose&&(D.onclose(g),D.onclose=null),F.onclose&&F.onclose(D.id),S.length&&ZT(D,S.shift())}}function y5(T,o){if(T&&T.shared)return T;let F=process.env,A=(!T||typeof T==="string"?o:T)||{},{url:y,multihost:S}=_5(T),f=[...y.searchParams].reduce((Y,[H,Q])=>(Y[H]=Q,Y),{}),$=A.hostname||A.host||S||y.hostname||F.PGHOST||"localhost",_=A.port||y.port||F.PGPORT||5432,J=A.user||A.username||y.username||F.PGUSERNAME||F.PGUSER||R5();A.no_prepare&&(A.prepare=!1),f.sslmode&&(f.ssl=f.sslmode,delete f.sslmode),"timeout"in A&&(console.log("The timeout option is deprecated, use idle_timeout instead"),A.idle_timeout=A.timeout),f.sslrootcert==="system"&&(f.ssl="verify-full");let R=["idle_timeout","connect_timeout","max_lifetime","max_pipeline","backoff","keep_alive"],O={max:10,ssl:!1,idle_timeout:null,connect_timeout:30,max_lifetime:$5,max_pipeline:100,backoff:f5,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||(y.pathname||"").slice(1)||F.PGDATABASE||J,user:J,pass:A.pass||A.password||y.password||F.PGPASSWORD||"",...Object.entries(O).reduce((Y,[H,Q])=>{let E=H in A?A[H]:(H in f)?f[H]==="disable"||f[H]==="false"?!1:f[H]:F["PG"+H.toUpperCase()]||Q;return Y[H]=typeof E==="string"&&R.includes(H)?+E:E,Y},{}),connection:{application_name:"postgres.js",...A.connection,...Object.entries(f).reduce((Y,[H,Q])=>((H in O)||(Y[H]=Q),Y),{})},types:A.types||{},target_session_attrs:S5(A,y,F),onnotice:A.onnotice,onnotify:A.onnotify,onclose:A.onclose,onparameter:A.onparameter,socket:A.socket,transform:J5(A.transform||{undefined:void 0}),parameters:{},shared:{retries:0,typeArrayMap:{}},...d2(A.types)}}function S5(T,o,F){let A=T.target_session_attrs||o.searchParams.get("target_session_attrs")||F.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 f5(T){return(0.5+Math.random()/2)*Math.min(3**T/100,20)}function $5(){return 60*(30+Math.random()*30)}function J5(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 _5(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 F=new URL(T.replace(o,o.split(",")[0]));return{url:{username:decodeURIComponent(F.username),password:decodeURIComponent(F.password),host:F.host,hostname:F.hostname,port:F.port,pathname:F.pathname,searchParams:F.searchParams},multihost:o.indexOf(",")>-1&&o}}function R5(){try{return F5.userInfo().username}catch(T){return process.env.USERNAME||process.env.USER||process.env.LOGNAME}}class pT{static[M]="SelectionProxyHandler";config;constructor(T){this.config={...T}}get(T,o){if(o==="_")return{...T._,selectedFields:new Proxy(T._.selectedFields,this)};if(o===QT)return{...T[QT],selectedFields:new Proxy(T[QT].selectedFields,this)};if(typeof o==="symbol")return T[o];let A=(w(T,iT)?T._.selectedFields:w(T,Ko)?T[QT].selectedFields:T)[o];if(w(A,b.Aliased)){if(this.config.sqlAliasedBehavior==="sql"&&!A.isSelectionField)return A.sql;let y=A.clone();return y.isSelectionField=!0,y}if(w(A,b)){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(w(A,GT)){if(this.config.alias)return new Proxy(A,new BA(new Proxy(A.table,new ky(this.config.alias,this.config.replaceOriginalName??!1))));return A}if(typeof A!=="object"||A===null)return A;return new Proxy(A,new pT(this.config))}}class Gf extends Mo{constructor(T,o,F,A){super();this.session=o,this.dialect=F,this.config={table:T,withList:A}}static[M]="PgDelete";config;where(T){return this.config.where=T,this}returning(T=this.config.table[x.Symbol.Columns]){return this.config.returningFields=T,this.config.returning=qo(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 pT({alias:lT(this.config.table),sqlAliasedBehavior:"alias",sqlBehavior:"error"})):void 0}$dynamic(){return this}}function W5(T){return(T.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).map((F)=>F.toLowerCase()).join("_")}function M5(T){return(T.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).reduce((F,A,y)=>{let S=y===0?A.toLowerCase():`${A[0].toUpperCase()}${A.slice(1)}`;return F+S},"")}function O5(T){return T}class S_{static[M]="CasingCache";cache={};cachedTables={};convert;constructor(T){this.convert=T==="snake_case"?W5:T==="camelCase"?M5:O5}getColumnCasing(T){if(!T.keyAsName)return T.name;let o=T.table[x.Symbol.Schema]??"public",F=T.table[x.Symbol.OriginalName],A=`${o}.${F}.${T.name}`;if(!this.cache[A])this.cacheTable(T.table);return this.cache[A]}cacheTable(T){let o=T[x.Symbol.Schema]??"public",F=T[x.Symbol.OriginalName],A=`${o}.${F}`;if(!this.cachedTables[A]){for(let y of Object.values(T[x.Symbol.Columns])){let S=`${A}.${y.name}`;this.cache[S]=this.convert(y.name)}this.cachedTables[A]=!0}}clearCache(){this.cache={},this.cachedTables={}}}class hy extends Ko{static[M]="PgViewBase"}class TA{static[M]="PgDialect";casing;constructor(T){this.casing=new S_(T?.casing)}async migrate(T,o,F){let A=typeof F==="string"?"__drizzle_migrations":F.migrationsTable??"__drizzle_migrations",y=typeof F==="string"?"drizzle":F.migrationsSchema??"drizzle",S=X`
|
|
82
|
+
CREATE TABLE IF NOT EXISTS ${X.identifier(y)}.${X.identifier(A)} (
|
|
77
83
|
id SERIAL PRIMARY KEY,
|
|
78
84
|
hash text NOT NULL,
|
|
79
85
|
created_at bigint
|
|
80
86
|
)
|
|
81
|
-
`;await o.execute(X`CREATE SCHEMA IF NOT EXISTS ${X.identifier(A)}`),await o.execute(S);let $=(await o.all(X`select id, hash, created_at from ${X.identifier(A)}.${X.identifier(y)} 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(A)}.${X.identifier(y)} ("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[F,y]of T.entries())if(o.push(X`${X.identifier(y._.alias)} as (${y._.sql})`),F<T.length-1)o.push(X`, `);return o.push(X` `),X.join(o)}buildDeleteQuery({table:T,where:o,returning:F,withList:y}){let A=this.buildWithCTE(y),S=F?X` returning ${this.buildSelection(F,{isSingleTable:!0})}`:void 0,f=o?X` where ${o}`:void 0;return X`${A}delete from ${T}${f}${S}`}buildUpdateSet(T,o){let F=T[b.Symbol.Columns],y=Object.keys(F).filter((S)=>o[S]!==void 0||F[S]?.onUpdateFn!==void 0),A=y.length;return X.join(y.flatMap((S,f)=>{let $=F[S],_=o[S]??X.param($.onUpdateFn(),$),J=X`${X.identifier(this.casing.getColumnCasing($))} = ${_}`;if(f<A-1)return[J,X.raw(", ")];return[J]}))}buildUpdateQuery({table:T,set:o,where:F,returning:y,withList:A,from:S,joins:f}){let $=this.buildWithCTE(A),_=T[eT.Symbol.Name],J=T[eT.Symbol.Schema],R=T[eT.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=S&&X.join([X.raw(" from "),this.buildFromTable(S)]),w=this.buildJoins(f),B=y?X` returning ${this.buildSelection(y,{isSingleTable:!S})}`:void 0,p=F?X` where ${F}`:void 0;return X`${$}update ${Y} set ${H}${Q}${w}${p}${B}`}buildSelection(T,{isSingleTable:o=!1}={}){let F=T.length,y=T.flatMap(({field:A},S)=>{let f=[];if(E(A,j.Aliased)&&A.isSelectionField)f.push(X.identifier(A.fieldAlias));else if(E(A,j.Aliased)||E(A,j)){let $=E(A,j.Aliased)?A.sql:A;if(o)f.push(new j($.queryChunks.map((_)=>{if(E(_,I))return X.identifier(this.casing.getColumnCasing(_));return _})));else f.push($);if(E(A,j.Aliased))f.push(X` as ${X.identifier(A.fieldAlias)}`)}else if(E(A,ET))if(o)f.push(X.identifier(this.casing.getColumnCasing(A)));else f.push(A);if(S<F-1)f.push(X`, `);return f});return X.join(y)}buildJoins(T){if(!T||T.length===0)return;let o=[];for(let[F,y]of T.entries()){if(F===0)o.push(X` `);let A=y.table,S=y.lateral?X` lateral`:void 0;if(E(A,eT)){let f=A[eT.Symbol.Name],$=A[eT.Symbol.Schema],_=A[eT.Symbol.OriginalName],J=f===_?void 0:y.alias;o.push(X`${X.raw(y.joinType)} join${S} ${$?X`${X.identifier($)}.`:void 0}${X.identifier(_)}${J&&X` ${X.identifier(J)}`} on ${y.on}`)}else if(E(A,Uo)){let f=A[VT].name,$=A[VT].schema,_=A[VT].originalName,J=f===_?void 0:y.alias;o.push(X`${X.raw(y.joinType)} join${S} ${$?X`${X.identifier($)}.`:void 0}${X.identifier(_)}${J&&X` ${X.identifier(J)}`} on ${y.on}`)}else o.push(X`${X.raw(y.joinType)} join${S} ${A} on ${y.on}`);if(F<T.length-1)o.push(X` `)}return X.join(o)}buildFromTable(T){if(E(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:F,where:y,having:A,table:S,joins:f,orderBy:$,groupBy:_,limit:J,offset:R,lockingClause:M,distinct:Y,setOperators:H}){let Q=F??to(o);for(let e of Q)if(E(e.field,ET)&&lT(e.field.table)!==(E(S,iT)?S._.alias:E(S,mA)?S[VT].name:E(S,j)?void 0:lT(S))&&!((HT)=>f?.some(({alias:vT})=>vT===(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=!f||f.length===0,B=this.buildWithCTE(T),p;if(Y)p=Y===!0?X` distinct`:X` distinct on (${X.join(Y.on,X`, `)})`;let q=this.buildSelection(Q,{isSingleTable:w}),h=this.buildFromTable(S),K=this.buildJoins(f),V=y?X` where ${y}`:void 0,L=A?X` having ${A}`:void 0,C;if($&&$.length>0)C=X` order by ${X.join($,X`, `)}`;let m;if(_&&_.length>0)m=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${p} ${q} from ${h}${K}${V}${m}${L}${C}${s}${z}${a}`;if(H.length>0)return this.buildSetOperations(P,H);return P}buildSetOperations(T,o){let[F,...y]=o;if(!F)throw new Error("Cannot pass undefined values to any set operator");if(y.length===0)return this.buildSetOperationQuery({leftSelect:T,setOperator:F});return this.buildSetOperations(this.buildSetOperationQuery({leftSelect:T,setOperator:F}),y)}buildSetOperationQuery({leftSelect:T,setOperator:{type:o,isAll:F,rightSelect:y,limit:A,orderBy:S,offset:f}}){let $=X`(${T.getSQL()}) `,_=X`(${y.getSQL()})`,J;if(S&&S.length>0){let H=[];for(let Q of S)if(E(Q,I))H.push(X.identifier(Q.name));else if(E(Q,j)){for(let w=0;w<Q.queryChunks.length;w++){let B=Q.queryChunks[w];if(E(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 A==="object"||typeof A==="number"&&A>=0?X` limit ${A}`:void 0,M=X.raw(`${o} ${F?"all ":""}`),Y=f?X` offset ${f}`:void 0;return X`${$}${M}${_}${J}${R}${Y}`}buildInsertQuery({table:T,values:o,onConflict:F,returning:y,withList:A,select:S,overridingSystemValue_:f}){let $=[],_=T[b.Symbol.Columns],J=Object.entries(_).filter(([B,p])=>!p.shouldDisableInsert()),R=J.map(([,B])=>X.identifier(this.casing.getColumnCasing(B)));if(S){let B=o;if(E(B,j))$.push(B);else $.push(B.getSQL())}else{let B=o;$.push(X.raw("values "));for(let[p,q]of B.entries()){let h=[];for(let[K,V]of J){let L=q[K];if(L===void 0||E(L,Co)&&L.value===void 0)if(V.defaultFn!==void 0){let C=V.defaultFn(),m=E(C,j)?C:X.param(C,V);h.push(m)}else if(!V.default&&V.onUpdateFn!==void 0){let C=V.onUpdateFn(),m=E(C,j)?C:X.param(C,V);h.push(m)}else h.push(X`default`);else h.push(L)}if($.push(h),p<B.length-1)$.push(X`, `)}}let M=this.buildWithCTE(A),Y=X.join($),H=y?X` returning ${this.buildSelection(y,{isSingleTable:!0})}`:void 0,Q=F?X` on conflict ${F}`:void 0,w=f===!0?X`overriding system value `:void 0;return X`${M}insert into ${T} ${R} ${w}${Y}${Q}${H}`}buildRefreshMaterializedViewQuery({view:T,concurrently:o,withNoData:F}){let y=o?X` concurrently`:void 0,A=F?X` with no data`:void 0;return X`refresh materialized view${y} ${T}${A}`}prepareTyping(T){if(E(T,aS)||E(T,sS))return"json";else if(E(T,eS))return"decimal";else if(E(T,Tf))return"time";else if(E(T,of)||E(T,Ff))return"timestamp";else if(E(T,dS)||E(T,rS))return"date";else if(E(T,yf))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:F,table:y,tableConfig:A,queryConfig:S,tableAlias:f,nestedQueryRelation:$,joinOn:_}){let J=[],R,M,Y=[],H,Q=[];if(S===!0)J=Object.entries(A.columns).map(([p,q])=>({dbKey:q.name,tsKey:p,field:oF(q,f),relationTableTsKey:void 0,isJson:!1,selection:[]}));else{let B=Object.fromEntries(Object.entries(A.columns).map(([L,C])=>[L,oF(C,f)]));if(S.where){let L=typeof S.where==="function"?S.where(B,I2()):S.where;H=L&&IA(L,f)}let p=[],q=[];if(S.columns){let L=!1;for(let[C,m]of Object.entries(S.columns)){if(m===void 0)continue;if(C in A.columns){if(!L&&m===!0)L=!0;q.push(C)}}if(q.length>0)q=L?q.filter((C)=>S.columns?.[C]===!0):Object.keys(A.columns).filter((C)=>!q.includes(C))}else q=Object.keys(A.columns);for(let L of q){let C=A.columns[L];p.push({tsKey:L,value:C})}let h=[];if(S.with)h=Object.entries(S.with).filter((L)=>!!L[1]).map(([L,C])=>({tsKey:L,queryConfig:C,relation:A.relations[L]}));let K;if(S.extras){K=typeof S.extras==="function"?S.extras(B,{sql:X}):S.extras;for(let[L,C]of Object.entries(K))p.push({tsKey:L,value:NJ(C,f)})}for(let{tsKey:L,value:C}of p)J.push({dbKey:E(C,j.Aliased)?C.fieldAlias:A.columns[L].name,tsKey:L,field:E(C,ET)?oF(C,f):C,relationTableTsKey:void 0,isJson:!1,selection:[]});let V=typeof S.orderBy==="function"?S.orderBy(B,k2()):S.orderBy??[];if(!Array.isArray(V))V=[V];Y=V.map((L)=>{if(E(L,ET))return oF(L,f);return IA(L,f)}),R=S.limit,M=S.offset;for(let{tsKey:L,queryConfig:C,relation:m}of h){let s=N2(o,F,m),z=iF(m.referencedTable),a=F[z],P=`${f}_${L}`,e=kA(...s.fields.map((Xo,yF)=>cS(oF(s.references[yF],P),oF(Xo,f)))),HT=this.buildRelationalQueryWithoutPK({fullSchema:T,schema:o,tableNamesMap:F,table:T[a],tableConfig:o[a],queryConfig:E(m,bF)?C===!0?{limit:1}:{...C,limit:1}:C,tableAlias:P,joinOn:e,nestedQueryRelation:m}),vT=X`${X.identifier(P)}.${X.identifier("data")}`.as(L);Q.push({on:X`true`,table:new iT(HT.sql,{},P),alias:P,joinType:"left",lateral:!0}),J.push({dbKey:L,tsKey:L,field:vT,relationTableTsKey:a,isJson:!0,selection:HT.selection})}}if(J.length===0)throw new uS({message:`No fields selected for table "${A.tsName}" ("${f}")`});let w;if(H=kA(_,H),$){let B=X`json_build_array(${X.join(J.map(({field:h,tsKey:K,isJson:V})=>V?X`${X.identifier(`${f}_${K}`)}.${X.identifier("data")}`:E(h,j.Aliased)?h.sql:h),X`, `)})`;if(E($,xA))B=X`coalesce(json_agg(${B}${Y.length>0?X` order by ${X.join(Y,X`, `)}`:void 0}), '[]'::json)`;let p=[{dbKey:"data",tsKey:"data",field:B.as("data"),isJson:!0,relationTableTsKey:A.tsName,selection:J}];if(R!==void 0||M!==void 0||Y.length>0)w=this.buildSelectQuery({table:nS(y,f),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=nS(y,f);w=this.buildSelectQuery({table:E(w,eT)?w:new iT(w,{},f),fields:{},fieldsFlat:p.map(({field:h})=>({path:[],field:E(h,ET)?oF(h,f):h})),joins:Q,where:H,limit:R,offset:M,orderBy:Y,setOperators:[]})}else w=this.buildSelectQuery({table:nS(y,f),fields:{},fieldsFlat:J.map(({field:B})=>({path:[],field:E(B,ET)?oF(B,f):B})),joins:Q,where:H,limit:R,offset:M,orderBy:Y,setOperators:[]});return{tableTsKey:A.tsName,sql:w,selection:J}}}class A_{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,F=T,y;if(this.fields)y=this.fields;else if(E(F,iT))y=Object.fromEntries(Object.keys(F._.selectedFields).map((A)=>[A,F[A]]));else if(E(F,mA))y=F[VT].selectedFields;else if(E(F,j))y={};else y=IO(F);return new S_({table:F,fields:y,isPartialSelect:o,session:this.session,dialect:this.dialect,withList:this.withList,distinct:this.distinct}).setToken(this.authToken)}}class T4 extends A_{static[O]="PgSelectQueryBuilder";_;config;joinsNotNullableMap;tableName;isPartialSelect;session;dialect;constructor({table:T,fields:o,isPartialSelect:F,session:y,dialect:A,withList:S,distinct:f}){super();this.config={withList:S,table:T,fields:{...o},distinct:f,setOperators:[]},this.isPartialSelect=F,this.session=y,this.dialect=A,this._={selectedFields:o},this.tableName=GF(T),this.joinsNotNullableMap=typeof this.tableName==="string"?{[this.tableName]:!0}:{}}createJoin(T){return(o,F)=>{let y=this.tableName,A=GF(o);if(typeof A==="string"&&this.config.joins?.some((S)=>S.alias===A))throw new Error(`Alias "${A}" is already used in this query`);if(!this.isPartialSelect){if(Object.keys(this.joinsNotNullableMap).length===1&&typeof y==="string")this.config.fields={[y]:this.config.fields};if(typeof A==="string"&&!E(o,j)){let S=E(o,iT)?o._.selectedFields:E(o,Uo)?o[VT].selectedFields:o[b.Symbol.Columns];this.config.fields[A]=S}}if(typeof F==="function")F=F(new Proxy(this.config.fields,new pT({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));if(!this.config.joins)this.config.joins=[];if(this.config.joins.push({on:F,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(([S])=>[S,!1])),this.joinsNotNullableMap[A]=!0;break}case"inner":{this.joinsNotNullableMap[A]=!0;break}case"full":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([S])=>[S,!1])),this.joinsNotNullableMap[A]=!1;break}}return this}}leftJoin=this.createJoin("left");rightJoin=this.createJoin("right");innerJoin=this.createJoin("inner");fullJoin=this.createJoin("full");createSetOperator(T,o){return(F)=>{let y=typeof F==="function"?F(A5()):F;if(!BA(this.getSelectedFields(),y.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:y}),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 pT({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));return this.config.where=T,this}having(T){if(typeof T==="function")T=T(new Proxy(this.config.fields,new pT({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 pT({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 pT({sqlAliasedBehavior:"alias",sqlBehavior:"sql"}))),F=Array.isArray(o)?o:[o];if(this.config.setOperators.length>0)this.config.setOperators.at(-1).orderBy=F;else this.config.orderBy=F}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 iT(this.getSQL(),this.config.fields,T),new pT({alias:T,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}getSelectedFields(){return new Proxy(this.config.fields,new pT({alias:this.tableName,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}$dynamic(){return this}}class S_ extends T4{static[O]="PgSelect";_prepare(T){let{session:o,config:F,dialect:y,joinsNotNullableMap:A,authToken:S}=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 f=to(F.fields),$=o.prepareQuery(y.sqlToQuery(this.getSQL()),f,T,!0);return $.joinsNotNullableMap=A,$.setToken(S)})}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(S_,[Oo]);function xy(T,o){return(F,y,...A)=>{let S=[y,...A].map((f)=>({type:T,isAll:o,rightSelect:f}));for(let f of S)if(!BA(F.getSelectedFields(),f.rightSelect.getSelectedFields()))throw new Error("Set operator error (union / intersect / except): selected fields are not the same or are in a different order");return F.addSetOperators(S)}}var A5=()=>({union:S5,unionAll:f5,intersect:$5,intersectAll:J5,except:_5,exceptAll:R5}),S5=xy("union",!1),f5=xy("union",!0),$5=xy("intersect",!1),J5=xy("intersect",!0),_5=xy("except",!1),R5=xy("except",!0);class PA{static[O]="PgQueryBuilder";dialect;dialectConfig;constructor(T){this.dialect=E(T,aF)?T:void 0,this.dialectConfig=E(T,aF)?void 0:T}$with=(T,o)=>{let F=this;return{as:(A)=>{if(typeof A==="function")A=A(F);return new Proxy(new DA(A.getSQL(),o??("getSelectedFields"in A?A.getSelectedFields()??{}:{}),T,!0),new pT({alias:T,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}};with(...T){let o=this;function F(S){return new Mo({fields:S??void 0,session:void 0,dialect:o.getDialect(),withList:T})}function y(S){return new Mo({fields:S??void 0,session:void 0,dialect:o.getDialect(),distinct:!0})}function A(S,f){return new Mo({fields:f??void 0,session:void 0,dialect:o.getDialect(),distinct:{on:S}})}return{select:F,selectDistinct:y,selectDistinctOn:A}}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 aF(this.dialectConfig);return this.dialect}}class Hf{constructor(T,o,F,y,A){this.table=T,this.session=o,this.dialect=F,this.withList=y,this.overridingSystemValue_=A}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((F)=>{let y={},A=this.table[b.Symbol.Columns];for(let S of Object.keys(F)){let f=F[S];y[S]=E(f,j)?f:new Co(f,A[S])}return y});return new f_(this.table,o,this.session,this.dialect,this.withList,!1,this.overridingSystemValue_).setToken(this.authToken)}select(T){let o=typeof T==="function"?T(new PA):T;if(!E(o,j)&&!BA(this.table[hS],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 f_(this.table,o,this.session,this.dialect,this.withList,!0)}}class f_ extends Oo{constructor(T,o,F,y,A,S,f){super();this.session=F,this.dialect=y,this.config={table:T,values:o,withList:A,select:S,overridingSystemValue_:f}}static[O]="PgInsert";config;returning(T=this.config.table[b.Symbol.Columns]){return this.config.returningFields=T,this.config.returning=to(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((y)=>this.dialect.escapeName(this.dialect.casing.getColumnCasing(y))).join(","):this.dialect.escapeName(this.dialect.casing.getColumnCasing(T.target));let F=T.where?X` where ${T.where}`:void 0;this.config.onConflict=X`(${X.raw(o)})${F} 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,F=T.targetWhere?X` where ${T.targetWhere}`:void 0,y=T.setWhere?X` where ${T.setWhere}`:void 0,A=this.dialect.buildUpdateSet(this.config.table,iS(this.config.table,T.set)),S="";return S=Array.isArray(T.target)?T.target.map((f)=>this.dialect.escapeName(this.dialect.casing.getColumnCasing(f))).join(","):this.dialect.escapeName(this.dialect.casing.getColumnCasing(T.target)),this.config.onConflict=X`(${X.raw(S)})${F} do update set ${A}${o}${y}`,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 pT({alias:lT(this.config.table),sqlAliasedBehavior:"alias",sqlBehavior:"error"})):void 0}$dynamic(){return this}}class $_ extends Oo{constructor(T,o,F){super();this.session=o,this.dialect=F,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 Gf{constructor(T,o,F,y){this.table=T,this.session=o,this.dialect=F,this.withList=y}static[O]="PgUpdateBuilder";authToken;setToken(T){return this.authToken=T,this}set(T){return new o4(this.table,iS(this.table,T),this.session,this.dialect,this.withList).setToken(this.authToken)}}class o4 extends Oo{constructor(T,o,F,y,A){super();this.session=F,this.dialect=y,this.config={set:o,table:T,withList:A,joins:[]},this.tableName=GF(T),this.joinsNotNullableMap=typeof this.tableName==="string"?{[this.tableName]:!0}:{}}static[O]="PgUpdate";config;tableName;joinsNotNullableMap;from(T){let o=T,F=GF(o);if(typeof F==="string")this.joinsNotNullableMap[F]=!0;return this.config.from=o,this}getTableLikeFields(T){if(E(T,eT))return T[b.Symbol.Columns];else if(E(T,iT))return T._.selectedFields;return T[VT].selectedFields}createJoin(T){return(o,F)=>{let y=GF(o);if(typeof y==="string"&&this.config.joins.some((A)=>A.alias===y))throw new Error(`Alias "${y}" is already used in this query`);if(typeof F==="function"){let A=this.config.from&&!E(this.config.from,j)?this.getTableLikeFields(this.config.from):void 0;F=F(new Proxy(this.config.table[b.Symbol.Columns],new pT({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})),A&&new Proxy(A,new pT({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})))}if(this.config.joins.push({on:F,table:o,joinType:T,alias:y}),typeof y==="string")switch(T){case"left":{this.joinsNotNullableMap[y]=!1;break}case"right":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([A])=>[A,!1])),this.joinsNotNullableMap[y]=!0;break}case"inner":{this.joinsNotNullableMap[y]=!0;break}case"full":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([A])=>[A,!1])),this.joinsNotNullableMap[y]=!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=GF(this.config.from);if(typeof o==="string"&&this.config.from&&!E(this.config.from,j)){let F=this.getTableLikeFields(this.config.from);T[o]=F}for(let F of this.config.joins){let y=GF(F.table);if(typeof y==="string"&&!E(F.table,j)){let A=this.getTableLikeFields(F.table);T[y]=A}}}}return this.config.returningFields=T,this.config.returning=to(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 pT({alias:lT(this.config.table),sqlAliasedBehavior:"alias",sqlBehavior:"error"})):void 0}$dynamic(){return this}}class hA extends j{constructor(T){super(hA.buildEmbeddedCount(T.source,T.filters).queryChunks);this.params=T,this.mapWith(Number),this.session=T.session,this.sql=hA.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 __{constructor(T,o,F,y,A,S,f){this.fullSchema=T,this.schema=o,this.tableNamesMap=F,this.table=y,this.tableConfig=A,this.dialect=S,this.session=f}static[O]="PgRelationalQueryBuilder";findMany(T){return new J_(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,T?T:{},"many")}findFirst(T){return new J_(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,T?{...T,limit:1}:{limit:1},"first")}}class J_ extends Oo{constructor(T,o,F,y,A,S,f,$,_){super();this.fullSchema=T,this.schema=o,this.tableNamesMap=F,this.table=y,this.tableConfig=A,this.dialect=S,this.session=f,this.config=$,this.mode=_}static[O]="PgRelationalQuery";_prepare(T){return wT.startActiveSpan("drizzle.prepareQuery",()=>{let{query:o,builtQuery:F}=this._toSQL();return this.session.prepareQuery(F,void 0,T,!0,(y,A)=>{let S=y.map((f)=>Af(this.schema,this.tableConfig,f,o.selection,A));if(this.mode==="first")return S[0];return S})})}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 R_ extends Oo{constructor(T,o,F,y){super();this.execute=T,this.sql=o,this.query=F,this.mapBatchResult=y}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 gA{constructor(T,o,F){if(this.dialect=T,this.session=o,this._=F?{schema:F.schema,fullSchema:F.fullSchema,tableNamesMap:F.tableNamesMap,session:o}:{schema:void 0,fullSchema:{},tableNamesMap:{},session:o},this.query={},this._.schema)for(let[y,A]of Object.entries(this._.schema))this.query[y]=new __(F.fullSchema,this._.schema,this._.tableNamesMap,F.fullSchema[y],A,T,o)}static[O]="PgDatabase";query;$with=(T,o)=>{let F=this;return{as:(A)=>{if(typeof A==="function")A=A(new PA(F.dialect));return new Proxy(new DA(A.getSQL(),o??("getSelectedFields"in A?A.getSelectedFields()??{}:{}),T,!0),new pT({alias:T,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}};$count(T,o){return new hA({source:T,filters:o,session:this.session})}with(...T){let o=this;function F(_){return new Mo({fields:_??void 0,session:o.session,dialect:o.dialect,withList:T})}function y(_){return new Mo({fields:_??void 0,session:o.session,dialect:o.dialect,withList:T,distinct:!0})}function A(_,J){return new Mo({fields:J??void 0,session:o.session,dialect:o.dialect,withList:T,distinct:{on:_}})}function S(_){return new Gf(_,o.session,o.dialect,T)}function f(_){return new Hf(_,o.session,o.dialect,T)}function $(_){return new Zf(_,o.session,o.dialect,T)}return{select:F,selectDistinct:y,selectDistinctOn:A,update:S,insert:f,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 Gf(T,this.session,this.dialect)}insert(T){return new Hf(T,this.session,this.dialect)}delete(T){return new Zf(T,this.session,this.dialect)}refreshMaterializedView(T){return new $_(T,this.session,this.dialect)}authToken;execute(T){let o=typeof T==="string"?X.raw(T):T.getSQL(),F=this.dialect.sqlToQuery(o),y=this.session.prepareQuery(F,void 0,void 0,!1);return new R_(()=>y.execute(void 0,this.authToken),o,F,(A)=>y.mapResult(A,!0))}transaction(T,o){return this.session.transaction(T,o)}}class F4{constructor(T,o){this.unique=T,this.name=o}static[O]="PgIndexBuilderOn";on(...T){return new Ef(T.map((o)=>{if(E(o,j))return o;o=o;let F=new VA(o.name,!!o.keyAsName,o.columnType,o.indexConfig);return o.indexConfig=JSON.parse(JSON.stringify(o.defaultConfig)),F}),this.unique,!1,this.name)}onOnly(...T){return new Ef(T.map((o)=>{if(E(o,j))return o;o=o;let F=new VA(o.name,!!o.keyAsName,o.columnType,o.indexConfig);return o.indexConfig=o.defaultConfig,F}),this.unique,!0,this.name)}using(T,...o){return new Ef(o.map((F)=>{if(E(F,j))return F;F=F;let y=new VA(F.name,!!F.keyAsName,F.columnType,F.indexConfig);return F.indexConfig=JSON.parse(JSON.stringify(F.defaultConfig)),y}),this.unique,!0,this.name,T)}}class Ef{static[O]="PgIndexBuilder";config;constructor(T,o,F,y,A="btree"){this.config={name:y,columns:T,unique:o,only:F,method:A}}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 y4(this.config,T)}}class y4{static[O]="PgIndex";config;constructor(T,o){this.config={...T,table:o}}}function W_(T){return new F4(!0,T)}class O_{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 M_{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 F=await this.execute(T,o);return Number(F[0].count)}}class X_ extends gA{constructor(T,o,F,y=0){super(T,o,F);this.schema=F,this.nestedIndex=y}static[O]="PgTransaction";rollback(){throw new pJ}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 A4 extends O_{constructor(T,o,F,y,A,S,f){super({sql:o,params:F});this.client=T,this.queryString=o,this.params=F,this.logger=y,this.fields=A,this._isResponseInArrayMode=S,this.customResultMapper=f}static[O]="PostgresJsPreparedQuery";async execute(T={}){return wT.startActiveSpan("drizzle.execute",async(o)=>{let F=BJ(this.params,T);o?.setAttributes({"drizzle.query.text":this.queryString,"drizzle.query.params":JSON.stringify(F)}),this.logger.logQuery(this.queryString,F);let{fields:y,queryString:A,client:S,joinsNotNullableMap:f,customResultMapper:$}=this;if(!y&&!$)return wT.startActiveSpan("drizzle.driver.execute",()=>{return S.unsafe(A,F)});let _=await wT.startActiveSpan("drizzle.driver.execute",()=>{return o?.setAttributes({"drizzle.query.text":A,"drizzle.query.params":JSON.stringify(F)}),S.unsafe(A,F).values()});return wT.startActiveSpan("drizzle.mapResponse",()=>{return $?$(_):_.map((J)=>CO(y,J,f))})})}all(T={}){return wT.startActiveSpan("drizzle.execute",async(o)=>{let F=BJ(this.params,T);return o?.setAttributes({"drizzle.query.text":this.queryString,"drizzle.query.params":JSON.stringify(F)}),this.logger.logQuery(this.queryString,F),wT.startActiveSpan("drizzle.driver.execute",()=>{return o?.setAttributes({"drizzle.query.text":this.queryString,"drizzle.query.params":JSON.stringify(F)}),this.client.unsafe(this.queryString,F)})})}isResponseInArrayMode(){return this._isResponseInArrayMode}}class nA extends M_{constructor(T,o,F,y={}){super(o);this.client=T,this.schema=F,this.options=y,this.logger=y.logger??new bJ}static[O]="PostgresJsSession";logger;prepareQuery(T,o,F,y,A){return new A4(this.client,T.sql,T.params,this.logger,o,y,A)}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(F)=>{let y=new nA(F,this.dialect,this.schema,this.options),A=new Y_(this.dialect,y,this.schema);if(o)await A.setTransaction(o);return T(A)})}}class Y_ extends X_{constructor(T,o,F,y=0){super(T,o,F,y);this.session=o}static[O]="PostgresJsTransaction";transaction(T){return this.session.client.savepoint((o)=>{let F=new nA(o,this.dialect,this.schema,this.session.options),y=new Y_(this.dialect,F,this.schema);return T(y)})}}class S4 extends gA{static[O]="PostgresJsDatabase"}function by(T,o={}){let F=(_)=>_;for(let _ of["1184","1082","1083","1114","1182","1185","1115","1231"])T.options.parsers[_]=F,T.options.serializers[_]=F;T.options.serializers["114"]=F,T.options.serializers["3802"]=F;let y=new aF({casing:o.casing}),A;if(o.logger===!0)A=new xJ;else if(o.logger!==!1)A=o.logger;let S;if(o.schema){let _=B2(o.schema,p2);S={fullSchema:o.schema,schema:_.tables,tableNamesMap:_.tableNamesMap}}let f=new nA(T,y,S,{logger:A}),$=new S4(y,f,S);return $.$client=T,$}function wf(...T){if(typeof T[0]==="string"){let o=py(T[0]);return by(o,T[1])}if(kO(T[0])){let{connection:o,client:F,...y}=T[0];if(F)return by(F,y);if(typeof o==="object"&&o.url!==void 0){let{url:S,...f}=o,$=py(S,f);return by($,y)}let A=py(o);return by(A,y)}return by(T[0],T[1])}((T)=>{function o(F){return by({options:{parsers:{},serializers:{}}},F)}T.mock=o})(wf||(wf={}));var H_={};RX(H_,{users:()=>eF,userChanges:()=>O5,untrackedUserColumnNames:()=>W5,twoFactorMethod:()=>R4,trackedUserColumnName:()=>_4,trackableUserColumnNames:()=>J4,role:()=>$4,players:()=>Z_,passwordResetAttempts:()=>X5,loginHistory:()=>M5,games:()=>Uf,banishedIps:()=>Y5});function f4(T){return X`lower(${T})`}var $4=mS("role",["admin","user"]),eF=xF("users",{id:Lo().primaryKey().defaultRandom(),username:$o({length:16}).notNull(),email:$o({length:254}).notNull(),password:$o({length:254}).notNull(),createdAt:io({withTimezone:!0}).notNull().defaultNow(),createdIp:$o({length:45}).notNull(),isActive:NA().notNull().default(!1),verifiedAt:io({withTimezone:!0}),userRole:$4().default("user")},(T)=>[W_("usernameUniqueIndex").on(f4(T.username)),W_("emailUniqueIndex").on(f4(T.email))]),W5=["id","createdAt","createdIp","isActive","verifiedAt"],J4=["username","email","password","userRole"],_4=mS("trackedUserColumnName",J4),O5=xF("userChanges",{id:Lo().primaryKey().defaultRandom(),userId:Lo().notNull().references(()=>eF.id,{onDelete:"cascade"}),changedAt:io({withTimezone:!0}).notNull().defaultNow(),changedIp:$o({length:45}).notNull(),changedColumn:_4().notNull(),oldValue:$o({length:255}),newValue:$o({length:255})}),Uf=xF("games",{id:Lo().primaryKey().defaultRandom()}),Z_=xF("players",{userId:Lo().notNull().references(()=>eF.id,{onDelete:"cascade"}),gameId:Lo().notNull().references(()=>Uf.id,{onDelete:"cascade"}),score:lS().notNull()},(T)=>[D2({name:"players_userId_gameId_pk",columns:[T.userId,T.gameId]})]),M5=xF("loginHistory",{id:Lo().primaryKey().defaultRandom(),userId:Lo().references(()=>eF.id,{onDelete:"cascade"}),loginTime:io({withTimezone:!0}).notNull().defaultNow(),ipAddress:$o({length:45}).notNull(),userAgent:$o({length:1024}),successful:NA().notNull().default(!1)}),R4=mS("twoFactorMethod",["email","phone"]),X5=xF("passwordResetAttempts",{id:Lo().primaryKey().defaultRandom(),userId:Lo().notNull().references(()=>eF.id,{onDelete:"cascade"}),requestedIp:$o({length:45}).notNull(),requestedAt:io({withTimezone:!0}).notNull().defaultNow(),succeededIp:$o({length:45}),succeededAt:io({withTimezone:!0}),verificationMethod:R4().notNull()}),Y5=xF("banishedIps",{ip:$o({length:45}).primaryKey(),reason:$o({length:2048}).notNull(),banishedAt:io({withTimezone:!0}).notNull().defaultNow(),banishedUntil:io({withTimezone:!0})});var __dirname="/home/runner/work/wayforge/wayforge/apps/tempest.games/src/database";class G_{options;sql;drizzle;observers=new Map;async setupTriggersAndNotifications(){await this.sql.file(Z5.resolve(__dirname,"notify_update.sql"));let T=[lT(eF),lT(Uf),lT(Z_)];await this.sql`SELECT create_notify_triggers(${this.sql.array(T)})`,await this.sql.listen("table_update",(o)=>{let F=o.split(","),y=F[0],A=F[1],S=`${y}("${A}")`;if(this.observers.has(S))this.observers.get(S).next(S)})}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=py(o),this.drizzle=wf(this.sql,{schema:H_,logger:T})}observe(T,o){if(!this.observers.has(T))this.observers.set(T,new oT);this.observers.get(T).subscribe("SINGLETON",o)}}var Kf={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 G5=xo(Kf),E5=G5.keyof().pipe((T)=>H5(T)),W4=xo([E5,"string"]);var w_=new ZJ,{logger:zo}=w_;Object.assign(console,zo,{log:zo.info});zo.info("ready");var E_=M4(import.meta.dir,"..","app"),Sg=new G_({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,F=new URL(T.url);if(zo.info(T.method,F.pathname),F.pathname==="/")return new Response(Bun.file(M4(E_,"index.html")));if(F.pathname==="/index.html")return Response.redirect("/");let y=w5(E_,F.pathname),A=U5(y);if(!A.startsWith(E_))throw[403,"Access Denied"];if(!await O4(A).exists())return Response.redirect("/");return new Response(O4(A))}catch(o){let F=W4(o);if(F instanceof xo.errors===!1){let[y,A]=F,f=`${Kf[y]}. ${A}`;return zo.info(`\u274C ${y}: ${f}`),new Response(f,{status:y})}if(o instanceof Error)zo.error(o.message);else{let y=Dy(o);zo.error("frontend server threw",y)}return new Response(Kf[500],{status:500})}}});function zf(){zo.info("\uD83D\uDEEC frontend server exiting"),process.exit(0)}process.on("SIGINT",()=>{zo.info("\u2757 received SIGINT; exiting gracefully"),zf()});process.on("SIGTERM",()=>{zo.info("\u2757 received SIGTERM; exiting gracefully"),zf()});process.on("exit",()=>{zo.info("\u2757 received exit; exiting gracefully"),zf()});w_.on("timeToStop",()=>{zo.info('\u2757 backend server received signal "timeToStop"; exiting gracefully'),zf()});zo.info(`\uD83D\uDEEB frontend server running at http://localhost:${uo.FRONTEND_PORT}/`);w_.emit("alive");
|
|
87
|
+
`;await o.execute(X`CREATE SCHEMA IF NOT EXISTS ${X.identifier(y)}`),await o.execute(S);let $=(await o.all(X`select id, hash, created_at from ${X.identifier(y)}.${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(y)}.${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[F,A]of T.entries())if(o.push(X`${X.identifier(A._.alias)} as (${A._.sql})`),F<T.length-1)o.push(X`, `);return o.push(X` `),X.join(o)}buildDeleteQuery({table:T,where:o,returning:F,withList:A}){let y=this.buildWithCTE(A),S=F?X` returning ${this.buildSelection(F,{isSingleTable:!0})}`:void 0,f=o?X` where ${o}`:void 0;return X`${y}delete from ${T}${f}${S}`}buildUpdateSet(T,o){let F=T[x.Symbol.Columns],A=Object.keys(F).filter((S)=>o[S]!==void 0||F[S]?.onUpdateFn!==void 0),y=A.length;return X.join(A.flatMap((S,f)=>{let $=F[S],_=o[S]??X.param($.onUpdateFn(),$),J=X`${X.identifier(this.casing.getColumnCasing($))} = ${_}`;if(f<y-1)return[J,X.raw(", ")];return[J]}))}buildUpdateQuery({table:T,set:o,where:F,returning:A,withList:y,from:S,joins:f}){let $=this.buildWithCTE(y),_=T[eT.Symbol.Name],J=T[eT.Symbol.Schema],R=T[eT.Symbol.OriginalName],O=_===R?void 0:_,Y=X`${J?X`${X.identifier(J)}.`:void 0}${X.identifier(R)}${O&&X` ${X.identifier(O)}`}`,H=this.buildUpdateSet(T,o),Q=S&&X.join([X.raw(" from "),this.buildFromTable(S)]),E=this.buildJoins(f),B=A?X` returning ${this.buildSelection(A,{isSingleTable:!S})}`:void 0,p=F?X` where ${F}`:void 0;return X`${$}update ${Y} set ${H}${Q}${E}${p}${B}`}buildSelection(T,{isSingleTable:o=!1}={}){let F=T.length,A=T.flatMap(({field:y},S)=>{let f=[];if(w(y,b.Aliased)&&y.isSelectionField)f.push(X.identifier(y.fieldAlias));else if(w(y,b.Aliased)||w(y,b)){let $=w(y,b.Aliased)?y.sql:y;if(o)f.push(new b($.queryChunks.map((_)=>{if(w(_,C))return X.identifier(this.casing.getColumnCasing(_));return _})));else f.push($);if(w(y,b.Aliased))f.push(X` as ${X.identifier(y.fieldAlias)}`)}else if(w(y,GT))if(o)f.push(X.identifier(this.casing.getColumnCasing(y)));else f.push(y);if(S<F-1)f.push(X`, `);return f});return X.join(A)}buildJoins(T){if(!T||T.length===0)return;let o=[];for(let[F,A]of T.entries()){if(F===0)o.push(X` `);let y=A.table,S=A.lateral?X` lateral`:void 0;if(w(y,eT)){let f=y[eT.Symbol.Name],$=y[eT.Symbol.Schema],_=y[eT.Symbol.OriginalName],J=f===_?void 0:A.alias;o.push(X`${X.raw(A.joinType)} join${S} ${$?X`${X.identifier($)}.`:void 0}${X.identifier(_)}${J&&X` ${X.identifier(J)}`} on ${A.on}`)}else if(w(y,Ko)){let f=y[QT].name,$=y[QT].schema,_=y[QT].originalName,J=f===_?void 0:A.alias;o.push(X`${X.raw(A.joinType)} join${S} ${$?X`${X.identifier($)}.`:void 0}${X.identifier(_)}${J&&X` ${X.identifier(J)}`} on ${A.on}`)}else o.push(X`${X.raw(A.joinType)} join${S} ${y} on ${A.on}`);if(F<T.length-1)o.push(X` `)}return X.join(o)}buildFromTable(T){if(w(T,x)&&T[x.Symbol.IsAlias]){let o=X`${X.identifier(T[x.Symbol.OriginalName])}`;if(T[x.Symbol.Schema])o=X`${X.identifier(T[x.Symbol.Schema])}.${o}`;return X`${o} ${X.identifier(T[x.Symbol.Name])}`}return T}buildSelectQuery({withList:T,fields:o,fieldsFlat:F,where:A,having:y,table:S,joins:f,orderBy:$,groupBy:_,limit:J,offset:R,lockingClause:O,distinct:Y,setOperators:H}){let Q=F??qo(o);for(let e of Q)if(w(e.field,GT)&&lT(e.field.table)!==(w(S,iT)?S._.alias:w(S,hy)?S[QT].name:w(S,b)?void 0:lT(S))&&!((ZT)=>f?.some(({alias:vT})=>vT===(ZT[x.Symbol.IsAlias]?lT(ZT):ZT[x.Symbol.BaseName])))(e.field.table)){let ZT=lT(e.field.table);throw new Error(`Your "${e.path.join("->")}" field references a column "${ZT}"."${e.field.name}", but the table "${ZT}" is not part of the query! Did you forget to join it?`)}let E=!f||f.length===0,B=this.buildWithCTE(T),p;if(Y)p=Y===!0?X` distinct`:X` distinct on (${X.join(Y.on,X`, `)})`;let v=this.buildSelection(Q,{isSingleTable:E}),h=this.buildFromTable(S),U=this.buildJoins(f),V=A?X` where ${A}`:void 0,I=y?X` having ${y}`:void 0,L;if($&&$.length>0)L=X` order by ${X.join($,X`, `)}`;let m;if(_&&_.length>0)m=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(O){let e=X` for ${X.raw(O.strength)}`;if(O.config.of)e.append(X` of ${X.join(Array.isArray(O.config.of)?O.config.of:[O.config.of],X`, `)}`);if(O.config.noWait)e.append(X` no wait`);else if(O.config.skipLocked)e.append(X` skip locked`);a.append(e)}let t=X`${B}select${p} ${v} from ${h}${U}${V}${m}${I}${L}${s}${z}${a}`;if(H.length>0)return this.buildSetOperations(t,H);return t}buildSetOperations(T,o){let[F,...A]=o;if(!F)throw new Error("Cannot pass undefined values to any set operator");if(A.length===0)return this.buildSetOperationQuery({leftSelect:T,setOperator:F});return this.buildSetOperations(this.buildSetOperationQuery({leftSelect:T,setOperator:F}),A)}buildSetOperationQuery({leftSelect:T,setOperator:{type:o,isAll:F,rightSelect:A,limit:y,orderBy:S,offset:f}}){let $=X`(${T.getSQL()}) `,_=X`(${A.getSQL()})`,J;if(S&&S.length>0){let H=[];for(let Q of S)if(w(Q,C))H.push(X.identifier(Q.name));else if(w(Q,b)){for(let E=0;E<Q.queryChunks.length;E++){let B=Q.queryChunks[E];if(w(B,C))Q.queryChunks[E]=X.identifier(B.name)}H.push(X`${Q}`)}else H.push(X`${Q}`);J=X` order by ${X.join(H,X`, `)} `}let R=typeof y==="object"||typeof y==="number"&&y>=0?X` limit ${y}`:void 0,O=X.raw(`${o} ${F?"all ":""}`),Y=f?X` offset ${f}`:void 0;return X`${$}${O}${_}${J}${R}${Y}`}buildInsertQuery({table:T,values:o,onConflict:F,returning:A,withList:y,select:S,overridingSystemValue_:f}){let $=[],_=T[x.Symbol.Columns],J=Object.entries(_).filter(([B,p])=>!p.shouldDisableInsert()),R=J.map(([,B])=>X.identifier(this.casing.getColumnCasing(B)));if(S){let B=o;if(w(B,b))$.push(B);else $.push(B.getSQL())}else{let B=o;$.push(X.raw("values "));for(let[p,v]of B.entries()){let h=[];for(let[U,V]of J){let I=v[U];if(I===void 0||w(I,Lo)&&I.value===void 0)if(V.defaultFn!==void 0){let L=V.defaultFn(),m=w(L,b)?L:X.param(L,V);h.push(m)}else if(!V.default&&V.onUpdateFn!==void 0){let L=V.onUpdateFn(),m=w(L,b)?L:X.param(L,V);h.push(m)}else h.push(X`default`);else h.push(I)}if($.push(h),p<B.length-1)$.push(X`, `)}}let O=this.buildWithCTE(y),Y=X.join($),H=A?X` returning ${this.buildSelection(A,{isSingleTable:!0})}`:void 0,Q=F?X` on conflict ${F}`:void 0,E=f===!0?X`overriding system value `:void 0;return X`${O}insert into ${T} ${R} ${E}${Y}${Q}${H}`}buildRefreshMaterializedViewQuery({view:T,concurrently:o,withNoData:F}){let A=o?X` concurrently`:void 0,y=F?X` with no data`:void 0;return X`refresh materialized view${A} ${T}${y}`}prepareTyping(T){if(w(T,eS)||w(T,aS))return"json";else if(w(T,Tf))return"decimal";else if(w(T,of))return"time";else if(w(T,Ff)||w(T,Af))return"timestamp";else if(w(T,rS)||w(T,lS))return"date";else if(w(T,yf))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:F,table:A,tableConfig:y,queryConfig:S,tableAlias:f,nestedQueryRelation:$,joinOn:_}){let J=[],R,O,Y=[],H,Q=[];if(S===!0)J=Object.entries(y.columns).map(([p,v])=>({dbKey:v.name,tsKey:p,field:oF(v,f),relationTableTsKey:void 0,isJson:!1,selection:[]}));else{let B=Object.fromEntries(Object.entries(y.columns).map(([I,L])=>[I,oF(L,f)]));if(S.where){let I=typeof S.where==="function"?S.where(B,x2()):S.where;H=I&&By(I,f)}let p=[],v=[];if(S.columns){let I=!1;for(let[L,m]of Object.entries(S.columns)){if(m===void 0)continue;if(L in y.columns){if(!I&&m===!0)I=!0;v.push(L)}}if(v.length>0)v=I?v.filter((L)=>S.columns?.[L]===!0):Object.keys(y.columns).filter((L)=>!v.includes(L))}else v=Object.keys(y.columns);for(let I of v){let L=y.columns[I];p.push({tsKey:I,value:L})}let h=[];if(S.with)h=Object.entries(S.with).filter((I)=>!!I[1]).map(([I,L])=>({tsKey:I,queryConfig:L,relation:y.relations[I]}));let U;if(S.extras){U=typeof S.extras==="function"?S.extras(B,{sql:X}):S.extras;for(let[I,L]of Object.entries(U))p.push({tsKey:I,value:jJ(L,f)})}for(let{tsKey:I,value:L}of p)J.push({dbKey:w(L,b.Aliased)?L.fieldAlias:y.columns[I].name,tsKey:I,field:w(L,GT)?oF(L,f):L,relationTableTsKey:void 0,isJson:!1,selection:[]});let V=typeof S.orderBy==="function"?S.orderBy(B,b2()):S.orderBy??[];if(!Array.isArray(V))V=[V];Y=V.map((I)=>{if(w(I,GT))return oF(I,f);return By(I,f)}),R=S.limit,O=S.offset;for(let{tsKey:I,queryConfig:L,relation:m}of h){let s=v2(o,F,m),z=rF(m.referencedTable),a=F[z],t=`${f}_${I}`,e=xy(...s.fields.map((Xo,AF)=>Sf(oF(s.references[AF],t),oF(Xo,f)))),ZT=this.buildRelationalQueryWithoutPK({fullSchema:T,schema:o,tableNamesMap:F,table:T[a],tableConfig:o[a],queryConfig:w(m,xF)?L===!0?{limit:1}:{...L,limit:1}:L,tableAlias:t,joinOn:e,nestedQueryRelation:m}),vT=X`${X.identifier(t)}.${X.identifier("data")}`.as(I);Q.push({on:X`true`,table:new iT(ZT.sql,{},t),alias:t,joinType:"left",lateral:!0}),J.push({dbKey:I,tsKey:I,field:vT,relationTableTsKey:a,isJson:!0,selection:ZT.selection})}}if(J.length===0)throw new iS({message:`No fields selected for table "${y.tsName}" ("${f}")`});let E;if(H=xy(_,H),$){let B=X`json_build_array(${X.join(J.map(({field:h,tsKey:U,isJson:V})=>V?X`${X.identifier(`${f}_${U}`)}.${X.identifier("data")}`:w(h,b.Aliased)?h.sql:h),X`, `)})`;if(w($,by))B=X`coalesce(json_agg(${B}${Y.length>0?X` order by ${X.join(Y,X`, `)}`:void 0}), '[]'::json)`;let p=[{dbKey:"data",tsKey:"data",field:B.as("data"),isJson:!0,relationTableTsKey:y.tsName,selection:J}];if(R!==void 0||O!==void 0||Y.length>0)E=this.buildSelectQuery({table:cS(A,f),fields:{},fieldsFlat:[{path:[],field:X.raw("*")}],where:H,limit:R,offset:O,orderBy:Y,setOperators:[]}),H=void 0,R=void 0,O=void 0,Y=[];else E=cS(A,f);E=this.buildSelectQuery({table:w(E,eT)?E:new iT(E,{},f),fields:{},fieldsFlat:p.map(({field:h})=>({path:[],field:w(h,GT)?oF(h,f):h})),joins:Q,where:H,limit:R,offset:O,orderBy:Y,setOperators:[]})}else E=this.buildSelectQuery({table:cS(A,f),fields:{},fieldsFlat:J.map(({field:B})=>({path:[],field:w(B,GT)?oF(B,f):B})),joins:Q,where:H,limit:R,offset:O,orderBy:Y,setOperators:[]});return{tableTsKey:y.tsName,sql:E,selection:J}}}class f_{static[M]="TypedQueryBuilder";getSelectedFields(){return this._.selectedFields}}class Oo{static[M]="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,F=T,A;if(this.fields)A=this.fields;else if(w(F,iT))A=Object.fromEntries(Object.keys(F._.selectedFields).map((y)=>[y,F[y]]));else if(w(F,hy))A=F[QT].selectedFields;else if(w(F,b))A={};else A=XM(F);return new $_({table:F,fields:A,isPartialSelect:o,session:this.session,dialect:this.dialect,withList:this.withList,distinct:this.distinct}).setToken(this.authToken)}}class f4 extends f_{static[M]="PgSelectQueryBuilder";_;config;joinsNotNullableMap;tableName;isPartialSelect;session;dialect;constructor({table:T,fields:o,isPartialSelect:F,session:A,dialect:y,withList:S,distinct:f}){super();this.config={withList:S,table:T,fields:{...o},distinct:f,setOperators:[]},this.isPartialSelect=F,this.session=A,this.dialect=y,this._={selectedFields:o},this.tableName=HF(T),this.joinsNotNullableMap=typeof this.tableName==="string"?{[this.tableName]:!0}:{}}createJoin(T){return(o,F)=>{let A=this.tableName,y=HF(o);if(typeof y==="string"&&this.config.joins?.some((S)=>S.alias===y))throw new Error(`Alias "${y}" 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 y==="string"&&!w(o,b)){let S=w(o,iT)?o._.selectedFields:w(o,Ko)?o[QT].selectedFields:o[x.Symbol.Columns];this.config.fields[y]=S}}if(typeof F==="function")F=F(new Proxy(this.config.fields,new pT({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));if(!this.config.joins)this.config.joins=[];if(this.config.joins.push({on:F,table:o,joinType:T,alias:y}),typeof y==="string")switch(T){case"left":{this.joinsNotNullableMap[y]=!1;break}case"right":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([S])=>[S,!1])),this.joinsNotNullableMap[y]=!0;break}case"inner":{this.joinsNotNullableMap[y]=!0;break}case"full":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([S])=>[S,!1])),this.joinsNotNullableMap[y]=!1;break}}return this}}leftJoin=this.createJoin("left");rightJoin=this.createJoin("right");innerJoin=this.createJoin("inner");fullJoin=this.createJoin("full");createSetOperator(T,o){return(F)=>{let A=typeof F==="function"?F(X5()):F;if(!Ny(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 pT({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));return this.config.where=T,this}having(T){if(typeof T==="function")T=T(new Proxy(this.config.fields,new pT({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 pT({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 pT({sqlAliasedBehavior:"alias",sqlBehavior:"sql"}))),F=Array.isArray(o)?o:[o];if(this.config.setOperators.length>0)this.config.setOperators.at(-1).orderBy=F;else this.config.orderBy=F}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 iT(this.getSQL(),this.config.fields,T),new pT({alias:T,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}getSelectedFields(){return new Proxy(this.config.fields,new pT({alias:this.tableName,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}$dynamic(){return this}}class $_ extends f4{static[M]="PgSelect";_prepare(T){let{session:o,config:F,dialect:A,joinsNotNullableMap:y,authToken:S}=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 f=qo(F.fields),$=o.prepareQuery(A.sqlToQuery(this.getSQL()),f,T,!0);return $.joinsNotNullableMap=y,$.setToken(S)})}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)})}}OM($_,[Mo]);function bA(T,o){return(F,A,...y)=>{let S=[A,...y].map((f)=>({type:T,isAll:o,rightSelect:f}));for(let f of S)if(!Ny(F.getSelectedFields(),f.rightSelect.getSelectedFields()))throw new Error("Set operator error (union / intersect / except): selected fields are not the same or are in a different order");return F.addSetOperators(S)}}var X5=()=>({union:Y5,unionAll:Z5,intersect:H5,intersectAll:G5,except:w5,exceptAll:E5}),Y5=bA("union",!1),Z5=bA("union",!0),H5=bA("intersect",!1),G5=bA("intersect",!0),w5=bA("except",!1),E5=bA("except",!0);class gy{static[M]="PgQueryBuilder";dialect;dialectConfig;constructor(T){this.dialect=w(T,TA)?T:void 0,this.dialectConfig=w(T,TA)?void 0:T}$with=(T,o)=>{let F=this;return{as:(y)=>{if(typeof y==="function")y=y(F);return new Proxy(new Cy(y.getSQL(),o??("getSelectedFields"in y?y.getSelectedFields()??{}:{}),T,!0),new pT({alias:T,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}};with(...T){let o=this;function F(S){return new Oo({fields:S??void 0,session:void 0,dialect:o.getDialect(),withList:T})}function A(S){return new Oo({fields:S??void 0,session:void 0,dialect:o.getDialect(),distinct:!0})}function y(S,f){return new Oo({fields:f??void 0,session:void 0,dialect:o.getDialect(),distinct:{on:S}})}return{select:F,selectDistinct:A,selectDistinctOn:y}}select(T){return new Oo({fields:T??void 0,session:void 0,dialect:this.getDialect()})}selectDistinct(T){return new Oo({fields:T??void 0,session:void 0,dialect:this.getDialect(),distinct:!0})}selectDistinctOn(T,o){return new Oo({fields:o??void 0,session:void 0,dialect:this.getDialect(),distinct:{on:T}})}getDialect(){if(!this.dialect)this.dialect=new TA(this.dialectConfig);return this.dialect}}class wf{constructor(T,o,F,A,y){this.table=T,this.session=o,this.dialect=F,this.withList=A,this.overridingSystemValue_=y}static[M]="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((F)=>{let A={},y=this.table[x.Symbol.Columns];for(let S of Object.keys(F)){let f=F[S];A[S]=w(f,b)?f:new Lo(f,y[S])}return A});return new J_(this.table,o,this.session,this.dialect,this.withList,!1,this.overridingSystemValue_).setToken(this.authToken)}select(T){let o=typeof T==="function"?T(new gy):T;if(!w(o,b)&&!Ny(this.table[nS],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 J_(this.table,o,this.session,this.dialect,this.withList,!0)}}class J_ extends Mo{constructor(T,o,F,A,y,S,f){super();this.session=F,this.dialect=A,this.config={table:T,values:o,withList:y,select:S,overridingSystemValue_:f}}static[M]="PgInsert";config;returning(T=this.config.table[x.Symbol.Columns]){return this.config.returningFields=T,this.config.returning=qo(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 F=T.where?X` where ${T.where}`:void 0;this.config.onConflict=X`(${X.raw(o)})${F} 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,F=T.targetWhere?X` where ${T.targetWhere}`:void 0,A=T.setWhere?X` where ${T.setWhere}`:void 0,y=this.dialect.buildUpdateSet(this.config.table,dS(this.config.table,T.set)),S="";return S=Array.isArray(T.target)?T.target.map((f)=>this.dialect.escapeName(this.dialect.casing.getColumnCasing(f))).join(","):this.dialect.escapeName(this.dialect.casing.getColumnCasing(T.target)),this.config.onConflict=X`(${X.raw(S)})${F} do update set ${y}${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 pT({alias:lT(this.config.table),sqlAliasedBehavior:"alias",sqlBehavior:"error"})):void 0}$dynamic(){return this}}class __ extends Mo{constructor(T,o,F){super();this.session=o,this.dialect=F,this.config={view:T}}static[M]="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 Ef{constructor(T,o,F,A){this.table=T,this.session=o,this.dialect=F,this.withList=A}static[M]="PgUpdateBuilder";authToken;setToken(T){return this.authToken=T,this}set(T){return new $4(this.table,dS(this.table,T),this.session,this.dialect,this.withList).setToken(this.authToken)}}class $4 extends Mo{constructor(T,o,F,A,y){super();this.session=F,this.dialect=A,this.config={set:o,table:T,withList:y,joins:[]},this.tableName=HF(T),this.joinsNotNullableMap=typeof this.tableName==="string"?{[this.tableName]:!0}:{}}static[M]="PgUpdate";config;tableName;joinsNotNullableMap;from(T){let o=T,F=HF(o);if(typeof F==="string")this.joinsNotNullableMap[F]=!0;return this.config.from=o,this}getTableLikeFields(T){if(w(T,eT))return T[x.Symbol.Columns];else if(w(T,iT))return T._.selectedFields;return T[QT].selectedFields}createJoin(T){return(o,F)=>{let A=HF(o);if(typeof A==="string"&&this.config.joins.some((y)=>y.alias===A))throw new Error(`Alias "${A}" is already used in this query`);if(typeof F==="function"){let y=this.config.from&&!w(this.config.from,b)?this.getTableLikeFields(this.config.from):void 0;F=F(new Proxy(this.config.table[x.Symbol.Columns],new pT({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})),y&&new Proxy(y,new pT({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})))}if(this.config.joins.push({on:F,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(([y])=>[y,!1])),this.joinsNotNullableMap[A]=!0;break}case"inner":{this.joinsNotNullableMap[A]=!0;break}case"full":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([y])=>[y,!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[x.Symbol.Columns]),this.config.from){let o=HF(this.config.from);if(typeof o==="string"&&this.config.from&&!w(this.config.from,b)){let F=this.getTableLikeFields(this.config.from);T[o]=F}for(let F of this.config.joins){let A=HF(F.table);if(typeof A==="string"&&!w(F.table,b)){let y=this.getTableLikeFields(F.table);T[A]=y}}}}return this.config.returningFields=T,this.config.returning=qo(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 pT({alias:lT(this.config.table),sqlAliasedBehavior:"alias",sqlBehavior:"error"})):void 0}$dynamic(){return this}}class ny extends b{constructor(T){super(ny.buildEmbeddedCount(T.source,T.filters).queryChunks);this.params=T,this.mapWith(Number),this.session=T.session,this.sql=ny.buildCount(T.source,T.filters)}sql;token;static[M]="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 W_{constructor(T,o,F,A,y,S,f){this.fullSchema=T,this.schema=o,this.tableNamesMap=F,this.table=A,this.tableConfig=y,this.dialect=S,this.session=f}static[M]="PgRelationalQueryBuilder";findMany(T){return new R_(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,T?T:{},"many")}findFirst(T){return new R_(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,T?{...T,limit:1}:{limit:1},"first")}}class R_ extends Mo{constructor(T,o,F,A,y,S,f,$,_){super();this.fullSchema=T,this.schema=o,this.tableNamesMap=F,this.table=A,this.tableConfig=y,this.dialect=S,this.session=f,this.config=$,this.mode=_}static[M]="PgRelationalQuery";_prepare(T){return wT.startActiveSpan("drizzle.prepareQuery",()=>{let{query:o,builtQuery:F}=this._toSQL();return this.session.prepareQuery(F,void 0,T,!0,(A,y)=>{let S=A.map((f)=>ff(this.schema,this.tableConfig,f,o.selection,y));if(this.mode==="first")return S[0];return S})})}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 M_ extends Mo{constructor(T,o,F,A){super();this.execute=T,this.sql=o,this.query=F,this.mapBatchResult=A}static[M]="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 uy{constructor(T,o,F){if(this.dialect=T,this.session=o,this._=F?{schema:F.schema,fullSchema:F.fullSchema,tableNamesMap:F.tableNamesMap,session:o}:{schema:void 0,fullSchema:{},tableNamesMap:{},session:o},this.query={},this._.schema)for(let[A,y]of Object.entries(this._.schema))this.query[A]=new W_(F.fullSchema,this._.schema,this._.tableNamesMap,F.fullSchema[A],y,T,o)}static[M]="PgDatabase";query;$with=(T,o)=>{let F=this;return{as:(y)=>{if(typeof y==="function")y=y(new gy(F.dialect));return new Proxy(new Cy(y.getSQL(),o??("getSelectedFields"in y?y.getSelectedFields()??{}:{}),T,!0),new pT({alias:T,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}};$count(T,o){return new ny({source:T,filters:o,session:this.session})}with(...T){let o=this;function F(_){return new Oo({fields:_??void 0,session:o.session,dialect:o.dialect,withList:T})}function A(_){return new Oo({fields:_??void 0,session:o.session,dialect:o.dialect,withList:T,distinct:!0})}function y(_,J){return new Oo({fields:J??void 0,session:o.session,dialect:o.dialect,withList:T,distinct:{on:_}})}function S(_){return new Ef(_,o.session,o.dialect,T)}function f(_){return new wf(_,o.session,o.dialect,T)}function $(_){return new Gf(_,o.session,o.dialect,T)}return{select:F,selectDistinct:A,selectDistinctOn:y,update:S,insert:f,delete:$}}select(T){return new Oo({fields:T??void 0,session:this.session,dialect:this.dialect})}selectDistinct(T){return new Oo({fields:T??void 0,session:this.session,dialect:this.dialect,distinct:!0})}selectDistinctOn(T,o){return new Oo({fields:o??void 0,session:this.session,dialect:this.dialect,distinct:{on:T}})}update(T){return new Ef(T,this.session,this.dialect)}insert(T){return new wf(T,this.session,this.dialect)}delete(T){return new Gf(T,this.session,this.dialect)}refreshMaterializedView(T){return new __(T,this.session,this.dialect)}authToken;execute(T){let o=typeof T==="string"?X.raw(T):T.getSQL(),F=this.dialect.sqlToQuery(o),A=this.session.prepareQuery(F,void 0,void 0,!1);return new M_(()=>A.execute(void 0,this.authToken),o,F,(y)=>A.mapResult(y,!0))}transaction(T,o){return this.session.transaction(T,o)}}class J4{constructor(T,o){this.unique=T,this.name=o}static[M]="PgIndexBuilderOn";on(...T){return new Kf(T.map((o)=>{if(w(o,b))return o;o=o;let F=new Ly(o.name,!!o.keyAsName,o.columnType,o.indexConfig);return o.indexConfig=JSON.parse(JSON.stringify(o.defaultConfig)),F}),this.unique,!1,this.name)}onOnly(...T){return new Kf(T.map((o)=>{if(w(o,b))return o;o=o;let F=new Ly(o.name,!!o.keyAsName,o.columnType,o.indexConfig);return o.indexConfig=o.defaultConfig,F}),this.unique,!0,this.name)}using(T,...o){return new Kf(o.map((F)=>{if(w(F,b))return F;F=F;let A=new Ly(F.name,!!F.keyAsName,F.columnType,F.indexConfig);return F.indexConfig=JSON.parse(JSON.stringify(F.defaultConfig)),A}),this.unique,!0,this.name,T)}}class Kf{static[M]="PgIndexBuilder";config;constructor(T,o,F,A,y="btree"){this.config={name:A,columns:T,unique:o,only:F,method:y}}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 _4(this.config,T)}}class _4{static[M]="PgIndex";config;constructor(T,o){this.config={...T,table:o}}}function O_(T){return new J4(!0,T)}class X_{constructor(T){this.query=T}authToken;getQuery(){return this.query}mapResult(T,o){return T}setToken(T){return this.authToken=T,this}static[M]="PgPreparedQuery";joinsNotNullableMap}class Y_{constructor(T){this.dialect=T}static[M]="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 F=await this.execute(T,o);return Number(F[0].count)}}class Z_ extends uy{constructor(T,o,F,A=0){super(T,o,F);this.schema=F,this.nestedIndex=A}static[M]="PgTransaction";rollback(){throw new xJ}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 R4 extends X_{constructor(T,o,F,A,y,S,f){super({sql:o,params:F});this.client=T,this.queryString=o,this.params=F,this.logger=A,this.fields=y,this._isResponseInArrayMode=S,this.customResultMapper=f}static[M]="PostgresJsPreparedQuery";async execute(T={}){return wT.startActiveSpan("drizzle.execute",async(o)=>{let F=pJ(this.params,T);o?.setAttributes({"drizzle.query.text":this.queryString,"drizzle.query.params":JSON.stringify(F)}),this.logger.logQuery(this.queryString,F);let{fields:A,queryString:y,client:S,joinsNotNullableMap:f,customResultMapper:$}=this;if(!A&&!$)return wT.startActiveSpan("drizzle.driver.execute",()=>{return S.unsafe(y,F)});let _=await wT.startActiveSpan("drizzle.driver.execute",()=>{return o?.setAttributes({"drizzle.query.text":y,"drizzle.query.params":JSON.stringify(F)}),S.unsafe(y,F).values()});return wT.startActiveSpan("drizzle.mapResponse",()=>{return $?$(_):_.map((J)=>MM(A,J,f))})})}all(T={}){return wT.startActiveSpan("drizzle.execute",async(o)=>{let F=pJ(this.params,T);return o?.setAttributes({"drizzle.query.text":this.queryString,"drizzle.query.params":JSON.stringify(F)}),this.logger.logQuery(this.queryString,F),wT.startActiveSpan("drizzle.driver.execute",()=>{return o?.setAttributes({"drizzle.query.text":this.queryString,"drizzle.query.params":JSON.stringify(F)}),this.client.unsafe(this.queryString,F)})})}isResponseInArrayMode(){return this._isResponseInArrayMode}}class cy extends Y_{constructor(T,o,F,A={}){super(o);this.client=T,this.schema=F,this.options=A,this.logger=A.logger??new qJ}static[M]="PostgresJsSession";logger;prepareQuery(T,o,F,A,y){return new R4(this.client,T.sql,T.params,this.logger,o,A,y)}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(F)=>{let A=new cy(F,this.dialect,this.schema,this.options),y=new H_(this.dialect,A,this.schema);if(o)await y.setTransaction(o);return T(y)})}}class H_ extends Z_{constructor(T,o,F,A=0){super(T,o,F,A);this.session=o}static[M]="PostgresJsTransaction";transaction(T){return this.session.client.savepoint((o)=>{let F=new cy(o,this.dialect,this.schema,this.session.options),A=new H_(this.dialect,F,this.schema);return T(A)})}}class W4 extends uy{static[M]="PostgresJsDatabase"}function qA(T,o={}){let F=(_)=>_;for(let _ of["1184","1082","1083","1114","1182","1185","1115","1231"])T.options.parsers[_]=F,T.options.serializers[_]=F;T.options.serializers["114"]=F,T.options.serializers["3802"]=F;let A=new TA({casing:o.casing}),y;if(o.logger===!0)y=new bJ;else if(o.logger!==!1)y=o.logger;let S;if(o.schema){let _=q2(o.schema,P2);S={fullSchema:o.schema,schema:_.tables,tableNamesMap:_.tableNamesMap}}let f=new cy(T,A,S,{logger:y}),$=new W4(A,f,S);return $.$client=T,$}function Uf(...T){if(typeof T[0]==="string"){let o=xA(T[0]);return qA(o,T[1])}if(YM(T[0])){let{connection:o,client:F,...A}=T[0];if(F)return qA(F,A);if(typeof o==="object"&&o.url!==void 0){let{url:S,...f}=o,$=xA(S,f);return qA($,A)}let y=xA(o);return qA(y,A)}return qA(T[0],T[1])}((T)=>{function o(F){return qA({options:{parsers:{},serializers:{}}},F)}T.mock=o})(Uf||(Uf={}));var w_={};ZX(w_,{users:()=>oA,userChanges:()=>U5,untrackedUserColumnNames:()=>K5,twoFactorMethod:()=>Z4,trackedUserColumnName:()=>Y4,trackableUserColumnNames:()=>X4,role:()=>O4,players:()=>G_,passwordResetAttempts:()=>Q5,loginHistory:()=>z5,games:()=>zf,banishedIps:()=>V5});function M4(T){return X`lower(${T})`}var O4=hS("role",["admin","user"]),oA=jF("users",{id:Co().primaryKey().defaultRandom(),username:$o({length:16}).notNull(),email:$o({length:254}).notNull(),password:$o({length:254}).notNull(),createdAt:io({withTimezone:!0}).notNull().defaultNow(),createdIp:$o({length:45}).notNull(),isActive:py().notNull().default(!1),verifiedAt:io({withTimezone:!0}),userRole:O4().default("user")},(T)=>[O_("usernameUniqueIndex").on(M4(T.username)),O_("emailUniqueIndex").on(M4(T.email))]),K5=["id","createdAt","createdIp","isActive","verifiedAt"],X4=["username","email","password","userRole"],Y4=hS("trackedUserColumnName",X4),U5=jF("userChanges",{id:Co().primaryKey().defaultRandom(),userId:Co().notNull().references(()=>oA.id,{onDelete:"cascade"}),changedAt:io({withTimezone:!0}).notNull().defaultNow(),changedIp:$o({length:45}).notNull(),changedColumn:Y4().notNull(),oldValue:$o({length:255}),newValue:$o({length:255})}),zf=jF("games",{id:Co().primaryKey().defaultRandom()}),G_=jF("players",{userId:Co().notNull().references(()=>oA.id,{onDelete:"cascade"}),gameId:Co().notNull().references(()=>zf.id,{onDelete:"cascade"}),score:sS().notNull()},(T)=>[W2({name:"players_userId_gameId_pk",columns:[T.userId,T.gameId]})]),z5=jF("loginHistory",{id:Co().primaryKey().defaultRandom(),userId:Co().references(()=>oA.id,{onDelete:"cascade"}),loginTime:io({withTimezone:!0}).notNull().defaultNow(),ipAddress:$o({length:45}).notNull(),userAgent:$o({length:1024}),successful:py().notNull().default(!1)}),Z4=hS("twoFactorMethod",["email","phone"]),Q5=jF("passwordResetAttempts",{id:Co().primaryKey().defaultRandom(),userId:Co().notNull().references(()=>oA.id,{onDelete:"cascade"}),requestedIp:$o({length:45}).notNull(),requestedAt:io({withTimezone:!0}).notNull().defaultNow(),succeededIp:$o({length:45}),succeededAt:io({withTimezone:!0}),verificationMethod:Z4().notNull()}),V5=jF("banishedIps",{ip:$o({length:45}).primaryKey(),reason:$o({length:2048}).notNull(),banishedAt:io({withTimezone:!0}).notNull().defaultNow(),banishedUntil:io({withTimezone:!0})});var __dirname="/home/runner/work/wayforge/wayforge/apps/tempest.games/src/database";class E_{options;sql;drizzle;observers=new Map;async setupTriggersAndNotifications(){await this.sql.file(D5.resolve(__dirname,"notify_update.sql"));let T=[lT(oA),lT(zf),lT(G_)];await this.sql`SELECT create_notify_triggers(${this.sql.array(T)})`,await this.sql.listen("table_update",(o)=>{let F=o.split(","),A=F[0],y=F[1],S=`${A}("${y}")`;if(this.observers.has(S))this.observers.get(S).next(S)})}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=xA(o),this.drizzle=Uf(this.sql,{schema:w_,logger:T})}observe(T,o){if(!this.observers.has(T))this.observers.set(T,new oT);this.observers.get(T).subscribe("SINGLETON",o)}}var Qf={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 L5(T){return Number.parseInt(T,10)}var C5=jo(Qf),I5=C5.keyof().pipe((T)=>L5(T)),H4=jo([I5,"string"]);var U_=new wJ,{logger:zo}=U_;Object.assign(console,zo,{log:zo.info});zo.info("ready");var K_=w4(import.meta.dir,"..","app"),Rg=new E_({logQuery(T,o){zo.info("\uD83D\uDCDD query",T,o)}});N5({hostname:"0.0.0.0",port:uo.FRONTEND_PORT??3333,...cW??void 0,async fetch(T){try{let o=new Date,F=new URL(T.url);if(zo.info(T.method,F.pathname),F.pathname==="/")return new Response(Bun.file(w4(K_,"index.html")));if(F.pathname==="/index.html")return Response.redirect("/");let A=k5(K_,F.pathname),y=B5(A);if(!y.startsWith(K_))throw[403,"Access Denied"];if(!await G4(y).exists())return Response.redirect("/");return new Response(G4(y))}catch(o){let F=H4(o);if(F instanceof jo.errors===!1){let[A,y]=F,f=`${Qf[A]}. ${y}`;return zo.info(`\u274C ${A}: ${f}`),new Response(f,{status:A})}if(o instanceof Error)zo.error(o.message);else{let A=CA(o);zo.error("frontend server threw",A)}return new Response(Qf[500],{status:500})}}});function Vf(){zo.info("\uD83D\uDEEC frontend server exiting"),process.exit(0)}process.on("SIGINT",()=>{zo.info("\u2757 received SIGINT; exiting gracefully"),Vf()});process.on("SIGTERM",()=>{zo.info("\u2757 received SIGTERM; exiting gracefully"),Vf()});process.on("exit",()=>{zo.info("\u2757 received exit; exiting gracefully"),Vf()});U_.on("timeToStop",()=>{zo.info('\u2757 backend server received signal "timeToStop"; exiting gracefully'),Vf()});zo.info(`\uD83D\uDEEB frontend server running at http://localhost:${uo.FRONTEND_PORT}/`);U_.emit("alive");
|