tempest.games 0.2.32 → 0.2.34

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.
@@ -1,78 +1,78 @@
1
1
  #!/usr/bin/env bun
2
2
  // @bun
3
- var TJ=Object.create;var{getPrototypeOf:KJ,defineProperty:$Z,getOwnPropertyNames:qJ}=Object;var jJ=Object.prototype.hasOwnProperty;var bO=(Y,Z,X)=>{X=Y!=null?TJ(KJ(Y)):{};let _=Z||!Y||!Y.__esModule?$Z(X,"default",{value:Y,enumerable:!0}):X;for(let G of qJ(Y))if(!jJ.call(_,G))$Z(_,G,{get:()=>Y[G],enumerable:!0});return _};var kO=(Y,Z)=>()=>(Z||Y((Z={exports:{}}).exports,Z),Z.exports);var PJ=(Y,Z)=>{for(var X in Z)$Z(Y,X,{get:Z[X],enumerable:!0,configurable:!0,set:(_)=>Z[X]=()=>_})};var gO=(Y,Z)=>()=>(Y&&(Z=Y(Y=0)),Z);var yO=import.meta.require;import SO,{join as vO,normalize as xO,resolve as xH}from"path";var U4=(Y)=>Array.isArray(Y)?Y:[Y],z_=(Y,Z)=>{let X=[[],[]];for(let _ of Y)if(Z(_))X[0].push(_);else X[1].push(_);return X},g6=Array,s1=(Y,Z)=>Y.includes(Z),F_=(Y,Z=0)=>[...new Array(Y)].map((X,_)=>_+Z),Z0=(Y,Z,X)=>{if(Y===void 0)return Z===void 0?[]:Array.isArray(Z)?Z:[Z];if(X?.prepend)if(Array.isArray(Z))Y.unshift(...Z);else Y.unshift(Z);else if(Array.isArray(Z))Y.push(...Z);else Y.push(Z);return Y},a1=(Y,Z)=>{if(Z===void 0||Z===null)return Y??[];if(Y===void 0||Y===null)return U4(Z);return Y.concat(Z)},U_=(...Y)=>Y.reduce(a1,[]),d1=(Y,Z,X)=>{if(Y===void 0)return Array.isArray(Z)?Z:[Z];let _=X?.isEqual??((G,W)=>G===W);for(let G of U4(Z))if(!Y.some((W)=>_(W,G)))Y.push(G);return Y},O_=(Y,Z)=>Y.reduce((X,_)=>{let G=_[Z];return X[G]=Z0(X[G],_),X},{}),t1=(Y,Z,X)=>Y.length===Z.length&&Y.every(X?.isEqual?(_,G)=>X.isEqual(_,Z[G]):(_,G)=>_===Z[G]);var $1=(Y,Z)=>y0(Y)===Z,y0=(Y)=>{let Z=typeof Y;return Z==="object"?Y===null?"null":"object":Z==="function"?"object":Z},z1={boolean:"boolean",null:"null",undefined:"undefined",bigint:"a bigint",number:"a number",object:"an object",string:"a string",symbol:"a symbol"},E_={...z1,function:"a function"};class D_ extends Error{}var _0=(Y)=>q4(Y,D_),q4=(Y,Z=Error)=>{throw new Z(Y)};class P8 extends Error{name="ParseError"}var w=(Y)=>q4(Y,P8),x1=(Y)=>` ${Y}`;var o=(Y,Z)=>{let X={},_=Array.isArray(Y),G=!1;for(let[W,H]of Object.entries(Y).entries()){let J=_?Z(W,H[1]):Z(...H,W);G||=typeof J[0]==="number";let $=Array.isArray(J[0])||J.length===0?J:[J];for(let[Q,z]of $)if(typeof Q==="object")X[Q.group]=Z0(X[Q.group],z);else X[Q]=z}return G?Object.values(X):X};var zZ=Object.entries;var p0=(Y,Z)=>(Y in Z),n4=(Y,Z)=>(Z in Y);class FZ{constructor(Y){Object.assign(this,Y)}}var L_=class{};class S8 extends L_{}var SJ=(Y,Z)=>{let X={},_={},G;for(G in Y)if(G in Z)X[G]=Y[G];else _[G]=Y[G];return[X,_]};var V_=(Y,Z)=>SJ(Y,Z)[1],c1=(Y)=>Object.keys(Y).length===0,j4=(Y)=>[...Object.entries(Y),...Object.getOwnPropertySymbols(Y).map((Z)=>[Z,Y[Z]])],M_=(Y,Z)=>Object.defineProperties(Y,Object.getOwnPropertyDescriptors(Z)),A_=(Y)=>{let Z=Object.keys(Y).sort(),X={};for(let _=0;_<Z.length;_++)X[Z[_]]=Y[Z[_]];return X};var A1=x1("represents an uninitialized value"),w_=(Y)=>Object.values(Y).filter((Z)=>{if(typeof Z==="number")return!0;return typeof Y[Z]!=="number"});var UZ={Array,Boolean,Date,Error,Function,Map,Number,Promise,RegExp,Set,String,WeakMap,WeakSet},OZ=globalThis.File??Blob,EZ={ArrayBuffer,Blob,File:OZ,FormData,Headers,Request,Response,URL},vJ={Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array},P4={...UZ,...EZ,...vJ,String,Number,Boolean},v8=(Y)=>{let Z=Object.getPrototypeOf(Y);while(Z?.constructor&&(!p0(Z.constructor.name,P4)||!(Y instanceof P4[Z.constructor.name])))Z=Object.getPrototypeOf(Z);let X=Z?.constructor?.name;if(X===void 0||X==="Object")return;return X},x8=(Y)=>typeof Y==="object"&&Y!==null?v8(Y)??"object":y0(Y);var O0=Array.isArray,xJ={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"},hJ={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"},fJ={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"},R_={...xJ,...hJ,...fJ},h8=(Y)=>{let Z=Object(Y).name??null;return Z&&p0(Z,P4)&&P4[Z]===Y?Z:null};var DZ=(Y,Z)=>{let X=Y.prototype;while(X!==null){if(X===Z.prototype)return!0;X=Object.getPrototypeOf(X)}return!1};var N_=(Y)=>I_(Y,new Map),I_=(Y,Z)=>{if(typeof Y!=="object"||Y===null)return Y;if(Z?.has(Y))return Z.get(Y);let X=h8(Y.constructor);if(X==="Date")return new Date(Y.getTime());if(X&&X!=="Array")return Y;let _=Array.isArray(Y)?Y.slice():Object.create(Object.getPrototypeOf(Y)),G=Object.getOwnPropertyDescriptors(Y);if(Z){Z.set(Y,_);for(let W in G){let H=G[W];if("get"in H||"set"in H)continue;H.value=I_(H.value,Z)}}return Object.defineProperties(_,G),_};var bJ=(Y)=>{let Z=A1;return()=>Z===A1?Z=Y():Z},O4=(Y)=>typeof Y==="function"&&Y.length===0;var B_=class extends Function{constructor(...Y){let Z=Y.slice(0,-1),X=Y.at(-1);try{super(...Z,X)}catch(_){return _0(`Encountered an unexpected error while compiling your definition:
3
+ var BH=Object.create;var{getPrototypeOf:CH,defineProperty:zY,getOwnPropertyNames:TH}=Object;var KH=Object.prototype.hasOwnProperty;var hO=(Y,Z,X)=>{X=Y!=null?BH(CH(Y)):{};let _=Z||!Y||!Y.__esModule?zY(X,"default",{value:Y,enumerable:!0}):X;for(let G of TH(Y))if(!KH.call(_,G))zY(_,G,{get:()=>Y[G],enumerable:!0});return _};var fO=(Y,Z)=>()=>(Z||Y((Z={exports:{}}).exports,Z),Z.exports);var qH=(Y,Z)=>{for(var X in Z)zY(Y,X,{get:Z[X],enumerable:!0,configurable:!0,set:(_)=>Z[X]=()=>_})};var bO=(Y,Z)=>()=>(Y&&(Z=Y(Y=0)),Z);var kO=import.meta.require;import jO,{join as PO,normalize as SO,resolve as S$}from"path";var F4=(Y)=>Array.isArray(Y)?Y:[Y],zX=(Y,Z)=>{let X=[[],[]];for(let _ of Y)if(Z(_))X[0].push(_);else X[1].push(_);return X},g2=Array,s1=(Y,Z)=>Y.includes(Z),UX=(Y,Z=0)=>[...new Array(Y)].map((X,_)=>_+Z),Z0=(Y,Z,X)=>{if(Y===void 0)return Z===void 0?[]:Array.isArray(Z)?Z:[Z];if(X?.prepend)if(Array.isArray(Z))Y.unshift(...Z);else Y.unshift(Z);else if(Array.isArray(Z))Y.push(...Z);else Y.push(Z);return Y},a1=(Y,Z)=>{if(Z===void 0||Z===null)return Y??[];if(Y===void 0||Y===null)return F4(Z);return Y.concat(Z)},FX=(...Y)=>Y.reduce(a1,[]),d1=(Y,Z,X)=>{if(Y===void 0)return Array.isArray(Z)?Z:[Z];let _=X?.isEqual??((G,W)=>G===W);for(let G of F4(Z))if(!Y.some((W)=>_(W,G)))Y.push(G);return Y},OX=(Y,Z)=>Y.reduce((X,_)=>{let G=_[Z];return X[G]=Z0(X[G],_),X},{}),t1=(Y,Z,X)=>Y.length===Z.length&&Y.every(X?.isEqual?(_,G)=>X.isEqual(_,Z[G]):(_,G)=>_===Z[G]);var Q1=(Y,Z)=>y0(Y)===Z,y0=(Y)=>{let Z=typeof Y;return Z==="object"?Y===null?"null":"object":Z==="function"?"object":Z},z1={boolean:"boolean",null:"null",undefined:"undefined",bigint:"a bigint",number:"a number",object:"an object",string:"a string",symbol:"a symbol"},EX={...z1,function:"a function"};class DX extends Error{}var _0=(Y)=>q4(Y,DX),q4=(Y,Z=Error)=>{throw new Z(Y)};class S8 extends Error{name="ParseError"}var w=(Y)=>q4(Y,S8),x1=(Y)=>` ${Y}`;var o=(Y,Z)=>{let X={},_=Array.isArray(Y),G=!1;for(let[W,$]of Object.entries(Y).entries()){let H=_?Z(W,$[1]):Z(...$,W);G||=typeof H[0]==="number";let Q=Array.isArray(H[0])||H.length===0?H:[H];for(let[J,z]of Q)if(typeof J==="object")X[J.group]=Z0(X[J.group],z);else X[J]=z}return G?Object.values(X):X};var UY=Object.entries;var p0=(Y,Z)=>(Y in Z),n4=(Y,Z)=>(Z in Y);class FY{constructor(Y){Object.assign(this,Y)}}var LX=class{};class v8 extends LX{}var jH=(Y,Z)=>{let X={},_={},G;for(G in Y)if(G in Z)X[G]=Y[G];else _[G]=Y[G];return[X,_]};var VX=(Y,Z)=>jH(Y,Z)[1],c1=(Y)=>Object.keys(Y).length===0,j4=(Y)=>[...Object.entries(Y),...Object.getOwnPropertySymbols(Y).map((Z)=>[Z,Y[Z]])],MX=(Y,Z)=>Object.defineProperties(Y,Object.getOwnPropertyDescriptors(Z)),AX=(Y)=>{let Z=Object.keys(Y).sort(),X={};for(let _=0;_<Z.length;_++)X[Z[_]]=Y[Z[_]];return X};var A1=x1("represents an uninitialized value"),wX=(Y)=>Object.values(Y).filter((Z)=>{if(typeof Z==="number")return!0;return typeof Y[Z]!=="number"});var OY={Array,Boolean,Date,Error,Function,Map,Number,Promise,RegExp,Set,String,WeakMap,WeakSet},EY=globalThis.File??Blob,DY={ArrayBuffer,Blob,File:EY,FormData,Headers,Request,Response,URL},PH={Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array},P4={...OY,...DY,...PH,String,Number,Boolean},x8=(Y)=>{let Z=Object.getPrototypeOf(Y);while(Z?.constructor&&(!p0(Z.constructor.name,P4)||!(Y instanceof P4[Z.constructor.name])))Z=Object.getPrototypeOf(Z);let X=Z?.constructor?.name;if(X===void 0||X==="Object")return;return X},h8=(Y)=>typeof Y==="object"&&Y!==null?x8(Y)??"object":y0(Y);var O0=Array.isArray,SH={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"},vH={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"},xH={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"},RX={...SH,...vH,...xH},f8=(Y)=>{let Z=Object(Y).name??null;return Z&&p0(Z,P4)&&P4[Z]===Y?Z:null};var LY=(Y,Z)=>{let X=Y.prototype;while(X!==null){if(X===Z.prototype)return!0;X=Object.getPrototypeOf(X)}return!1};var NX=(Y)=>IX(Y,new Map),IX=(Y,Z)=>{if(typeof Y!=="object"||Y===null)return Y;if(Z?.has(Y))return Z.get(Y);let X=f8(Y.constructor);if(X==="Date")return new Date(Y.getTime());if(X&&X!=="Array")return Y;let _=Array.isArray(Y)?Y.slice():Object.create(Object.getPrototypeOf(Y)),G=Object.getOwnPropertyDescriptors(Y);if(Z){Z.set(Y,_);for(let W in G){let $=G[W];if("get"in $||"set"in $)continue;$.value=IX($.value,Z)}}return Object.defineProperties(_,G),_};var hH=(Y)=>{let Z=A1;return()=>Z===A1?Z=Y():Z},O4=(Y)=>typeof Y==="function"&&Y.length===0;var BX=class extends Function{constructor(...Y){let Z=Y.slice(0,-1),X=Y.at(-1);try{super(...Z,X)}catch(_){return _0(`Encountered an unexpected error while compiling your definition:
4
4
  Message: ${_}
5
5
  Source: (${Y.slice(0,-1)}) => {
6
6
  ${Y.at(-1)}
7
- }`)}}};class h1{constructor(Y,...[Z]){return Object.assign(Object.setPrototypeOf(Y.bind(Z?.bind??this),this.constructor.prototype),Z?.attach)}}var C_=bJ(()=>{try{return new Function("return false")()}catch{return!0}});var HE=x1("brand");var T_=x1("arkInferred");var $E=x1("args");class a0{constructor(){}}var kJ=()=>{try{return((new Error().stack?.split(`
8
- `)[2]?.trim()||"").match(/\(?(.+?)(?::\d+:\d+)?\)?$/)?.[1]||"unknown").replace(/^file:\/\//,"")}catch{return"unknown"}},gJ=globalThis.process?.env??{},K_={fileName:kJ,env:gJ};var q_=(Y)=>Y[0].toUpperCase()+Y.slice(1);var LZ=(Y)=>new RegExp(yJ(Y),typeof Y==="string"?"":Y.flags);var yJ=(Y)=>{return`^(?:${typeof Y==="string"?Y:Y.source})$`};var e1={negativeLookahead:(Y)=>`(?!${Y})`,nonCapturingGroup:(Y)=>`(?:${Y})`},f8="\\",E4={" ":1,"\n":1,"\t":1};var pJ=/^-0\.?0*$/.source,P_=/[1-9]\d*/.source,mJ=/\.\d+/.source,uJ=/\.\d*[1-9]/.source,S_=(Y)=>LZ(e1.negativeLookahead(pJ)+e1.nonCapturingGroup("-?"+e1.nonCapturingGroup(e1.nonCapturingGroup("0|"+P_)+e1.nonCapturingGroup(Y.decimalPattern)+"?")+(Y.allowDecimalOnly?"|"+Y.decimalPattern:"")+"?")),j_=S_({decimalPattern:uJ,allowDecimalOnly:!1}),dJ=j_.test.bind(j_),y6=S_({decimalPattern:mJ,allowDecimalOnly:!0}),LE=y6.test.bind(y6),cJ=/^-?\d*\.?\d*$/,lJ=(Y)=>Y.length!==0&&cJ.test(Y),b8=LZ(e1.negativeLookahead("^-0$")+"-?"+e1.nonCapturingGroup(e1.nonCapturingGroup("0|"+P_))),iJ=b8.test.bind(b8),VZ=/^-?\d+$/,oJ=VZ.test.bind(VZ),v_={number:"a number",bigint:"a bigint",integer:"an integer"},x_=(Y,Z)=>`'${Y}' was parsed as ${v_[Z]} but could not be narrowed to a literal value. Avoid unnecessary leading or trailing zeros and other abnormal notation`,nJ=(Y,Z)=>Z==="number"?dJ(Y):iJ(Y),rJ=(Y,Z)=>Z==="number"?Number(Y):Number.parseInt(Y),sJ=(Y,Z)=>Z==="number"?lJ(Y):oJ(Y),h_=(Y,Z)=>MZ(Y,"number",Z),f_=(Y,Z)=>MZ(Y,"number",{...Z,strict:!0}),b_=(Y,Z)=>MZ(Y,"integer",Z),MZ=(Y,Z,X)=>{let _=rJ(Y,Z);if(!Number.isNaN(_)){if(sJ(Y,Z)){if(X?.strict)return nJ(Y,Z)?_:w(x_(Y,Z));return _}}return X?.errorOnFail?w(X?.errorOnFail===!0?`Failed to parse ${v_[Z]} from '${Y}'`:X?.errorOnFail):void 0},k_=(Y)=>{if(Y[Y.length-1]!=="n")return;let Z=Y.slice(0,-1),X;try{X=BigInt(Z)}catch{return}if(b8.test(Z))return X;if(VZ.test(Z))return w(x_(Y,"bigint"))};var aJ="0.46.0",tJ={version:aJ,filename:K_.fileName(),FileConstructor:OZ},S4=tJ,g_=new Map,AZ=Object.create(null),k8=(Y)=>{let Z=g_.get(Y);if(Z)return Z;let X=eJ(Y);if(AZ[X])X=`${X}${AZ[X]++}`;else AZ[X]=1;return S4[X]=Y,g_.set(Y,X),X},D4=(Y)=>/^[$A-Z_a-z][\w$]*$/.test(Y),eJ=(Y)=>{switch(typeof Y){case"object":{if(Y===null)break;let Z=v8(Y)??"object";return Z[0].toLowerCase()+Z.slice(1)}case"function":return D4(Y.name)?Y.name:"fn";case"symbol":return Y.description&&D4(Y.description)?Y.description:"symbol"}return _0(`Unexpected attempt to register serializable value of type ${y0(Y)}`)};var g8=(Y)=>typeof Y==="string"?JSON.stringify(Y):typeof Y==="bigint"?`${Y}n`:`${Y}`;var y_=(Y,Z={})=>y8(Y,{onUndefined:"$ark.undefined",onBigInt:(X)=>`$ark.bigint-${X}`,...Z},[]);var n=(Y,Z)=>{switch(y0(Y)){case"object":let X=Y,_=X.constructor.name;return _==="Object"||_==="Array"?Z?.quoteKeys===!1?p6(X,Z?.indent??0,""):JSON.stringify(y8(X,r4,[]),null,Z?.indent):p6(X,Z?.indent??0,"");case"symbol":return r4.onSymbol(Y);default:return g8(Y)}},p6=(Y,Z,X)=>{if(typeof Y==="function")return r4.onFunction(Y);if(typeof Y!=="object"||Y===null)return g8(Y);let _=X+" ".repeat(Z);if(Array.isArray(Y)){if(Y.length===0)return"[]";let W=Y.map((H)=>p6(H,Z,_)).join(`,
7
+ }`)}}};class h1{constructor(Y,...[Z]){return Object.assign(Object.setPrototypeOf(Y.bind(Z?.bind??this),this.constructor.prototype),Z?.attach)}}var CX=hH(()=>{try{return new Function("return false")()}catch{return!0}});var GE=x1("brand");var TX=x1("arkInferred");var HE=x1("args");class a0{constructor(){}}var fH=()=>{try{return((new Error().stack?.split(`
8
+ `)[2]?.trim()||"").match(/\(?(.+?)(?::\d+:\d+)?\)?$/)?.[1]||"unknown").replace(/^file:\/\//,"")}catch{return"unknown"}},bH=globalThis.process?.env??{},KX={fileName:fH,env:bH};var qX=(Y)=>Y[0].toUpperCase()+Y.slice(1);var VY=(Y)=>new RegExp(kH(Y),typeof Y==="string"?"":Y.flags);var kH=(Y)=>{return`^(?:${typeof Y==="string"?Y:Y.source})$`};var e1={negativeLookahead:(Y)=>`(?!${Y})`,nonCapturingGroup:(Y)=>`(?:${Y})`},b8="\\",E4={" ":1,"\n":1,"\t":1};var gH=/^-0\.?0*$/.source,PX=/[1-9]\d*/.source,yH=/\.\d+/.source,pH=/\.\d*[1-9]/.source,SX=(Y)=>VY(e1.negativeLookahead(gH)+e1.nonCapturingGroup("-?"+e1.nonCapturingGroup(e1.nonCapturingGroup("0|"+PX)+e1.nonCapturingGroup(Y.decimalPattern)+"?")+(Y.allowDecimalOnly?"|"+Y.decimalPattern:"")+"?")),jX=SX({decimalPattern:pH,allowDecimalOnly:!1}),mH=jX.test.bind(jX),y2=SX({decimalPattern:yH,allowDecimalOnly:!0}),EE=y2.test.bind(y2),uH=/^-?\d*\.?\d*$/,dH=(Y)=>Y.length!==0&&uH.test(Y),k8=VY(e1.negativeLookahead("^-0$")+"-?"+e1.nonCapturingGroup(e1.nonCapturingGroup("0|"+PX))),cH=k8.test.bind(k8),MY=/^-?\d+$/,lH=MY.test.bind(MY),vX={number:"a number",bigint:"a bigint",integer:"an integer"},xX=(Y,Z)=>`'${Y}' was parsed as ${vX[Z]} but could not be narrowed to a literal value. Avoid unnecessary leading or trailing zeros and other abnormal notation`,iH=(Y,Z)=>Z==="number"?mH(Y):cH(Y),oH=(Y,Z)=>Z==="number"?Number(Y):Number.parseInt(Y),nH=(Y,Z)=>Z==="number"?dH(Y):lH(Y),hX=(Y,Z)=>AY(Y,"number",Z),fX=(Y,Z)=>AY(Y,"number",{...Z,strict:!0}),bX=(Y,Z)=>AY(Y,"integer",Z),AY=(Y,Z,X)=>{let _=oH(Y,Z);if(!Number.isNaN(_)){if(nH(Y,Z)){if(X?.strict)return iH(Y,Z)?_:w(xX(Y,Z));return _}}return X?.errorOnFail?w(X?.errorOnFail===!0?`Failed to parse ${vX[Z]} from '${Y}'`:X?.errorOnFail):void 0},kX=(Y)=>{if(Y[Y.length-1]!=="n")return;let Z=Y.slice(0,-1),X;try{X=BigInt(Z)}catch{return}if(k8.test(Z))return X;if(MY.test(Z))return w(xX(Y,"bigint"))};var rH="0.46.0",sH={version:rH,filename:KX.fileName(),FileConstructor:EY},S4=sH,gX=new Map,wY=Object.create(null),g8=(Y)=>{let Z=gX.get(Y);if(Z)return Z;let X=aH(Y);if(wY[X])X=`${X}${wY[X]++}`;else wY[X]=1;return S4[X]=Y,gX.set(Y,X),X},D4=(Y)=>/^[$A-Z_a-z][\w$]*$/.test(Y),aH=(Y)=>{switch(typeof Y){case"object":{if(Y===null)break;let Z=x8(Y)??"object";return Z[0].toLowerCase()+Z.slice(1)}case"function":return D4(Y.name)?Y.name:"fn";case"symbol":return Y.description&&D4(Y.description)?Y.description:"symbol"}return _0(`Unexpected attempt to register serializable value of type ${y0(Y)}`)};var y8=(Y)=>typeof Y==="string"?JSON.stringify(Y):typeof Y==="bigint"?`${Y}n`:`${Y}`;var yX=(Y,Z={})=>p8(Y,{onUndefined:"$ark.undefined",onBigInt:(X)=>`$ark.bigint-${X}`,...Z},[]);var n=(Y,Z)=>{switch(y0(Y)){case"object":let X=Y,_=X.constructor.name;return _==="Object"||_==="Array"?Z?.quoteKeys===!1?p2(X,Z?.indent??0,""):JSON.stringify(p8(X,r4,[]),null,Z?.indent):p2(X,Z?.indent??0,"");case"symbol":return r4.onSymbol(Y);default:return y8(Y)}},p2=(Y,Z,X)=>{if(typeof Y==="function")return r4.onFunction(Y);if(typeof Y!=="object"||Y===null)return y8(Y);let _=X+" ".repeat(Z);if(Array.isArray(Y)){if(Y.length===0)return"[]";let W=Y.map(($)=>p2($,Z,_)).join(`,
9
9
  `+_);return Z?`[
10
10
  ${_}${W}
11
- ${X}]`:`[${W}]`}let G=Y.constructor.name;if(G==="Object"){let W=j4(Y).map(([H,J])=>{let $=typeof H==="symbol"?r4.onSymbol(H):D4(H)?H:JSON.stringify(H),Q=p6(J,Z,_);return`${_}${$}: ${Q}`});if(W.length===0)return"{}";return Z?`{
11
+ ${X}]`:`[${W}]`}let G=Y.constructor.name;if(G==="Object"){let W=j4(Y).map(([$,H])=>{let Q=typeof $==="symbol"?r4.onSymbol($):D4($)?$:JSON.stringify($),J=p2(H,Z,_);return`${_}${Q}: ${J}`});if(W.length===0)return"{}";return Z?`{
12
12
  ${W.join(`,
13
13
  `)}
14
- ${X}}`:`{${W.join(", ")}}`}if(Y instanceof Date)return v4(Y);if("expression"in Y&&typeof Y.expression==="string")return Y.expression;return G},r4={onCycle:()=>"(cycle)",onSymbol:(Y)=>`Symbol(${k8(Y)})`,onFunction:(Y)=>`Function(${k8(Y)})`},y8=(Y,Z,X)=>{switch(y0(Y)){case"object":{let _=Y;if("toJSON"in _&&typeof _.toJSON==="function")return _.toJSON();if(typeof _==="function")return r4.onFunction(_);if(X.includes(_))return"(cycle)";let G=[...X,_];if(Array.isArray(_))return _.map((H)=>y8(H,Z,G));if(_ instanceof Date)return _.toDateString();let W={};for(let H in _)W[H]=y8(_[H],Z,G);for(let H of Object.getOwnPropertySymbols(_))W[Z.onSymbol?.(H)??H.toString()]=y8(_[H],Z,G);return W}case"symbol":return r4.onSymbol(Y);case"bigint":return Z.onBigInt?.(Y)??`${Y}n`;case"undefined":return Z.onUndefined??"undefined";case"string":return Y.replaceAll("\\","\\\\");default:return Y}},v4=(Y)=>{let Z=Y.getFullYear(),X=Y.getMonth(),_=Y.getDate(),G=Y.getHours(),W=Y.getMinutes(),H=Y.getSeconds(),J=Y.getMilliseconds();if(X===0&&_===1&&G===0&&W===0&&H===0&&J===0)return`${Z}`;let $=`${YQ[X]} ${_}, ${Z}`;if(G===0&&W===0&&H===0&&J===0)return $;let Q=Y.toLocaleTimeString(),z=Q.endsWith(" AM")||Q.endsWith(" PM")?Q.slice(-3):"";if(z)Q=Q.slice(0,-z.length);if(J)Q+=`.${XQ(J,3)}`;else if(ZQ.test(Q))Q=Q.slice(0,-3);return`${Q+z}, ${$}`},YQ=["January","February","March","April","May","June","July","August","September","October","November","December"],ZQ=/:\d\d:00$/,XQ=(Y,Z)=>String(Y).padStart(Z,"0");var p_=(Y,Z,...[X])=>{let _=X?.stringifySymbol??n,G=Y;switch(typeof Z){case"string":G=D4(Z)?Y===""?Z:`${Y}.${Z}`:`${Y}[${JSON.stringify(Z)}]`;break;case"number":G=`${Y}[${Z}]`;break;case"symbol":G=`${Y}[${_(Z)}]`;break;default:if(X?.stringifyNonKey)G=`${Y}[${X.stringifyNonKey(Z)}]`;else w(`${n(Z)} must be a PropertyKey or stringifyNonKey must be passed to options`)}return G},Y4=(Y,...Z)=>Y.reduce((X,_)=>p_(X,_,...Z),"");class p8 extends g6{cache={};constructor(...Y){super();this.push(...Y)}toJSON(){if(this.cache.json)return this.cache.json;this.cache.json=[];for(let Y=0;Y<this.length;Y++)this.cache.json.push(typeof this[Y]==="symbol"?n(this[Y]):this[Y]);return this.cache.json}stringify(){if(this.cache.stringify)return this.cache.stringify;return this.cache.stringify=Y4(this)}stringifyAncestors(){if(this.cache.stringifyAncestors)return this.cache.stringifyAncestors;let Y="",Z=[Y];for(let X of this)Y=p_(Y,X),Z.push(Y);return this.cache.stringifyAncestors=Z}}class wZ{chars;i;def;constructor(Y){this.def=Y,this.chars=[...Y],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(Y){let Z="";while(this.lookahead){if(Y(this,Z))if(Z[Z.length-1]===f8)Z=Z.slice(0,-1);else break;Z+=this.shift()}return Z}shiftUntilLookahead(Y){return typeof Y==="string"?this.shiftUntil((Z)=>Z.lookahead===Y):this.shiftUntil((Z)=>(Z.lookahead in Y))}shiftUntilNonWhitespace(){return this.shiftUntil(()=>!(this.lookahead in E4))}jumpToIndex(Y){this.i=Y<0?this.length+Y:Y}jumpForward(Y){this.i+=Y}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(Y,Z){return this.chars.slice(Y,Z).join("")}lookaheadIs(Y){return this.lookahead===Y}lookaheadIsIn(Y){return this.lookahead in Y}}var mE=x1("implementedTraits");var RZ="$ark",_Q=2;while(RZ in globalThis)RZ=`$ark${_Q++}`;var m_=RZ;globalThis[m_]=S4;var B=S4,GQ=(Y)=>`${m_}.${Y}`,K0=(Y)=>GQ(k8(Y));class m6 extends S8{argNames;body="";constructor(...Y){super();this.argNames=Y;for(let Z of Y){if(Z in this)throw new Error(`Arg name '${Z}' would overwrite an existing property on FunctionBody`);this[Z]=Z}}indentation=0;indent(){return this.indentation+=4,this}dedent(){return this.indentation-=4,this}prop(Y,Z=!1){return NZ(Y,Z)}index(Y,Z=!1){return u_(`${Y}`,Z)}line(Y){return this.body+=`${" ".repeat(this.indentation)}${Y}
14
+ ${X}}`:`{${W.join(", ")}}`}if(Y instanceof Date)return v4(Y);if("expression"in Y&&typeof Y.expression==="string")return Y.expression;return G},r4={onCycle:()=>"(cycle)",onSymbol:(Y)=>`Symbol(${g8(Y)})`,onFunction:(Y)=>`Function(${g8(Y)})`},p8=(Y,Z,X)=>{switch(y0(Y)){case"object":{let _=Y;if("toJSON"in _&&typeof _.toJSON==="function")return _.toJSON();if(typeof _==="function")return r4.onFunction(_);if(X.includes(_))return"(cycle)";let G=[...X,_];if(Array.isArray(_))return _.map(($)=>p8($,Z,G));if(_ instanceof Date)return _.toDateString();let W={};for(let $ in _)W[$]=p8(_[$],Z,G);for(let $ of Object.getOwnPropertySymbols(_))W[Z.onSymbol?.($)??$.toString()]=p8(_[$],Z,G);return W}case"symbol":return r4.onSymbol(Y);case"bigint":return Z.onBigInt?.(Y)??`${Y}n`;case"undefined":return Z.onUndefined??"undefined";case"string":return Y.replaceAll("\\","\\\\");default:return Y}},v4=(Y)=>{let Z=Y.getFullYear(),X=Y.getMonth(),_=Y.getDate(),G=Y.getHours(),W=Y.getMinutes(),$=Y.getSeconds(),H=Y.getMilliseconds();if(X===0&&_===1&&G===0&&W===0&&$===0&&H===0)return`${Z}`;let Q=`${tH[X]} ${_}, ${Z}`;if(G===0&&W===0&&$===0&&H===0)return Q;let J=Y.toLocaleTimeString(),z=J.endsWith(" AM")||J.endsWith(" PM")?J.slice(-3):"";if(z)J=J.slice(0,-z.length);if(H)J+=`.${YJ(H,3)}`;else if(eH.test(J))J=J.slice(0,-3);return`${J+z}, ${Q}`},tH=["January","February","March","April","May","June","July","August","September","October","November","December"],eH=/:\d\d:00$/,YJ=(Y,Z)=>String(Y).padStart(Z,"0");var pX=(Y,Z,...[X])=>{let _=X?.stringifySymbol??n,G=Y;switch(typeof Z){case"string":G=D4(Z)?Y===""?Z:`${Y}.${Z}`:`${Y}[${JSON.stringify(Z)}]`;break;case"number":G=`${Y}[${Z}]`;break;case"symbol":G=`${Y}[${_(Z)}]`;break;default:if(X?.stringifyNonKey)G=`${Y}[${X.stringifyNonKey(Z)}]`;else w(`${n(Z)} must be a PropertyKey or stringifyNonKey must be passed to options`)}return G},Y4=(Y,...Z)=>Y.reduce((X,_)=>pX(X,_,...Z),"");class m8 extends g2{cache={};constructor(...Y){super();this.push(...Y)}toJSON(){if(this.cache.json)return this.cache.json;this.cache.json=[];for(let Y=0;Y<this.length;Y++)this.cache.json.push(typeof this[Y]==="symbol"?n(this[Y]):this[Y]);return this.cache.json}stringify(){if(this.cache.stringify)return this.cache.stringify;return this.cache.stringify=Y4(this)}stringifyAncestors(){if(this.cache.stringifyAncestors)return this.cache.stringifyAncestors;let Y="",Z=[Y];for(let X of this)Y=pX(Y,X),Z.push(Y);return this.cache.stringifyAncestors=Z}}class RY{chars;i;def;constructor(Y){this.def=Y,this.chars=[...Y],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(Y){let Z="";while(this.lookahead){if(Y(this,Z))if(Z[Z.length-1]===b8)Z=Z.slice(0,-1);else break;Z+=this.shift()}return Z}shiftUntilLookahead(Y){return typeof Y==="string"?this.shiftUntil((Z)=>Z.lookahead===Y):this.shiftUntil((Z)=>(Z.lookahead in Y))}shiftUntilNonWhitespace(){return this.shiftUntil(()=>!(this.lookahead in E4))}jumpToIndex(Y){this.i=Y<0?this.length+Y:Y}jumpForward(Y){this.i+=Y}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(Y,Z){return this.chars.slice(Y,Z).join("")}lookaheadIs(Y){return this.lookahead===Y}lookaheadIsIn(Y){return this.lookahead in Y}}var yE=x1("implementedTraits");var NY="$ark",ZJ=2;while(NY in globalThis)NY=`$ark${ZJ++}`;var mX=NY;globalThis[mX]=S4;var B=S4,XJ=(Y)=>`${mX}.${Y}`,K0=(Y)=>XJ(g8(Y));class m2 extends v8{argNames;body="";constructor(...Y){super();this.argNames=Y;for(let Z of Y){if(Z in this)throw new Error(`Arg name '${Z}' would overwrite an existing property on FunctionBody`);this[Z]=Z}}indentation=0;indent(){return this.indentation+=4,this}dedent(){return this.indentation-=4,this}prop(Y,Z=!1){return IY(Y,Z)}index(Y,Z=!1){return uX(`${Y}`,Z)}line(Y){return this.body+=`${" ".repeat(this.indentation)}${Y}
15
15
  `,this}const(Y,Z){return this.line(`const ${Y} = ${Z}`),this}let(Y,Z){return this.line(`let ${Y} = ${Z}`)}set(Y,Z){return this.line(`${Y} = ${Z}`)}if(Y,Z){return this.block(`if (${Y})`,Z)}elseIf(Y,Z){return this.block(`else if (${Y})`,Z)}else(Y){return this.block("else",Y)}for(Y,Z,X=0){return this.block(`for (let i = ${X}; ${Y}; i++)`,Z)}forIn(Y,Z){return this.block(`for (const k in ${Y})`,Z)}block(Y,Z,X=""){return this.line(`${Y} {`),this.indent(),Z(this),this.dedent(),this.line(`}${X}`)}return(Y=""){return this.line(`return ${Y}`)}write(Y="anonymous",Z=0){return`${Y}(${this.argNames.join(", ")}) { ${Z?this.body.split(`
16
16
  `).map((X)=>" ".repeat(Z)+`${X}`).join(`
17
- `):this.body} }`}compile(){return new B_(...this.argNames,this.body)}}var Z4=(Y)=>$1(Y,"object")||typeof Y==="symbol"?K0(Y):g8(Y),NZ=(Y,Z=!1)=>{if(typeof Y==="string"&&D4(Y))return`${Z?"?":""}.${Y}`;return u_(WQ(Y),Z)},WQ=(Y)=>typeof Y==="symbol"?K0(Y):JSON.stringify(Y),u_=(Y,Z=!1)=>`${Z?"?.":""}[${Y}]`;class m8 extends m6{traversalKind;optimistic;constructor(Y){super("data","ctx");this.traversalKind=Y.kind,this.optimistic=Y.optimistic===!0}invoke(Y,Z){let X=Z?.arg??this.data,_=typeof Y==="string"?!0:this.requiresContextFor(Y),G=typeof Y==="string"?Y:Y.id;if(_)return`${this.referenceToId(G,Z)}(${X}, ${this.ctx})`;return`${this.referenceToId(G,Z)}(${X})`}referenceToId(Y,Z){let X=Z?.kind??this.traversalKind,_=`this.${Y}${X}`;return Z?.bind?`${_}.bind(${Z?.bind})`:_}requiresContextFor(Y){return this.traversalKind==="Apply"||Y.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(Y,Z,X){let _=this.requiresContextFor(X);if(_)this.line(`${this.ctx}.path.push(${Y})`);if(this.check(X,{arg:Z}),_)this.line(`${this.ctx}.path.pop()`);return this}check(Y,Z){return this.traversalKind==="Allows"?this.if(`!${this.invoke(Y,Z)}`,()=>this.return(!1)):this.line(this.invoke(Y,Z))}}var u6=(Y)=>o(Y,(Z,X)=>[Z,O0(X)?[...X]:X]),X1=x1("arkKind"),y=(Y,Z)=>Y?.[X1]===Z,V0=(Y)=>y(Y,"root")||y(Y,"constraint");var d_=["unit","proto","domain"],s4=["required","optional","index","sequence"],IZ=["pattern","divisor","exactLength","max","min","maxLength","minLength","before","after"],d6=[...IZ,...s4,"structure","predicate"],a4=["alias","union","morph","unit","intersection","proto","domain"],HQ=[...a4,...d6],c6=o(d6,(Y,Z)=>[Z,1]),c_=o([...s4,"undeclared"],(Y,Z)=>[Z,1]),l_=o(HQ,(Y,Z)=>[Z,Y]),t4=(Y)=>typeof Y==="string"&&(Y in l_);var e4=(Y)=>l_[Y],l6=(Y)=>a4.slice(e4(Y)+1),BD=[...l6("union"),"alias"],CD=[...l6("morph"),"alias"],B1=(Y)=>{if(typeof Y==="string"||typeof Y==="boolean"||Y===null)return Y;if(typeof Y==="number"){if(Number.isNaN(Y))return"NaN";if(Y===Number.POSITIVE_INFINITY)return"Infinity";if(Y===Number.NEGATIVE_INFINITY)return"-Infinity";return Y}return Z4(Y)},L4=(Y)=>{let Z="{ ";for(let[X,_]of Object.entries(Y))Z+=`${X}: ${Z4(_)}, `;return Z+" }"},r=(Y)=>{let Z=Y;if(Z.hasAssociatedError)Z.defaults.expected??=(X)=>("description"in X)?X.description:Z.defaults.description(X),Z.defaults.actual??=(X)=>n(X),Z.defaults.problem??=(X)=>`must be ${X.expected}${X.actual?` (was ${X.actual})`:""}`,Z.defaults.message??=(X)=>{if(X.path.length===0)return X.problem;let _=`${X.propString} ${X.problem}`;if(_[0]==="[")return`value at ${_}`;return _};return Z};class i_ extends Error{name="ToJsonSchemaError";code;context;constructor(Y,Z){super(n(Z,{quoteKeys:!1,indent:4}));this.code=Y,this.context=Z}hasCode(Y){return this.code===Y}}var JQ={dialect:"https://json-schema.org/draft/2020-12/schema",useRefs:!1,fallback:{arrayObject:(Y)=>N0.throw("arrayObject",Y),arrayPostfix:(Y)=>N0.throw("arrayPostfix",Y),defaultValue:(Y)=>N0.throw("defaultValue",Y),domain:(Y)=>N0.throw("domain",Y),morph:(Y)=>N0.throw("morph",Y),patternIntersection:(Y)=>N0.throw("patternIntersection",Y),predicate:(Y)=>N0.throw("predicate",Y),proto:(Y)=>N0.throw("proto",Y),symbolKey:(Y)=>N0.throw("symbolKey",Y),unit:(Y)=>N0.throw("unit",Y),date:(Y)=>N0.throw("date",Y)}},N0={Error:i_,throw:(...Y)=>{throw new N0.Error(...Y)},throwInternalOperandError:(Y,Z)=>_0(`Unexpected JSON Schema input for ${Y}: ${n(Z)}`),defaultConfig:JQ};B.config??={};var u8=(Y,Z)=>{if(!Z)return Y;let X={...Y},_;for(_ in Z){let G={...Y.keywords};if(_==="keywords"){for(let W in Z[_]){let H=Z.keywords[W];if(H===void 0)continue;G[W]=typeof H==="string"?{description:H}:H}X.keywords=G}else if(_==="toJsonSchema")X[_]=BZ(Y.toJsonSchema,Z.toJsonSchema);else if(t4(_))X[_]={...Y[_],...Z[_]};else X[_]=Z[_]}return X},BZ=(Y,Z)=>{if(!Y)return Z??{};if(!Z)return Y;let X={...Y},_;for(_ in Z)if(_==="fallback")X.fallback=QQ(Y.fallback,Z.fallback);else X[_]=Z[_];return X},QQ=(Y,Z)=>{Y=o_(Y),Z=o_(Z);let X={},_;for(_ in N0.defaultConfig.fallback)X[_]=Z[_]??Z.default??Y[_]??Y.default??N0.defaultConfig.fallback[_];return X},o_=(Y)=>typeof Y==="function"?{default:Y}:Y??{};class V4 extends S8{[X1]="error";path;data;nodeConfig;input;ctx;constructor({prefixPath:Y,relativePath:Z,...X},_){super();this.input=X,this.ctx=_,M_(this,X);let G=_.data;if(X.code==="union")X.errors=X.errors.flatMap((H)=>{let J=H.hasCode("union")?H.errors:[H];if(!Y&&!Z)return J;return J.map(($)=>$.transform((Q)=>({...Q,path:U_(Y,Q.path,Z)})))});this.nodeConfig=_.config[this.code];let W=[...X.path??_.path];if(Z)W.push(...Z);if(Y)W.unshift(...Y);this.path=new p8(...W),this.data="data"in X?X.data:G}transform(Y){return new V4(Y({data:this.data,path:this.path,...this.input}),this.ctx)}hasCode(Y){return this.code===Y}get propString(){return Y4(this.path)}get expected(){if(this.input.expected)return this.input.expected;let Y=this.meta?.expected??this.nodeConfig.expected;return typeof Y==="function"?Y(this.input):Y}get actual(){if(this.input.actual)return this.input.actual;let Y=this.meta?.actual??this.nodeConfig.actual;return typeof Y==="function"?Y(this.data):Y}get problem(){if(this.input.problem)return this.input.problem;let Y=this.meta?.problem??this.nodeConfig.problem;return typeof Y==="function"?Y(this):Y}get message(){if(this.input.message)return this.input.message;let Y=this.meta?.message??this.nodeConfig.message;return typeof Y==="function"?Y(this):Y}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 F1 extends g6{[X1]="errors";ctx;constructor(Y){super();this.ctx=Y}byPath=Object.create(null);get flatByPath(){return o(this.byPath,(Y,Z)=>[Y,Z.flat])}get flatProblemsByPath(){return o(this.byPath,(Y,Z)=>[Y,Z.flat.map((X)=>X.problem)])}byAncestorPath=Object.create(null);count=0;mutable=this;throw(){throw this.toTraversalError()}toTraversalError(){return new CZ(this)}add(Y){if(this.includes(Y))return;this._add(Y)}transform(Y){let Z=new F1(this.ctx);for(let X of this)Z.add(Y(X));return Z}merge(Y){for(let Z of Y){if(this.includes(Z))continue;this._add(new V4({...Z,path:[...this.ctx.path,...Z.path]},this.ctx))}}affectsPath(Y){if(this.length===0)return!1;return Y.stringifyAncestors().some((Z)=>(Z in this.byPath))||Y.stringify()in this.byAncestorPath}get summary(){return this.toString()}get issues(){return this}toJSON(){return[...this.map((Y)=>Y.toJSON())]}toString(){return this.join(`
18
- `)}_add(Y){let Z=this.byPath[Y.propString];if(Z){if(Z.hasCode("union")&&Z.errors.length===0)return;let X=Y.hasCode("union")&&Y.errors.length===0?Y:new V4({code:"intersection",errors:Z.hasCode("intersection")?[...Z.errors,Y]:[Z,Y]},this.ctx),_=this.indexOf(Z);this.mutable[_===-1?this.length:_]=X,this.byPath[Y.propString]=X,this.addAncestorPaths(Y)}else this.byPath[Y.propString]=Y,this.addAncestorPaths(Y),this.mutable.push(Y);this.count++}addAncestorPaths(Y){for(let Z of Y.path.stringifyAncestors())this.byAncestorPath[Z]=Z0(this.byAncestorPath[Z],Y)}}class CZ extends Error{name="TraversalError";constructor(Y){if(Y.length===1)super(Y.summary);else super(`
19
- `+Y.map((Z)=>` \u2022 ${$Q(Z)}`).join(`
20
- `));Object.defineProperty(this,"arkErrors",{value:Y,enumerable:!1})}}var $Q=(Y)=>Y.toString().split(`
17
+ `):this.body} }`}compile(){return new BX(...this.argNames,this.body)}}var Z4=(Y)=>Q1(Y,"object")||typeof Y==="symbol"?K0(Y):y8(Y),IY=(Y,Z=!1)=>{if(typeof Y==="string"&&D4(Y))return`${Z?"?":""}.${Y}`;return uX(_J(Y),Z)},_J=(Y)=>typeof Y==="symbol"?K0(Y):JSON.stringify(Y),uX=(Y,Z=!1)=>`${Z?"?.":""}[${Y}]`;class u8 extends m2{traversalKind;optimistic;constructor(Y){super("data","ctx");this.traversalKind=Y.kind,this.optimistic=Y.optimistic===!0}invoke(Y,Z){let X=Z?.arg??this.data,_=typeof Y==="string"?!0:this.requiresContextFor(Y),G=typeof Y==="string"?Y:Y.id;if(_)return`${this.referenceToId(G,Z)}(${X}, ${this.ctx})`;return`${this.referenceToId(G,Z)}(${X})`}referenceToId(Y,Z){let X=Z?.kind??this.traversalKind,_=`this.${Y}${X}`;return Z?.bind?`${_}.bind(${Z?.bind})`:_}requiresContextFor(Y){return this.traversalKind==="Apply"||Y.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(Y,Z,X){let _=this.requiresContextFor(X);if(_)this.line(`${this.ctx}.path.push(${Y})`);if(this.check(X,{arg:Z}),_)this.line(`${this.ctx}.path.pop()`);return this}check(Y,Z){return this.traversalKind==="Allows"?this.if(`!${this.invoke(Y,Z)}`,()=>this.return(!1)):this.line(this.invoke(Y,Z))}}var u2=(Y)=>o(Y,(Z,X)=>[Z,O0(X)?[...X]:X]),X1=x1("arkKind"),y=(Y,Z)=>Y?.[X1]===Z,V0=(Y)=>y(Y,"root")||y(Y,"constraint");var dX=["unit","proto","domain"],s4=["required","optional","index","sequence"],BY=["pattern","divisor","exactLength","max","min","maxLength","minLength","before","after"],d2=[...BY,...s4,"structure","predicate"],a4=["alias","union","morph","unit","intersection","proto","domain"],GJ=[...a4,...d2],c2=o(d2,(Y,Z)=>[Z,1]),cX=o([...s4,"undeclared"],(Y,Z)=>[Z,1]),lX=o(GJ,(Y,Z)=>[Z,Y]),t4=(Y)=>typeof Y==="string"&&(Y in lX);var e4=(Y)=>lX[Y],l2=(Y)=>a4.slice(e4(Y)+1),ND=[...l2("union"),"alias"],ID=[...l2("morph"),"alias"],B1=(Y)=>{if(typeof Y==="string"||typeof Y==="boolean"||Y===null)return Y;if(typeof Y==="number"){if(Number.isNaN(Y))return"NaN";if(Y===Number.POSITIVE_INFINITY)return"Infinity";if(Y===Number.NEGATIVE_INFINITY)return"-Infinity";return Y}return Z4(Y)},L4=(Y)=>{let Z="{ ";for(let[X,_]of Object.entries(Y))Z+=`${X}: ${Z4(_)}, `;return Z+" }"},r=(Y)=>{let Z=Y;if(Z.hasAssociatedError)Z.defaults.expected??=(X)=>("description"in X)?X.description:Z.defaults.description(X),Z.defaults.actual??=(X)=>n(X),Z.defaults.problem??=(X)=>`must be ${X.expected}${X.actual?` (was ${X.actual})`:""}`,Z.defaults.message??=(X)=>{if(X.path.length===0)return X.problem;let _=`${X.propString} ${X.problem}`;if(_[0]==="[")return`value at ${_}`;return _};return Z};class iX extends Error{name="ToJsonSchemaError";code;context;constructor(Y,Z){super(n(Z,{quoteKeys:!1,indent:4}));this.code=Y,this.context=Z}hasCode(Y){return this.code===Y}}var WJ={dialect:"https://json-schema.org/draft/2020-12/schema",useRefs:!1,fallback:{arrayObject:(Y)=>N0.throw("arrayObject",Y),arrayPostfix:(Y)=>N0.throw("arrayPostfix",Y),defaultValue:(Y)=>N0.throw("defaultValue",Y),domain:(Y)=>N0.throw("domain",Y),morph:(Y)=>N0.throw("morph",Y),patternIntersection:(Y)=>N0.throw("patternIntersection",Y),predicate:(Y)=>N0.throw("predicate",Y),proto:(Y)=>N0.throw("proto",Y),symbolKey:(Y)=>N0.throw("symbolKey",Y),unit:(Y)=>N0.throw("unit",Y),date:(Y)=>N0.throw("date",Y)}},N0={Error:iX,throw:(...Y)=>{throw new N0.Error(...Y)},throwInternalOperandError:(Y,Z)=>_0(`Unexpected JSON Schema input for ${Y}: ${n(Z)}`),defaultConfig:WJ};B.config??={};var d8=(Y,Z)=>{if(!Z)return Y;let X={...Y},_;for(_ in Z){let G={...Y.keywords};if(_==="keywords"){for(let W in Z[_]){let $=Z.keywords[W];if($===void 0)continue;G[W]=typeof $==="string"?{description:$}:$}X.keywords=G}else if(_==="toJsonSchema")X[_]=CY(Y.toJsonSchema,Z.toJsonSchema);else if(t4(_))X[_]={...Y[_],...Z[_]};else X[_]=Z[_]}return X},CY=(Y,Z)=>{if(!Y)return Z??{};if(!Z)return Y;let X={...Y},_;for(_ in Z)if(_==="fallback")X.fallback=$J(Y.fallback,Z.fallback);else X[_]=Z[_];return X},$J=(Y,Z)=>{Y=oX(Y),Z=oX(Z);let X={},_;for(_ in N0.defaultConfig.fallback)X[_]=Z[_]??Z.default??Y[_]??Y.default??N0.defaultConfig.fallback[_];return X},oX=(Y)=>typeof Y==="function"?{default:Y}:Y??{};class V4 extends v8{[X1]="error";path;data;nodeConfig;input;ctx;constructor({prefixPath:Y,relativePath:Z,...X},_){super();this.input=X,this.ctx=_,MX(this,X);let G=_.data;if(X.code==="union")X.errors=X.errors.flatMap(($)=>{let H=$.hasCode("union")?$.errors:[$];if(!Y&&!Z)return H;return H.map((Q)=>Q.transform((J)=>({...J,path:FX(Y,J.path,Z)})))});this.nodeConfig=_.config[this.code];let W=[...X.path??_.path];if(Z)W.push(...Z);if(Y)W.unshift(...Y);this.path=new m8(...W),this.data="data"in X?X.data:G}transform(Y){return new V4(Y({data:this.data,path:this.path,...this.input}),this.ctx)}hasCode(Y){return this.code===Y}get propString(){return Y4(this.path)}get expected(){if(this.input.expected)return this.input.expected;let Y=this.meta?.expected??this.nodeConfig.expected;return typeof Y==="function"?Y(this.input):Y}get actual(){if(this.input.actual)return this.input.actual;let Y=this.meta?.actual??this.nodeConfig.actual;return typeof Y==="function"?Y(this.data):Y}get problem(){if(this.input.problem)return this.input.problem;let Y=this.meta?.problem??this.nodeConfig.problem;return typeof Y==="function"?Y(this):Y}get message(){if(this.input.message)return this.input.message;let Y=this.meta?.message??this.nodeConfig.message;return typeof Y==="function"?Y(this):Y}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 U1 extends g2{[X1]="errors";ctx;constructor(Y){super();this.ctx=Y}byPath=Object.create(null);get flatByPath(){return o(this.byPath,(Y,Z)=>[Y,Z.flat])}get flatProblemsByPath(){return o(this.byPath,(Y,Z)=>[Y,Z.flat.map((X)=>X.problem)])}byAncestorPath=Object.create(null);count=0;mutable=this;throw(){throw this.toTraversalError()}toTraversalError(){return new TY(this)}add(Y){if(this.includes(Y))return;this._add(Y)}transform(Y){let Z=new U1(this.ctx);for(let X of this)Z.add(Y(X));return Z}merge(Y){for(let Z of Y){if(this.includes(Z))continue;this._add(new V4({...Z,path:[...this.ctx.path,...Z.path]},this.ctx))}}affectsPath(Y){if(this.length===0)return!1;return Y.stringifyAncestors().some((Z)=>(Z in this.byPath))||Y.stringify()in this.byAncestorPath}get summary(){return this.toString()}get issues(){return this}toJSON(){return[...this.map((Y)=>Y.toJSON())]}toString(){return this.join(`
18
+ `)}_add(Y){let Z=this.byPath[Y.propString];if(Z){if(Z.hasCode("union")&&Z.errors.length===0)return;let X=Y.hasCode("union")&&Y.errors.length===0?Y:new V4({code:"intersection",errors:Z.hasCode("intersection")?[...Z.errors,Y]:[Z,Y]},this.ctx),_=this.indexOf(Z);this.mutable[_===-1?this.length:_]=X,this.byPath[Y.propString]=X,this.addAncestorPaths(Y)}else this.byPath[Y.propString]=Y,this.addAncestorPaths(Y),this.mutable.push(Y);this.count++}addAncestorPaths(Y){for(let Z of Y.path.stringifyAncestors())this.byAncestorPath[Z]=Z0(this.byAncestorPath[Z],Y)}}class TY extends Error{name="TraversalError";constructor(Y){if(Y.length===1)super(Y.summary);else super(`
19
+ `+Y.map((Z)=>` \u2022 ${HJ(Z)}`).join(`
20
+ `));Object.defineProperty(this,"arkErrors",{value:Y,enumerable:!1})}}var HJ=(Y)=>Y.toString().split(`
21
21
  `).join(`
22
- `);class f1{path=[];errors=new F1(this);root;config;queuedMorphs=[];branches=[];seen={};constructor(Y,Z){this.root=Y,this.config=Z}get data(){let Y=this.root;for(let Z of this.path)Y=Y?.[Z];return Y}get propString(){return Y4(this.path)}reject(Y){return this.error(Y),!1}mustBe(Y){return this.error(Y),!1}error(Y){let Z=typeof Y==="object"?Y.code?Y:{...Y,code:"predicate"}:{code:"predicate",expected:Y};return this.errorFromContext(Z)}hasError(){return this.currentErrorCount!==0}get currentBranch(){return this.branches.at(-1)}queueMorphs(Y){let Z={path:new p8(...this.path),morphs:Y};if(this.currentBranch)this.currentBranch.queuedMorphs.push(Z);else this.queuedMorphs.push(Z)}finalize(Y){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 Y?Y(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(Y){return this.errorFromContext(Y)}errorFromContext(Y){let Z=new V4(Y,this);if(this.currentBranch)this.currentBranch.error=Z;else this.errors.add(Z);return Z}applyQueuedMorphs(){while(this.queuedMorphs.length){let Y=this.queuedMorphs;this.queuedMorphs=[];for(let{path:Z,morphs:X}of Y){if(this.errors.affectsPath(Z))continue;this.applyMorphsAtPath(Z,X)}}}applyMorphsAtPath(Y,Z){let X=Y.at(-1),_;if(X!==void 0){_=this.root;for(let G=0;G<Y.length-1;G++)_=_[Y[G]]}this.path=[...Y];for(let G of Z){let W=V0(G),H=G(_===void 0?this.root:_[X],this);if(H instanceof V4){this.errors.add(H);break}if(H instanceof F1){if(!W)this.errors.merge(H);break}if(_===void 0)this.root=H;else _[X]=H;this.applyQueuedMorphs()}}}var U1=(Y,Z,X)=>{if(!X)return Z();X.path.push(Y);let _=Z();return X.path.pop(),_};class c8 extends h1{attachments;$;onFail;includesTransform;includesContextualPredicate;isCyclic;allowsRequiresContext;rootApplyStrategy;contextFreeMorph;rootApply;referencesById;shallowReferences;flatRefs;flatMorphs;allows;get shallowMorphs(){return[]}constructor(Y,Z){super((_,G,W=this.onFail)=>{if(G)return this.traverseApply(_,G),G.hasError()?G.errors:G.data;return this.rootApply(_,W)},{attach:Y});this.attachments=Y,this.$=Z,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((_,G)=>OQ(_,G.shallowReferences),[this]);let X=this.isStructural();this.flatRefs=[],this.flatMorphs=[];for(let _=0;_<this.children.length;_++){if(this.includesTransform||=this.children[_].includesTransform,this.includesContextualPredicate||=this.children[_].includesContextualPredicate,this.isCyclic||=this.children[_].isCyclic,!X){let G=this.children[_].flatRefs;for(let W=0;W<G.length;W++){let H=G[W];if(!this.flatRefs.some((J)=>r_(J,H))){this.flatRefs.push(H);for(let J of H.node.branches)if(J.hasKind("morph")||J.hasKind("intersection")&&J.structure?.structuralMorph!==void 0)this.flatMorphs.push({path:H.path,propString:H.propString,node:J})}}}Object.assign(this.referencesById,this.children[_].referencesById)}this.flatRefs.sort((_,G)=>_.path.length>G.path.length?1:_.path.length<G.path.length?-1:_.propString>G.propString?1:_.propString<G.propString?-1:_.node.expression<G.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((_)=>_.length===1||_.name==="$arkStructuralMorph")?this.hasKind("union")?this.branches.some((_)=>_.shallowMorphs.length>1)?"contextual":"branchedOptimistic":this.shallowMorphs.length>1?"contextual":"optimistic":"contextual":"contextual",this.rootApply=this.createRootApply(),this.allows=this.allowsRequiresContext?(_)=>this.traverseAllows(_,new f1(_,this.$.resolvedConfig)):(_)=>this.traverseAllows(_)}createRootApply(){switch(this.rootApplyStrategy){case"allows":return(Z,X)=>{if(this.allows(Z))return Z;let _=new f1(Z,this.$.resolvedConfig);return this.traverseApply(Z,_),_.finalize(X)};case"contextual":return(Z,X)=>{let _=new f1(Z,this.$.resolvedConfig);return this.traverseApply(Z,_),_.finalize(X)};case"optimistic":this.contextFreeMorph=this.shallowMorphs[0];let Y=this.$.resolvedConfig.clone;return(Z,X)=>{if(this.allows(Z))return this.contextFreeMorph(Y&&(typeof Z==="object"&&Z!==null||typeof Z==="function")?Y(Z):Z);let _=new f1(Z,this.$.resolvedConfig);return this.traverseApply(Z,_),_.finalize(X)};case"branchedOptimistic":return this.createBranchedOptimisticRootApply();default:return this.rootApplyStrategy,_0(`Unexpected rootApplyStrategy ${this.rootApplyStrategy}`)}}compiledMeta=UQ(this.metaJson);cacheGetter(Y,Z){return Object.defineProperty(this,Y,{value:Z}),Z}get description(){return this.cacheGetter("description",this.meta?.description??this.$.resolvedConfig[this.kind].description(this))}get references(){return Object.values(this.referencesById)}precedence=e4(this.kind);precompilation;assert=(Y,Z)=>this(Y,Z,(X)=>X.throw());traverse(Y,Z){return this(Y,Z,null)}get in(){return this.cacheGetter("in",this.getIo("in"))}get out(){return this.cacheGetter("out",this.getIo("out"))}getIo(Y){if(!this.includesTransform)return this;let Z={};for(let[X,_]of this.innerEntries){let G=this.impl.keys[X];if(G.reduceIo)G.reduceIo(Y,Z,_);else if(G.child){let W=_;Z[X]=O0(W)?W.map((H)=>H[Y]):W[Y]}else Z[X]=_}return this.$.node(this.kind,Z)}toJSON(){return this.json}toString(){return`Type<${this.expression}>`}equals(Y){let Z=V0(Y)?Y:this.$.parseDefinition(Y);return this.innerHash===Z.innerHash}ifEquals(Y){return this.equals(Y)?this:void 0}hasKind(Y){return this.kind===Y}assertHasKind(Y){if(this.kind!==Y)q4(`${this.kind} node was not of asserted kind ${Y}`);return this}hasKindIn(...Y){return Y.includes(this.kind)}assertHasKindIn(...Y){if(!s1(Y,this.kind))q4(`${this.kind} node was not one of asserted kinds ${Y}`);return this}isBasis(){return s1(d_,this.kind)}isConstraint(){return s1(d6,this.kind)}isStructural(){return s1(s4,this.kind)}isRefinement(){return s1(IZ,this.kind)}isRoot(){return s1(a4,this.kind)}isUnknown(){return this.hasKind("intersection")&&this.children.length===0}isNever(){return this.hasKind("union")&&this.children.length===0}hasUnit(Y){return this.hasKind("unit")&&this.allows(Y)}hasOpenIntersection(){return this.impl.intersectionIsOpen}get nestableExpression(){return this.expression}select(Y){let Z=d8.normalize(Y);return this._select(Z)}_select(Y){let Z=d8.applyBoundary[Y.boundary??"references"](this);if(Y.kind)Z=Z.filter((X)=>X.kind===Y.kind);if(Y.where)Z=Z.filter(Y.where);return d8.applyMethod[Y.method??"filter"](Z,this,Y)}transform(Y,Z){return this._transform(Y,this._createTransformContext(Z))}_createTransformContext(Y){return{root:this,selected:void 0,seen:{},path:[],parseOptions:{prereduced:Y?.prereduced??!1},undeclaredKeyHandling:void 0,...Y}}_transform(Y,Z){let X=Z.bindScope??this.$;if(Z.seen[this.id])return this.$.lazilyResolve(Z.seen[this.id]);if(Z.shouldTransform?.(this,Z)===!1)return this;let _;if(Z.seen[this.id]=()=>_,this.hasKind("structure")&&this.undeclared!==Z.undeclaredKeyHandling)Z={...Z,undeclaredKeyHandling:this.undeclared};let G=o(this.inner,(Q,z)=>{if(!this.impl.keys[Q].child)return[Q,z];let O=z;if(!O0(O)){let V=O._transform(Y,Z);return V?[Q,V]:[]}if(O.length===0)return[Q,z];let D=O.flatMap((V)=>{return V._transform(Y,Z)??[]});return D.length?[Q,D]:[]});delete Z.seen[this.id];let W=Object.assign(G,{meta:this.meta}),H=Z.selected&&!Z.selected.includes(this)?W:Y(this.kind,W,Z);if(H===null)return null;if(V0(H))return _=H;let J=Object.keys(H);if((J.length===0||J.length===1&&J[0]==="meta")&&!c1(this.inner))return null;if((this.kind==="required"||this.kind==="optional"||this.kind==="index")&&!("value"in H))return Z.undeclaredKeyHandling?{...H,value:B.intrinsic.unknown}:null;if(this.kind==="morph")H.in??=B.intrinsic.unknown;return _=X.node(this.kind,H,Z.parseOptions)}configureReferences(Y,Z="references"){let X=d8.normalize(Z),_=typeof Y==="string"?(J,$)=>({...$,meta:{...$.meta,description:Y}}):typeof Y==="function"?(J,$)=>({...$,meta:Y($.meta)}):(J,$)=>({...$,meta:{...$.meta,...Y}});if(X.boundary==="self")return this.$.node(this.kind,_(this.kind,{...this.inner,meta:this.meta}));let G=this._select(X),W=G&&U4(G),H=X.boundary==="child"?(J,$)=>$.root.children.includes(J):X.boundary==="shallow"?(J)=>J.kind!=="structure":()=>!0;return this.$.finalize(this.transform(_,{shouldTransform:H,selected:W}))}}var d8={applyBoundary:{self:(Y)=>[Y],child:(Y)=>[...Y.children],shallow:(Y)=>[...Y.shallowReferences],references:(Y)=>[...Y.references]},applyMethod:{filter:(Y)=>Y,assertFilter:(Y,Z,X)=>{if(Y.length===0)q4(n_(Z,X));return Y},find:(Y)=>Y[0],assertFind:(Y,Z,X)=>{if(Y.length===0)q4(n_(Z,X));return Y[0]}},normalize:(Y)=>typeof Y==="function"?{boundary:"references",method:"filter",where:Y}:typeof Y==="string"?p0(Y,d8.applyBoundary)?{method:"filter",boundary:Y}:{boundary:"references",method:"filter",kind:Y}:{boundary:"references",method:"filter",...Y}},n_=(Y,Z)=>`${Y} had no references matching ${n(Z)}.`,zQ=(Y)=>Y4(Y,{stringifyNonKey:(Z)=>Z.expression}),FQ=/"(\$ark\.[^"]+)"/g,UQ=(Y)=>JSON.stringify(Y).replaceAll(FQ,"$1"),b1=(Y,Z)=>({path:Y,node:Z,propString:zQ(Y)}),r_=(Y,Z)=>Y.propString===Z.propString&&Y.node.equals(Z.node),TZ=(Y,Z)=>d1(Y,Z,{isEqual:r_}),OQ=(Y,Z)=>d1(Y,Z,{isEqual:(X,_)=>X.equals(_)});class S extends Array{static init(Y,Z,X,_){return new S({kind:Y,l:Z,r:X,path:_?.path??[],optional:_?.optional??!1})}add(Y,Z,X,_){return this.push({kind:Y,l:Z,r:X,path:_?.path??[],optional:_?.optional??!1}),this}get summary(){return this.describeReasons()}describeReasons(){if(this.length===1){let{path:Y,l:Z,r:X}=this[0],_=Y4(Y);return qZ(`Intersection${_&&` at ${_}`} of ${s_(Z,X)}`)}return`The following intersections result in unsatisfiable types:
23
- \u2022 ${this.map(({path:Y,l:Z,r:X})=>`${Y}: ${s_(Z,X)}`).join(`
24
- \u2022 `)}`}throw(){return w(this.describeReasons())}invert(){let Y=this.map((Z)=>({...Z,l:Z.r,r:Z.l}));if(!(Y instanceof S))return new S(...Y);return Y}withPrefixKey(Y,Z){return this.map((X)=>({...X,path:[Y,...X.path],optional:X.optional||Z==="optional"}))}toNeverIfDisjoint(){return B.intrinsic.never}}var s_=(Y,Z)=>`${KZ(Y)} and ${KZ(Z)}`,KZ=(Y)=>V0(Y)?Y.expression:O0(Y)?Y.map(KZ).join(" | ")||"never":String(Y),qZ=(Y)=>`${Y} results in an unsatisfiable type`;var Y8={},O1=(Y,Z,X)=>M0(Y,Z,{$:X,invert:!1,pipe:!1}),l8=(Y,Z,X)=>M0(Y,Z,{$:X,invert:!1,pipe:!0}),M0=(Y,Z,X)=>{let _=X.pipe?"|>":"&",G=`${Y.hash}${_}${Z.hash}`;if(Y8[G]!==void 0)return Y8[G];if(!X.pipe){let J=`${Z.hash}${_}${Y.hash}`;if(Y8[J]!==void 0){let $=Y8[J],Q=$ instanceof S?$.invert():$;return Y8[G]=Q,Q}}let W=!X.pipe||!Y.includesTransform&&!Z.includesTransform;if(W&&Y.equals(Z))return Y;let H=W?jZ(Y,Z,X):Y.hasKindIn(...a4)?EQ(Y,Z,X):jZ(Y,Z,X);if(V0(H)){if(Y.equals(H))H=Y;else if(Z.equals(H))H=Z}return Y8[G]=H,H},jZ=(Y,Z,X)=>{let _=Y.precedence<Z.precedence?Y.kind:Z.kind,G=Y.impl.intersections[Z.kind]??Z.impl.intersections[Y.kind];if(G===void 0)return null;else if(_===Y.kind)return G(Y,Z,X);else{let W=G(Z,Y,{...X,invert:!X.invert});if(W instanceof S)W=W.invert();return W}},EQ=(Y,Z,X)=>Y.includesTransform||Z.includesTransform?X.invert?a_(Z,Y,X):a_(Y,Z,X):jZ(Y,Z,X),a_=(Y,Z,X)=>Y.distribute((_)=>DQ(_,Z,X),(_)=>{let G=_.filter(V0);if(G.length===0)return S.init("union",Y.branches,Z.branches);if(G.length<Y.branches.length||!Y.branches.every((J,$)=>J.in.equals(G[$].in)))return X.$.parseSchema(G);let W;if(G.length===1){let J=G[0];if(!W)return J;return X.$.node("morph",{...J.inner,in:J.in.configure(W,"self")})}let H={branches:G};if(W)H.meta=W;return X.$.parseSchema(H)}),DQ=(Y,Z,X)=>{if(Y.hasKind("morph")){let G=[...Y.morphs];if(Y.lastMorphIfNode){let W=M0(Y.lastMorphIfNode,Z,X);if(W instanceof S)return W;G[G.length-1]=W}else G.push(Z);return X.$.node("morph",{morphs:G,in:Y.inner.in})}if(Z.hasKind("morph")){let G=M0(Y,Z.in,X);if(G instanceof S)return G;return X.$.node("morph",{morphs:[Z],in:G})}return X.$.node("morph",{morphs:[Z],in:Y})};class C1 extends c8{constructor(Y,Z){super(Y,Z);Object.defineProperty(this,X1,{value:"constraint",enumerable:!1})}impliedSiblings;intersect(Y){return O1(this,Y,this.$)}}class X4 extends C1{traverseApply=(Y,Z)=>{if(!this.traverseAllows(Y,Z))Z.errorFromNodeContext(this.errorContext)};compile(Y){if(Y.traversalKind==="Allows")Y.return(this.compiledCondition);else Y.if(this.compiledNegation,()=>Y.line(`${Y.ctx}.errorFromNodeContext(${this.compiledErrorContext})`))}get errorContext(){return{code:this.kind,description:this.description,meta:this.meta,...this.inner}}get compiledErrorContext(){return L4(this.errorContext)}}var t0=(Y)=>(Z,X)=>{if(O0(Z)){if(Z.length===0)return;let G=Z.map((W)=>X.$.node(Y,W));if(Y==="predicate")return G;return G.sort((W,H)=>W.hash<H.hash?-1:1)}let _=X.$.node(Y,Z);return _.hasOpenIntersection()?[_]:_},Z8=(Y)=>{let Z=Y.r.shift();if(!Z){let _=Y.l.length===0&&Y.kind==="structure"?B.intrinsic.unknown.internal:Y.ctx.$.node(Y.kind,Object.assign(Y.baseInner,LQ(Y.l)),{prereduced:!0});for(let G of Y.roots){if(_ instanceof S)return _;_=M0(G,_,Y.ctx)}return _}let X=!1;for(let _=0;_<Y.l.length;_++){let G=M0(Y.l[_],Z,Y.ctx);if(G===null)continue;if(G instanceof S)return G;if(!X){if(G.isRoot())return Y.roots.push(G),Y.l.splice(_),Z8(Y);Y.l[_]=G,X=!0}else if(!Y.l.includes(G))return _0(`Unexpectedly encountered multiple distinct intersection results for refinement ${G}`)}if(!X)Y.l.push(Z);if(Y.kind==="intersection"){if(Z.impliedSiblings)for(let _ of Z.impliedSiblings)d1(Y.r,_)}return Z8(Y)},X8=(Y)=>{return Object.entries(Y).flatMap(([X,_])=>(X in c6)?_:[]).sort((X,_)=>X.precedence<_.precedence?-1:X.precedence>_.precedence?1:X.kind==="predicate"&&_.kind==="predicate"?0:X.hash<_.hash?-1:1)},LQ=(Y)=>{let Z={};for(let X of Y)if(X.hasOpenIntersection())Z[X.kind]=Z0(Z[X.kind],X);else{if(Z[X.kind])return _0(`Unexpected intersection of closed refinements of kind ${X.kind}`);Z[X.kind]=X}return Z},t_=(...Y)=>w(e_(...Y)),e_=(Y,Z,X)=>{let _=X.hasKind("morph")?"a morph":X.isUnknown()?"unknown":X.exclude(Z).defaultShortDescription;return`${q_(Y)} operand must be ${Z.description} (was ${_})`};var YG=(Y,Z,X)=>new M4(Y,Z,X,X,null);class i6 extends h1{}class M4 extends h1{[X1]="generic";paramDefs;bodyDef;$;arg$;baseInstantiation;hkt;description;constructor(Y,Z,X,_,G){super((...W)=>{let H=o(this.names,(J,$)=>{let Q=this.arg$.parse(W[J]);if(!Q.extends(this.constraints[J]))w(VQ($,this.constraints[J].expression,Q.expression));return[$,Q]});if(this.defIsLazy()){let J=this.bodyDef(H);return this.$.parse(J)}return this.$.parse(Z,{args:H})});this.paramDefs=Y,this.bodyDef=Z,this.$=X,this.arg$=_,this.hkt=G,this.description=G?new G().description??`a generic type for ${G.constructor.name}`:"a generic type",this.baseInstantiation=this(...this.constraints)}defIsLazy(){return this.bodyDef instanceof i6}cacheGetter(Y,Z){return Object.defineProperty(this,Y,{value:Z}),Z}get json(){return this.cacheGetter("json",{params:this.params.map((Y)=>Y[1].isUnknown()?Y[0]:[Y[0],Y[1].json]),body:y_(this.bodyDef)})}get params(){return this.cacheGetter("params",this.paramDefs.map((Y)=>typeof Y==="string"?[Y,B.intrinsic.unknown]:[Y[0],this.$.parse(Y[1])]))}get names(){return this.cacheGetter("names",this.params.map((Y)=>Y[0]))}get constraints(){return this.cacheGetter("constraints",this.params.map((Y)=>Y[1]))}get internal(){return this}get referencesById(){return this.baseInstantiation.internal.referencesById}get references(){return this.baseInstantiation.internal.references}}var VQ=(Y,Z,X)=>`${Y} must be assignable to ${Z} (was ${X})`;var MQ=r({kind:"predicate",hasAssociatedError:!0,collapsibleKey:"predicate",keys:{predicate:{}},normalize:(Y)=>typeof Y==="function"?{predicate:Y}:Y,defaults:{description:(Y)=>`valid according to ${Y.predicate.name||"an anonymous predicate"}`},intersectionIsOpen:!0,intersections:{predicate:()=>null}});class ZG extends C1{serializedPredicate=K0(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=L4(this.errorContext);traverseApply=(Y,Z)=>{if(!this.predicate(Y,Z.external)&&!Z.hasError())Z.errorFromNodeContext(this.errorContext)};compile(Y){if(Y.traversalKind==="Allows"){Y.return(this.compiledCondition);return}Y.if(`${this.compiledNegation} && !ctx.hasError()`,()=>Y.line(`ctx.errorFromNodeContext(${this.compiledErrorContext})`))}reduceJsonSchema(Y,Z){return Z.fallback.predicate({code:"predicate",base:Y,predicate:this.predicate})}}var PZ={implementation:MQ,Node:ZG};var AQ=r({kind:"divisor",collapsibleKey:"rule",keys:{rule:{parse:(Y)=>Number.isInteger(Y)?Y:w(wQ(Y))}},normalize:(Y)=>typeof Y==="number"?{rule:Y}:Y,hasAssociatedError:!0,defaults:{description:(Y)=>Y.rule===1?"an integer":Y.rule===2?"even":`a multiple of ${Y.rule}`},intersections:{divisor:(Y,Z,X)=>X.$.node("divisor",{rule:Math.abs(Y.rule*Z.rule/RQ(Y.rule,Z.rule))})},obviatesBasisDescription:!0});class XG extends X4{traverseAllows=(Y)=>Y%this.rule===0;compiledCondition=`data % ${this.rule} === 0`;compiledNegation=`data % ${this.rule} !== 0`;impliedBasis=B.intrinsic.number.internal;expression=`% ${this.rule}`;reduceJsonSchema(Y){if(Y.type="integer",this.rule===1)return Y;return Y.multipleOf=this.rule,Y}}var SZ={implementation:AQ,Node:XG};var wQ=(Y)=>`divisor must be an integer (was ${Y})`,RQ=(Y,Z)=>{let X,_=Y,G=Z;while(G!==0)X=G,G=_%G,_=X;return _};class w1 extends X4{boundOperandKind=CQ[this.kind];compiledActual=this.boundOperandKind==="value"?"data":this.boundOperandKind==="length"?"data.length":"data.valueOf()";comparator=TQ(this.kind,this.exclusive);numericLimit=this.rule.valueOf();expression=`${this.comparator} ${this.rule}`;compiledCondition=`${this.compiledActual} ${this.comparator} ${this.numericLimit}`;compiledNegation=`${this.compiledActual} ${NQ[this.comparator]} ${this.numericLimit}`;stringLimit=this.boundOperandKind==="date"?KQ(this.numericLimit):`${this.numericLimit}`;limitKind=this.comparator["0"]==="<"?"upper":"lower";isStricterThan(Y){return(this.limitKind==="upper"?this.numericLimit<Y.numericLimit:this.numericLimit>Y.numericLimit)||this.numericLimit===Y.numericLimit&&this.exclusive===!0&&!Y.exclusive}overlapsRange(Y){if(this.isStricterThan(Y))return!1;if(this.numericLimit===Y.numericLimit&&(this.exclusive||Y.exclusive))return!1;return!0}overlapIsUnit(Y){return this.numericLimit===Y.numericLimit&&!this.exclusive&&!Y.exclusive}}var NQ={"<":">=","<=":">",">":"<=",">=":"<"},IQ={min:"max",minLength:"maxLength",after:"before"},o6={parse:(Y)=>Y||void 0},n6=(Y)=>(Z)=>{if(typeof Z==="number")return{rule:Z};let{exclusive:X,..._}=Z;return X?{..._,rule:Y==="minLength"?_.rule+1:_.rule-1}:_},r6=(Y)=>(Z)=>{if(typeof Z==="number"||typeof Z==="string"||Z instanceof Date)return{rule:Z};let{exclusive:X,..._}=Z;if(!X)return _;let G=typeof _.rule==="number"?_.rule:typeof _.rule==="string"?new Date(_.rule).valueOf():_.rule.valueOf();return X?{..._,rule:Y==="after"?G+1:G-1}:_},s6=(Y)=>typeof Y==="string"||typeof Y==="number"?new Date(Y):Y,BQ=(Y,Z)=>`${Y} bound must be a positive integer (was ${Z})`,_8=(Y)=>(Z)=>{if(!Number.isInteger(Z)||Z<0)w(BQ(Y,Z));return Z},CQ={min:"value",max:"value",minLength:"length",maxLength:"length",after:"date",before:"date"},TQ=(Y,Z)=>`${p0(Y,IQ)?">":"<"}${Z?"":"="}`,KQ=(Y)=>typeof Y==="string"?Y:new Date(Y).toLocaleString(),_G=(Y)=>`Bounded expression ${Y} must be exactly one of number, string, Array, or Date`;var qQ=r({kind:"after",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:s6,serialize:(Y)=>Y.toISOString()}},normalize:r6("after"),defaults:{description:(Y)=>`${Y.collapsibleLimitString} or later`,actual:v4},intersections:{after:(Y,Z)=>Y.isStricterThan(Z)?Y:Z}});class GG extends w1{impliedBasis=B.intrinsic.Date.internal;collapsibleLimitString=v4(this.rule);traverseAllows=(Y)=>Y>=this.rule;reduceJsonSchema(Y,Z){return Z.fallback.date({code:"date",base:Y,after:this.rule})}}var vZ={implementation:qQ,Node:GG};var jQ=r({kind:"before",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:s6,serialize:(Y)=>Y.toISOString()}},normalize:r6("before"),defaults:{description:(Y)=>`${Y.collapsibleLimitString} or earlier`,actual:v4},intersections:{before:(Y,Z)=>Y.isStricterThan(Z)?Y:Z,after:(Y,Z,X)=>Y.overlapsRange(Z)?Y.overlapIsUnit(Z)?X.$.node("unit",{unit:Y.rule}):null:S.init("range",Y,Z)}});class WG extends w1{collapsibleLimitString=v4(this.rule);traverseAllows=(Y)=>Y<=this.rule;impliedBasis=B.intrinsic.Date.internal;reduceJsonSchema(Y,Z){return Z.fallback.date({code:"date",base:Y,before:this.rule})}}var xZ={implementation:jQ,Node:WG};var PQ=r({kind:"exactLength",collapsibleKey:"rule",keys:{rule:{parse:_8("exactLength")}},normalize:(Y)=>typeof Y==="number"?{rule:Y}:Y,hasAssociatedError:!0,defaults:{description:(Y)=>`exactly length ${Y.rule}`,actual:(Y)=>`${Y.length}`},intersections:{exactLength:(Y,Z,X)=>S.init("unit",X.$.node("unit",{unit:Y.rule}),X.$.node("unit",{unit:Z.rule}),{path:["length"]}),minLength:(Y,Z)=>Y.rule>=Z.rule?Y:S.init("range",Y,Z),maxLength:(Y,Z)=>Y.rule<=Z.rule?Y:S.init("range",Y,Z)}});class HG extends X4{traverseAllows=(Y)=>Y.length===this.rule;compiledCondition=`data.length === ${this.rule}`;compiledNegation=`data.length !== ${this.rule}`;impliedBasis=B.intrinsic.lengthBoundable.internal;expression=`== ${this.rule}`;reduceJsonSchema(Y){switch(Y.type){case"string":return Y.minLength=this.rule,Y.maxLength=this.rule,Y;case"array":return Y.minItems=this.rule,Y.maxItems=this.rule,Y;default:return N0.throwInternalOperandError("exactLength",Y)}}}var hZ={implementation:PQ,Node:HG};var SQ=r({kind:"max",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{},exclusive:o6},normalize:(Y)=>typeof Y==="number"?{rule:Y}:Y,defaults:{description:(Y)=>{if(Y.rule===0)return Y.exclusive?"negative":"non-positive";return`${Y.exclusive?"less than":"at most"} ${Y.rule}`}},intersections:{max:(Y,Z)=>Y.isStricterThan(Z)?Y:Z,min:(Y,Z,X)=>Y.overlapsRange(Z)?Y.overlapIsUnit(Z)?X.$.node("unit",{unit:Y.rule}):null:S.init("range",Y,Z)},obviatesBasisDescription:!0});class JG extends w1{impliedBasis=B.intrinsic.number.internal;traverseAllows=this.exclusive?(Y)=>Y<this.rule:(Y)=>Y<=this.rule;reduceJsonSchema(Y){if(this.exclusive)Y.exclusiveMaximum=this.rule;else Y.maximum=this.rule;return Y}}var fZ={implementation:SQ,Node:JG};var vQ=r({kind:"maxLength",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:_8("maxLength")}},reduce:(Y,Z)=>Y.rule===0?Z.node("exactLength",Y):void 0,normalize:n6("maxLength"),defaults:{description:(Y)=>`at most length ${Y.rule}`,actual:(Y)=>`${Y.length}`},intersections:{maxLength:(Y,Z)=>Y.isStricterThan(Z)?Y:Z,minLength:(Y,Z,X)=>Y.overlapsRange(Z)?Y.overlapIsUnit(Z)?X.$.node("exactLength",{rule:Y.rule}):null:S.init("range",Y,Z)}});class QG extends w1{impliedBasis=B.intrinsic.lengthBoundable.internal;traverseAllows=(Y)=>Y.length<=this.rule;reduceJsonSchema(Y){switch(Y.type){case"string":return Y.maxLength=this.rule,Y;case"array":return Y.maxItems=this.rule,Y;default:return N0.throwInternalOperandError("maxLength",Y)}}}var bZ={implementation:vQ,Node:QG};var xQ=r({kind:"min",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{},exclusive:o6},normalize:(Y)=>typeof Y==="number"?{rule:Y}:Y,defaults:{description:(Y)=>{if(Y.rule===0)return Y.exclusive?"positive":"non-negative";return`${Y.exclusive?"more than":"at least"} ${Y.rule}`}},intersections:{min:(Y,Z)=>Y.isStricterThan(Z)?Y:Z},obviatesBasisDescription:!0});class $G extends w1{impliedBasis=B.intrinsic.number.internal;traverseAllows=this.exclusive?(Y)=>Y>this.rule:(Y)=>Y>=this.rule;reduceJsonSchema(Y){if(this.exclusive)Y.exclusiveMinimum=this.rule;else Y.minimum=this.rule;return Y}}var kZ={implementation:xQ,Node:$G};var hQ=r({kind:"minLength",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:_8("minLength")}},reduce:(Y)=>Y.rule===0?B.intrinsic.unknown:void 0,normalize:n6("minLength"),defaults:{description:(Y)=>Y.rule===1?"non-empty":`at least length ${Y.rule}`,actual:(Y)=>Y.length===0?"":`${Y.length}`},intersections:{minLength:(Y,Z)=>Y.isStricterThan(Z)?Y:Z}});class zG extends w1{impliedBasis=B.intrinsic.lengthBoundable.internal;traverseAllows=(Y)=>Y.length>=this.rule;reduceJsonSchema(Y){switch(Y.type){case"string":return Y.minLength=this.rule,Y;case"array":return Y.minItems=this.rule,Y;default:return N0.throwInternalOperandError("minLength",Y)}}}var gZ={implementation:hQ,Node:zG};var FG={min:kZ.implementation,max:fZ.implementation,minLength:gZ.implementation,maxLength:bZ.implementation,exactLength:hZ.implementation,after:vZ.implementation,before:xZ.implementation},UG={min:kZ.Node,max:fZ.Node,minLength:gZ.Node,maxLength:bZ.Node,exactLength:hZ.Node,after:vZ.Node,before:xZ.Node};var fQ=r({kind:"pattern",collapsibleKey:"rule",keys:{rule:{},flags:{}},normalize:(Y)=>typeof Y==="string"?{rule:Y}:Y instanceof RegExp?Y.flags?{rule:Y.source,flags:Y.flags}:{rule:Y.source}:Y,obviatesBasisDescription:!0,obviatesBasisExpression:!0,hasAssociatedError:!0,intersectionIsOpen:!0,defaults:{description:(Y)=>`matched by ${Y.rule}`},intersections:{pattern:()=>null}});class OG extends X4{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=B.intrinsic.string.internal;reduceJsonSchema(Y,Z){if(Y.pattern)return Z.fallback.patternIntersection({code:"patternIntersection",base:Y,pattern:this.rule});return Y.pattern=this.rule,Y}}var yZ={implementation:fQ,Node:OG};var i8=(Y,Z)=>{let X=bQ(Y);if(Z&&!Z.includes(X))return w(`Root of kind ${X} should be one of ${Z}`);return X},bQ=(Y)=>{if(y(Y,"root"))return Y.kind;if(typeof Y==="string")return Y[0]==="$"?"alias":(Y in z1)?"domain":"proto";if(typeof Y==="function")return"proto";if(typeof Y!=="object"||Y===null)return w(EG(Y));if("morphs"in Y)return"morph";if("branches"in Y||O0(Y))return"union";if("unit"in Y)return"unit";if("reference"in Y)return"alias";let Z=Object.keys(Y);if(Z.length===0||Z.some((X)=>(X in c6)))return"intersection";if("proto"in Y)return"proto";if("domain"in Y)return"domain";return w(EG(Y))},EG=(Y)=>`${n(Y)} is not a valid type schema`,DG={},kQ=(Y)=>O0(Y)?Y.map((Z)=>Z.collapsibleJson):Y.collapsibleJson,_1={};B.nodesByRegisteredId=_1;var pZ=(Y)=>{return DG[Y]??=0,`${Y}${++DG[Y]}`},mZ=(Y)=>{let Z=G8[Y.kind],X=Z.applyConfig?.(Y.def,Y.$.resolvedConfig)??Y.def,_={},{meta:G,...W}=X,H=G===void 0?{}:typeof G==="string"?{description:G}:G,J=zZ(W).sort(([Q],[z])=>t4(Q)?t4(z)?e4(Q)-e4(z):1:t4(z)?-1:Q<z?-1:1).filter(([Q,z])=>{if(Q.startsWith("meta.")){let O=Q.slice(5);return H[O]=z,!1}return!0});for(let Q of J){let z=Q[0],O=Z.keys[z];if(!O)return w(`Key ${z} is not valid on ${Y.kind} schema`);let D=O.parse?O.parse(Q[1],Y):Q[1];if(D!==A1&&(D!==void 0||O.preserveUndefined))_[z]=D}if(Z.reduce&&!Y.prereduced){let Q=Z.reduce(_,Y.$);if(Q){if(Q instanceof S)return Q.throw();return gQ(Q,H)}}return uZ({id:Y.id,kind:Y.kind,inner:_,meta:H,$:Y.$})},uZ=({id:Y,kind:Z,inner:X,meta:_,$:G,ignoreCache:W})=>{let H=G8[Z],J=zZ(X),$=[],Q={};for(let[b,f]of J){let h=H.keys[b],I=h.serialize??(h.child?kQ:B1);if(Q[b]=I(f),h.child===!0){let N=f;if(O0(N))$.push(...N);else $.push(N)}else if(typeof h.child==="function")$.push(...h.child(f))}if(H.finalizeInnerJson)Q=H.finalizeInnerJson(Q);let z={...Q},O={};if(!c1(_))O=o(_,(b,f)=>[b,b==="examples"?f:B1(f)]),z.meta=a6(O,"description",!0);Q=a6(Q,H.collapsibleKey,!1);let D=JSON.stringify({kind:Z,...Q});z=a6(z,H.collapsibleKey,!1);let V=a6(z,H.collapsibleKey,!0),R=JSON.stringify({kind:Z,...z});if(G.nodesByHash[R]&&!W)return G.nodesByHash[R];let A={id:Y,kind:Z,impl:H,inner:X,innerEntries:J,innerJson:Q,innerHash:D,meta:_,metaJson:O,json:z,hash:R,collapsibleJson:V,children:$};if(Z!=="intersection"){for(let b in X)if(b!=="in"&&b!=="out")A[b]=X[b]}let g=new VG[Z](A,G);return G.nodesByHash[R]=g},LG=(Y,Z)=>{if(Y.id===Z)return Y;if(V0(_1[Z]))_0(`Unexpected attempt to overwrite node id ${Z}`);return uZ({id:Z,kind:Y.kind,inner:Y.inner,meta:Y.meta,$:Y.$,ignoreCache:!0})},gQ=(Y,Z,X)=>{if(X&&V0(_1[X]))_0(`Unexpected attempt to overwrite node id ${X}`);return uZ({id:X??pZ(Z.alias??Y.kind),kind:Y.kind,inner:Y.inner,meta:Z,$:Y.$})},a6=(Y,Z,X)=>{let _=Object.keys(Y);if(_.length===1&&_[0]===Z){let G=Y[Z];if(X)return G;if($1(G,"object")&&(Object.keys(G).length===1||Array.isArray(G)))return G}return Y};var o8=(Y,Z,X)=>{if(Y.key!==Z.key)return null;let _=Y.key,G=M0(Y.value,Z.value,X),W=Y.required||Z.required?"required":"optional";if(G instanceof S)if(W==="optional")G=B.intrinsic.never.internal;else return G.withPrefixKey(Y.key,Y.required&&Z.required?"required":"optional");if(W==="required")return X.$.node("required",{key:_,value:G});let H=Y.hasDefault()?Z.hasDefault()?Y.default===Z.default?Y.default:w(dZ(Y.default,Z.default)):Y.default:Z.hasDefault()?Z.default:A1;return X.$.node("optional",{key:_,value:G,default:H})};class n8 extends C1{required=this.kind==="required";optional=this.kind==="optional";impliedBasis=B.intrinsic.object.internal;serializedKey=Z4(this.key);compiledKey=typeof this.key==="string"?this.key:this.serializedKey;flatRefs=Z0(this.value.flatRefs.map((Y)=>b1([this.key,...Y.path],Y.node)),b1([this.key],this.value));_transform(Y,Z){Z.path.push(this.key);let X=super._transform(Y,Z);return Z.path.pop(),X}hasDefault(){return"default"in this.inner}traverseAllows=(Y,Z)=>{if(this.key in Y)return U1(this.key,()=>this.value.traverseAllows(Y[this.key],Z),Z);return this.optional};traverseApply=(Y,Z)=>{if(this.key in Y)U1(this.key,()=>this.value.traverseApply(Y[this.key],Z),Z);else if(this.hasKind("required"))Z.errorFromNodeContext(this.errorContext)};compile(Y){if(Y.if(`${this.serializedKey} in data`,()=>Y.traverseKey(this.serializedKey,`data${Y.prop(this.key)}`,this.value)),this.hasKind("required"))Y.else(()=>Y.traversalKind==="Apply"?Y.line(`ctx.errorFromNodeContext(${this.compiledErrorContext})`):Y.return(!1));if(Y.traversalKind==="Allows")Y.return(!0)}}var dZ=(Y,Z)=>`Invalid intersection of default values ${n(Y)} & ${n(Z)}`;var yQ=r({kind:"optional",hasAssociatedError:!1,intersectionIsOpen:!0,keys:{key:{},value:{child:!0,parse:(Y,Z)=>Z.$.parseSchema(Y)},default:{preserveUndefined:!0}},normalize:(Y)=>Y,reduce:(Y,Z)=>{if(Z.resolvedConfig.exactOptionalPropertyTypes===!1){if(!Y.value.allows(void 0))return Z.node("optional",{...Y,value:Y.value.or(d.undefined)},{prereduced:!0})}},defaults:{description:(Y)=>`${Y.compiledKey}?: ${Y.value.description}`},intersections:{optional:o8}});class MG extends n8{constructor(...Y){super(...Y);if("default"in this.inner)s8(this.value,this.inner.default,this.key)}get outProp(){if(!this.hasDefault())return this;let{default:Y,...Z}=this.inner;return this.cacheGetter("outProp",this.$.node("required",Z,{prereduced:!0}))}expression=this.hasDefault()?`${this.compiledKey}: ${this.value.expression} = ${n(this.inner.default)}`:`${this.compiledKey}?: ${this.value.expression}`;defaultValueMorph=mQ(this);defaultValueMorphRef=this.defaultValueMorph&&K0(this.defaultValueMorph)}var r8={implementation:yQ,Node:MG},pQ={},mQ=(Y)=>{if(!Y.hasDefault())return;let Z=`{${Y.compiledKey}: ${Y.value.id} = ${B1(Y.default)}}`;return pQ[Z]??=cZ(Y.key,Y.value,Y.default)},cZ=(Y,Z,X)=>{if(typeof X==="function")return Z.includesTransform?(G,W)=>{return U1(Y,()=>Z(G[Y]=X(),W),W),G}:(G)=>{return G[Y]=X(),G};let _=Z.includesTransform?Z.assert(X):X;return $1(_,"object")?(G,W)=>{return U1(Y,()=>Z(G[Y]=X,W),W),G}:(G)=>{return G[Y]=_,G}},s8=(Y,Z,X)=>{let _=O4(Z);if($1(Z,"object")&&!_)w(uQ(X));let G=Y.in(_?Z():Z);if(G instanceof F1){if(X===null)w(`Default ${G.summary}`);let W=G.transform((H)=>H.transform((J)=>({...J,prefixPath:[X]})));w(`Default for ${W.summary}`)}return Z},uQ=(Y)=>{return`Non-primitive default ${Y===null?"":typeof Y==="number"?`for value at [${Y}] `:`for ${Z4(Y)} `}must be specified as a function like () => ({my: 'object'})`};class T1 extends c8{constructor(Y,Z){super(Y,Z);Object.defineProperty(this,X1,{value:"root",enumerable:!1})}get internal(){return this}get "~standard"(){return{vendor:"arktype",version:1,validate:(Y)=>{let Z=this(Y);if(Z instanceof F1)return Z;return{value:Z}}}}as(){return this}brand(Y){if(Y==="")return w(dQ);return this}readonly(){return this}branches=this.hasKind("union")?this.inner.branches:[this];distribute(Y,Z){let X=this.branches.map(Y);return Z?.(X)??X}get shortDescription(){return this.meta.description??this.defaultShortDescription}toJsonSchema(Y={}){let Z=BZ(this.$.resolvedConfig.toJsonSchema,Y);Z.useRefs||=this.isCyclic;let X=typeof Z.dialect==="string"?{$schema:Z.dialect}:{};if(Object.assign(X,this.toJsonSchemaRecurse(Z)),Z.useRefs)X.$defs=o(this.references,(_,G)=>G.isRoot()&&!G.alwaysExpandJsonSchema?[G.id,G.toResolvedJsonSchema(Z)]:[]);return X}toJsonSchemaRecurse(Y){if(Y.useRefs&&!this.alwaysExpandJsonSchema)return{$ref:`#/$defs/${this.id}`};return this.toResolvedJsonSchema(Y)}get alwaysExpandJsonSchema(){return this.isBasis()||this.kind==="alias"||this.hasKind("union")&&this.isBoolean}toResolvedJsonSchema(Y){let Z=this.innerToJsonSchema(Y);return Object.assign(Z,this.metaJson)}intersect(Y){let Z=this.$.parseDefinition(Y),X=this.rawIntersect(Z);if(X instanceof S)return X;return this.$.finalize(X)}rawIntersect(Y){return O1(this,Y,this.$)}toNeverIfDisjoint(){return this}and(Y){let Z=this.intersect(Y);return Z instanceof S?Z.throw():Z}rawAnd(Y){let Z=this.rawIntersect(Y);return Z instanceof S?Z.throw():Z}or(Y){let Z=this.$.parseDefinition(Y);return this.$.finalize(this.rawOr(Z))}rawOr(Y){let Z=[...this.branches,...Y.branches];return this.$.node("union",Z)}map(Y){return this.$.schema(this.applyStructuralOperation("map",[Y]))}pick(...Y){return this.$.schema(this.applyStructuralOperation("pick",Y))}omit(...Y){return this.$.schema(this.applyStructuralOperation("omit",Y))}required(){return this.$.schema(this.applyStructuralOperation("required",[]))}partial(){return this.$.schema(this.applyStructuralOperation("partial",[]))}_keyof;keyof(){if(this._keyof)return this._keyof;let Y=this.applyStructuralOperation("keyof",[]).reduce((Z,X)=>Z.intersect(X).toNeverIfDisjoint(),B.intrinsic.unknown.internal);if(Y.branches.length===0)w(qZ(`keyof ${this.expression}`));return this._keyof=this.$.finalize(Y)}get props(){if(this.branches.length!==1)return w(cQ(this.expression));return[...this.applyStructuralOperation("props",[])[0]]}merge(Y){let Z=this.$.parseDefinition(Y);return this.$.schema(Z.distribute((X)=>this.applyStructuralOperation("merge",[AG(X)??w(wG("merge",X.expression))])))}applyStructuralOperation(Y,Z){return this.distribute((X)=>{if(X.equals(B.intrinsic.object)&&Y!=="merge")return X;let _=AG(X);if(!_)w(wG(Y,X.expression));if(Y==="keyof")return _.keyof();if(Y==="get")return _.get(...Z);if(Y==="props")return _.props;let G=Y==="required"?"require":Y==="partial"?"optionalize":Y;return this.$.node("intersection",{...X.inner,structure:_[G](...Z)})})}get(...Y){if(Y[0]===void 0)return this;return this.$.schema(this.applyStructuralOperation("get",Y))}extract(Y){let Z=this.$.parseDefinition(Y);return this.$.schema(this.branches.filter((X)=>X.extends(Z)))}exclude(Y){let Z=this.$.parseDefinition(Y);return this.$.schema(this.branches.filter((X)=>!X.extends(Z)))}array(){return this.$.schema(this.isUnknown()?{proto:Array}:{proto:Array,sequence:this},{prereduced:!0})}overlaps(Y){return!(this.intersect(Y)instanceof S)}extends(Y){let Z=this.intersect(Y);return!(Z instanceof S)&&this.equals(Z)}ifExtends(Y){return this.extends(Y)?this:void 0}subsumes(Y){return this.$.parseDefinition(Y).extends(this)}configure(Y,Z="shallow"){return this.configureReferences(Y,Z)}describe(Y,Z="shallow"){return this.configure({description:Y},Z)}optional(){return[this,"?"]}default(Y){return s8(this,Y,null),[this,"=",Y]}from(Y){return this.assert(Y)}_pipe(...Y){let Z=Y.reduce((X,_)=>X.rawPipeOnce(_),this);return this.$.finalize(Z)}tryPipe(...Y){let Z=Y.reduce((X,_)=>X.rawPipeOnce(y(_,"root")?_:(G,W)=>{try{return _(G,W)}catch(H){return W.error({code:"predicate",predicate:_,actual:`aborted due to error:
25
- ${H}
26
- `})}}),this);return this.$.finalize(Z)}pipe=Object.assign(this._pipe.bind(this),{try:this.tryPipe.bind(this)});to(Y){return this.$.finalize(this.toNode(this.$.parseDefinition(Y)))}toNode(Y){let Z=l8(this,Y,this.$);if(Z instanceof S)return Z.throw();return Z}rawPipeOnce(Y){if(y(Y,"root"))return this.toNode(Y);return this.distribute((Z)=>Z.hasKind("morph")?this.$.node("morph",{in:Z.inner.in,morphs:[...Z.morphs,Y]}):this.$.node("morph",{in:Z,morphs:[Y]}),this.$.parseSchema)}narrow(Y){return this.constrainOut("predicate",Y)}constrain(Y,Z){return this._constrain("root",Y,Z)}constrainIn(Y,Z){return this._constrain("in",Y,Z)}constrainOut(Y,Z){return this._constrain("out",Y,Z)}_constrain(Y,Z,X){let _=this.$.node(Z,X);if(_.isRoot())return _.isUnknown()?this:_0(`Unexpected constraint node ${_}`);let G=Y==="root"?this:this[Y];if(G.hasKind("morph")||_.impliedBasis&&!G.extends(_.impliedBasis))return t_(Z,_.impliedBasis,this);let W=this.$.node("intersection",{[_.kind]:_}),H=Y==="out"?l8(this,W,this.$):O1(this,W,this.$);if(H instanceof S)H.throw();return this.$.finalize(H)}onUndeclaredKey(Y){let Z=typeof Y==="string"?Y:Y.rule,X=typeof Y==="string"?!1:Y.deep;return this.$.finalize(this.transform((_,G)=>_==="structure"?Z==="ignore"?V_(G,{undeclared:1}):{...G,undeclared:Z}:G,X?void 0:{shouldTransform:(_)=>!s1(s4,_.kind)}))}hasEqualMorphs(Y){if(!this.includesTransform&&!Y.includesTransform)return!0;if(!t1(this.shallowMorphs,Y.shallowMorphs))return!1;if(!t1(this.flatMorphs,Y.flatMorphs,{isEqual:(Z,X)=>Z.propString===X.propString&&(Z.node.hasKind("morph")&&X.node.hasKind("morph")?Z.node.hasEqualMorphs(X.node):Z.node.hasKind("intersection")&&X.node.hasKind("intersection")?Z.node.structure?.structuralMorphRef===X.node.structure?.structuralMorphRef:!1)}))return!1;return!0}onDeepUndeclaredKey(Y){return this.onUndeclaredKey({rule:Y,deep:!0})}filter(Y){return this.constrainIn("predicate",Y)}divisibleBy(Y){return this.constrain("divisor",Y)}matching(Y){return this.constrain("pattern",Y)}atLeast(Y){return this.constrain("min",Y)}atMost(Y){return this.constrain("max",Y)}moreThan(Y){return this.constrain("min",W8(Y))}lessThan(Y){return this.constrain("max",W8(Y))}atLeastLength(Y){return this.constrain("minLength",Y)}atMostLength(Y){return this.constrain("maxLength",Y)}moreThanLength(Y){return this.constrain("minLength",W8(Y))}lessThanLength(Y){return this.constrain("maxLength",W8(Y))}exactlyLength(Y){return this.constrain("exactLength",Y)}atOrAfter(Y){return this.constrain("after",Y)}atOrBefore(Y){return this.constrain("before",Y)}laterThan(Y){return this.constrain("after",W8(Y))}earlierThan(Y){return this.constrain("before",W8(Y))}}var dQ="Expected a non-empty brand name after #",W8=(Y)=>typeof Y==="object"&&!(Y instanceof Date)?{...Y,exclusive:!0}:{rule:Y,exclusive:!0},a8=(Y,Z)=>y(Z,"root")?y(Y,"root")?Y.extends(Z):Z.allows(Y):y(Y,"root")?Y.hasUnit(Z):Z===Y,AG=(Y)=>{if(Y.hasKind("morph"))return null;if(Y.hasKind("intersection"))return Y.inner.structure??(Y.basis?.domain==="object"?Y.$.bindReference(B.intrinsic.emptyStructure):null);if(Y.isBasis()&&Y.domain==="object")return Y.$.bindReference(B.intrinsic.emptyStructure);return null},cQ=(Y)=>`Props cannot be extracted from a union. Use .distribute to extract props from each branch instead. Received:
27
- ${Y}`,wG=(Y,Z)=>`${Y} operand must be an object (was ${Z})`;var l1=(Y,Z)=>o(l6(Y),(X,_)=>[_,Z]);var lQ=(Y)=>typeof Y==="string"?{reference:Y}:Y,RG=(Y)=>Y instanceof S?B.intrinsic.never.internal:Y,iQ=r({kind:"alias",hasAssociatedError:!1,collapsibleKey:"reference",keys:{reference:{serialize:(Y)=>Y.startsWith("$")?Y:`$ark.${Y}`},resolve:{}},normalize:lQ,defaults:{description:(Y)=>Y.reference},intersections:{alias:(Y,Z,X)=>X.$.lazilyResolve(()=>RG(M0(Y.resolution,Z.resolution,X)),`${Y.reference}${X.pipe?"=>":"&"}${Z.reference}`),...l1("alias",(Y,Z,X)=>{if(Z.isUnknown())return Y;if(Z.isNever())return Z;if(Z.isBasis()&&!Z.overlaps(B.intrinsic.object))return S.init("assignability",B.intrinsic.object,Z);return X.$.lazilyResolve(()=>RG(M0(Y.resolution,Z,X)),`${Y.reference}${X.pipe?"=>":"&"}${Z.id}`)})}});class NG extends T1{expression=this.reference;structure=void 0;get resolution(){let Y=this._resolve();return _1[this.id]=Y}_resolve(){if(this.resolve)return this.resolve();if(this.reference[0]==="$")return this.$.resolveRoot(this.reference.slice(1));let Y=this.reference,Z=_1[Y],X=[];while(y(Z,"context")){if(X.includes(Z.id))return w(oQ(Z.id,X));X.push(Z.id),Z=_1[Z.id]}if(!y(Z,"root"))return _0(`Unexpected resolution for reference ${this.reference}
22
+ `);class f1{path=[];errors=new U1(this);root;config;queuedMorphs=[];branches=[];seen={};constructor(Y,Z){this.root=Y,this.config=Z}get data(){let Y=this.root;for(let Z of this.path)Y=Y?.[Z];return Y}get propString(){return Y4(this.path)}reject(Y){return this.error(Y),!1}mustBe(Y){return this.error(Y),!1}error(Y){let Z=typeof Y==="object"?Y.code?Y:{...Y,code:"predicate"}:{code:"predicate",expected:Y};return this.errorFromContext(Z)}hasError(){return this.currentErrorCount!==0}get currentBranch(){return this.branches.at(-1)}queueMorphs(Y){let Z={path:new m8(...this.path),morphs:Y};if(this.currentBranch)this.currentBranch.queuedMorphs.push(Z);else this.queuedMorphs.push(Z)}finalize(Y){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 Y?Y(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(Y){return this.errorFromContext(Y)}errorFromContext(Y){let Z=new V4(Y,this);if(this.currentBranch)this.currentBranch.error=Z;else this.errors.add(Z);return Z}applyQueuedMorphs(){while(this.queuedMorphs.length){let Y=this.queuedMorphs;this.queuedMorphs=[];for(let{path:Z,morphs:X}of Y){if(this.errors.affectsPath(Z))continue;this.applyMorphsAtPath(Z,X)}}}applyMorphsAtPath(Y,Z){let X=Y.at(-1),_;if(X!==void 0){_=this.root;for(let G=0;G<Y.length-1;G++)_=_[Y[G]]}this.path=[...Y];for(let G of Z){let W=V0(G),$=G(_===void 0?this.root:_[X],this);if($ instanceof V4){this.errors.add($);break}if($ instanceof U1){if(!W)this.errors.merge($);break}if(_===void 0)this.root=$;else _[X]=$;this.applyQueuedMorphs()}}}var F1=(Y,Z,X)=>{if(!X)return Z();X.path.push(Y);let _=Z();return X.path.pop(),_};class l8 extends h1{attachments;$;onFail;includesTransform;includesContextualPredicate;isCyclic;allowsRequiresContext;rootApplyStrategy;contextFreeMorph;rootApply;referencesById;shallowReferences;flatRefs;flatMorphs;allows;get shallowMorphs(){return[]}constructor(Y,Z){super((_,G,W=this.onFail)=>{if(G)return this.traverseApply(_,G),G.hasError()?G.errors:G.data;return this.rootApply(_,W)},{attach:Y});this.attachments=Y,this.$=Z,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((_,G)=>UJ(_,G.shallowReferences),[this]);let X=this.isStructural();this.flatRefs=[],this.flatMorphs=[];for(let _=0;_<this.children.length;_++){if(this.includesTransform||=this.children[_].includesTransform,this.includesContextualPredicate||=this.children[_].includesContextualPredicate,this.isCyclic||=this.children[_].isCyclic,!X){let G=this.children[_].flatRefs;for(let W=0;W<G.length;W++){let $=G[W];if(!this.flatRefs.some((H)=>rX(H,$))){this.flatRefs.push($);for(let H of $.node.branches)if(H.hasKind("morph")||H.hasKind("intersection")&&H.structure?.structuralMorph!==void 0)this.flatMorphs.push({path:$.path,propString:$.propString,node:H})}}}Object.assign(this.referencesById,this.children[_].referencesById)}this.flatRefs.sort((_,G)=>_.path.length>G.path.length?1:_.path.length<G.path.length?-1:_.propString>G.propString?1:_.propString<G.propString?-1:_.node.expression<G.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((_)=>_.length===1||_.name==="$arkStructuralMorph")?this.hasKind("union")?this.branches.some((_)=>_.shallowMorphs.length>1)?"contextual":"branchedOptimistic":this.shallowMorphs.length>1?"contextual":"optimistic":"contextual":"contextual",this.rootApply=this.createRootApply(),this.allows=this.allowsRequiresContext?(_)=>this.traverseAllows(_,new f1(_,this.$.resolvedConfig)):(_)=>this.traverseAllows(_)}createRootApply(){switch(this.rootApplyStrategy){case"allows":return(Z,X)=>{if(this.allows(Z))return Z;let _=new f1(Z,this.$.resolvedConfig);return this.traverseApply(Z,_),_.finalize(X)};case"contextual":return(Z,X)=>{let _=new f1(Z,this.$.resolvedConfig);return this.traverseApply(Z,_),_.finalize(X)};case"optimistic":this.contextFreeMorph=this.shallowMorphs[0];let Y=this.$.resolvedConfig.clone;return(Z,X)=>{if(this.allows(Z))return this.contextFreeMorph(Y&&(typeof Z==="object"&&Z!==null||typeof Z==="function")?Y(Z):Z);let _=new f1(Z,this.$.resolvedConfig);return this.traverseApply(Z,_),_.finalize(X)};case"branchedOptimistic":return this.createBranchedOptimisticRootApply();default:return this.rootApplyStrategy,_0(`Unexpected rootApplyStrategy ${this.rootApplyStrategy}`)}}compiledMeta=zJ(this.metaJson);cacheGetter(Y,Z){return Object.defineProperty(this,Y,{value:Z}),Z}get description(){return this.cacheGetter("description",this.meta?.description??this.$.resolvedConfig[this.kind].description(this))}get references(){return Object.values(this.referencesById)}precedence=e4(this.kind);precompilation;assert=(Y,Z)=>this(Y,Z,(X)=>X.throw());traverse(Y,Z){return this(Y,Z,null)}get in(){return this.cacheGetter("in",this.getIo("in"))}get out(){return this.cacheGetter("out",this.getIo("out"))}getIo(Y){if(!this.includesTransform)return this;let Z={};for(let[X,_]of this.innerEntries){let G=this.impl.keys[X];if(G.reduceIo)G.reduceIo(Y,Z,_);else if(G.child){let W=_;Z[X]=O0(W)?W.map(($)=>$[Y]):W[Y]}else Z[X]=_}return this.$.node(this.kind,Z)}toJSON(){return this.json}toString(){return`Type<${this.expression}>`}equals(Y){let Z=V0(Y)?Y:this.$.parseDefinition(Y);return this.innerHash===Z.innerHash}ifEquals(Y){return this.equals(Y)?this:void 0}hasKind(Y){return this.kind===Y}assertHasKind(Y){if(this.kind!==Y)q4(`${this.kind} node was not of asserted kind ${Y}`);return this}hasKindIn(...Y){return Y.includes(this.kind)}assertHasKindIn(...Y){if(!s1(Y,this.kind))q4(`${this.kind} node was not one of asserted kinds ${Y}`);return this}isBasis(){return s1(dX,this.kind)}isConstraint(){return s1(d2,this.kind)}isStructural(){return s1(s4,this.kind)}isRefinement(){return s1(BY,this.kind)}isRoot(){return s1(a4,this.kind)}isUnknown(){return this.hasKind("intersection")&&this.children.length===0}isNever(){return this.hasKind("union")&&this.children.length===0}hasUnit(Y){return this.hasKind("unit")&&this.allows(Y)}hasOpenIntersection(){return this.impl.intersectionIsOpen}get nestableExpression(){return this.expression}select(Y){let Z=c8.normalize(Y);return this._select(Z)}_select(Y){let Z=c8.applyBoundary[Y.boundary??"references"](this);if(Y.kind)Z=Z.filter((X)=>X.kind===Y.kind);if(Y.where)Z=Z.filter(Y.where);return c8.applyMethod[Y.method??"filter"](Z,this,Y)}transform(Y,Z){return this._transform(Y,this._createTransformContext(Z))}_createTransformContext(Y){return{root:this,selected:void 0,seen:{},path:[],parseOptions:{prereduced:Y?.prereduced??!1},undeclaredKeyHandling:void 0,...Y}}_transform(Y,Z){let X=Z.bindScope??this.$;if(Z.seen[this.id])return this.$.lazilyResolve(Z.seen[this.id]);if(Z.shouldTransform?.(this,Z)===!1)return this;let _;if(Z.seen[this.id]=()=>_,this.hasKind("structure")&&this.undeclared!==Z.undeclaredKeyHandling)Z={...Z,undeclaredKeyHandling:this.undeclared};let G=o(this.inner,(J,z)=>{if(!this.impl.keys[J].child)return[J,z];let O=z;if(!O0(O)){let V=O._transform(Y,Z);return V?[J,V]:[]}if(O.length===0)return[J,z];let D=O.flatMap((V)=>{return V._transform(Y,Z)??[]});return D.length?[J,D]:[]});delete Z.seen[this.id];let W=Object.assign(G,{meta:this.meta}),$=Z.selected&&!Z.selected.includes(this)?W:Y(this.kind,W,Z);if($===null)return null;if(V0($))return _=$;let H=Object.keys($);if((H.length===0||H.length===1&&H[0]==="meta")&&!c1(this.inner))return null;if((this.kind==="required"||this.kind==="optional"||this.kind==="index")&&!("value"in $))return Z.undeclaredKeyHandling?{...$,value:B.intrinsic.unknown}:null;if(this.kind==="morph")$.in??=B.intrinsic.unknown;return _=X.node(this.kind,$,Z.parseOptions)}configureReferences(Y,Z="references"){let X=c8.normalize(Z),_=typeof Y==="string"?(H,Q)=>({...Q,meta:{...Q.meta,description:Y}}):typeof Y==="function"?(H,Q)=>({...Q,meta:Y(Q.meta)}):(H,Q)=>({...Q,meta:{...Q.meta,...Y}});if(X.boundary==="self")return this.$.node(this.kind,_(this.kind,{...this.inner,meta:this.meta}));let G=this._select(X),W=G&&F4(G),$=X.boundary==="child"?(H,Q)=>Q.root.children.includes(H):X.boundary==="shallow"?(H)=>H.kind!=="structure":()=>!0;return this.$.finalize(this.transform(_,{shouldTransform:$,selected:W}))}}var c8={applyBoundary:{self:(Y)=>[Y],child:(Y)=>[...Y.children],shallow:(Y)=>[...Y.shallowReferences],references:(Y)=>[...Y.references]},applyMethod:{filter:(Y)=>Y,assertFilter:(Y,Z,X)=>{if(Y.length===0)q4(nX(Z,X));return Y},find:(Y)=>Y[0],assertFind:(Y,Z,X)=>{if(Y.length===0)q4(nX(Z,X));return Y[0]}},normalize:(Y)=>typeof Y==="function"?{boundary:"references",method:"filter",where:Y}:typeof Y==="string"?p0(Y,c8.applyBoundary)?{method:"filter",boundary:Y}:{boundary:"references",method:"filter",kind:Y}:{boundary:"references",method:"filter",...Y}},nX=(Y,Z)=>`${Y} had no references matching ${n(Z)}.`,JJ=(Y)=>Y4(Y,{stringifyNonKey:(Z)=>Z.expression}),QJ=/"(\$ark\.[^"]+)"/g,zJ=(Y)=>JSON.stringify(Y).replaceAll(QJ,"$1"),b1=(Y,Z)=>({path:Y,node:Z,propString:JJ(Y)}),rX=(Y,Z)=>Y.propString===Z.propString&&Y.node.equals(Z.node),KY=(Y,Z)=>d1(Y,Z,{isEqual:rX}),UJ=(Y,Z)=>d1(Y,Z,{isEqual:(X,_)=>X.equals(_)});class S extends Array{static init(Y,Z,X,_){return new S({kind:Y,l:Z,r:X,path:_?.path??[],optional:_?.optional??!1})}add(Y,Z,X,_){return this.push({kind:Y,l:Z,r:X,path:_?.path??[],optional:_?.optional??!1}),this}get summary(){return this.describeReasons()}describeReasons(){if(this.length===1){let{path:Y,l:Z,r:X}=this[0],_=Y4(Y);return jY(`Intersection${_&&` at ${_}`} of ${sX(Z,X)}`)}return`The following intersections result in unsatisfiable types:
23
+ \u2022 ${this.map(({path:Y,l:Z,r:X})=>`${Y}: ${sX(Z,X)}`).join(`
24
+ \u2022 `)}`}throw(){return w(this.describeReasons())}invert(){let Y=this.map((Z)=>({...Z,l:Z.r,r:Z.l}));if(!(Y instanceof S))return new S(...Y);return Y}withPrefixKey(Y,Z){return this.map((X)=>({...X,path:[Y,...X.path],optional:X.optional||Z==="optional"}))}toNeverIfDisjoint(){return B.intrinsic.never}}var sX=(Y,Z)=>`${qY(Y)} and ${qY(Z)}`,qY=(Y)=>V0(Y)?Y.expression:O0(Y)?Y.map(qY).join(" | ")||"never":String(Y),jY=(Y)=>`${Y} results in an unsatisfiable type`;var Y8={},O1=(Y,Z,X)=>M0(Y,Z,{$:X,invert:!1,pipe:!1}),i8=(Y,Z,X)=>M0(Y,Z,{$:X,invert:!1,pipe:!0}),M0=(Y,Z,X)=>{let _=X.pipe?"|>":"&",G=`${Y.hash}${_}${Z.hash}`;if(Y8[G]!==void 0)return Y8[G];if(!X.pipe){let H=`${Z.hash}${_}${Y.hash}`;if(Y8[H]!==void 0){let Q=Y8[H],J=Q instanceof S?Q.invert():Q;return Y8[G]=J,J}}let W=!X.pipe||!Y.includesTransform&&!Z.includesTransform;if(W&&Y.equals(Z))return Y;let $=W?PY(Y,Z,X):Y.hasKindIn(...a4)?FJ(Y,Z,X):PY(Y,Z,X);if(V0($)){if(Y.equals($))$=Y;else if(Z.equals($))$=Z}return Y8[G]=$,$},PY=(Y,Z,X)=>{let _=Y.precedence<Z.precedence?Y.kind:Z.kind,G=Y.impl.intersections[Z.kind]??Z.impl.intersections[Y.kind];if(G===void 0)return null;else if(_===Y.kind)return G(Y,Z,X);else{let W=G(Z,Y,{...X,invert:!X.invert});if(W instanceof S)W=W.invert();return W}},FJ=(Y,Z,X)=>Y.includesTransform||Z.includesTransform?X.invert?aX(Z,Y,X):aX(Y,Z,X):PY(Y,Z,X),aX=(Y,Z,X)=>Y.distribute((_)=>OJ(_,Z,X),(_)=>{let G=_.filter(V0);if(G.length===0)return S.init("union",Y.branches,Z.branches);if(G.length<Y.branches.length||!Y.branches.every((H,Q)=>H.in.equals(G[Q].in)))return X.$.parseSchema(G);let W;if(G.length===1){let H=G[0];if(!W)return H;return X.$.node("morph",{...H.inner,in:H.in.configure(W,"self")})}let $={branches:G};if(W)$.meta=W;return X.$.parseSchema($)}),OJ=(Y,Z,X)=>{if(Y.hasKind("morph")){let G=[...Y.morphs];if(Y.lastMorphIfNode){let W=M0(Y.lastMorphIfNode,Z,X);if(W instanceof S)return W;G[G.length-1]=W}else G.push(Z);return X.$.node("morph",{morphs:G,in:Y.inner.in})}if(Z.hasKind("morph")){let G=M0(Y,Z.in,X);if(G instanceof S)return G;return X.$.node("morph",{morphs:[Z],in:G})}return X.$.node("morph",{morphs:[Z],in:Y})};class C1 extends l8{constructor(Y,Z){super(Y,Z);Object.defineProperty(this,X1,{value:"constraint",enumerable:!1})}impliedSiblings;intersect(Y){return O1(this,Y,this.$)}}class X4 extends C1{traverseApply=(Y,Z)=>{if(!this.traverseAllows(Y,Z))Z.errorFromNodeContext(this.errorContext)};compile(Y){if(Y.traversalKind==="Allows")Y.return(this.compiledCondition);else Y.if(this.compiledNegation,()=>Y.line(`${Y.ctx}.errorFromNodeContext(${this.compiledErrorContext})`))}get errorContext(){return{code:this.kind,description:this.description,meta:this.meta,...this.inner}}get compiledErrorContext(){return L4(this.errorContext)}}var t0=(Y)=>(Z,X)=>{if(O0(Z)){if(Z.length===0)return;let G=Z.map((W)=>X.$.node(Y,W));if(Y==="predicate")return G;return G.sort((W,$)=>W.hash<$.hash?-1:1)}let _=X.$.node(Y,Z);return _.hasOpenIntersection()?[_]:_},Z8=(Y)=>{let Z=Y.r.shift();if(!Z){let _=Y.l.length===0&&Y.kind==="structure"?B.intrinsic.unknown.internal:Y.ctx.$.node(Y.kind,Object.assign(Y.baseInner,EJ(Y.l)),{prereduced:!0});for(let G of Y.roots){if(_ instanceof S)return _;_=M0(G,_,Y.ctx)}return _}let X=!1;for(let _=0;_<Y.l.length;_++){let G=M0(Y.l[_],Z,Y.ctx);if(G===null)continue;if(G instanceof S)return G;if(!X){if(G.isRoot())return Y.roots.push(G),Y.l.splice(_),Z8(Y);Y.l[_]=G,X=!0}else if(!Y.l.includes(G))return _0(`Unexpectedly encountered multiple distinct intersection results for refinement ${G}`)}if(!X)Y.l.push(Z);if(Y.kind==="intersection"){if(Z.impliedSiblings)for(let _ of Z.impliedSiblings)d1(Y.r,_)}return Z8(Y)},X8=(Y)=>{return Object.entries(Y).flatMap(([X,_])=>(X in c2)?_:[]).sort((X,_)=>X.precedence<_.precedence?-1:X.precedence>_.precedence?1:X.kind==="predicate"&&_.kind==="predicate"?0:X.hash<_.hash?-1:1)},EJ=(Y)=>{let Z={};for(let X of Y)if(X.hasOpenIntersection())Z[X.kind]=Z0(Z[X.kind],X);else{if(Z[X.kind])return _0(`Unexpected intersection of closed refinements of kind ${X.kind}`);Z[X.kind]=X}return Z},tX=(...Y)=>w(eX(...Y)),eX=(Y,Z,X)=>{let _=X.hasKind("morph")?"a morph":X.isUnknown()?"unknown":X.exclude(Z).defaultShortDescription;return`${qX(Y)} operand must be ${Z.description} (was ${_})`};var Y_=(Y,Z,X)=>new M4(Y,Z,X,X,null);class i2 extends h1{}class M4 extends h1{[X1]="generic";paramDefs;bodyDef;$;arg$;baseInstantiation;hkt;description;constructor(Y,Z,X,_,G){super((...W)=>{let $=o(this.names,(H,Q)=>{let J=this.arg$.parse(W[H]);if(!J.extends(this.constraints[H]))w(DJ(Q,this.constraints[H].expression,J.expression));return[Q,J]});if(this.defIsLazy()){let H=this.bodyDef($);return this.$.parse(H)}return this.$.parse(Z,{args:$})});this.paramDefs=Y,this.bodyDef=Z,this.$=X,this.arg$=_,this.hkt=G,this.description=G?new G().description??`a generic type for ${G.constructor.name}`:"a generic type",this.baseInstantiation=this(...this.constraints)}defIsLazy(){return this.bodyDef instanceof i2}cacheGetter(Y,Z){return Object.defineProperty(this,Y,{value:Z}),Z}get json(){return this.cacheGetter("json",{params:this.params.map((Y)=>Y[1].isUnknown()?Y[0]:[Y[0],Y[1].json]),body:yX(this.bodyDef)})}get params(){return this.cacheGetter("params",this.paramDefs.map((Y)=>typeof Y==="string"?[Y,B.intrinsic.unknown]:[Y[0],this.$.parse(Y[1])]))}get names(){return this.cacheGetter("names",this.params.map((Y)=>Y[0]))}get constraints(){return this.cacheGetter("constraints",this.params.map((Y)=>Y[1]))}get internal(){return this}get referencesById(){return this.baseInstantiation.internal.referencesById}get references(){return this.baseInstantiation.internal.references}}var DJ=(Y,Z,X)=>`${Y} must be assignable to ${Z} (was ${X})`;var LJ=r({kind:"predicate",hasAssociatedError:!0,collapsibleKey:"predicate",keys:{predicate:{}},normalize:(Y)=>typeof Y==="function"?{predicate:Y}:Y,defaults:{description:(Y)=>`valid according to ${Y.predicate.name||"an anonymous predicate"}`},intersectionIsOpen:!0,intersections:{predicate:()=>null}});class Z_ extends C1{serializedPredicate=K0(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=L4(this.errorContext);traverseApply=(Y,Z)=>{if(!this.predicate(Y,Z.external)&&!Z.hasError())Z.errorFromNodeContext(this.errorContext)};compile(Y){if(Y.traversalKind==="Allows"){Y.return(this.compiledCondition);return}Y.if(`${this.compiledNegation} && !ctx.hasError()`,()=>Y.line(`ctx.errorFromNodeContext(${this.compiledErrorContext})`))}reduceJsonSchema(Y,Z){return Z.fallback.predicate({code:"predicate",base:Y,predicate:this.predicate})}}var SY={implementation:LJ,Node:Z_};var VJ=r({kind:"divisor",collapsibleKey:"rule",keys:{rule:{parse:(Y)=>Number.isInteger(Y)?Y:w(MJ(Y))}},normalize:(Y)=>typeof Y==="number"?{rule:Y}:Y,hasAssociatedError:!0,defaults:{description:(Y)=>Y.rule===1?"an integer":Y.rule===2?"even":`a multiple of ${Y.rule}`},intersections:{divisor:(Y,Z,X)=>X.$.node("divisor",{rule:Math.abs(Y.rule*Z.rule/AJ(Y.rule,Z.rule))})},obviatesBasisDescription:!0});class X_ extends X4{traverseAllows=(Y)=>Y%this.rule===0;compiledCondition=`data % ${this.rule} === 0`;compiledNegation=`data % ${this.rule} !== 0`;impliedBasis=B.intrinsic.number.internal;expression=`% ${this.rule}`;reduceJsonSchema(Y){if(Y.type="integer",this.rule===1)return Y;return Y.multipleOf=this.rule,Y}}var vY={implementation:VJ,Node:X_};var MJ=(Y)=>`divisor must be an integer (was ${Y})`,AJ=(Y,Z)=>{let X,_=Y,G=Z;while(G!==0)X=G,G=_%G,_=X;return _};class w1 extends X4{boundOperandKind=IJ[this.kind];compiledActual=this.boundOperandKind==="value"?"data":this.boundOperandKind==="length"?"data.length":"data.valueOf()";comparator=BJ(this.kind,this.exclusive);numericLimit=this.rule.valueOf();expression=`${this.comparator} ${this.rule}`;compiledCondition=`${this.compiledActual} ${this.comparator} ${this.numericLimit}`;compiledNegation=`${this.compiledActual} ${wJ[this.comparator]} ${this.numericLimit}`;stringLimit=this.boundOperandKind==="date"?CJ(this.numericLimit):`${this.numericLimit}`;limitKind=this.comparator["0"]==="<"?"upper":"lower";isStricterThan(Y){return(this.limitKind==="upper"?this.numericLimit<Y.numericLimit:this.numericLimit>Y.numericLimit)||this.numericLimit===Y.numericLimit&&this.exclusive===!0&&!Y.exclusive}overlapsRange(Y){if(this.isStricterThan(Y))return!1;if(this.numericLimit===Y.numericLimit&&(this.exclusive||Y.exclusive))return!1;return!0}overlapIsUnit(Y){return this.numericLimit===Y.numericLimit&&!this.exclusive&&!Y.exclusive}}var wJ={"<":">=","<=":">",">":"<=",">=":"<"},RJ={min:"max",minLength:"maxLength",after:"before"},o2={parse:(Y)=>Y||void 0},n2=(Y)=>(Z)=>{if(typeof Z==="number")return{rule:Z};let{exclusive:X,..._}=Z;return X?{..._,rule:Y==="minLength"?_.rule+1:_.rule-1}:_},r2=(Y)=>(Z)=>{if(typeof Z==="number"||typeof Z==="string"||Z instanceof Date)return{rule:Z};let{exclusive:X,..._}=Z;if(!X)return _;let G=typeof _.rule==="number"?_.rule:typeof _.rule==="string"?new Date(_.rule).valueOf():_.rule.valueOf();return X?{..._,rule:Y==="after"?G+1:G-1}:_},s2=(Y)=>typeof Y==="string"||typeof Y==="number"?new Date(Y):Y,NJ=(Y,Z)=>`${Y} bound must be a positive integer (was ${Z})`,_8=(Y)=>(Z)=>{if(!Number.isInteger(Z)||Z<0)w(NJ(Y,Z));return Z},IJ={min:"value",max:"value",minLength:"length",maxLength:"length",after:"date",before:"date"},BJ=(Y,Z)=>`${p0(Y,RJ)?">":"<"}${Z?"":"="}`,CJ=(Y)=>typeof Y==="string"?Y:new Date(Y).toLocaleString(),__=(Y)=>`Bounded expression ${Y} must be exactly one of number, string, Array, or Date`;var TJ=r({kind:"after",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:s2,serialize:(Y)=>Y.toISOString()}},normalize:r2("after"),defaults:{description:(Y)=>`${Y.collapsibleLimitString} or later`,actual:v4},intersections:{after:(Y,Z)=>Y.isStricterThan(Z)?Y:Z}});class G_ extends w1{impliedBasis=B.intrinsic.Date.internal;collapsibleLimitString=v4(this.rule);traverseAllows=(Y)=>Y>=this.rule;reduceJsonSchema(Y,Z){return Z.fallback.date({code:"date",base:Y,after:this.rule})}}var xY={implementation:TJ,Node:G_};var KJ=r({kind:"before",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:s2,serialize:(Y)=>Y.toISOString()}},normalize:r2("before"),defaults:{description:(Y)=>`${Y.collapsibleLimitString} or earlier`,actual:v4},intersections:{before:(Y,Z)=>Y.isStricterThan(Z)?Y:Z,after:(Y,Z,X)=>Y.overlapsRange(Z)?Y.overlapIsUnit(Z)?X.$.node("unit",{unit:Y.rule}):null:S.init("range",Y,Z)}});class W_ extends w1{collapsibleLimitString=v4(this.rule);traverseAllows=(Y)=>Y<=this.rule;impliedBasis=B.intrinsic.Date.internal;reduceJsonSchema(Y,Z){return Z.fallback.date({code:"date",base:Y,before:this.rule})}}var hY={implementation:KJ,Node:W_};var qJ=r({kind:"exactLength",collapsibleKey:"rule",keys:{rule:{parse:_8("exactLength")}},normalize:(Y)=>typeof Y==="number"?{rule:Y}:Y,hasAssociatedError:!0,defaults:{description:(Y)=>`exactly length ${Y.rule}`,actual:(Y)=>`${Y.length}`},intersections:{exactLength:(Y,Z,X)=>S.init("unit",X.$.node("unit",{unit:Y.rule}),X.$.node("unit",{unit:Z.rule}),{path:["length"]}),minLength:(Y,Z)=>Y.rule>=Z.rule?Y:S.init("range",Y,Z),maxLength:(Y,Z)=>Y.rule<=Z.rule?Y:S.init("range",Y,Z)}});class $_ extends X4{traverseAllows=(Y)=>Y.length===this.rule;compiledCondition=`data.length === ${this.rule}`;compiledNegation=`data.length !== ${this.rule}`;impliedBasis=B.intrinsic.lengthBoundable.internal;expression=`== ${this.rule}`;reduceJsonSchema(Y){switch(Y.type){case"string":return Y.minLength=this.rule,Y.maxLength=this.rule,Y;case"array":return Y.minItems=this.rule,Y.maxItems=this.rule,Y;default:return N0.throwInternalOperandError("exactLength",Y)}}}var fY={implementation:qJ,Node:$_};var jJ=r({kind:"max",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{},exclusive:o2},normalize:(Y)=>typeof Y==="number"?{rule:Y}:Y,defaults:{description:(Y)=>{if(Y.rule===0)return Y.exclusive?"negative":"non-positive";return`${Y.exclusive?"less than":"at most"} ${Y.rule}`}},intersections:{max:(Y,Z)=>Y.isStricterThan(Z)?Y:Z,min:(Y,Z,X)=>Y.overlapsRange(Z)?Y.overlapIsUnit(Z)?X.$.node("unit",{unit:Y.rule}):null:S.init("range",Y,Z)},obviatesBasisDescription:!0});class H_ extends w1{impliedBasis=B.intrinsic.number.internal;traverseAllows=this.exclusive?(Y)=>Y<this.rule:(Y)=>Y<=this.rule;reduceJsonSchema(Y){if(this.exclusive)Y.exclusiveMaximum=this.rule;else Y.maximum=this.rule;return Y}}var bY={implementation:jJ,Node:H_};var PJ=r({kind:"maxLength",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:_8("maxLength")}},reduce:(Y,Z)=>Y.rule===0?Z.node("exactLength",Y):void 0,normalize:n2("maxLength"),defaults:{description:(Y)=>`at most length ${Y.rule}`,actual:(Y)=>`${Y.length}`},intersections:{maxLength:(Y,Z)=>Y.isStricterThan(Z)?Y:Z,minLength:(Y,Z,X)=>Y.overlapsRange(Z)?Y.overlapIsUnit(Z)?X.$.node("exactLength",{rule:Y.rule}):null:S.init("range",Y,Z)}});class J_ extends w1{impliedBasis=B.intrinsic.lengthBoundable.internal;traverseAllows=(Y)=>Y.length<=this.rule;reduceJsonSchema(Y){switch(Y.type){case"string":return Y.maxLength=this.rule,Y;case"array":return Y.maxItems=this.rule,Y;default:return N0.throwInternalOperandError("maxLength",Y)}}}var kY={implementation:PJ,Node:J_};var SJ=r({kind:"min",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{},exclusive:o2},normalize:(Y)=>typeof Y==="number"?{rule:Y}:Y,defaults:{description:(Y)=>{if(Y.rule===0)return Y.exclusive?"positive":"non-negative";return`${Y.exclusive?"more than":"at least"} ${Y.rule}`}},intersections:{min:(Y,Z)=>Y.isStricterThan(Z)?Y:Z},obviatesBasisDescription:!0});class Q_ extends w1{impliedBasis=B.intrinsic.number.internal;traverseAllows=this.exclusive?(Y)=>Y>this.rule:(Y)=>Y>=this.rule;reduceJsonSchema(Y){if(this.exclusive)Y.exclusiveMinimum=this.rule;else Y.minimum=this.rule;return Y}}var gY={implementation:SJ,Node:Q_};var vJ=r({kind:"minLength",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:_8("minLength")}},reduce:(Y)=>Y.rule===0?B.intrinsic.unknown:void 0,normalize:n2("minLength"),defaults:{description:(Y)=>Y.rule===1?"non-empty":`at least length ${Y.rule}`,actual:(Y)=>Y.length===0?"":`${Y.length}`},intersections:{minLength:(Y,Z)=>Y.isStricterThan(Z)?Y:Z}});class z_ extends w1{impliedBasis=B.intrinsic.lengthBoundable.internal;traverseAllows=(Y)=>Y.length>=this.rule;reduceJsonSchema(Y){switch(Y.type){case"string":return Y.minLength=this.rule,Y;case"array":return Y.minItems=this.rule,Y;default:return N0.throwInternalOperandError("minLength",Y)}}}var yY={implementation:vJ,Node:z_};var U_={min:gY.implementation,max:bY.implementation,minLength:yY.implementation,maxLength:kY.implementation,exactLength:fY.implementation,after:xY.implementation,before:hY.implementation},F_={min:gY.Node,max:bY.Node,minLength:yY.Node,maxLength:kY.Node,exactLength:fY.Node,after:xY.Node,before:hY.Node};var xJ=r({kind:"pattern",collapsibleKey:"rule",keys:{rule:{},flags:{}},normalize:(Y)=>typeof Y==="string"?{rule:Y}:Y instanceof RegExp?Y.flags?{rule:Y.source,flags:Y.flags}:{rule:Y.source}:Y,obviatesBasisDescription:!0,obviatesBasisExpression:!0,hasAssociatedError:!0,intersectionIsOpen:!0,defaults:{description:(Y)=>`matched by ${Y.rule}`},intersections:{pattern:()=>null}});class O_ extends X4{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=B.intrinsic.string.internal;reduceJsonSchema(Y,Z){if(Y.pattern)return Z.fallback.patternIntersection({code:"patternIntersection",base:Y,pattern:this.rule});return Y.pattern=this.rule,Y}}var pY={implementation:xJ,Node:O_};var o8=(Y,Z)=>{let X=hJ(Y);if(Z&&!Z.includes(X))return w(`Root of kind ${X} should be one of ${Z}`);return X},hJ=(Y)=>{if(y(Y,"root"))return Y.kind;if(typeof Y==="string")return Y[0]==="$"?"alias":(Y in z1)?"domain":"proto";if(typeof Y==="function")return"proto";if(typeof Y!=="object"||Y===null)return w(E_(Y));if("morphs"in Y)return"morph";if("branches"in Y||O0(Y))return"union";if("unit"in Y)return"unit";if("reference"in Y)return"alias";let Z=Object.keys(Y);if(Z.length===0||Z.some((X)=>(X in c2)))return"intersection";if("proto"in Y)return"proto";if("domain"in Y)return"domain";return w(E_(Y))},E_=(Y)=>`${n(Y)} is not a valid type schema`,D_={},fJ=(Y)=>O0(Y)?Y.map((Z)=>Z.collapsibleJson):Y.collapsibleJson,_1={};B.nodesByRegisteredId=_1;var mY=(Y)=>{return D_[Y]??=0,`${Y}${++D_[Y]}`},uY=(Y)=>{let Z=G8[Y.kind],X=Z.applyConfig?.(Y.def,Y.$.resolvedConfig)??Y.def,_={},{meta:G,...W}=X,$=G===void 0?{}:typeof G==="string"?{description:G}:G,H=UY(W).sort(([J],[z])=>t4(J)?t4(z)?e4(J)-e4(z):1:t4(z)?-1:J<z?-1:1).filter(([J,z])=>{if(J.startsWith("meta.")){let O=J.slice(5);return $[O]=z,!1}return!0});for(let J of H){let z=J[0],O=Z.keys[z];if(!O)return w(`Key ${z} is not valid on ${Y.kind} schema`);let D=O.parse?O.parse(J[1],Y):J[1];if(D!==A1&&(D!==void 0||O.preserveUndefined))_[z]=D}if(Z.reduce&&!Y.prereduced){let J=Z.reduce(_,Y.$);if(J){if(J instanceof S)return J.throw();return bJ(J,$)}}return dY({id:Y.id,kind:Y.kind,inner:_,meta:$,$:Y.$})},dY=({id:Y,kind:Z,inner:X,meta:_,$:G,ignoreCache:W})=>{let $=G8[Z],H=UY(X),Q=[],J={};for(let[b,f]of H){let h=$.keys[b],I=h.serialize??(h.child?fJ:B1);if(J[b]=I(f),h.child===!0){let N=f;if(O0(N))Q.push(...N);else Q.push(N)}else if(typeof h.child==="function")Q.push(...h.child(f))}if($.finalizeInnerJson)J=$.finalizeInnerJson(J);let z={...J},O={};if(!c1(_))O=o(_,(b,f)=>[b,b==="examples"?f:B1(f)]),z.meta=a2(O,"description",!0);J=a2(J,$.collapsibleKey,!1);let D=JSON.stringify({kind:Z,...J});z=a2(z,$.collapsibleKey,!1);let V=a2(z,$.collapsibleKey,!0),R=JSON.stringify({kind:Z,...z});if(G.nodesByHash[R]&&!W)return G.nodesByHash[R];let A={id:Y,kind:Z,impl:$,inner:X,innerEntries:H,innerJson:J,innerHash:D,meta:_,metaJson:O,json:z,hash:R,collapsibleJson:V,children:Q};if(Z!=="intersection"){for(let b in X)if(b!=="in"&&b!=="out")A[b]=X[b]}let g=new V_[Z](A,G);return G.nodesByHash[R]=g},L_=(Y,Z)=>{if(Y.id===Z)return Y;if(V0(_1[Z]))_0(`Unexpected attempt to overwrite node id ${Z}`);return dY({id:Z,kind:Y.kind,inner:Y.inner,meta:Y.meta,$:Y.$,ignoreCache:!0})},bJ=(Y,Z,X)=>{if(X&&V0(_1[X]))_0(`Unexpected attempt to overwrite node id ${X}`);return dY({id:X??mY(Z.alias??Y.kind),kind:Y.kind,inner:Y.inner,meta:Z,$:Y.$})},a2=(Y,Z,X)=>{let _=Object.keys(Y);if(_.length===1&&_[0]===Z){let G=Y[Z];if(X)return G;if(Q1(G,"object")&&(Object.keys(G).length===1||Array.isArray(G)))return G}return Y};var n8=(Y,Z,X)=>{if(Y.key!==Z.key)return null;let _=Y.key,G=M0(Y.value,Z.value,X),W=Y.required||Z.required?"required":"optional";if(G instanceof S)if(W==="optional")G=B.intrinsic.never.internal;else return G.withPrefixKey(Y.key,Y.required&&Z.required?"required":"optional");if(W==="required")return X.$.node("required",{key:_,value:G});let $=Y.hasDefault()?Z.hasDefault()?Y.default===Z.default?Y.default:w(cY(Y.default,Z.default)):Y.default:Z.hasDefault()?Z.default:A1;return X.$.node("optional",{key:_,value:G,default:$})};class r8 extends C1{required=this.kind==="required";optional=this.kind==="optional";impliedBasis=B.intrinsic.object.internal;serializedKey=Z4(this.key);compiledKey=typeof this.key==="string"?this.key:this.serializedKey;flatRefs=Z0(this.value.flatRefs.map((Y)=>b1([this.key,...Y.path],Y.node)),b1([this.key],this.value));_transform(Y,Z){Z.path.push(this.key);let X=super._transform(Y,Z);return Z.path.pop(),X}hasDefault(){return"default"in this.inner}traverseAllows=(Y,Z)=>{if(this.key in Y)return F1(this.key,()=>this.value.traverseAllows(Y[this.key],Z),Z);return this.optional};traverseApply=(Y,Z)=>{if(this.key in Y)F1(this.key,()=>this.value.traverseApply(Y[this.key],Z),Z);else if(this.hasKind("required"))Z.errorFromNodeContext(this.errorContext)};compile(Y){if(Y.if(`${this.serializedKey} in data`,()=>Y.traverseKey(this.serializedKey,`data${Y.prop(this.key)}`,this.value)),this.hasKind("required"))Y.else(()=>Y.traversalKind==="Apply"?Y.line(`ctx.errorFromNodeContext(${this.compiledErrorContext})`):Y.return(!1));if(Y.traversalKind==="Allows")Y.return(!0)}}var cY=(Y,Z)=>`Invalid intersection of default values ${n(Y)} & ${n(Z)}`;var kJ=r({kind:"optional",hasAssociatedError:!1,intersectionIsOpen:!0,keys:{key:{},value:{child:!0,parse:(Y,Z)=>Z.$.parseSchema(Y)},default:{preserveUndefined:!0}},normalize:(Y)=>Y,reduce:(Y,Z)=>{if(Z.resolvedConfig.exactOptionalPropertyTypes===!1){if(!Y.value.allows(void 0))return Z.node("optional",{...Y,value:Y.value.or(d.undefined)},{prereduced:!0})}},defaults:{description:(Y)=>`${Y.compiledKey}?: ${Y.value.description}`},intersections:{optional:n8}});class M_ extends r8{constructor(...Y){super(...Y);if("default"in this.inner)a8(this.value,this.inner.default,this.key)}get outProp(){if(!this.hasDefault())return this;let{default:Y,...Z}=this.inner;return this.cacheGetter("outProp",this.$.node("required",Z,{prereduced:!0}))}expression=this.hasDefault()?`${this.compiledKey}: ${this.value.expression} = ${n(this.inner.default)}`:`${this.compiledKey}?: ${this.value.expression}`;defaultValueMorph=yJ(this);defaultValueMorphRef=this.defaultValueMorph&&K0(this.defaultValueMorph)}var s8={implementation:kJ,Node:M_},gJ={},yJ=(Y)=>{if(!Y.hasDefault())return;let Z=`{${Y.compiledKey}: ${Y.value.id} = ${B1(Y.default)}}`;return gJ[Z]??=lY(Y.key,Y.value,Y.default)},lY=(Y,Z,X)=>{if(typeof X==="function")return Z.includesTransform?(G,W)=>{return F1(Y,()=>Z(G[Y]=X(),W),W),G}:(G)=>{return G[Y]=X(),G};let _=Z.includesTransform?Z.assert(X):X;return Q1(_,"object")?(G,W)=>{return F1(Y,()=>Z(G[Y]=X,W),W),G}:(G)=>{return G[Y]=_,G}},a8=(Y,Z,X)=>{let _=O4(Z);if(Q1(Z,"object")&&!_)w(pJ(X));let G=Y.in(_?Z():Z);if(G instanceof U1){if(X===null)w(`Default ${G.summary}`);let W=G.transform(($)=>$.transform((H)=>({...H,prefixPath:[X]})));w(`Default for ${W.summary}`)}return Z},pJ=(Y)=>{return`Non-primitive default ${Y===null?"":typeof Y==="number"?`for value at [${Y}] `:`for ${Z4(Y)} `}must be specified as a function like () => ({my: 'object'})`};class T1 extends l8{constructor(Y,Z){super(Y,Z);Object.defineProperty(this,X1,{value:"root",enumerable:!1})}get internal(){return this}get "~standard"(){return{vendor:"arktype",version:1,validate:(Y)=>{let Z=this(Y);if(Z instanceof U1)return Z;return{value:Z}}}}as(){return this}brand(Y){if(Y==="")return w(mJ);return this}readonly(){return this}branches=this.hasKind("union")?this.inner.branches:[this];distribute(Y,Z){let X=this.branches.map(Y);return Z?.(X)??X}get shortDescription(){return this.meta.description??this.defaultShortDescription}toJsonSchema(Y={}){let Z=CY(this.$.resolvedConfig.toJsonSchema,Y);Z.useRefs||=this.isCyclic;let X=typeof Z.dialect==="string"?{$schema:Z.dialect}:{};if(Object.assign(X,this.toJsonSchemaRecurse(Z)),Z.useRefs)X.$defs=o(this.references,(_,G)=>G.isRoot()&&!G.alwaysExpandJsonSchema?[G.id,G.toResolvedJsonSchema(Z)]:[]);return X}toJsonSchemaRecurse(Y){if(Y.useRefs&&!this.alwaysExpandJsonSchema)return{$ref:`#/$defs/${this.id}`};return this.toResolvedJsonSchema(Y)}get alwaysExpandJsonSchema(){return this.isBasis()||this.kind==="alias"||this.hasKind("union")&&this.isBoolean}toResolvedJsonSchema(Y){let Z=this.innerToJsonSchema(Y);return Object.assign(Z,this.metaJson)}intersect(Y){let Z=this.$.parseDefinition(Y),X=this.rawIntersect(Z);if(X instanceof S)return X;return this.$.finalize(X)}rawIntersect(Y){return O1(this,Y,this.$)}toNeverIfDisjoint(){return this}and(Y){let Z=this.intersect(Y);return Z instanceof S?Z.throw():Z}rawAnd(Y){let Z=this.rawIntersect(Y);return Z instanceof S?Z.throw():Z}or(Y){let Z=this.$.parseDefinition(Y);return this.$.finalize(this.rawOr(Z))}rawOr(Y){let Z=[...this.branches,...Y.branches];return this.$.node("union",Z)}map(Y){return this.$.schema(this.applyStructuralOperation("map",[Y]))}pick(...Y){return this.$.schema(this.applyStructuralOperation("pick",Y))}omit(...Y){return this.$.schema(this.applyStructuralOperation("omit",Y))}required(){return this.$.schema(this.applyStructuralOperation("required",[]))}partial(){return this.$.schema(this.applyStructuralOperation("partial",[]))}_keyof;keyof(){if(this._keyof)return this._keyof;let Y=this.applyStructuralOperation("keyof",[]).reduce((Z,X)=>Z.intersect(X).toNeverIfDisjoint(),B.intrinsic.unknown.internal);if(Y.branches.length===0)w(jY(`keyof ${this.expression}`));return this._keyof=this.$.finalize(Y)}get props(){if(this.branches.length!==1)return w(uJ(this.expression));return[...this.applyStructuralOperation("props",[])[0]]}merge(Y){let Z=this.$.parseDefinition(Y);return this.$.schema(Z.distribute((X)=>this.applyStructuralOperation("merge",[A_(X)??w(w_("merge",X.expression))])))}applyStructuralOperation(Y,Z){return this.distribute((X)=>{if(X.equals(B.intrinsic.object)&&Y!=="merge")return X;let _=A_(X);if(!_)w(w_(Y,X.expression));if(Y==="keyof")return _.keyof();if(Y==="get")return _.get(...Z);if(Y==="props")return _.props;let G=Y==="required"?"require":Y==="partial"?"optionalize":Y;return this.$.node("intersection",{...X.inner,structure:_[G](...Z)})})}get(...Y){if(Y[0]===void 0)return this;return this.$.schema(this.applyStructuralOperation("get",Y))}extract(Y){let Z=this.$.parseDefinition(Y);return this.$.schema(this.branches.filter((X)=>X.extends(Z)))}exclude(Y){let Z=this.$.parseDefinition(Y);return this.$.schema(this.branches.filter((X)=>!X.extends(Z)))}array(){return this.$.schema(this.isUnknown()?{proto:Array}:{proto:Array,sequence:this},{prereduced:!0})}overlaps(Y){return!(this.intersect(Y)instanceof S)}extends(Y){let Z=this.intersect(Y);return!(Z instanceof S)&&this.equals(Z)}ifExtends(Y){return this.extends(Y)?this:void 0}subsumes(Y){return this.$.parseDefinition(Y).extends(this)}configure(Y,Z="shallow"){return this.configureReferences(Y,Z)}describe(Y,Z="shallow"){return this.configure({description:Y},Z)}optional(){return[this,"?"]}default(Y){return a8(this,Y,null),[this,"=",Y]}from(Y){return this.assert(Y)}_pipe(...Y){let Z=Y.reduce((X,_)=>X.rawPipeOnce(_),this);return this.$.finalize(Z)}tryPipe(...Y){let Z=Y.reduce((X,_)=>X.rawPipeOnce(y(_,"root")?_:(G,W)=>{try{return _(G,W)}catch($){return W.error({code:"predicate",predicate:_,actual:`aborted due to error:
25
+ ${$}
26
+ `})}}),this);return this.$.finalize(Z)}pipe=Object.assign(this._pipe.bind(this),{try:this.tryPipe.bind(this)});to(Y){return this.$.finalize(this.toNode(this.$.parseDefinition(Y)))}toNode(Y){let Z=i8(this,Y,this.$);if(Z instanceof S)return Z.throw();return Z}rawPipeOnce(Y){if(y(Y,"root"))return this.toNode(Y);return this.distribute((Z)=>Z.hasKind("morph")?this.$.node("morph",{in:Z.inner.in,morphs:[...Z.morphs,Y]}):this.$.node("morph",{in:Z,morphs:[Y]}),this.$.parseSchema)}narrow(Y){return this.constrainOut("predicate",Y)}constrain(Y,Z){return this._constrain("root",Y,Z)}constrainIn(Y,Z){return this._constrain("in",Y,Z)}constrainOut(Y,Z){return this._constrain("out",Y,Z)}_constrain(Y,Z,X){let _=this.$.node(Z,X);if(_.isRoot())return _.isUnknown()?this:_0(`Unexpected constraint node ${_}`);let G=Y==="root"?this:this[Y];if(G.hasKind("morph")||_.impliedBasis&&!G.extends(_.impliedBasis))return tX(Z,_.impliedBasis,this);let W=this.$.node("intersection",{[_.kind]:_}),$=Y==="out"?i8(this,W,this.$):O1(this,W,this.$);if($ instanceof S)$.throw();return this.$.finalize($)}onUndeclaredKey(Y){let Z=typeof Y==="string"?Y:Y.rule,X=typeof Y==="string"?!1:Y.deep;return this.$.finalize(this.transform((_,G)=>_==="structure"?Z==="ignore"?VX(G,{undeclared:1}):{...G,undeclared:Z}:G,X?void 0:{shouldTransform:(_)=>!s1(s4,_.kind)}))}hasEqualMorphs(Y){if(!this.includesTransform&&!Y.includesTransform)return!0;if(!t1(this.shallowMorphs,Y.shallowMorphs))return!1;if(!t1(this.flatMorphs,Y.flatMorphs,{isEqual:(Z,X)=>Z.propString===X.propString&&(Z.node.hasKind("morph")&&X.node.hasKind("morph")?Z.node.hasEqualMorphs(X.node):Z.node.hasKind("intersection")&&X.node.hasKind("intersection")?Z.node.structure?.structuralMorphRef===X.node.structure?.structuralMorphRef:!1)}))return!1;return!0}onDeepUndeclaredKey(Y){return this.onUndeclaredKey({rule:Y,deep:!0})}filter(Y){return this.constrainIn("predicate",Y)}divisibleBy(Y){return this.constrain("divisor",Y)}matching(Y){return this.constrain("pattern",Y)}atLeast(Y){return this.constrain("min",Y)}atMost(Y){return this.constrain("max",Y)}moreThan(Y){return this.constrain("min",W8(Y))}lessThan(Y){return this.constrain("max",W8(Y))}atLeastLength(Y){return this.constrain("minLength",Y)}atMostLength(Y){return this.constrain("maxLength",Y)}moreThanLength(Y){return this.constrain("minLength",W8(Y))}lessThanLength(Y){return this.constrain("maxLength",W8(Y))}exactlyLength(Y){return this.constrain("exactLength",Y)}atOrAfter(Y){return this.constrain("after",Y)}atOrBefore(Y){return this.constrain("before",Y)}laterThan(Y){return this.constrain("after",W8(Y))}earlierThan(Y){return this.constrain("before",W8(Y))}}var mJ="Expected a non-empty brand name after #",W8=(Y)=>typeof Y==="object"&&!(Y instanceof Date)?{...Y,exclusive:!0}:{rule:Y,exclusive:!0},t8=(Y,Z)=>y(Z,"root")?y(Y,"root")?Y.extends(Z):Z.allows(Y):y(Y,"root")?Y.hasUnit(Z):Z===Y,A_=(Y)=>{if(Y.hasKind("morph"))return null;if(Y.hasKind("intersection"))return Y.inner.structure??(Y.basis?.domain==="object"?Y.$.bindReference(B.intrinsic.emptyStructure):null);if(Y.isBasis()&&Y.domain==="object")return Y.$.bindReference(B.intrinsic.emptyStructure);return null},uJ=(Y)=>`Props cannot be extracted from a union. Use .distribute to extract props from each branch instead. Received:
27
+ ${Y}`,w_=(Y,Z)=>`${Y} operand must be an object (was ${Z})`;var l1=(Y,Z)=>o(l2(Y),(X,_)=>[_,Z]);var dJ=(Y)=>typeof Y==="string"?{reference:Y}:Y,R_=(Y)=>Y instanceof S?B.intrinsic.never.internal:Y,cJ=r({kind:"alias",hasAssociatedError:!1,collapsibleKey:"reference",keys:{reference:{serialize:(Y)=>Y.startsWith("$")?Y:`$ark.${Y}`},resolve:{}},normalize:dJ,defaults:{description:(Y)=>Y.reference},intersections:{alias:(Y,Z,X)=>X.$.lazilyResolve(()=>R_(M0(Y.resolution,Z.resolution,X)),`${Y.reference}${X.pipe?"=>":"&"}${Z.reference}`),...l1("alias",(Y,Z,X)=>{if(Z.isUnknown())return Y;if(Z.isNever())return Z;if(Z.isBasis()&&!Z.overlaps(B.intrinsic.object))return S.init("assignability",B.intrinsic.object,Z);return X.$.lazilyResolve(()=>R_(M0(Y.resolution,Z,X)),`${Y.reference}${X.pipe?"=>":"&"}${Z.id}`)})}});class N_ extends T1{expression=this.reference;structure=void 0;get resolution(){let Y=this._resolve();return _1[this.id]=Y}_resolve(){if(this.resolve)return this.resolve();if(this.reference[0]==="$")return this.$.resolveRoot(this.reference.slice(1));let Y=this.reference,Z=_1[Y],X=[];while(y(Z,"context")){if(X.includes(Z.id))return w(lJ(Z.id,X));X.push(Z.id),Z=_1[Z.id]}if(!y(Z,"root"))return _0(`Unexpected resolution for reference ${this.reference}
28
28
  Seen: [${X.join("->")}]
29
- Resolution: ${n(Z)}`);return Z}get resolutionId(){if(this.reference.includes("&")||this.reference.includes("=>"))return this.resolution.id;if(this.reference[0]!=="$")return this.reference;let Y=this.reference.slice(1),Z=this.$.resolutions[Y];if(typeof Z==="string")return Z;if(y(Z,"root"))return Z.id;return _0(`Unexpected resolution for reference ${this.reference}: ${n(Z)}`)}get defaultShortDescription(){return z1.object}innerToJsonSchema(Y){return this.resolution.toJsonSchemaRecurse(Y)}traverseAllows=(Y,Z)=>{let X=Z.seen[this.reference];if(X?.includes(Y))return!0;return Z.seen[this.reference]=Z0(X,Y),this.resolution.traverseAllows(Y,Z)};traverseApply=(Y,Z)=>{let X=Z.seen[this.reference];if(X?.includes(Y))return;Z.seen[this.reference]=Z0(X,Y),this.resolution.traverseApply(Y,Z)};compile(Y){let Z=this.resolutionId;Y.if(`ctx.seen.${Z} && ctx.seen.${Z}.includes(data)`,()=>Y.return(!0)),Y.if(`!ctx.seen.${Z}`,()=>Y.line(`ctx.seen.${Z} = []`)),Y.line(`ctx.seen.${Z}.push(data)`),Y.return(Y.invoke(Z))}}var oQ=(Y,Z)=>`Alias '${Y}' has a shallow resolution cycle: ${[...Z,Y].join("->")}`,t8={implementation:iQ,Node:NG};class x4 extends T1{traverseApply=(Y,Z)=>{if(!this.traverseAllows(Y,Z))Z.errorFromNodeContext(this.errorContext)};get errorContext(){return{code:this.kind,description:this.description,meta:this.meta,...this.inner}}get compiledErrorContext(){return L4(this.errorContext)}compile(Y){if(Y.traversalKind==="Allows")Y.return(this.compiledCondition);else Y.if(this.compiledNegation,()=>Y.line(`${Y.ctx}.errorFromNodeContext(${this.compiledErrorContext})`))}}var nQ=r({kind:"domain",hasAssociatedError:!0,collapsibleKey:"domain",keys:{domain:{},numberAllowsNaN:{}},normalize:(Y)=>typeof Y==="string"?{domain:Y}:n4(Y,"numberAllowsNaN")&&Y.domain!=="number"?w(t6.writeBadAllowNanMessage(Y.domain)):Y,applyConfig:(Y,Z)=>Y.numberAllowsNaN===void 0&&Y.domain==="number"&&Z.numberAllowsNaN?{...Y,numberAllowsNaN:!0}:Y,defaults:{description:(Y)=>z1[Y.domain],actual:(Y)=>Number.isNaN(Y)?"NaN":z1[y0(Y)]},intersections:{domain:(Y,Z)=>Y.domain==="number"&&Z.domain==="number"?Y.numberAllowsNaN?Z:Y:S.init("domain",Y,Z)}});class IG extends x4{requiresNaNCheck=this.domain==="number"&&!this.numberAllowsNaN;traverseAllows=this.requiresNaNCheck?(Y)=>typeof Y==="number"&&!Number.isNaN(Y):(Y)=>y0(Y)===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 z1[this.domain]}innerToJsonSchema(Y){if(this.domain==="bigint"||this.domain==="symbol")return Y.fallback.domain({code:"domain",base:{},domain:this.domain});return{type:this.domain}}}var t6={implementation:nQ,Node:IG,writeBadAllowNanMessage:(Y)=>`numberAllowsNaN may only be specified with domain "number" (was ${Y})`};var rQ=r({kind:"intersection",hasAssociatedError:!0,normalize:(Y)=>{if(V0(Y))return Y;let{structure:Z,...X}=Y,_=!!Z,G=Z??{},W=o(X,(H,J)=>{if(p0(H,c_)){if(_)w(`Flattened structure key ${H} cannot be specified alongside a root 'structure' key.`);return G[H]=J,[]}return[H,J]});if(y(G,"constraint")||!c1(G))W.structure=G;return W},finalizeInnerJson:({structure:Y,...Z})=>$1(Y,"object")?{...Y,...Z}:Z,keys:{domain:{child:!0,parse:(Y,Z)=>Z.$.node("domain",Y)},proto:{child:!0,parse:(Y,Z)=>Z.$.node("proto",Y)},structure:{child:!0,parse:(Y,Z)=>Z.$.node("structure",Y),serialize:(Y)=>{if(!Y.sequence?.minLength)return Y.collapsibleJson;let{sequence:Z,...X}=Y.collapsibleJson,{minVariadicLength:_,...G}=Z,W=G.variadic&&Object.keys(G).length===1?G.variadic:G;return{...X,sequence:W}}},divisor:{child:!0,parse:t0("divisor")},max:{child:!0,parse:t0("max")},min:{child:!0,parse:t0("min")},maxLength:{child:!0,parse:t0("maxLength")},minLength:{child:!0,parse:t0("minLength")},exactLength:{child:!0,parse:t0("exactLength")},before:{child:!0,parse:t0("before")},after:{child:!0,parse:t0("after")},pattern:{child:!0,parse:t0("pattern")},predicate:{child:!0,parse:t0("predicate")}},reduce:(Y,Z)=>BG({},Y,{$:Z,invert:!1,pipe:!1}),defaults:{description:(Y)=>{if(Y.children.length===0)return"unknown";if(Y.structure)return Y.structure.description;let Z=[];if(Y.basis&&!Y.refinements.some((X)=>X.impl.obviatesBasisDescription))Z.push(Y.basis.description);if(Y.refinements.length){let X=Y.refinements.toSorted((_,G)=>_.kind==="min"&&G.kind==="max"?-1:0).map((_)=>_.description);Z.push(...X)}if(Y.inner.predicate)Z.push(...Y.inner.predicate.map((X)=>X.description));return Z.join(" and ")},expected:(Y)=>` \u25E6 ${Y.errors.map((Z)=>Z.expected).join(`
29
+ Resolution: ${n(Z)}`);return Z}get resolutionId(){if(this.reference.includes("&")||this.reference.includes("=>"))return this.resolution.id;if(this.reference[0]!=="$")return this.reference;let Y=this.reference.slice(1),Z=this.$.resolutions[Y];if(typeof Z==="string")return Z;if(y(Z,"root"))return Z.id;return _0(`Unexpected resolution for reference ${this.reference}: ${n(Z)}`)}get defaultShortDescription(){return z1.object}innerToJsonSchema(Y){return this.resolution.toJsonSchemaRecurse(Y)}traverseAllows=(Y,Z)=>{let X=Z.seen[this.reference];if(X?.includes(Y))return!0;return Z.seen[this.reference]=Z0(X,Y),this.resolution.traverseAllows(Y,Z)};traverseApply=(Y,Z)=>{let X=Z.seen[this.reference];if(X?.includes(Y))return;Z.seen[this.reference]=Z0(X,Y),this.resolution.traverseApply(Y,Z)};compile(Y){let Z=this.resolutionId;Y.if(`ctx.seen.${Z} && ctx.seen.${Z}.includes(data)`,()=>Y.return(!0)),Y.if(`!ctx.seen.${Z}`,()=>Y.line(`ctx.seen.${Z} = []`)),Y.line(`ctx.seen.${Z}.push(data)`),Y.return(Y.invoke(Z))}}var lJ=(Y,Z)=>`Alias '${Y}' has a shallow resolution cycle: ${[...Z,Y].join("->")}`,e8={implementation:cJ,Node:N_};class x4 extends T1{traverseApply=(Y,Z)=>{if(!this.traverseAllows(Y,Z))Z.errorFromNodeContext(this.errorContext)};get errorContext(){return{code:this.kind,description:this.description,meta:this.meta,...this.inner}}get compiledErrorContext(){return L4(this.errorContext)}compile(Y){if(Y.traversalKind==="Allows")Y.return(this.compiledCondition);else Y.if(this.compiledNegation,()=>Y.line(`${Y.ctx}.errorFromNodeContext(${this.compiledErrorContext})`))}}var iJ=r({kind:"domain",hasAssociatedError:!0,collapsibleKey:"domain",keys:{domain:{},numberAllowsNaN:{}},normalize:(Y)=>typeof Y==="string"?{domain:Y}:n4(Y,"numberAllowsNaN")&&Y.domain!=="number"?w(t2.writeBadAllowNanMessage(Y.domain)):Y,applyConfig:(Y,Z)=>Y.numberAllowsNaN===void 0&&Y.domain==="number"&&Z.numberAllowsNaN?{...Y,numberAllowsNaN:!0}:Y,defaults:{description:(Y)=>z1[Y.domain],actual:(Y)=>Number.isNaN(Y)?"NaN":z1[y0(Y)]},intersections:{domain:(Y,Z)=>Y.domain==="number"&&Z.domain==="number"?Y.numberAllowsNaN?Z:Y:S.init("domain",Y,Z)}});class I_ extends x4{requiresNaNCheck=this.domain==="number"&&!this.numberAllowsNaN;traverseAllows=this.requiresNaNCheck?(Y)=>typeof Y==="number"&&!Number.isNaN(Y):(Y)=>y0(Y)===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 z1[this.domain]}innerToJsonSchema(Y){if(this.domain==="bigint"||this.domain==="symbol")return Y.fallback.domain({code:"domain",base:{},domain:this.domain});return{type:this.domain}}}var t2={implementation:iJ,Node:I_,writeBadAllowNanMessage:(Y)=>`numberAllowsNaN may only be specified with domain "number" (was ${Y})`};var oJ=r({kind:"intersection",hasAssociatedError:!0,normalize:(Y)=>{if(V0(Y))return Y;let{structure:Z,...X}=Y,_=!!Z,G=Z??{},W=o(X,($,H)=>{if(p0($,cX)){if(_)w(`Flattened structure key ${$} cannot be specified alongside a root 'structure' key.`);return G[$]=H,[]}return[$,H]});if(y(G,"constraint")||!c1(G))W.structure=G;return W},finalizeInnerJson:({structure:Y,...Z})=>Q1(Y,"object")?{...Y,...Z}:Z,keys:{domain:{child:!0,parse:(Y,Z)=>Z.$.node("domain",Y)},proto:{child:!0,parse:(Y,Z)=>Z.$.node("proto",Y)},structure:{child:!0,parse:(Y,Z)=>Z.$.node("structure",Y),serialize:(Y)=>{if(!Y.sequence?.minLength)return Y.collapsibleJson;let{sequence:Z,...X}=Y.collapsibleJson,{minVariadicLength:_,...G}=Z,W=G.variadic&&Object.keys(G).length===1?G.variadic:G;return{...X,sequence:W}}},divisor:{child:!0,parse:t0("divisor")},max:{child:!0,parse:t0("max")},min:{child:!0,parse:t0("min")},maxLength:{child:!0,parse:t0("maxLength")},minLength:{child:!0,parse:t0("minLength")},exactLength:{child:!0,parse:t0("exactLength")},before:{child:!0,parse:t0("before")},after:{child:!0,parse:t0("after")},pattern:{child:!0,parse:t0("pattern")},predicate:{child:!0,parse:t0("predicate")}},reduce:(Y,Z)=>B_({},Y,{$:Z,invert:!1,pipe:!1}),defaults:{description:(Y)=>{if(Y.children.length===0)return"unknown";if(Y.structure)return Y.structure.description;let Z=[];if(Y.basis&&!Y.refinements.some((X)=>X.impl.obviatesBasisDescription))Z.push(Y.basis.description);if(Y.refinements.length){let X=Y.refinements.toSorted((_,G)=>_.kind==="min"&&G.kind==="max"?-1:0).map((_)=>_.description);Z.push(...X)}if(Y.inner.predicate)Z.push(...Y.inner.predicate.map((X)=>X.description));return Z.join(" and ")},expected:(Y)=>` \u25E6 ${Y.errors.map((Z)=>Z.expected).join(`
30
30
  \u25E6 `)}`,problem:(Y)=>`(${Y.actual}) must be...
31
- ${Y.expected}`},intersections:{intersection:(Y,Z,X)=>BG(Y.inner,Z.inner,X),...l1("intersection",(Y,Z,X)=>{if(Y.children.length===0)return Z;let{domain:_,proto:G,...W}=Y.inner,H=G??_,J=H?M0(H,Z,X):Z;return J instanceof S?J:Y?.basis?.equals(J)?Y:Y.$.node("intersection",{...W,[J.kind]:J},{prereduced:!0})})}});class CG extends T1{basis=this.inner.domain??this.inner.proto??null;refinements=this.children.filter((Y)=>Y.isRefinement());structure=this.inner.structure;expression=sQ(this);get shallowMorphs(){return this.inner.structure?.structuralMorph?[this.inner.structure.structuralMorph]:[]}get defaultShortDescription(){return this.basis?.defaultShortDescription??"present"}innerToJsonSchema(Y){return this.children.reduce((Z,X)=>X.isBasis()?X.toJsonSchemaRecurse(Y):X.reduceJsonSchema(Z,Y),{})}traverseAllows=(Y,Z)=>this.children.every((X)=>X.traverseAllows(Y,Z));traverseApply=(Y,Z)=>{let X=Z.currentErrorCount;if(this.basis){if(this.basis.traverseApply(Y,Z),Z.currentErrorCount>X)return}if(this.refinements.length){for(let _=0;_<this.refinements.length-1;_++)if(this.refinements[_].traverseApply(Y,Z),Z.failFast&&Z.currentErrorCount>X)return;if(this.refinements.at(-1).traverseApply(Y,Z),Z.currentErrorCount>X)return}if(this.structure){if(this.structure.traverseApply(Y,Z),Z.currentErrorCount>X)return}if(this.inner.predicate){for(let _=0;_<this.inner.predicate.length-1;_++)if(this.inner.predicate[_].traverseApply(Y,Z),Z.failFast&&Z.currentErrorCount>X)return;this.inner.predicate.at(-1).traverseApply(Y,Z)}};compile(Y){if(Y.traversalKind==="Allows"){for(let Z of this.children)Y.check(Z);Y.return(!0);return}if(Y.initializeErrorCount(),this.basis){if(Y.check(this.basis),this.children.length>1)Y.returnIfFail()}if(this.refinements.length){for(let Z=0;Z<this.refinements.length-1;Z++)Y.check(this.refinements[Z]),Y.returnIfFailFast();if(Y.check(this.refinements.at(-1)),this.structure||this.inner.predicate)Y.returnIfFail()}if(this.structure){if(Y.check(this.structure),this.inner.predicate)Y.returnIfFail()}if(this.inner.predicate){for(let Z=0;Z<this.inner.predicate.length-1;Z++)Y.check(this.inner.predicate[Z]),Y.returnIfFail();Y.check(this.inner.predicate.at(-1))}}}var lZ={implementation:rQ,Node:CG},sQ=(Y)=>{let Z=Y.structure?.expression||`${Y.basis&&!Y.refinements.some((X)=>X.impl.obviatesBasisExpression)?Y.basis.nestableExpression+" ":""}${Y.refinements.map((X)=>X.expression).join(" & ")}`||"unknown";if(Z==="Array == 0")Z="[]";return Z},BG=(Y,Z,X)=>{let _={},G=Y.proto??Y.domain,W=Z.proto??Z.domain,H=G?W?M0(G,W,X):G:W;if(H instanceof S)return H;if(H)_[H.kind]=H;return Z8({kind:"intersection",baseInner:_,l:X8(Y),r:X8(Z),roots:[],ctx:X})};var aQ=r({kind:"morph",hasAssociatedError:!1,keys:{in:{child:!0,parse:(Y,Z)=>Z.$.parseSchema(Y)},morphs:{parse:U4,serialize:(Y)=>Y.map((Z)=>y(Z,"root")?Z.json:K0(Z))},declaredIn:{child:!1,serialize:(Y)=>Y.json},declaredOut:{child:!1,serialize:(Y)=>Y.json}},normalize:(Y)=>Y,defaults:{description:(Y)=>`a morph from ${Y.in.description} to ${Y.out?.description??"unknown"}`},intersections:{morph:(Y,Z,X)=>{if(!Y.hasEqualMorphs(Z))return w(tQ(Y.expression,Z.expression));let _=M0(Y.in,Z.in,X);if(_ instanceof S)return _;let G={morphs:Y.morphs};if(Y.declaredIn||Z.declaredIn){let W=M0(Y.in,Z.in,X);if(W instanceof S)return W.throw();else G.declaredIn=W}if(Y.declaredOut||Z.declaredOut){let W=M0(Y.out,Z.out,X);if(W instanceof S)return W.throw();else G.declaredOut=W}return _.distribute((W)=>X.$.node("morph",{...G,in:W}),X.$.parseSchema)},...l1("morph",(Y,Z,X)=>{let _=Y.inner.in?M0(Y.inner.in,Z,X):Z;return _ instanceof S?_:_.equals(Y.inner.in)?Y:X.$.node("morph",{...Y.inner,in:_})})}});class TG extends T1{serializedMorphs=this.morphs.map(K0);compiledMorphs=`[${this.serializedMorphs}]`;lastMorph=this.inner.morphs.at(-1);lastMorphIfNode=y(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??B.intrinsic.unknown.internal}get out(){return this.declaredOut??this.introspectableOut??B.intrinsic.unknown.internal}declareIn(Y){return this.$.node("morph",{...this.inner,declaredIn:Y})}declareOut(Y){return this.$.node("morph",{...this.inner,declaredOut:Y})}expression=`(In: ${this.in.expression}) => ${this.lastMorphIfNode?"To":"Out"}<${this.out.expression}>`;get defaultShortDescription(){return this.in.meta.description??this.in.defaultShortDescription}innerToJsonSchema(Y){return Y.fallback.morph({code:"morph",base:this.in.toJsonSchemaRecurse(Y),out:this.introspectableOut?.toJsonSchemaRecurse(Y)??null})}compile(Y){if(Y.traversalKind==="Allows"){if(!this.introspectableIn)return;Y.return(Y.invoke(this.introspectableIn));return}if(this.introspectableIn)Y.line(Y.invoke(this.introspectableIn));Y.line(`ctx.queueMorphs(${this.compiledMorphs})`)}traverseAllows=(Y,Z)=>!this.introspectableIn||this.introspectableIn.traverseAllows(Y,Z);traverseApply=(Y,Z)=>{if(this.introspectableIn)this.introspectableIn.traverseApply(Y,Z);Z.queueMorphs(this.morphs)};hasEqualMorphs(Y){return t1(this.morphs,Y.morphs,{isEqual:(Z,X)=>Z===X||y(Z,"root")&&y(X,"root")&&Z.equals(X)})}}var iZ={implementation:aQ,Node:TG},tQ=(Y,Z)=>`The intersection of distinct morphs at a single path is indeterminate:
31
+ ${Y.expected}`},intersections:{intersection:(Y,Z,X)=>B_(Y.inner,Z.inner,X),...l1("intersection",(Y,Z,X)=>{if(Y.children.length===0)return Z;let{domain:_,proto:G,...W}=Y.inner,$=G??_,H=$?M0($,Z,X):Z;return H instanceof S?H:Y?.basis?.equals(H)?Y:Y.$.node("intersection",{...W,[H.kind]:H},{prereduced:!0})})}});class C_ extends T1{basis=this.inner.domain??this.inner.proto??null;refinements=this.children.filter((Y)=>Y.isRefinement());structure=this.inner.structure;expression=nJ(this);get shallowMorphs(){return this.inner.structure?.structuralMorph?[this.inner.structure.structuralMorph]:[]}get defaultShortDescription(){return this.basis?.defaultShortDescription??"present"}innerToJsonSchema(Y){return this.children.reduce((Z,X)=>X.isBasis()?X.toJsonSchemaRecurse(Y):X.reduceJsonSchema(Z,Y),{})}traverseAllows=(Y,Z)=>this.children.every((X)=>X.traverseAllows(Y,Z));traverseApply=(Y,Z)=>{let X=Z.currentErrorCount;if(this.basis){if(this.basis.traverseApply(Y,Z),Z.currentErrorCount>X)return}if(this.refinements.length){for(let _=0;_<this.refinements.length-1;_++)if(this.refinements[_].traverseApply(Y,Z),Z.failFast&&Z.currentErrorCount>X)return;if(this.refinements.at(-1).traverseApply(Y,Z),Z.currentErrorCount>X)return}if(this.structure){if(this.structure.traverseApply(Y,Z),Z.currentErrorCount>X)return}if(this.inner.predicate){for(let _=0;_<this.inner.predicate.length-1;_++)if(this.inner.predicate[_].traverseApply(Y,Z),Z.failFast&&Z.currentErrorCount>X)return;this.inner.predicate.at(-1).traverseApply(Y,Z)}};compile(Y){if(Y.traversalKind==="Allows"){for(let Z of this.children)Y.check(Z);Y.return(!0);return}if(Y.initializeErrorCount(),this.basis){if(Y.check(this.basis),this.children.length>1)Y.returnIfFail()}if(this.refinements.length){for(let Z=0;Z<this.refinements.length-1;Z++)Y.check(this.refinements[Z]),Y.returnIfFailFast();if(Y.check(this.refinements.at(-1)),this.structure||this.inner.predicate)Y.returnIfFail()}if(this.structure){if(Y.check(this.structure),this.inner.predicate)Y.returnIfFail()}if(this.inner.predicate){for(let Z=0;Z<this.inner.predicate.length-1;Z++)Y.check(this.inner.predicate[Z]),Y.returnIfFail();Y.check(this.inner.predicate.at(-1))}}}var iY={implementation:oJ,Node:C_},nJ=(Y)=>{let Z=Y.structure?.expression||`${Y.basis&&!Y.refinements.some((X)=>X.impl.obviatesBasisExpression)?Y.basis.nestableExpression+" ":""}${Y.refinements.map((X)=>X.expression).join(" & ")}`||"unknown";if(Z==="Array == 0")Z="[]";return Z},B_=(Y,Z,X)=>{let _={},G=Y.proto??Y.domain,W=Z.proto??Z.domain,$=G?W?M0(G,W,X):G:W;if($ instanceof S)return $;if($)_[$.kind]=$;return Z8({kind:"intersection",baseInner:_,l:X8(Y),r:X8(Z),roots:[],ctx:X})};var rJ=r({kind:"morph",hasAssociatedError:!1,keys:{in:{child:!0,parse:(Y,Z)=>Z.$.parseSchema(Y)},morphs:{parse:F4,serialize:(Y)=>Y.map((Z)=>y(Z,"root")?Z.json:K0(Z))},declaredIn:{child:!1,serialize:(Y)=>Y.json},declaredOut:{child:!1,serialize:(Y)=>Y.json}},normalize:(Y)=>Y,defaults:{description:(Y)=>`a morph from ${Y.in.description} to ${Y.out?.description??"unknown"}`},intersections:{morph:(Y,Z,X)=>{if(!Y.hasEqualMorphs(Z))return w(sJ(Y.expression,Z.expression));let _=M0(Y.in,Z.in,X);if(_ instanceof S)return _;let G={morphs:Y.morphs};if(Y.declaredIn||Z.declaredIn){let W=M0(Y.in,Z.in,X);if(W instanceof S)return W.throw();else G.declaredIn=W}if(Y.declaredOut||Z.declaredOut){let W=M0(Y.out,Z.out,X);if(W instanceof S)return W.throw();else G.declaredOut=W}return _.distribute((W)=>X.$.node("morph",{...G,in:W}),X.$.parseSchema)},...l1("morph",(Y,Z,X)=>{let _=Y.inner.in?M0(Y.inner.in,Z,X):Z;return _ instanceof S?_:_.equals(Y.inner.in)?Y:X.$.node("morph",{...Y.inner,in:_})})}});class T_ extends T1{serializedMorphs=this.morphs.map(K0);compiledMorphs=`[${this.serializedMorphs}]`;lastMorph=this.inner.morphs.at(-1);lastMorphIfNode=y(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??B.intrinsic.unknown.internal}get out(){return this.declaredOut??this.introspectableOut??B.intrinsic.unknown.internal}declareIn(Y){return this.$.node("morph",{...this.inner,declaredIn:Y})}declareOut(Y){return this.$.node("morph",{...this.inner,declaredOut:Y})}expression=`(In: ${this.in.expression}) => ${this.lastMorphIfNode?"To":"Out"}<${this.out.expression}>`;get defaultShortDescription(){return this.in.meta.description??this.in.defaultShortDescription}innerToJsonSchema(Y){return Y.fallback.morph({code:"morph",base:this.in.toJsonSchemaRecurse(Y),out:this.introspectableOut?.toJsonSchemaRecurse(Y)??null})}compile(Y){if(Y.traversalKind==="Allows"){if(!this.introspectableIn)return;Y.return(Y.invoke(this.introspectableIn));return}if(this.introspectableIn)Y.line(Y.invoke(this.introspectableIn));Y.line(`ctx.queueMorphs(${this.compiledMorphs})`)}traverseAllows=(Y,Z)=>!this.introspectableIn||this.introspectableIn.traverseAllows(Y,Z);traverseApply=(Y,Z)=>{if(this.introspectableIn)this.introspectableIn.traverseApply(Y,Z);Z.queueMorphs(this.morphs)};hasEqualMorphs(Y){return t1(this.morphs,Y.morphs,{isEqual:(Z,X)=>Z===X||y(Z,"root")&&y(X,"root")&&Z.equals(X)})}}var oY={implementation:rJ,Node:T_},sJ=(Y,Z)=>`The intersection of distinct morphs at a single path is indeterminate:
32
32
  Left: ${Y}
33
- Right: ${Z}`;var eQ=r({kind:"proto",hasAssociatedError:!0,collapsibleKey:"proto",keys:{proto:{serialize:(Y)=>h8(Y)??B1(Y)},dateAllowsInvalid:{}},normalize:(Y)=>{let Z=typeof Y==="string"?{proto:P4[Y]}:typeof Y==="function"?V0(Y)?Y:{proto:Y}:typeof Y.proto==="string"?{...Y,proto:P4[Y.proto]}:Y;if(typeof Z.proto!=="function")w(e8.writeInvalidSchemaMessage(Z.proto));if(n4(Z,"dateAllowsInvalid")&&Z.proto!==Date)w(e8.writeBadInvalidDateMessage(Z.proto));return Z},applyConfig:(Y,Z)=>{if(Y.dateAllowsInvalid===void 0&&Y.proto===Date&&Z.dateAllowsInvalid)return{...Y,dateAllowsInvalid:!0};return Y},defaults:{description:(Y)=>Y.builtinName?R_[Y.builtinName]:`an instance of ${Y.proto.name}`,actual:(Y)=>Y instanceof Date&&Y.toString()==="Invalid Date"?"an invalid Date":x8(Y)},intersections:{proto:(Y,Z)=>Y.proto===Date&&Z.proto===Date?Y.dateAllowsInvalid?Z:Y:DZ(Y.proto,Z.proto)?Y:DZ(Z.proto,Y.proto)?Z:S.init("proto",Y,Z),domain:(Y,Z)=>Z.domain==="object"?Y:S.init("domain",B.intrinsic.object.internal,Z)}});class KG extends x4{builtinName=h8(this.proto);serializedConstructor=this.json.proto;requiresInvalidDateCheck=this.proto===Date&&!this.dateAllowsInvalid;traverseAllows=this.requiresInvalidDateCheck?(Y)=>Y instanceof Date&&Y.toString()!=="Invalid Date":(Y)=>Y instanceof this.proto;compiledCondition=`data instanceof ${this.serializedConstructor}${this.requiresInvalidDateCheck?' && data.toString() !== "Invalid Date"':""}`;compiledNegation=`!(${this.compiledCondition})`;innerToJsonSchema(Y){switch(this.builtinName){case"Array":return{type:"array"};case"Date":return Y.fallback.date?.({code:"date",base:{}})??Y.fallback.proto({code:"proto",base:{},proto:this.proto});default:return Y.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 e8={implementation:eQ,Node:KG,writeBadInvalidDateMessage:(Y)=>`dateAllowsInvalid may only be specified with constructor Date (was ${Y.name})`,writeInvalidSchemaMessage:(Y)=>`instanceOf operand must be a function (was ${y0(Y)})`};var Y$=r({kind:"union",hasAssociatedError:!0,collapsibleKey:"branches",keys:{ordered:{},branches:{child:!0,parse:(Y,Z)=>{let X=[];for(let _ of Y){let G=y(_,"root")?_.branches:Z.$.parseSchema(_).branches;for(let W of G)if(W.hasKind("morph")){let H=X.findIndex((J)=>J.hasKind("morph")&&J.hasEqualMorphs(W));if(H===-1)X.push(W);else{let J=X[H];X[H]=Z.$.node("morph",{...J.inner,in:J.in.rawOr(W.in)})}}else X.push(W)}if(!Z.def.ordered)X.sort((_,G)=>_.hash<G.hash?-1:1);return X}}},normalize:(Y)=>O0(Y)?{branches:Y}:Y,reduce:(Y,Z)=>{let X=z$(Y);if(X.length===1)return X[0];if(X.length===Y.branches.length)return;return Z.node("union",{...Y,branches:X},{prereduced:!0})},defaults:{description:(Y)=>Y.distribute((Z)=>Z.description,H8),expected:(Y)=>{let Z=O_(Y.errors,"propString"),X=Object.entries(Z).map(([_,G])=>{let W=[];for(let $ of G)d1(W,$.expected);let H=H8(W),J=G.every(($)=>$.actual===G[0].actual)?G[0].actual:n(G[0].data);return`${_&&`${_} `}must be ${H}${J&&` (was ${J})`}`});return H8(X)},problem:(Y)=>Y.expected,message:(Y)=>Y.problem},intersections:{union:(Y,Z,X)=>{if(Y.isNever!==Z.isNever)return S.init("presence",Y,Z);let _;if(Y.ordered){if(Z.ordered)w(U$(Y.expression,Z.expression));if(_=oZ(Z.branches,Y.branches,X),_ instanceof S)_.invert()}else _=oZ(Y.branches,Z.branches,X);if(_ instanceof S)return _;return X.$.parseSchema(Y.ordered||Z.ordered?{branches:_,ordered:!0}:{branches:_})},...l1("union",(Y,Z,X)=>{let _=oZ(Y.branches,[Z],X);if(_ instanceof S)return _;if(_.length===1)return _[0];return X.$.parseSchema(Y.ordered?{branches:_,ordered:!0}:{branches:_})})}});class PG extends T1{isBoolean=this.branches.length===2&&this.branches[0].hasUnit(!1)&&this.branches[1].hasUnit(!0);get branchGroups(){let Y=[],Z=-1;for(let X of this.branches){if(X.hasKind("unit")&&X.domain==="boolean"){if(Z===-1)Z=Y.length,Y.push(X);else Y[Z]=B.intrinsic.boolean;continue}Y.push(X)}return Y}unitBranches=this.branches.filter((Y)=>Y.in.hasKind("unit"));discriminant=this.discriminate();discriminantJson=this.discriminant?J$(this.discriminant):null;expression=this.distribute((Y)=>Y.nestableExpression,$$);createBranchedOptimisticRootApply(){return(Y,Z)=>{let X=this.traverseOptimistic(Y);if(X!==A1)return X;let _=new f1(Y,this.$.resolvedConfig);return this.traverseApply(Y,_),_.finalize(Z)}}get shallowMorphs(){return this.branches.reduce((Y,Z)=>d1(Y,Z.shallowMorphs),[])}get defaultShortDescription(){return this.distribute((Y)=>Y.defaultShortDescription,H8)}innerToJsonSchema(Y){if(this.branchGroups.length===1&&this.branchGroups[0].equals(B.intrinsic.boolean))return{type:"boolean"};let Z=this.branchGroups.map((X)=>X.toJsonSchemaRecurse(Y));if(Z.every((X)=>Object.keys(X).length===1&&n4(X,"const")))return{enum:Z.map((X)=>X.const)};return{anyOf:Z}}traverseAllows=(Y,Z)=>this.branches.some((X)=>X.traverseAllows(Y,Z));traverseApply=(Y,Z)=>{let X=[];for(let _=0;_<this.branches.length;_++){if(Z.pushBranch(),this.branches[_].traverseApply(Y,Z),!Z.hasError()){if(this.branches[_].includesTransform)return Z.queuedMorphs.push(...Z.popBranch().queuedMorphs);return Z.popBranch()}X.push(Z.popBranch().error)}Z.errorFromNodeContext({code:"union",errors:X,meta:this.meta})};traverseOptimistic=(Y)=>{for(let Z=0;Z<this.branches.length;Z++){let X=this.branches[Z];if(X.traverseAllows(Y)){if(X.contextFreeMorph)return X.contextFreeMorph(Y);return Y}}return A1};compile(Y){if(!this.discriminant||this.unitBranches.length===this.branches.length&&this.branches.length===2)return this.compileIndiscriminable(Y);let Z=this.discriminant.optionallyChainedPropString;if(this.discriminant.kind==="domain")Z=`typeof ${Z} === "object" ? ${Z} === null ? "null" : "object" : typeof ${Z} === "function" ? "object" : typeof ${Z}`;let X=this.discriminant.cases,_=Object.keys(X),{optimistic:G}=Y;if(Y.optimistic=!1,Y.block(`switch(${Z})`,()=>{for(let Q in X){let z=X[Q],O=Q==="default"?Q:`case ${Q}`;Y.line(`${O}: return ${z===!0?G?Y.data:z:G?`${Y.invoke(z)} ? ${z.contextFreeMorph?`${K0(z.contextFreeMorph)}(${Y.data})`:Y.data} : "${A1}"`:Y.invoke(z)}`)}return Y}),Y.traversalKind==="Allows"){Y.return(G?`"${A1}"`:!1);return}let W=H8(this.discriminant.kind==="domain"?_.map((Q)=>{let z=Q.slice(1,-1);return z==="function"?z1.object:z1[z]}):_),H=this.discriminant.path.map((Q)=>typeof Q==="symbol"?K0(Q):JSON.stringify(Q)),J=JSON.stringify(W),$=this.discriminant.kind==="domain"?`${W$}[${Z}]`:`${H$}(${Z})`;Y.line(`ctx.errorFromNodeContext({
33
+ Right: ${Z}`;var aJ=r({kind:"proto",hasAssociatedError:!0,collapsibleKey:"proto",keys:{proto:{serialize:(Y)=>f8(Y)??B1(Y)},dateAllowsInvalid:{}},normalize:(Y)=>{let Z=typeof Y==="string"?{proto:P4[Y]}:typeof Y==="function"?V0(Y)?Y:{proto:Y}:typeof Y.proto==="string"?{...Y,proto:P4[Y.proto]}:Y;if(typeof Z.proto!=="function")w(Y2.writeInvalidSchemaMessage(Z.proto));if(n4(Z,"dateAllowsInvalid")&&Z.proto!==Date)w(Y2.writeBadInvalidDateMessage(Z.proto));return Z},applyConfig:(Y,Z)=>{if(Y.dateAllowsInvalid===void 0&&Y.proto===Date&&Z.dateAllowsInvalid)return{...Y,dateAllowsInvalid:!0};return Y},defaults:{description:(Y)=>Y.builtinName?RX[Y.builtinName]:`an instance of ${Y.proto.name}`,actual:(Y)=>Y instanceof Date&&Y.toString()==="Invalid Date"?"an invalid Date":h8(Y)},intersections:{proto:(Y,Z)=>Y.proto===Date&&Z.proto===Date?Y.dateAllowsInvalid?Z:Y:LY(Y.proto,Z.proto)?Y:LY(Z.proto,Y.proto)?Z:S.init("proto",Y,Z),domain:(Y,Z)=>Z.domain==="object"?Y:S.init("domain",B.intrinsic.object.internal,Z)}});class K_ extends x4{builtinName=f8(this.proto);serializedConstructor=this.json.proto;requiresInvalidDateCheck=this.proto===Date&&!this.dateAllowsInvalid;traverseAllows=this.requiresInvalidDateCheck?(Y)=>Y instanceof Date&&Y.toString()!=="Invalid Date":(Y)=>Y instanceof this.proto;compiledCondition=`data instanceof ${this.serializedConstructor}${this.requiresInvalidDateCheck?' && data.toString() !== "Invalid Date"':""}`;compiledNegation=`!(${this.compiledCondition})`;innerToJsonSchema(Y){switch(this.builtinName){case"Array":return{type:"array"};case"Date":return Y.fallback.date?.({code:"date",base:{}})??Y.fallback.proto({code:"proto",base:{},proto:this.proto});default:return Y.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 Y2={implementation:aJ,Node:K_,writeBadInvalidDateMessage:(Y)=>`dateAllowsInvalid may only be specified with constructor Date (was ${Y.name})`,writeInvalidSchemaMessage:(Y)=>`instanceOf operand must be a function (was ${y0(Y)})`};var tJ=r({kind:"union",hasAssociatedError:!0,collapsibleKey:"branches",keys:{ordered:{},branches:{child:!0,parse:(Y,Z)=>{let X=[];for(let _ of Y){let G=y(_,"root")?_.branches:Z.$.parseSchema(_).branches;for(let W of G)if(W.hasKind("morph")){let $=X.findIndex((H)=>H.hasKind("morph")&&H.hasEqualMorphs(W));if($===-1)X.push(W);else{let H=X[$];X[$]=Z.$.node("morph",{...H.inner,in:H.in.rawOr(W.in)})}}else X.push(W)}if(!Z.def.ordered)X.sort((_,G)=>_.hash<G.hash?-1:1);return X}}},normalize:(Y)=>O0(Y)?{branches:Y}:Y,reduce:(Y,Z)=>{let X=JQ(Y);if(X.length===1)return X[0];if(X.length===Y.branches.length)return;return Z.node("union",{...Y,branches:X},{prereduced:!0})},defaults:{description:(Y)=>Y.distribute((Z)=>Z.description,$8),expected:(Y)=>{let Z=OX(Y.errors,"propString"),X=Object.entries(Z).map(([_,G])=>{let W=[];for(let Q of G)d1(W,Q.expected);let $=$8(W),H=G.every((Q)=>Q.actual===G[0].actual)?G[0].actual:n(G[0].data);return`${_&&`${_} `}must be ${$}${H&&` (was ${H})`}`});return $8(X)},problem:(Y)=>Y.expected,message:(Y)=>Y.problem},intersections:{union:(Y,Z,X)=>{if(Y.isNever!==Z.isNever)return S.init("presence",Y,Z);let _;if(Y.ordered){if(Z.ordered)w(zQ(Y.expression,Z.expression));if(_=nY(Z.branches,Y.branches,X),_ instanceof S)_.invert()}else _=nY(Y.branches,Z.branches,X);if(_ instanceof S)return _;return X.$.parseSchema(Y.ordered||Z.ordered?{branches:_,ordered:!0}:{branches:_})},...l1("union",(Y,Z,X)=>{let _=nY(Y.branches,[Z],X);if(_ instanceof S)return _;if(_.length===1)return _[0];return X.$.parseSchema(Y.ordered?{branches:_,ordered:!0}:{branches:_})})}});class P_ extends T1{isBoolean=this.branches.length===2&&this.branches[0].hasUnit(!1)&&this.branches[1].hasUnit(!0);get branchGroups(){let Y=[],Z=-1;for(let X of this.branches){if(X.hasKind("unit")&&X.domain==="boolean"){if(Z===-1)Z=Y.length,Y.push(X);else Y[Z]=B.intrinsic.boolean;continue}Y.push(X)}return Y}unitBranches=this.branches.filter((Y)=>Y.in.hasKind("unit"));discriminant=this.discriminate();discriminantJson=this.discriminant?WQ(this.discriminant):null;expression=this.distribute((Y)=>Y.nestableExpression,HQ);createBranchedOptimisticRootApply(){return(Y,Z)=>{let X=this.traverseOptimistic(Y);if(X!==A1)return X;let _=new f1(Y,this.$.resolvedConfig);return this.traverseApply(Y,_),_.finalize(Z)}}get shallowMorphs(){return this.branches.reduce((Y,Z)=>d1(Y,Z.shallowMorphs),[])}get defaultShortDescription(){return this.distribute((Y)=>Y.defaultShortDescription,$8)}innerToJsonSchema(Y){if(this.branchGroups.length===1&&this.branchGroups[0].equals(B.intrinsic.boolean))return{type:"boolean"};let Z=this.branchGroups.map((X)=>X.toJsonSchemaRecurse(Y));if(Z.every((X)=>Object.keys(X).length===1&&n4(X,"const")))return{enum:Z.map((X)=>X.const)};return{anyOf:Z}}traverseAllows=(Y,Z)=>this.branches.some((X)=>X.traverseAllows(Y,Z));traverseApply=(Y,Z)=>{let X=[];for(let _=0;_<this.branches.length;_++){if(Z.pushBranch(),this.branches[_].traverseApply(Y,Z),!Z.hasError()){if(this.branches[_].includesTransform)return Z.queuedMorphs.push(...Z.popBranch().queuedMorphs);return Z.popBranch()}X.push(Z.popBranch().error)}Z.errorFromNodeContext({code:"union",errors:X,meta:this.meta})};traverseOptimistic=(Y)=>{for(let Z=0;Z<this.branches.length;Z++){let X=this.branches[Z];if(X.traverseAllows(Y)){if(X.contextFreeMorph)return X.contextFreeMorph(Y);return Y}}return A1};compile(Y){if(!this.discriminant||this.unitBranches.length===this.branches.length&&this.branches.length===2)return this.compileIndiscriminable(Y);let Z=this.discriminant.optionallyChainedPropString;if(this.discriminant.kind==="domain")Z=`typeof ${Z} === "object" ? ${Z} === null ? "null" : "object" : typeof ${Z} === "function" ? "object" : typeof ${Z}`;let X=this.discriminant.cases,_=Object.keys(X),{optimistic:G}=Y;if(Y.optimistic=!1,Y.block(`switch(${Z})`,()=>{for(let J in X){let z=X[J],O=J==="default"?J:`case ${J}`;Y.line(`${O}: return ${z===!0?G?Y.data:z:G?`${Y.invoke(z)} ? ${z.contextFreeMorph?`${K0(z.contextFreeMorph)}(${Y.data})`:Y.data} : "${A1}"`:Y.invoke(z)}`)}return Y}),Y.traversalKind==="Allows"){Y.return(G?`"${A1}"`:!1);return}let W=$8(this.discriminant.kind==="domain"?_.map((J)=>{let z=J.slice(1,-1);return z==="function"?z1.object:z1[z]}):_),$=this.discriminant.path.map((J)=>typeof J==="symbol"?K0(J):JSON.stringify(J)),H=JSON.stringify(W),Q=this.discriminant.kind==="domain"?`${_Q}[${Z}]`:`${GQ}(${Z})`;Y.line(`ctx.errorFromNodeContext({
34
34
  code: "predicate",
35
- expected: ${J},
36
- actual: ${$},
37
- relativePath: [${H}],
35
+ expected: ${H},
36
+ actual: ${Q},
37
+ relativePath: [${$}],
38
38
  meta: ${this.compiledMeta}
39
- })`)}compileIndiscriminable(Y){if(Y.traversalKind==="Apply"){Y.const("errors","[]");for(let Z of this.branches)Y.line("ctx.pushBranch()").line(Y.invoke(Z)).if("!ctx.hasError()",()=>Y.return(Z.includesTransform?"ctx.queuedMorphs.push(...ctx.popBranch().queuedMorphs)":"ctx.popBranch()")).line("errors.push(ctx.popBranch().error)");Y.line(`ctx.errorFromNodeContext({ code: "union", errors, meta: ${this.compiledMeta} })`)}else{let{optimistic:Z}=Y;Y.optimistic=!1;for(let X of this.branches)Y.if(`${Y.invoke(X)}`,()=>Y.return(Z?X.contextFreeMorph?`${K0(X.contextFreeMorph)}(${Y.data})`:Y.data:!0));Y.return(Z?`"${A1}"`:!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 G=o(this.unitBranches,(W,H)=>[`${H.in.serializedValue}`,H.hasKind("morph")?H:!0]);return{kind:"unit",path:[],optionallyChainedPropString:"data",cases:G}}let Y=[];for(let G=0;G<this.branches.length-1;G++){let W=this.branches[G];for(let H=G+1;H<this.branches.length;H++){let J=this.branches[H],$=O1(W.in,J.in,W.$);if(!($ instanceof S))continue;for(let Q of $){if(!Q.kind||Q.optional)continue;let z,O;if(Q.kind==="domain"){let{l:V,r:R}=Q;z=`"${typeof V==="string"?V:V.domain}"`,O=`"${typeof R==="string"?R:R.domain}"`}else if(Q.kind==="unit")z=Q.l.serializedValue,O=Q.r.serializedValue;else continue;let D=Y.find((V)=>t1(V.path,Q.path)&&V.kind===Q.kind);if(!D)Y.push({kind:Q.kind,cases:{[z]:{branchIndices:[G],condition:Q.l},[O]:{branchIndices:[H],condition:Q.r}},path:Q.path});else{if(D.cases[z])D.cases[z].branchIndices=d1(D.cases[z].branchIndices,G);else D.cases[z]??={branchIndices:[G],condition:Q.l};if(D.cases[O])D.cases[O].branchIndices=d1(D.cases[O].branchIndices,H);else D.cases[O]??={branchIndices:[H],condition:Q.r}}}}}let Z=this.ordered?_$(Y,this.branches):Y;if(!Z.length)return null;let X=Z$(Z,this),_={};for(let G in X.best.cases){let W=X$(X,G);if(W===null){_[G]=!0;continue}if(W.length===this.branches.length)return null;if(this.ordered)W.sort(($,Q)=>$.originalIndex-Q.originalIndex);let H=W.map(($)=>$.branch),J=H.length===1?H[0]:this.$.node("union",this.ordered?{branches:H,ordered:!0}:H);Object.assign(this.referencesById,J.referencesById),_[G]=J}if(X.defaultEntries.length){let G=X.defaultEntries.map((W)=>W.branch);_.default=this.$.node("union",this.ordered?{branches:G,ordered:!0}:G,{prereduced:!0}),Object.assign(this.referencesById,_.default.referencesById)}return Object.assign(X.location,{cases:_})}}var Z$=(Y,Z)=>{let X=Y.sort((W,H)=>Object.keys(H.cases).length-Object.keys(W.cases).length)[0],_={kind:X.kind,path:X.path,optionallyChainedPropString:SG(X.path)},G=Z.branches.map((W,H)=>({originalIndex:H,branch:W}));return{best:X,location:_,defaultEntries:G,node:Z}},X$=(Y,Z)=>{let X=Y.best.cases[Z],_=G$(X.condition,Y.location.path,Y.node.$),G=[],W=[];for(let H=0;H<Y.defaultEntries.length;H++){let J=Y.defaultEntries[H];if(X.branchIndices.includes(J.originalIndex)){let $=qG(Y.node.branches[J.originalIndex],Y.location);if($===null)G=null;else G?.push({originalIndex:J.originalIndex,branch:$})}else if(J.branch.hasKind("alias")&&_.hasKind("domain")&&_.domain==="object")G?.push(J);else{if(J.branch.in.overlaps(_)){let $=qG(J.branch,Y.location);G?.push({originalIndex:J.originalIndex,branch:$})}W.push(J)}}return Y.defaultEntries=W,G},_$=(Y,Z)=>{return Y.filter((_)=>{let G=Object.values(_.cases).map((W)=>W.branchIndices);for(let W=0;W<G.length-1;W++){let H=G[W];for(let J=W+1;J<G.length;J++){let $=G[J];for(let Q of H)for(let z of $)if(Q>z){if(Z[Q].overlaps(Z[z]))return!1}}}return!0})},G$=(Y,Z,X)=>{let _=Y==="undefined"?X.node("unit",{unit:void 0}):Y==="null"?X.node("unit",{unit:null}):Y==="boolean"?X.units([!0,!1]):Y;for(let G=Z.length-1;G>=0;G--){let W=Z[G];_=X.node("intersection",typeof W==="number"?{proto:"Array",sequence:[...F_(W).map((H)=>({})),_]}:{domain:"object",required:[{key:W,value:_}]})}return _},SG=(Y)=>Y.reduce((Z,X)=>Z+NZ(X,!0),"data"),W$=K0(E_),H$=K0(n),nZ={implementation:Y$,Node:PG},J$=(Y)=>({kind:Y.kind,path:Y.path.map((Z)=>typeof Z==="string"?Z:Z4(Z)),cases:o(Y.cases,(Z,X)=>[Z,X===!0?X:X.hasKind("union")&&X.discriminantJson?X.discriminantJson:X.json])}),Q$={delimiter:" | ",finalDelimiter:" | "},$$=(Y)=>H8(Y,Q$),H8=(Y,Z)=>{let X=Z?.delimiter??", ",_=Z?.finalDelimiter??" or ";if(Y.length===0)return"never";if(Y.length===1)return Y[0];if(Y.length===2&&Y[0]==="false"&&Y[1]==="true"||Y[0]==="true"&&Y[1]==="false")return"boolean";let G={},W=Y.filter((J)=>G[J]?!1:G[J]=!0),H=W.pop();return`${W.join(X)}${W.length?_:""}${H}`},oZ=(Y,Z,X)=>{let _=Z.map(()=>[]);for(let W=0;W<Y.length;W++){let H={};for(let J=0;J<Z.length;J++){if(_[J]===null)continue;if(Y[W].equals(Z[J])){_[J]=null,H={};break}let $=M0(Y[W],Z[J],X);if($ instanceof S)continue;if($.equals(Y[W])){_[J].push(Y[W]),H={};break}if($.equals(Z[J]))_[J]=null;else H[J]=$}for(let J in H)_[J][W]=H[J]}let G=_.flatMap((W,H)=>W?.flatMap((J)=>J.branches)??Z[H]);return G.length===0?S.init("union",Y,Z):G},z$=({branches:Y,ordered:Z})=>{if(Y.length<2)return Y;let X=Y.map(()=>!0);for(let _=0;_<Y.length;_++)for(let G=_+1;G<Y.length&&X[_]&&X[G];G++){if(Y[_].equals(Y[G])){X[G]=!1;continue}let W=O1(Y[_].in,Y[G].in,Y[0].$);if(W instanceof S)continue;if(!Z)F$(Y[_],Y[G]);if(W.equals(Y[_].in))X[_]=!!Z;else if(W.equals(Y[G].in))X[G]=!1}return Y.filter((_,G)=>X[G])},F$=(Y,Z)=>{if(!Y.includesTransform&&!Z.includesTransform)return;if(!t1(Y.shallowMorphs,Z.shallowMorphs))w(jG(Y.expression,Z.expression));if(!t1(Y.flatMorphs,Z.flatMorphs,{isEqual:(X,_)=>X.propString===_.propString&&(X.node.hasKind("morph")&&_.node.hasKind("morph")?X.node.hasEqualMorphs(_.node):X.node.hasKind("intersection")&&_.node.hasKind("intersection")?X.node.structure?.structuralMorphRef===_.node.structure?.structuralMorphRef:!1)}))w(jG(Y.expression,Z.expression))},qG=(Y,Z)=>Y.transform((X,_)=>{if(X==="domain"||X==="unit")return null;return _},{shouldTransform:(X,_)=>{let G=SG(_.path);if(!Z.optionallyChainedPropString.startsWith(G))return!1;if(X.hasKind("domain")&&X.domain==="object")return!0;if((X.hasKind("domain")||Z.kind==="unit")&&G===Z.optionallyChainedPropString)return!0;return X.children.length!==0&&X.kind!=="index"}}),jG=(Y,Z)=>`An unordered union of a type including a morph and a type with overlapping input is indeterminate:
39
+ })`)}compileIndiscriminable(Y){if(Y.traversalKind==="Apply"){Y.const("errors","[]");for(let Z of this.branches)Y.line("ctx.pushBranch()").line(Y.invoke(Z)).if("!ctx.hasError()",()=>Y.return(Z.includesTransform?"ctx.queuedMorphs.push(...ctx.popBranch().queuedMorphs)":"ctx.popBranch()")).line("errors.push(ctx.popBranch().error)");Y.line(`ctx.errorFromNodeContext({ code: "union", errors, meta: ${this.compiledMeta} })`)}else{let{optimistic:Z}=Y;Y.optimistic=!1;for(let X of this.branches)Y.if(`${Y.invoke(X)}`,()=>Y.return(Z?X.contextFreeMorph?`${K0(X.contextFreeMorph)}(${Y.data})`:Y.data:!0));Y.return(Z?`"${A1}"`:!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 G=o(this.unitBranches,(W,$)=>[`${$.in.serializedValue}`,$.hasKind("morph")?$:!0]);return{kind:"unit",path:[],optionallyChainedPropString:"data",cases:G}}let Y=[];for(let G=0;G<this.branches.length-1;G++){let W=this.branches[G];for(let $=G+1;$<this.branches.length;$++){let H=this.branches[$],Q=O1(W.in,H.in,W.$);if(!(Q instanceof S))continue;for(let J of Q){if(!J.kind||J.optional)continue;let z,O;if(J.kind==="domain"){let{l:V,r:R}=J;z=`"${typeof V==="string"?V:V.domain}"`,O=`"${typeof R==="string"?R:R.domain}"`}else if(J.kind==="unit")z=J.l.serializedValue,O=J.r.serializedValue;else continue;let D=Y.find((V)=>t1(V.path,J.path)&&V.kind===J.kind);if(!D)Y.push({kind:J.kind,cases:{[z]:{branchIndices:[G],condition:J.l},[O]:{branchIndices:[$],condition:J.r}},path:J.path});else{if(D.cases[z])D.cases[z].branchIndices=d1(D.cases[z].branchIndices,G);else D.cases[z]??={branchIndices:[G],condition:J.l};if(D.cases[O])D.cases[O].branchIndices=d1(D.cases[O].branchIndices,$);else D.cases[O]??={branchIndices:[$],condition:J.r}}}}}let Z=this.ordered?ZQ(Y,this.branches):Y;if(!Z.length)return null;let X=eJ(Z,this),_={};for(let G in X.best.cases){let W=YQ(X,G);if(W===null){_[G]=!0;continue}if(W.length===this.branches.length)return null;if(this.ordered)W.sort((Q,J)=>Q.originalIndex-J.originalIndex);let $=W.map((Q)=>Q.branch),H=$.length===1?$[0]:this.$.node("union",this.ordered?{branches:$,ordered:!0}:$);Object.assign(this.referencesById,H.referencesById),_[G]=H}if(X.defaultEntries.length){let G=X.defaultEntries.map((W)=>W.branch);_.default=this.$.node("union",this.ordered?{branches:G,ordered:!0}:G,{prereduced:!0}),Object.assign(this.referencesById,_.default.referencesById)}return Object.assign(X.location,{cases:_})}}var eJ=(Y,Z)=>{let X=Y.sort((W,$)=>Object.keys($.cases).length-Object.keys(W.cases).length)[0],_={kind:X.kind,path:X.path,optionallyChainedPropString:S_(X.path)},G=Z.branches.map((W,$)=>({originalIndex:$,branch:W}));return{best:X,location:_,defaultEntries:G,node:Z}},YQ=(Y,Z)=>{let X=Y.best.cases[Z],_=XQ(X.condition,Y.location.path,Y.node.$),G=[],W=[];for(let $=0;$<Y.defaultEntries.length;$++){let H=Y.defaultEntries[$];if(X.branchIndices.includes(H.originalIndex)){let Q=q_(Y.node.branches[H.originalIndex],Y.location);if(Q===null)G=null;else G?.push({originalIndex:H.originalIndex,branch:Q})}else if(H.branch.hasKind("alias")&&_.hasKind("domain")&&_.domain==="object")G?.push(H);else{if(H.branch.in.overlaps(_)){let Q=q_(H.branch,Y.location);G?.push({originalIndex:H.originalIndex,branch:Q})}W.push(H)}}return Y.defaultEntries=W,G},ZQ=(Y,Z)=>{return Y.filter((_)=>{let G=Object.values(_.cases).map((W)=>W.branchIndices);for(let W=0;W<G.length-1;W++){let $=G[W];for(let H=W+1;H<G.length;H++){let Q=G[H];for(let J of $)for(let z of Q)if(J>z){if(Z[J].overlaps(Z[z]))return!1}}}return!0})},XQ=(Y,Z,X)=>{let _=Y==="undefined"?X.node("unit",{unit:void 0}):Y==="null"?X.node("unit",{unit:null}):Y==="boolean"?X.units([!0,!1]):Y;for(let G=Z.length-1;G>=0;G--){let W=Z[G];_=X.node("intersection",typeof W==="number"?{proto:"Array",sequence:[...UX(W).map(($)=>({})),_]}:{domain:"object",required:[{key:W,value:_}]})}return _},S_=(Y)=>Y.reduce((Z,X)=>Z+IY(X,!0),"data"),_Q=K0(EX),GQ=K0(n),rY={implementation:tJ,Node:P_},WQ=(Y)=>({kind:Y.kind,path:Y.path.map((Z)=>typeof Z==="string"?Z:Z4(Z)),cases:o(Y.cases,(Z,X)=>[Z,X===!0?X:X.hasKind("union")&&X.discriminantJson?X.discriminantJson:X.json])}),$Q={delimiter:" | ",finalDelimiter:" | "},HQ=(Y)=>$8(Y,$Q),$8=(Y,Z)=>{let X=Z?.delimiter??", ",_=Z?.finalDelimiter??" or ";if(Y.length===0)return"never";if(Y.length===1)return Y[0];if(Y.length===2&&Y[0]==="false"&&Y[1]==="true"||Y[0]==="true"&&Y[1]==="false")return"boolean";let G={},W=Y.filter((H)=>G[H]?!1:G[H]=!0),$=W.pop();return`${W.join(X)}${W.length?_:""}${$}`},nY=(Y,Z,X)=>{let _=Z.map(()=>[]);for(let W=0;W<Y.length;W++){let $={};for(let H=0;H<Z.length;H++){if(_[H]===null)continue;if(Y[W].equals(Z[H])){_[H]=null,$={};break}let Q=M0(Y[W],Z[H],X);if(Q instanceof S)continue;if(Q.equals(Y[W])){_[H].push(Y[W]),$={};break}if(Q.equals(Z[H]))_[H]=null;else $[H]=Q}for(let H in $)_[H][W]=$[H]}let G=_.flatMap((W,$)=>W?.flatMap((H)=>H.branches)??Z[$]);return G.length===0?S.init("union",Y,Z):G},JQ=({branches:Y,ordered:Z})=>{if(Y.length<2)return Y;let X=Y.map(()=>!0);for(let _=0;_<Y.length;_++)for(let G=_+1;G<Y.length&&X[_]&&X[G];G++){if(Y[_].equals(Y[G])){X[G]=!1;continue}let W=O1(Y[_].in,Y[G].in,Y[0].$);if(W instanceof S)continue;if(!Z)QQ(Y[_],Y[G]);if(W.equals(Y[_].in))X[_]=!!Z;else if(W.equals(Y[G].in))X[G]=!1}return Y.filter((_,G)=>X[G])},QQ=(Y,Z)=>{if(!Y.includesTransform&&!Z.includesTransform)return;if(!t1(Y.shallowMorphs,Z.shallowMorphs))w(j_(Y.expression,Z.expression));if(!t1(Y.flatMorphs,Z.flatMorphs,{isEqual:(X,_)=>X.propString===_.propString&&(X.node.hasKind("morph")&&_.node.hasKind("morph")?X.node.hasEqualMorphs(_.node):X.node.hasKind("intersection")&&_.node.hasKind("intersection")?X.node.structure?.structuralMorphRef===_.node.structure?.structuralMorphRef:!1)}))w(j_(Y.expression,Z.expression))},q_=(Y,Z)=>Y.transform((X,_)=>{if(X==="domain"||X==="unit")return null;return _},{shouldTransform:(X,_)=>{let G=S_(_.path);if(!Z.optionallyChainedPropString.startsWith(G))return!1;if(X.hasKind("domain")&&X.domain==="object")return!0;if((X.hasKind("domain")||Z.kind==="unit")&&G===Z.optionallyChainedPropString)return!0;return X.children.length!==0&&X.kind!=="index"}}),j_=(Y,Z)=>`An unordered union of a type including a morph and a type with overlapping input is indeterminate:
40
40
  Left: ${Y}
41
- Right: ${Z}`,U$=(Y,Z)=>`The intersection of two ordered unions is indeterminate:
41
+ Right: ${Z}`,zQ=(Y,Z)=>`The intersection of two ordered unions is indeterminate:
42
42
  Left: ${Y}
43
- Right: ${Z}`;var O$=r({kind:"unit",hasAssociatedError:!0,keys:{unit:{preserveUndefined:!0,serialize:(Y)=>Y instanceof Date?Y.toISOString():B1(Y)}},normalize:(Y)=>Y,defaults:{description:(Y)=>n(Y.unit),problem:({expected:Y,actual:Z})=>`${Y===Z?`must be reference equal to ${Y} (serialized to the same value)`:`must be ${Y} (was ${Z})`}`},intersections:{unit:(Y,Z)=>S.init("unit",Y,Z),...l1("unit",(Y,Z)=>{if(Z.allows(Y.unit))return Y;let X=Z.hasKind("intersection")?Z.basis:Z;if(X){let _=X.hasKind("domain")?X:B.intrinsic.object;if(Y.domain!==_.domain){let G=Y.domain==="undefined"||Y.domain==="null"||Y.domain==="boolean"?Y.domain:B.intrinsic[Y.domain];return S.init("domain",G,_)}}return S.init("assignability",Y,Z.hasKind("intersection")?Z.children.find((_)=>!_.allows(Y.unit)):Z)})}});class xG extends x4{compiledValue=this.json.unit;serializedValue=typeof this.unit==="string"||this.unit instanceof Date?JSON.stringify(this.compiledValue):`${this.compiledValue}`;compiledCondition=vG(this.unit,this.serializedValue);compiledNegation=vG(this.unit,this.serializedValue,"negated");expression=n(this.unit);domain=y0(this.unit);get defaultShortDescription(){return this.domain==="object"?z1.object:this.description}innerToJsonSchema(Y){return this.unit===null?{type:"null"}:B.intrinsic.jsonPrimitive.allows(this.unit)?{const:this.unit}:Y.fallback.unit({code:"unit",base:{},unit:this.unit})}traverseAllows=this.unit instanceof Date?(Y)=>Y instanceof Date&&Y.toISOString()===this.compiledValue:Number.isNaN(this.unit)?(Y)=>Number.isNaN(Y):(Y)=>Y===this.unit}var rZ={implementation:O$,Node:xG},vG=(Y,Z,X)=>{if(Y instanceof Date){let _=`data instanceof Date && data.toISOString() === ${Z}`;return X?`!(${_})`:_}if(Number.isNaN(Y))return`${X?"!":""}Number.isNaN(data)`;return`data ${X?"!":"="}== ${Z}`};var E$=r({kind:"index",hasAssociatedError:!1,intersectionIsOpen:!0,keys:{signature:{child:!0,parse:(Y,Z)=>{let X=Z.$.parseSchema(Y);if(!X.extends(B.intrinsic.key))return w(L$(X.expression));let _=X.branches.filter((G)=>G.hasKind("unit"));if(_.length)return w(D$(_.map((G)=>n(G.unit))));return X}},value:{child:!0,parse:(Y,Z)=>Z.$.parseSchema(Y)}},normalize:(Y)=>Y,defaults:{description:(Y)=>`[${Y.signature.expression}]: ${Y.value.description}`},intersections:{index:(Y,Z,X)=>{if(Y.signature.equals(Z.signature)){let _=M0(Y.value,Z.value,X),G=_ instanceof S?B.intrinsic.never.internal:_;return X.$.node("index",{signature:Y.signature,value:G})}if(Y.signature.extends(Z.signature)&&Y.value.subsumes(Z.value))return Z;if(Z.signature.extends(Y.signature)&&Z.value.subsumes(Y.value))return Y;return null}}});class hG extends C1{impliedBasis=B.intrinsic.object.internal;expression=`[${this.signature.expression}]: ${this.value.expression}`;flatRefs=Z0(this.value.flatRefs.map((Y)=>b1([this.signature,...Y.path],Y.node)),b1([this.signature],this.value));traverseAllows=(Y,Z)=>j4(Y).every((X)=>{if(this.signature.traverseAllows(X[0],Z))return U1(X[0],()=>this.value.traverseAllows(X[1],Z),Z);return!0});traverseApply=(Y,Z)=>{for(let X of j4(Y))if(this.signature.traverseAllows(X[0],Z))U1(X[0],()=>this.value.traverseApply(X[1],Z),Z)};_transform(Y,Z){Z.path.push(this.signature);let X=super._transform(Y,Z);return Z.path.pop(),X}compile(){}}var sZ={implementation:E$,Node:hG},D$=(Y)=>`Index keys ${Y.join(", ")} should be specified as named props.`,L$=(Y)=>`Indexed key definition '${Y}' must be a string or symbol`;var V$=r({kind:"required",hasAssociatedError:!0,intersectionIsOpen:!0,keys:{key:{},value:{child:!0,parse:(Y,Z)=>Z.$.parseSchema(Y)}},normalize:(Y)=>Y,defaults:{description:(Y)=>`${Y.compiledKey}: ${Y.value.description}`,expected:(Y)=>Y.missingValueDescription,actual:()=>"missing"},intersections:{required:o8,optional:o8}});class fG extends n8{expression=`${this.compiledKey}: ${this.value.expression}`;errorContext=Object.freeze({code:"required",missingValueDescription:this.value.defaultShortDescription,relativePath:[this.key],meta:this.meta});compiledErrorContext=L4(this.errorContext)}var aZ={implementation:V$,Node:fG};var M$=r({kind:"sequence",hasAssociatedError:!1,collapsibleKey:"variadic",keys:{prefix:{child:!0,parse:(Y,Z)=>{if(Y.length===0)return;return Y.map((X)=>Z.$.parseSchema(X))}},optionals:{child:!0,parse:(Y,Z)=>{if(Y.length===0)return;return Y.map((X)=>Z.$.parseSchema(X))}},defaultables:{child:(Y)=>Y.map((Z)=>Z[0]),parse:(Y,Z)=>{if(Y.length===0)return;return Y.map((X)=>{let _=Z.$.parseSchema(X[0]);return s8(_,X[1],null),[_,X[1]]})},serialize:(Y)=>Y.map((Z)=>[Z[0].collapsibleJson,B1(Z[1])])},variadic:{child:!0,parse:(Y,Z)=>Z.$.parseSchema(Y,Z)},minVariadicLength:{parse:(Y)=>Y===0?void 0:Y},postfix:{child:!0,parse:(Y,Z)=>{if(Y.length===0)return;return Y.map((X)=>Z.$.parseSchema(X))}}},normalize:(Y)=>{if(typeof Y==="string")return{variadic:Y};if("variadic"in Y||"prefix"in Y||"defaultables"in Y||"optionals"in Y||"postfix"in Y||"minVariadicLength"in Y){if(Y.postfix?.length){if(!Y.variadic)return w(N$);if(Y.optionals?.length||Y.defaultables?.length)return w(eZ)}if(Y.minVariadicLength&&!Y.variadic)return w("minVariadicLength may not be specified without a variadic element");return Y}return{variadic:Y}},reduce:(Y,Z)=>{let X=Y.minVariadicLength??0,_=Y.prefix?.slice()??[],G=Y.defaultables?.slice()??[],W=Y.optionals?.slice()??[],H=Y.postfix?.slice()??[];if(Y.variadic){while(W.at(-1)?.equals(Y.variadic))W.pop();if(W.length===0&&G.length===0)while(_.at(-1)?.equals(Y.variadic))_.pop(),X++;while(H[0]?.equals(Y.variadic))H.shift(),X++}else if(W.length===0&&G.length===0)_.push(...H.splice(0));if(X!==Y.minVariadicLength||Y.prefix&&Y.prefix.length!==_.length)return Z.node("sequence",{...Y,prefix:_,defaultables:G,optionals:W,postfix:H,minVariadicLength:X},{prereduced:!0})},defaults:{description:(Y)=>{if(Y.isVariadicOnly)return`${Y.variadic.nestableExpression}[]`;return`[${Y.tuple.map((X)=>X.kind==="defaultables"?`${X.node.nestableExpression} = ${n(X.default)}`:X.kind==="optionals"?`${X.node.nestableExpression}?`:X.kind==="variadic"?`...${X.node.nestableExpression}[]`:X.node.expression).join(", ")}]`}},intersections:{sequence:(Y,Z,X)=>{let _=Y6({l:Y.tuple,r:Z.tuple,disjoint:new S,result:[],fixedVariants:[],ctx:X}),G=_.disjoint.length===0?[_,..._.fixedVariants]:_.fixedVariants;return G.length===0?_.disjoint:G.length===1?X.$.node("sequence",bG(G[0].result)):X.$.node("union",G.map((W)=>({proto:Array,sequence:bG(W.result)})))}}});class kG extends C1{impliedBasis=B.intrinsic.Array.internal;tuple=R$(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((Y)=>{if(Y.kind==="defaultables"||Y.kind==="optionals")return this.defaultablesAndOptionals.push(Y.node),!0;return Y.kind==="prefix"});variadicOrPostfix=a1(this.variadic&&[this.variadic],this.postfix);flatRefs=this.addFlatRefs();addFlatRefs(){return TZ(this.flatRefs,this.prevariadic.flatMap((Y,Z)=>Z0(Y.node.flatRefs.map((X)=>b1([`${Z}`,...X.path],X.node)),b1([`${Z}`],Y.node)))),TZ(this.flatRefs,this.variadicOrPostfix.flatMap((Y)=>Z0(Y.flatRefs.map((Z)=>b1([B.intrinsic.nonNegativeIntegerString.internal,...Z.path],Z.node)),b1([B.intrinsic.nonNegativeIntegerString.internal],Y)))),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=w$(this);defaultValueMorphsReference=this.defaultValueMorphs.length?K0(this.defaultValueMorphs):void 0;elementAtIndex(Y,Z){if(Z<this.prevariadic.length)return this.tuple[Z];let X=Y.length-this.postfixLength;if(Z>=X)return{kind:"postfix",node:this.postfix[Z-X]};return{kind:"variadic",node:this.variadic??_0(`Unexpected attempt to access index ${Z} on ${this}`)}}traverseAllows=(Y,Z)=>{for(let X=0;X<Y.length;X++)if(!this.elementAtIndex(Y,X).node.traverseAllows(Y[X],Z))return!1;return!0};traverseApply=(Y,Z)=>{let X=0;for(;X<Y.length;X++)U1(X,()=>this.elementAtIndex(Y,X).node.traverseApply(Y[X],Z),Z)};get element(){return this.cacheGetter("element",this.$.node("union",this.children))}compile(Y){if(this.prefix)for(let[Z,X]of this.prefix.entries())Y.traverseKey(`${Z}`,`data[${Z}]`,X);for(let[Z,X]of this.defaultablesAndOptionals.entries()){let _=`${Z+this.prefixLength}`;Y.if(`${_} >= ${Y.data}.length`,()=>Y.traversalKind==="Allows"?Y.return(!0):Y.return()),Y.traverseKey(_,`data[${_}]`,X)}if(this.variadic){if(this.postfix)Y.const("firstPostfixIndex",`${Y.data}.length${this.postfix?`- ${this.postfix.length}`:""}`);if(Y.for(`i < ${this.postfix?"firstPostfixIndex":"data.length"}`,()=>Y.traverseKey("i","data[i]",this.variadic),this.prevariadic.length),this.postfix)for(let[Z,X]of this.postfix.entries()){let _=`firstPostfixIndex + ${Z}`;Y.traverseKey(_,`data[${_}]`,X)}}if(Y.traversalKind==="Allows")Y.return(!0)}_transform(Y,Z){Z.path.push(B.intrinsic.nonNegativeIntegerString.internal);let X=super._transform(Y,Z);return Z.path.pop(),X}expression=this.description;reduceJsonSchema(Y,Z){if(this.prevariadic.length)Y.prefixItems=this.prevariadic.map((X)=>{let _=X.node.toJsonSchemaRecurse(Z);if(X.kind==="defaultables"){let G=typeof X.default==="function"?X.default():X.default;_.default=B.intrinsic.jsonData.allows(G)?G:Z.fallback.defaultValue({code:"defaultValue",base:_,value:G})}return _});if(this.minLength)Y.minItems=this.minLength;if(this.variadic){let X=Object.assign(Y,{items:this.variadic.toJsonSchemaRecurse(Z)});if(this.maxLength)X.maxItems=this.maxLength;if(this.postfix){let _=this.postfix.map((G)=>G.toJsonSchemaRecurse(Z));Y=Z.fallback.arrayPostfix({code:"arrayPostfix",base:X,elements:_})}}else Y.items=!1,delete Y.maxItems;return Y}}var A$={},w$=(Y)=>{if(!Y.defaultables)return[];let Z=[],X="[",_=Y.prefixLength+Y.defaultablesLength-1;for(let G=Y.prefixLength;G<=_;G++){let[W,H]=Y.defaultables[G-Y.prefixLength];Z.push(cZ(G,W,H)),X+=`${G}: ${W.id} = ${B1(H)}, `}return X+="]",A$[X]??=Z},tZ={implementation:M$,Node:kG},R$=(Y)=>{let Z=[];if(Y.prefix)for(let X of Y.prefix)Z.push({kind:"prefix",node:X});if(Y.defaultables)for(let[X,_]of Y.defaultables)Z.push({kind:"defaultables",node:X,default:_});if(Y.optionals)for(let X of Y.optionals)Z.push({kind:"optionals",node:X});if(Y.variadic)Z.push({kind:"variadic",node:Y.variadic});if(Y.postfix)for(let X of Y.postfix)Z.push({kind:"postfix",node:X});return Z},bG=(Y)=>Y.reduce((Z,X)=>{if(X.kind==="variadic")Z.variadic=X.node;else if(X.kind==="defaultables")Z.defaultables=Z0(Z.defaultables,[[X.node,X.default]]);else Z[X.kind]=Z0(Z[X.kind],X.node);return Z},{}),eZ="A postfix required element cannot follow an optional or defaultable element",N$="A postfix element requires a variadic element",Y6=(Y)=>{let[Z,...X]=Y.l,[_,...G]=Y.r;if(!Z||!_)return Y;let W=X.at(-1)?.kind==="postfix",H=G.at(-1)?.kind==="postfix",J=Z.kind==="prefix"||_.kind==="prefix"?"prefix":Z.kind==="postfix"||_.kind==="postfix"?"postfix":Z.kind==="variadic"&&_.kind==="variadic"?"variadic":W||H?"prefix":Z.kind==="defaultables"||_.kind==="defaultables"?"defaultables":"optionals";if(Z.kind==="prefix"&&_.kind==="variadic"&&H){let O=Y6({...Y,fixedVariants:[],r:G.map((D)=>({...D,kind:"prefix"}))});if(O.disjoint.length===0)Y.fixedVariants.push(O)}else if(_.kind==="prefix"&&Z.kind==="variadic"&&W){let O=Y6({...Y,fixedVariants:[],l:X.map((D)=>({...D,kind:"prefix"}))});if(O.disjoint.length===0)Y.fixedVariants.push(O)}let $=M0(Z.node,_.node,Y.ctx);if($ instanceof S)if(J==="prefix"||J==="postfix")Y.disjoint.push(...$.withPrefixKey(J==="prefix"?Y.result.length:`-${X.length+1}`,"required")),Y.result=[...Y.result,{kind:J,node:B.intrinsic.never.internal}];else if(J==="optionals"||J==="defaultables")return Y;else return Y6({...Y,fixedVariants:[],l:X.map((O)=>({...O,kind:"prefix"})),r:X.map((O)=>({...O,kind:"prefix"}))});else if(J==="defaultables"){if(Z.kind==="defaultables"&&_.kind==="defaultables"&&Z.default!==_.default)w(dZ(Z.default,_.default));Y.result=[...Y.result,{kind:J,node:$,default:Z.kind==="defaultables"?Z.default:_.kind==="defaultables"?_.default:_0(`Unexpected defaultable intersection from ${Z.kind} and ${_.kind} elements.`)}]}else Y.result=[...Y.result,{kind:J,node:$}];let Q=Y.l.length,z=Y.r.length;if(Z.kind!=="variadic"||Q>=z&&(_.kind==="variadic"||z===1))Y.l=X;if(_.kind!=="variadic"||z>=Q&&(Z.kind==="variadic"||Q===1))Y.r=G;return Y6(Y)};var pG=(Y)=>(Z)=>{if(Z.props.length||Z.index){let X=Z.index?.map((G)=>G[Y])??[];for(let G of Z.props)X.push(G[Y]);if(Z.undeclared)X.push(`+ (undeclared): ${Z.undeclared}`);let _=`{ ${X.join(", ")} }`;return Z.sequence?`${_} & ${Z.sequence.description}`:_}return Z.sequence?.description??"{}"},I$=pG("description"),B$=pG("expression"),gG=(Y,Z,X)=>{let _=Y.required?"required":"optional";if(!Z.signature.allows(Y.key))return null;let G=O1(Y.value,Z.value,X);if(G instanceof S)return _==="optional"?X.node("optional",{key:Y.key,value:B.intrinsic.never.internal}):G.withPrefixKey(Y.key,Y.kind);return null},C$=r({kind:"structure",hasAssociatedError:!1,normalize:(Y)=>Y,applyConfig:(Y,Z)=>{if(!Y.undeclared&&Z.onUndeclaredKey!=="ignore")return{...Y,undeclared:Z.onUndeclaredKey};return Y},keys:{required:{child:!0,parse:t0("required"),reduceIo:(Y,Z,X)=>{Z.required=Z0(Z.required,X.map((_)=>_[Y]));return}},optional:{child:!0,parse:t0("optional"),reduceIo:(Y,Z,X)=>{if(Y==="in"){Z.optional=X.map((_)=>_.in);return}for(let _ of X)Z[_.outProp.kind]=Z0(Z[_.outProp.kind],_.outProp.out)}},index:{child:!0,parse:t0("index")},sequence:{child:!0,parse:t0("sequence")},undeclared:{parse:(Y)=>Y==="ignore"?void 0:Y,reduceIo:(Y,Z,X)=>{if(X!=="delete")return;if(Y==="in")delete Z.undeclared;else Z.undeclared="reject"}}},defaults:{description:I$},intersections:{structure:(Y,Z,X)=>{let _={...Y.inner},G={...Z.inner},W=new S;if(Y.undeclared){let $=Y.keyof();for(let Q of Z.requiredKeys)if(!$.allows(Q))W.add("presence",B.intrinsic.never.internal,Z.propsByKey[Q].value,{path:[Q]});if(G.optional)G.optional=G.optional.filter((Q)=>$.allows(Q.key));if(G.index)G.index=G.index.flatMap((Q)=>{if(Q.signature.extends($))return Q;let z=O1($,Q.signature,X.$);if(z instanceof S)return[];let O=e6(z,Q.value,X.$);if(O.required)G.required=a1(G.required,O.required);if(O.optional)G.optional=a1(G.optional,O.optional);return O.index??[]})}if(Z.undeclared){let $=Z.keyof();for(let Q of Y.requiredKeys)if(!$.allows(Q))W.add("presence",Y.propsByKey[Q].value,B.intrinsic.never.internal,{path:[Q]});if(_.optional)_.optional=_.optional.filter((Q)=>$.allows(Q.key));if(_.index)_.index=_.index.flatMap((Q)=>{if(Q.signature.extends($))return Q;let z=O1($,Q.signature,X.$);if(z instanceof S)return[];let O=e6(z,Q.value,X.$);if(O.required)_.required=a1(_.required,O.required);if(O.optional)_.optional=a1(_.optional,O.optional);return O.index??[]})}let H={};if(Y.undeclared||Z.undeclared)H.undeclared=Y.undeclared==="reject"||Z.undeclared==="reject"?"reject":"delete";let J=Z8({kind:"structure",baseInner:H,l:X8(_),r:X8(G),roots:[],ctx:X});if(J instanceof S)W.push(...J);if(W.length)return W;return J}},reduce:(Y,Z)=>{if(Y.index){if(!(Y.required||Y.optional))return;let X=!1,_=Y.required??[],G=Y.optional??[],W=[...G];for(let H of Y.index){for(let J of _){let $=gG(J,H,Z);if($ instanceof S)return $}for(let[J,$]of G.entries()){let Q=gG($,H,Z);if(Q instanceof S)return Q;if(Q===null)continue;W[J]=Q,X=!0}}if(X)return Z.node("structure",{...Y,optional:W},{prereduced:!0})}}});class mG extends C1{impliedBasis=B.intrinsic.object.internal;impliedSiblings=this.children.flatMap((Y)=>Y.impliedSiblings??[]);props=a1(this.required,this.optional);propsByKey=o(this.props,(Y,Z)=>[Z.key,Z]);propsByKeyReference=K0(this.propsByKey);expression=B$(this);requiredKeys=this.required?.map((Y)=>Y.key)??[];optionalKeys=this.optional?.map((Y)=>Y.key)??[];literalKeys=[...this.requiredKeys,...this.optionalKeys];_keyof;keyof(){if(this._keyof)return this._keyof;let Y=this.$.units(this.literalKeys).branches;if(this.index)for(let{signature:Z}of this.index)Y=Y.concat(Z.branches);return this._keyof=this.$.node("union",Y)}map(Y){return this.$.node("structure",this.props.flatMap(Y).reduce((Z,X)=>{let _=this.propsByKey[X.key];if(V0(X)){if(X.kind!=="required"&&X.kind!=="optional")return w(`Map result must have kind "required" or "optional" (was ${X.kind})`);return Z[X.kind]=Z0(Z[X.kind],X),Z}let G=X.kind??_?.kind??"required",W=o(X,(H,J)=>(H in r8.implementation.keys)?[H,J]:[]);return Z[G]=Z0(Z[G],this.$.node(G,W)),Z},{}))}assertHasKeys(Y){let Z=Y.filter((X)=>!a8(X,this.keyof()));if(Z.length)return w(yG(this.expression,Z))}get(Y,...Z){let X,_=!1,G=j$(Y);if((typeof G==="string"||typeof G==="symbol")&&this.propsByKey[G])X=this.propsByKey[G].value,_=this.propsByKey[G].required;if(this.index){for(let H of this.index)if(a8(G,H.signature))X=X?.and(H.value)??H.value}if(this.sequence&&a8(G,B.intrinsic.nonNegativeIntegerString))if(y(G,"root")){if(this.sequence.variadic)X=X?.and(this.sequence.element)??this.sequence.element}else{let H=Number.parseInt(G);if(H<this.sequence.prevariadic.length){let J=this.sequence.prevariadic[H].node;X=X?.and(J)??J,_||=H<this.sequence.prefixLength}else if(this.sequence.variadic){let J=this.$.node("union",this.sequence.variadicOrPostfix);X=X?.and(J)??J}}if(!X){if(this.sequence?.variadic&&y(G,"root")&&G.extends(B.intrinsic.number))return w(P$(G.expression,this.sequence.expression));return w(yG(this.expression,[G]))}let W=X.get(...Z);return _?W:W.or(B.intrinsic.undefined)}pick(...Y){return this.assertHasKeys(Y),this.$.node("structure",this.filterKeys("pick",Y))}omit(...Y){return this.assertHasKeys(Y),this.$.node("structure",this.filterKeys("omit",Y))}optionalize(){let{required:Y,...Z}=this.inner;return this.$.node("structure",{...Z,optional:this.props.map((X)=>X.hasKind("required")?this.$.node("optional",X.inner):X)})}require(){let{optional:Y,...Z}=this.inner;return this.$.node("structure",{...Z,required:this.props.map((X)=>X.hasKind("optional")?{key:X.key,value:X.value}:X)})}merge(Y){let Z=this.filterKeys("omit",[Y.keyof()]);if(Y.required)Z.required=Z0(Z.required,Y.required);if(Y.optional)Z.optional=Z0(Z.optional,Y.optional);if(Y.index)Z.index=Z0(Z.index,Y.index);if(Y.sequence)Z.sequence=Y.sequence;if(Y.undeclared)Z.undeclared=Y.undeclared;else delete Z.undeclared;return this.$.node("structure",Z)}filterKeys(Y,Z){let X=u6(this.inner),_=(G)=>{let W=Z.some((H)=>a8(G,H));return Y==="pick"?W:!W};if(X.required)X.required=X.required.filter((G)=>_(G.key));if(X.optional)X.optional=X.optional.filter((G)=>_(G.key));if(X.index)X.index=X.index.filter((G)=>_(G.signature));return X}traverseAllows=(Y,Z)=>this._traverse("Allows",Y,Z);traverseApply=(Y,Z)=>this._traverse("Apply",Y,Z);_traverse=(Y,Z,X)=>{let _=X?.currentErrorCount??0;for(let G=0;G<this.props.length;G++)if(Y==="Allows"){if(!this.props[G].traverseAllows(Z,X))return!1}else if(this.props[G].traverseApply(Z,X),X.failFast&&X.currentErrorCount>_)return!1;if(this.sequence){if(Y==="Allows"){if(!this.sequence.traverseAllows(Z,X))return!1}else if(this.sequence.traverseApply(Z,X),X.failFast&&X.currentErrorCount>_)return!1}if(this.index||this.undeclared==="reject"){let G=Object.keys(Z);G.push(...Object.getOwnPropertySymbols(Z));for(let W=0;W<G.length;W++){let H=G[W];if(this.index){for(let J of this.index)if(J.signature.traverseAllows(H,X)){if(Y==="Allows"){if(!U1(H,()=>J.value.traverseAllows(Z[H],X),X))return!1}else if(U1(H,()=>J.value.traverseApply(Z[H],X),X),X.failFast&&X.currentErrorCount>_)return!1}}if(this.undeclared==="reject"&&!this.declaresKey(H)){if(Y==="Allows")return!1;if(X.errorFromNodeContext({code:"predicate",expected:"removed",actual:"",relativePath:[H],meta:this.meta}),X.failFast)return!1}}}if(this.structuralMorph&&X&&!X.hasError())X.queueMorphs([this.structuralMorph]);return!0};get defaultable(){return this.cacheGetter("defaultable",this.optional?.filter((Y)=>Y.hasDefault())??[])}declaresKey=(Y)=>(Y in this.propsByKey)||this.index?.some((Z)=>Z.signature.allows(Y))||this.sequence!==void 0&&B.intrinsic.nonNegativeIntegerString.allows(Y);_compileDeclaresKey(Y){let Z=[];if(this.props.length)Z.push(`k in ${this.propsByKeyReference}`);if(this.index)for(let X of this.index)Z.push(Y.invoke(X.signature,{kind:"Allows",arg:"k"}));if(this.sequence)Z.push("$ark.intrinsic.nonNegativeIntegerString.allows(k)");return Z.join(" || ")||"false"}get structuralMorph(){return this.cacheGetter("structuralMorph",K$(this))}structuralMorphRef=this.structuralMorph&&K0(this.structuralMorph);compile(Y){if(Y.traversalKind==="Apply")Y.initializeErrorCount();for(let Z of this.props)if(Y.check(Z),Y.traversalKind==="Apply")Y.returnIfFailFast();if(this.sequence){if(Y.check(this.sequence),Y.traversalKind==="Apply")Y.returnIfFailFast()}if(this.index||this.undeclared==="reject")Y.const("keys","Object.keys(data)"),Y.line("keys.push(...Object.getOwnPropertySymbols(data))"),Y.for("i < keys.length",()=>this.compileExhaustiveEntry(Y));if(Y.traversalKind==="Allows")return Y.return(!0);if(this.structuralMorphRef)Y.if("ctx && !ctx.hasError()",()=>{return Y.line("ctx.queueMorphs(["),q$(Y,this),Y.line("])")})}compileExhaustiveEntry(Y){if(Y.const("k","keys[i]"),this.index)for(let Z of this.index)Y.if(`${Y.invoke(Z.signature,{arg:"k",kind:"Allows"})}`,()=>Y.traverseKey("k","data[k]",Z.value));if(this.undeclared==="reject")Y.if(`!(${this._compileDeclaresKey(Y)})`,()=>{if(Y.traversalKind==="Allows")return Y.return(!1);return Y.line(`ctx.errorFromNodeContext({ code: "predicate", expected: "removed", actual: "", relativePath: [k], meta: ${this.compiledMeta} })`).if("ctx.failFast",()=>Y.return())});return Y}reduceJsonSchema(Y,Z){switch(Y.type){case"object":return this.reduceObjectJsonSchema(Y,Z);case"array":let X=this.sequence?.reduceJsonSchema(Y,Z)??Y;if(this.props.length||this.index)return Z.fallback.arrayObject({code:"arrayObject",base:X,object:this.reduceObjectJsonSchema({type:"object"},Z)});return X;default:return N0.throwInternalOperandError("structure",Y)}}reduceObjectJsonSchema(Y,Z){if(this.props.length){Y.properties={};for(let X of this.props){let _=X.value.toJsonSchemaRecurse(Z);if(typeof X.key==="symbol"){Z.fallback.symbolKey({code:"symbolKey",base:Y,key:X.key,value:_,optional:X.optional});continue}if(X.hasDefault()){let G=typeof X.default==="function"?X.default():X.default;_.default=B.intrinsic.jsonData.allows(G)?G:Z.fallback.defaultValue({code:"defaultValue",base:_,value:G})}Y.properties[X.key]=_}if(this.requiredKeys.length&&Y.properties)Y.required=this.requiredKeys.filter((X)=>typeof X==="string"&&(X in Y.properties))}if(this.index)for(let X of this.index){let _=X.value.toJsonSchemaRecurse(Z);if(X.signature.equals(B.intrinsic.string)){Y.additionalProperties=_;continue}for(let G of X.signature.branches){if(!G.extends(B.intrinsic.string)){Y=Z.fallback.symbolKey({code:"symbolKey",base:Y,key:null,value:_,optional:!1});continue}let W={type:"string"};if(G.hasKind("morph"))W=Z.fallback.morph({code:"morph",base:G.in.toJsonSchemaRecurse(Z),out:G.out.toJsonSchemaRecurse(Z)});if(!G.hasKind("intersection"))return _0(`Unexpected index branch kind ${G.kind}.`);let{pattern:H}=G.inner;if(H){let J=Object.assign(W,{pattern:H[0].rule});for(let $=1;$<H.length;$++)W=Z.fallback.patternIntersection({code:"patternIntersection",base:J,pattern:H[$].rule});Y.patternProperties??={},Y.patternProperties[J.pattern]=_}}}if(this.undeclared&&!Y.additionalProperties)Y.additionalProperties=!1;return Y}}var Y5={},T$=(Y)=>{let Z="";for(let X=0;X<Y.defaultable.length;X++)Z+=Y.defaultable[X].defaultValueMorphRef;if(Y.sequence?.defaultValueMorphsReference)Z+=Y.sequence?.defaultValueMorphsReference;if(Y.undeclared==="delete"){if(Z+="delete !(",Y.required)for(let X of Y.required)Z+=X.compiledKey+" | ";if(Y.optional)for(let X of Y.optional)Z+=X.compiledKey+" | ";if(Y.index)for(let X of Y.index)Z+=X.signature.id+" | ";if(Y.sequence)if(Y.sequence.maxLength===null)Z+=d.nonNegativeIntegerString.id;else for(let X=0;X<Y.sequence.tuple.length;X++)Z+=X+" | ";Z+=")"}return Z},K$=(Y)=>{let Z=T$(Y);if(!Z)return;if(Y5[Z])return Y5[Z];let X=(_,G)=>{for(let W=0;W<Y.defaultable.length;W++)if(!(Y.defaultable[W].key in _))Y.defaultable[W].defaultValueMorph(_,G);if(Y.sequence?.defaultables)for(let W=_.length-Y.sequence.prefixLength;W<Y.sequence.defaultables.length;W++)Y.sequence.defaultValueMorphs[W](_,G);if(Y.undeclared==="delete"){for(let W in _)if(!Y.declaresKey(W))delete _[W]}return _};return Y5[Z]=X},q$=(Y,Z)=>{let _=`(data${Z.defaultable.some((G)=>G.defaultValueMorph.length===2)||Z.sequence?.defaultValueMorphs.some((G)=>G.length===2)?", ctx":""})`;return Y.block(`${_} => `,(G)=>{for(let W=0;W<Z.defaultable.length;W++){let{serializedKey:H,defaultValueMorphRef:J}=Z.defaultable[W];G.if(`!(${H} in data)`,($)=>$.line(`${J}${_}`))}if(Z.sequence?.defaultables)G.for(`i < ${Z.sequence.defaultables.length}`,(W)=>W.set("data[i]",5),`data.length - ${Z.sequence.prefixLength}`);if(Z.undeclared==="delete")G.forIn("data",(W)=>W.if(`!(${Z._compileDeclaresKey(W)})`,(H)=>H.line("delete data[k]")));return G.return("data")})},Z5={implementation:C$,Node:mG},j$=(Y)=>{if(y(Y,"root")&&Y.hasKind("unit"))Y=Y.unit;if(typeof Y==="number")Y=`${Y}`;return Y},P$=(Y,Z)=>`${Y} is not allowed as an array index on ${Z}. Use the 'nonNegativeIntegerString' keyword instead.`,e6=(Y,Z,X)=>{let[_,G]=z_(Y.branches,(H)=>H.hasKind("unit"));if(!_.length)return{index:X.node("index",{signature:Y,value:Z})};let W={};for(let H of _){let J=X.node("required",{key:H.unit,value:Z});W[J.kind]=Z0(W[J.kind],J)}if(G.length)W.index=X.node("index",{signature:G,value:Z});return W},S$=(Y)=>y(Y,"root")?Y.expression:n(Y),yG=(Y,Z)=>`Key${Z.length===1?"":"s"} ${Z.map(S$).join(", ")} ${Z.length===1?"does":"do"} not exist on ${Y}`;var G8={...FG,alias:t8.implementation,domain:t6.implementation,unit:rZ.implementation,proto:e8.implementation,union:nZ.implementation,morph:iZ.implementation,intersection:lZ.implementation,divisor:SZ.implementation,pattern:yZ.implementation,predicate:PZ.implementation,required:aZ.implementation,optional:r8.implementation,index:sZ.implementation,sequence:tZ.implementation,structure:Z5.implementation};B.defaultConfig=A_(Object.assign(o(G8,(Y,Z)=>[Y,Z.defaults]),{jitless:C_(),clone:N_,onUndeclaredKey:"ignore",exactOptionalPropertyTypes:!0,numberAllowsNaN:!1,dateAllowsInvalid:!1,onFail:null,keywords:{},toJsonSchema:N0.defaultConfig}));B.resolvedConfig=u8(B.defaultConfig,B.config);var VG={...UG,alias:t8.Node,domain:t6.Node,unit:rZ.Node,proto:e8.Node,union:nZ.Node,morph:iZ.Node,intersection:lZ.Node,divisor:SZ.Node,pattern:yZ.Node,predicate:PZ.Node,required:aZ.Node,optional:r8.Node,index:sZ.Node,sequence:tZ.Node,structure:Z5.Node};class J8 extends FZ{get[X1](){return"module"}}var X5=(Y,Z)=>new J8(o(Y,(X,_)=>[X,y(_,"module")?X5(_,Z):Z.bindReference(_)]));var v$=(Y)=>O0(Y)?Y:("branches"in Y)&&O0(Y.branches)?Y.branches:void 0,x$=(Y,Z)=>w(`Node of kind ${Z} is not valid as a ${Y} definition`),uG=(Y)=>`#${Y} duplicates public alias ${Y}`,_5={};B.ambient??={};var dG,lG="function $",h$=(Y)=>iG(Y,oG(Y)),iG=(Y,Z)=>{let X=Z.write(lG,4),_=Z.compile()();for(let G of Y){if(G.precompilation)continue;if(G.traverseAllows=_[`${G.id}Allows`].bind(_),G.isRoot()&&!G.allowsRequiresContext)G.allows=G.traverseAllows;if(G.traverseApply=_[`${G.id}Apply`].bind(_),_[`${G.id}Optimistic`])G.traverseOptimistic=_[`${G.id}Optimistic`].bind(_);G.precompilation=X}},oG=(Y)=>new m6().return(Y.reduce((Z,X)=>{let _=new m8({kind:"Allows"}).indent();X.compile(_);let G=_.write(`${X.id}Allows`),W=new m8({kind:"Apply"}).indent();X.compile(W);let H=W.write(`${X.id}Apply`),J=`${Z}${G},
44
- ${H},
45
- `;if(!X.hasKind("union"))return J;let $=new m8({kind:"Allows",optimistic:!0}).indent();X.compile($);let Q=$.write(`${X.id}Optimistic`);return`${J}${Q},
43
+ Right: ${Z}`;var UQ=r({kind:"unit",hasAssociatedError:!0,keys:{unit:{preserveUndefined:!0,serialize:(Y)=>Y instanceof Date?Y.toISOString():B1(Y)}},normalize:(Y)=>Y,defaults:{description:(Y)=>n(Y.unit),problem:({expected:Y,actual:Z})=>`${Y===Z?`must be reference equal to ${Y} (serialized to the same value)`:`must be ${Y} (was ${Z})`}`},intersections:{unit:(Y,Z)=>S.init("unit",Y,Z),...l1("unit",(Y,Z)=>{if(Z.allows(Y.unit))return Y;let X=Z.hasKind("intersection")?Z.basis:Z;if(X){let _=X.hasKind("domain")?X:B.intrinsic.object;if(Y.domain!==_.domain){let G=Y.domain==="undefined"||Y.domain==="null"||Y.domain==="boolean"?Y.domain:B.intrinsic[Y.domain];return S.init("domain",G,_)}}return S.init("assignability",Y,Z.hasKind("intersection")?Z.children.find((_)=>!_.allows(Y.unit)):Z)})}});class x_ extends x4{compiledValue=this.json.unit;serializedValue=typeof this.unit==="string"||this.unit instanceof Date?JSON.stringify(this.compiledValue):`${this.compiledValue}`;compiledCondition=v_(this.unit,this.serializedValue);compiledNegation=v_(this.unit,this.serializedValue,"negated");expression=n(this.unit);domain=y0(this.unit);get defaultShortDescription(){return this.domain==="object"?z1.object:this.description}innerToJsonSchema(Y){return this.unit===null?{type:"null"}:B.intrinsic.jsonPrimitive.allows(this.unit)?{const:this.unit}:Y.fallback.unit({code:"unit",base:{},unit:this.unit})}traverseAllows=this.unit instanceof Date?(Y)=>Y instanceof Date&&Y.toISOString()===this.compiledValue:Number.isNaN(this.unit)?(Y)=>Number.isNaN(Y):(Y)=>Y===this.unit}var sY={implementation:UQ,Node:x_},v_=(Y,Z,X)=>{if(Y instanceof Date){let _=`data instanceof Date && data.toISOString() === ${Z}`;return X?`!(${_})`:_}if(Number.isNaN(Y))return`${X?"!":""}Number.isNaN(data)`;return`data ${X?"!":"="}== ${Z}`};var FQ=r({kind:"index",hasAssociatedError:!1,intersectionIsOpen:!0,keys:{signature:{child:!0,parse:(Y,Z)=>{let X=Z.$.parseSchema(Y);if(!X.extends(B.intrinsic.key))return w(EQ(X.expression));let _=X.branches.filter((G)=>G.hasKind("unit"));if(_.length)return w(OQ(_.map((G)=>n(G.unit))));return X}},value:{child:!0,parse:(Y,Z)=>Z.$.parseSchema(Y)}},normalize:(Y)=>Y,defaults:{description:(Y)=>`[${Y.signature.expression}]: ${Y.value.description}`},intersections:{index:(Y,Z,X)=>{if(Y.signature.equals(Z.signature)){let _=M0(Y.value,Z.value,X),G=_ instanceof S?B.intrinsic.never.internal:_;return X.$.node("index",{signature:Y.signature,value:G})}if(Y.signature.extends(Z.signature)&&Y.value.subsumes(Z.value))return Z;if(Z.signature.extends(Y.signature)&&Z.value.subsumes(Y.value))return Y;return null}}});class h_ extends C1{impliedBasis=B.intrinsic.object.internal;expression=`[${this.signature.expression}]: ${this.value.expression}`;flatRefs=Z0(this.value.flatRefs.map((Y)=>b1([this.signature,...Y.path],Y.node)),b1([this.signature],this.value));traverseAllows=(Y,Z)=>j4(Y).every((X)=>{if(this.signature.traverseAllows(X[0],Z))return F1(X[0],()=>this.value.traverseAllows(X[1],Z),Z);return!0});traverseApply=(Y,Z)=>{for(let X of j4(Y))if(this.signature.traverseAllows(X[0],Z))F1(X[0],()=>this.value.traverseApply(X[1],Z),Z)};_transform(Y,Z){Z.path.push(this.signature);let X=super._transform(Y,Z);return Z.path.pop(),X}compile(){}}var aY={implementation:FQ,Node:h_},OQ=(Y)=>`Index keys ${Y.join(", ")} should be specified as named props.`,EQ=(Y)=>`Indexed key definition '${Y}' must be a string or symbol`;var DQ=r({kind:"required",hasAssociatedError:!0,intersectionIsOpen:!0,keys:{key:{},value:{child:!0,parse:(Y,Z)=>Z.$.parseSchema(Y)}},normalize:(Y)=>Y,defaults:{description:(Y)=>`${Y.compiledKey}: ${Y.value.description}`,expected:(Y)=>Y.missingValueDescription,actual:()=>"missing"},intersections:{required:n8,optional:n8}});class f_ extends r8{expression=`${this.compiledKey}: ${this.value.expression}`;errorContext=Object.freeze({code:"required",missingValueDescription:this.value.defaultShortDescription,relativePath:[this.key],meta:this.meta});compiledErrorContext=L4(this.errorContext)}var tY={implementation:DQ,Node:f_};var LQ=r({kind:"sequence",hasAssociatedError:!1,collapsibleKey:"variadic",keys:{prefix:{child:!0,parse:(Y,Z)=>{if(Y.length===0)return;return Y.map((X)=>Z.$.parseSchema(X))}},optionals:{child:!0,parse:(Y,Z)=>{if(Y.length===0)return;return Y.map((X)=>Z.$.parseSchema(X))}},defaultables:{child:(Y)=>Y.map((Z)=>Z[0]),parse:(Y,Z)=>{if(Y.length===0)return;return Y.map((X)=>{let _=Z.$.parseSchema(X[0]);return a8(_,X[1],null),[_,X[1]]})},serialize:(Y)=>Y.map((Z)=>[Z[0].collapsibleJson,B1(Z[1])])},variadic:{child:!0,parse:(Y,Z)=>Z.$.parseSchema(Y,Z)},minVariadicLength:{parse:(Y)=>Y===0?void 0:Y},postfix:{child:!0,parse:(Y,Z)=>{if(Y.length===0)return;return Y.map((X)=>Z.$.parseSchema(X))}}},normalize:(Y)=>{if(typeof Y==="string")return{variadic:Y};if("variadic"in Y||"prefix"in Y||"defaultables"in Y||"optionals"in Y||"postfix"in Y||"minVariadicLength"in Y){if(Y.postfix?.length){if(!Y.variadic)return w(wQ);if(Y.optionals?.length||Y.defaultables?.length)return w(YZ)}if(Y.minVariadicLength&&!Y.variadic)return w("minVariadicLength may not be specified without a variadic element");return Y}return{variadic:Y}},reduce:(Y,Z)=>{let X=Y.minVariadicLength??0,_=Y.prefix?.slice()??[],G=Y.defaultables?.slice()??[],W=Y.optionals?.slice()??[],$=Y.postfix?.slice()??[];if(Y.variadic){while(W.at(-1)?.equals(Y.variadic))W.pop();if(W.length===0&&G.length===0)while(_.at(-1)?.equals(Y.variadic))_.pop(),X++;while($[0]?.equals(Y.variadic))$.shift(),X++}else if(W.length===0&&G.length===0)_.push(...$.splice(0));if(X!==Y.minVariadicLength||Y.prefix&&Y.prefix.length!==_.length)return Z.node("sequence",{...Y,prefix:_,defaultables:G,optionals:W,postfix:$,minVariadicLength:X},{prereduced:!0})},defaults:{description:(Y)=>{if(Y.isVariadicOnly)return`${Y.variadic.nestableExpression}[]`;return`[${Y.tuple.map((X)=>X.kind==="defaultables"?`${X.node.nestableExpression} = ${n(X.default)}`:X.kind==="optionals"?`${X.node.nestableExpression}?`:X.kind==="variadic"?`...${X.node.nestableExpression}[]`:X.node.expression).join(", ")}]`}},intersections:{sequence:(Y,Z,X)=>{let _=Z2({l:Y.tuple,r:Z.tuple,disjoint:new S,result:[],fixedVariants:[],ctx:X}),G=_.disjoint.length===0?[_,..._.fixedVariants]:_.fixedVariants;return G.length===0?_.disjoint:G.length===1?X.$.node("sequence",b_(G[0].result)):X.$.node("union",G.map((W)=>({proto:Array,sequence:b_(W.result)})))}}});class k_ extends C1{impliedBasis=B.intrinsic.Array.internal;tuple=AQ(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((Y)=>{if(Y.kind==="defaultables"||Y.kind==="optionals")return this.defaultablesAndOptionals.push(Y.node),!0;return Y.kind==="prefix"});variadicOrPostfix=a1(this.variadic&&[this.variadic],this.postfix);flatRefs=this.addFlatRefs();addFlatRefs(){return KY(this.flatRefs,this.prevariadic.flatMap((Y,Z)=>Z0(Y.node.flatRefs.map((X)=>b1([`${Z}`,...X.path],X.node)),b1([`${Z}`],Y.node)))),KY(this.flatRefs,this.variadicOrPostfix.flatMap((Y)=>Z0(Y.flatRefs.map((Z)=>b1([B.intrinsic.nonNegativeIntegerString.internal,...Z.path],Z.node)),b1([B.intrinsic.nonNegativeIntegerString.internal],Y)))),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=MQ(this);defaultValueMorphsReference=this.defaultValueMorphs.length?K0(this.defaultValueMorphs):void 0;elementAtIndex(Y,Z){if(Z<this.prevariadic.length)return this.tuple[Z];let X=Y.length-this.postfixLength;if(Z>=X)return{kind:"postfix",node:this.postfix[Z-X]};return{kind:"variadic",node:this.variadic??_0(`Unexpected attempt to access index ${Z} on ${this}`)}}traverseAllows=(Y,Z)=>{for(let X=0;X<Y.length;X++)if(!this.elementAtIndex(Y,X).node.traverseAllows(Y[X],Z))return!1;return!0};traverseApply=(Y,Z)=>{let X=0;for(;X<Y.length;X++)F1(X,()=>this.elementAtIndex(Y,X).node.traverseApply(Y[X],Z),Z)};get element(){return this.cacheGetter("element",this.$.node("union",this.children))}compile(Y){if(this.prefix)for(let[Z,X]of this.prefix.entries())Y.traverseKey(`${Z}`,`data[${Z}]`,X);for(let[Z,X]of this.defaultablesAndOptionals.entries()){let _=`${Z+this.prefixLength}`;Y.if(`${_} >= ${Y.data}.length`,()=>Y.traversalKind==="Allows"?Y.return(!0):Y.return()),Y.traverseKey(_,`data[${_}]`,X)}if(this.variadic){if(this.postfix)Y.const("firstPostfixIndex",`${Y.data}.length${this.postfix?`- ${this.postfix.length}`:""}`);if(Y.for(`i < ${this.postfix?"firstPostfixIndex":"data.length"}`,()=>Y.traverseKey("i","data[i]",this.variadic),this.prevariadic.length),this.postfix)for(let[Z,X]of this.postfix.entries()){let _=`firstPostfixIndex + ${Z}`;Y.traverseKey(_,`data[${_}]`,X)}}if(Y.traversalKind==="Allows")Y.return(!0)}_transform(Y,Z){Z.path.push(B.intrinsic.nonNegativeIntegerString.internal);let X=super._transform(Y,Z);return Z.path.pop(),X}expression=this.description;reduceJsonSchema(Y,Z){if(this.prevariadic.length)Y.prefixItems=this.prevariadic.map((X)=>{let _=X.node.toJsonSchemaRecurse(Z);if(X.kind==="defaultables"){let G=typeof X.default==="function"?X.default():X.default;_.default=B.intrinsic.jsonData.allows(G)?G:Z.fallback.defaultValue({code:"defaultValue",base:_,value:G})}return _});if(this.minLength)Y.minItems=this.minLength;if(this.variadic){let X=Object.assign(Y,{items:this.variadic.toJsonSchemaRecurse(Z)});if(this.maxLength)X.maxItems=this.maxLength;if(this.postfix){let _=this.postfix.map((G)=>G.toJsonSchemaRecurse(Z));Y=Z.fallback.arrayPostfix({code:"arrayPostfix",base:X,elements:_})}}else Y.items=!1,delete Y.maxItems;return Y}}var VQ={},MQ=(Y)=>{if(!Y.defaultables)return[];let Z=[],X="[",_=Y.prefixLength+Y.defaultablesLength-1;for(let G=Y.prefixLength;G<=_;G++){let[W,$]=Y.defaultables[G-Y.prefixLength];Z.push(lY(G,W,$)),X+=`${G}: ${W.id} = ${B1($)}, `}return X+="]",VQ[X]??=Z},eY={implementation:LQ,Node:k_},AQ=(Y)=>{let Z=[];if(Y.prefix)for(let X of Y.prefix)Z.push({kind:"prefix",node:X});if(Y.defaultables)for(let[X,_]of Y.defaultables)Z.push({kind:"defaultables",node:X,default:_});if(Y.optionals)for(let X of Y.optionals)Z.push({kind:"optionals",node:X});if(Y.variadic)Z.push({kind:"variadic",node:Y.variadic});if(Y.postfix)for(let X of Y.postfix)Z.push({kind:"postfix",node:X});return Z},b_=(Y)=>Y.reduce((Z,X)=>{if(X.kind==="variadic")Z.variadic=X.node;else if(X.kind==="defaultables")Z.defaultables=Z0(Z.defaultables,[[X.node,X.default]]);else Z[X.kind]=Z0(Z[X.kind],X.node);return Z},{}),YZ="A postfix required element cannot follow an optional or defaultable element",wQ="A postfix element requires a variadic element",Z2=(Y)=>{let[Z,...X]=Y.l,[_,...G]=Y.r;if(!Z||!_)return Y;let W=X.at(-1)?.kind==="postfix",$=G.at(-1)?.kind==="postfix",H=Z.kind==="prefix"||_.kind==="prefix"?"prefix":Z.kind==="postfix"||_.kind==="postfix"?"postfix":Z.kind==="variadic"&&_.kind==="variadic"?"variadic":W||$?"prefix":Z.kind==="defaultables"||_.kind==="defaultables"?"defaultables":"optionals";if(Z.kind==="prefix"&&_.kind==="variadic"&&$){let O=Z2({...Y,fixedVariants:[],r:G.map((D)=>({...D,kind:"prefix"}))});if(O.disjoint.length===0)Y.fixedVariants.push(O)}else if(_.kind==="prefix"&&Z.kind==="variadic"&&W){let O=Z2({...Y,fixedVariants:[],l:X.map((D)=>({...D,kind:"prefix"}))});if(O.disjoint.length===0)Y.fixedVariants.push(O)}let Q=M0(Z.node,_.node,Y.ctx);if(Q instanceof S)if(H==="prefix"||H==="postfix")Y.disjoint.push(...Q.withPrefixKey(H==="prefix"?Y.result.length:`-${X.length+1}`,"required")),Y.result=[...Y.result,{kind:H,node:B.intrinsic.never.internal}];else if(H==="optionals"||H==="defaultables")return Y;else return Z2({...Y,fixedVariants:[],l:X.map((O)=>({...O,kind:"prefix"})),r:X.map((O)=>({...O,kind:"prefix"}))});else if(H==="defaultables"){if(Z.kind==="defaultables"&&_.kind==="defaultables"&&Z.default!==_.default)w(cY(Z.default,_.default));Y.result=[...Y.result,{kind:H,node:Q,default:Z.kind==="defaultables"?Z.default:_.kind==="defaultables"?_.default:_0(`Unexpected defaultable intersection from ${Z.kind} and ${_.kind} elements.`)}]}else Y.result=[...Y.result,{kind:H,node:Q}];let J=Y.l.length,z=Y.r.length;if(Z.kind!=="variadic"||J>=z&&(_.kind==="variadic"||z===1))Y.l=X;if(_.kind!=="variadic"||z>=J&&(Z.kind==="variadic"||J===1))Y.r=G;return Z2(Y)};var p_=(Y)=>(Z)=>{if(Z.props.length||Z.index){let X=Z.index?.map((G)=>G[Y])??[];for(let G of Z.props)X.push(G[Y]);if(Z.undeclared)X.push(`+ (undeclared): ${Z.undeclared}`);let _=`{ ${X.join(", ")} }`;return Z.sequence?`${_} & ${Z.sequence.description}`:_}return Z.sequence?.description??"{}"},RQ=p_("description"),NQ=p_("expression"),g_=(Y,Z,X)=>{let _=Y.required?"required":"optional";if(!Z.signature.allows(Y.key))return null;let G=O1(Y.value,Z.value,X);if(G instanceof S)return _==="optional"?X.node("optional",{key:Y.key,value:B.intrinsic.never.internal}):G.withPrefixKey(Y.key,Y.kind);return null},IQ=r({kind:"structure",hasAssociatedError:!1,normalize:(Y)=>Y,applyConfig:(Y,Z)=>{if(!Y.undeclared&&Z.onUndeclaredKey!=="ignore")return{...Y,undeclared:Z.onUndeclaredKey};return Y},keys:{required:{child:!0,parse:t0("required"),reduceIo:(Y,Z,X)=>{Z.required=Z0(Z.required,X.map((_)=>_[Y]));return}},optional:{child:!0,parse:t0("optional"),reduceIo:(Y,Z,X)=>{if(Y==="in"){Z.optional=X.map((_)=>_.in);return}for(let _ of X)Z[_.outProp.kind]=Z0(Z[_.outProp.kind],_.outProp.out)}},index:{child:!0,parse:t0("index")},sequence:{child:!0,parse:t0("sequence")},undeclared:{parse:(Y)=>Y==="ignore"?void 0:Y,reduceIo:(Y,Z,X)=>{if(X!=="delete")return;if(Y==="in")delete Z.undeclared;else Z.undeclared="reject"}}},defaults:{description:RQ},intersections:{structure:(Y,Z,X)=>{let _={...Y.inner},G={...Z.inner},W=new S;if(Y.undeclared){let Q=Y.keyof();for(let J of Z.requiredKeys)if(!Q.allows(J))W.add("presence",B.intrinsic.never.internal,Z.propsByKey[J].value,{path:[J]});if(G.optional)G.optional=G.optional.filter((J)=>Q.allows(J.key));if(G.index)G.index=G.index.flatMap((J)=>{if(J.signature.extends(Q))return J;let z=O1(Q,J.signature,X.$);if(z instanceof S)return[];let O=e2(z,J.value,X.$);if(O.required)G.required=a1(G.required,O.required);if(O.optional)G.optional=a1(G.optional,O.optional);return O.index??[]})}if(Z.undeclared){let Q=Z.keyof();for(let J of Y.requiredKeys)if(!Q.allows(J))W.add("presence",Y.propsByKey[J].value,B.intrinsic.never.internal,{path:[J]});if(_.optional)_.optional=_.optional.filter((J)=>Q.allows(J.key));if(_.index)_.index=_.index.flatMap((J)=>{if(J.signature.extends(Q))return J;let z=O1(Q,J.signature,X.$);if(z instanceof S)return[];let O=e2(z,J.value,X.$);if(O.required)_.required=a1(_.required,O.required);if(O.optional)_.optional=a1(_.optional,O.optional);return O.index??[]})}let $={};if(Y.undeclared||Z.undeclared)$.undeclared=Y.undeclared==="reject"||Z.undeclared==="reject"?"reject":"delete";let H=Z8({kind:"structure",baseInner:$,l:X8(_),r:X8(G),roots:[],ctx:X});if(H instanceof S)W.push(...H);if(W.length)return W;return H}},reduce:(Y,Z)=>{if(Y.index){if(!(Y.required||Y.optional))return;let X=!1,_=Y.required??[],G=Y.optional??[],W=[...G];for(let $ of Y.index){for(let H of _){let Q=g_(H,$,Z);if(Q instanceof S)return Q}for(let[H,Q]of G.entries()){let J=g_(Q,$,Z);if(J instanceof S)return J;if(J===null)continue;W[H]=J,X=!0}}if(X)return Z.node("structure",{...Y,optional:W},{prereduced:!0})}}});class m_ extends C1{impliedBasis=B.intrinsic.object.internal;impliedSiblings=this.children.flatMap((Y)=>Y.impliedSiblings??[]);props=a1(this.required,this.optional);propsByKey=o(this.props,(Y,Z)=>[Z.key,Z]);propsByKeyReference=K0(this.propsByKey);expression=NQ(this);requiredKeys=this.required?.map((Y)=>Y.key)??[];optionalKeys=this.optional?.map((Y)=>Y.key)??[];literalKeys=[...this.requiredKeys,...this.optionalKeys];_keyof;keyof(){if(this._keyof)return this._keyof;let Y=this.$.units(this.literalKeys).branches;if(this.index)for(let{signature:Z}of this.index)Y=Y.concat(Z.branches);return this._keyof=this.$.node("union",Y)}map(Y){return this.$.node("structure",this.props.flatMap(Y).reduce((Z,X)=>{let _=this.propsByKey[X.key];if(V0(X)){if(X.kind!=="required"&&X.kind!=="optional")return w(`Map result must have kind "required" or "optional" (was ${X.kind})`);return Z[X.kind]=Z0(Z[X.kind],X),Z}let G=X.kind??_?.kind??"required",W=o(X,($,H)=>($ in s8.implementation.keys)?[$,H]:[]);return Z[G]=Z0(Z[G],this.$.node(G,W)),Z},{}))}assertHasKeys(Y){let Z=Y.filter((X)=>!t8(X,this.keyof()));if(Z.length)return w(y_(this.expression,Z))}get(Y,...Z){let X,_=!1,G=KQ(Y);if((typeof G==="string"||typeof G==="symbol")&&this.propsByKey[G])X=this.propsByKey[G].value,_=this.propsByKey[G].required;if(this.index){for(let $ of this.index)if(t8(G,$.signature))X=X?.and($.value)??$.value}if(this.sequence&&t8(G,B.intrinsic.nonNegativeIntegerString))if(y(G,"root")){if(this.sequence.variadic)X=X?.and(this.sequence.element)??this.sequence.element}else{let $=Number.parseInt(G);if($<this.sequence.prevariadic.length){let H=this.sequence.prevariadic[$].node;X=X?.and(H)??H,_||=$<this.sequence.prefixLength}else if(this.sequence.variadic){let H=this.$.node("union",this.sequence.variadicOrPostfix);X=X?.and(H)??H}}if(!X){if(this.sequence?.variadic&&y(G,"root")&&G.extends(B.intrinsic.number))return w(qQ(G.expression,this.sequence.expression));return w(y_(this.expression,[G]))}let W=X.get(...Z);return _?W:W.or(B.intrinsic.undefined)}pick(...Y){return this.assertHasKeys(Y),this.$.node("structure",this.filterKeys("pick",Y))}omit(...Y){return this.assertHasKeys(Y),this.$.node("structure",this.filterKeys("omit",Y))}optionalize(){let{required:Y,...Z}=this.inner;return this.$.node("structure",{...Z,optional:this.props.map((X)=>X.hasKind("required")?this.$.node("optional",X.inner):X)})}require(){let{optional:Y,...Z}=this.inner;return this.$.node("structure",{...Z,required:this.props.map((X)=>X.hasKind("optional")?{key:X.key,value:X.value}:X)})}merge(Y){let Z=this.filterKeys("omit",[Y.keyof()]);if(Y.required)Z.required=Z0(Z.required,Y.required);if(Y.optional)Z.optional=Z0(Z.optional,Y.optional);if(Y.index)Z.index=Z0(Z.index,Y.index);if(Y.sequence)Z.sequence=Y.sequence;if(Y.undeclared)Z.undeclared=Y.undeclared;else delete Z.undeclared;return this.$.node("structure",Z)}filterKeys(Y,Z){let X=u2(this.inner),_=(G)=>{let W=Z.some(($)=>t8(G,$));return Y==="pick"?W:!W};if(X.required)X.required=X.required.filter((G)=>_(G.key));if(X.optional)X.optional=X.optional.filter((G)=>_(G.key));if(X.index)X.index=X.index.filter((G)=>_(G.signature));return X}traverseAllows=(Y,Z)=>this._traverse("Allows",Y,Z);traverseApply=(Y,Z)=>this._traverse("Apply",Y,Z);_traverse=(Y,Z,X)=>{let _=X?.currentErrorCount??0;for(let G=0;G<this.props.length;G++)if(Y==="Allows"){if(!this.props[G].traverseAllows(Z,X))return!1}else if(this.props[G].traverseApply(Z,X),X.failFast&&X.currentErrorCount>_)return!1;if(this.sequence){if(Y==="Allows"){if(!this.sequence.traverseAllows(Z,X))return!1}else if(this.sequence.traverseApply(Z,X),X.failFast&&X.currentErrorCount>_)return!1}if(this.index||this.undeclared==="reject"){let G=Object.keys(Z);G.push(...Object.getOwnPropertySymbols(Z));for(let W=0;W<G.length;W++){let $=G[W];if(this.index){for(let H of this.index)if(H.signature.traverseAllows($,X)){if(Y==="Allows"){if(!F1($,()=>H.value.traverseAllows(Z[$],X),X))return!1}else if(F1($,()=>H.value.traverseApply(Z[$],X),X),X.failFast&&X.currentErrorCount>_)return!1}}if(this.undeclared==="reject"&&!this.declaresKey($)){if(Y==="Allows")return!1;if(X.errorFromNodeContext({code:"predicate",expected:"removed",actual:"",relativePath:[$],meta:this.meta}),X.failFast)return!1}}}if(this.structuralMorph&&X&&!X.hasError())X.queueMorphs([this.structuralMorph]);return!0};get defaultable(){return this.cacheGetter("defaultable",this.optional?.filter((Y)=>Y.hasDefault())??[])}declaresKey=(Y)=>(Y in this.propsByKey)||this.index?.some((Z)=>Z.signature.allows(Y))||this.sequence!==void 0&&B.intrinsic.nonNegativeIntegerString.allows(Y);_compileDeclaresKey(Y){let Z=[];if(this.props.length)Z.push(`k in ${this.propsByKeyReference}`);if(this.index)for(let X of this.index)Z.push(Y.invoke(X.signature,{kind:"Allows",arg:"k"}));if(this.sequence)Z.push("$ark.intrinsic.nonNegativeIntegerString.allows(k)");return Z.join(" || ")||"false"}get structuralMorph(){return this.cacheGetter("structuralMorph",CQ(this))}structuralMorphRef=this.structuralMorph&&K0(this.structuralMorph);compile(Y){if(Y.traversalKind==="Apply")Y.initializeErrorCount();for(let Z of this.props)if(Y.check(Z),Y.traversalKind==="Apply")Y.returnIfFailFast();if(this.sequence){if(Y.check(this.sequence),Y.traversalKind==="Apply")Y.returnIfFailFast()}if(this.index||this.undeclared==="reject")Y.const("keys","Object.keys(data)"),Y.line("keys.push(...Object.getOwnPropertySymbols(data))"),Y.for("i < keys.length",()=>this.compileExhaustiveEntry(Y));if(Y.traversalKind==="Allows")return Y.return(!0);if(this.structuralMorphRef)Y.if("ctx && !ctx.hasError()",()=>{return Y.line("ctx.queueMorphs(["),TQ(Y,this),Y.line("])")})}compileExhaustiveEntry(Y){if(Y.const("k","keys[i]"),this.index)for(let Z of this.index)Y.if(`${Y.invoke(Z.signature,{arg:"k",kind:"Allows"})}`,()=>Y.traverseKey("k","data[k]",Z.value));if(this.undeclared==="reject")Y.if(`!(${this._compileDeclaresKey(Y)})`,()=>{if(Y.traversalKind==="Allows")return Y.return(!1);return Y.line(`ctx.errorFromNodeContext({ code: "predicate", expected: "removed", actual: "", relativePath: [k], meta: ${this.compiledMeta} })`).if("ctx.failFast",()=>Y.return())});return Y}reduceJsonSchema(Y,Z){switch(Y.type){case"object":return this.reduceObjectJsonSchema(Y,Z);case"array":let X=this.sequence?.reduceJsonSchema(Y,Z)??Y;if(this.props.length||this.index)return Z.fallback.arrayObject({code:"arrayObject",base:X,object:this.reduceObjectJsonSchema({type:"object"},Z)});return X;default:return N0.throwInternalOperandError("structure",Y)}}reduceObjectJsonSchema(Y,Z){if(this.props.length){Y.properties={};for(let X of this.props){let _=X.value.toJsonSchemaRecurse(Z);if(typeof X.key==="symbol"){Z.fallback.symbolKey({code:"symbolKey",base:Y,key:X.key,value:_,optional:X.optional});continue}if(X.hasDefault()){let G=typeof X.default==="function"?X.default():X.default;_.default=B.intrinsic.jsonData.allows(G)?G:Z.fallback.defaultValue({code:"defaultValue",base:_,value:G})}Y.properties[X.key]=_}if(this.requiredKeys.length&&Y.properties)Y.required=this.requiredKeys.filter((X)=>typeof X==="string"&&(X in Y.properties))}if(this.index)for(let X of this.index){let _=X.value.toJsonSchemaRecurse(Z);if(X.signature.equals(B.intrinsic.string)){Y.additionalProperties=_;continue}for(let G of X.signature.branches){if(!G.extends(B.intrinsic.string)){Y=Z.fallback.symbolKey({code:"symbolKey",base:Y,key:null,value:_,optional:!1});continue}let W={type:"string"};if(G.hasKind("morph"))W=Z.fallback.morph({code:"morph",base:G.in.toJsonSchemaRecurse(Z),out:G.out.toJsonSchemaRecurse(Z)});if(!G.hasKind("intersection"))return _0(`Unexpected index branch kind ${G.kind}.`);let{pattern:$}=G.inner;if($){let H=Object.assign(W,{pattern:$[0].rule});for(let Q=1;Q<$.length;Q++)W=Z.fallback.patternIntersection({code:"patternIntersection",base:H,pattern:$[Q].rule});Y.patternProperties??={},Y.patternProperties[H.pattern]=_}}}if(this.undeclared&&!Y.additionalProperties)Y.additionalProperties=!1;return Y}}var ZZ={},BQ=(Y)=>{let Z="";for(let X=0;X<Y.defaultable.length;X++)Z+=Y.defaultable[X].defaultValueMorphRef;if(Y.sequence?.defaultValueMorphsReference)Z+=Y.sequence?.defaultValueMorphsReference;if(Y.undeclared==="delete"){if(Z+="delete !(",Y.required)for(let X of Y.required)Z+=X.compiledKey+" | ";if(Y.optional)for(let X of Y.optional)Z+=X.compiledKey+" | ";if(Y.index)for(let X of Y.index)Z+=X.signature.id+" | ";if(Y.sequence)if(Y.sequence.maxLength===null)Z+=d.nonNegativeIntegerString.id;else for(let X=0;X<Y.sequence.tuple.length;X++)Z+=X+" | ";Z+=")"}return Z},CQ=(Y)=>{let Z=BQ(Y);if(!Z)return;if(ZZ[Z])return ZZ[Z];let X=(_,G)=>{for(let W=0;W<Y.defaultable.length;W++)if(!(Y.defaultable[W].key in _))Y.defaultable[W].defaultValueMorph(_,G);if(Y.sequence?.defaultables)for(let W=_.length-Y.sequence.prefixLength;W<Y.sequence.defaultables.length;W++)Y.sequence.defaultValueMorphs[W](_,G);if(Y.undeclared==="delete"){for(let W in _)if(!Y.declaresKey(W))delete _[W]}return _};return ZZ[Z]=X},TQ=(Y,Z)=>{let _=`(data${Z.defaultable.some((G)=>G.defaultValueMorph.length===2)||Z.sequence?.defaultValueMorphs.some((G)=>G.length===2)?", ctx":""})`;return Y.block(`${_} => `,(G)=>{for(let W=0;W<Z.defaultable.length;W++){let{serializedKey:$,defaultValueMorphRef:H}=Z.defaultable[W];G.if(`!(${$} in data)`,(Q)=>Q.line(`${H}${_}`))}if(Z.sequence?.defaultables)G.for(`i < ${Z.sequence.defaultables.length}`,(W)=>W.set("data[i]",5),`data.length - ${Z.sequence.prefixLength}`);if(Z.undeclared==="delete")G.forIn("data",(W)=>W.if(`!(${Z._compileDeclaresKey(W)})`,($)=>$.line("delete data[k]")));return G.return("data")})},XZ={implementation:IQ,Node:m_},KQ=(Y)=>{if(y(Y,"root")&&Y.hasKind("unit"))Y=Y.unit;if(typeof Y==="number")Y=`${Y}`;return Y},qQ=(Y,Z)=>`${Y} is not allowed as an array index on ${Z}. Use the 'nonNegativeIntegerString' keyword instead.`,e2=(Y,Z,X)=>{let[_,G]=zX(Y.branches,($)=>$.hasKind("unit"));if(!_.length)return{index:X.node("index",{signature:Y,value:Z})};let W={};for(let $ of _){let H=X.node("required",{key:$.unit,value:Z});W[H.kind]=Z0(W[H.kind],H)}if(G.length)W.index=X.node("index",{signature:G,value:Z});return W},jQ=(Y)=>y(Y,"root")?Y.expression:n(Y),y_=(Y,Z)=>`Key${Z.length===1?"":"s"} ${Z.map(jQ).join(", ")} ${Z.length===1?"does":"do"} not exist on ${Y}`;var G8={...U_,alias:e8.implementation,domain:t2.implementation,unit:sY.implementation,proto:Y2.implementation,union:rY.implementation,morph:oY.implementation,intersection:iY.implementation,divisor:vY.implementation,pattern:pY.implementation,predicate:SY.implementation,required:tY.implementation,optional:s8.implementation,index:aY.implementation,sequence:eY.implementation,structure:XZ.implementation};B.defaultConfig=AX(Object.assign(o(G8,(Y,Z)=>[Y,Z.defaults]),{jitless:CX(),clone:NX,onUndeclaredKey:"ignore",exactOptionalPropertyTypes:!0,numberAllowsNaN:!1,dateAllowsInvalid:!1,onFail:null,keywords:{},toJsonSchema:N0.defaultConfig}));B.resolvedConfig=d8(B.defaultConfig,B.config);var V_={...F_,alias:e8.Node,domain:t2.Node,unit:sY.Node,proto:Y2.Node,union:rY.Node,morph:oY.Node,intersection:iY.Node,divisor:vY.Node,pattern:pY.Node,predicate:SY.Node,required:tY.Node,optional:s8.Node,index:aY.Node,sequence:eY.Node,structure:XZ.Node};class H8 extends FY{get[X1](){return"module"}}var _Z=(Y,Z)=>new H8(o(Y,(X,_)=>[X,y(_,"module")?_Z(_,Z):Z.bindReference(_)]));var PQ=(Y)=>O0(Y)?Y:("branches"in Y)&&O0(Y.branches)?Y.branches:void 0,SQ=(Y,Z)=>w(`Node of kind ${Z} is not valid as a ${Y} definition`),u_=(Y)=>`#${Y} duplicates public alias ${Y}`,GZ={};B.ambient??={};var d_,l_="function $",vQ=(Y)=>i_(Y,o_(Y)),i_=(Y,Z)=>{let X=Z.write(l_,4),_=Z.compile()();for(let G of Y){if(G.precompilation)continue;if(G.traverseAllows=_[`${G.id}Allows`].bind(_),G.isRoot()&&!G.allowsRequiresContext)G.allows=G.traverseAllows;if(G.traverseApply=_[`${G.id}Apply`].bind(_),_[`${G.id}Optimistic`])G.traverseOptimistic=_[`${G.id}Optimistic`].bind(_);G.precompilation=X}},o_=(Y)=>new m2().return(Y.reduce((Z,X)=>{let _=new u8({kind:"Allows"}).indent();X.compile(_);let G=_.write(`${X.id}Allows`),W=new u8({kind:"Apply"}).indent();X.compile(W);let $=W.write(`${X.id}Apply`),H=`${Z}${G},
44
+ ${$},
45
+ `;if(!X.hasKind("union"))return H;let Q=new u8({kind:"Allows",optimistic:!0}).indent();X.compile(Q);let J=Q.write(`${X.id}Optimistic`);return`${H}${J},
46
46
  `},`{
47
- `)+"}");class YY{config;resolvedConfig;name;get[X1](){return"scope"}referencesById={};references=[];resolutions={};exportedNames=[];aliases={};resolved=!1;nodesByHash={};intrinsic;constructor(Y,Z){if(this.config=u8(B.config,Z),this.resolvedConfig=u8(B.resolvedConfig,Z),this.name=this.resolvedConfig.name??`anonymousScope${Object.keys(_5).length}`,this.name in _5)w(`A Scope already named ${this.name} already exists`);_5[this.name]=this;let X=Object.entries(Y).map((_)=>this.preparseOwnAliasEntry(..._));for(let[_,G]of X){let W=_;if(_[0]==="#"){if(W=_.slice(1),W in this.aliases)w(uG(W));this.aliases[W]=G}else{if(W in this.aliases)w(uG(_));this.aliases[W]=G,this.exportedNames.push(W)}if(!y(G,"module")&&!y(G,"generic")&&!O4(G)){let H=this.preparseOwnDefinitionFormat(G,{alias:W});this.resolutions[W]=y(H,"root")?this.bindReference(H):this.createParseContext(H).id}}dG??=this.node("union",{branches:["string","number","object","bigint","symbol",{unit:!0},{unit:!1},{unit:void 0},{unit:null}]},{prereduced:!0}),this.nodesByHash[dG.hash]=this.node("intersection",{},{prereduced:!0}),this.intrinsic=B.intrinsic?o(B.intrinsic,(_,G)=>_.startsWith("json")?[]:[_,this.bindReference(G)]):{}}cacheGetter(Y,Z){return Object.defineProperty(this,Y,{value:Z}),Z}get internal(){return this}_json;get json(){if(!this._json)this.export();return this._json}defineSchema(Y){return Y}generic=(...Y)=>{let Z=this;return(X,_)=>new M4(Y,_?new i6(X):X,Z,Z,_??null)};units=(Y,Z)=>{let X=[];for(let G of Y)if(!X.includes(G))X.push(G);let _=X.map((G)=>this.node("unit",{unit:G},Z));return this.node("union",_,{...Z,prereduced:!0})};lazyResolutions=[];lazilyResolve(Y,Z){let X=this.node("alias",{reference:Z??"synthetic",resolve:Y},{prereduced:!0});if(!this.resolved)this.lazyResolutions.push(X);return X}schema=(Y,Z)=>this.finalize(this.parseSchema(Y,Z));parseSchema=(Y,Z)=>this.node(i8(Y),Y,Z);preparseNode(Y,Z,X){let _=typeof Y==="string"?Y:i8(Z,Y);if(V0(Z)&&Z.kind===_)return Z;if(_==="alias"&&!X?.prereduced){let{reference:H}=t8.implementation.normalize(Z,this);if(H.startsWith("$")){let J=this.resolveRoot(H.slice(1));Z=J,_=J.kind}}else if(_==="union"&&$1(Z,"object")){let H=v$(Z);if(H?.length===1)Z=H[0],_=i8(Z)}if(V0(Z)&&Z.kind===_)return Z;let W=G8[_].normalize?.(Z,this)??Z;if(V0(W))return W.kind===_?W:x$(_,W.kind);return{...X,$:this,kind:_,def:W,prefix:X.alias??_}}bindReference(Y){let Z;if(V0(Y))Z=Y.$===this?Y:new Y.constructor(Y.attachments,this);else Z=Y.$===this?Y:new M4(Y.params,Y.bodyDef,Y.$,this,Y.hkt);if(!this.resolved)Object.assign(this.referencesById,Z.referencesById);return Z}resolveRoot(Y){return this.maybeResolveRoot(Y)??w(H5(Y))}maybeResolveRoot(Y){let Z=this.maybeResolve(Y);if(y(Z,"generic"))return;return Z}maybeResolveSubalias(Y){return G5(this.aliases,Y)??G5(this.ambient,Y)}get ambient(){return B.ambient}maybeResolve(Y){let Z=this.resolutions[Y];if(Z){if(typeof Z!=="string")return this.bindReference(Z);let _=_1[Z];if(y(_,"root"))return this.resolutions[Y]=_;if(y(_,"context")){if(_.phase==="resolving")return this.node("alias",{reference:`$${Y}`},{prereduced:!0});if(_.phase==="resolved")return _0(`Unexpected resolved context for was uncached by its scope: ${n(_)}`);_.phase="resolving";let G=this.bindReference(this.parseOwnDefinitionFormat(_.def,_));return _.phase="resolved",_1[G.id]=G,_1[_.id]=G,this.resolutions[Y]=G}return _0(`Unexpected nodesById entry for ${Z}: ${n(_)}`)}let X=this.aliases[Y]??this.ambient?.[Y];if(!X)return this.maybeResolveSubalias(Y);if(X=this.normalizeRootScopeValue(X),y(X,"generic"))return this.resolutions[Y]=this.bindReference(X);if(y(X,"module")){if(!X.root)w(sG(Y));return this.resolutions[Y]=this.bindReference(X.root)}return this.resolutions[Y]=this.parse(X,{alias:Y})}createParseContext(Y){let Z=Y.id??pZ(Y.prefix);return _1[Z]=Object.assign(Y,{[X1]:"context",$:this,id:Z,phase:"unresolved"})}traversal(Y){return new f1(Y,this.resolvedConfig)}import(...Y){return new J8(o(this.export(...Y),(Z,X)=>[`#${Z}`,X]))}precompilation;_exportedResolutions;_exports;export(...Y){if(!this._exports){this._exports={};for(let X of this.exportedNames){let _=this.aliases[X];this._exports[X]=y(_,"module")?X5(_,this):cG(this.maybeResolve(X))}for(let X of this.lazyResolutions)X.resolution;if(this._exportedResolutions=rG(this,this._exports),this._json=nG(this._exportedResolutions),Object.assign(this.resolutions,this._exportedResolutions),this.references=Object.values(this.referencesById),!this.resolvedConfig.jitless){let X=oG(this.references);this.precompilation=X.write(lG,4),iG(this.references,X)}this.resolved=!0}let Z=Y.length?Y:this.exportedNames;return new J8(o(Z,(X,_)=>[_,this._exports[_]]))}resolve(Y){return this.export()[Y]}node=(Y,Z,X={})=>{let _=this.preparseNode(Y,Z,X);if(V0(_))return this.bindReference(_);let G=this.createParseContext(_),W=mZ(G),H=this.bindReference(W);return _1[G.id]=H};parse=(Y,Z={})=>this.finalize(this.parseDefinition(Y,Z));parseDefinition(Y,Z={}){if(y(Y,"root"))return this.bindReference(Y);let X=this.preparseOwnDefinitionFormat(Y,Z);if(y(X,"root"))return this.bindReference(X);let _=this.createParseContext(X);_1[_.id]=_;let G=this.bindReference(this.parseOwnDefinitionFormat(Y,_));if(G.isCyclic)G=LG(G,_.id);return _1[_.id]=G,G}finalize(Y){if(cG(Y),!Y.precompilation&&!this.resolvedConfig.jitless)h$(Y.references);return Y}}class W5 extends YY{parseOwnDefinitionFormat(Y,Z){return mZ(Z)}preparseOwnDefinitionFormat(Y,Z){return this.preparseNode(i8(Y),Y,Z)}preparseOwnAliasEntry(Y,Z){return[Y,Z]}normalizeRootScopeValue(Y){return Y}}var cG=(Y)=>{let Z=Y.references.filter((X)=>X.hasKind("alias"));for(let X of Z){Object.assign(X.referencesById,X.resolution.referencesById);for(let _ of Y.references)if(X.id in _.referencesById)Object.assign(_.referencesById,X.referencesById)}return Y},nG=(Y)=>o(Y,(Z,X)=>[Z,y(X,"root")||y(X,"generic")?X.json:y(X,"module")?nG(X):_0(`Unexpected resolution ${n(X)}`)]),G5=(Y,Z)=>{let X=Z.indexOf(".");if(X===-1)return;let _=Z.slice(0,X),G=Y[_];if(G===void 0)return;if(!y(G,"module"))return w(f$(_));let W=Z.slice(X+1),H=G[W];if(H===void 0)return G5(G,W);if(y(H,"root")||y(H,"generic"))return H;if(y(H,"module"))return H.root??w(sG(Z));_0(`Unexpected resolution for alias '${Z}': ${n(H)}`)},ZY=(Y,Z)=>new W5(Y,Z),Z6=new W5({});var rG=(Y,Z)=>{let X={};for(let _ in Z){let G=Z[_];if(y(G,"module")){let W=rG(Y,G),H=o(W,(J,$)=>[`${_}.${J}`,$]);Object.assign(X,H)}else if(y(G,"root")||y(G,"generic"))X[_]=G;else _0(`Unexpected scope resolution ${n(G)}`)}return X},H5=(Y)=>`'${Y}' is unresolvable`,f$=(Y)=>`'${Y}' must reference a module to be accessed using dot syntax`,sG=(Y)=>`Reference to submodule '${Y}' must specify an alias`;Z6.export();var{schema:Q0,node:Q8,defineSchema:Pw,generic:K1}=Z6;var J5="^(?:0|[1-9]\\d*)$",b$=new RegExp(J5),xw=K0(b$);var aG=ZY({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();B.intrinsic={...aG};var tG=ZY({integer:{domain:"number",divisor:1},lengthBoundable:["string",Array],key:["string","symbol"],nonNegativeIntegerString:{domain:"string",pattern:J5}},{prereducedAliases:!0}).export();Object.assign(B.intrinsic,tG);var k$=ZY({jsonPrimitive:["string","number",{unit:!0},{unit:!1},{unit:null}],jsonObject:{domain:"object",index:{signature:"string",value:"$jsonData"}},jsonData:["$jsonPrimitive","$jsonObject"]},{prereducedAliases:!0}).export(),d={...aG,...tG,...k$,emptyStructure:Q8("structure",{},{prereduced:!0})};B.intrinsic={...d};var Y9=(Y)=>typeof Y==="string"&&Y[0]==="d"&&(Y[1]==="'"||Y[1]==='"')&&Y.at(-1)===Y[1],eG=(Y)=>Y.toString()!=="Invalid Date",Z9=(Y)=>Y.slice(2,-1),Q5=(Y)=>`'${Y}' could not be parsed by the Date constructor`,X9=(Y,Z)=>g$(Y,Z),g$=(Y,Z)=>{let X=new Date(Y);if(eG(X))return X;let _=h_(Y);if(_!==void 0){let G=new Date(_);if(eG(G))return G}return Z?w(Z===!0?Q5(Y):Z):void 0};var $5=(Y,Z)=>{let X=Y.scanner.shiftUntil(y$[G9[Z]]);if(Y.scanner.lookahead==="")return Y.error(m$(X,Z));if(Y.scanner.shift(),Z==="/"){try{new RegExp(X)}catch(_){w(String(_))}Y.root=Y.ctx.$.node("intersection",{domain:"string",pattern:X},{prereduced:!0})}else if(p0(Z,z5))Y.root=Y.ctx.$.node("unit",{unit:X});else{let _=X9(X,Q5(X));Y.root=Y.ctx.$.node("unit",{meta:X,unit:_})}},z5={"'":1,'"':1},_9={"/":1,"'":1,'"':1},G9={"d'":"'",'d"':'"',"'":"'",'"':'"',"/":"/"},y$={"'":(Y)=>Y.lookahead==="'",'"':(Y)=>Y.lookahead==='"',"/":(Y)=>Y.lookahead==="/"},p$={'"':"double-quote","'":"single-quote","/":"forward slash"},m$=(Y,Z)=>`${Z}${Y} requires a closing ${p$[G9[Z]]}`;var W9=(Y)=>`Private type references should not include '#'. Use '${Y}' instead.`,XY="Optional definitions like 'string?' are only valid as properties in an object or tuple",_Y="Defaultable definitions like 'number = 0' are only valid as properties in an object or tuple";var H9={">":!0,">=":!0},J9={"<":!0,"<=":!0};var $8={"<":">",">":"<","<=":">=",">=":"<=","==":"=="},Q9=(Y)=>`Unmatched )${Y===""?"":` before ${Y}`}`,GY=(Y)=>`Missing ${Y}`,$9=(Y,Z)=>`Left bounds are only valid when paired with right bounds (try ...${Z}${Y})`,WY=(Y)=>`Left-bounded expressions must specify their limits using < or <= (was ${Y})`,z9=(Y,Z,X,_)=>`An expression may have at most one left bound (parsed ${Y}${$8[Z]}, ${X}${$8[_]})`;var F9=(Y,Z,X)=>U9(Y,Z,X,[]),U9=(Y,Z,X,_)=>{let G=X.parseUntilFinalizer();if(_.push(G.root),G.finalizer===">"){if(_.length!==Z.params.length)return X.error(F5(Y,Z.names,_.map((W)=>W.expression)));return _}if(G.finalizer===",")return U9(Y,Z,X,_);return G.error(GY(">"))},F5=(Y,Z,X)=>`${Y}<${Z.join(", ")}> requires exactly ${Z.length} args (got ${X.length}${X.length===0?"":`: ${X.join(", ")}`})`;var U5=(Y)=>{let Z=Y.scanner.shiftUntilNextTerminator();if(Z==="keyof")Y.addPrefix("keyof");else Y.root=d$(Y,Z)},u$=(Y,Z,X)=>{if(X.scanner.shiftUntilNonWhitespace(),X.scanner.shift()!=="<")return X.error(F5(Y,Z.names,[]));let G=F9(Y,Z,X);return Z(...G)},d$=(Y,Z)=>c$(Y,Z)??l$(Y,Z)??Y.error(Z===""?Y.scanner.lookahead==="#"?W9(Y.shiftedByOne().scanner.shiftUntilNextTerminator()):O5(Y):H5(Z)),c$=(Y,Z)=>{if(Y.ctx.args?.[Z]){let _=Y.ctx.args[Z];if(typeof _!=="string")return _;return Y.ctx.$.node("alias",{reference:_},{prereduced:!0})}let X=Y.ctx.$.maybeResolve(Z);if(y(X,"root"))return X;if(X===void 0)return;if(y(X,"generic"))return u$(Z,X,Y);return w(`Unexpected resolution ${n(X)}`)},l$=(Y,Z)=>{let X=f_(Z);if(X!==void 0)return Y.ctx.$.node("unit",{unit:X});let _=k_(Z);if(_!==void 0)return Y.ctx.$.node("unit",{unit:_})},O5=(Y)=>{let Z=Y.previousOperator();return Z?E5(Z,Y.scanner.unscanned):i$(Y.scanner.unscanned)},E5=(Y,Z="")=>`Token '${Y}' requires a right operand${Z?` before '${Z}'`:""}`,i$=(Y)=>`Expected an expression${Y?` before '${Y}'`:""}`;var D5=(Y)=>Y.scanner.lookahead===""?Y.error(O5(Y)):Y.scanner.lookahead==="("?Y.shiftedByOne().reduceGroupOpen():Y.scanner.lookaheadIsIn(_9)?$5(Y,Y.scanner.shift()):Y.scanner.lookaheadIsIn(E4)?D5(Y.shiftedByOne()):Y.scanner.lookahead==="d"?Y.scanner.nextLookahead in z5?$5(Y,`${Y.scanner.shift()}${Y.scanner.shift()}`):U5(Y):U5(Y);class _4 extends wZ{shiftUntilNextTerminator(){return this.shiftUntilNonWhitespace(),this.shiftUntil(()=>(this.lookahead in _4.terminatingChars))}static terminatingChars={"<":1,">":1,"=":1,"|":1,"&":1,")":1,"[":1,"%":1,",":1,":":1,"?":1,"#":1,...E4};static finalizingLookaheads={">":1,",":1,"":1,"=":1,"?":1};static lookaheadIsFinalizing=(Y,Z)=>Y===">"?Z[0]==="="?Z[1]==="=":Z.trimStart()===""||p0(Z.trimStart()[0],_4.terminatingChars):Y==="="?Z[0]!=="=":Y===","||Y==="?"}var E9=(Y,Z)=>{let X=o$(Y,Z);if(Y.root.hasKind("unit")){if(typeof Y.root.unit==="number"){Y.reduceLeftBound(Y.root.unit,X),Y.unsetRoot();return}if(Y.root.unit instanceof Date){let _=`d'${Y.root.description??Y.root.unit.toISOString()}'`;Y.unsetRoot(),Y.reduceLeftBound(_,X);return}}return r$(Y,X)},D9={"<":1,">":1,"=":1},o$=(Y,Z)=>Y.scanner.lookaheadIs("=")?`${Z}${Y.scanner.shift()}`:Z;var O9=(Y,Z,X,_)=>{if(X.extends(B.intrinsic.number)){if(typeof Z!=="number")return w(L5(Y,Z,_));return Y==="=="?["min","max"]:Y[0]===">"?["min"]:["max"]}if(X.extends(B.intrinsic.lengthBoundable)){if(typeof Z!=="number")return w(L5(Y,Z,_));return Y==="=="?["exactLength"]:Y[0]===">"?["minLength"]:["maxLength"]}if(X.extends(B.intrinsic.Date))return Y==="=="?["after","before"]:Y[0]===">"?["after"]:["before"];return w(_G(X.expression))},n$=(Y)=>({rule:Y9(Y.limit)?Z9(Y.limit):Y.limit,exclusive:Y.comparator.length===1}),r$=(Y,Z)=>{let X=Y.unsetRoot(),_=Y.scanner.location;Y.parseOperand();let G=Y.unsetRoot(),W=Y.scanner.sliceChars(_,Y.scanner.location);if(Y.root=X,!G.hasKind("unit")||typeof G.unit!=="number"&&!(G.unit instanceof Date))return Y.error(L5(Z,W,"right"));let H=G.unit,J=Z.length===1,$=O9(Z,typeof H==="number"?H:W,X,"right");for(let z of $)Y.constrainRoot(z,Z==="=="?{rule:H}:{rule:H,exclusive:J});if(!Y.branches.leftBound)return;if(!p0(Z,J9))return Y.error(WY(Z));let Q=O9(Y.branches.leftBound.comparator,Y.branches.leftBound.limit,X,"left");Y.constrainRoot(Q[0],n$(Y.branches.leftBound)),Y.branches.leftBound=null},L5=(Y,Z,X)=>`Comparator ${X==="left"?$8[Y]:Y} must be ${X==="left"?"preceded":"followed"} by a corresponding literal (was ${Z})`;var L9=(Y)=>{Y.scanner.shiftUntilNonWhitespace();let Z=Y.scanner.shiftUntilNextTerminator();Y.root=Y.root.brand(Z)};var M9=(Y)=>{let Z=Y.scanner.shiftUntilNextTerminator(),X=b_(Z,{errorOnFail:V9(Z)});if(X===0)Y.error(V9(0));Y.root=Y.root.constrain("divisor",X)},V9=(Y)=>`% operator must be followed by a non-zero integer literal (was ${Y})`;var V5=(Y)=>{let Z=Y.scanner.shift();return Z===""?Y.finalize(""):Z==="["?Y.scanner.shift()==="]"?Y.setRoot(Y.root.array()):Y.error(s$):Z==="|"?Y.scanner.lookahead===">"?Y.shiftedByOne().pushRootToBranch("|>"):Y.pushRootToBranch(Z):Z==="&"?Y.pushRootToBranch(Z):Z===")"?Y.finalizeGroup():_4.lookaheadIsFinalizing(Z,Y.scanner.unscanned)?Y.finalize(Z):p0(Z,D9)?E9(Y,Z):Z==="%"?M9(Y):Z==="#"?L9(Y):(Z in E4)?V5(Y):Y.error(HY(Z))},HY=(Y,Z="")=>`'${Y}' is not allowed here${Z&&` (should be ${Z})`}`,s$="Missing expected ']'";var A9=(Y)=>{let Z=Y.unsetRoot();Y.parseOperand();let X=Y.unsetRoot();if(!X.hasKind("unit"))return Y.error(a$(X.expression));let _=X.unit instanceof Date?()=>new Date(X.unit):X.unit;return[Z,"=",_]},a$=(Y)=>`Default value '${Y}' must a literal value`;var M5=(Y,Z)=>{let X=Z.$.maybeResolveRoot(Y);if(X)return X;if(Y.endsWith("[]")){let W=Z.$.maybeResolveRoot(Y.slice(0,-2));if(W)return W.array()}let _=new z8(new _4(Y),Z),G=t$(_);if(_.finalizer===">")w(HY(">"));return G},t$=(Y)=>{Y.parseOperand();let Z=X6(Y).root;if(!Z)return _0(`Root was unexpectedly unset after parsing string '${Y.scanner.scanned}'`);if(Y.finalizer==="=")Z=A9(Y);else if(Y.finalizer==="?")Z=[Z,"?"];if(Y.scanner.shiftUntilNonWhitespace(),Y.scanner.lookahead)w(HY(Y.scanner.lookahead));return Z},X6=(Y)=>{while(Y.finalizer===void 0)e$(Y);return Y},e$=(Y)=>Y.hasRoot()?Y.parseOperator():Y.parseOperand();class z8{root;branches={prefixes:[],leftBound:null,intersection:null,union:null,pipe:null};finalizer;groups=[];scanner;ctx;constructor(Y,Z){this.scanner=Y,this.ctx=Z}error(Y){return w(Y)}hasRoot(){return this.root!==void 0}setRoot(Y){this.root=Y}unsetRoot(){let Y=this.root;return this.root=void 0,Y}constrainRoot(...Y){this.root=this.root.constrain(Y[0],Y[1])}finalize(Y){if(this.groups.length)return this.error(GY(")"));this.finalizeBranches(),this.finalizer=Y}reduceLeftBound(Y,Z){let X=$8[Z];if(!p0(X,H9))return this.error(WY(Z));if(this.branches.leftBound)return this.error(z9(this.branches.leftBound.limit,this.branches.leftBound.comparator,Y,X));this.branches.leftBound={comparator:X,limit:Y}}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 Y=this.groups.pop();if(!Y)return this.error(Q9(this.scanner.unscanned));this.branches=Y}addPrefix(Y){this.branches.prefixes.push(Y)}applyPrefixes(){while(this.branches.prefixes.length){let Y=this.branches.prefixes.pop();this.root=Y==="keyof"?this.root.keyof():_0(`Unexpected prefix '${Y}'`)}}pushRootToBranch(Y){this.assertRangeUnset(),this.applyPrefixes();let Z=this.root;if(this.root=void 0,this.branches.intersection=this.branches.intersection?.rawAnd(Z)??Z,Y==="&")return;if(this.branches.union=this.branches.union?.rawOr(this.branches.intersection)??this.branches.intersection,this.branches.intersection=null,Y==="|")return;this.branches.pipe=this.branches.pipe?.rawPipeOnce(this.branches.union)??this.branches.union,this.branches.union=null}parseUntilFinalizer(){return X6(new z8(this.scanner,this.ctx))}parseOperator(){return V5(this)}parseOperand(){return D5(this)}assertRangeUnset(){if(this.branches.leftBound)return this.error($9(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 Yz="An empty string is not a valid generic parameter name",JY=(Y,Z,X)=>{Y.shiftUntilNonWhitespace();let _=Y.shiftUntilNextTerminator();if(_===""){if(Y.lookahead===""&&Z.length)return Z;return w(Yz)}return Y.shiftUntilNonWhitespace(),Zz(Y,_,Z,X)},w9="extends ",Zz=(Y,Z,X,_)=>{if(Y.shiftUntilNonWhitespace(),Y.unscanned.startsWith(w9))Y.jumpForward(w9.length);else{if(Y.lookahead===",")Y.shift();return X.push(Z),JY(Y,X,_)}let G=X6(new z8(Y,_));return X.push([Z,G.root]),JY(Y,X,_)};class A5 extends h1{$;constructor(Y){super((...Z)=>new _6(Y)(...Z),{bind:Y});this.$=Y}in(Y){return new _6(this.$,Y===void 0?void 0:this.$.parse(Y))}at(Y,Z){return new _6(this.$).at(Y,Z)}case(Y,Z){return new _6(this.$).case(Y,Z)}}class _6 extends h1{$;in;key;branches=[];constructor(Y,Z){super((X)=>this.caseEntries(Object.entries(X).map(([_,G])=>_==="default"?[_,G]:[this.$.parse(_),G])));this.$=Y,this.in=Z}at(Y,Z){if(this.key)w(_z);if(this.branches.length)w(Xz);return this.key=Y,Z?this.match(Z):this}case(Y,Z){return this.caseEntry(this.$.parse(Y),Z)}caseEntry(Y,Z){let _=(this.key?this.$.parse({[this.key]:Y}):Y).pipe(Z);return this.branches.push(_),this}match(Y){return this(Y)}strings(Y){return this.caseEntries(Object.entries(Y).map(([Z,X])=>Z==="default"?[Z,X]:[this.$.node("unit",{unit:Z}),X]))}caseEntries(Y){for(let Z=0;Z<Y.length;Z++){let[X,_]=Y[Z];if(X==="default"){if(Z!==Y.length-1)w("default may only be specified as the last key of a switch definition");return this.default(_)}if(typeof _!=="function")return w(`Value for case "${X}" must be a function (was ${y0(_)})`);this.caseEntry(X,_)}return this}default(Y){if(typeof Y==="function")this.case(d.unknown,Y);let Z={branches:this.branches,ordered:!0};if(Y==="never"||Y==="assert")Z.meta={onFail:R9};let X=this.$.node("union",Z);if(!this.in)return this.$.finalize(X);let _=this.in.pipe(X);if(Y==="never"||Y==="assert")_=_.configureReferences({onFail:R9},"self");return this.$.finalize(_)}}var R9=(Y)=>Y.throw(),Xz="A key matcher must be specified before the first case i.e. match.at('foo') or match.in<object>().at('bar')",_z="At most one key matcher may be specified per expression";var QY=(Y,Z)=>{if(O0(Y)){if(Y[1]==="=")return[Z.$.parseOwnDefinitionFormat(Y[0],Z),"=",Y[2]];if(Y[1]==="?")return[Z.$.parseOwnDefinitionFormat(Y[0],Z),"?"]}return $Y(Y,Z)},N9="Only required keys may make their values optional, e.g. { [mySymbol]: ['number', '?'] }",I9="Only required keys may specify default values, e.g. { value: 'number = 0' }";var B9=(Y,Z)=>{let X,_={},G=j4(Y);for(let[H,J]of G){let $=Hz(H);if($.kind==="spread"){if(!c1(_))return w(Wz);let V=Z.$.parseOwnDefinitionFormat(J,Z);if(V.equals(d.object))continue;if(!V.hasKind("intersection")||!V.basis?.equals(d.object))return w(Jz(V.expression));X=V.structure;continue}if($.kind==="undeclared"){if(J!=="reject"&&J!=="delete"&&J!=="ignore")w(Gz(J));_.undeclared=J;continue}let Q=QY(J,Z),z=$;if($.kind==="required"){if(!O0(Q))w5(_,"required",{key:$.normalized,value:Q},Z);else w5(_,"optional",Q[1]==="="?{key:$.normalized,value:Q[0],default:Q[2]}:{key:$.normalized,value:Q[0]},Z);continue}if(O0(Q)){if(Q[1]==="?")w(N9);if(Q[1]==="=")w(I9)}if($.kind==="optional"){w5(_,"optional",{key:$.normalized,value:Q},Z);continue}let O=Z.$.parseOwnDefinitionFormat(z.normalized,Z),D=e6(O,Q,Z.$);if(D.index)_.index=Z0(_.index,D.index);if(D.required)_.required=Z0(_.required,D.required)}let W=Z.$.node("structure",_);return Z.$.parseSchema({domain:"object",structure:X?.merge(W)??W})},w5=(Y,Z,X,_)=>{Y[Z]=Z0(Y[Z],_.$.node(Z,X))},Gz=(Y)=>`Value of '+' key must be 'reject', 'delete', or 'ignore' (was ${n(Y)})`,Wz="Spread operator may only be used as the first key in an object",Hz=(Y)=>typeof Y==="symbol"?{kind:"required",normalized:Y}:Y.at(-1)==="?"?Y.at(-2)===f8?{kind:"required",normalized:`${Y.slice(0,-2)}?`}:{kind:"optional",normalized:Y.slice(0,-1)}:Y[0]==="["&&Y.at(-1)==="]"?{kind:"index",normalized:Y.slice(1,-1)}:Y[0]===f8&&Y[1]==="["&&Y.at(-1)==="]"?{kind:"required",normalized:Y.slice(1)}:Y==="..."?{kind:"spread"}:Y==="+"?{kind:"undeclared"}:{kind:"required",normalized:Y==="\\..."?"...":Y==="\\+"?"+":Y},Jz=(Y)=>`Spread operand must resolve to an object literal type (was ${Y})`;var T9=(Y,Z)=>Vz(Y)?P9[Y[0]](Y,Z):Dz(Y)?j9[Y[1]](Y,Z):null,Qz=(Y,Z)=>Z.$.parseOwnDefinitionFormat(Y[1],Z).keyof(),R5=(Y,Z)=>{if(Y[2]===void 0)return w(E5(Y[1],""));let X=Z.$.parseOwnDefinitionFormat(Y[0],Z),_=Z.$.parseOwnDefinitionFormat(Y[2],Z);if(Y[1]==="|")return Z.$.node("union",{branches:[X,_]});let G=Y[1]==="&"?O1(X,_,Z.$):l8(X,_,Z.$);if(G instanceof S)return G.throw();return G},$z=(Y,Z)=>Z.$.parseOwnDefinitionFormat(Y[0],Z).array(),zz=(Y,Z)=>{if(typeof Y[2]!=="function")return w(K9("=>",Y[2]));return Z.$.parseOwnDefinitionFormat(Y[0],Z).pipe(Y[2])},K9=(Y,Z)=>`${Y===":"?"Narrow":"Morph"} expression requires a function following '${Y}' (was ${typeof Z})`,Fz=(Y,Z)=>{if(typeof Y[2]!=="function")return w(K9(":",Y[2]));return Z.$.parseOwnDefinitionFormat(Y[0],Z).constrain("predicate",Y[2])},Uz=(Y,Z)=>Z.$.parseOwnDefinitionFormat(Y[0],Z).configureReferences(Y[2],"shallow"),q9=(Y)=>Y,Oz=q9({"[]":$z,"?":()=>w(XY)}),Ez=q9({"|":R5,"&":R5,":":Fz,"=>":zz,"|>":R5,"@":Uz,"=":()=>w(_Y)}),j9={...Oz,...Ez},Dz=(Y)=>j9[Y[1]]!==void 0,Lz=(Y)=>Y,P9=Lz({keyof:Qz,instanceof:(Y,Z)=>{if(typeof Y[1]!=="function")return w(C9(x8(Y[1])));let X=Y.slice(1).map((_)=>typeof _==="function"?Z.$.node("proto",{proto:_}):w(C9(x8(_))));return X.length===1?X[0]:Z.$.node("union",{branches:X})},"===":(Y,Z)=>Z.$.units(Y.slice(1))}),Vz=(Y)=>P9[Y[0]]!==void 0,C9=(Y)=>`Expected a constructor following 'instanceof' operator (was ${Y})`;var x9=(Y,Z)=>{let X=[{}],_=0;while(_<Y.length){let G=!1;if(Y[_]==="..."&&_<Y.length-1)G=!0,_++;let W=QY(Y[_],Z),[H,J,$]=!O0(W)?[W]:W;if(_++,G){if(!H.extends(B.intrinsic.Array))return w(wz(H.expression));X=X.flatMap((Q)=>H.distribute((z)=>Az(u6(Q),z)))}else X=X.map((Q)=>{if(J==="?")return h9(Q,H);if(J==="=")return Mz(Q,H,$);return N5(Q,H)})}return Z.$.parseSchema(X.map((G)=>c1(G)?{proto:Array,exactLength:0}:{proto:Array,sequence:G}))},N5=(Y,Z)=>{if(Y.defaultables||Y.optionals)return w(Y.variadic?eZ:Rz);if(Y.variadic)Y.postfix=Z0(Y.postfix,Z);else Y.prefix=Z0(Y.prefix,Z);return Y},h9=(Y,Z)=>{if(Y.variadic)return w(f9);return Y.optionals=Z0(Y.optionals,Z),Y},Mz=(Y,Z,X)=>{if(Y.variadic)return w(f9);if(Y.optionals)return w(Nz);return Y.defaultables=Z0(Y.defaultables,[[Z,X]]),Y},S9=(Y,Z)=>{if(Y.postfix)w(v9);if(Y.variadic){if(!Y.variadic.equals(Z))w(v9)}else Y.variadic=Z.internal;return Y},Az=(Y,Z)=>{let X=Z.select({method:"find",kind:"sequence"});if(!X)return S9(Y,B.intrinsic.unknown);if(X.prefix)for(let _ of X.prefix)N5(Y,_);if(X.optionals)for(let _ of X.optionals)h9(Y,_);if(X.variadic)S9(Y,X.variadic);if(X.postfix)for(let _ of X.postfix)N5(Y,_);return Y},wz=(Y)=>`Spread element must be an array (was ${Y})`,v9="A tuple may have at most one variadic element",Rz="A required element may not follow an optional element",f9="An optional element may not follow a variadic element";var Nz="A defaultable element may not follow an optional element without a default";var Iz={},$Y=(Y,Z)=>{if(typeof Y==="string"){if(Z.args&&Object.keys(Z.args).some((_)=>Y.includes(_)))return M5(Y,Z);let X=Iz[Z.$.name]??={};return X[Y]??=M5(Y,Z)}return $1(Y,"object")?Bz(Y,Z):w(I5(y0(Y)))},Bz=(Y,Z)=>{let X=v8(Y);switch(X){case void 0:if(y(Y,"root"))return Y;return B9(Y,Z);case"Array":return Cz(Y,Z);case"RegExp":return Z.$.node("intersection",{domain:"string",pattern:Y},{prereduced:!0});case"Function":{let _=O4(Y)?Y():Y;if(y(_,"root"))return _;return w(I5("Function"))}default:return w(I5(X??n(Y)))}},Cz=(Y,Z)=>T9(Y,Z)??x9(Y,Z),I5=(Y)=>`Type definitions must be strings or objects (was ${Y})`;class B5 extends h1{constructor(Y){let Z=Object.assign({errors:F1,hkt:a0,$:Y,raw:Y.parse,module:Y.constructor.module,scope:Y.constructor.scope,define:Y.define,match:Y.match,generic:Y.generic,schema:Y.schema,keywords:Y.ambient,unit:Y.unit,enumerated:Y.enumerated,instanceOf:Y.instanceOf,valueOf:Y.valueOf,or:Y.or,and:Y.and,merge:Y.merge,pipe:Y.pipe},Y.ambientAttachments);super((...X)=>{if(X.length===1)return Y.parse(X[0]);if(X.length===2&&typeof X[0]==="string"&&X[0][0]==="<"&&X[0].at(-1)===">"){let _=X[0].slice(1,-1),G=Y.parseGenericParams(_,{});return new M4(G,X[1],Y,Y,null)}return Y.parse(X)},{bind:Y,attach:Z})}}var F8=B;class zY extends YY{get ambientAttachments(){if(!F8.typeAttachments)return;return this.cacheGetter("ambientAttachments",o(F8.typeAttachments,(Y,Z)=>[Y,this.bindReference(Z)]))}preparseOwnAliasEntry(Y,Z){let X=Y.indexOf("<");if(X===-1){if(y(Z,"module")||y(Z,"generic"))return[Y,Z];let W=this.name==="ark"?Y:Y==="root"?this.name:`${this.name}.${Y}`,H=this.resolvedConfig.keywords?.[W];if(H)Z=[Z,"@",H];return[Y,Z]}if(Y.at(-1)!==">")w("'>' must be the last character of a generic declaration in a scope");let _=Y.slice(0,X),G=Y.slice(X+1,-1);return[_,()=>{let W=this.parseGenericParams(G,{alias:_});return YG(W,Z,this)}]}parseGenericParams(Y,Z){return JY(new _4(Y),[],this.createParseContext({...Z,def:Y,prefix:"generic"}))}normalizeRootScopeValue(Y){if(O4(Y)&&!y(Y,"generic"))return Y();return Y}preparseOwnDefinitionFormat(Y,Z){return{...Z,def:Y,prefix:Z.alias??"type"}}parseOwnDefinitionFormat(Y,Z){if(!(Z.alias&&(Z.alias in this.aliases))&&!Z.args)Z.args={this:Z.id};let _=$Y(Y,Z);if(O0(_)){if(_[1]==="=")return w(_Y);if(_[1]==="?")return w(XY)}return _}unit=(Y)=>this.units([Y]);valueOf=(Y)=>this.units(w_(Y));enumerated=(...Y)=>this.units(Y);instanceOf=(Y)=>this.node("proto",{proto:Y},{prereduced:!0});or=(...Y)=>this.schema(Y.map((Z)=>this.parse(Z)));and=(...Y)=>Y.reduce((Z,X)=>Z.and(this.parse(X)),this.intrinsic.unknown);merge=(...Y)=>Y.reduce((Z,X)=>Z.merge(this.parse(X)),this.intrinsic.object);pipe=(...Y)=>this.intrinsic.unknown.pipe(...Y);match=new A5(this);declare=()=>({type:this.type});define(Y){return Y}type=new B5(this);static scope=(Y,Z={})=>new zY(Y,Z);static module=(Y,Z={})=>this.scope(Y,Z).export()}var C5=Object.assign(zY.scope,{define:(Y)=>Y}),Y0=zY;class b9 extends a0{description='merge an object\'s properties onto another like `Merge(User, { isAdmin: "true" })`'}var Tz=K1(["base",d.object],["props",d.object])((Y)=>Y.base.merge(Y.props),b9),k9=Y0.module({Key:d.key,Merge:Tz});class g9 extends a0{}var Kz=K1("element")((Y)=>{let Z=Y.element.exclude(d.Array),X=Z.array();return Z.rawOr(X).pipe(U4).distribute((_)=>_.assertHasKind("morph").declareOut(X),Q0)},g9),y9=Y0.module({root:d.Array,readonly:"root",index:d.nonNegativeIntegerString,liftFrom:Kz},{name:"Array"});var T5=Q0(["string",S4.FileConstructor]),qz=T5.rawOr(T5.array()),p9=Q0({meta:"an object representing parsed form data",domain:"object",index:{signature:"string",value:qz}}),m9=Y0.module({root:["instanceof",FormData],value:T5,parsed:p9,parse:Q0({in:FormData,morphs:(Y)=>{let Z={};for(let[X,_]of Y)if(X in Z){let G=Z[X];if(typeof G==="string"||G instanceof S4.FileConstructor)Z[X]=[G,_];else G.push(_)}else Z[X]=_;return Z},declaredOut:p9})},{name:"FormData"});var u9=Y0.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 jz={Boolean:1,Number:1,String:1},d9=Y0.module({...o({...UZ,...EZ},(Y,Z)=>(Y in jz)?[]:[Y,["instanceof",Z]]),Array:y9,TypedArray:u9,FormData:m9});var Pz=Q0({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"}),Sz=Q0({domain:"number",divisor:1}),FY=Y0.module({root:d.number,integer:Sz,epoch:Pz,safe:Q0({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 I0=(Y,Z,X)=>{let _={domain:"string",pattern:{rule:Y.source,flags:Y.flags,meta:Z}};if(X)_.meta={format:X};return Q8("intersection",_)},c9=I0(b8,"a well-formed integer string"),X7=Y0.module({root:c9,parse:Q0({in:c9,morphs:(Y,Z)=>{let X=Number.parseInt(Y);return Number.isSafeInteger(X)?X:Z.error("an integer in the range Number.MIN_SAFE_INTEGER to Number.MAX_SAFE_INTEGER")},declaredOut:d.integer})},{name:"string.integer"}),vz=I0(/^[\dA-Fa-f]+$/,"hex characters only"),xz=Y0.module({root:I0(/^(?:[\d+/A-Za-z]{4})*(?:[\d+/A-Za-z]{2}==|[\d+/A-Za-z]{3}=)?$/,"base64-encoded"),url:I0(/^(?:[\w-]{4})*(?:[\w-]{2}(?:==|%3D%3D)?|[\w-]{3}(?:=|%3D)?)?$/,"base64url-encoded")},{name:"string.base64"}),l9=I0(/^[A-Z].*$/,"capitalized"),hz=Y0.module({root:Q0({in:"string",morphs:(Y)=>Y.charAt(0).toUpperCase()+Y.slice(1),declaredOut:l9}),preformatted:l9},{name:"string.capitalize"}),fz=(Y)=>{let Z=Y.replaceAll(/[ -]+/g,""),X=0,_,G,W=!1;for(let H=Z.length-1;H>=0;H--){if(_=Z.substring(H,H+1),G=Number.parseInt(_,10),W)G*=2,X+=G>=10?G%10+1:G;else X+=G;W=!W}return!!(X%10===0?Z:!1)},bz=/^(?: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}))$/,kz=Q0({domain:"string",pattern:{meta:"a credit card number",rule:bz.source},predicate:{meta:"a credit card number",predicate:fz}});var gz=/^([+-]?\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 yz=(Y)=>!Number.isNaN(new Date(Y).valueOf()),i9=Q0({domain:"string",predicate:{meta:"a parsable date",predicate:yz}}).assertHasKind("intersection"),o9=X7.root.internal.narrow((Y,Z)=>{let X=Number.parseInt(Y),_=FY.epoch(X);if(_ instanceof F1)return Z.errors.merge(_),!1;return!0}).configure({description:"an integer string representing a safe Unix timestamp"},"self").assertHasKind("intersection"),pz=Y0.module({root:o9,parse:Q0({in:o9,morphs:(Y)=>new Date(Y),declaredOut:d.Date})},{name:"string.date.epoch"}),n9=I0(gz,"an ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) date").internal.assertHasKind("intersection"),mz=Y0.module({root:n9,parse:Q0({in:n9,morphs:(Y)=>new Date(Y),declaredOut:d.Date})},{name:"string.date.iso"}),uz=Y0.module({root:i9,parse:Q0({declaredIn:i9,in:"string",morphs:(Y,Z)=>{let X=new Date(Y);if(Number.isNaN(X.valueOf()))return Z.error("a parsable date");return X},declaredOut:d.Date}),iso:mz,epoch:pz},{name:"string.date"}),dz=I0(/^[\w%+.-]+@[\d.A-Za-z-]+\.[A-Za-z]{2,}$/,"an email address","email"),r9="(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])",A4=`(${r9}[.]){3}${r9}`,cz=new RegExp(`^${A4}$`),v0="(?:[0-9a-fA-F]{1,4})",lz=new RegExp(`^((?:${v0}:){7}(?:${v0}|:)|(?:${v0}:){6}(?:${A4}|:${v0}|:)|(?:${v0}:){5}(?::${A4}|(:${v0}){1,2}|:)|(?:${v0}:){4}(?:(:${v0}){0,1}:${A4}|(:${v0}){1,3}|:)|(?:${v0}:){3}(?:(:${v0}){0,2}:${A4}|(:${v0}){1,4}|:)|(?:${v0}:){2}(?:(:${v0}){0,3}:${A4}|(:${v0}){1,5}|:)|(?:${v0}:){1}(?:(:${v0}){0,4}:${A4}|(:${v0}){1,6}|:)|(?::((?::${v0}){0,5}:${A4}|(?::${v0}){1,7}|:)))(%[0-9a-zA-Z.]{1,})?$`),iz=Y0.module({root:["v4 | v6","@","an IP address"],v4:I0(cz,"an IPv4 address","ipv4"),v6:I0(lz,"an IPv6 address","ipv6")},{name:"string.ip"}),U8="a JSON string",_7=(Y)=>{if(!(Y instanceof SyntaxError))throw Y;return`must be ${U8} (${Y})`},oz=Q0({meta:U8,domain:"string",predicate:{meta:U8,predicate:(Y,Z)=>{try{return JSON.parse(Y),!0}catch(X){return Z.reject({code:"predicate",expected:U8,problem:_7(X)})}}}}),nz=(Y,Z)=>{if(Y.length===0)return Z.error({code:"predicate",expected:U8,actual:"empty"});try{return JSON.parse(Y)}catch(X){return Z.error({code:"predicate",expected:U8,problem:_7(X)})}},rz=Y0.module({root:oz,parse:Q0({meta:"safe JSON string parser",in:"string",morphs:nz,declaredOut:d.jsonObject})},{name:"string.json"}),s9=I0(/^[a-z]*$/,"only lowercase letters"),sz=Y0.module({root:Q0({in:"string",morphs:(Y)=>Y.toLowerCase(),declaredOut:s9}),preformatted:s9},{name:"string.lower"}),G7=["NFC","NFD","NFKC","NFKD"],G6=o(G7,(Y,Z)=>[Z,Q0({domain:"string",predicate:(X)=>X.normalize(Z)===X,meta:`${Z}-normalized unicode`})]),UY=o(G7,(Y,Z)=>[Z,Q0({in:"string",morphs:(X)=>X.normalize(Z),declaredOut:G6[Z]})]),az=Y0.module({root:UY.NFC,preformatted:G6.NFC},{name:"string.normalize.NFC"}),tz=Y0.module({root:UY.NFD,preformatted:G6.NFD},{name:"string.normalize.NFD"}),ez=Y0.module({root:UY.NFKC,preformatted:G6.NFKC},{name:"string.normalize.NFKC"}),YF=Y0.module({root:UY.NFKD,preformatted:G6.NFKD},{name:"string.normalize.NFKD"}),ZF=Y0.module({root:"NFC",NFC:az,NFD:tz,NFKC:ez,NFKD:YF},{name:"string.normalize"}),a9=I0(y6,"a well-formed numeric string"),XF=Y0.module({root:a9,parse:Q0({in:a9,morphs:(Y)=>Number.parseFloat(Y),declaredOut:d.number})},{name:"string.numeric"}),t9="a regex pattern",_F=Q0({domain:"string",predicate:{meta:t9,predicate:(Y,Z)=>{try{return new RegExp(Y),!0}catch(X){return Z.reject({code:"predicate",expected:t9,problem:String(X)})}}},meta:{format:"regex"}}),GF=/^(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-]+)*))?$/,WF=I0(GF,"a semantic version (see https://semver.org/)"),e9=I0(/^\S.*\S$|^\S?$/,"trimmed"),HF=Y0.module({root:Q0({in:"string",morphs:(Y)=>Y.trim(),declaredOut:e9}),preformatted:e9},{name:"string.trim"}),Y7=I0(/^[A-Z]*$/,"only uppercase letters"),JF=Y0.module({root:Q0({in:"string",morphs:(Y)=>Y.toUpperCase(),declaredOut:Y7}),preformatted:Y7},{name:"string.upper"}),QF=(Y)=>{if(URL.canParse)return URL.canParse(Y);try{return new URL(Y),!0}catch{return!1}},Z7=Q0({domain:"string",predicate:{meta:"a URL string",predicate:QF},meta:{format:"uri"}}),$F=Y0.module({root:Z7,parse:Q0({declaredIn:Z7,in:"string",morphs:(Y,Z)=>{try{return new URL(Y)}catch{return Z.error("a URL string")}},declaredOut:Q0(URL)})},{name:"string.url"}),zF=Y0.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:I0(/^[\da-f]{8}-[\da-f]{4}-1[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv1"),v2:I0(/^[\da-f]{8}-[\da-f]{4}-2[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv2"),v3:I0(/^[\da-f]{8}-[\da-f]{4}-3[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv3"),v4:I0(/^[\da-f]{8}-[\da-f]{4}-4[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv4"),v5:I0(/^[\da-f]{8}-[\da-f]{4}-5[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv5"),v6:I0(/^[\da-f]{8}-[\da-f]{4}-6[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv6"),v7:I0(/^[\da-f]{8}-[\da-f]{4}-7[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv7"),v8:I0(/^[\da-f]{8}-[\da-f]{4}-8[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv8")},{name:"string.uuid"}),W7=Y0.module({root:d.string,alpha:I0(/^[A-Za-z]*$/,"only letters"),alphanumeric:I0(/^[\dA-Za-z]*$/,"only letters and digits 0-9"),hex:vz,base64:xz,capitalize:hz,creditCard:kz,date:uz,digits:I0(/^\d*$/,"only digits 0-9"),email:dz,integer:X7,ip:iz,json:rz,lower:sz,normalize:ZF,numeric:XF,regex:_F,semver:WF,trim:HF,upper:JF,url:$F,uuid:zF},{name:"string"});var H7=Y0.module({bigint:d.bigint,boolean:d.boolean,false:d.false,never:d.never,null:d.null,number:d.number,object:d.object,string:d.string,symbol:d.symbol,true:d.true,unknown:d.unknown,undefined:d.undefined}),J7=Y0.module({root:d.unknown,any:d.unknown},{name:"unknown"}),FF=Y0.module({root:d.jsonObject,stringify:Q8("morph",{in:d.jsonObject,morphs:(Y)=>JSON.stringify(Y),declaredOut:d.string})},{name:"object.json"}),Q7=Y0.module({root:d.object,json:FF},{name:"object"});class $7 extends a0{description='instantiate an object from an index signature and corresponding value type like `Record("string", "number")`'}var UF=K1(["K",d.key],"V")((Y)=>({domain:"object",index:{signature:Y.K,value:Y.V}}),$7);class z7 extends a0{description='pick a set of properties from an object like `Pick(User, "name | age")`'}var OF=K1(["T",d.object],["K",d.key])((Y)=>Y.T.pick(Y.K),z7);class F7 extends a0{description='omit a set of properties from an object like `Omit(User, "age")`'}var EF=K1(["T",d.object],["K",d.key])((Y)=>Y.T.omit(Y.K),F7);class U7 extends a0{description="make all named properties of an object optional like `Partial(User)`"}var DF=K1(["T",d.object])((Y)=>Y.T.partial(),U7);class O7 extends a0{description="make all named properties of an object required like `Required(User)`"}var LF=K1(["T",d.object])((Y)=>Y.T.required(),O7);class E7 extends a0{description='exclude branches of a union like `Exclude("boolean", "true")`'}var VF=K1("T","U")((Y)=>Y.T.exclude(Y.U),E7);class D7 extends a0{description='extract branches of a union like `Extract("0 | false | 1", "number")`'}var MF=K1("T","U")((Y)=>Y.T.extract(Y.U),D7),L7=Y0.module({Exclude:VF,Extract:MF,Omit:EF,Partial:DF,Pick:OF,Record:UF,Required:LF});var w4=C5({...H7,...L7,...d9,...k9,string:W7,number:FY,object:Q7,unknown:J7},{prereducedAliases:!0,name:"ark"}),m0=w4.export();Object.assign(F8.ambient,m0);F8.typeAttachments={string:m0.string.root,number:m0.number.root,bigint:m0.bigint,boolean:m0.boolean,symbol:m0.symbol,undefined:m0.undefined,null:m0.null,object:m0.object.root,unknown:m0.unknown.root,false:m0.false,true:m0.true,never:m0.never,arrayIndex:m0.Array.index,Key:m0.Key,Record:m0.Record,Array:m0.Array.root,Date:m0.Date};var E1=Object.assign(w4.type,F8.typeAttachments),AF=w4.match,wF=w4.generic,ZB=w4.schema,RF=w4.define,NF=w4.declare;var V7=(Y,Z,X=x0.STORE)=>{return K5(X,{key:`${Y.key}:JSON`,get:({get:_})=>Z.toJson(_(Y)),set:({set:_},G)=>{_(Y,Z.fromJson(G))}})};function M7(Y,Z,X){return OY(Y,{key:`${Z.key}:JSON`,get:(G)=>({get:W})=>{let H=W(Z,G);return X.toJson(H)},set:(G)=>({set:W},H)=>{W(Z,G,X.fromJson(H))}},["mutable","json"])}var G1=(Y)=>JSON.parse(Y),z0=(Y)=>JSON.stringify(Y),MB=[Array.prototype,Boolean.prototype,Number.prototype,Object.prototype,String.prototype];function O8(Y){return T7(x0.STORE,Y)}function W6(Y){return N7(x0.STORE,Y)}function j5(...Y){if(Y.length===2)return k1(x0.STORE,...Y);return k1(x0.STORE,...Y)}function EY(Y,Z){return K7(x0.STORE,Y,Z)}function A7(Y){return j7(Y,x0.STORE)}var q5=(Y)=>(Z,X,_,G,...W)=>{console[Y](`${Z} ${X} "${_}" ${G}`,...W)},IF={error:q5("error"),info:q5("info"),warn:q5("warn")},w7=class{logLevel;filter;logger;constructor(Y,Z,X=IF){this.logLevel=Y,this.filter=Z,this.logger=X}error=(...Y)=>{let Z=this.filter?.(...Y)??!0;if(this.logLevel!==null){if(Z===!0)this.logger.error(...Y);else if(Z!==!1)this.logger.error(...Z)}};info=(...Y)=>{let Z=this.filter?.(...Y)??!0;if(this.logLevel==="info"){if(Z===!0)this.logger.info(...Y);else if(Z!==!1)this.logger.info(...Z)}};warn=(...Y)=>{let Z=this.filter?.(...Y)??!0;if(this.logLevel!=="error"&&this.logLevel!==null){if(Z===!0)this.logger.warn(...Y);else if(Z!==!1)this.logger.warn(...Z)}}};var BF=class{store;constructor(Y=x0.STORE){this.store=Y,I7("root",Y)}allocate(Y,Z,X){return D8(this.store,Y,Z,X)}fuse(Y,Z,X){return B7(this.store,Y,Z,X)}deallocate(Y){L8(this.store,Y)}claim(Y,Z,X){return J6(this.store,Y,Z,X)}},R7=class{store;realm;constructor(Y=x0.STORE){this.store=Y,this.realm=new BF(Y)}allocate(Y,Z,X){D8(this.store,Y,Z,X)}deallocate(Y){L8(this.store,Y)}claim(Y,Z,X){J6(this.store,Y,Z,X)}};function DY(Y){return x5(x0.STORE,Y)}function H6(Y){return v5(x0.STORE,Y)}var D1=class Y extends Set{mode="record";subject=new J0;cacheLimit=0;cache=[];cacheIdx=-1;cacheUpdateNumber=-1;constructor(Z,X=0){super(Z);if(Z instanceof Y)this.parent=Z,this.cacheUpdateNumber=Z.cacheUpdateNumber;if(X)this.cacheLimit=X,this.cache=new Array(X),this.subscribe("auto cache",(_)=>{this.cacheIdx++,this.cacheIdx%=this.cacheLimit,this.cache[this.cacheIdx]=_})}toJSON(){return{members:[...this],cache:this.cache,cacheLimit:this.cacheLimit,cacheIdx:this.cacheIdx,cacheUpdateNumber:this.cacheUpdateNumber}}static fromJSON(Z){let X=new Y(Z.members,Z.cacheLimit);return X.cache=Z.cache,X.cacheIdx=Z.cacheIdx,X.cacheUpdateNumber=Z.cacheUpdateNumber,X}add(Z){let X=super.add(Z);if(this.mode==="record")this.cacheUpdateNumber++,this.emit(`add:${z0(Z)}`);return X}clear(){let Z=this.mode==="record"?[...this]:null;if(super.clear(),Z)this.cacheUpdateNumber++,this.emit(`clear:${JSON.stringify(Z)}`)}delete(Z){let X=super.delete(Z);if(this.mode==="record")this.cacheUpdateNumber++,this.emit(`del:${z0(Z)}`);return X}parent=null;child=null;transactionUpdates=null;transaction(Z){this.mode="transaction",this.transactionUpdates=[],this.child=new Y(this);let X=this.child._subscribe("transaction",(_)=>{this.transactionUpdates?.push(_)});try{if(Z(this.child)){for(let G of this.transactionUpdates)this.doStep(G);this.cacheUpdateNumber++,this.emit(`tx:${this.transactionUpdates.join(";")}`)}}catch(_){throw console.warn("Did not apply transaction to SetRTX; this error was thrown:",_),_}finally{X(),this.child=null,this.transactionUpdates=null,this.mode="record"}}_subscribe(Z,X){return this.subject.subscribe(Z,X)}subscribe(Z,X){return this.subject.subscribe(Z,(_)=>{X(`${this.cacheUpdateNumber}=${_}`)})}emit(Z){this.subject.next(Z)}doStep(Z){let X=Z.indexOf(":"),_=Z.substring(0,X),G=Z.substring(X+1);switch(_){case"add":this.add(JSON.parse(G));break;case"clear":this.clear();break;case"del":this.delete(JSON.parse(G));break;case"tx":for(let W of G.split(";"))this.doStep(W)}}getUpdateNumber(Z){let X=Z.indexOf("=");return Number(Z.substring(0,X))}do(Z){let X=Z.indexOf("="),_=Number(Z.substring(0,X)),G=_-this.cacheUpdateNumber;if(G>0){if(G===1){this.mode="playback";let H=Z.substring(X+1);return this.doStep(H),this.mode="record",this.cacheUpdateNumber=_,null}return this.cacheUpdateNumber+1}if(Math.abs(G)<this.cacheLimit){let H=this.cacheIdx+G;if(this.cache[H]===Z)return null;this.mode="playback";let $=!1;while(!$){this.cacheIdx%=this.cacheLimit;let z=this.cache[this.cacheIdx];if(this.cacheIdx--,!z)return"OUT_OF_RANGE";this.undo(z),$=this.cacheIdx===H-1}let Q=Z.substring(X+1);return this.doStep(Q),this.mode="record",this.cacheUpdateNumber=_,null}return"OUT_OF_RANGE"}undoStep(Z){let X=Z.indexOf(":"),_=Z.substring(0,X),G=Z.substring(X+1);switch(_){case"add":this.delete(JSON.parse(G));break;case"del":this.add(JSON.parse(G));break;case"clear":{let W=JSON.parse(G);for(let H of W)this.add(H);break}case"tx":{let W=G.split(";");for(let H=W.length-1;H>=0;H--)this.undoStep(W[H])}}}undo(Z){let X=Z.indexOf("=");if(Number(Z.substring(0,X))===this.cacheUpdateNumber){this.mode="playback";let G=Z.substring(X+1);return this.undoStep(G),this.mode="record",this.cacheUpdateNumber--,null}return this.cacheUpdateNumber}};function P5(Y=Math.random){return Y().toString(36).slice(2)}function i(Y){while(Y.child!==null)Y=Y.child;return Y}var TF=class Y{_buffer;_index=0;constructor(Z){let X;if(typeof Z==="number")X=Z;else X=Z.length;this._buffer=Array.from({length:X})}get buffer(){return this._buffer}get index(){return this._index}add(Z){this._buffer[this._index]=Z,this._index=(this._index+1)%this._buffer.length}copy(){let Z=new Y([...this._buffer]);return Z._index=this._index,Z}},KF={atom_family:"atom",molecule_family:"molecule",mutable_atom_family:"mutable_atom",readonly_held_selector_family:"readonly_held_selector",readonly_pure_selector_family:"readonly_pure_selector",writable_held_selector_family:"writable_held_selector",writable_pure_selector_family:"writable_pure_selector"};function qF(Y,Z){let X=z0(Z),_=`${Y.key}(${X})`,G=KF[Y.type],W={key:_,type:G};return Object.assign(W,{family:{key:Y.key,subKey:X}}),Object.assign(W,{counterfeit:!0}),W}function G4(Y){let Z={key:Y.key,type:Y.type};if("family"in Y)Z.family=Y.family;return Z}var W1=class{a;b;cardinality;relations=new Map;contents=new Map;isAType;isBType;isContent;makeContentKey=(Y,Z)=>`${Y}:${Z}`;warn;getRelatedKeys(Y){return this.relations.get(Y)}addRelation(Y,Z){let X=this.relations.get(Y),_=this.relations.get(Z);if(X)X.add(Z);else X=new Set([Z]),this.relations.set(Y,X);if(_)_.add(Y);else _=new Set([Y]),this.relations.set(Z,_)}deleteRelation(Y,Z){let X=this.relations.get(Y);if(X){if(X.delete(Z),X.size===0)this.relations.delete(Y);let _=this.relations.get(Z);if(_){if(_.delete(Y),_.size===0)this.relations.delete(Z)}}}replaceRelationsUnsafely(Y,Z){this.relations.set(Y,new Set(Z));for(let X of Z){let _=new Set().add(Y);this.relations.set(X,_)}}replaceRelationsSafely(Y,Z){let X=this.relations.get(Y),_=this.isAType?.(Y)?Y:void 0,G=_===void 0?Y:void 0;if(X)for(let W of X){_??=W,G??=W;let H=this.relations.get(W);if(H){if(H.size===1)this.relations.delete(W);else H.delete(Y);this.contents.delete(this.makeContentKey(_,G))}}this.relations.set(Y,new Set(Z));for(let W of Z){let H=this.relations.get(W);if(H)H.add(Y);else H=new Set().add(Y),this.relations.set(W,H)}}getContentInternal(Y){return this.contents.get(Y)}setContent(Y,Z){this.contents.set(Y,Z)}deleteContent(Y){this.contents.delete(Y)}constructor(Y,Z){if(this.a=Y.between[0],this.b=Y.between[1],this.cardinality=Y.cardinality,!Z?.externalStore)this.relations=new Map(Y.relations?.map(([X,_])=>[X,new Set(_)])),this.contents=new Map(Y.contents);if(this.isAType=Z?.isAType??null,this.isBType=Z?.isBType??null,this.isContent=Z?.isContent??null,Z?.makeContentKey)this.makeContentKey=Z.makeContentKey;if(Z?.externalStore){let X=Z.externalStore;if(this.has=(_,G)=>X.has(_,G),this.addRelation=(_,G)=>{X.addRelation(_,G)},this.deleteRelation=(_,G)=>{X.deleteRelation(_,G)},this.replaceRelationsSafely=(_,G)=>{X.replaceRelationsSafely(_,G)},this.replaceRelationsUnsafely=(_,G)=>{X.replaceRelationsUnsafely(_,G)},this.getRelatedKeys=(_)=>X.getRelatedKeys(_),X.getContent)this.getContentInternal=(_)=>{return X.getContent(_)},this.setContent=(_,G)=>{X.setContent(_,G)},this.deleteContent=(_)=>{X.deleteContent(_)};for(let[_,G]of Y.relations??[]){let W=this.isAType?.(_)?_:void 0,H=W===void 0?_:void 0;for(let J of G)W??=J,H??=J,this.addRelation(W,H)}for(let[_,G]of Y.contents??[])this.setContent(_,G)}if(Z?.warn)this.warn=Z.warn}toJSON(){return{between:[this.a,this.b],cardinality:this.cardinality,relations:[...this.relations.entries()].map(([Y,Z])=>[Y,[...Z]]),contents:[...this.contents.entries()]}}set(...Y){let Z,X,_;switch(Y.length){case 1:{let G=Y[0];Z=G[this.a],X=G[this.b],_=void 0;break}case 2:{let G=Y[0];if(typeof G==="string")[Z,X]=Y;else Z=G[this.a],X=G[this.b],_=Y[1];break}default:Z=Y[0],X=Y[1],_=Y[2];break}switch(this.cardinality){case"1:1":{let G=this.getRelatedKey(Z);if(G&&G!==X)this.delete(Z,G)}case"1:n":{let G=this.getRelatedKey(X);if(G&&G!==Z)this.delete(G,X)}break;case"n:n":}if(_){let G=this.makeContentKey(Z,X);this.setContent(G,_)}return this.addRelation(Z,X),this}delete(Y,Z){Z=typeof Z==="string"?Z:Y[this.b];let X=typeof Y==="string"?Y:Y[this.a];if(X===void 0&&typeof Z==="string"){let _=this.getRelatedKeys(Z);if(_)for(let G of _)this.delete(G,Z)}if(typeof X==="string"&&Z===void 0){let _=this.getRelatedKeys(X);if(_)for(let G of _)this.delete(X,G)}if(typeof X==="string"&&typeof Z==="string"){this.deleteRelation(X,Z);let _=this.makeContentKey(X,Z);this.deleteContent(_)}return this}getRelatedKey(Y){let Z=this.getRelatedKeys(Y);if(Z){if(Z.size>1)this.warn?.(`${Z.size} related keys were found for key "${Y}": (${[...Z].map((_)=>`"${_}"`).join(", ")}). Only one related key was expected.`);let X;for(let _ of Z){X=_;break}return X}}replaceRelations(Y,Z,X){let _=!Array.isArray(Z),G=_?Object.keys(Z):Z;if(X?.reckless)this.replaceRelationsUnsafely(Y,G);else this.replaceRelationsSafely(Y,G);if(_)for(let W of G){let H=this.makeContentKey(Y,W),J=Z[W];this.setContent(H,J)}return this}getContent(Y,Z){let X=this.makeContentKey(Y,Z);return this.getContentInternal(X)}getRelationEntries(Y){let Z=Y[this.a],X=Y[this.b];if(Z!==void 0&&X===void 0){let _=this.getRelatedKeys(Z);if(_)return[..._].map((G)=>{return[G,this.getContent(Z,G)]})}if(Z===void 0&&X!==void 0){let _=this.getRelatedKeys(X);if(_)return[..._].map((G)=>{return[G,this.getContent(G,X)]})}return[]}has(Y,Z){if(Z)return this.getRelatedKeys(Y)?.has(Z)??!1;return this.relations.has(Y)}},J0=class{Subscriber;subscribers=new Map;subscribe(Y,Z){return this.subscribers.set(Y,Z),()=>{this.unsubscribe(Y)}}unsubscribe(Y){this.subscribers.delete(Y)}next(Y){let Z=this.subscribers.values();for(let X of Z)X(Y)}},jF=class extends J0{state;constructor(Y){super();this.state=Y}next(Y){this.state=Y,super.next(Y)}},PF=(Y,Z)=>{let X=i(Y);if(X.operation.open)return X.operation.prev.get(Z.key);return X.valueMap.get(Z.key)};var h5=class extends Promise{fate;resolve;reject;done=!1;constructor(Y){let Z,X;super((_,G)=>{Z=_,X=G});this.resolve=Z,this.reject=X,this.use(Y instanceof Promise?Y:new Promise(Y))}pass(Y,Z){if(Y===this.fate)this.resolve(Z),this.done=!0}fail(Y,Z){if(Y===this.fate)this.reject(Z),this.done=!0}use(Y){if(this===Y)return;if(Y instanceof Promise){let Z=Y;this.fate=Z,Z.then((X)=>{this.pass(Z,X)},(X)=>{this.fail(Z,X)})}else this.resolve(Y),this.fate=void 0}};function f5(Y,Z,X){let _=X.valueMap.get(Z.key),G=Y.valueMap.get(Z.key);if(_!==G)return G;if(_===void 0)return Z.default();X.logger.info("\uD83D\uDCC3","atom",Z.key,"copying");let W=Z.toJson(_),H=Z.fromJson(W);return Y.valueMap.set(Z.key,H),new d5(Z,X),H}function R4(Y){return"epoch"in Y.transactionMeta}function o0(Y){return"phase"in Y.transactionMeta}var LY=(Y,Z)=>{if(Y.operation.open){let X=performance.now();return Y.logger.info("\u2757",Z.type,Z.key,`deferring setState at T-${X} until setState for "${Y.operation.token.key}" is done`),X}Y.operation={open:!0,done:new Set,prev:new Map,time:Date.now(),token:Z},Y.logger.info("\u2B55",Z.type,Z.key,`operation start in store "${Y.config.name}"${!o0(Y)?"":` ${Y.transactionMeta.phase} "${Y.transactionMeta.update.key}"`}`)},VY=(Y)=>{if(Y.operation.open)Y.logger.info("\uD83D\uDD34",Y.operation.token.type,Y.operation.token.key,`operation done in store "${Y.config.name}"`);Y.operation={open:!1},Y.on.operationClose.next(Y.operation)},f7=(Y,Z)=>{if(!Y.operation.open)return Y.logger.error("\uD83D\uDC1E","unknown",Z,"isDone called outside of an operation. This is probably a bug in AtomIO."),!0;return Y.operation.done.has(Z)},$6=(Y,Z)=>{if(!Y.operation.open){Y.logger.error("\uD83D\uDC1E","unknown",Z,"markDone called outside of an operation. This is probably a bug in AtomIO.");return}Y.operation.done.add(Z)};function b5(Y,Z){let X=i(Y),_=X.selectorAtoms.getRelatedKeys(Z.key);if(X.logger.info("\uD83E\uDDF9",Z.type,Z.key,_?`evicting ${_.size} states downstream:`:"no downstream states",_??"to evict"),_){if(X.operation.open)X.logger.info("\uD83E\uDDF9",Z.type,Z.key,`[ ${[...X.operation.done].join(", ")} ] already done`);for(let G of _){if(f7(X,G))continue;b7(X,G),$6(X,G)}}}function SF(Y,Z){let X=i(Y),_=X.selectorGraph.getRelationEntries({upstreamSelectorKey:Z.key}).filter(([G,{source:W}])=>W===Z.key);for(let[G]of _){if(f7(X,G))continue;b7(X,G),$6(X,G)}}function W4(Y,Z,X,_){let G=Y.valueMap.get(Z);if(G instanceof h5&&!G.done){let W=G;if(X instanceof Promise)return W.use(X),W;return Y.valueMap.set(Z,X),X}if(X instanceof Promise){let W=new h5(X);return Y.valueMap.set(Z,W),W.then(function H(J){if(Y.valueMap.get(Z)===W){W4(Y,Z,J,_);let Q=Y.atoms.get(Z);if(Q)LY(Y,Q),b5(Y,Q),VY(Y);else{let z=Y.writableSelectors.get(Z)??Y.readonlySelectors.get(Z);if(z)LY(Y,z),SF(Y,z),VY(Y)}_.next({newValue:J,oldValue:W})}}).catch((H)=>{Y.logger.error("\uD83D\uDCA5","state",Z,"rejected:",H)}),W}return Y.valueMap.set(Z,X),X}var vF=(Y,Z)=>{Z.logger.info("\uD83D\uDCD6",Y.type,Y.key,"reading cached value");let X=Z.valueMap.get(Y.key);if(Y.type==="mutable_atom"&&o0(Z)){let{parent:_}=Z;X=f5(Z,Y,_)}return X},b7=(Y,Z)=>{let X=Y.valueMap.get(Z);if(X instanceof h5){let _=Y.writableSelectors.get(Z)??Y.readonlySelectors.get(Z);if(_)_.get();return}if(Y.operation.open)Y.operation.prev.set(Z,X);Y.valueMap.delete(Z),Y.logger.info("\uD83D\uDDD1","state",Z,"evicted")},z6=(Y,Z)=>{if(Y.valueMap.has(Z.key))return vF(Z,Y);switch(Z.type){case"readonly_held_selector":case"readonly_pure_selector":case"writable_held_selector":case"writable_pure_selector":return Y.logger.info("\uD83E\uDDEE",Z.type,Z.key,"computing value"),Z.get();case"atom":case"mutable_atom":{let X=Z.default,_;if(X instanceof Function)_=X();else _=X;let G=W4(Y,Z.key,_,Z.subject);return Y.logger.info("\uD83D\uDC81","atom",Z.key,"could not find cached value; using default",_),G}}},S7=(Y,Z,X)=>{return X.subject.subscribe(`${Z.type}:${Z.key}`,(_)=>{Y.logger.info("\uD83D\uDCE2",Z.type,Z.key,"root",X.key,"went",_.oldValue,"->",_.newValue);let G=PF(Y,Z),W=z6(Y,Z);Y.logger.info("\u2728",Z.type,Z.key,"went",G,"->",W),Z.subject.next({newValue:W,oldValue:G})})};function F6(Y,Z,X){let _={key:Z.key,type:"atom_family"},G=Y.families.get(Z.key);if(G)Y.logger.error("\u2757","atom_family",Z.key,`Overwriting an existing ${f4(G)} "${G.key}" in store "${Y.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);let W=new J0,J=Object.assign(($)=>{let Q=z0($),z={key:Z.key,subKey:Q},O=`${Z.key}(${Q})`,D=i(Y),V=Z.default,R={key:O,default:V instanceof Function?()=>V($):V};if(Z.effects)R.effects=Z.effects($);let A=k4(D,R,z);return W.next({type:"state_creation",token:A}),A},_,{subject:W,install:($)=>F6($,Z),internalRoles:X});return Y.families.set(Z.key,J),Y.defaults.set(Z.key,Z.default),_}function N7(Y,Z){if("mutable"in Z)return l5(Y,Z);return F6(Y,Z)}var k5=(Y)=>(Z)=>Y instanceof Function?Y(Z):Y,xF=(Y,Z,X)=>{switch(Z.type){case"mutable_atom":Y.logger.info("\uD83D\uDCE2",Z.type,Z.key,"is now (",X.newValue,") subscribers:",Z.subject.subscribers);break;case"atom":case"writable_pure_selector":case"readonly_pure_selector":case"writable_held_selector":case"readonly_held_selector":Y.logger.info("\uD83D\uDCE2",Z.type,Z.key,"went (",X.oldValue,"->",X.newValue,") subscribers:",Z.subject.subscribers)}Z.subject.next(X)},k7=(Y,Z,X)=>{let _=z6(Y,Z),G=_;if(Z.type==="mutable_atom"&&o0(Y)){let{parent:H}=Y;G=f5(Y,Z,H)}G=k5(X)(G),Y.logger.info("\uD83D\uDCDD","atom",Z.key,"set to",G),G=W4(Y,Z.key,G,Z.subject),$6(Y,Z.key),b5(Y,Z);let W={oldValue:_,newValue:G};if(!o0(Y)){xF(Y,Z,W);return}if(Y.on.transactionApplying.state===null){let{key:H}=Z;if(GU(W.newValue))return;let J={type:"atom_update",key:H,...W};if(Z.family)J.family=Z.family;Y.transactionMeta.update.updates.push(J),Y.logger.info("\uD83D\uDCC1","atom",H,"stowed (",W.oldValue,"->",W.newValue,")")}else if(Z.key.startsWith("*")){let H=Z.key.slice(1),J=Y.atoms.get(H),$=Y.valueMap.get(H);if(J.type==="mutable_atom"&&o0(Y)){let{parent:z}=Y;$=f5(Y,J,z)}if($.do(W.newValue)===null)b5(Y,J)}};function v7(Y,Z){let X=Z.default;if(X instanceof Function)X=X();k7(Y,Z,X)}function hF(Y,Z){switch(Z.type){case"atom":case"mutable_atom":v7(Y,Z);break;case"writable_pure_selector":case"writable_held_selector":{let X=MY(Y,Z.key);for(let _ of X.values())v7(Y,_)}break}}function g7(Y,Z){if(Z.family){let X=Y.families.get(Z.family.key);if(X)return X}}function E8(Y,...Z){let X,_,G;if(Z.length===1){if(X=Z[0],_=g7(Y,X)??null,_)G=X.family?G1(X.family.subKey):null,X=H0(Y,_,G)}else _=Z[0],G=Z[1],X=H0(Y,_,G);if("counterfeit"in X&&"family"in X){let J=X.family.subKey,$=Y.disposalTraces.buffer.find((Q)=>Q?.key===J);Y.logger.error("\u274C",X.type,X.key,`could not be reset because it was not found in the store "${Y.config.name}".`,$?`This state was previously disposed:
48
- ${$.trace}`:"No previous disposal trace was found.");return}let W=LY(Y,X);if(W){let J=Y.on.operationClose.subscribe(`waiting to reset "${X.key}" at T-${W}`,()=>{J(),Y.logger.info("\uD83D\uDFE2",X.type,X.key,`resuming deferred resetState from T-${W}`),E8(Y,X)});return}let H=h0(Y,X);hF(Y,H),VY(Y)}var y7=(Y,Z,X)=>{switch(Z.type){case"atom":case"mutable_atom":k7(Y,Z,X);break;case"writable_pure_selector":case"writable_held_selector":Z.set(X);break}};function R1(Y,...Z){let X,_,G,W;if(Z.length===2){if(X=Z[0],W=Z[1],_=g7(Y,X)??null,_)G=X.family?G1(X.family.subKey):null,X=H0(Y,_,G)}else _=Z[0],G=Z[1],W=Z[2],X=H0(Y,_,G);if("counterfeit"in X&&"family"in X){let $=X.family.subKey,Q=Y.disposalTraces.buffer.find((z)=>z?.key===$);Y.logger.error("\u274C",X.type,X.key,`could not be set because it was not found in the store "${Y.config.name}".`,Q?`This state was previously disposed:
49
- ${Q.trace}`:"No previous disposal trace was found.");return}let H=LY(Y,X);if(H){let $=Y.on.operationClose.subscribe(`waiting to set "${X.key}" at T-${H}`,()=>{$(),Y.logger.info("\uD83D\uDFE2",X.type,X.key,`resuming deferred setState from T-${H}`),R1(Y,X,W)});return}let J=h0(Y,X);y7(Y,J,W),VY(Y)}var p7=(Y,Z)=>i(Y).atoms.has(Z),fF=(Y,Z)=>i(Y).writableSelectors.has(Z),bF=(Y,Z)=>i(Y).readonlySelectors.has(Z),kF=(Y,Z)=>p7(Y,Z)||fF(Y,Z)||bF(Y,Z),x7=(Y,Z)=>{return i(Y).selectorGraph.getRelationEntries({downstreamSelectorKey:Z}).filter(([_,{source:G}])=>G!==Z).map(([_,{source:G}])=>G).filter((_)=>kF(Y,_))},MY=(Y,Z,X=new Set)=>{let _=x7(Y,Z),G=new Map;while(_.length>0){let W=_.pop();if(X.has(W))continue;if(X.add(W),p7(Y,W)){let H=Y.atoms.get(W);G.set(H.key,H)}else _.push(...x7(Y,W))}return G},gF=(Y,Z,X,_,G)=>{let W=i(Y),{type:H,key:J}=_;if(H==="atom"||H==="mutable_atom")W.selectorAtoms.set({selectorKey:X,atomKey:J}),Y.logger.info("\uD83D\uDD0D",Z,X,`discovers root atom "${J}"`);else{let $=MY(Y,J,G);Y.logger.info("\uD83D\uDD0D",Z,X,`discovers root atoms: [ ${[...$.values()].map((Q)=>`"${Q.key}"`).join(", ")} ]`);for(let{key:Q}of $.values())W.selectorAtoms=W.selectorAtoms.set({selectorKey:X,atomKey:Q})}G.add(J)},AY=(Y,Z,X,_)=>({get:(...G)=>{let W=i(Y),H;if(G.length===2){let[z,O]=G;H=H0(Y,z,O)}else[H]=G;let J=h0(Y,H),$=z6(Y,J),Q=H.key;return Y.logger.info("\uD83D\uDD0C",Z,X,`registers dependency ( "${Q}" =`,$,")"),W.selectorGraph.set({upstreamSelectorKey:Q,downstreamSelectorKey:X},{source:H.key}),gF(Y,Z,X,H,_),$},set:(...G)=>{let W,H;if(G.length===2)W=G[0],H=G[1];else{let Q=G[0],z=G[1];H=G[2],W=H0(Y,Q,z)}let J=i(Y),$=h0(J,W);y7(J,$,H)},find:(...G)=>H0(Y,...G),json:(G)=>b4(Y,G)}),g5=(Y,Z,X)=>{let _=i(Y),G=new J0,W=new Set,{key:H,const:J}=Z,$="readonly_held_selector",{get:Q,find:z,json:O}=AY(_,"readonly_held_selector",H,W),V={...Z,type:"readonly_held_selector",subject:G,install:(A)=>g5(A,Z,X),get:()=>{let A=i(Y),g=A.selectorGraph.getRelationEntries({downstreamSelectorKey:H});for(let[b,{source:f}]of g)if(f!==H)A.selectorGraph.delete(b,H);return A.selectorAtoms.delete(H),Z.get({get:Q,find:z,json:O},J),W4(i(Y),H,J,G),W.clear(),J},...X&&{family:X}};_.readonlySelectors.set(H,V),Y.logger.info("\u2728","readonly_held_selector",H,"=",J);let R={key:H,type:"readonly_held_selector"};if(X)R.family=X;return R},y5=(Y,Z,X)=>{let _=i(Y),G=new J0,W=new Set,H=Z.key,J="readonly_pure_selector",{get:$,find:Q,json:z}=AY(_,"readonly_pure_selector",H,W),D={...Z,type:"readonly_pure_selector",subject:G,install:(R)=>y5(R,Z,X),get:()=>{let R=i(Y),A=R.selectorGraph.getRelationEntries({downstreamSelectorKey:H});for(let[f,{source:h}]of A)if(h!==H)R.selectorGraph.delete(f,H);R.selectorAtoms.delete(H);let g=Z.get({get:$,find:Q,json:z}),b=W4(R,H,g,G);return Y.logger.info("\u2728","readonly_pure_selector",H,"=",b),W.clear(),b},...X&&{family:X}};_.readonlySelectors.set(H,D);let V={key:H,type:"readonly_pure_selector"};if(X)V.family=X;return V},yF=(Y)=>{let Z=i(Y);if(!o0(Z)){Y.logger.warn("\uD83D\uDC1E","transaction","???","abortTransaction called outside of a transaction. This is probably a bug in AtomIO.");return}Y.logger.info("\uD83E\uDE82","transaction",Z.transactionMeta.update.key,"Aborting transaction"),Z.parent.child=null};function B0(Y){return Y[0].toUpperCase()+Y.slice(1)}function f4(Y){return Y.type.split("_").map(B0).join(" ")}var p5=class extends Error{constructor(Y,Z){super(`${f4(Y)} ${z0(Y.key)} not found in store "${Z.config.name}".`)}};function S5(Y,Z,X){return(..._)=>{let G=h0(Y,Z);if(G)return G.run(_,X);throw new p5(Z,Y)}}function pF(Y,Z,X){let{key:_,newValue:G,oldValue:W}=Z,H=Y==="newValue"?G:W,J={key:_,type:"atom"};if(Z.family)Object.assign(J,{family:Z.family});R1(X,J,H)}function mF(Y){let{stack:Z}=Y;if(Z)return`
47
+ `)+"}");class Y6{config;resolvedConfig;name;get[X1](){return"scope"}referencesById={};references=[];resolutions={};exportedNames=[];aliases={};resolved=!1;nodesByHash={};intrinsic;constructor(Y,Z){if(this.config=d8(B.config,Z),this.resolvedConfig=d8(B.resolvedConfig,Z),this.name=this.resolvedConfig.name??`anonymousScope${Object.keys(GZ).length}`,this.name in GZ)w(`A Scope already named ${this.name} already exists`);GZ[this.name]=this;let X=Object.entries(Y).map((_)=>this.preparseOwnAliasEntry(..._));for(let[_,G]of X){let W=_;if(_[0]==="#"){if(W=_.slice(1),W in this.aliases)w(u_(W));this.aliases[W]=G}else{if(W in this.aliases)w(u_(_));this.aliases[W]=G,this.exportedNames.push(W)}if(!y(G,"module")&&!y(G,"generic")&&!O4(G)){let $=this.preparseOwnDefinitionFormat(G,{alias:W});this.resolutions[W]=y($,"root")?this.bindReference($):this.createParseContext($).id}}d_??=this.node("union",{branches:["string","number","object","bigint","symbol",{unit:!0},{unit:!1},{unit:void 0},{unit:null}]},{prereduced:!0}),this.nodesByHash[d_.hash]=this.node("intersection",{},{prereduced:!0}),this.intrinsic=B.intrinsic?o(B.intrinsic,(_,G)=>_.startsWith("json")?[]:[_,this.bindReference(G)]):{}}cacheGetter(Y,Z){return Object.defineProperty(this,Y,{value:Z}),Z}get internal(){return this}_json;get json(){if(!this._json)this.export();return this._json}defineSchema(Y){return Y}generic=(...Y)=>{let Z=this;return(X,_)=>new M4(Y,_?new i2(X):X,Z,Z,_??null)};units=(Y,Z)=>{let X=[];for(let G of Y)if(!X.includes(G))X.push(G);let _=X.map((G)=>this.node("unit",{unit:G},Z));return this.node("union",_,{...Z,prereduced:!0})};lazyResolutions=[];lazilyResolve(Y,Z){let X=this.node("alias",{reference:Z??"synthetic",resolve:Y},{prereduced:!0});if(!this.resolved)this.lazyResolutions.push(X);return X}schema=(Y,Z)=>this.finalize(this.parseSchema(Y,Z));parseSchema=(Y,Z)=>this.node(o8(Y),Y,Z);preparseNode(Y,Z,X){let _=typeof Y==="string"?Y:o8(Z,Y);if(V0(Z)&&Z.kind===_)return Z;if(_==="alias"&&!X?.prereduced){let{reference:$}=e8.implementation.normalize(Z,this);if($.startsWith("$")){let H=this.resolveRoot($.slice(1));Z=H,_=H.kind}}else if(_==="union"&&Q1(Z,"object")){let $=PQ(Z);if($?.length===1)Z=$[0],_=o8(Z)}if(V0(Z)&&Z.kind===_)return Z;let W=G8[_].normalize?.(Z,this)??Z;if(V0(W))return W.kind===_?W:SQ(_,W.kind);return{...X,$:this,kind:_,def:W,prefix:X.alias??_}}bindReference(Y){let Z;if(V0(Y))Z=Y.$===this?Y:new Y.constructor(Y.attachments,this);else Z=Y.$===this?Y:new M4(Y.params,Y.bodyDef,Y.$,this,Y.hkt);if(!this.resolved)Object.assign(this.referencesById,Z.referencesById);return Z}resolveRoot(Y){return this.maybeResolveRoot(Y)??w(HZ(Y))}maybeResolveRoot(Y){let Z=this.maybeResolve(Y);if(y(Z,"generic"))return;return Z}maybeResolveSubalias(Y){return WZ(this.aliases,Y)??WZ(this.ambient,Y)}get ambient(){return B.ambient}maybeResolve(Y){let Z=this.resolutions[Y];if(Z){if(typeof Z!=="string")return this.bindReference(Z);let _=_1[Z];if(y(_,"root"))return this.resolutions[Y]=_;if(y(_,"context")){if(_.phase==="resolving")return this.node("alias",{reference:`$${Y}`},{prereduced:!0});if(_.phase==="resolved")return _0(`Unexpected resolved context for was uncached by its scope: ${n(_)}`);_.phase="resolving";let G=this.bindReference(this.parseOwnDefinitionFormat(_.def,_));return _.phase="resolved",_1[G.id]=G,_1[_.id]=G,this.resolutions[Y]=G}return _0(`Unexpected nodesById entry for ${Z}: ${n(_)}`)}let X=this.aliases[Y]??this.ambient?.[Y];if(!X)return this.maybeResolveSubalias(Y);if(X=this.normalizeRootScopeValue(X),y(X,"generic"))return this.resolutions[Y]=this.bindReference(X);if(y(X,"module")){if(!X.root)w(s_(Y));return this.resolutions[Y]=this.bindReference(X.root)}return this.resolutions[Y]=this.parse(X,{alias:Y})}createParseContext(Y){let Z=Y.id??mY(Y.prefix);return _1[Z]=Object.assign(Y,{[X1]:"context",$:this,id:Z,phase:"unresolved"})}traversal(Y){return new f1(Y,this.resolvedConfig)}import(...Y){return new H8(o(this.export(...Y),(Z,X)=>[`#${Z}`,X]))}precompilation;_exportedResolutions;_exports;export(...Y){if(!this._exports){this._exports={};for(let X of this.exportedNames){let _=this.aliases[X];this._exports[X]=y(_,"module")?_Z(_,this):c_(this.maybeResolve(X))}for(let X of this.lazyResolutions)X.resolution;if(this._exportedResolutions=r_(this,this._exports),this._json=n_(this._exportedResolutions),Object.assign(this.resolutions,this._exportedResolutions),this.references=Object.values(this.referencesById),!this.resolvedConfig.jitless){let X=o_(this.references);this.precompilation=X.write(l_,4),i_(this.references,X)}this.resolved=!0}let Z=Y.length?Y:this.exportedNames;return new H8(o(Z,(X,_)=>[_,this._exports[_]]))}resolve(Y){return this.export()[Y]}node=(Y,Z,X={})=>{let _=this.preparseNode(Y,Z,X);if(V0(_))return this.bindReference(_);let G=this.createParseContext(_),W=uY(G),$=this.bindReference(W);return _1[G.id]=$};parse=(Y,Z={})=>this.finalize(this.parseDefinition(Y,Z));parseDefinition(Y,Z={}){if(y(Y,"root"))return this.bindReference(Y);let X=this.preparseOwnDefinitionFormat(Y,Z);if(y(X,"root"))return this.bindReference(X);let _=this.createParseContext(X);_1[_.id]=_;let G=this.bindReference(this.parseOwnDefinitionFormat(Y,_));if(G.isCyclic)G=L_(G,_.id);return _1[_.id]=G,G}finalize(Y){if(c_(Y),!Y.precompilation&&!this.resolvedConfig.jitless)vQ(Y.references);return Y}}class $Z extends Y6{parseOwnDefinitionFormat(Y,Z){return uY(Z)}preparseOwnDefinitionFormat(Y,Z){return this.preparseNode(o8(Y),Y,Z)}preparseOwnAliasEntry(Y,Z){return[Y,Z]}normalizeRootScopeValue(Y){return Y}}var c_=(Y)=>{let Z=Y.references.filter((X)=>X.hasKind("alias"));for(let X of Z){Object.assign(X.referencesById,X.resolution.referencesById);for(let _ of Y.references)if(X.id in _.referencesById)Object.assign(_.referencesById,X.referencesById)}return Y},n_=(Y)=>o(Y,(Z,X)=>[Z,y(X,"root")||y(X,"generic")?X.json:y(X,"module")?n_(X):_0(`Unexpected resolution ${n(X)}`)]),WZ=(Y,Z)=>{let X=Z.indexOf(".");if(X===-1)return;let _=Z.slice(0,X),G=Y[_];if(G===void 0)return;if(!y(G,"module"))return w(xQ(_));let W=Z.slice(X+1),$=G[W];if($===void 0)return WZ(G,W);if(y($,"root")||y($,"generic"))return $;if(y($,"module"))return $.root??w(s_(Z));_0(`Unexpected resolution for alias '${Z}': ${n($)}`)},Z6=(Y,Z)=>new $Z(Y,Z),X2=new $Z({});var r_=(Y,Z)=>{let X={};for(let _ in Z){let G=Z[_];if(y(G,"module")){let W=r_(Y,G),$=o(W,(H,Q)=>[`${_}.${H}`,Q]);Object.assign(X,$)}else if(y(G,"root")||y(G,"generic"))X[_]=G;else _0(`Unexpected scope resolution ${n(G)}`)}return X},HZ=(Y)=>`'${Y}' is unresolvable`,xQ=(Y)=>`'${Y}' must reference a module to be accessed using dot syntax`,s_=(Y)=>`Reference to submodule '${Y}' must specify an alias`;X2.export();var{schema:J0,node:J8,defineSchema:qw,generic:K1}=X2;var JZ="^(?:0|[1-9]\\d*)$",hQ=new RegExp(JZ),Sw=K0(hQ);var a_=Z6({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();B.intrinsic={...a_};var t_=Z6({integer:{domain:"number",divisor:1},lengthBoundable:["string",Array],key:["string","symbol"],nonNegativeIntegerString:{domain:"string",pattern:JZ}},{prereducedAliases:!0}).export();Object.assign(B.intrinsic,t_);var fQ=Z6({jsonPrimitive:["string","number",{unit:!0},{unit:!1},{unit:null}],jsonObject:{domain:"object",index:{signature:"string",value:"$jsonData"}},jsonData:["$jsonPrimitive","$jsonObject"]},{prereducedAliases:!0}).export(),d={...a_,...t_,...fQ,emptyStructure:J8("structure",{},{prereduced:!0})};B.intrinsic={...d};var YG=(Y)=>typeof Y==="string"&&Y[0]==="d"&&(Y[1]==="'"||Y[1]==='"')&&Y.at(-1)===Y[1],e_=(Y)=>Y.toString()!=="Invalid Date",ZG=(Y)=>Y.slice(2,-1),QZ=(Y)=>`'${Y}' could not be parsed by the Date constructor`,XG=(Y,Z)=>bQ(Y,Z),bQ=(Y,Z)=>{let X=new Date(Y);if(e_(X))return X;let _=hX(Y);if(_!==void 0){let G=new Date(_);if(e_(G))return G}return Z?w(Z===!0?QZ(Y):Z):void 0};var zZ=(Y,Z)=>{let X=Y.scanner.shiftUntil(kQ[GG[Z]]);if(Y.scanner.lookahead==="")return Y.error(yQ(X,Z));if(Y.scanner.shift(),Z==="/"){try{new RegExp(X)}catch(_){w(String(_))}Y.root=Y.ctx.$.node("intersection",{domain:"string",pattern:X},{prereduced:!0})}else if(p0(Z,UZ))Y.root=Y.ctx.$.node("unit",{unit:X});else{let _=XG(X,QZ(X));Y.root=Y.ctx.$.node("unit",{meta:X,unit:_})}},UZ={"'":1,'"':1},_G={"/":1,"'":1,'"':1},GG={"d'":"'",'d"':'"',"'":"'",'"':'"',"/":"/"},kQ={"'":(Y)=>Y.lookahead==="'",'"':(Y)=>Y.lookahead==='"',"/":(Y)=>Y.lookahead==="/"},gQ={'"':"double-quote","'":"single-quote","/":"forward slash"},yQ=(Y,Z)=>`${Z}${Y} requires a closing ${gQ[GG[Z]]}`;var WG=(Y)=>`Private type references should not include '#'. Use '${Y}' instead.`,X6="Optional definitions like 'string?' are only valid as properties in an object or tuple",_6="Defaultable definitions like 'number = 0' are only valid as properties in an object or tuple";var $G={">":!0,">=":!0},HG={"<":!0,"<=":!0};var Q8={"<":">",">":"<","<=":">=",">=":"<=","==":"=="},JG=(Y)=>`Unmatched )${Y===""?"":` before ${Y}`}`,G6=(Y)=>`Missing ${Y}`,QG=(Y,Z)=>`Left bounds are only valid when paired with right bounds (try ...${Z}${Y})`,W6=(Y)=>`Left-bounded expressions must specify their limits using < or <= (was ${Y})`,zG=(Y,Z,X,_)=>`An expression may have at most one left bound (parsed ${Y}${Q8[Z]}, ${X}${Q8[_]})`;var UG=(Y,Z,X)=>FG(Y,Z,X,[]),FG=(Y,Z,X,_)=>{let G=X.parseUntilFinalizer();if(_.push(G.root),G.finalizer===">"){if(_.length!==Z.params.length)return X.error(FZ(Y,Z.names,_.map((W)=>W.expression)));return _}if(G.finalizer===",")return FG(Y,Z,X,_);return G.error(G6(">"))},FZ=(Y,Z,X)=>`${Y}<${Z.join(", ")}> requires exactly ${Z.length} args (got ${X.length}${X.length===0?"":`: ${X.join(", ")}`})`;var OZ=(Y)=>{let Z=Y.scanner.shiftUntilNextTerminator();if(Z==="keyof")Y.addPrefix("keyof");else Y.root=mQ(Y,Z)},pQ=(Y,Z,X)=>{if(X.scanner.shiftUntilNonWhitespace(),X.scanner.shift()!=="<")return X.error(FZ(Y,Z.names,[]));let G=UG(Y,Z,X);return Z(...G)},mQ=(Y,Z)=>uQ(Y,Z)??dQ(Y,Z)??Y.error(Z===""?Y.scanner.lookahead==="#"?WG(Y.shiftedByOne().scanner.shiftUntilNextTerminator()):EZ(Y):HZ(Z)),uQ=(Y,Z)=>{if(Y.ctx.args?.[Z]){let _=Y.ctx.args[Z];if(typeof _!=="string")return _;return Y.ctx.$.node("alias",{reference:_},{prereduced:!0})}let X=Y.ctx.$.maybeResolve(Z);if(y(X,"root"))return X;if(X===void 0)return;if(y(X,"generic"))return pQ(Z,X,Y);return w(`Unexpected resolution ${n(X)}`)},dQ=(Y,Z)=>{let X=fX(Z);if(X!==void 0)return Y.ctx.$.node("unit",{unit:X});let _=kX(Z);if(_!==void 0)return Y.ctx.$.node("unit",{unit:_})},EZ=(Y)=>{let Z=Y.previousOperator();return Z?DZ(Z,Y.scanner.unscanned):cQ(Y.scanner.unscanned)},DZ=(Y,Z="")=>`Token '${Y}' requires a right operand${Z?` before '${Z}'`:""}`,cQ=(Y)=>`Expected an expression${Y?` before '${Y}'`:""}`;var LZ=(Y)=>Y.scanner.lookahead===""?Y.error(EZ(Y)):Y.scanner.lookahead==="("?Y.shiftedByOne().reduceGroupOpen():Y.scanner.lookaheadIsIn(_G)?zZ(Y,Y.scanner.shift()):Y.scanner.lookaheadIsIn(E4)?LZ(Y.shiftedByOne()):Y.scanner.lookahead==="d"?Y.scanner.nextLookahead in UZ?zZ(Y,`${Y.scanner.shift()}${Y.scanner.shift()}`):OZ(Y):OZ(Y);class _4 extends RY{shiftUntilNextTerminator(){return this.shiftUntilNonWhitespace(),this.shiftUntil(()=>(this.lookahead in _4.terminatingChars))}static terminatingChars={"<":1,">":1,"=":1,"|":1,"&":1,")":1,"[":1,"%":1,",":1,":":1,"?":1,"#":1,...E4};static finalizingLookaheads={">":1,",":1,"":1,"=":1,"?":1};static lookaheadIsFinalizing=(Y,Z)=>Y===">"?Z[0]==="="?Z[1]==="=":Z.trimStart()===""||p0(Z.trimStart()[0],_4.terminatingChars):Y==="="?Z[0]!=="=":Y===","||Y==="?"}var EG=(Y,Z)=>{let X=lQ(Y,Z);if(Y.root.hasKind("unit")){if(typeof Y.root.unit==="number"){Y.reduceLeftBound(Y.root.unit,X),Y.unsetRoot();return}if(Y.root.unit instanceof Date){let _=`d'${Y.root.description??Y.root.unit.toISOString()}'`;Y.unsetRoot(),Y.reduceLeftBound(_,X);return}}return oQ(Y,X)},DG={"<":1,">":1,"=":1},lQ=(Y,Z)=>Y.scanner.lookaheadIs("=")?`${Z}${Y.scanner.shift()}`:Z;var OG=(Y,Z,X,_)=>{if(X.extends(B.intrinsic.number)){if(typeof Z!=="number")return w(VZ(Y,Z,_));return Y==="=="?["min","max"]:Y[0]===">"?["min"]:["max"]}if(X.extends(B.intrinsic.lengthBoundable)){if(typeof Z!=="number")return w(VZ(Y,Z,_));return Y==="=="?["exactLength"]:Y[0]===">"?["minLength"]:["maxLength"]}if(X.extends(B.intrinsic.Date))return Y==="=="?["after","before"]:Y[0]===">"?["after"]:["before"];return w(__(X.expression))},iQ=(Y)=>({rule:YG(Y.limit)?ZG(Y.limit):Y.limit,exclusive:Y.comparator.length===1}),oQ=(Y,Z)=>{let X=Y.unsetRoot(),_=Y.scanner.location;Y.parseOperand();let G=Y.unsetRoot(),W=Y.scanner.sliceChars(_,Y.scanner.location);if(Y.root=X,!G.hasKind("unit")||typeof G.unit!=="number"&&!(G.unit instanceof Date))return Y.error(VZ(Z,W,"right"));let $=G.unit,H=Z.length===1,Q=OG(Z,typeof $==="number"?$:W,X,"right");for(let z of Q)Y.constrainRoot(z,Z==="=="?{rule:$}:{rule:$,exclusive:H});if(!Y.branches.leftBound)return;if(!p0(Z,HG))return Y.error(W6(Z));let J=OG(Y.branches.leftBound.comparator,Y.branches.leftBound.limit,X,"left");Y.constrainRoot(J[0],iQ(Y.branches.leftBound)),Y.branches.leftBound=null},VZ=(Y,Z,X)=>`Comparator ${X==="left"?Q8[Y]:Y} must be ${X==="left"?"preceded":"followed"} by a corresponding literal (was ${Z})`;var LG=(Y)=>{Y.scanner.shiftUntilNonWhitespace();let Z=Y.scanner.shiftUntilNextTerminator();Y.root=Y.root.brand(Z)};var MG=(Y)=>{let Z=Y.scanner.shiftUntilNextTerminator(),X=bX(Z,{errorOnFail:VG(Z)});if(X===0)Y.error(VG(0));Y.root=Y.root.constrain("divisor",X)},VG=(Y)=>`% operator must be followed by a non-zero integer literal (was ${Y})`;var MZ=(Y)=>{let Z=Y.scanner.shift();return Z===""?Y.finalize(""):Z==="["?Y.scanner.shift()==="]"?Y.setRoot(Y.root.array()):Y.error(nQ):Z==="|"?Y.scanner.lookahead===">"?Y.shiftedByOne().pushRootToBranch("|>"):Y.pushRootToBranch(Z):Z==="&"?Y.pushRootToBranch(Z):Z===")"?Y.finalizeGroup():_4.lookaheadIsFinalizing(Z,Y.scanner.unscanned)?Y.finalize(Z):p0(Z,DG)?EG(Y,Z):Z==="%"?MG(Y):Z==="#"?LG(Y):(Z in E4)?MZ(Y):Y.error($6(Z))},$6=(Y,Z="")=>`'${Y}' is not allowed here${Z&&` (should be ${Z})`}`,nQ="Missing expected ']'";var AG=(Y)=>{let Z=Y.unsetRoot();Y.parseOperand();let X=Y.unsetRoot();if(!X.hasKind("unit"))return Y.error(rQ(X.expression));let _=X.unit instanceof Date?()=>new Date(X.unit):X.unit;return[Z,"=",_]},rQ=(Y)=>`Default value '${Y}' must a literal value`;var AZ=(Y,Z)=>{let X=Z.$.maybeResolveRoot(Y);if(X)return X;if(Y.endsWith("[]")){let W=Z.$.maybeResolveRoot(Y.slice(0,-2));if(W)return W.array()}let _=new z8(new _4(Y),Z),G=sQ(_);if(_.finalizer===">")w($6(">"));return G},sQ=(Y)=>{Y.parseOperand();let Z=_2(Y).root;if(!Z)return _0(`Root was unexpectedly unset after parsing string '${Y.scanner.scanned}'`);if(Y.finalizer==="=")Z=AG(Y);else if(Y.finalizer==="?")Z=[Z,"?"];if(Y.scanner.shiftUntilNonWhitespace(),Y.scanner.lookahead)w($6(Y.scanner.lookahead));return Z},_2=(Y)=>{while(Y.finalizer===void 0)aQ(Y);return Y},aQ=(Y)=>Y.hasRoot()?Y.parseOperator():Y.parseOperand();class z8{root;branches={prefixes:[],leftBound:null,intersection:null,union:null,pipe:null};finalizer;groups=[];scanner;ctx;constructor(Y,Z){this.scanner=Y,this.ctx=Z}error(Y){return w(Y)}hasRoot(){return this.root!==void 0}setRoot(Y){this.root=Y}unsetRoot(){let Y=this.root;return this.root=void 0,Y}constrainRoot(...Y){this.root=this.root.constrain(Y[0],Y[1])}finalize(Y){if(this.groups.length)return this.error(G6(")"));this.finalizeBranches(),this.finalizer=Y}reduceLeftBound(Y,Z){let X=Q8[Z];if(!p0(X,$G))return this.error(W6(Z));if(this.branches.leftBound)return this.error(zG(this.branches.leftBound.limit,this.branches.leftBound.comparator,Y,X));this.branches.leftBound={comparator:X,limit:Y}}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 Y=this.groups.pop();if(!Y)return this.error(JG(this.scanner.unscanned));this.branches=Y}addPrefix(Y){this.branches.prefixes.push(Y)}applyPrefixes(){while(this.branches.prefixes.length){let Y=this.branches.prefixes.pop();this.root=Y==="keyof"?this.root.keyof():_0(`Unexpected prefix '${Y}'`)}}pushRootToBranch(Y){this.assertRangeUnset(),this.applyPrefixes();let Z=this.root;if(this.root=void 0,this.branches.intersection=this.branches.intersection?.rawAnd(Z)??Z,Y==="&")return;if(this.branches.union=this.branches.union?.rawOr(this.branches.intersection)??this.branches.intersection,this.branches.intersection=null,Y==="|")return;this.branches.pipe=this.branches.pipe?.rawPipeOnce(this.branches.union)??this.branches.union,this.branches.union=null}parseUntilFinalizer(){return _2(new z8(this.scanner,this.ctx))}parseOperator(){return MZ(this)}parseOperand(){return LZ(this)}assertRangeUnset(){if(this.branches.leftBound)return this.error(QG(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 tQ="An empty string is not a valid generic parameter name",H6=(Y,Z,X)=>{Y.shiftUntilNonWhitespace();let _=Y.shiftUntilNextTerminator();if(_===""){if(Y.lookahead===""&&Z.length)return Z;return w(tQ)}return Y.shiftUntilNonWhitespace(),eQ(Y,_,Z,X)},wG="extends ",eQ=(Y,Z,X,_)=>{if(Y.shiftUntilNonWhitespace(),Y.unscanned.startsWith(wG))Y.jumpForward(wG.length);else{if(Y.lookahead===",")Y.shift();return X.push(Z),H6(Y,X,_)}let G=_2(new z8(Y,_));return X.push([Z,G.root]),H6(Y,X,_)};class wZ extends h1{$;constructor(Y){super((...Z)=>new G2(Y)(...Z),{bind:Y});this.$=Y}in(Y){return new G2(this.$,Y===void 0?void 0:this.$.parse(Y))}at(Y,Z){return new G2(this.$).at(Y,Z)}case(Y,Z){return new G2(this.$).case(Y,Z)}}class G2 extends h1{$;in;key;branches=[];constructor(Y,Z){super((X)=>this.caseEntries(Object.entries(X).map(([_,G])=>_==="default"?[_,G]:[this.$.parse(_),G])));this.$=Y,this.in=Z}at(Y,Z){if(this.key)w(Zz);if(this.branches.length)w(Yz);return this.key=Y,Z?this.match(Z):this}case(Y,Z){return this.caseEntry(this.$.parse(Y),Z)}caseEntry(Y,Z){let _=(this.key?this.$.parse({[this.key]:Y}):Y).pipe(Z);return this.branches.push(_),this}match(Y){return this(Y)}strings(Y){return this.caseEntries(Object.entries(Y).map(([Z,X])=>Z==="default"?[Z,X]:[this.$.node("unit",{unit:Z}),X]))}caseEntries(Y){for(let Z=0;Z<Y.length;Z++){let[X,_]=Y[Z];if(X==="default"){if(Z!==Y.length-1)w("default may only be specified as the last key of a switch definition");return this.default(_)}if(typeof _!=="function")return w(`Value for case "${X}" must be a function (was ${y0(_)})`);this.caseEntry(X,_)}return this}default(Y){if(typeof Y==="function")this.case(d.unknown,Y);let Z={branches:this.branches,ordered:!0};if(Y==="never"||Y==="assert")Z.meta={onFail:RG};let X=this.$.node("union",Z);if(!this.in)return this.$.finalize(X);let _=this.in.pipe(X);if(Y==="never"||Y==="assert")_=_.configureReferences({onFail:RG},"self");return this.$.finalize(_)}}var RG=(Y)=>Y.throw(),Yz="A key matcher must be specified before the first case i.e. match.at('foo') or match.in<object>().at('bar')",Zz="At most one key matcher may be specified per expression";var J6=(Y,Z)=>{if(O0(Y)){if(Y[1]==="=")return[Z.$.parseOwnDefinitionFormat(Y[0],Z),"=",Y[2]];if(Y[1]==="?")return[Z.$.parseOwnDefinitionFormat(Y[0],Z),"?"]}return Q6(Y,Z)},NG="Only required keys may make their values optional, e.g. { [mySymbol]: ['number', '?'] }",IG="Only required keys may specify default values, e.g. { value: 'number = 0' }";var BG=(Y,Z)=>{let X,_={},G=j4(Y);for(let[$,H]of G){let Q=Gz($);if(Q.kind==="spread"){if(!c1(_))return w(_z);let V=Z.$.parseOwnDefinitionFormat(H,Z);if(V.equals(d.object))continue;if(!V.hasKind("intersection")||!V.basis?.equals(d.object))return w(Wz(V.expression));X=V.structure;continue}if(Q.kind==="undeclared"){if(H!=="reject"&&H!=="delete"&&H!=="ignore")w(Xz(H));_.undeclared=H;continue}let J=J6(H,Z),z=Q;if(Q.kind==="required"){if(!O0(J))RZ(_,"required",{key:Q.normalized,value:J},Z);else RZ(_,"optional",J[1]==="="?{key:Q.normalized,value:J[0],default:J[2]}:{key:Q.normalized,value:J[0]},Z);continue}if(O0(J)){if(J[1]==="?")w(NG);if(J[1]==="=")w(IG)}if(Q.kind==="optional"){RZ(_,"optional",{key:Q.normalized,value:J},Z);continue}let O=Z.$.parseOwnDefinitionFormat(z.normalized,Z),D=e2(O,J,Z.$);if(D.index)_.index=Z0(_.index,D.index);if(D.required)_.required=Z0(_.required,D.required)}let W=Z.$.node("structure",_);return Z.$.parseSchema({domain:"object",structure:X?.merge(W)??W})},RZ=(Y,Z,X,_)=>{Y[Z]=Z0(Y[Z],_.$.node(Z,X))},Xz=(Y)=>`Value of '+' key must be 'reject', 'delete', or 'ignore' (was ${n(Y)})`,_z="Spread operator may only be used as the first key in an object",Gz=(Y)=>typeof Y==="symbol"?{kind:"required",normalized:Y}:Y.at(-1)==="?"?Y.at(-2)===b8?{kind:"required",normalized:`${Y.slice(0,-2)}?`}:{kind:"optional",normalized:Y.slice(0,-1)}:Y[0]==="["&&Y.at(-1)==="]"?{kind:"index",normalized:Y.slice(1,-1)}:Y[0]===b8&&Y[1]==="["&&Y.at(-1)==="]"?{kind:"required",normalized:Y.slice(1)}:Y==="..."?{kind:"spread"}:Y==="+"?{kind:"undeclared"}:{kind:"required",normalized:Y==="\\..."?"...":Y==="\\+"?"+":Y},Wz=(Y)=>`Spread operand must resolve to an object literal type (was ${Y})`;var TG=(Y,Z)=>Dz(Y)?PG[Y[0]](Y,Z):Oz(Y)?jG[Y[1]](Y,Z):null,$z=(Y,Z)=>Z.$.parseOwnDefinitionFormat(Y[1],Z).keyof(),NZ=(Y,Z)=>{if(Y[2]===void 0)return w(DZ(Y[1],""));let X=Z.$.parseOwnDefinitionFormat(Y[0],Z),_=Z.$.parseOwnDefinitionFormat(Y[2],Z);if(Y[1]==="|")return Z.$.node("union",{branches:[X,_]});let G=Y[1]==="&"?O1(X,_,Z.$):i8(X,_,Z.$);if(G instanceof S)return G.throw();return G},Hz=(Y,Z)=>Z.$.parseOwnDefinitionFormat(Y[0],Z).array(),Jz=(Y,Z)=>{if(typeof Y[2]!=="function")return w(KG("=>",Y[2]));return Z.$.parseOwnDefinitionFormat(Y[0],Z).pipe(Y[2])},KG=(Y,Z)=>`${Y===":"?"Narrow":"Morph"} expression requires a function following '${Y}' (was ${typeof Z})`,Qz=(Y,Z)=>{if(typeof Y[2]!=="function")return w(KG(":",Y[2]));return Z.$.parseOwnDefinitionFormat(Y[0],Z).constrain("predicate",Y[2])},zz=(Y,Z)=>Z.$.parseOwnDefinitionFormat(Y[0],Z).configureReferences(Y[2],"shallow"),qG=(Y)=>Y,Uz=qG({"[]":Hz,"?":()=>w(X6)}),Fz=qG({"|":NZ,"&":NZ,":":Qz,"=>":Jz,"|>":NZ,"@":zz,"=":()=>w(_6)}),jG={...Uz,...Fz},Oz=(Y)=>jG[Y[1]]!==void 0,Ez=(Y)=>Y,PG=Ez({keyof:$z,instanceof:(Y,Z)=>{if(typeof Y[1]!=="function")return w(CG(h8(Y[1])));let X=Y.slice(1).map((_)=>typeof _==="function"?Z.$.node("proto",{proto:_}):w(CG(h8(_))));return X.length===1?X[0]:Z.$.node("union",{branches:X})},"===":(Y,Z)=>Z.$.units(Y.slice(1))}),Dz=(Y)=>PG[Y[0]]!==void 0,CG=(Y)=>`Expected a constructor following 'instanceof' operator (was ${Y})`;var xG=(Y,Z)=>{let X=[{}],_=0;while(_<Y.length){let G=!1;if(Y[_]==="..."&&_<Y.length-1)G=!0,_++;let W=J6(Y[_],Z),[$,H,Q]=!O0(W)?[W]:W;if(_++,G){if(!$.extends(B.intrinsic.Array))return w(Mz($.expression));X=X.flatMap((J)=>$.distribute((z)=>Vz(u2(J),z)))}else X=X.map((J)=>{if(H==="?")return hG(J,$);if(H==="=")return Lz(J,$,Q);return IZ(J,$)})}return Z.$.parseSchema(X.map((G)=>c1(G)?{proto:Array,exactLength:0}:{proto:Array,sequence:G}))},IZ=(Y,Z)=>{if(Y.defaultables||Y.optionals)return w(Y.variadic?YZ:Az);if(Y.variadic)Y.postfix=Z0(Y.postfix,Z);else Y.prefix=Z0(Y.prefix,Z);return Y},hG=(Y,Z)=>{if(Y.variadic)return w(fG);return Y.optionals=Z0(Y.optionals,Z),Y},Lz=(Y,Z,X)=>{if(Y.variadic)return w(fG);if(Y.optionals)return w(wz);return Y.defaultables=Z0(Y.defaultables,[[Z,X]]),Y},SG=(Y,Z)=>{if(Y.postfix)w(vG);if(Y.variadic){if(!Y.variadic.equals(Z))w(vG)}else Y.variadic=Z.internal;return Y},Vz=(Y,Z)=>{let X=Z.select({method:"find",kind:"sequence"});if(!X)return SG(Y,B.intrinsic.unknown);if(X.prefix)for(let _ of X.prefix)IZ(Y,_);if(X.optionals)for(let _ of X.optionals)hG(Y,_);if(X.variadic)SG(Y,X.variadic);if(X.postfix)for(let _ of X.postfix)IZ(Y,_);return Y},Mz=(Y)=>`Spread element must be an array (was ${Y})`,vG="A tuple may have at most one variadic element",Az="A required element may not follow an optional element",fG="An optional element may not follow a variadic element";var wz="A defaultable element may not follow an optional element without a default";var Rz={},Q6=(Y,Z)=>{if(typeof Y==="string"){if(Z.args&&Object.keys(Z.args).some((_)=>Y.includes(_)))return AZ(Y,Z);let X=Rz[Z.$.name]??={};return X[Y]??=AZ(Y,Z)}return Q1(Y,"object")?Nz(Y,Z):w(BZ(y0(Y)))},Nz=(Y,Z)=>{let X=x8(Y);switch(X){case void 0:if(y(Y,"root"))return Y;return BG(Y,Z);case"Array":return Iz(Y,Z);case"RegExp":return Z.$.node("intersection",{domain:"string",pattern:Y},{prereduced:!0});case"Function":{let _=O4(Y)?Y():Y;if(y(_,"root"))return _;return w(BZ("Function"))}default:return w(BZ(X??n(Y)))}},Iz=(Y,Z)=>TG(Y,Z)??xG(Y,Z),BZ=(Y)=>`Type definitions must be strings or objects (was ${Y})`;class CZ extends h1{constructor(Y){let Z=Object.assign({errors:U1,hkt:a0,$:Y,raw:Y.parse,module:Y.constructor.module,scope:Y.constructor.scope,define:Y.define,match:Y.match,generic:Y.generic,schema:Y.schema,keywords:Y.ambient,unit:Y.unit,enumerated:Y.enumerated,instanceOf:Y.instanceOf,valueOf:Y.valueOf,or:Y.or,and:Y.and,merge:Y.merge,pipe:Y.pipe},Y.ambientAttachments);super((...X)=>{if(X.length===1)return Y.parse(X[0]);if(X.length===2&&typeof X[0]==="string"&&X[0][0]==="<"&&X[0].at(-1)===">"){let _=X[0].slice(1,-1),G=Y.parseGenericParams(_,{});return new M4(G,X[1],Y,Y,null)}return Y.parse(X)},{bind:Y,attach:Z})}}var U8=B;class z6 extends Y6{get ambientAttachments(){if(!U8.typeAttachments)return;return this.cacheGetter("ambientAttachments",o(U8.typeAttachments,(Y,Z)=>[Y,this.bindReference(Z)]))}preparseOwnAliasEntry(Y,Z){let X=Y.indexOf("<");if(X===-1){if(y(Z,"module")||y(Z,"generic"))return[Y,Z];let W=this.name==="ark"?Y:Y==="root"?this.name:`${this.name}.${Y}`,$=this.resolvedConfig.keywords?.[W];if($)Z=[Z,"@",$];return[Y,Z]}if(Y.at(-1)!==">")w("'>' must be the last character of a generic declaration in a scope");let _=Y.slice(0,X),G=Y.slice(X+1,-1);return[_,()=>{let W=this.parseGenericParams(G,{alias:_});return Y_(W,Z,this)}]}parseGenericParams(Y,Z){return H6(new _4(Y),[],this.createParseContext({...Z,def:Y,prefix:"generic"}))}normalizeRootScopeValue(Y){if(O4(Y)&&!y(Y,"generic"))return Y();return Y}preparseOwnDefinitionFormat(Y,Z){return{...Z,def:Y,prefix:Z.alias??"type"}}parseOwnDefinitionFormat(Y,Z){if(!(Z.alias&&(Z.alias in this.aliases))&&!Z.args)Z.args={this:Z.id};let _=Q6(Y,Z);if(O0(_)){if(_[1]==="=")return w(_6);if(_[1]==="?")return w(X6)}return _}unit=(Y)=>this.units([Y]);valueOf=(Y)=>this.units(wX(Y));enumerated=(...Y)=>this.units(Y);instanceOf=(Y)=>this.node("proto",{proto:Y},{prereduced:!0});or=(...Y)=>this.schema(Y.map((Z)=>this.parse(Z)));and=(...Y)=>Y.reduce((Z,X)=>Z.and(this.parse(X)),this.intrinsic.unknown);merge=(...Y)=>Y.reduce((Z,X)=>Z.merge(this.parse(X)),this.intrinsic.object);pipe=(...Y)=>this.intrinsic.unknown.pipe(...Y);match=new wZ(this);declare=()=>({type:this.type});define(Y){return Y}type=new CZ(this);static scope=(Y,Z={})=>new z6(Y,Z);static module=(Y,Z={})=>this.scope(Y,Z).export()}var TZ=Object.assign(z6.scope,{define:(Y)=>Y}),Y0=z6;class bG extends a0{description='merge an object\'s properties onto another like `Merge(User, { isAdmin: "true" })`'}var Bz=K1(["base",d.object],["props",d.object])((Y)=>Y.base.merge(Y.props),bG),kG=Y0.module({Key:d.key,Merge:Bz});class gG extends a0{}var Cz=K1("element")((Y)=>{let Z=Y.element.exclude(d.Array),X=Z.array();return Z.rawOr(X).pipe(F4).distribute((_)=>_.assertHasKind("morph").declareOut(X),J0)},gG),yG=Y0.module({root:d.Array,readonly:"root",index:d.nonNegativeIntegerString,liftFrom:Cz},{name:"Array"});var KZ=J0(["string",S4.FileConstructor]),Tz=KZ.rawOr(KZ.array()),pG=J0({meta:"an object representing parsed form data",domain:"object",index:{signature:"string",value:Tz}}),mG=Y0.module({root:["instanceof",FormData],value:KZ,parsed:pG,parse:J0({in:FormData,morphs:(Y)=>{let Z={};for(let[X,_]of Y)if(X in Z){let G=Z[X];if(typeof G==="string"||G instanceof S4.FileConstructor)Z[X]=[G,_];else G.push(_)}else Z[X]=_;return Z},declaredOut:pG})},{name:"FormData"});var uG=Y0.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 Kz={Boolean:1,Number:1,String:1},dG=Y0.module({...o({...OY,...DY},(Y,Z)=>(Y in Kz)?[]:[Y,["instanceof",Z]]),Array:yG,TypedArray:uG,FormData:mG});var qz=J0({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"}),jz=J0({domain:"number",divisor:1}),U6=Y0.module({root:d.number,integer:jz,epoch:qz,safe:J0({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 I0=(Y,Z,X)=>{let _={domain:"string",pattern:{rule:Y.source,flags:Y.flags,meta:Z}};if(X)_.meta={format:X};return J8("intersection",_)},cG=I0(k8,"a well-formed integer string"),X9=Y0.module({root:cG,parse:J0({in:cG,morphs:(Y,Z)=>{let X=Number.parseInt(Y);return Number.isSafeInteger(X)?X:Z.error("an integer in the range Number.MIN_SAFE_INTEGER to Number.MAX_SAFE_INTEGER")},declaredOut:d.integer})},{name:"string.integer"}),Pz=I0(/^[\dA-Fa-f]+$/,"hex characters only"),Sz=Y0.module({root:I0(/^(?:[\d+/A-Za-z]{4})*(?:[\d+/A-Za-z]{2}==|[\d+/A-Za-z]{3}=)?$/,"base64-encoded"),url:I0(/^(?:[\w-]{4})*(?:[\w-]{2}(?:==|%3D%3D)?|[\w-]{3}(?:=|%3D)?)?$/,"base64url-encoded")},{name:"string.base64"}),lG=I0(/^[A-Z].*$/,"capitalized"),vz=Y0.module({root:J0({in:"string",morphs:(Y)=>Y.charAt(0).toUpperCase()+Y.slice(1),declaredOut:lG}),preformatted:lG},{name:"string.capitalize"}),xz=(Y)=>{let Z=Y.replaceAll(/[ -]+/g,""),X=0,_,G,W=!1;for(let $=Z.length-1;$>=0;$--){if(_=Z.substring($,$+1),G=Number.parseInt(_,10),W)G*=2,X+=G>=10?G%10+1:G;else X+=G;W=!W}return!!(X%10===0?Z:!1)},hz=/^(?: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}))$/,fz=J0({domain:"string",pattern:{meta:"a credit card number",rule:hz.source},predicate:{meta:"a credit card number",predicate:xz}});var bz=/^([+-]?\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 kz=(Y)=>!Number.isNaN(new Date(Y).valueOf()),iG=J0({domain:"string",predicate:{meta:"a parsable date",predicate:kz}}).assertHasKind("intersection"),oG=X9.root.internal.narrow((Y,Z)=>{let X=Number.parseInt(Y),_=U6.epoch(X);if(_ instanceof U1)return Z.errors.merge(_),!1;return!0}).configure({description:"an integer string representing a safe Unix timestamp"},"self").assertHasKind("intersection"),gz=Y0.module({root:oG,parse:J0({in:oG,morphs:(Y)=>new Date(Y),declaredOut:d.Date})},{name:"string.date.epoch"}),nG=I0(bz,"an ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) date").internal.assertHasKind("intersection"),yz=Y0.module({root:nG,parse:J0({in:nG,morphs:(Y)=>new Date(Y),declaredOut:d.Date})},{name:"string.date.iso"}),pz=Y0.module({root:iG,parse:J0({declaredIn:iG,in:"string",morphs:(Y,Z)=>{let X=new Date(Y);if(Number.isNaN(X.valueOf()))return Z.error("a parsable date");return X},declaredOut:d.Date}),iso:yz,epoch:gz},{name:"string.date"}),mz=I0(/^[\w%+.-]+@[\d.A-Za-z-]+\.[A-Za-z]{2,}$/,"an email address","email"),rG="(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])",A4=`(${rG}[.]){3}${rG}`,uz=new RegExp(`^${A4}$`),v0="(?:[0-9a-fA-F]{1,4})",dz=new RegExp(`^((?:${v0}:){7}(?:${v0}|:)|(?:${v0}:){6}(?:${A4}|:${v0}|:)|(?:${v0}:){5}(?::${A4}|(:${v0}){1,2}|:)|(?:${v0}:){4}(?:(:${v0}){0,1}:${A4}|(:${v0}){1,3}|:)|(?:${v0}:){3}(?:(:${v0}){0,2}:${A4}|(:${v0}){1,4}|:)|(?:${v0}:){2}(?:(:${v0}){0,3}:${A4}|(:${v0}){1,5}|:)|(?:${v0}:){1}(?:(:${v0}){0,4}:${A4}|(:${v0}){1,6}|:)|(?::((?::${v0}){0,5}:${A4}|(?::${v0}){1,7}|:)))(%[0-9a-zA-Z.]{1,})?$`),cz=Y0.module({root:["v4 | v6","@","an IP address"],v4:I0(uz,"an IPv4 address","ipv4"),v6:I0(dz,"an IPv6 address","ipv6")},{name:"string.ip"}),F8="a JSON string",_9=(Y)=>{if(!(Y instanceof SyntaxError))throw Y;return`must be ${F8} (${Y})`},lz=J0({meta:F8,domain:"string",predicate:{meta:F8,predicate:(Y,Z)=>{try{return JSON.parse(Y),!0}catch(X){return Z.reject({code:"predicate",expected:F8,problem:_9(X)})}}}}),iz=(Y,Z)=>{if(Y.length===0)return Z.error({code:"predicate",expected:F8,actual:"empty"});try{return JSON.parse(Y)}catch(X){return Z.error({code:"predicate",expected:F8,problem:_9(X)})}},oz=Y0.module({root:lz,parse:J0({meta:"safe JSON string parser",in:"string",morphs:iz,declaredOut:d.jsonObject})},{name:"string.json"}),sG=I0(/^[a-z]*$/,"only lowercase letters"),nz=Y0.module({root:J0({in:"string",morphs:(Y)=>Y.toLowerCase(),declaredOut:sG}),preformatted:sG},{name:"string.lower"}),G9=["NFC","NFD","NFKC","NFKD"],W2=o(G9,(Y,Z)=>[Z,J0({domain:"string",predicate:(X)=>X.normalize(Z)===X,meta:`${Z}-normalized unicode`})]),F6=o(G9,(Y,Z)=>[Z,J0({in:"string",morphs:(X)=>X.normalize(Z),declaredOut:W2[Z]})]),rz=Y0.module({root:F6.NFC,preformatted:W2.NFC},{name:"string.normalize.NFC"}),sz=Y0.module({root:F6.NFD,preformatted:W2.NFD},{name:"string.normalize.NFD"}),az=Y0.module({root:F6.NFKC,preformatted:W2.NFKC},{name:"string.normalize.NFKC"}),tz=Y0.module({root:F6.NFKD,preformatted:W2.NFKD},{name:"string.normalize.NFKD"}),ez=Y0.module({root:"NFC",NFC:rz,NFD:sz,NFKC:az,NFKD:tz},{name:"string.normalize"}),aG=I0(y2,"a well-formed numeric string"),YU=Y0.module({root:aG,parse:J0({in:aG,morphs:(Y)=>Number.parseFloat(Y),declaredOut:d.number})},{name:"string.numeric"}),tG="a regex pattern",ZU=J0({domain:"string",predicate:{meta:tG,predicate:(Y,Z)=>{try{return new RegExp(Y),!0}catch(X){return Z.reject({code:"predicate",expected:tG,problem:String(X)})}}},meta:{format:"regex"}}),XU=/^(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-]+)*))?$/,_U=I0(XU,"a semantic version (see https://semver.org/)"),eG=I0(/^\S.*\S$|^\S?$/,"trimmed"),GU=Y0.module({root:J0({in:"string",morphs:(Y)=>Y.trim(),declaredOut:eG}),preformatted:eG},{name:"string.trim"}),Y9=I0(/^[A-Z]*$/,"only uppercase letters"),WU=Y0.module({root:J0({in:"string",morphs:(Y)=>Y.toUpperCase(),declaredOut:Y9}),preformatted:Y9},{name:"string.upper"}),$U=(Y)=>{if(URL.canParse)return URL.canParse(Y);try{return new URL(Y),!0}catch{return!1}},Z9=J0({domain:"string",predicate:{meta:"a URL string",predicate:$U},meta:{format:"uri"}}),HU=Y0.module({root:Z9,parse:J0({declaredIn:Z9,in:"string",morphs:(Y,Z)=>{try{return new URL(Y)}catch{return Z.error("a URL string")}},declaredOut:J0(URL)})},{name:"string.url"}),JU=Y0.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:I0(/^[\da-f]{8}-[\da-f]{4}-1[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv1"),v2:I0(/^[\da-f]{8}-[\da-f]{4}-2[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv2"),v3:I0(/^[\da-f]{8}-[\da-f]{4}-3[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv3"),v4:I0(/^[\da-f]{8}-[\da-f]{4}-4[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv4"),v5:I0(/^[\da-f]{8}-[\da-f]{4}-5[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv5"),v6:I0(/^[\da-f]{8}-[\da-f]{4}-6[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv6"),v7:I0(/^[\da-f]{8}-[\da-f]{4}-7[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv7"),v8:I0(/^[\da-f]{8}-[\da-f]{4}-8[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv8")},{name:"string.uuid"}),W9=Y0.module({root:d.string,alpha:I0(/^[A-Za-z]*$/,"only letters"),alphanumeric:I0(/^[\dA-Za-z]*$/,"only letters and digits 0-9"),hex:Pz,base64:Sz,capitalize:vz,creditCard:fz,date:pz,digits:I0(/^\d*$/,"only digits 0-9"),email:mz,integer:X9,ip:cz,json:oz,lower:nz,normalize:ez,numeric:YU,regex:ZU,semver:_U,trim:GU,upper:WU,url:HU,uuid:JU},{name:"string"});var $9=Y0.module({bigint:d.bigint,boolean:d.boolean,false:d.false,never:d.never,null:d.null,number:d.number,object:d.object,string:d.string,symbol:d.symbol,true:d.true,unknown:d.unknown,undefined:d.undefined}),H9=Y0.module({root:d.unknown,any:d.unknown},{name:"unknown"}),QU=Y0.module({root:d.jsonObject,stringify:J8("morph",{in:d.jsonObject,morphs:(Y)=>JSON.stringify(Y),declaredOut:d.string})},{name:"object.json"}),J9=Y0.module({root:d.object,json:QU},{name:"object"});class Q9 extends a0{description='instantiate an object from an index signature and corresponding value type like `Record("string", "number")`'}var zU=K1(["K",d.key],"V")((Y)=>({domain:"object",index:{signature:Y.K,value:Y.V}}),Q9);class z9 extends a0{description='pick a set of properties from an object like `Pick(User, "name | age")`'}var UU=K1(["T",d.object],["K",d.key])((Y)=>Y.T.pick(Y.K),z9);class U9 extends a0{description='omit a set of properties from an object like `Omit(User, "age")`'}var FU=K1(["T",d.object],["K",d.key])((Y)=>Y.T.omit(Y.K),U9);class F9 extends a0{description="make all named properties of an object optional like `Partial(User)`"}var OU=K1(["T",d.object])((Y)=>Y.T.partial(),F9);class O9 extends a0{description="make all named properties of an object required like `Required(User)`"}var EU=K1(["T",d.object])((Y)=>Y.T.required(),O9);class E9 extends a0{description='exclude branches of a union like `Exclude("boolean", "true")`'}var DU=K1("T","U")((Y)=>Y.T.exclude(Y.U),E9);class D9 extends a0{description='extract branches of a union like `Extract("0 | false | 1", "number")`'}var LU=K1("T","U")((Y)=>Y.T.extract(Y.U),D9),L9=Y0.module({Exclude:DU,Extract:LU,Omit:FU,Partial:OU,Pick:UU,Record:zU,Required:EU});var w4=TZ({...$9,...L9,...dG,...kG,string:W9,number:U6,object:J9,unknown:H9},{prereducedAliases:!0,name:"ark"}),m0=w4.export();Object.assign(U8.ambient,m0);U8.typeAttachments={string:m0.string.root,number:m0.number.root,bigint:m0.bigint,boolean:m0.boolean,symbol:m0.symbol,undefined:m0.undefined,null:m0.null,object:m0.object.root,unknown:m0.unknown.root,false:m0.false,true:m0.true,never:m0.never,arrayIndex:m0.Array.index,Key:m0.Key,Record:m0.Record,Array:m0.Array.root,Date:m0.Date};var E1=Object.assign(w4.type,U8.typeAttachments),VU=w4.match,MU=w4.generic,eI=w4.schema,AU=w4.define,wU=w4.declare;var V9=(Y,Z,X=x0.STORE)=>{return qZ(X,{key:`${Y.key}:JSON`,get:({get:_})=>Z.toJson(_(Y)),set:({set:_},G)=>{_(Y,Z.fromJson(G))}})};function M9(Y,Z,X){return O6(Y,{key:`${Z.key}:JSON`,get:(G)=>({get:W})=>{let $=W(Z,G);return X.toJson($)},set:(G)=>({set:W},$)=>{W(Z,G,X.fromJson($))}},["mutable","json"])}var G1=(Y)=>JSON.parse(Y),z0=(Y)=>JSON.stringify(Y),LB=[Array.prototype,Boolean.prototype,Number.prototype,Object.prototype,String.prototype];function O8(Y){return L6(x0.STORE,Y,void 0)}function $2(Y){return V8(x0.STORE,Y)}function PZ(...Y){if(Y.length===2)return k1(x0.STORE,...Y);return k1(x0.STORE,...Y)}function E6(Y,Z){return C9(x0.STORE,Y,Z)}function A9(Y){return K9(Y,x0.STORE)}var jZ=(Y)=>(Z,X,_,G,...W)=>{console[Y](`${Z} ${X} "${_}" ${G}`,...W)},RU={error:jZ("error"),info:jZ("info"),warn:jZ("warn")},w9=class{logLevel;filter;logger;constructor(Y,Z,X=RU){this.logLevel=Y,this.filter=Z,this.logger=X}error=(...Y)=>{let Z=this.filter?.(...Y)??!0;if(this.logLevel!==null){if(Z===!0)this.logger.error(...Y);else if(Z!==!1)this.logger.error(...Z)}};info=(...Y)=>{let Z=this.filter?.(...Y)??!0;if(this.logLevel==="info"){if(Z===!0)this.logger.info(...Y);else if(Z!==!1)this.logger.info(...Z)}};warn=(...Y)=>{let Z=this.filter?.(...Y)??!0;if(this.logLevel!=="error"&&this.logLevel!==null){if(Z===!0)this.logger.warn(...Y);else if(Z!==!1)this.logger.warn(...Z)}}};var NU=class{store;constructor(Y=x0.STORE){this.store=Y,N9("root",Y)}allocate(Y,Z,X){return D8(this.store,Y,Z,X)}fuse(Y,Z,X){return I9(this.store,Y,Z,X)}deallocate(Y){L8(this.store,Y)}claim(Y,Z,X){return J2(this.store,Y,Z,X)}},R9=class{store;realm;constructor(Y=x0.STORE){this.store=Y,this.realm=new NU(Y)}allocate(Y,Z,X){D8(this.store,Y,Z,X)}deallocate(Y){L8(this.store,Y)}claim(Y,Z,X){J2(this.store,Y,Z,X)}};function D6(Y){return hZ(x0.STORE,Y)}function H2(Y){return xZ(x0.STORE,Y)}var D1=class Y extends Set{mode="record";subject=new H0;cacheLimit=0;cache=[];cacheIdx=-1;cacheUpdateNumber=-1;constructor(Z,X=0){super(Z);if(Z instanceof Y)this.parent=Z,this.cacheUpdateNumber=Z.cacheUpdateNumber;if(X)this.cacheLimit=X,this.cache=new Array(X),this.subscribe("auto cache",(_)=>{this.cacheIdx++,this.cacheIdx%=this.cacheLimit,this.cache[this.cacheIdx]=_})}toJSON(){return{members:[...this],cache:this.cache,cacheLimit:this.cacheLimit,cacheIdx:this.cacheIdx,cacheUpdateNumber:this.cacheUpdateNumber}}static fromJSON(Z){let X=new Y(Z.members,Z.cacheLimit);return X.cache=Z.cache,X.cacheIdx=Z.cacheIdx,X.cacheUpdateNumber=Z.cacheUpdateNumber,X}add(Z){let X=super.add(Z);if(this.mode==="record")this.cacheUpdateNumber++,this.emit(`add:${z0(Z)}`);return X}clear(){let Z=this.mode==="record"?[...this]:null;if(super.clear(),Z)this.cacheUpdateNumber++,this.emit(`clear:${JSON.stringify(Z)}`)}delete(Z){let X=super.delete(Z);if(this.mode==="record")this.cacheUpdateNumber++,this.emit(`del:${z0(Z)}`);return X}parent=null;child=null;transactionUpdates=null;transaction(Z){this.mode="transaction",this.transactionUpdates=[],this.child=new Y(this);let X=this.child._subscribe("transaction",(_)=>{this.transactionUpdates?.push(_)});try{if(Z(this.child)){for(let G of this.transactionUpdates)this.doStep(G);this.cacheUpdateNumber++,this.emit(`tx:${this.transactionUpdates.join(";")}`)}}catch(_){throw console.warn("Did not apply transaction to SetRTX; this error was thrown:",_),_}finally{X(),this.child=null,this.transactionUpdates=null,this.mode="record"}}_subscribe(Z,X){return this.subject.subscribe(Z,X)}subscribe(Z,X){return this.subject.subscribe(Z,(_)=>{X(`${this.cacheUpdateNumber}=${_}`)})}emit(Z){this.subject.next(Z)}doStep(Z){let X=Z.indexOf(":"),_=Z.substring(0,X),G=Z.substring(X+1);switch(_){case"add":this.add(JSON.parse(G));break;case"clear":this.clear();break;case"del":this.delete(JSON.parse(G));break;case"tx":for(let W of G.split(";"))this.doStep(W)}}getUpdateNumber(Z){let X=Z.indexOf("=");return Number(Z.substring(0,X))}do(Z){let X=Z.indexOf("="),_=Number(Z.substring(0,X)),G=_-this.cacheUpdateNumber;if(G>0){if(G===1){this.mode="playback";let $=Z.substring(X+1);return this.doStep($),this.mode="record",this.cacheUpdateNumber=_,null}return this.cacheUpdateNumber+1}if(Math.abs(G)<this.cacheLimit){let $=this.cacheIdx+G;if(this.cache[$]===Z)return null;this.mode="playback";let Q=!1;while(!Q){this.cacheIdx%=this.cacheLimit;let z=this.cache[this.cacheIdx];if(this.cacheIdx--,!z)return"OUT_OF_RANGE";this.undo(z),Q=this.cacheIdx===$-1}let J=Z.substring(X+1);return this.doStep(J),this.mode="record",this.cacheUpdateNumber=_,null}return"OUT_OF_RANGE"}undoStep(Z){let X=Z.indexOf(":"),_=Z.substring(0,X),G=Z.substring(X+1);switch(_){case"add":this.delete(JSON.parse(G));break;case"del":this.add(JSON.parse(G));break;case"clear":{let W=JSON.parse(G);for(let $ of W)this.add($);break}case"tx":{let W=G.split(";");for(let $=W.length-1;$>=0;$--)this.undoStep(W[$])}}}undo(Z){let X=Z.indexOf("=");if(Number(Z.substring(0,X))===this.cacheUpdateNumber){this.mode="playback";let G=Z.substring(X+1);return this.undoStep(G),this.mode="record",this.cacheUpdateNumber--,null}return this.cacheUpdateNumber}};function SZ(Y=Math.random){return Y().toString(36).slice(2)}function i(Y){while(Y.child!==null)Y=Y.child;return Y}var BU=class Y{_buffer;_index=0;constructor(Z){let X;if(typeof Z==="number")X=Z;else X=Z.length;this._buffer=Array.from({length:X})}get buffer(){return this._buffer}get index(){return this._index}add(Z){this._buffer[this._index]=Z,this._index=(this._index+1)%this._buffer.length}copy(){let Z=new Y([...this._buffer]);return Z._index=this._index,Z}},CU={atom_family:"atom",molecule_family:"molecule",mutable_atom_family:"mutable_atom",readonly_held_selector_family:"readonly_held_selector",readonly_pure_selector_family:"readonly_pure_selector",writable_held_selector_family:"writable_held_selector",writable_pure_selector_family:"writable_pure_selector"};function TU(Y,Z){let X=z0(Z),_=`${Y.key}(${X})`,G=CU[Y.type],W={key:_,type:G};return Object.assign(W,{family:{key:Y.key,subKey:X}}),Object.assign(W,{counterfeit:!0}),W}function G4(Y){let Z={key:Y.key,type:Y.type};if("family"in Y)Z.family=Y.family;return Z}var W1=class{a;b;cardinality;relations=new Map;contents=new Map;isAType;isBType;isContent;makeContentKey=(Y,Z)=>`${Y}:${Z}`;warn;getRelatedKeys(Y){return this.relations.get(Y)}addRelation(Y,Z){let X=this.relations.get(Y),_=this.relations.get(Z);if(X)X.add(Z);else X=new Set([Z]),this.relations.set(Y,X);if(_)_.add(Y);else _=new Set([Y]),this.relations.set(Z,_)}deleteRelation(Y,Z){let X=this.relations.get(Y);if(X){if(X.delete(Z),X.size===0)this.relations.delete(Y);let _=this.relations.get(Z);if(_){if(_.delete(Y),_.size===0)this.relations.delete(Z)}}}replaceRelationsUnsafely(Y,Z){this.relations.set(Y,new Set(Z));for(let X of Z){let _=new Set().add(Y);this.relations.set(X,_)}}replaceRelationsSafely(Y,Z){let X=this.relations.get(Y),_=this.isAType?.(Y)?Y:void 0,G=_===void 0?Y:void 0;if(X)for(let W of X){_??=W,G??=W;let $=this.relations.get(W);if($){if($.size===1)this.relations.delete(W);else $.delete(Y);this.contents.delete(this.makeContentKey(_,G))}}this.relations.set(Y,new Set(Z));for(let W of Z){let $=this.relations.get(W);if($)$.add(Y);else $=new Set().add(Y),this.relations.set(W,$)}}getContentInternal(Y){return this.contents.get(Y)}setContent(Y,Z){this.contents.set(Y,Z)}deleteContent(Y){this.contents.delete(Y)}constructor(Y,Z){if(this.a=Y.between[0],this.b=Y.between[1],this.cardinality=Y.cardinality,!Z?.externalStore)this.relations=new Map(Y.relations?.map(([X,_])=>[X,new Set(_)])),this.contents=new Map(Y.contents);if(this.isAType=Z?.isAType??null,this.isBType=Z?.isBType??null,this.isContent=Z?.isContent??null,Z?.makeContentKey)this.makeContentKey=Z.makeContentKey;if(Z?.externalStore){let X=Z.externalStore;if(this.has=(_,G)=>X.has(_,G),this.addRelation=(_,G)=>{X.addRelation(_,G)},this.deleteRelation=(_,G)=>{X.deleteRelation(_,G)},this.replaceRelationsSafely=(_,G)=>{X.replaceRelationsSafely(_,G)},this.replaceRelationsUnsafely=(_,G)=>{X.replaceRelationsUnsafely(_,G)},this.getRelatedKeys=(_)=>X.getRelatedKeys(_),X.getContent)this.getContentInternal=(_)=>{return X.getContent(_)},this.setContent=(_,G)=>{X.setContent(_,G)},this.deleteContent=(_)=>{X.deleteContent(_)};for(let[_,G]of Y.relations??[]){let W=this.isAType?.(_)?_:void 0,$=W===void 0?_:void 0;for(let H of G)W??=H,$??=H,this.addRelation(W,$)}for(let[_,G]of Y.contents??[])this.setContent(_,G)}if(Z?.warn)this.warn=Z.warn}toJSON(){return{between:[this.a,this.b],cardinality:this.cardinality,relations:[...this.relations.entries()].map(([Y,Z])=>[Y,[...Z]]),contents:[...this.contents.entries()]}}set(...Y){let Z,X,_;switch(Y.length){case 1:{let G=Y[0];Z=G[this.a],X=G[this.b],_=void 0;break}case 2:{let G=Y[0];if(typeof G==="string")[Z,X]=Y;else Z=G[this.a],X=G[this.b],_=Y[1];break}default:Z=Y[0],X=Y[1],_=Y[2];break}switch(this.cardinality){case"1:1":{let G=this.getRelatedKey(Z);if(G&&G!==X)this.delete(Z,G)}case"1:n":{let G=this.getRelatedKey(X);if(G&&G!==Z)this.delete(G,X)}break;case"n:n":}if(_){let G=this.makeContentKey(Z,X);this.setContent(G,_)}return this.addRelation(Z,X),this}delete(Y,Z){Z=typeof Z==="string"?Z:Y[this.b];let X=typeof Y==="string"?Y:Y[this.a];if(X===void 0&&typeof Z==="string"){let _=this.getRelatedKeys(Z);if(_)for(let G of _)this.delete(G,Z)}if(typeof X==="string"&&Z===void 0){let _=this.getRelatedKeys(X);if(_)for(let G of _)this.delete(X,G)}if(typeof X==="string"&&typeof Z==="string"){this.deleteRelation(X,Z);let _=this.makeContentKey(X,Z);this.deleteContent(_)}return this}getRelatedKey(Y){let Z=this.getRelatedKeys(Y);if(Z){if(Z.size>1)this.warn?.(`${Z.size} related keys were found for key "${Y}": (${[...Z].map((_)=>`"${_}"`).join(", ")}). Only one related key was expected.`);let X;for(let _ of Z){X=_;break}return X}}replaceRelations(Y,Z,X){let _=!Array.isArray(Z),G=_?Object.keys(Z):Z;if(X?.reckless)this.replaceRelationsUnsafely(Y,G);else this.replaceRelationsSafely(Y,G);if(_)for(let W of G){let $=this.makeContentKey(Y,W),H=Z[W];this.setContent($,H)}return this}getContent(Y,Z){let X=this.makeContentKey(Y,Z);return this.getContentInternal(X)}getRelationEntries(Y){let Z=Y[this.a],X=Y[this.b];if(Z!==void 0&&X===void 0){let _=this.getRelatedKeys(Z);if(_)return[..._].map((G)=>{return[G,this.getContent(Z,G)]})}if(Z===void 0&&X!==void 0){let _=this.getRelatedKeys(X);if(_)return[..._].map((G)=>{return[G,this.getContent(G,X)]})}return[]}has(Y,Z){if(Z)return this.getRelatedKeys(Y)?.has(Z)??!1;return this.relations.has(Y)}},H0=class{Subscriber;subscribers=new Map;subscribe(Y,Z){return this.subscribers.set(Y,Z),()=>{this.unsubscribe(Y)}}unsubscribe(Y){this.subscribers.delete(Y)}next(Y){let Z=this.subscribers.values();for(let X of Z)X(Y)}},KU=class extends H0{state;constructor(Y){super();this.state=Y}next(Y){this.state=Y,super.next(Y)}},qU=(Y,Z)=>{let X=i(Y);if(X.operation.open)return X.operation.prev.get(Z.key);return X.valueMap.get(Z.key)};var bZ=class extends Promise{fate;resolve;reject;done=!1;constructor(Y){let Z,X;super((_,G)=>{Z=_,X=G});this.resolve=Z,this.reject=X,this.use(Y instanceof Promise?Y:new Promise(Y))}pass(Y,Z){if(Y===this.fate)this.resolve(Z),this.done=!0}fail(Y,Z){if(Y===this.fate)this.reject(Z),this.done=!0}use(Y){if(this===Y)return;if(Y instanceof Promise){let Z=Y;this.fate=Z,Z.then((X)=>{this.pass(Z,X)},(X)=>{this.fail(Z,X)})}else this.resolve(Y),this.fate=void 0}};function kZ(Y,Z,X){let _=X.valueMap.get(Z.key),G=Y.valueMap.get(Z.key);if(_!==G)return G;if(_===void 0)return Z.default();X.logger.info("\uD83D\uDCC3","atom",Z.key,"copying");let W=Z.toJson(_),$=Z.fromJson(W);return Y.valueMap.set(Z.key,$),new lZ(Z,X),$}function R4(Y){return"epoch"in Y.transactionMeta}function o0(Y){return"phase"in Y.transactionMeta}var V6=(Y,Z)=>{if(Y.operation.open){let X=performance.now();return Y.logger.info("\u2757",Z.type,Z.key,`deferring setState at T-${X} until setState for "${Y.operation.token.key}" is done`),X}Y.operation={open:!0,done:new Set,prev:new Map,time:Date.now(),token:Z},Y.logger.info("\u2B55",Z.type,Z.key,`operation start in store "${Y.config.name}"${!o0(Y)?"":` ${Y.transactionMeta.phase} "${Y.transactionMeta.update.key}"`}`)},M6=(Y)=>{if(Y.operation.open)Y.logger.info("\uD83D\uDD34",Y.operation.token.type,Y.operation.token.key,`operation done in store "${Y.config.name}"`);Y.operation={open:!1},Y.on.operationClose.next(Y.operation)},x9=(Y,Z)=>{if(!Y.operation.open)return Y.logger.error("\uD83D\uDC1E","unknown",Z,"isDone called outside of an operation. This is probably a bug in AtomIO."),!0;return Y.operation.done.has(Z)},z2=(Y,Z)=>{if(!Y.operation.open){Y.logger.error("\uD83D\uDC1E","unknown",Z,"markDone called outside of an operation. This is probably a bug in AtomIO.");return}Y.operation.done.add(Z)};function gZ(Y,Z){let X=i(Y),_=X.selectorAtoms.getRelatedKeys(Z.key);if(X.logger.info("\uD83E\uDDF9",Z.type,Z.key,_?`evicting ${_.size} states downstream:`:"no downstream states",_??"to evict"),_){if(X.operation.open)X.logger.info("\uD83E\uDDF9",Z.type,Z.key,`[ ${[...X.operation.done].join(", ")} ] already done`);for(let G of _){if(x9(X,G))continue;h9(X,G),z2(X,G)}}}function jU(Y,Z){let X=i(Y),_=X.selectorGraph.getRelationEntries({upstreamSelectorKey:Z.key}).filter(([G,{source:W}])=>W===Z.key);for(let[G]of _){if(x9(X,G))continue;h9(X,G),z2(X,G)}}function W4(Y,Z,X,_){let G=Y.valueMap.get(Z);if(G instanceof bZ&&!G.done){let W=G;if(X instanceof Promise)return W.use(X),W;return Y.valueMap.set(Z,X),X}if(X instanceof Promise){let W=new bZ(X);return Y.valueMap.set(Z,W),W.then(function $(H){if(Y.valueMap.get(Z)===W){W4(Y,Z,H,_);let J=Y.atoms.get(Z);if(J)V6(Y,J),gZ(Y,J),M6(Y);else{let z=Y.writableSelectors.get(Z)??Y.readonlySelectors.get(Z);if(z)V6(Y,z),jU(Y,z),M6(Y)}_.next({newValue:H,oldValue:W})}}).catch(($)=>{Y.logger.error("\uD83D\uDCA5","state",Z,"rejected:",$)}),W}return Y.valueMap.set(Z,X),X}var PU=(Y,Z)=>{Z.logger.info("\uD83D\uDCD6",Y.type,Y.key,"reading cached value");let X=Z.valueMap.get(Y.key);if(Y.type==="mutable_atom"&&o0(Z)){let{parent:_}=Z;X=kZ(Z,Y,_)}return X},h9=(Y,Z)=>{let X=Y.valueMap.get(Z);if(X instanceof bZ){let _=Y.writableSelectors.get(Z)??Y.readonlySelectors.get(Z);if(_)_.get();return}if(Y.operation.open)Y.operation.prev.set(Z,X);Y.valueMap.delete(Z),Y.logger.info("\uD83D\uDDD1","state",Z,"evicted")},U2=(Y,Z)=>{if(Y.valueMap.has(Z.key))return PU(Z,Y);switch(Z.type){case"readonly_held_selector":case"readonly_pure_selector":case"writable_held_selector":case"writable_pure_selector":return Y.logger.info("\uD83E\uDDEE",Z.type,Z.key,"computing value"),Z.get();case"atom":case"mutable_atom":{let X=Z.default,_;if(X instanceof Function)_=X();else _=X;let G=W4(Y,Z.key,_,Z.subject);return Y.logger.info("\uD83D\uDC81","atom",Z.key,"could not find cached value; using default",_),G}}},j9=(Y,Z,X)=>{return X.subject.subscribe(`${Z.type}:${Z.key}`,(_)=>{Y.logger.info("\uD83D\uDCE2",Z.type,Z.key,"root",X.key,"went",_.oldValue,"->",_.newValue);let G=qU(Y,Z),W=U2(Y,Z);Y.logger.info("\u2728",Z.type,Z.key,"went",G,"->",W),Z.subject.next({newValue:W,oldValue:G})})},yZ=(Y)=>(Z)=>Y instanceof Function?Y(Z):Y,SU=(Y,Z,X)=>{switch(Z.type){case"mutable_atom":Y.logger.info("\uD83D\uDCE2",Z.type,Z.key,"is now (",X.newValue,") subscribers:",Z.subject.subscribers);break;case"atom":case"writable_pure_selector":case"readonly_pure_selector":case"writable_held_selector":case"readonly_held_selector":Y.logger.info("\uD83D\uDCE2",Z.type,Z.key,"went (",X.oldValue,"->",X.newValue,") subscribers:",Z.subject.subscribers)}Z.subject.next(X)},f9=(Y,Z,X)=>{let _=U2(Y,Z),G=_;if(Z.type==="mutable_atom"&&o0(Y)){let{parent:$}=Y;G=kZ(Y,Z,$)}G=yZ(X)(G),Y.logger.info("\uD83D\uDCDD","atom",Z.key,"set to",G),G=W4(Y,Z.key,G,Z.subject),z2(Y,Z.key),gZ(Y,Z);let W={oldValue:_,newValue:G};if(!o0(Y)){SU(Y,Z,W);return}if(Y.on.transactionApplying.state===null){let{key:$}=Z;if(XF(W.newValue))return;let H={type:"atom_update",key:$,...W};if(Z.family)H.family=Z.family;Y.transactionMeta.update.updates.push(H),Y.logger.info("\uD83D\uDCC1","atom",$,"stowed (",W.oldValue,"->",W.newValue,")")}else if(Z.key.startsWith("*")){let $=Z.key.slice(1),H=Y.atoms.get($),Q=Y.valueMap.get($);if(H.type==="mutable_atom"&&o0(Y)){let{parent:z}=Y;Q=kZ(Y,H,z)}if(Q.do(W.newValue)===null)gZ(Y,H)}};function P9(Y,Z){let X=Z.default;if(X instanceof Function)X=X();f9(Y,Z,X)}function vU(Y,Z){switch(Z.type){case"atom":case"mutable_atom":P9(Y,Z);break;case"writable_pure_selector":case"writable_held_selector":{let X=A6(Y,Z.key);for(let _ of X.values())P9(Y,_)}break}}function b9(Y,Z){if(Z.family){let X=Y.families.get(Z.family.key);if(X)return X}}function E8(Y,...Z){let X,_,G;if(Z.length===1){if(X=Z[0],_=b9(Y,X)??null,_)G=X.family?G1(X.family.subKey):null,X=$0(Y,_,G)}else _=Z[0],G=Z[1],X=$0(Y,_,G);if("counterfeit"in X&&"family"in X){let H=X.family.subKey,Q=Y.disposalTraces.buffer.find((J)=>J?.key===H);Y.logger.error("\u274C",X.type,X.key,`could not be reset because it was not found in the store "${Y.config.name}".`,Q?`This state was previously disposed:
48
+ ${Q.trace}`:"No previous disposal trace was found.");return}let W=V6(Y,X);if(W){let H=Y.on.operationClose.subscribe(`waiting to reset "${X.key}" at T-${W}`,()=>{H(),Y.logger.info("\uD83D\uDFE2",X.type,X.key,`resuming deferred resetState from T-${W}`),E8(Y,X)});return}let $=h0(Y,X);vU(Y,$),M6(Y)}var k9=(Y,Z,X)=>{switch(Z.type){case"atom":case"mutable_atom":f9(Y,Z,X);break;case"writable_pure_selector":case"writable_held_selector":Z.set(X);break}};function R1(Y,...Z){let X,_,G,W;if(Z.length===2){if(X=Z[0],W=Z[1],_=b9(Y,X)??null,_)G=X.family?G1(X.family.subKey):null,X=$0(Y,_,G)}else _=Z[0],G=Z[1],W=Z[2],X=$0(Y,_,G);if("counterfeit"in X&&"family"in X){let Q=X.family.subKey,J=Y.disposalTraces.buffer.find((z)=>z?.key===Q);Y.logger.error("\u274C",X.type,X.key,`could not be set because it was not found in the store "${Y.config.name}".`,J?`This state was previously disposed:
49
+ ${J.trace}`:"No previous disposal trace was found.");return}let $=V6(Y,X);if($){let Q=Y.on.operationClose.subscribe(`waiting to set "${X.key}" at T-${$}`,()=>{Q(),Y.logger.info("\uD83D\uDFE2",X.type,X.key,`resuming deferred setState from T-${$}`),R1(Y,X,W)});return}let H=h0(Y,X);k9(Y,H,W),M6(Y)}var g9=(Y,Z)=>i(Y).atoms.has(Z),xU=(Y,Z)=>i(Y).writableSelectors.has(Z),hU=(Y,Z)=>i(Y).readonlySelectors.has(Z),fU=(Y,Z)=>g9(Y,Z)||xU(Y,Z)||hU(Y,Z),S9=(Y,Z)=>{return i(Y).selectorGraph.getRelationEntries({downstreamSelectorKey:Z}).filter(([_,{source:G}])=>G!==Z).map(([_,{source:G}])=>G).filter((_)=>fU(Y,_))},A6=(Y,Z,X=new Set)=>{let _=S9(Y,Z),G=new Map;while(_.length>0){let W=_.pop();if(X.has(W))continue;if(X.add(W),g9(Y,W)){let $=Y.atoms.get(W);G.set($.key,$)}else _.push(...S9(Y,W))}return G},bU=(Y,Z,X,_,G)=>{let W=i(Y),{type:$,key:H}=_;if($==="atom"||$==="mutable_atom")W.selectorAtoms.set({selectorKey:X,atomKey:H}),Y.logger.info("\uD83D\uDD0D",Z,X,`discovers root atom "${H}"`);else{let Q=A6(Y,H,G);Y.logger.info("\uD83D\uDD0D",Z,X,`discovers root atoms: [ ${[...Q.values()].map((J)=>`"${J.key}"`).join(", ")} ]`);for(let{key:J}of Q.values())W.selectorAtoms=W.selectorAtoms.set({selectorKey:X,atomKey:J})}G.add(H)},w6=(Y,Z,X,_)=>({get:(...G)=>{let W=i(Y),$;if(G.length===2){let[z,O]=G;$=$0(Y,z,O)}else[$]=G;let H=h0(Y,$),Q=U2(Y,H),J=$.key;return Y.logger.info("\uD83D\uDD0C",Z,X,`registers dependency ( "${J}" =`,Q,")"),W.selectorGraph.set({upstreamSelectorKey:J,downstreamSelectorKey:X},{source:$.key}),bU(Y,Z,X,$,_),Q},set:(...G)=>{let W,$;if(G.length===2)W=G[0],$=G[1];else{let J=G[0],z=G[1];$=G[2],W=$0(Y,J,z)}let H=i(Y),Q=h0(H,W);k9(H,Q,$)},find:(...G)=>$0(Y,...G),json:(G)=>k4(Y,G)}),pZ=(Y,Z,X)=>{let _=i(Y),G=new H0,W=new Set,{key:$,const:H}=Z,Q="readonly_held_selector",{get:J,find:z,json:O}=w6(_,"readonly_held_selector",$,W),V={...Z,type:"readonly_held_selector",subject:G,install:(A)=>pZ(A,Z,X),get:()=>{let A=i(Y),g=A.selectorGraph.getRelationEntries({downstreamSelectorKey:$});for(let[b,{source:f}]of g)if(f!==$)A.selectorGraph.delete(b,$);return A.selectorAtoms.delete($),Z.get({get:J,find:z,json:O},H),W4(i(Y),$,H,G),W.clear(),H},...X&&{family:X}};_.readonlySelectors.set($,V),Y.logger.info("\u2728","readonly_held_selector",$,"=",H);let R={key:$,type:"readonly_held_selector"};if(X)R.family=X;return R},mZ=(Y,Z,X)=>{let _=i(Y),G=new H0,W=new Set,$=Z.key,H="readonly_pure_selector",{get:Q,find:J,json:z}=w6(_,"readonly_pure_selector",$,W),D={...Z,type:"readonly_pure_selector",subject:G,install:(R)=>mZ(R,Z,X),get:()=>{let R=i(Y),A=R.selectorGraph.getRelationEntries({downstreamSelectorKey:$});for(let[f,{source:h}]of A)if(h!==$)R.selectorGraph.delete(f,$);R.selectorAtoms.delete($);let g=Z.get({get:Q,find:J,json:z}),b=W4(R,$,g,G);return Y.logger.info("\u2728","readonly_pure_selector",$,"=",b),W.clear(),b},...X&&{family:X}};_.readonlySelectors.set($,D);let V={key:$,type:"readonly_pure_selector"};if(X)V.family=X;return V},kU=(Y)=>{let Z=i(Y);if(!o0(Z)){Y.logger.warn("\uD83D\uDC1E","transaction","???","abortTransaction called outside of a transaction. This is probably a bug in AtomIO.");return}Y.logger.info("\uD83E\uDE82","transaction",Z.transactionMeta.update.key,"Aborting transaction"),Z.parent.child=null};function B0(Y){return Y[0].toUpperCase()+Y.slice(1)}function b4(Y){return Y.type.split("_").map(B0).join(" ")}var uZ=class extends Error{constructor(Y,Z){super(`${b4(Y)} ${z0(Y.key)} not found in store "${Z.config.name}".`)}};function vZ(Y,Z,X){return(..._)=>{let G=h0(Y,Z);if(G)return G.run(_,X);throw new uZ(Z,Y)}}function gU(Y,Z,X){let{key:_,newValue:G,oldValue:W}=Z,$=Y==="newValue"?G:W,H={key:_,type:"atom"};if(Z.family)Object.assign(H,{family:Z.family});R1(X,H,$)}function yU(Y){let{stack:Z}=Y;if(Z)return`
50
50
  `+Z.split(`
51
51
  `)?.slice(1)?.join(`
52
- `);return""}function I7(Y,Z=x0.STORE){let X={key:Y,stringKey:z0(Y),dependsOn:"any"};return Z.molecules.set(z0(Y),X),Y}function D8(Y,Z,X,_="any"){let G=Z,W=z0(X),H=[],J=i(Y);if(Array.isArray(G))for(let z of G){let O=z0(z);if(J.molecules.get(O))Y.moleculeGraph.set(O,W,{source:O});else H.push(O)}else{let z=z0(G);if(J.molecules.get(z))Y.moleculeGraph.set(z,W,{source:z});else H.push(z)}if(H.length===0)J.molecules.set(W,{key:X,stringKey:W,dependsOn:_});let $={type:"molecule_creation",key:X,provenance:G};if(o0(J)&&J.transactionMeta.phase==="building")J.transactionMeta.update.updates.push($);else J.on.moleculeCreation.next($);for(let z of H){let O=Y.disposalTraces.buffer.find((D)=>D?.key===z);Y.logger.error("\u274C","molecule",X,"allocation failed:",`Could not allocate to ${z} in store "${Y.config.name}".`,O?`
52
+ `);return""}function N9(Y,Z=x0.STORE){let X={key:Y,stringKey:z0(Y),dependsOn:"any"};return Z.molecules.set(z0(Y),X),Y}function D8(Y,Z,X,_="any"){let G=Z,W=z0(X),$=[],H=i(Y);if(Array.isArray(G))for(let z of G){let O=z0(z);if(H.molecules.get(O))Y.moleculeGraph.set(O,W,{source:O});else $.push(O)}else{let z=z0(G);if(H.molecules.get(z))Y.moleculeGraph.set(z,W,{source:z});else $.push(z)}if($.length===0)H.molecules.set(W,{key:X,stringKey:W,dependsOn:_});let Q={type:"molecule_creation",key:X,provenance:G};if(o0(H)&&H.transactionMeta.phase==="building")H.transactionMeta.update.updates.push(Q);else H.on.moleculeCreation.next(Q);for(let z of $){let O=Y.disposalTraces.buffer.find((D)=>D?.key===z);Y.logger.error("\u274C","molecule",X,"allocation failed:",`Could not allocate to ${z} in store "${Y.config.name}".`,O?`
53
53
  ${z} was most recently disposed
54
- ${O.trace}`:`No previous disposal trace for ${z} was found.`)}return X}function B7(Y,Z,X,_){let G=`T$--${Z}==${X}++${_}`;return D8(Y,[X,_],G,"all"),G}function L8(Y,Z){let X=z0(Z),_=Y.molecules.get(X);if(!_){let V=Y.disposalTraces.buffer.find((R)=>R?.key===X);Y.logger.error("\u274C","molecule",Z,"deallocation failed:",`Could not find allocation for ${X} in store "${Y.config.name}".`,V?`
54
+ ${O.trace}`:`No previous disposal trace for ${z} was found.`)}return X}function I9(Y,Z,X,_){let G=`T$--${Z}==${X}++${_}`;return D8(Y,[X,_],G,"all"),G}function L8(Y,Z){let X=z0(Z),_=Y.molecules.get(X);if(!_){let V=Y.disposalTraces.buffer.find((R)=>R?.key===X);Y.logger.error("\u274C","molecule",Z,"deallocation failed:",`Could not find allocation for ${X} in store "${Y.config.name}".`,V?`
55
55
  This state was most recently deallocated
56
- ${V.trace}`:`No previous disposal trace for ${X} was found.`);return}let G=Y.moleculeJoins.getRelatedKeys(_.key);if(G)for(let V of G){let R=Y.joins.get(V);if(R)R.relations.delete(_.key),R.molecules.delete(_.stringKey)}Y.moleculeJoins.delete(_.stringKey);let W=[],H=[],J={type:"molecule_disposal",key:_.key,values:H,provenance:W},$=i(Y);$.molecules.delete(X);let Q=o0($)&&$.transactionMeta.phase==="building";if(Q)$.transactionMeta.update.updates.push(J);let z=Y.moleculeGraph.getRelationEntries({downstreamMoleculeKey:_.stringKey});if(z)for(let[V,{source:R}]of z)if(R===_.stringKey){let A=G1(V);L8(Y,A)}else W.push(R);let O=$.moleculeData.getRelatedKeys(_.stringKey);if(O)for(let V of O){let R=$.families.get(V),A=H0(Y,R,_.key);H.push([R.key,A]),V8(Y,A)}if($.moleculeGraph.delete(_.stringKey),$.moleculeJoins.delete(_.stringKey),$.moleculeData.delete(_.stringKey),!Q)$.on.moleculeDisposal.next(J);$.molecules.delete(_.stringKey);let D=mF(new Error);Y.disposalTraces.add({key:X,trace:D})}function J6(Y,Z,X,_){let G=z0(X),W=i(Y),H=W.molecules.get(G);if(!H){let D=Y.disposalTraces.buffer.find((V)=>V?.key===G);return Y.logger.error("\u274C","molecule",X,"claim failed:",`Could not allocate to ${G} in store "${Y.config.name}".`,D?`
56
+ ${V.trace}`:`No previous disposal trace for ${X} was found.`);return}let G=Y.moleculeJoins.getRelatedKeys(_.key);if(G)for(let V of G){let R=Y.joins.get(V);if(R)R.relations.delete(_.key),R.molecules.delete(_.stringKey)}Y.moleculeJoins.delete(_.stringKey);let W=[],$=[],H={type:"molecule_disposal",key:_.key,values:$,provenance:W},Q=i(Y);Q.molecules.delete(X);let J=o0(Q)&&Q.transactionMeta.phase==="building";if(J)Q.transactionMeta.update.updates.push(H);let z=Y.moleculeGraph.getRelationEntries({downstreamMoleculeKey:_.stringKey});if(z)for(let[V,{source:R}]of z)if(R===_.stringKey){let A=G1(V);L8(Y,A)}else W.push(R);let O=Q.moleculeData.getRelatedKeys(_.stringKey);if(O)for(let V of O){let R=Q.families.get(V),A=$0(Y,R,_.key);$.push([R.key,A]),M8(Y,A)}if(Q.moleculeGraph.delete(_.stringKey),Q.moleculeJoins.delete(_.stringKey),Q.moleculeData.delete(_.stringKey),!J)Q.on.moleculeDisposal.next(H);Q.molecules.delete(_.stringKey);let D=yU(new Error);Y.disposalTraces.add({key:X,trace:D})}function J2(Y,Z,X,_){let G=z0(X),W=i(Y),$=W.molecules.get(G);if(!$){let D=Y.disposalTraces.buffer.find((V)=>V?.key===G);return Y.logger.error("\u274C","molecule",X,"claim failed:",`Could not allocate to ${G} in store "${Y.config.name}".`,D?`
57
57
  ${G} was most recently disposed
58
- ${D.trace}`:`No previous disposal trace for ${G} was found.`),X}let J=z0(Z),$=W.molecules.get(J);if(!$){let D=Y.disposalTraces.buffer.find((V)=>V?.key===J);return Y.logger.error("\u274C","molecule",X,"claim failed:",`Could not allocate to ${J} in store "${Y.config.name}".`,D?`
59
- ${J} was most recently disposed
60
- ${D.trace}`:`No previous disposal trace for ${J} was found.`),X}let Q=Y.moleculeGraph.getRelationEntries({downstreamMoleculeKey:H.stringKey}).filter(([,{source:D}])=>D!==G).map(([D])=>G1(D));if(_)W.moleculeGraph.delete(G);W.moleculeGraph.set({upstreamMoleculeKey:$.stringKey,downstreamMoleculeKey:H.stringKey},{source:$.stringKey});let z={type:"molecule_transfer",key:H.key,from:Q,to:[$.key]};if(o0(W)&&W.transactionMeta.phase==="building")W.transactionMeta.update.updates.push(z);return X}function uF(Y,Z,X){switch(Z){case"newValue":m7(Y,X);break;case"oldValue":V8(X,Y.token);break}}function dF(Y,Z,X){switch(Z){case"newValue":V8(X,Y.token);break;case"oldValue":if(m7(Y,X),Y.subType==="atom")X.valueMap.set(Y.token.key,Y.value);break}}function m7(Y,Z){let{family:X}=Y.token;if(X){let _=Z.families.get(X.key);if(_)H0(Z,_,G1(X.subKey))}}function cF(Y,Z,X){switch(Z){case"newValue":D8(X,Y.provenance,Y.key);break;case"oldValue":L8(X,Y.key);break}}function lF(Y,Z,X){switch(Z){case"newValue":L8(X,Y.key);break;case"oldValue":{let _=Y.provenance.map(G1);D8(X,_,Y.key);for(let[G,W]of Y.values){let H=X.families.get(G);if(H){H0(X,H,Y.key);let J=`${G}(${z0(Y.key)})`;X.valueMap.set(J,W)}}}break}}function iF(Y,Z,X){switch(Z){case"newValue":{let _=Y.to.length===1?Y.to[0]:Y.to;J6(X,_,Y.key,"exclusive")}break;case"oldValue":{let _=Y.from.length===1?Y.from[0]:Y.from;J6(X,_,Y.key,"exclusive")}break}}function u7(Y,Z,X){let _=Y==="newValue"?Z.updates:[...Z.updates].reverse();for(let G of _)switch(G.type){case"atom_update":case"selector_update":pF(Y,G,X);break;case"state_creation":uF(G,Y,X);break;case"state_disposal":dF(G,Y,X);break;case"molecule_creation":cF(G,Y,X);break;case"molecule_disposal":lF(G,Y,X);break;case"molecule_transfer":iF(G,Y,X);break;case"transaction_update":u7(Y,G,X);break}}function d7(Y,Z){return Y.transactionMeta.actionContinuities.getRelatedKey(Z)}function oF(Y,Z){return Y.transactionMeta.epoch.get(Z)}function nF(Y,Z){if(!R4(Y))return;let _=d7(Y,Z);if(_===void 0)return;return oF(Y,_)}function rF(Y,Z,X){if(!R4(Y))return;let G=d7(Y,Z);if(G!==void 0)Y.transactionMeta.epoch.set(G,X)}var sF=(Y,Z)=>{let X=i(Z),{parent:_}=X;if(_===null||!o0(X)||X.transactionMeta?.phase!=="building"){Z.logger.warn("\uD83D\uDC1E","transaction","???","applyTransaction called outside of a transaction. This is probably a bug in AtomIO.");return}X.transactionMeta.phase="applying",X.transactionMeta.update.output=Y,_.child=null,_.on.transactionApplying.next(X.transactionMeta);let{updates:G}=X.transactionMeta.update;if(Z.logger.info("\uD83D\uDEC4","transaction",X.transactionMeta.update.key,`Applying transaction with ${G.length} updates:`,G),u7("newValue",X.transactionMeta.update,_),R4(_))rF(_,X.transactionMeta.update.key,X.transactionMeta.update.epoch),h0(Z,{key:X.transactionMeta.update.key,type:"transaction"})?.subject.next(X.transactionMeta.update),Z.logger.info("\uD83D\uDEEC","transaction",X.transactionMeta.update.key,"Finished applying transaction.");else if(o0(_))_.transactionMeta.update.updates.push(X.transactionMeta.update);_.on.transactionApplying.next(null)};function aF(Y){return{store:Y}}var i1=class extends Map{deleted=new Set;source;constructor(Y){super();this.source=Y}get(Y){if(super.has(Y))return super.get(Y);if(!this.deleted.has(Y)&&this.source.has(Y))return this.source.get(Y);return}set(Y,Z){return this.deleted.delete(Y),super.set(Y,Z)}hasOwn(Y){return super.has(Y)}has(Y){return!this.deleted.has(Y)&&(super.has(Y)||this.source.has(Y))}delete(Y){return this.deleted.add(Y),super.delete(Y)}},tF=(Y,Z,X,_)=>{let G=i(Y),W={parent:G,child:null,on:G.on,loggers:G.loggers,logger:G.logger,config:G.config,atoms:new i1(G.atoms),atomsThatAreDefault:new Set(G.atomsThatAreDefault),families:new i1(G.families),joins:new i1(G.joins),operation:{open:!1},readonlySelectors:new i1(G.readonlySelectors),timelines:new i1(G.timelines),timelineTopics:new W1(G.timelineTopics.toJSON()),trackers:new Map,transactions:new i1(G.transactions),selectorAtoms:new W1(G.selectorAtoms.toJSON()),selectorGraph:new W1(G.selectorGraph.toJSON(),{makeContentKey:(...Q)=>Q.sort().join(":")}),writableSelectors:new i1(G.writableSelectors),valueMap:new i1(G.valueMap),defaults:G.defaults,disposalTraces:Y.disposalTraces.copy(),molecules:new i1(G.molecules),moleculeGraph:new W1(G.moleculeGraph.toJSON(),{makeContentKey:G.moleculeGraph.makeContentKey}),moleculeData:new W1(G.moleculeData.toJSON(),{makeContentKey:G.moleculeData.makeContentKey}),moleculeJoins:new W1(G.moleculeJoins.toJSON(),{makeContentKey:G.moleculeJoins.makeContentKey}),miscResources:new i1(G.miscResources)},H=nF(Y,Z),J={phase:"building",update:{type:"transaction_update",key:Z,id:_,epoch:H===void 0?NaN:H+1,updates:[],params:X,output:void 0},toolkit:{get:(...Q)=>k1($,...Q),set:(...Q)=>{R1($,...Q)},reset:(...Q)=>{E8($,...Q)},run:(Q,z=P5())=>S5($,Q,z),find:(...Q)=>H0(Y,...Q),json:(Q)=>b4($,Q),dispose:(...Q)=>{V8($,...Q)},env:()=>aF($)}},$=Object.assign(W,{transactionMeta:J});return G.child=$,Y.logger.info("\uD83D\uDEEB","transaction",Z,"Building transaction with params:",X),$};function v5(Y,Z){let{key:X}=Z,_=Y.transactions.has(X),G={key:X,type:"transaction",run:(J,$)=>{let Q=tF(Y,X,J,$);try{let z=i(Y),{toolkit:O}=Q.transactionMeta,D=Z.do(O,...J);return sF(D,z),D}catch(z){throw yF(W),Y.logger.warn("\uD83D\uDCA5","transaction",X,"caught:",z),z}},install:(J)=>v5(J,Z),subject:new J0},W=i(Y);W.transactions.set(X,G);let H=G4(G);if(!_)Y.on.transactionCreation.next(H);return H}var m5=(Y,Z,X)=>{let _=i(Y),G=new J0,W=new Set,{key:H,const:J}=Z,$="writable_held_selector",Q=AY(_,"writable_held_selector",H,W),{find:z,get:O,json:D}=Q,V={find:z,get:O,json:D},R=(f=Z.get,h=i(Y))=>{let I=h.selectorGraph.getRelationEntries({downstreamSelectorKey:H});for(let[N,{source:q}]of I)if(q!==H)h.selectorGraph.delete(N,H);return h.selectorAtoms.delete(H),f(V,J),W4(h,H,J,G),Y.logger.info("\u2728","writable_held_selector",H,"=",J),W.clear(),J},g={...Z,type:"writable_held_selector",subject:G,install:(f)=>m5(f,Z,X),get:R,set:(f)=>{let h=i(Y),I=R(Z.get,h),N=k5(f)(I);if(Y.logger.info("\uD83D\uDCDD","writable_held_selector",H,"set (",I,"->",N,")"),W4(h,H,N,G),$6(h,H),R4(h))G.next({newValue:N,oldValue:I});Z.set(Q,N)},...X&&{family:X}};_.writableSelectors.set(H,g);let b={key:H,type:"writable_held_selector"};if(X)b.family=X;return b},u5=(Y,Z,X)=>{let _=i(Y),G=new J0,W=new Set,H=Z.key,J="writable_pure_selector",$=AY(_,"writable_pure_selector",H,W),{find:Q,get:z,json:O}=$,D={find:Q,get:z,json:O},V=(f=Z.get,h=i(Y))=>{let I=h.selectorGraph.getRelationEntries({downstreamSelectorKey:H});for(let[K,{source:p}]of I)if(p!==H)h.selectorGraph.delete(K,H);h.selectorAtoms.delete(H);let N=f(D),q=W4(h,H,N,G);return Y.logger.info("\u2728","writable_pure_selector",H,"=",q),W.clear(),N},A={...Z,type:"writable_pure_selector",subject:G,install:(f)=>u5(f,Z,X),get:V,set:(f)=>{let h=i(Y),I=V(Z.get,h),N=k5(f)(I);if(Y.logger.info("\uD83D\uDCDD","writable_pure_selector",H,"set (",I,"->",N,")"),W4(h,Z.key,N,G),$6(h,Z.key),R4(h))G.next({newValue:N,oldValue:I});Z.set($,N)},...X&&{family:X}};_.writableSelectors.set(H,A);let g=V();Y.logger.info("\u2728",A.type,A.key,"=",g);let b={key:H,type:"writable_pure_selector"};if(X)b.family=X;return b};function K5(Y,Z){let X="set"in Z,_="const"in Z;if(_&&X){let W=m5(Y,Z,void 0);return Y.on.selectorCreation.next(W),W}if(_){let W=g5(Y,Z,void 0);return Y.on.selectorCreation.next(W),W}if(X){let W=u5(Y,Z,void 0);return Y.on.selectorCreation.next(W),W}let G=y5(Y,Z,void 0);return Y.on.selectorCreation.next(G),G}function eF(Y,Z){let X=i(Y),{key:_,type:G}=Z,W=h0(X,Z);if(!W.family)Y.logger.error("\u274C",G,_,"Standalone selectors cannot be disposed.");else{if(X.molecules.get(W.family.subKey))X.moleculeData.delete(W.family.subKey,W.family.key);let J;switch(Z.type){case"writable_held_selector":X.writableSelectors.delete(_),J={key:W.family.key,type:"writable_held_selector_family"},h0(Y,J).subject.next({type:"state_disposal",subType:"selector",token:Z});break;case"writable_pure_selector":X.writableSelectors.delete(_),J={key:W.family.key,type:"writable_pure_selector_family"},h0(Y,J).subject.next({type:"state_disposal",subType:"selector",token:Z});break;case"readonly_held_selector":X.readonlySelectors.delete(_),J={key:W.family.key,type:"readonly_held_selector_family"},h0(Y,J).subject.next({type:"state_disposal",subType:"selector",token:Z});break;case"readonly_pure_selector":X.readonlySelectors.delete(_),J={key:W.family.key,type:"readonly_pure_selector_family"},h0(Y,J).subject.next({type:"state_disposal",subType:"selector",token:Z});break}if(X.valueMap.delete(_),X.selectorAtoms.delete(_),X.selectorGraph.delete(_),Y.logger.info("\uD83D\uDD25",Z.type,_,"deleted"),o0(X)&&X.transactionMeta.phase==="building")X.transactionMeta.update.updates.push({type:"state_disposal",subType:"selector",token:Z});else Y.on.selectorDisposal.next(Z)}}function h4(Y,Z,X){let _=Z.key,G="readonly_pure_selector_family",W={key:_,type:"readonly_pure_selector_family"},H=Y.families.get(_);if(H)Y.logger.error("\u2757","readonly_pure_selector_family",_,`Overwriting an existing ${f4(H)} "${H.key}" in store "${Y.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);let J=new J0,Q=Object.assign((z)=>{let O=z0(z),D={key:_,subKey:O},V=`${_}(${O})`,R=i(Y),A=y5(R,{key:V,get:Z.get(z)},D);return J.next({type:"state_creation",token:A}),A},W,{internalRoles:X,subject:J,install:(z)=>h4(z,Z),default:(z)=>{return Z.get(z)({get:(...D)=>k1(Y,...D),find:(...D)=>H0(Y,...D),json:(D)=>b4(Y,D)})}});return Y.families.set(_,Q),W}function c7(Y,Z,X){let _=Z.key,G="readonly_held_selector_family",W={key:_,type:"readonly_held_selector_family"},H=Y.families.get(_);if(H)Y.logger.error("\u2757","readonly_held_selector_family",_,`Overwriting an existing ${f4(H)} "${H.key}" in store "${Y.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);let J=new J0,Q=Object.assign((z)=>{let O=z0(z),D={key:_,subKey:O},V=`${_}(${O})`,R=i(Y),A=g5(R,{key:V,const:Z.const(z),get:Z.get(z)},D);return J.next({type:"state_creation",token:A}),A},W,{internalRoles:X,subject:J,install:(z)=>c7(z,Z),default:Z.const});return Y.families.set(_,Q),W}function l7(Y,Z,X){let _=Z.key,G="writable_held_selector_family",W={key:_,type:"writable_held_selector_family"},H=Y.families.get(_);if(H)Y.logger.error("\u2757","writable_held_selector_family",_,`Overwriting an existing ${f4(H)} "${H.key}" in store "${Y.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);let J=new J0,Q=Object.assign((z)=>{let O=z0(z),D={key:_,subKey:O},V=`${_}(${O})`,R=i(Y),A=m5(R,{key:V,const:Z.const(z),get:Z.get(z),set:Z.set(z)},D);return J.next({type:"state_creation",token:A}),A},W,{internalRoles:X,subject:J,install:(z)=>l7(z,Z),default:Z.const});return Y.families.set(_,Q),W}function OY(Y,Z,X){let _=Z.key,G="writable_pure_selector_family",W={key:_,type:"writable_pure_selector_family"},H=Y.families.get(_);if(H)Y.logger.error("\u2757","writable_pure_selector_family",_,`Overwriting an existing ${f4(H)} "${H.key}" in store "${Y.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);let J=new J0,Q=Object.assign((z)=>{let O=z0(z),D={key:_,subKey:O},V=`${_}(${O})`,R=i(Y),A=u5(R,{key:V,get:Z.get(z),set:Z.set(z)},D);return J.next({type:"state_creation",token:A}),A},W,{internalRoles:X,subject:J,install:(z)=>OY(z,Z),default:(z)=>{return Z.get(z)({get:(...D)=>k1(Y,...D),find:(...D)=>H0(Y,...D),json:(D)=>b4(Y,D)})}});return Y.families.set(_,Q),W}function x5(Y,Z){let X="set"in Z,_="const"in Z;if(_&&X)return l7(Y,Z,void 0);if(_)return c7(Y,Z,void 0);if(X)return OY(Y,Z);return h4(Y,Z)}function YU(Y,Z,X){let _=Y.families.get(Z.key);if(_===void 0)throw new p5(Z,Y);let G=_(X),W=i(Y);if(G.family){if(R4(W))switch(G.type){case"atom":case"mutable_atom":Y.on.atomCreation.next(G);break;case"writable_pure_selector":case"readonly_pure_selector":case"writable_held_selector":case"readonly_held_selector":Y.on.selectorCreation.next(G);break}else if(o0(W)&&W.on.transactionApplying.state===null)W.transactionMeta.update.updates.push({type:"state_creation",token:G})}return G}function ZU(Y,Z,X){let _=z0(X),G=`${Z.key}(${_})`,W=i(Y),H;switch(Z.type){case"atom_family":case"mutable_atom_family":H=W.atoms.get(G);break;case"writable_held_selector_family":case"writable_pure_selector_family":H=W.writableSelectors.get(G);break;case"readonly_held_selector_family":case"readonly_pure_selector_family":H=W.readonlySelectors.get(G);break}if(H)return G4(H);return H}function H0(Y,Z,X){let _=ZU(Y,Z,X);if(_)return _;let G=z0(X),W=Y.molecules.get(G);if(!W&&Y.config.lifespan==="immortal"){let H=qF(Z,X);return Y.logger.error("\u274C",H.type,H.key,`was not found in store "${Y.config.name}"; returned a counterfeit token.`),H}if(_=YU(Y,Z,X),W)i(Y).moleculeData.set(G,Z.key);return _}function V8(Y,...Z){let X;if(Z.length===1)X=Z[0];else{let _=Z[0],G=Z[1];X=H0(Y,_,G)}try{h0(Y,X)}catch(_){Y.logger.error("\u274C",X.type,X.key,`could not be disposed because it was not found in the store "${Y.config.name}".`);return}switch(X.type){case"atom":case"mutable_atom":o7(Y,X);break;case"writable_pure_selector":case"readonly_pure_selector":case"writable_held_selector":case"readonly_held_selector":eF(Y,X);break}}function k1(Y,...Z){let X,_,G;if(Z.length===1)X=Z[0];else _=Z[0],G=Z[1],X=H0(Y,_,G);if("counterfeit"in X&&"family"in X){_=Y.families.get(X.family.key);let W=X.family.subKey,H=Y.disposalTraces.buffer.find((J)=>J?.key===W);switch(Y.logger.error("\u274C",X.type,X.key,`could not be retrieved because it was not found in the store "${Y.config.name}".`,H?`This state was previously disposed:
61
- ${H.trace}`:"No previous disposal trace was found."),_.type){case"atom_family":case"mutable_atom_family":return Y.defaults.get(_.key);case"readonly_pure_selector_family":case"writable_pure_selector_family":case"readonly_held_selector_family":case"writable_held_selector_family":{if(Y.defaults.has(_.key))return Y.defaults.get(X.family.key);let J=h0(Y,_).default(W);return Y.defaults.set(_.key,J),J}}}return z6(Y,h0(Y,X))}function M8(Y,Z,X,_){function G(O){if(Y.operation.open){let D=Y.on.operationClose.subscribe(`state subscription ${X}`,()=>{D(),_(O)})}else _(O)}let W=h0(Y,Z);Y.logger.info("\uD83D\uDC40",W.type,W.key,`Adding subscription "${X}"`);let H=W.type==="writable_pure_selector"||W.type==="readonly_pure_selector",J=new Map,$=G;if(H){z6(Y,W);for(let[O,D]of MY(Y,W.key))J.set(O,S7(Y,W,D));$=function O(D){let V=MY(Y,W.key);for(let[R,A]of J)if(V.get(R))V.delete(R);else A(),J.delete(R);for(let[R,A]of V)J.set(R,S7(Y,W,A));G(D)}}let Q=W.subject.subscribe(X,$);return()=>{Y.logger.info("\uD83D\uDE48",W.type,W.key,`Removing subscription "${X}"`),Q();for(let O of J.values())O()}}var i7=(Y,Z,X,_)=>{let G=h0(Y,Z);Y.logger.info("\uD83D\uDC40","timeline",Z.key,`Adding subscription "${X}"`);let W=G.subject.subscribe(X,_);return()=>{Y.logger.info("\uD83D\uDE48","timeline",Z.key,`Removing subscription "${X}" from timeline`),W()}};var d5=class{initializeState(Y,Z){let X=`*${Y.key}`;Z.atoms.delete(X),Z.valueMap.delete(X);let _=Y.family?{key:`*${Y.family.key}`,subKey:Y.family.subKey}:void 0,G=k4(Z,{key:X,default:null},_);if(Z.parent?.valueMap.has(X)){let W=Z.parent.valueMap.get(X);Z.valueMap.set(X,W)}return G}unsubscribeFromInnerValue;unsubscribeFromState;observeCore(Y,Z,X){let _=`tracker:${X.config.name}:${o0(X)?X.transactionMeta.update.key:"main"}:${Y.key}`,G=k1(X,Y);this.unsubscribeFromInnerValue=G.subscribe(_,(W)=>{R1(X,Z,W)}),this.unsubscribeFromState=M8(X,Y,_,(W)=>{if(W.newValue!==W.oldValue)this.unsubscribeFromInnerValue(),this.unsubscribeFromInnerValue=W.newValue.subscribe(_,(H)=>{R1(X,Z,H)})})}updateCore(Y,Z,X){let _=`tracker:${X.config.name}:${o0(X)?X.transactionMeta.update.key:"main"}:${Y.key}`;M8(X,Z,_,({newValue:G,oldValue:W})=>{let H=X.timelineTopics.getRelatedKey(Z.key);if(H){if(X.timelines.get(H)?.timeTraveling){let Q=i7(X,{key:H,type:"timeline"},_,(z)=>{Q(),R1(X,Y,(O)=>{if(z==="redo"&&G)O.do(G);else if(z==="undo"&&W)O.undo(W);return O})});return}}let J=X.on.operationClose.subscribe(_,()=>{J();let $=k1(X,Y),Q=G===null?-1:$.getUpdateNumber(G),z=Q-$.cacheUpdateNumber;if(G&&z===1)R1(X,Y,(O)=>(O.do(G),O));else X.logger.info("\u274C","mutable_atom",Y.key,`could not be updated. Expected update number ${$.cacheUpdateNumber+1}, but got ${Q}`)})})}mutableState;latestUpdateState;[Symbol.dispose];constructor(Y,Z){this.mutableState=Y;let X=i(Z);this.latestUpdateState=this.initializeState(Y,X),this.observeCore(Y,this.latestUpdateState,X),this.updateCore(Y,this.latestUpdateState,X),X.trackers.set(Y.key,this),this[Symbol.dispose]=()=>{this.unsubscribeFromInnerValue(),this.unsubscribeFromState(),X.trackers.delete(Y.key)}}};function c5(Y,Z,X){Y.logger.info("\uD83D\uDD28","atom",Z.key,`creating in store "${Y.config.name}"`);let _=i(Y),{key:G}=Z,W=_.atoms.get(G),H="mutable_atom";if(W&&W.type===H)return Y.logger.error("\u274C",H,G,"Tried to create atom, but it already exists in the store."),G4(W);let J=new J0,$={...Z,type:H,install:(z)=>{return z.logger.info("\uD83D\uDEE0\uFE0F","atom",G,`installing in store "${z.config.name}"`),c5(z,Z,X)},subject:J};if(X)$.family=X;_.atoms.set($.key,$);let Q=G4($);if(Z.effects){let z=0,O=[];for(let D of Z.effects){let V=D({resetSelf:()=>{E8(Y,Q)},setSelf:(R)=>{R1(Y,Q,R)},onSet:(R)=>M8(Y,Q,`effect[${z}]`,R)});if(V)O.push(V);++z}$.cleanup=()=>{for(let D of O)D()}}if(new d5(Q,Y),!X)V7(Q,Z,Y);return Q}var _U=class{trackers=new Map;latestUpdateAtoms;mutableAtoms;constructor(Y,Z){let X=F6(Z,{key:`*${Y.key}`,default:null},["mutable","updates"]);this.latestUpdateAtoms=h0(Z,X),this.mutableAtoms=Y,this.mutableAtoms.subject.subscribe(`store=${Z.config.name}::tracker-atom-family`,(_)=>{let{type:G,token:W}=_;if(W.family){let H=G1(W.family.subKey);switch(G){case"state_creation":this.trackers.set(H,new d5(W,Z));break;case"state_disposal":{let J=this.trackers.get(H);if(J)J[Symbol.dispose](),this.trackers.delete(H)}break}}})}};function l5(Y,Z,X){let _={key:Z.key,type:"mutable_atom_family"},G=Y.families.get(Z.key);if(G)Y.logger.error("\u2757","mutable_atom_family",Z.key,`Overwriting an existing ${f4(G)} "${G.key}" in store "${Y.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);let W=new J0,J=Object.assign(($)=>{let Q=z0($),z={key:Z.key,subKey:Q},O=`${Z.key}(${Q})`,D=i(Y),V={key:O,default:()=>Z.default($),toJson:Z.toJson,fromJson:Z.fromJson,mutable:!0};if(Z.effects)V.effects=Z.effects($);let R=c5(D,V,z);return W.next({type:"state_creation",token:R}),R},_,{subject:W,install:($)=>l5($,Z),toJson:Z.toJson,fromJson:Z.fromJson,internalRoles:X});return Y.families.set(Z.key,J),M7(Y,J,Z),new _U(J,Y),_}var h7=(Y,Z)=>{let X=i(Z),_=`${Y.key}:JSON`;return X.families.get(_)},b4=(Y,Z)=>{if(Z.family){let _=i(Y),W={key:`${Z.family.key}:JSON`,type:"writable_pure_selector_family"},H=h0(_,W),J=JSON.parse(Z.family.subKey);return H0(Y,H,J)}return{type:"writable_pure_selector",key:`${Z.key}:JSON`}};var i5=(Y)=>{let X={type:"atom",key:`*${Y.key}`};if(Y.family)X.family={key:`*${Y.family.key}`,subKey:Y.family.subKey};return X};function GU(Y){return typeof Y==="object"&&Y!==null&&"do"in Y&&"undo"in Y&&"subscribe"in Y}var C7=class{parent=null;child=null;valueMap=new Map;defaults=new Map;atoms=new Map;writableSelectors=new Map;readonlySelectors=new Map;atomsThatAreDefault=new Set;selectorAtoms=new W1({between:["selectorKey","atomKey"],cardinality:"n:n"});selectorGraph=new W1({between:["upstreamSelectorKey","downstreamSelectorKey"],cardinality:"n:n"},{makeContentKey:(...Y)=>Y.sort().join(":")});trackers=new Map;families=new Map;joins=new Map;transactions=new Map;transactionMeta={epoch:new Map,actionContinuities:new W1({between:["continuity","action"],cardinality:"1:n"})};timelines=new Map;timelineTopics=new W1({between:["timelineKey","topicKey"],cardinality:"1:n"});disposalTraces=new TF(100);molecules=new Map;moleculeJoins=new W1({between:["moleculeKey","joinKey"],cardinality:"n:n"},{makeContentKey:(...Y)=>Y.sort().join(":")});moleculeGraph=new W1({between:["upstreamMoleculeKey","downstreamMoleculeKey"],cardinality:"n:n"},{makeContentKey:(...Y)=>Y.sort().join(":")});moleculeData=new W1({between:["moleculeKey","stateFamilyKey"],cardinality:"n:n"},{makeContentKey:(...Y)=>Y.sort().join(":")});miscResources=new Map;on={atomCreation:new J0,atomDisposal:new J0,selectorCreation:new J0,selectorDisposal:new J0,timelineCreation:new J0,transactionCreation:new J0,transactionApplying:new jF(null),operationClose:new J0,moleculeCreation:new J0,moleculeDisposal:new J0};operation={open:!1};config={name:"IMPLICIT_STORE",lifespan:"ephemeral"};loggers=[new w7("warn",(Y,Z,X)=>!A8(X))];logger={error:(...Y)=>{for(let Z of this.loggers)Z.error(...Y)},info:(...Y)=>{for(let Z of this.loggers)Z.info(...Y)},warn:(...Y)=>{for(let Z of this.loggers)Z.warn(...Y)}};constructor(Y,Z=null){if(this.config={...Z?.config,...Y},Z!==null){if(this.operation={...Z?.operation},R4(Z))this.transactionMeta={epoch:new Map(Z?.transactionMeta.epoch),actionContinuities:new W1(Z?.transactionMeta.actionContinuities.toJSON())};for(let[,_]of Z.families){if(_.internalRoles?.includes("mutable")||_.internalRoles?.includes("join"))continue;_.install(this)}let X=new Set;for(let[,_]of Z.atoms){if(X.has(_.key))continue;if(_.install(this),_.type==="mutable_atom"){let G=b4(Z,_),W=i5(_);X.add(G.key),X.add(W.key)}}for(let[,_]of Z.readonlySelectors)_.install(this);for(let[,_]of Z.writableSelectors){if(X.has(_.key))continue;_.install(this)}for(let[,_]of Z.transactions)_.install(this);for(let[,_]of Z.timelines)_.install(this)}}},x0={get STORE(){return globalThis.ATOM_IO_IMPLICIT_STORE??=new C7({name:"IMPLICIT_STORE",lifespan:"ephemeral"}),globalThis.ATOM_IO_IMPLICIT_STORE}};function h0(Y,Z){let X,_=Y;while(_!==null){switch(Z.type){case"atom":case"mutable_atom":X=_.atoms.get(Z.key);break;case"writable_pure_selector":case"writable_held_selector":X=_.writableSelectors.get(Z.key);break;case"readonly_pure_selector":case"readonly_held_selector":X=_.readonlySelectors.get(Z.key);break;case"atom_family":case"mutable_atom_family":case"writable_pure_selector_family":case"readonly_pure_selector_family":case"writable_held_selector_family":case"readonly_held_selector_family":X=_.families.get(Z.key);break;case"timeline":X=_.timelines.get(Z.key);break;case"transaction":X=_.transactions.get(Z.key);break}if(X)return X;_=_.child}throw new p5(Z,Y)}function k4(Y,Z,X){let{key:G}=Z;Y.logger.info("\uD83D\uDD28","atom",G,`creating in store "${Y.config.name}"`);let W=i(Y),H=W.atoms.get(G);if(H&&H.type==="atom")return Y.logger.error("\u274C","atom",G,"Tried to create atom, but it already exists in the store."),G4(H);let J=new J0,$={...Z,type:"atom",install:(z)=>{return z.logger.info("\uD83D\uDEE0\uFE0F","atom",G,`installing in store "${z.config.name}"`),k4(z,Z,X)},subject:J};if(X)$.family=X;W.atoms.set(G,$);let Q=G4($);if(Z.effects){let z=0,O=[];for(let D of Z.effects){let V=D({resetSelf:()=>{E8(Y,Q)},setSelf:(R)=>{R1(Y,Q,R)},onSet:(R)=>M8(Y,Q,`effect[${z}]`,R)});if(V)O.push(V);++z}$.cleanup=()=>{for(let D of O)D()}}return Q}function T7(Y,Z){if("mutable"in Z){let G=c5(Y,Z,void 0);return Y.on.atomCreation.next(G),G}let _=k4(Y,Z,void 0);return Y.on.atomCreation.next(_),_}function o7(Y,Z){let X=i(Y),{key:_,family:G}=Z,W=h0(X,Z);if(!G)Y.logger.error("\u274C","atom",_,"Standalone atoms cannot be disposed.");else{W.cleanup?.();let H=Y.valueMap.get(W.key),J=h0(Y,{key:G.key,type:"atom_family"}),$={type:"state_disposal",subType:"atom",token:Z,value:H};J.subject.next($);let Q=o0(X);if(X.atoms.delete(_),X.valueMap.delete(_),X.selectorAtoms.delete(_),X.atomsThatAreDefault.delete(_),Y.timelineTopics.delete(_),Z.type==="mutable_atom"){let z=i5(Z);o7(Y,z),Y.trackers.delete(_)}if(Y.logger.info("\uD83D\uDD25","atom",_,"deleted"),Q&&X.transactionMeta.phase==="building"){let z=X.transactionMeta.update.updates.at(-1);if(!(z?.type==="molecule_disposal"&&z.values.some(([V])=>V===W.family?.key)))X.transactionMeta.update.updates.push($)}else Y.on.atomDisposal.next(Z)}}function K7(Y,Z,X){return Y.joins.set(Z.key,new o5(Z,X,Y)),{key:Z.key,type:"join",a:Z.between[0],b:Z.between[1],cardinality:Z.cardinality}}var o5=class{toolkit;options;defaultContent;molecules=new Map;relations;states;core;transact(Y,Z){let X=this.toolkit;this.toolkit=Y,Z(this),this.toolkit=X}store;realm;[Symbol.dispose](){}constructor(Y,Z,X=x0.STORE){this.store=X,this.realm=new R7(X),this.options=Y,this.defaultContent=Z,this.store.miscResources.set(`join:${Y.key}`,this),this.realm.allocate("root",Y.key),this.toolkit={get:(...I)=>k1(X,...I),set:(...I)=>{R1(X,...I)},find:(...I)=>H0(X,...I),json:(I)=>b4(X,I)};let _=Y.between[0],G=Y.between[1],W=l5(X,{key:`${Y.key}/relatedKeys`,default:()=>new D1,mutable:!0,fromJson:(I)=>D1.fromJSON(I),toJson:(I)=>I.toJSON()},["join","relations"]);this.core={relatedKeysAtoms:W};let H=({get:I},N)=>I(W,N),J=({set:I},N,q)=>{if(!this.store.molecules.has(z0(N)))this.realm.allocate(Y.key,N);I(W,N,(K)=>K.add(q)),I(W,q,(K)=>K.add(N))},$=({set:I},N,q)=>{I(W,N,(K)=>{return K.delete(q),K}),I(W,q,(K)=>{return K.delete(N),K})},Q=(I,N,q)=>{let{find:K,get:p,set:s}=I,C=K(W,N),t=p(C);for(let m of t){if(q.includes(m))continue;s(W,m,(U0)=>{return U0.delete(N),U0})}s(C,(m)=>{return m.transaction((e)=>{e.clear();for(let U0 of q){let b0=H(I,U0),Q1=b0.has(N);if(this.relations.cardinality==="1:n"){let r1=[];for(let T of b0){if(T===N)continue;let u=H(I,T);if(u.delete(U0),u.size===0)r1.push(T)}if(!Q1&&b0.size>0)b0.clear();for(let T of r1){let u=[U0,T].sort(),G0=`"${u[0]}:${u[1]}"`;this.molecules.delete(G0)}}if(!Q1)b0.add(N);e.add(U0)}return!0}),m})},z=(I,N,q)=>{let{set:K}=I;K(W,N,(p)=>{return p.transaction((s)=>{for(let C of q)s.add(C);return!0}),p});for(let p of q)K(W,p,(s)=>{return s.add(N),s});return!0},O=(I,N,q)=>{let K=H(I,N);return q?K.has(q):K.size>0},D={getRelatedKeys:(I)=>H(this.toolkit,I),addRelation:(I,N)=>{this.store.moleculeJoins.set(I,Y.key),this.store.moleculeJoins.set(N,Y.key),J(this.toolkit,I,N)},deleteRelation:(I,N)=>{$(this.toolkit,I,N)},replaceRelationsSafely:(I,N)=>{Q(this.toolkit,I,N)},replaceRelationsUnsafely:(I,N)=>{z(this.toolkit,I,N)},has:(I,N)=>O(this.toolkit,I,N)},V,R;if(Z){R=F6(X,{key:`${Y.key}/content`,default:Z},["join","content"]);let I=({get:K},p)=>K(R,p),N=({set:K},p,s)=>{K(R,p,s)};V=Object.assign(D,{getContent:(K)=>{return I(this.toolkit,K)},setContent:(K,p)=>{N(this.toolkit,K,p)},deleteContent:(K)=>{this.realm.deallocate(K)}})}else V=D;let A=new W1(Y,{externalStore:V,isAType:Y.isAType,isBType:Y.isBType,makeContentKey:(...I)=>{let[N,q]=I,K=I.sort(),p=`${K[0]}:${K[1]}`,s=X.molecules.get(z0(N)),C=X.molecules.get(z0(q));if(!s)this.realm.allocate(Y.key,N);if(!C)this.realm.allocate(Y.key,q);return this.realm.allocate(N,p,"all"),this.realm.claim(q,p),this.store.moleculeJoins.set(p,Y.key),p}}),g=()=>h4(X,{key:`${Y.key}/singleRelatedKey`,get:(I)=>({get:N})=>{let q=N(W,I);for(let K of q)return K;return null}},["join","keys"]),b=()=>{return h4(X,{key:`${Y.key}/multipleRelatedKeys`,get:(I)=>({get:N})=>{let q=h7(W,X);return N(q,I).members}},["join","keys"])},f=()=>h4(X,{key:`${Y.key}/singleRelatedEntry`,get:(I)=>({get:N})=>{let q=N(W,I);for(let K of q){let p=A.isAType?.(I)?I:void 0,s=p===void 0?I:void 0;p??=K,s??=K;let C=A.makeContentKey(p,s),t=N(R,C);return[K,t]}return null}},["join","entries"]),h=()=>h4(X,{key:`${Y.key}/multipleRelatedEntries`,get:(I)=>({get:N})=>{let q=h7(W,X);return N(q,I).members.map((p)=>{let s=A.isAType?.(I)?I:void 0,C=s===void 0?I:void 0;s??=p,C??=p;let t=A.makeContentKey(s,C),m=N(R,t);return[p,m]})}},["join","entries"]);switch(Y.cardinality){case"1:1":{let I=g(),N=`${_}KeyOf${B0(G)}`,q=`${G}KeyOf${B0(_)}`,K={[N]:I,[q]:I},p;if(Z){let s=f(),C=`${_}EntryOf${B0(G)}`,t=`${G}EntryOf${B0(_)}`,m={[C]:s,[t]:s};p=Object.assign(K,m)}else p=K;this.relations=A,this.states=p;break}case"1:n":{let I=g(),N=b(),q=`${_}KeyOf${B0(G)}`,K=`${G}KeysOf${B0(_)}`,p={[q]:I,[K]:N},s;if(Z){let C=f(),t=h(),m=`${_}EntryOf${B0(G)}`,e=`${G}EntriesOf${B0(_)}`,U0={[m]:C,[e]:t};s=Object.assign(p,U0)}else s=p;this.relations=A,this.states=s;break}case"n:n":{let I=b(),N=`${_}KeysOf${B0(G)}`,q=`${G}KeysOf${B0(_)}`,K={[N]:I,[q]:I},p;if(Z){let s=h(),C=`${_}EntriesOf${B0(G)}`,t=`${G}EntriesOf${B0(_)}`,m={[C]:s,[t]:s};p=Object.assign(K,m)}else p=K;this.relations=A,this.states=p}}}};function n5(Y,Z){let X=Z.joins.get(Y.key);if(X===void 0){let G=x0.STORE.joins.get(Y.key);if(G===void 0)throw new Error(`Join "${Y.key}" not found in store "${Z.config.name}"`);X=new o5(G.options,G.defaultContent,Z),Z.joins.set(Y.key,X)}return X}function Q6(Y,Z,X){let _=n5(Y,X),G=i(X);if(o0(G)){let{toolkit:W}=G.transactionMeta;_.transact(W,({relations:H})=>{Z(H)})}else Z(_.relations)}function q7(Y,Z,X){let _=n5(Y,X),G;switch(Y.cardinality){case"1:1":{let W=`${Y.a}KeyOf${B0(Y.b)}`,H=`${Y.b}KeyOf${B0(Y.a)}`;G={get[W](){let $=_.states[W];return H0(X,$,Z)},get[H](){let $=_.states[H];return H0(X,$,Z)}};let J=`${Y.a}EntryOf${B0(Y.b)}`;if(J in _.states){let $=`${Y.b}EntryOf${B0(Y.a)}`;Object.assign(G,{get[J](){let Q=_.states[J];return H0(X,Q,Z)},get[$](){let Q=_.states[$];return H0(X,Q,Z)}})}break}case"1:n":{let W=`${Y.a}KeyOf${B0(Y.b)}`,H=`${Y.b}KeysOf${B0(Y.a)}`;G={get[W](){let $=_.states[W];return H0(X,$,Z)},get[H](){let $=_.states[H];return H0(X,$,Z)}};let J=`${Y.a}EntryOf${B0(Y.b)}`;if(J in _.states){let $=`${Y.b}EntriesOf${B0(Y.a)}`;Object.assign(G,{get[J](){let Q=_.states[J];return H0(X,Q,Z)},get[$](){let Q=_.states[$];return H0(X,Q,Z)}})}break}case"n:n":{let W=`${Y.a}KeysOf${B0(Y.b)}`,H=`${Y.b}KeysOf${B0(Y.a)}`;G={get[W](){let $=_.states[W];return H0(X,$,Z)},get[H](){let $=_.states[H];return H0(X,$,Z)}};let J=`${Y.a}EntriesOf${B0(Y.b)}`;if(J in _.states){let $=`${Y.b}EntriesOf${B0(Y.a)}`;Object.assign(G,{get[J](){let Q=_.states[J];return H0(X,Q,Z)},get[$](){let Q=_.states[$];return H0(X,Q,Z)}})}}}return G}function j7(Y,Z){return n5(Y,Z).core.relatedKeysAtoms}function A8(Y){return Y.startsWith("\uD83D\uDD0D ")}var WU=(Y)=>{return k4(Y,{key:"\uD83D\uDD0D Atom Token Index",default:()=>{let Z=new Map;for(let[X,_]of Y.atoms){if(A8(X))continue;let G=G4(_);if(_.family){let W=Z.get(_.family.key);if(!W||!("familyMembers"in W))W={key:_.family.key,familyMembers:new Map},Z.set(_.family.key,W);W.familyMembers.set(_.family.subKey,G)}else Z.set(X,G)}return Z},effects:[({setSelf:Z})=>{Y.on.atomCreation.subscribe("introspection",(X)=>{if(A8(X.key))return;Z((_)=>{if(X.family){let{key:G,subKey:W}=X.family,H=_.get(G);if(H===void 0||!("familyMembers"in H))H={key:G,familyMembers:new Map},_.set(G,H);H.familyMembers.set(W,X)}else _.set(X.key,X);return new Map(_)})}),Y.on.atomDisposal.subscribe("introspection",(X)=>{Z((_)=>{if(X.family){let{key:G,subKey:W}=X.family,H=_.get(G);if(H&&"familyMembers"in H){if(H.familyMembers.delete(W),H.familyMembers.size===0)_.delete(G)}}return new Map(_)})})}]},void 0)},HU=(Y)=>{return k4(Y,{key:"\uD83D\uDD0D Selector Token Index",default:()=>{let Z=new Map;for(let X of[Y.readonlySelectors,Y.writableSelectors])for(let[_,G]of X){if(A8(_))continue;let W=G4(G);if(G.family){let H=Z.get(G.family.key);if(!H||!("familyMembers"in H))H={key:G.family.key,familyMembers:new Map},Z.set(G.family.key,H);H.familyMembers.set(G.family.subKey,W)}else Z.set(_,W)}return Z},effects:[({setSelf:Z})=>{Y.on.selectorCreation.subscribe("introspection",(X)=>{if(A8(X.key))return;Z((_)=>{if(X.family){let{key:G,subKey:W}=X.family,H=_.get(G);if(H===void 0||!("familyMembers"in H))H={key:G,familyMembers:new Map},_.set(G,H);H.familyMembers.set(W,X)}else _.set(X.key,X);return new Map(_)})}),Y.on.selectorDisposal.subscribe("introspection",(X)=>{Z((_)=>{if(X.family){let{key:G,subKey:W}=X.family,H=_.get(G);if(H&&"familyMembers"in H){if(H.familyMembers.delete(W),H.familyMembers.size===0)_.delete(G)}}else _.delete(X.key);return new Map(_)})})}]},void 0)};var r5=class{supported;constructor(Y){this.supported=Y}refine(Y){for(let[Z,X]of Object.entries(this.supported))try{if(X(Y)===!0&&X!==Boolean)return{type:Z,data:Y}}catch(_){try{if(Y instanceof X)return{type:Z,data:Y}}catch(G){}}return null}},r7=new r5({number:(Y)=>typeof Y==="number",string:(Y)=>typeof Y==="string",boolean:(Y)=>typeof Y==="boolean",null:(Y)=>Y===null});function s7(Y){if(!Y)return!1;return Object.getPrototypeOf(Y)===Object.prototype}var a7=new r5({object:s7,array:(Y)=>Array.isArray(Y)}),JU=new r5({...r7.supported,...a7.supported}),wY=(Y)=>{if(Y===void 0)return"undefined";let Z=JU.refine(Y);if(Z)return Z.type;return Object.getPrototypeOf(Y).constructor.name};var oB=class Y{store;auditorCreatedAt=performance.now();statesCreatedAt=new Map;atomIndex;selectorIndex;disposed=!1;unsubscribeFromAtomCreation;unsubscribeFromAtomDisposal;unsubscribeFromSelectorCreation;unsubscribeFromSelectorDisposal;constructor(Z=x0.STORE){this.store=Z,this.atomIndex=WU(this.store),this.selectorIndex=HU(this.store),this.unsubscribeFromAtomCreation=this.store.on.atomCreation.subscribe(`auditor-${this.auditorCreatedAt}`,({key:X})=>{this.statesCreatedAt.set(X,performance.now()-this.auditorCreatedAt)}),this.unsubscribeFromAtomDisposal=this.store.on.atomDisposal.subscribe(`auditor-${this.auditorCreatedAt}`,({key:X})=>{this.statesCreatedAt.delete(X)}),this.unsubscribeFromSelectorCreation=this.store.on.selectorCreation.subscribe(`auditor-${this.auditorCreatedAt}`,({key:X})=>{this.statesCreatedAt.set(X,performance.now()-this.auditorCreatedAt)}),this.unsubscribeFromSelectorDisposal=this.store.on.selectorDisposal.subscribe(`auditor-${this.auditorCreatedAt}`,({key:X})=>{this.statesCreatedAt.delete(X)})}static DEFAULT_LIST_RESOURCES_PARAM={atomFamilies:!0,selectorFamilies:!0};listResources(Z=Y.DEFAULT_LIST_RESOURCES_PARAM){if(this.disposed)throw new Error("This Auditor has been disposed");let X=j5(this.atomIndex),_=j5(this.selectorIndex),G=[...X.values()].filter(($)=>("familyMembers"in $)),W=[..._.values()].filter(($)=>("familyMembers"in $)),H=performance.now(),J=[];if(Z.atomFamilies)for(let $ of G){let Q=$.familyMembers.values();for(let z of Q){let D=this.statesCreatedAt.get(z.key)??this.auditorCreatedAt,V=H-D;J.push([z,V])}}if(Z.selectorFamilies)for(let $ of W){let Q=$.familyMembers.values();for(let z of Q){let D=this.statesCreatedAt.get(z.key)??this.auditorCreatedAt,V=H-D;J.push([z,V])}}return J}[Symbol.dispose](){this.unsubscribeFromAtomCreation(),this.unsubscribeFromAtomDisposal(),this.unsubscribeFromSelectorCreation(),this.unsubscribeFromSelectorDisposal(),this.disposed=!0}},n7=(Y,Z)=>{let X=(_,G)=>{let H=(($,Q)=>{let z=Z($,Q);if(z)return z;return null})(_,G);if(H?.jobComplete??H?.pathComplete)return H;let J=Array.isArray(G)?G.map(($,Q)=>[Q,$]):s7(G)?Object.entries(G):[];for(let[$,Q]of J){let z=X([..._,$],Q);if(z?.jobComplete)return z}return{}};X([],Y)};function QU(Y,Z){return{summary:`${Y<Z?"+":"-"}${Math.abs(Y-Z)} (${Y} \u2192 ${Z})`}}function $U(Y,Z){return{summary:`${Y.length<Z.length?"+":"-"}${Math.abs(Y.length-Z.length)} ("${Y}" \u2192 "${Z}")`}}function zU(Y,Z){return{summary:`${Y} \u2192 ${Z}`}}function t7(Y,Z,X){let _="",G=[],W=[],H=[];return n7(Y,(J,$)=>{let Q;for(Q of J){let z=Z[Q];if(z===void 0)W.push([Q,JSON.stringify($)]);else{let O=X($,z);if(O.summary!=="No Change")H.push([Q,O])}}}),n7(Z,(J,$)=>{let Q;for(Q of J)if(Y[Q]===void 0)G.push([Q,JSON.stringify($)])}),_=`\uFF5E${H.length} \uFF0B${G.length} \uFF0D${W.length}`,{summary:_,added:G,removed:W,changed:H}}function FU(Y,Z,X){return t7(Y,Z,X)}var UU=class{leafRefinery;treeRefinery;leafDiffers;treeDiffers;constructor(Y,Z,X){this.leafRefinery=Y,this.treeRefinery=Z,this.leafDiffers={},this.treeDiffers={};for(let _ of Object.keys(Y.supported)){let G=X[_];this.leafDiffers[_]=G}for(let _ of Object.keys(Z.supported)){let G=X[_];this.treeDiffers[_]=G}}diff(Y,Z){if(Y===Z)return{summary:"No Change"};let X=this.leafRefinery.refine(Y)??this.treeRefinery.refine(Y),_=this.leafRefinery.refine(Z)??this.treeRefinery.refine(Z);if(X!==null&&_!==null){if(X.type===_.type){if(X.type in this.leafDiffers)return this.leafDiffers[X.type](X.data,_.data);if(X.type in this.treeDiffers)return this.treeDiffers[X.type](X.data,_.data,(J,$)=>this.diff(J,$))}}let G=wY(Y),W=wY(Z);if(G===W)return{summary:`${G} \u2192 ${W}`};return{summary:`Type change: ${G} \u2192 ${W}`}}},nB=new UU(r7,a7,{number:QU,string:$U,boolean:zU,null:()=>({summary:"No Change"}),object:t7,array:FU});var OU=class extends Map{set(Y,Z){if(this.has(Y))return console.warn("Tried to set a key that already exists in an InvariantMap",{key:Y,value:Z}),this;return super.set(Y,Z)}clear(){throw new Error("Cannot clear an InvariantMap")}},YC=class Y{type="continuity";globals=[];actions=[];perspectives=[];key;constructor(Z){this.key=Z}static existing=new OU;static create(Z,X){let _=new Y(Z),{type:G,globals:W,actions:H,perspectives:J}=X(_),$={type:G,key:Z,globals:W,actions:H,perspectives:J};return Y.existing.set(Z,$),$}add(...Z){switch(Z[0].type){case"atom":case"mutable_atom":this.globals.push(...Z);break;case"transaction":this.actions.push(...Z);break;case"atom_family":case"mutable_atom_family":{let[_,G]=Z;this.perspectives.push({type:"realtime_perspective",resourceAtoms:_,viewAtoms:G})}break}return this}};var ZC=O8({key:"usersInRoomIndex",mutable:!0,default:()=>new D1,toJson:(Y)=>Y.toJSON(),fromJson:(Y)=>D1.fromJSON(Y)}),s5=O8({key:"roomIndex",default:()=>new D1,mutable:!0,toJson:(Y)=>Y.toJSON(),fromJson:(Y)=>D1.fromJSON(Y)}),EU={enteredAtEpoch:0},U6=EY({key:"usersInRooms",between:["room","user"],cardinality:"1:n",isAType:(Y)=>typeof Y==="string",isBType:(Y)=>typeof Y==="string"},EU),XC=DY({key:"usersInMyRoomView",get:(Y)=>({find:Z})=>{let X=A7(U6);return[Z(X,Y)]}});import{spawn as DU}from"child_process";var a5=class{listeners;globalListeners;handleEvent(Y,...Z){for(let _ of this.globalListeners)_(Y,...Z);let X=this.listeners.get(Y);if(X)for(let _ of X)_(...Z)}id="no_id_retrieved";emit;constructor(Y){this.emit=Y,this.listeners=new Map,this.globalListeners=new Set}on(Y,Z){let X=this.listeners.get(Y);if(X)X.add(Z);else this.listeners.set(Y,new Set([Z]));return this}onAny(Y){return this.globalListeners.add(Y),this}off(Y,Z){let X=this.listeners.get(Y);if(X)if(Z)X.delete(Z);else this.listeners.delete(Y);return this}offAny(Y){return this.globalListeners.delete(Y),this}},LU=class extends a5{incompleteData="";unprocessedEvents=[];incompleteLog="";unprocessedLogs=[];id="#####";process;key;logger;handleLog(Y){if(Array.isArray(Y)){let[Z,...X]=Y;switch(Z){case"i":this.logger.info(...X);break;case"w":this.logger.warn(...X);break;case"e":this.logger.error(...X);break;default:return}}}constructor(Y,Z,X){super((_,...G)=>{let W=JSON.stringify([_,...G])+"\x03",H=(J)=>{if(J.code==="EPIPE")console.error("EPIPE error during write",this.process.stdin);this.process.stdin.removeListener("error",H)};return this.process.stdin.once("error",H),this.process.stdin.write(W),this});if(this.process=Y,this.key=Z,this.logger=X??{info:(..._)=>{console.info(this.id,this.key,..._)},warn:(..._)=>{console.warn(this.id,this.key,..._)},error:(..._)=>{console.error(this.id,this.key,..._)}},this.process.stdout.on("data",(_)=>{let G=_.toString();if(G==="ALIVE")return;this.unprocessedEvents.push(...G.split("\x03"));let W=this.unprocessedEvents.shift();this.incompleteData+=W??"";try{if(this.incompleteData.startsWith("error"))console.log("\u2757",this.incompleteData);let H=G1(this.incompleteData);this.handleEvent(...H);while(this.unprocessedEvents.length>0){let J=this.unprocessedEvents.shift();if(J){if(this.unprocessedEvents.length===0)this.incompleteData=J;H=G1(J),this.handleEvent(...H)}}this.incompleteData=""}catch(H){console.warn("\u26A0\uFE0F----------------\u26A0\uFE0F"),console.warn(this.incompleteData),console.warn("\u26A0\uFE0F----------------\u26A0\uFE0F"),console.error(H)}}),this.process.stderr.on("data",(_)=>{let G=_.toString();this.unprocessedLogs.push(...G.split("\x03"));let W=this.unprocessedLogs.shift();this.incompleteLog+=W??"";try{let H=G1(this.incompleteLog);this.handleLog(H);while(this.unprocessedLogs.length>0)if(this.incompleteLog=this.unprocessedLogs.shift()??"",this.incompleteLog)H=G1(this.incompleteLog),this.handleLog(H)}catch(H){console.error("\u274C\u274C\u274C"),console.error(this.incompleteLog),console.error(H),console.error("\u274C\u274C\u274C\uFE0F")}}),Y.pid)this.id=Y.pid.toString()}},VU=class extends a5{in;out;id="no_id_retrieved";disposalFunctions=[];constructor(Y){super((...Z)=>{return this.out.next(Z),this});this.id=Y,this.in=new J0,this.out=new J0,this.in.subscribe("socket",(Z)=>{this.handleEvent(...Z)})}dispose(){for(let Y of this.disposalFunctions)Y()}},e7=class extends a5{incompleteData="";unprocessedEvents=[];relays;relayServices;process;id="#####";log(...Y){this.process.stderr.write(z0(Y.map((Z)=>Z instanceof D1?`{ ${Z.toJSON().members.join(" | ")} }`:Z))+"\x03")}logger={info:(...Y)=>{this.log("i",...Y)},warn:(...Y)=>{this.log("w",...Y)},error:(...Y)=>{this.log("e",...Y)}};constructor(){super((Y,...Z)=>{let X=JSON.stringify([Y,...Z]);return this.process.stdout.write(X+"\x03"),this});if(this.process=process,this.process.stdin.resume(),this.relays=new Map,this.relayServices=[],this.process.stdin.on("data",(Y)=>{let Z=Y.toString();this.unprocessedEvents.push(...Z.split("\x03"));let X=this.unprocessedEvents.shift();this.incompleteData+=X??"";try{let _=G1(this.incompleteData);this.logger.info("\uD83C\uDFB0","received",_),this.handleEvent(..._);while(this.unprocessedEvents.length>0){let G=this.unprocessedEvents.shift();if(G){if(this.unprocessedEvents.length===0)this.incompleteData=G;let W=G1(G);this.handleEvent(...W)}}this.incompleteData=""}catch(_){if(_ instanceof Error)this.logger.error("\u2757",_.message,_.cause,_.stack)}}),this.on("exit",()=>{this.logger.info("\uD83D\uDD25",this.id,'received "exit"'),process.exit(0)}),process.on("exit",(Y)=>{this.logger.info("\uD83D\uDD25",this.id,`exited with code ${Y}`)}),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",(Y)=>{this.logger.info("\uD83D\uDC64","user",Y,"joined");let Z=new VU(`user:${Y}`);this.relays.set(Y,Z),this.logger.info("\uD83D\uDD17","attaching services:",`[${[...this.relayServices.keys()].join(", ")}]`);for(let X of this.relayServices){let _=X(Z);if(_)Z.disposalFunctions.push(_)}this.on(`user:${Y}`,(...X)=>{Z.in.next(X)}),Z.out.subscribe("socket",(X)=>{this.emit(...X)})}),this.on("user-leaves",(Y)=>{let Z=this.relays.get(Y);if(this.off(`relay:${Y}`),Z)Z.dispose(),this.relays.delete(Y)}),process.stdout.write("ALIVE")}relay(Y){this.logger.info("\uD83D\uDD17","running relay method"),this.relayServices.push(Y)}},Y3=W6({key:"roomArguments",default:["echo",["Hello World!"]]}),MU=DY({key:"room",get:(Y)=>async({get:Z,find:X})=>{let _=X(Y3,Y),G=Z(_),[W,H]=G,J=await new Promise(($)=>{let Q=DU(W,H,{env:process.env}),z=(O)=>{if(O.toString()==="ALIVE")Q.stdout.off("data",z),$(Q)};Q.stdout.on("data",z)});return new LU(J,Y)}}),FC=H6({key:"createRoom",do:({get:Y,set:Z,find:X},_,G,W)=>{let H=W?[G,W]:[G],J=X(Y3,_);Z(J,H),Z(s5,(z)=>z.add(_));let $=X(MU,_);return Y($)}}),UC=H6({key:"joinRoom",do:(Y,Z,X,_)=>{let G={enteredAtEpoch:_};return Q6(U6,(W)=>{W.set({room:Z,user:X},G)},Y.env().store),G}}),OC=H6({key:"leaveRoom",do:(Y,Z,X)=>{Q6(U6,(_)=>{_.delete({room:Z,user:X})},Y.env().store)}}),EC=H6({key:"destroyRoom",do:(Y,Z)=>{Q6(U6,(X)=>{X.delete({room:Z})},Y.env().store),Y.set(s5,(X)=>(X.delete(Z),X))}});var DC=W6({key:"redactor",default:{occlude:(Y)=>Y}}),LC=W6({key:"unacknowledgedUpdates",default:()=>[]}),VC=W6({key:"sockets",default:null}),MC=O8({key:"socketsIndex",mutable:!0,default:()=>new D1,toJson:(Y)=>Y.toJSON(),fromJson:(Y)=>D1.fromJSON(Y)}),AC=O8({key:"usersIndex",mutable:!0,default:()=>new D1,toJson:(Y)=>Y.toJSON(),fromJson:(Y)=>D1.fromJSON(Y)}),wC=EY({key:"usersOfSockets",between:["user","socket"],cardinality:"1:1",isAType:(Y)=>Y.startsWith("user::"),isBType:(Y)=>Y.startsWith("socket::")});var{file:vH,serve:hO}=globalThis.Bun;import{readFileSync as _3}from"fs";import{createServer as NU}from"http";import{createServer as IU}from"https";import{resolve as e5}from"path";function Z3(Y,Z){if(Y instanceof Promise)throw new Error(Z)}function AU(Y,Z){let X={},_=[];for(let G in Y){let W=Y[G]["~standard"].validate(Z[G]);if(Z3(W,`Validation must be synchronous, but ${G} returned a Promise.`),W.issues){_.push(...W.issues.map((H)=>({...H,message:H.message,path:[G,...H.path??[]]})));continue}X[G]=W.value}if(_.length)return{issues:_};return{value:X}}function t5(Y){let Z=Y.runtimeEnvStrict??Y.runtimeEnv??process.env;if(Y.emptyStringAsUndefined??!1){for(let[f,h]of Object.entries(Z))if(h==="")delete Z[f]}if(!!Y.skipValidation)return Z;let G=typeof Y.client==="object"?Y.client:{},W=typeof Y.server==="object"?Y.server:{},H=typeof Y.shared==="object"?Y.shared:{},J=Y.isServer??(typeof window==="undefined"||("Deno"in window)),$=J?{...W,...H,...G}:{...G,...H},Q=Y.createFinalSchema?.($,J)["~standard"].validate(Z)??AU($,Z);Z3(Q,"Validation must be synchronous");let z=Y.onValidationError??((f)=>{throw console.error("\u274C Invalid environment variables:",f),new Error("Invalid environment variables")}),O=Y.onInvalidAccess??(()=>{throw new Error("\u274C Attempted to access a server-side environment variable on the client")});if(Q.issues)return z(Q.issues);let D=(f)=>{if(!Y.clientPrefix)return!0;return!f.startsWith(Y.clientPrefix)&&!(f in H)},V=(f)=>{return J||!D(f)},R=(f)=>{return f==="__esModule"||f==="$$typeof"},A=(Y.extends??[]).reduce((f,h)=>{return Object.assign(f,h)},{}),g=Object.assign(A,Q.value);return new Proxy(g,{get(f,h){if(typeof h!=="string")return;if(R(h))return;if(!V(h))return O(h);return Reflect.get(f,h)}})}var wU="__vite_start_time"in globalThis,RU=typeof window!=="undefined",SC="vitest"in globalThis,H4=E1("string"),X3=E1('"true" | "false" | undefined'),g1=t5({isServer:!wU&&!RU,server:{CI:E1("string | undefined").pipe(Boolean),POSTGRES_USER:H4,POSTGRES_PASSWORD:H4,POSTGRES_DATABASE:H4,POSTGRES_HOST:H4,POSTGRES_PORT:H4.pipe((Y)=>Number.parseInt(Y,10)),BACKEND_PORT:H4.pipe((Y)=>Number.parseInt(Y,10)),RUN_WORKERS_FROM_SOURCE:X3.pipe((Y)=>Y==="true"),FRONTEND_PORT:H4.pipe((Y)=>Number.parseInt(Y,10)),FRONTEND_ORIGINS:H4.pipe.try((Y)=>JSON.parse(Y),E1("string[]")),API_KEY_OPENAI:E1("string | undefined"),API_KEY_RESEND:E1("string | undefined")},clientPrefix:"VITE_",client:{VITE_BACKEND_ORIGIN:H4,VITE_DEV_FRONTEND_HOST:E1("string | undefined"),VITE_DEV_HTTPS:X3.pipe((Y)=>Y==="true")},runtimeEnv:import.meta.env,emptyStringAsUndefined:!0});var G3=e5(import.meta.dirname,"../dev"),RY=g1.VITE_DEV_HTTPS?{cert:_3(e5(G3,"./cert.pem"),"utf-8"),key:_3(e5(G3,"./key.pem"),"utf-8")}:void 0;function gC(Y){if(RY)return IU(RY,Y);return NU({},Y)}import KO from"path";var U=Symbol.for("drizzle:entityKind");function M(Y,Z){if(!Y||typeof Y!=="object")return!1;if(Y instanceof Z)return!0;if(!Object.prototype.hasOwnProperty.call(Z,U))throw new Error(`Class "${Z.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 X=Object.getPrototypeOf(Y).constructor;if(X)while(X){if(U in X&&X[U]===Z[U])return!0;X=Object.getPrototypeOf(X)}return!1}class E0{constructor(Y,Z){this.table=Y,this.config=Z,this.name=Z.name,this.keyAsName=Z.keyAsName,this.notNull=Z.notNull,this.default=Z.default,this.defaultFn=Z.defaultFn,this.onUpdateFn=Z.onUpdateFn,this.hasDefault=Z.hasDefault,this.primary=Z.primaryKey,this.isUnique=Z.isUnique,this.uniqueName=Z.uniqueName,this.uniqueType=Z.uniqueType,this.dataType=Z.dataType,this.columnType=Z.columnType,this.generated=Z.generated,this.generatedIdentity=Z.generatedIdentity}static[U]="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(Y){return Y}mapToDriverValue(Y){return Y}shouldDisableInsert(){return this.config.generated!==void 0&&this.config.generated.type!=="byDefault"}}class YX{static[U]="ColumnBuilder";config;constructor(Y,Z,X){this.config={name:Y,keyAsName:Y==="",notNull:!1,default:void 0,hasDefault:!1,primaryKey:!1,isUnique:!1,uniqueName:void 0,uniqueType:void 0,dataType:Z,columnType:X,generated:void 0}}$type(){return this}notNull(){return this.config.notNull=!0,this}default(Y){return this.config.default=Y,this.config.hasDefault=!0,this}$defaultFn(Y){return this.config.defaultFn=Y,this.config.hasDefault=!0,this}$default=this.$defaultFn;$onUpdateFn(Y){return this.config.onUpdateFn=Y,this.config.hasDefault=!0,this}$onUpdate=this.$onUpdateFn;primaryKey(){return this.config.primaryKey=!0,this.config.notNull=!0,this}setName(Y){if(this.config.name!=="")return;this.config.name=Y}}var y1=Symbol.for("drizzle:Name");class ZX{static[U]="PgForeignKeyBuilder";reference;_onUpdate="no action";_onDelete="no action";constructor(Y,Z){if(this.reference=()=>{let{name:X,columns:_,foreignColumns:G}=Y();return{name:X,columns:_,foreignTable:G[0].table,foreignColumns:G}},Z)this._onUpdate=Z.onUpdate,this._onDelete=Z.onDelete}onUpdate(Y){return this._onUpdate=Y===void 0?"no action":Y,this}onDelete(Y){return this._onDelete=Y===void 0?"no action":Y,this}build(Y){return new W3(Y,this)}}class W3{constructor(Y,Z){this.table=Y,this.reference=Z.reference,this.onUpdate=Z._onUpdate,this.onDelete=Z._onDelete}static[U]="PgForeignKey";reference;onUpdate;onDelete;getName(){let{name:Y,columns:Z,foreignColumns:X}=this.reference(),_=Z.map((H)=>H.name),G=X.map((H)=>H.name),W=[this.table[y1],..._,X[0].table[y1],...G];return Y??`${W.join("_")}_fk`}}function NY(Y,...Z){return Y(...Z)}function H3(Y,Z){return`${Y[y1]}_${Z.join("_")}_unique`}function J3(Y,Z,X){for(let _=Z;_<Y.length;_++){let G=Y[_];if(G==="\\"){_++;continue}if(G==='"')return[Y.slice(Z,_).replace(/\\/g,""),_+1];if(X)continue;if(G===","||G==="}")return[Y.slice(Z,_).replace(/\\/g,""),_]}return[Y.slice(Z).replace(/\\/g,""),Y.length]}function Q3(Y,Z=0){let X=[],_=Z,G=!1;while(_<Y.length){let W=Y[_];if(W===","){if(G||_===Z)X.push("");G=!0,_++;continue}if(G=!1,W==="\\"){_+=2;continue}if(W==='"'){let[$,Q]=J3(Y,_+1,!0);X.push($),_=Q;continue}if(W==="}")return[X,_+1];if(W==="{"){let[$,Q]=Q3(Y,_+1);X.push($),_=Q;continue}let[H,J]=J3(Y,_,!1);X.push(H),_=J}return[X,_]}function $3(Y){let[Z]=Q3(Y,1);return Z}function XX(Y){return`{${Y.map((Z)=>{if(Array.isArray(Z))return XX(Z);if(typeof Z==="string")return`"${Z.replace(/\\/g,"\\\\").replace(/"/g,"\\\"")}"`;return`${Z}`}).join(",")}}`}class k extends YX{foreignKeyConfigs=[];static[U]="PgColumnBuilder";array(Y){return new F3(this.config.name,this,Y)}references(Y,Z={}){return this.foreignKeyConfigs.push({ref:Y,actions:Z}),this}unique(Y,Z){return this.config.isUnique=!0,this.config.uniqueName=Y,this.config.uniqueType=Z?.nulls,this}generatedAlwaysAs(Y){return this.config.generated={as:Y,type:"always",mode:"stored"},this}buildForeignKeys(Y,Z){return this.foreignKeyConfigs.map(({ref:X,actions:_})=>{return NY((G,W)=>{let H=new ZX(()=>{let J=G();return{columns:[Y],foreignColumns:[J]}});if(W.onUpdate)H.onUpdate(W.onUpdate);if(W.onDelete)H.onDelete(W.onDelete);return H.build(Z)},X,_)})}buildExtraConfigColumn(Y){return new z3(Y,this.config)}}class j extends E0{constructor(Y,Z){if(!Z.uniqueName)Z.uniqueName=H3(Y,[Z.name]);super(Y,Z);this.table=Y}static[U]="PgColumn"}class z3 extends j{static[U]="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(Y){return this.indexConfig.opClass=Y,this}}class O6{static[U]="IndexedColumn";constructor(Y,Z,X,_){this.name=Y,this.keyAsName=Z,this.type=X,this.indexConfig=_}name;keyAsName;type;indexConfig}class F3 extends k{static[U]="PgArrayBuilder";constructor(Y,Z,X){super(Y,"array","PgArray");this.config.baseBuilder=Z,this.config.size=X}build(Y){let Z=this.config.baseBuilder.build(Y);return new _X(Y,this.config,Z)}}class _X extends j{constructor(Y,Z,X,_){super(Y,Z);this.baseColumn=X,this.range=_,this.size=Z.size}size;static[U]="PgArray";getSQLType(){return`${this.baseColumn.getSQLType()}[${typeof this.size==="number"?this.size:""}]`}mapFromDriverValue(Y){if(typeof Y==="string")Y=$3(Y);return Y.map((Z)=>this.baseColumn.mapFromDriverValue(Z))}mapToDriverValue(Y,Z=!1){let X=Y.map((_)=>_===null?null:M(this.baseColumn,_X)?this.baseColumn.mapToDriverValue(_,!0):this.baseColumn.mapToDriverValue(_));if(Z)return X;return XX(X)}}class U3 extends k{static[U]="PgEnumObjectColumnBuilder";constructor(Y,Z){super(Y,"string","PgEnumObjectColumn");this.config.enum=Z}build(Y){return new O3(Y,this.config)}}class O3 extends j{static[U]="PgEnumObjectColumn";enum;enumValues=this.config.enum.enumValues;constructor(Y,Z){super(Y,Z);this.enum=Z.enum}getSQLType(){return this.enum.enumName}}var IY=Symbol.for("drizzle:isPgEnum");function E3(Y){return!!Y&&typeof Y==="function"&&IY in Y&&Y[IY]===!0}class D3 extends k{static[U]="PgEnumColumnBuilder";constructor(Y,Z){super(Y,"string","PgEnumColumn");this.config.enum=Z}build(Y){return new L3(Y,this.config)}}class L3 extends j{static[U]="PgEnumColumn";enum=this.config.enum;enumValues=this.config.enum.enumValues;constructor(Y,Z){super(Y,Z);this.enum=Z.enum}getSQLType(){return this.enum.enumName}}function E6(Y,Z){return Array.isArray(Z)?BU(Y,[...Z],void 0):CU(Y,Z,void 0)}function BU(Y,Z,X){let _=Object.assign((G)=>new D3(G??"",_),{enumName:Y,enumValues:Z,schema:X,[IY]:!0});return _}function CU(Y,Z,X){let _=Object.assign((G)=>new U3(G??"",_),{enumName:Y,enumValues:Object.values(Z),schema:X,[IY]:!0});return _}class P0{static[U]="Subquery";constructor(Y,Z,X,_=!1,G=[]){this._={brand:"Subquery",sql:Y,selectedFields:Z,alias:X,isWith:_,usedTables:G}}}class D6 extends P0{static[U]="WithSubquery"}var V3="0.44.4";var GX,WX,D0={startActiveSpan(Y,Z){if(!GX)return Z();if(!WX)WX=GX.trace.getTracer("drizzle-orm",V3);return NY((X,_)=>_.startActiveSpan(Y,(G)=>{try{return Z(G)}catch(W){throw G.setStatus({code:X.SpanStatusCode.ERROR,message:W instanceof Error?W.message:"Unknown error"}),W}finally{G.end()}}),GX,WX)}};var A0=Symbol.for("drizzle:ViewBaseConfig");var g4=Symbol.for("drizzle:Schema"),BY=Symbol.for("drizzle:Columns"),M3=Symbol.for("drizzle:ExtraConfigColumns"),HX=Symbol.for("drizzle:OriginalName"),JX=Symbol.for("drizzle:BaseName"),L6=Symbol.for("drizzle:IsAlias"),A3=Symbol.for("drizzle:ExtraConfigBuilder"),TU=Symbol.for("drizzle:IsDrizzleTable");class P{static[U]="Table";static Symbol={Name:y1,Schema:g4,OriginalName:HX,Columns:BY,ExtraConfigColumns:M3,BaseName:JX,IsAlias:L6,ExtraConfigBuilder:A3};[y1];[HX];[g4];[BY];[M3];[JX];[L6]=!1;[TU]=!0;[A3]=void 0;constructor(Y,Z,X){this[y1]=this[HX]=Y,this[g4]=Z,this[JX]=X}}function c0(Y){return Y[y1]}function y4(Y){return`${Y[g4]??"public"}.${Y[y1]}`}function QX(Y){return Y!==null&&Y!==void 0&&typeof Y.getSQL==="function"}function KU(Y){let Z={sql:"",params:[]};for(let X of Y)if(Z.sql+=X.sql,Z.params.push(...X.params),X.typings?.length){if(!Z.typings)Z.typings=[];Z.typings.push(...X.typings)}return Z}class u0{static[U]="StringChunk";value;constructor(Y){this.value=Array.isArray(Y)?Y:[Y]}getSQL(){return new x([this])}}class x{constructor(Y){this.queryChunks=Y;for(let Z of Y)if(M(Z,P)){let X=Z[P.Symbol.Schema];this.usedTables.push(X===void 0?Z[P.Symbol.Name]:X+"."+Z[P.Symbol.Name])}}static[U]="SQL";decoder=R3;shouldInlineParams=!1;usedTables=[];append(Y){return this.queryChunks.push(...Y.queryChunks),this}toQuery(Y){return D0.startActiveSpan("drizzle.buildSQL",(Z)=>{let X=this.buildQueryFromSourceParams(this.queryChunks,Y);return Z?.setAttributes({"drizzle.query.text":X.sql,"drizzle.query.params":JSON.stringify(X.params)}),X})}buildQueryFromSourceParams(Y,Z){let X=Object.assign({},Z,{inlineParams:Z.inlineParams||this.shouldInlineParams,paramStartIndex:Z.paramStartIndex||{value:0}}),{casing:_,escapeName:G,escapeParam:W,prepareTyping:H,inlineParams:J,paramStartIndex:$}=X;return KU(Y.map((Q)=>{if(M(Q,u0))return{sql:Q.value.join(""),params:[]};if(M(Q,CY))return{sql:G(Q.value),params:[]};if(Q===void 0)return{sql:"",params:[]};if(Array.isArray(Q)){let z=[new u0("(")];for(let[O,D]of Q.entries())if(z.push(D),O<Q.length-1)z.push(new u0(", "));return z.push(new u0(")")),this.buildQueryFromSourceParams(z,X)}if(M(Q,x))return this.buildQueryFromSourceParams(Q.queryChunks,{...X,inlineParams:J||Q.shouldInlineParams});if(M(Q,P)){let z=Q[P.Symbol.Schema],O=Q[P.Symbol.Name];return{sql:z===void 0||Q[L6]?G(O):G(z)+"."+G(O),params:[]}}if(M(Q,E0)){let z=_.getColumnCasing(Q);if(Z.invokeSource==="indexes")return{sql:G(z),params:[]};let O=Q.table[P.Symbol.Schema];return{sql:Q.table[L6]||O===void 0?G(Q.table[P.Symbol.Name])+"."+G(z):G(O)+"."+G(Q.table[P.Symbol.Name])+"."+G(z),params:[]}}if(M(Q,L1)){let z=Q[A0].schema,O=Q[A0].name;return{sql:z===void 0||Q[A0].isAlias?G(O):G(z)+"."+G(O),params:[]}}if(M(Q,N1)){if(M(Q.value,N4))return{sql:W($.value++,Q),params:[Q],typings:["none"]};let z=Q.value===null?null:Q.encoder.mapToDriverValue(Q.value);if(M(z,x))return this.buildQueryFromSourceParams([z],X);if(J)return{sql:this.mapInlineParam(z,X),params:[]};let O=["none"];if(H)O=[H(Q.encoder)];return{sql:W($.value++,z),params:[z],typings:O}}if(M(Q,N4))return{sql:W($.value++,Q),params:[Q],typings:["none"]};if(M(Q,x.Aliased)&&Q.fieldAlias!==void 0)return{sql:G(Q.fieldAlias),params:[]};if(M(Q,P0)){if(Q._.isWith)return{sql:G(Q._.alias),params:[]};return this.buildQueryFromSourceParams([new u0("("),Q._.sql,new u0(") "),new CY(Q._.alias)],X)}if(E3(Q)){if(Q.schema)return{sql:G(Q.schema)+"."+G(Q.enumName),params:[]};return{sql:G(Q.enumName),params:[]}}if(QX(Q)){if(Q.shouldOmitSQLParens?.())return this.buildQueryFromSourceParams([Q.getSQL()],X);return this.buildQueryFromSourceParams([new u0("("),Q.getSQL(),new u0(")")],X)}if(J)return{sql:this.mapInlineParam(Q,X),params:[]};return{sql:W($.value++,Q),params:[Q],typings:["none"]}}))}mapInlineParam(Y,{escapeString:Z}){if(Y===null)return"null";if(typeof Y==="number"||typeof Y==="boolean")return Y.toString();if(typeof Y==="string")return Z(Y);if(typeof Y==="object"){let X=Y.toString();if(X==="[object Object]")return Z(JSON.stringify(Y));return Z(X)}throw new Error("Unexpected param value: "+Y)}getSQL(){return this}as(Y){if(Y===void 0)return this;return new x.Aliased(this,Y)}mapWith(Y){return this.decoder=typeof Y==="function"?{mapFromDriverValue:Y}:Y,this}inlineParams(){return this.shouldInlineParams=!0,this}if(Y){return Y?this:void 0}}class CY{constructor(Y){this.value=Y}static[U]="Name";brand;getSQL(){return new x([this])}}function w3(Y){return typeof Y==="object"&&Y!==null&&"mapToDriverValue"in Y&&typeof Y.mapToDriverValue==="function"}var R3={mapFromDriverValue:(Y)=>Y},N3={mapToDriverValue:(Y)=>Y},KT={...R3,...N3};class N1{constructor(Y,Z=N3){this.value=Y,this.encoder=Z}static[U]="Param";brand;getSQL(){return new x([this])}}function E(Y,...Z){let X=[];if(Z.length>0||Y.length>0&&Y[0]!=="")X.push(new u0(Y[0]));for(let[_,G]of Z.entries())X.push(G,new u0(Y[_+1]));return new x(X)}((Y)=>{function Z(){return new x([])}Y.empty=Z;function X($){return new x($)}Y.fromList=X;function _($){return new x([new u0($)])}Y.raw=_;function G($,Q){let z=[];for(let[O,D]of $.entries()){if(O>0&&Q!==void 0)z.push(Q);z.push(D)}return new x(z)}Y.join=G;function W($){return new CY($)}Y.identifier=W;function H($){return new N4($)}Y.placeholder=H;function J($,Q){return new N1($,Q)}Y.param=J})(E||(E={}));((Y)=>{class Z{constructor(X,_){this.sql=X,this.fieldAlias=_}static[U]="SQL.Aliased";isSelectionField=!1;getSQL(){return this.sql}clone(){return new Z(this.sql,this.fieldAlias)}}Y.Aliased=Z})(x||(x={}));class N4{constructor(Y){this.name=Y}static[U]="Placeholder";getSQL(){return new x([this])}}function $X(Y,Z){return Y.map((X)=>{if(M(X,N4)){if(!(X.name in Z))throw new Error(`No value for placeholder "${X.name}" was provided`);return Z[X.name]}if(M(X,N1)&&M(X.value,N4)){if(!(X.value.name in Z))throw new Error(`No value for placeholder "${X.value.name}" was provided`);return X.encoder.mapToDriverValue(Z[X.value.name])}return X})}var qU=Symbol.for("drizzle:IsDrizzleView");class L1{static[U]="View";[A0];[qU]=!0;constructor({name:Y,schema:Z,selectedFields:X,query:_}){this[A0]={name:Y,originalName:Y,schema:Z,selectedFields:X,query:_,isExisting:!_,isAlias:!1}}getSQL(){return new x([this])}}E0.prototype.getSQL=function(){return new x([this])};P.prototype.getSQL=function(){return new x([this])};P0.prototype.getSQL=function(){return new x([this])};class w8{constructor(Y){this.table=Y}static[U]="ColumnAliasProxyHandler";get(Y,Z){if(Z==="table")return this.table;return Y[Z]}}class V6{constructor(Y,Z){this.alias=Y,this.replaceOriginalName=Z}static[U]="TableAliasProxyHandler";get(Y,Z){if(Z===P.Symbol.IsAlias)return!0;if(Z===P.Symbol.Name)return this.alias;if(this.replaceOriginalName&&Z===P.Symbol.OriginalName)return this.alias;if(Z===A0)return{...Y[A0],name:this.alias,isAlias:!0};if(Z===P.Symbol.Columns){let _=Y[P.Symbol.Columns];if(!_)return _;let G={};return Object.keys(_).map((W)=>{G[W]=new Proxy(_[W],new w8(new Proxy(Y,this)))}),G}let X=Y[Z];if(M(X,E0))return new Proxy(X,new w8(new Proxy(Y,this)));return X}}function TY(Y,Z){return new Proxy(Y,new V6(Z,!1))}function o1(Y,Z){return new Proxy(Y,new w8(new Proxy(Y.table,new V6(Z,!1))))}function zX(Y,Z){return new x.Aliased(M6(Y.sql,Z),Y.fieldAlias)}function M6(Y,Z){return E.join(Y.queryChunks.map((X)=>{if(M(X,E0))return o1(X,Z);if(M(X,x))return M6(X,Z);if(M(X,x.Aliased))return zX(X,Z);return X}))}class KY extends Error{static[U]="DrizzleError";constructor({message:Y,cause:Z}){super(Y);this.name="DrizzleError",this.cause=Z}}class J4 extends Error{constructor(Y,Z,X){super(`Failed query: ${Y}
62
- params: ${Z}`);if(this.query=Y,this.params=Z,this.cause=X,Error.captureStackTrace(this,J4),X)this.cause=X}}class FX extends KY{static[U]="TransactionRollbackError";constructor(){super({message:"Rollback"})}}class I3{static[U]="ConsoleLogWriter";write(Y){console.log(Y)}}class UX{static[U]="DefaultLogger";writer;constructor(Y){this.writer=Y?.writer??new I3}logQuery(Y,Z){let X=Z.map((G)=>{try{return JSON.stringify(G)}catch{return String(G)}}),_=X.length?` -- params: [${X.join(", ")}]`:"";this.writer.write(`Query: ${Y}${_}`)}}class OX{static[U]="NoopLogger";logQuery(){}}class H1{static[U]="QueryPromise";[Symbol.toStringTag]="QueryPromise";catch(Y){return this.then(void 0,Y)}finally(Y){return this.then((Z)=>{return Y?.(),Z},(Z)=>{throw Y?.(),Z})}then(Y,Z){return this.execute().then(Y,Z)}}function B3(Y,Z,X){let _={},G=Y.reduce((W,{path:H,field:J},$)=>{let Q;if(M(J,E0))Q=J;else if(M(J,x))Q=J.decoder;else Q=J.sql.decoder;let z=W;for(let[O,D]of H.entries())if(O<H.length-1){if(!(D in z))z[D]={};z=z[D]}else{let V=Z[$],R=z[D]=V===null?null:Q.mapFromDriverValue(V);if(X&&M(J,E0)&&H.length===2){let A=H[0];if(!(A in _))_[A]=R===null?c0(J.table):!1;else if(typeof _[A]==="string"&&_[A]!==c0(J.table))_[A]=!1}}return W},{});if(X&&Object.keys(_).length>0){for(let[W,H]of Object.entries(_))if(typeof H==="string"&&!X[H])G[W]=null}return G}function q1(Y,Z){return Object.entries(Y).reduce((X,[_,G])=>{if(typeof _!=="string")return X;let W=Z?[...Z,_]:[_];if(M(G,E0)||M(G,x)||M(G,x.Aliased))X.push({path:W,field:G});else if(M(G,P))X.push(...q1(G[P.Symbol.Columns],W));else X.push(...q1(G,W));return X},[])}function A6(Y,Z){let X=Object.keys(Y),_=Object.keys(Z);if(X.length!==_.length)return!1;for(let[G,W]of X.entries())if(W!==_[G])return!1;return!0}function qY(Y,Z){let X=Object.entries(Z).filter(([,_])=>_!==void 0).map(([_,G])=>{if(M(G,x)||M(G,E0))return[_,G];else return[_,new N1(G,Y[P.Symbol.Columns][_])]});if(X.length===0)throw new Error("No values to set");return Object.fromEntries(X)}function C3(Y,Z){for(let X of Z)for(let _ of Object.getOwnPropertyNames(X.prototype)){if(_==="constructor")continue;Object.defineProperty(Y.prototype,_,Object.getOwnPropertyDescriptor(X.prototype,_)||Object.create(null))}}function T3(Y){return Y[P.Symbol.Columns]}function Q4(Y){return M(Y,P0)?Y._.alias:M(Y,L1)?Y[A0].name:M(Y,x)?void 0:Y[P.Symbol.IsAlias]?Y[P.Symbol.Name]:Y[P.Symbol.BaseName]}function X0(Y,Z){return{name:typeof Y==="string"&&Y.length>0?Y:"",config:typeof Y==="object"?Y:Z}}function K3(Y){if(typeof Y!=="object"||Y===null)return!1;if(Y.constructor.name!=="Object")return!1;if("logger"in Y){let Z=typeof Y.logger;if(Z!=="boolean"&&(Z!=="object"||typeof Y.logger.logQuery!=="function")&&Z!=="undefined")return!1;return!0}if("schema"in Y){let Z=typeof Y.schema;if(Z!=="object"&&Z!=="undefined")return!1;return!0}if("casing"in Y){let Z=typeof Y.casing;if(Z!=="string"&&Z!=="undefined")return!1;return!0}if("mode"in Y){if(Y.mode!=="default"||Y.mode!=="planetscale"||Y.mode!==void 0)return!1;return!0}if("connection"in Y){let Z=typeof Y.connection;if(Z!=="string"&&Z!=="object"&&Z!=="undefined")return!1;return!0}if("client"in Y){let Z=typeof Y.client;if(Z!=="object"&&Z!=="function"&&Z!=="undefined")return!1;return!0}if(Object.keys(Y).length===0)return!0;return!1}class I4 extends k{static[U]="PgIntColumnBaseBuilder";generatedAlwaysAsIdentity(Y){if(Y){let{name:Z,...X}=Y;this.config.generatedIdentity={type:"always",sequenceName:Z,sequenceOptions:X}}else this.config.generatedIdentity={type:"always"};return this.config.hasDefault=!0,this.config.notNull=!0,this}generatedByDefaultAsIdentity(Y){if(Y){let{name:Z,...X}=Y;this.config.generatedIdentity={type:"byDefault",sequenceName:Z,sequenceOptions:X}}else this.config.generatedIdentity={type:"byDefault"};return this.config.hasDefault=!0,this.config.notNull=!0,this}}class q3 extends I4{static[U]="PgBigInt53Builder";constructor(Y){super(Y,"number","PgBigInt53")}build(Y){return new j3(Y,this.config)}}class j3 extends j{static[U]="PgBigInt53";getSQLType(){return"bigint"}mapFromDriverValue(Y){if(typeof Y==="number")return Y;return Number(Y)}}class P3 extends I4{static[U]="PgBigInt64Builder";constructor(Y){super(Y,"bigint","PgBigInt64")}build(Y){return new S3(Y,this.config)}}class S3 extends j{static[U]="PgBigInt64";getSQLType(){return"bigint"}mapFromDriverValue(Y){return BigInt(Y)}}function v3(Y,Z){let{name:X,config:_}=X0(Y,Z);if(_.mode==="number")return new q3(X);return new P3(X)}class x3 extends k{static[U]="PgBigSerial53Builder";constructor(Y){super(Y,"number","PgBigSerial53");this.config.hasDefault=!0,this.config.notNull=!0}build(Y){return new h3(Y,this.config)}}class h3 extends j{static[U]="PgBigSerial53";getSQLType(){return"bigserial"}mapFromDriverValue(Y){if(typeof Y==="number")return Y;return Number(Y)}}class f3 extends k{static[U]="PgBigSerial64Builder";constructor(Y){super(Y,"bigint","PgBigSerial64");this.config.hasDefault=!0}build(Y){return new b3(Y,this.config)}}class b3 extends j{static[U]="PgBigSerial64";getSQLType(){return"bigserial"}mapFromDriverValue(Y){return BigInt(Y)}}function k3(Y,Z){let{name:X,config:_}=X0(Y,Z);if(_.mode==="number")return new x3(X);return new f3(X)}class g3 extends k{static[U]="PgBooleanBuilder";constructor(Y){super(Y,"boolean","PgBoolean")}build(Y){return new y3(Y,this.config)}}class y3 extends j{static[U]="PgBoolean";getSQLType(){return"boolean"}}function w6(Y){return new g3(Y??"")}class p3 extends k{static[U]="PgCharBuilder";constructor(Y,Z){super(Y,"string","PgChar");this.config.length=Z.length,this.config.enumValues=Z.enum}build(Y){return new m3(Y,this.config)}}class m3 extends j{static[U]="PgChar";length=this.config.length;enumValues=this.config.enumValues;getSQLType(){return this.length===void 0?"char":`char(${this.length})`}}function u3(Y,Z={}){let{name:X,config:_}=X0(Y,Z);return new p3(X,_)}class d3 extends k{static[U]="PgCidrBuilder";constructor(Y){super(Y,"string","PgCidr")}build(Y){return new c3(Y,this.config)}}class c3 extends j{static[U]="PgCidr";getSQLType(){return"cidr"}}function l3(Y){return new d3(Y??"")}class i3 extends k{static[U]="PgCustomColumnBuilder";constructor(Y,Z,X){super(Y,"custom","PgCustomColumn");this.config.fieldConfig=Z,this.config.customTypeParams=X}build(Y){return new o3(Y,this.config)}}class o3 extends j{static[U]="PgCustomColumn";sqlName;mapTo;mapFrom;constructor(Y,Z){super(Y,Z);this.sqlName=Z.customTypeParams.dataType(Z.fieldConfig),this.mapTo=Z.customTypeParams.toDriver,this.mapFrom=Z.customTypeParams.fromDriver}getSQLType(){return this.sqlName}mapFromDriverValue(Y){return typeof this.mapFrom==="function"?this.mapFrom(Y):Y}mapToDriverValue(Y){return typeof this.mapTo==="function"?this.mapTo(Y):Y}}function n3(Y){return(Z,X)=>{let{name:_,config:G}=X0(Z,X);return new i3(_,G,Y)}}class $4 extends k{static[U]="PgDateColumnBaseBuilder";defaultNow(){return this.default(E`now()`)}}class r3 extends $4{static[U]="PgDateBuilder";constructor(Y){super(Y,"date","PgDate")}build(Y){return new jY(Y,this.config)}}class jY extends j{static[U]="PgDate";getSQLType(){return"date"}mapFromDriverValue(Y){return new Date(Y)}mapToDriverValue(Y){return Y.toISOString()}}class s3 extends $4{static[U]="PgDateStringBuilder";constructor(Y){super(Y,"string","PgDateString")}build(Y){return new PY(Y,this.config)}}class PY extends j{static[U]="PgDateString";getSQLType(){return"date"}}function a3(Y,Z){let{name:X,config:_}=X0(Y,Z);if(_?.mode==="date")return new r3(X);return new s3(X)}class t3 extends k{static[U]="PgDoublePrecisionBuilder";constructor(Y){super(Y,"number","PgDoublePrecision")}build(Y){return new e3(Y,this.config)}}class e3 extends j{static[U]="PgDoublePrecision";getSQLType(){return"double precision"}mapFromDriverValue(Y){if(typeof Y==="string")return Number.parseFloat(Y);return Y}}function YW(Y){return new t3(Y??"")}class ZW extends k{static[U]="PgInetBuilder";constructor(Y){super(Y,"string","PgInet")}build(Y){return new XW(Y,this.config)}}class XW extends j{static[U]="PgInet";getSQLType(){return"inet"}}function _W(Y){return new ZW(Y??"")}class GW extends I4{static[U]="PgIntegerBuilder";constructor(Y){super(Y,"number","PgInteger")}build(Y){return new WW(Y,this.config)}}class WW extends j{static[U]="PgInteger";getSQLType(){return"integer"}mapFromDriverValue(Y){if(typeof Y==="string")return Number.parseInt(Y);return Y}}function R6(Y){return new GW(Y??"")}class HW extends k{static[U]="PgIntervalBuilder";constructor(Y,Z){super(Y,"string","PgInterval");this.config.intervalConfig=Z}build(Y){return new JW(Y,this.config)}}class JW extends j{static[U]="PgInterval";fields=this.config.intervalConfig.fields;precision=this.config.intervalConfig.precision;getSQLType(){let Y=this.fields?` ${this.fields}`:"",Z=this.precision?`(${this.precision})`:"";return`interval${Y}${Z}`}}function QW(Y,Z={}){let{name:X,config:_}=X0(Y,Z);return new HW(X,_)}class $W extends k{static[U]="PgJsonBuilder";constructor(Y){super(Y,"json","PgJson")}build(Y){return new SY(Y,this.config)}}class SY extends j{static[U]="PgJson";constructor(Y,Z){super(Y,Z)}getSQLType(){return"json"}mapToDriverValue(Y){return JSON.stringify(Y)}mapFromDriverValue(Y){if(typeof Y==="string")try{return JSON.parse(Y)}catch{return Y}return Y}}function zW(Y){return new $W(Y??"")}class FW extends k{static[U]="PgJsonbBuilder";constructor(Y){super(Y,"json","PgJsonb")}build(Y){return new vY(Y,this.config)}}class vY extends j{static[U]="PgJsonb";constructor(Y,Z){super(Y,Z)}getSQLType(){return"jsonb"}mapToDriverValue(Y){return JSON.stringify(Y)}mapFromDriverValue(Y){if(typeof Y==="string")try{return JSON.parse(Y)}catch{return Y}return Y}}function UW(Y){return new FW(Y??"")}class OW extends k{static[U]="PgLineBuilder";constructor(Y){super(Y,"array","PgLine")}build(Y){return new EW(Y,this.config)}}class EW extends j{static[U]="PgLine";getSQLType(){return"line"}mapFromDriverValue(Y){let[Z,X,_]=Y.slice(1,-1).split(",");return[Number.parseFloat(Z),Number.parseFloat(X),Number.parseFloat(_)]}mapToDriverValue(Y){return`{${Y[0]},${Y[1]},${Y[2]}}`}}class DW extends k{static[U]="PgLineABCBuilder";constructor(Y){super(Y,"json","PgLineABC")}build(Y){return new LW(Y,this.config)}}class LW extends j{static[U]="PgLineABC";getSQLType(){return"line"}mapFromDriverValue(Y){let[Z,X,_]=Y.slice(1,-1).split(",");return{a:Number.parseFloat(Z),b:Number.parseFloat(X),c:Number.parseFloat(_)}}mapToDriverValue(Y){return`{${Y.a},${Y.b},${Y.c}}`}}function VW(Y,Z){let{name:X,config:_}=X0(Y,Z);if(!_?.mode||_.mode==="tuple")return new OW(X);return new DW(X)}class MW extends k{static[U]="PgMacaddrBuilder";constructor(Y){super(Y,"string","PgMacaddr")}build(Y){return new AW(Y,this.config)}}class AW extends j{static[U]="PgMacaddr";getSQLType(){return"macaddr"}}function wW(Y){return new MW(Y??"")}class RW extends k{static[U]="PgMacaddr8Builder";constructor(Y){super(Y,"string","PgMacaddr8")}build(Y){return new NW(Y,this.config)}}class NW extends j{static[U]="PgMacaddr8";getSQLType(){return"macaddr8"}}function IW(Y){return new RW(Y??"")}class BW extends k{static[U]="PgNumericBuilder";constructor(Y,Z,X){super(Y,"string","PgNumeric");this.config.precision=Z,this.config.scale=X}build(Y){return new xY(Y,this.config)}}class xY extends j{static[U]="PgNumeric";precision;scale;constructor(Y,Z){super(Y,Z);this.precision=Z.precision,this.scale=Z.scale}mapFromDriverValue(Y){if(typeof Y==="string")return Y;return String(Y)}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 CW extends k{static[U]="PgNumericNumberBuilder";constructor(Y,Z,X){super(Y,"number","PgNumericNumber");this.config.precision=Z,this.config.scale=X}build(Y){return new TW(Y,this.config)}}class TW extends j{static[U]="PgNumericNumber";precision;scale;constructor(Y,Z){super(Y,Z);this.precision=Z.precision,this.scale=Z.scale}mapFromDriverValue(Y){if(typeof Y==="number")return Y;return Number(Y)}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 KW extends k{static[U]="PgNumericBigIntBuilder";constructor(Y,Z,X){super(Y,"bigint","PgNumericBigInt");this.config.precision=Z,this.config.scale=X}build(Y){return new qW(Y,this.config)}}class qW extends j{static[U]="PgNumericBigInt";precision;scale;constructor(Y,Z){super(Y,Z);this.precision=Z.precision,this.scale=Z.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 jW(Y,Z){let{name:X,config:_}=X0(Y,Z),G=_?.mode;return G==="number"?new CW(X,_?.precision,_?.scale):G==="bigint"?new KW(X,_?.precision,_?.scale):new BW(X,_?.precision,_?.scale)}class PW extends k{static[U]="PgPointTupleBuilder";constructor(Y){super(Y,"array","PgPointTuple")}build(Y){return new SW(Y,this.config)}}class SW extends j{static[U]="PgPointTuple";getSQLType(){return"point"}mapFromDriverValue(Y){if(typeof Y==="string"){let[Z,X]=Y.slice(1,-1).split(",");return[Number.parseFloat(Z),Number.parseFloat(X)]}return[Y.x,Y.y]}mapToDriverValue(Y){return`(${Y[0]},${Y[1]})`}}class vW extends k{static[U]="PgPointObjectBuilder";constructor(Y){super(Y,"json","PgPointObject")}build(Y){return new xW(Y,this.config)}}class xW extends j{static[U]="PgPointObject";getSQLType(){return"point"}mapFromDriverValue(Y){if(typeof Y==="string"){let[Z,X]=Y.slice(1,-1).split(",");return{x:Number.parseFloat(Z),y:Number.parseFloat(X)}}return Y}mapToDriverValue(Y){return`(${Y.x},${Y.y})`}}function hW(Y,Z){let{name:X,config:_}=X0(Y,Z);if(!_?.mode||_.mode==="tuple")return new PW(X);return new vW(X)}function jU(Y){let Z=[];for(let X=0;X<Y.length;X+=2)Z.push(Number.parseInt(Y.slice(X,X+2),16));return new Uint8Array(Z)}function fW(Y,Z){let X=new ArrayBuffer(8),_=new DataView(X);for(let G=0;G<8;G++)_.setUint8(G,Y[Z+G]);return _.getFloat64(0,!0)}function EX(Y){let Z=jU(Y),X=0,_=Z[X];X+=1;let G=new DataView(Z.buffer),W=G.getUint32(X,_===1);X+=4;let H;if(W&536870912)H=G.getUint32(X,_===1),X+=4;if((W&65535)===1){let J=fW(Z,X);X+=8;let $=fW(Z,X);return X+=8,[J,$]}throw new Error("Unsupported geometry type")}class bW extends k{static[U]="PgGeometryBuilder";constructor(Y){super(Y,"array","PgGeometry")}build(Y){return new kW(Y,this.config)}}class kW extends j{static[U]="PgGeometry";getSQLType(){return"geometry(point)"}mapFromDriverValue(Y){return EX(Y)}mapToDriverValue(Y){return`point(${Y[0]} ${Y[1]})`}}class gW extends k{static[U]="PgGeometryObjectBuilder";constructor(Y){super(Y,"json","PgGeometryObject")}build(Y){return new yW(Y,this.config)}}class yW extends j{static[U]="PgGeometryObject";getSQLType(){return"geometry(point)"}mapFromDriverValue(Y){let Z=EX(Y);return{x:Z[0],y:Z[1]}}mapToDriverValue(Y){return`point(${Y.x} ${Y.y})`}}function pW(Y,Z){let{name:X,config:_}=X0(Y,Z);if(!_?.mode||_.mode==="tuple")return new bW(X);return new gW(X)}class mW extends k{static[U]="PgRealBuilder";constructor(Y,Z){super(Y,"number","PgReal");this.config.length=Z}build(Y){return new uW(Y,this.config)}}class uW extends j{static[U]="PgReal";constructor(Y,Z){super(Y,Z)}getSQLType(){return"real"}mapFromDriverValue=(Y)=>{if(typeof Y==="string")return Number.parseFloat(Y);return Y}}function dW(Y){return new mW(Y??"")}class cW extends k{static[U]="PgSerialBuilder";constructor(Y){super(Y,"number","PgSerial");this.config.hasDefault=!0,this.config.notNull=!0}build(Y){return new lW(Y,this.config)}}class lW extends j{static[U]="PgSerial";getSQLType(){return"serial"}}function iW(Y){return new cW(Y??"")}class oW extends I4{static[U]="PgSmallIntBuilder";constructor(Y){super(Y,"number","PgSmallInt")}build(Y){return new nW(Y,this.config)}}class nW extends j{static[U]="PgSmallInt";getSQLType(){return"smallint"}mapFromDriverValue=(Y)=>{if(typeof Y==="string")return Number(Y);return Y}}function rW(Y){return new oW(Y??"")}class sW extends k{static[U]="PgSmallSerialBuilder";constructor(Y){super(Y,"number","PgSmallSerial");this.config.hasDefault=!0,this.config.notNull=!0}build(Y){return new aW(Y,this.config)}}class aW extends j{static[U]="PgSmallSerial";getSQLType(){return"smallserial"}}function tW(Y){return new sW(Y??"")}class eW extends k{static[U]="PgTextBuilder";constructor(Y,Z){super(Y,"string","PgText");this.config.enumValues=Z.enum}build(Y){return new Y2(Y,this.config)}}class Y2 extends j{static[U]="PgText";enumValues=this.config.enumValues;getSQLType(){return"text"}}function Z2(Y,Z={}){let{name:X,config:_}=X0(Y,Z);return new eW(X,_)}class X2 extends $4{constructor(Y,Z,X){super(Y,"string","PgTime");this.withTimezone=Z,this.precision=X,this.config.withTimezone=Z,this.config.precision=X}static[U]="PgTimeBuilder";build(Y){return new hY(Y,this.config)}}class hY extends j{static[U]="PgTime";withTimezone;precision;constructor(Y,Z){super(Y,Z);this.withTimezone=Z.withTimezone,this.precision=Z.precision}getSQLType(){return`time${this.precision===void 0?"":`(${this.precision})`}${this.withTimezone?" with time zone":""}`}}function _2(Y,Z={}){let{name:X,config:_}=X0(Y,Z);return new X2(X,_.withTimezone??!1,_.precision)}class G2 extends $4{static[U]="PgTimestampBuilder";constructor(Y,Z,X){super(Y,"date","PgTimestamp");this.config.withTimezone=Z,this.config.precision=X}build(Y){return new fY(Y,this.config)}}class fY extends j{static[U]="PgTimestamp";withTimezone;precision;constructor(Y,Z){super(Y,Z);this.withTimezone=Z.withTimezone,this.precision=Z.precision}getSQLType(){return`timestamp${this.precision===void 0?"":` (${this.precision})`}${this.withTimezone?" with time zone":""}`}mapFromDriverValue=(Y)=>{return new Date(this.withTimezone?Y:Y+"+0000")};mapToDriverValue=(Y)=>{return Y.toISOString()}}class W2 extends $4{static[U]="PgTimestampStringBuilder";constructor(Y,Z,X){super(Y,"string","PgTimestampString");this.config.withTimezone=Z,this.config.precision=X}build(Y){return new bY(Y,this.config)}}class bY extends j{static[U]="PgTimestampString";withTimezone;precision;constructor(Y,Z){super(Y,Z);this.withTimezone=Z.withTimezone,this.precision=Z.precision}getSQLType(){return`timestamp${this.precision===void 0?"":`(${this.precision})`}${this.withTimezone?" with time zone":""}`}}function H2(Y,Z={}){let{name:X,config:_}=X0(Y,Z);if(_?.mode==="string")return new W2(X,_.withTimezone??!1,_.precision);return new G2(X,_?.withTimezone??!1,_?.precision)}class J2 extends k{static[U]="PgUUIDBuilder";constructor(Y){super(Y,"string","PgUUID")}defaultRandom(){return this.default(E`gen_random_uuid()`)}build(Y){return new kY(Y,this.config)}}class kY extends j{static[U]="PgUUID";getSQLType(){return"uuid"}}function j1(Y){return new J2(Y??"")}class Q2 extends k{static[U]="PgVarcharBuilder";constructor(Y,Z){super(Y,"string","PgVarchar");this.config.length=Z.length,this.config.enumValues=Z.enum}build(Y){return new $2(Y,this.config)}}class $2 extends j{static[U]="PgVarchar";length=this.config.length;enumValues=this.config.enumValues;getSQLType(){return this.length===void 0?"varchar":`varchar(${this.length})`}}function e0(Y,Z={}){let{name:X,config:_}=X0(Y,Z);return new Q2(X,_)}class z2 extends k{static[U]="PgBinaryVectorBuilder";constructor(Y,Z){super(Y,"string","PgBinaryVector");this.config.dimensions=Z.dimensions}build(Y){return new F2(Y,this.config)}}class F2 extends j{static[U]="PgBinaryVector";dimensions=this.config.dimensions;getSQLType(){return`bit(${this.dimensions})`}}function U2(Y,Z){let{name:X,config:_}=X0(Y,Z);return new z2(X,_)}class O2 extends k{static[U]="PgHalfVectorBuilder";constructor(Y,Z){super(Y,"array","PgHalfVector");this.config.dimensions=Z.dimensions}build(Y){return new E2(Y,this.config)}}class E2 extends j{static[U]="PgHalfVector";dimensions=this.config.dimensions;getSQLType(){return`halfvec(${this.dimensions})`}mapToDriverValue(Y){return JSON.stringify(Y)}mapFromDriverValue(Y){return Y.slice(1,-1).split(",").map((Z)=>Number.parseFloat(Z))}}function D2(Y,Z){let{name:X,config:_}=X0(Y,Z);return new O2(X,_)}class L2 extends k{static[U]="PgSparseVectorBuilder";constructor(Y,Z){super(Y,"string","PgSparseVector");this.config.dimensions=Z.dimensions}build(Y){return new V2(Y,this.config)}}class V2 extends j{static[U]="PgSparseVector";dimensions=this.config.dimensions;getSQLType(){return`sparsevec(${this.dimensions})`}}function M2(Y,Z){let{name:X,config:_}=X0(Y,Z);return new L2(X,_)}class A2 extends k{static[U]="PgVectorBuilder";constructor(Y,Z){super(Y,"array","PgVector");this.config.dimensions=Z.dimensions}build(Y){return new w2(Y,this.config)}}class w2 extends j{static[U]="PgVector";dimensions=this.config.dimensions;getSQLType(){return`vector(${this.dimensions})`}mapToDriverValue(Y){return JSON.stringify(Y)}mapFromDriverValue(Y){return Y.slice(1,-1).split(",").map((Z)=>Number.parseFloat(Z))}}function R2(Y,Z){let{name:X,config:_}=X0(Y,Z);return new A2(X,_)}function N2(){return{bigint:v3,bigserial:k3,boolean:w6,char:u3,cidr:l3,customType:n3,date:a3,doublePrecision:YW,inet:_W,integer:R6,interval:QW,json:zW,jsonb:UW,line:VW,macaddr:wW,macaddr8:IW,numeric:jW,point:hW,geometry:pW,real:dW,serial:iW,smallint:rW,smallserial:tW,text:Z2,time:_2,timestamp:H2,uuid:j1,varchar:e0,bit:U2,halfvec:D2,sparsevec:M2,vector:R2}}var DX=Symbol.for("drizzle:PgInlineForeignKeys"),I2=Symbol.for("drizzle:EnableRLS");class d0 extends P{static[U]="PgTable";static Symbol=Object.assign({},P.Symbol,{InlineForeignKeys:DX,EnableRLS:I2});[DX]=[];[I2]=!1;[P.Symbol.ExtraConfigBuilder]=void 0;[P.Symbol.ExtraConfigColumns]={}}function PU(Y,Z,X,_,G=Y){let W=new d0(Y,_,G),H=typeof Z==="function"?Z(N2()):Z,J=Object.fromEntries(Object.entries(H).map(([z,O])=>{let D=O;D.setName(z);let V=D.build(W);return W[DX].push(...D.buildForeignKeys(V,W)),[z,V]})),$=Object.fromEntries(Object.entries(H).map(([z,O])=>{let D=O;D.setName(z);let V=D.buildExtraConfigColumn(W);return[z,V]})),Q=Object.assign(W,J);if(Q[P.Symbol.Columns]=J,Q[P.Symbol.ExtraConfigColumns]=$,X)Q[d0.Symbol.ExtraConfigBuilder]=X;return Object.assign(Q,{enableRLS:()=>{return Q[d0.Symbol.EnableRLS]=!0,Q}})}var B4=(Y,Z,X)=>{return PU(Y,Z,X,void 0)};function B2(...Y){if(Y[0].columns)return new N6(Y[0].columns,Y[0].name);return new N6(Y)}class N6{static[U]="PgPrimaryKeyBuilder";columns;name;constructor(Y,Z){this.columns=Y,this.name=Z}build(Y){return new C2(Y,this.columns,this.name)}}class C2{constructor(Y,Z,X){this.table=Y,this.columns=Z,this.name=X}static[U]="PgPrimaryKey";columns;name;getName(){return this.name??`${this.table[d0.Symbol.Name]}_${this.columns.map((Y)=>Y.name).join("_")}_pk`}}function V1(Y,Z){if(w3(Z)&&!QX(Y)&&!M(Y,N1)&&!M(Y,N4)&&!M(Y,E0)&&!M(Y,P)&&!M(Y,L1))return new N1(Y,Z);return Y}var gY=(Y,Z)=>{return E`${Y} = ${V1(Z,Y)}`},T2=(Y,Z)=>{return E`${Y} <> ${V1(Z,Y)}`};function I6(...Y){let Z=Y.filter((X)=>X!==void 0);if(Z.length===0)return;if(Z.length===1)return new x(Z);return new x([new u0("("),E.join(Z,new u0(" and ")),new u0(")")])}function K2(...Y){let Z=Y.filter((X)=>X!==void 0);if(Z.length===0)return;if(Z.length===1)return new x(Z);return new x([new u0("("),E.join(Z,new u0(" or ")),new u0(")")])}function q2(Y){return E`not ${Y}`}var j2=(Y,Z)=>{return E`${Y} > ${V1(Z,Y)}`},P2=(Y,Z)=>{return E`${Y} >= ${V1(Z,Y)}`},S2=(Y,Z)=>{return E`${Y} < ${V1(Z,Y)}`},v2=(Y,Z)=>{return E`${Y} <= ${V1(Z,Y)}`};function x2(Y,Z){if(Array.isArray(Z)){if(Z.length===0)return E`false`;return E`${Y} in ${Z.map((X)=>V1(X,Y))}`}return E`${Y} in ${V1(Z,Y)}`}function h2(Y,Z){if(Array.isArray(Z)){if(Z.length===0)return E`true`;return E`${Y} not in ${Z.map((X)=>V1(X,Y))}`}return E`${Y} not in ${V1(Z,Y)}`}function f2(Y){return E`${Y} is null`}function b2(Y){return E`${Y} is not null`}function k2(Y){return E`exists ${Y}`}function g2(Y){return E`not exists ${Y}`}function y2(Y,Z,X){return E`${Y} between ${V1(Z,Y)} and ${V1(X,Y)}`}function p2(Y,Z,X){return E`${Y} not between ${V1(Z,Y)} and ${V1(X,Y)}`}function m2(Y,Z){return E`${Y} like ${Z}`}function u2(Y,Z){return E`${Y} not like ${Z}`}function d2(Y,Z){return E`${Y} ilike ${Z}`}function c2(Y,Z){return E`${Y} not ilike ${Z}`}function l2(Y){return E`${Y} asc`}function i2(Y){return E`${Y} desc`}class LX{constructor(Y,Z,X){this.sourceTable=Y,this.referencedTable=Z,this.relationName=X,this.referencedTableName=Z[P.Symbol.Name]}static[U]="Relation";referencedTableName;fieldName}class o2{constructor(Y,Z){this.table=Y,this.config=Z}static[U]="Relations"}class C4 extends LX{constructor(Y,Z,X,_){super(Y,Z,X?.relationName);this.config=X,this.isNullable=_}static[U]="One";withFieldName(Y){let Z=new C4(this.sourceTable,this.referencedTable,this.config,this.isNullable);return Z.fieldName=Y,Z}}class B6 extends LX{constructor(Y,Z,X){super(Y,Z,X?.relationName);this.config=X}static[U]="Many";withFieldName(Y){let Z=new B6(this.sourceTable,this.referencedTable,this.config);return Z.fieldName=Y,Z}}function n2(){return{and:I6,between:y2,eq:gY,exists:k2,gt:j2,gte:P2,ilike:d2,inArray:x2,isNull:f2,isNotNull:b2,like:m2,lt:S2,lte:v2,ne:T2,not:q2,notBetween:p2,notExists:g2,notLike:u2,notIlike:c2,notInArray:h2,or:K2,sql:E}}function r2(){return{sql:E,asc:l2,desc:i2}}function s2(Y,Z){if(Object.keys(Y).length===1&&"default"in Y&&!M(Y.default,P))Y=Y.default;let X={},_={},G={};for(let[W,H]of Object.entries(Y))if(M(H,P)){let J=y4(H),$=_[J];X[J]=W,G[W]={tsName:W,dbName:H[P.Symbol.Name],schema:H[P.Symbol.Schema],columns:H[P.Symbol.Columns],relations:$?.relations??{},primaryKey:$?.primaryKey??[]};for(let z of Object.values(H[P.Symbol.Columns]))if(z.primary)G[W].primaryKey.push(z);let Q=H[P.Symbol.ExtraConfigBuilder]?.(H[P.Symbol.ExtraConfigColumns]);if(Q){for(let z of Object.values(Q))if(M(z,N6))G[W].primaryKey.push(...z.columns)}}else if(M(H,o2)){let J=y4(H.table),$=X[J],Q=H.config(Z(H.table)),z;for(let[O,D]of Object.entries(Q))if($){let V=G[$];if(V.relations[O]=D,z)V.primaryKey.push(...z)}else{if(!(J in _))_[J]={relations:{},primaryKey:z};_[J].relations[O]=D}}return{tables:G,tableNamesMap:X}}function SU(Y){return function Z(X,_){return new C4(Y,X,_,_?.fields.reduce((G,W)=>G&&W.notNull,!0)??!1)}}function vU(Y){return function Z(X,_){return new B6(Y,X,_)}}function a2(Y,Z,X){if(M(X,C4)&&X.config)return{fields:X.config.fields,references:X.config.references};let _=Z[y4(X.referencedTable)];if(!_)throw new Error(`Table "${X.referencedTable[P.Symbol.Name]}" not found in schema`);let G=Y[_];if(!G)throw new Error(`Table "${_}" not found in schema`);let W=X.sourceTable,H=Z[y4(W)];if(!H)throw new Error(`Table "${W[P.Symbol.Name]}" not found in schema`);let J=[];for(let $ of Object.values(G.relations))if(X.relationName&&X!==$&&$.relationName===X.relationName||!X.relationName&&$.referencedTable===X.sourceTable)J.push($);if(J.length>1)throw X.relationName?new Error(`There are multiple relations with name "${X.relationName}" in table "${_}"`):new Error(`There are multiple relations between "${_}" and "${X.sourceTable[P.Symbol.Name]}". Please specify relation name`);if(J[0]&&M(J[0],C4)&&J[0].config)return{fields:J[0].config.references,references:J[0].config.fields};throw new Error(`There is not enough information to infer relation "${H}.${X.fieldName}"`)}function t2(Y){return{one:SU(Y),many:vU(Y)}}function yY(Y,Z,X,_,G=(W)=>W){let W={};for(let[H,J]of _.entries())if(J.isJson){let $=Z.relations[J.tsKey],Q=X[H],z=typeof Q==="string"?JSON.parse(Q):Q;W[J.tsKey]=M($,C4)?z&&yY(Y,Y[J.relationTableTsKey],z,J.selection,G):z.map((O)=>yY(Y,Y[J.relationTableTsKey],O,J.selection,G))}else{let $=G(X[H]),Q=J.field,z;if(M(Q,E0))z=Q;else if(M(Q,x))z=Q.decoder;else z=Q.sql.decoder;W[J.tsKey]=$===null?null:z.mapFromDriverValue($)}return W}import XO from"os";import _O from"fs";var pY=new Map,VX=new Map,MX=Symbol("OriginError"),R8={};class P1 extends Promise{constructor(Y,Z,X,_,G={}){let W,H;super((J,$)=>{W=J,H=$});this.tagged=Array.isArray(Y.raw),this.strings=Y,this.args=Z,this.handler=X,this.canceller=_,this.options=G,this.state=null,this.statement=null,this.resolve=(J)=>(this.active=!1,W(J)),this.reject=(J)=>(this.active=!1,H(J)),this.active=!1,this.cancelled=null,this.executed=!1,this.signature="",this[MX]=this.handler.debug?new Error:this.tagged&&xU(this.strings)}get origin(){return(this.handler.debug?this[MX].stack:this.tagged&&VX.has(this.strings)?VX.get(this.strings):VX.set(this.strings,this[MX].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(Y=1,Z){if(this.options.simple=!1,typeof Y==="function")Z=Y,Y=1;if(this.cursorRows=Y,typeof Z==="function")return this.cursorFn=Z,this;let X;return{[Symbol.asyncIterator]:()=>({next:()=>{if(this.executed&&!this.active)return{done:!0};X&&X();let _=new Promise((G,W)=>{this.cursorFn=(H)=>{return G({value:H,done:!1}),new Promise((J)=>X=J)},this.resolve=()=>(this.active=!1,G({done:!0})),this.reject=(H)=>(this.active=!1,W(H))});return this.execute(),_},return(){return X&&X(R8),{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(Y){return this.forEachFn=Y,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 xU(Y){if(pY.has(Y))return pY.get(Y);let Z=Error.stackTraceLimit;return Error.stackTraceLimit=4,pY.set(Y,new Error),Error.stackTraceLimit=Z,pY.get(Y)}class N8 extends Error{constructor(Y){super(Y.message);this.name=this.constructor.name,Object.assign(this,Y)}}var f0={connection:e2,postgres:YH,generic:ZH,notSupported:XH};function e2(Y,Z,X){let{host:_,port:G}=X||Z,W=Object.assign(new Error("write "+Y+" "+(Z.path||_+":"+G)),{code:Y,errno:Y,address:Z.path||_},Z.path?{}:{port:G});return Error.captureStackTrace(W,e2),W}function YH(Y){let Z=new N8(Y);return Error.captureStackTrace(Z,YH),Z}function ZH(Y,Z){let X=Object.assign(new Error(Y+": "+Z),{code:Y});return Error.captureStackTrace(X,ZH),X}function XH(Y){let Z=Object.assign(new Error(Y+" (B) is not supported"),{code:"MESSAGE_NOT_SUPPORTED",name:Y});return Error.captureStackTrace(Z,XH),Z}var hU={string:{to:25,from:null,serialize:(Y)=>""+Y},number:{to:0,from:[21,23,26,700,701],serialize:(Y)=>""+Y,parse:(Y)=>+Y},json:{to:114,from:[114,3802],serialize:(Y)=>JSON.stringify(Y),parse:(Y)=>JSON.parse(Y)},boolean:{to:16,from:16,serialize:(Y)=>Y===!0?"t":"f",parse:(Y)=>Y==="t"},date:{to:1184,from:[1082,1114,1184],serialize:(Y)=>(Y instanceof Date?Y:new Date(Y)).toISOString(),parse:(Y)=>new Date(Y)},bytea:{to:17,from:17,serialize:(Y)=>"\\x"+Buffer.from(Y).toString("hex"),parse:(Y)=>Buffer.from(Y.slice(2),"hex")}};class dY{then(){AX()}catch(){AX()}finally(){AX()}}class q6 extends dY{constructor(Y){super();this.value=iY(Y)}}class n1 extends dY{constructor(Y,Z,X){super();this.value=Y,this.type=Z,this.array=X}}class cY extends dY{constructor(Y,Z){super();this.first=Y,this.rest=Z}build(Y,Z,X,_){let G=fU.map(([W,H])=>({fn:H,i:Y.search(W)})).sort((W,H)=>W.i-H.i).pop();return G.i===-1?BX(this.first,_):G.fn(this.first,this.rest,Z,X,_)}}function lY(Y,Z,X,_){let G=Y instanceof n1?Y.value:Y;if(G===void 0){if(Y instanceof n1?Y.value=_.transform.undefined:G=Y=_.transform.undefined,G===void 0)throw f0.generic("UNDEFINED_VALUE","Undefined values are not allowed")}return"$"+X.push(Y instanceof n1?(Z.push(Y.value),Y.array?Y.array[Y.type||uY(Y.value)]||Y.type||HH(Y.value):Y.type):(Z.push(Y),uY(Y)))}var GH=QH(hU);function NX(Y,Z,X,_,G,W){for(let H=1;H<Y.strings.length;H++)Z+=IX(Z,X,_,G,W)+Y.strings[H],X=Y.args[H];return Z}function IX(Y,Z,X,_,G){return Z instanceof cY?Z.build(Y,X,_,G):Z instanceof P1?RX(Z,X,_,G):Z instanceof q6?Z.value:Z&&Z[0]instanceof P1?Z.reduce((W,H)=>W+" "+RX(H,X,_,G),""):lY(Z,X,_,G)}function RX(Y,Z,X,_){return Y.fragment=!0,NX(Y,Y.strings[0],Y.args[0],Z,X,_)}function WH(Y,Z,X,_,G){return Y.map((W)=>"("+_.map((H)=>IX("values",W[H],Z,X,G)).join(",")+")").join(",")}function _H(Y,Z,X,_,G){let W=Array.isArray(Y[0]),H=Z.length?Z.flat():Object.keys(W?Y[0]:Y);return WH(W?Y:[Y],X,_,H,G)}function mY(Y,Z,X,_,G){if(typeof Y==="string"&&(Y=[Y].concat(Z)),Array.isArray(Y))return BX(Y,G);let W;return(Z.length?Z.flat():Object.keys(Y)).map((J)=>{return W=Y[J],(W instanceof P1?RX(W,X,_,G):W instanceof q6?W.value:lY(W,X,_,G))+" as "+iY(G.transform.column.to?G.transform.column.to(J):J)}).join(",")}var fU=Object.entries({values:_H,in:(...Y)=>{let Z=_H(...Y);return Z==="()"?"(null)":Z},select:mY,as:mY,returning:mY,"\\(":mY,update(Y,Z,X,_,G){return(Z.length?Z.flat():Object.keys(Y)).map((W)=>iY(G.transform.column.to?G.transform.column.to(W):W)+"="+IX("values",Y[W],X,_,G))},insert(Y,Z,X,_,G){let W=Z.length?Z.flat():Object.keys(Array.isArray(Y)?Y[0]:Y);return"("+BX(W,G)+")values"+WH(Array.isArray(Y)?Y:[Y],X,_,W,G)}}).map(([Y,Z])=>[new RegExp("((?:^|[\\s(])"+Y+"(?:$|[\\s(]))(?![\\s\\S]*\\1)","i"),Z]);function AX(){throw f0.generic("NOT_TAGGED_CALL","Query not called as a tagged template literal")}var{serializers:bU,parsers:kU}=GH;function HH(Y){if(Array.isArray(Y))return HH(Y[0]);return typeof Y==="string"?1009:0}var JH=function(Y){let Z=QH(Y||{});return{serializers:Object.assign({},bU,Z.serializers),parsers:Object.assign({},kU,Z.parsers)}};function QH(Y){return Object.keys(Y).reduce((Z,X)=>{if(Y[X].from&&[].concat(Y[X].from).forEach((_)=>Z.parsers[_]=Y[X].parse),Y[X].serialize)Z.serializers[Y[X].to]=Y[X].serialize,Y[X].from&&[].concat(Y[X].from).forEach((_)=>Z.serializers[_]=Y[X].serialize);return Z},{parsers:{},serializers:{}})}function BX(Y,{transform:{column:Z}}){return Y.map((X)=>iY(Z.to?Z.to(X):X)).join(",")}var iY=function Y(Z){return'"'+Z.replace(/"/g,'""').replace(/\./g,'"."')+'"'},uY=function Y(Z){return Z instanceof n1?Z.type:Z instanceof Date?1184:Z instanceof Uint8Array?17:Z===!0||Z===!1?16:typeof Z==="bigint"?20:Array.isArray(Z)?Y(Z[0]):0},gU=/\\/g,yU=/"/g;function pU(Y){return Y.replace(gU,"\\\\").replace(yU,"\\\"")}var $H=function Y(Z,X,_,G){if(Array.isArray(Z)===!1)return Z;if(!Z.length)return"{}";let W=Z[0],H=G===1020?";":",";if(Array.isArray(W)&&!W.type)return"{"+Z.map((J)=>Y(J,X,_,G)).join(H)+"}";return"{"+Z.map((J)=>{if(J===void 0){if(J=_.transform.undefined,J===void 0)throw f0.generic("UNDEFINED_VALUE","Undefined values are not allowed")}return J===null?"null":'"'+pU(X?X(J.type?J.value:J):""+J)+'"'}).join(H)+"}"},wX={i:0,char:null,str:"",quoted:!1,last:0},zH=function Y(Z,X,_){return wX.i=wX.last=0,FH(wX,Z,X,_)};function FH(Y,Z,X,_){let G=[],W=_===1020?";":",";for(;Y.i<Z.length;Y.i++){if(Y.char=Z[Y.i],Y.quoted)if(Y.char==="\\")Y.str+=Z[++Y.i];else if(Y.char==='"')G.push(X?X(Y.str):Y.str),Y.str="",Y.quoted=Z[Y.i+1]==='"',Y.last=Y.i+2;else Y.str+=Y.char;else if(Y.char==='"')Y.quoted=!0;else if(Y.char==="{")Y.last=++Y.i,G.push(FH(Y,Z,X,_));else if(Y.char==="}"){Y.quoted=!1,Y.last<Y.i&&G.push(X?X(Z.slice(Y.last,Y.i)):Z.slice(Y.last,Y.i)),Y.last=Y.i+1;break}else if(Y.char===W&&Y.p!=="}"&&Y.p!=='"')G.push(X?X(Z.slice(Y.last,Y.i)):Z.slice(Y.last,Y.i)),Y.last=Y.i+1;Y.p=Y.char}return Y.last<Y.i&&G.push(X?X(Z.slice(Y.last,Y.i+1)):Z.slice(Y.last,Y.i+1)),G}var p4=(Y)=>{let Z=Y[0];for(let X=1;X<Y.length;X++)Z+=Y[X]==="_"?Y[++X].toUpperCase():Y[X];return Z},m4=(Y)=>{let Z=Y[0].toUpperCase();for(let X=1;X<Y.length;X++)Z+=Y[X]==="_"?Y[++X].toUpperCase():Y[X];return Z},u4=(Y)=>Y.replace(/_/g,"-"),C6=(Y)=>Y.replace(/([A-Z])/g,"_$1").toLowerCase(),T6=(Y)=>(Y.slice(0,1)+Y.slice(1).replace(/([A-Z])/g,"_$1")).toLowerCase(),K6=(Y)=>Y.replace(/-/g,"_");function CX(Y){return function Z(X,_){return typeof X==="object"&&X!==null&&(_.type===114||_.type===3802)?Array.isArray(X)?X.map((G)=>Z(G,_)):Object.entries(X).reduce((G,[W,H])=>Object.assign(G,{[Y(W)]:Z(H,_)}),{}):X}}p4.column={from:p4};p4.value={from:CX(p4)};C6.column={to:C6};var TX={...p4};TX.column.to=C6;m4.column={from:m4};m4.value={from:CX(m4)};T6.column={to:T6};var KX={...m4};KX.column.to=T6;u4.column={from:u4};u4.value={from:CX(u4)};K6.column={to:K6};var qX={...u4};qX.column.to=K6;import UH from"net";import cU from"tls";import j6 from"crypto";import jX from"stream";import{performance as OH}from"perf_hooks";class d4 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 I1=mU;function mU(Y=[]){let Z=Y.slice(),X=0;return{get length(){return Z.length-X},remove:(_)=>{let G=Z.indexOf(_);return G===-1?null:(Z.splice(G,1),_)},push:(_)=>(Z.push(_),_),shift:()=>{let _=Z[X++];if(X===Z.length)X=0,Z=[];else Z[X-1]=void 0;return _}}}var Y1=Buffer.allocUnsafe(256),uU="BCcDdEFfHPpQSX".split("").reduce((Y,Z)=>{let X=Z.charCodeAt(0);return Y[Z]=()=>{return Y1[0]=X,F0.i=5,F0},Y},{}),F0=Object.assign(dU,uU,{N:String.fromCharCode(0),i:0,inc(Y){return F0.i+=Y,F0},str(Y){let Z=Buffer.byteLength(Y);return oY(Z),F0.i+=Y1.write(Y,F0.i,Z,"utf8"),F0},i16(Y){return oY(2),Y1.writeUInt16BE(Y,F0.i),F0.i+=2,F0},i32(Y,Z){if(Z||Z===0)return Y1.writeUInt32BE(Y,Z),F0;return oY(4),Y1.writeUInt32BE(Y,F0.i),F0.i+=4,F0},z(Y){return oY(Y),Y1.fill(0,F0.i,F0.i+Y),F0.i+=Y,F0},raw(Y){return Y1=Buffer.concat([Y1.subarray(0,F0.i),Y]),F0.i=Y1.length,F0},end(Y=1){Y1.writeUInt32BE(F0.i-Y,Y);let Z=Y1.subarray(0,F0.i);return F0.i=0,Y1=Buffer.allocUnsafe(256),Z}}),c=F0;function oY(Y){if(Y1.length-F0.i<Y){let Z=Y1,X=Z.length;Y1=Buffer.allocUnsafe(X+(X>>1)+Y),Z.copy(Y1)}}function dU(){return F0.i=0,F0}var vX=LH,lU=1,T4=c().S().end(),EH=c().H().end(),iU=c().i32(8).i32(80877103).end(8),oU=Buffer.concat([c().E().str(c.N).i32(0).end(),T4]),nU=c().D().str("S").str(c.N).end(),I8=()=>{},rU=new Set(["FetchPreparedStatement","RevalidateCachedQuery","transformAssignedExpr"]),sU={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 LH(Y,Z={},{onopen:X=I8,onend:_=I8,onclose:G=I8}={}){let{ssl:W,max:H,user:J,host:$,port:Q,database:z,parsers:O,transform:D,onnotice:V,onnotify:R,onparameter:A,max_pipeline:g,keep_alive:b,backoff:f,target_session_attrs:h}=Y,I=I1(),N=lU++,q={pid:null,secret:null},K=SX(JZ,Y.idle_timeout),p=SX(JZ,Y.max_lifetime),s=SX(yH,Y.connect_timeout),C=null,t,m=new d4,e=Buffer.alloc(0),U0=Y.fetch_types,b0={},Q1={},r1=Math.random().toString(36).slice(2),T=1,u=0,G0=0,C0=0,k0=0,a=0,$0=0,S0=0,T0=null,w0=null,n0=!1,L0=null,S1=null,l0=null,z4=null,g0=null,R0=null,v1=null,m1=null,v=null,K8=null,r0={queue:Z.closed,idleTimer:K,connect(F){l0=F,W_()},terminate:j8,execute:q8,cancel:fH,end:JZ,count:0,id:N};return Z.closed&&Z.closed.push(r0),r0;async function hH(){let F;try{F=Y.socket?await Promise.resolve(Y.socket(Y)):new UH.Socket}catch(L){o4(L);return}return F.on("error",o4),F.on("close",H_),F.on("drain",__),F}async function fH({pid:F,secret:L},l,W0){try{t=c().i32(16).i32(80877102).i32(F).i32(L).end(16),await G_(),C.once("error",W0),C.once("close",l)}catch(q0){W0(q0)}}function q8(F){if(n0)return k6(F,f0.connection("CONNECTION_DESTROYED",Y));if(F.cancelled)return;try{return F.state=q,v?I.push(F):(v=F,v.active=!0),gH(F),i0(bH(F))&&!F.describeFirst&&!F.cursorFn&&I.length<g&&(!F.options.onexecute||F.options.onexecute(r0))}catch(L){return I.length===0&&i0(T4),u1(L),!0}}function bH(F){if(F.parameters.length>=65534)throw f0.generic("MAX_PARAMETERS_EXCEEDED","Max number of parameters (65534) exceeded");return F.options.simple?c().Q().str(F.statement.string+c.N).end():F.describeFirst?Buffer.concat([Y_(F),EH]):F.prepare?F.prepared?b6(F):Buffer.concat([Y_(F),b6(F)]):kH(F)}function Y_(F){return Buffer.concat([Q_(F.statement.string,F.parameters,F.statement.types,F.statement.name),IJ("S",F.statement.name)])}function b6(F){return Buffer.concat([NJ(F.parameters,F.statement.types,F.statement.name,F.cursorName),F.cursorFn?$_("",F.cursorRows):oU])}function kH(F){return Buffer.concat([Q_(F.statement.string,F.parameters,F.statement.types),nU,b6(F)])}function gH(F){let L=[],l=[],W0=NX(F,F.strings[0],F.args[0],L,l,Y);!F.tagged&&F.args.forEach((q0)=>lY(q0,L,l,Y)),F.prepare=Y.prepare&&("prepare"in F.options?F.options.prepare:!0),F.string=W0,F.signature=F.prepare&&l+W0,F.onlyDescribe&&delete Q1[F.signature],F.parameters=F.parameters||L,F.prepared=F.prepare&&F.signature in Q1,F.describeFirst=F.onlyDescribe||L.length&&!F.prepared,F.statement=F.prepared?Q1[F.signature]:{string:W0,types:l,name:F.prepare?r1+T++:""},typeof Y.debug==="function"&&Y.debug(N,W0,L,l)}function i0(F,L){if(R0=R0?Buffer.concat([R0,F]):Buffer.from(F),L||R0.length>=1024)return Z_(L);return w0===null&&(w0=setImmediate(Z_)),!0}function Z_(F){let L=C.write(R0,F);return w0!==null&&clearImmediate(w0),R0=w0=null,L}function yH(){u1(f0.connection("CONNECT_TIMEOUT",Y,C)),C.destroy()}async function X_(){if(i0(iU),!await new Promise((L)=>C.once("data",(l)=>L(l[0]===83)))&&W==="prefer")return i4();C.removeAllListeners(),C=cU.connect({socket:C,servername:UH.isIP(C.host)?void 0:C.host,...W==="require"||W==="allow"||W==="prefer"?{rejectUnauthorized:!1}:W==="verify-full"?{}:typeof W==="object"?W:{}}),C.on("secureConnect",i4),C.on("error",o4),C.on("close",H_),C.on("drain",__)}function __(){!v&&X(r0)}function HZ(F){if(L0){if(L0.push(F),G0-=F.length,G0>0)return}e=L0?Buffer.concat(L0,a-G0):e.length===0?F:Buffer.concat([e,F],e.length+F.length);while(e.length>4){if(a=e.readUInt32BE(1),a>=e.length){G0=a-e.length,L0=[e];break}try{pH(e.subarray(0,a+1))}catch(L){v&&(v.cursorFn||v.describeFirst)&&i0(T4),u1(L)}e=e.subarray(a+1),G0=0,L0=null}}async function G_(){if(n0=!1,b0={},C||(C=await hH()),!C)return;if(s.start(),Y.socket)return W?X_():i4();if(C.on("connect",W?X_:i4),Y.path)return C.connect(Y.path);C.ssl=W,C.connect(Q[C0],$[C0]),C.host=$[C0],C.port=Q[C0],C0=(C0+1)%Q.length}function W_(){setTimeout(G_,u?u+$0-OH.now():0)}function i4(){try{Q1={},U0=Y.fetch_types,r1=Math.random().toString(36).slice(2),T=1,p.start(),C.on("data",HZ),b&&C.setKeepAlive&&C.setKeepAlive(!0,1000*b);let F=CJ();i0(F)}catch(F){o4(F)}}function o4(F){if(r0.queue===Z.connecting&&Y.host[k0+1])return;u1(F);while(I.length)k6(I.shift(),F)}function u1(F){g0&&(g0.destroy(F),g0=null),v&&k6(v,F),l0&&(k6(l0,F),l0=null)}function k6(F,L){if(F.reserve)return F.reject(L);if(!L||typeof L!=="object")L=new Error(L);"query"in L||"parameters"in L||Object.defineProperties(L,{stack:{value:L.stack+F.origin.replace(/.*\n/,`
63
- `),enumerable:Y.debug},query:{value:F.string,enumerable:Y.debug},parameters:{value:F.parameters,enumerable:Y.debug},args:{value:F.args,enumerable:Y.debug},types:{value:F.statement&&F.statement.types,enumerable:Y.debug}}),F.reject(L)}function JZ(){return z4||(!r0.reserved&&_(r0),!r0.reserved&&!l0&&!v&&I.length===0?(j8(),new Promise((F)=>C&&C.readyState!=="closed"?C.once("close",F):F())):z4=new Promise((F)=>v1=F))}function j8(){if(n0=!0,g0||v||l0||I.length)o4(f0.connection("CONNECTION_DESTROYED",Y));if(clearImmediate(w0),C)C.removeListener("data",HZ),C.removeListener("connect",i4),C.readyState==="open"&&C.end(c().X().end());v1&&(v1(),z4=v1=null)}async function H_(F){if(e=Buffer.alloc(0),G0=0,L0=null,clearImmediate(w0),C.removeListener("data",HZ),C.removeListener("connect",i4),K.cancel(),p.cancel(),s.cancel(),C.removeAllListeners(),C=null,l0)return W_();!F&&(v||I.length)&&o4(f0.connection("CONNECTION_CLOSED",Y,C)),u=OH.now(),F&&Y.shared.retries++,$0=(typeof f==="function"?f(Y.shared.retries):f)*1000,G(r0,f0.connection("CONNECTION_CLOSED",Y,C))}function pH(F,L=F[0]){(L===68?mH:L===100?EJ:L===65?QJ:L===83?uH:L===90?dH:L===67?cH:L===50?J_:L===49?lH:L===116?iH:L===84?oH:L===82?nH:L===110?YJ:L===75?ZJ:L===69?HJ:L===115?$J:L===51?zJ:L===71?FJ:L===78?LJ:L===72?UJ:L===99?DJ:L===73?VJ:L===86?MJ:L===118?AJ:L===87?OJ:wJ)(F)}function mH(F){let L=7,l,W0,q0,s0=v.isRaw?new Array(v.statement.columns.length):{};for(let Z1=0;Z1<v.statement.columns.length;Z1++)W0=v.statement.columns[Z1],l=F.readInt32BE(L),L+=4,q0=l===-1?null:v.isRaw===!0?F.subarray(L,L+=l):W0.parser===void 0?F.toString("utf8",L,L+=l):W0.parser.array===!0?W0.parser(F.toString("utf8",L+1,L+=l)):W0.parser(F.toString("utf8",L,L+=l)),v.isRaw?s0[Z1]=v.isRaw===!0?q0:D.value.from?D.value.from(q0,W0):q0:s0[W0.name]=D.value.from?D.value.from(q0,W0):q0;v.forEachFn?v.forEachFn(D.row.from?D.row.from(s0):s0,m):m[S0++]=D.row.from?D.row.from(s0):s0}function uH(F){let[L,l]=F.toString("utf8",5,F.length-1).split(c.N);if(b0[L]=l,Y.parameters[L]!==l)Y.parameters[L]=l,A&&A(L,l)}function dH(F){if(v&&v.options.simple&&v.resolve(S1||m),v=S1=null,m=new d4,s.cancel(),l0){if(h){if(!b0.in_hot_standby||!b0.default_transaction_read_only)return WJ();else if(GJ(h,b0))return j8()}if(U0)return l0.reserve&&(l0=null),XJ();l0&&!l0.reserve&&q8(l0),Y.shared.retries=k0=0,l0=null;return}while(I.length&&(v=I.shift())&&(v.active=!0,v.cancelled))LH(Y).cancel(v.state,v.cancelled.resolve,v.cancelled.reject);if(v)return;r0.reserved?!r0.reserved.release&&F[5]===73?z4?j8():(r0.reserved=null,X(r0)):r0.reserved():z4?j8():X(r0)}function cH(F){S0=0;for(let L=F.length-1;L>0;L--){if(F[L]===32&&F[L+1]<58&&m.count===null)m.count=+F.toString("utf8",L+1,F.length-1);if(F[L-1]>=65){m.command=F.toString("utf8",5,L),m.state=q;break}}if(K8&&(K8(),K8=null),m.command==="BEGIN"&&H!==1&&!r0.reserved)return u1(f0.generic("UNSAFE_TRANSACTION","Only use sql.begin, sql.reserved or max: 1"));if(v.options.simple)return J_();if(v.cursorFn)m.count&&v.cursorFn(m),i0(T4);v.resolve(m)}function lH(){v.parsing=!1}function J_(){!m.statement&&(m.statement=v.statement),m.columns=v.statement.columns}function iH(F){let L=F.readUInt16BE(5);for(let l=0;l<L;++l)!v.statement.types[l]&&(v.statement.types[l]=F.readUInt32BE(7+l*4));v.prepare&&(Q1[v.signature]=v.statement),v.describeFirst&&!v.onlyDescribe&&(i0(b6(v)),v.describeFirst=!1)}function oH(F){if(m.command)S1=S1||[m],S1.push(m=new d4),m.count=null,v.statement.columns=null;let L=F.readUInt16BE(5),l=7,W0;v.statement.columns=Array(L);for(let q0=0;q0<L;++q0){W0=l;while(F[l++]!==0);let s0=F.readUInt32BE(l),Z1=F.readUInt16BE(l+4),F4=F.readUInt32BE(l+6);v.statement.columns[q0]={name:D.column.from?D.column.from(F.toString("utf8",W0,l-1)):F.toString("utf8",W0,l-1),parser:O[F4],table:s0,number:Z1,type:F4},l+=18}if(m.statement=v.statement,v.onlyDescribe)return v.resolve(v.statement),i0(T4)}async function nH(F,L=F.readUInt32BE(5)){(L===3?rH:L===5?sH:L===10?aH:L===11?tH:L===12?eH:L!==0?RJ:I8)(F,L)}async function rH(){let F=await QZ();i0(c().p().str(F).z(1).end())}async function sH(F){let L="md5"+await DH(Buffer.concat([Buffer.from(await DH(await QZ()+J)),F.subarray(9)]));i0(c().p().str(L).z(1).end())}async function aH(){m1=(await j6.randomBytes(18)).toString("base64"),c().p().str("SCRAM-SHA-256"+c.N);let F=c.i;i0(c.inc(4).str("n,,n=*,r="+m1).i32(c.i-F-4,F).end())}async function tH(F){let L=F.toString("utf8",9).split(",").reduce((Z1,F4)=>(Z1[F4[0]]=F4.slice(2),Z1),{}),l=await j6.pbkdf2Sync(await QZ(),Buffer.from(L.s,"base64"),parseInt(L.i),32,"sha256"),W0=await nY(l,"Client Key"),q0="n=*,r="+m1+",r="+L.r+",s="+L.s+",i="+L.i+",c=biws,r="+L.r;T0=(await nY(await nY(l,"Server Key"),q0)).toString("base64");let s0="c=biws,r="+L.r+",p="+tU(W0,Buffer.from(await nY(await aU(W0),q0))).toString("base64");i0(c().p().str(s0).end())}function eH(F){if(F.toString("utf8",9).split(c.N,1)[0].slice(2)===T0)return;u1(f0.generic("SASL_SIGNATURE_MISMATCH","The server did not return the correct signature")),C.destroy()}function QZ(){return Promise.resolve(typeof Y.pass==="function"?Y.pass():Y.pass)}function YJ(){if(m.statement=v.statement,m.statement.columns=[],v.onlyDescribe)return v.resolve(v.statement),i0(T4)}function ZJ(F){q.pid=F.readUInt32BE(5),q.secret=F.readUInt32BE(9)}async function XJ(){U0=!1,(await new P1([`
58
+ ${D.trace}`:`No previous disposal trace for ${G} was found.`),X}let H=z0(Z),Q=W.molecules.get(H);if(!Q){let D=Y.disposalTraces.buffer.find((V)=>V?.key===H);return Y.logger.error("\u274C","molecule",X,"claim failed:",`Could not allocate to ${H} in store "${Y.config.name}".`,D?`
59
+ ${H} was most recently disposed
60
+ ${D.trace}`:`No previous disposal trace for ${H} was found.`),X}let J=Y.moleculeGraph.getRelationEntries({downstreamMoleculeKey:$.stringKey}).filter(([,{source:D}])=>D!==G).map(([D])=>G1(D));if(_)W.moleculeGraph.delete(G);W.moleculeGraph.set({upstreamMoleculeKey:Q.stringKey,downstreamMoleculeKey:$.stringKey},{source:Q.stringKey});let z={type:"molecule_transfer",key:$.key,from:J,to:[Q.key]};if(o0(W)&&W.transactionMeta.phase==="building")W.transactionMeta.update.updates.push(z);return X}function pU(Y,Z,X){switch(Z){case"newValue":y9(Y,X);break;case"oldValue":M8(X,Y.token);break}}function mU(Y,Z,X){switch(Z){case"newValue":M8(X,Y.token);break;case"oldValue":if(y9(Y,X),Y.subType==="atom")X.valueMap.set(Y.token.key,Y.value);break}}function y9(Y,Z){let{family:X}=Y.token;if(X){let _=Z.families.get(X.key);if(_)$0(Z,_,G1(X.subKey))}}function uU(Y,Z,X){switch(Z){case"newValue":D8(X,Y.provenance,Y.key);break;case"oldValue":L8(X,Y.key);break}}function dU(Y,Z,X){switch(Z){case"newValue":L8(X,Y.key);break;case"oldValue":{let _=Y.provenance.map(G1);D8(X,_,Y.key);for(let[G,W]of Y.values){let $=X.families.get(G);if($){$0(X,$,Y.key);let H=`${G}(${z0(Y.key)})`;X.valueMap.set(H,W)}}}break}}function cU(Y,Z,X){switch(Z){case"newValue":{let _=Y.to.length===1?Y.to[0]:Y.to;J2(X,_,Y.key,"exclusive")}break;case"oldValue":{let _=Y.from.length===1?Y.from[0]:Y.from;J2(X,_,Y.key,"exclusive")}break}}function p9(Y,Z,X){let _=Y==="newValue"?Z.updates:[...Z.updates].reverse();for(let G of _)switch(G.type){case"atom_update":case"selector_update":gU(Y,G,X);break;case"state_creation":pU(G,Y,X);break;case"state_disposal":mU(G,Y,X);break;case"molecule_creation":uU(G,Y,X);break;case"molecule_disposal":dU(G,Y,X);break;case"molecule_transfer":cU(G,Y,X);break;case"transaction_update":p9(Y,G,X);break}}function m9(Y,Z){return Y.transactionMeta.actionContinuities.getRelatedKey(Z)}function lU(Y,Z){return Y.transactionMeta.epoch.get(Z)}function iU(Y,Z){if(!R4(Y))return;let _=m9(Y,Z);if(_===void 0)return;return lU(Y,_)}function oU(Y,Z,X){if(!R4(Y))return;let G=m9(Y,Z);if(G!==void 0)Y.transactionMeta.epoch.set(G,X)}var nU=(Y,Z)=>{let X=i(Z),{parent:_}=X;if(_===null||!o0(X)||X.transactionMeta?.phase!=="building"){Z.logger.warn("\uD83D\uDC1E","transaction","???","applyTransaction called outside of a transaction. This is probably a bug in AtomIO.");return}X.transactionMeta.phase="applying",X.transactionMeta.update.output=Y,_.child=null,_.on.transactionApplying.next(X.transactionMeta);let{updates:G}=X.transactionMeta.update;if(Z.logger.info("\uD83D\uDEC4","transaction",X.transactionMeta.update.key,`Applying transaction with ${G.length} updates:`,G),p9("newValue",X.transactionMeta.update,_),R4(_))oU(_,X.transactionMeta.update.key,X.transactionMeta.update.epoch),h0(Z,{key:X.transactionMeta.update.key,type:"transaction"})?.subject.next(X.transactionMeta.update),Z.logger.info("\uD83D\uDEEC","transaction",X.transactionMeta.update.key,"Finished applying transaction.");else if(o0(_))_.transactionMeta.update.updates.push(X.transactionMeta.update);_.on.transactionApplying.next(null)};function rU(Y){return{store:Y}}var i1=class extends Map{deleted=new Set;source;constructor(Y){super();this.source=Y}get(Y){if(super.has(Y))return super.get(Y);if(!this.deleted.has(Y)&&this.source.has(Y))return this.source.get(Y);return}set(Y,Z){return this.deleted.delete(Y),super.set(Y,Z)}hasOwn(Y){return super.has(Y)}has(Y){return!this.deleted.has(Y)&&(super.has(Y)||this.source.has(Y))}delete(Y){return this.deleted.add(Y),super.delete(Y)}},sU=(Y,Z,X,_)=>{let G=i(Y),W={parent:G,child:null,on:G.on,loggers:G.loggers,logger:G.logger,config:G.config,atoms:new i1(G.atoms),atomsThatAreDefault:new Set(G.atomsThatAreDefault),families:new i1(G.families),joins:new i1(G.joins),operation:{open:!1},readonlySelectors:new i1(G.readonlySelectors),timelines:new i1(G.timelines),timelineTopics:new W1(G.timelineTopics.toJSON()),trackers:new Map,transactions:new i1(G.transactions),selectorAtoms:new W1(G.selectorAtoms.toJSON()),selectorGraph:new W1(G.selectorGraph.toJSON(),{makeContentKey:(...J)=>J.sort().join(":")}),writableSelectors:new i1(G.writableSelectors),valueMap:new i1(G.valueMap),defaults:G.defaults,disposalTraces:Y.disposalTraces.copy(),molecules:new i1(G.molecules),moleculeGraph:new W1(G.moleculeGraph.toJSON(),{makeContentKey:G.moleculeGraph.makeContentKey}),moleculeData:new W1(G.moleculeData.toJSON(),{makeContentKey:G.moleculeData.makeContentKey}),moleculeJoins:new W1(G.moleculeJoins.toJSON(),{makeContentKey:G.moleculeJoins.makeContentKey}),miscResources:new i1(G.miscResources)},$=iU(Y,Z),H={phase:"building",update:{type:"transaction_update",key:Z,id:_,epoch:$===void 0?NaN:$+1,updates:[],params:X,output:void 0},toolkit:{get:(...J)=>k1(Q,...J),set:(...J)=>{R1(Q,...J)},reset:(...J)=>{E8(Q,...J)},run:(J,z=SZ())=>vZ(Q,J,z),find:(...J)=>$0(Y,...J),json:(J)=>k4(Q,J),dispose:(...J)=>{M8(Q,...J)},env:()=>rU(Q)}},Q=Object.assign(W,{transactionMeta:H});return G.child=Q,Y.logger.info("\uD83D\uDEEB","transaction",Z,"Building transaction with params:",X),Q};function xZ(Y,Z){let{key:X}=Z,_=Y.transactions.has(X),G={key:X,type:"transaction",run:(H,Q)=>{let J=sU(Y,X,H,Q);try{let z=i(Y),{toolkit:O}=J.transactionMeta,D=Z.do(O,...H);return nU(D,z),D}catch(z){throw kU(W),Y.logger.warn("\uD83D\uDCA5","transaction",X,"caught:",z),z}},install:(H)=>xZ(H,Z),subject:new H0},W=i(Y);W.transactions.set(X,G);let $=G4(G);if(!_)Y.on.transactionCreation.next($);return $}var dZ=(Y,Z,X)=>{let _=i(Y),G=new H0,W=new Set,{key:$,const:H}=Z,Q="writable_held_selector",J=w6(_,"writable_held_selector",$,W),{find:z,get:O,json:D}=J,V={find:z,get:O,json:D},R=(f=Z.get,h=i(Y))=>{let I=h.selectorGraph.getRelationEntries({downstreamSelectorKey:$});for(let[N,{source:q}]of I)if(q!==$)h.selectorGraph.delete(N,$);return h.selectorAtoms.delete($),f(V,H),W4(h,$,H,G),Y.logger.info("\u2728","writable_held_selector",$,"=",H),W.clear(),H},g={...Z,type:"writable_held_selector",subject:G,install:(f)=>dZ(f,Z,X),get:R,set:(f)=>{let h=i(Y),I=R(Z.get,h),N=yZ(f)(I);if(Y.logger.info("\uD83D\uDCDD","writable_held_selector",$,"set (",I,"->",N,")"),W4(h,$,N,G),z2(h,$),R4(h))G.next({newValue:N,oldValue:I});Z.set(J,N)},...X&&{family:X}};_.writableSelectors.set($,g);let b={key:$,type:"writable_held_selector"};if(X)b.family=X;return b},cZ=(Y,Z,X)=>{let _=i(Y),G=new H0,W=new Set,$=Z.key,H="writable_pure_selector",Q=w6(_,"writable_pure_selector",$,W),{find:J,get:z,json:O}=Q,D={find:J,get:z,json:O},V=(f=Z.get,h=i(Y))=>{let I=h.selectorGraph.getRelationEntries({downstreamSelectorKey:$});for(let[K,{source:p}]of I)if(p!==$)h.selectorGraph.delete(K,$);h.selectorAtoms.delete($);let N=f(D),q=W4(h,$,N,G);return Y.logger.info("\u2728","writable_pure_selector",$,"=",q),W.clear(),N},A={...Z,type:"writable_pure_selector",subject:G,install:(f)=>cZ(f,Z,X),get:V,set:(f)=>{let h=i(Y),I=V(Z.get,h),N=yZ(f)(I);if(Y.logger.info("\uD83D\uDCDD","writable_pure_selector",$,"set (",I,"->",N,")"),W4(h,Z.key,N,G),z2(h,Z.key),R4(h))G.next({newValue:N,oldValue:I});Z.set(Q,N)},...X&&{family:X}};_.writableSelectors.set($,A);let g=V();Y.logger.info("\u2728",A.type,A.key,"=",g);let b={key:$,type:"writable_pure_selector"};if(X)b.family=X;return b};function qZ(Y,Z){let X="set"in Z,_="const"in Z;if(_&&X){let W=dZ(Y,Z,void 0);return Y.on.selectorCreation.next(W),W}if(_){let W=pZ(Y,Z,void 0);return Y.on.selectorCreation.next(W),W}if(X){let W=cZ(Y,Z,void 0);return Y.on.selectorCreation.next(W),W}let G=mZ(Y,Z,void 0);return Y.on.selectorCreation.next(G),G}function aU(Y,Z){let X=i(Y),{key:_,type:G}=Z,W=h0(X,Z);if(!W.family)Y.logger.error("\u274C",G,_,"Standalone selectors cannot be disposed.");else{if(X.molecules.get(W.family.subKey))X.moleculeData.delete(W.family.subKey,W.family.key);let H;switch(Z.type){case"writable_held_selector":X.writableSelectors.delete(_),H={key:W.family.key,type:"writable_held_selector_family"},h0(Y,H).subject.next({type:"state_disposal",subType:"selector",token:Z});break;case"writable_pure_selector":X.writableSelectors.delete(_),H={key:W.family.key,type:"writable_pure_selector_family"},h0(Y,H).subject.next({type:"state_disposal",subType:"selector",token:Z});break;case"readonly_held_selector":X.readonlySelectors.delete(_),H={key:W.family.key,type:"readonly_held_selector_family"},h0(Y,H).subject.next({type:"state_disposal",subType:"selector",token:Z});break;case"readonly_pure_selector":X.readonlySelectors.delete(_),H={key:W.family.key,type:"readonly_pure_selector_family"},h0(Y,H).subject.next({type:"state_disposal",subType:"selector",token:Z});break}if(X.valueMap.delete(_),X.selectorAtoms.delete(_),X.selectorGraph.delete(_),Y.logger.info("\uD83D\uDD25",Z.type,_,"deleted"),o0(X)&&X.transactionMeta.phase==="building")X.transactionMeta.update.updates.push({type:"state_disposal",subType:"selector",token:Z});else Y.on.selectorDisposal.next(Z)}}function f4(Y,Z,X){let _=Z.key,G="readonly_pure_selector_family",W={key:_,type:"readonly_pure_selector_family"},$=Y.families.get(_);if($)Y.logger.error("\u2757","readonly_pure_selector_family",_,`Overwriting an existing ${b4($)} "${$.key}" in store "${Y.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);let H=new H0,J=Object.assign((z)=>{let O=z0(z),D={key:_,subKey:O},V=`${_}(${O})`,R=i(Y),A=mZ(R,{key:V,get:Z.get(z)},D);return H.next({type:"state_creation",token:A}),A},W,{internalRoles:X,subject:H,install:(z)=>f4(z,Z),default:(z)=>{return Z.get(z)({get:(...D)=>k1(Y,...D),find:(...D)=>$0(Y,...D),json:(D)=>k4(Y,D)})}});return Y.families.set(_,J),W}function V8(Y,Z,X){let _={key:Z.key,type:"atom_family"},G=Y.families.get(Z.key);if(G)Y.logger.error("\u2757","atom_family",Z.key,`Overwriting an existing ${b4(G)} "${G.key}" in store "${Y.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);let W=new H0,H=Object.assign((Q)=>{let J=z0(Q),z={key:Z.key,subKey:J},O=`${Z.key}(${J})`,D=i(Y),V=Z.default,R={key:O,default:V instanceof Function?()=>V(Q):V};if(Z.effects)R.effects=Z.effects(Q);let A=h4(D,R,z);return W.next({type:"state_creation",token:A}),A},_,{subject:W,install:(Q)=>V8(Q,Z),internalRoles:X});return Y.families.set(Z.key,H),Y.defaults.set(Z.key,Z.default),_}function u9(Y,Z,X){let _=Z.key,G="readonly_held_selector_family",W={key:_,type:"readonly_held_selector_family"},$=Y.families.get(_);if($)Y.logger.error("\u2757","readonly_held_selector_family",_,`Overwriting an existing ${b4($)} "${$.key}" in store "${Y.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);let H=new H0,J=Object.assign((z)=>{let O=z0(z),D={key:_,subKey:O},V=`${_}(${O})`,R=i(Y),A=pZ(R,{key:V,const:Z.const(z),get:Z.get(z)},D);return H.next({type:"state_creation",token:A}),A},W,{internalRoles:X,subject:H,install:(z)=>u9(z,Z),default:Z.const});return Y.families.set(_,J),W}function d9(Y,Z,X){let _=Z.key,G="writable_held_selector_family",W={key:_,type:"writable_held_selector_family"},$=Y.families.get(_);if($)Y.logger.error("\u2757","writable_held_selector_family",_,`Overwriting an existing ${b4($)} "${$.key}" in store "${Y.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);let H=new H0,J=Object.assign((z)=>{let O=z0(z),D={key:_,subKey:O},V=`${_}(${O})`,R=i(Y),A=dZ(R,{key:V,const:Z.const(z),get:Z.get(z),set:Z.set(z)},D);return H.next({type:"state_creation",token:A}),A},W,{internalRoles:X,subject:H,install:(z)=>d9(z,Z),default:Z.const});return Y.families.set(_,J),W}function O6(Y,Z,X){let _=Z.key,G="writable_pure_selector_family",W={key:_,type:"writable_pure_selector_family"},$=Y.families.get(_);if($)Y.logger.error("\u2757","writable_pure_selector_family",_,`Overwriting an existing ${b4($)} "${$.key}" in store "${Y.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);let H=new H0,J=Object.assign((z)=>{let O=z0(z),D={key:_,subKey:O},V=`${_}(${O})`,R=i(Y),A=cZ(R,{key:V,get:Z.get(z),set:Z.set(z)},D);return H.next({type:"state_creation",token:A}),A},W,{internalRoles:X,subject:H,install:(z)=>O6(z,Z),default:(z)=>{return Z.get(z)({get:(...D)=>k1(Y,...D),find:(...D)=>$0(Y,...D),json:(D)=>k4(Y,D)})}});return Y.families.set(_,J),W}function hZ(Y,Z){let X="set"in Z,_="const"in Z;if(_&&X)return d9(Y,Z,void 0);if(_)return u9(Y,Z,void 0);if(X)return O6(Y,Z);return f4(Y,Z)}function tU(Y,Z,X){let _=Y.families.get(Z.key);if(_===void 0)throw new uZ(Z,Y);let G=_(X),W=i(Y);if(G.family){if(R4(W))switch(G.type){case"atom":case"mutable_atom":Y.on.atomCreation.next(G);break;case"writable_pure_selector":case"readonly_pure_selector":case"writable_held_selector":case"readonly_held_selector":Y.on.selectorCreation.next(G);break}else if(o0(W)&&W.on.transactionApplying.state===null)W.transactionMeta.update.updates.push({type:"state_creation",token:G})}return G}function eU(Y,Z,X){let _=z0(X),G=`${Z.key}(${_})`,W=i(Y),$;switch(Z.type){case"atom_family":case"mutable_atom_family":$=W.atoms.get(G);break;case"writable_held_selector_family":case"writable_pure_selector_family":$=W.writableSelectors.get(G);break;case"readonly_held_selector_family":case"readonly_pure_selector_family":$=W.readonlySelectors.get(G);break}if($)return G4($);return $}function $0(Y,Z,X){let _=eU(Y,Z,X);if(_)return _;let G=z0(X),W=Y.molecules.get(G);if(!W&&Y.config.lifespan==="immortal"){let $=TU(Z,X);return Y.logger.error("\u274C",$.type,$.key,`was not found in store "${Y.config.name}"; returned a counterfeit token.`),$}if(_=tU(Y,Z,X),W)i(Y).moleculeData.set(G,Z.key);return _}function M8(Y,...Z){let X;if(Z.length===1)X=Z[0];else{let _=Z[0],G=Z[1];X=$0(Y,_,G)}try{h0(Y,X)}catch(_){Y.logger.error("\u274C",X.type,X.key,`could not be disposed because it was not found in the store "${Y.config.name}".`);return}switch(X.type){case"atom":case"mutable_atom":l9(Y,X);break;case"writable_pure_selector":case"readonly_pure_selector":case"writable_held_selector":case"readonly_held_selector":aU(Y,X);break}}function k1(Y,...Z){let X,_,G;if(Z.length===1)X=Z[0];else _=Z[0],G=Z[1],X=$0(Y,_,G);if("counterfeit"in X&&"family"in X){_=Y.families.get(X.family.key);let W=X.family.subKey,$=Y.disposalTraces.buffer.find((H)=>H?.key===W);switch(Y.logger.error("\u274C",X.type,X.key,`could not be retrieved because it was not found in the store "${Y.config.name}".`,$?`This state was previously disposed:
61
+ ${$.trace}`:"No previous disposal trace was found."),_.type){case"atom_family":case"mutable_atom_family":return Y.defaults.get(_.key);case"readonly_pure_selector_family":case"writable_pure_selector_family":case"readonly_held_selector_family":case"writable_held_selector_family":{if(Y.defaults.has(_.key))return Y.defaults.get(X.family.key);let H=h0(Y,_).default(W);return Y.defaults.set(_.key,H),H}}}return U2(Y,h0(Y,X))}function A8(Y,Z,X,_){function G(O){if(Y.operation.open){let D=Y.on.operationClose.subscribe(`state subscription ${X}`,()=>{D(),_(O)})}else _(O)}let W=h0(Y,Z);Y.logger.info("\uD83D\uDC40",W.type,W.key,`Adding subscription "${X}"`);let $=W.type==="writable_pure_selector"||W.type==="readonly_pure_selector",H=new Map,Q=G;if($){U2(Y,W);for(let[O,D]of A6(Y,W.key))H.set(O,j9(Y,W,D));Q=function O(D){let V=A6(Y,W.key);for(let[R,A]of H)if(V.get(R))V.delete(R);else A(),H.delete(R);for(let[R,A]of V)H.set(R,j9(Y,W,A));G(D)}}let J=W.subject.subscribe(X,Q);return()=>{Y.logger.info("\uD83D\uDE48",W.type,W.key,`Removing subscription "${X}"`),J();for(let O of H.values())O()}}var c9=(Y,Z,X,_)=>{let G=h0(Y,Z);Y.logger.info("\uD83D\uDC40","timeline",Z.key,`Adding subscription "${X}"`);let W=G.subject.subscribe(X,_);return()=>{Y.logger.info("\uD83D\uDE48","timeline",Z.key,`Removing subscription "${X}" from timeline`),W()}};var lZ=class{initializeState(Y,Z){let X=`*${Y.key}`;Z.atoms.delete(X),Z.valueMap.delete(X);let _=Y.family?{key:`*${Y.family.key}`,subKey:Y.family.subKey}:void 0,G=h4(Z,{key:X,default:null},_);if(Z.parent?.valueMap.has(X)){let W=Z.parent.valueMap.get(X);Z.valueMap.set(X,W)}return G}unsubscribeFromInnerValue;unsubscribeFromState;observeCore(Y,Z,X){let _=`tracker:${X.config.name}:${o0(X)?X.transactionMeta.update.key:"main"}:${Y.key}`,G=k1(X,Y);this.unsubscribeFromInnerValue=G.subscribe(_,(W)=>{R1(X,Z,W)}),this.unsubscribeFromState=A8(X,Y,_,(W)=>{if(W.newValue!==W.oldValue)this.unsubscribeFromInnerValue(),this.unsubscribeFromInnerValue=W.newValue.subscribe(_,($)=>{R1(X,Z,$)})})}updateCore(Y,Z,X){let _=`tracker:${X.config.name}:${o0(X)?X.transactionMeta.update.key:"main"}:${Y.key}`;A8(X,Z,_,({newValue:G,oldValue:W})=>{let $=X.timelineTopics.getRelatedKey(Z.key);if($){if(X.timelines.get($)?.timeTraveling){let J=c9(X,{key:$,type:"timeline"},_,(z)=>{J(),R1(X,Y,(O)=>{if(z==="redo"&&G)O.do(G);else if(z==="undo"&&W)O.undo(W);return O})});return}}let H=X.on.operationClose.subscribe(_,()=>{H();let Q=k1(X,Y),J=G===null?-1:Q.getUpdateNumber(G),z=J-Q.cacheUpdateNumber;if(G&&z===1)R1(X,Y,(O)=>(O.do(G),O));else X.logger.info("\u274C","mutable_atom",Y.key,`could not be updated. Expected update number ${Q.cacheUpdateNumber+1}, but got ${J}`)})})}mutableState;latestUpdateState;[Symbol.dispose];constructor(Y,Z){this.mutableState=Y;let X=i(Z);this.latestUpdateState=this.initializeState(Y,X),this.observeCore(Y,this.latestUpdateState,X),this.updateCore(Y,this.latestUpdateState,X),X.trackers.set(Y.key,this),this[Symbol.dispose]=()=>{this.unsubscribeFromInnerValue(),this.unsubscribeFromState(),X.trackers.delete(Y.key)}}};function L6(Y,Z,X){Y.logger.info("\uD83D\uDD28","atom",Z.key,`creating in store "${Y.config.name}"`);let _=i(Y),{key:G}=Z,W=_.atoms.get(G),$="mutable_atom";if(W&&W.type===$)return Y.logger.error("\u274C",$,G,"Tried to create atom, but it already exists in the store."),G4(W);let H=new H0,Q={...Z,type:$,install:(z)=>{return z.logger.info("\uD83D\uDEE0\uFE0F","atom",G,`installing in store "${z.config.name}"`),L6(z,Z,X)},subject:H};if(X)Q.family=X;_.atoms.set(Q.key,Q);let J=G4(Q);if(Z.effects){let z=0,O=[];for(let D of Z.effects){let V=D({resetSelf:()=>{E8(Y,J)},setSelf:(R)=>{R1(Y,J,R)},onSet:(R)=>A8(Y,J,`effect[${z}]`,R)});if(V)O.push(V);++z}Q.cleanup=()=>{for(let D of O)D()}}if(new lZ(J,Y),!X)V9(J,Z,Y);return Y.on.atomCreation.next(J),J}var ZF=class{trackers=new Map;latestUpdateAtoms;mutableAtoms;constructor(Y,Z){let X=V8(Z,{key:`*${Y.key}`,default:null},["mutable","updates"]);this.latestUpdateAtoms=h0(Z,X),this.mutableAtoms=Y,this.mutableAtoms.subject.subscribe(`store=${Z.config.name}::tracker-atom-family`,(_)=>{let{type:G,token:W}=_;if(W.family){let $=G1(W.family.subKey);switch(G){case"state_creation":this.trackers.set($,new lZ(W,Z));break;case"state_disposal":{let H=this.trackers.get($);if(H)H[Symbol.dispose](),this.trackers.delete($)}break}}})}};function fZ(Y,Z,X){let _={key:Z.key,type:"mutable_atom_family"},G=Y.families.get(Z.key);if(G)Y.logger.error("\u2757","mutable_atom_family",Z.key,`Overwriting an existing ${b4(G)} "${G.key}" in store "${Y.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);let W=new H0,H=Object.assign((Q)=>{let J=z0(Q),z={key:Z.key,subKey:J},O=`${Z.key}(${J})`,D=i(Y),V={key:O,default:()=>Z.default(Q),toJson:Z.toJson,fromJson:Z.fromJson};if(Z.effects)V.effects=Z.effects(Q);let R=L6(D,V,z);return W.next({type:"state_creation",token:R}),R},_,{subject:W,install:(Q)=>fZ(Q,Z),toJson:Z.toJson,fromJson:Z.fromJson,internalRoles:X});return Y.families.set(Z.key,H),M9(Y,H,Z),new ZF(H,Y),_}var v9=(Y,Z)=>{let X=i(Z),_=`${Y.key}:JSON`;return X.families.get(_)},k4=(Y,Z)=>{if(Z.family){let _=i(Y),W={key:`${Z.family.key}:JSON`,type:"writable_pure_selector_family"},$=h0(_,W),H=JSON.parse(Z.family.subKey);return $0(Y,$,H)}return{type:"writable_pure_selector",key:`${Z.key}:JSON`}};var iZ=(Y)=>{let X={type:"atom",key:`*${Y.key}`};if(Y.family)X.family={key:`*${Y.family.key}`,subKey:Y.family.subKey};return X};function XF(Y){return typeof Y==="object"&&Y!==null&&"do"in Y&&"undo"in Y&&"subscribe"in Y}var B9=class{parent=null;child=null;valueMap=new Map;defaults=new Map;atoms=new Map;writableSelectors=new Map;readonlySelectors=new Map;atomsThatAreDefault=new Set;selectorAtoms=new W1({between:["selectorKey","atomKey"],cardinality:"n:n"});selectorGraph=new W1({between:["upstreamSelectorKey","downstreamSelectorKey"],cardinality:"n:n"},{makeContentKey:(...Y)=>Y.sort().join(":")});trackers=new Map;families=new Map;joins=new Map;transactions=new Map;transactionMeta={epoch:new Map,actionContinuities:new W1({between:["continuity","action"],cardinality:"1:n"})};timelines=new Map;timelineTopics=new W1({between:["timelineKey","topicKey"],cardinality:"1:n"});disposalTraces=new BU(100);molecules=new Map;moleculeJoins=new W1({between:["moleculeKey","joinKey"],cardinality:"n:n"},{makeContentKey:(...Y)=>Y.sort().join(":")});moleculeGraph=new W1({between:["upstreamMoleculeKey","downstreamMoleculeKey"],cardinality:"n:n"},{makeContentKey:(...Y)=>Y.sort().join(":")});moleculeData=new W1({between:["moleculeKey","stateFamilyKey"],cardinality:"n:n"},{makeContentKey:(...Y)=>Y.sort().join(":")});miscResources=new Map;on={atomCreation:new H0,atomDisposal:new H0,selectorCreation:new H0,selectorDisposal:new H0,timelineCreation:new H0,transactionCreation:new H0,transactionApplying:new KU(null),operationClose:new H0,moleculeCreation:new H0,moleculeDisposal:new H0};operation={open:!1};config={name:"IMPLICIT_STORE",lifespan:"ephemeral"};loggers=[new w9("warn",(Y,Z,X)=>!w8(X))];logger={error:(...Y)=>{for(let Z of this.loggers)Z.error(...Y)},info:(...Y)=>{for(let Z of this.loggers)Z.info(...Y)},warn:(...Y)=>{for(let Z of this.loggers)Z.warn(...Y)}};constructor(Y,Z=null){if(this.config={...Z?.config,...Y},Z!==null){if(this.operation={...Z?.operation},R4(Z))this.transactionMeta={epoch:new Map(Z?.transactionMeta.epoch),actionContinuities:new W1(Z?.transactionMeta.actionContinuities.toJSON())};for(let[,_]of Z.families){if(_.internalRoles?.includes("mutable")||_.internalRoles?.includes("join"))continue;_.install(this)}let X=new Set;for(let[,_]of Z.atoms){if(X.has(_.key))continue;if(_.install(this),_.type==="mutable_atom"){let G=k4(Z,_),W=iZ(_);X.add(G.key),X.add(W.key)}}for(let[,_]of Z.readonlySelectors)_.install(this);for(let[,_]of Z.writableSelectors){if(X.has(_.key))continue;_.install(this)}for(let[,_]of Z.transactions)_.install(this);for(let[,_]of Z.timelines)_.install(this)}}},x0={get STORE(){return globalThis.ATOM_IO_IMPLICIT_STORE??=new B9({name:"IMPLICIT_STORE",lifespan:"ephemeral"}),globalThis.ATOM_IO_IMPLICIT_STORE}};function h0(Y,Z){let X,_=Y;while(_!==null){switch(Z.type){case"atom":case"mutable_atom":X=_.atoms.get(Z.key);break;case"writable_pure_selector":case"writable_held_selector":X=_.writableSelectors.get(Z.key);break;case"readonly_pure_selector":case"readonly_held_selector":X=_.readonlySelectors.get(Z.key);break;case"atom_family":case"mutable_atom_family":case"writable_pure_selector_family":case"readonly_pure_selector_family":case"writable_held_selector_family":case"readonly_held_selector_family":X=_.families.get(Z.key);break;case"timeline":X=_.timelines.get(Z.key);break;case"transaction":X=_.transactions.get(Z.key);break}if(X)return X;_=_.child}throw new uZ(Z,Y)}function h4(Y,Z,X){let{key:G}=Z;Y.logger.info("\uD83D\uDD28","atom",G,`creating in store "${Y.config.name}"`);let W=i(Y),$=W.atoms.get(G);if($&&$.type==="atom")return Y.logger.error("\u274C","atom",G,"Tried to create atom, but it already exists in the store."),G4($);let H=new H0,Q={...Z,type:"atom",install:(z)=>{return z.logger.info("\uD83D\uDEE0\uFE0F","atom",G,`installing in store "${z.config.name}"`),h4(z,Z,X)},subject:H};if(X)Q.family=X;W.atoms.set(G,Q);let J=G4(Q);if(Z.effects){let z=0,O=[];for(let D of Z.effects){let V=D({resetSelf:()=>{E8(Y,J)},setSelf:(R)=>{R1(Y,J,R)},onSet:(R)=>A8(Y,J,`effect[${z}]`,R)});if(V)O.push(V);++z}Q.cleanup=()=>{for(let D of O)D()}}return Y.on.atomCreation.next(J),J}function l9(Y,Z){let X=i(Y),{key:_,family:G}=Z,W=h0(X,Z);if(!G)Y.logger.error("\u274C","atom",_,"Standalone atoms cannot be disposed.");else{W.cleanup?.();let $=Y.valueMap.get(W.key),H=h0(Y,{key:G.key,type:"atom_family"}),Q={type:"state_disposal",subType:"atom",token:Z,value:$};H.subject.next(Q);let J=o0(X);if(X.atoms.delete(_),X.valueMap.delete(_),X.selectorAtoms.delete(_),X.atomsThatAreDefault.delete(_),Y.timelineTopics.delete(_),Z.type==="mutable_atom"){let z=iZ(Z);l9(Y,z),Y.trackers.delete(_)}if(Y.logger.info("\uD83D\uDD25","atom",_,"deleted"),J&&X.transactionMeta.phase==="building"){let z=X.transactionMeta.update.updates.at(-1);if(!(z?.type==="molecule_disposal"&&z.values.some(([V])=>V===W.family?.key)))X.transactionMeta.update.updates.push(Q)}else Y.on.atomDisposal.next(Z)}}function C9(Y,Z,X){return Y.joins.set(Z.key,new oZ(Z,X,Y)),{key:Z.key,type:"join",a:Z.between[0],b:Z.between[1],cardinality:Z.cardinality}}var oZ=class{toolkit;options;defaultContent;molecules=new Map;relations;states;core;transact(Y,Z){let X=this.toolkit;this.toolkit=Y,Z(this),this.toolkit=X}store;realm;[Symbol.dispose](){}constructor(Y,Z,X=x0.STORE){this.store=X,this.realm=new R9(X),this.options=Y,this.defaultContent=Z,this.store.miscResources.set(`join:${Y.key}`,this),this.realm.allocate("root",Y.key),this.toolkit={get:(...I)=>k1(X,...I),set:(...I)=>{R1(X,...I)},find:(...I)=>$0(X,...I),json:(I)=>k4(X,I)};let _=Y.between[0],G=Y.between[1],W=fZ(X,{key:`${Y.key}/relatedKeys`,default:()=>new D1,fromJson:(I)=>D1.fromJSON(I),toJson:(I)=>I.toJSON()},["join","relations"]);this.core={relatedKeysAtoms:W};let $=({get:I},N)=>I(W,N),H=({set:I},N,q)=>{if(!this.store.molecules.has(z0(N)))this.realm.allocate(Y.key,N);I(W,N,(K)=>K.add(q)),I(W,q,(K)=>K.add(N))},Q=({set:I},N,q)=>{I(W,N,(K)=>{return K.delete(q),K}),I(W,q,(K)=>{return K.delete(N),K})},J=(I,N,q)=>{let{find:K,get:p,set:s}=I,C=K(W,N),t=p(C);for(let m of t){if(q.includes(m))continue;s(W,m,(F0)=>{return F0.delete(N),F0})}s(C,(m)=>{return m.transaction((e)=>{e.clear();for(let F0 of q){let b0=$(I,F0),J1=b0.has(N);if(this.relations.cardinality==="1:n"){let r1=[];for(let T of b0){if(T===N)continue;let u=$(I,T);if(u.delete(F0),u.size===0)r1.push(T)}if(!J1&&b0.size>0)b0.clear();for(let T of r1){let u=[F0,T].sort(),G0=`"${u[0]}:${u[1]}"`;this.molecules.delete(G0)}}if(!J1)b0.add(N);e.add(F0)}return!0}),m})},z=(I,N,q)=>{let{set:K}=I;K(W,N,(p)=>{return p.transaction((s)=>{for(let C of q)s.add(C);return!0}),p});for(let p of q)K(W,p,(s)=>{return s.add(N),s});return!0},O=(I,N,q)=>{let K=$(I,N);return q?K.has(q):K.size>0},D={getRelatedKeys:(I)=>$(this.toolkit,I),addRelation:(I,N)=>{this.store.moleculeJoins.set(I,Y.key),this.store.moleculeJoins.set(N,Y.key),H(this.toolkit,I,N)},deleteRelation:(I,N)=>{Q(this.toolkit,I,N)},replaceRelationsSafely:(I,N)=>{J(this.toolkit,I,N)},replaceRelationsUnsafely:(I,N)=>{z(this.toolkit,I,N)},has:(I,N)=>O(this.toolkit,I,N)},V,R;if(Z){R=V8(X,{key:`${Y.key}/content`,default:Z},["join","content"]);let I=({get:K},p)=>K(R,p),N=({set:K},p,s)=>{K(R,p,s)};V=Object.assign(D,{getContent:(K)=>{return I(this.toolkit,K)},setContent:(K,p)=>{N(this.toolkit,K,p)},deleteContent:(K)=>{this.realm.deallocate(K)}})}else V=D;let A=new W1(Y,{externalStore:V,isAType:Y.isAType,isBType:Y.isBType,makeContentKey:(...I)=>{let[N,q]=I,K=I.sort(),p=`${K[0]}:${K[1]}`,s=X.molecules.get(z0(N)),C=X.molecules.get(z0(q));if(!s)this.realm.allocate(Y.key,N);if(!C)this.realm.allocate(Y.key,q);return this.realm.allocate(N,p,"all"),this.realm.claim(q,p),this.store.moleculeJoins.set(p,Y.key),p}}),g=()=>f4(X,{key:`${Y.key}/singleRelatedKey`,get:(I)=>({get:N})=>{let q=N(W,I);for(let K of q)return K;return null}},["join","keys"]),b=()=>{return f4(X,{key:`${Y.key}/multipleRelatedKeys`,get:(I)=>({get:N})=>{let q=v9(W,X);return N(q,I).members}},["join","keys"])},f=()=>f4(X,{key:`${Y.key}/singleRelatedEntry`,get:(I)=>({get:N})=>{let q=N(W,I);for(let K of q){let p=A.isAType?.(I)?I:void 0,s=p===void 0?I:void 0;p??=K,s??=K;let C=A.makeContentKey(p,s),t=N(R,C);return[K,t]}return null}},["join","entries"]),h=()=>f4(X,{key:`${Y.key}/multipleRelatedEntries`,get:(I)=>({get:N})=>{let q=v9(W,X);return N(q,I).members.map((p)=>{let s=A.isAType?.(I)?I:void 0,C=s===void 0?I:void 0;s??=p,C??=p;let t=A.makeContentKey(s,C),m=N(R,t);return[p,m]})}},["join","entries"]);switch(Y.cardinality){case"1:1":{let I=g(),N=`${_}KeyOf${B0(G)}`,q=`${G}KeyOf${B0(_)}`,K={[N]:I,[q]:I},p;if(Z){let s=f(),C=`${_}EntryOf${B0(G)}`,t=`${G}EntryOf${B0(_)}`,m={[C]:s,[t]:s};p=Object.assign(K,m)}else p=K;this.relations=A,this.states=p;break}case"1:n":{let I=g(),N=b(),q=`${_}KeyOf${B0(G)}`,K=`${G}KeysOf${B0(_)}`,p={[q]:I,[K]:N},s;if(Z){let C=f(),t=h(),m=`${_}EntryOf${B0(G)}`,e=`${G}EntriesOf${B0(_)}`,F0={[m]:C,[e]:t};s=Object.assign(p,F0)}else s=p;this.relations=A,this.states=s;break}case"n:n":{let I=b(),N=`${_}KeysOf${B0(G)}`,q=`${G}KeysOf${B0(_)}`,K={[N]:I,[q]:I},p;if(Z){let s=h(),C=`${_}EntriesOf${B0(G)}`,t=`${G}EntriesOf${B0(_)}`,m={[C]:s,[t]:s};p=Object.assign(K,m)}else p=K;this.relations=A,this.states=p}}}};function nZ(Y,Z){let X=Z.joins.get(Y.key);if(X===void 0){let G=x0.STORE.joins.get(Y.key);if(G===void 0)throw new Error(`Join "${Y.key}" not found in store "${Z.config.name}"`);X=new oZ(G.options,G.defaultContent,Z),Z.joins.set(Y.key,X)}return X}function Q2(Y,Z,X){let _=nZ(Y,X),G=i(X);if(o0(G)){let{toolkit:W}=G.transactionMeta;_.transact(W,({relations:$})=>{Z($)})}else Z(_.relations)}function T9(Y,Z,X){let _=nZ(Y,X),G;switch(Y.cardinality){case"1:1":{let W=`${Y.a}KeyOf${B0(Y.b)}`,$=`${Y.b}KeyOf${B0(Y.a)}`;G={get[W](){let Q=_.states[W];return $0(X,Q,Z)},get[$](){let Q=_.states[$];return $0(X,Q,Z)}};let H=`${Y.a}EntryOf${B0(Y.b)}`;if(H in _.states){let Q=`${Y.b}EntryOf${B0(Y.a)}`;Object.assign(G,{get[H](){let J=_.states[H];return $0(X,J,Z)},get[Q](){let J=_.states[Q];return $0(X,J,Z)}})}break}case"1:n":{let W=`${Y.a}KeyOf${B0(Y.b)}`,$=`${Y.b}KeysOf${B0(Y.a)}`;G={get[W](){let Q=_.states[W];return $0(X,Q,Z)},get[$](){let Q=_.states[$];return $0(X,Q,Z)}};let H=`${Y.a}EntryOf${B0(Y.b)}`;if(H in _.states){let Q=`${Y.b}EntriesOf${B0(Y.a)}`;Object.assign(G,{get[H](){let J=_.states[H];return $0(X,J,Z)},get[Q](){let J=_.states[Q];return $0(X,J,Z)}})}break}case"n:n":{let W=`${Y.a}KeysOf${B0(Y.b)}`,$=`${Y.b}KeysOf${B0(Y.a)}`;G={get[W](){let Q=_.states[W];return $0(X,Q,Z)},get[$](){let Q=_.states[$];return $0(X,Q,Z)}};let H=`${Y.a}EntriesOf${B0(Y.b)}`;if(H in _.states){let Q=`${Y.b}EntriesOf${B0(Y.a)}`;Object.assign(G,{get[H](){let J=_.states[H];return $0(X,J,Z)},get[Q](){let J=_.states[Q];return $0(X,J,Z)}})}}}return G}function K9(Y,Z){return nZ(Y,Z).core.relatedKeysAtoms}function w8(Y){return Y.startsWith("\uD83D\uDD0D ")}var _F=(Y)=>{return h4(Y,{key:"\uD83D\uDD0D Atom Token Index",default:()=>{let Z=new Map;for(let[X,_]of Y.atoms){if(w8(X))continue;let G=G4(_);if(_.family){let W=Z.get(_.family.key);if(!W||!("familyMembers"in W))W={key:_.family.key,familyMembers:new Map},Z.set(_.family.key,W);W.familyMembers.set(_.family.subKey,G)}else Z.set(X,G)}return Z},effects:[({setSelf:Z})=>{Y.on.atomCreation.subscribe("introspection",(X)=>{if(w8(X.key))return;Z((_)=>{if(X.family){let{key:G,subKey:W}=X.family,$=_.get(G);if($===void 0||!("familyMembers"in $))$={key:G,familyMembers:new Map},_.set(G,$);$.familyMembers.set(W,X)}else _.set(X.key,X);return new Map(_)})}),Y.on.atomDisposal.subscribe("introspection",(X)=>{Z((_)=>{if(X.family){let{key:G,subKey:W}=X.family,$=_.get(G);if($&&"familyMembers"in $){if($.familyMembers.delete(W),$.familyMembers.size===0)_.delete(G)}}return new Map(_)})})}]},void 0)},GF=(Y)=>{return h4(Y,{key:"\uD83D\uDD0D Selector Token Index",default:()=>{let Z=new Map;for(let X of[Y.readonlySelectors,Y.writableSelectors])for(let[_,G]of X){if(w8(_))continue;let W=G4(G);if(G.family){let $=Z.get(G.family.key);if(!$||!("familyMembers"in $))$={key:G.family.key,familyMembers:new Map},Z.set(G.family.key,$);$.familyMembers.set(G.family.subKey,W)}else Z.set(_,W)}return Z},effects:[({setSelf:Z})=>{Y.on.selectorCreation.subscribe("introspection",(X)=>{if(w8(X.key))return;Z((_)=>{if(X.family){let{key:G,subKey:W}=X.family,$=_.get(G);if($===void 0||!("familyMembers"in $))$={key:G,familyMembers:new Map},_.set(G,$);$.familyMembers.set(W,X)}else _.set(X.key,X);return new Map(_)})}),Y.on.selectorDisposal.subscribe("introspection",(X)=>{Z((_)=>{if(X.family){let{key:G,subKey:W}=X.family,$=_.get(G);if($&&"familyMembers"in $){if($.familyMembers.delete(W),$.familyMembers.size===0)_.delete(G)}}else _.delete(X.key);return new Map(_)})})}]},void 0)};var rZ=class{supported;constructor(Y){this.supported=Y}refine(Y){for(let[Z,X]of Object.entries(this.supported))try{if(X(Y)===!0&&X!==Boolean)return{type:Z,data:Y}}catch(_){try{if(Y instanceof X)return{type:Z,data:Y}}catch(G){}}return null}},o9=new rZ({number:(Y)=>typeof Y==="number",string:(Y)=>typeof Y==="string",boolean:(Y)=>typeof Y==="boolean",null:(Y)=>Y===null});function n9(Y){if(!Y)return!1;return Object.getPrototypeOf(Y)===Object.prototype}var r9=new rZ({object:n9,array:(Y)=>Array.isArray(Y)}),WF=new rZ({...o9.supported,...r9.supported}),R6=(Y)=>{if(Y===void 0)return"undefined";let Z=WF.refine(Y);if(Z)return Z.type;return Object.getPrototypeOf(Y).constructor.name};var lB=class Y{store;auditorCreatedAt=performance.now();statesCreatedAt=new Map;atomIndex;selectorIndex;disposed=!1;unsubscribeFromAtomCreation;unsubscribeFromAtomDisposal;unsubscribeFromSelectorCreation;unsubscribeFromSelectorDisposal;constructor(Z=x0.STORE){this.store=Z,this.atomIndex=_F(this.store),this.selectorIndex=GF(this.store),this.unsubscribeFromAtomCreation=this.store.on.atomCreation.subscribe(`auditor-${this.auditorCreatedAt}`,({key:X})=>{this.statesCreatedAt.set(X,performance.now()-this.auditorCreatedAt)}),this.unsubscribeFromAtomDisposal=this.store.on.atomDisposal.subscribe(`auditor-${this.auditorCreatedAt}`,({key:X})=>{this.statesCreatedAt.delete(X)}),this.unsubscribeFromSelectorCreation=this.store.on.selectorCreation.subscribe(`auditor-${this.auditorCreatedAt}`,({key:X})=>{this.statesCreatedAt.set(X,performance.now()-this.auditorCreatedAt)}),this.unsubscribeFromSelectorDisposal=this.store.on.selectorDisposal.subscribe(`auditor-${this.auditorCreatedAt}`,({key:X})=>{this.statesCreatedAt.delete(X)})}static DEFAULT_LIST_RESOURCES_PARAM={atomFamilies:!0,selectorFamilies:!0};listResources(Z=Y.DEFAULT_LIST_RESOURCES_PARAM){if(this.disposed)throw new Error("This Auditor has been disposed");let X=PZ(this.atomIndex),_=PZ(this.selectorIndex),G=[...X.values()].filter((Q)=>("familyMembers"in Q)),W=[..._.values()].filter((Q)=>("familyMembers"in Q)),$=performance.now(),H=[];if(Z.atomFamilies)for(let Q of G){let J=Q.familyMembers.values();for(let z of J){let D=this.statesCreatedAt.get(z.key)??this.auditorCreatedAt,V=$-D;H.push([z,V])}}if(Z.selectorFamilies)for(let Q of W){let J=Q.familyMembers.values();for(let z of J){let D=this.statesCreatedAt.get(z.key)??this.auditorCreatedAt,V=$-D;H.push([z,V])}}return H}[Symbol.dispose](){this.unsubscribeFromAtomCreation(),this.unsubscribeFromAtomDisposal(),this.unsubscribeFromSelectorCreation(),this.unsubscribeFromSelectorDisposal(),this.disposed=!0}},i9=(Y,Z)=>{let X=(_,G)=>{let $=((Q,J)=>{let z=Z(Q,J);if(z)return z;return null})(_,G);if($?.jobComplete??$?.pathComplete)return $;let H=Array.isArray(G)?G.map((Q,J)=>[J,Q]):n9(G)?Object.entries(G):[];for(let[Q,J]of H){let z=X([..._,Q],J);if(z?.jobComplete)return z}return{}};X([],Y)};function $F(Y,Z){return{summary:`${Y<Z?"+":"-"}${Math.abs(Y-Z)} (${Y} \u2192 ${Z})`}}function HF(Y,Z){return{summary:`${Y.length<Z.length?"+":"-"}${Math.abs(Y.length-Z.length)} ("${Y}" \u2192 "${Z}")`}}function JF(Y,Z){return{summary:`${Y} \u2192 ${Z}`}}function s9(Y,Z,X){let _="",G=[],W=[],$=[];return i9(Y,(H,Q)=>{let J;for(J of H){let z=Z[J];if(z===void 0)W.push([J,JSON.stringify(Q)]);else{let O=X(Q,z);if(O.summary!=="No Change")$.push([J,O])}}}),i9(Z,(H,Q)=>{let J;for(J of H)if(Y[J]===void 0)G.push([J,JSON.stringify(Q)])}),_=`\uFF5E${$.length} \uFF0B${G.length} \uFF0D${W.length}`,{summary:_,added:G,removed:W,changed:$}}function QF(Y,Z,X){return s9(Y,Z,X)}var zF=class{leafRefinery;treeRefinery;leafDiffers;treeDiffers;constructor(Y,Z,X){this.leafRefinery=Y,this.treeRefinery=Z,this.leafDiffers={},this.treeDiffers={};for(let _ of Object.keys(Y.supported)){let G=X[_];this.leafDiffers[_]=G}for(let _ of Object.keys(Z.supported)){let G=X[_];this.treeDiffers[_]=G}}diff(Y,Z){if(Y===Z)return{summary:"No Change"};let X=this.leafRefinery.refine(Y)??this.treeRefinery.refine(Y),_=this.leafRefinery.refine(Z)??this.treeRefinery.refine(Z);if(X!==null&&_!==null){if(X.type===_.type){if(X.type in this.leafDiffers)return this.leafDiffers[X.type](X.data,_.data);if(X.type in this.treeDiffers)return this.treeDiffers[X.type](X.data,_.data,(H,Q)=>this.diff(H,Q))}}let G=R6(Y),W=R6(Z);if(G===W)return{summary:`${G} \u2192 ${W}`};return{summary:`Type change: ${G} \u2192 ${W}`}}},iB=new zF(o9,r9,{number:$F,string:HF,boolean:JF,null:()=>({summary:"No Change"}),object:s9,array:QF});var UF=class extends Map{set(Y,Z){if(this.has(Y))return console.warn("Tried to set a key that already exists in an InvariantMap",{key:Y,value:Z}),this;return super.set(Y,Z)}clear(){throw new Error("Cannot clear an InvariantMap")}},tB=class Y{type="continuity";globals=[];actions=[];perspectives=[];key;constructor(Z){this.key=Z}static existing=new UF;static create(Z,X){let _=new Y(Z),{type:G,globals:W,actions:$,perspectives:H}=X(_),Q={type:G,key:Z,globals:W,actions:$,perspectives:H};return Y.existing.set(Z,Q),Q}add(...Z){switch(Z[0].type){case"atom":case"mutable_atom":this.globals.push(...Z);break;case"transaction":this.actions.push(...Z);break;case"atom_family":case"mutable_atom_family":{let[_,G]=Z;this.perspectives.push({type:"realtime_perspective",resourceAtoms:_,viewAtoms:G})}break}return this}};var eB=O8({key:"usersInRoomIndex",default:()=>new D1,toJson:(Y)=>Y.toJSON(),fromJson:(Y)=>D1.fromJSON(Y)}),sZ=O8({key:"roomIndex",default:()=>new D1,toJson:(Y)=>Y.toJSON(),fromJson:(Y)=>D1.fromJSON(Y)}),FF={enteredAtEpoch:0},F2=E6({key:"usersInRooms",between:["room","user"],cardinality:"1:n",isAType:(Y)=>typeof Y==="string",isBType:(Y)=>typeof Y==="string"},FF),YC=D6({key:"usersInMyRoomView",get:(Y)=>({find:Z})=>{let X=A9(F2);return[Z(X,Y)]}});import{spawn as OF}from"child_process";var aZ=class{listeners;globalListeners;handleEvent(Y,...Z){for(let _ of this.globalListeners)_(Y,...Z);let X=this.listeners.get(Y);if(X)for(let _ of X)_(...Z)}id="no_id_retrieved";emit;constructor(Y){this.emit=Y,this.listeners=new Map,this.globalListeners=new Set}on(Y,Z){let X=this.listeners.get(Y);if(X)X.add(Z);else this.listeners.set(Y,new Set([Z]));return this}onAny(Y){return this.globalListeners.add(Y),this}off(Y,Z){let X=this.listeners.get(Y);if(X)if(Z)X.delete(Z);else this.listeners.delete(Y);return this}offAny(Y){return this.globalListeners.delete(Y),this}},EF=class extends aZ{incompleteData="";unprocessedEvents=[];incompleteLog="";unprocessedLogs=[];id="#####";process;key;logger;handleLog(Y){if(Array.isArray(Y)){let[Z,...X]=Y;switch(Z){case"i":this.logger.info(...X);break;case"w":this.logger.warn(...X);break;case"e":this.logger.error(...X);break;default:return}}}constructor(Y,Z,X){super((_,...G)=>{let W=JSON.stringify([_,...G])+"\x03",$=(H)=>{if(H.code==="EPIPE")console.error("EPIPE error during write",this.process.stdin);this.process.stdin.removeListener("error",$)};return this.process.stdin.once("error",$),this.process.stdin.write(W),this});if(this.process=Y,this.key=Z,this.logger=X??{info:(..._)=>{console.info(this.id,this.key,..._)},warn:(..._)=>{console.warn(this.id,this.key,..._)},error:(..._)=>{console.error(this.id,this.key,..._)}},this.process.stdout.on("data",(_)=>{let G=_.toString();if(G==="ALIVE")return;this.unprocessedEvents.push(...G.split("\x03"));let W=this.unprocessedEvents.shift();this.incompleteData+=W??"";try{if(this.incompleteData.startsWith("error"))console.log("\u2757",this.incompleteData);let $=G1(this.incompleteData);this.handleEvent(...$);while(this.unprocessedEvents.length>0){let H=this.unprocessedEvents.shift();if(H){if(this.unprocessedEvents.length===0)this.incompleteData=H;$=G1(H),this.handleEvent(...$)}}this.incompleteData=""}catch($){console.warn("\u26A0\uFE0F----------------\u26A0\uFE0F"),console.warn(this.incompleteData),console.warn("\u26A0\uFE0F----------------\u26A0\uFE0F"),console.error($)}}),this.process.stderr.on("data",(_)=>{let G=_.toString();this.unprocessedLogs.push(...G.split("\x03"));let W=this.unprocessedLogs.shift();this.incompleteLog+=W??"";try{let $=G1(this.incompleteLog);this.handleLog($);while(this.unprocessedLogs.length>0)if(this.incompleteLog=this.unprocessedLogs.shift()??"",this.incompleteLog)$=G1(this.incompleteLog),this.handleLog($)}catch($){console.error("\u274C\u274C\u274C"),console.error(this.incompleteLog),console.error($),console.error("\u274C\u274C\u274C\uFE0F")}}),Y.pid)this.id=Y.pid.toString()}},DF=class extends aZ{in;out;id="no_id_retrieved";disposalFunctions=[];constructor(Y){super((...Z)=>{return this.out.next(Z),this});this.id=Y,this.in=new H0,this.out=new H0,this.in.subscribe("socket",(Z)=>{this.handleEvent(...Z)})}dispose(){for(let Y of this.disposalFunctions)Y()}},a9=class extends aZ{incompleteData="";unprocessedEvents=[];relays;relayServices;process;id="#####";log(...Y){this.process.stderr.write(z0(Y.map((Z)=>Z instanceof D1?`{ ${Z.toJSON().members.join(" | ")} }`:Z))+"\x03")}logger={info:(...Y)=>{this.log("i",...Y)},warn:(...Y)=>{this.log("w",...Y)},error:(...Y)=>{this.log("e",...Y)}};constructor(){super((Y,...Z)=>{let X=JSON.stringify([Y,...Z]);return this.process.stdout.write(X+"\x03"),this});if(this.process=process,this.process.stdin.resume(),this.relays=new Map,this.relayServices=[],this.process.stdin.on("data",(Y)=>{let Z=Y.toString();this.unprocessedEvents.push(...Z.split("\x03"));let X=this.unprocessedEvents.shift();this.incompleteData+=X??"";try{let _=G1(this.incompleteData);this.logger.info("\uD83C\uDFB0","received",_),this.handleEvent(..._);while(this.unprocessedEvents.length>0){let G=this.unprocessedEvents.shift();if(G){if(this.unprocessedEvents.length===0)this.incompleteData=G;let W=G1(G);this.handleEvent(...W)}}this.incompleteData=""}catch(_){if(_ instanceof Error)this.logger.error("\u2757",_.message,_.cause,_.stack)}}),this.on("exit",()=>{this.logger.info("\uD83D\uDD25",this.id,'received "exit"'),process.exit(0)}),process.on("exit",(Y)=>{this.logger.info("\uD83D\uDD25",this.id,`exited with code ${Y}`)}),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",(Y)=>{this.logger.info("\uD83D\uDC64","user",Y,"joined");let Z=new DF(`user:${Y}`);this.relays.set(Y,Z),this.logger.info("\uD83D\uDD17","attaching services:",`[${[...this.relayServices.keys()].join(", ")}]`);for(let X of this.relayServices){let _=X(Z);if(_)Z.disposalFunctions.push(_)}this.on(`user:${Y}`,(...X)=>{Z.in.next(X)}),Z.out.subscribe("socket",(X)=>{this.emit(...X)})}),this.on("user-leaves",(Y)=>{let Z=this.relays.get(Y);if(this.off(`relay:${Y}`),Z)Z.dispose(),this.relays.delete(Y)}),process.stdout.write("ALIVE")}relay(Y){this.logger.info("\uD83D\uDD17","running relay method"),this.relayServices.push(Y)}},t9=$2({key:"roomArguments",default:["echo",["Hello World!"]]}),LF=D6({key:"room",get:(Y)=>async({get:Z,find:X})=>{let _=X(t9,Y),G=Z(_),[W,$]=G,H=await new Promise((Q)=>{let J=OF(W,$,{env:process.env}),z=(O)=>{if(O.toString()==="ALIVE")J.stdout.off("data",z),Q(J)};J.stdout.on("data",z)});return new EF(H,Y)}}),QC=H2({key:"createRoom",do:({get:Y,set:Z,find:X},_,G,W)=>{let $=W?[G,W]:[G],H=X(t9,_);Z(H,$),Z(sZ,(z)=>z.add(_));let Q=X(LF,_);return Y(Q)}}),zC=H2({key:"joinRoom",do:(Y,Z,X,_)=>{let G={enteredAtEpoch:_};return Q2(F2,(W)=>{W.set({room:Z,user:X},G)},Y.env().store),G}}),UC=H2({key:"leaveRoom",do:(Y,Z,X)=>{Q2(F2,(_)=>{_.delete({room:Z,user:X})},Y.env().store)}}),FC=H2({key:"destroyRoom",do:(Y,Z)=>{Q2(F2,(X)=>{X.delete({room:Z})},Y.env().store),Y.set(sZ,(X)=>(X.delete(Z),X))}});var OC=$2({key:"redactor",default:{occlude:(Y)=>Y}}),EC=$2({key:"unacknowledgedUpdates",default:()=>[]}),DC=$2({key:"sockets",default:null}),LC=O8({key:"socketsIndex",default:()=>new D1,toJson:(Y)=>Y.toJSON(),fromJson:(Y)=>D1.fromJSON(Y)}),VC=O8({key:"usersIndex",default:()=>new D1,toJson:(Y)=>Y.toJSON(),fromJson:(Y)=>D1.fromJSON(Y)}),MC=E6({key:"usersOfSockets",between:["user","socket"],cardinality:"1:1",isAType:(Y)=>Y.startsWith("user::"),isBType:(Y)=>Y.startsWith("socket::")});var{file:P$,serve:vO}=globalThis.Bun;import{readFileSync as Z7}from"fs";import{createServer as wF}from"http";import{createServer as RF}from"https";import{resolve as eZ}from"path";function e9(Y,Z){if(Y instanceof Promise)throw new Error(Z)}function VF(Y,Z){let X={},_=[];for(let G in Y){let W=Y[G]["~standard"].validate(Z[G]);if(e9(W,`Validation must be synchronous, but ${G} returned a Promise.`),W.issues){_.push(...W.issues.map(($)=>({...$,message:$.message,path:[G,...$.path??[]]})));continue}X[G]=W.value}if(_.length)return{issues:_};return{value:X}}function tZ(Y){let Z=Y.runtimeEnvStrict??Y.runtimeEnv??process.env;if(Y.emptyStringAsUndefined??!1){for(let[f,h]of Object.entries(Z))if(h==="")delete Z[f]}if(!!Y.skipValidation)return Z;let G=typeof Y.client==="object"?Y.client:{},W=typeof Y.server==="object"?Y.server:{},$=typeof Y.shared==="object"?Y.shared:{},H=Y.isServer??(typeof window==="undefined"||("Deno"in window)),Q=H?{...W,...$,...G}:{...G,...$},J=Y.createFinalSchema?.(Q,H)["~standard"].validate(Z)??VF(Q,Z);e9(J,"Validation must be synchronous");let z=Y.onValidationError??((f)=>{throw console.error("\u274C Invalid environment variables:",f),new Error("Invalid environment variables")}),O=Y.onInvalidAccess??(()=>{throw new Error("\u274C Attempted to access a server-side environment variable on the client")});if(J.issues)return z(J.issues);let D=(f)=>{if(!Y.clientPrefix)return!0;return!f.startsWith(Y.clientPrefix)&&!(f in $)},V=(f)=>{return H||!D(f)},R=(f)=>{return f==="__esModule"||f==="$$typeof"},A=(Y.extends??[]).reduce((f,h)=>{return Object.assign(f,h)},{}),g=Object.assign(A,J.value);return new Proxy(g,{get(f,h){if(typeof h!=="string")return;if(R(h))return;if(!V(h))return O(h);return Reflect.get(f,h)}})}var MF="__vite_start_time"in globalThis,AF=typeof window!=="undefined",jC="vitest"in globalThis,$4=E1("string"),Y7=E1('"true" | "false" | undefined'),g1=tZ({isServer:!MF&&!AF,server:{CI:E1("string | undefined").pipe(Boolean),POSTGRES_USER:$4,POSTGRES_PASSWORD:$4,POSTGRES_DATABASE:$4,POSTGRES_HOST:$4,POSTGRES_PORT:$4.pipe((Y)=>Number.parseInt(Y,10)),BACKEND_PORT:$4.pipe((Y)=>Number.parseInt(Y,10)),RUN_WORKERS_FROM_SOURCE:Y7.pipe((Y)=>Y==="true"),FRONTEND_PORT:$4.pipe((Y)=>Number.parseInt(Y,10)),FRONTEND_ORIGINS:$4.pipe.try((Y)=>JSON.parse(Y),E1("string[]")),API_KEY_OPENAI:E1("string | undefined"),API_KEY_RESEND:E1("string | undefined")},clientPrefix:"VITE_",client:{VITE_BACKEND_ORIGIN:$4,VITE_DEV_FRONTEND_HOST:E1("string | undefined"),VITE_DEV_HTTPS:Y7.pipe((Y)=>Y==="true")},runtimeEnv:import.meta.env,emptyStringAsUndefined:!0});var X7=eZ(import.meta.dirname,"../dev"),N6=g1.VITE_DEV_HTTPS?{cert:Z7(eZ(X7,"./cert.pem"),"utf-8"),key:Z7(eZ(X7,"./key.pem"),"utf-8")}:void 0;function bC(Y){if(N6)return RF(N6,Y);return wF({},Y)}import CO from"path";var F=Symbol.for("drizzle:entityKind");function M(Y,Z){if(!Y||typeof Y!=="object")return!1;if(Y instanceof Z)return!0;if(!Object.prototype.hasOwnProperty.call(Z,F))throw new Error(`Class "${Z.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 X=Object.getPrototypeOf(Y).constructor;if(X)while(X){if(F in X&&X[F]===Z[F])return!0;X=Object.getPrototypeOf(X)}return!1}class E0{constructor(Y,Z){this.table=Y,this.config=Z,this.name=Z.name,this.keyAsName=Z.keyAsName,this.notNull=Z.notNull,this.default=Z.default,this.defaultFn=Z.defaultFn,this.onUpdateFn=Z.onUpdateFn,this.hasDefault=Z.hasDefault,this.primary=Z.primaryKey,this.isUnique=Z.isUnique,this.uniqueName=Z.uniqueName,this.uniqueType=Z.uniqueType,this.dataType=Z.dataType,this.columnType=Z.columnType,this.generated=Z.generated,this.generatedIdentity=Z.generatedIdentity}static[F]="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(Y){return Y}mapToDriverValue(Y){return Y}shouldDisableInsert(){return this.config.generated!==void 0&&this.config.generated.type!=="byDefault"}}class Y5{static[F]="ColumnBuilder";config;constructor(Y,Z,X){this.config={name:Y,keyAsName:Y==="",notNull:!1,default:void 0,hasDefault:!1,primaryKey:!1,isUnique:!1,uniqueName:void 0,uniqueType:void 0,dataType:Z,columnType:X,generated:void 0}}$type(){return this}notNull(){return this.config.notNull=!0,this}default(Y){return this.config.default=Y,this.config.hasDefault=!0,this}$defaultFn(Y){return this.config.defaultFn=Y,this.config.hasDefault=!0,this}$default=this.$defaultFn;$onUpdateFn(Y){return this.config.onUpdateFn=Y,this.config.hasDefault=!0,this}$onUpdate=this.$onUpdateFn;primaryKey(){return this.config.primaryKey=!0,this.config.notNull=!0,this}setName(Y){if(this.config.name!=="")return;this.config.name=Y}}var y1=Symbol.for("drizzle:Name");class Z5{static[F]="PgForeignKeyBuilder";reference;_onUpdate="no action";_onDelete="no action";constructor(Y,Z){if(this.reference=()=>{let{name:X,columns:_,foreignColumns:G}=Y();return{name:X,columns:_,foreignTable:G[0].table,foreignColumns:G}},Z)this._onUpdate=Z.onUpdate,this._onDelete=Z.onDelete}onUpdate(Y){return this._onUpdate=Y===void 0?"no action":Y,this}onDelete(Y){return this._onDelete=Y===void 0?"no action":Y,this}build(Y){return new _7(Y,this)}}class _7{constructor(Y,Z){this.table=Y,this.reference=Z.reference,this.onUpdate=Z._onUpdate,this.onDelete=Z._onDelete}static[F]="PgForeignKey";reference;onUpdate;onDelete;getName(){let{name:Y,columns:Z,foreignColumns:X}=this.reference(),_=Z.map(($)=>$.name),G=X.map(($)=>$.name),W=[this.table[y1],..._,X[0].table[y1],...G];return Y??`${W.join("_")}_fk`}}function I6(Y,...Z){return Y(...Z)}function G7(Y,Z){return`${Y[y1]}_${Z.join("_")}_unique`}function W7(Y,Z,X){for(let _=Z;_<Y.length;_++){let G=Y[_];if(G==="\\"){_++;continue}if(G==='"')return[Y.slice(Z,_).replace(/\\/g,""),_+1];if(X)continue;if(G===","||G==="}")return[Y.slice(Z,_).replace(/\\/g,""),_]}return[Y.slice(Z).replace(/\\/g,""),Y.length]}function $7(Y,Z=0){let X=[],_=Z,G=!1;while(_<Y.length){let W=Y[_];if(W===","){if(G||_===Z)X.push("");G=!0,_++;continue}if(G=!1,W==="\\"){_+=2;continue}if(W==='"'){let[Q,J]=W7(Y,_+1,!0);X.push(Q),_=J;continue}if(W==="}")return[X,_+1];if(W==="{"){let[Q,J]=$7(Y,_+1);X.push(Q),_=J;continue}let[$,H]=W7(Y,_,!1);X.push($),_=H}return[X,_]}function H7(Y){let[Z]=$7(Y,1);return Z}function X5(Y){return`{${Y.map((Z)=>{if(Array.isArray(Z))return X5(Z);if(typeof Z==="string")return`"${Z.replace(/\\/g,"\\\\").replace(/"/g,"\\\"")}"`;return`${Z}`}).join(",")}}`}class k extends Y5{foreignKeyConfigs=[];static[F]="PgColumnBuilder";array(Y){return new Q7(this.config.name,this,Y)}references(Y,Z={}){return this.foreignKeyConfigs.push({ref:Y,actions:Z}),this}unique(Y,Z){return this.config.isUnique=!0,this.config.uniqueName=Y,this.config.uniqueType=Z?.nulls,this}generatedAlwaysAs(Y){return this.config.generated={as:Y,type:"always",mode:"stored"},this}buildForeignKeys(Y,Z){return this.foreignKeyConfigs.map(({ref:X,actions:_})=>{return I6((G,W)=>{let $=new Z5(()=>{let H=G();return{columns:[Y],foreignColumns:[H]}});if(W.onUpdate)$.onUpdate(W.onUpdate);if(W.onDelete)$.onDelete(W.onDelete);return $.build(Z)},X,_)})}buildExtraConfigColumn(Y){return new J7(Y,this.config)}}class j extends E0{constructor(Y,Z){if(!Z.uniqueName)Z.uniqueName=G7(Y,[Z.name]);super(Y,Z);this.table=Y}static[F]="PgColumn"}class J7 extends j{static[F]="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(Y){return this.indexConfig.opClass=Y,this}}class O2{static[F]="IndexedColumn";constructor(Y,Z,X,_){this.name=Y,this.keyAsName=Z,this.type=X,this.indexConfig=_}name;keyAsName;type;indexConfig}class Q7 extends k{static[F]="PgArrayBuilder";constructor(Y,Z,X){super(Y,"array","PgArray");this.config.baseBuilder=Z,this.config.size=X}build(Y){let Z=this.config.baseBuilder.build(Y);return new _5(Y,this.config,Z)}}class _5 extends j{constructor(Y,Z,X,_){super(Y,Z);this.baseColumn=X,this.range=_,this.size=Z.size}size;static[F]="PgArray";getSQLType(){return`${this.baseColumn.getSQLType()}[${typeof this.size==="number"?this.size:""}]`}mapFromDriverValue(Y){if(typeof Y==="string")Y=H7(Y);return Y.map((Z)=>this.baseColumn.mapFromDriverValue(Z))}mapToDriverValue(Y,Z=!1){let X=Y.map((_)=>_===null?null:M(this.baseColumn,_5)?this.baseColumn.mapToDriverValue(_,!0):this.baseColumn.mapToDriverValue(_));if(Z)return X;return X5(X)}}class z7 extends k{static[F]="PgEnumObjectColumnBuilder";constructor(Y,Z){super(Y,"string","PgEnumObjectColumn");this.config.enum=Z}build(Y){return new U7(Y,this.config)}}class U7 extends j{static[F]="PgEnumObjectColumn";enum;enumValues=this.config.enum.enumValues;constructor(Y,Z){super(Y,Z);this.enum=Z.enum}getSQLType(){return this.enum.enumName}}var B6=Symbol.for("drizzle:isPgEnum");function F7(Y){return!!Y&&typeof Y==="function"&&B6 in Y&&Y[B6]===!0}class O7 extends k{static[F]="PgEnumColumnBuilder";constructor(Y,Z){super(Y,"string","PgEnumColumn");this.config.enum=Z}build(Y){return new E7(Y,this.config)}}class E7 extends j{static[F]="PgEnumColumn";enum=this.config.enum;enumValues=this.config.enum.enumValues;constructor(Y,Z){super(Y,Z);this.enum=Z.enum}getSQLType(){return this.enum.enumName}}function E2(Y,Z){return Array.isArray(Z)?NF(Y,[...Z],void 0):IF(Y,Z,void 0)}function NF(Y,Z,X){let _=Object.assign((G)=>new O7(G??"",_),{enumName:Y,enumValues:Z,schema:X,[B6]:!0});return _}function IF(Y,Z,X){let _=Object.assign((G)=>new z7(G??"",_),{enumName:Y,enumValues:Object.values(Z),schema:X,[B6]:!0});return _}class P0{static[F]="Subquery";constructor(Y,Z,X,_=!1,G=[]){this._={brand:"Subquery",sql:Y,selectedFields:Z,alias:X,isWith:_,usedTables:G}}}class D2 extends P0{static[F]="WithSubquery"}var D7="0.44.4";var G5,W5,D0={startActiveSpan(Y,Z){if(!G5)return Z();if(!W5)W5=G5.trace.getTracer("drizzle-orm",D7);return I6((X,_)=>_.startActiveSpan(Y,(G)=>{try{return Z(G)}catch(W){throw G.setStatus({code:X.SpanStatusCode.ERROR,message:W instanceof Error?W.message:"Unknown error"}),W}finally{G.end()}}),G5,W5)}};var A0=Symbol.for("drizzle:ViewBaseConfig");var g4=Symbol.for("drizzle:Schema"),C6=Symbol.for("drizzle:Columns"),L7=Symbol.for("drizzle:ExtraConfigColumns"),$5=Symbol.for("drizzle:OriginalName"),H5=Symbol.for("drizzle:BaseName"),L2=Symbol.for("drizzle:IsAlias"),V7=Symbol.for("drizzle:ExtraConfigBuilder"),BF=Symbol.for("drizzle:IsDrizzleTable");class P{static[F]="Table";static Symbol={Name:y1,Schema:g4,OriginalName:$5,Columns:C6,ExtraConfigColumns:L7,BaseName:H5,IsAlias:L2,ExtraConfigBuilder:V7};[y1];[$5];[g4];[C6];[L7];[H5];[L2]=!1;[BF]=!0;[V7]=void 0;constructor(Y,Z,X){this[y1]=this[$5]=Y,this[g4]=Z,this[H5]=X}}function c0(Y){return Y[y1]}function y4(Y){return`${Y[g4]??"public"}.${Y[y1]}`}function J5(Y){return Y!==null&&Y!==void 0&&typeof Y.getSQL==="function"}function CF(Y){let Z={sql:"",params:[]};for(let X of Y)if(Z.sql+=X.sql,Z.params.push(...X.params),X.typings?.length){if(!Z.typings)Z.typings=[];Z.typings.push(...X.typings)}return Z}class u0{static[F]="StringChunk";value;constructor(Y){this.value=Array.isArray(Y)?Y:[Y]}getSQL(){return new x([this])}}class x{constructor(Y){this.queryChunks=Y;for(let Z of Y)if(M(Z,P)){let X=Z[P.Symbol.Schema];this.usedTables.push(X===void 0?Z[P.Symbol.Name]:X+"."+Z[P.Symbol.Name])}}static[F]="SQL";decoder=A7;shouldInlineParams=!1;usedTables=[];append(Y){return this.queryChunks.push(...Y.queryChunks),this}toQuery(Y){return D0.startActiveSpan("drizzle.buildSQL",(Z)=>{let X=this.buildQueryFromSourceParams(this.queryChunks,Y);return Z?.setAttributes({"drizzle.query.text":X.sql,"drizzle.query.params":JSON.stringify(X.params)}),X})}buildQueryFromSourceParams(Y,Z){let X=Object.assign({},Z,{inlineParams:Z.inlineParams||this.shouldInlineParams,paramStartIndex:Z.paramStartIndex||{value:0}}),{casing:_,escapeName:G,escapeParam:W,prepareTyping:$,inlineParams:H,paramStartIndex:Q}=X;return CF(Y.map((J)=>{if(M(J,u0))return{sql:J.value.join(""),params:[]};if(M(J,T6))return{sql:G(J.value),params:[]};if(J===void 0)return{sql:"",params:[]};if(Array.isArray(J)){let z=[new u0("(")];for(let[O,D]of J.entries())if(z.push(D),O<J.length-1)z.push(new u0(", "));return z.push(new u0(")")),this.buildQueryFromSourceParams(z,X)}if(M(J,x))return this.buildQueryFromSourceParams(J.queryChunks,{...X,inlineParams:H||J.shouldInlineParams});if(M(J,P)){let z=J[P.Symbol.Schema],O=J[P.Symbol.Name];return{sql:z===void 0||J[L2]?G(O):G(z)+"."+G(O),params:[]}}if(M(J,E0)){let z=_.getColumnCasing(J);if(Z.invokeSource==="indexes")return{sql:G(z),params:[]};let O=J.table[P.Symbol.Schema];return{sql:J.table[L2]||O===void 0?G(J.table[P.Symbol.Name])+"."+G(z):G(O)+"."+G(J.table[P.Symbol.Name])+"."+G(z),params:[]}}if(M(J,L1)){let z=J[A0].schema,O=J[A0].name;return{sql:z===void 0||J[A0].isAlias?G(O):G(z)+"."+G(O),params:[]}}if(M(J,N1)){if(M(J.value,N4))return{sql:W(Q.value++,J),params:[J],typings:["none"]};let z=J.value===null?null:J.encoder.mapToDriverValue(J.value);if(M(z,x))return this.buildQueryFromSourceParams([z],X);if(H)return{sql:this.mapInlineParam(z,X),params:[]};let O=["none"];if($)O=[$(J.encoder)];return{sql:W(Q.value++,z),params:[z],typings:O}}if(M(J,N4))return{sql:W(Q.value++,J),params:[J],typings:["none"]};if(M(J,x.Aliased)&&J.fieldAlias!==void 0)return{sql:G(J.fieldAlias),params:[]};if(M(J,P0)){if(J._.isWith)return{sql:G(J._.alias),params:[]};return this.buildQueryFromSourceParams([new u0("("),J._.sql,new u0(") "),new T6(J._.alias)],X)}if(F7(J)){if(J.schema)return{sql:G(J.schema)+"."+G(J.enumName),params:[]};return{sql:G(J.enumName),params:[]}}if(J5(J)){if(J.shouldOmitSQLParens?.())return this.buildQueryFromSourceParams([J.getSQL()],X);return this.buildQueryFromSourceParams([new u0("("),J.getSQL(),new u0(")")],X)}if(H)return{sql:this.mapInlineParam(J,X),params:[]};return{sql:W(Q.value++,J),params:[J],typings:["none"]}}))}mapInlineParam(Y,{escapeString:Z}){if(Y===null)return"null";if(typeof Y==="number"||typeof Y==="boolean")return Y.toString();if(typeof Y==="string")return Z(Y);if(typeof Y==="object"){let X=Y.toString();if(X==="[object Object]")return Z(JSON.stringify(Y));return Z(X)}throw new Error("Unexpected param value: "+Y)}getSQL(){return this}as(Y){if(Y===void 0)return this;return new x.Aliased(this,Y)}mapWith(Y){return this.decoder=typeof Y==="function"?{mapFromDriverValue:Y}:Y,this}inlineParams(){return this.shouldInlineParams=!0,this}if(Y){return Y?this:void 0}}class T6{constructor(Y){this.value=Y}static[F]="Name";brand;getSQL(){return new x([this])}}function M7(Y){return typeof Y==="object"&&Y!==null&&"mapToDriverValue"in Y&&typeof Y.mapToDriverValue==="function"}var A7={mapFromDriverValue:(Y)=>Y},w7={mapToDriverValue:(Y)=>Y},CT={...A7,...w7};class N1{constructor(Y,Z=w7){this.value=Y,this.encoder=Z}static[F]="Param";brand;getSQL(){return new x([this])}}function E(Y,...Z){let X=[];if(Z.length>0||Y.length>0&&Y[0]!=="")X.push(new u0(Y[0]));for(let[_,G]of Z.entries())X.push(G,new u0(Y[_+1]));return new x(X)}((Y)=>{function Z(){return new x([])}Y.empty=Z;function X(Q){return new x(Q)}Y.fromList=X;function _(Q){return new x([new u0(Q)])}Y.raw=_;function G(Q,J){let z=[];for(let[O,D]of Q.entries()){if(O>0&&J!==void 0)z.push(J);z.push(D)}return new x(z)}Y.join=G;function W(Q){return new T6(Q)}Y.identifier=W;function $(Q){return new N4(Q)}Y.placeholder=$;function H(Q,J){return new N1(Q,J)}Y.param=H})(E||(E={}));((Y)=>{class Z{constructor(X,_){this.sql=X,this.fieldAlias=_}static[F]="SQL.Aliased";isSelectionField=!1;getSQL(){return this.sql}clone(){return new Z(this.sql,this.fieldAlias)}}Y.Aliased=Z})(x||(x={}));class N4{constructor(Y){this.name=Y}static[F]="Placeholder";getSQL(){return new x([this])}}function Q5(Y,Z){return Y.map((X)=>{if(M(X,N4)){if(!(X.name in Z))throw new Error(`No value for placeholder "${X.name}" was provided`);return Z[X.name]}if(M(X,N1)&&M(X.value,N4)){if(!(X.value.name in Z))throw new Error(`No value for placeholder "${X.value.name}" was provided`);return X.encoder.mapToDriverValue(Z[X.value.name])}return X})}var TF=Symbol.for("drizzle:IsDrizzleView");class L1{static[F]="View";[A0];[TF]=!0;constructor({name:Y,schema:Z,selectedFields:X,query:_}){this[A0]={name:Y,originalName:Y,schema:Z,selectedFields:X,query:_,isExisting:!_,isAlias:!1}}getSQL(){return new x([this])}}E0.prototype.getSQL=function(){return new x([this])};P.prototype.getSQL=function(){return new x([this])};P0.prototype.getSQL=function(){return new x([this])};class R8{constructor(Y){this.table=Y}static[F]="ColumnAliasProxyHandler";get(Y,Z){if(Z==="table")return this.table;return Y[Z]}}class V2{constructor(Y,Z){this.alias=Y,this.replaceOriginalName=Z}static[F]="TableAliasProxyHandler";get(Y,Z){if(Z===P.Symbol.IsAlias)return!0;if(Z===P.Symbol.Name)return this.alias;if(this.replaceOriginalName&&Z===P.Symbol.OriginalName)return this.alias;if(Z===A0)return{...Y[A0],name:this.alias,isAlias:!0};if(Z===P.Symbol.Columns){let _=Y[P.Symbol.Columns];if(!_)return _;let G={};return Object.keys(_).map((W)=>{G[W]=new Proxy(_[W],new R8(new Proxy(Y,this)))}),G}let X=Y[Z];if(M(X,E0))return new Proxy(X,new R8(new Proxy(Y,this)));return X}}function K6(Y,Z){return new Proxy(Y,new V2(Z,!1))}function o1(Y,Z){return new Proxy(Y,new R8(new Proxy(Y.table,new V2(Z,!1))))}function z5(Y,Z){return new x.Aliased(M2(Y.sql,Z),Y.fieldAlias)}function M2(Y,Z){return E.join(Y.queryChunks.map((X)=>{if(M(X,E0))return o1(X,Z);if(M(X,x))return M2(X,Z);if(M(X,x.Aliased))return z5(X,Z);return X}))}class q6 extends Error{static[F]="DrizzleError";constructor({message:Y,cause:Z}){super(Y);this.name="DrizzleError",this.cause=Z}}class H4 extends Error{constructor(Y,Z,X){super(`Failed query: ${Y}
62
+ params: ${Z}`);if(this.query=Y,this.params=Z,this.cause=X,Error.captureStackTrace(this,H4),X)this.cause=X}}class U5 extends q6{static[F]="TransactionRollbackError";constructor(){super({message:"Rollback"})}}class R7{static[F]="ConsoleLogWriter";write(Y){console.log(Y)}}class F5{static[F]="DefaultLogger";writer;constructor(Y){this.writer=Y?.writer??new R7}logQuery(Y,Z){let X=Z.map((G)=>{try{return JSON.stringify(G)}catch{return String(G)}}),_=X.length?` -- params: [${X.join(", ")}]`:"";this.writer.write(`Query: ${Y}${_}`)}}class O5{static[F]="NoopLogger";logQuery(){}}class $1{static[F]="QueryPromise";[Symbol.toStringTag]="QueryPromise";catch(Y){return this.then(void 0,Y)}finally(Y){return this.then((Z)=>{return Y?.(),Z},(Z)=>{throw Y?.(),Z})}then(Y,Z){return this.execute().then(Y,Z)}}function N7(Y,Z,X){let _={},G=Y.reduce((W,{path:$,field:H},Q)=>{let J;if(M(H,E0))J=H;else if(M(H,x))J=H.decoder;else J=H.sql.decoder;let z=W;for(let[O,D]of $.entries())if(O<$.length-1){if(!(D in z))z[D]={};z=z[D]}else{let V=Z[Q],R=z[D]=V===null?null:J.mapFromDriverValue(V);if(X&&M(H,E0)&&$.length===2){let A=$[0];if(!(A in _))_[A]=R===null?c0(H.table):!1;else if(typeof _[A]==="string"&&_[A]!==c0(H.table))_[A]=!1}}return W},{});if(X&&Object.keys(_).length>0){for(let[W,$]of Object.entries(_))if(typeof $==="string"&&!X[$])G[W]=null}return G}function q1(Y,Z){return Object.entries(Y).reduce((X,[_,G])=>{if(typeof _!=="string")return X;let W=Z?[...Z,_]:[_];if(M(G,E0)||M(G,x)||M(G,x.Aliased))X.push({path:W,field:G});else if(M(G,P))X.push(...q1(G[P.Symbol.Columns],W));else X.push(...q1(G,W));return X},[])}function A2(Y,Z){let X=Object.keys(Y),_=Object.keys(Z);if(X.length!==_.length)return!1;for(let[G,W]of X.entries())if(W!==_[G])return!1;return!0}function j6(Y,Z){let X=Object.entries(Z).filter(([,_])=>_!==void 0).map(([_,G])=>{if(M(G,x)||M(G,E0))return[_,G];else return[_,new N1(G,Y[P.Symbol.Columns][_])]});if(X.length===0)throw new Error("No values to set");return Object.fromEntries(X)}function I7(Y,Z){for(let X of Z)for(let _ of Object.getOwnPropertyNames(X.prototype)){if(_==="constructor")continue;Object.defineProperty(Y.prototype,_,Object.getOwnPropertyDescriptor(X.prototype,_)||Object.create(null))}}function B7(Y){return Y[P.Symbol.Columns]}function J4(Y){return M(Y,P0)?Y._.alias:M(Y,L1)?Y[A0].name:M(Y,x)?void 0:Y[P.Symbol.IsAlias]?Y[P.Symbol.Name]:Y[P.Symbol.BaseName]}function X0(Y,Z){return{name:typeof Y==="string"&&Y.length>0?Y:"",config:typeof Y==="object"?Y:Z}}function C7(Y){if(typeof Y!=="object"||Y===null)return!1;if(Y.constructor.name!=="Object")return!1;if("logger"in Y){let Z=typeof Y.logger;if(Z!=="boolean"&&(Z!=="object"||typeof Y.logger.logQuery!=="function")&&Z!=="undefined")return!1;return!0}if("schema"in Y){let Z=typeof Y.schema;if(Z!=="object"&&Z!=="undefined")return!1;return!0}if("casing"in Y){let Z=typeof Y.casing;if(Z!=="string"&&Z!=="undefined")return!1;return!0}if("mode"in Y){if(Y.mode!=="default"||Y.mode!=="planetscale"||Y.mode!==void 0)return!1;return!0}if("connection"in Y){let Z=typeof Y.connection;if(Z!=="string"&&Z!=="object"&&Z!=="undefined")return!1;return!0}if("client"in Y){let Z=typeof Y.client;if(Z!=="object"&&Z!=="function"&&Z!=="undefined")return!1;return!0}if(Object.keys(Y).length===0)return!0;return!1}class I4 extends k{static[F]="PgIntColumnBaseBuilder";generatedAlwaysAsIdentity(Y){if(Y){let{name:Z,...X}=Y;this.config.generatedIdentity={type:"always",sequenceName:Z,sequenceOptions:X}}else this.config.generatedIdentity={type:"always"};return this.config.hasDefault=!0,this.config.notNull=!0,this}generatedByDefaultAsIdentity(Y){if(Y){let{name:Z,...X}=Y;this.config.generatedIdentity={type:"byDefault",sequenceName:Z,sequenceOptions:X}}else this.config.generatedIdentity={type:"byDefault"};return this.config.hasDefault=!0,this.config.notNull=!0,this}}class T7 extends I4{static[F]="PgBigInt53Builder";constructor(Y){super(Y,"number","PgBigInt53")}build(Y){return new K7(Y,this.config)}}class K7 extends j{static[F]="PgBigInt53";getSQLType(){return"bigint"}mapFromDriverValue(Y){if(typeof Y==="number")return Y;return Number(Y)}}class q7 extends I4{static[F]="PgBigInt64Builder";constructor(Y){super(Y,"bigint","PgBigInt64")}build(Y){return new j7(Y,this.config)}}class j7 extends j{static[F]="PgBigInt64";getSQLType(){return"bigint"}mapFromDriverValue(Y){return BigInt(Y)}}function P7(Y,Z){let{name:X,config:_}=X0(Y,Z);if(_.mode==="number")return new T7(X);return new q7(X)}class S7 extends k{static[F]="PgBigSerial53Builder";constructor(Y){super(Y,"number","PgBigSerial53");this.config.hasDefault=!0,this.config.notNull=!0}build(Y){return new v7(Y,this.config)}}class v7 extends j{static[F]="PgBigSerial53";getSQLType(){return"bigserial"}mapFromDriverValue(Y){if(typeof Y==="number")return Y;return Number(Y)}}class x7 extends k{static[F]="PgBigSerial64Builder";constructor(Y){super(Y,"bigint","PgBigSerial64");this.config.hasDefault=!0}build(Y){return new h7(Y,this.config)}}class h7 extends j{static[F]="PgBigSerial64";getSQLType(){return"bigserial"}mapFromDriverValue(Y){return BigInt(Y)}}function f7(Y,Z){let{name:X,config:_}=X0(Y,Z);if(_.mode==="number")return new S7(X);return new x7(X)}class b7 extends k{static[F]="PgBooleanBuilder";constructor(Y){super(Y,"boolean","PgBoolean")}build(Y){return new k7(Y,this.config)}}class k7 extends j{static[F]="PgBoolean";getSQLType(){return"boolean"}}function w2(Y){return new b7(Y??"")}class g7 extends k{static[F]="PgCharBuilder";constructor(Y,Z){super(Y,"string","PgChar");this.config.length=Z.length,this.config.enumValues=Z.enum}build(Y){return new y7(Y,this.config)}}class y7 extends j{static[F]="PgChar";length=this.config.length;enumValues=this.config.enumValues;getSQLType(){return this.length===void 0?"char":`char(${this.length})`}}function p7(Y,Z={}){let{name:X,config:_}=X0(Y,Z);return new g7(X,_)}class m7 extends k{static[F]="PgCidrBuilder";constructor(Y){super(Y,"string","PgCidr")}build(Y){return new u7(Y,this.config)}}class u7 extends j{static[F]="PgCidr";getSQLType(){return"cidr"}}function d7(Y){return new m7(Y??"")}class c7 extends k{static[F]="PgCustomColumnBuilder";constructor(Y,Z,X){super(Y,"custom","PgCustomColumn");this.config.fieldConfig=Z,this.config.customTypeParams=X}build(Y){return new l7(Y,this.config)}}class l7 extends j{static[F]="PgCustomColumn";sqlName;mapTo;mapFrom;constructor(Y,Z){super(Y,Z);this.sqlName=Z.customTypeParams.dataType(Z.fieldConfig),this.mapTo=Z.customTypeParams.toDriver,this.mapFrom=Z.customTypeParams.fromDriver}getSQLType(){return this.sqlName}mapFromDriverValue(Y){return typeof this.mapFrom==="function"?this.mapFrom(Y):Y}mapToDriverValue(Y){return typeof this.mapTo==="function"?this.mapTo(Y):Y}}function i7(Y){return(Z,X)=>{let{name:_,config:G}=X0(Z,X);return new c7(_,G,Y)}}class Q4 extends k{static[F]="PgDateColumnBaseBuilder";defaultNow(){return this.default(E`now()`)}}class o7 extends Q4{static[F]="PgDateBuilder";constructor(Y){super(Y,"date","PgDate")}build(Y){return new P6(Y,this.config)}}class P6 extends j{static[F]="PgDate";getSQLType(){return"date"}mapFromDriverValue(Y){return new Date(Y)}mapToDriverValue(Y){return Y.toISOString()}}class n7 extends Q4{static[F]="PgDateStringBuilder";constructor(Y){super(Y,"string","PgDateString")}build(Y){return new S6(Y,this.config)}}class S6 extends j{static[F]="PgDateString";getSQLType(){return"date"}}function r7(Y,Z){let{name:X,config:_}=X0(Y,Z);if(_?.mode==="date")return new o7(X);return new n7(X)}class s7 extends k{static[F]="PgDoublePrecisionBuilder";constructor(Y){super(Y,"number","PgDoublePrecision")}build(Y){return new a7(Y,this.config)}}class a7 extends j{static[F]="PgDoublePrecision";getSQLType(){return"double precision"}mapFromDriverValue(Y){if(typeof Y==="string")return Number.parseFloat(Y);return Y}}function t7(Y){return new s7(Y??"")}class e7 extends k{static[F]="PgInetBuilder";constructor(Y){super(Y,"string","PgInet")}build(Y){return new Y3(Y,this.config)}}class Y3 extends j{static[F]="PgInet";getSQLType(){return"inet"}}function Z3(Y){return new e7(Y??"")}class X3 extends I4{static[F]="PgIntegerBuilder";constructor(Y){super(Y,"number","PgInteger")}build(Y){return new _3(Y,this.config)}}class _3 extends j{static[F]="PgInteger";getSQLType(){return"integer"}mapFromDriverValue(Y){if(typeof Y==="string")return Number.parseInt(Y);return Y}}function R2(Y){return new X3(Y??"")}class G3 extends k{static[F]="PgIntervalBuilder";constructor(Y,Z){super(Y,"string","PgInterval");this.config.intervalConfig=Z}build(Y){return new W3(Y,this.config)}}class W3 extends j{static[F]="PgInterval";fields=this.config.intervalConfig.fields;precision=this.config.intervalConfig.precision;getSQLType(){let Y=this.fields?` ${this.fields}`:"",Z=this.precision?`(${this.precision})`:"";return`interval${Y}${Z}`}}function $3(Y,Z={}){let{name:X,config:_}=X0(Y,Z);return new G3(X,_)}class H3 extends k{static[F]="PgJsonBuilder";constructor(Y){super(Y,"json","PgJson")}build(Y){return new v6(Y,this.config)}}class v6 extends j{static[F]="PgJson";constructor(Y,Z){super(Y,Z)}getSQLType(){return"json"}mapToDriverValue(Y){return JSON.stringify(Y)}mapFromDriverValue(Y){if(typeof Y==="string")try{return JSON.parse(Y)}catch{return Y}return Y}}function J3(Y){return new H3(Y??"")}class Q3 extends k{static[F]="PgJsonbBuilder";constructor(Y){super(Y,"json","PgJsonb")}build(Y){return new x6(Y,this.config)}}class x6 extends j{static[F]="PgJsonb";constructor(Y,Z){super(Y,Z)}getSQLType(){return"jsonb"}mapToDriverValue(Y){return JSON.stringify(Y)}mapFromDriverValue(Y){if(typeof Y==="string")try{return JSON.parse(Y)}catch{return Y}return Y}}function z3(Y){return new Q3(Y??"")}class U3 extends k{static[F]="PgLineBuilder";constructor(Y){super(Y,"array","PgLine")}build(Y){return new F3(Y,this.config)}}class F3 extends j{static[F]="PgLine";getSQLType(){return"line"}mapFromDriverValue(Y){let[Z,X,_]=Y.slice(1,-1).split(",");return[Number.parseFloat(Z),Number.parseFloat(X),Number.parseFloat(_)]}mapToDriverValue(Y){return`{${Y[0]},${Y[1]},${Y[2]}}`}}class O3 extends k{static[F]="PgLineABCBuilder";constructor(Y){super(Y,"json","PgLineABC")}build(Y){return new E3(Y,this.config)}}class E3 extends j{static[F]="PgLineABC";getSQLType(){return"line"}mapFromDriverValue(Y){let[Z,X,_]=Y.slice(1,-1).split(",");return{a:Number.parseFloat(Z),b:Number.parseFloat(X),c:Number.parseFloat(_)}}mapToDriverValue(Y){return`{${Y.a},${Y.b},${Y.c}}`}}function D3(Y,Z){let{name:X,config:_}=X0(Y,Z);if(!_?.mode||_.mode==="tuple")return new U3(X);return new O3(X)}class L3 extends k{static[F]="PgMacaddrBuilder";constructor(Y){super(Y,"string","PgMacaddr")}build(Y){return new V3(Y,this.config)}}class V3 extends j{static[F]="PgMacaddr";getSQLType(){return"macaddr"}}function M3(Y){return new L3(Y??"")}class A3 extends k{static[F]="PgMacaddr8Builder";constructor(Y){super(Y,"string","PgMacaddr8")}build(Y){return new w3(Y,this.config)}}class w3 extends j{static[F]="PgMacaddr8";getSQLType(){return"macaddr8"}}function R3(Y){return new A3(Y??"")}class N3 extends k{static[F]="PgNumericBuilder";constructor(Y,Z,X){super(Y,"string","PgNumeric");this.config.precision=Z,this.config.scale=X}build(Y){return new h6(Y,this.config)}}class h6 extends j{static[F]="PgNumeric";precision;scale;constructor(Y,Z){super(Y,Z);this.precision=Z.precision,this.scale=Z.scale}mapFromDriverValue(Y){if(typeof Y==="string")return Y;return String(Y)}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 I3 extends k{static[F]="PgNumericNumberBuilder";constructor(Y,Z,X){super(Y,"number","PgNumericNumber");this.config.precision=Z,this.config.scale=X}build(Y){return new B3(Y,this.config)}}class B3 extends j{static[F]="PgNumericNumber";precision;scale;constructor(Y,Z){super(Y,Z);this.precision=Z.precision,this.scale=Z.scale}mapFromDriverValue(Y){if(typeof Y==="number")return Y;return Number(Y)}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 C3 extends k{static[F]="PgNumericBigIntBuilder";constructor(Y,Z,X){super(Y,"bigint","PgNumericBigInt");this.config.precision=Z,this.config.scale=X}build(Y){return new T3(Y,this.config)}}class T3 extends j{static[F]="PgNumericBigInt";precision;scale;constructor(Y,Z){super(Y,Z);this.precision=Z.precision,this.scale=Z.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 K3(Y,Z){let{name:X,config:_}=X0(Y,Z),G=_?.mode;return G==="number"?new I3(X,_?.precision,_?.scale):G==="bigint"?new C3(X,_?.precision,_?.scale):new N3(X,_?.precision,_?.scale)}class q3 extends k{static[F]="PgPointTupleBuilder";constructor(Y){super(Y,"array","PgPointTuple")}build(Y){return new j3(Y,this.config)}}class j3 extends j{static[F]="PgPointTuple";getSQLType(){return"point"}mapFromDriverValue(Y){if(typeof Y==="string"){let[Z,X]=Y.slice(1,-1).split(",");return[Number.parseFloat(Z),Number.parseFloat(X)]}return[Y.x,Y.y]}mapToDriverValue(Y){return`(${Y[0]},${Y[1]})`}}class P3 extends k{static[F]="PgPointObjectBuilder";constructor(Y){super(Y,"json","PgPointObject")}build(Y){return new S3(Y,this.config)}}class S3 extends j{static[F]="PgPointObject";getSQLType(){return"point"}mapFromDriverValue(Y){if(typeof Y==="string"){let[Z,X]=Y.slice(1,-1).split(",");return{x:Number.parseFloat(Z),y:Number.parseFloat(X)}}return Y}mapToDriverValue(Y){return`(${Y.x},${Y.y})`}}function v3(Y,Z){let{name:X,config:_}=X0(Y,Z);if(!_?.mode||_.mode==="tuple")return new q3(X);return new P3(X)}function KF(Y){let Z=[];for(let X=0;X<Y.length;X+=2)Z.push(Number.parseInt(Y.slice(X,X+2),16));return new Uint8Array(Z)}function x3(Y,Z){let X=new ArrayBuffer(8),_=new DataView(X);for(let G=0;G<8;G++)_.setUint8(G,Y[Z+G]);return _.getFloat64(0,!0)}function E5(Y){let Z=KF(Y),X=0,_=Z[X];X+=1;let G=new DataView(Z.buffer),W=G.getUint32(X,_===1);X+=4;let $;if(W&536870912)$=G.getUint32(X,_===1),X+=4;if((W&65535)===1){let H=x3(Z,X);X+=8;let Q=x3(Z,X);return X+=8,[H,Q]}throw new Error("Unsupported geometry type")}class h3 extends k{static[F]="PgGeometryBuilder";constructor(Y){super(Y,"array","PgGeometry")}build(Y){return new f3(Y,this.config)}}class f3 extends j{static[F]="PgGeometry";getSQLType(){return"geometry(point)"}mapFromDriverValue(Y){return E5(Y)}mapToDriverValue(Y){return`point(${Y[0]} ${Y[1]})`}}class b3 extends k{static[F]="PgGeometryObjectBuilder";constructor(Y){super(Y,"json","PgGeometryObject")}build(Y){return new k3(Y,this.config)}}class k3 extends j{static[F]="PgGeometryObject";getSQLType(){return"geometry(point)"}mapFromDriverValue(Y){let Z=E5(Y);return{x:Z[0],y:Z[1]}}mapToDriverValue(Y){return`point(${Y.x} ${Y.y})`}}function g3(Y,Z){let{name:X,config:_}=X0(Y,Z);if(!_?.mode||_.mode==="tuple")return new h3(X);return new b3(X)}class y3 extends k{static[F]="PgRealBuilder";constructor(Y,Z){super(Y,"number","PgReal");this.config.length=Z}build(Y){return new p3(Y,this.config)}}class p3 extends j{static[F]="PgReal";constructor(Y,Z){super(Y,Z)}getSQLType(){return"real"}mapFromDriverValue=(Y)=>{if(typeof Y==="string")return Number.parseFloat(Y);return Y}}function m3(Y){return new y3(Y??"")}class u3 extends k{static[F]="PgSerialBuilder";constructor(Y){super(Y,"number","PgSerial");this.config.hasDefault=!0,this.config.notNull=!0}build(Y){return new d3(Y,this.config)}}class d3 extends j{static[F]="PgSerial";getSQLType(){return"serial"}}function c3(Y){return new u3(Y??"")}class l3 extends I4{static[F]="PgSmallIntBuilder";constructor(Y){super(Y,"number","PgSmallInt")}build(Y){return new i3(Y,this.config)}}class i3 extends j{static[F]="PgSmallInt";getSQLType(){return"smallint"}mapFromDriverValue=(Y)=>{if(typeof Y==="string")return Number(Y);return Y}}function o3(Y){return new l3(Y??"")}class n3 extends k{static[F]="PgSmallSerialBuilder";constructor(Y){super(Y,"number","PgSmallSerial");this.config.hasDefault=!0,this.config.notNull=!0}build(Y){return new r3(Y,this.config)}}class r3 extends j{static[F]="PgSmallSerial";getSQLType(){return"smallserial"}}function s3(Y){return new n3(Y??"")}class a3 extends k{static[F]="PgTextBuilder";constructor(Y,Z){super(Y,"string","PgText");this.config.enumValues=Z.enum}build(Y){return new t3(Y,this.config)}}class t3 extends j{static[F]="PgText";enumValues=this.config.enumValues;getSQLType(){return"text"}}function e3(Y,Z={}){let{name:X,config:_}=X0(Y,Z);return new a3(X,_)}class YW extends Q4{constructor(Y,Z,X){super(Y,"string","PgTime");this.withTimezone=Z,this.precision=X,this.config.withTimezone=Z,this.config.precision=X}static[F]="PgTimeBuilder";build(Y){return new f6(Y,this.config)}}class f6 extends j{static[F]="PgTime";withTimezone;precision;constructor(Y,Z){super(Y,Z);this.withTimezone=Z.withTimezone,this.precision=Z.precision}getSQLType(){return`time${this.precision===void 0?"":`(${this.precision})`}${this.withTimezone?" with time zone":""}`}}function ZW(Y,Z={}){let{name:X,config:_}=X0(Y,Z);return new YW(X,_.withTimezone??!1,_.precision)}class XW extends Q4{static[F]="PgTimestampBuilder";constructor(Y,Z,X){super(Y,"date","PgTimestamp");this.config.withTimezone=Z,this.config.precision=X}build(Y){return new b6(Y,this.config)}}class b6 extends j{static[F]="PgTimestamp";withTimezone;precision;constructor(Y,Z){super(Y,Z);this.withTimezone=Z.withTimezone,this.precision=Z.precision}getSQLType(){return`timestamp${this.precision===void 0?"":` (${this.precision})`}${this.withTimezone?" with time zone":""}`}mapFromDriverValue=(Y)=>{return new Date(this.withTimezone?Y:Y+"+0000")};mapToDriverValue=(Y)=>{return Y.toISOString()}}class _W extends Q4{static[F]="PgTimestampStringBuilder";constructor(Y,Z,X){super(Y,"string","PgTimestampString");this.config.withTimezone=Z,this.config.precision=X}build(Y){return new k6(Y,this.config)}}class k6 extends j{static[F]="PgTimestampString";withTimezone;precision;constructor(Y,Z){super(Y,Z);this.withTimezone=Z.withTimezone,this.precision=Z.precision}getSQLType(){return`timestamp${this.precision===void 0?"":`(${this.precision})`}${this.withTimezone?" with time zone":""}`}}function GW(Y,Z={}){let{name:X,config:_}=X0(Y,Z);if(_?.mode==="string")return new _W(X,_.withTimezone??!1,_.precision);return new XW(X,_?.withTimezone??!1,_?.precision)}class WW extends k{static[F]="PgUUIDBuilder";constructor(Y){super(Y,"string","PgUUID")}defaultRandom(){return this.default(E`gen_random_uuid()`)}build(Y){return new g6(Y,this.config)}}class g6 extends j{static[F]="PgUUID";getSQLType(){return"uuid"}}function j1(Y){return new WW(Y??"")}class $W extends k{static[F]="PgVarcharBuilder";constructor(Y,Z){super(Y,"string","PgVarchar");this.config.length=Z.length,this.config.enumValues=Z.enum}build(Y){return new HW(Y,this.config)}}class HW extends j{static[F]="PgVarchar";length=this.config.length;enumValues=this.config.enumValues;getSQLType(){return this.length===void 0?"varchar":`varchar(${this.length})`}}function e0(Y,Z={}){let{name:X,config:_}=X0(Y,Z);return new $W(X,_)}class JW extends k{static[F]="PgBinaryVectorBuilder";constructor(Y,Z){super(Y,"string","PgBinaryVector");this.config.dimensions=Z.dimensions}build(Y){return new QW(Y,this.config)}}class QW extends j{static[F]="PgBinaryVector";dimensions=this.config.dimensions;getSQLType(){return`bit(${this.dimensions})`}}function zW(Y,Z){let{name:X,config:_}=X0(Y,Z);return new JW(X,_)}class UW extends k{static[F]="PgHalfVectorBuilder";constructor(Y,Z){super(Y,"array","PgHalfVector");this.config.dimensions=Z.dimensions}build(Y){return new FW(Y,this.config)}}class FW extends j{static[F]="PgHalfVector";dimensions=this.config.dimensions;getSQLType(){return`halfvec(${this.dimensions})`}mapToDriverValue(Y){return JSON.stringify(Y)}mapFromDriverValue(Y){return Y.slice(1,-1).split(",").map((Z)=>Number.parseFloat(Z))}}function OW(Y,Z){let{name:X,config:_}=X0(Y,Z);return new UW(X,_)}class EW extends k{static[F]="PgSparseVectorBuilder";constructor(Y,Z){super(Y,"string","PgSparseVector");this.config.dimensions=Z.dimensions}build(Y){return new DW(Y,this.config)}}class DW extends j{static[F]="PgSparseVector";dimensions=this.config.dimensions;getSQLType(){return`sparsevec(${this.dimensions})`}}function LW(Y,Z){let{name:X,config:_}=X0(Y,Z);return new EW(X,_)}class VW extends k{static[F]="PgVectorBuilder";constructor(Y,Z){super(Y,"array","PgVector");this.config.dimensions=Z.dimensions}build(Y){return new MW(Y,this.config)}}class MW extends j{static[F]="PgVector";dimensions=this.config.dimensions;getSQLType(){return`vector(${this.dimensions})`}mapToDriverValue(Y){return JSON.stringify(Y)}mapFromDriverValue(Y){return Y.slice(1,-1).split(",").map((Z)=>Number.parseFloat(Z))}}function AW(Y,Z){let{name:X,config:_}=X0(Y,Z);return new VW(X,_)}function wW(){return{bigint:P7,bigserial:f7,boolean:w2,char:p7,cidr:d7,customType:i7,date:r7,doublePrecision:t7,inet:Z3,integer:R2,interval:$3,json:J3,jsonb:z3,line:D3,macaddr:M3,macaddr8:R3,numeric:K3,point:v3,geometry:g3,real:m3,serial:c3,smallint:o3,smallserial:s3,text:e3,time:ZW,timestamp:GW,uuid:j1,varchar:e0,bit:zW,halfvec:OW,sparsevec:LW,vector:AW}}var D5=Symbol.for("drizzle:PgInlineForeignKeys"),RW=Symbol.for("drizzle:EnableRLS");class d0 extends P{static[F]="PgTable";static Symbol=Object.assign({},P.Symbol,{InlineForeignKeys:D5,EnableRLS:RW});[D5]=[];[RW]=!1;[P.Symbol.ExtraConfigBuilder]=void 0;[P.Symbol.ExtraConfigColumns]={}}function qF(Y,Z,X,_,G=Y){let W=new d0(Y,_,G),$=typeof Z==="function"?Z(wW()):Z,H=Object.fromEntries(Object.entries($).map(([z,O])=>{let D=O;D.setName(z);let V=D.build(W);return W[D5].push(...D.buildForeignKeys(V,W)),[z,V]})),Q=Object.fromEntries(Object.entries($).map(([z,O])=>{let D=O;D.setName(z);let V=D.buildExtraConfigColumn(W);return[z,V]})),J=Object.assign(W,H);if(J[P.Symbol.Columns]=H,J[P.Symbol.ExtraConfigColumns]=Q,X)J[d0.Symbol.ExtraConfigBuilder]=X;return Object.assign(J,{enableRLS:()=>{return J[d0.Symbol.EnableRLS]=!0,J}})}var B4=(Y,Z,X)=>{return qF(Y,Z,X,void 0)};function NW(...Y){if(Y[0].columns)return new N2(Y[0].columns,Y[0].name);return new N2(Y)}class N2{static[F]="PgPrimaryKeyBuilder";columns;name;constructor(Y,Z){this.columns=Y,this.name=Z}build(Y){return new IW(Y,this.columns,this.name)}}class IW{constructor(Y,Z,X){this.table=Y,this.columns=Z,this.name=X}static[F]="PgPrimaryKey";columns;name;getName(){return this.name??`${this.table[d0.Symbol.Name]}_${this.columns.map((Y)=>Y.name).join("_")}_pk`}}function V1(Y,Z){if(M7(Z)&&!J5(Y)&&!M(Y,N1)&&!M(Y,N4)&&!M(Y,E0)&&!M(Y,P)&&!M(Y,L1))return new N1(Y,Z);return Y}var y6=(Y,Z)=>{return E`${Y} = ${V1(Z,Y)}`},BW=(Y,Z)=>{return E`${Y} <> ${V1(Z,Y)}`};function I2(...Y){let Z=Y.filter((X)=>X!==void 0);if(Z.length===0)return;if(Z.length===1)return new x(Z);return new x([new u0("("),E.join(Z,new u0(" and ")),new u0(")")])}function CW(...Y){let Z=Y.filter((X)=>X!==void 0);if(Z.length===0)return;if(Z.length===1)return new x(Z);return new x([new u0("("),E.join(Z,new u0(" or ")),new u0(")")])}function TW(Y){return E`not ${Y}`}var KW=(Y,Z)=>{return E`${Y} > ${V1(Z,Y)}`},qW=(Y,Z)=>{return E`${Y} >= ${V1(Z,Y)}`},jW=(Y,Z)=>{return E`${Y} < ${V1(Z,Y)}`},PW=(Y,Z)=>{return E`${Y} <= ${V1(Z,Y)}`};function SW(Y,Z){if(Array.isArray(Z)){if(Z.length===0)return E`false`;return E`${Y} in ${Z.map((X)=>V1(X,Y))}`}return E`${Y} in ${V1(Z,Y)}`}function vW(Y,Z){if(Array.isArray(Z)){if(Z.length===0)return E`true`;return E`${Y} not in ${Z.map((X)=>V1(X,Y))}`}return E`${Y} not in ${V1(Z,Y)}`}function xW(Y){return E`${Y} is null`}function hW(Y){return E`${Y} is not null`}function fW(Y){return E`exists ${Y}`}function bW(Y){return E`not exists ${Y}`}function kW(Y,Z,X){return E`${Y} between ${V1(Z,Y)} and ${V1(X,Y)}`}function gW(Y,Z,X){return E`${Y} not between ${V1(Z,Y)} and ${V1(X,Y)}`}function yW(Y,Z){return E`${Y} like ${Z}`}function pW(Y,Z){return E`${Y} not like ${Z}`}function mW(Y,Z){return E`${Y} ilike ${Z}`}function uW(Y,Z){return E`${Y} not ilike ${Z}`}function dW(Y){return E`${Y} asc`}function cW(Y){return E`${Y} desc`}class L5{constructor(Y,Z,X){this.sourceTable=Y,this.referencedTable=Z,this.relationName=X,this.referencedTableName=Z[P.Symbol.Name]}static[F]="Relation";referencedTableName;fieldName}class lW{constructor(Y,Z){this.table=Y,this.config=Z}static[F]="Relations"}class C4 extends L5{constructor(Y,Z,X,_){super(Y,Z,X?.relationName);this.config=X,this.isNullable=_}static[F]="One";withFieldName(Y){let Z=new C4(this.sourceTable,this.referencedTable,this.config,this.isNullable);return Z.fieldName=Y,Z}}class B2 extends L5{constructor(Y,Z,X){super(Y,Z,X?.relationName);this.config=X}static[F]="Many";withFieldName(Y){let Z=new B2(this.sourceTable,this.referencedTable,this.config);return Z.fieldName=Y,Z}}function iW(){return{and:I2,between:kW,eq:y6,exists:fW,gt:KW,gte:qW,ilike:mW,inArray:SW,isNull:xW,isNotNull:hW,like:yW,lt:jW,lte:PW,ne:BW,not:TW,notBetween:gW,notExists:bW,notLike:pW,notIlike:uW,notInArray:vW,or:CW,sql:E}}function oW(){return{sql:E,asc:dW,desc:cW}}function nW(Y,Z){if(Object.keys(Y).length===1&&"default"in Y&&!M(Y.default,P))Y=Y.default;let X={},_={},G={};for(let[W,$]of Object.entries(Y))if(M($,P)){let H=y4($),Q=_[H];X[H]=W,G[W]={tsName:W,dbName:$[P.Symbol.Name],schema:$[P.Symbol.Schema],columns:$[P.Symbol.Columns],relations:Q?.relations??{},primaryKey:Q?.primaryKey??[]};for(let z of Object.values($[P.Symbol.Columns]))if(z.primary)G[W].primaryKey.push(z);let J=$[P.Symbol.ExtraConfigBuilder]?.($[P.Symbol.ExtraConfigColumns]);if(J){for(let z of Object.values(J))if(M(z,N2))G[W].primaryKey.push(...z.columns)}}else if(M($,lW)){let H=y4($.table),Q=X[H],J=$.config(Z($.table)),z;for(let[O,D]of Object.entries(J))if(Q){let V=G[Q];if(V.relations[O]=D,z)V.primaryKey.push(...z)}else{if(!(H in _))_[H]={relations:{},primaryKey:z};_[H].relations[O]=D}}return{tables:G,tableNamesMap:X}}function jF(Y){return function Z(X,_){return new C4(Y,X,_,_?.fields.reduce((G,W)=>G&&W.notNull,!0)??!1)}}function PF(Y){return function Z(X,_){return new B2(Y,X,_)}}function rW(Y,Z,X){if(M(X,C4)&&X.config)return{fields:X.config.fields,references:X.config.references};let _=Z[y4(X.referencedTable)];if(!_)throw new Error(`Table "${X.referencedTable[P.Symbol.Name]}" not found in schema`);let G=Y[_];if(!G)throw new Error(`Table "${_}" not found in schema`);let W=X.sourceTable,$=Z[y4(W)];if(!$)throw new Error(`Table "${W[P.Symbol.Name]}" not found in schema`);let H=[];for(let Q of Object.values(G.relations))if(X.relationName&&X!==Q&&Q.relationName===X.relationName||!X.relationName&&Q.referencedTable===X.sourceTable)H.push(Q);if(H.length>1)throw X.relationName?new Error(`There are multiple relations with name "${X.relationName}" in table "${_}"`):new Error(`There are multiple relations between "${_}" and "${X.sourceTable[P.Symbol.Name]}". Please specify relation name`);if(H[0]&&M(H[0],C4)&&H[0].config)return{fields:H[0].config.references,references:H[0].config.fields};throw new Error(`There is not enough information to infer relation "${$}.${X.fieldName}"`)}function sW(Y){return{one:jF(Y),many:PF(Y)}}function p6(Y,Z,X,_,G=(W)=>W){let W={};for(let[$,H]of _.entries())if(H.isJson){let Q=Z.relations[H.tsKey],J=X[$],z=typeof J==="string"?JSON.parse(J):J;W[H.tsKey]=M(Q,C4)?z&&p6(Y,Y[H.relationTableTsKey],z,H.selection,G):z.map((O)=>p6(Y,Y[H.relationTableTsKey],O,H.selection,G))}else{let Q=G(X[$]),J=H.field,z;if(M(J,E0))z=J;else if(M(J,x))z=J.decoder;else z=J.sql.decoder;W[H.tsKey]=Q===null?null:z.mapFromDriverValue(Q)}return W}import YO from"os";import ZO from"fs";var m6=new Map,V5=new Map,M5=Symbol("OriginError"),N8={};class P1 extends Promise{constructor(Y,Z,X,_,G={}){let W,$;super((H,Q)=>{W=H,$=Q});this.tagged=Array.isArray(Y.raw),this.strings=Y,this.args=Z,this.handler=X,this.canceller=_,this.options=G,this.state=null,this.statement=null,this.resolve=(H)=>(this.active=!1,W(H)),this.reject=(H)=>(this.active=!1,$(H)),this.active=!1,this.cancelled=null,this.executed=!1,this.signature="",this[M5]=this.handler.debug?new Error:this.tagged&&SF(this.strings)}get origin(){return(this.handler.debug?this[M5].stack:this.tagged&&V5.has(this.strings)?V5.get(this.strings):V5.set(this.strings,this[M5].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(Y=1,Z){if(this.options.simple=!1,typeof Y==="function")Z=Y,Y=1;if(this.cursorRows=Y,typeof Z==="function")return this.cursorFn=Z,this;let X;return{[Symbol.asyncIterator]:()=>({next:()=>{if(this.executed&&!this.active)return{done:!0};X&&X();let _=new Promise((G,W)=>{this.cursorFn=($)=>{return G({value:$,done:!1}),new Promise((H)=>X=H)},this.resolve=()=>(this.active=!1,G({done:!0})),this.reject=($)=>(this.active=!1,W($))});return this.execute(),_},return(){return X&&X(N8),{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(Y){return this.forEachFn=Y,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 SF(Y){if(m6.has(Y))return m6.get(Y);let Z=Error.stackTraceLimit;return Error.stackTraceLimit=4,m6.set(Y,new Error),Error.stackTraceLimit=Z,m6.get(Y)}class I8 extends Error{constructor(Y){super(Y.message);this.name=this.constructor.name,Object.assign(this,Y)}}var f0={connection:aW,postgres:tW,generic:eW,notSupported:Y$};function aW(Y,Z,X){let{host:_,port:G}=X||Z,W=Object.assign(new Error("write "+Y+" "+(Z.path||_+":"+G)),{code:Y,errno:Y,address:Z.path||_},Z.path?{}:{port:G});return Error.captureStackTrace(W,aW),W}function tW(Y){let Z=new I8(Y);return Error.captureStackTrace(Z,tW),Z}function eW(Y,Z){let X=Object.assign(new Error(Y+": "+Z),{code:Y});return Error.captureStackTrace(X,eW),X}function Y$(Y){let Z=Object.assign(new Error(Y+" (B) is not supported"),{code:"MESSAGE_NOT_SUPPORTED",name:Y});return Error.captureStackTrace(Z,Y$),Z}var vF={string:{to:25,from:null,serialize:(Y)=>""+Y},number:{to:0,from:[21,23,26,700,701],serialize:(Y)=>""+Y,parse:(Y)=>+Y},json:{to:114,from:[114,3802],serialize:(Y)=>JSON.stringify(Y),parse:(Y)=>JSON.parse(Y)},boolean:{to:16,from:16,serialize:(Y)=>Y===!0?"t":"f",parse:(Y)=>Y==="t"},date:{to:1184,from:[1082,1114,1184],serialize:(Y)=>(Y instanceof Date?Y:new Date(Y)).toISOString(),parse:(Y)=>new Date(Y)},bytea:{to:17,from:17,serialize:(Y)=>"\\x"+Buffer.from(Y).toString("hex"),parse:(Y)=>Buffer.from(Y.slice(2),"hex")}};class c6{then(){A5()}catch(){A5()}finally(){A5()}}class q2 extends c6{constructor(Y){super();this.value=o6(Y)}}class n1 extends c6{constructor(Y,Z,X){super();this.value=Y,this.type=Z,this.array=X}}class l6 extends c6{constructor(Y,Z){super();this.first=Y,this.rest=Z}build(Y,Z,X,_){let G=xF.map(([W,$])=>({fn:$,i:Y.search(W)})).sort((W,$)=>W.i-$.i).pop();return G.i===-1?B5(this.first,_):G.fn(this.first,this.rest,Z,X,_)}}function i6(Y,Z,X,_){let G=Y instanceof n1?Y.value:Y;if(G===void 0){if(Y instanceof n1?Y.value=_.transform.undefined:G=Y=_.transform.undefined,G===void 0)throw f0.generic("UNDEFINED_VALUE","Undefined values are not allowed")}return"$"+X.push(Y instanceof n1?(Z.push(Y.value),Y.array?Y.array[Y.type||d6(Y.value)]||Y.type||G$(Y.value):Y.type):(Z.push(Y),d6(Y)))}var X$=$$(vF);function N5(Y,Z,X,_,G,W){for(let $=1;$<Y.strings.length;$++)Z+=I5(Z,X,_,G,W)+Y.strings[$],X=Y.args[$];return Z}function I5(Y,Z,X,_,G){return Z instanceof l6?Z.build(Y,X,_,G):Z instanceof P1?R5(Z,X,_,G):Z instanceof q2?Z.value:Z&&Z[0]instanceof P1?Z.reduce((W,$)=>W+" "+R5($,X,_,G),""):i6(Z,X,_,G)}function R5(Y,Z,X,_){return Y.fragment=!0,N5(Y,Y.strings[0],Y.args[0],Z,X,_)}function _$(Y,Z,X,_,G){return Y.map((W)=>"("+_.map(($)=>I5("values",W[$],Z,X,G)).join(",")+")").join(",")}function Z$(Y,Z,X,_,G){let W=Array.isArray(Y[0]),$=Z.length?Z.flat():Object.keys(W?Y[0]:Y);return _$(W?Y:[Y],X,_,$,G)}function u6(Y,Z,X,_,G){if(typeof Y==="string"&&(Y=[Y].concat(Z)),Array.isArray(Y))return B5(Y,G);let W;return(Z.length?Z.flat():Object.keys(Y)).map((H)=>{return W=Y[H],(W instanceof P1?R5(W,X,_,G):W instanceof q2?W.value:i6(W,X,_,G))+" as "+o6(G.transform.column.to?G.transform.column.to(H):H)}).join(",")}var xF=Object.entries({values:Z$,in:(...Y)=>{let Z=Z$(...Y);return Z==="()"?"(null)":Z},select:u6,as:u6,returning:u6,"\\(":u6,update(Y,Z,X,_,G){return(Z.length?Z.flat():Object.keys(Y)).map((W)=>o6(G.transform.column.to?G.transform.column.to(W):W)+"="+I5("values",Y[W],X,_,G))},insert(Y,Z,X,_,G){let W=Z.length?Z.flat():Object.keys(Array.isArray(Y)?Y[0]:Y);return"("+B5(W,G)+")values"+_$(Array.isArray(Y)?Y:[Y],X,_,W,G)}}).map(([Y,Z])=>[new RegExp("((?:^|[\\s(])"+Y+"(?:$|[\\s(]))(?![\\s\\S]*\\1)","i"),Z]);function A5(){throw f0.generic("NOT_TAGGED_CALL","Query not called as a tagged template literal")}var{serializers:hF,parsers:fF}=X$;function G$(Y){if(Array.isArray(Y))return G$(Y[0]);return typeof Y==="string"?1009:0}var W$=function(Y){let Z=$$(Y||{});return{serializers:Object.assign({},hF,Z.serializers),parsers:Object.assign({},fF,Z.parsers)}};function $$(Y){return Object.keys(Y).reduce((Z,X)=>{if(Y[X].from&&[].concat(Y[X].from).forEach((_)=>Z.parsers[_]=Y[X].parse),Y[X].serialize)Z.serializers[Y[X].to]=Y[X].serialize,Y[X].from&&[].concat(Y[X].from).forEach((_)=>Z.serializers[_]=Y[X].serialize);return Z},{parsers:{},serializers:{}})}function B5(Y,{transform:{column:Z}}){return Y.map((X)=>o6(Z.to?Z.to(X):X)).join(",")}var o6=function Y(Z){return'"'+Z.replace(/"/g,'""').replace(/\./g,'"."')+'"'},d6=function Y(Z){return Z instanceof n1?Z.type:Z instanceof Date?1184:Z instanceof Uint8Array?17:Z===!0||Z===!1?16:typeof Z==="bigint"?20:Array.isArray(Z)?Y(Z[0]):0},bF=/\\/g,kF=/"/g;function gF(Y){return Y.replace(bF,"\\\\").replace(kF,"\\\"")}var H$=function Y(Z,X,_,G){if(Array.isArray(Z)===!1)return Z;if(!Z.length)return"{}";let W=Z[0],$=G===1020?";":",";if(Array.isArray(W)&&!W.type)return"{"+Z.map((H)=>Y(H,X,_,G)).join($)+"}";return"{"+Z.map((H)=>{if(H===void 0){if(H=_.transform.undefined,H===void 0)throw f0.generic("UNDEFINED_VALUE","Undefined values are not allowed")}return H===null?"null":'"'+gF(X?X(H.type?H.value:H):""+H)+'"'}).join($)+"}"},w5={i:0,char:null,str:"",quoted:!1,last:0},J$=function Y(Z,X,_){return w5.i=w5.last=0,Q$(w5,Z,X,_)};function Q$(Y,Z,X,_){let G=[],W=_===1020?";":",";for(;Y.i<Z.length;Y.i++){if(Y.char=Z[Y.i],Y.quoted)if(Y.char==="\\")Y.str+=Z[++Y.i];else if(Y.char==='"')G.push(X?X(Y.str):Y.str),Y.str="",Y.quoted=Z[Y.i+1]==='"',Y.last=Y.i+2;else Y.str+=Y.char;else if(Y.char==='"')Y.quoted=!0;else if(Y.char==="{")Y.last=++Y.i,G.push(Q$(Y,Z,X,_));else if(Y.char==="}"){Y.quoted=!1,Y.last<Y.i&&G.push(X?X(Z.slice(Y.last,Y.i)):Z.slice(Y.last,Y.i)),Y.last=Y.i+1;break}else if(Y.char===W&&Y.p!=="}"&&Y.p!=='"')G.push(X?X(Z.slice(Y.last,Y.i)):Z.slice(Y.last,Y.i)),Y.last=Y.i+1;Y.p=Y.char}return Y.last<Y.i&&G.push(X?X(Z.slice(Y.last,Y.i+1)):Z.slice(Y.last,Y.i+1)),G}var p4=(Y)=>{let Z=Y[0];for(let X=1;X<Y.length;X++)Z+=Y[X]==="_"?Y[++X].toUpperCase():Y[X];return Z},m4=(Y)=>{let Z=Y[0].toUpperCase();for(let X=1;X<Y.length;X++)Z+=Y[X]==="_"?Y[++X].toUpperCase():Y[X];return Z},u4=(Y)=>Y.replace(/_/g,"-"),C2=(Y)=>Y.replace(/([A-Z])/g,"_$1").toLowerCase(),T2=(Y)=>(Y.slice(0,1)+Y.slice(1).replace(/([A-Z])/g,"_$1")).toLowerCase(),K2=(Y)=>Y.replace(/-/g,"_");function C5(Y){return function Z(X,_){return typeof X==="object"&&X!==null&&(_.type===114||_.type===3802)?Array.isArray(X)?X.map((G)=>Z(G,_)):Object.entries(X).reduce((G,[W,$])=>Object.assign(G,{[Y(W)]:Z($,_)}),{}):X}}p4.column={from:p4};p4.value={from:C5(p4)};C2.column={to:C2};var T5={...p4};T5.column.to=C2;m4.column={from:m4};m4.value={from:C5(m4)};T2.column={to:T2};var K5={...m4};K5.column.to=T2;u4.column={from:u4};u4.value={from:C5(u4)};K2.column={to:K2};var q5={...u4};q5.column.to=K2;import z$ from"net";import uF from"tls";import j2 from"crypto";import j5 from"stream";import{performance as U$}from"perf_hooks";class d4 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 I1=yF;function yF(Y=[]){let Z=Y.slice(),X=0;return{get length(){return Z.length-X},remove:(_)=>{let G=Z.indexOf(_);return G===-1?null:(Z.splice(G,1),_)},push:(_)=>(Z.push(_),_),shift:()=>{let _=Z[X++];if(X===Z.length)X=0,Z=[];else Z[X-1]=void 0;return _}}}var Y1=Buffer.allocUnsafe(256),pF="BCcDdEFfHPpQSX".split("").reduce((Y,Z)=>{let X=Z.charCodeAt(0);return Y[Z]=()=>{return Y1[0]=X,U0.i=5,U0},Y},{}),U0=Object.assign(mF,pF,{N:String.fromCharCode(0),i:0,inc(Y){return U0.i+=Y,U0},str(Y){let Z=Buffer.byteLength(Y);return n6(Z),U0.i+=Y1.write(Y,U0.i,Z,"utf8"),U0},i16(Y){return n6(2),Y1.writeUInt16BE(Y,U0.i),U0.i+=2,U0},i32(Y,Z){if(Z||Z===0)return Y1.writeUInt32BE(Y,Z),U0;return n6(4),Y1.writeUInt32BE(Y,U0.i),U0.i+=4,U0},z(Y){return n6(Y),Y1.fill(0,U0.i,U0.i+Y),U0.i+=Y,U0},raw(Y){return Y1=Buffer.concat([Y1.subarray(0,U0.i),Y]),U0.i=Y1.length,U0},end(Y=1){Y1.writeUInt32BE(U0.i-Y,Y);let Z=Y1.subarray(0,U0.i);return U0.i=0,Y1=Buffer.allocUnsafe(256),Z}}),c=U0;function n6(Y){if(Y1.length-U0.i<Y){let Z=Y1,X=Z.length;Y1=Buffer.allocUnsafe(X+(X>>1)+Y),Z.copy(Y1)}}function mF(){return U0.i=0,U0}var v5=E$,dF=1,T4=c().S().end(),F$=c().H().end(),cF=c().i32(8).i32(80877103).end(8),lF=Buffer.concat([c().E().str(c.N).i32(0).end(),T4]),iF=c().D().str("S").str(c.N).end(),B8=()=>{},oF=new Set(["FetchPreparedStatement","RevalidateCachedQuery","transformAssignedExpr"]),nF={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 E$(Y,Z={},{onopen:X=B8,onend:_=B8,onclose:G=B8}={}){let{ssl:W,max:$,user:H,host:Q,port:J,database:z,parsers:O,transform:D,onnotice:V,onnotify:R,onparameter:A,max_pipeline:g,keep_alive:b,backoff:f,target_session_attrs:h}=Y,I=I1(),N=dF++,q={pid:null,secret:null},K=S5(JY,Y.idle_timeout),p=S5(JY,Y.max_lifetime),s=S5(k$,Y.connect_timeout),C=null,t,m=new d4,e=Buffer.alloc(0),F0=Y.fetch_types,b0={},J1={},r1=Math.random().toString(36).slice(2),T=1,u=0,G0=0,C0=0,k0=0,a=0,Q0=0,S0=0,T0=null,w0=null,n0=!1,L0=null,S1=null,l0=null,z4=null,g0=null,R0=null,v1=null,m1=null,v=null,q8=null,r0={queue:Z.closed,idleTimer:K,connect(U){l0=U,WX()},terminate:P8,execute:j8,cancel:x$,end:JY,count:0,id:N};return Z.closed&&Z.closed.push(r0),r0;async function v$(){let U;try{U=Y.socket?await Promise.resolve(Y.socket(Y)):new z$.Socket}catch(L){o4(L);return}return U.on("error",o4),U.on("close",$X),U.on("drain",_X),U}async function x$({pid:U,secret:L},l,W0){try{t=c().i32(16).i32(80877102).i32(U).i32(L).end(16),await GX(),C.once("error",W0),C.once("close",l)}catch(q0){W0(q0)}}function j8(U){if(n0)return k2(U,f0.connection("CONNECTION_DESTROYED",Y));if(U.cancelled)return;try{return U.state=q,v?I.push(U):(v=U,v.active=!0),b$(U),i0(h$(U))&&!U.describeFirst&&!U.cursorFn&&I.length<g&&(!U.options.onexecute||U.options.onexecute(r0))}catch(L){return I.length===0&&i0(T4),u1(L),!0}}function h$(U){if(U.parameters.length>=65534)throw f0.generic("MAX_PARAMETERS_EXCEEDED","Max number of parameters (65534) exceeded");return U.options.simple?c().Q().str(U.statement.string+c.N).end():U.describeFirst?Buffer.concat([YX(U),F$]):U.prepare?U.prepared?b2(U):Buffer.concat([YX(U),b2(U)]):f$(U)}function YX(U){return Buffer.concat([JX(U.statement.string,U.parameters,U.statement.types,U.statement.name),RH("S",U.statement.name)])}function b2(U){return Buffer.concat([wH(U.parameters,U.statement.types,U.statement.name,U.cursorName),U.cursorFn?QX("",U.cursorRows):lF])}function f$(U){return Buffer.concat([JX(U.statement.string,U.parameters,U.statement.types),iF,b2(U)])}function b$(U){let L=[],l=[],W0=N5(U,U.strings[0],U.args[0],L,l,Y);!U.tagged&&U.args.forEach((q0)=>i6(q0,L,l,Y)),U.prepare=Y.prepare&&("prepare"in U.options?U.options.prepare:!0),U.string=W0,U.signature=U.prepare&&l+W0,U.onlyDescribe&&delete J1[U.signature],U.parameters=U.parameters||L,U.prepared=U.prepare&&U.signature in J1,U.describeFirst=U.onlyDescribe||L.length&&!U.prepared,U.statement=U.prepared?J1[U.signature]:{string:W0,types:l,name:U.prepare?r1+T++:""},typeof Y.debug==="function"&&Y.debug(N,W0,L,l)}function i0(U,L){if(R0=R0?Buffer.concat([R0,U]):Buffer.from(U),L||R0.length>=1024)return ZX(L);return w0===null&&(w0=setImmediate(ZX)),!0}function ZX(U){let L=C.write(R0,U);return w0!==null&&clearImmediate(w0),R0=w0=null,L}function k$(){u1(f0.connection("CONNECT_TIMEOUT",Y,C)),C.destroy()}async function XX(){if(i0(cF),!await new Promise((L)=>C.once("data",(l)=>L(l[0]===83)))&&W==="prefer")return i4();C.removeAllListeners(),C=uF.connect({socket:C,servername:z$.isIP(C.host)?void 0:C.host,...W==="require"||W==="allow"||W==="prefer"?{rejectUnauthorized:!1}:W==="verify-full"?{}:typeof W==="object"?W:{}}),C.on("secureConnect",i4),C.on("error",o4),C.on("close",$X),C.on("drain",_X)}function _X(){!v&&X(r0)}function HY(U){if(L0){if(L0.push(U),G0-=U.length,G0>0)return}e=L0?Buffer.concat(L0,a-G0):e.length===0?U:Buffer.concat([e,U],e.length+U.length);while(e.length>4){if(a=e.readUInt32BE(1),a>=e.length){G0=a-e.length,L0=[e];break}try{g$(e.subarray(0,a+1))}catch(L){v&&(v.cursorFn||v.describeFirst)&&i0(T4),u1(L)}e=e.subarray(a+1),G0=0,L0=null}}async function GX(){if(n0=!1,b0={},C||(C=await v$()),!C)return;if(s.start(),Y.socket)return W?XX():i4();if(C.on("connect",W?XX:i4),Y.path)return C.connect(Y.path);C.ssl=W,C.connect(J[C0],Q[C0]),C.host=Q[C0],C.port=J[C0],C0=(C0+1)%J.length}function WX(){setTimeout(GX,u?u+Q0-U$.now():0)}function i4(){try{J1={},F0=Y.fetch_types,r1=Math.random().toString(36).slice(2),T=1,p.start(),C.on("data",HY),b&&C.setKeepAlive&&C.setKeepAlive(!0,1000*b);let U=IH();i0(U)}catch(U){o4(U)}}function o4(U){if(r0.queue===Z.connecting&&Y.host[k0+1])return;u1(U);while(I.length)k2(I.shift(),U)}function u1(U){g0&&(g0.destroy(U),g0=null),v&&k2(v,U),l0&&(k2(l0,U),l0=null)}function k2(U,L){if(U.reserve)return U.reject(L);if(!L||typeof L!=="object")L=new Error(L);"query"in L||"parameters"in L||Object.defineProperties(L,{stack:{value:L.stack+U.origin.replace(/.*\n/,`
63
+ `),enumerable:Y.debug},query:{value:U.string,enumerable:Y.debug},parameters:{value:U.parameters,enumerable:Y.debug},args:{value:U.args,enumerable:Y.debug},types:{value:U.statement&&U.statement.types,enumerable:Y.debug}}),U.reject(L)}function JY(){return z4||(!r0.reserved&&_(r0),!r0.reserved&&!l0&&!v&&I.length===0?(P8(),new Promise((U)=>C&&C.readyState!=="closed"?C.once("close",U):U())):z4=new Promise((U)=>v1=U))}function P8(){if(n0=!0,g0||v||l0||I.length)o4(f0.connection("CONNECTION_DESTROYED",Y));if(clearImmediate(w0),C)C.removeListener("data",HY),C.removeListener("connect",i4),C.readyState==="open"&&C.end(c().X().end());v1&&(v1(),z4=v1=null)}async function $X(U){if(e=Buffer.alloc(0),G0=0,L0=null,clearImmediate(w0),C.removeListener("data",HY),C.removeListener("connect",i4),K.cancel(),p.cancel(),s.cancel(),C.removeAllListeners(),C=null,l0)return WX();!U&&(v||I.length)&&o4(f0.connection("CONNECTION_CLOSED",Y,C)),u=U$.now(),U&&Y.shared.retries++,Q0=(typeof f==="function"?f(Y.shared.retries):f)*1000,G(r0,f0.connection("CONNECTION_CLOSED",Y,C))}function g$(U,L=U[0]){(L===68?y$:L===100?FH:L===65?$H:L===83?p$:L===90?m$:L===67?u$:L===50?HX:L===49?d$:L===116?c$:L===84?l$:L===82?i$:L===110?t$:L===75?e$:L===69?GH:L===115?HH:L===51?JH:L===71?QH:L===78?EH:L===72?zH:L===99?OH:L===73?DH:L===86?LH:L===118?VH:L===87?UH:MH)(U)}function y$(U){let L=7,l,W0,q0,s0=v.isRaw?new Array(v.statement.columns.length):{};for(let Z1=0;Z1<v.statement.columns.length;Z1++)W0=v.statement.columns[Z1],l=U.readInt32BE(L),L+=4,q0=l===-1?null:v.isRaw===!0?U.subarray(L,L+=l):W0.parser===void 0?U.toString("utf8",L,L+=l):W0.parser.array===!0?W0.parser(U.toString("utf8",L+1,L+=l)):W0.parser(U.toString("utf8",L,L+=l)),v.isRaw?s0[Z1]=v.isRaw===!0?q0:D.value.from?D.value.from(q0,W0):q0:s0[W0.name]=D.value.from?D.value.from(q0,W0):q0;v.forEachFn?v.forEachFn(D.row.from?D.row.from(s0):s0,m):m[S0++]=D.row.from?D.row.from(s0):s0}function p$(U){let[L,l]=U.toString("utf8",5,U.length-1).split(c.N);if(b0[L]=l,Y.parameters[L]!==l)Y.parameters[L]=l,A&&A(L,l)}function m$(U){if(v&&v.options.simple&&v.resolve(S1||m),v=S1=null,m=new d4,s.cancel(),l0){if(h){if(!b0.in_hot_standby||!b0.default_transaction_read_only)return _H();else if(XH(h,b0))return P8()}if(F0)return l0.reserve&&(l0=null),YH();l0&&!l0.reserve&&j8(l0),Y.shared.retries=k0=0,l0=null;return}while(I.length&&(v=I.shift())&&(v.active=!0,v.cancelled))E$(Y).cancel(v.state,v.cancelled.resolve,v.cancelled.reject);if(v)return;r0.reserved?!r0.reserved.release&&U[5]===73?z4?P8():(r0.reserved=null,X(r0)):r0.reserved():z4?P8():X(r0)}function u$(U){S0=0;for(let L=U.length-1;L>0;L--){if(U[L]===32&&U[L+1]<58&&m.count===null)m.count=+U.toString("utf8",L+1,U.length-1);if(U[L-1]>=65){m.command=U.toString("utf8",5,L),m.state=q;break}}if(q8&&(q8(),q8=null),m.command==="BEGIN"&&$!==1&&!r0.reserved)return u1(f0.generic("UNSAFE_TRANSACTION","Only use sql.begin, sql.reserved or max: 1"));if(v.options.simple)return HX();if(v.cursorFn)m.count&&v.cursorFn(m),i0(T4);v.resolve(m)}function d$(){v.parsing=!1}function HX(){!m.statement&&(m.statement=v.statement),m.columns=v.statement.columns}function c$(U){let L=U.readUInt16BE(5);for(let l=0;l<L;++l)!v.statement.types[l]&&(v.statement.types[l]=U.readUInt32BE(7+l*4));v.prepare&&(J1[v.signature]=v.statement),v.describeFirst&&!v.onlyDescribe&&(i0(b2(v)),v.describeFirst=!1)}function l$(U){if(m.command)S1=S1||[m],S1.push(m=new d4),m.count=null,v.statement.columns=null;let L=U.readUInt16BE(5),l=7,W0;v.statement.columns=Array(L);for(let q0=0;q0<L;++q0){W0=l;while(U[l++]!==0);let s0=U.readUInt32BE(l),Z1=U.readUInt16BE(l+4),U4=U.readUInt32BE(l+6);v.statement.columns[q0]={name:D.column.from?D.column.from(U.toString("utf8",W0,l-1)):U.toString("utf8",W0,l-1),parser:O[U4],table:s0,number:Z1,type:U4},l+=18}if(m.statement=v.statement,v.onlyDescribe)return v.resolve(v.statement),i0(T4)}async function i$(U,L=U.readUInt32BE(5)){(L===3?o$:L===5?n$:L===10?r$:L===11?s$:L===12?a$:L!==0?AH:B8)(U,L)}async function o$(){let U=await QY();i0(c().p().str(U).z(1).end())}async function n$(U){let L="md5"+await O$(Buffer.concat([Buffer.from(await O$(await QY()+H)),U.subarray(9)]));i0(c().p().str(L).z(1).end())}async function r$(){m1=(await j2.randomBytes(18)).toString("base64"),c().p().str("SCRAM-SHA-256"+c.N);let U=c.i;i0(c.inc(4).str("n,,n=*,r="+m1).i32(c.i-U-4,U).end())}async function s$(U){let L=U.toString("utf8",9).split(",").reduce((Z1,U4)=>(Z1[U4[0]]=U4.slice(2),Z1),{}),l=await j2.pbkdf2Sync(await QY(),Buffer.from(L.s,"base64"),parseInt(L.i),32,"sha256"),W0=await r6(l,"Client Key"),q0="n=*,r="+m1+",r="+L.r+",s="+L.s+",i="+L.i+",c=biws,r="+L.r;T0=(await r6(await r6(l,"Server Key"),q0)).toString("base64");let s0="c=biws,r="+L.r+",p="+sF(W0,Buffer.from(await r6(await rF(W0),q0))).toString("base64");i0(c().p().str(s0).end())}function a$(U){if(U.toString("utf8",9).split(c.N,1)[0].slice(2)===T0)return;u1(f0.generic("SASL_SIGNATURE_MISMATCH","The server did not return the correct signature")),C.destroy()}function QY(){return Promise.resolve(typeof Y.pass==="function"?Y.pass():Y.pass)}function t$(){if(m.statement=v.statement,m.statement.columns=[],v.onlyDescribe)return v.resolve(v.statement),i0(T4)}function e$(U){q.pid=U.readUInt32BE(5),q.secret=U.readUInt32BE(9)}async function YH(){F0=!1,(await new P1([`
64
64
  select b.oid, b.typarray
65
65
  from pg_catalog.pg_type a
66
66
  left join pg_catalog.pg_type b on b.oid = a.typelem
67
67
  where a.typcategory = 'A'
68
68
  group by b.oid, b.typarray
69
69
  order by b.oid
70
- `],[],q8)).forEach(({oid:L,typarray:l})=>_J(L,l))}function _J(F,L){if(!!Y.parsers[L]&&!!Y.serializers[L])return;let l=Y.parsers[F];Y.shared.typeArrayMap[F]=L,Y.parsers[L]=(W0)=>zH(W0,l,L),Y.parsers[L].array=!0,Y.serializers[L]=(W0)=>$H(W0,Y.serializers[F],Y,L)}function GJ(F,L){return F==="read-write"&&L.default_transaction_read_only==="on"||F==="read-only"&&L.default_transaction_read_only==="off"||F==="primary"&&L.in_hot_standby==="on"||F==="standby"&&L.in_hot_standby==="off"||F==="prefer-standby"&&L.in_hot_standby==="off"&&Y.host[k0]}function WJ(){let F=new P1([`
70
+ `],[],j8)).forEach(({oid:L,typarray:l})=>ZH(L,l))}function ZH(U,L){if(!!Y.parsers[L]&&!!Y.serializers[L])return;let l=Y.parsers[U];Y.shared.typeArrayMap[U]=L,Y.parsers[L]=(W0)=>J$(W0,l,L),Y.parsers[L].array=!0,Y.serializers[L]=(W0)=>H$(W0,Y.serializers[U],Y,L)}function XH(U,L){return U==="read-write"&&L.default_transaction_read_only==="on"||U==="read-only"&&L.default_transaction_read_only==="off"||U==="primary"&&L.in_hot_standby==="on"||U==="standby"&&L.in_hot_standby==="off"||U==="prefer-standby"&&L.in_hot_standby==="off"&&Y.host[k0]}function _H(){let U=new P1([`
71
71
  show transaction_read_only;
72
72
  select pg_catalog.pg_is_in_recovery()
73
- `],[],q8,null,{simple:!0});F.resolve=([[L],[l]])=>{b0.default_transaction_read_only=L.transaction_read_only,b0.in_hot_standby=l.pg_is_in_recovery?"on":"off"},F.execute()}function HJ(F){v&&(v.cursorFn||v.describeFirst)&&i0(T4);let L=f0.postgres(PX(F));v&&v.retried?u1(v.retried):v&&v.prepared&&rU.has(L.routine)?JJ(v,L):u1(L)}function JJ(F,L){delete Q1[F.signature],F.retried=L,q8(F)}function QJ(F){if(!R)return;let L=9;while(F[L++]!==0);R(F.toString("utf8",9,L-1),F.toString("utf8",L,F.length-1))}async function $J(){try{let F=await Promise.resolve(v.cursorFn(m));S0=0,F===R8?i0(BJ(v.portal)):(m=new d4,i0($_("",v.cursorRows)))}catch(F){i0(T4),v.reject(F)}}function zJ(){m.count&&v.cursorFn(m),v.resolve(m)}function FJ(){g0=new jX.Writable({autoDestroy:!0,write(F,L,l){C.write(c().d().raw(F).end(),l)},destroy(F,L){L(F),C.write(c().f().str(F+c.N).end()),g0=null},final(F){C.write(c().c().end()),K8=F}}),v.resolve(g0)}function UJ(){g0=new jX.Readable({read(){C.resume()}}),v.resolve(g0)}function OJ(){g0=new jX.Duplex({autoDestroy:!0,read(){C.resume()},write(F,L,l){C.write(c().d().raw(F).end(),l)},destroy(F,L){L(F),C.write(c().f().str(F+c.N).end()),g0=null},final(F){C.write(c().c().end()),K8=F}}),v.resolve(g0)}function EJ(F){g0&&(g0.push(F.subarray(5))||C.pause())}function DJ(){g0&&g0.push(null),g0=null}function LJ(F){V?V(PX(F)):console.log(PX(F))}function VJ(){}function MJ(){u1(f0.notSupported("FunctionCallResponse"))}function AJ(){u1(f0.notSupported("NegotiateProtocolVersion"))}function wJ(F){console.error("Postgres.js : Unknown Message:",F[0])}function RJ(F,L){console.error("Postgres.js : Unknown Auth:",L)}function NJ(F,L,l="",W0=""){let q0,s0;return c().B().str(W0+c.N).str(l+c.N).i16(0).i16(F.length),F.forEach((Z1,F4)=>{if(Z1===null)return c.i32(4294967295);s0=L[F4],F[F4]=Z1=s0 in Y.serializers?Y.serializers[s0](Z1):""+Z1,q0=c.i,c.inc(4).str(Z1).i32(c.i-q0-4,q0)}),c.i16(0),c.end()}function Q_(F,L,l,W0=""){return c().P().str(W0+c.N).str(F+c.N).i16(L.length),L.forEach((q0,s0)=>c.i32(l[s0]||0)),c.end()}function IJ(F,L=""){return c().D().str(F).str(L+c.N).end()}function $_(F="",L=0){return Buffer.concat([c().E().str(F+c.N).i32(L).end(),EH])}function BJ(F=""){return Buffer.concat([c().C().str("P").str(F+c.N).end(),c().S().end()])}function CJ(){return t||c().inc(4).i16(3).z(2).str(Object.entries(Object.assign({user:J,database:z,client_encoding:"UTF8"},Y.connection)).filter(([,F])=>F).map(([F,L])=>F+c.N+L).join(c.N)).z(2).end(0)}}function PX(Y){let Z={},X=5;for(let _=5;_<Y.length-1;_++)if(Y[_]===0)Z[sU[Y[X]]]=Y.toString("utf8",X+1,_),X=_+1;return Z}function DH(Y){return j6.createHash("md5").update(Y).digest("hex")}function nY(Y,Z){return j6.createHmac("sha256",Y).update(Z).digest()}function aU(Y){return j6.createHash("sha256").update(Y).digest()}function tU(Y,Z){let X=Math.max(Y.length,Z.length),_=Buffer.allocUnsafe(X);for(let G=0;G<X;G++)_[G]=Y[G]^Z[G];return _}function SX(Y,Z){if(Z=typeof Z==="function"?Z():Z,!Z)return{cancel:I8,start:I8};let X;return{cancel(){X&&(clearTimeout(X),X=null)},start(){X&&clearTimeout(X),X=setTimeout(_,Z*1000,arguments)}};function _(G){Y.apply(null,G),X=null}}var VH=()=>{};function xX(Y,Z){let X=new Map,_="postgresjs_"+Math.random().toString(36).slice(2),G={},W,H,J=!1,$=O.sql=Y({...Z,transform:{column:{},value:{},row:{}},max:1,fetch_types:!1,idle_timeout:null,max_lifetime:null,connection:{...Z.connection,replication:"database"},onclose:async function(){if(J)return;H=null,G.pid=G.secret=void 0,D(await V($,_,Z.publications)),X.forEach((A)=>A.forEach(({onsubscribe:g})=>g()))},no_subscribe:!0}),Q=$.end,z=$.close;return $.end=async()=>{return J=!0,H&&await new Promise((A)=>(H.once("close",A),H.end())),Q()},$.close=async()=>{return H&&await new Promise((A)=>(H.once("close",A),H.end())),z()},O;async function O(A,g,b=VH,f=VH){if(A=ZO(A),!W)W=V($,_,Z.publications);let h={fn:g,onsubscribe:b},I=X.has(A)?X.get(A).add(h):X.set(A,new Set([h])).get(A),N=()=>{I.delete(h),I.size===0&&X.delete(A)};return W.then((q)=>{return D(q),b(),H&&H.on("error",f),{unsubscribe:N,state:G,sql:$}})}function D(A){H=A.stream,G.pid=A.state.pid,G.secret=A.state.secret}async function V(A,g,b){if(!b)throw new Error("Missing publication names");let f=await A.unsafe(`CREATE_REPLICATION_SLOT ${g} TEMPORARY LOGICAL pgoutput NOEXPORT_SNAPSHOT`),[h]=f,I=await A.unsafe(`START_REPLICATION SLOT ${g} LOGICAL ${h.consistent_point} (proto_version '1', publication_names '${b}')`).writable(),N={lsn:Buffer.concat(h.consistent_point.split("/").map((C)=>Buffer.from(("00000000"+C).slice(-8),"hex")))};return I.on("data",K),I.on("error",q),I.on("close",A.close),{stream:I,state:f.state};function q(C){console.error("Unexpected error during logical streaming - reconnecting",C)}function K(C){if(C[0]===119)YO(C.subarray(25),N,A.options.parsers,p,Z.transform);else if(C[0]===107&&C[17])N.lsn=C.subarray(1,9),s()}function p(C,t){let m=t.relation.schema+"."+t.relation.table;R("*",C,t),R("*:"+m,C,t),t.relation.keys.length&&R("*:"+m+"="+t.relation.keys.map((e)=>C[e.name]),C,t),R(t.command,C,t),R(t.command+":"+m,C,t),t.relation.keys.length&&R(t.command+":"+m+"="+t.relation.keys.map((e)=>C[e.name]),C,t)}function s(){let C=Buffer.alloc(34);C[0]=114,C.fill(N.lsn,1),C.writeBigInt64BE(BigInt(Date.now()-Date.UTC(2000,0,1))*BigInt(1000),25),I.write(C)}}function R(A,g,b){X.has(A)&&X.get(A).forEach(({fn:f})=>f(g,b,A))}}function eU(Y){return new Date(Date.UTC(2000,0,1)+Number(Y/BigInt(1000)))}function YO(Y,Z,X,_,G){let W=(H,[J,$])=>(H[J.charCodeAt(0)]=$,H);Object.entries({R:(H)=>{let J=1,$=Z[H.readUInt32BE(J)]={schema:H.toString("utf8",J+=4,J=H.indexOf(0,J))||"pg_catalog",table:H.toString("utf8",J+1,J=H.indexOf(0,J+1)),columns:Array(H.readUInt16BE(J+=2)),keys:[]};J+=2;let Q=0,z;while(J<H.length)z=$.columns[Q++]={key:H[J++],name:G.column.from?G.column.from(H.toString("utf8",J,J=H.indexOf(0,J))):H.toString("utf8",J,J=H.indexOf(0,J)),type:H.readUInt32BE(J+=1),parser:X[H.readUInt32BE(J)],atttypmod:H.readUInt32BE(J+=4)},z.key&&$.keys.push(z),J+=4},Y:()=>{},O:()=>{},B:(H)=>{Z.date=eU(H.readBigInt64BE(9)),Z.lsn=H.subarray(1,9)},I:(H)=>{let J=1,$=Z[H.readUInt32BE(J)],{row:Q}=rY(H,$.columns,J+=7,G);_(Q,{command:"insert",relation:$})},D:(H)=>{let J=1,$=Z[H.readUInt32BE(J)];J+=4;let Q=H[J]===75;_(Q||H[J]===79?rY(H,$.columns,J+=3,G).row:null,{command:"delete",relation:$,key:Q})},U:(H)=>{let J=1,$=Z[H.readUInt32BE(J)];J+=4;let Q=H[J]===75,z=Q||H[J]===79?rY(H,$.columns,J+=3,G):null;z&&(J=z.i);let{row:O}=rY(H,$.columns,J+3,G);_(O,{command:"update",relation:$,key:Q,old:z&&z.row})},T:()=>{},C:()=>{}}).reduce(W,{})[Y[0]](Y)}function rY(Y,Z,X,_){let G,W,H,J=_.raw?new Array(Z.length):{};for(let $=0;$<Z.length;$++)G=Y[X++],W=Z[$],H=G===110?null:G===117?void 0:W.parser===void 0?Y.toString("utf8",X+4,X+=4+Y.readUInt32BE(X)):W.parser.array===!0?W.parser(Y.toString("utf8",X+5,X+=4+Y.readUInt32BE(X))):W.parser(Y.toString("utf8",X+4,X+=4+Y.readUInt32BE(X))),_.raw?J[$]=_.raw===!0?H:_.value.from?_.value.from(H,W):H:J[W.name]=_.value.from?_.value.from(H,W):H;return{i:X,row:_.row.from?_.row.from(J):J}}function ZO(Y){let Z=Y.match(/^(\*|insert|update|delete)?:?([^.]+?\.?[^=]+)?=?(.+)?/i)||[];if(!Z)throw new Error("Malformed subscribe pattern: "+Y);let[,X,_,G]=Z;return(X||"*")+(_?":"+(_.indexOf(".")===-1?"public."+_:_):"")+(G?"="+G:"")}import MH from"stream";function hX(Y,Z,X=393216){return new Promise(async(_,G)=>{await Y.begin(async(W)=>{let H;!Z&&([{oid:Z}]=await W`select lo_creat(-1) as oid`);let[{fd:J}]=await W`select lo_open(${Z}, ${X}) as fd`,$={writable:z,readable:Q,close:()=>W`select lo_close(${J})`.then(H),tell:()=>W`select lo_tell64(${J})`,read:(O)=>W`select loread(${J}, ${O}) as data`,write:(O)=>W`select lowrite(${J}, ${O})`,truncate:(O)=>W`select lo_truncate64(${J}, ${O})`,seek:(O,D=0)=>W`select lo_lseek64(${J}, ${O}, ${D})`,size:()=>W`
73
+ `],[],j8,null,{simple:!0});U.resolve=([[L],[l]])=>{b0.default_transaction_read_only=L.transaction_read_only,b0.in_hot_standby=l.pg_is_in_recovery?"on":"off"},U.execute()}function GH(U){v&&(v.cursorFn||v.describeFirst)&&i0(T4);let L=f0.postgres(P5(U));v&&v.retried?u1(v.retried):v&&v.prepared&&oF.has(L.routine)?WH(v,L):u1(L)}function WH(U,L){delete J1[U.signature],U.retried=L,j8(U)}function $H(U){if(!R)return;let L=9;while(U[L++]!==0);R(U.toString("utf8",9,L-1),U.toString("utf8",L,U.length-1))}async function HH(){try{let U=await Promise.resolve(v.cursorFn(m));S0=0,U===N8?i0(NH(v.portal)):(m=new d4,i0(QX("",v.cursorRows)))}catch(U){i0(T4),v.reject(U)}}function JH(){m.count&&v.cursorFn(m),v.resolve(m)}function QH(){g0=new j5.Writable({autoDestroy:!0,write(U,L,l){C.write(c().d().raw(U).end(),l)},destroy(U,L){L(U),C.write(c().f().str(U+c.N).end()),g0=null},final(U){C.write(c().c().end()),q8=U}}),v.resolve(g0)}function zH(){g0=new j5.Readable({read(){C.resume()}}),v.resolve(g0)}function UH(){g0=new j5.Duplex({autoDestroy:!0,read(){C.resume()},write(U,L,l){C.write(c().d().raw(U).end(),l)},destroy(U,L){L(U),C.write(c().f().str(U+c.N).end()),g0=null},final(U){C.write(c().c().end()),q8=U}}),v.resolve(g0)}function FH(U){g0&&(g0.push(U.subarray(5))||C.pause())}function OH(){g0&&g0.push(null),g0=null}function EH(U){V?V(P5(U)):console.log(P5(U))}function DH(){}function LH(){u1(f0.notSupported("FunctionCallResponse"))}function VH(){u1(f0.notSupported("NegotiateProtocolVersion"))}function MH(U){console.error("Postgres.js : Unknown Message:",U[0])}function AH(U,L){console.error("Postgres.js : Unknown Auth:",L)}function wH(U,L,l="",W0=""){let q0,s0;return c().B().str(W0+c.N).str(l+c.N).i16(0).i16(U.length),U.forEach((Z1,U4)=>{if(Z1===null)return c.i32(4294967295);s0=L[U4],U[U4]=Z1=s0 in Y.serializers?Y.serializers[s0](Z1):""+Z1,q0=c.i,c.inc(4).str(Z1).i32(c.i-q0-4,q0)}),c.i16(0),c.end()}function JX(U,L,l,W0=""){return c().P().str(W0+c.N).str(U+c.N).i16(L.length),L.forEach((q0,s0)=>c.i32(l[s0]||0)),c.end()}function RH(U,L=""){return c().D().str(U).str(L+c.N).end()}function QX(U="",L=0){return Buffer.concat([c().E().str(U+c.N).i32(L).end(),F$])}function NH(U=""){return Buffer.concat([c().C().str("P").str(U+c.N).end(),c().S().end()])}function IH(){return t||c().inc(4).i16(3).z(2).str(Object.entries(Object.assign({user:H,database:z,client_encoding:"UTF8"},Y.connection)).filter(([,U])=>U).map(([U,L])=>U+c.N+L).join(c.N)).z(2).end(0)}}function P5(Y){let Z={},X=5;for(let _=5;_<Y.length-1;_++)if(Y[_]===0)Z[nF[Y[X]]]=Y.toString("utf8",X+1,_),X=_+1;return Z}function O$(Y){return j2.createHash("md5").update(Y).digest("hex")}function r6(Y,Z){return j2.createHmac("sha256",Y).update(Z).digest()}function rF(Y){return j2.createHash("sha256").update(Y).digest()}function sF(Y,Z){let X=Math.max(Y.length,Z.length),_=Buffer.allocUnsafe(X);for(let G=0;G<X;G++)_[G]=Y[G]^Z[G];return _}function S5(Y,Z){if(Z=typeof Z==="function"?Z():Z,!Z)return{cancel:B8,start:B8};let X;return{cancel(){X&&(clearTimeout(X),X=null)},start(){X&&clearTimeout(X),X=setTimeout(_,Z*1000,arguments)}};function _(G){Y.apply(null,G),X=null}}var D$=()=>{};function x5(Y,Z){let X=new Map,_="postgresjs_"+Math.random().toString(36).slice(2),G={},W,$,H=!1,Q=O.sql=Y({...Z,transform:{column:{},value:{},row:{}},max:1,fetch_types:!1,idle_timeout:null,max_lifetime:null,connection:{...Z.connection,replication:"database"},onclose:async function(){if(H)return;$=null,G.pid=G.secret=void 0,D(await V(Q,_,Z.publications)),X.forEach((A)=>A.forEach(({onsubscribe:g})=>g()))},no_subscribe:!0}),J=Q.end,z=Q.close;return Q.end=async()=>{return H=!0,$&&await new Promise((A)=>($.once("close",A),$.end())),J()},Q.close=async()=>{return $&&await new Promise((A)=>($.once("close",A),$.end())),z()},O;async function O(A,g,b=D$,f=D$){if(A=eF(A),!W)W=V(Q,_,Z.publications);let h={fn:g,onsubscribe:b},I=X.has(A)?X.get(A).add(h):X.set(A,new Set([h])).get(A),N=()=>{I.delete(h),I.size===0&&X.delete(A)};return W.then((q)=>{return D(q),b(),$&&$.on("error",f),{unsubscribe:N,state:G,sql:Q}})}function D(A){$=A.stream,G.pid=A.state.pid,G.secret=A.state.secret}async function V(A,g,b){if(!b)throw new Error("Missing publication names");let f=await A.unsafe(`CREATE_REPLICATION_SLOT ${g} TEMPORARY LOGICAL pgoutput NOEXPORT_SNAPSHOT`),[h]=f,I=await A.unsafe(`START_REPLICATION SLOT ${g} LOGICAL ${h.consistent_point} (proto_version '1', publication_names '${b}')`).writable(),N={lsn:Buffer.concat(h.consistent_point.split("/").map((C)=>Buffer.from(("00000000"+C).slice(-8),"hex")))};return I.on("data",K),I.on("error",q),I.on("close",A.close),{stream:I,state:f.state};function q(C){console.error("Unexpected error during logical streaming - reconnecting",C)}function K(C){if(C[0]===119)tF(C.subarray(25),N,A.options.parsers,p,Z.transform);else if(C[0]===107&&C[17])N.lsn=C.subarray(1,9),s()}function p(C,t){let m=t.relation.schema+"."+t.relation.table;R("*",C,t),R("*:"+m,C,t),t.relation.keys.length&&R("*:"+m+"="+t.relation.keys.map((e)=>C[e.name]),C,t),R(t.command,C,t),R(t.command+":"+m,C,t),t.relation.keys.length&&R(t.command+":"+m+"="+t.relation.keys.map((e)=>C[e.name]),C,t)}function s(){let C=Buffer.alloc(34);C[0]=114,C.fill(N.lsn,1),C.writeBigInt64BE(BigInt(Date.now()-Date.UTC(2000,0,1))*BigInt(1000),25),I.write(C)}}function R(A,g,b){X.has(A)&&X.get(A).forEach(({fn:f})=>f(g,b,A))}}function aF(Y){return new Date(Date.UTC(2000,0,1)+Number(Y/BigInt(1000)))}function tF(Y,Z,X,_,G){let W=($,[H,Q])=>($[H.charCodeAt(0)]=Q,$);Object.entries({R:($)=>{let H=1,Q=Z[$.readUInt32BE(H)]={schema:$.toString("utf8",H+=4,H=$.indexOf(0,H))||"pg_catalog",table:$.toString("utf8",H+1,H=$.indexOf(0,H+1)),columns:Array($.readUInt16BE(H+=2)),keys:[]};H+=2;let J=0,z;while(H<$.length)z=Q.columns[J++]={key:$[H++],name:G.column.from?G.column.from($.toString("utf8",H,H=$.indexOf(0,H))):$.toString("utf8",H,H=$.indexOf(0,H)),type:$.readUInt32BE(H+=1),parser:X[$.readUInt32BE(H)],atttypmod:$.readUInt32BE(H+=4)},z.key&&Q.keys.push(z),H+=4},Y:()=>{},O:()=>{},B:($)=>{Z.date=aF($.readBigInt64BE(9)),Z.lsn=$.subarray(1,9)},I:($)=>{let H=1,Q=Z[$.readUInt32BE(H)],{row:J}=s6($,Q.columns,H+=7,G);_(J,{command:"insert",relation:Q})},D:($)=>{let H=1,Q=Z[$.readUInt32BE(H)];H+=4;let J=$[H]===75;_(J||$[H]===79?s6($,Q.columns,H+=3,G).row:null,{command:"delete",relation:Q,key:J})},U:($)=>{let H=1,Q=Z[$.readUInt32BE(H)];H+=4;let J=$[H]===75,z=J||$[H]===79?s6($,Q.columns,H+=3,G):null;z&&(H=z.i);let{row:O}=s6($,Q.columns,H+3,G);_(O,{command:"update",relation:Q,key:J,old:z&&z.row})},T:()=>{},C:()=>{}}).reduce(W,{})[Y[0]](Y)}function s6(Y,Z,X,_){let G,W,$,H=_.raw?new Array(Z.length):{};for(let Q=0;Q<Z.length;Q++)G=Y[X++],W=Z[Q],$=G===110?null:G===117?void 0:W.parser===void 0?Y.toString("utf8",X+4,X+=4+Y.readUInt32BE(X)):W.parser.array===!0?W.parser(Y.toString("utf8",X+5,X+=4+Y.readUInt32BE(X))):W.parser(Y.toString("utf8",X+4,X+=4+Y.readUInt32BE(X))),_.raw?H[Q]=_.raw===!0?$:_.value.from?_.value.from($,W):$:H[W.name]=_.value.from?_.value.from($,W):$;return{i:X,row:_.row.from?_.row.from(H):H}}function eF(Y){let Z=Y.match(/^(\*|insert|update|delete)?:?([^.]+?\.?[^=]+)?=?(.+)?/i)||[];if(!Z)throw new Error("Malformed subscribe pattern: "+Y);let[,X,_,G]=Z;return(X||"*")+(_?":"+(_.indexOf(".")===-1?"public."+_:_):"")+(G?"="+G:"")}import L$ from"stream";function h5(Y,Z,X=393216){return new Promise(async(_,G)=>{await Y.begin(async(W)=>{let $;!Z&&([{oid:Z}]=await W`select lo_creat(-1) as oid`);let[{fd:H}]=await W`select lo_open(${Z}, ${X}) as fd`,Q={writable:z,readable:J,close:()=>W`select lo_close(${H})`.then($),tell:()=>W`select lo_tell64(${H})`,read:(O)=>W`select loread(${H}, ${O}) as data`,write:(O)=>W`select lowrite(${H}, ${O})`,truncate:(O)=>W`select lo_truncate64(${H}, ${O})`,seek:(O,D=0)=>W`select lo_lseek64(${H}, ${O}, ${D})`,size:()=>W`
74
74
  select
75
- lo_lseek64(${J}, location, 0) as position,
75
+ lo_lseek64(${H}, location, 0) as position,
76
76
  seek.size
77
77
  from (
78
78
  select
@@ -80,10 +80,10 @@ params: ${Z}`);if(this.query=Y,this.params=Z,this.cause=X,Error.captureStackTrac
80
80
  tell.location
81
81
  from (select lo_tell64($1) as location) tell
82
82
  ) seek
83
- `};return _($),new Promise(async(O)=>H=O);async function Q({highWaterMark:O=16384,start:D=0,end:V=1/0}={}){let R=V-D;return D&&await $.seek(D),new MH.Readable({highWaterMark:O,async read(A){let g=A>R?A-R:A;R-=A;let[{data:b}]=await $.read(g);if(this.push(b),b.length<A)this.push(null)}})}async function z({highWaterMark:O=16384,start:D=0}={}){return D&&await $.seek(D),new MH.Writable({highWaterMark:O,write(V,R,A){$.write(V).then(()=>A(),A)}})}}).catch(G)})}Object.assign(sY,{PostgresError:N8,toPascal:m4,pascal:KX,toCamel:p4,camel:TX,toKebab:u4,kebab:qX,fromPascal:T6,fromCamel:C6,fromKebab:K6,BigInt:{to:20,from:[20],parse:(Y)=>BigInt(Y),serialize:(Y)=>Y.toString()}});var B8=sY;function sY(Y,Z){let X=GO(Y,Z),_=X.no_subscribe||xX(sY,{...X}),G=!1,W=I1(),H=I1(),J=I1(),$=I1(),Q=I1(),z=I1(),O=I1(),D=I1(),V={connecting:H,reserved:J,closed:$,ended:Q,open:z,busy:O,full:D},R=[...Array(X.max)].map(()=>vX(X,V,{onopen:Q1,onend:b0,onclose:r1})),A=g(p);return Object.assign(A,{get parameters(){return X.parameters},largeObject:hX.bind(null,A),subscribe:_,CLOSE:R8,END:R8,PostgresError:N8,options:X,reserve:h,listen:b,begin:I,close:m,end:t}),A;function g(T){return T.debug=X.debug,Object.entries(X.types).reduce((a,[$0,S0])=>{return a[$0]=(T0)=>new n1(T0,S0.to),a},u),Object.assign(G0,{types:u,typed:u,unsafe:C0,notify:f,array:K,json:q,file:k0}),G0;function u(a,$0){return new n1(a,$0)}function G0(a,...$0){return a&&Array.isArray(a.raw)?new P1(a,$0,T,C):typeof a==="string"&&!$0.length?new q6(X.transform.column.to?X.transform.column.to(a):a):new cY(a,$0)}function C0(a,$0=[],S0={}){return arguments.length===2&&!Array.isArray($0)&&(S0=$0,$0=[]),new P1([a],$0,T,C,{prepare:!1,...S0,simple:"simple"in S0?S0.simple:$0.length===0})}function k0(a,$0=[],S0={}){return arguments.length===2&&!Array.isArray($0)&&(S0=$0,$0=[]),new P1([],$0,(w0)=>{_O.readFile(a,"utf8",(n0,L0)=>{if(n0)return w0.reject(n0);w0.strings=[L0],T(w0)})},C,{...S0,simple:"simple"in S0?S0.simple:$0.length===0})}}async function b(T,u,G0){let C0={fn:u,onlisten:G0},k0=b.sql||(b.sql=sY({...X,max:1,idle_timeout:null,max_lifetime:null,fetch_types:!1,onclose(){Object.entries(b.channels).forEach(([w0,{listeners:n0}])=>{delete b.channels[w0],Promise.all(n0.map((L0)=>b(w0,L0.fn,L0.onlisten).catch(()=>{})))})},onnotify(w0,n0){w0 in b.channels&&b.channels[w0].listeners.forEach((L0)=>L0.fn(n0))}})),a=b.channels||(b.channels={});if(T in a){a[T].listeners.push(C0);let w0=await a[T].result;return C0.onlisten&&C0.onlisten(),{state:w0.state,unlisten:T0}}a[T]={result:k0`listen ${k0.unsafe('"'+T.replace(/"/g,'""')+'"')}`,listeners:[C0]};let S0=await a[T].result;return C0.onlisten&&C0.onlisten(),{state:S0.state,unlisten:T0};async function T0(){if(T in a===!1)return;if(a[T].listeners=a[T].listeners.filter((w0)=>w0!==C0),a[T].listeners.length)return;return delete a[T],k0`unlisten ${k0.unsafe('"'+T.replace(/"/g,'""')+'"')}`}}async function f(T,u){return await A`select pg_notify(${T}, ${""+u})`}async function h(){let T=I1(),u=z.length?z.shift():await new Promise((k0,a)=>{let $0={reserve:k0,reject:a};W.push($0),$.length&&U0($.shift(),$0)});N(u,J),u.reserved=()=>T.length?u.execute(T.shift()):N(u,J),u.reserved.release=!0;let G0=g(C0);return G0.release=()=>{u.reserved=null,Q1(u)},G0;function C0(k0){u.queue===D?T.push(k0):u.execute(k0)||N(u,D)}}async function I(T,u){!u&&(u=T,T="");let G0=I1(),C0=0,k0,a=null;try{return await A.unsafe("begin "+T.replace(/[^a-z ]/ig,""),[],{onexecute:S0}).execute(),await Promise.race([$0(k0,u),new Promise((T0,w0)=>k0.onclose=w0)])}catch(T0){throw T0}async function $0(T0,w0,n0){let L0=g(g0);L0.savepoint=z4,L0.prepare=(R0)=>a=R0.replace(/[^a-z0-9$-_. ]/gi);let S1,l0;n0&&await L0`savepoint ${L0(n0)}`;try{if(l0=await new Promise((R0,v1)=>{let m1=w0(L0);Promise.resolve(Array.isArray(m1)?Promise.all(m1):m1).then(R0,v1)}),S1)throw S1}catch(R0){throw await(n0?L0`rollback to ${L0(n0)}`:L0`rollback`),R0 instanceof N8&&R0.code==="25P02"&&S1||R0}if(!n0)a?await L0`prepare transaction '${L0.unsafe(a)}'`:await L0`commit`;return l0;function z4(R0,v1){if(R0&&Array.isArray(R0.raw))return z4((m1)=>m1.apply(m1,arguments));return arguments.length===1&&(v1=R0,R0=null),$0(T0,v1,"s"+C0+++(R0?"_"+R0:""))}function g0(R0){R0.catch((v1)=>S1||(S1=v1)),T0.queue===D?G0.push(R0):T0.execute(R0)||N(T0,D)}}function S0(T0){k0=T0,N(T0,J),T0.reserved=()=>G0.length?T0.execute(G0.shift()):N(T0,J)}}function N(T,u){return T.queue.remove(T),u.push(T),T.queue=u,u===z?T.idleTimer.start():T.idleTimer.cancel(),T}function q(T){return new n1(T,3802)}function K(T,u){if(!Array.isArray(T))return K(Array.from(arguments));return new n1(T,u||(T.length?uY(T)||25:0),X.shared.typeArrayMap)}function p(T){if(G)return T.reject(f0.connection("CONNECTION_ENDED",X,X));if(z.length)return s(z.shift(),T);if($.length)return U0($.shift(),T);O.length?s(O.shift(),T):W.push(T)}function s(T,u){return T.execute(u)?N(T,O):N(T,D)}function C(T){return new Promise((u,G0)=>{T.state?T.active?vX(X).cancel(T.state,u,G0):T.cancelled={resolve:u,reject:G0}:(W.remove(T),T.cancelled=!0,T.reject(f0.generic("57014","canceling statement due to user request")),u())})}async function t({timeout:T=null}={}){if(G)return G;await 1;let u;return G=Promise.race([new Promise((G0)=>T!==null&&(u=setTimeout(e,T*1000,G0))),Promise.all(R.map((G0)=>G0.end()).concat(b.sql?b.sql.end({timeout:0}):[],_.sql?_.sql.end({timeout:0}):[]))]).then(()=>clearTimeout(u))}async function m(){await Promise.all(R.map((T)=>T.end()))}async function e(T){await Promise.all(R.map((u)=>u.terminate()));while(W.length)W.shift().reject(f0.connection("CONNECTION_DESTROYED",X));T()}function U0(T,u){return N(T,H),T.connect(u),T}function b0(T){N(T,Q)}function Q1(T){if(W.length===0)return N(T,z);let u=Math.ceil(W.length/(H.length+1)),G0=!0;while(G0&&W.length&&u-- >0){let C0=W.shift();if(C0.reserve)return C0.reserve(T);G0=T.execute(C0)}G0?N(T,O):N(T,D)}function r1(T,u){N(T,$),T.reserved=null,T.onclose&&(T.onclose(u),T.onclose=null),X.onclose&&X.onclose(T.id),W.length&&U0(T,W.shift())}}function GO(Y,Z){if(Y&&Y.shared)return Y;let X=process.env,_=(!Y||typeof Y==="string"?Z:Y)||{},{url:G,multihost:W}=$O(Y),H=[...G.searchParams].reduce((D,[V,R])=>(D[V]=R,D),{}),J=_.hostname||_.host||W||G.hostname||X.PGHOST||"localhost",$=_.port||G.port||X.PGPORT||5432,Q=_.user||_.username||G.username||X.PGUSERNAME||X.PGUSER||zO();_.no_prepare&&(_.prepare=!1),H.sslmode&&(H.ssl=H.sslmode,delete H.sslmode),"timeout"in _&&(console.log("The timeout option is deprecated, use idle_timeout instead"),_.idle_timeout=_.timeout),H.sslrootcert==="system"&&(H.ssl="verify-full");let z=["idle_timeout","connect_timeout","max_lifetime","max_pipeline","backoff","keep_alive"],O={max:10,ssl:!1,idle_timeout:null,connect_timeout:30,max_lifetime:JO,max_pipeline:100,backoff:HO,keep_alive:60,prepare:!0,debug:!1,fetch_types:!0,publications:"alltables",target_session_attrs:null};return{host:Array.isArray(J)?J:J.split(",").map((D)=>D.split(":")[0]),port:Array.isArray($)?$:J.split(",").map((D)=>parseInt(D.split(":")[1]||$)),path:_.path||J.indexOf("/")>-1&&J+"/.s.PGSQL."+$,database:_.database||_.db||(G.pathname||"").slice(1)||X.PGDATABASE||Q,user:Q,pass:_.pass||_.password||G.password||X.PGPASSWORD||"",...Object.entries(O).reduce((D,[V,R])=>{let A=V in _?_[V]:(V in H)?H[V]==="disable"||H[V]==="false"?!1:H[V]:X["PG"+V.toUpperCase()]||R;return D[V]=typeof A==="string"&&z.includes(V)?+A:A,D},{}),connection:{application_name:X.PGAPPNAME||"postgres.js",..._.connection,...Object.entries(H).reduce((D,[V,R])=>((V in O)||(D[V]=R),D),{})},types:_.types||{},target_session_attrs:WO(_,G,X),onnotice:_.onnotice,onnotify:_.onnotify,onclose:_.onclose,onparameter:_.onparameter,socket:_.socket,transform:QO(_.transform||{undefined:void 0}),parameters:{},shared:{retries:0,typeArrayMap:{}},...JH(_.types)}}function WO(Y,Z,X){let _=Y.target_session_attrs||Z.searchParams.get("target_session_attrs")||X.PGTARGETSESSIONATTRS;if(!_||["read-write","read-only","primary","standby","prefer-standby"].includes(_))return _;throw new Error("target_session_attrs "+_+" is not supported")}function HO(Y){return(0.5+Math.random()/2)*Math.min(3**Y/100,20)}function JO(){return 60*(30+Math.random()*30)}function QO(Y){return{undefined:Y.undefined,column:{from:typeof Y.column==="function"?Y.column:Y.column&&Y.column.from,to:Y.column&&Y.column.to},value:{from:typeof Y.value==="function"?Y.value:Y.value&&Y.value.from,to:Y.value&&Y.value.to},row:{from:typeof Y.row==="function"?Y.row:Y.row&&Y.row.from,to:Y.row&&Y.row.to}}}function $O(Y){if(!Y||typeof Y!=="string")return{url:{searchParams:new Map}};let Z=Y;Z=Z.slice(Z.indexOf("://")+3).split(/[?/]/)[0],Z=decodeURIComponent(Z.slice(Z.indexOf("@")+1));let X=new URL(Y.replace(Z,Z.split(",")[0]));return{url:{username:decodeURIComponent(X.username),password:decodeURIComponent(X.password),host:X.host,hostname:X.hostname,port:X.port,pathname:X.pathname,searchParams:X.searchParams},multihost:Z.indexOf(",")>-1&&Z}}function zO(){try{return XO.userInfo().username}catch(Y){return process.env.USERNAME||process.env.USER||process.env.LOGNAME}}class j0{static[U]="SelectionProxyHandler";config;constructor(Y){this.config={...Y}}get(Y,Z){if(Z==="_")return{...Y._,selectedFields:new Proxy(Y._.selectedFields,this)};if(Z===A0)return{...Y[A0],selectedFields:new Proxy(Y[A0].selectedFields,this)};if(typeof Z==="symbol")return Y[Z];let _=(M(Y,P0)?Y._.selectedFields:M(Y,L1)?Y[A0].selectedFields:Y)[Z];if(M(_,x.Aliased)){if(this.config.sqlAliasedBehavior==="sql"&&!_.isSelectionField)return _.sql;let G=_.clone();return G.isSelectionField=!0,G}if(M(_,x)){if(this.config.sqlBehavior==="sql")return _;throw new Error(`You tried to reference "${Z}" 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(M(_,E0)){if(this.config.alias)return new Proxy(_,new w8(new Proxy(_.table,new V6(this.config.alias,this.config.replaceOriginalName??!1))));return _}if(typeof _!=="object"||_===null)return _;return new Proxy(_,new j0(this.config))}}class AH{constructor(Y,Z){this.unique=Y,this.name=Z}static[U]="PgIndexBuilderOn";on(...Y){return new aY(Y.map((Z)=>{if(M(Z,x))return Z;Z=Z;let X=new O6(Z.name,!!Z.keyAsName,Z.columnType,Z.indexConfig);return Z.indexConfig=JSON.parse(JSON.stringify(Z.defaultConfig)),X}),this.unique,!1,this.name)}onOnly(...Y){return new aY(Y.map((Z)=>{if(M(Z,x))return Z;Z=Z;let X=new O6(Z.name,!!Z.keyAsName,Z.columnType,Z.indexConfig);return Z.indexConfig=Z.defaultConfig,X}),this.unique,!0,this.name)}using(Y,...Z){return new aY(Z.map((X)=>{if(M(X,x))return X;X=X;let _=new O6(X.name,!!X.keyAsName,X.columnType,X.indexConfig);return X.indexConfig=JSON.parse(JSON.stringify(X.defaultConfig)),_}),this.unique,!0,this.name,Y)}}class aY{static[U]="PgIndexBuilder";config;constructor(Y,Z,X,_,G="btree"){this.config={name:_,columns:Y,unique:Z,only:X,method:G}}concurrently(){return this.config.concurrently=!0,this}with(Y){return this.config.with=Y,this}where(Y){return this.config.where=Y,this}build(Y){return new wH(this.config,Y)}}class wH{static[U]="PgIndex";config;constructor(Y,Z){this.config={...Y,table:Z}}}function fX(Y){return new AH(!0,Y)}function FO(Y){return(Y.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).map((X)=>X.toLowerCase()).join("_")}function UO(Y){return(Y.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).reduce((X,_,G)=>{let W=G===0?_.toLowerCase():`${_[0].toUpperCase()}${_.slice(1)}`;return X+W},"")}function OO(Y){return Y}class bX{static[U]="CasingCache";cache={};cachedTables={};convert;constructor(Y){this.convert=Y==="snake_case"?FO:Y==="camelCase"?UO:OO}getColumnCasing(Y){if(!Y.keyAsName)return Y.name;let Z=Y.table[P.Symbol.Schema]??"public",X=Y.table[P.Symbol.OriginalName],_=`${Z}.${X}.${Y.name}`;if(!this.cache[_])this.cacheTable(Y.table);return this.cache[_]}cacheTable(Y){let Z=Y[P.Symbol.Schema]??"public",X=Y[P.Symbol.OriginalName],_=`${Z}.${X}`;if(!this.cachedTables[_]){for(let G of Object.values(Y[P.Symbol.Columns])){let W=`${_}.${G.name}`;this.cache[W]=this.convert(G.name)}this.cachedTables[_]=!0}}clearCache(){this.cache={},this.cachedTables={}}}class P6 extends L1{static[U]="PgViewBase"}class c4{static[U]="PgDialect";casing;constructor(Y){this.casing=new bX(Y?.casing)}async migrate(Y,Z,X){let _=typeof X==="string"?"__drizzle_migrations":X.migrationsTable??"__drizzle_migrations",G=typeof X==="string"?"drizzle":X.migrationsSchema??"drizzle",W=E`
83
+ `};return _(Q),new Promise(async(O)=>$=O);async function J({highWaterMark:O=16384,start:D=0,end:V=1/0}={}){let R=V-D;return D&&await Q.seek(D),new L$.Readable({highWaterMark:O,async read(A){let g=A>R?A-R:A;R-=A;let[{data:b}]=await Q.read(g);if(this.push(b),b.length<A)this.push(null)}})}async function z({highWaterMark:O=16384,start:D=0}={}){return D&&await Q.seek(D),new L$.Writable({highWaterMark:O,write(V,R,A){Q.write(V).then(()=>A(),A)}})}}).catch(G)})}Object.assign(a6,{PostgresError:I8,toPascal:m4,pascal:K5,toCamel:p4,camel:T5,toKebab:u4,kebab:q5,fromPascal:T2,fromCamel:C2,fromKebab:K2,BigInt:{to:20,from:[20],parse:(Y)=>BigInt(Y),serialize:(Y)=>Y.toString()}});var C8=a6;function a6(Y,Z){let X=XO(Y,Z),_=X.no_subscribe||x5(a6,{...X}),G=!1,W=I1(),$=I1(),H=I1(),Q=I1(),J=I1(),z=I1(),O=I1(),D=I1(),V={connecting:$,reserved:H,closed:Q,ended:J,open:z,busy:O,full:D},R=[...Array(X.max)].map(()=>v5(X,V,{onopen:J1,onend:b0,onclose:r1})),A=g(p);return Object.assign(A,{get parameters(){return X.parameters},largeObject:h5.bind(null,A),subscribe:_,CLOSE:N8,END:N8,PostgresError:I8,options:X,reserve:h,listen:b,begin:I,close:m,end:t}),A;function g(T){return T.debug=X.debug,Object.entries(X.types).reduce((a,[Q0,S0])=>{return a[Q0]=(T0)=>new n1(T0,S0.to),a},u),Object.assign(G0,{types:u,typed:u,unsafe:C0,notify:f,array:K,json:q,file:k0}),G0;function u(a,Q0){return new n1(a,Q0)}function G0(a,...Q0){return a&&Array.isArray(a.raw)?new P1(a,Q0,T,C):typeof a==="string"&&!Q0.length?new q2(X.transform.column.to?X.transform.column.to(a):a):new l6(a,Q0)}function C0(a,Q0=[],S0={}){return arguments.length===2&&!Array.isArray(Q0)&&(S0=Q0,Q0=[]),new P1([a],Q0,T,C,{prepare:!1,...S0,simple:"simple"in S0?S0.simple:Q0.length===0})}function k0(a,Q0=[],S0={}){return arguments.length===2&&!Array.isArray(Q0)&&(S0=Q0,Q0=[]),new P1([],Q0,(w0)=>{ZO.readFile(a,"utf8",(n0,L0)=>{if(n0)return w0.reject(n0);w0.strings=[L0],T(w0)})},C,{...S0,simple:"simple"in S0?S0.simple:Q0.length===0})}}async function b(T,u,G0){let C0={fn:u,onlisten:G0},k0=b.sql||(b.sql=a6({...X,max:1,idle_timeout:null,max_lifetime:null,fetch_types:!1,onclose(){Object.entries(b.channels).forEach(([w0,{listeners:n0}])=>{delete b.channels[w0],Promise.all(n0.map((L0)=>b(w0,L0.fn,L0.onlisten).catch(()=>{})))})},onnotify(w0,n0){w0 in b.channels&&b.channels[w0].listeners.forEach((L0)=>L0.fn(n0))}})),a=b.channels||(b.channels={});if(T in a){a[T].listeners.push(C0);let w0=await a[T].result;return C0.onlisten&&C0.onlisten(),{state:w0.state,unlisten:T0}}a[T]={result:k0`listen ${k0.unsafe('"'+T.replace(/"/g,'""')+'"')}`,listeners:[C0]};let S0=await a[T].result;return C0.onlisten&&C0.onlisten(),{state:S0.state,unlisten:T0};async function T0(){if(T in a===!1)return;if(a[T].listeners=a[T].listeners.filter((w0)=>w0!==C0),a[T].listeners.length)return;return delete a[T],k0`unlisten ${k0.unsafe('"'+T.replace(/"/g,'""')+'"')}`}}async function f(T,u){return await A`select pg_notify(${T}, ${""+u})`}async function h(){let T=I1(),u=z.length?z.shift():await new Promise((k0,a)=>{let Q0={reserve:k0,reject:a};W.push(Q0),Q.length&&F0(Q.shift(),Q0)});N(u,H),u.reserved=()=>T.length?u.execute(T.shift()):N(u,H),u.reserved.release=!0;let G0=g(C0);return G0.release=()=>{u.reserved=null,J1(u)},G0;function C0(k0){u.queue===D?T.push(k0):u.execute(k0)||N(u,D)}}async function I(T,u){!u&&(u=T,T="");let G0=I1(),C0=0,k0,a=null;try{return await A.unsafe("begin "+T.replace(/[^a-z ]/ig,""),[],{onexecute:S0}).execute(),await Promise.race([Q0(k0,u),new Promise((T0,w0)=>k0.onclose=w0)])}catch(T0){throw T0}async function Q0(T0,w0,n0){let L0=g(g0);L0.savepoint=z4,L0.prepare=(R0)=>a=R0.replace(/[^a-z0-9$-_. ]/gi);let S1,l0;n0&&await L0`savepoint ${L0(n0)}`;try{if(l0=await new Promise((R0,v1)=>{let m1=w0(L0);Promise.resolve(Array.isArray(m1)?Promise.all(m1):m1).then(R0,v1)}),S1)throw S1}catch(R0){throw await(n0?L0`rollback to ${L0(n0)}`:L0`rollback`),R0 instanceof I8&&R0.code==="25P02"&&S1||R0}if(!n0)a?await L0`prepare transaction '${L0.unsafe(a)}'`:await L0`commit`;return l0;function z4(R0,v1){if(R0&&Array.isArray(R0.raw))return z4((m1)=>m1.apply(m1,arguments));return arguments.length===1&&(v1=R0,R0=null),Q0(T0,v1,"s"+C0+++(R0?"_"+R0:""))}function g0(R0){R0.catch((v1)=>S1||(S1=v1)),T0.queue===D?G0.push(R0):T0.execute(R0)||N(T0,D)}}function S0(T0){k0=T0,N(T0,H),T0.reserved=()=>G0.length?T0.execute(G0.shift()):N(T0,H)}}function N(T,u){return T.queue.remove(T),u.push(T),T.queue=u,u===z?T.idleTimer.start():T.idleTimer.cancel(),T}function q(T){return new n1(T,3802)}function K(T,u){if(!Array.isArray(T))return K(Array.from(arguments));return new n1(T,u||(T.length?d6(T)||25:0),X.shared.typeArrayMap)}function p(T){if(G)return T.reject(f0.connection("CONNECTION_ENDED",X,X));if(z.length)return s(z.shift(),T);if(Q.length)return F0(Q.shift(),T);O.length?s(O.shift(),T):W.push(T)}function s(T,u){return T.execute(u)?N(T,O):N(T,D)}function C(T){return new Promise((u,G0)=>{T.state?T.active?v5(X).cancel(T.state,u,G0):T.cancelled={resolve:u,reject:G0}:(W.remove(T),T.cancelled=!0,T.reject(f0.generic("57014","canceling statement due to user request")),u())})}async function t({timeout:T=null}={}){if(G)return G;await 1;let u;return G=Promise.race([new Promise((G0)=>T!==null&&(u=setTimeout(e,T*1000,G0))),Promise.all(R.map((G0)=>G0.end()).concat(b.sql?b.sql.end({timeout:0}):[],_.sql?_.sql.end({timeout:0}):[]))]).then(()=>clearTimeout(u))}async function m(){await Promise.all(R.map((T)=>T.end()))}async function e(T){await Promise.all(R.map((u)=>u.terminate()));while(W.length)W.shift().reject(f0.connection("CONNECTION_DESTROYED",X));T()}function F0(T,u){return N(T,$),T.connect(u),T}function b0(T){N(T,J)}function J1(T){if(W.length===0)return N(T,z);let u=Math.ceil(W.length/($.length+1)),G0=!0;while(G0&&W.length&&u-- >0){let C0=W.shift();if(C0.reserve)return C0.reserve(T);G0=T.execute(C0)}G0?N(T,O):N(T,D)}function r1(T,u){N(T,Q),T.reserved=null,T.onclose&&(T.onclose(u),T.onclose=null),X.onclose&&X.onclose(T.id),W.length&&F0(T,W.shift())}}function XO(Y,Z){if(Y&&Y.shared)return Y;let X=process.env,_=(!Y||typeof Y==="string"?Z:Y)||{},{url:G,multihost:W}=HO(Y),$=[...G.searchParams].reduce((D,[V,R])=>(D[V]=R,D),{}),H=_.hostname||_.host||W||G.hostname||X.PGHOST||"localhost",Q=_.port||G.port||X.PGPORT||5432,J=_.user||_.username||G.username||X.PGUSERNAME||X.PGUSER||JO();_.no_prepare&&(_.prepare=!1),$.sslmode&&($.ssl=$.sslmode,delete $.sslmode),"timeout"in _&&(console.log("The timeout option is deprecated, use idle_timeout instead"),_.idle_timeout=_.timeout),$.sslrootcert==="system"&&($.ssl="verify-full");let z=["idle_timeout","connect_timeout","max_lifetime","max_pipeline","backoff","keep_alive"],O={max:10,ssl:!1,idle_timeout:null,connect_timeout:30,max_lifetime:WO,max_pipeline:100,backoff:GO,keep_alive:60,prepare:!0,debug:!1,fetch_types:!0,publications:"alltables",target_session_attrs:null};return{host:Array.isArray(H)?H:H.split(",").map((D)=>D.split(":")[0]),port:Array.isArray(Q)?Q:H.split(",").map((D)=>parseInt(D.split(":")[1]||Q)),path:_.path||H.indexOf("/")>-1&&H+"/.s.PGSQL."+Q,database:_.database||_.db||(G.pathname||"").slice(1)||X.PGDATABASE||J,user:J,pass:_.pass||_.password||G.password||X.PGPASSWORD||"",...Object.entries(O).reduce((D,[V,R])=>{let A=V in _?_[V]:(V in $)?$[V]==="disable"||$[V]==="false"?!1:$[V]:X["PG"+V.toUpperCase()]||R;return D[V]=typeof A==="string"&&z.includes(V)?+A:A,D},{}),connection:{application_name:X.PGAPPNAME||"postgres.js",..._.connection,...Object.entries($).reduce((D,[V,R])=>((V in O)||(D[V]=R),D),{})},types:_.types||{},target_session_attrs:_O(_,G,X),onnotice:_.onnotice,onnotify:_.onnotify,onclose:_.onclose,onparameter:_.onparameter,socket:_.socket,transform:$O(_.transform||{undefined:void 0}),parameters:{},shared:{retries:0,typeArrayMap:{}},...W$(_.types)}}function _O(Y,Z,X){let _=Y.target_session_attrs||Z.searchParams.get("target_session_attrs")||X.PGTARGETSESSIONATTRS;if(!_||["read-write","read-only","primary","standby","prefer-standby"].includes(_))return _;throw new Error("target_session_attrs "+_+" is not supported")}function GO(Y){return(0.5+Math.random()/2)*Math.min(3**Y/100,20)}function WO(){return 60*(30+Math.random()*30)}function $O(Y){return{undefined:Y.undefined,column:{from:typeof Y.column==="function"?Y.column:Y.column&&Y.column.from,to:Y.column&&Y.column.to},value:{from:typeof Y.value==="function"?Y.value:Y.value&&Y.value.from,to:Y.value&&Y.value.to},row:{from:typeof Y.row==="function"?Y.row:Y.row&&Y.row.from,to:Y.row&&Y.row.to}}}function HO(Y){if(!Y||typeof Y!=="string")return{url:{searchParams:new Map}};let Z=Y;Z=Z.slice(Z.indexOf("://")+3).split(/[?/]/)[0],Z=decodeURIComponent(Z.slice(Z.indexOf("@")+1));let X=new URL(Y.replace(Z,Z.split(",")[0]));return{url:{username:decodeURIComponent(X.username),password:decodeURIComponent(X.password),host:X.host,hostname:X.hostname,port:X.port,pathname:X.pathname,searchParams:X.searchParams},multihost:Z.indexOf(",")>-1&&Z}}function JO(){try{return YO.userInfo().username}catch(Y){return process.env.USERNAME||process.env.USER||process.env.LOGNAME}}class j0{static[F]="SelectionProxyHandler";config;constructor(Y){this.config={...Y}}get(Y,Z){if(Z==="_")return{...Y._,selectedFields:new Proxy(Y._.selectedFields,this)};if(Z===A0)return{...Y[A0],selectedFields:new Proxy(Y[A0].selectedFields,this)};if(typeof Z==="symbol")return Y[Z];let _=(M(Y,P0)?Y._.selectedFields:M(Y,L1)?Y[A0].selectedFields:Y)[Z];if(M(_,x.Aliased)){if(this.config.sqlAliasedBehavior==="sql"&&!_.isSelectionField)return _.sql;let G=_.clone();return G.isSelectionField=!0,G}if(M(_,x)){if(this.config.sqlBehavior==="sql")return _;throw new Error(`You tried to reference "${Z}" 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(M(_,E0)){if(this.config.alias)return new Proxy(_,new R8(new Proxy(_.table,new V2(this.config.alias,this.config.replaceOriginalName??!1))));return _}if(typeof _!=="object"||_===null)return _;return new Proxy(_,new j0(this.config))}}class V${constructor(Y,Z){this.unique=Y,this.name=Z}static[F]="PgIndexBuilderOn";on(...Y){return new t6(Y.map((Z)=>{if(M(Z,x))return Z;Z=Z;let X=new O2(Z.name,!!Z.keyAsName,Z.columnType,Z.indexConfig);return Z.indexConfig=JSON.parse(JSON.stringify(Z.defaultConfig)),X}),this.unique,!1,this.name)}onOnly(...Y){return new t6(Y.map((Z)=>{if(M(Z,x))return Z;Z=Z;let X=new O2(Z.name,!!Z.keyAsName,Z.columnType,Z.indexConfig);return Z.indexConfig=Z.defaultConfig,X}),this.unique,!0,this.name)}using(Y,...Z){return new t6(Z.map((X)=>{if(M(X,x))return X;X=X;let _=new O2(X.name,!!X.keyAsName,X.columnType,X.indexConfig);return X.indexConfig=JSON.parse(JSON.stringify(X.defaultConfig)),_}),this.unique,!0,this.name,Y)}}class t6{static[F]="PgIndexBuilder";config;constructor(Y,Z,X,_,G="btree"){this.config={name:_,columns:Y,unique:Z,only:X,method:G}}concurrently(){return this.config.concurrently=!0,this}with(Y){return this.config.with=Y,this}where(Y){return this.config.where=Y,this}build(Y){return new M$(this.config,Y)}}class M${static[F]="PgIndex";config;constructor(Y,Z){this.config={...Y,table:Z}}}function f5(Y){return new V$(!0,Y)}function QO(Y){return(Y.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).map((X)=>X.toLowerCase()).join("_")}function zO(Y){return(Y.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).reduce((X,_,G)=>{let W=G===0?_.toLowerCase():`${_[0].toUpperCase()}${_.slice(1)}`;return X+W},"")}function UO(Y){return Y}class b5{static[F]="CasingCache";cache={};cachedTables={};convert;constructor(Y){this.convert=Y==="snake_case"?QO:Y==="camelCase"?zO:UO}getColumnCasing(Y){if(!Y.keyAsName)return Y.name;let Z=Y.table[P.Symbol.Schema]??"public",X=Y.table[P.Symbol.OriginalName],_=`${Z}.${X}.${Y.name}`;if(!this.cache[_])this.cacheTable(Y.table);return this.cache[_]}cacheTable(Y){let Z=Y[P.Symbol.Schema]??"public",X=Y[P.Symbol.OriginalName],_=`${Z}.${X}`;if(!this.cachedTables[_]){for(let G of Object.values(Y[P.Symbol.Columns])){let W=`${_}.${G.name}`;this.cache[W]=this.convert(G.name)}this.cachedTables[_]=!0}}clearCache(){this.cache={},this.cachedTables={}}}class P2 extends L1{static[F]="PgViewBase"}class c4{static[F]="PgDialect";casing;constructor(Y){this.casing=new b5(Y?.casing)}async migrate(Y,Z,X){let _=typeof X==="string"?"__drizzle_migrations":X.migrationsTable??"__drizzle_migrations",G=typeof X==="string"?"drizzle":X.migrationsSchema??"drizzle",W=E`
84
84
  CREATE TABLE IF NOT EXISTS ${E.identifier(G)}.${E.identifier(_)} (
85
85
  id SERIAL PRIMARY KEY,
86
86
  hash text NOT NULL,
87
87
  created_at bigint
88
88
  )
89
- `;await Z.execute(E`CREATE SCHEMA IF NOT EXISTS ${E.identifier(G)}`),await Z.execute(W);let J=(await Z.all(E`select id, hash, created_at from ${E.identifier(G)}.${E.identifier(_)} order by created_at desc limit 1`))[0];await Z.transaction(async($)=>{for await(let Q of Y)if(!J||Number(J.created_at)<Q.folderMillis){for(let z of Q.sql)await $.execute(E.raw(z));await $.execute(E`insert into ${E.identifier(G)}.${E.identifier(_)} ("hash", "created_at") values(${Q.hash}, ${Q.folderMillis})`)}})}escapeName(Y){return`"${Y}"`}escapeParam(Y){return`$${Y+1}`}escapeString(Y){return`'${Y.replace(/'/g,"''")}'`}buildWithCTE(Y){if(!Y?.length)return;let Z=[E`with `];for(let[X,_]of Y.entries())if(Z.push(E`${E.identifier(_._.alias)} as (${_._.sql})`),X<Y.length-1)Z.push(E`, `);return Z.push(E` `),E.join(Z)}buildDeleteQuery({table:Y,where:Z,returning:X,withList:_}){let G=this.buildWithCTE(_),W=X?E` returning ${this.buildSelection(X,{isSingleTable:!0})}`:void 0,H=Z?E` where ${Z}`:void 0;return E`${G}delete from ${Y}${H}${W}`}buildUpdateSet(Y,Z){let X=Y[P.Symbol.Columns],_=Object.keys(X).filter((W)=>Z[W]!==void 0||X[W]?.onUpdateFn!==void 0),G=_.length;return E.join(_.flatMap((W,H)=>{let J=X[W],$=Z[W]??E.param(J.onUpdateFn(),J),Q=E`${E.identifier(this.casing.getColumnCasing(J))} = ${$}`;if(H<G-1)return[Q,E.raw(", ")];return[Q]}))}buildUpdateQuery({table:Y,set:Z,where:X,returning:_,withList:G,from:W,joins:H}){let J=this.buildWithCTE(G),$=Y[d0.Symbol.Name],Q=Y[d0.Symbol.Schema],z=Y[d0.Symbol.OriginalName],O=$===z?void 0:$,D=E`${Q?E`${E.identifier(Q)}.`:void 0}${E.identifier(z)}${O&&E` ${E.identifier(O)}`}`,V=this.buildUpdateSet(Y,Z),R=W&&E.join([E.raw(" from "),this.buildFromTable(W)]),A=this.buildJoins(H),g=_?E` returning ${this.buildSelection(_,{isSingleTable:!W})}`:void 0,b=X?E` where ${X}`:void 0;return E`${J}update ${D} set ${V}${R}${A}${b}${g}`}buildSelection(Y,{isSingleTable:Z=!1}={}){let X=Y.length,_=Y.flatMap(({field:G},W)=>{let H=[];if(M(G,x.Aliased)&&G.isSelectionField)H.push(E.identifier(G.fieldAlias));else if(M(G,x.Aliased)||M(G,x)){let J=M(G,x.Aliased)?G.sql:G;if(Z)H.push(new x(J.queryChunks.map(($)=>{if(M($,j))return E.identifier(this.casing.getColumnCasing($));return $})));else H.push(J);if(M(G,x.Aliased))H.push(E` as ${E.identifier(G.fieldAlias)}`)}else if(M(G,E0))if(Z)H.push(E.identifier(this.casing.getColumnCasing(G)));else H.push(G);if(W<X-1)H.push(E`, `);return H});return E.join(_)}buildJoins(Y){if(!Y||Y.length===0)return;let Z=[];for(let[X,_]of Y.entries()){if(X===0)Z.push(E` `);let G=_.table,W=_.lateral?E` lateral`:void 0,H=_.on?E` on ${_.on}`:void 0;if(M(G,d0)){let J=G[d0.Symbol.Name],$=G[d0.Symbol.Schema],Q=G[d0.Symbol.OriginalName],z=J===Q?void 0:_.alias;Z.push(E`${E.raw(_.joinType)} join${W} ${$?E`${E.identifier($)}.`:void 0}${E.identifier(Q)}${z&&E` ${E.identifier(z)}`}${H}`)}else if(M(G,L1)){let J=G[A0].name,$=G[A0].schema,Q=G[A0].originalName,z=J===Q?void 0:_.alias;Z.push(E`${E.raw(_.joinType)} join${W} ${$?E`${E.identifier($)}.`:void 0}${E.identifier(Q)}${z&&E` ${E.identifier(z)}`}${H}`)}else Z.push(E`${E.raw(_.joinType)} join${W} ${G}${H}`);if(X<Y.length-1)Z.push(E` `)}return E.join(Z)}buildFromTable(Y){if(M(Y,P)&&Y[P.Symbol.IsAlias]){let Z=E`${E.identifier(Y[P.Symbol.OriginalName])}`;if(Y[P.Symbol.Schema])Z=E`${E.identifier(Y[P.Symbol.Schema])}.${Z}`;return E`${Z} ${E.identifier(Y[P.Symbol.Name])}`}return Y}buildSelectQuery({withList:Y,fields:Z,fieldsFlat:X,where:_,having:G,table:W,joins:H,orderBy:J,groupBy:$,limit:Q,offset:z,lockingClause:O,distinct:D,setOperators:V}){let R=X??q1(Z);for(let e of R)if(M(e.field,E0)&&c0(e.field.table)!==(M(W,P0)?W._.alias:M(W,P6)?W[A0].name:M(W,x)?void 0:c0(W))&&!((U0)=>H?.some(({alias:b0})=>b0===(U0[P.Symbol.IsAlias]?c0(U0):U0[P.Symbol.BaseName])))(e.field.table)){let U0=c0(e.field.table);throw new Error(`Your "${e.path.join("->")}" field references a column "${U0}"."${e.field.name}", but the table "${U0}" is not part of the query! Did you forget to join it?`)}let A=!H||H.length===0,g=this.buildWithCTE(Y),b;if(D)b=D===!0?E` distinct`:E` distinct on (${E.join(D.on,E`, `)})`;let f=this.buildSelection(R,{isSingleTable:A}),h=this.buildFromTable(W),I=this.buildJoins(H),N=_?E` where ${_}`:void 0,q=G?E` having ${G}`:void 0,K;if(J&&J.length>0)K=E` order by ${E.join(J,E`, `)}`;let p;if($&&$.length>0)p=E` group by ${E.join($,E`, `)}`;let s=typeof Q==="object"||typeof Q==="number"&&Q>=0?E` limit ${Q}`:void 0,C=z?E` offset ${z}`:void 0,t=E.empty();if(O){let e=E` for ${E.raw(O.strength)}`;if(O.config.of)e.append(E` of ${E.join(Array.isArray(O.config.of)?O.config.of:[O.config.of],E`, `)}`);if(O.config.noWait)e.append(E` nowait`);else if(O.config.skipLocked)e.append(E` skip locked`);t.append(e)}let m=E`${g}select${b} ${f} from ${h}${I}${N}${p}${q}${K}${s}${C}${t}`;if(V.length>0)return this.buildSetOperations(m,V);return m}buildSetOperations(Y,Z){let[X,..._]=Z;if(!X)throw new Error("Cannot pass undefined values to any set operator");if(_.length===0)return this.buildSetOperationQuery({leftSelect:Y,setOperator:X});return this.buildSetOperations(this.buildSetOperationQuery({leftSelect:Y,setOperator:X}),_)}buildSetOperationQuery({leftSelect:Y,setOperator:{type:Z,isAll:X,rightSelect:_,limit:G,orderBy:W,offset:H}}){let J=E`(${Y.getSQL()}) `,$=E`(${_.getSQL()})`,Q;if(W&&W.length>0){let V=[];for(let R of W)if(M(R,j))V.push(E.identifier(R.name));else if(M(R,x)){for(let A=0;A<R.queryChunks.length;A++){let g=R.queryChunks[A];if(M(g,j))R.queryChunks[A]=E.identifier(g.name)}V.push(E`${R}`)}else V.push(E`${R}`);Q=E` order by ${E.join(V,E`, `)} `}let z=typeof G==="object"||typeof G==="number"&&G>=0?E` limit ${G}`:void 0,O=E.raw(`${Z} ${X?"all ":""}`),D=H?E` offset ${H}`:void 0;return E`${J}${O}${$}${Q}${z}${D}`}buildInsertQuery({table:Y,values:Z,onConflict:X,returning:_,withList:G,select:W,overridingSystemValue_:H}){let J=[],$=Y[P.Symbol.Columns],Q=Object.entries($).filter(([g,b])=>!b.shouldDisableInsert()),z=Q.map(([,g])=>E.identifier(this.casing.getColumnCasing(g)));if(W){let g=Z;if(M(g,x))J.push(g);else J.push(g.getSQL())}else{let g=Z;J.push(E.raw("values "));for(let[b,f]of g.entries()){let h=[];for(let[I,N]of Q){let q=f[I];if(q===void 0||M(q,N1)&&q.value===void 0)if(N.defaultFn!==void 0){let K=N.defaultFn(),p=M(K,x)?K:E.param(K,N);h.push(p)}else if(!N.default&&N.onUpdateFn!==void 0){let K=N.onUpdateFn(),p=M(K,x)?K:E.param(K,N);h.push(p)}else h.push(E`default`);else h.push(q)}if(J.push(h),b<g.length-1)J.push(E`, `)}}let O=this.buildWithCTE(G),D=E.join(J),V=_?E` returning ${this.buildSelection(_,{isSingleTable:!0})}`:void 0,R=X?E` on conflict ${X}`:void 0,A=H===!0?E`overriding system value `:void 0;return E`${O}insert into ${Y} ${z} ${A}${D}${R}${V}`}buildRefreshMaterializedViewQuery({view:Y,concurrently:Z,withNoData:X}){let _=Z?E` concurrently`:void 0,G=X?E` with no data`:void 0;return E`refresh materialized view${_} ${Y}${G}`}prepareTyping(Y){if(M(Y,vY)||M(Y,SY))return"json";else if(M(Y,xY))return"decimal";else if(M(Y,hY))return"time";else if(M(Y,fY)||M(Y,bY))return"timestamp";else if(M(Y,jY)||M(Y,PY))return"date";else if(M(Y,kY))return"uuid";else return"none"}sqlToQuery(Y,Z){return Y.toQuery({casing:this.casing,escapeName:this.escapeName,escapeParam:this.escapeParam,escapeString:this.escapeString,prepareTyping:this.prepareTyping,invokeSource:Z})}buildRelationalQueryWithoutPK({fullSchema:Y,schema:Z,tableNamesMap:X,table:_,tableConfig:G,queryConfig:W,tableAlias:H,nestedQueryRelation:J,joinOn:$}){let Q=[],z,O,D=[],V,R=[];if(W===!0)Q=Object.entries(G.columns).map(([b,f])=>({dbKey:f.name,tsKey:b,field:o1(f,H),relationTableTsKey:void 0,isJson:!1,selection:[]}));else{let g=Object.fromEntries(Object.entries(G.columns).map(([q,K])=>[q,o1(K,H)]));if(W.where){let q=typeof W.where==="function"?W.where(g,n2()):W.where;V=q&&M6(q,H)}let b=[],f=[];if(W.columns){let q=!1;for(let[K,p]of Object.entries(W.columns)){if(p===void 0)continue;if(K in G.columns){if(!q&&p===!0)q=!0;f.push(K)}}if(f.length>0)f=q?f.filter((K)=>W.columns?.[K]===!0):Object.keys(G.columns).filter((K)=>!f.includes(K))}else f=Object.keys(G.columns);for(let q of f){let K=G.columns[q];b.push({tsKey:q,value:K})}let h=[];if(W.with)h=Object.entries(W.with).filter((q)=>!!q[1]).map(([q,K])=>({tsKey:q,queryConfig:K,relation:G.relations[q]}));let I;if(W.extras){I=typeof W.extras==="function"?W.extras(g,{sql:E}):W.extras;for(let[q,K]of Object.entries(I))b.push({tsKey:q,value:zX(K,H)})}for(let{tsKey:q,value:K}of b)Q.push({dbKey:M(K,x.Aliased)?K.fieldAlias:G.columns[q].name,tsKey:q,field:M(K,E0)?o1(K,H):K,relationTableTsKey:void 0,isJson:!1,selection:[]});let N=typeof W.orderBy==="function"?W.orderBy(g,r2()):W.orderBy??[];if(!Array.isArray(N))N=[N];D=N.map((q)=>{if(M(q,E0))return o1(q,H);return M6(q,H)}),z=W.limit,O=W.offset;for(let{tsKey:q,queryConfig:K,relation:p}of h){let s=a2(Z,X,p),C=y4(p.referencedTable),t=X[C],m=`${H}_${q}`,e=I6(...s.fields.map((Q1,r1)=>gY(o1(s.references[r1],m),o1(Q1,H)))),U0=this.buildRelationalQueryWithoutPK({fullSchema:Y,schema:Z,tableNamesMap:X,table:Y[t],tableConfig:Z[t],queryConfig:M(p,C4)?K===!0?{limit:1}:{...K,limit:1}:K,tableAlias:m,joinOn:e,nestedQueryRelation:p}),b0=E`${E.identifier(m)}.${E.identifier("data")}`.as(q);R.push({on:E`true`,table:new P0(U0.sql,{},m),alias:m,joinType:"left",lateral:!0}),Q.push({dbKey:q,tsKey:q,field:b0,relationTableTsKey:t,isJson:!0,selection:U0.selection})}}if(Q.length===0)throw new KY({message:`No fields selected for table "${G.tsName}" ("${H}")`});let A;if(V=I6($,V),J){let g=E`json_build_array(${E.join(Q.map(({field:h,tsKey:I,isJson:N})=>N?E`${E.identifier(`${H}_${I}`)}.${E.identifier("data")}`:M(h,x.Aliased)?h.sql:h),E`, `)})`;if(M(J,B6))g=E`coalesce(json_agg(${g}${D.length>0?E` order by ${E.join(D,E`, `)}`:void 0}), '[]'::json)`;let b=[{dbKey:"data",tsKey:"data",field:g.as("data"),isJson:!0,relationTableTsKey:G.tsName,selection:Q}];if(z!==void 0||O!==void 0||D.length>0)A=this.buildSelectQuery({table:TY(_,H),fields:{},fieldsFlat:[{path:[],field:E.raw("*")}],where:V,limit:z,offset:O,orderBy:D,setOperators:[]}),V=void 0,z=void 0,O=void 0,D=[];else A=TY(_,H);A=this.buildSelectQuery({table:M(A,d0)?A:new P0(A,{},H),fields:{},fieldsFlat:b.map(({field:h})=>({path:[],field:M(h,E0)?o1(h,H):h})),joins:R,where:V,limit:z,offset:O,orderBy:D,setOperators:[]})}else A=this.buildSelectQuery({table:TY(_,H),fields:{},fieldsFlat:Q.map(({field:g})=>({path:[],field:M(g,E0)?o1(g,H):g})),joins:R,where:V,limit:z,offset:O,orderBy:D,setOperators:[]});return{tableTsKey:G.tsName,sql:A,selection:Q}}}class kX{static[U]="TypedQueryBuilder";getSelectedFields(){return this._.selectedFields}}class J1{static[U]="PgSelectBuilder";fields;session;dialect;withList=[];distinct;constructor(Y){if(this.fields=Y.fields,this.session=Y.session,this.dialect=Y.dialect,Y.withList)this.withList=Y.withList;this.distinct=Y.distinct}authToken;setToken(Y){return this.authToken=Y,this}from(Y){let Z=!!this.fields,X=Y,_;if(this.fields)_=this.fields;else if(M(X,P0))_=Object.fromEntries(Object.keys(X._.selectedFields).map((G)=>[G,X[G]]));else if(M(X,P6))_=X[A0].selectedFields;else if(M(X,x))_={};else _=T3(X);return new gX({table:X,fields:_,isPartialSelect:Z,session:this.session,dialect:this.dialect,withList:this.withList,distinct:this.distinct}).setToken(this.authToken)}}class RH extends kX{static[U]="PgSelectQueryBuilder";_;config;joinsNotNullableMap;tableName;isPartialSelect;session;dialect;cacheConfig=void 0;usedTables=new Set;constructor({table:Y,fields:Z,isPartialSelect:X,session:_,dialect:G,withList:W,distinct:H}){super();this.config={withList:W,table:Y,fields:{...Z},distinct:H,setOperators:[]},this.isPartialSelect=X,this.session=_,this.dialect=G,this._={selectedFields:Z,config:this.config},this.tableName=Q4(Y),this.joinsNotNullableMap=typeof this.tableName==="string"?{[this.tableName]:!0}:{};for(let J of p1(Y))this.usedTables.add(J)}getUsedTables(){return[...this.usedTables]}createJoin(Y,Z){return(X,_)=>{let G=this.tableName,W=Q4(X);for(let H of p1(X))this.usedTables.add(H);if(typeof W==="string"&&this.config.joins?.some((H)=>H.alias===W))throw new Error(`Alias "${W}" is already used in this query`);if(!this.isPartialSelect){if(Object.keys(this.joinsNotNullableMap).length===1&&typeof G==="string")this.config.fields={[G]:this.config.fields};if(typeof W==="string"&&!M(X,x)){let H=M(X,P0)?X._.selectedFields:M(X,L1)?X[A0].selectedFields:X[P.Symbol.Columns];this.config.fields[W]=H}}if(typeof _==="function")_=_(new Proxy(this.config.fields,new j0({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));if(!this.config.joins)this.config.joins=[];if(this.config.joins.push({on:_,table:X,joinType:Y,alias:W,lateral:Z}),typeof W==="string")switch(Y){case"left":{this.joinsNotNullableMap[W]=!1;break}case"right":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([H])=>[H,!1])),this.joinsNotNullableMap[W]=!0;break}case"cross":case"inner":{this.joinsNotNullableMap[W]=!0;break}case"full":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([H])=>[H,!1])),this.joinsNotNullableMap[W]=!1;break}}return this}}leftJoin=this.createJoin("left",!1);leftJoinLateral=this.createJoin("left",!0);rightJoin=this.createJoin("right",!1);innerJoin=this.createJoin("inner",!1);innerJoinLateral=this.createJoin("inner",!0);fullJoin=this.createJoin("full",!1);crossJoin=this.createJoin("cross",!1);crossJoinLateral=this.createJoin("cross",!0);createSetOperator(Y,Z){return(X)=>{let _=typeof X==="function"?X(EO()):X;if(!A6(this.getSelectedFields(),_.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:Y,isAll:Z,rightSelect:_}),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(Y){return this.config.setOperators.push(...Y),this}where(Y){if(typeof Y==="function")Y=Y(new Proxy(this.config.fields,new j0({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));return this.config.where=Y,this}having(Y){if(typeof Y==="function")Y=Y(new Proxy(this.config.fields,new j0({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));return this.config.having=Y,this}groupBy(...Y){if(typeof Y[0]==="function"){let Z=Y[0](new Proxy(this.config.fields,new j0({sqlAliasedBehavior:"alias",sqlBehavior:"sql"})));this.config.groupBy=Array.isArray(Z)?Z:[Z]}else this.config.groupBy=Y;return this}orderBy(...Y){if(typeof Y[0]==="function"){let Z=Y[0](new Proxy(this.config.fields,new j0({sqlAliasedBehavior:"alias",sqlBehavior:"sql"}))),X=Array.isArray(Z)?Z:[Z];if(this.config.setOperators.length>0)this.config.setOperators.at(-1).orderBy=X;else this.config.orderBy=X}else{let Z=Y;if(this.config.setOperators.length>0)this.config.setOperators.at(-1).orderBy=Z;else this.config.orderBy=Z}return this}limit(Y){if(this.config.setOperators.length>0)this.config.setOperators.at(-1).limit=Y;else this.config.limit=Y;return this}offset(Y){if(this.config.setOperators.length>0)this.config.setOperators.at(-1).offset=Y;else this.config.offset=Y;return this}for(Y,Z={}){return this.config.lockingClause={strength:Y,config:Z},this}getSQL(){return this.dialect.buildSelectQuery(this.config)}toSQL(){let{typings:Y,...Z}=this.dialect.sqlToQuery(this.getSQL());return Z}as(Y){let Z=[];if(Z.push(...p1(this.config.table)),this.config.joins)for(let X of this.config.joins)Z.push(...p1(X.table));return new Proxy(new P0(this.getSQL(),this.config.fields,Y,!1,[...new Set(Z)]),new j0({alias:Y,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}getSelectedFields(){return new Proxy(this.config.fields,new j0({alias:this.tableName,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}$dynamic(){return this}$withCache(Y){return this.cacheConfig=Y===void 0?{config:{},enable:!0,autoInvalidate:!0}:Y===!1?{enable:!1}:{enable:!0,autoInvalidate:!0,...Y},this}}class gX extends RH{static[U]="PgSelect";_prepare(Y){let{session:Z,config:X,dialect:_,joinsNotNullableMap:G,authToken:W,cacheConfig:H,usedTables:J}=this;if(!Z)throw new Error("Cannot execute a query on a query builder. Please use a database instance instead.");let{fields:$}=X;return D0.startActiveSpan("drizzle.prepareQuery",()=>{let Q=q1($),z=Z.prepareQuery(_.sqlToQuery(this.getSQL()),Q,Y,!0,void 0,{type:"select",tables:[...J]},H);return z.joinsNotNullableMap=G,z.setToken(W)})}prepare(Y){return this._prepare(Y)}authToken;setToken(Y){return this.authToken=Y,this}execute=(Y)=>{return D0.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(Y,this.authToken)})}}C3(gX,[H1]);function C8(Y,Z){return(X,_,...G)=>{let W=[_,...G].map((H)=>({type:Y,isAll:Z,rightSelect:H}));for(let H of W)if(!A6(X.getSelectedFields(),H.rightSelect.getSelectedFields()))throw new Error("Set operator error (union / intersect / except): selected fields are not the same or are in a different order");return X.addSetOperators(W)}}var EO=()=>({union:DO,unionAll:LO,intersect:VO,intersectAll:MO,except:AO,exceptAll:wO}),DO=C8("union",!1),LO=C8("union",!0),VO=C8("intersect",!1),MO=C8("intersect",!0),AO=C8("except",!1),wO=C8("except",!0);class S6{static[U]="PgQueryBuilder";dialect;dialectConfig;constructor(Y){this.dialect=M(Y,c4)?Y:void 0,this.dialectConfig=M(Y,c4)?void 0:Y}$with=(Y,Z)=>{let X=this;return{as:(G)=>{if(typeof G==="function")G=G(X);return new Proxy(new D6(G.getSQL(),Z??("getSelectedFields"in G?G.getSelectedFields()??{}:{}),Y,!0),new j0({alias:Y,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}};with(...Y){let Z=this;function X(W){return new J1({fields:W??void 0,session:void 0,dialect:Z.getDialect(),withList:Y})}function _(W){return new J1({fields:W??void 0,session:void 0,dialect:Z.getDialect(),distinct:!0})}function G(W,H){return new J1({fields:H??void 0,session:void 0,dialect:Z.getDialect(),distinct:{on:W}})}return{select:X,selectDistinct:_,selectDistinctOn:G}}select(Y){return new J1({fields:Y??void 0,session:void 0,dialect:this.getDialect()})}selectDistinct(Y){return new J1({fields:Y??void 0,session:void 0,dialect:this.getDialect(),distinct:!0})}selectDistinctOn(Y,Z){return new J1({fields:Z??void 0,session:void 0,dialect:this.getDialect(),distinct:{on:Y}})}getDialect(){if(!this.dialect)this.dialect=new c4(this.dialectConfig);return this.dialect}}function p1(Y){if(M(Y,d0))return[Y[g4]?`${Y[g4]}.${Y[P.Symbol.BaseName]}`:Y[P.Symbol.BaseName]];if(M(Y,P0))return Y._.usedTables??[];if(M(Y,x))return Y.usedTables??[];return[]}class tY extends H1{constructor(Y,Z,X,_){super();this.session=Z,this.dialect=X,this.config={table:Y,withList:_}}static[U]="PgDelete";config;cacheConfig;where(Y){return this.config.where=Y,this}returning(Y=this.config.table[P.Symbol.Columns]){return this.config.returningFields=Y,this.config.returning=q1(Y),this}getSQL(){return this.dialect.buildDeleteQuery(this.config)}toSQL(){let{typings:Y,...Z}=this.dialect.sqlToQuery(this.getSQL());return Z}_prepare(Y){return D0.startActiveSpan("drizzle.prepareQuery",()=>{return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,Y,!0,void 0,{type:"delete",tables:p1(this.config.table)},this.cacheConfig)})}prepare(Y){return this._prepare(Y)}authToken;setToken(Y){return this.authToken=Y,this}execute=(Y)=>{return D0.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(Y,this.authToken)})};getSelectedFields(){return this.config.returningFields?new Proxy(this.config.returningFields,new j0({alias:c0(this.config.table),sqlAliasedBehavior:"alias",sqlBehavior:"error"})):void 0}$dynamic(){return this}}class eY{constructor(Y,Z,X,_,G){this.table=Y,this.session=Z,this.dialect=X,this.withList=_,this.overridingSystemValue_=G}static[U]="PgInsertBuilder";authToken;setToken(Y){return this.authToken=Y,this}overridingSystemValue(){return this.overridingSystemValue_=!0,this}values(Y){if(Y=Array.isArray(Y)?Y:[Y],Y.length===0)throw new Error("values() must be called with at least one value");let Z=Y.map((X)=>{let _={},G=this.table[P.Symbol.Columns];for(let W of Object.keys(X)){let H=X[W];_[W]=M(H,x)?H:new N1(H,G[W])}return _});return new yX(this.table,Z,this.session,this.dialect,this.withList,!1,this.overridingSystemValue_).setToken(this.authToken)}select(Y){let Z=typeof Y==="function"?Y(new S6):Y;if(!M(Z,x)&&!A6(this.table[BY],Z._.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 yX(this.table,Z,this.session,this.dialect,this.withList,!0)}}class yX extends H1{constructor(Y,Z,X,_,G,W,H){super();this.session=X,this.dialect=_,this.config={table:Y,values:Z,withList:G,select:W,overridingSystemValue_:H}}static[U]="PgInsert";config;cacheConfig;returning(Y=this.config.table[P.Symbol.Columns]){return this.config.returningFields=Y,this.config.returning=q1(Y),this}onConflictDoNothing(Y={}){if(Y.target===void 0)this.config.onConflict=E`do nothing`;else{let Z="";Z=Array.isArray(Y.target)?Y.target.map((_)=>this.dialect.escapeName(this.dialect.casing.getColumnCasing(_))).join(","):this.dialect.escapeName(this.dialect.casing.getColumnCasing(Y.target));let X=Y.where?E` where ${Y.where}`:void 0;this.config.onConflict=E`(${E.raw(Z)})${X} do nothing`}return this}onConflictDoUpdate(Y){if(Y.where&&(Y.targetWhere||Y.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 Z=Y.where?E` where ${Y.where}`:void 0,X=Y.targetWhere?E` where ${Y.targetWhere}`:void 0,_=Y.setWhere?E` where ${Y.setWhere}`:void 0,G=this.dialect.buildUpdateSet(this.config.table,qY(this.config.table,Y.set)),W="";return W=Array.isArray(Y.target)?Y.target.map((H)=>this.dialect.escapeName(this.dialect.casing.getColumnCasing(H))).join(","):this.dialect.escapeName(this.dialect.casing.getColumnCasing(Y.target)),this.config.onConflict=E`(${E.raw(W)})${X} do update set ${G}${Z}${_}`,this}getSQL(){return this.dialect.buildInsertQuery(this.config)}toSQL(){let{typings:Y,...Z}=this.dialect.sqlToQuery(this.getSQL());return Z}_prepare(Y){return D0.startActiveSpan("drizzle.prepareQuery",()=>{return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,Y,!0,void 0,{type:"insert",tables:p1(this.config.table)},this.cacheConfig)})}prepare(Y){return this._prepare(Y)}authToken;setToken(Y){return this.authToken=Y,this}execute=(Y)=>{return D0.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(Y,this.authToken)})};getSelectedFields(){return this.config.returningFields?new Proxy(this.config.returningFields,new j0({alias:c0(this.config.table),sqlAliasedBehavior:"alias",sqlBehavior:"error"})):void 0}$dynamic(){return this}}class pX extends H1{constructor(Y,Z,X){super();this.session=Z,this.dialect=X,this.config={view:Y}}static[U]="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:Y,...Z}=this.dialect.sqlToQuery(this.getSQL());return Z}_prepare(Y){return D0.startActiveSpan("drizzle.prepareQuery",()=>{return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),void 0,Y,!0)})}prepare(Y){return this._prepare(Y)}authToken;setToken(Y){return this.authToken=Y,this}execute=(Y)=>{return D0.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(Y,this.authToken)})}}class YZ{constructor(Y,Z,X,_){this.table=Y,this.session=Z,this.dialect=X,this.withList=_}static[U]="PgUpdateBuilder";authToken;setToken(Y){return this.authToken=Y,this}set(Y){return new NH(this.table,qY(this.table,Y),this.session,this.dialect,this.withList).setToken(this.authToken)}}class NH extends H1{constructor(Y,Z,X,_,G){super();this.session=X,this.dialect=_,this.config={set:Z,table:Y,withList:G,joins:[]},this.tableName=Q4(Y),this.joinsNotNullableMap=typeof this.tableName==="string"?{[this.tableName]:!0}:{}}static[U]="PgUpdate";config;tableName;joinsNotNullableMap;cacheConfig;from(Y){let Z=Y,X=Q4(Z);if(typeof X==="string")this.joinsNotNullableMap[X]=!0;return this.config.from=Z,this}getTableLikeFields(Y){if(M(Y,d0))return Y[P.Symbol.Columns];else if(M(Y,P0))return Y._.selectedFields;return Y[A0].selectedFields}createJoin(Y){return(Z,X)=>{let _=Q4(Z);if(typeof _==="string"&&this.config.joins.some((G)=>G.alias===_))throw new Error(`Alias "${_}" is already used in this query`);if(typeof X==="function"){let G=this.config.from&&!M(this.config.from,x)?this.getTableLikeFields(this.config.from):void 0;X=X(new Proxy(this.config.table[P.Symbol.Columns],new j0({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})),G&&new Proxy(G,new j0({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})))}if(this.config.joins.push({on:X,table:Z,joinType:Y,alias:_}),typeof _==="string")switch(Y){case"left":{this.joinsNotNullableMap[_]=!1;break}case"right":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([G])=>[G,!1])),this.joinsNotNullableMap[_]=!0;break}case"inner":{this.joinsNotNullableMap[_]=!0;break}case"full":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([G])=>[G,!1])),this.joinsNotNullableMap[_]=!1;break}}return this}}leftJoin=this.createJoin("left");rightJoin=this.createJoin("right");innerJoin=this.createJoin("inner");fullJoin=this.createJoin("full");where(Y){return this.config.where=Y,this}returning(Y){if(!Y){if(Y=Object.assign({},this.config.table[P.Symbol.Columns]),this.config.from){let Z=Q4(this.config.from);if(typeof Z==="string"&&this.config.from&&!M(this.config.from,x)){let X=this.getTableLikeFields(this.config.from);Y[Z]=X}for(let X of this.config.joins){let _=Q4(X.table);if(typeof _==="string"&&!M(X.table,x)){let G=this.getTableLikeFields(X.table);Y[_]=G}}}}return this.config.returningFields=Y,this.config.returning=q1(Y),this}getSQL(){return this.dialect.buildUpdateQuery(this.config)}toSQL(){let{typings:Y,...Z}=this.dialect.sqlToQuery(this.getSQL());return Z}_prepare(Y){let Z=this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,Y,!0,void 0,{type:"insert",tables:p1(this.config.table)},this.cacheConfig);return Z.joinsNotNullableMap=this.joinsNotNullableMap,Z}prepare(Y){return this._prepare(Y)}authToken;setToken(Y){return this.authToken=Y,this}execute=(Y)=>{return this._prepare().execute(Y,this.authToken)};getSelectedFields(){return this.config.returningFields?new Proxy(this.config.returningFields,new j0({alias:c0(this.config.table),sqlAliasedBehavior:"alias",sqlBehavior:"error"})):void 0}$dynamic(){return this}}class v6 extends x{constructor(Y){super(v6.buildEmbeddedCount(Y.source,Y.filters).queryChunks);this.params=Y,this.mapWith(Number),this.session=Y.session,this.sql=v6.buildCount(Y.source,Y.filters)}sql;token;static[U]="PgCountBuilder";[Symbol.toStringTag]="PgCountBuilder";session;static buildEmbeddedCount(Y,Z){return E`(select count(*) from ${Y}${E.raw(" where ").if(Z)}${Z})`}static buildCount(Y,Z){return E`select count(*) as count from ${Y}${E.raw(" where ").if(Z)}${Z};`}setToken(Y){return this.token=Y,this}then(Y,Z){return Promise.resolve(this.session.count(this.sql,this.token)).then(Y,Z)}catch(Y){return this.then(void 0,Y)}finally(Y){return this.then((Z)=>{return Y?.(),Z},(Z)=>{throw Y?.(),Z})}}class uX{constructor(Y,Z,X,_,G,W,H){this.fullSchema=Y,this.schema=Z,this.tableNamesMap=X,this.table=_,this.tableConfig=G,this.dialect=W,this.session=H}static[U]="PgRelationalQueryBuilder";findMany(Y){return new mX(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,Y?Y:{},"many")}findFirst(Y){return new mX(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,Y?{...Y,limit:1}:{limit:1},"first")}}class mX extends H1{constructor(Y,Z,X,_,G,W,H,J,$){super();this.fullSchema=Y,this.schema=Z,this.tableNamesMap=X,this.table=_,this.tableConfig=G,this.dialect=W,this.session=H,this.config=J,this.mode=$}static[U]="PgRelationalQuery";_prepare(Y){return D0.startActiveSpan("drizzle.prepareQuery",()=>{let{query:Z,builtQuery:X}=this._toSQL();return this.session.prepareQuery(X,void 0,Y,!0,(_,G)=>{let W=_.map((H)=>yY(this.schema,this.tableConfig,H,Z.selection,G));if(this.mode==="first")return W[0];return W})})}prepare(Y){return this._prepare(Y)}_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 Y=this._getQuery(),Z=this.dialect.sqlToQuery(Y.sql);return{query:Y,builtQuery:Z}}toSQL(){return this._toSQL().builtQuery}authToken;setToken(Y){return this.authToken=Y,this}execute(){return D0.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(void 0,this.authToken)})}}class dX extends H1{constructor(Y,Z,X,_){super();this.execute=Y,this.sql=Z,this.query=X,this.mapBatchResult=_}static[U]="PgRaw";getSQL(){return this.sql}getQuery(){return this.query}mapResult(Y,Z){return Z?this.mapBatchResult(Y):Y}_prepare(){return this}isResponseInArrayMode(){return!1}}class x6{constructor(Y,Z,X){if(this.dialect=Y,this.session=Z,this._=X?{schema:X.schema,fullSchema:X.fullSchema,tableNamesMap:X.tableNamesMap,session:Z}:{schema:void 0,fullSchema:{},tableNamesMap:{},session:Z},this.query={},this._.schema)for(let[_,G]of Object.entries(this._.schema))this.query[_]=new uX(X.fullSchema,this._.schema,this._.tableNamesMap,X.fullSchema[_],G,Y,Z);this.$cache={invalidate:async(_)=>{}}}static[U]="PgDatabase";query;$with=(Y,Z)=>{let X=this;return{as:(G)=>{if(typeof G==="function")G=G(new S6(X.dialect));return new Proxy(new D6(G.getSQL(),Z??("getSelectedFields"in G?G.getSelectedFields()??{}:{}),Y,!0),new j0({alias:Y,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}};$count(Y,Z){return new v6({source:Y,filters:Z,session:this.session})}$cache;with(...Y){let Z=this;function X($){return new J1({fields:$??void 0,session:Z.session,dialect:Z.dialect,withList:Y})}function _($){return new J1({fields:$??void 0,session:Z.session,dialect:Z.dialect,withList:Y,distinct:!0})}function G($,Q){return new J1({fields:Q??void 0,session:Z.session,dialect:Z.dialect,withList:Y,distinct:{on:$}})}function W($){return new YZ($,Z.session,Z.dialect,Y)}function H($){return new eY($,Z.session,Z.dialect,Y)}function J($){return new tY($,Z.session,Z.dialect,Y)}return{select:X,selectDistinct:_,selectDistinctOn:G,update:W,insert:H,delete:J}}select(Y){return new J1({fields:Y??void 0,session:this.session,dialect:this.dialect})}selectDistinct(Y){return new J1({fields:Y??void 0,session:this.session,dialect:this.dialect,distinct:!0})}selectDistinctOn(Y,Z){return new J1({fields:Z??void 0,session:this.session,dialect:this.dialect,distinct:{on:Y}})}update(Y){return new YZ(Y,this.session,this.dialect)}insert(Y){return new eY(Y,this.session,this.dialect)}delete(Y){return new tY(Y,this.session,this.dialect)}refreshMaterializedView(Y){return new pX(Y,this.session,this.dialect)}authToken;execute(Y){let Z=typeof Y==="string"?E.raw(Y):Y.getSQL(),X=this.dialect.sqlToQuery(Z),_=this.session.prepareQuery(X,void 0,void 0,!1);return new dX(()=>_.execute(void 0,this.authToken),Z,X,(G)=>_.mapResult(G,!0))}transaction(Y,Z){return this.session.transaction(Y,Z)}}class IH{static[U]="Cache"}class h6 extends IH{strategy(){return"all"}static[U]="NoopCache";async get(Y){return}async put(Y,Z,X,_){}async onMutate(Y){}}async function cX(Y,Z){let X=`${Y}-${JSON.stringify(Z)}`,G=new TextEncoder().encode(X),W=await crypto.subtle.digest("SHA-256",G);return[...new Uint8Array(W)].map(($)=>$.toString(16).padStart(2,"0")).join("")}class lX{constructor(Y,Z,X,_){if(this.query=Y,this.cache=Z,this.queryMetadata=X,this.cacheConfig=_,Z&&Z.strategy()==="all"&&_===void 0)this.cacheConfig={enable:!0,autoInvalidate:!0};if(!this.cacheConfig?.enable)this.cacheConfig=void 0}authToken;getQuery(){return this.query}mapResult(Y,Z){return Y}setToken(Y){return this.authToken=Y,this}static[U]="PgPreparedQuery";joinsNotNullableMap;async queryWithCache(Y,Z,X){if(this.cache===void 0||M(this.cache,h6)||this.queryMetadata===void 0)try{return await X()}catch(_){throw new J4(Y,Z,_)}if(this.cacheConfig&&!this.cacheConfig.enable)try{return await X()}catch(_){throw new J4(Y,Z,_)}if((this.queryMetadata.type==="insert"||this.queryMetadata.type==="update"||this.queryMetadata.type==="delete")&&this.queryMetadata.tables.length>0)try{let[_]=await Promise.all([X(),this.cache.onMutate({tables:this.queryMetadata.tables})]);return _}catch(_){throw new J4(Y,Z,_)}if(!this.cacheConfig)try{return await X()}catch(_){throw new J4(Y,Z,_)}if(this.queryMetadata.type==="select"){let _=await this.cache.get(this.cacheConfig.tag??await cX(Y,Z),this.queryMetadata.tables,this.cacheConfig.tag!==void 0,this.cacheConfig.autoInvalidate);if(_===void 0){let G;try{G=await X()}catch(W){throw new J4(Y,Z,W)}return await this.cache.put(this.cacheConfig.tag??await cX(Y,Z),G,this.cacheConfig.autoInvalidate?this.queryMetadata.tables:[],this.cacheConfig.tag!==void 0,this.cacheConfig.config),G}return _}try{return await X()}catch(_){throw new J4(Y,Z,_)}}}class iX{constructor(Y){this.dialect=Y}static[U]="PgSession";execute(Y,Z){return D0.startActiveSpan("drizzle.operation",()=>{return D0.startActiveSpan("drizzle.prepareQuery",()=>{return this.prepareQuery(this.dialect.sqlToQuery(Y),void 0,void 0,!1)}).setToken(Z).execute(void 0,Z)})}all(Y){return this.prepareQuery(this.dialect.sqlToQuery(Y),void 0,void 0,!1).all()}async count(Y,Z){let X=await this.execute(Y,Z);return Number(X[0].count)}}class oX extends x6{constructor(Y,Z,X,_=0){super(Y,Z,X);this.schema=X,this.nestedIndex=_}static[U]="PgTransaction";rollback(){throw new FX}getTransactionConfigSQL(Y){let Z=[];if(Y.isolationLevel)Z.push(`isolation level ${Y.isolationLevel}`);if(Y.accessMode)Z.push(Y.accessMode);if(typeof Y.deferrable==="boolean")Z.push(Y.deferrable?"deferrable":"not deferrable");return E.raw(Z.join(" "))}setTransaction(Y){return this.session.execute(E`set transaction ${this.getTransactionConfigSQL(Y)}`)}}class BH extends lX{constructor(Y,Z,X,_,G,W,H,J,$,Q){super({sql:Z,params:X},G,W,H);this.client=Y,this.queryString=Z,this.params=X,this.logger=_,this.fields=J,this._isResponseInArrayMode=$,this.customResultMapper=Q}static[U]="PostgresJsPreparedQuery";async execute(Y={}){return D0.startActiveSpan("drizzle.execute",async(Z)=>{let X=$X(this.params,Y);Z?.setAttributes({"drizzle.query.text":this.queryString,"drizzle.query.params":JSON.stringify(X)}),this.logger.logQuery(this.queryString,X);let{fields:_,queryString:G,client:W,joinsNotNullableMap:H,customResultMapper:J}=this;if(!_&&!J)return D0.startActiveSpan("drizzle.driver.execute",()=>{return this.queryWithCache(G,X,async()=>{return await W.unsafe(G,X)})});let $=await D0.startActiveSpan("drizzle.driver.execute",()=>{return Z?.setAttributes({"drizzle.query.text":G,"drizzle.query.params":JSON.stringify(X)}),this.queryWithCache(G,X,async()=>{return await W.unsafe(G,X).values()})});return D0.startActiveSpan("drizzle.mapResponse",()=>{return J?J($):$.map((Q)=>B3(_,Q,H))})})}all(Y={}){return D0.startActiveSpan("drizzle.execute",async(Z)=>{let X=$X(this.params,Y);return Z?.setAttributes({"drizzle.query.text":this.queryString,"drizzle.query.params":JSON.stringify(X)}),this.logger.logQuery(this.queryString,X),D0.startActiveSpan("drizzle.driver.execute",()=>{return Z?.setAttributes({"drizzle.query.text":this.queryString,"drizzle.query.params":JSON.stringify(X)}),this.queryWithCache(this.queryString,X,async()=>{return this.client.unsafe(this.queryString,X)})})})}isResponseInArrayMode(){return this._isResponseInArrayMode}}class f6 extends iX{constructor(Y,Z,X,_={}){super(Z);this.client=Y,this.schema=X,this.options=_,this.logger=_.logger??new OX,this.cache=_.cache??new h6}static[U]="PostgresJsSession";logger;cache;prepareQuery(Y,Z,X,_,G,W,H){return new BH(this.client,Y.sql,Y.params,this.logger,this.cache,W,H,Z,_,G)}query(Y,Z){return this.logger.logQuery(Y,Z),this.client.unsafe(Y,Z).values()}queryObjects(Y,Z){return this.client.unsafe(Y,Z)}transaction(Y,Z){return this.client.begin(async(X)=>{let _=new f6(X,this.dialect,this.schema,this.options),G=new nX(this.dialect,_,this.schema);if(Z)await G.setTransaction(Z);return Y(G)})}}class nX extends oX{constructor(Y,Z,X,_=0){super(Y,Z,X,_);this.session=Z}static[U]="PostgresJsTransaction";transaction(Y){return this.session.client.savepoint((Z)=>{let X=new f6(Z,this.dialect,this.schema,this.session.options),_=new nX(this.dialect,X,this.schema);return Y(_)})}}class CH extends x6{static[U]="PostgresJsDatabase"}function T8(Y,Z={}){let X=($)=>$;for(let $ of["1184","1082","1083","1114","1182","1185","1115","1231"])Y.options.parsers[$]=X,Y.options.serializers[$]=X;Y.options.serializers["114"]=X,Y.options.serializers["3802"]=X;let _=new c4({casing:Z.casing}),G;if(Z.logger===!0)G=new UX;else if(Z.logger!==!1)G=Z.logger;let W;if(Z.schema){let $=s2(Z.schema,t2);W={fullSchema:Z.schema,schema:$.tables,tableNamesMap:$.tableNamesMap}}let H=new f6(Y,_,W,{logger:G,cache:Z.cache}),J=new CH(_,H,W);if(J.$client=Y,J.$cache=Z.cache,J.$cache)J.$cache.invalidate=Z.cache?.onMutate;return J}function ZZ(...Y){if(typeof Y[0]==="string"){let Z=B8(Y[0]);return T8(Z,Y[1])}if(K3(Y[0])){let{connection:Z,client:X,..._}=Y[0];if(X)return T8(X,_);if(typeof Z==="object"&&Z.url!==void 0){let{url:W,...H}=Z,J=B8(W,H);return T8(J,_)}let G=B8(Z);return T8(G,_)}return T8(Y[0],Y[1])}((Y)=>{function Z(X){return T8({options:{parsers:{},serializers:{}}},X)}Y.mock=Z})(ZZ||(ZZ={}));var sX={};PJ(sX,{users:()=>l4,untrackedUserColumnNames:()=>RO,twoFactorMethod:()=>PH,trackedUserColumnName:()=>NO,trackableUserColumnNames:()=>qH,signInHistory:()=>BO,role:()=>KH,players:()=>rX,passwordResetAttempts:()=>CO,games:()=>_Z,banishedIps:()=>TO,accountActions:()=>IO,accountAction:()=>jH});function K4(){return e0({length:24}).$type()}function TH(Y){return E`lower(${Y})`}var XZ=E`TO_CHAR(NOW() AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.MS"Z"')`,KH=E6("role",["admin","user"]),l4=B4("users",{id:j1().primaryKey().defaultRandom(),username:e0({length:16}).notNull(),emailOffered:e0({length:254}).notNull(),emailVerified:e0({length:254}),password:e0({length:254}),createdAtIso:K4().notNull().default(XZ),createdIp:e0({length:45}).notNull(),isActive:w6().notNull().default(!1),verifiedAtIso:K4(),userRole:KH().default("user")},(Y)=>[fX("usernameUniqueIndex").on(TH(Y.username)),fX("emailVerifiedUniqueIndex").on(TH(Y.emailVerified))]),RO=["id","createdAtIso","createdIp","isActive","verifiedAtIso"],qH=["username","emailOffered","emailVerified","password","userRole"],NO=E6("trackedUserColumnName",qH),jH=E6("accountAction",["cooldown","confirmEmail","signIn","resetPassword"]),IO=B4("accountActions",{userId:j1().references(()=>l4.id).primaryKey(),action:jH().notNull(),code:e0({length:254}).notNull(),wrongCodeCount:R6().notNull().default(0),expiresAtIso:K4().notNull()}),_Z=B4("games",{id:j1().primaryKey().defaultRandom()}),rX=B4("players",{userId:j1().notNull().references(()=>l4.id,{onDelete:"cascade"}),gameId:j1().notNull().references(()=>_Z.id,{onDelete:"cascade"}),score:R6().notNull()},(Y)=>[B2({name:"players_userId_gameId_pk",columns:[Y.userId,Y.gameId]})]),BO=B4("signInHistory",{id:j1().primaryKey().defaultRandom(),userId:j1().references(()=>l4.id,{onDelete:"cascade"}),signInTimeIso:K4().notNull().default(XZ),ipAddress:e0({length:45}).notNull(),userAgent:e0({length:1024}),successful:w6().notNull().default(!1)}),PH=E6("twoFactorMethod",["email","phone"]),CO=B4("passwordResetAttempts",{id:j1().primaryKey().defaultRandom(),userId:j1().notNull().references(()=>l4.id,{onDelete:"cascade"}),requestedIp:e0({length:45}).notNull(),requestedAtIso:K4().notNull().default(XZ),succeededIp:e0({length:45}),succeededAtIso:K4(),verificationMethod:PH().notNull()}),TO=B4("banishedIps",{ip:e0({length:45}).primaryKey(),reason:e0({length:2048}).notNull(),banishedAtIso:K4().notNull().default(XZ),banishedUntilIso:K4()});var __dirname="/home/runner/work/wayforge/wayforge/apps/tempest.games/src/database";class aX{options;sql;drizzle;observers=new Map;async setupTriggersAndNotifications(){await this.sql.file(KO.resolve(__dirname,"notify_update.sql"));let Y=[c0(l4),c0(_Z),c0(rX)];await this.sql`SELECT create_notify_triggers(${this.sql.array(Y)})`,await this.sql.listen("table_update",(Z)=>{let X=Z.split(","),_=X[0],G=X[1],W=`${_}("${G}")`;if(this.observers.has(W))this.observers.get(W).next(W)})}constructor(Y=!1,Z={host:g1.POSTGRES_HOST,port:g1.POSTGRES_PORT,user:g1.POSTGRES_USER,password:g1.POSTGRES_PASSWORD,database:g1.POSTGRES_DATABASE}){this.options=Z,this.sql=B8(Z),this.drizzle=ZZ(this.sql,{schema:sX,logger:Y})}observe(Y,Z){if(!this.observers.has(Y))this.observers.set(Y,new J0);this.observers.get(Y).subscribe("SINGLETON",Z)}}var GZ={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 qO(Y){return Number.parseInt(Y,10)}var jO=E1(GZ),PO=jO.keyof().pipe((Y)=>qO(Y)),SH=E1([PO,"string"]);var eX=new e7,{logger:M1}=eX;Object.assign(console,M1,{log:M1.info});M1.info("ready");var tX=xH(import.meta.dir,"..","app"),sx=new aX({logQuery(Y,Z){M1.info("\uD83D\uDCDD query",Y,Z)}});hO({hostname:"0.0.0.0",port:g1.FRONTEND_PORT??3333,...RY??void 0,async fetch(Y){try{let Z=new Date,X=new URL(Y.url);if(M1.info(Y.method,X.pathname),X.pathname==="/")return new Response(Bun.file(xH(tX,"index.html")));if(X.pathname==="/index.html")return Response.redirect("/");let _=vO(tX,X.pathname),G=xO(_);if(!G.startsWith(tX))throw[403,"Access Denied"];if(!await vH(G).exists())return Response.redirect("/");return new Response(vH(G))}catch(Z){let X=SH(Z);if(X instanceof E1.errors===!1){let[_,G]=X,H=`${GZ[_]}. ${G}`;return M1.info(`\u274C ${_}: ${H}`),new Response(H,{status:_})}if(Z instanceof Error)M1.error(Z.message);else{let _=wY(Z);M1.error("frontend server threw",_)}return new Response(GZ[500],{status:500})}}});function WZ(){M1.info("\uD83D\uDEEC frontend server exiting"),process.exit(0)}process.on("SIGINT",()=>{M1.info("\u2757 received SIGINT; exiting gracefully"),WZ()});process.on("SIGTERM",()=>{M1.info("\u2757 received SIGTERM; exiting gracefully"),WZ()});process.on("exit",()=>{M1.info("\u2757 received exit; exiting gracefully"),WZ()});eX.on("timeToStop",()=>{M1.info('\u2757 backend server received signal "timeToStop"; exiting gracefully'),WZ()});var{version:fO}=await Bun.file(SO.resolve(import.meta.dir,"../package.json")).json();M1.info(`\uD83D\uDEEB frontend v${fO} running at http://localhost:${g1.FRONTEND_PORT}/`);eX.emit("alive");
89
+ `;await Z.execute(E`CREATE SCHEMA IF NOT EXISTS ${E.identifier(G)}`),await Z.execute(W);let H=(await Z.all(E`select id, hash, created_at from ${E.identifier(G)}.${E.identifier(_)} order by created_at desc limit 1`))[0];await Z.transaction(async(Q)=>{for await(let J of Y)if(!H||Number(H.created_at)<J.folderMillis){for(let z of J.sql)await Q.execute(E.raw(z));await Q.execute(E`insert into ${E.identifier(G)}.${E.identifier(_)} ("hash", "created_at") values(${J.hash}, ${J.folderMillis})`)}})}escapeName(Y){return`"${Y}"`}escapeParam(Y){return`$${Y+1}`}escapeString(Y){return`'${Y.replace(/'/g,"''")}'`}buildWithCTE(Y){if(!Y?.length)return;let Z=[E`with `];for(let[X,_]of Y.entries())if(Z.push(E`${E.identifier(_._.alias)} as (${_._.sql})`),X<Y.length-1)Z.push(E`, `);return Z.push(E` `),E.join(Z)}buildDeleteQuery({table:Y,where:Z,returning:X,withList:_}){let G=this.buildWithCTE(_),W=X?E` returning ${this.buildSelection(X,{isSingleTable:!0})}`:void 0,$=Z?E` where ${Z}`:void 0;return E`${G}delete from ${Y}${$}${W}`}buildUpdateSet(Y,Z){let X=Y[P.Symbol.Columns],_=Object.keys(X).filter((W)=>Z[W]!==void 0||X[W]?.onUpdateFn!==void 0),G=_.length;return E.join(_.flatMap((W,$)=>{let H=X[W],Q=Z[W]??E.param(H.onUpdateFn(),H),J=E`${E.identifier(this.casing.getColumnCasing(H))} = ${Q}`;if($<G-1)return[J,E.raw(", ")];return[J]}))}buildUpdateQuery({table:Y,set:Z,where:X,returning:_,withList:G,from:W,joins:$}){let H=this.buildWithCTE(G),Q=Y[d0.Symbol.Name],J=Y[d0.Symbol.Schema],z=Y[d0.Symbol.OriginalName],O=Q===z?void 0:Q,D=E`${J?E`${E.identifier(J)}.`:void 0}${E.identifier(z)}${O&&E` ${E.identifier(O)}`}`,V=this.buildUpdateSet(Y,Z),R=W&&E.join([E.raw(" from "),this.buildFromTable(W)]),A=this.buildJoins($),g=_?E` returning ${this.buildSelection(_,{isSingleTable:!W})}`:void 0,b=X?E` where ${X}`:void 0;return E`${H}update ${D} set ${V}${R}${A}${b}${g}`}buildSelection(Y,{isSingleTable:Z=!1}={}){let X=Y.length,_=Y.flatMap(({field:G},W)=>{let $=[];if(M(G,x.Aliased)&&G.isSelectionField)$.push(E.identifier(G.fieldAlias));else if(M(G,x.Aliased)||M(G,x)){let H=M(G,x.Aliased)?G.sql:G;if(Z)$.push(new x(H.queryChunks.map((Q)=>{if(M(Q,j))return E.identifier(this.casing.getColumnCasing(Q));return Q})));else $.push(H);if(M(G,x.Aliased))$.push(E` as ${E.identifier(G.fieldAlias)}`)}else if(M(G,E0))if(Z)$.push(E.identifier(this.casing.getColumnCasing(G)));else $.push(G);if(W<X-1)$.push(E`, `);return $});return E.join(_)}buildJoins(Y){if(!Y||Y.length===0)return;let Z=[];for(let[X,_]of Y.entries()){if(X===0)Z.push(E` `);let G=_.table,W=_.lateral?E` lateral`:void 0,$=_.on?E` on ${_.on}`:void 0;if(M(G,d0)){let H=G[d0.Symbol.Name],Q=G[d0.Symbol.Schema],J=G[d0.Symbol.OriginalName],z=H===J?void 0:_.alias;Z.push(E`${E.raw(_.joinType)} join${W} ${Q?E`${E.identifier(Q)}.`:void 0}${E.identifier(J)}${z&&E` ${E.identifier(z)}`}${$}`)}else if(M(G,L1)){let H=G[A0].name,Q=G[A0].schema,J=G[A0].originalName,z=H===J?void 0:_.alias;Z.push(E`${E.raw(_.joinType)} join${W} ${Q?E`${E.identifier(Q)}.`:void 0}${E.identifier(J)}${z&&E` ${E.identifier(z)}`}${$}`)}else Z.push(E`${E.raw(_.joinType)} join${W} ${G}${$}`);if(X<Y.length-1)Z.push(E` `)}return E.join(Z)}buildFromTable(Y){if(M(Y,P)&&Y[P.Symbol.IsAlias]){let Z=E`${E.identifier(Y[P.Symbol.OriginalName])}`;if(Y[P.Symbol.Schema])Z=E`${E.identifier(Y[P.Symbol.Schema])}.${Z}`;return E`${Z} ${E.identifier(Y[P.Symbol.Name])}`}return Y}buildSelectQuery({withList:Y,fields:Z,fieldsFlat:X,where:_,having:G,table:W,joins:$,orderBy:H,groupBy:Q,limit:J,offset:z,lockingClause:O,distinct:D,setOperators:V}){let R=X??q1(Z);for(let e of R)if(M(e.field,E0)&&c0(e.field.table)!==(M(W,P0)?W._.alias:M(W,P2)?W[A0].name:M(W,x)?void 0:c0(W))&&!((F0)=>$?.some(({alias:b0})=>b0===(F0[P.Symbol.IsAlias]?c0(F0):F0[P.Symbol.BaseName])))(e.field.table)){let F0=c0(e.field.table);throw new Error(`Your "${e.path.join("->")}" field references a column "${F0}"."${e.field.name}", but the table "${F0}" is not part of the query! Did you forget to join it?`)}let A=!$||$.length===0,g=this.buildWithCTE(Y),b;if(D)b=D===!0?E` distinct`:E` distinct on (${E.join(D.on,E`, `)})`;let f=this.buildSelection(R,{isSingleTable:A}),h=this.buildFromTable(W),I=this.buildJoins($),N=_?E` where ${_}`:void 0,q=G?E` having ${G}`:void 0,K;if(H&&H.length>0)K=E` order by ${E.join(H,E`, `)}`;let p;if(Q&&Q.length>0)p=E` group by ${E.join(Q,E`, `)}`;let s=typeof J==="object"||typeof J==="number"&&J>=0?E` limit ${J}`:void 0,C=z?E` offset ${z}`:void 0,t=E.empty();if(O){let e=E` for ${E.raw(O.strength)}`;if(O.config.of)e.append(E` of ${E.join(Array.isArray(O.config.of)?O.config.of:[O.config.of],E`, `)}`);if(O.config.noWait)e.append(E` nowait`);else if(O.config.skipLocked)e.append(E` skip locked`);t.append(e)}let m=E`${g}select${b} ${f} from ${h}${I}${N}${p}${q}${K}${s}${C}${t}`;if(V.length>0)return this.buildSetOperations(m,V);return m}buildSetOperations(Y,Z){let[X,..._]=Z;if(!X)throw new Error("Cannot pass undefined values to any set operator");if(_.length===0)return this.buildSetOperationQuery({leftSelect:Y,setOperator:X});return this.buildSetOperations(this.buildSetOperationQuery({leftSelect:Y,setOperator:X}),_)}buildSetOperationQuery({leftSelect:Y,setOperator:{type:Z,isAll:X,rightSelect:_,limit:G,orderBy:W,offset:$}}){let H=E`(${Y.getSQL()}) `,Q=E`(${_.getSQL()})`,J;if(W&&W.length>0){let V=[];for(let R of W)if(M(R,j))V.push(E.identifier(R.name));else if(M(R,x)){for(let A=0;A<R.queryChunks.length;A++){let g=R.queryChunks[A];if(M(g,j))R.queryChunks[A]=E.identifier(g.name)}V.push(E`${R}`)}else V.push(E`${R}`);J=E` order by ${E.join(V,E`, `)} `}let z=typeof G==="object"||typeof G==="number"&&G>=0?E` limit ${G}`:void 0,O=E.raw(`${Z} ${X?"all ":""}`),D=$?E` offset ${$}`:void 0;return E`${H}${O}${Q}${J}${z}${D}`}buildInsertQuery({table:Y,values:Z,onConflict:X,returning:_,withList:G,select:W,overridingSystemValue_:$}){let H=[],Q=Y[P.Symbol.Columns],J=Object.entries(Q).filter(([g,b])=>!b.shouldDisableInsert()),z=J.map(([,g])=>E.identifier(this.casing.getColumnCasing(g)));if(W){let g=Z;if(M(g,x))H.push(g);else H.push(g.getSQL())}else{let g=Z;H.push(E.raw("values "));for(let[b,f]of g.entries()){let h=[];for(let[I,N]of J){let q=f[I];if(q===void 0||M(q,N1)&&q.value===void 0)if(N.defaultFn!==void 0){let K=N.defaultFn(),p=M(K,x)?K:E.param(K,N);h.push(p)}else if(!N.default&&N.onUpdateFn!==void 0){let K=N.onUpdateFn(),p=M(K,x)?K:E.param(K,N);h.push(p)}else h.push(E`default`);else h.push(q)}if(H.push(h),b<g.length-1)H.push(E`, `)}}let O=this.buildWithCTE(G),D=E.join(H),V=_?E` returning ${this.buildSelection(_,{isSingleTable:!0})}`:void 0,R=X?E` on conflict ${X}`:void 0,A=$===!0?E`overriding system value `:void 0;return E`${O}insert into ${Y} ${z} ${A}${D}${R}${V}`}buildRefreshMaterializedViewQuery({view:Y,concurrently:Z,withNoData:X}){let _=Z?E` concurrently`:void 0,G=X?E` with no data`:void 0;return E`refresh materialized view${_} ${Y}${G}`}prepareTyping(Y){if(M(Y,x6)||M(Y,v6))return"json";else if(M(Y,h6))return"decimal";else if(M(Y,f6))return"time";else if(M(Y,b6)||M(Y,k6))return"timestamp";else if(M(Y,P6)||M(Y,S6))return"date";else if(M(Y,g6))return"uuid";else return"none"}sqlToQuery(Y,Z){return Y.toQuery({casing:this.casing,escapeName:this.escapeName,escapeParam:this.escapeParam,escapeString:this.escapeString,prepareTyping:this.prepareTyping,invokeSource:Z})}buildRelationalQueryWithoutPK({fullSchema:Y,schema:Z,tableNamesMap:X,table:_,tableConfig:G,queryConfig:W,tableAlias:$,nestedQueryRelation:H,joinOn:Q}){let J=[],z,O,D=[],V,R=[];if(W===!0)J=Object.entries(G.columns).map(([b,f])=>({dbKey:f.name,tsKey:b,field:o1(f,$),relationTableTsKey:void 0,isJson:!1,selection:[]}));else{let g=Object.fromEntries(Object.entries(G.columns).map(([q,K])=>[q,o1(K,$)]));if(W.where){let q=typeof W.where==="function"?W.where(g,iW()):W.where;V=q&&M2(q,$)}let b=[],f=[];if(W.columns){let q=!1;for(let[K,p]of Object.entries(W.columns)){if(p===void 0)continue;if(K in G.columns){if(!q&&p===!0)q=!0;f.push(K)}}if(f.length>0)f=q?f.filter((K)=>W.columns?.[K]===!0):Object.keys(G.columns).filter((K)=>!f.includes(K))}else f=Object.keys(G.columns);for(let q of f){let K=G.columns[q];b.push({tsKey:q,value:K})}let h=[];if(W.with)h=Object.entries(W.with).filter((q)=>!!q[1]).map(([q,K])=>({tsKey:q,queryConfig:K,relation:G.relations[q]}));let I;if(W.extras){I=typeof W.extras==="function"?W.extras(g,{sql:E}):W.extras;for(let[q,K]of Object.entries(I))b.push({tsKey:q,value:z5(K,$)})}for(let{tsKey:q,value:K}of b)J.push({dbKey:M(K,x.Aliased)?K.fieldAlias:G.columns[q].name,tsKey:q,field:M(K,E0)?o1(K,$):K,relationTableTsKey:void 0,isJson:!1,selection:[]});let N=typeof W.orderBy==="function"?W.orderBy(g,oW()):W.orderBy??[];if(!Array.isArray(N))N=[N];D=N.map((q)=>{if(M(q,E0))return o1(q,$);return M2(q,$)}),z=W.limit,O=W.offset;for(let{tsKey:q,queryConfig:K,relation:p}of h){let s=rW(Z,X,p),C=y4(p.referencedTable),t=X[C],m=`${$}_${q}`,e=I2(...s.fields.map((J1,r1)=>y6(o1(s.references[r1],m),o1(J1,$)))),F0=this.buildRelationalQueryWithoutPK({fullSchema:Y,schema:Z,tableNamesMap:X,table:Y[t],tableConfig:Z[t],queryConfig:M(p,C4)?K===!0?{limit:1}:{...K,limit:1}:K,tableAlias:m,joinOn:e,nestedQueryRelation:p}),b0=E`${E.identifier(m)}.${E.identifier("data")}`.as(q);R.push({on:E`true`,table:new P0(F0.sql,{},m),alias:m,joinType:"left",lateral:!0}),J.push({dbKey:q,tsKey:q,field:b0,relationTableTsKey:t,isJson:!0,selection:F0.selection})}}if(J.length===0)throw new q6({message:`No fields selected for table "${G.tsName}" ("${$}")`});let A;if(V=I2(Q,V),H){let g=E`json_build_array(${E.join(J.map(({field:h,tsKey:I,isJson:N})=>N?E`${E.identifier(`${$}_${I}`)}.${E.identifier("data")}`:M(h,x.Aliased)?h.sql:h),E`, `)})`;if(M(H,B2))g=E`coalesce(json_agg(${g}${D.length>0?E` order by ${E.join(D,E`, `)}`:void 0}), '[]'::json)`;let b=[{dbKey:"data",tsKey:"data",field:g.as("data"),isJson:!0,relationTableTsKey:G.tsName,selection:J}];if(z!==void 0||O!==void 0||D.length>0)A=this.buildSelectQuery({table:K6(_,$),fields:{},fieldsFlat:[{path:[],field:E.raw("*")}],where:V,limit:z,offset:O,orderBy:D,setOperators:[]}),V=void 0,z=void 0,O=void 0,D=[];else A=K6(_,$);A=this.buildSelectQuery({table:M(A,d0)?A:new P0(A,{},$),fields:{},fieldsFlat:b.map(({field:h})=>({path:[],field:M(h,E0)?o1(h,$):h})),joins:R,where:V,limit:z,offset:O,orderBy:D,setOperators:[]})}else A=this.buildSelectQuery({table:K6(_,$),fields:{},fieldsFlat:J.map(({field:g})=>({path:[],field:M(g,E0)?o1(g,$):g})),joins:R,where:V,limit:z,offset:O,orderBy:D,setOperators:[]});return{tableTsKey:G.tsName,sql:A,selection:J}}}class k5{static[F]="TypedQueryBuilder";getSelectedFields(){return this._.selectedFields}}class H1{static[F]="PgSelectBuilder";fields;session;dialect;withList=[];distinct;constructor(Y){if(this.fields=Y.fields,this.session=Y.session,this.dialect=Y.dialect,Y.withList)this.withList=Y.withList;this.distinct=Y.distinct}authToken;setToken(Y){return this.authToken=Y,this}from(Y){let Z=!!this.fields,X=Y,_;if(this.fields)_=this.fields;else if(M(X,P0))_=Object.fromEntries(Object.keys(X._.selectedFields).map((G)=>[G,X[G]]));else if(M(X,P2))_=X[A0].selectedFields;else if(M(X,x))_={};else _=B7(X);return new g5({table:X,fields:_,isPartialSelect:Z,session:this.session,dialect:this.dialect,withList:this.withList,distinct:this.distinct}).setToken(this.authToken)}}class A$ extends k5{static[F]="PgSelectQueryBuilder";_;config;joinsNotNullableMap;tableName;isPartialSelect;session;dialect;cacheConfig=void 0;usedTables=new Set;constructor({table:Y,fields:Z,isPartialSelect:X,session:_,dialect:G,withList:W,distinct:$}){super();this.config={withList:W,table:Y,fields:{...Z},distinct:$,setOperators:[]},this.isPartialSelect=X,this.session=_,this.dialect=G,this._={selectedFields:Z,config:this.config},this.tableName=J4(Y),this.joinsNotNullableMap=typeof this.tableName==="string"?{[this.tableName]:!0}:{};for(let H of p1(Y))this.usedTables.add(H)}getUsedTables(){return[...this.usedTables]}createJoin(Y,Z){return(X,_)=>{let G=this.tableName,W=J4(X);for(let $ of p1(X))this.usedTables.add($);if(typeof W==="string"&&this.config.joins?.some(($)=>$.alias===W))throw new Error(`Alias "${W}" is already used in this query`);if(!this.isPartialSelect){if(Object.keys(this.joinsNotNullableMap).length===1&&typeof G==="string")this.config.fields={[G]:this.config.fields};if(typeof W==="string"&&!M(X,x)){let $=M(X,P0)?X._.selectedFields:M(X,L1)?X[A0].selectedFields:X[P.Symbol.Columns];this.config.fields[W]=$}}if(typeof _==="function")_=_(new Proxy(this.config.fields,new j0({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));if(!this.config.joins)this.config.joins=[];if(this.config.joins.push({on:_,table:X,joinType:Y,alias:W,lateral:Z}),typeof W==="string")switch(Y){case"left":{this.joinsNotNullableMap[W]=!1;break}case"right":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([$])=>[$,!1])),this.joinsNotNullableMap[W]=!0;break}case"cross":case"inner":{this.joinsNotNullableMap[W]=!0;break}case"full":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([$])=>[$,!1])),this.joinsNotNullableMap[W]=!1;break}}return this}}leftJoin=this.createJoin("left",!1);leftJoinLateral=this.createJoin("left",!0);rightJoin=this.createJoin("right",!1);innerJoin=this.createJoin("inner",!1);innerJoinLateral=this.createJoin("inner",!0);fullJoin=this.createJoin("full",!1);crossJoin=this.createJoin("cross",!1);crossJoinLateral=this.createJoin("cross",!0);createSetOperator(Y,Z){return(X)=>{let _=typeof X==="function"?X(FO()):X;if(!A2(this.getSelectedFields(),_.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:Y,isAll:Z,rightSelect:_}),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(Y){return this.config.setOperators.push(...Y),this}where(Y){if(typeof Y==="function")Y=Y(new Proxy(this.config.fields,new j0({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));return this.config.where=Y,this}having(Y){if(typeof Y==="function")Y=Y(new Proxy(this.config.fields,new j0({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));return this.config.having=Y,this}groupBy(...Y){if(typeof Y[0]==="function"){let Z=Y[0](new Proxy(this.config.fields,new j0({sqlAliasedBehavior:"alias",sqlBehavior:"sql"})));this.config.groupBy=Array.isArray(Z)?Z:[Z]}else this.config.groupBy=Y;return this}orderBy(...Y){if(typeof Y[0]==="function"){let Z=Y[0](new Proxy(this.config.fields,new j0({sqlAliasedBehavior:"alias",sqlBehavior:"sql"}))),X=Array.isArray(Z)?Z:[Z];if(this.config.setOperators.length>0)this.config.setOperators.at(-1).orderBy=X;else this.config.orderBy=X}else{let Z=Y;if(this.config.setOperators.length>0)this.config.setOperators.at(-1).orderBy=Z;else this.config.orderBy=Z}return this}limit(Y){if(this.config.setOperators.length>0)this.config.setOperators.at(-1).limit=Y;else this.config.limit=Y;return this}offset(Y){if(this.config.setOperators.length>0)this.config.setOperators.at(-1).offset=Y;else this.config.offset=Y;return this}for(Y,Z={}){return this.config.lockingClause={strength:Y,config:Z},this}getSQL(){return this.dialect.buildSelectQuery(this.config)}toSQL(){let{typings:Y,...Z}=this.dialect.sqlToQuery(this.getSQL());return Z}as(Y){let Z=[];if(Z.push(...p1(this.config.table)),this.config.joins)for(let X of this.config.joins)Z.push(...p1(X.table));return new Proxy(new P0(this.getSQL(),this.config.fields,Y,!1,[...new Set(Z)]),new j0({alias:Y,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}getSelectedFields(){return new Proxy(this.config.fields,new j0({alias:this.tableName,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}$dynamic(){return this}$withCache(Y){return this.cacheConfig=Y===void 0?{config:{},enable:!0,autoInvalidate:!0}:Y===!1?{enable:!1}:{enable:!0,autoInvalidate:!0,...Y},this}}class g5 extends A${static[F]="PgSelect";_prepare(Y){let{session:Z,config:X,dialect:_,joinsNotNullableMap:G,authToken:W,cacheConfig:$,usedTables:H}=this;if(!Z)throw new Error("Cannot execute a query on a query builder. Please use a database instance instead.");let{fields:Q}=X;return D0.startActiveSpan("drizzle.prepareQuery",()=>{let J=q1(Q),z=Z.prepareQuery(_.sqlToQuery(this.getSQL()),J,Y,!0,void 0,{type:"select",tables:[...H]},$);return z.joinsNotNullableMap=G,z.setToken(W)})}prepare(Y){return this._prepare(Y)}authToken;setToken(Y){return this.authToken=Y,this}execute=(Y)=>{return D0.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(Y,this.authToken)})}}I7(g5,[$1]);function T8(Y,Z){return(X,_,...G)=>{let W=[_,...G].map(($)=>({type:Y,isAll:Z,rightSelect:$}));for(let $ of W)if(!A2(X.getSelectedFields(),$.rightSelect.getSelectedFields()))throw new Error("Set operator error (union / intersect / except): selected fields are not the same or are in a different order");return X.addSetOperators(W)}}var FO=()=>({union:OO,unionAll:EO,intersect:DO,intersectAll:LO,except:VO,exceptAll:MO}),OO=T8("union",!1),EO=T8("union",!0),DO=T8("intersect",!1),LO=T8("intersect",!0),VO=T8("except",!1),MO=T8("except",!0);class S2{static[F]="PgQueryBuilder";dialect;dialectConfig;constructor(Y){this.dialect=M(Y,c4)?Y:void 0,this.dialectConfig=M(Y,c4)?void 0:Y}$with=(Y,Z)=>{let X=this;return{as:(G)=>{if(typeof G==="function")G=G(X);return new Proxy(new D2(G.getSQL(),Z??("getSelectedFields"in G?G.getSelectedFields()??{}:{}),Y,!0),new j0({alias:Y,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}};with(...Y){let Z=this;function X(W){return new H1({fields:W??void 0,session:void 0,dialect:Z.getDialect(),withList:Y})}function _(W){return new H1({fields:W??void 0,session:void 0,dialect:Z.getDialect(),distinct:!0})}function G(W,$){return new H1({fields:$??void 0,session:void 0,dialect:Z.getDialect(),distinct:{on:W}})}return{select:X,selectDistinct:_,selectDistinctOn:G}}select(Y){return new H1({fields:Y??void 0,session:void 0,dialect:this.getDialect()})}selectDistinct(Y){return new H1({fields:Y??void 0,session:void 0,dialect:this.getDialect(),distinct:!0})}selectDistinctOn(Y,Z){return new H1({fields:Z??void 0,session:void 0,dialect:this.getDialect(),distinct:{on:Y}})}getDialect(){if(!this.dialect)this.dialect=new c4(this.dialectConfig);return this.dialect}}function p1(Y){if(M(Y,d0))return[Y[g4]?`${Y[g4]}.${Y[P.Symbol.BaseName]}`:Y[P.Symbol.BaseName]];if(M(Y,P0))return Y._.usedTables??[];if(M(Y,x))return Y.usedTables??[];return[]}class e6 extends $1{constructor(Y,Z,X,_){super();this.session=Z,this.dialect=X,this.config={table:Y,withList:_}}static[F]="PgDelete";config;cacheConfig;where(Y){return this.config.where=Y,this}returning(Y=this.config.table[P.Symbol.Columns]){return this.config.returningFields=Y,this.config.returning=q1(Y),this}getSQL(){return this.dialect.buildDeleteQuery(this.config)}toSQL(){let{typings:Y,...Z}=this.dialect.sqlToQuery(this.getSQL());return Z}_prepare(Y){return D0.startActiveSpan("drizzle.prepareQuery",()=>{return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,Y,!0,void 0,{type:"delete",tables:p1(this.config.table)},this.cacheConfig)})}prepare(Y){return this._prepare(Y)}authToken;setToken(Y){return this.authToken=Y,this}execute=(Y)=>{return D0.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(Y,this.authToken)})};getSelectedFields(){return this.config.returningFields?new Proxy(this.config.returningFields,new j0({alias:c0(this.config.table),sqlAliasedBehavior:"alias",sqlBehavior:"error"})):void 0}$dynamic(){return this}}class YY{constructor(Y,Z,X,_,G){this.table=Y,this.session=Z,this.dialect=X,this.withList=_,this.overridingSystemValue_=G}static[F]="PgInsertBuilder";authToken;setToken(Y){return this.authToken=Y,this}overridingSystemValue(){return this.overridingSystemValue_=!0,this}values(Y){if(Y=Array.isArray(Y)?Y:[Y],Y.length===0)throw new Error("values() must be called with at least one value");let Z=Y.map((X)=>{let _={},G=this.table[P.Symbol.Columns];for(let W of Object.keys(X)){let $=X[W];_[W]=M($,x)?$:new N1($,G[W])}return _});return new y5(this.table,Z,this.session,this.dialect,this.withList,!1,this.overridingSystemValue_).setToken(this.authToken)}select(Y){let Z=typeof Y==="function"?Y(new S2):Y;if(!M(Z,x)&&!A2(this.table[C6],Z._.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 y5(this.table,Z,this.session,this.dialect,this.withList,!0)}}class y5 extends $1{constructor(Y,Z,X,_,G,W,$){super();this.session=X,this.dialect=_,this.config={table:Y,values:Z,withList:G,select:W,overridingSystemValue_:$}}static[F]="PgInsert";config;cacheConfig;returning(Y=this.config.table[P.Symbol.Columns]){return this.config.returningFields=Y,this.config.returning=q1(Y),this}onConflictDoNothing(Y={}){if(Y.target===void 0)this.config.onConflict=E`do nothing`;else{let Z="";Z=Array.isArray(Y.target)?Y.target.map((_)=>this.dialect.escapeName(this.dialect.casing.getColumnCasing(_))).join(","):this.dialect.escapeName(this.dialect.casing.getColumnCasing(Y.target));let X=Y.where?E` where ${Y.where}`:void 0;this.config.onConflict=E`(${E.raw(Z)})${X} do nothing`}return this}onConflictDoUpdate(Y){if(Y.where&&(Y.targetWhere||Y.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 Z=Y.where?E` where ${Y.where}`:void 0,X=Y.targetWhere?E` where ${Y.targetWhere}`:void 0,_=Y.setWhere?E` where ${Y.setWhere}`:void 0,G=this.dialect.buildUpdateSet(this.config.table,j6(this.config.table,Y.set)),W="";return W=Array.isArray(Y.target)?Y.target.map(($)=>this.dialect.escapeName(this.dialect.casing.getColumnCasing($))).join(","):this.dialect.escapeName(this.dialect.casing.getColumnCasing(Y.target)),this.config.onConflict=E`(${E.raw(W)})${X} do update set ${G}${Z}${_}`,this}getSQL(){return this.dialect.buildInsertQuery(this.config)}toSQL(){let{typings:Y,...Z}=this.dialect.sqlToQuery(this.getSQL());return Z}_prepare(Y){return D0.startActiveSpan("drizzle.prepareQuery",()=>{return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,Y,!0,void 0,{type:"insert",tables:p1(this.config.table)},this.cacheConfig)})}prepare(Y){return this._prepare(Y)}authToken;setToken(Y){return this.authToken=Y,this}execute=(Y)=>{return D0.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(Y,this.authToken)})};getSelectedFields(){return this.config.returningFields?new Proxy(this.config.returningFields,new j0({alias:c0(this.config.table),sqlAliasedBehavior:"alias",sqlBehavior:"error"})):void 0}$dynamic(){return this}}class p5 extends $1{constructor(Y,Z,X){super();this.session=Z,this.dialect=X,this.config={view:Y}}static[F]="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:Y,...Z}=this.dialect.sqlToQuery(this.getSQL());return Z}_prepare(Y){return D0.startActiveSpan("drizzle.prepareQuery",()=>{return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),void 0,Y,!0)})}prepare(Y){return this._prepare(Y)}authToken;setToken(Y){return this.authToken=Y,this}execute=(Y)=>{return D0.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(Y,this.authToken)})}}class ZY{constructor(Y,Z,X,_){this.table=Y,this.session=Z,this.dialect=X,this.withList=_}static[F]="PgUpdateBuilder";authToken;setToken(Y){return this.authToken=Y,this}set(Y){return new w$(this.table,j6(this.table,Y),this.session,this.dialect,this.withList).setToken(this.authToken)}}class w$ extends $1{constructor(Y,Z,X,_,G){super();this.session=X,this.dialect=_,this.config={set:Z,table:Y,withList:G,joins:[]},this.tableName=J4(Y),this.joinsNotNullableMap=typeof this.tableName==="string"?{[this.tableName]:!0}:{}}static[F]="PgUpdate";config;tableName;joinsNotNullableMap;cacheConfig;from(Y){let Z=Y,X=J4(Z);if(typeof X==="string")this.joinsNotNullableMap[X]=!0;return this.config.from=Z,this}getTableLikeFields(Y){if(M(Y,d0))return Y[P.Symbol.Columns];else if(M(Y,P0))return Y._.selectedFields;return Y[A0].selectedFields}createJoin(Y){return(Z,X)=>{let _=J4(Z);if(typeof _==="string"&&this.config.joins.some((G)=>G.alias===_))throw new Error(`Alias "${_}" is already used in this query`);if(typeof X==="function"){let G=this.config.from&&!M(this.config.from,x)?this.getTableLikeFields(this.config.from):void 0;X=X(new Proxy(this.config.table[P.Symbol.Columns],new j0({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})),G&&new Proxy(G,new j0({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})))}if(this.config.joins.push({on:X,table:Z,joinType:Y,alias:_}),typeof _==="string")switch(Y){case"left":{this.joinsNotNullableMap[_]=!1;break}case"right":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([G])=>[G,!1])),this.joinsNotNullableMap[_]=!0;break}case"inner":{this.joinsNotNullableMap[_]=!0;break}case"full":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([G])=>[G,!1])),this.joinsNotNullableMap[_]=!1;break}}return this}}leftJoin=this.createJoin("left");rightJoin=this.createJoin("right");innerJoin=this.createJoin("inner");fullJoin=this.createJoin("full");where(Y){return this.config.where=Y,this}returning(Y){if(!Y){if(Y=Object.assign({},this.config.table[P.Symbol.Columns]),this.config.from){let Z=J4(this.config.from);if(typeof Z==="string"&&this.config.from&&!M(this.config.from,x)){let X=this.getTableLikeFields(this.config.from);Y[Z]=X}for(let X of this.config.joins){let _=J4(X.table);if(typeof _==="string"&&!M(X.table,x)){let G=this.getTableLikeFields(X.table);Y[_]=G}}}}return this.config.returningFields=Y,this.config.returning=q1(Y),this}getSQL(){return this.dialect.buildUpdateQuery(this.config)}toSQL(){let{typings:Y,...Z}=this.dialect.sqlToQuery(this.getSQL());return Z}_prepare(Y){let Z=this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,Y,!0,void 0,{type:"insert",tables:p1(this.config.table)},this.cacheConfig);return Z.joinsNotNullableMap=this.joinsNotNullableMap,Z}prepare(Y){return this._prepare(Y)}authToken;setToken(Y){return this.authToken=Y,this}execute=(Y)=>{return this._prepare().execute(Y,this.authToken)};getSelectedFields(){return this.config.returningFields?new Proxy(this.config.returningFields,new j0({alias:c0(this.config.table),sqlAliasedBehavior:"alias",sqlBehavior:"error"})):void 0}$dynamic(){return this}}class v2 extends x{constructor(Y){super(v2.buildEmbeddedCount(Y.source,Y.filters).queryChunks);this.params=Y,this.mapWith(Number),this.session=Y.session,this.sql=v2.buildCount(Y.source,Y.filters)}sql;token;static[F]="PgCountBuilder";[Symbol.toStringTag]="PgCountBuilder";session;static buildEmbeddedCount(Y,Z){return E`(select count(*) from ${Y}${E.raw(" where ").if(Z)}${Z})`}static buildCount(Y,Z){return E`select count(*) as count from ${Y}${E.raw(" where ").if(Z)}${Z};`}setToken(Y){return this.token=Y,this}then(Y,Z){return Promise.resolve(this.session.count(this.sql,this.token)).then(Y,Z)}catch(Y){return this.then(void 0,Y)}finally(Y){return this.then((Z)=>{return Y?.(),Z},(Z)=>{throw Y?.(),Z})}}class u5{constructor(Y,Z,X,_,G,W,$){this.fullSchema=Y,this.schema=Z,this.tableNamesMap=X,this.table=_,this.tableConfig=G,this.dialect=W,this.session=$}static[F]="PgRelationalQueryBuilder";findMany(Y){return new m5(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,Y?Y:{},"many")}findFirst(Y){return new m5(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,Y?{...Y,limit:1}:{limit:1},"first")}}class m5 extends $1{constructor(Y,Z,X,_,G,W,$,H,Q){super();this.fullSchema=Y,this.schema=Z,this.tableNamesMap=X,this.table=_,this.tableConfig=G,this.dialect=W,this.session=$,this.config=H,this.mode=Q}static[F]="PgRelationalQuery";_prepare(Y){return D0.startActiveSpan("drizzle.prepareQuery",()=>{let{query:Z,builtQuery:X}=this._toSQL();return this.session.prepareQuery(X,void 0,Y,!0,(_,G)=>{let W=_.map(($)=>p6(this.schema,this.tableConfig,$,Z.selection,G));if(this.mode==="first")return W[0];return W})})}prepare(Y){return this._prepare(Y)}_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 Y=this._getQuery(),Z=this.dialect.sqlToQuery(Y.sql);return{query:Y,builtQuery:Z}}toSQL(){return this._toSQL().builtQuery}authToken;setToken(Y){return this.authToken=Y,this}execute(){return D0.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(void 0,this.authToken)})}}class d5 extends $1{constructor(Y,Z,X,_){super();this.execute=Y,this.sql=Z,this.query=X,this.mapBatchResult=_}static[F]="PgRaw";getSQL(){return this.sql}getQuery(){return this.query}mapResult(Y,Z){return Z?this.mapBatchResult(Y):Y}_prepare(){return this}isResponseInArrayMode(){return!1}}class x2{constructor(Y,Z,X){if(this.dialect=Y,this.session=Z,this._=X?{schema:X.schema,fullSchema:X.fullSchema,tableNamesMap:X.tableNamesMap,session:Z}:{schema:void 0,fullSchema:{},tableNamesMap:{},session:Z},this.query={},this._.schema)for(let[_,G]of Object.entries(this._.schema))this.query[_]=new u5(X.fullSchema,this._.schema,this._.tableNamesMap,X.fullSchema[_],G,Y,Z);this.$cache={invalidate:async(_)=>{}}}static[F]="PgDatabase";query;$with=(Y,Z)=>{let X=this;return{as:(G)=>{if(typeof G==="function")G=G(new S2(X.dialect));return new Proxy(new D2(G.getSQL(),Z??("getSelectedFields"in G?G.getSelectedFields()??{}:{}),Y,!0),new j0({alias:Y,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}};$count(Y,Z){return new v2({source:Y,filters:Z,session:this.session})}$cache;with(...Y){let Z=this;function X(Q){return new H1({fields:Q??void 0,session:Z.session,dialect:Z.dialect,withList:Y})}function _(Q){return new H1({fields:Q??void 0,session:Z.session,dialect:Z.dialect,withList:Y,distinct:!0})}function G(Q,J){return new H1({fields:J??void 0,session:Z.session,dialect:Z.dialect,withList:Y,distinct:{on:Q}})}function W(Q){return new ZY(Q,Z.session,Z.dialect,Y)}function $(Q){return new YY(Q,Z.session,Z.dialect,Y)}function H(Q){return new e6(Q,Z.session,Z.dialect,Y)}return{select:X,selectDistinct:_,selectDistinctOn:G,update:W,insert:$,delete:H}}select(Y){return new H1({fields:Y??void 0,session:this.session,dialect:this.dialect})}selectDistinct(Y){return new H1({fields:Y??void 0,session:this.session,dialect:this.dialect,distinct:!0})}selectDistinctOn(Y,Z){return new H1({fields:Z??void 0,session:this.session,dialect:this.dialect,distinct:{on:Y}})}update(Y){return new ZY(Y,this.session,this.dialect)}insert(Y){return new YY(Y,this.session,this.dialect)}delete(Y){return new e6(Y,this.session,this.dialect)}refreshMaterializedView(Y){return new p5(Y,this.session,this.dialect)}authToken;execute(Y){let Z=typeof Y==="string"?E.raw(Y):Y.getSQL(),X=this.dialect.sqlToQuery(Z),_=this.session.prepareQuery(X,void 0,void 0,!1);return new d5(()=>_.execute(void 0,this.authToken),Z,X,(G)=>_.mapResult(G,!0))}transaction(Y,Z){return this.session.transaction(Y,Z)}}class R${static[F]="Cache"}class h2 extends R${strategy(){return"all"}static[F]="NoopCache";async get(Y){return}async put(Y,Z,X,_){}async onMutate(Y){}}async function c5(Y,Z){let X=`${Y}-${JSON.stringify(Z)}`,G=new TextEncoder().encode(X),W=await crypto.subtle.digest("SHA-256",G);return[...new Uint8Array(W)].map((Q)=>Q.toString(16).padStart(2,"0")).join("")}class l5{constructor(Y,Z,X,_){if(this.query=Y,this.cache=Z,this.queryMetadata=X,this.cacheConfig=_,Z&&Z.strategy()==="all"&&_===void 0)this.cacheConfig={enable:!0,autoInvalidate:!0};if(!this.cacheConfig?.enable)this.cacheConfig=void 0}authToken;getQuery(){return this.query}mapResult(Y,Z){return Y}setToken(Y){return this.authToken=Y,this}static[F]="PgPreparedQuery";joinsNotNullableMap;async queryWithCache(Y,Z,X){if(this.cache===void 0||M(this.cache,h2)||this.queryMetadata===void 0)try{return await X()}catch(_){throw new H4(Y,Z,_)}if(this.cacheConfig&&!this.cacheConfig.enable)try{return await X()}catch(_){throw new H4(Y,Z,_)}if((this.queryMetadata.type==="insert"||this.queryMetadata.type==="update"||this.queryMetadata.type==="delete")&&this.queryMetadata.tables.length>0)try{let[_]=await Promise.all([X(),this.cache.onMutate({tables:this.queryMetadata.tables})]);return _}catch(_){throw new H4(Y,Z,_)}if(!this.cacheConfig)try{return await X()}catch(_){throw new H4(Y,Z,_)}if(this.queryMetadata.type==="select"){let _=await this.cache.get(this.cacheConfig.tag??await c5(Y,Z),this.queryMetadata.tables,this.cacheConfig.tag!==void 0,this.cacheConfig.autoInvalidate);if(_===void 0){let G;try{G=await X()}catch(W){throw new H4(Y,Z,W)}return await this.cache.put(this.cacheConfig.tag??await c5(Y,Z),G,this.cacheConfig.autoInvalidate?this.queryMetadata.tables:[],this.cacheConfig.tag!==void 0,this.cacheConfig.config),G}return _}try{return await X()}catch(_){throw new H4(Y,Z,_)}}}class i5{constructor(Y){this.dialect=Y}static[F]="PgSession";execute(Y,Z){return D0.startActiveSpan("drizzle.operation",()=>{return D0.startActiveSpan("drizzle.prepareQuery",()=>{return this.prepareQuery(this.dialect.sqlToQuery(Y),void 0,void 0,!1)}).setToken(Z).execute(void 0,Z)})}all(Y){return this.prepareQuery(this.dialect.sqlToQuery(Y),void 0,void 0,!1).all()}async count(Y,Z){let X=await this.execute(Y,Z);return Number(X[0].count)}}class o5 extends x2{constructor(Y,Z,X,_=0){super(Y,Z,X);this.schema=X,this.nestedIndex=_}static[F]="PgTransaction";rollback(){throw new U5}getTransactionConfigSQL(Y){let Z=[];if(Y.isolationLevel)Z.push(`isolation level ${Y.isolationLevel}`);if(Y.accessMode)Z.push(Y.accessMode);if(typeof Y.deferrable==="boolean")Z.push(Y.deferrable?"deferrable":"not deferrable");return E.raw(Z.join(" "))}setTransaction(Y){return this.session.execute(E`set transaction ${this.getTransactionConfigSQL(Y)}`)}}class N$ extends l5{constructor(Y,Z,X,_,G,W,$,H,Q,J){super({sql:Z,params:X},G,W,$);this.client=Y,this.queryString=Z,this.params=X,this.logger=_,this.fields=H,this._isResponseInArrayMode=Q,this.customResultMapper=J}static[F]="PostgresJsPreparedQuery";async execute(Y={}){return D0.startActiveSpan("drizzle.execute",async(Z)=>{let X=Q5(this.params,Y);Z?.setAttributes({"drizzle.query.text":this.queryString,"drizzle.query.params":JSON.stringify(X)}),this.logger.logQuery(this.queryString,X);let{fields:_,queryString:G,client:W,joinsNotNullableMap:$,customResultMapper:H}=this;if(!_&&!H)return D0.startActiveSpan("drizzle.driver.execute",()=>{return this.queryWithCache(G,X,async()=>{return await W.unsafe(G,X)})});let Q=await D0.startActiveSpan("drizzle.driver.execute",()=>{return Z?.setAttributes({"drizzle.query.text":G,"drizzle.query.params":JSON.stringify(X)}),this.queryWithCache(G,X,async()=>{return await W.unsafe(G,X).values()})});return D0.startActiveSpan("drizzle.mapResponse",()=>{return H?H(Q):Q.map((J)=>N7(_,J,$))})})}all(Y={}){return D0.startActiveSpan("drizzle.execute",async(Z)=>{let X=Q5(this.params,Y);return Z?.setAttributes({"drizzle.query.text":this.queryString,"drizzle.query.params":JSON.stringify(X)}),this.logger.logQuery(this.queryString,X),D0.startActiveSpan("drizzle.driver.execute",()=>{return Z?.setAttributes({"drizzle.query.text":this.queryString,"drizzle.query.params":JSON.stringify(X)}),this.queryWithCache(this.queryString,X,async()=>{return this.client.unsafe(this.queryString,X)})})})}isResponseInArrayMode(){return this._isResponseInArrayMode}}class f2 extends i5{constructor(Y,Z,X,_={}){super(Z);this.client=Y,this.schema=X,this.options=_,this.logger=_.logger??new O5,this.cache=_.cache??new h2}static[F]="PostgresJsSession";logger;cache;prepareQuery(Y,Z,X,_,G,W,$){return new N$(this.client,Y.sql,Y.params,this.logger,this.cache,W,$,Z,_,G)}query(Y,Z){return this.logger.logQuery(Y,Z),this.client.unsafe(Y,Z).values()}queryObjects(Y,Z){return this.client.unsafe(Y,Z)}transaction(Y,Z){return this.client.begin(async(X)=>{let _=new f2(X,this.dialect,this.schema,this.options),G=new n5(this.dialect,_,this.schema);if(Z)await G.setTransaction(Z);return Y(G)})}}class n5 extends o5{constructor(Y,Z,X,_=0){super(Y,Z,X,_);this.session=Z}static[F]="PostgresJsTransaction";transaction(Y){return this.session.client.savepoint((Z)=>{let X=new f2(Z,this.dialect,this.schema,this.session.options),_=new n5(this.dialect,X,this.schema);return Y(_)})}}class I$ extends x2{static[F]="PostgresJsDatabase"}function K8(Y,Z={}){let X=(Q)=>Q;for(let Q of["1184","1082","1083","1114","1182","1185","1115","1231"])Y.options.parsers[Q]=X,Y.options.serializers[Q]=X;Y.options.serializers["114"]=X,Y.options.serializers["3802"]=X;let _=new c4({casing:Z.casing}),G;if(Z.logger===!0)G=new F5;else if(Z.logger!==!1)G=Z.logger;let W;if(Z.schema){let Q=nW(Z.schema,sW);W={fullSchema:Z.schema,schema:Q.tables,tableNamesMap:Q.tableNamesMap}}let $=new f2(Y,_,W,{logger:G,cache:Z.cache}),H=new I$(_,$,W);if(H.$client=Y,H.$cache=Z.cache,H.$cache)H.$cache.invalidate=Z.cache?.onMutate;return H}function XY(...Y){if(typeof Y[0]==="string"){let Z=C8(Y[0]);return K8(Z,Y[1])}if(C7(Y[0])){let{connection:Z,client:X,..._}=Y[0];if(X)return K8(X,_);if(typeof Z==="object"&&Z.url!==void 0){let{url:W,...$}=Z,H=C8(W,$);return K8(H,_)}let G=C8(Z);return K8(G,_)}return K8(Y[0],Y[1])}((Y)=>{function Z(X){return K8({options:{parsers:{},serializers:{}}},X)}Y.mock=Z})(XY||(XY={}));var s5={};qH(s5,{users:()=>l4,untrackedUserColumnNames:()=>AO,twoFactorMethod:()=>q$,trackedUserColumnName:()=>wO,trackableUserColumnNames:()=>T$,signInHistory:()=>NO,role:()=>C$,players:()=>r5,passwordResetAttempts:()=>IO,games:()=>GY,banishedIps:()=>BO,accountActions:()=>RO,accountAction:()=>K$});function K4(){return e0({length:24}).$type()}function B$(Y){return E`lower(${Y})`}var _Y=E`TO_CHAR(NOW() AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.MS"Z"')`,C$=E2("role",["admin","user"]),l4=B4("users",{id:j1().primaryKey().defaultRandom(),username:e0({length:16}).notNull(),emailOffered:e0({length:254}).notNull(),emailVerified:e0({length:254}),password:e0({length:254}),createdAtIso:K4().notNull().default(_Y),createdIp:e0({length:45}).notNull(),isActive:w2().notNull().default(!1),verifiedAtIso:K4(),userRole:C$().default("user")},(Y)=>[f5("usernameUniqueIndex").on(B$(Y.username)),f5("emailVerifiedUniqueIndex").on(B$(Y.emailVerified))]),AO=["id","createdAtIso","createdIp","isActive","verifiedAtIso"],T$=["username","emailOffered","emailVerified","password","userRole"],wO=E2("trackedUserColumnName",T$),K$=E2("accountAction",["cooldown","confirmEmail","signIn","resetPassword"]),RO=B4("accountActions",{userId:j1().references(()=>l4.id).primaryKey(),action:K$().notNull(),code:e0({length:254}).notNull(),wrongCodeCount:R2().notNull().default(0),expiresAtIso:K4().notNull()}),GY=B4("games",{id:j1().primaryKey().defaultRandom()}),r5=B4("players",{userId:j1().notNull().references(()=>l4.id,{onDelete:"cascade"}),gameId:j1().notNull().references(()=>GY.id,{onDelete:"cascade"}),score:R2().notNull()},(Y)=>[NW({name:"players_userId_gameId_pk",columns:[Y.userId,Y.gameId]})]),NO=B4("signInHistory",{id:j1().primaryKey().defaultRandom(),userId:j1().references(()=>l4.id,{onDelete:"cascade"}),signInTimeIso:K4().notNull().default(_Y),ipAddress:e0({length:45}).notNull(),userAgent:e0({length:1024}),successful:w2().notNull().default(!1)}),q$=E2("twoFactorMethod",["email","phone"]),IO=B4("passwordResetAttempts",{id:j1().primaryKey().defaultRandom(),userId:j1().notNull().references(()=>l4.id,{onDelete:"cascade"}),requestedIp:e0({length:45}).notNull(),requestedAtIso:K4().notNull().default(_Y),succeededIp:e0({length:45}),succeededAtIso:K4(),verificationMethod:q$().notNull()}),BO=B4("banishedIps",{ip:e0({length:45}).primaryKey(),reason:e0({length:2048}).notNull(),banishedAtIso:K4().notNull().default(_Y),banishedUntilIso:K4()});var __dirname="/home/runner/work/wayforge/wayforge/apps/tempest.games/src/database";class a5{options;sql;drizzle;observers=new Map;async setupTriggersAndNotifications(){await this.sql.file(CO.resolve(__dirname,"notify_update.sql"));let Y=[c0(l4),c0(GY),c0(r5)];await this.sql`SELECT create_notify_triggers(${this.sql.array(Y)})`,await this.sql.listen("table_update",(Z)=>{let X=Z.split(","),_=X[0],G=X[1],W=`${_}("${G}")`;if(this.observers.has(W))this.observers.get(W).next(W)})}constructor(Y=!1,Z={host:g1.POSTGRES_HOST,port:g1.POSTGRES_PORT,user:g1.POSTGRES_USER,password:g1.POSTGRES_PASSWORD,database:g1.POSTGRES_DATABASE}){this.options=Z,this.sql=C8(Z),this.drizzle=XY(this.sql,{schema:s5,logger:Y})}observe(Y,Z){if(!this.observers.has(Y))this.observers.set(Y,new H0);this.observers.get(Y).subscribe("SINGLETON",Z)}}var WY={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 TO(Y){return Number.parseInt(Y,10)}var KO=E1(WY),qO=KO.keyof().pipe((Y)=>TO(Y)),j$=E1([qO,"string"]);var e5=new a9,{logger:M1}=e5;Object.assign(console,M1,{log:M1.info});M1.info("ready");var t5=S$(import.meta.dir,"..","app"),nx=new a5({logQuery(Y,Z){M1.info("\uD83D\uDCDD query",Y,Z)}});vO({hostname:"0.0.0.0",port:g1.FRONTEND_PORT??3333,...N6??void 0,async fetch(Y){try{let Z=new Date,X=new URL(Y.url);if(M1.info(Y.method,X.pathname),X.pathname==="/")return new Response(Bun.file(S$(t5,"index.html")));if(X.pathname==="/index.html")return Response.redirect("/");let _=PO(t5,X.pathname),G=SO(_);if(!G.startsWith(t5))throw[403,"Access Denied"];if(!await P$(G).exists())return Response.redirect("/");return new Response(P$(G))}catch(Z){let X=j$(Z);if(X instanceof E1.errors===!1){let[_,G]=X,$=`${WY[_]}. ${G}`;return M1.info(`\u274C ${_}: ${$}`),new Response($,{status:_})}if(Z instanceof Error)M1.error(Z.message);else{let _=R6(Z);M1.error("frontend server threw",_)}return new Response(WY[500],{status:500})}}});function $Y(){M1.info("\uD83D\uDEEC frontend server exiting"),process.exit(0)}process.on("SIGINT",()=>{M1.info("\u2757 received SIGINT; exiting gracefully"),$Y()});process.on("SIGTERM",()=>{M1.info("\u2757 received SIGTERM; exiting gracefully"),$Y()});process.on("exit",()=>{M1.info("\u2757 received exit; exiting gracefully"),$Y()});e5.on("timeToStop",()=>{M1.info('\u2757 backend server received signal "timeToStop"; exiting gracefully'),$Y()});var{version:xO}=await Bun.file(jO.resolve(import.meta.dir,"../package.json")).json();M1.info(`\uD83D\uDEEB frontend v${xO} running at http://localhost:${g1.FRONTEND_PORT}/`);e5.emit("alive");