tempest.games 0.2.54 → 0.2.56

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,80 +1,80 @@
1
1
  #!/usr/bin/env bun
2
2
  // @bun
3
- var iH=Object.create;var{getPrototypeOf:oH,defineProperty:IZ,getOwnPropertyNames:nH}=Object;var rH=Object.prototype.hasOwnProperty;var gE=(Z,Y,X)=>{X=Z!=null?iH(oH(Z)):{};let G=Y||!Z||!Z.__esModule?IZ(X,"default",{value:Z,enumerable:!0}):X;for(let _ of nH(Z))if(!rH.call(G,_))IZ(G,_,{get:()=>Z[_],enumerable:!0});return G};var pE=(Z,Y)=>()=>(Y||Z((Y={exports:{}}).exports,Y),Y.exports);var sH=(Z,Y)=>{for(var X in Y)IZ(Z,X,{get:Y[X],enumerable:!0,configurable:!0,set:(G)=>Y[X]=()=>G})};var mE=(Z,Y)=>()=>(Z&&(Y=Z(Z=0)),Y);var uE=import.meta.require;import fE,{join as hE,normalize as kE,resolve as eW}from"path";var E4=(Z)=>Array.isArray(Z)?Z:[Z],TX=(Z,Y)=>{let X=[[],[]];for(let G of Z)if(Y(G))X[0].push(G);else X[1].push(G);return X},p8=Array,a1=(Z,Y)=>Z.includes(Y),qX=(Z,Y=0)=>[...new Array(Z)].map((X,G)=>G+Y),Y0=(Z,Y,X)=>{if(Z===void 0)return Y===void 0?[]:Array.isArray(Y)?Y:[Y];if(X?.prepend)if(Array.isArray(Y))Z.unshift(...Y);else Z.unshift(Y);else if(Array.isArray(Y))Z.push(...Y);else Z.push(Y);return Z},t1=(Z,Y)=>{if(Y===void 0||Y===null)return Z??[];if(Z===void 0||Z===null)return E4(Y);return Z.concat(Y)},jX=(...Z)=>Z.reduce(t1,[]),c1=(Z,Y,X)=>{if(Z===void 0)return Array.isArray(Y)?Y:[Y];let G=X?.isEqual??((_,$)=>_===$);for(let _ of E4(Y))if(!Z.some(($)=>G($,_)))Z.push(_);return Z},PX=(Z,Y)=>Z.reduce((X,G)=>{let _=G[Y];return X[_]=Y0(X[_],G),X},{}),e1=(Z,Y,X)=>Z.length===Y.length&&Z.every(X?.isEqual?(G,_)=>X.isEqual(G,Y[_]):(G,_)=>G===Y[_]);var H1=(Z,Y)=>y0(Z)===Y,y0=(Z)=>{let Y=typeof Z;return Y==="object"?Z===null?"null":"object":Y==="function"?"object":Y},J1={boolean:"boolean",null:"null",undefined:"undefined",bigint:"a bigint",number:"a number",object:"an object",string:"a string",symbol:"a symbol"},SX={...J1,function:"a function"};class vX extends Error{}var G0=(Z)=>P4(Z,vX),P4=(Z,Y=Error)=>{throw new Y(Z)};class v2 extends Error{name="ParseError"}var A=(Z)=>P4(Z,v2),f1=(Z)=>` ${Z}`;var i=(Z,Y)=>{let X={},G=Array.isArray(Z),_=!1;for(let[$,W]of Object.entries(Z).entries()){let H=G?Y($,W[1]):Y(...W,$);_||=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]=Y0(X[J.group],z);else X[J]=z}return _?Object.values(X):X};var BZ=Object.entries;var g0=(Z,Y)=>(Z in Y),s4=(Z,Y)=>(Y in Z);class KZ{constructor(Z){Object.assign(this,Z)}}var xX=class{};class x2 extends xX{}var aH=(Z,Y)=>{let X={},G={},_;for(_ in Z)if(_ in Y)X[_]=Z[_];else G[_]=Z[_];return[X,G]};var fX=(Z,Y)=>aH(Z,Y)[1],l1=(Z)=>Object.keys(Z).length===0,S4=(Z)=>[...Object.entries(Z),...Object.getOwnPropertySymbols(Z).map((Y)=>[Y,Z[Y]])],hX=(Z,Y)=>Object.defineProperties(Z,Object.getOwnPropertyDescriptors(Y)),kX=(Z)=>{let Y=Object.keys(Z).sort(),X={};for(let G=0;G<Y.length;G++)X[Y[G]]=Z[Y[G]];return X};var V1=f1("represents an uninitialized value"),bX=(Z)=>Object.values(Z).filter((Y)=>{if(typeof Y==="number")return!0;return typeof Z[Y]!=="number"});var CZ={Array,Boolean,Date,Error,Function,Map,Number,Promise,RegExp,Set,String,WeakMap,WeakSet},TZ=globalThis.File??Blob,qZ={ArrayBuffer,Blob,File:TZ,FormData,Headers,Request,Response,URL},tH={Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array},v4={...CZ,...qZ,...tH,String,Number,Boolean},f2=(Z)=>{let Y=Object.getPrototypeOf(Z);while(Y?.constructor&&(!g0(Y.constructor.name,v4)||!(Z instanceof v4[Y.constructor.name])))Y=Object.getPrototypeOf(Y);let X=Y?.constructor?.name;if(X===void 0||X==="Object")return;return X},h2=(Z)=>typeof Z==="object"&&Z!==null?f2(Z)??"object":y0(Z);var U0=Array.isArray,eH={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"},ZJ={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"},YJ={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"},yX={...eH,...ZJ,...YJ},k2=(Z)=>{let Y=Object(Z).name??null;return Y&&g0(Y,v4)&&v4[Y]===Z?Y:null};var jZ=(Z,Y)=>{let X=Z.prototype;while(X!==null){if(X===Y.prototype)return!0;X=Object.getPrototypeOf(X)}return!1};var gX=(Z)=>pX(Z,new Map),pX=(Z,Y)=>{if(typeof Z!=="object"||Z===null)return Z;if(Y?.has(Z))return Y.get(Z);let X=k2(Z.constructor);if(X==="Date")return new Date(Z.getTime());if(X&&X!=="Array")return Z;let G=Array.isArray(Z)?Z.slice():Object.create(Object.getPrototypeOf(Z)),_=Object.getOwnPropertyDescriptors(Z);if(Y){Y.set(Z,G);for(let $ in _){let W=_[$];if("get"in W||"set"in W)continue;W.value=pX(W.value,Y)}}return Object.defineProperties(G,_),G};var XJ=(Z)=>{let Y=V1;return()=>Y===V1?Y=Z():Y},L4=(Z)=>typeof Z==="function"&&Z.length===0;var mX=class extends Function{constructor(...Z){let Y=Z.slice(0,-1),X=Z.at(-1);try{super(...Y,X)}catch(G){return G0(`Encountered an unexpected error while compiling your definition:
4
- Message: ${G}
5
- Source: (${Z.slice(0,-1)}) => {
6
- ${Z.at(-1)}
7
- }`)}}};class h1{constructor(Z,...[Y]){return Object.assign(Object.setPrototypeOf(Z.bind(Y?.bind??this),this.constructor.prototype),Y?.attach)}}var uX=XJ(()=>{try{return new Function("return false")()}catch{return!0}});var QL=f1("brand");var dX=f1("arkInferred");var FL=f1("args");class r0{constructor(){}}var GJ=()=>{try{return((new Error().stack?.split(`
8
- `)[2]?.trim()||"").match(/\(?(.+?)(?::\d+:\d+)?\)?$/)?.[1]||"unknown").replace(/^file:\/\//,"")}catch{return"unknown"}},_J=globalThis.process?.env??{},cX={fileName:GJ,env:_J};var lX=(Z)=>Z[0].toUpperCase()+Z.slice(1);var PZ=(Z)=>new RegExp($J(Z),typeof Z==="string"?"":Z.flags);var $J=(Z)=>{return`^(?:${typeof Z==="string"?Z:Z.source})$`};var Z4={negativeLookahead:(Z)=>`(?!${Z})`,nonCapturingGroup:(Z)=>`(?:${Z})`},b2="\\",D4={" ":1,"\n":1,"\t":1};var WJ=/^-0\.?0*$/.source,oX=/[1-9]\d*/.source,HJ=/\.\d+/.source,JJ=/\.\d*[1-9]/.source,nX=(Z)=>PZ(Z4.negativeLookahead(WJ)+Z4.nonCapturingGroup("-?"+Z4.nonCapturingGroup(Z4.nonCapturingGroup("0|"+oX)+Z4.nonCapturingGroup(Z.decimalPattern)+"?")+(Z.allowDecimalOnly?"|"+Z.decimalPattern:"")+"?")),iX=nX({decimalPattern:JJ,allowDecimalOnly:!1}),QJ=iX.test.bind(iX),m8=nX({decimalPattern:HJ,allowDecimalOnly:!0}),AL=m8.test.bind(m8),zJ=/^-?\d*\.?\d*$/,UJ=(Z)=>Z.length!==0&&zJ.test(Z),y2=PZ(Z4.negativeLookahead("^-0$")+"-?"+Z4.nonCapturingGroup(Z4.nonCapturingGroup("0|"+oX))),FJ=y2.test.bind(y2),SZ=/^-?\d+$/,EJ=SZ.test.bind(SZ),rX={number:"a number",bigint:"a bigint",integer:"an integer"},sX=(Z,Y)=>`'${Z}' was parsed as ${rX[Y]} but could not be narrowed to a literal value. Avoid unnecessary leading or trailing zeros and other abnormal notation`,LJ=(Z,Y)=>Y==="number"?QJ(Z):FJ(Z),DJ=(Z,Y)=>Y==="number"?Number(Z):Number.parseInt(Z),OJ=(Z,Y)=>Y==="number"?UJ(Z):EJ(Z),aX=(Z,Y)=>vZ(Z,"number",Y),tX=(Z,Y)=>vZ(Z,"number",{...Y,strict:!0}),eX=(Z,Y)=>vZ(Z,"integer",Y),vZ=(Z,Y,X)=>{let G=DJ(Z,Y);if(!Number.isNaN(G)){if(OJ(Z,Y)){if(X?.strict)return LJ(Z,Y)?G:A(sX(Z,Y));return G}}return X?.errorOnFail?A(X?.errorOnFail===!0?`Failed to parse ${rX[Y]} from '${Z}'`:X?.errorOnFail):void 0},ZG=(Z)=>{if(Z[Z.length-1]!=="n")return;let Y=Z.slice(0,-1),X;try{X=BigInt(Y)}catch{return}if(y2.test(Y))return X;if(SZ.test(Y))return A(sX(Z,"bigint"))};var VJ="0.49.0",MJ={version:VJ,filename:cX.fileName(),FileConstructor:TZ},x4=MJ,YG=new Map,xZ=Object.create(null),g2=(Z)=>{let Y=YG.get(Z);if(Y)return Y;let X=AJ(Z);if(xZ[X])X=`${X}${xZ[X]++}`;else xZ[X]=1;return x4[X]=Z,YG.set(Z,X),X},O4=(Z)=>/^[$A-Z_a-z][\w$]*$/.test(Z),AJ=(Z)=>{switch(typeof Z){case"object":{if(Z===null)break;let Y=f2(Z)??"object";return Y[0].toLowerCase()+Y.slice(1)}case"function":return O4(Z.name)?Z.name:"fn";case"symbol":return Z.description&&O4(Z.description)?Z.description:"symbol"}return G0(`Unexpected attempt to register serializable value of type ${y0(Z)}`)};var p2=(Z)=>typeof Z==="string"?JSON.stringify(Z):typeof Z==="bigint"?`${Z}n`:`${Z}`;var XG=(Z,Y={})=>m2(Z,{onUndefined:"$ark.undefined",onBigInt:(X)=>`$ark.bigint-${X}`,...Y},[]);var o=(Z,Y)=>{switch(y0(Z)){case"object":let X=Z,G=X.constructor.name;return G==="Object"||G==="Array"?Y?.quoteKeys===!1?u8(X,Y?.indent??0,""):JSON.stringify(m2(X,a4,[]),null,Y?.indent):u8(X,Y?.indent??0,"");case"symbol":return a4.onSymbol(Z);default:return p2(Z)}},u8=(Z,Y,X)=>{if(typeof Z==="function")return a4.onFunction(Z);if(typeof Z!=="object"||Z===null)return p2(Z);let G=X+" ".repeat(Y);if(Array.isArray(Z)){if(Z.length===0)return"[]";let $=Z.map((W)=>u8(W,Y,G)).join(`,
9
- `+G);return Y?`[
10
- ${G}${$}
11
- ${X}]`:`[${$}]`}let _=Z.constructor.name;if(_==="Object"){let $=S4(Z).map(([W,H])=>{let Q=typeof W==="symbol"?a4.onSymbol(W):O4(W)?W:JSON.stringify(W),J=u8(H,Y,G);return`${G}${Q}: ${J}`});if($.length===0)return"{}";return Y?`{
3
+ var hH=Object.create;var{getPrototypeOf:kH,defineProperty:DY,getOwnPropertyNames:bH}=Object;var yH=Object.prototype.hasOwnProperty;var uE=(Y,Z,X)=>{X=Y!=null?hH(kH(Y)):{};let _=Z||!Y||!Y.__esModule?DY(X,"default",{value:Y,enumerable:!0}):X;for(let G of bH(Y))if(!yH.call(_,G))DY(_,G,{get:()=>Y[G],enumerable:!0});return _};var dE=(Y,Z)=>()=>(Z||Y((Z={exports:{}}).exports,Z),Z.exports);var gH=(Y,Z)=>{for(var X in Z)DY(Y,X,{get:Z[X],enumerable:!0,configurable:!0,set:(_)=>Z[X]=()=>_})};var cE=(Y,Z)=>()=>(Y&&(Z=Y(Y=0)),Z);var lE=import.meta.require;import bE,{join as yE,normalize as gE,resolve as uW}from"path";var F4=(Y)=>Array.isArray(Y)?Y:[Y],MX=(Y,Z)=>{let X=[[],[]];for(let _ of Y)if(Z(_))X[0].push(_);else X[1].push(_);return X},p8=Array,s1=(Y,Z)=>Y.includes(Z),AX=(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},t1=(Y,Z)=>{if(Z===void 0||Z===null)return Y??[];if(Y===void 0||Y===null)return F4(Z);return Y.concat(Z)},RX=(...Y)=>Y.reduce(t1,[]),c1=(Y,Z,X)=>{if(Y===void 0)return Array.isArray(Z)?Z:[Z];let _=X?.isEqual??((G,$)=>G===$);for(let G of F4(Z))if(!Y.some(($)=>_($,G)))Y.push(G);return Y},wX=(Y,Z)=>Y.reduce((X,_)=>{let G=_[Z];return X[G]=Z0(X[G],_),X},{}),a1=(Y,Z,X)=>Y.length===Z.length&&Y.every(X?.isEqual?(_,G)=>X.isEqual(_,Z[G]):(_,G)=>_===Z[G]);var W1=(Y,Z)=>y0(Y)===Z,y0=(Y)=>{let Z=typeof Y;return Z==="object"?Y===null?"null":"object":Z==="function"?"object":Z},H1={boolean:"boolean",null:"null",undefined:"undefined",bigint:"a bigint",number:"a number",object:"an object",string:"a string",symbol:"a symbol"},NX={...H1,function:"a function"};class IX extends Error{}var _0=(Y)=>C4(Y,IX),C4=(Y,Z=Error)=>{throw new Z(Y)};class q2 extends Error{name="ParseError"}var A=(Y)=>C4(Y,q2),S1=(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 LY=Object.entries;var g0=(Y,Z)=>(Y in Z),n4=(Y,Z)=>(Z in Y);class MY{constructor(Y){Object.assign(this,Y)}}var KX=class{};class j2 extends KX{}var pH=(Y,Z)=>{let X={},_={},G;for(G in Y)if(G in Z)X[G]=Y[G];else _[G]=Y[G];return[X,_]};var BX=(Y,Z)=>pH(Y,Z)[1],l1=(Y)=>Object.keys(Y).length===0,q4=(Y)=>[...Object.entries(Y),...Object.getOwnPropertySymbols(Y).map((Z)=>[Z,Y[Z]])],TX=(Y,Z)=>Object.defineProperties(Y,Object.getOwnPropertyDescriptors(Z)),CX=(Y)=>{let Z=Object.keys(Y).sort(),X={};for(let _=0;_<Z.length;_++)X[Z[_]]=Y[Z[_]];return X};var L1=S1("represents an uninitialized value"),qX=(Y)=>Object.values(Y).filter((Z)=>{if(typeof Z==="number")return!0;return typeof Y[Z]!=="number"});var AY={Array,Boolean,Date,Error,Function,Map,Number,Promise,RegExp,Set,String,WeakMap,WeakSet},RY=globalThis.File??Blob,wY={ArrayBuffer,Blob,File:RY,FormData,Headers,Request,Response,URL},mH={Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array},j4={...AY,...wY,...mH,String,Number,Boolean},P2=(Y)=>{let Z=Object.getPrototypeOf(Y);while(Z?.constructor&&(!g0(Z.constructor.name,j4)||!(Y instanceof j4[Z.constructor.name])))Z=Object.getPrototypeOf(Z);let X=Z?.constructor?.name;if(X===void 0||X==="Object")return;return X},S2=(Y)=>typeof Y==="object"&&Y!==null?P2(Y)??"object":y0(Y);var U0=Array.isArray,uH={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"},dH={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"},cH={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"},jX={...uH,...dH,...cH},v2=(Y)=>{let Z=Object(Y).name??null;return Z&&g0(Z,j4)&&j4[Z]===Y?Z:null};var NY=(Y,Z)=>{let X=Y.prototype;while(X!==null){if(X===Z.prototype)return!0;X=Object.getPrototypeOf(X)}return!1};var PX=(Y)=>SX(Y,new Map),SX=(Y,Z)=>{if(typeof Y!=="object"||Y===null)return Y;if(Z?.has(Y))return Z.get(Y);let X=v2(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 $ in G){let W=G[$];if("get"in W||"set"in W)continue;W.value=SX(W.value,Z)}}return Object.defineProperties(_,G),_};var lH=(Y)=>{let Z=L1;return()=>Z===L1?Z=Y():Z},E4=(Y)=>typeof Y==="function"&&Y.length===0;var vX=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
+ Message: ${_}
5
+ Source: (${Y.slice(0,-1)}) => {
6
+ ${Y.at(-1)}
7
+ }`)}}};class v1{constructor(Y,...[Z]){return Object.assign(Object.setPrototypeOf(Y.bind(Z?.bind??this),this.constructor.prototype),Z?.attach)}}var xX=lH(()=>{try{return new Function("return false")()}catch{return!0}});var FV=S1("brand");var fX=S1("arkInferred");var OV=S1("args");class r0{constructor(){}}var oH=()=>{try{return((new Error().stack?.split(`
8
+ `)[2]?.trim()||"").match(/\(?(.+?)(?::\d+:\d+)?\)?$/)?.[1]||"unknown").replace(/^file:\/\//,"")}catch{return"unknown"}},iH=globalThis.process?.env??{},hX={fileName:oH,env:iH};var kX=(Y)=>Y[0].toUpperCase()+Y.slice(1);var IY=(Y)=>new RegExp(nH(Y),typeof Y==="string"?"":Y.flags);var nH=(Y)=>{return`^(?:${typeof Y==="string"?Y:Y.source})$`};var e1={negativeLookahead:(Y)=>`(?!${Y})`,nonCapturingGroup:(Y)=>`(?:${Y})`},x2="\\",V4={" ":1,"\n":1,"\t":1};var rH=/^-0\.?0*$/.source,yX=/[1-9]\d*/.source,sH=/\.\d+/.source,tH=/\.\d*[1-9]/.source,gX=(Y)=>IY(e1.negativeLookahead(rH)+e1.nonCapturingGroup("-?"+e1.nonCapturingGroup(e1.nonCapturingGroup("0|"+yX)+e1.nonCapturingGroup(Y.decimalPattern)+"?")+(Y.allowDecimalOnly?"|"+Y.decimalPattern:"")+"?")),bX=gX({decimalPattern:tH,allowDecimalOnly:!1}),aH=bX.test.bind(bX),m8=gX({decimalPattern:sH,allowDecimalOnly:!0}),NV=m8.test.bind(m8),eH=/^-?\d*\.?\d*$/,YJ=(Y)=>Y.length!==0&&eH.test(Y),f2=IY(e1.negativeLookahead("^-0$")+"-?"+e1.nonCapturingGroup(e1.nonCapturingGroup("0|"+yX))),ZJ=f2.test.bind(f2),KY=/^-?\d+$/,XJ=KY.test.bind(KY),pX={number:"a number",bigint:"a bigint",integer:"an integer"},mX=(Y,Z)=>`'${Y}' was parsed as ${pX[Z]} but could not be narrowed to a literal value. Avoid unnecessary leading or trailing zeros and other abnormal notation`,_J=(Y,Z)=>Z==="number"?aH(Y):ZJ(Y),GJ=(Y,Z)=>Z==="number"?Number(Y):Number.parseInt(Y),$J=(Y,Z)=>Z==="number"?YJ(Y):XJ(Y),uX=(Y,Z)=>BY(Y,"number",Z),dX=(Y,Z)=>BY(Y,"number",{...Z,strict:!0}),cX=(Y,Z)=>BY(Y,"integer",Z),BY=(Y,Z,X)=>{let _=GJ(Y,Z);if(!Number.isNaN(_)){if($J(Y,Z)){if(X?.strict)return _J(Y,Z)?_:A(mX(Y,Z));return _}}return X?.errorOnFail?A(X?.errorOnFail===!0?`Failed to parse ${pX[Z]} from '${Y}'`:X?.errorOnFail):void 0},lX=(Y)=>{if(Y[Y.length-1]!=="n")return;let Z=Y.slice(0,-1),X;try{X=BigInt(Z)}catch{return}if(f2.test(Z))return X;if(KY.test(Z))return A(mX(Y,"bigint"))};var WJ="0.49.0",HJ={version:WJ,filename:hX.fileName(),FileConstructor:RY},P4=HJ,oX=new Map,TY=Object.create(null),h2=(Y)=>{let Z=oX.get(Y);if(Z)return Z;let X=JJ(Y);if(TY[X])X=`${X}${TY[X]++}`;else TY[X]=1;return P4[X]=Y,oX.set(Y,X),X},O4=(Y)=>/^[$A-Z_a-z][\w$]*$/.test(Y),JJ=(Y)=>{switch(typeof Y){case"object":{if(Y===null)break;let Z=P2(Y)??"object";return Z[0].toLowerCase()+Z.slice(1)}case"function":return O4(Y.name)?Y.name:"fn";case"symbol":return Y.description&&O4(Y.description)?Y.description:"symbol"}return _0(`Unexpected attempt to register serializable value of type ${y0(Y)}`)};var k2=(Y)=>typeof Y==="string"?JSON.stringify(Y):typeof Y==="bigint"?`${Y}n`:`${Y}`;var iX=(Y,Z={})=>b2(Y,{onUndefined:"$ark.undefined",onBigInt:(X)=>`$ark.bigint-${X}`,...Z},[]);var i=(Y,Z)=>{switch(y0(Y)){case"object":let X=Y,_=X.constructor.name;return _==="Object"||_==="Array"?Z?.quoteKeys===!1?u8(X,Z?.indent??0,""):JSON.stringify(b2(X,r4,[]),null,Z?.indent):u8(X,Z?.indent??0,"");case"symbol":return r4.onSymbol(Y);default:return k2(Y)}},u8=(Y,Z,X)=>{if(typeof Y==="function")return r4.onFunction(Y);if(typeof Y!=="object"||Y===null)return k2(Y);let _=X+" ".repeat(Z);if(Array.isArray(Y)){if(Y.length===0)return"[]";let $=Y.map((W)=>u8(W,Z,_)).join(`,
9
+ `+_);return Z?`[
10
+ ${_}${$}
11
+ ${X}]`:`[${$}]`}let G=Y.constructor.name;if(G==="Object"){let $=q4(Y).map(([W,H])=>{let Q=typeof W==="symbol"?r4.onSymbol(W):O4(W)?W:JSON.stringify(W),J=u8(H,Z,_);return`${_}${Q}: ${J}`});if($.length===0)return"{}";return Z?`{
12
12
  ${$.join(`,
13
13
  `)}
14
- ${X}}`:`{${$.join(", ")}}`}if(Z instanceof Date)return f4(Z);if("expression"in Z&&typeof Z.expression==="string")return Z.expression;return _},a4={onCycle:()=>"(cycle)",onSymbol:(Z)=>`Symbol(${g2(Z)})`,onFunction:(Z)=>`Function(${g2(Z)})`},m2=(Z,Y,X)=>{switch(y0(Z)){case"object":{let G=Z;if("toJSON"in G&&typeof G.toJSON==="function")return G.toJSON();if(typeof G==="function")return a4.onFunction(G);if(X.includes(G))return"(cycle)";let _=[...X,G];if(Array.isArray(G))return G.map((W)=>m2(W,Y,_));if(G instanceof Date)return G.toDateString();let $={};for(let W in G)$[W]=m2(G[W],Y,_);for(let W of Object.getOwnPropertySymbols(G))$[Y.onSymbol?.(W)??W.toString()]=m2(G[W],Y,_);return $}case"symbol":return a4.onSymbol(Z);case"bigint":return Y.onBigInt?.(Z)??`${Z}n`;case"undefined":return Y.onUndefined??"undefined";case"string":return Z.replaceAll("\\","\\\\");default:return Z}},f4=(Z)=>{let Y=Z.getFullYear(),X=Z.getMonth(),G=Z.getDate(),_=Z.getHours(),$=Z.getMinutes(),W=Z.getSeconds(),H=Z.getMilliseconds();if(X===0&&G===1&&_===0&&$===0&&W===0&&H===0)return`${Y}`;let Q=`${RJ[X]} ${G}, ${Y}`;if(_===0&&$===0&&W===0&&H===0)return Q;let J=Z.toLocaleTimeString(),z=J.endsWith(" AM")||J.endsWith(" PM")?J.slice(-3):"";if(z)J=J.slice(0,-z.length);if(H)J+=`.${wJ(H,3)}`;else if(NJ.test(J))J=J.slice(0,-3);return`${J+z}, ${Q}`},RJ=["January","February","March","April","May","June","July","August","September","October","November","December"],NJ=/:\d\d:00$/,wJ=(Z,Y)=>String(Z).padStart(Y,"0");var GG=(Z,Y,...[X])=>{let G=X?.stringifySymbol??o,_=Z;switch(typeof Y){case"string":_=O4(Y)?Z===""?Y:`${Z}.${Y}`:`${Z}[${JSON.stringify(Y)}]`;break;case"number":_=`${Z}[${Y}]`;break;case"symbol":_=`${Z}[${G(Y)}]`;break;default:if(X?.stringifyNonKey)_=`${Z}[${X.stringifyNonKey(Y)}]`;else A(`${o(Y)} must be a PropertyKey or stringifyNonKey must be passed to options`)}return _},Y4=(Z,...Y)=>Z.reduce((X,G)=>GG(X,G,...Y),"");class u2 extends p8{cache={};constructor(...Z){super();this.push(...Z)}toJSON(){if(this.cache.json)return this.cache.json;this.cache.json=[];for(let Z=0;Z<this.length;Z++)this.cache.json.push(typeof this[Z]==="symbol"?o(this[Z]):this[Z]);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 Z="",Y=[Z];for(let X of this)Z=GG(Z,X),Y.push(Z);return this.cache.stringifyAncestors=Y}}class fZ{chars;i;def;constructor(Z){this.def=Z,this.chars=[...Z],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(Z){let Y="";while(this.lookahead){if(Z(this,Y))if(Y[Y.length-1]===b2)Y=Y.slice(0,-1);else break;Y+=this.shift()}return Y}shiftUntilLookahead(Z){return typeof Z==="string"?this.shiftUntil((Y)=>Y.lookahead===Z):this.shiftUntil((Y)=>(Y.lookahead in Z))}shiftUntilNonWhitespace(){return this.shiftUntil(()=>!(this.lookahead in D4))}jumpToIndex(Z){this.i=Z<0?this.length+Z:Z}jumpForward(Z){this.i+=Z}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(Z,Y){return this.chars.slice(Z,Y).join("")}lookaheadIs(Z){return this.lookahead===Z}lookaheadIsIn(Z){return this.lookahead in Z}}var cL=f1("implementedTraits");var hZ="$ark",IJ=2;while(hZ in globalThis)hZ=`$ark${IJ++}`;var _G=hZ;globalThis[_G]=x4;var I=x4,BJ=(Z)=>`${_G}.${Z}`,C0=(Z)=>BJ(g2(Z));class d8 extends x2{argNames;body="";constructor(...Z){super();this.argNames=Z;for(let Y of Z){if(Y in this)throw new Error(`Arg name '${Y}' would overwrite an existing property on FunctionBody`);this[Y]=Y}}indentation=0;indent(){return this.indentation+=4,this}dedent(){return this.indentation-=4,this}prop(Z,Y=!1){return kZ(Z,Y)}index(Z,Y=!1){return $G(`${Z}`,Y)}line(Z){return this.body+=`${" ".repeat(this.indentation)}${Z}
15
- `,this}const(Z,Y){return this.line(`const ${Z} = ${Y}`),this}let(Z,Y){return this.line(`let ${Z} = ${Y}`)}set(Z,Y){return this.line(`${Z} = ${Y}`)}if(Z,Y){return this.block(`if (${Z})`,Y)}elseIf(Z,Y){return this.block(`else if (${Z})`,Y)}else(Z){return this.block("else",Z)}for(Z,Y,X=0){return this.block(`for (let i = ${X}; ${Z}; i++)`,Y)}forIn(Z,Y){return this.block(`for (const k in ${Z})`,Y)}block(Z,Y,X=""){return this.line(`${Z} {`),this.indent(),Y(this),this.dedent(),this.line(`}${X}`)}return(Z=""){return this.line(`return ${Z}`)}write(Z="anonymous",Y=0){return`${Z}(${this.argNames.join(", ")}) { ${Y?this.body.split(`
16
- `).map((X)=>" ".repeat(Y)+`${X}`).join(`
17
- `):this.body} }`}compile(){return new mX(...this.argNames,this.body)}}var X4=(Z)=>H1(Z,"object")||typeof Z==="symbol"?C0(Z):p2(Z),kZ=(Z,Y=!1)=>{if(typeof Z==="string"&&O4(Z))return`${Y?"?":""}.${Z}`;return $G(KJ(Z),Y)},KJ=(Z)=>typeof Z==="symbol"?C0(Z):JSON.stringify(Z),$G=(Z,Y=!1)=>`${Y?"?.":""}[${Z}]`;class d2 extends d8{traversalKind;optimistic;constructor(Z){super("data","ctx");this.traversalKind=Z.kind,this.optimistic=Z.optimistic===!0}invoke(Z,Y){let X=Y?.arg??this.data,G=typeof Z==="string"?!0:this.requiresContextFor(Z),_=typeof Z==="string"?Z:Z.id;if(G)return`${this.referenceToId(_,Y)}(${X}, ${this.ctx})`;return`${this.referenceToId(_,Y)}(${X})`}referenceToId(Z,Y){let X=Y?.kind??this.traversalKind,G=`this.${Z}${X}`;return Y?.bind?`${G}.bind(${Y?.bind})`:G}requiresContextFor(Z){return this.traversalKind==="Apply"||Z.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(Z,Y,X){let G=this.requiresContextFor(X);if(G)this.line(`${this.ctx}.path.push(${Z})`);if(this.check(X,{arg:Y}),G)this.line(`${this.ctx}.path.pop()`);return this}check(Z,Y){return this.traversalKind==="Allows"?this.if(`!${this.invoke(Z,Y)}`,()=>this.return(!1)):this.line(this.invoke(Z,Y))}}var c8=(Z)=>i(Z,(Y,X)=>[Y,U0(X)?[...X]:X]),Y1=f1("arkKind"),y=(Z,Y)=>Z?.[Y1]===Y,O0=(Z)=>y(Z,"root")||y(Z,"constraint");var WG=["unit","proto","domain"],t4=["required","optional","index","sequence"],bZ=["pattern","divisor","exactLength","max","min","maxLength","minLength","before","after"],l8=[...bZ,...t4,"structure","predicate"],e4=["alias","union","morph","unit","intersection","proto","domain"],CJ=[...e4,...l8],i8=i(l8,(Z,Y)=>[Y,1]),HG=i([...t4,"undeclared"],(Z,Y)=>[Y,1]),JG=i(CJ,(Z,Y)=>[Y,Z]),Z2=(Z)=>typeof Z==="string"&&(Z in JG);var Y2=(Z)=>JG[Z],o8=(Z)=>e4.slice(Y2(Z)+1),TD=[...o8("union"),"alias"],qD=[...o8("morph"),"alias"],B1=(Z)=>{if(typeof Z==="string"||typeof Z==="boolean"||Z===null)return Z;if(typeof Z==="number"){if(Number.isNaN(Z))return"NaN";if(Z===Number.POSITIVE_INFINITY)return"Infinity";if(Z===Number.NEGATIVE_INFINITY)return"-Infinity";return Z}return X4(Z)},V4=(Z)=>{let Y="{ ";for(let[X,G]of Object.entries(Z))Y+=`${X}: ${X4(G)}, `;return Y+" }"},r=(Z)=>{let Y=Z;if(Y.hasAssociatedError)Y.defaults.expected??=(X)=>("description"in X)?X.description:Y.defaults.description(X),Y.defaults.actual??=(X)=>o(X),Y.defaults.problem??=(X)=>`must be ${X.expected}${X.actual?` (was ${X.actual})`:""}`,Y.defaults.message??=(X)=>{if(X.path.length===0)return X.problem;let G=`${X.propString} ${X.problem}`;if(G[0]==="[")return`value at ${G}`;return G};return Y};class QG extends Error{name="ToJsonSchemaError";code;context;constructor(Z,Y){super(o(Y,{quoteKeys:!1,indent:4}));this.code=Z,this.context=Y}hasCode(Z){return this.code===Z}}var TJ={dialect:"https://json-schema.org/draft/2020-12/schema",useRefs:!1,fallback:{arrayObject:(Z)=>N0.throw("arrayObject",Z),arrayPostfix:(Z)=>N0.throw("arrayPostfix",Z),defaultValue:(Z)=>N0.throw("defaultValue",Z),domain:(Z)=>N0.throw("domain",Z),morph:(Z)=>N0.throw("morph",Z),patternIntersection:(Z)=>N0.throw("patternIntersection",Z),predicate:(Z)=>N0.throw("predicate",Z),proto:(Z)=>N0.throw("proto",Z),symbolKey:(Z)=>N0.throw("symbolKey",Z),unit:(Z)=>N0.throw("unit",Z),date:(Z)=>N0.throw("date",Z)}},N0={Error:QG,throw:(...Z)=>{throw new N0.Error(...Z)},throwInternalOperandError:(Z,Y)=>G0(`Unexpected JSON Schema input for ${Z}: ${o(Y)}`),defaultConfig:TJ};I.config??={};var c2=(Z,Y)=>{if(!Y)return Z;let X={...Z},G;for(G in Y){let _={...Z.keywords};if(G==="keywords"){for(let $ in Y[G]){let W=Y.keywords[$];if(W===void 0)continue;_[$]=typeof W==="string"?{description:W}:W}X.keywords=_}else if(G==="toJsonSchema")X[G]=yZ(Z.toJsonSchema,Y.toJsonSchema);else if(Z2(G))X[G]={...Z[G],...Y[G]};else X[G]=Y[G]}return X},yZ=(Z,Y)=>{if(!Z)return Y??{};if(!Y)return Z;let X={...Z},G;for(G in Y)if(G==="fallback")X.fallback=qJ(Z.fallback,Y.fallback);else X[G]=Y[G];return X},qJ=(Z,Y)=>{Z=zG(Z),Y=zG(Y);let X={},G;for(G in N0.defaultConfig.fallback)X[G]=Y[G]??Y.default??Z[G]??Z.default??N0.defaultConfig.fallback[G];return X},zG=(Z)=>typeof Z==="function"?{default:Z}:Z??{};class M4 extends x2{[Y1]="error";path;data;nodeConfig;input;ctx;constructor({prefixPath:Z,relativePath:Y,...X},G){super();this.input=X,this.ctx=G,hX(this,X);let _=G.data;if(X.code==="union")X.errors=X.errors.flatMap((W)=>{let H=W.hasCode("union")?W.errors:[W];if(!Z&&!Y)return H;return H.map((Q)=>Q.transform((J)=>({...J,path:jX(Z,J.path,Y)})))});this.nodeConfig=G.config[this.code];let $=[...X.path??G.path];if(Y)$.push(...Y);if(Z)$.unshift(...Z);this.path=new u2(...$),this.data="data"in X?X.data:_}transform(Z){return new M4(Z({data:this.data,path:this.path,...this.input}),this.ctx)}hasCode(Z){return this.code===Z}get propString(){return Y4(this.path)}get expected(){if(this.input.expected)return this.input.expected;let Z=this.meta?.expected??this.nodeConfig.expected;return typeof Z==="function"?Z(this.input):Z}get actual(){if(this.input.actual)return this.input.actual;let Z=this.meta?.actual??this.nodeConfig.actual;return typeof Z==="function"?Z(this.data):Z}get problem(){if(this.input.problem)return this.input.problem;let Z=this.meta?.problem??this.nodeConfig.problem;return typeof Z==="function"?Z(this):Z}get message(){if(this.input.message)return this.input.message;let Z=this.meta?.message??this.nodeConfig.message;return typeof Z==="function"?Z(this):Z}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 Q1 extends p8{[Y1]="errors";ctx;constructor(Z){super();this.ctx=Z}byPath=Object.create(null);get flatByPath(){return i(this.byPath,(Z,Y)=>[Z,Y.flat])}get flatProblemsByPath(){return i(this.byPath,(Z,Y)=>[Z,Y.flat.map((X)=>X.problem)])}byAncestorPath=Object.create(null);count=0;mutable=this;throw(){throw this.toTraversalError()}toTraversalError(){return new gZ(this)}add(Z){if(this.includes(Z))return;this._add(Z)}transform(Z){let Y=new Q1(this.ctx);for(let X of this)Y.add(Z(X));return Y}merge(Z){for(let Y of Z){if(this.includes(Y))continue;this._add(new M4({...Y,path:[...this.ctx.path,...Y.path]},this.ctx))}}affectsPath(Z){if(this.length===0)return!1;return Z.stringifyAncestors().some((Y)=>(Y in this.byPath))||Z.stringify()in this.byAncestorPath}get summary(){return this.toString()}get issues(){return this}toJSON(){return[...this.map((Z)=>Z.toJSON())]}toString(){return this.join(`
18
- `)}_add(Z){let Y=this.byPath[Z.propString];if(Y){if(Y.hasCode("union")&&Y.errors.length===0)return;let X=Z.hasCode("union")&&Z.errors.length===0?Z:new M4({code:"intersection",errors:Y.hasCode("intersection")?[...Y.errors,Z]:[Y,Z]},this.ctx),G=this.indexOf(Y);this.mutable[G===-1?this.length:G]=X,this.byPath[Z.propString]=X,this.addAncestorPaths(Z)}else this.byPath[Z.propString]=Z,this.addAncestorPaths(Z),this.mutable.push(Z);this.count++}addAncestorPaths(Z){for(let Y of Z.path.stringifyAncestors())this.byAncestorPath[Y]=Y0(this.byAncestorPath[Y],Z)}}class gZ extends Error{name="TraversalError";constructor(Z){if(Z.length===1)super(Z.summary);else super(`
19
- `+Z.map((Y)=>` \u2022 ${jJ(Y)}`).join(`
20
- `));Object.defineProperty(this,"arkErrors",{value:Z,enumerable:!1})}}var jJ=(Z)=>Z.toString().split(`
14
+ ${X}}`:`{${$.join(", ")}}`}if(Y instanceof Date)return S4(Y);if("expression"in Y&&typeof Y.expression==="string")return Y.expression;return G},r4={onCycle:()=>"(cycle)",onSymbol:(Y)=>`Symbol(${h2(Y)})`,onFunction:(Y)=>`Function(${h2(Y)})`},b2=(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((W)=>b2(W,Z,G));if(_ instanceof Date)return _.toDateString();let $={};for(let W in _)$[W]=b2(_[W],Z,G);for(let W of Object.getOwnPropertySymbols(_))$[Z.onSymbol?.(W)??W.toString()]=b2(_[W],Z,G);return $}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}},S4=(Y)=>{let Z=Y.getFullYear(),X=Y.getMonth(),_=Y.getDate(),G=Y.getHours(),$=Y.getMinutes(),W=Y.getSeconds(),H=Y.getMilliseconds();if(X===0&&_===1&&G===0&&$===0&&W===0&&H===0)return`${Z}`;let Q=`${QJ[X]} ${_}, ${Z}`;if(G===0&&$===0&&W===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+=`.${UJ(H,3)}`;else if(zJ.test(J))J=J.slice(0,-3);return`${J+z}, ${Q}`},QJ=["January","February","March","April","May","June","July","August","September","October","November","December"],zJ=/:\d\d:00$/,UJ=(Y,Z)=>String(Y).padStart(Z,"0");var nX=(Y,Z,...[X])=>{let _=X?.stringifySymbol??i,G=Y;switch(typeof Z){case"string":G=O4(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 A(`${i(Z)} must be a PropertyKey or stringifyNonKey must be passed to options`)}return G},Y4=(Y,...Z)=>Y.reduce((X,_)=>nX(X,_,...Z),"");class y2 extends p8{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"?i(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=nX(Y,X),Z.push(Y);return this.cache.stringifyAncestors=Z}}class CY{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]===x2)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 V4))}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 iV=S1("implementedTraits");var qY="$ark",FJ=2;while(qY in globalThis)qY=`$ark${FJ++}`;var rX=qY;globalThis[rX]=P4;var I=P4,EJ=(Y)=>`${rX}.${Y}`,T0=(Y)=>EJ(h2(Y));class d8 extends j2{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 jY(Y,Z)}index(Y,Z=!1){return sX(`${Y}`,Z)}line(Y){return this.body+=`${" ".repeat(this.indentation)}${Y}
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
+ `).map((X)=>" ".repeat(Z)+`${X}`).join(`
17
+ `):this.body} }`}compile(){return new vX(...this.argNames,this.body)}}var Z4=(Y)=>W1(Y,"object")||typeof Y==="symbol"?T0(Y):k2(Y),jY=(Y,Z=!1)=>{if(typeof Y==="string"&&O4(Y))return`${Z?"?":""}.${Y}`;return sX(VJ(Y),Z)},VJ=(Y)=>typeof Y==="symbol"?T0(Y):JSON.stringify(Y),sX=(Y,Z=!1)=>`${Z?"?.":""}[${Y}]`;class g2 extends d8{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 c8=(Y)=>o(Y,(Z,X)=>[Z,U0(X)?[...X]:X]),Y1=S1("arkKind"),y=(Y,Z)=>Y?.[Y1]===Z,D0=(Y)=>y(Y,"root")||y(Y,"constraint");var tX=["unit","proto","domain"],s4=["required","optional","index","sequence"],PY=["pattern","divisor","exactLength","max","min","maxLength","minLength","before","after"],l8=[...PY,...s4,"structure","predicate"],t4=["alias","union","morph","unit","intersection","proto","domain"],OJ=[...t4,...l8],o8=o(l8,(Y,Z)=>[Z,1]),aX=o([...s4,"undeclared"],(Y,Z)=>[Z,1]),eX=o(OJ,(Y,Z)=>[Z,Y]),a4=(Y)=>typeof Y==="string"&&(Y in eX);var e4=(Y)=>eX[Y],i8=(Y)=>t4.slice(e4(Y)+1),PO=[...i8("union"),"alias"],SO=[...i8("morph"),"alias"],w1=(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)},D4=(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)=>i(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 Y_ extends Error{name="ToJsonSchemaError";code;context;constructor(Y,Z){super(i(Z,{quoteKeys:!1,indent:4}));this.code=Y,this.context=Z}hasCode(Y){return this.code===Y}}var DJ={dialect:"https://json-schema.org/draft/2020-12/schema",useRefs:!1,fallback:{arrayObject:(Y)=>w0.throw("arrayObject",Y),arrayPostfix:(Y)=>w0.throw("arrayPostfix",Y),defaultValue:(Y)=>w0.throw("defaultValue",Y),domain:(Y)=>w0.throw("domain",Y),morph:(Y)=>w0.throw("morph",Y),patternIntersection:(Y)=>w0.throw("patternIntersection",Y),predicate:(Y)=>w0.throw("predicate",Y),proto:(Y)=>w0.throw("proto",Y),symbolKey:(Y)=>w0.throw("symbolKey",Y),unit:(Y)=>w0.throw("unit",Y),date:(Y)=>w0.throw("date",Y)}},w0={Error:Y_,throw:(...Y)=>{throw new w0.Error(...Y)},throwInternalOperandError:(Y,Z)=>_0(`Unexpected JSON Schema input for ${Y}: ${i(Z)}`),defaultConfig:DJ};I.config??={};var p2=(Y,Z)=>{if(!Z)return Y;let X={...Y},_;for(_ in Z){let G={...Y.keywords};if(_==="keywords"){for(let $ in Z[_]){let W=Z.keywords[$];if(W===void 0)continue;G[$]=typeof W==="string"?{description:W}:W}X.keywords=G}else if(_==="toJsonSchema")X[_]=SY(Y.toJsonSchema,Z.toJsonSchema);else if(a4(_))X[_]={...Y[_],...Z[_]};else X[_]=Z[_]}return X},SY=(Y,Z)=>{if(!Y)return Z??{};if(!Z)return Y;let X={...Y},_;for(_ in Z)if(_==="fallback")X.fallback=LJ(Y.fallback,Z.fallback);else X[_]=Z[_];return X},LJ=(Y,Z)=>{Y=Z_(Y),Z=Z_(Z);let X={},_;for(_ in w0.defaultConfig.fallback)X[_]=Z[_]??Z.default??Y[_]??Y.default??w0.defaultConfig.fallback[_];return X},Z_=(Y)=>typeof Y==="function"?{default:Y}:Y??{};class L4 extends j2{[Y1]="error";path;data;nodeConfig;input;ctx;constructor({prefixPath:Y,relativePath:Z,...X},_){super();this.input=X,this.ctx=_,TX(this,X);let G=_.data;if(X.code==="union")X.errors=X.errors.flatMap((W)=>{let H=W.hasCode("union")?W.errors:[W];if(!Y&&!Z)return H;return H.map((Q)=>Q.transform((J)=>({...J,path:RX(Y,J.path,Z)})))});this.nodeConfig=_.config[this.code];let $=[...X.path??_.path];if(Z)$.push(...Z);if(Y)$.unshift(...Y);this.path=new y2(...$),this.data="data"in X?X.data:G}transform(Y){return new L4(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 J1 extends p8{[Y1]="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 vY(this)}add(Y){if(this.includes(Y))return;this._add(Y)}transform(Y){let Z=new J1(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 L4({...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 L4({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 vY extends Error{name="TraversalError";constructor(Y){if(Y.length===1)super(Y.summary);else super(`
19
+ `+Y.map((Z)=>` \u2022 ${MJ(Z)}`).join(`
20
+ `));Object.defineProperty(this,"arkErrors",{value:Y,enumerable:!1})}}var MJ=(Y)=>Y.toString().split(`
21
21
  `).join(`
22
- `);class k1{path=[];errors=new Q1(this);root;config;queuedMorphs=[];branches=[];seen={};constructor(Z,Y){this.root=Z,this.config=Y}get data(){let Z=this.root;for(let Y of this.path)Z=Z?.[Y];return Z}get propString(){return Y4(this.path)}reject(Z){return this.error(Z),!1}mustBe(Z){return this.error(Z),!1}error(Z){let Y=typeof Z==="object"?Z.code?Z:{...Z,code:"predicate"}:{code:"predicate",expected:Z};return this.errorFromContext(Y)}hasError(){return this.currentErrorCount!==0}get currentBranch(){return this.branches.at(-1)}queueMorphs(Z){let Y={path:new u2(...this.path),morphs:Z};if(this.currentBranch)this.currentBranch.queuedMorphs.push(Y);else this.queuedMorphs.push(Y)}finalize(Z){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 Z?Z(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(Z){return this.errorFromContext(Z)}errorFromContext(Z){let Y=new M4(Z,this);if(this.currentBranch)this.currentBranch.error=Y;else this.errors.add(Y);return Y}applyQueuedMorphs(){while(this.queuedMorphs.length){let Z=this.queuedMorphs;this.queuedMorphs=[];for(let{path:Y,morphs:X}of Z){if(this.errors.affectsPath(Y))continue;this.applyMorphsAtPath(Y,X)}}}applyMorphsAtPath(Z,Y){let X=Z.at(-1),G;if(X!==void 0){G=this.root;for(let _=0;_<Z.length-1;_++)G=G[Z[_]]}for(let _ of Y){this.path=[...Z];let $=O0(_),W=_(G===void 0?this.root:G[X],this);if(W instanceof M4){this.errors.add(W);break}if(W instanceof Q1){if(!$)this.errors.merge(W);break}if(G===void 0)this.root=W;else G[X]=W;this.applyQueuedMorphs()}}}var z1=(Z,Y,X)=>{if(!X)return Y();X.path.push(Z);let G=Y();return X.path.pop(),G};class i2 extends h1{attachments;$;onFail;includesTransform;includesContextualPredicate;isCyclic;allowsRequiresContext;rootApplyStrategy;contextFreeMorph;rootApply;referencesById;shallowReferences;flatRefs;flatMorphs;allows;get shallowMorphs(){return[]}constructor(Z,Y){super((G,_,$=this.onFail)=>{if(_)return this.traverseApply(G,_),_.hasError()?_.errors:_.data;return this.rootApply(G,$)},{attach:Z});this.attachments=Z,this.$=Y,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,_)=>xJ(G,_.shallowReferences),[this]);let X=this.isStructural();this.flatRefs=[],this.flatMorphs=[];for(let G=0;G<this.children.length;G++){if(this.includesTransform||=this.children[G].includesTransform,this.includesContextualPredicate||=this.children[G].includesContextualPredicate,this.isCyclic||=this.children[G].isCyclic,!X){let _=this.children[G].flatRefs;for(let $=0;$<_.length;$++){let W=_[$];if(!this.flatRefs.some((H)=>FG(H,W))){this.flatRefs.push(W);for(let H of W.node.branches)if(H.hasKind("morph")||H.hasKind("intersection")&&H.structure?.structuralMorph!==void 0)this.flatMorphs.push({path:W.path,propString:W.propString,node:H})}}}Object.assign(this.referencesById,this.children[G].referencesById)}this.flatRefs.sort((G,_)=>G.path.length>_.path.length?1:G.path.length<_.path.length?-1:G.propString>_.propString?1:G.propString<_.propString?-1:G.node.expression<_.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((G)=>G.length===1||G.name==="$arkStructuralMorph")?this.hasKind("union")?this.branches.some((G)=>G.shallowMorphs.length>1)?"contextual":"branchedOptimistic":this.shallowMorphs.length>1?"contextual":"optimistic":"contextual":"contextual",this.rootApply=this.createRootApply(),this.allows=this.allowsRequiresContext?(G)=>this.traverseAllows(G,new k1(G,this.$.resolvedConfig)):(G)=>this.traverseAllows(G)}createRootApply(){switch(this.rootApplyStrategy){case"allows":return(Y,X)=>{if(this.allows(Y))return Y;let G=new k1(Y,this.$.resolvedConfig);return this.traverseApply(Y,G),G.finalize(X)};case"contextual":return(Y,X)=>{let G=new k1(Y,this.$.resolvedConfig);return this.traverseApply(Y,G),G.finalize(X)};case"optimistic":this.contextFreeMorph=this.shallowMorphs[0];let Z=this.$.resolvedConfig.clone;return(Y,X)=>{if(this.allows(Y))return this.contextFreeMorph(Z&&(typeof Y==="object"&&Y!==null||typeof Y==="function")?Z(Y):Y);let G=new k1(Y,this.$.resolvedConfig);return this.traverseApply(Y,G),G.finalize(X)};case"branchedOptimistic":return this.createBranchedOptimisticRootApply();default:return this.rootApplyStrategy,G0(`Unexpected rootApplyStrategy ${this.rootApplyStrategy}`)}}compiledMeta=vJ(this.metaJson);cacheGetter(Z,Y){return Object.defineProperty(this,Z,{value:Y}),Y}get description(){return this.cacheGetter("description",this.meta?.description??this.$.resolvedConfig[this.kind].description(this))}get references(){return Object.values(this.referencesById)}precedence=Y2(this.kind);precompilation;assert=(Z,Y)=>this(Z,Y,(X)=>X.throw());traverse(Z,Y){return this(Z,Y,null)}get in(){return this.cacheGetter("in",this.getIo("in"))}get out(){return this.cacheGetter("out",this.getIo("out"))}getIo(Z){if(!this.includesTransform)return this;let Y={};for(let[X,G]of this.innerEntries){let _=this.impl.keys[X];if(_.reduceIo)_.reduceIo(Z,Y,G);else if(_.child){let $=G;Y[X]=U0($)?$.map((W)=>W[Z]):$[Z]}else Y[X]=G}return this.$.node(this.kind,Y)}toJSON(){return this.json}toString(){return`Type<${this.expression}>`}equals(Z){let Y=O0(Z)?Z:this.$.parseDefinition(Z);return this.innerHash===Y.innerHash}ifEquals(Z){return this.equals(Z)?this:void 0}hasKind(Z){return this.kind===Z}assertHasKind(Z){if(this.kind!==Z)P4(`${this.kind} node was not of asserted kind ${Z}`);return this}hasKindIn(...Z){return Z.includes(this.kind)}assertHasKindIn(...Z){if(!a1(Z,this.kind))P4(`${this.kind} node was not one of asserted kinds ${Z}`);return this}isBasis(){return a1(WG,this.kind)}isConstraint(){return a1(l8,this.kind)}isStructural(){return a1(t4,this.kind)}isRefinement(){return a1(bZ,this.kind)}isRoot(){return a1(e4,this.kind)}isUnknown(){return this.hasKind("intersection")&&this.children.length===0}isNever(){return this.hasKind("union")&&this.children.length===0}hasUnit(Z){return this.hasKind("unit")&&this.allows(Z)}hasOpenIntersection(){return this.impl.intersectionIsOpen}get nestableExpression(){return this.expression}select(Z){let Y=l2.normalize(Z);return this._select(Y)}_select(Z){let Y=l2.applyBoundary[Z.boundary??"references"](this);if(Z.kind)Y=Y.filter((X)=>X.kind===Z.kind);if(Z.where)Y=Y.filter(Z.where);return l2.applyMethod[Z.method??"filter"](Y,this,Z)}transform(Z,Y){return this._transform(Z,this._createTransformContext(Y))}_createTransformContext(Z){return{root:this,selected:void 0,seen:{},path:[],parseOptions:{prereduced:Z?.prereduced??!1},undeclaredKeyHandling:void 0,...Z}}_transform(Z,Y){let X=Y.bindScope??this.$;if(Y.seen[this.id])return this.$.lazilyResolve(Y.seen[this.id]);if(Y.shouldTransform?.(this,Y)===!1)return this;let G;if(Y.seen[this.id]=()=>G,this.hasKind("structure")&&this.undeclared!==Y.undeclaredKeyHandling)Y={...Y,undeclaredKeyHandling:this.undeclared};let _=i(this.inner,(J,z)=>{if(!this.impl.keys[J].child)return[J,z];let U=z;if(!U0(U)){let V=U._transform(Z,Y);return V?[J,V]:[]}if(U.length===0)return[J,z];let D=U.flatMap((V)=>{return V._transform(Z,Y)??[]});return D.length?[J,D]:[]});delete Y.seen[this.id];let $=Object.assign(_,{meta:this.meta}),W=Y.selected&&!Y.selected.includes(this)?$:Z(this.kind,$,Y);if(W===null)return null;if(O0(W))return G=W;let H=Object.keys(W);if((H.length===0||H.length===1&&H[0]==="meta")&&!l1(this.inner))return null;if((this.kind==="required"||this.kind==="optional"||this.kind==="index")&&!("value"in W))return Y.undeclaredKeyHandling?{...W,value:I.intrinsic.unknown}:null;if(this.kind==="morph")W.in??=I.intrinsic.unknown;return G=X.node(this.kind,W,Y.parseOptions)}configureReferences(Z,Y="references"){let X=l2.normalize(Y),G=typeof Z==="string"?(H,Q)=>({...Q,meta:{...Q.meta,description:Z}}):typeof Z==="function"?(H,Q)=>({...Q,meta:Z(Q.meta)}):(H,Q)=>({...Q,meta:{...Q.meta,...Z}});if(X.boundary==="self")return this.$.node(this.kind,G(this.kind,{...this.inner,meta:this.meta}));let _=this._select(X),$=_&&E4(_),W=X.boundary==="child"?(H,Q)=>Q.root.children.includes(H):X.boundary==="shallow"?(H)=>H.kind!=="structure":()=>!0;return this.$.finalize(this.transform(G,{shouldTransform:W,selected:$}))}}var l2={applyBoundary:{self:(Z)=>[Z],child:(Z)=>[...Z.children],shallow:(Z)=>[...Z.shallowReferences],references:(Z)=>[...Z.references]},applyMethod:{filter:(Z)=>Z,assertFilter:(Z,Y,X)=>{if(Z.length===0)P4(UG(Y,X));return Z},find:(Z)=>Z[0],assertFind:(Z,Y,X)=>{if(Z.length===0)P4(UG(Y,X));return Z[0]}},normalize:(Z)=>typeof Z==="function"?{boundary:"references",method:"filter",where:Z}:typeof Z==="string"?g0(Z,l2.applyBoundary)?{method:"filter",boundary:Z}:{boundary:"references",method:"filter",kind:Z}:{boundary:"references",method:"filter",...Z}},UG=(Z,Y)=>`${Z} had no references matching ${o(Y)}.`,PJ=(Z)=>Y4(Z,{stringifyNonKey:(Y)=>Y.expression}),SJ=/"(\$ark\.[^"]+)"/g,vJ=(Z)=>JSON.stringify(Z).replaceAll(SJ,"$1"),b1=(Z,Y)=>({path:Z,node:Y,propString:PJ(Z)}),FG=(Z,Y)=>Z.propString===Y.propString&&Z.node.equals(Y.node),pZ=(Z,Y)=>c1(Z,Y,{isEqual:FG}),xJ=(Z,Y)=>c1(Z,Y,{isEqual:(X,G)=>X.equals(G)});class S extends Array{static init(Z,Y,X,G){return new S({kind:Z,l:Y,r:X,path:G?.path??[],optional:G?.optional??!1})}add(Z,Y,X,G){return this.push({kind:Z,l:Y,r:X,path:G?.path??[],optional:G?.optional??!1}),this}get summary(){return this.describeReasons()}describeReasons(){if(this.length===1){let{path:Z,l:Y,r:X}=this[0],G=Y4(Z);return uZ(`Intersection${G&&` at ${G}`} of ${EG(Y,X)}`)}return`The following intersections result in unsatisfiable types:
23
- \u2022 ${this.map(({path:Z,l:Y,r:X})=>`${Z}: ${EG(Y,X)}`).join(`
24
- \u2022 `)}`}throw(){return A(this.describeReasons())}invert(){let Z=this.map((Y)=>({...Y,l:Y.r,r:Y.l}));if(!(Z instanceof S))return new S(...Z);return Z}withPrefixKey(Z,Y){return this.map((X)=>({...X,path:[Z,...X.path],optional:X.optional||Y==="optional"}))}toNeverIfDisjoint(){return I.intrinsic.never}}var EG=(Z,Y)=>`${mZ(Z)} and ${mZ(Y)}`,mZ=(Z)=>O0(Z)?Z.expression:U0(Z)?Z.map(mZ).join(" | ")||"never":String(Z),uZ=(Z)=>`${Z} results in an unsatisfiable type`;var X2={},U1=(Z,Y,X)=>V0(Z,Y,{$:X,invert:!1,pipe:!1}),o2=(Z,Y,X)=>V0(Z,Y,{$:X,invert:!1,pipe:!0}),V0=(Z,Y,X)=>{let G=X.pipe?"|>":"&",_=`${Z.hash}${G}${Y.hash}`;if(X2[_]!==void 0)return X2[_];if(!X.pipe){let H=`${Y.hash}${G}${Z.hash}`;if(X2[H]!==void 0){let Q=X2[H],J=Q instanceof S?Q.invert():Q;return X2[_]=J,J}}let $=!X.pipe||!Z.includesTransform&&!Y.includesTransform;if($&&Z.equals(Y))return Z;let W=$?dZ(Z,Y,X):Z.hasKindIn(...e4)?fJ(Z,Y,X):dZ(Z,Y,X);if(O0(W)){if(Z.equals(W))W=Z;else if(Y.equals(W))W=Y}return X2[_]=W,W},dZ=(Z,Y,X)=>{let G=Z.precedence<Y.precedence?Z.kind:Y.kind,_=Z.impl.intersections[Y.kind]??Y.impl.intersections[Z.kind];if(_===void 0)return null;else if(G===Z.kind)return _(Z,Y,X);else{let $=_(Y,Z,{...X,invert:!X.invert});if($ instanceof S)$=$.invert();return $}},fJ=(Z,Y,X)=>Z.includesTransform||Y.includesTransform?X.invert?LG(Y,Z,X):LG(Z,Y,X):dZ(Z,Y,X),LG=(Z,Y,X)=>Z.distribute((G)=>hJ(G,Y,X),(G)=>{let _=G.filter(O0);if(_.length===0)return S.init("union",Z.branches,Y.branches);if(_.length<Z.branches.length||!Z.branches.every((H,Q)=>H.in.equals(_[Q].in)))return X.$.parseSchema(_);let $;if(_.length===1){let H=_[0];if(!$)return H;return X.$.node("morph",{...H.inner,in:H.in.configure($,"self")})}let W={branches:_};if($)W.meta=$;return X.$.parseSchema(W)}),hJ=(Z,Y,X)=>{if(Z.hasKind("morph")){let _=[...Z.morphs];if(Z.lastMorphIfNode){let $=V0(Z.lastMorphIfNode,Y,X);if($ instanceof S)return $;_[_.length-1]=$}else _.push(Y);return X.$.node("morph",{morphs:_,in:Z.inner.in})}if(Y.hasKind("morph")){let _=V0(Z,Y.in,X);if(_ instanceof S)return _;return X.$.node("morph",{morphs:[Y],in:_})}return X.$.node("morph",{morphs:[Y],in:Z})};class K1 extends i2{constructor(Z,Y){super(Z,Y);Object.defineProperty(this,Y1,{value:"constraint",enumerable:!1})}impliedSiblings;intersect(Z){return U1(this,Z,this.$)}}class G4 extends K1{traverseApply=(Z,Y)=>{if(!this.traverseAllows(Z,Y))Y.errorFromNodeContext(this.errorContext)};compile(Z){if(Z.traversalKind==="Allows")Z.return(this.compiledCondition);else Z.if(this.compiledNegation,()=>Z.line(`${Z.ctx}.errorFromNodeContext(${this.compiledErrorContext})`))}get errorContext(){return{code:this.kind,description:this.description,meta:this.meta,...this.inner}}get compiledErrorContext(){return V4(this.errorContext)}}var s0=(Z)=>(Y,X)=>{if(U0(Y)){if(Y.length===0)return;let _=Y.map(($)=>X.$.node(Z,$));if(Z==="predicate")return _;return _.sort(($,W)=>$.hash<W.hash?-1:1)}let G=X.$.node(Z,Y);return G.hasOpenIntersection()?[G]:G},G2=(Z)=>{let Y=Z.r.shift();if(!Y){let G=Z.l.length===0&&Z.kind==="structure"?I.intrinsic.unknown.internal:Z.ctx.$.node(Z.kind,Object.assign(Z.baseInner,kJ(Z.l)),{prereduced:!0});for(let _ of Z.roots){if(G instanceof S)return G;G=V0(_,G,Z.ctx)}return G}let X=!1;for(let G=0;G<Z.l.length;G++){let _=V0(Z.l[G],Y,Z.ctx);if(_===null)continue;if(_ instanceof S)return _;if(!X){if(_.isRoot())return Z.roots.push(_),Z.l.splice(G),G2(Z);Z.l[G]=_,X=!0}else if(!Z.l.includes(_))return G0(`Unexpectedly encountered multiple distinct intersection results for refinement ${_}`)}if(!X)Z.l.push(Y);if(Z.kind==="intersection"){if(Y.impliedSiblings)for(let G of Y.impliedSiblings)c1(Z.r,G)}return G2(Z)},_2=(Z)=>{return Object.entries(Z).flatMap(([X,G])=>(X in i8)?G:[]).sort((X,G)=>X.precedence<G.precedence?-1:X.precedence>G.precedence?1:X.kind==="predicate"&&G.kind==="predicate"?0:X.hash<G.hash?-1:1)},kJ=(Z)=>{let Y={};for(let X of Z)if(X.hasOpenIntersection())Y[X.kind]=Y0(Y[X.kind],X);else{if(Y[X.kind])return G0(`Unexpected intersection of closed refinements of kind ${X.kind}`);Y[X.kind]=X}return Y},DG=(...Z)=>A(OG(...Z)),OG=(Z,Y,X)=>{let G=X.hasKind("morph")?"a morph":X.isUnknown()?"unknown":X.exclude(Y).defaultShortDescription;return`${lX(Z)} operand must be ${Y.description} (was ${G})`};var VG=(Z,Y,X)=>new A4(Z,Y,X,X,null);class n8 extends h1{}class A4 extends h1{[Y1]="generic";paramDefs;bodyDef;$;arg$;baseInstantiation;hkt;description;constructor(Z,Y,X,G,_){super((...$)=>{let W=i(this.names,(H,Q)=>{let J=this.arg$.parse($[H]);if(!J.extends(this.constraints[H]))A(bJ(Q,this.constraints[H].expression,J.expression));return[Q,J]});if(this.defIsLazy()){let H=this.bodyDef(W);return this.$.parse(H)}return this.$.parse(Y,{args:W})});this.paramDefs=Z,this.bodyDef=Y,this.$=X,this.arg$=G,this.hkt=_,this.description=_?new _().description??`a generic type for ${_.constructor.name}`:"a generic type",this.baseInstantiation=this(...this.constraints)}defIsLazy(){return this.bodyDef instanceof n8}cacheGetter(Z,Y){return Object.defineProperty(this,Z,{value:Y}),Y}get json(){return this.cacheGetter("json",{params:this.params.map((Z)=>Z[1].isUnknown()?Z[0]:[Z[0],Z[1].json]),body:XG(this.bodyDef)})}get params(){return this.cacheGetter("params",this.paramDefs.map((Z)=>typeof Z==="string"?[Z,I.intrinsic.unknown]:[Z[0],this.$.parse(Z[1])]))}get names(){return this.cacheGetter("names",this.params.map((Z)=>Z[0]))}get constraints(){return this.cacheGetter("constraints",this.params.map((Z)=>Z[1]))}get internal(){return this}get referencesById(){return this.baseInstantiation.internal.referencesById}get references(){return this.baseInstantiation.internal.references}}var bJ=(Z,Y,X)=>`${Z} must be assignable to ${Y} (was ${X})`;var yJ=r({kind:"predicate",hasAssociatedError:!0,collapsibleKey:"predicate",keys:{predicate:{}},normalize:(Z)=>typeof Z==="function"?{predicate:Z}:Z,defaults:{description:(Z)=>`valid according to ${Z.predicate.name||"an anonymous predicate"}`},intersectionIsOpen:!0,intersections:{predicate:()=>null}});class MG extends K1{serializedPredicate=C0(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=V4(this.errorContext);traverseApply=(Z,Y)=>{if(!this.predicate(Z,Y.external)&&!Y.hasError())Y.errorFromNodeContext(this.errorContext)};compile(Z){if(Z.traversalKind==="Allows"){Z.return(this.compiledCondition);return}Z.if(`${this.compiledNegation} && !ctx.hasError()`,()=>Z.line(`ctx.errorFromNodeContext(${this.compiledErrorContext})`))}reduceJsonSchema(Z,Y){return Y.fallback.predicate({code:"predicate",base:Z,predicate:this.predicate})}}var cZ={implementation:yJ,Node:MG};var gJ=r({kind:"divisor",collapsibleKey:"rule",keys:{rule:{parse:(Z)=>Number.isInteger(Z)?Z:A(pJ(Z))}},normalize:(Z)=>typeof Z==="number"?{rule:Z}:Z,hasAssociatedError:!0,defaults:{description:(Z)=>Z.rule===1?"an integer":Z.rule===2?"even":`a multiple of ${Z.rule}`},intersections:{divisor:(Z,Y,X)=>X.$.node("divisor",{rule:Math.abs(Z.rule*Y.rule/mJ(Z.rule,Y.rule))})},obviatesBasisDescription:!0});class AG extends G4{traverseAllows=(Z)=>Z%this.rule===0;compiledCondition=`data % ${this.rule} === 0`;compiledNegation=`data % ${this.rule} !== 0`;impliedBasis=I.intrinsic.number.internal;expression=`% ${this.rule}`;reduceJsonSchema(Z){if(Z.type="integer",this.rule===1)return Z;return Z.multipleOf=this.rule,Z}}var lZ={implementation:gJ,Node:AG};var pJ=(Z)=>`divisor must be an integer (was ${Z})`,mJ=(Z,Y)=>{let X,G=Z,_=Y;while(_!==0)X=_,_=G%_,G=X;return G};class M1 extends G4{boundOperandKind=lJ[this.kind];compiledActual=this.boundOperandKind==="value"?"data":this.boundOperandKind==="length"?"data.length":"data.valueOf()";comparator=iJ(this.kind,this.exclusive);numericLimit=this.rule.valueOf();expression=`${this.comparator} ${this.rule}`;compiledCondition=`${this.compiledActual} ${this.comparator} ${this.numericLimit}`;compiledNegation=`${this.compiledActual} ${uJ[this.comparator]} ${this.numericLimit}`;stringLimit=this.boundOperandKind==="date"?oJ(this.numericLimit):`${this.numericLimit}`;limitKind=this.comparator["0"]==="<"?"upper":"lower";isStricterThan(Z){return(this.limitKind==="upper"?this.numericLimit<Z.numericLimit:this.numericLimit>Z.numericLimit)||this.numericLimit===Z.numericLimit&&this.exclusive===!0&&!Z.exclusive}overlapsRange(Z){if(this.isStricterThan(Z))return!1;if(this.numericLimit===Z.numericLimit&&(this.exclusive||Z.exclusive))return!1;return!0}overlapIsUnit(Z){return this.numericLimit===Z.numericLimit&&!this.exclusive&&!Z.exclusive}}var uJ={"<":">=","<=":">",">":"<=",">=":"<"},dJ={min:"max",minLength:"maxLength",after:"before"},r8={parse:(Z)=>Z||void 0},s8=(Z)=>(Y)=>{if(typeof Y==="number")return{rule:Y};let{exclusive:X,...G}=Y;return X?{...G,rule:Z==="minLength"?G.rule+1:G.rule-1}:G},a8=(Z)=>(Y)=>{if(typeof Y==="number"||typeof Y==="string"||Y instanceof Date)return{rule:Y};let{exclusive:X,...G}=Y;if(!X)return G;let _=typeof G.rule==="number"?G.rule:typeof G.rule==="string"?new Date(G.rule).valueOf():G.rule.valueOf();return X?{...G,rule:Z==="after"?_+1:_-1}:G},t8=(Z)=>typeof Z==="string"||typeof Z==="number"?new Date(Z):Z,cJ=(Z,Y)=>`${Z} bound must be a positive integer (was ${Y})`,$2=(Z)=>(Y)=>{if(!Number.isInteger(Y)||Y<0)A(cJ(Z,Y));return Y},lJ={min:"value",max:"value",minLength:"length",maxLength:"length",after:"date",before:"date"},iJ=(Z,Y)=>`${g0(Z,dJ)?">":"<"}${Y?"":"="}`,oJ=(Z)=>typeof Z==="string"?Z:new Date(Z).toLocaleString(),RG=(Z)=>`Bounded expression ${Z} must be exactly one of number, string, Array, or Date`;var nJ=r({kind:"after",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:t8,serialize:(Z)=>Z.toISOString()}},normalize:a8("after"),defaults:{description:(Z)=>`${Z.collapsibleLimitString} or later`,actual:f4},intersections:{after:(Z,Y)=>Z.isStricterThan(Y)?Z:Y}});class NG extends M1{impliedBasis=I.intrinsic.Date.internal;collapsibleLimitString=f4(this.rule);traverseAllows=(Z)=>Z>=this.rule;reduceJsonSchema(Z,Y){return Y.fallback.date({code:"date",base:Z,after:this.rule})}}var iZ={implementation:nJ,Node:NG};var rJ=r({kind:"before",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:t8,serialize:(Z)=>Z.toISOString()}},normalize:a8("before"),defaults:{description:(Z)=>`${Z.collapsibleLimitString} or earlier`,actual:f4},intersections:{before:(Z,Y)=>Z.isStricterThan(Y)?Z:Y,after:(Z,Y,X)=>Z.overlapsRange(Y)?Z.overlapIsUnit(Y)?X.$.node("unit",{unit:Z.rule}):null:S.init("range",Z,Y)}});class wG extends M1{collapsibleLimitString=f4(this.rule);traverseAllows=(Z)=>Z<=this.rule;impliedBasis=I.intrinsic.Date.internal;reduceJsonSchema(Z,Y){return Y.fallback.date({code:"date",base:Z,before:this.rule})}}var oZ={implementation:rJ,Node:wG};var sJ=r({kind:"exactLength",collapsibleKey:"rule",keys:{rule:{parse:$2("exactLength")}},normalize:(Z)=>typeof Z==="number"?{rule:Z}:Z,hasAssociatedError:!0,defaults:{description:(Z)=>`exactly length ${Z.rule}`,actual:(Z)=>`${Z.length}`},intersections:{exactLength:(Z,Y,X)=>S.init("unit",X.$.node("unit",{unit:Z.rule}),X.$.node("unit",{unit:Y.rule}),{path:["length"]}),minLength:(Z,Y)=>Z.rule>=Y.rule?Z:S.init("range",Z,Y),maxLength:(Z,Y)=>Z.rule<=Y.rule?Z:S.init("range",Z,Y)}});class IG extends G4{traverseAllows=(Z)=>Z.length===this.rule;compiledCondition=`data.length === ${this.rule}`;compiledNegation=`data.length !== ${this.rule}`;impliedBasis=I.intrinsic.lengthBoundable.internal;expression=`== ${this.rule}`;reduceJsonSchema(Z){switch(Z.type){case"string":return Z.minLength=this.rule,Z.maxLength=this.rule,Z;case"array":return Z.minItems=this.rule,Z.maxItems=this.rule,Z;default:return N0.throwInternalOperandError("exactLength",Z)}}}var nZ={implementation:sJ,Node:IG};var aJ=r({kind:"max",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{},exclusive:r8},normalize:(Z)=>typeof Z==="number"?{rule:Z}:Z,defaults:{description:(Z)=>{if(Z.rule===0)return Z.exclusive?"negative":"non-positive";return`${Z.exclusive?"less than":"at most"} ${Z.rule}`}},intersections:{max:(Z,Y)=>Z.isStricterThan(Y)?Z:Y,min:(Z,Y,X)=>Z.overlapsRange(Y)?Z.overlapIsUnit(Y)?X.$.node("unit",{unit:Z.rule}):null:S.init("range",Z,Y)},obviatesBasisDescription:!0});class BG extends M1{impliedBasis=I.intrinsic.number.internal;traverseAllows=this.exclusive?(Z)=>Z<this.rule:(Z)=>Z<=this.rule;reduceJsonSchema(Z){if(this.exclusive)Z.exclusiveMaximum=this.rule;else Z.maximum=this.rule;return Z}}var rZ={implementation:aJ,Node:BG};var tJ=r({kind:"maxLength",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:$2("maxLength")}},reduce:(Z,Y)=>Z.rule===0?Y.node("exactLength",Z):void 0,normalize:s8("maxLength"),defaults:{description:(Z)=>`at most length ${Z.rule}`,actual:(Z)=>`${Z.length}`},intersections:{maxLength:(Z,Y)=>Z.isStricterThan(Y)?Z:Y,minLength:(Z,Y,X)=>Z.overlapsRange(Y)?Z.overlapIsUnit(Y)?X.$.node("exactLength",{rule:Z.rule}):null:S.init("range",Z,Y)}});class KG extends M1{impliedBasis=I.intrinsic.lengthBoundable.internal;traverseAllows=(Z)=>Z.length<=this.rule;reduceJsonSchema(Z){switch(Z.type){case"string":return Z.maxLength=this.rule,Z;case"array":return Z.maxItems=this.rule,Z;default:return N0.throwInternalOperandError("maxLength",Z)}}}var sZ={implementation:tJ,Node:KG};var eJ=r({kind:"min",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{},exclusive:r8},normalize:(Z)=>typeof Z==="number"?{rule:Z}:Z,defaults:{description:(Z)=>{if(Z.rule===0)return Z.exclusive?"positive":"non-negative";return`${Z.exclusive?"more than":"at least"} ${Z.rule}`}},intersections:{min:(Z,Y)=>Z.isStricterThan(Y)?Z:Y},obviatesBasisDescription:!0});class CG extends M1{impliedBasis=I.intrinsic.number.internal;traverseAllows=this.exclusive?(Z)=>Z>this.rule:(Z)=>Z>=this.rule;reduceJsonSchema(Z){if(this.exclusive)Z.exclusiveMinimum=this.rule;else Z.minimum=this.rule;return Z}}var aZ={implementation:eJ,Node:CG};var ZQ=r({kind:"minLength",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:$2("minLength")}},reduce:(Z)=>Z.rule===0?I.intrinsic.unknown:void 0,normalize:s8("minLength"),defaults:{description:(Z)=>Z.rule===1?"non-empty":`at least length ${Z.rule}`,actual:(Z)=>Z.length===0?"":`${Z.length}`},intersections:{minLength:(Z,Y)=>Z.isStricterThan(Y)?Z:Y}});class TG extends M1{impliedBasis=I.intrinsic.lengthBoundable.internal;traverseAllows=(Z)=>Z.length>=this.rule;reduceJsonSchema(Z){switch(Z.type){case"string":return Z.minLength=this.rule,Z;case"array":return Z.minItems=this.rule,Z;default:return N0.throwInternalOperandError("minLength",Z)}}}var tZ={implementation:ZQ,Node:TG};var qG={min:aZ.implementation,max:rZ.implementation,minLength:tZ.implementation,maxLength:sZ.implementation,exactLength:nZ.implementation,after:iZ.implementation,before:oZ.implementation},jG={min:aZ.Node,max:rZ.Node,minLength:tZ.Node,maxLength:sZ.Node,exactLength:nZ.Node,after:iZ.Node,before:oZ.Node};var YQ=r({kind:"pattern",collapsibleKey:"rule",keys:{rule:{},flags:{}},normalize:(Z)=>typeof Z==="string"?{rule:Z}:Z instanceof RegExp?Z.flags?{rule:Z.source,flags:Z.flags}:{rule:Z.source}:Z,obviatesBasisDescription:!0,obviatesBasisExpression:!0,hasAssociatedError:!0,intersectionIsOpen:!0,defaults:{description:(Z)=>`matched by ${Z.rule}`},intersections:{pattern:()=>null}});class PG extends G4{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=I.intrinsic.string.internal;reduceJsonSchema(Z,Y){if(Z.pattern)return Y.fallback.patternIntersection({code:"patternIntersection",base:Z,pattern:this.rule});return Z.pattern=this.rule,Z}}var eZ={implementation:YQ,Node:PG};var n2=(Z,Y)=>{let X=XQ(Z);if(Y&&!Y.includes(X))return A(`Root of kind ${X} should be one of ${Y}`);return X},XQ=(Z)=>{if(y(Z,"root"))return Z.kind;if(typeof Z==="string")return Z[0]==="$"?"alias":(Z in J1)?"domain":"proto";if(typeof Z==="function")return"proto";if(typeof Z!=="object"||Z===null)return A(SG(Z));if("morphs"in Z)return"morph";if("branches"in Z||U0(Z))return"union";if("unit"in Z)return"unit";if("reference"in Z)return"alias";let Y=Object.keys(Z);if(Y.length===0||Y.some((X)=>(X in i8)))return"intersection";if("proto"in Z)return"proto";if("domain"in Z)return"domain";return A(SG(Z))},SG=(Z)=>`${o(Z)} is not a valid type schema`,vG={},GQ=(Z)=>U0(Z)?Z.map((Y)=>Y.collapsibleJson):Z.collapsibleJson,X1={};I.nodesByRegisteredId=X1;var Z5=(Z)=>{return vG[Z]??=0,`${Z}${++vG[Z]}`},Y5=(Z)=>{let Y=W2[Z.kind],X=Y.applyConfig?.(Z.def,Z.$.resolvedConfig)??Z.def,G={},{meta:_,...$}=X,W=_===void 0?{}:typeof _==="string"?{description:_}:_,H=BZ($).sort(([J],[z])=>Z2(J)?Z2(z)?Y2(J)-Y2(z):1:Z2(z)?-1:J<z?-1:1).filter(([J,z])=>{if(J.startsWith("meta.")){let U=J.slice(5);return W[U]=z,!1}return!0});for(let J of H){let z=J[0],U=Y.keys[z];if(!U)return A(`Key ${z} is not valid on ${Z.kind} schema`);let D=U.parse?U.parse(J[1],Z):J[1];if(D!==V1&&(D!==void 0||U.preserveUndefined))G[z]=D}if(Y.reduce&&!Z.prereduced){let J=Y.reduce(G,Z.$);if(J){if(J instanceof S)return J.throw();return _Q(J,W)}}return X5({id:Z.id,kind:Z.kind,inner:G,meta:W,$:Z.$})},X5=({id:Z,kind:Y,inner:X,meta:G,$:_,ignoreCache:$})=>{let W=W2[Y],H=BZ(X),Q=[],J={};for(let[x,h]of H){let g=W.keys[x],K=g.serialize??(g.child?GQ:B1);if(J[x]=K(h),g.child===!0){let B=h;if(U0(B))Q.push(...B);else Q.push(B)}else if(typeof g.child==="function")Q.push(...g.child(h))}if(W.finalizeInnerJson)J=W.finalizeInnerJson(J);let z={...J},U={};if(!l1(G))U=i(G,(x,h)=>[x,x==="examples"?h:B1(h)]),z.meta=e8(U,"description",!0);J=e8(J,W.collapsibleKey,!1);let D=JSON.stringify({kind:Y,...J});z=e8(z,W.collapsibleKey,!1);let V=e8(z,W.collapsibleKey,!0),N=JSON.stringify({kind:Y,...z});if(_.nodesByHash[N]&&!$)return _.nodesByHash[N];let R={id:Z,kind:Y,impl:W,inner:X,innerEntries:H,innerJson:J,innerHash:D,meta:G,metaJson:U,json:z,hash:N,collapsibleJson:V,children:Q};if(Y!=="intersection"){for(let x in X)if(x!=="in"&&x!=="out")R[x]=X[x]}let b=new fG[Y](R,_);return _.nodesByHash[N]=b},xG=(Z,Y)=>{if(Z.id===Y)return Z;if(O0(X1[Y]))G0(`Unexpected attempt to overwrite node id ${Y}`);return X5({id:Y,kind:Z.kind,inner:Z.inner,meta:Z.meta,$:Z.$,ignoreCache:!0})},_Q=(Z,Y,X)=>{if(X&&O0(X1[X]))G0(`Unexpected attempt to overwrite node id ${X}`);return X5({id:X??Z5(Y.alias??Z.kind),kind:Z.kind,inner:Z.inner,meta:Y,$:Z.$})},e8=(Z,Y,X)=>{let G=Object.keys(Z);if(G.length===1&&G[0]===Y){let _=Z[Y];if(X)return _;if(H1(_,"object")&&(Object.keys(_).length===1||Array.isArray(_)))return _}return Z};var r2=(Z,Y,X)=>{if(Z.key!==Y.key)return null;let G=Z.key,_=V0(Z.value,Y.value,X),$=Z.required||Y.required?"required":"optional";if(_ instanceof S)if($==="optional")_=I.intrinsic.never.internal;else return _.withPrefixKey(Z.key,Z.required&&Y.required?"required":"optional");if($==="required")return X.$.node("required",{key:G,value:_});let W=Z.hasDefault()?Y.hasDefault()?Z.default===Y.default?Z.default:A(G5(Z.default,Y.default)):Z.default:Y.hasDefault()?Y.default:V1;return X.$.node("optional",{key:G,value:_,default:W})};class s2 extends K1{required=this.kind==="required";optional=this.kind==="optional";impliedBasis=I.intrinsic.object.internal;serializedKey=X4(this.key);compiledKey=typeof this.key==="string"?this.key:this.serializedKey;flatRefs=Y0(this.value.flatRefs.map((Z)=>b1([this.key,...Z.path],Z.node)),b1([this.key],this.value));_transform(Z,Y){Y.path.push(this.key);let X=super._transform(Z,Y);return Y.path.pop(),X}hasDefault(){return"default"in this.inner}traverseAllows=(Z,Y)=>{if(this.key in Z)return z1(this.key,()=>this.value.traverseAllows(Z[this.key],Y),Y);return this.optional};traverseApply=(Z,Y)=>{if(this.key in Z)z1(this.key,()=>this.value.traverseApply(Z[this.key],Y),Y);else if(this.hasKind("required"))Y.errorFromNodeContext(this.errorContext)};compile(Z){if(Z.if(`${this.serializedKey} in data`,()=>Z.traverseKey(this.serializedKey,`data${Z.prop(this.key)}`,this.value)),this.hasKind("required"))Z.else(()=>Z.traversalKind==="Apply"?Z.line(`ctx.errorFromNodeContext(${this.compiledErrorContext})`):Z.return(!1));if(Z.traversalKind==="Allows")Z.return(!0)}}var G5=(Z,Y)=>`Invalid intersection of default values ${o(Z)} & ${o(Y)}`;var $Q=r({kind:"optional",hasAssociatedError:!1,intersectionIsOpen:!0,keys:{key:{},value:{child:!0,parse:(Z,Y)=>Y.$.parseSchema(Z)},default:{preserveUndefined:!0}},normalize:(Z)=>Z,reduce:(Z,Y)=>{if(Y.resolvedConfig.exactOptionalPropertyTypes===!1){if(!Z.value.allows(void 0))return Y.node("optional",{...Z,value:Z.value.or(u.undefined)},{prereduced:!0})}},defaults:{description:(Z)=>`${Z.compiledKey}?: ${Z.value.description}`},intersections:{optional:r2}});class hG extends s2{constructor(...Z){super(...Z);if("default"in this.inner)t2(this.value,this.inner.default,this.key)}get outProp(){if(!this.hasDefault())return this;let{default:Z,...Y}=this.inner;return this.cacheGetter("outProp",this.$.node("required",Y,{prereduced:!0}))}expression=this.hasDefault()?`${this.compiledKey}: ${this.value.expression} = ${o(this.inner.default)}`:`${this.compiledKey}?: ${this.value.expression}`;defaultValueMorph=HQ(this);defaultValueMorphRef=this.defaultValueMorph&&C0(this.defaultValueMorph)}var a2={implementation:$Q,Node:hG},WQ={},HQ=(Z)=>{if(!Z.hasDefault())return;let Y=`{${Z.compiledKey}: ${Z.value.id} = ${B1(Z.default)}}`;return WQ[Y]??=_5(Z.key,Z.value,Z.default)},_5=(Z,Y,X)=>{if(typeof X==="function")return Y.includesTransform?(_,$)=>{return z1(Z,()=>Y(_[Z]=X(),$),$),_}:(_)=>{return _[Z]=X(),_};let G=Y.includesTransform?Y.assert(X):X;return H1(G,"object")?(_,$)=>{return z1(Z,()=>Y(_[Z]=X,$),$),_}:(_)=>{return _[Z]=G,_}},t2=(Z,Y,X)=>{let G=L4(Y);if(H1(Y,"object")&&!G)A(JQ(X));let _=Z.in(G?Y():Y);if(_ instanceof Q1){if(X===null)A(`Default ${_.summary}`);let $=_.transform((W)=>W.transform((H)=>({...H,prefixPath:[X]})));A(`Default for ${$.summary}`)}return Y},JQ=(Z)=>{return`Non-primitive default ${Z===null?"":typeof Z==="number"?`for value at [${Z}] `:`for ${X4(Z)} `}must be specified as a function like () => ({my: 'object'})`};class C1 extends i2{constructor(Z,Y){super(Z,Y);Object.defineProperty(this,Y1,{value:"root",enumerable:!1})}get internal(){return this}get "~standard"(){return{vendor:"arktype",version:1,validate:(Z)=>{let Y=this(Z);if(Y instanceof Q1)return Y;return{value:Y}},toJSONSchema:(Z)=>{if(Z.target&&Z.target!=="draft-2020-12")return A(`JSONSchema target '${Z.target}' is not supported (must be "draft-2020-12")`);if(Z.io==="input")return this.in.toJsonSchema();return this.out.toJsonSchema()}}}as(){return this}brand(Z){if(Z==="")return A(QQ);return this}readonly(){return this}branches=this.hasKind("union")?this.inner.branches:[this];distribute(Z,Y){let X=this.branches.map(Z);return Y?.(X)??X}get shortDescription(){return this.meta.description??this.defaultShortDescription}toJsonSchema(Z={}){let Y=yZ(this.$.resolvedConfig.toJsonSchema,Z);Y.useRefs||=this.isCyclic;let X=typeof Y.dialect==="string"?{$schema:Y.dialect}:{};if(Object.assign(X,this.toJsonSchemaRecurse(Y)),Y.useRefs)X.$defs=i(this.references,(G,_)=>_.isRoot()&&!_.alwaysExpandJsonSchema?[_.id,_.toResolvedJsonSchema(Y)]:[]);return X}toJsonSchemaRecurse(Z){if(Z.useRefs&&!this.alwaysExpandJsonSchema)return{$ref:`#/$defs/${this.id}`};return this.toResolvedJsonSchema(Z)}get alwaysExpandJsonSchema(){return this.isBasis()||this.kind==="alias"||this.hasKind("union")&&this.isBoolean}toResolvedJsonSchema(Z){let Y=this.innerToJsonSchema(Z);return Object.assign(Y,this.metaJson)}intersect(Z){let Y=this.$.parseDefinition(Z),X=this.rawIntersect(Y);if(X instanceof S)return X;return this.$.finalize(X)}rawIntersect(Z){return U1(this,Z,this.$)}toNeverIfDisjoint(){return this}and(Z){let Y=this.intersect(Z);return Y instanceof S?Y.throw():Y}rawAnd(Z){let Y=this.rawIntersect(Z);return Y instanceof S?Y.throw():Y}or(Z){let Y=this.$.parseDefinition(Z);return this.$.finalize(this.rawOr(Y))}rawOr(Z){let Y=[...this.branches,...Z.branches];return this.$.node("union",Y)}map(Z){return this.$.schema(this.applyStructuralOperation("map",[Z]))}pick(...Z){return this.$.schema(this.applyStructuralOperation("pick",Z))}omit(...Z){return this.$.schema(this.applyStructuralOperation("omit",Z))}required(){return this.$.schema(this.applyStructuralOperation("required",[]))}partial(){return this.$.schema(this.applyStructuralOperation("partial",[]))}_keyof;keyof(){if(this._keyof)return this._keyof;let Z=this.applyStructuralOperation("keyof",[]).reduce((Y,X)=>Y.intersect(X).toNeverIfDisjoint(),I.intrinsic.unknown.internal);if(Z.branches.length===0)A(uZ(`keyof ${this.expression}`));return this._keyof=this.$.finalize(Z)}get props(){if(this.branches.length!==1)return A(zQ(this.expression));return[...this.applyStructuralOperation("props",[])[0]]}merge(Z){let Y=this.$.parseDefinition(Z);return this.$.schema(Y.distribute((X)=>this.applyStructuralOperation("merge",[kG(X)??A(bG("merge",X.expression))])))}applyStructuralOperation(Z,Y){return this.distribute((X)=>{if(X.equals(I.intrinsic.object)&&Z!=="merge")return X;let G=kG(X);if(!G)A(bG(Z,X.expression));if(Z==="keyof")return G.keyof();if(Z==="get")return G.get(...Y);if(Z==="props")return G.props;let _=Z==="required"?"require":Z==="partial"?"optionalize":Z;return this.$.node("intersection",{...X.inner,structure:G[_](...Y)})})}get(...Z){if(Z[0]===void 0)return this;return this.$.schema(this.applyStructuralOperation("get",Z))}extract(Z){let Y=this.$.parseDefinition(Z);return this.$.schema(this.branches.filter((X)=>X.extends(Y)))}exclude(Z){let Y=this.$.parseDefinition(Z);return this.$.schema(this.branches.filter((X)=>!X.extends(Y)))}array(){return this.$.schema(this.isUnknown()?{proto:Array}:{proto:Array,sequence:this},{prereduced:!0})}overlaps(Z){return!(this.intersect(Z)instanceof S)}extends(Z){let Y=this.intersect(Z);return!(Y instanceof S)&&this.equals(Y)}ifExtends(Z){return this.extends(Z)?this:void 0}subsumes(Z){return this.$.parseDefinition(Z).extends(this)}configure(Z,Y="shallow"){return this.configureReferences(Z,Y)}describe(Z,Y="shallow"){return this.configure({description:Z},Y)}optional(){return[this,"?"]}default(Z){return t2(this,Z,null),[this,"=",Z]}from(Z){return this.assert(Z)}_pipe(...Z){let Y=Z.reduce((X,G)=>X.rawPipeOnce(G),this);return this.$.finalize(Y)}tryPipe(...Z){let Y=Z.reduce((X,G)=>X.rawPipeOnce(y(G,"root")?G:(_,$)=>{try{return G(_,$)}catch(W){return $.error({code:"predicate",predicate:G,actual:`aborted due to error:
22
+ `);class x1{path=[];errors=new J1(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 y2(...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 L4(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]]}for(let G of Z){this.path=[...Y];let $=D0(G),W=G(_===void 0?this.root:_[X],this);if(W instanceof L4){this.errors.add(W);break}if(W instanceof J1){if(!$)this.errors.merge(W);break}if(_===void 0)this.root=W;else _[X]=W;this.applyQueuedMorphs()}}}var Q1=(Y,Z,X)=>{if(!X)return Z();X.path.push(Y);let _=Z();return X.path.pop(),_};class u2 extends v1{attachments;$;onFail;includesTransform;includesContextualPredicate;isCyclic;allowsRequiresContext;rootApplyStrategy;contextFreeMorph;rootApply;referencesById;shallowReferences;flatRefs;flatMorphs;allows;get shallowMorphs(){return[]}constructor(Y,Z){super((_,G,$=this.onFail)=>{if(G)return this.traverseApply(_,G),G.hasError()?G.errors:G.data;return this.rootApply(_,$)},{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)=>NJ(_,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 $=0;$<G.length;$++){let W=G[$];if(!this.flatRefs.some((H)=>__(H,W))){this.flatRefs.push(W);for(let H of W.node.branches)if(H.hasKind("morph")||H.hasKind("intersection")&&H.structure?.structuralMorph!==void 0)this.flatMorphs.push({path:W.path,propString:W.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 x1(_,this.$.resolvedConfig)):(_)=>this.traverseAllows(_)}createRootApply(){switch(this.rootApplyStrategy){case"allows":return(Z,X)=>{if(this.allows(Z))return Z;let _=new x1(Z,this.$.resolvedConfig);return this.traverseApply(Z,_),_.finalize(X)};case"contextual":return(Z,X)=>{let _=new x1(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 x1(Z,this.$.resolvedConfig);return this.traverseApply(Z,_),_.finalize(X)};case"branchedOptimistic":return this.createBranchedOptimisticRootApply();default:return this.rootApplyStrategy,_0(`Unexpected rootApplyStrategy ${this.rootApplyStrategy}`)}}compiledMeta=wJ(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 $=_;Z[X]=U0($)?$.map((W)=>W[Y]):$[Y]}else Z[X]=_}return this.$.node(this.kind,Z)}toJSON(){return this.json}toString(){return`Type<${this.expression}>`}equals(Y){let Z=D0(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)C4(`${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))C4(`${this.kind} node was not one of asserted kinds ${Y}`);return this}isBasis(){return s1(tX,this.kind)}isConstraint(){return s1(l8,this.kind)}isStructural(){return s1(s4,this.kind)}isRefinement(){return s1(PY,this.kind)}isRoot(){return s1(t4,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=m2.normalize(Y);return this._select(Z)}_select(Y){let Z=m2.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 m2.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 F=z;if(!U0(F)){let L=F._transform(Y,Z);return L?[J,L]:[]}if(F.length===0)return[J,z];let O=F.flatMap((L)=>{return L._transform(Y,Z)??[]});return O.length?[J,O]:[]});delete Z.seen[this.id];let $=Object.assign(G,{meta:this.meta}),W=Z.selected&&!Z.selected.includes(this)?$:Y(this.kind,$,Z);if(W===null)return null;if(D0(W))return _=W;let H=Object.keys(W);if((H.length===0||H.length===1&&H[0]==="meta")&&!l1(this.inner))return null;if((this.kind==="required"||this.kind==="optional"||this.kind==="index")&&!("value"in W))return Z.undeclaredKeyHandling?{...W,value:I.intrinsic.unknown}:null;if(this.kind==="morph")W.in??=I.intrinsic.unknown;return _=X.node(this.kind,W,Z.parseOptions)}configureReferences(Y,Z="references"){let X=m2.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),$=G&&F4(G),W=X.boundary==="child"?(H,Q)=>Q.root.children.includes(H):X.boundary==="shallow"?(H)=>H.kind!=="structure":()=>!0;return this.$.finalize(this.transform(_,{shouldTransform:W,selected:$}))}}var m2={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)C4(X_(Z,X));return Y},find:(Y)=>Y[0],assertFind:(Y,Z,X)=>{if(Y.length===0)C4(X_(Z,X));return Y[0]}},normalize:(Y)=>typeof Y==="function"?{boundary:"references",method:"filter",where:Y}:typeof Y==="string"?g0(Y,m2.applyBoundary)?{method:"filter",boundary:Y}:{boundary:"references",method:"filter",kind:Y}:{boundary:"references",method:"filter",...Y}},X_=(Y,Z)=>`${Y} had no references matching ${i(Z)}.`,AJ=(Y)=>Y4(Y,{stringifyNonKey:(Z)=>Z.expression}),RJ=/"(\$ark\.[^"]+)"/g,wJ=(Y)=>JSON.stringify(Y).replaceAll(RJ,"$1"),f1=(Y,Z)=>({path:Y,node:Z,propString:AJ(Y)}),__=(Y,Z)=>Y.propString===Z.propString&&Y.node.equals(Z.node),xY=(Y,Z)=>c1(Y,Z,{isEqual:__}),NJ=(Y,Z)=>c1(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 hY(`Intersection${_&&` at ${_}`} of ${G_(Z,X)}`)}return`The following intersections result in unsatisfiable types:
23
+ \u2022 ${this.map(({path:Y,l:Z,r:X})=>`${Y}: ${G_(Z,X)}`).join(`
24
+ \u2022 `)}`}throw(){return A(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 I.intrinsic.never}}var G_=(Y,Z)=>`${fY(Y)} and ${fY(Z)}`,fY=(Y)=>D0(Y)?Y.expression:U0(Y)?Y.map(fY).join(" | ")||"never":String(Y),hY=(Y)=>`${Y} results in an unsatisfiable type`;var Y2={},z1=(Y,Z,X)=>L0(Y,Z,{$:X,invert:!1,pipe:!1}),d2=(Y,Z,X)=>L0(Y,Z,{$:X,invert:!1,pipe:!0}),L0=(Y,Z,X)=>{let _=X.pipe?"|>":"&",G=`${Y.hash}${_}${Z.hash}`;if(Y2[G]!==void 0)return Y2[G];if(!X.pipe){let H=`${Z.hash}${_}${Y.hash}`;if(Y2[H]!==void 0){let Q=Y2[H],J=Q instanceof S?Q.invert():Q;return Y2[G]=J,J}}let $=!X.pipe||!Y.includesTransform&&!Z.includesTransform;if($&&Y.equals(Z))return Y;let W=$?kY(Y,Z,X):Y.hasKindIn(...t4)?IJ(Y,Z,X):kY(Y,Z,X);if(D0(W)){if(Y.equals(W))W=Y;else if(Z.equals(W))W=Z}return Y2[G]=W,W},kY=(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 $=G(Z,Y,{...X,invert:!X.invert});if($ instanceof S)$=$.invert();return $}},IJ=(Y,Z,X)=>Y.includesTransform||Z.includesTransform?X.invert?$_(Z,Y,X):$_(Y,Z,X):kY(Y,Z,X),$_=(Y,Z,X)=>Y.distribute((_)=>KJ(_,Z,X),(_)=>{let G=_.filter(D0);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 $;if(G.length===1){let H=G[0];if(!$)return H;return X.$.node("morph",{...H.inner,in:H.in.configure($,"self")})}let W={branches:G};if($)W.meta=$;return X.$.parseSchema(W)}),KJ=(Y,Z,X)=>{if(Y.hasKind("morph")){let G=[...Y.morphs];if(Y.lastMorphIfNode){let $=L0(Y.lastMorphIfNode,Z,X);if($ instanceof S)return $;G[G.length-1]=$}else G.push(Z);return X.$.node("morph",{morphs:G,in:Y.inner.in})}if(Z.hasKind("morph")){let G=L0(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 N1 extends u2{constructor(Y,Z){super(Y,Z);Object.defineProperty(this,Y1,{value:"constraint",enumerable:!1})}impliedSiblings;intersect(Y){return z1(this,Y,this.$)}}class X4 extends N1{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 D4(this.errorContext)}}var s0=(Y)=>(Z,X)=>{if(U0(Z)){if(Z.length===0)return;let G=Z.map(($)=>X.$.node(Y,$));if(Y==="predicate")return G;return G.sort(($,W)=>$.hash<W.hash?-1:1)}let _=X.$.node(Y,Z);return _.hasOpenIntersection()?[_]:_},Z2=(Y)=>{let Z=Y.r.shift();if(!Z){let _=Y.l.length===0&&Y.kind==="structure"?I.intrinsic.unknown.internal:Y.ctx.$.node(Y.kind,Object.assign(Y.baseInner,BJ(Y.l)),{prereduced:!0});for(let G of Y.roots){if(_ instanceof S)return _;_=L0(G,_,Y.ctx)}return _}let X=!1;for(let _=0;_<Y.l.length;_++){let G=L0(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(_),Z2(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)c1(Y.r,_)}return Z2(Y)},X2=(Y)=>{return Object.entries(Y).flatMap(([X,_])=>(X in o8)?_:[]).sort((X,_)=>X.precedence<_.precedence?-1:X.precedence>_.precedence?1:X.kind==="predicate"&&_.kind==="predicate"?0:X.hash<_.hash?-1:1)},BJ=(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},W_=(...Y)=>A(H_(...Y)),H_=(Y,Z,X)=>{let _=X.hasKind("morph")?"a morph":X.isUnknown()?"unknown":X.exclude(Z).defaultShortDescription;return`${kX(Y)} operand must be ${Z.description} (was ${_})`};var J_=(Y,Z,X)=>new M4(Y,Z,X,X,null);class n8 extends v1{}class M4 extends v1{[Y1]="generic";paramDefs;bodyDef;$;arg$;baseInstantiation;hkt;description;constructor(Y,Z,X,_,G){super((...$)=>{let W=o(this.names,(H,Q)=>{let J=this.arg$.parse($[H]);if(!J.extends(this.constraints[H]))A(TJ(Q,this.constraints[H].expression,J.expression));return[Q,J]});if(this.defIsLazy()){let H=this.bodyDef(W);return this.$.parse(H)}return this.$.parse(Z,{args:W})});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 n8}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:iX(this.bodyDef)})}get params(){return this.cacheGetter("params",this.paramDefs.map((Y)=>typeof Y==="string"?[Y,I.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 TJ=(Y,Z,X)=>`${Y} must be assignable to ${Z} (was ${X})`;var CJ=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 Q_ extends N1{serializedPredicate=T0(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=D4(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 bY={implementation:CJ,Node:Q_};var qJ=r({kind:"divisor",collapsibleKey:"rule",keys:{rule:{parse:(Y)=>Number.isInteger(Y)?Y:A(jJ(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/PJ(Y.rule,Z.rule))})},obviatesBasisDescription:!0});class z_ extends X4{traverseAllows=(Y)=>Y%this.rule===0;compiledCondition=`data % ${this.rule} === 0`;compiledNegation=`data % ${this.rule} !== 0`;impliedBasis=I.intrinsic.number.internal;expression=`% ${this.rule}`;reduceJsonSchema(Y){if(Y.type="integer",this.rule===1)return Y;return Y.multipleOf=this.rule,Y}}var yY={implementation:qJ,Node:z_};var jJ=(Y)=>`divisor must be an integer (was ${Y})`,PJ=(Y,Z)=>{let X,_=Y,G=Z;while(G!==0)X=G,G=_%G,_=X;return _};class M1 extends X4{boundOperandKind=fJ[this.kind];compiledActual=this.boundOperandKind==="value"?"data":this.boundOperandKind==="length"?"data.length":"data.valueOf()";comparator=hJ(this.kind,this.exclusive);numericLimit=this.rule.valueOf();expression=`${this.comparator} ${this.rule}`;compiledCondition=`${this.compiledActual} ${this.comparator} ${this.numericLimit}`;compiledNegation=`${this.compiledActual} ${SJ[this.comparator]} ${this.numericLimit}`;stringLimit=this.boundOperandKind==="date"?kJ(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 SJ={"<":">=","<=":">",">":"<=",">=":"<"},vJ={min:"max",minLength:"maxLength",after:"before"},r8={parse:(Y)=>Y||void 0},s8=(Y)=>(Z)=>{if(typeof Z==="number")return{rule:Z};let{exclusive:X,..._}=Z;return X?{..._,rule:Y==="minLength"?_.rule+1:_.rule-1}:_},t8=(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}:_},a8=(Y)=>typeof Y==="string"||typeof Y==="number"?new Date(Y):Y,xJ=(Y,Z)=>`${Y} bound must be a positive integer (was ${Z})`,_2=(Y)=>(Z)=>{if(!Number.isInteger(Z)||Z<0)A(xJ(Y,Z));return Z},fJ={min:"value",max:"value",minLength:"length",maxLength:"length",after:"date",before:"date"},hJ=(Y,Z)=>`${g0(Y,vJ)?">":"<"}${Z?"":"="}`,kJ=(Y)=>typeof Y==="string"?Y:new Date(Y).toLocaleString(),U_=(Y)=>`Bounded expression ${Y} must be exactly one of number, string, Array, or Date`;var bJ=r({kind:"after",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:a8,serialize:(Y)=>Y.toISOString()}},normalize:t8("after"),defaults:{description:(Y)=>`${Y.collapsibleLimitString} or later`,actual:S4},intersections:{after:(Y,Z)=>Y.isStricterThan(Z)?Y:Z}});class F_ extends M1{impliedBasis=I.intrinsic.Date.internal;collapsibleLimitString=S4(this.rule);traverseAllows=(Y)=>Y>=this.rule;reduceJsonSchema(Y,Z){return Z.fallback.date({code:"date",base:Y,after:this.rule})}}var gY={implementation:bJ,Node:F_};var yJ=r({kind:"before",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:a8,serialize:(Y)=>Y.toISOString()}},normalize:t8("before"),defaults:{description:(Y)=>`${Y.collapsibleLimitString} or earlier`,actual:S4},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 E_ extends M1{collapsibleLimitString=S4(this.rule);traverseAllows=(Y)=>Y<=this.rule;impliedBasis=I.intrinsic.Date.internal;reduceJsonSchema(Y,Z){return Z.fallback.date({code:"date",base:Y,before:this.rule})}}var pY={implementation:yJ,Node:E_};var gJ=r({kind:"exactLength",collapsibleKey:"rule",keys:{rule:{parse:_2("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 V_ extends X4{traverseAllows=(Y)=>Y.length===this.rule;compiledCondition=`data.length === ${this.rule}`;compiledNegation=`data.length !== ${this.rule}`;impliedBasis=I.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 w0.throwInternalOperandError("exactLength",Y)}}}var mY={implementation:gJ,Node:V_};var pJ=r({kind:"max",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{},exclusive:r8},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 O_ extends M1{impliedBasis=I.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 uY={implementation:pJ,Node:O_};var mJ=r({kind:"maxLength",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:_2("maxLength")}},reduce:(Y,Z)=>Y.rule===0?Z.node("exactLength",Y):void 0,normalize:s8("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 D_ extends M1{impliedBasis=I.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 w0.throwInternalOperandError("maxLength",Y)}}}var dY={implementation:mJ,Node:D_};var uJ=r({kind:"min",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{},exclusive:r8},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 L_ extends M1{impliedBasis=I.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 cY={implementation:uJ,Node:L_};var dJ=r({kind:"minLength",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:_2("minLength")}},reduce:(Y)=>Y.rule===0?I.intrinsic.unknown:void 0,normalize:s8("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 M_ extends M1{impliedBasis=I.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 w0.throwInternalOperandError("minLength",Y)}}}var lY={implementation:dJ,Node:M_};var A_={min:cY.implementation,max:uY.implementation,minLength:lY.implementation,maxLength:dY.implementation,exactLength:mY.implementation,after:gY.implementation,before:pY.implementation},R_={min:cY.Node,max:uY.Node,minLength:lY.Node,maxLength:dY.Node,exactLength:mY.Node,after:gY.Node,before:pY.Node};var cJ=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 w_ 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=I.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 oY={implementation:cJ,Node:w_};var c2=(Y,Z)=>{let X=lJ(Y);if(Z&&!Z.includes(X))return A(`Root of kind ${X} should be one of ${Z}`);return X},lJ=(Y)=>{if(y(Y,"root"))return Y.kind;if(typeof Y==="string")return Y[0]==="$"?"alias":(Y in H1)?"domain":"proto";if(typeof Y==="function")return"proto";if(typeof Y!=="object"||Y===null)return A(N_(Y));if("morphs"in Y)return"morph";if("branches"in Y||U0(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 o8)))return"intersection";if("proto"in Y)return"proto";if("domain"in Y)return"domain";return A(N_(Y))},N_=(Y)=>`${i(Y)} is not a valid type schema`,I_={},oJ=(Y)=>U0(Y)?Y.map((Z)=>Z.collapsibleJson):Y.collapsibleJson,Z1={};I.nodesByRegisteredId=Z1;var iY=(Y)=>{return I_[Y]??=0,`${Y}${++I_[Y]}`},nY=(Y)=>{let Z=G2[Y.kind],X=Z.applyConfig?.(Y.def,Y.$.resolvedConfig)??Y.def,_={},{meta:G,...$}=X,W=G===void 0?{}:typeof G==="string"?{description:G}:G,H=LY($).sort(([J],[z])=>a4(J)?a4(z)?e4(J)-e4(z):1:a4(z)?-1:J<z?-1:1).filter(([J,z])=>{if(J.startsWith("meta.")){let F=J.slice(5);return W[F]=z,!1}return!0});for(let J of H){let z=J[0],F=Z.keys[z];if(!F)return A(`Key ${z} is not valid on ${Y.kind} schema`);let O=F.parse?F.parse(J[1],Y):J[1];if(O!==L1&&(O!==void 0||F.preserveUndefined))_[z]=O}if(Z.reduce&&!Y.prereduced){let J=Z.reduce(_,Y.$);if(J){if(J instanceof S)return J.throw();return iJ(J,W)}}return rY({id:Y.id,kind:Y.kind,inner:_,meta:W,$:Y.$})},rY=({id:Y,kind:Z,inner:X,meta:_,$:G,ignoreCache:$})=>{let W=G2[Z],H=LY(X),Q=[],J={};for(let[x,h]of H){let g=W.keys[x],B=g.serialize??(g.child?oJ:w1);if(J[x]=B(h),g.child===!0){let K=h;if(U0(K))Q.push(...K);else Q.push(K)}else if(typeof g.child==="function")Q.push(...g.child(h))}if(W.finalizeInnerJson)J=W.finalizeInnerJson(J);let z={...J},F={};if(!l1(_))F=o(_,(x,h)=>[x,x==="examples"?h:w1(h)]),z.meta=e8(F,"description",!0);J=e8(J,W.collapsibleKey,!1);let O=JSON.stringify({kind:Z,...J});z=e8(z,W.collapsibleKey,!1);let L=e8(z,W.collapsibleKey,!0),w=JSON.stringify({kind:Z,...z});if(G.nodesByHash[w]&&!$)return G.nodesByHash[w];let R={id:Y,kind:Z,impl:W,inner:X,innerEntries:H,innerJson:J,innerHash:O,meta:_,metaJson:F,json:z,hash:w,collapsibleJson:L,children:Q};if(Z!=="intersection"){for(let x in X)if(x!=="in"&&x!=="out")R[x]=X[x]}let b=new B_[Z](R,G);return G.nodesByHash[w]=b},K_=(Y,Z)=>{if(Y.id===Z)return Y;if(D0(Z1[Z]))_0(`Unexpected attempt to overwrite node id ${Z}`);return rY({id:Z,kind:Y.kind,inner:Y.inner,meta:Y.meta,$:Y.$,ignoreCache:!0})},iJ=(Y,Z,X)=>{if(X&&D0(Z1[X]))_0(`Unexpected attempt to overwrite node id ${X}`);return rY({id:X??iY(Z.alias??Y.kind),kind:Y.kind,inner:Y.inner,meta:Z,$:Y.$})},e8=(Y,Z,X)=>{let _=Object.keys(Y);if(_.length===1&&_[0]===Z){let G=Y[Z];if(X)return G;if(W1(G,"object")&&(Object.keys(G).length===1||Array.isArray(G)))return G}return Y};var l2=(Y,Z,X)=>{if(Y.key!==Z.key)return null;let _=Y.key,G=L0(Y.value,Z.value,X),$=Y.required||Z.required?"required":"optional";if(G instanceof S)if($==="optional")G=I.intrinsic.never.internal;else return G.withPrefixKey(Y.key,Y.required&&Z.required?"required":"optional");if($==="required")return X.$.node("required",{key:_,value:G});let W=Y.hasDefault()?Z.hasDefault()?Y.default===Z.default?Y.default:A(sY(Y.default,Z.default)):Y.default:Z.hasDefault()?Z.default:L1;return X.$.node("optional",{key:_,value:G,default:W})};class o2 extends N1{required=this.kind==="required";optional=this.kind==="optional";impliedBasis=I.intrinsic.object.internal;serializedKey=Z4(this.key);compiledKey=typeof this.key==="string"?this.key:this.serializedKey;flatRefs=Z0(this.value.flatRefs.map((Y)=>f1([this.key,...Y.path],Y.node)),f1([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 Q1(this.key,()=>this.value.traverseAllows(Y[this.key],Z),Z);return this.optional};traverseApply=(Y,Z)=>{if(this.key in Y)Q1(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 sY=(Y,Z)=>`Invalid intersection of default values ${i(Y)} & ${i(Z)}`;var nJ=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(u.undefined)},{prereduced:!0})}},defaults:{description:(Y)=>`${Y.compiledKey}?: ${Y.value.description}`},intersections:{optional:l2}});class T_ extends o2{constructor(...Y){super(...Y);if("default"in this.inner)n2(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} = ${i(this.inner.default)}`:`${this.compiledKey}?: ${this.value.expression}`;defaultValueMorph=sJ(this);defaultValueMorphRef=this.defaultValueMorph&&T0(this.defaultValueMorph)}var i2={implementation:nJ,Node:T_},rJ={},sJ=(Y)=>{if(!Y.hasDefault())return;let Z=`{${Y.compiledKey}: ${Y.value.id} = ${w1(Y.default)}}`;return rJ[Z]??=tY(Y.key,Y.value,Y.default)},tY=(Y,Z,X)=>{if(typeof X==="function")return Z.includesTransform?(G,$)=>{return Q1(Y,()=>Z(G[Y]=X(),$),$),G}:(G)=>{return G[Y]=X(),G};let _=Z.includesTransform?Z.assert(X):X;return W1(_,"object")?(G,$)=>{return Q1(Y,()=>Z(G[Y]=X,$),$),G}:(G)=>{return G[Y]=_,G}},n2=(Y,Z,X)=>{let _=E4(Z);if(W1(Z,"object")&&!_)A(tJ(X));let G=Y.in(_?Z():Z);if(G instanceof J1){if(X===null)A(`Default ${G.summary}`);let $=G.transform((W)=>W.transform((H)=>({...H,prefixPath:[X]})));A(`Default for ${$.summary}`)}return Z},tJ=(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 I1 extends u2{constructor(Y,Z){super(Y,Z);Object.defineProperty(this,Y1,{value:"root",enumerable:!1})}get internal(){return this}get "~standard"(){return{vendor:"arktype",version:1,validate:(Y)=>{let Z=this(Y);if(Z instanceof J1)return Z;return{value:Z}},toJSONSchema:(Y)=>{if(Y.target&&Y.target!=="draft-2020-12")return A(`JSONSchema target '${Y.target}' is not supported (must be "draft-2020-12")`);if(Y.io==="input")return this.in.toJsonSchema();return this.out.toJsonSchema()}}}as(){return this}brand(Y){if(Y==="")return A(aJ);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=SY(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 z1(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(),I.intrinsic.unknown.internal);if(Y.branches.length===0)A(hY(`keyof ${this.expression}`));return this._keyof=this.$.finalize(Y)}get props(){if(this.branches.length!==1)return A(eJ(this.expression));return[...this.applyStructuralOperation("props",[])[0]]}merge(Y){let Z=this.$.parseDefinition(Y);return this.$.schema(Z.distribute((X)=>this.applyStructuralOperation("merge",[C_(X)??A(q_("merge",X.expression))])))}applyStructuralOperation(Y,Z){return this.distribute((X)=>{if(X.equals(I.intrinsic.object)&&Y!=="merge")return X;let _=C_(X);if(!_)A(q_(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 n2(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,$)=>{try{return _(G,$)}catch(W){return $.error({code:"predicate",predicate:_,actual:`aborted due to error:
25
25
  ${W}
26
- `})}}),this);return this.$.finalize(Y)}pipe=Object.assign(this._pipe.bind(this),{try:this.tryPipe.bind(this)});to(Z){return this.$.finalize(this.toNode(this.$.parseDefinition(Z)))}toNode(Z){let Y=o2(this,Z,this.$);if(Y instanceof S)return Y.throw();return Y}rawPipeOnce(Z){if(y(Z,"root"))return this.toNode(Z);return this.distribute((Y)=>Y.hasKind("morph")?this.$.node("morph",{in:Y.inner.in,morphs:[...Y.morphs,Z]}):this.$.node("morph",{in:Y,morphs:[Z]}),this.$.parseSchema)}narrow(Z){return this.constrainOut("predicate",Z)}constrain(Z,Y){return this._constrain("root",Z,Y)}constrainIn(Z,Y){return this._constrain("in",Z,Y)}constrainOut(Z,Y){return this._constrain("out",Z,Y)}_constrain(Z,Y,X){let G=this.$.node(Y,X);if(G.isRoot())return G.isUnknown()?this:G0(`Unexpected constraint node ${G}`);let _=Z==="root"?this:this[Z];if(_.hasKind("morph")||G.impliedBasis&&!_.extends(G.impliedBasis))return DG(Y,G.impliedBasis,this);let $=this.$.node("intersection",{[G.kind]:G}),W=Z==="out"?o2(this,$,this.$):U1(this,$,this.$);if(W instanceof S)W.throw();return this.$.finalize(W)}onUndeclaredKey(Z){let Y=typeof Z==="string"?Z:Z.rule,X=typeof Z==="string"?!1:Z.deep;return this.$.finalize(this.transform((G,_)=>G==="structure"?Y==="ignore"?fX(_,{undeclared:1}):{..._,undeclared:Y}:_,X?void 0:{shouldTransform:(G)=>!a1(t4,G.kind)}))}hasEqualMorphs(Z){if(!this.includesTransform&&!Z.includesTransform)return!0;if(!e1(this.shallowMorphs,Z.shallowMorphs))return!1;if(!e1(this.flatMorphs,Z.flatMorphs,{isEqual:(Y,X)=>Y.propString===X.propString&&(Y.node.hasKind("morph")&&X.node.hasKind("morph")?Y.node.hasEqualMorphs(X.node):Y.node.hasKind("intersection")&&X.node.hasKind("intersection")?Y.node.structure?.structuralMorphRef===X.node.structure?.structuralMorphRef:!1)}))return!1;return!0}onDeepUndeclaredKey(Z){return this.onUndeclaredKey({rule:Z,deep:!0})}filter(Z){return this.constrainIn("predicate",Z)}divisibleBy(Z){return this.constrain("divisor",Z)}matching(Z){return this.constrain("pattern",Z)}atLeast(Z){return this.constrain("min",Z)}atMost(Z){return this.constrain("max",Z)}moreThan(Z){return this.constrain("min",H2(Z))}lessThan(Z){return this.constrain("max",H2(Z))}atLeastLength(Z){return this.constrain("minLength",Z)}atMostLength(Z){return this.constrain("maxLength",Z)}moreThanLength(Z){return this.constrain("minLength",H2(Z))}lessThanLength(Z){return this.constrain("maxLength",H2(Z))}exactlyLength(Z){return this.constrain("exactLength",Z)}atOrAfter(Z){return this.constrain("after",Z)}atOrBefore(Z){return this.constrain("before",Z)}laterThan(Z){return this.constrain("after",H2(Z))}earlierThan(Z){return this.constrain("before",H2(Z))}}var QQ="Expected a non-empty brand name after #",H2=(Z)=>typeof Z==="object"&&!(Z instanceof Date)?{...Z,exclusive:!0}:{rule:Z,exclusive:!0},e2=(Z,Y)=>y(Y,"root")?y(Z,"root")?Z.extends(Y):Y.allows(Z):y(Z,"root")?Z.hasUnit(Y):Y===Z,kG=(Z)=>{if(Z.hasKind("morph"))return null;if(Z.hasKind("intersection"))return Z.inner.structure??(Z.basis?.domain==="object"?Z.$.bindReference(I.intrinsic.emptyStructure):null);if(Z.isBasis()&&Z.domain==="object")return Z.$.bindReference(I.intrinsic.emptyStructure);return null},zQ=(Z)=>`Props cannot be extracted from a union. Use .distribute to extract props from each branch instead. Received:
27
- ${Z}`,bG=(Z,Y)=>`${Z} operand must be an object (was ${Y})`;var i1=(Z,Y)=>i(o8(Z),(X,G)=>[G,Y]);var UQ=(Z)=>typeof Z==="string"?{reference:Z}:Z,yG=(Z)=>Z instanceof S?I.intrinsic.never.internal:Z,FQ=r({kind:"alias",hasAssociatedError:!1,collapsibleKey:"reference",keys:{reference:{serialize:(Z)=>Z.startsWith("$")?Z:`$ark.${Z}`},resolve:{}},normalize:UQ,defaults:{description:(Z)=>Z.reference},intersections:{alias:(Z,Y,X)=>X.$.lazilyResolve(()=>yG(V0(Z.resolution,Y.resolution,X)),`${Z.reference}${X.pipe?"=>":"&"}${Y.reference}`),...i1("alias",(Z,Y,X)=>{if(Y.isUnknown())return Z;if(Y.isNever())return Y;if(Y.isBasis()&&!Y.overlaps(I.intrinsic.object))return S.init("assignability",I.intrinsic.object,Y);return X.$.lazilyResolve(()=>yG(V0(Z.resolution,Y,X)),`${Z.reference}${X.pipe?"=>":"&"}${Y.id}`)})}});class gG extends C1{expression=this.reference;structure=void 0;get resolution(){let Z=this._resolve();return X1[this.id]=Z}_resolve(){if(this.resolve)return this.resolve();if(this.reference[0]==="$")return this.$.resolveRoot(this.reference.slice(1));let Z=this.reference,Y=X1[Z],X=[];while(y(Y,"context")){if(X.includes(Y.id))return A(EQ(Y.id,X));X.push(Y.id),Y=X1[Y.id]}if(!y(Y,"root"))return G0(`Unexpected resolution for reference ${this.reference}
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=d2(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 W_(Z,_.impliedBasis,this);let $=this.$.node("intersection",{[_.kind]:_}),W=Y==="out"?d2(this,$,this.$):z1(this,$,this.$);if(W instanceof S)W.throw();return this.$.finalize(W)}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"?BX(G,{undeclared:1}):{...G,undeclared:Z}:G,X?void 0:{shouldTransform:(_)=>!s1(s4,_.kind)}))}hasEqualMorphs(Y){if(!this.includesTransform&&!Y.includesTransform)return!0;if(!a1(this.shallowMorphs,Y.shallowMorphs))return!1;if(!a1(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",$2(Y))}lessThan(Y){return this.constrain("max",$2(Y))}atLeastLength(Y){return this.constrain("minLength",Y)}atMostLength(Y){return this.constrain("maxLength",Y)}moreThanLength(Y){return this.constrain("minLength",$2(Y))}lessThanLength(Y){return this.constrain("maxLength",$2(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",$2(Y))}earlierThan(Y){return this.constrain("before",$2(Y))}}var aJ="Expected a non-empty brand name after #",$2=(Y)=>typeof Y==="object"&&!(Y instanceof Date)?{...Y,exclusive:!0}:{rule:Y,exclusive:!0},r2=(Y,Z)=>y(Z,"root")?y(Y,"root")?Y.extends(Z):Z.allows(Y):y(Y,"root")?Y.hasUnit(Z):Z===Y,C_=(Y)=>{if(Y.hasKind("morph"))return null;if(Y.hasKind("intersection"))return Y.inner.structure??(Y.basis?.domain==="object"?Y.$.bindReference(I.intrinsic.emptyStructure):null);if(Y.isBasis()&&Y.domain==="object")return Y.$.bindReference(I.intrinsic.emptyStructure);return null},eJ=(Y)=>`Props cannot be extracted from a union. Use .distribute to extract props from each branch instead. Received:
27
+ ${Y}`,q_=(Y,Z)=>`${Y} operand must be an object (was ${Z})`;var o1=(Y,Z)=>o(i8(Y),(X,_)=>[_,Z]);var YQ=(Y)=>typeof Y==="string"?{reference:Y}:Y,j_=(Y)=>Y instanceof S?I.intrinsic.never.internal:Y,ZQ=r({kind:"alias",hasAssociatedError:!1,collapsibleKey:"reference",keys:{reference:{serialize:(Y)=>Y.startsWith("$")?Y:`$ark.${Y}`},resolve:{}},normalize:YQ,defaults:{description:(Y)=>Y.reference},intersections:{alias:(Y,Z,X)=>X.$.lazilyResolve(()=>j_(L0(Y.resolution,Z.resolution,X)),`${Y.reference}${X.pipe?"=>":"&"}${Z.reference}`),...o1("alias",(Y,Z,X)=>{if(Z.isUnknown())return Y;if(Z.isNever())return Z;if(Z.isBasis()&&!Z.overlaps(I.intrinsic.object))return S.init("assignability",I.intrinsic.object,Z);return X.$.lazilyResolve(()=>j_(L0(Y.resolution,Z,X)),`${Y.reference}${X.pipe?"=>":"&"}${Z.id}`)})}});class P_ extends I1{expression=this.reference;structure=void 0;get resolution(){let Y=this._resolve();return Z1[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=Z1[Y],X=[];while(y(Z,"context")){if(X.includes(Z.id))return A(XQ(Z.id,X));X.push(Z.id),Z=Z1[Z.id]}if(!y(Z,"root"))return _0(`Unexpected resolution for reference ${this.reference}
28
28
  Seen: [${X.join("->")}]
29
- Resolution: ${o(Y)}`);return Y}get resolutionId(){if(this.reference.includes("&")||this.reference.includes("=>"))return this.resolution.id;if(this.reference[0]!=="$")return this.reference;let Z=this.reference.slice(1),Y=this.$.resolutions[Z];if(typeof Y==="string")return Y;if(y(Y,"root"))return Y.id;return G0(`Unexpected resolution for reference ${this.reference}: ${o(Y)}`)}get defaultShortDescription(){return J1.object}innerToJsonSchema(Z){return this.resolution.toJsonSchemaRecurse(Z)}traverseAllows=(Z,Y)=>{let X=Y.seen[this.reference];if(X?.includes(Z))return!0;return Y.seen[this.reference]=Y0(X,Z),this.resolution.traverseAllows(Z,Y)};traverseApply=(Z,Y)=>{let X=Y.seen[this.reference];if(X?.includes(Z))return;Y.seen[this.reference]=Y0(X,Z),this.resolution.traverseApply(Z,Y)};compile(Z){let Y=this.resolutionId;Z.if(`ctx.seen.${Y} && ctx.seen.${Y}.includes(data)`,()=>Z.return(!0)),Z.if(`!ctx.seen.${Y}`,()=>Z.line(`ctx.seen.${Y} = []`)),Z.line(`ctx.seen.${Y}.push(data)`),Z.return(Z.invoke(Y))}}var EQ=(Z,Y)=>`Alias '${Z}' has a shallow resolution cycle: ${[...Y,Z].join("->")}`,Z8={implementation:FQ,Node:gG};class h4 extends C1{traverseApply=(Z,Y)=>{if(!this.traverseAllows(Z,Y))Y.errorFromNodeContext(this.errorContext)};get errorContext(){return{code:this.kind,description:this.description,meta:this.meta,...this.inner}}get compiledErrorContext(){return V4(this.errorContext)}compile(Z){if(Z.traversalKind==="Allows")Z.return(this.compiledCondition);else Z.if(this.compiledNegation,()=>Z.line(`${Z.ctx}.errorFromNodeContext(${this.compiledErrorContext})`))}}var LQ=r({kind:"domain",hasAssociatedError:!0,collapsibleKey:"domain",keys:{domain:{},numberAllowsNaN:{}},normalize:(Z)=>typeof Z==="string"?{domain:Z}:s4(Z,"numberAllowsNaN")&&Z.domain!=="number"?A(Z6.writeBadAllowNanMessage(Z.domain)):Z,applyConfig:(Z,Y)=>Z.numberAllowsNaN===void 0&&Z.domain==="number"&&Y.numberAllowsNaN?{...Z,numberAllowsNaN:!0}:Z,defaults:{description:(Z)=>J1[Z.domain],actual:(Z)=>Number.isNaN(Z)?"NaN":J1[y0(Z)]},intersections:{domain:(Z,Y)=>Z.domain==="number"&&Y.domain==="number"?Z.numberAllowsNaN?Y:Z:S.init("domain",Z,Y)}});class pG extends h4{requiresNaNCheck=this.domain==="number"&&!this.numberAllowsNaN;traverseAllows=this.requiresNaNCheck?(Z)=>typeof Z==="number"&&!Number.isNaN(Z):(Z)=>y0(Z)===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 J1[this.domain]}innerToJsonSchema(Z){if(this.domain==="bigint"||this.domain==="symbol")return Z.fallback.domain({code:"domain",base:{},domain:this.domain});return{type:this.domain}}}var Z6={implementation:LQ,Node:pG,writeBadAllowNanMessage:(Z)=>`numberAllowsNaN may only be specified with domain "number" (was ${Z})`};var DQ=r({kind:"intersection",hasAssociatedError:!0,normalize:(Z)=>{if(O0(Z))return Z;let{structure:Y,...X}=Z,G=!!Y,_=Y??{},$=i(X,(W,H)=>{if(g0(W,HG)){if(G)A(`Flattened structure key ${W} cannot be specified alongside a root 'structure' key.`);return _[W]=H,[]}return[W,H]});if(y(_,"constraint")||!l1(_))$.structure=_;return $},finalizeInnerJson:({structure:Z,...Y})=>H1(Z,"object")?{...Z,...Y}:Y,keys:{domain:{child:!0,parse:(Z,Y)=>Y.$.node("domain",Z)},proto:{child:!0,parse:(Z,Y)=>Y.$.node("proto",Z)},structure:{child:!0,parse:(Z,Y)=>Y.$.node("structure",Z),serialize:(Z)=>{if(!Z.sequence?.minLength)return Z.collapsibleJson;let{sequence:Y,...X}=Z.collapsibleJson,{minVariadicLength:G,..._}=Y,$=_.variadic&&Object.keys(_).length===1?_.variadic:_;return{...X,sequence:$}}},divisor:{child:!0,parse:s0("divisor")},max:{child:!0,parse:s0("max")},min:{child:!0,parse:s0("min")},maxLength:{child:!0,parse:s0("maxLength")},minLength:{child:!0,parse:s0("minLength")},exactLength:{child:!0,parse:s0("exactLength")},before:{child:!0,parse:s0("before")},after:{child:!0,parse:s0("after")},pattern:{child:!0,parse:s0("pattern")},predicate:{child:!0,parse:s0("predicate")}},reduce:(Z,Y)=>mG({},Z,{$:Y,invert:!1,pipe:!1}),defaults:{description:(Z)=>{if(Z.children.length===0)return"unknown";if(Z.structure)return Z.structure.description;let Y=[];if(Z.basis&&!Z.refinements.some((X)=>X.impl.obviatesBasisDescription))Y.push(Z.basis.description);if(Z.refinements.length){let X=Z.refinements.toSorted((G,_)=>G.kind==="min"&&_.kind==="max"?-1:0).map((G)=>G.description);Y.push(...X)}if(Z.inner.predicate)Y.push(...Z.inner.predicate.map((X)=>X.description));return Y.join(" and ")},expected:(Z)=>` \u25E6 ${Z.errors.map((Y)=>Y.expected).join(`
30
- \u25E6 `)}`,problem:(Z)=>`(${Z.actual}) must be...
31
- ${Z.expected}`},intersections:{intersection:(Z,Y,X)=>mG(Z.inner,Y.inner,X),...i1("intersection",(Z,Y,X)=>{if(Z.children.length===0)return Y;let{domain:G,proto:_,...$}=Z.inner,W=_??G,H=W?V0(W,Y,X):Y;return H instanceof S?H:Z?.basis?.equals(H)?Z:Z.$.node("intersection",{...$,[H.kind]:H},{prereduced:!0})})}});class uG extends C1{basis=this.inner.domain??this.inner.proto??null;refinements=this.children.filter((Z)=>Z.isRefinement());structure=this.inner.structure;expression=OQ(this);get shallowMorphs(){return this.inner.structure?.structuralMorph?[this.inner.structure.structuralMorph]:[]}get defaultShortDescription(){return this.basis?.defaultShortDescription??"present"}innerToJsonSchema(Z){return this.children.reduce((Y,X)=>X.isBasis()?X.toJsonSchemaRecurse(Z):X.reduceJsonSchema(Y,Z),{})}traverseAllows=(Z,Y)=>this.children.every((X)=>X.traverseAllows(Z,Y));traverseApply=(Z,Y)=>{let X=Y.currentErrorCount;if(this.basis){if(this.basis.traverseApply(Z,Y),Y.currentErrorCount>X)return}if(this.refinements.length){for(let G=0;G<this.refinements.length-1;G++)if(this.refinements[G].traverseApply(Z,Y),Y.failFast&&Y.currentErrorCount>X)return;if(this.refinements.at(-1).traverseApply(Z,Y),Y.currentErrorCount>X)return}if(this.structure){if(this.structure.traverseApply(Z,Y),Y.currentErrorCount>X)return}if(this.inner.predicate){for(let G=0;G<this.inner.predicate.length-1;G++)if(this.inner.predicate[G].traverseApply(Z,Y),Y.failFast&&Y.currentErrorCount>X)return;this.inner.predicate.at(-1).traverseApply(Z,Y)}};compile(Z){if(Z.traversalKind==="Allows"){for(let Y of this.children)Z.check(Y);Z.return(!0);return}if(Z.initializeErrorCount(),this.basis){if(Z.check(this.basis),this.children.length>1)Z.returnIfFail()}if(this.refinements.length){for(let Y=0;Y<this.refinements.length-1;Y++)Z.check(this.refinements[Y]),Z.returnIfFailFast();if(Z.check(this.refinements.at(-1)),this.structure||this.inner.predicate)Z.returnIfFail()}if(this.structure){if(Z.check(this.structure),this.inner.predicate)Z.returnIfFail()}if(this.inner.predicate){for(let Y=0;Y<this.inner.predicate.length-1;Y++)Z.check(this.inner.predicate[Y]),Z.returnIfFail();Z.check(this.inner.predicate.at(-1))}}}var $5={implementation:DQ,Node:uG},OQ=(Z)=>{let Y=Z.structure?.expression||`${Z.basis&&!Z.refinements.some((X)=>X.impl.obviatesBasisExpression)?Z.basis.nestableExpression+" ":""}${Z.refinements.map((X)=>X.expression).join(" & ")}`||"unknown";if(Y==="Array == 0")Y="[]";return Y},mG=(Z,Y,X)=>{let G={},_=Z.proto??Z.domain,$=Y.proto??Y.domain,W=_?$?V0(_,$,X):_:$;if(W instanceof S)return W;if(W)G[W.kind]=W;return G2({kind:"intersection",baseInner:G,l:_2(Z),r:_2(Y),roots:[],ctx:X})};var VQ=r({kind:"morph",hasAssociatedError:!1,keys:{in:{child:!0,parse:(Z,Y)=>Y.$.parseSchema(Z)},morphs:{parse:E4,serialize:(Z)=>Z.map((Y)=>y(Y,"root")?Y.json:C0(Y))},declaredIn:{child:!1,serialize:(Z)=>Z.json},declaredOut:{child:!1,serialize:(Z)=>Z.json}},normalize:(Z)=>Z,defaults:{description:(Z)=>`a morph from ${Z.in.description} to ${Z.out?.description??"unknown"}`},intersections:{morph:(Z,Y,X)=>{if(!Z.hasEqualMorphs(Y))return A(MQ(Z.expression,Y.expression));let G=V0(Z.in,Y.in,X);if(G instanceof S)return G;let _={morphs:Z.morphs};if(Z.declaredIn||Y.declaredIn){let $=V0(Z.in,Y.in,X);if($ instanceof S)return $.throw();else _.declaredIn=$}if(Z.declaredOut||Y.declaredOut){let $=V0(Z.out,Y.out,X);if($ instanceof S)return $.throw();else _.declaredOut=$}return G.distribute(($)=>X.$.node("morph",{..._,in:$}),X.$.parseSchema)},...i1("morph",(Z,Y,X)=>{let G=Z.inner.in?V0(Z.inner.in,Y,X):Y;return G instanceof S?G:G.equals(Z.inner.in)?Z:X.$.node("morph",{...Z.inner,in:G})})}});class dG extends C1{serializedMorphs=this.morphs.map(C0);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??I.intrinsic.unknown.internal}get out(){return this.declaredOut??this.introspectableOut??I.intrinsic.unknown.internal}declareIn(Z){return this.$.node("morph",{...this.inner,declaredIn:Z})}declareOut(Z){return this.$.node("morph",{...this.inner,declaredOut:Z})}expression=`(In: ${this.in.expression}) => ${this.lastMorphIfNode?"To":"Out"}<${this.out.expression}>`;get defaultShortDescription(){return this.in.meta.description??this.in.defaultShortDescription}innerToJsonSchema(Z){return Z.fallback.morph({code:"morph",base:this.in.toJsonSchemaRecurse(Z),out:this.introspectableOut?.toJsonSchemaRecurse(Z)??null})}compile(Z){if(Z.traversalKind==="Allows"){if(!this.introspectableIn)return;Z.return(Z.invoke(this.introspectableIn));return}if(this.introspectableIn)Z.line(Z.invoke(this.introspectableIn));Z.line(`ctx.queueMorphs(${this.compiledMorphs})`)}traverseAllows=(Z,Y)=>!this.introspectableIn||this.introspectableIn.traverseAllows(Z,Y);traverseApply=(Z,Y)=>{if(this.introspectableIn)this.introspectableIn.traverseApply(Z,Y);Y.queueMorphs(this.morphs)};hasEqualMorphs(Z){return e1(this.morphs,Z.morphs,{isEqual:(Y,X)=>Y===X||y(Y,"root")&&y(X,"root")&&Y.equals(X)})}}var W5={implementation:VQ,Node:dG},MQ=(Z,Y)=>`The intersection of distinct morphs at a single path is indeterminate:
32
- Left: ${Z}
33
- Right: ${Y}`;var AQ=r({kind:"proto",hasAssociatedError:!0,collapsibleKey:"proto",keys:{proto:{serialize:(Z)=>k2(Z)??B1(Z)},dateAllowsInvalid:{}},normalize:(Z)=>{let Y=typeof Z==="string"?{proto:v4[Z]}:typeof Z==="function"?O0(Z)?Z:{proto:Z}:typeof Z.proto==="string"?{...Z,proto:v4[Z.proto]}:Z;if(typeof Y.proto!=="function")A(Y8.writeInvalidSchemaMessage(Y.proto));if(s4(Y,"dateAllowsInvalid")&&Y.proto!==Date)A(Y8.writeBadInvalidDateMessage(Y.proto));return Y},applyConfig:(Z,Y)=>{if(Z.dateAllowsInvalid===void 0&&Z.proto===Date&&Y.dateAllowsInvalid)return{...Z,dateAllowsInvalid:!0};return Z},defaults:{description:(Z)=>Z.builtinName?yX[Z.builtinName]:`an instance of ${Z.proto.name}`,actual:(Z)=>Z instanceof Date&&Z.toString()==="Invalid Date"?"an invalid Date":h2(Z)},intersections:{proto:(Z,Y)=>Z.proto===Date&&Y.proto===Date?Z.dateAllowsInvalid?Y:Z:jZ(Z.proto,Y.proto)?Z:jZ(Y.proto,Z.proto)?Y:S.init("proto",Z,Y),domain:(Z,Y)=>Y.domain==="object"?Z:S.init("domain",I.intrinsic.object.internal,Y)}});class cG extends h4{builtinName=k2(this.proto);serializedConstructor=this.json.proto;requiresInvalidDateCheck=this.proto===Date&&!this.dateAllowsInvalid;traverseAllows=this.requiresInvalidDateCheck?(Z)=>Z instanceof Date&&Z.toString()!=="Invalid Date":(Z)=>Z instanceof this.proto;compiledCondition=`data instanceof ${this.serializedConstructor}${this.requiresInvalidDateCheck?' && data.toString() !== "Invalid Date"':""}`;compiledNegation=`!(${this.compiledCondition})`;innerToJsonSchema(Z){switch(this.builtinName){case"Array":return{type:"array"};case"Date":return Z.fallback.date?.({code:"date",base:{}})??Z.fallback.proto({code:"proto",base:{},proto:this.proto});default:return Z.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 Y8={implementation:AQ,Node:cG,writeBadInvalidDateMessage:(Z)=>`dateAllowsInvalid may only be specified with constructor Date (was ${Z.name})`,writeInvalidSchemaMessage:(Z)=>`instanceOf operand must be a function (was ${y0(Z)})`};var RQ=r({kind:"union",hasAssociatedError:!0,collapsibleKey:"branches",keys:{ordered:{},branches:{child:!0,parse:(Z,Y)=>{let X=[];for(let G of Z){let _=y(G,"root")?G.branches:Y.$.parseSchema(G).branches;for(let $ of _)if($.hasKind("morph")){let W=X.findIndex((H)=>H.hasKind("morph")&&H.hasEqualMorphs($));if(W===-1)X.push($);else{let H=X[W];X[W]=Y.$.node("morph",{...H.inner,in:H.in.rawOr($.in)})}}else X.push($)}if(!Y.def.ordered)X.sort((G,_)=>G.hash<_.hash?-1:1);return X}}},normalize:(Z)=>U0(Z)?{branches:Z}:Z,reduce:(Z,Y)=>{let X=PQ(Z);if(X.length===1)return X[0];if(X.length===Z.branches.length)return;return Y.node("union",{...Z,branches:X},{prereduced:!0})},defaults:{description:(Z)=>Z.distribute((Y)=>Y.description,J2),expected:(Z)=>{let Y=PX(Z.errors,"propString"),X=Object.entries(Y).map(([G,_])=>{let $=[];for(let Q of _)c1($,Q.expected);let W=J2($),H=_.every((Q)=>Q.actual===_[0].actual)?_[0].actual:o(_[0].data);return`${G&&`${G} `}must be ${W}${H&&` (was ${H})`}`});return J2(X)},problem:(Z)=>Z.expected,message:(Z)=>Z.problem},intersections:{union:(Z,Y,X)=>{if(Z.isNever!==Y.isNever)return S.init("presence",Z,Y);let G;if(Z.ordered){if(Y.ordered)A(vQ(Z.expression,Y.expression));if(G=H5(Y.branches,Z.branches,X),G instanceof S)G.invert()}else G=H5(Z.branches,Y.branches,X);if(G instanceof S)return G;return X.$.parseSchema(Z.ordered||Y.ordered?{branches:G,ordered:!0}:{branches:G})},...i1("union",(Z,Y,X)=>{let G=H5(Z.branches,[Y],X);if(G instanceof S)return G;if(G.length===1)return G[0];return X.$.parseSchema(Z.ordered?{branches:G,ordered:!0}:{branches:G})})}});class oG extends C1{isBoolean=this.branches.length===2&&this.branches[0].hasUnit(!1)&&this.branches[1].hasUnit(!0);get branchGroups(){let Z=[],Y=-1;for(let X of this.branches){if(X.hasKind("unit")&&X.domain==="boolean"){if(Y===-1)Y=Z.length,Z.push(X);else Z[Y]=I.intrinsic.boolean;continue}Z.push(X)}return Z}unitBranches=this.branches.filter((Z)=>Z.in.hasKind("unit"));discriminant=this.discriminate();discriminantJson=this.discriminant?TQ(this.discriminant):null;expression=this.distribute((Z)=>Z.nestableExpression,jQ);createBranchedOptimisticRootApply(){return(Z,Y)=>{let X=this.traverseOptimistic(Z);if(X!==V1)return X;let G=new k1(Z,this.$.resolvedConfig);return this.traverseApply(Z,G),G.finalize(Y)}}get shallowMorphs(){return this.branches.reduce((Z,Y)=>c1(Z,Y.shallowMorphs),[])}get defaultShortDescription(){return this.distribute((Z)=>Z.defaultShortDescription,J2)}innerToJsonSchema(Z){if(this.branchGroups.length===1&&this.branchGroups[0].equals(I.intrinsic.boolean))return{type:"boolean"};let Y=this.branchGroups.map((X)=>X.toJsonSchemaRecurse(Z));if(Y.every((X)=>Object.keys(X).length===1&&s4(X,"const")))return{enum:Y.map((X)=>X.const)};return{anyOf:Y}}traverseAllows=(Z,Y)=>this.branches.some((X)=>X.traverseAllows(Z,Y));traverseApply=(Z,Y)=>{let X=[];for(let G=0;G<this.branches.length;G++){if(Y.pushBranch(),this.branches[G].traverseApply(Z,Y),!Y.hasError()){if(this.branches[G].includesTransform)return Y.queuedMorphs.push(...Y.popBranch().queuedMorphs);return Y.popBranch()}X.push(Y.popBranch().error)}Y.errorFromNodeContext({code:"union",errors:X,meta:this.meta})};traverseOptimistic=(Z)=>{for(let Y=0;Y<this.branches.length;Y++){let X=this.branches[Y];if(X.traverseAllows(Z)){if(X.contextFreeMorph)return X.contextFreeMorph(Z);return Z}}return V1};compile(Z){if(!this.discriminant||this.unitBranches.length===this.branches.length&&this.branches.length===2)return this.compileIndiscriminable(Z);let Y=this.discriminant.optionallyChainedPropString;if(this.discriminant.kind==="domain")Y=`typeof ${Y} === "object" ? ${Y} === null ? "null" : "object" : typeof ${Y} === "function" ? "object" : typeof ${Y}`;let X=this.discriminant.cases,G=Object.keys(X),{optimistic:_}=Z;if(Z.optimistic=!1,Z.block(`switch(${Y})`,()=>{for(let J in X){let z=X[J],U=J==="default"?J:`case ${J}`;Z.line(`${U}: return ${z===!0?_?Z.data:z:_?`${Z.invoke(z)} ? ${z.contextFreeMorph?`${C0(z.contextFreeMorph)}(${Z.data})`:Z.data} : "${V1}"`:Z.invoke(z)}`)}return Z}),Z.traversalKind==="Allows"){Z.return(_?`"${V1}"`:!1);return}let $=J2(this.discriminant.kind==="domain"?G.map((J)=>{let z=J.slice(1,-1);return z==="function"?J1.object:J1[z]}):G),W=this.discriminant.path.map((J)=>typeof J==="symbol"?C0(J):JSON.stringify(J)),H=JSON.stringify($),Q=this.discriminant.kind==="domain"?`${KQ}[${Y}]`:`${CQ}(${Y})`;Z.line(`ctx.errorFromNodeContext({
29
+ Resolution: ${i(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}: ${i(Z)}`)}get defaultShortDescription(){return H1.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 XQ=(Y,Z)=>`Alias '${Y}' has a shallow resolution cycle: ${[...Z,Y].join("->")}`,s2={implementation:ZQ,Node:P_};class v4 extends I1{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 D4(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 _Q=r({kind:"domain",hasAssociatedError:!0,collapsibleKey:"domain",keys:{domain:{},numberAllowsNaN:{}},normalize:(Y)=>typeof Y==="string"?{domain:Y}:n4(Y,"numberAllowsNaN")&&Y.domain!=="number"?A(Y6.writeBadAllowNanMessage(Y.domain)):Y,applyConfig:(Y,Z)=>Y.numberAllowsNaN===void 0&&Y.domain==="number"&&Z.numberAllowsNaN?{...Y,numberAllowsNaN:!0}:Y,defaults:{description:(Y)=>H1[Y.domain],actual:(Y)=>Number.isNaN(Y)?"NaN":H1[y0(Y)]},intersections:{domain:(Y,Z)=>Y.domain==="number"&&Z.domain==="number"?Y.numberAllowsNaN?Z:Y:S.init("domain",Y,Z)}});class S_ extends v4{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 H1[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 Y6={implementation:_Q,Node:S_,writeBadAllowNanMessage:(Y)=>`numberAllowsNaN may only be specified with domain "number" (was ${Y})`};var GQ=r({kind:"intersection",hasAssociatedError:!0,normalize:(Y)=>{if(D0(Y))return Y;let{structure:Z,...X}=Y,_=!!Z,G=Z??{},$=o(X,(W,H)=>{if(g0(W,aX)){if(_)A(`Flattened structure key ${W} cannot be specified alongside a root 'structure' key.`);return G[W]=H,[]}return[W,H]});if(y(G,"constraint")||!l1(G))$.structure=G;return $},finalizeInnerJson:({structure:Y,...Z})=>W1(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,$=G.variadic&&Object.keys(G).length===1?G.variadic:G;return{...X,sequence:$}}},divisor:{child:!0,parse:s0("divisor")},max:{child:!0,parse:s0("max")},min:{child:!0,parse:s0("min")},maxLength:{child:!0,parse:s0("maxLength")},minLength:{child:!0,parse:s0("minLength")},exactLength:{child:!0,parse:s0("exactLength")},before:{child:!0,parse:s0("before")},after:{child:!0,parse:s0("after")},pattern:{child:!0,parse:s0("pattern")},predicate:{child:!0,parse:s0("predicate")}},reduce:(Y,Z)=>v_({},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
+ \u25E6 `)}`,problem:(Y)=>`(${Y.actual}) must be...
31
+ ${Y.expected}`},intersections:{intersection:(Y,Z,X)=>v_(Y.inner,Z.inner,X),...o1("intersection",(Y,Z,X)=>{if(Y.children.length===0)return Z;let{domain:_,proto:G,...$}=Y.inner,W=G??_,H=W?L0(W,Z,X):Z;return H instanceof S?H:Y?.basis?.equals(H)?Y:Y.$.node("intersection",{...$,[H.kind]:H},{prereduced:!0})})}});class x_ extends I1{basis=this.inner.domain??this.inner.proto??null;refinements=this.children.filter((Y)=>Y.isRefinement());structure=this.inner.structure;expression=$Q(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 aY={implementation:GQ,Node:x_},$Q=(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},v_=(Y,Z,X)=>{let _={},G=Y.proto??Y.domain,$=Z.proto??Z.domain,W=G?$?L0(G,$,X):G:$;if(W instanceof S)return W;if(W)_[W.kind]=W;return Z2({kind:"intersection",baseInner:_,l:X2(Y),r:X2(Z),roots:[],ctx:X})};var WQ=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:T0(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 A(HQ(Y.expression,Z.expression));let _=L0(Y.in,Z.in,X);if(_ instanceof S)return _;let G={morphs:Y.morphs};if(Y.declaredIn||Z.declaredIn){let $=L0(Y.in,Z.in,X);if($ instanceof S)return $.throw();else G.declaredIn=$}if(Y.declaredOut||Z.declaredOut){let $=L0(Y.out,Z.out,X);if($ instanceof S)return $.throw();else G.declaredOut=$}return _.distribute(($)=>X.$.node("morph",{...G,in:$}),X.$.parseSchema)},...o1("morph",(Y,Z,X)=>{let _=Y.inner.in?L0(Y.inner.in,Z,X):Z;return _ instanceof S?_:_.equals(Y.inner.in)?Y:X.$.node("morph",{...Y.inner,in:_})})}});class f_ extends I1{serializedMorphs=this.morphs.map(T0);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??I.intrinsic.unknown.internal}get out(){return this.declaredOut??this.introspectableOut??I.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 a1(this.morphs,Y.morphs,{isEqual:(Z,X)=>Z===X||y(Z,"root")&&y(X,"root")&&Z.equals(X)})}}var eY={implementation:WQ,Node:f_},HQ=(Y,Z)=>`The intersection of distinct morphs at a single path is indeterminate:
32
+ Left: ${Y}
33
+ Right: ${Z}`;var JQ=r({kind:"proto",hasAssociatedError:!0,collapsibleKey:"proto",keys:{proto:{serialize:(Y)=>v2(Y)??w1(Y)},dateAllowsInvalid:{}},normalize:(Y)=>{let Z=typeof Y==="string"?{proto:j4[Y]}:typeof Y==="function"?D0(Y)?Y:{proto:Y}:typeof Y.proto==="string"?{...Y,proto:j4[Y.proto]}:Y;if(typeof Z.proto!=="function")A(t2.writeInvalidSchemaMessage(Z.proto));if(n4(Z,"dateAllowsInvalid")&&Z.proto!==Date)A(t2.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?jX[Y.builtinName]:`an instance of ${Y.proto.name}`,actual:(Y)=>Y instanceof Date&&Y.toString()==="Invalid Date"?"an invalid Date":S2(Y)},intersections:{proto:(Y,Z)=>Y.proto===Date&&Z.proto===Date?Y.dateAllowsInvalid?Z:Y:NY(Y.proto,Z.proto)?Y:NY(Z.proto,Y.proto)?Z:S.init("proto",Y,Z),domain:(Y,Z)=>Z.domain==="object"?Y:S.init("domain",I.intrinsic.object.internal,Z)}});class h_ extends v4{builtinName=v2(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 t2={implementation:JQ,Node:h_,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 QQ=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 $ of G)if($.hasKind("morph")){let W=X.findIndex((H)=>H.hasKind("morph")&&H.hasEqualMorphs($));if(W===-1)X.push($);else{let H=X[W];X[W]=Z.$.node("morph",{...H.inner,in:H.in.rawOr($.in)})}}else X.push($)}if(!Z.def.ordered)X.sort((_,G)=>_.hash<G.hash?-1:1);return X}}},normalize:(Y)=>U0(Y)?{branches:Y}:Y,reduce:(Y,Z)=>{let X=AQ(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,W2),expected:(Y)=>{let Z=wX(Y.errors,"propString"),X=Object.entries(Z).map(([_,G])=>{let $=[];for(let Q of G)c1($,Q.expected);let W=W2($),H=G.every((Q)=>Q.actual===G[0].actual)?G[0].actual:i(G[0].data);return`${_&&`${_} `}must be ${W}${H&&` (was ${H})`}`});return W2(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)A(wQ(Y.expression,Z.expression));if(_=YZ(Z.branches,Y.branches,X),_ instanceof S)_.invert()}else _=YZ(Y.branches,Z.branches,X);if(_ instanceof S)return _;return X.$.parseSchema(Y.ordered||Z.ordered?{branches:_,ordered:!0}:{branches:_})},...o1("union",(Y,Z,X)=>{let _=YZ(Y.branches,[Z],X);if(_ instanceof S)return _;if(_.length===1)return _[0];return X.$.parseSchema(Y.ordered?{branches:_,ordered:!0}:{branches:_})})}});class y_ extends I1{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]=I.intrinsic.boolean;continue}Y.push(X)}return Y}unitBranches=this.branches.filter((Y)=>Y.in.hasKind("unit"));discriminant=this.discriminate();discriminantJson=this.discriminant?DQ(this.discriminant):null;expression=this.distribute((Y)=>Y.nestableExpression,MQ);createBranchedOptimisticRootApply(){return(Y,Z)=>{let X=this.traverseOptimistic(Y);if(X!==L1)return X;let _=new x1(Y,this.$.resolvedConfig);return this.traverseApply(Y,_),_.finalize(Z)}}get shallowMorphs(){return this.branches.reduce((Y,Z)=>c1(Y,Z.shallowMorphs),[])}get defaultShortDescription(){return this.distribute((Y)=>Y.defaultShortDescription,W2)}innerToJsonSchema(Y){if(this.branchGroups.length===1&&this.branchGroups[0].equals(I.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 L1};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],F=J==="default"?J:`case ${J}`;Y.line(`${F}: return ${z===!0?G?Y.data:z:G?`${Y.invoke(z)} ? ${z.contextFreeMorph?`${T0(z.contextFreeMorph)}(${Y.data})`:Y.data} : "${L1}"`:Y.invoke(z)}`)}return Y}),Y.traversalKind==="Allows"){Y.return(G?`"${L1}"`:!1);return}let $=W2(this.discriminant.kind==="domain"?_.map((J)=>{let z=J.slice(1,-1);return z==="function"?H1.object:H1[z]}):_),W=this.discriminant.path.map((J)=>typeof J==="symbol"?T0(J):JSON.stringify(J)),H=JSON.stringify($),Q=this.discriminant.kind==="domain"?`${VQ}[${Z}]`:`${OQ}(${Z})`;Y.line(`ctx.errorFromNodeContext({
34
34
  code: "predicate",
35
35
  expected: ${H},
36
36
  actual: ${Q},
37
37
  relativePath: [${W}],
38
38
  meta: ${this.compiledMeta}
39
- })`)}compileIndiscriminable(Z){if(Z.traversalKind==="Apply"){Z.const("errors","[]");for(let Y of this.branches)Z.line("ctx.pushBranch()").line(Z.invoke(Y)).if("!ctx.hasError()",()=>Z.return(Y.includesTransform?"ctx.queuedMorphs.push(...ctx.popBranch().queuedMorphs)":"ctx.popBranch()")).line("errors.push(ctx.popBranch().error)");Z.line(`ctx.errorFromNodeContext({ code: "union", errors, meta: ${this.compiledMeta} })`)}else{let{optimistic:Y}=Z;Z.optimistic=!1;for(let X of this.branches)Z.if(`${Z.invoke(X)}`,()=>Z.return(Y?X.contextFreeMorph?`${C0(X.contextFreeMorph)}(${Z.data})`:Z.data:!0));Z.return(Y?`"${V1}"`:!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 _=i(this.unitBranches,($,W)=>[`${W.in.serializedValue}`,W.hasKind("morph")?W:!0]);return{kind:"unit",path:[],optionallyChainedPropString:"data",cases:_}}let Z=[];for(let _=0;_<this.branches.length-1;_++){let $=this.branches[_];for(let W=_+1;W<this.branches.length;W++){let H=this.branches[W],Q=U1($.in,H.in,$.$);if(!(Q instanceof S))continue;for(let J of Q){if(!J.kind||J.optional)continue;let z,U;if(J.kind==="domain"){let{l:V,r:N}=J;z=`"${typeof V==="string"?V:V.domain}"`,U=`"${typeof N==="string"?N:N.domain}"`}else if(J.kind==="unit")z=J.l.serializedValue,U=J.r.serializedValue;else continue;let D=Z.find((V)=>e1(V.path,J.path)&&V.kind===J.kind);if(!D)Z.push({kind:J.kind,cases:{[z]:{branchIndices:[_],condition:J.l},[U]:{branchIndices:[W],condition:J.r}},path:J.path});else{if(D.cases[z])D.cases[z].branchIndices=c1(D.cases[z].branchIndices,_);else D.cases[z]??={branchIndices:[_],condition:J.l};if(D.cases[U])D.cases[U].branchIndices=c1(D.cases[U].branchIndices,W);else D.cases[U]??={branchIndices:[W],condition:J.r}}}}}let Y=this.ordered?IQ(Z,this.branches):Z;if(!Y.length)return null;let X=NQ(Y,this),G={};for(let _ in X.best.cases){let $=wQ(X,_);if($===null){G[_]=!0;continue}if($.length===this.branches.length)return null;if(this.ordered)$.sort((Q,J)=>Q.originalIndex-J.originalIndex);let W=$.map((Q)=>Q.branch),H=W.length===1?W[0]:this.$.node("union",this.ordered?{branches:W,ordered:!0}:W);Object.assign(this.referencesById,H.referencesById),G[_]=H}if(X.defaultEntries.length){let _=X.defaultEntries.map(($)=>$.branch);G.default=this.$.node("union",this.ordered?{branches:_,ordered:!0}:_,{prereduced:!0}),Object.assign(this.referencesById,G.default.referencesById)}return Object.assign(X.location,{cases:G})}}var NQ=(Z,Y)=>{let X=Z.sort(($,W)=>Object.keys(W.cases).length-Object.keys($.cases).length)[0],G={kind:X.kind,path:X.path,optionallyChainedPropString:nG(X.path)},_=Y.branches.map(($,W)=>({originalIndex:W,branch:$}));return{best:X,location:G,defaultEntries:_,node:Y}},wQ=(Z,Y)=>{let X=Z.best.cases[Y],G=BQ(X.condition,Z.location.path,Z.node.$),_=[],$=[];for(let W=0;W<Z.defaultEntries.length;W++){let H=Z.defaultEntries[W];if(X.branchIndices.includes(H.originalIndex)){let Q=lG(Z.node.branches[H.originalIndex],Z.location);if(Q===null)_=null;else _?.push({originalIndex:H.originalIndex,branch:Q})}else if(H.branch.hasKind("alias")&&G.hasKind("domain")&&G.domain==="object")_?.push(H);else{if(H.branch.in.overlaps(G)){let Q=lG(H.branch,Z.location);_?.push({originalIndex:H.originalIndex,branch:Q})}$.push(H)}}return Z.defaultEntries=$,_},IQ=(Z,Y)=>{return Z.filter((G)=>{let _=Object.values(G.cases).map(($)=>$.branchIndices);for(let $=0;$<_.length-1;$++){let W=_[$];for(let H=$+1;H<_.length;H++){let Q=_[H];for(let J of W)for(let z of Q)if(J>z){if(Y[J].overlaps(Y[z]))return!1}}}return!0})},BQ=(Z,Y,X)=>{let G=Z==="undefined"?X.node("unit",{unit:void 0}):Z==="null"?X.node("unit",{unit:null}):Z==="boolean"?X.units([!0,!1]):Z;for(let _=Y.length-1;_>=0;_--){let $=Y[_];G=X.node("intersection",typeof $==="number"?{proto:"Array",sequence:[...qX($).map((W)=>({})),G]}:{domain:"object",required:[{key:$,value:G}]})}return G},nG=(Z)=>Z.reduce((Y,X)=>Y+kZ(X,!0),"data"),KQ=C0(SX),CQ=C0(o),J5={implementation:RQ,Node:oG},TQ=(Z)=>({kind:Z.kind,path:Z.path.map((Y)=>typeof Y==="string"?Y:X4(Y)),cases:i(Z.cases,(Y,X)=>[Y,X===!0?X:X.hasKind("union")&&X.discriminantJson?X.discriminantJson:X.json])}),qQ={delimiter:" | ",finalDelimiter:" | "},jQ=(Z)=>J2(Z,qQ),J2=(Z,Y)=>{let X=Y?.delimiter??", ",G=Y?.finalDelimiter??" or ";if(Z.length===0)return"never";if(Z.length===1)return Z[0];if(Z.length===2&&Z[0]==="false"&&Z[1]==="true"||Z[0]==="true"&&Z[1]==="false")return"boolean";let _={},$=Z.filter((H)=>_[H]?!1:_[H]=!0),W=$.pop();return`${$.join(X)}${$.length?G:""}${W}`},H5=(Z,Y,X)=>{let G=Y.map(()=>[]);for(let $=0;$<Z.length;$++){let W={};for(let H=0;H<Y.length;H++){if(G[H]===null)continue;if(Z[$].equals(Y[H])){G[H]=null,W={};break}let Q=V0(Z[$],Y[H],X);if(Q instanceof S)continue;if(Q.equals(Z[$])){G[H].push(Z[$]),W={};break}if(Q.equals(Y[H]))G[H]=null;else W[H]=Q}for(let H in W)G[H][$]=W[H]}let _=G.flatMap(($,W)=>$?.flatMap((H)=>H.branches)??Y[W]);return _.length===0?S.init("union",Z,Y):_},PQ=({branches:Z,ordered:Y})=>{if(Z.length<2)return Z;let X=Z.map(()=>!0);for(let G=0;G<Z.length;G++)for(let _=G+1;_<Z.length&&X[G]&&X[_];_++){if(Z[G].equals(Z[_])){X[_]=!1;continue}let $=U1(Z[G].in,Z[_].in,Z[0].$);if($ instanceof S)continue;if(!Y)SQ(Z[G],Z[_]);if($.equals(Z[G].in))X[G]=!!Y;else if($.equals(Z[_].in))X[_]=!1}return Z.filter((G,_)=>X[_])},SQ=(Z,Y)=>{if(!Z.includesTransform&&!Y.includesTransform)return;if(!e1(Z.shallowMorphs,Y.shallowMorphs))A(iG(Z.expression,Y.expression));if(!e1(Z.flatMorphs,Y.flatMorphs,{isEqual:(X,G)=>X.propString===G.propString&&(X.node.hasKind("morph")&&G.node.hasKind("morph")?X.node.hasEqualMorphs(G.node):X.node.hasKind("intersection")&&G.node.hasKind("intersection")?X.node.structure?.structuralMorphRef===G.node.structure?.structuralMorphRef:!1)}))A(iG(Z.expression,Y.expression))},lG=(Z,Y)=>Z.transform((X,G)=>{if(X==="domain"||X==="unit")return null;return G},{shouldTransform:(X,G)=>{let _=nG(G.path);if(!Y.optionallyChainedPropString.startsWith(_))return!1;if(X.hasKind("domain")&&X.domain==="object")return!0;if((X.hasKind("domain")||Y.kind==="unit")&&_===Y.optionallyChainedPropString)return!0;return X.children.length!==0&&X.kind!=="index"}}),iG=(Z,Y)=>`An unordered union of a type including a morph and a type with overlapping input is indeterminate:
40
- Left: ${Z}
41
- Right: ${Y}`,vQ=(Z,Y)=>`The intersection of two ordered unions is indeterminate:
42
- Left: ${Z}
43
- Right: ${Y}`;var xQ=r({kind:"unit",hasAssociatedError:!0,keys:{unit:{preserveUndefined:!0,serialize:(Z)=>Z instanceof Date?Z.toISOString():B1(Z)}},normalize:(Z)=>Z,defaults:{description:(Z)=>o(Z.unit),problem:({expected:Z,actual:Y})=>`${Z===Y?`must be reference equal to ${Z} (serialized to the same value)`:`must be ${Z} (was ${Y})`}`},intersections:{unit:(Z,Y)=>S.init("unit",Z,Y),...i1("unit",(Z,Y)=>{if(Y.allows(Z.unit))return Z;let X=Y.hasKind("intersection")?Y.basis:Y;if(X){let G=X.hasKind("domain")?X:I.intrinsic.object;if(Z.domain!==G.domain){let _=Z.domain==="undefined"||Z.domain==="null"||Z.domain==="boolean"?Z.domain:I.intrinsic[Z.domain];return S.init("domain",_,G)}}return S.init("assignability",Z,Y.hasKind("intersection")?Y.children.find((G)=>!G.allows(Z.unit)):Y)})}});class sG extends h4{compiledValue=this.json.unit;serializedValue=typeof this.unit==="string"||this.unit instanceof Date?JSON.stringify(this.compiledValue):`${this.compiledValue}`;compiledCondition=rG(this.unit,this.serializedValue);compiledNegation=rG(this.unit,this.serializedValue,"negated");expression=o(this.unit);domain=y0(this.unit);get defaultShortDescription(){return this.domain==="object"?J1.object:this.description}innerToJsonSchema(Z){return this.unit===null?{type:"null"}:I.intrinsic.jsonPrimitive.allows(this.unit)?{const:this.unit}:Z.fallback.unit({code:"unit",base:{},unit:this.unit})}traverseAllows=this.unit instanceof Date?(Z)=>Z instanceof Date&&Z.toISOString()===this.compiledValue:Number.isNaN(this.unit)?(Z)=>Number.isNaN(Z):(Z)=>Z===this.unit}var Q5={implementation:xQ,Node:sG},rG=(Z,Y,X)=>{if(Z instanceof Date){let G=`data instanceof Date && data.toISOString() === ${Y}`;return X?`!(${G})`:G}if(Number.isNaN(Z))return`${X?"!":""}Number.isNaN(data)`;return`data ${X?"!":"="}== ${Y}`};var fQ=r({kind:"index",hasAssociatedError:!1,intersectionIsOpen:!0,keys:{signature:{child:!0,parse:(Z,Y)=>{let X=Y.$.parseSchema(Z);if(!X.extends(I.intrinsic.key))return A(kQ(X.expression));let G=X.branches.filter((_)=>_.hasKind("unit"));if(G.length)return A(hQ(G.map((_)=>o(_.unit))));return X}},value:{child:!0,parse:(Z,Y)=>Y.$.parseSchema(Z)}},normalize:(Z)=>Z,defaults:{description:(Z)=>`[${Z.signature.expression}]: ${Z.value.description}`},intersections:{index:(Z,Y,X)=>{if(Z.signature.equals(Y.signature)){let G=V0(Z.value,Y.value,X),_=G instanceof S?I.intrinsic.never.internal:G;return X.$.node("index",{signature:Z.signature,value:_})}if(Z.signature.extends(Y.signature)&&Z.value.subsumes(Y.value))return Y;if(Y.signature.extends(Z.signature)&&Y.value.subsumes(Z.value))return Z;return null}}});class aG extends K1{impliedBasis=I.intrinsic.object.internal;expression=`[${this.signature.expression}]: ${this.value.expression}`;flatRefs=Y0(this.value.flatRefs.map((Z)=>b1([this.signature,...Z.path],Z.node)),b1([this.signature],this.value));traverseAllows=(Z,Y)=>S4(Z).every((X)=>{if(this.signature.traverseAllows(X[0],Y))return z1(X[0],()=>this.value.traverseAllows(X[1],Y),Y);return!0});traverseApply=(Z,Y)=>{for(let X of S4(Z))if(this.signature.traverseAllows(X[0],Y))z1(X[0],()=>this.value.traverseApply(X[1],Y),Y)};_transform(Z,Y){Y.path.push(this.signature);let X=super._transform(Z,Y);return Y.path.pop(),X}compile(){}}var z5={implementation:fQ,Node:aG},hQ=(Z)=>`Index keys ${Z.join(", ")} should be specified as named props.`,kQ=(Z)=>`Indexed key definition '${Z}' must be a string or symbol`;var bQ=r({kind:"required",hasAssociatedError:!0,intersectionIsOpen:!0,keys:{key:{},value:{child:!0,parse:(Z,Y)=>Y.$.parseSchema(Z)}},normalize:(Z)=>Z,defaults:{description:(Z)=>`${Z.compiledKey}: ${Z.value.description}`,expected:(Z)=>Z.missingValueDescription,actual:()=>"missing"},intersections:{required:r2,optional:r2}});class tG extends s2{expression=`${this.compiledKey}: ${this.value.expression}`;errorContext=Object.freeze({code:"required",missingValueDescription:this.value.defaultShortDescription,relativePath:[this.key],meta:this.meta});compiledErrorContext=V4(this.errorContext)}var U5={implementation:bQ,Node:tG};var yQ=r({kind:"sequence",hasAssociatedError:!1,collapsibleKey:"variadic",keys:{prefix:{child:!0,parse:(Z,Y)=>{if(Z.length===0)return;return Z.map((X)=>Y.$.parseSchema(X))}},optionals:{child:!0,parse:(Z,Y)=>{if(Z.length===0)return;return Z.map((X)=>Y.$.parseSchema(X))}},defaultables:{child:(Z)=>Z.map((Y)=>Y[0]),parse:(Z,Y)=>{if(Z.length===0)return;return Z.map((X)=>{let G=Y.$.parseSchema(X[0]);return t2(G,X[1],null),[G,X[1]]})},serialize:(Z)=>Z.map((Y)=>[Y[0].collapsibleJson,B1(Y[1])])},variadic:{child:!0,parse:(Z,Y)=>Y.$.parseSchema(Z,Y)},minVariadicLength:{parse:(Z)=>Z===0?void 0:Z},postfix:{child:!0,parse:(Z,Y)=>{if(Z.length===0)return;return Z.map((X)=>Y.$.parseSchema(X))}}},normalize:(Z)=>{if(typeof Z==="string")return{variadic:Z};if("variadic"in Z||"prefix"in Z||"defaultables"in Z||"optionals"in Z||"postfix"in Z||"minVariadicLength"in Z){if(Z.postfix?.length){if(!Z.variadic)return A(uQ);if(Z.optionals?.length||Z.defaultables?.length)return A(E5)}if(Z.minVariadicLength&&!Z.variadic)return A("minVariadicLength may not be specified without a variadic element");return Z}return{variadic:Z}},reduce:(Z,Y)=>{let X=Z.minVariadicLength??0,G=Z.prefix?.slice()??[],_=Z.defaultables?.slice()??[],$=Z.optionals?.slice()??[],W=Z.postfix?.slice()??[];if(Z.variadic){while($.at(-1)?.equals(Z.variadic))$.pop();if($.length===0&&_.length===0)while(G.at(-1)?.equals(Z.variadic))G.pop(),X++;while(W[0]?.equals(Z.variadic))W.shift(),X++}else if($.length===0&&_.length===0)G.push(...W.splice(0));if(X!==Z.minVariadicLength||Z.prefix&&Z.prefix.length!==G.length)return Y.node("sequence",{...Z,prefix:G,defaultables:_,optionals:$,postfix:W,minVariadicLength:X},{prereduced:!0})},defaults:{description:(Z)=>{if(Z.isVariadicOnly)return`${Z.variadic.nestableExpression}[]`;return`[${Z.tuple.map((X)=>X.kind==="defaultables"?`${X.node.nestableExpression} = ${o(X.default)}`:X.kind==="optionals"?`${X.node.nestableExpression}?`:X.kind==="variadic"?`...${X.node.nestableExpression}[]`:X.node.expression).join(", ")}]`}},intersections:{sequence:(Z,Y,X)=>{let G=X8({l:Z.tuple,r:Y.tuple,disjoint:new S,result:[],fixedVariants:[],ctx:X}),_=G.disjoint.length===0?[G,...G.fixedVariants]:G.fixedVariants;return _.length===0?G.disjoint:_.length===1?X.$.node("sequence",eG(_[0].result)):X.$.node("union",_.map(($)=>({proto:Array,sequence:eG($.result)})))}}});class Z9 extends K1{impliedBasis=I.intrinsic.Array.internal;tuple=mQ(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((Z)=>{if(Z.kind==="defaultables"||Z.kind==="optionals")return this.defaultablesAndOptionals.push(Z.node),!0;return Z.kind==="prefix"});variadicOrPostfix=t1(this.variadic&&[this.variadic],this.postfix);flatRefs=this.addFlatRefs();addFlatRefs(){return pZ(this.flatRefs,this.prevariadic.flatMap((Z,Y)=>Y0(Z.node.flatRefs.map((X)=>b1([`${Y}`,...X.path],X.node)),b1([`${Y}`],Z.node)))),pZ(this.flatRefs,this.variadicOrPostfix.flatMap((Z)=>Y0(Z.flatRefs.map((Y)=>b1([I.intrinsic.nonNegativeIntegerString.internal,...Y.path],Y.node)),b1([I.intrinsic.nonNegativeIntegerString.internal],Z)))),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=pQ(this);defaultValueMorphsReference=this.defaultValueMorphs.length?C0(this.defaultValueMorphs):void 0;elementAtIndex(Z,Y){if(Y<this.prevariadic.length)return this.tuple[Y];let X=Z.length-this.postfixLength;if(Y>=X)return{kind:"postfix",node:this.postfix[Y-X]};return{kind:"variadic",node:this.variadic??G0(`Unexpected attempt to access index ${Y} on ${this}`)}}traverseAllows=(Z,Y)=>{for(let X=0;X<Z.length;X++)if(!this.elementAtIndex(Z,X).node.traverseAllows(Z[X],Y))return!1;return!0};traverseApply=(Z,Y)=>{let X=0;for(;X<Z.length;X++)z1(X,()=>this.elementAtIndex(Z,X).node.traverseApply(Z[X],Y),Y)};get element(){return this.cacheGetter("element",this.$.node("union",this.children))}compile(Z){if(this.prefix)for(let[Y,X]of this.prefix.entries())Z.traverseKey(`${Y}`,`data[${Y}]`,X);for(let[Y,X]of this.defaultablesAndOptionals.entries()){let G=`${Y+this.prefixLength}`;Z.if(`${G} >= ${Z.data}.length`,()=>Z.traversalKind==="Allows"?Z.return(!0):Z.return()),Z.traverseKey(G,`data[${G}]`,X)}if(this.variadic){if(this.postfix)Z.const("firstPostfixIndex",`${Z.data}.length${this.postfix?`- ${this.postfix.length}`:""}`);if(Z.for(`i < ${this.postfix?"firstPostfixIndex":"data.length"}`,()=>Z.traverseKey("i","data[i]",this.variadic),this.prevariadic.length),this.postfix)for(let[Y,X]of this.postfix.entries()){let G=`firstPostfixIndex + ${Y}`;Z.traverseKey(G,`data[${G}]`,X)}}if(Z.traversalKind==="Allows")Z.return(!0)}_transform(Z,Y){Y.path.push(I.intrinsic.nonNegativeIntegerString.internal);let X=super._transform(Z,Y);return Y.path.pop(),X}expression=this.description;reduceJsonSchema(Z,Y){if(this.prevariadic.length)Z.prefixItems=this.prevariadic.map((X)=>{let G=X.node.toJsonSchemaRecurse(Y);if(X.kind==="defaultables"){let _=typeof X.default==="function"?X.default():X.default;G.default=I.intrinsic.jsonData.allows(_)?_:Y.fallback.defaultValue({code:"defaultValue",base:G,value:_})}return G});if(this.minLength)Z.minItems=this.minLength;if(this.variadic){let X=Object.assign(Z,{items:this.variadic.toJsonSchemaRecurse(Y)});if(this.maxLength)X.maxItems=this.maxLength;if(this.postfix){let G=this.postfix.map((_)=>_.toJsonSchemaRecurse(Y));Z=Y.fallback.arrayPostfix({code:"arrayPostfix",base:X,elements:G})}}else Z.items=!1,delete Z.maxItems;return Z}}var gQ={},pQ=(Z)=>{if(!Z.defaultables)return[];let Y=[],X="[",G=Z.prefixLength+Z.defaultablesLength-1;for(let _=Z.prefixLength;_<=G;_++){let[$,W]=Z.defaultables[_-Z.prefixLength];Y.push(_5(_,$,W)),X+=`${_}: ${$.id} = ${B1(W)}, `}return X+="]",gQ[X]??=Y},F5={implementation:yQ,Node:Z9},mQ=(Z)=>{let Y=[];if(Z.prefix)for(let X of Z.prefix)Y.push({kind:"prefix",node:X});if(Z.defaultables)for(let[X,G]of Z.defaultables)Y.push({kind:"defaultables",node:X,default:G});if(Z.optionals)for(let X of Z.optionals)Y.push({kind:"optionals",node:X});if(Z.variadic)Y.push({kind:"variadic",node:Z.variadic});if(Z.postfix)for(let X of Z.postfix)Y.push({kind:"postfix",node:X});return Y},eG=(Z)=>Z.reduce((Y,X)=>{if(X.kind==="variadic")Y.variadic=X.node;else if(X.kind==="defaultables")Y.defaultables=Y0(Y.defaultables,[[X.node,X.default]]);else Y[X.kind]=Y0(Y[X.kind],X.node);return Y},{}),E5="A postfix required element cannot follow an optional or defaultable element",uQ="A postfix element requires a variadic element",X8=(Z)=>{let[Y,...X]=Z.l,[G,..._]=Z.r;if(!Y||!G)return Z;let $=X.at(-1)?.kind==="postfix",W=_.at(-1)?.kind==="postfix",H=Y.kind==="prefix"||G.kind==="prefix"?"prefix":Y.kind==="postfix"||G.kind==="postfix"?"postfix":Y.kind==="variadic"&&G.kind==="variadic"?"variadic":$||W?"prefix":Y.kind==="defaultables"||G.kind==="defaultables"?"defaultables":"optionals";if(Y.kind==="prefix"&&G.kind==="variadic"&&W){let U=X8({...Z,fixedVariants:[],r:_.map((D)=>({...D,kind:"prefix"}))});if(U.disjoint.length===0)Z.fixedVariants.push(U)}else if(G.kind==="prefix"&&Y.kind==="variadic"&&$){let U=X8({...Z,fixedVariants:[],l:X.map((D)=>({...D,kind:"prefix"}))});if(U.disjoint.length===0)Z.fixedVariants.push(U)}let Q=V0(Y.node,G.node,Z.ctx);if(Q instanceof S)if(H==="prefix"||H==="postfix")Z.disjoint.push(...Q.withPrefixKey(H==="prefix"?Z.result.length:`-${X.length+1}`,"required")),Z.result=[...Z.result,{kind:H,node:I.intrinsic.never.internal}];else if(H==="optionals"||H==="defaultables")return Z;else return X8({...Z,fixedVariants:[],l:X.map((U)=>({...U,kind:"prefix"})),r:X.map((U)=>({...U,kind:"prefix"}))});else if(H==="defaultables"){if(Y.kind==="defaultables"&&G.kind==="defaultables"&&Y.default!==G.default)A(G5(Y.default,G.default));Z.result=[...Z.result,{kind:H,node:Q,default:Y.kind==="defaultables"?Y.default:G.kind==="defaultables"?G.default:G0(`Unexpected defaultable intersection from ${Y.kind} and ${G.kind} elements.`)}]}else Z.result=[...Z.result,{kind:H,node:Q}];let J=Z.l.length,z=Z.r.length;if(Y.kind!=="variadic"||J>=z&&(G.kind==="variadic"||z===1))Z.l=X;if(G.kind!=="variadic"||z>=J&&(Y.kind==="variadic"||J===1))Z.r=_;return X8(Z)};var G9=(Z)=>(Y)=>{if(Y.props.length||Y.index){let X=Y.index?.map((_)=>_[Z])??[];for(let _ of Y.props)X.push(_[Z]);if(Y.undeclared)X.push(`+ (undeclared): ${Y.undeclared}`);let G=`{ ${X.join(", ")} }`;return Y.sequence?`${G} & ${Y.sequence.description}`:G}return Y.sequence?.description??"{}"},dQ=G9("description"),cQ=G9("expression"),Y9=(Z,Y,X)=>{let G=Z.required?"required":"optional";if(!Y.signature.allows(Z.key))return null;let _=U1(Z.value,Y.value,X);if(_ instanceof S)return G==="optional"?X.node("optional",{key:Z.key,value:I.intrinsic.never.internal}):_.withPrefixKey(Z.key,Z.kind);return null},lQ=r({kind:"structure",hasAssociatedError:!1,normalize:(Z)=>Z,applyConfig:(Z,Y)=>{if(!Z.undeclared&&Y.onUndeclaredKey!=="ignore")return{...Z,undeclared:Y.onUndeclaredKey};return Z},keys:{required:{child:!0,parse:s0("required"),reduceIo:(Z,Y,X)=>{Y.required=Y0(Y.required,X.map((G)=>G[Z]));return}},optional:{child:!0,parse:s0("optional"),reduceIo:(Z,Y,X)=>{if(Z==="in"){Y.optional=X.map((G)=>G.in);return}for(let G of X)Y[G.outProp.kind]=Y0(Y[G.outProp.kind],G.outProp.out)}},index:{child:!0,parse:s0("index")},sequence:{child:!0,parse:s0("sequence")},undeclared:{parse:(Z)=>Z==="ignore"?void 0:Z,reduceIo:(Z,Y,X)=>{if(X!=="delete")return;if(Z==="in")delete Y.undeclared;else Y.undeclared="reject"}}},defaults:{description:dQ},intersections:{structure:(Z,Y,X)=>{let G={...Z.inner},_={...Y.inner},$=new S;if(Z.undeclared){let Q=Z.keyof();for(let J of Y.requiredKeys)if(!Q.allows(J))$.add("presence",I.intrinsic.never.internal,Y.propsByKey[J].value,{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=U1(Q,J.signature,X.$);if(z instanceof S)return[];let U=Y6(z,J.value,X.$);if(U.required)_.required=t1(_.required,U.required);if(U.optional)_.optional=t1(_.optional,U.optional);return U.index??[]})}if(Y.undeclared){let Q=Y.keyof();for(let J of Z.requiredKeys)if(!Q.allows(J))$.add("presence",Z.propsByKey[J].value,I.intrinsic.never.internal,{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=U1(Q,J.signature,X.$);if(z instanceof S)return[];let U=Y6(z,J.value,X.$);if(U.required)G.required=t1(G.required,U.required);if(U.optional)G.optional=t1(G.optional,U.optional);return U.index??[]})}let W={};if(Z.undeclared||Y.undeclared)W.undeclared=Z.undeclared==="reject"||Y.undeclared==="reject"?"reject":"delete";let H=G2({kind:"structure",baseInner:W,l:_2(G),r:_2(_),roots:[],ctx:X});if(H instanceof S)$.push(...H);if($.length)return $;return H}},reduce:(Z,Y)=>{if(Z.index){if(!(Z.required||Z.optional))return;let X=!1,G=Z.required??[],_=Z.optional??[],$=[..._];for(let W of Z.index){for(let H of G){let Q=Y9(H,W,Y);if(Q instanceof S)return Q}for(let[H,Q]of _.entries()){let J=Y9(Q,W,Y);if(J instanceof S)return J;if(J===null)continue;$[H]=J,X=!0}}if(X)return Y.node("structure",{...Z,optional:$},{prereduced:!0})}}});class _9 extends K1{impliedBasis=I.intrinsic.object.internal;impliedSiblings=this.children.flatMap((Z)=>Z.impliedSiblings??[]);props=t1(this.required,this.optional);propsByKey=i(this.props,(Z,Y)=>[Y.key,Y]);propsByKeyReference=C0(this.propsByKey);expression=cQ(this);requiredKeys=this.required?.map((Z)=>Z.key)??[];optionalKeys=this.optional?.map((Z)=>Z.key)??[];literalKeys=[...this.requiredKeys,...this.optionalKeys];_keyof;keyof(){if(this._keyof)return this._keyof;let Z=this.$.units(this.literalKeys).branches;if(this.index)for(let{signature:Y}of this.index)Z=Z.concat(Y.branches);return this._keyof=this.$.node("union",Z)}map(Z){return this.$.node("structure",this.props.flatMap(Z).reduce((Y,X)=>{let G=this.propsByKey[X.key];if(O0(X)){if(X.kind!=="required"&&X.kind!=="optional")return A(`Map result must have kind "required" or "optional" (was ${X.kind})`);return Y[X.kind]=Y0(Y[X.kind],X),Y}let _=X.kind??G?.kind??"required",$=i(X,(W,H)=>(W in a2.implementation.keys)?[W,H]:[]);return Y[_]=Y0(Y[_],this.$.node(_,$)),Y},{}))}assertHasKeys(Z){let Y=Z.filter((X)=>!e2(X,this.keyof()));if(Y.length)return A(X9(this.expression,Y))}get(Z,...Y){let X,G=!1,_=rQ(Z);if((typeof _==="string"||typeof _==="symbol")&&this.propsByKey[_])X=this.propsByKey[_].value,G=this.propsByKey[_].required;if(this.index){for(let W of this.index)if(e2(_,W.signature))X=X?.and(W.value)??W.value}if(this.sequence&&e2(_,I.intrinsic.nonNegativeIntegerString))if(y(_,"root")){if(this.sequence.variadic)X=X?.and(this.sequence.element)??this.sequence.element}else{let W=Number.parseInt(_);if(W<this.sequence.prevariadic.length){let H=this.sequence.prevariadic[W].node;X=X?.and(H)??H,G||=W<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(_,"root")&&_.extends(I.intrinsic.number))return A(sQ(_.expression,this.sequence.expression));return A(X9(this.expression,[_]))}let $=X.get(...Y);return G?$:$.or(I.intrinsic.undefined)}pick(...Z){return this.assertHasKeys(Z),this.$.node("structure",this.filterKeys("pick",Z))}omit(...Z){return this.assertHasKeys(Z),this.$.node("structure",this.filterKeys("omit",Z))}optionalize(){let{required:Z,...Y}=this.inner;return this.$.node("structure",{...Y,optional:this.props.map((X)=>X.hasKind("required")?this.$.node("optional",X.inner):X)})}require(){let{optional:Z,...Y}=this.inner;return this.$.node("structure",{...Y,required:this.props.map((X)=>X.hasKind("optional")?{key:X.key,value:X.value}:X)})}merge(Z){let Y=this.filterKeys("omit",[Z.keyof()]);if(Z.required)Y.required=Y0(Y.required,Z.required);if(Z.optional)Y.optional=Y0(Y.optional,Z.optional);if(Z.index)Y.index=Y0(Y.index,Z.index);if(Z.sequence)Y.sequence=Z.sequence;if(Z.undeclared)Y.undeclared=Z.undeclared;else delete Y.undeclared;return this.$.node("structure",Y)}filterKeys(Z,Y){let X=c8(this.inner),G=(_)=>{let $=Y.some((W)=>e2(_,W));return Z==="pick"?$:!$};if(X.required)X.required=X.required.filter((_)=>G(_.key));if(X.optional)X.optional=X.optional.filter((_)=>G(_.key));if(X.index)X.index=X.index.filter((_)=>G(_.signature));return X}traverseAllows=(Z,Y)=>this._traverse("Allows",Z,Y);traverseApply=(Z,Y)=>this._traverse("Apply",Z,Y);_traverse=(Z,Y,X)=>{let G=X?.currentErrorCount??0;for(let _=0;_<this.props.length;_++)if(Z==="Allows"){if(!this.props[_].traverseAllows(Y,X))return!1}else if(this.props[_].traverseApply(Y,X),X.failFast&&X.currentErrorCount>G)return!1;if(this.sequence){if(Z==="Allows"){if(!this.sequence.traverseAllows(Y,X))return!1}else if(this.sequence.traverseApply(Y,X),X.failFast&&X.currentErrorCount>G)return!1}if(this.index||this.undeclared==="reject"){let _=Object.keys(Y);_.push(...Object.getOwnPropertySymbols(Y));for(let $=0;$<_.length;$++){let W=_[$];if(this.index){for(let H of this.index)if(H.signature.traverseAllows(W,X)){if(Z==="Allows"){if(!z1(W,()=>H.value.traverseAllows(Y[W],X),X))return!1}else if(z1(W,()=>H.value.traverseApply(Y[W],X),X),X.failFast&&X.currentErrorCount>G)return!1}}if(this.undeclared==="reject"&&!this.declaresKey(W)){if(Z==="Allows")return!1;if(X.errorFromNodeContext({code:"predicate",expected:"removed",actual:"",relativePath:[W],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((Z)=>Z.hasDefault())??[])}declaresKey=(Z)=>(Z in this.propsByKey)||this.index?.some((Y)=>Y.signature.allows(Z))||this.sequence!==void 0&&I.intrinsic.nonNegativeIntegerString.allows(Z);_compileDeclaresKey(Z){let Y=[];if(this.props.length)Y.push(`k in ${this.propsByKeyReference}`);if(this.index)for(let X of this.index)Y.push(Z.invoke(X.signature,{kind:"Allows",arg:"k"}));if(this.sequence)Y.push("$ark.intrinsic.nonNegativeIntegerString.allows(k)");return Y.join(" || ")||"false"}get structuralMorph(){return this.cacheGetter("structuralMorph",oQ(this))}structuralMorphRef=this.structuralMorph&&C0(this.structuralMorph);compile(Z){if(Z.traversalKind==="Apply")Z.initializeErrorCount();for(let Y of this.props)if(Z.check(Y),Z.traversalKind==="Apply")Z.returnIfFailFast();if(this.sequence){if(Z.check(this.sequence),Z.traversalKind==="Apply")Z.returnIfFailFast()}if(this.index||this.undeclared==="reject")Z.const("keys","Object.keys(data)"),Z.line("keys.push(...Object.getOwnPropertySymbols(data))"),Z.for("i < keys.length",()=>this.compileExhaustiveEntry(Z));if(Z.traversalKind==="Allows")return Z.return(!0);if(this.structuralMorphRef)Z.if("ctx && !ctx.hasError()",()=>{return Z.line("ctx.queueMorphs(["),nQ(Z,this),Z.line("])")})}compileExhaustiveEntry(Z){if(Z.const("k","keys[i]"),this.index)for(let Y of this.index)Z.if(`${Z.invoke(Y.signature,{arg:"k",kind:"Allows"})}`,()=>Z.traverseKey("k","data[k]",Y.value));if(this.undeclared==="reject")Z.if(`!(${this._compileDeclaresKey(Z)})`,()=>{if(Z.traversalKind==="Allows")return Z.return(!1);return Z.line(`ctx.errorFromNodeContext({ code: "predicate", expected: "removed", actual: "", relativePath: [k], meta: ${this.compiledMeta} })`).if("ctx.failFast",()=>Z.return())});return Z}reduceJsonSchema(Z,Y){switch(Z.type){case"object":return this.reduceObjectJsonSchema(Z,Y);case"array":let X=this.sequence?.reduceJsonSchema(Z,Y)??Z;if(this.props.length||this.index)return Y.fallback.arrayObject({code:"arrayObject",base:X,object:this.reduceObjectJsonSchema({type:"object"},Y)});return X;default:return N0.throwInternalOperandError("structure",Z)}}reduceObjectJsonSchema(Z,Y){if(this.props.length){Z.properties={};for(let X of this.props){let G=X.value.toJsonSchemaRecurse(Y);if(typeof X.key==="symbol"){Y.fallback.symbolKey({code:"symbolKey",base:Z,key:X.key,value:G,optional:X.optional});continue}if(X.hasDefault()){let _=typeof X.default==="function"?X.default():X.default;G.default=I.intrinsic.jsonData.allows(_)?_:Y.fallback.defaultValue({code:"defaultValue",base:G,value:_})}Z.properties[X.key]=G}if(this.requiredKeys.length&&Z.properties)Z.required=this.requiredKeys.filter((X)=>typeof X==="string"&&(X in Z.properties))}if(this.index)for(let X of this.index){let G=X.value.toJsonSchemaRecurse(Y);if(X.signature.equals(I.intrinsic.string)){Z.additionalProperties=G;continue}for(let _ of X.signature.branches){if(!_.extends(I.intrinsic.string)){Z=Y.fallback.symbolKey({code:"symbolKey",base:Z,key:null,value:G,optional:!1});continue}let $={type:"string"};if(_.hasKind("morph"))$=Y.fallback.morph({code:"morph",base:_.in.toJsonSchemaRecurse(Y),out:_.out.toJsonSchemaRecurse(Y)});if(!_.hasKind("intersection"))return G0(`Unexpected index branch kind ${_.kind}.`);let{pattern:W}=_.inner;if(W){let H=Object.assign($,{pattern:W[0].rule});for(let Q=1;Q<W.length;Q++)$=Y.fallback.patternIntersection({code:"patternIntersection",base:H,pattern:W[Q].rule});Z.patternProperties??={},Z.patternProperties[H.pattern]=G}}}if(this.undeclared&&!Z.additionalProperties)Z.additionalProperties=!1;return Z}}var L5={},iQ=(Z)=>{let Y="";for(let X=0;X<Z.defaultable.length;X++)Y+=Z.defaultable[X].defaultValueMorphRef;if(Z.sequence?.defaultValueMorphsReference)Y+=Z.sequence?.defaultValueMorphsReference;if(Z.undeclared==="delete"){if(Y+="delete !(",Z.required)for(let X of Z.required)Y+=X.compiledKey+" | ";if(Z.optional)for(let X of Z.optional)Y+=X.compiledKey+" | ";if(Z.index)for(let X of Z.index)Y+=X.signature.id+" | ";if(Z.sequence)if(Z.sequence.maxLength===null)Y+=u.nonNegativeIntegerString.id;else for(let X=0;X<Z.sequence.tuple.length;X++)Y+=X+" | ";Y+=")"}return Y},oQ=(Z)=>{let Y=iQ(Z);if(!Y)return;if(L5[Y])return L5[Y];let X=(G,_)=>{for(let $=0;$<Z.defaultable.length;$++)if(!(Z.defaultable[$].key in G))Z.defaultable[$].defaultValueMorph(G,_);if(Z.sequence?.defaultables)for(let $=G.length-Z.sequence.prefixLength;$<Z.sequence.defaultables.length;$++)Z.sequence.defaultValueMorphs[$](G,_);if(Z.undeclared==="delete"){for(let $ in G)if(!Z.declaresKey($))delete G[$]}return G};return L5[Y]=X},nQ=(Z,Y)=>{let G=`(data${Y.defaultable.some((_)=>_.defaultValueMorph.length===2)||Y.sequence?.defaultValueMorphs.some((_)=>_.length===2)?", ctx":""})`;return Z.block(`${G} => `,(_)=>{for(let $=0;$<Y.defaultable.length;$++){let{serializedKey:W,defaultValueMorphRef:H}=Y.defaultable[$];_.if(`!(${W} in data)`,(Q)=>Q.line(`${H}${G}`))}if(Y.sequence?.defaultables)_.for(`i < ${Y.sequence.defaultables.length}`,($)=>$.set("data[i]",5),`data.length - ${Y.sequence.prefixLength}`);if(Y.undeclared==="delete")_.forIn("data",($)=>$.if(`!(${Y._compileDeclaresKey($)})`,(W)=>W.line("delete data[k]")));return _.return("data")})},D5={implementation:lQ,Node:_9},rQ=(Z)=>{if(y(Z,"root")&&Z.hasKind("unit"))Z=Z.unit;if(typeof Z==="number")Z=`${Z}`;return Z},sQ=(Z,Y)=>`${Z} is not allowed as an array index on ${Y}. Use the 'nonNegativeIntegerString' keyword instead.`,Y6=(Z,Y,X)=>{let[G,_]=TX(Z.branches,(W)=>W.hasKind("unit"));if(!G.length)return{index:X.node("index",{signature:Z,value:Y})};let $={};for(let W of G){let H=X.node("required",{key:W.unit,value:Y});$[H.kind]=Y0($[H.kind],H)}if(_.length)$.index=X.node("index",{signature:_,value:Y});return $},aQ=(Z)=>y(Z,"root")?Z.expression:o(Z),X9=(Z,Y)=>`Key${Y.length===1?"":"s"} ${Y.map(aQ).join(", ")} ${Y.length===1?"does":"do"} not exist on ${Z}`;var W2={...qG,alias:Z8.implementation,domain:Z6.implementation,unit:Q5.implementation,proto:Y8.implementation,union:J5.implementation,morph:W5.implementation,intersection:$5.implementation,divisor:lZ.implementation,pattern:eZ.implementation,predicate:cZ.implementation,required:U5.implementation,optional:a2.implementation,index:z5.implementation,sequence:F5.implementation,structure:D5.implementation};I.defaultConfig=kX(Object.assign(i(W2,(Z,Y)=>[Z,Y.defaults]),{jitless:uX(),clone:gX,onUndeclaredKey:"ignore",exactOptionalPropertyTypes:!0,numberAllowsNaN:!1,dateAllowsInvalid:!1,onFail:null,keywords:{},toJsonSchema:N0.defaultConfig}));I.resolvedConfig=c2(I.defaultConfig,I.config);var fG={...jG,alias:Z8.Node,domain:Z6.Node,unit:Q5.Node,proto:Y8.Node,union:J5.Node,morph:W5.Node,intersection:$5.Node,divisor:lZ.Node,pattern:eZ.Node,predicate:cZ.Node,required:U5.Node,optional:a2.Node,index:z5.Node,sequence:F5.Node,structure:D5.Node};class Q2 extends KZ{get[Y1](){return"module"}}var O5=(Z,Y)=>new Q2(i(Z,(X,G)=>[X,y(G,"module")?O5(G,Y):Y.bindReference(G)]));var tQ=(Z)=>U0(Z)?Z:("branches"in Z)&&U0(Z.branches)?Z.branches:void 0,eQ=(Z,Y)=>A(`Node of kind ${Y} is not valid as a ${Z} definition`),$9=(Z)=>`#${Z} duplicates public alias ${Z}`,V5={};I.ambient??={};var W9,J9="function $",Zz=(Z)=>Q9(Z,z9(Z)),Q9=(Z,Y)=>{let X=Y.write(J9,4),G=Y.compile()();for(let _ of Z){if(_.precompilation)continue;if(_.traverseAllows=G[`${_.id}Allows`].bind(G),_.isRoot()&&!_.allowsRequiresContext)_.allows=_.traverseAllows;if(_.traverseApply=G[`${_.id}Apply`].bind(G),G[`${_.id}Optimistic`])_.traverseOptimistic=G[`${_.id}Optimistic`].bind(G);_.precompilation=X}},z9=(Z)=>new d8().return(Z.reduce((Y,X)=>{let G=new d2({kind:"Allows"}).indent();X.compile(G);let _=G.write(`${X.id}Allows`),$=new d2({kind:"Apply"}).indent();X.compile($);let W=$.write(`${X.id}Apply`),H=`${Y}${_},
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?`${T0(X.contextFreeMorph)}(${Y.data})`:Y.data:!0));Y.return(Z?`"${L1}"`:!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)=>[`${W.in.serializedValue}`,W.hasKind("morph")?W:!0]);return{kind:"unit",path:[],optionallyChainedPropString:"data",cases:G}}let Y=[];for(let G=0;G<this.branches.length-1;G++){let $=this.branches[G];for(let W=G+1;W<this.branches.length;W++){let H=this.branches[W],Q=z1($.in,H.in,$.$);if(!(Q instanceof S))continue;for(let J of Q){if(!J.kind||J.optional)continue;let z,F;if(J.kind==="domain"){let{l:L,r:w}=J;z=`"${typeof L==="string"?L:L.domain}"`,F=`"${typeof w==="string"?w:w.domain}"`}else if(J.kind==="unit")z=J.l.serializedValue,F=J.r.serializedValue;else continue;let O=Y.find((L)=>a1(L.path,J.path)&&L.kind===J.kind);if(!O)Y.push({kind:J.kind,cases:{[z]:{branchIndices:[G],condition:J.l},[F]:{branchIndices:[W],condition:J.r}},path:J.path});else{if(O.cases[z])O.cases[z].branchIndices=c1(O.cases[z].branchIndices,G);else O.cases[z]??={branchIndices:[G],condition:J.l};if(O.cases[F])O.cases[F].branchIndices=c1(O.cases[F].branchIndices,W);else O.cases[F]??={branchIndices:[W],condition:J.r}}}}}let Z=this.ordered?FQ(Y,this.branches):Y;if(!Z.length)return null;let X=zQ(Z,this),_={};for(let G in X.best.cases){let $=UQ(X,G);if($===null){_[G]=!0;continue}if($.length===this.branches.length)return null;if(this.ordered)$.sort((Q,J)=>Q.originalIndex-J.originalIndex);let W=$.map((Q)=>Q.branch),H=W.length===1?W[0]:this.$.node("union",this.ordered?{branches:W,ordered:!0}:W);Object.assign(this.referencesById,H.referencesById),_[G]=H}if(X.defaultEntries.length){let G=X.defaultEntries.map(($)=>$.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 zQ=(Y,Z)=>{let X=Y.sort(($,W)=>Object.keys(W.cases).length-Object.keys($.cases).length)[0],_={kind:X.kind,path:X.path,optionallyChainedPropString:g_(X.path)},G=Z.branches.map(($,W)=>({originalIndex:W,branch:$}));return{best:X,location:_,defaultEntries:G,node:Z}},UQ=(Y,Z)=>{let X=Y.best.cases[Z],_=EQ(X.condition,Y.location.path,Y.node.$),G=[],$=[];for(let W=0;W<Y.defaultEntries.length;W++){let H=Y.defaultEntries[W];if(X.branchIndices.includes(H.originalIndex)){let Q=k_(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=k_(H.branch,Y.location);G?.push({originalIndex:H.originalIndex,branch:Q})}$.push(H)}}return Y.defaultEntries=$,G},FQ=(Y,Z)=>{return Y.filter((_)=>{let G=Object.values(_.cases).map(($)=>$.branchIndices);for(let $=0;$<G.length-1;$++){let W=G[$];for(let H=$+1;H<G.length;H++){let Q=G[H];for(let J of W)for(let z of Q)if(J>z){if(Z[J].overlaps(Z[z]))return!1}}}return!0})},EQ=(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 $=Z[G];_=X.node("intersection",typeof $==="number"?{proto:"Array",sequence:[...AX($).map((W)=>({})),_]}:{domain:"object",required:[{key:$,value:_}]})}return _},g_=(Y)=>Y.reduce((Z,X)=>Z+jY(X,!0),"data"),VQ=T0(NX),OQ=T0(i),ZZ={implementation:QQ,Node:y_},DQ=(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])}),LQ={delimiter:" | ",finalDelimiter:" | "},MQ=(Y)=>W2(Y,LQ),W2=(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={},$=Y.filter((H)=>G[H]?!1:G[H]=!0),W=$.pop();return`${$.join(X)}${$.length?_:""}${W}`},YZ=(Y,Z,X)=>{let _=Z.map(()=>[]);for(let $=0;$<Y.length;$++){let W={};for(let H=0;H<Z.length;H++){if(_[H]===null)continue;if(Y[$].equals(Z[H])){_[H]=null,W={};break}let Q=L0(Y[$],Z[H],X);if(Q instanceof S)continue;if(Q.equals(Y[$])){_[H].push(Y[$]),W={};break}if(Q.equals(Z[H]))_[H]=null;else W[H]=Q}for(let H in W)_[H][$]=W[H]}let G=_.flatMap(($,W)=>$?.flatMap((H)=>H.branches)??Z[W]);return G.length===0?S.init("union",Y,Z):G},AQ=({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 $=z1(Y[_].in,Y[G].in,Y[0].$);if($ instanceof S)continue;if(!Z)RQ(Y[_],Y[G]);if($.equals(Y[_].in))X[_]=!!Z;else if($.equals(Y[G].in))X[G]=!1}return Y.filter((_,G)=>X[G])},RQ=(Y,Z)=>{if(!Y.includesTransform&&!Z.includesTransform)return;if(!a1(Y.shallowMorphs,Z.shallowMorphs))A(b_(Y.expression,Z.expression));if(!a1(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)}))A(b_(Y.expression,Z.expression))},k_=(Y,Z)=>Y.transform((X,_)=>{if(X==="domain"||X==="unit")return null;return _},{shouldTransform:(X,_)=>{let G=g_(_.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"}}),b_=(Y,Z)=>`An unordered union of a type including a morph and a type with overlapping input is indeterminate:
40
+ Left: ${Y}
41
+ Right: ${Z}`,wQ=(Y,Z)=>`The intersection of two ordered unions is indeterminate:
42
+ Left: ${Y}
43
+ Right: ${Z}`;var NQ=r({kind:"unit",hasAssociatedError:!0,keys:{unit:{preserveUndefined:!0,serialize:(Y)=>Y instanceof Date?Y.toISOString():w1(Y)}},normalize:(Y)=>Y,defaults:{description:(Y)=>i(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),...o1("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:I.intrinsic.object;if(Y.domain!==_.domain){let G=Y.domain==="undefined"||Y.domain==="null"||Y.domain==="boolean"?Y.domain:I.intrinsic[Y.domain];return S.init("domain",G,_)}}return S.init("assignability",Y,Z.hasKind("intersection")?Z.children.find((_)=>!_.allows(Y.unit)):Z)})}});class m_ extends v4{compiledValue=this.json.unit;serializedValue=typeof this.unit==="string"||this.unit instanceof Date?JSON.stringify(this.compiledValue):`${this.compiledValue}`;compiledCondition=p_(this.unit,this.serializedValue);compiledNegation=p_(this.unit,this.serializedValue,"negated");expression=i(this.unit);domain=y0(this.unit);get defaultShortDescription(){return this.domain==="object"?H1.object:this.description}innerToJsonSchema(Y){return this.unit===null?{type:"null"}:I.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 XZ={implementation:NQ,Node:m_},p_=(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 IQ=r({kind:"index",hasAssociatedError:!1,intersectionIsOpen:!0,keys:{signature:{child:!0,parse:(Y,Z)=>{let X=Z.$.parseSchema(Y);if(!X.extends(I.intrinsic.key))return A(BQ(X.expression));let _=X.branches.filter((G)=>G.hasKind("unit"));if(_.length)return A(KQ(_.map((G)=>i(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 _=L0(Y.value,Z.value,X),G=_ instanceof S?I.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 u_ extends N1{impliedBasis=I.intrinsic.object.internal;expression=`[${this.signature.expression}]: ${this.value.expression}`;flatRefs=Z0(this.value.flatRefs.map((Y)=>f1([this.signature,...Y.path],Y.node)),f1([this.signature],this.value));traverseAllows=(Y,Z)=>q4(Y).every((X)=>{if(this.signature.traverseAllows(X[0],Z))return Q1(X[0],()=>this.value.traverseAllows(X[1],Z),Z);return!0});traverseApply=(Y,Z)=>{for(let X of q4(Y))if(this.signature.traverseAllows(X[0],Z))Q1(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 _Z={implementation:IQ,Node:u_},KQ=(Y)=>`Index keys ${Y.join(", ")} should be specified as named props.`,BQ=(Y)=>`Indexed key definition '${Y}' must be a string or symbol`;var TQ=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:l2,optional:l2}});class d_ extends o2{expression=`${this.compiledKey}: ${this.value.expression}`;errorContext=Object.freeze({code:"required",missingValueDescription:this.value.defaultShortDescription,relativePath:[this.key],meta:this.meta});compiledErrorContext=D4(this.errorContext)}var GZ={implementation:TQ,Node:d_};var CQ=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 n2(_,X[1],null),[_,X[1]]})},serialize:(Y)=>Y.map((Z)=>[Z[0].collapsibleJson,w1(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 A(SQ);if(Y.optionals?.length||Y.defaultables?.length)return A(WZ)}if(Y.minVariadicLength&&!Y.variadic)return A("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()??[],$=Y.optionals?.slice()??[],W=Y.postfix?.slice()??[];if(Y.variadic){while($.at(-1)?.equals(Y.variadic))$.pop();if($.length===0&&G.length===0)while(_.at(-1)?.equals(Y.variadic))_.pop(),X++;while(W[0]?.equals(Y.variadic))W.shift(),X++}else if($.length===0&&G.length===0)_.push(...W.splice(0));if(X!==Y.minVariadicLength||Y.prefix&&Y.prefix.length!==_.length)return Z.node("sequence",{...Y,prefix:_,defaultables:G,optionals:$,postfix:W,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} = ${i(X.default)}`:X.kind==="optionals"?`${X.node.nestableExpression}?`:X.kind==="variadic"?`...${X.node.nestableExpression}[]`:X.node.expression).join(", ")}]`}},intersections:{sequence:(Y,Z,X)=>{let _=a2({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",c_(G[0].result)):X.$.node("union",G.map(($)=>({proto:Array,sequence:c_($.result)})))}}});class l_ extends N1{impliedBasis=I.intrinsic.Array.internal;tuple=PQ(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=t1(this.variadic&&[this.variadic],this.postfix);flatRefs=this.addFlatRefs();addFlatRefs(){return xY(this.flatRefs,this.prevariadic.flatMap((Y,Z)=>Z0(Y.node.flatRefs.map((X)=>f1([`${Z}`,...X.path],X.node)),f1([`${Z}`],Y.node)))),xY(this.flatRefs,this.variadicOrPostfix.flatMap((Y)=>Z0(Y.flatRefs.map((Z)=>f1([I.intrinsic.nonNegativeIntegerString.internal,...Z.path],Z.node)),f1([I.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=jQ(this);defaultValueMorphsReference=this.defaultValueMorphs.length?T0(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++)Q1(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(I.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=I.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 qQ={},jQ=(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(tY(G,$,W)),X+=`${G}: ${$.id} = ${w1(W)}, `}return X+="]",qQ[X]??=Z},$Z={implementation:CQ,Node:l_},PQ=(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},c_=(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},{}),WZ="A postfix required element cannot follow an optional or defaultable element",SQ="A postfix element requires a variadic element",a2=(Y)=>{let[Z,...X]=Y.l,[_,...G]=Y.r;if(!Z||!_)return Y;let $=X.at(-1)?.kind==="postfix",W=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"&&W){let F=a2({...Y,fixedVariants:[],r:G.map((O)=>({...O,kind:"prefix"}))});if(F.disjoint.length===0)Y.fixedVariants.push(F)}else if(_.kind==="prefix"&&Z.kind==="variadic"&&$){let F=a2({...Y,fixedVariants:[],l:X.map((O)=>({...O,kind:"prefix"}))});if(F.disjoint.length===0)Y.fixedVariants.push(F)}let Q=L0(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:I.intrinsic.never.internal}];else if(H==="optionals"||H==="defaultables")return Y;else return a2({...Y,fixedVariants:[],l:X.map((F)=>({...F,kind:"prefix"})),r:X.map((F)=>({...F,kind:"prefix"}))});else if(H==="defaultables"){if(Z.kind==="defaultables"&&_.kind==="defaultables"&&Z.default!==_.default)A(sY(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 a2(Y)};var n_=(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??"{}"},vQ=n_("description"),xQ=n_("expression"),o_=(Y,Z,X)=>{let _=Y.required?"required":"optional";if(!Z.signature.allows(Y.key))return null;let G=z1(Y.value,Z.value,X);if(G instanceof S)return _==="optional"?X.node("optional",{key:Y.key,value:I.intrinsic.never.internal}):G.withPrefixKey(Y.key,Y.kind);return null},fQ=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:s0("required"),reduceIo:(Y,Z,X)=>{Z.required=Z0(Z.required,X.map((_)=>_[Y]));return}},optional:{child:!0,parse:s0("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:s0("index")},sequence:{child:!0,parse:s0("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:vQ},intersections:{structure:(Y,Z,X)=>{let _={...Y.inner},G={...Z.inner},$=new S;if(Y.undeclared){let Q=Y.keyof();for(let J of Z.requiredKeys)if(!Q.allows(J))$.add("presence",I.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=z1(Q,J.signature,X.$);if(z instanceof S)return[];let F=Z6(z,J.value,X.$);if(F.required)G.required=t1(G.required,F.required);if(F.optional)G.optional=t1(G.optional,F.optional);return F.index??[]})}if(Z.undeclared){let Q=Z.keyof();for(let J of Y.requiredKeys)if(!Q.allows(J))$.add("presence",Y.propsByKey[J].value,I.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=z1(Q,J.signature,X.$);if(z instanceof S)return[];let F=Z6(z,J.value,X.$);if(F.required)_.required=t1(_.required,F.required);if(F.optional)_.optional=t1(_.optional,F.optional);return F.index??[]})}let W={};if(Y.undeclared||Z.undeclared)W.undeclared=Y.undeclared==="reject"||Z.undeclared==="reject"?"reject":"delete";let H=Z2({kind:"structure",baseInner:W,l:X2(_),r:X2(G),roots:[],ctx:X});if(H instanceof S)$.push(...H);if($.length)return $;return H}},reduce:(Y,Z)=>{if(Y.index){if(!(Y.required||Y.optional))return;let X=!1,_=Y.required??[],G=Y.optional??[],$=[...G];for(let W of Y.index){for(let H of _){let Q=o_(H,W,Z);if(Q instanceof S)return Q}for(let[H,Q]of G.entries()){let J=o_(Q,W,Z);if(J instanceof S)return J;if(J===null)continue;$[H]=J,X=!0}}if(X)return Z.node("structure",{...Y,optional:$},{prereduced:!0})}}});class r_ extends N1{impliedBasis=I.intrinsic.object.internal;impliedSiblings=this.children.flatMap((Y)=>Y.impliedSiblings??[]);props=t1(this.required,this.optional);propsByKey=o(this.props,(Y,Z)=>[Z.key,Z]);propsByKeyReference=T0(this.propsByKey);expression=xQ(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(D0(X)){if(X.kind!=="required"&&X.kind!=="optional")return A(`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",$=o(X,(W,H)=>(W in i2.implementation.keys)?[W,H]:[]);return Z[G]=Z0(Z[G],this.$.node(G,$)),Z},{}))}assertHasKeys(Y){let Z=Y.filter((X)=>!r2(X,this.keyof()));if(Z.length)return A(i_(this.expression,Z))}get(Y,...Z){let X,_=!1,G=yQ(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 W of this.index)if(r2(G,W.signature))X=X?.and(W.value)??W.value}if(this.sequence&&r2(G,I.intrinsic.nonNegativeIntegerString))if(y(G,"root")){if(this.sequence.variadic)X=X?.and(this.sequence.element)??this.sequence.element}else{let W=Number.parseInt(G);if(W<this.sequence.prevariadic.length){let H=this.sequence.prevariadic[W].node;X=X?.and(H)??H,_||=W<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(I.intrinsic.number))return A(gQ(G.expression,this.sequence.expression));return A(i_(this.expression,[G]))}let $=X.get(...Z);return _?$:$.or(I.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=c8(this.inner),_=(G)=>{let $=Z.some((W)=>r2(G,W));return Y==="pick"?$:!$};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 $=0;$<G.length;$++){let W=G[$];if(this.index){for(let H of this.index)if(H.signature.traverseAllows(W,X)){if(Y==="Allows"){if(!Q1(W,()=>H.value.traverseAllows(Z[W],X),X))return!1}else if(Q1(W,()=>H.value.traverseApply(Z[W],X),X),X.failFast&&X.currentErrorCount>_)return!1}}if(this.undeclared==="reject"&&!this.declaresKey(W)){if(Y==="Allows")return!1;if(X.errorFromNodeContext({code:"predicate",expected:"removed",actual:"",relativePath:[W],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&&I.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",kQ(this))}structuralMorphRef=this.structuralMorph&&T0(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(["),bQ(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 w0.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=I.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(I.intrinsic.string)){Y.additionalProperties=_;continue}for(let G of X.signature.branches){if(!G.extends(I.intrinsic.string)){Y=Z.fallback.symbolKey({code:"symbolKey",base:Y,key:null,value:_,optional:!1});continue}let $={type:"string"};if(G.hasKind("morph"))$=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:W}=G.inner;if(W){let H=Object.assign($,{pattern:W[0].rule});for(let Q=1;Q<W.length;Q++)$=Z.fallback.patternIntersection({code:"patternIntersection",base:H,pattern:W[Q].rule});Y.patternProperties??={},Y.patternProperties[H.pattern]=_}}}if(this.undeclared&&!Y.additionalProperties)Y.additionalProperties=!1;return Y}}var HZ={},hQ=(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+=u.nonNegativeIntegerString.id;else for(let X=0;X<Y.sequence.tuple.length;X++)Z+=X+" | ";Z+=")"}return Z},kQ=(Y)=>{let Z=hQ(Y);if(!Z)return;if(HZ[Z])return HZ[Z];let X=(_,G)=>{for(let $=0;$<Y.defaultable.length;$++)if(!(Y.defaultable[$].key in _))Y.defaultable[$].defaultValueMorph(_,G);if(Y.sequence?.defaultables)for(let $=_.length-Y.sequence.prefixLength;$<Y.sequence.defaultables.length;$++)Y.sequence.defaultValueMorphs[$](_,G);if(Y.undeclared==="delete"){for(let $ in _)if(!Y.declaresKey($))delete _[$]}return _};return HZ[Z]=X},bQ=(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 $=0;$<Z.defaultable.length;$++){let{serializedKey:W,defaultValueMorphRef:H}=Z.defaultable[$];G.if(`!(${W} in data)`,(Q)=>Q.line(`${H}${_}`))}if(Z.sequence?.defaultables)G.for(`i < ${Z.sequence.defaultables.length}`,($)=>$.set("data[i]",5),`data.length - ${Z.sequence.prefixLength}`);if(Z.undeclared==="delete")G.forIn("data",($)=>$.if(`!(${Z._compileDeclaresKey($)})`,(W)=>W.line("delete data[k]")));return G.return("data")})},JZ={implementation:fQ,Node:r_},yQ=(Y)=>{if(y(Y,"root")&&Y.hasKind("unit"))Y=Y.unit;if(typeof Y==="number")Y=`${Y}`;return Y},gQ=(Y,Z)=>`${Y} is not allowed as an array index on ${Z}. Use the 'nonNegativeIntegerString' keyword instead.`,Z6=(Y,Z,X)=>{let[_,G]=MX(Y.branches,(W)=>W.hasKind("unit"));if(!_.length)return{index:X.node("index",{signature:Y,value:Z})};let $={};for(let W of _){let H=X.node("required",{key:W.unit,value:Z});$[H.kind]=Z0($[H.kind],H)}if(G.length)$.index=X.node("index",{signature:G,value:Z});return $},pQ=(Y)=>y(Y,"root")?Y.expression:i(Y),i_=(Y,Z)=>`Key${Z.length===1?"":"s"} ${Z.map(pQ).join(", ")} ${Z.length===1?"does":"do"} not exist on ${Y}`;var G2={...A_,alias:s2.implementation,domain:Y6.implementation,unit:XZ.implementation,proto:t2.implementation,union:ZZ.implementation,morph:eY.implementation,intersection:aY.implementation,divisor:yY.implementation,pattern:oY.implementation,predicate:bY.implementation,required:GZ.implementation,optional:i2.implementation,index:_Z.implementation,sequence:$Z.implementation,structure:JZ.implementation};I.defaultConfig=CX(Object.assign(o(G2,(Y,Z)=>[Y,Z.defaults]),{jitless:xX(),clone:PX,onUndeclaredKey:"ignore",exactOptionalPropertyTypes:!0,numberAllowsNaN:!1,dateAllowsInvalid:!1,onFail:null,keywords:{},toJsonSchema:w0.defaultConfig}));I.resolvedConfig=p2(I.defaultConfig,I.config);var B_={...R_,alias:s2.Node,domain:Y6.Node,unit:XZ.Node,proto:t2.Node,union:ZZ.Node,morph:eY.Node,intersection:aY.Node,divisor:yY.Node,pattern:oY.Node,predicate:bY.Node,required:GZ.Node,optional:i2.Node,index:_Z.Node,sequence:$Z.Node,structure:JZ.Node};class H2 extends MY{get[Y1](){return"module"}}var QZ=(Y,Z)=>new H2(o(Y,(X,_)=>[X,y(_,"module")?QZ(_,Z):Z.bindReference(_)]));var mQ=(Y)=>U0(Y)?Y:("branches"in Y)&&U0(Y.branches)?Y.branches:void 0,uQ=(Y,Z)=>A(`Node of kind ${Z} is not valid as a ${Y} definition`),s_=(Y)=>`#${Y} duplicates public alias ${Y}`,zZ={};I.ambient??={};var t_,e_="function $",dQ=(Y)=>YG(Y,ZG(Y)),YG=(Y,Z)=>{let X=Z.write(e_,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}},ZG=(Y)=>new d8().return(Y.reduce((Z,X)=>{let _=new g2({kind:"Allows"}).indent();X.compile(_);let G=_.write(`${X.id}Allows`),$=new g2({kind:"Apply"}).indent();X.compile($);let W=$.write(`${X.id}Apply`),H=`${Z}${G},
44
44
  ${W},
45
- `;if(!X.hasKind("union"))return H;let Q=new d2({kind:"Allows",optimistic:!0}).indent();X.compile(Q);let J=Q.write(`${X.id}Optimistic`);return`${H}${J},
45
+ `;if(!X.hasKind("union"))return H;let Q=new g2({kind:"Allows",optimistic:!0}).indent();X.compile(Q);let J=Q.write(`${X.id}Optimistic`);return`${H}${J},
46
46
  `},`{
47
- `)+"}");class X6{config;resolvedConfig;name;get[Y1](){return"scope"}referencesById={};references=[];resolutions={};exportedNames=[];aliases={};resolved=!1;nodesByHash={};intrinsic;constructor(Z,Y){if(this.config=c2(I.config,Y),this.resolvedConfig=c2(I.resolvedConfig,Y),this.name=this.resolvedConfig.name??`anonymousScope${Object.keys(V5).length}`,this.name in V5)A(`A Scope already named ${this.name} already exists`);V5[this.name]=this;let X=Object.entries(Z).map((G)=>this.preparseOwnAliasEntry(...G));for(let[G,_]of X){let $=G;if(G[0]==="#"){if($=G.slice(1),$ in this.aliases)A($9($));this.aliases[$]=_}else{if($ in this.aliases)A($9(G));this.aliases[$]=_,this.exportedNames.push($)}if(!y(_,"module")&&!y(_,"generic")&&!L4(_)){let W=this.preparseOwnDefinitionFormat(_,{alias:$});this.resolutions[$]=y(W,"root")?this.bindReference(W):this.createParseContext(W).id}}W9??=this.node("union",{branches:["string","number","object","bigint","symbol",{unit:!0},{unit:!1},{unit:void 0},{unit:null}]},{prereduced:!0}),this.nodesByHash[W9.hash]=this.node("intersection",{},{prereduced:!0}),this.intrinsic=I.intrinsic?i(I.intrinsic,(G,_)=>G.startsWith("json")?[]:[G,this.bindReference(_)]):{}}cacheGetter(Z,Y){return Object.defineProperty(this,Z,{value:Y}),Y}get internal(){return this}_json;get json(){if(!this._json)this.export();return this._json}defineSchema(Z){return Z}generic=(...Z)=>{let Y=this;return(X,G)=>new A4(Z,G?new n8(X):X,Y,Y,G??null)};units=(Z,Y)=>{let X=[];for(let _ of Z)if(!X.includes(_))X.push(_);let G=X.map((_)=>this.node("unit",{unit:_},Y));return this.node("union",G,{...Y,prereduced:!0})};lazyResolutions=[];lazilyResolve(Z,Y){let X=this.node("alias",{reference:Y??"synthetic",resolve:Z},{prereduced:!0});if(!this.resolved)this.lazyResolutions.push(X);return X}schema=(Z,Y)=>this.finalize(this.parseSchema(Z,Y));parseSchema=(Z,Y)=>this.node(n2(Z),Z,Y);preparseNode(Z,Y,X){let G=typeof Z==="string"?Z:n2(Y,Z);if(O0(Y)&&Y.kind===G)return Y;if(G==="alias"&&!X?.prereduced){let{reference:W}=Z8.implementation.normalize(Y,this);if(W.startsWith("$")){let H=this.resolveRoot(W.slice(1));Y=H,G=H.kind}}else if(G==="union"&&H1(Y,"object")){let W=tQ(Y);if(W?.length===1)Y=W[0],G=n2(Y)}if(O0(Y)&&Y.kind===G)return Y;let $=W2[G].normalize?.(Y,this)??Y;if(O0($))return $.kind===G?$:eQ(G,$.kind);return{...X,$:this,kind:G,def:$,prefix:X.alias??G}}bindReference(Z){let Y;if(O0(Z))Y=Z.$===this?Z:new Z.constructor(Z.attachments,this);else Y=Z.$===this?Z:new A4(Z.params,Z.bodyDef,Z.$,this,Z.hkt);if(!this.resolved)Object.assign(this.referencesById,Y.referencesById);return Y}resolveRoot(Z){return this.maybeResolveRoot(Z)??A(R5(Z))}maybeResolveRoot(Z){let Y=this.maybeResolve(Z);if(y(Y,"generic"))return;return Y}maybeResolveSubalias(Z){return M5(this.aliases,Z)??M5(this.ambient,Z)}get ambient(){return I.ambient}maybeResolve(Z){let Y=this.resolutions[Z];if(Y){if(typeof Y!=="string")return this.bindReference(Y);let G=X1[Y];if(y(G,"root"))return this.resolutions[Z]=G;if(y(G,"context")){if(G.phase==="resolving")return this.node("alias",{reference:`$${Z}`},{prereduced:!0});if(G.phase==="resolved")return G0(`Unexpected resolved context for was uncached by its scope: ${o(G)}`);G.phase="resolving";let _=this.bindReference(this.parseOwnDefinitionFormat(G.def,G));return G.phase="resolved",X1[_.id]=_,X1[G.id]=_,this.resolutions[Z]=_}return G0(`Unexpected nodesById entry for ${Y}: ${o(G)}`)}let X=this.aliases[Z]??this.ambient?.[Z];if(!X)return this.maybeResolveSubalias(Z);if(X=this.normalizeRootScopeValue(X),y(X,"generic"))return this.resolutions[Z]=this.bindReference(X);if(y(X,"module")){if(!X.root)A(E9(Z));return this.resolutions[Z]=this.bindReference(X.root)}return this.resolutions[Z]=this.parse(X,{alias:Z})}createParseContext(Z){let Y=Z.id??Z5(Z.prefix);return X1[Y]=Object.assign(Z,{[Y1]:"context",$:this,id:Y,phase:"unresolved"})}traversal(Z){return new k1(Z,this.resolvedConfig)}import(...Z){return new Q2(i(this.export(...Z),(Y,X)=>[`#${Y}`,X]))}precompilation;_exportedResolutions;_exports;export(...Z){if(!this._exports){this._exports={};for(let X of this.exportedNames){let G=this.aliases[X];this._exports[X]=y(G,"module")?O5(G,this):H9(this.maybeResolve(X))}for(let X of this.lazyResolutions)X.resolution;if(this._exportedResolutions=F9(this,this._exports),this._json=U9(this._exportedResolutions),Object.assign(this.resolutions,this._exportedResolutions),this.references=Object.values(this.referencesById),!this.resolvedConfig.jitless){let X=z9(this.references);this.precompilation=X.write(J9,4),Q9(this.references,X)}this.resolved=!0}let Y=Z.length?Z:this.exportedNames;return new Q2(i(Y,(X,G)=>[G,this._exports[G]]))}resolve(Z){return this.export()[Z]}node=(Z,Y,X={})=>{let G=this.preparseNode(Z,Y,X);if(O0(G))return this.bindReference(G);let _=this.createParseContext(G),$=Y5(_),W=this.bindReference($);return X1[_.id]=W};parse=(Z,Y={})=>this.finalize(this.parseDefinition(Z,Y));parseDefinition(Z,Y={}){if(y(Z,"root"))return this.bindReference(Z);let X=this.preparseOwnDefinitionFormat(Z,Y);if(y(X,"root"))return this.bindReference(X);let G=this.createParseContext(X);X1[G.id]=G;let _=this.bindReference(this.parseOwnDefinitionFormat(Z,G));if(_.isCyclic)_=xG(_,G.id);return X1[G.id]=_,_}finalize(Z){if(H9(Z),!Z.precompilation&&!this.resolvedConfig.jitless)Zz(Z.references);return Z}}class A5 extends X6{parseOwnDefinitionFormat(Z,Y){return Y5(Y)}preparseOwnDefinitionFormat(Z,Y){return this.preparseNode(n2(Z),Z,Y)}preparseOwnAliasEntry(Z,Y){return[Z,Y]}normalizeRootScopeValue(Z){return Z}}var H9=(Z)=>{let Y=Z.references.filter((X)=>X.hasKind("alias"));for(let X of Y){Object.assign(X.referencesById,X.resolution.referencesById);for(let G of Z.references)if(X.id in G.referencesById)Object.assign(G.referencesById,X.referencesById)}return Z},U9=(Z)=>i(Z,(Y,X)=>[Y,y(X,"root")||y(X,"generic")?X.json:y(X,"module")?U9(X):G0(`Unexpected resolution ${o(X)}`)]),M5=(Z,Y)=>{let X=Y.indexOf(".");if(X===-1)return;let G=Y.slice(0,X),_=Z[G];if(_===void 0)return;if(!y(_,"module"))return A(Yz(G));let $=Y.slice(X+1),W=_[$];if(W===void 0)return M5(_,$);if(y(W,"root")||y(W,"generic"))return W;if(y(W,"module"))return W.root??A(E9(Y));G0(`Unexpected resolution for alias '${Y}': ${o(W)}`)},G6=(Z,Y)=>new A5(Z,Y),G8=new A5({});var F9=(Z,Y)=>{let X={};for(let G in Y){let _=Y[G];if(y(_,"module")){let $=F9(Z,_),W=i($,(H,Q)=>[`${G}.${H}`,Q]);Object.assign(X,W)}else if(y(_,"root")||y(_,"generic"))X[G]=_;else G0(`Unexpected scope resolution ${o(_)}`)}return X},R5=(Z)=>`'${Z}' is unresolvable`,Yz=(Z)=>`'${Z}' must reference a module to be accessed using dot syntax`,E9=(Z)=>`Reference to submodule '${Z}' must specify an alias`;G8.export();var{schema:H0,node:z2,defineSchema:xR,generic:T1}=G8;var N5="^(?:0|[1-9]\\d*)$",Xz=new RegExp(N5),kR=C0(Xz);var L9=G6({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();I.intrinsic={...L9};var D9=G6({integer:{domain:"number",divisor:1},lengthBoundable:["string",Array],key:["string","symbol"],nonNegativeIntegerString:{domain:"string",pattern:N5}},{prereducedAliases:!0}).export();Object.assign(I.intrinsic,D9);var Gz=G6({jsonPrimitive:["string","number",{unit:!0},{unit:!1},{unit:null}],jsonObject:{domain:"object",index:{signature:"string",value:"$jsonData"}},jsonData:["$jsonPrimitive","$jsonObject"]},{prereducedAliases:!0}).export(),u={...L9,...D9,...Gz,emptyStructure:z2("structure",{},{prereduced:!0})};I.intrinsic={...u};var V9=(Z)=>typeof Z==="string"&&Z[0]==="d"&&(Z[1]==="'"||Z[1]==='"')&&Z.at(-1)===Z[1],O9=(Z)=>Z.toString()!=="Invalid Date",M9=(Z)=>Z.slice(2,-1),w5=(Z)=>`'${Z}' could not be parsed by the Date constructor`,A9=(Z,Y)=>_z(Z,Y),_z=(Z,Y)=>{let X=new Date(Z);if(O9(X))return X;let G=aX(Z);if(G!==void 0){let _=new Date(G);if(O9(_))return _}return Y?A(Y===!0?w5(Z):Y):void 0};var I5=(Z,Y)=>{let X=Z.scanner.shiftUntil($z[N9[Y]]);if(Z.scanner.lookahead==="")return Z.error(Hz(X,Y));if(Z.scanner.shift(),Y==="/"){try{new RegExp(X)}catch(G){A(String(G))}Z.root=Z.ctx.$.node("intersection",{domain:"string",pattern:X},{prereduced:!0})}else if(g0(Y,B5))Z.root=Z.ctx.$.node("unit",{unit:X});else{let G=A9(X,w5(X));Z.root=Z.ctx.$.node("unit",{meta:X,unit:G})}},B5={"'":1,'"':1},R9={"/":1,"'":1,'"':1},N9={"d'":"'",'d"':'"',"'":"'",'"':'"',"/":"/"},$z={"'":(Z)=>Z.lookahead==="'",'"':(Z)=>Z.lookahead==='"',"/":(Z)=>Z.lookahead==="/"},Wz={'"':"double-quote","'":"single-quote","/":"forward slash"},Hz=(Z,Y)=>`${Y}${Z} requires a closing ${Wz[N9[Y]]}`;var w9=(Z)=>`Private type references should not include '#'. Use '${Z}' instead.`,_6="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 I9={">":!0,">=":!0},B9={"<":!0,"<=":!0};var U2={"<":">",">":"<","<=":">=",">=":"<=","==":"=="},K9=(Z)=>`Unmatched )${Z===""?"":` before ${Z}`}`,W6=(Z)=>`Missing ${Z}`,C9=(Z,Y)=>`Left bounds are only valid when paired with right bounds (try ...${Y}${Z})`,H6=(Z)=>`Left-bounded expressions must specify their limits using < or <= (was ${Z})`,T9=(Z,Y,X,G)=>`An expression may have at most one left bound (parsed ${Z}${U2[Y]}, ${X}${U2[G]})`;var q9=(Z,Y,X)=>j9(Z,Y,X,[]),j9=(Z,Y,X,G)=>{let _=X.parseUntilFinalizer();if(G.push(_.root),_.finalizer===">"){if(G.length!==Y.params.length)return X.error(K5(Z,Y.names,G.map(($)=>$.expression)));return G}if(_.finalizer===",")return j9(Z,Y,X,G);return _.error(W6(">"))},K5=(Z,Y,X)=>`${Z}<${Y.join(", ")}> requires exactly ${Y.length} args (got ${X.length}${X.length===0?"":`: ${X.join(", ")}`})`;var C5=(Z)=>{let Y=Z.scanner.shiftUntilNextTerminator();if(Y==="keyof")Z.addPrefix("keyof");else Z.root=Qz(Z,Y)},Jz=(Z,Y,X)=>{if(X.scanner.shiftUntilNonWhitespace(),X.scanner.shift()!=="<")return X.error(K5(Z,Y.names,[]));let _=q9(Z,Y,X);return Y(..._)},Qz=(Z,Y)=>zz(Z,Y)??Uz(Z,Y)??Z.error(Y===""?Z.scanner.lookahead==="#"?w9(Z.shiftedByOne().scanner.shiftUntilNextTerminator()):T5(Z):R5(Y)),zz=(Z,Y)=>{if(Z.ctx.args?.[Y]){let G=Z.ctx.args[Y];if(typeof G!=="string")return G;return Z.ctx.$.node("alias",{reference:G},{prereduced:!0})}let X=Z.ctx.$.maybeResolve(Y);if(y(X,"root"))return X;if(X===void 0)return;if(y(X,"generic"))return Jz(Y,X,Z);return A(`Unexpected resolution ${o(X)}`)},Uz=(Z,Y)=>{let X=tX(Y);if(X!==void 0)return Z.ctx.$.node("unit",{unit:X});let G=ZG(Y);if(G!==void 0)return Z.ctx.$.node("unit",{unit:G})},T5=(Z)=>{let Y=Z.previousOperator();return Y?q5(Y,Z.scanner.unscanned):Fz(Z.scanner.unscanned)},q5=(Z,Y="")=>`Token '${Z}' requires a right operand${Y?` before '${Y}'`:""}`,Fz=(Z)=>`Expected an expression${Z?` before '${Z}'`:""}`;var j5=(Z)=>Z.scanner.lookahead===""?Z.error(T5(Z)):Z.scanner.lookahead==="("?Z.shiftedByOne().reduceGroupOpen():Z.scanner.lookaheadIsIn(R9)?I5(Z,Z.scanner.shift()):Z.scanner.lookaheadIsIn(D4)?j5(Z.shiftedByOne()):Z.scanner.lookahead==="d"?Z.scanner.nextLookahead in B5?I5(Z,`${Z.scanner.shift()}${Z.scanner.shift()}`):C5(Z):C5(Z);class _4 extends fZ{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,...D4};static finalizingLookaheads={">":1,",":1,"":1,"=":1,"?":1};static lookaheadIsFinalizing=(Z,Y)=>Z===">"?Y[0]==="="?Y[1]==="=":Y.trimStart()===""||g0(Y.trimStart()[0],_4.terminatingChars):Z==="="?Y[0]!=="=":Z===","||Z==="?"}var S9=(Z,Y)=>{let X=Ez(Z,Y);if(Z.root.hasKind("unit")){if(typeof Z.root.unit==="number"){Z.reduceLeftBound(Z.root.unit,X),Z.unsetRoot();return}if(Z.root.unit instanceof Date){let G=`d'${Z.root.description??Z.root.unit.toISOString()}'`;Z.unsetRoot(),Z.reduceLeftBound(G,X);return}}return Dz(Z,X)},v9={"<":1,">":1,"=":1},Ez=(Z,Y)=>Z.scanner.lookaheadIs("=")?`${Y}${Z.scanner.shift()}`:Y;var P9=(Z,Y,X,G)=>{if(X.extends(I.intrinsic.number)){if(typeof Y!=="number")return A(P5(Z,Y,G));return Z==="=="?["min","max"]:Z[0]===">"?["min"]:["max"]}if(X.extends(I.intrinsic.lengthBoundable)){if(typeof Y!=="number")return A(P5(Z,Y,G));return Z==="=="?["exactLength"]:Z[0]===">"?["minLength"]:["maxLength"]}if(X.extends(I.intrinsic.Date))return Z==="=="?["after","before"]:Z[0]===">"?["after"]:["before"];return A(RG(X.expression))},Lz=(Z)=>({rule:V9(Z.limit)?M9(Z.limit):Z.limit,exclusive:Z.comparator.length===1}),Dz=(Z,Y)=>{let X=Z.unsetRoot(),G=Z.scanner.location;Z.parseOperand();let _=Z.unsetRoot(),$=Z.scanner.sliceChars(G,Z.scanner.location);if(Z.root=X,!_.hasKind("unit")||typeof _.unit!=="number"&&!(_.unit instanceof Date))return Z.error(P5(Y,$,"right"));let W=_.unit,H=Y.length===1,Q=P9(Y,typeof W==="number"?W:$,X,"right");for(let z of Q)Z.constrainRoot(z,Y==="=="?{rule:W}:{rule:W,exclusive:H});if(!Z.branches.leftBound)return;if(!g0(Y,B9))return Z.error(H6(Y));let J=P9(Z.branches.leftBound.comparator,Z.branches.leftBound.limit,X,"left");Z.constrainRoot(J[0],Lz(Z.branches.leftBound)),Z.branches.leftBound=null},P5=(Z,Y,X)=>`Comparator ${X==="left"?U2[Z]:Z} must be ${X==="left"?"preceded":"followed"} by a corresponding literal (was ${Y})`;var x9=(Z)=>{Z.scanner.shiftUntilNonWhitespace();let Y=Z.scanner.shiftUntilNextTerminator();Z.root=Z.root.brand(Y)};var h9=(Z)=>{let Y=Z.scanner.shiftUntilNextTerminator(),X=eX(Y,{errorOnFail:f9(Y)});if(X===0)Z.error(f9(0));Z.root=Z.root.constrain("divisor",X)},f9=(Z)=>`% operator must be followed by a non-zero integer literal (was ${Z})`;var S5=(Z)=>{let Y=Z.scanner.shift();return Y===""?Z.finalize(""):Y==="["?Z.scanner.shift()==="]"?Z.setRoot(Z.root.array()):Z.error(Oz):Y==="|"?Z.scanner.lookahead===">"?Z.shiftedByOne().pushRootToBranch("|>"):Z.pushRootToBranch(Y):Y==="&"?Z.pushRootToBranch(Y):Y===")"?Z.finalizeGroup():_4.lookaheadIsFinalizing(Y,Z.scanner.unscanned)?Z.finalize(Y):g0(Y,v9)?S9(Z,Y):Y==="%"?h9(Z):Y==="#"?x9(Z):(Y in D4)?S5(Z):Z.error(J6(Y))},J6=(Z,Y="")=>`'${Z}' is not allowed here${Y&&` (should be ${Y})`}`,Oz="Missing expected ']'";var k9=(Z)=>{let Y=Z.unsetRoot();Z.parseOperand();let X=Z.unsetRoot();if(!X.hasKind("unit"))return Z.error(Vz(X.expression));let G=X.unit instanceof Date?()=>new Date(X.unit):X.unit;return[Y,"=",G]},Vz=(Z)=>`Default value '${Z}' must a literal value`;var v5=(Z,Y)=>{let X=Y.$.maybeResolveRoot(Z);if(X)return X;if(Z.endsWith("[]")){let $=Y.$.maybeResolveRoot(Z.slice(0,-2));if($)return $.array()}let G=new F2(new _4(Z),Y),_=Mz(G);if(G.finalizer===">")A(J6(">"));return _},Mz=(Z)=>{Z.parseOperand();let Y=_8(Z).root;if(!Y)return G0(`Root was unexpectedly unset after parsing string '${Z.scanner.scanned}'`);if(Z.finalizer==="=")Y=k9(Z);else if(Z.finalizer==="?")Y=[Y,"?"];if(Z.scanner.shiftUntilNonWhitespace(),Z.scanner.lookahead)A(J6(Z.scanner.lookahead));return Y},_8=(Z)=>{while(Z.finalizer===void 0)Az(Z);return Z},Az=(Z)=>Z.hasRoot()?Z.parseOperator():Z.parseOperand();class F2{root;branches={prefixes:[],leftBound:null,intersection:null,union:null,pipe:null};finalizer;groups=[];scanner;ctx;constructor(Z,Y){this.scanner=Z,this.ctx=Y}error(Z){return A(Z)}hasRoot(){return this.root!==void 0}setRoot(Z){this.root=Z}unsetRoot(){let Z=this.root;return this.root=void 0,Z}constrainRoot(...Z){this.root=this.root.constrain(Z[0],Z[1])}finalize(Z){if(this.groups.length)return this.error(W6(")"));this.finalizeBranches(),this.finalizer=Z}reduceLeftBound(Z,Y){let X=U2[Y];if(!g0(X,I9))return this.error(H6(Y));if(this.branches.leftBound)return this.error(T9(this.branches.leftBound.limit,this.branches.leftBound.comparator,Z,X));this.branches.leftBound={comparator:X,limit:Z}}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 Z=this.groups.pop();if(!Z)return this.error(K9(this.scanner.unscanned));this.branches=Z}addPrefix(Z){this.branches.prefixes.push(Z)}applyPrefixes(){while(this.branches.prefixes.length){let Z=this.branches.prefixes.pop();this.root=Z==="keyof"?this.root.keyof():G0(`Unexpected prefix '${Z}'`)}}pushRootToBranch(Z){this.assertRangeUnset(),this.applyPrefixes();let Y=this.root;if(this.root=void 0,this.branches.intersection=this.branches.intersection?.rawAnd(Y)??Y,Z==="&")return;if(this.branches.union=this.branches.union?.rawOr(this.branches.intersection)??this.branches.intersection,this.branches.intersection=null,Z==="|")return;this.branches.pipe=this.branches.pipe?.rawPipeOnce(this.branches.union)??this.branches.union,this.branches.union=null}parseUntilFinalizer(){return _8(new F2(this.scanner,this.ctx))}parseOperator(){return S5(this)}parseOperand(){return j5(this)}assertRangeUnset(){if(this.branches.leftBound)return this.error(C9(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 Rz="An empty string is not a valid generic parameter name",Q6=(Z,Y,X)=>{Z.shiftUntilNonWhitespace();let G=Z.shiftUntilNextTerminator();if(G===""){if(Z.lookahead===""&&Y.length)return Y;return A(Rz)}return Z.shiftUntilNonWhitespace(),Nz(Z,G,Y,X)},b9="extends ",Nz=(Z,Y,X,G)=>{if(Z.shiftUntilNonWhitespace(),Z.unscanned.startsWith(b9))Z.jumpForward(b9.length);else{if(Z.lookahead===",")Z.shift();return X.push(Y),Q6(Z,X,G)}let _=_8(new F2(Z,G));return X.push([Y,_.root]),Q6(Z,X,G)};class x5 extends h1{$;constructor(Z){super((...Y)=>new $8(Z)(...Y),{bind:Z});this.$=Z}in(Z){return new $8(this.$,Z===void 0?void 0:this.$.parse(Z))}at(Z,Y){return new $8(this.$).at(Z,Y)}case(Z,Y){return new $8(this.$).case(Z,Y)}}class $8 extends h1{$;in;key;branches=[];constructor(Z,Y){super((X)=>this.caseEntries(Object.entries(X).map(([G,_])=>G==="default"?[G,_]:[this.$.parse(G),_])));this.$=Z,this.in=Y}at(Z,Y){if(this.key)A(Iz);if(this.branches.length)A(wz);return this.key=Z,Y?this.match(Y):this}case(Z,Y){return this.caseEntry(this.$.parse(Z),Y)}caseEntry(Z,Y){let G=(this.key?this.$.parse({[this.key]:Z}):Z).pipe(Y);return this.branches.push(G),this}match(Z){return this(Z)}strings(Z){return this.caseEntries(Object.entries(Z).map(([Y,X])=>Y==="default"?[Y,X]:[this.$.node("unit",{unit:Y}),X]))}caseEntries(Z){for(let Y=0;Y<Z.length;Y++){let[X,G]=Z[Y];if(X==="default"){if(Y!==Z.length-1)A("default may only be specified as the last key of a switch definition");return this.default(G)}if(typeof G!=="function")return A(`Value for case "${X}" must be a function (was ${y0(G)})`);this.caseEntry(X,G)}return this}default(Z){if(typeof Z==="function")this.case(u.unknown,Z);let Y={branches:this.branches,ordered:!0};if(Z==="never"||Z==="assert")Y.meta={onFail:y9};let X=this.$.node("union",Y);if(!this.in)return this.$.finalize(X);let G=this.in.pipe(X);if(Z==="never"||Z==="assert")G=G.configureReferences({onFail:y9},"self");return this.$.finalize(G)}}var y9=(Z)=>Z.throw(),wz="A key matcher must be specified before the first case i.e. match.at('foo') or match.in<object>().at('bar')",Iz="At most one key matcher may be specified per expression";var z6=(Z,Y)=>{if(U0(Z)){if(Z[1]==="=")return[Y.$.parseOwnDefinitionFormat(Z[0],Y),"=",Z[2]];if(Z[1]==="?")return[Y.$.parseOwnDefinitionFormat(Z[0],Y),"?"]}return U6(Z,Y)},g9="Only required keys may make their values optional, e.g. { [mySymbol]: ['number', '?'] }",p9="Only required keys may specify default values, e.g. { value: 'number = 0' }";var m9=(Z,Y)=>{let X,G={},_=S4(Z);for(let[W,H]of _){let Q=Cz(W);if(Q.kind==="spread"){if(!l1(G))return A(Kz);let V=Y.$.parseOwnDefinitionFormat(H,Y);if(V.equals(u.object))continue;if(!V.hasKind("intersection")||!V.basis?.equals(u.object))return A(Tz(V.expression));X=V.structure;continue}if(Q.kind==="undeclared"){if(H!=="reject"&&H!=="delete"&&H!=="ignore")A(Bz(H));G.undeclared=H;continue}let J=z6(H,Y),z=Q;if(Q.kind==="required"){if(!U0(J))f5(G,"required",{key:Q.normalized,value:J},Y);else f5(G,"optional",J[1]==="="?{key:Q.normalized,value:J[0],default:J[2]}:{key:Q.normalized,value:J[0]},Y);continue}if(U0(J)){if(J[1]==="?")A(g9);if(J[1]==="=")A(p9)}if(Q.kind==="optional"){f5(G,"optional",{key:Q.normalized,value:J},Y);continue}let U=Y.$.parseOwnDefinitionFormat(z.normalized,Y),D=Y6(U,J,Y.$);if(D.index)G.index=Y0(G.index,D.index);if(D.required)G.required=Y0(G.required,D.required)}let $=Y.$.node("structure",G);return Y.$.parseSchema({domain:"object",structure:X?.merge($)??$})},f5=(Z,Y,X,G)=>{Z[Y]=Y0(Z[Y],G.$.node(Y,X))},Bz=(Z)=>`Value of '+' key must be 'reject', 'delete', or 'ignore' (was ${o(Z)})`,Kz="Spread operator may only be used as the first key in an object",Cz=(Z)=>typeof Z==="symbol"?{kind:"required",normalized:Z}:Z.at(-1)==="?"?Z.at(-2)===b2?{kind:"required",normalized:`${Z.slice(0,-2)}?`}:{kind:"optional",normalized:Z.slice(0,-1)}:Z[0]==="["&&Z.at(-1)==="]"?{kind:"index",normalized:Z.slice(1,-1)}:Z[0]===b2&&Z[1]==="["&&Z.at(-1)==="]"?{kind:"required",normalized:Z.slice(1)}:Z==="..."?{kind:"spread"}:Z==="+"?{kind:"undeclared"}:{kind:"required",normalized:Z==="\\..."?"...":Z==="\\+"?"+":Z},Tz=(Z)=>`Spread operand must resolve to an object literal type (was ${Z})`;var d9=(Z,Y)=>bz(Z)?o9[Z[0]](Z,Y):hz(Z)?i9[Z[1]](Z,Y):null,qz=(Z,Y)=>Y.$.parseOwnDefinitionFormat(Z[1],Y).keyof(),h5=(Z,Y)=>{if(Z[2]===void 0)return A(q5(Z[1],""));let X=Y.$.parseOwnDefinitionFormat(Z[0],Y),G=Y.$.parseOwnDefinitionFormat(Z[2],Y);if(Z[1]==="|")return Y.$.node("union",{branches:[X,G]});let _=Z[1]==="&"?U1(X,G,Y.$):o2(X,G,Y.$);if(_ instanceof S)return _.throw();return _},jz=(Z,Y)=>Y.$.parseOwnDefinitionFormat(Z[0],Y).array(),Pz=(Z,Y)=>{if(typeof Z[2]!=="function")return A(c9("=>",Z[2]));return Y.$.parseOwnDefinitionFormat(Z[0],Y).pipe(Z[2])},c9=(Z,Y)=>`${Z===":"?"Narrow":"Morph"} expression requires a function following '${Z}' (was ${typeof Y})`,Sz=(Z,Y)=>{if(typeof Z[2]!=="function")return A(c9(":",Z[2]));return Y.$.parseOwnDefinitionFormat(Z[0],Y).constrain("predicate",Z[2])},vz=(Z,Y)=>Y.$.parseOwnDefinitionFormat(Z[0],Y).configureReferences(Z[2],"shallow"),l9=(Z)=>Z,xz=l9({"[]":jz,"?":()=>A(_6)}),fz=l9({"|":h5,"&":h5,":":Sz,"=>":Pz,"|>":h5,"@":vz,"=":()=>A($6)}),i9={...xz,...fz},hz=(Z)=>i9[Z[1]]!==void 0,kz=(Z)=>Z,o9=kz({keyof:qz,instanceof:(Z,Y)=>{if(typeof Z[1]!=="function")return A(u9(h2(Z[1])));let X=Z.slice(1).map((G)=>typeof G==="function"?Y.$.node("proto",{proto:G}):A(u9(h2(G))));return X.length===1?X[0]:Y.$.node("union",{branches:X})},"===":(Z,Y)=>Y.$.units(Z.slice(1))}),bz=(Z)=>o9[Z[0]]!==void 0,u9=(Z)=>`Expected a constructor following 'instanceof' operator (was ${Z})`;var s9=(Z,Y)=>{let X=[{}],G=0;while(G<Z.length){let _=!1;if(Z[G]==="..."&&G<Z.length-1)_=!0,G++;let $=z6(Z[G],Y),[W,H,Q]=!U0($)?[$]:$;if(G++,_){if(!W.extends(I.intrinsic.Array))return A(pz(W.expression));X=X.flatMap((J)=>W.distribute((z)=>gz(c8(J),z)))}else X=X.map((J)=>{if(H==="?")return a9(J,W);if(H==="=")return yz(J,W,Q);return k5(J,W)})}return Y.$.parseSchema(X.map((_)=>l1(_)?{proto:Array,exactLength:0}:{proto:Array,sequence:_}))},k5=(Z,Y)=>{if(Z.defaultables||Z.optionals)return A(Z.variadic?E5:mz);if(Z.variadic)Z.postfix=Y0(Z.postfix,Y);else Z.prefix=Y0(Z.prefix,Y);return Z},a9=(Z,Y)=>{if(Z.variadic)return A(t9);return Z.optionals=Y0(Z.optionals,Y),Z},yz=(Z,Y,X)=>{if(Z.variadic)return A(t9);if(Z.optionals)return A(uz);return Z.defaultables=Y0(Z.defaultables,[[Y,X]]),Z},n9=(Z,Y)=>{if(Z.postfix)A(r9);if(Z.variadic){if(!Z.variadic.equals(Y))A(r9)}else Z.variadic=Y.internal;return Z},gz=(Z,Y)=>{let X=Y.select({method:"find",kind:"sequence"});if(!X)return n9(Z,I.intrinsic.unknown);if(X.prefix)for(let G of X.prefix)k5(Z,G);if(X.optionals)for(let G of X.optionals)a9(Z,G);if(X.variadic)n9(Z,X.variadic);if(X.postfix)for(let G of X.postfix)k5(Z,G);return Z},pz=(Z)=>`Spread element must be an array (was ${Z})`,r9="A tuple may have at most one variadic element",mz="A required element may not follow an optional element",t9="An optional element may not follow a variadic element";var uz="A defaultable element may not follow an optional element without a default";var dz={},U6=(Z,Y)=>{if(typeof Z==="string"){if(Y.args&&Object.keys(Y.args).some((G)=>Z.includes(G)))return v5(Z,Y);let X=dz[Y.$.name]??={};return X[Z]??=v5(Z,Y)}return H1(Z,"object")?cz(Z,Y):A(b5(y0(Z)))},cz=(Z,Y)=>{let X=f2(Z);switch(X){case void 0:if(y(Z,"root"))return Z;return m9(Z,Y);case"Array":return lz(Z,Y);case"RegExp":return Y.$.node("intersection",{domain:"string",pattern:Z},{prereduced:!0});case"Function":{let G=L4(Z)?Z():Z;if(y(G,"root"))return G;return A(b5("Function"))}default:return A(b5(X??o(Z)))}},lz=(Z,Y)=>d9(Z,Y)??s9(Z,Y),b5=(Z)=>`Type definitions must be strings or objects (was ${Z})`;class y5 extends h1{constructor(Z){let Y=Object.assign({errors:Q1,hkt:r0,$:Z,raw:Z.parse,module:Z.constructor.module,scope:Z.constructor.scope,define:Z.define,match:Z.match,generic:Z.generic,schema:Z.schema,keywords:Z.ambient,unit:Z.unit,enumerated:Z.enumerated,instanceOf:Z.instanceOf,valueOf:Z.valueOf,or:Z.or,and:Z.and,merge:Z.merge,pipe:Z.pipe},Z.ambientAttachments);super((...X)=>{if(X.length===1)return Z.parse(X[0]);if(X.length===2&&typeof X[0]==="string"&&X[0][0]==="<"&&X[0].at(-1)===">"){let G=X[0].slice(1,-1),_=Z.parseGenericParams(G,{});return new A4(_,X[1],Z,Z,null)}return Z.parse(X)},{bind:Z,attach:Y})}}var E2=I;class F6 extends X6{get ambientAttachments(){if(!E2.typeAttachments)return;return this.cacheGetter("ambientAttachments",i(E2.typeAttachments,(Z,Y)=>[Z,this.bindReference(Y)]))}preparseOwnAliasEntry(Z,Y){let X=Z.indexOf("<");if(X===-1){if(y(Y,"module")||y(Y,"generic"))return[Z,Y];let $=this.name==="ark"?Z:Z==="root"?this.name:`${this.name}.${Z}`,W=this.resolvedConfig.keywords?.[$];if(W)Y=[Y,"@",W];return[Z,Y]}if(Z.at(-1)!==">")A("'>' must be the last character of a generic declaration in a scope");let G=Z.slice(0,X),_=Z.slice(X+1,-1);return[G,()=>{let $=this.parseGenericParams(_,{alias:G});return VG($,Y,this)}]}parseGenericParams(Z,Y){return Q6(new _4(Z),[],this.createParseContext({...Y,def:Z,prefix:"generic"}))}normalizeRootScopeValue(Z){if(L4(Z)&&!y(Z,"generic"))return Z();return Z}preparseOwnDefinitionFormat(Z,Y){return{...Y,def:Z,prefix:Y.alias??"type"}}parseOwnDefinitionFormat(Z,Y){if(!(Y.alias&&(Y.alias in this.aliases))&&!Y.args)Y.args={this:Y.id};let G=U6(Z,Y);if(U0(G)){if(G[1]==="=")return A($6);if(G[1]==="?")return A(_6)}return G}unit=(Z)=>this.units([Z]);valueOf=(Z)=>this.units(bX(Z));enumerated=(...Z)=>this.units(Z);instanceOf=(Z)=>this.node("proto",{proto:Z},{prereduced:!0});or=(...Z)=>this.schema(Z.map((Y)=>this.parse(Y)));and=(...Z)=>Z.reduce((Y,X)=>Y.and(this.parse(X)),this.intrinsic.unknown);merge=(...Z)=>Z.reduce((Y,X)=>Y.merge(this.parse(X)),this.intrinsic.object);pipe=(...Z)=>this.intrinsic.unknown.pipe(...Z);match=new x5(this);declare=()=>({type:this.type});define(Z){return Z}type=new y5(this);static scope=(Z,Y={})=>new F6(Z,Y);static module=(Z,Y={})=>this.scope(Z,Y).export()}var g5=Object.assign(F6.scope,{define:(Z)=>Z}),e=F6;class e9 extends r0{description='merge an object\'s properties onto another like `Merge(User, { isAdmin: "true" })`'}var iz=T1(["base",u.object],["props",u.object])((Z)=>Z.base.merge(Z.props),e9),Z7=e.module({Key:u.key,Merge:iz});class Y7 extends r0{}var oz=T1("element")((Z)=>{let Y=Z.element.exclude(u.Array),X=Y.array();return Y.rawOr(X).pipe(E4).distribute((G)=>G.assertHasKind("morph").declareOut(X),H0)},Y7),X7=e.module({root:u.Array,readonly:"root",index:u.nonNegativeIntegerString,liftFrom:oz},{name:"Array"});var p5=H0(["string",x4.FileConstructor]),nz=p5.rawOr(p5.array()),G7=H0({meta:"an object representing parsed form data",domain:"object",index:{signature:"string",value:nz}}),_7=e.module({root:["instanceof",FormData],value:p5,parsed:G7,parse:H0({in:FormData,morphs:(Z)=>{let Y={};for(let[X,G]of Z)if(X in Y){let _=Y[X];if(typeof _==="string"||_ instanceof x4.FileConstructor)Y[X]=[_,G];else _.push(G)}else Y[X]=G;return Y},declaredOut:G7})},{name:"FormData"});var $7=e.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 rz={Boolean:1,Number:1,String:1},W7=e.module({...i({...CZ,...qZ},(Z,Y)=>(Z in rz)?[]:[Z,["instanceof",Y]]),Array:X7,TypedArray:$7,FormData:_7});var sz=H0({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"}),az=H0({domain:"number",divisor:1}),E6=e.module({root:u.number,integer:az,epoch:sz,safe:H0({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 w0=(Z,Y,X)=>{let G={domain:"string",pattern:{rule:Z.source,flags:Z.flags,meta:Y}};if(X)G.meta={format:X};return z2("intersection",G)},H7=w0(y2,"a well-formed integer string"),A7=e.module({root:H7,parse:H0({in:H7,morphs:(Z,Y)=>{let X=Number.parseInt(Z);return Number.isSafeInteger(X)?X:Y.error("an integer in the range Number.MIN_SAFE_INTEGER to Number.MAX_SAFE_INTEGER")},declaredOut:u.integer})},{name:"string.integer"}),tz=w0(/^[\dA-Fa-f]+$/,"hex characters only"),ez=e.module({root:w0(/^(?:[\d+/A-Za-z]{4})*(?:[\d+/A-Za-z]{2}==|[\d+/A-Za-z]{3}=)?$/,"base64-encoded"),url:w0(/^(?:[\w-]{4})*(?:[\w-]{2}(?:==|%3D%3D)?|[\w-]{3}(?:=|%3D)?)?$/,"base64url-encoded")},{name:"string.base64"}),J7=w0(/^[A-Z].*$/,"capitalized"),ZU=e.module({root:H0({in:"string",morphs:(Z)=>Z.charAt(0).toUpperCase()+Z.slice(1),declaredOut:J7}),preformatted:J7},{name:"string.capitalize"}),YU=(Z)=>{let Y=Z.replaceAll(/[ -]+/g,""),X=0,G,_,$=!1;for(let W=Y.length-1;W>=0;W--){if(G=Y.substring(W,W+1),_=Number.parseInt(G,10),$)_*=2,X+=_>=10?_%10+1:_;else X+=_;$=!$}return!!(X%10===0?Y:!1)},XU=/^(?: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}))$/,GU=H0({domain:"string",pattern:{meta:"a credit card number",rule:XU.source},predicate:{meta:"a credit card number",predicate:YU}});var _U=/^([+-]?\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 $U=(Z)=>!Number.isNaN(new Date(Z).valueOf()),Q7=H0({domain:"string",predicate:{meta:"a parsable date",predicate:$U}}).assertHasKind("intersection"),z7=A7.root.internal.narrow((Z,Y)=>{let X=Number.parseInt(Z),G=E6.epoch(X);if(G instanceof Q1)return Y.errors.merge(G),!1;return!0}).configure({description:"an integer string representing a safe Unix timestamp"},"self").assertHasKind("intersection"),WU=e.module({root:z7,parse:H0({in:z7,morphs:(Z)=>new Date(Z),declaredOut:u.Date})},{name:"string.date.epoch"}),U7=w0(_U,"an ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) date").internal.assertHasKind("intersection"),HU=e.module({root:U7,parse:H0({in:U7,morphs:(Z)=>new Date(Z),declaredOut:u.Date})},{name:"string.date.iso"}),JU=e.module({root:Q7,parse:H0({declaredIn:Q7,in:"string",morphs:(Z,Y)=>{let X=new Date(Z);if(Number.isNaN(X.valueOf()))return Y.error("a parsable date");return X},declaredOut:u.Date}),iso:HU,epoch:WU},{name:"string.date"}),QU=w0(/^[\w%+.-]+@[\d.A-Za-z-]+\.[A-Za-z]{2,}$/,"an email address","email"),F7="(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])",R4=`(${F7}[.]){3}${F7}`,zU=new RegExp(`^${R4}$`),x0="(?:[0-9a-fA-F]{1,4})",UU=new RegExp(`^((?:${x0}:){7}(?:${x0}|:)|(?:${x0}:){6}(?:${R4}|:${x0}|:)|(?:${x0}:){5}(?::${R4}|(:${x0}){1,2}|:)|(?:${x0}:){4}(?:(:${x0}){0,1}:${R4}|(:${x0}){1,3}|:)|(?:${x0}:){3}(?:(:${x0}){0,2}:${R4}|(:${x0}){1,4}|:)|(?:${x0}:){2}(?:(:${x0}){0,3}:${R4}|(:${x0}){1,5}|:)|(?:${x0}:){1}(?:(:${x0}){0,4}:${R4}|(:${x0}){1,6}|:)|(?::((?::${x0}){0,5}:${R4}|(?::${x0}){1,7}|:)))(%[0-9a-zA-Z.]{1,})?$`),FU=e.module({root:["v4 | v6","@","an IP address"],v4:w0(zU,"an IPv4 address","ipv4"),v6:w0(UU,"an IPv6 address","ipv6")},{name:"string.ip"}),L2="a JSON string",R7=(Z)=>{if(!(Z instanceof SyntaxError))throw Z;return`must be ${L2} (${Z})`},EU=H0({meta:L2,domain:"string",predicate:{meta:L2,predicate:(Z,Y)=>{try{return JSON.parse(Z),!0}catch(X){return Y.reject({code:"predicate",expected:L2,problem:R7(X)})}}}}),LU=(Z,Y)=>{if(Z.length===0)return Y.error({code:"predicate",expected:L2,actual:"empty"});try{return JSON.parse(Z)}catch(X){return Y.error({code:"predicate",expected:L2,problem:R7(X)})}},DU=e.module({root:EU,parse:H0({meta:"safe JSON string parser",in:"string",morphs:LU,declaredOut:u.jsonObject})},{name:"string.json"}),E7=w0(/^[a-z]*$/,"only lowercase letters"),OU=e.module({root:H0({in:"string",morphs:(Z)=>Z.toLowerCase(),declaredOut:E7}),preformatted:E7},{name:"string.lower"}),N7=["NFC","NFD","NFKC","NFKD"],W8=i(N7,(Z,Y)=>[Y,H0({domain:"string",predicate:(X)=>X.normalize(Y)===X,meta:`${Y}-normalized unicode`})]),L6=i(N7,(Z,Y)=>[Y,H0({in:"string",morphs:(X)=>X.normalize(Y),declaredOut:W8[Y]})]),VU=e.module({root:L6.NFC,preformatted:W8.NFC},{name:"string.normalize.NFC"}),MU=e.module({root:L6.NFD,preformatted:W8.NFD},{name:"string.normalize.NFD"}),AU=e.module({root:L6.NFKC,preformatted:W8.NFKC},{name:"string.normalize.NFKC"}),RU=e.module({root:L6.NFKD,preformatted:W8.NFKD},{name:"string.normalize.NFKD"}),NU=e.module({root:"NFC",NFC:VU,NFD:MU,NFKC:AU,NFKD:RU},{name:"string.normalize"}),L7=w0(m8,"a well-formed numeric string"),wU=e.module({root:L7,parse:H0({in:L7,morphs:(Z)=>Number.parseFloat(Z),declaredOut:u.number})},{name:"string.numeric"}),D7="a regex pattern",IU=H0({domain:"string",predicate:{meta:D7,predicate:(Z,Y)=>{try{return new RegExp(Z),!0}catch(X){return Y.reject({code:"predicate",expected:D7,problem:String(X)})}}},meta:{format:"regex"}}),BU=/^(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-]+)*))?$/,KU=w0(BU,"a semantic version (see https://semver.org/)"),O7=w0(/^\S.*\S$|^\S?$/,"trimmed"),CU=e.module({root:H0({in:"string",morphs:(Z)=>Z.trim(),declaredOut:O7}),preformatted:O7},{name:"string.trim"}),V7=w0(/^[A-Z]*$/,"only uppercase letters"),TU=e.module({root:H0({in:"string",morphs:(Z)=>Z.toUpperCase(),declaredOut:V7}),preformatted:V7},{name:"string.upper"}),qU=(Z)=>{if(URL.canParse)return URL.canParse(Z);try{return new URL(Z),!0}catch{return!1}},M7=H0({domain:"string",predicate:{meta:"a URL string",predicate:qU},meta:{format:"uri"}}),jU=e.module({root:M7,parse:H0({declaredIn:M7,in:"string",morphs:(Z,Y)=>{try{return new URL(Z)}catch{return Y.error("a URL string")}},declaredOut:H0(URL)})},{name:"string.url"}),PU=e.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:w0(/^[\da-f]{8}-[\da-f]{4}-1[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv1"),v2:w0(/^[\da-f]{8}-[\da-f]{4}-2[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv2"),v3:w0(/^[\da-f]{8}-[\da-f]{4}-3[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv3"),v4:w0(/^[\da-f]{8}-[\da-f]{4}-4[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv4"),v5:w0(/^[\da-f]{8}-[\da-f]{4}-5[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv5"),v6:w0(/^[\da-f]{8}-[\da-f]{4}-6[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv6"),v7:w0(/^[\da-f]{8}-[\da-f]{4}-7[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv7"),v8:w0(/^[\da-f]{8}-[\da-f]{4}-8[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv8")},{name:"string.uuid"}),w7=e.module({root:u.string,alpha:w0(/^[A-Za-z]*$/,"only letters"),alphanumeric:w0(/^[\dA-Za-z]*$/,"only letters and digits 0-9"),hex:tz,base64:ez,capitalize:ZU,creditCard:GU,date:JU,digits:w0(/^\d*$/,"only digits 0-9"),email:QU,integer:A7,ip:FU,json:DU,lower:OU,normalize:NU,numeric:wU,regex:IU,semver:KU,trim:CU,upper:TU,url:jU,uuid:PU},{name:"string"});var I7=e.module({bigint:u.bigint,boolean:u.boolean,false:u.false,never:u.never,null:u.null,number:u.number,object:u.object,string:u.string,symbol:u.symbol,true:u.true,unknown:u.unknown,undefined:u.undefined}),B7=e.module({root:u.unknown,any:u.unknown},{name:"unknown"}),SU=e.module({root:u.jsonObject,stringify:z2("morph",{in:u.jsonObject,morphs:(Z)=>JSON.stringify(Z),declaredOut:u.string})},{name:"object.json"}),K7=e.module({root:u.object,json:SU},{name:"object"});class C7 extends r0{description='instantiate an object from an index signature and corresponding value type like `Record("string", "number")`'}var vU=T1(["K",u.key],"V")((Z)=>({domain:"object",index:{signature:Z.K,value:Z.V}}),C7);class T7 extends r0{description='pick a set of properties from an object like `Pick(User, "name | age")`'}var xU=T1(["T",u.object],["K",u.key])((Z)=>Z.T.pick(Z.K),T7);class q7 extends r0{description='omit a set of properties from an object like `Omit(User, "age")`'}var fU=T1(["T",u.object],["K",u.key])((Z)=>Z.T.omit(Z.K),q7);class j7 extends r0{description="make all named properties of an object optional like `Partial(User)`"}var hU=T1(["T",u.object])((Z)=>Z.T.partial(),j7);class P7 extends r0{description="make all named properties of an object required like `Required(User)`"}var kU=T1(["T",u.object])((Z)=>Z.T.required(),P7);class S7 extends r0{description='exclude branches of a union like `Exclude("boolean", "true")`'}var bU=T1("T","U")((Z)=>Z.T.exclude(Z.U),S7);class v7 extends r0{description='extract branches of a union like `Extract("0 | false | 1", "number")`'}var yU=T1("T","U")((Z)=>Z.T.extract(Z.U),v7),x7=e.module({Exclude:bU,Extract:yU,Omit:fU,Partial:hU,Pick:xU,Record:vU,Required:kU});var N4=g5({...I7,...x7,...W7,...Z7,string:w7,number:E6,object:K7,unknown:B7},{prereducedAliases:!0,name:"ark"}),p0=N4.export();Object.assign(E2.ambient,p0);E2.typeAttachments={string:p0.string.root,number:p0.number.root,bigint:p0.bigint,boolean:p0.boolean,symbol:p0.symbol,undefined:p0.undefined,null:p0.null,object:p0.object.root,unknown:p0.unknown.root,false:p0.false,true:p0.true,never:p0.never,arrayIndex:p0.Array.index,Key:p0.Key,Record:p0.Record,Array:p0.Array.root,Date:p0.Date};var F1=Object.assign(N4.type,E2.typeAttachments),gU=N4.match,pU=N4.generic,_B=N4.schema,mU=N4.define,uU=N4.declare;var dU=/^\[object (?:Async|Generator|AsyncGenerator)?Function\]$/;function k4(Z){let Y=Object.prototype.toString.call(Z);return dU.test(Y)}function D2(Z){return N6(E1.STORE,Z,void 0)}function D6(Z){return O2(E1.STORE,Z)}function u5(...Z){return A1(E1.STORE,...Z)}function O6(Z,Y){return u7(E1.STORE,Z,Y)}function f7(Z){return d7(Z,E1.STORE)}var o1={atom_family:"atom family",atom:"atom",continuity:"continuity",key:"key",mutable_atom_family:"atom family [m]",mutable_atom:"atom [m]",readonly_held_selector_family:"selector family [h]",readonly_held_selector:"selector [h]",readonly_pure_selector_family:"selector family",readonly_pure_selector:"selector",state:"state",timeline:"timeline",transaction:"transaction",unknown:"unknown",writable_held_selector_family:"selector family [wh]",writable_held_selector:"selector [wh]",writable_pure_selector_family:"selector family [w]",writable_pure_selector:"selector [w]"};var m5=(Z)=>(Y,X,G,_,...$)=>{console[Z](`${Y} ${o1[X]} \`${G}\` ${_}`,...$)},cU={error:m5("error"),info:m5("info"),warn:m5("warn")},h7=class{logLevel;filter;logger;constructor(Z,Y,X=cU){this.logLevel=Z,this.filter=Y,this.logger=X}error=(...Z)=>{if(this.logLevel!==null){let Y=this.filter?.(...Z)??!0;if(Y===!0)this.logger.error(...Z);else if(Y)this.logger.error(...Y)}};info=(...Z)=>{if(this.logLevel==="info"){let Y=this.filter?.(...Z)??!0;if(Y===!0)this.logger.info(...Z);else if(Y)this.logger.info(...Y)}};warn=(...Z)=>{if(this.logLevel!=="error"&&this.logLevel!==null){let Y=this.filter?.(...Z)??!0;if(Y===!0)this.logger.warn(...Z);else if(Y)this.logger.warn(...Y)}}};var k7=class{store;deallocateTX;claimTX;constructor(Z=E1.STORE){this.store=Z,this.deallocateTX=y7(Z),this.claimTX=g7(Z),b7(Z,"root")}allocate(Z,Y,X){R6(this.store,Z,Y,X)}deallocate(Z){A6(this.store,this.deallocateTX,d5())(Z)}claim(Z,Y,X){J8(this.store,Z,Y,X)}};function V6(Z){return c5(E1.STORE,Z)}function M6(Z){return Q8(E1.STORE,Z)}function a0(Z){return JSON.parse(Z)}var Q0=(Z)=>JSON.stringify(Z),PB=[Array.prototype,Boolean.prototype,Number.prototype,Object.prototype,String.prototype];function Z0(Z){while(Z.child!==null)Z=Z.child;return Z}function l7(Z){while(Z.parent!==null)Z=Z.parent;return Z}function I6(Z,Y){if(k4(Z))return Z(Y);return Z}var B6=class extends Promise{fate;resolve;reject;done=!1;constructor(Z){let Y,X;super((G,_)=>{Y=G,X=_});this.resolve=Y,this.reject=X,this.use(Z instanceof Promise?Z:new Promise(Z))}pass(Z,Y){if(Z===this.fate)this.resolve(Y),this.done=!0}fail(Z,Y){if(Z===this.fate)this.reject(Y),this.done=!0}use(Z){if(this===Z)return;if(Z instanceof Promise){let Y=Z;this.fate=Y,Y.then((X)=>{this.pass(Y,X)},(X)=>{this.fail(Y,X)})}else this.resolve(Z),this.fate=void 0}},_0=class{Subscriber;subscribers=new Map;subscribe(Z,Y){return this.subscribers.set(Z,Y),()=>{this.unsubscribe(Z)}}unsubscribe(Z){this.subscribers.delete(Z)}next(Z){let Y=this.subscribers.values();for(let X of Y)X(Z)}},i7=class extends _0{state;constructor(Z){super();this.state=Z}next(Z){this.state=Z,super.next(Z)}};function q1(Z){let Y={key:Z.key,type:Z.type};if("family"in Z)Y.family=Z.family;return Y}function b4(Z){return"epoch"in Z.transactionMeta}function G1(Z){return"phase"in Z.transactionMeta}var o7=class extends Error{constructor(Z,Y){super(`${o1[Z.type]} ${Q0(Z.key)} not found in store "${Y.config.name}".`)}};function q0(Z,Y){let X,G=Z;while(G!==null){switch(Y.type){case"atom":case"mutable_atom":X=G.atoms.get(Y.key);break;case"writable_pure_selector":case"writable_held_selector":X=G.writableSelectors.get(Y.key);break;case"readonly_pure_selector":case"readonly_held_selector":X=G.readonlySelectors.get(Y.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=G.families.get(Y.key);break;case"timeline":X=G.timelines.get(Y.key);break;case"transaction":X=G.transactions.get(Y.key);break}if(X)return X;G=G.child}throw new o7(Y,Z)}function t5(Z,Y,X,G){let _=Z.disposalTraces.buffer.find(($)=>$?.key===Q0(G));switch(Z.logger.error("\u274C",Y.type,Y.key,"gets a fallback value because key",G,"is not allocated",_?`This key was previously disposed:
48
- ${_.trace}`:"(no previous disposal trace found)"),X.type){case"mutable_atom_family":{if(Z.defaults.has(X.key))return Z.defaults.get(X.key);let $=new X.class;return Z.defaults.set(X.key,$),$.READONLY_VIEW}case"atom_family":{if(Z.defaults.has(X.key))return Z.defaults.get(X.key);let $=X.default,W=$(G);return Z.defaults.set(X.key,W),W}case"readonly_pure_selector_family":case"writable_pure_selector_family":case"readonly_held_selector_family":case"writable_held_selector_family":{if(Z.defaults.has(X.key))return Z.defaults.get(X.key);let $=X.default(G);return Z.defaults.set(X.key,$),$}}}function K6(Z,Y){let{type:X,key:G,catch:_}=Y;switch(X){case"readonly_pure_selector":case"writable_pure_selector":{let $;Z.logger.info("\uD83E\uDDEE",X,G,"computing value");try{if($=Y.getFrom(Z),$ instanceof Promise)return $.catch((W)=>{if(Z.logger.error("\uD83D\uDCA5",X,G,"rejected:",W),_){for(let H of _)if(W instanceof H)return W}throw W})}catch(W){if(Z.logger.error("\uD83D\uDCA5",X,G,"rejected:",W),_){for(let H of _)if(W instanceof H)return N1(Z,Y,W)}throw W}return N1(Z,Y,$)}case"atom":{let $;if(k4(Y.default))try{if($=Y.default(),$ instanceof Promise)$=$.catch((W)=>{if(Z.logger.error("\uD83D\uDCA5",X,G,"rejected:",W),_){for(let H of _)if(W instanceof H)return W}throw W})}catch(W){if(Z.logger.error("\uD83D\uDCA5",X,G,"rejected:",W),_){for(let H of _)if(W instanceof H)return $=N1(Z,Y,W),Z.logger.info("\u2728",Y.type,G,"computed default",$),$}throw W}else $=Y.default,Z.logger.info("\u2728",Y.type,G,"using static default",$);return N1(Z,Y,$)}}}function I4(Z,Y,X){if(Z.valueMap.has(Y.key))return G_(Z,Y,X);Z.logger.info("\u2754",Y.type,Y.key,"value not found in cache");let{key:G}=Y;switch(Y.type){case"readonly_held_selector":case"writable_held_selector":return Z.logger.info("\uD83E\uDDEE",Y.type,G,"computing value"),Y.getFrom(Z);case"writable_pure_selector":case"readonly_pure_selector":case"atom":return K6(Z,Y);case"mutable_atom":{let _=new Y.class;return Z.logger.info("\u2728",Y.type,G,"created new instance",_),N1(Z,Y,_)}}}function T6(Z,Y){return q0(Z,{key:Y.family.key,type:`${Y.type}_family`})}var c7={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"},F8=Symbol("MUST_CREATE"),n7=Symbol("DO_NOT_CREATE");function V2(Z,Y,X,G){let _=Q0(G),$=Y.molecules.get(_);if(!$&&Y.config.lifespan==="immortal"){let{type:H,key:Q}=X;Y.logger.warn("\uD83D\uDCA3","key",_,"was used to mint a counterfeit token for",H,`"${Q}"`);let J=`${Q}(${_})`,z=c7[H];return{counterfeit:!0,key:J,type:z,family:{key:Q,subKey:_}}}let W;if(Z===F8){if(Y.logger.info("\uD83D\uDC6A",X.type,X.key,"adds member",typeof G==="string"?`\`${G}\``:G),W=X.create(G),$)Y.moleculeData.set(_,X.key)}else{let{type:H,key:Q}=X,J=`${Q}(${_})`,z=c7[H];return{key:J,type:z,family:{key:Q,subKey:_}}}return W}function q6(Z,...Y){let X,G,_,$,W;if(Y.length===1){if(W=Y[0],"family"in W){let Q=T6(Z,W);if(_=q0(Z,Q),$=a0(W.family.subKey),X=M2(Z,Q,$),"counterfeit"in W)return{token:W,family:_,subKey:$,isNew:!1};if(!X)G=V2(F8,Z,Q,$),W=G;else W=X}}else if(_=q0(Z,Y[0]),$=Y[1],X=M2(Z,_,$),!X)G=V2(F8,Z,_,$),W=G;else W=X;let H="counterfeit"in W;if(Boolean(G)&&H===!1&&_){let Q;switch(W.type){case"readonly_pure_selector":case"readonly_held_selector":Q="readable";break;case"atom":case"mutable_atom":case"writable_pure_selector":case"writable_held_selector":Q="writable";break}let J={type:"state_creation",subType:Q,token:W,timestamp:Date.now()};_.subject.next(J);let z=Z0(Z);if(W.family){if(b4(z))switch(W.type){case"atom":case"mutable_atom":Z.on.atomCreation.next(W);break;case"writable_pure_selector":case"readonly_pure_selector":case"writable_held_selector":case"readonly_held_selector":Z.on.selectorCreation.next(W);break}else if(G1(z)&&z.on.transactionApplying.state===null)z.transactionMeta.update.subEvents.push(J)}}return{token:W,family:_,subKey:$,isNew:Boolean(G)}}function A1(Z,...Y){let{token:X,family:G,subKey:_}=q6(Z,...Y);if("counterfeit"in X&&G&&_)return t5(Z,X,G,_);let $=q0(Z,X);return I4(Z,$)}function M2(Z,Y,X){let G=Q0(X),_=`${Y.key}(${G})`,$=Z0(Z),W;switch(Y.type){case"atom_family":case"mutable_atom_family":W=$.atoms.get(_);break;case"writable_held_selector_family":case"writable_pure_selector_family":W=$.writableSelectors.get(_);break;case"readonly_held_selector_family":case"readonly_pure_selector_family":W=$.readonlySelectors.get(_);break}if(W)return q1(W);return W}function e5(Z,Y){if(Z.operation.open){let X=performance.now();return Z.logger.info("\uD83D\uDEAB",Y.type,Y.key,`deferring setState at T-${X} until setState for "${Z.operation.token.key}" is done`),X}return Z.operation={open:!0,done:new Set,prev:new Map,timestamp:Date.now(),token:Y,subEvents:[]},Z.logger.info("\u2B55",Y.type,Y.key,`operation start in store "${Z.config.name}"${G1(Z)?` ${Z.transactionMeta.phase} "${Z.transactionMeta.update.token.key}"`:""}`),Z}function ZY(Z){if(Z.operation.open)Z.logger.info("\uD83D\uDD34",Z.operation.token.type,Z.operation.token.key,`operation done in store "${Z.config.name}"`);Z.operation={open:!1},Z.on.operationClose.next(Z.operation)}var YY=(Z,Y)=>{if(!Z.operation.open)return Z.logger.error("\uD83D\uDC1E","unknown",Y,"isDone called outside of an operation. This is probably a bug in AtomIO."),!0;return Z.operation.done.has(Y)},E8=(Z,Y)=>{if(!Z.operation.open){Z.logger.error("\uD83D\uDC1E","unknown",Y,"markDone called outside of an operation. This is probably a bug in AtomIO.");return}Z.operation.done.add(Y)};function o5(Z,Y,{oldValue:X,newValue:G},_,$){let W=q1(Y);if(_&&$){Y.subject.next({newValue:G});let U={checkpoint:!0,type:"state_creation",subType:"writable",token:W,timestamp:Date.now(),value:G};Z.operation.subEvents.push(U),$.subject.next(U);let D=Z0(Z);if(W.family){if(b4(D))switch(W.type){case"atom":case"mutable_atom":Z.on.atomCreation.next(W);break;case"writable_pure_selector":case"writable_held_selector":Z.on.selectorCreation.next(W);break}else if(G1(D)&&D.on.transactionApplying.state===null)D.transactionMeta.update.subEvents.push(U)}return}let{key:H,subject:Q,type:J}=Y,z={oldValue:w6(X)?X.READONLY_VIEW:X,newValue:w6(G)?G.READONLY_VIEW:G};if(b4(Z)){switch(J){case"mutable_atom":Z.logger.info("\uD83D\uDCE2",J,H,"is now (",G,") subscribers:",Q.subscribers.keys());break;case"atom":case"writable_pure_selector":case"writable_held_selector":Z.logger.info("\uD83D\uDCE2",J,H,"went (",X,"->",G,") subscribers:",Q.subscribers.keys())}Q.next(z)}if(G1(Z)&&(J==="mutable_atom"||J==="atom")){if(Z.on.transactionApplying.state===null){if(w6(G))return;let{timestamp:U}=Z.operation,D={type:"atom_update",token:W,timestamp:U,update:z};Z.transactionMeta.update.subEvents.push(D),Z.logger.info("\uD83D\uDCC1","atom",H,"stowed (",X,"->",G,")");return}if($Y(Y,"tracker:signal")){let U=H.slice(1),D=Z.atoms.get(U);if(I4(Z,D,"mut").do(z.newValue)===null===!0)S6(Z,D)}}}var n5=(Z,Y,X)=>{let G=I4(Z,Y,"mut"),_=I6(X,G);return Z.logger.info("\u2B50","atom",Y.key,"setting value",_),_=N1(Z,Y,_),E8(Z,Y.key),S6(Z,Y),{oldValue:G,newValue:_}};function i5(Z,Y){switch(Y.type){case"mutable_atom":return n5(Z,Y,new Y.class);case"atom":{let X;if(k4(Y.default))X=K6(Z,Y);else X=Y.default;return n5(Z,Y,X)}}}function r7(Z,Y){let X;switch(Y.type){case"atom":case"mutable_atom":X=i5(Z,Y);break;case"writable_held_selector":{let G=A2(Z,Y.key);for(let $ of G.values()){let W=i5(Z,$);o5(Z,Y,W,!1)}let _=Y.getFrom(Z);X={oldValue:_,newValue:_}}break;case"writable_pure_selector":{let G=K6(Z,Y),_=A2(Z,Y.key);for(let W of _.values()){let H=i5(Z,W);o5(Z,Y,H,!1)}let $=K6(Z,Y);X={oldValue:G,newValue:$}}break}return X}function R1(Z,...Y){j6(r5,Z,...Y)}var C6=Symbol("RESET");function H8(Z,...Y){let X=[...Y,C6];R1(Z,...X)}function iU(Z,Y,X){let G,_,$,{type:W,key:H}=Y;switch(Y.type){case"writable_pure_selector":G=I4(Z,Y,"mut"),_=I6(X,G),_=N1(Z,Y,_);break;case"writable_held_selector":$=Y.const,I6(X,$),G=$,_=$}return Z.logger.info("\u2B50",W,H,"setting to",_),E8(Z,H),Y.setSelf(_),{oldValue:G,newValue:_}}var s7=(Z,Y,X)=>{let G;switch(Y.type){case"atom":case"mutable_atom":G=n5(Z,Y,X);break;case"writable_pure_selector":case"writable_held_selector":G=iU(Z,Y,X);break}return G},r5=Symbol("OWN_OP"),a7=Symbol("JOIN_OP");function j6(Z,Y,...X){let G,_,$,W,H,Q;if(X.length===2){if($=X[0],Q=X[1],"family"in $)if(W=T6(Y,$),H=a0($.family.subKey),G=M2(Y,W,H),!G)$=_=V2(F8,Y,W,H);else $=G}else if(W=q0(Y,X[0]),H=X[1],Q=X[2],G=M2(Y,W,H),!G)$=_=V2(F8,Y,W,H);else $=G;let J=Q===C6?"reset":"set",z;if(Z===r5){let V=e5(Y,$);if(typeof V==="number"){let N=V,R=Y.on.operationClose.subscribe(`waiting to ${J} "${$.key}" at T-${N}`,function b(){R(),Y.logger.info("\uD83D\uDFE2",$.type,$.key,"resuming deferred",J,`from T-${N}`),j6(Z,Y,$,Q)});return}z=V}else z=Y;if("counterfeit"in $&&"family"in $){let V=$.family.subKey,N=Y.disposalTraces.buffer.find((R)=>R?.key===V);Y.logger.error("\u274C",$.type,$.key,"could not be",J,"because key",V,"is not allocated.",N?`this key was previously disposed:${N.trace}`:"(no previous disposal trace found)");return}let U=q0(z,$),D;if(Q===C6)D=r7(z,U);else D=s7(z,U,Q);if(o5(z,U,D,Boolean(_),W),Z===r5)ZY(z)}var XY=(Z,Y)=>Z0(Z).atoms.has(Y),t7=(Z,Y)=>Z0(Z).writableSelectors.has(Y),e7=(Z,Y)=>Z0(Z).readonlySelectors.has(Y),Z_=(Z,Y)=>XY(Z,Y)||t7(Z,Y)||e7(Z,Y);function s5(Z,Y){return Z0(Z).selectorGraph.getRelationEntries({downstreamSelectorKey:Y}).filter(([X,{source:G}])=>G!==Y).map(([X,{source:G}])=>G).filter((X)=>Z_(Z,X))}function A2(Z,Y,X=new Set){let G=s5(Z,Y),_=new Map;while(G.length>0){let $=G.pop();if(X.has($))continue;if(X.add($),XY(Z,$)){let W=Z.atoms.get($);_.set(W.key,W)}else G.push(...s5(Z,$))}return _}var Y_=(Z,Y)=>{let X=Z0(Z);if(X.operation.open)return X.operation.prev.get(Y.key);return X.valueMap.get(Y.key)},a5=(Z,Y,X)=>{return X.subject.subscribe(`${Y.type}:${Y.key}`,(G)=>{Z.logger.info("\uD83D\uDCE2",Y.type,Y.key,"root",X.key,"went",G.oldValue,"->",G.newValue);let _=Y_(Z,Y),$=I4(Z,Y);Z.logger.info("\u2728",Y.type,Y.key,"went",_,"->",$),Y.subject.next({newValue:$,oldValue:_})})};function R2(Z,Y,X,G){function _(U){if(Z.operation.open){let D=Z.on.operationClose.subscribe(`state subscription ${X}`,()=>{D(),G(U)})}else G(U)}q6(Z,Y);let $=q0(Z,Y);Z.logger.info("\uD83D\uDC40",$.type,$.key,`Adding subscription "${X}"`);let W=$.type==="writable_pure_selector"||$.type==="readonly_pure_selector",H=new Map,Q=_;if(W){I4(Z,$);for(let[U,D]of A2(Z,$.key))H.set(U,a5(Z,$,D));Q=function U(D){let V=A2(Z,$.key);for(let[N,R]of H)if(V.get(N))V.delete(N);else R(),H.delete(N);for(let[N,R]of V)H.set(N,a5(Z,$,R));_(D)}}let J=$.subject.subscribe(X,Q);return()=>{Z.logger.info("\uD83D\uDE48",$.type,$.key,`Removing subscription "${X}"`),J();for(let U of H.values())U()}}var X_=(Z,Y,X,G)=>{let _=q0(Z,Y);Z.logger.info("\uD83D\uDC40","timeline",Y.key,`Adding subscription "${X}"`);let $=_.subject.subscribe(X,G);return()=>{Z.logger.info("\uD83D\uDE48","timeline",Y.key,`Removing subscription "${X}" from timeline`),$()}},P6=class{initializeSignalAtom(Z,Y){let X=`*${Z.key}`;Y.atoms.delete(X),Y.valueMap.delete(X);let G=Z.family?{key:`*${Z.family.key}`,subKey:Z.family.subKey}:void 0,_=w4(Y,{key:X,default:null},G,["tracker:signal"]);if(Y.parent?.valueMap.has(X)){let $=Y.parent.valueMap.get(X);Y.valueMap.set(X,$)}return _}unsubscribeFromInnerValue;unsubscribeFromState;captureSignalsFromCore(Z,Y,X){let G=Z.key,_=X.config.name,$=G1(X)?X.transactionMeta.update.token.key:"main",W=`tracker:${_}:${$}:${G}`,H=(Q)=>{R1(X,Y,Q)};this.unsubscribeFromInnerValue=A1(X,Z).subscribe(W,H),this.unsubscribeFromState=R2(X,Z,W,function Q(J){if(J.newValue!==J.oldValue)this.unsubscribeFromInnerValue(),this.unsubscribeFromInnerValue=J.newValue.subscribe(W,H)}.bind(this))}supplySignalsToCore(Z,Y,X){let G=`tracker:${X.config.name}:${G1(X)?X.transactionMeta.update.token.key:"main"}:${Z.key}`;R2(X,Y,G,function _({newValue:$,oldValue:W}){let H=X.timelineTopics.getRelatedKey(Y.key);if(H&&X.timelines.get(H)?.timeTraveling){let U=X_(X,{key:H,type:"timeline"},G,function D(V){U(),R1(X,Z,(N)=>{if(V==="redo"&&$)N.do($);else if(V==="undo"&&W)N.undo(W);return N})});return}let Q=A1(X,Z),J=Q.getUpdateNumber($),z=J-Q.cacheUpdateNumber;if($&&z===1)R1(X,Z,(U)=>(U.do($),U));else{let U=Q.cacheUpdateNumber+1;X.logger.info("\u274C","mutable_atom",Z.key,"could not be updated. Expected update number",U,"but got",J)}})}mutableAtomToken;latestSignalToken;[Symbol.dispose];constructor(Z,Y){let X=Z0(Y),G=this.initializeSignalAtom(Z,X);this.mutableAtomToken=Z,this.latestSignalToken=G,this.captureSignalsFromCore(Z,G,X),this.supplySignalsToCore(Z,G,X),X.trackers.set(Z.key,this),this[Symbol.dispose]=()=>{this.unsubscribeFromInnerValue(),this.unsubscribeFromState(),X.trackers.delete(Z.key)}}};function w6(Z){return typeof Z==="object"&&Z!==null&&"do"in Z&&"undo"in Z&&"subscribe"in Z&&"cacheUpdateNumber"in Z&&"getUpdateNumber"in Z&&"READONLY_VIEW"in Z&&"toJSON"in Z}function N1(Z,Y,X){let{key:G,subject:_,type:$}=Y,W=Z.valueMap.get(G);if(W instanceof B6&&!W.done){let H=W;if(X instanceof Promise)return H.use(X),H;return Z.valueMap.set(G,X),X}if(X instanceof Promise){let H=new B6(X);return Z.valueMap.set(G,H),H.then(function Q(J){if(Z.valueMap.get(G)===H){switch(e5(Z,Y),N1(Z,Y,J),$){case"atom":S6(Z,Y);break;case"readonly_pure_selector":case"writable_pure_selector":_Y(Z,G);break}ZY(Z),_.next({newValue:J,oldValue:H})}}).catch((Q)=>{Z.logger.error("\uD83D\uDCA5",Y.type,G,"rejected:",Q)}),H}return Z.logger.info("\uD83D\uDCDD",Y.type,Y.key,"writing to cache",X),Z.valueMap.set(G,X),X}function G_(Z,Y,X){Z.logger.info("\uD83D\uDCD6",Y.type,Y.key,"reading cached value");let G=Z.valueMap.get(Y.key);if(X==="mut"&&Y.type==="mutable_atom"&&G1(Z)){let _=Y,{parent:$}=Z;if(Z.valueMap.hasOwn(_.key))return G;let W=$.valueMap.get(_.key);Z.logger.info("\uD83D\uDCC3","atom",_.key,"copying");let H=W.toJSON(),Q=_.class.fromJSON(H);Z.valueMap.set(_.key,Q),new P6(_,$),G=Q}return G}function GY(Z,Y){let X=Z.valueMap.get(Y);if(X instanceof B6){let G=Z.writableSelectors.get(Y)??Z.readonlySelectors.get(Y);if(G)G.getFrom(Z);return}if(Z.operation.open)Z.operation.prev.set(Y,X);Z.valueMap.delete(Y),Z.logger.info("\uD83D\uDDD1","state",Y,"evicted")}function S6(Z,Y){let X=Z0(Z),{key:G,type:_}=Y,$=X.selectorAtoms.getRelatedKeys(G);if(X.logger.info("\uD83E\uDDF9",_,G,$?`evicting ${$.size} states downstream:`:"no downstream states",$??"to evict"),$){if(X.operation.open)X.logger.info("\uD83E\uDDF9",_,G,`[ ${[...X.operation.done].join(", ")} ] already done`);for(let W of $){if(YY(X,W))continue;GY(X,W),E8(X,W)}}}function _Y(Z,Y){let X=Z0(Z),G=X.selectorGraph.getRelationEntries({upstreamSelectorKey:Y}).filter(([_,{source:$}])=>$===Y);for(let[_]of G){if(YY(X,_))continue;GY(X,_),E8(X,_),_Y(Z,_)}}function w4(Z,Y,X,G){let{key:$}=Y;Z.logger.info("\uD83D\uDD28","atom",$,"is being created");let W=Z0(Z),H=W.atoms.get($);if(H&&H.type==="atom")return Z.logger.error("\u274C","atom",$,"Tried to create atom, but it already exists in the store."),q1(H);let Q=new _0,J={...Y,type:"atom",install:(U)=>{return U.logger.info("\uD83D\uDEE0\uFE0F","atom",$,`installing in store "${U.config.name}"`),w4(U,Y,X)},subject:Q};if(X)J.family=X;if(G)J.internalRoles=G;W.atoms.set($,J);let z=q1(J);if(Y.effects){let U=0,D=[];for(let V of Y.effects){let N=V({resetSelf:()=>{H8(Z,z)},setSelf:(R)=>{R1(Z,z,R)},onSet:(R)=>R2(Z,z,`effect[${U}]`,R)});if(N)D.push(N);++U}J.cleanup=()=>{for(let V of D)V()}}return Z.on.atomCreation.next(z),z}function $Y(Z,Y){if("internalRoles"in Z===!1)return!1;return Z.internalRoles.includes(Y)}var $4=class Z extends Set{mode="record";subject=new _0;cacheLimit=0;cache=[];cacheIdx=-1;cacheUpdateNumber=-1;constructor(Y,X=0){super(Y);if(Y instanceof Z)this.parent=Y,this.cacheUpdateNumber=Y.cacheUpdateNumber;if(X)this.cacheLimit=X,this.cache=new Array(X),this.subscribe("auto cache",(G)=>{this.cacheIdx++,this.cacheIdx%=this.cacheLimit,this.cache[this.cacheIdx]=G})}READONLY_VIEW=this;toJSON(){return{members:[...this],cache:this.cache,cacheLimit:this.cacheLimit,cacheIdx:this.cacheIdx,cacheUpdateNumber:this.cacheUpdateNumber}}static fromJSON(Y){let X=new Z(Y.members,Y.cacheLimit);return X.cache=Y.cache,X.cacheIdx=Y.cacheIdx,X.cacheUpdateNumber=Y.cacheUpdateNumber,X}add(Y){let X=super.add(Y);if(this.mode==="record")this.cacheUpdateNumber++,this.emit(`add:${Q0(Y)}`);return X}clear(){let Y=this.mode==="record"?[...this]:null;if(super.clear(),Y)this.cacheUpdateNumber++,this.emit(`clear:${JSON.stringify(Y)}`)}delete(Y){let X=super.delete(Y);if(this.mode==="record")this.cacheUpdateNumber++,this.emit(`del:${Q0(Y)}`);return X}parent=null;child=null;transactionUpdates=null;transaction(Y){this.mode="transaction",this.transactionUpdates=[],this.child=new Z(this);let X=this.child._subscribe("transaction",(G)=>{this.transactionUpdates?.push(G)});try{if(Y(this.child)){for(let G of this.transactionUpdates)this.doStep(G);this.cacheUpdateNumber++,this.emit(`tx:${this.transactionUpdates.join(";")}`)}}catch(G){throw console.warn("Did not apply transaction to SetRTX; this error was thrown:",G),G}finally{X(),this.child=null,this.transactionUpdates=null,this.mode="record"}}_subscribe(Y,X){return this.subject.subscribe(Y,X)}subscribe(Y,X){return this.subject.subscribe(Y,(G)=>{X(`${this.cacheUpdateNumber}=${G}`)})}emit(Y){this.subject.next(Y)}doStep(Y){let X=Y.indexOf(":"),G=Y.substring(0,X),_=Y.substring(X+1);switch(G){case"add":this.add(JSON.parse(_));break;case"clear":this.clear();break;case"del":this.delete(JSON.parse(_));break;case"tx":for(let $ of _.split(";"))this.doStep($)}}getUpdateNumber(Y){let X=Y.indexOf("=");return Number(Y.substring(0,X))}do(Y){let X=Y.indexOf("="),G=Number(Y.substring(0,X)),_=G-this.cacheUpdateNumber;if(_>0){if(_===1){this.mode="playback";let $=Y.substring(X+1);return this.doStep($),this.mode="record",this.cacheUpdateNumber=G,null}return this.cacheUpdateNumber+1}if(Math.abs(_)<this.cacheLimit){let $=this.cacheIdx+_;if(this.cache[$]===Y)return null;this.mode="playback";let W=!1;while(!W){this.cacheIdx%=this.cacheLimit;let Q=this.cache[this.cacheIdx];if(this.cacheIdx--,!Q)return"OUT_OF_RANGE";this.undo(Q),W=this.cacheIdx===$-1}let H=Y.substring(X+1);return this.doStep(H),this.mode="record",this.cacheUpdateNumber=G,null}return"OUT_OF_RANGE"}undoStep(Y){let X=Y.indexOf(":"),G=Y.substring(0,X),_=Y.substring(X+1);switch(G){case"add":this.delete(JSON.parse(_));break;case"del":this.add(JSON.parse(_));break;case"clear":{let $=JSON.parse(_);for(let W of $)this.add(W);break}case"tx":{let $=_.split(";");for(let W=$.length-1;W>=0;W--)this.undoStep($[W])}}}undo(Y){let X=Y.indexOf("=");if(Number(Y.substring(0,X))===this.cacheUpdateNumber){this.mode="playback";let G=Y.substring(X+1);return this.undoStep(G),this.mode="record",this.cacheUpdateNumber--,null}return this.cacheUpdateNumber}};function d5(Z=Math.random){return Z().toString(36).slice(2)}var oU=class Z{_buffer;_index=0;constructor(Y){let X;if(typeof Y==="number")X=Y;else X=Y.length;this._buffer=Array.from({length:X})}get buffer(){return this._buffer}get index(){return this._index}add(Y){this._buffer[this._index]=Y,this._index=(this._index+1)%this._buffer.length}copy(){let Y=new Z([...this._buffer]);return Y._index=this._index,Y}},y1=class extends Map{deleted=new Set;changed=new Set;source;constructor(Z){super();this.source=Z}get(Z){if(super.has(Z))return super.get(Z);if(!this.deleted.has(Z)&&this.source.has(Z))return this.source.get(Z)}set(Z,Y){if(this.deleted.delete(Z),this.source.has(Z))this.changed.add(Z);return super.set(Z,Y)}hasOwn(Z){return super.has(Z)}has(Z){return!this.deleted.has(Z)&&(super.has(Z)||this.source.has(Z))}delete(Z){if(this.source.has(Z))this.deleted.add(Z),this.changed.delete(Z);return super.delete(Z)}clear(){this.deleted=new Set(this.source.keys()),this.changed.clear(),super.clear()}*[Symbol.iterator](){yield*super[Symbol.iterator]();for(let[Z,Y]of this.source)if(!this.deleted.has(Z)&&!this.changed.has(Z))yield[Z,Y]}*entries(){yield*this[Symbol.iterator]()}*keys(){yield*super.keys();for(let Z of this.source.keys())if(!this.deleted.has(Z)&&!this.changed.has(Z))yield Z}*values(){for(let[,Z]of this[Symbol.iterator]())yield Z}forEach(Z){for(let[Y,X]of this[Symbol.iterator]())Z(X,Y,this)}get size(){return super.size+this.source.size-this.changed.size-this.deleted.size}},$_=class extends Set{deleted=new Set;source;constructor(Z){super();this.source=Z}add(Z){if(this.source.has(Z))return this.deleted.delete(Z),this;return super.add(Z)}hasOwn(Z){return super.has(Z)}has(Z){return!this.deleted.has(Z)&&(super.has(Z)||this.source.has(Z))}delete(Z){if(this.source.has(Z))return this.deleted.add(Z),!0;return super.delete(Z)}clear(){this.deleted=new Set(this.source),super.clear()}*[Symbol.iterator](){yield*super[Symbol.iterator]();for(let Z of this.source)if(!this.deleted.has(Z))yield Z}*iterateOwn(){yield*super[Symbol.iterator]()}get size(){return super.size+this.source.size-this.deleted.size}},nU=class extends Map{deleted=new Set;source;constructor(Z){super();this.source=Z}get(Z){if(super.has(Z))return super.get(Z);if(!this.deleted.has(Z)&&this.source.has(Z)){let Y=this.source.get(Z),X=new $_(Y);return super.set(Z,X),X}}set(Z,Y){return this.deleted.delete(Z),super.set(Z,Y)}has(Z){return!this.deleted.has(Z)&&(super.has(Z)||this.source.has(Z))}delete(Z){return this.deleted.add(Z),super.delete(Z)}},W4=class Z{a;b;cardinality;relations=new Map;contents=new Map;isAType;isBType;isContent;makeContentKey=(Y,X)=>`${Y}:${X}`;warn;getRelatedKeys(Y){return this.relations.get(Y)}addRelation(Y,X){let G=this.relations.get(Y),_=this.relations.get(X);if(G)G.add(X);else G=new Set([X]),this.relations.set(Y,G);if(_)_.add(Y);else _=new Set([Y]),this.relations.set(X,_)}deleteRelation(Y,X){let G=this.relations.get(Y);if(G){if(G.delete(X),G.size===0)this.relations.delete(Y);let _=this.relations.get(X);if(_){if(_.delete(Y),_.size===0)this.relations.delete(X)}}}replaceRelationsUnsafely(Y,X){this.relations.set(Y,new Set(X));for(let G of X){let _=new Set().add(Y);this.relations.set(G,_)}}replaceRelationsSafely(Y,X){let G=this.relations.get(Y),_=this.isAType?.(Y)?Y:void 0,$=_===void 0?Y:void 0;if(G)for(let W of G){_??=W,$??=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(_,$))}}this.relations.set(Y,new Set(X));for(let W of X){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,X){this.contents.set(Y,X)}deleteContent(Y){this.contents.delete(Y)}constructor(Y,X){if(this.a=Y.between[0],this.b=Y.between[1],this.cardinality=Y.cardinality,this.isAType=X?.isAType??null,this.isBType=X?.isBType??null,this.isContent=X?.isContent??null,X?.makeContentKey)this.makeContentKey=X.makeContentKey;if(!X?.externalStore){let G=X?.source;if(G===void 0)this.relations=new Map(Y.relations?.map(([_,$])=>[_,new Set($)])),this.contents=new Map(Y.contents);if(G)this.relations=new nU(G.relations),this.contents=new y1(G.contents)}if(X?.externalStore){let G=X.externalStore;if(this.has=(_,$)=>G.has(_,$),this.addRelation=(_,$)=>{G.addRelation(_,$)},this.deleteRelation=(_,$)=>{G.deleteRelation(_,$)},this.replaceRelationsSafely=(_,$)=>{G.replaceRelationsSafely(_,$)},this.replaceRelationsUnsafely=(_,$)=>{G.replaceRelationsUnsafely(_,$)},this.getRelatedKeys=(_)=>G.getRelatedKeys(_),G.getContent)this.getContentInternal=(_)=>{return G.getContent(_)},this.setContent=(_,$)=>{G.setContent(_,$)},this.deleteContent=(_)=>{G.deleteContent(_)};for(let[_,$]of Y.relations??[]){let W=this.isAType?.(_)?_:void 0,H=W===void 0?_:void 0;for(let Q of $)W??=Q,H??=Q,this.addRelation(W,H)}for(let[_,$]of Y.contents??[])this.setContent(_,$)}if(X?.warn)this.warn=X.warn}toJSON(){return{between:[this.a,this.b],cardinality:this.cardinality,relations:[...this.relations.entries()].map(([Y,X])=>[Y,[...X]]),contents:[...this.contents.entries()]}}set(...Y){let X,G,_;switch(Y.length){case 1:{let $=Y[0];X=$[this.a],G=$[this.b],_=void 0;break}case 2:{let $=Y[0];if(typeof $==="string")[X,G]=Y;else X=$[this.a],G=$[this.b],_=Y[1];break}default:X=Y[0],G=Y[1],_=Y[2];break}switch(this.cardinality){case"1:1":{let $=this.getRelatedKey(X);if($&&$!==G)this.delete(X,$)}case"1:n":{let $=this.getRelatedKey(G);if($&&$!==X)this.delete($,G)}break;case"n:n":}if(_){let $=this.makeContentKey(X,G);this.setContent($,_)}return this.addRelation(X,G),this}delete(Y,X){X=typeof X==="string"?X:Y[this.b];let G=typeof Y==="string"?Y:Y[this.a];if(G===void 0&&typeof X==="string"){let _=this.getRelatedKeys(X);if(_)for(let $ of _)this.delete($,X)}else if(typeof G==="string"&&X===void 0){let _=this.getRelatedKeys(G);if(_)for(let $ of _)this.delete(G,$)}else if(typeof G==="string"&&typeof X==="string"){this.deleteRelation(G,X);let _=this.makeContentKey(G,X);this.deleteContent(_)}return this}getRelatedKey(Y){let X=this.getRelatedKeys(Y);if(X){if(X.size>1)this.warn?.(`${X.size} related keys were found for key "${Y}": (${[...X].map((_)=>`"${_}"`).join(", ")}). Only one related key was expected.`);let G;for(let _ of X){G=_;break}return G}}replaceRelations(Y,X,G){let _=!Array.isArray(X),$=_?Object.keys(X):X;if(G?.reckless)this.replaceRelationsUnsafely(Y,$);else this.replaceRelationsSafely(Y,$);if(_)for(let W of $){let H=this.makeContentKey(Y,W),Q=X[W];this.setContent(H,Q)}return this}getContent(Y,X){let G=this.makeContentKey(Y,X);return this.getContentInternal(G)}getRelationEntries(Y){let X=Y[this.a],G=Y[this.b];if(X!==void 0&&G===void 0){let _=this.getRelatedKeys(X);if(_)return[..._].map(($)=>{return[$,this.getContent(X,$)]})}if(X===void 0&&G!==void 0){let _=this.getRelatedKeys(G);if(_)return[..._].map(($)=>{return[$,this.getContent($,G)]})}return[]}has(Y,X){if(X)return this.getRelatedKeys(Y)?.has(X)??!1;return this.relations.has(Y)}overlay(){let Y={source:this,makeContentKey:this.makeContentKey};if(this.isAType)Y.isAType=this.isAType;if(this.isBType)Y.isBType=this.isBType;if(this.isContent)Y.isContent=this.isContent;if(this.warn)Y.warn=this.warn;return new Z({between:[this.a,this.b],cardinality:this.cardinality},Y)}incorporate(Y){let{relations:X,contents:G}=Y;for(let[_,$]of X)if($ instanceof $_){let{source:W}=$;for(let H of $.iterateOwn())W.add(H)}else this.relations.set(_,$);for(let _ of X.deleted)this.relations.delete(_);for(let[_,$]of G)this.contents.set(_,$);for(let _ of G.deleted)this.contents.delete(_)}};function N2(Z){return Z.startsWith("\uD83D\uDD0D ")}var rU=(Z)=>{Z.logger.info("\uD83E\uDE82","transaction",Z.transactionMeta.update.token.key,"Aborting transaction"),Z.parent.child=null};function A6(Z,Y,X){return(...G)=>{return q0(Z,Y).run(G,X)}}function sU(Z,Y,X){let{token:G,update:{newValue:_,oldValue:$}}=Y;R1(Z,G,X==="newValue"?_:$)}function aU(Z){let{stack:Y}=Z;if(Y)return`
49
- `+Y.split(`
47
+ `)+"}");class X6{config;resolvedConfig;name;get[Y1](){return"scope"}referencesById={};references=[];resolutions={};exportedNames=[];aliases={};resolved=!1;nodesByHash={};intrinsic;constructor(Y,Z){if(this.config=p2(I.config,Z),this.resolvedConfig=p2(I.resolvedConfig,Z),this.name=this.resolvedConfig.name??`anonymousScope${Object.keys(zZ).length}`,this.name in zZ)A(`A Scope already named ${this.name} already exists`);zZ[this.name]=this;let X=Object.entries(Y).map((_)=>this.preparseOwnAliasEntry(..._));for(let[_,G]of X){let $=_;if(_[0]==="#"){if($=_.slice(1),$ in this.aliases)A(s_($));this.aliases[$]=G}else{if($ in this.aliases)A(s_(_));this.aliases[$]=G,this.exportedNames.push($)}if(!y(G,"module")&&!y(G,"generic")&&!E4(G)){let W=this.preparseOwnDefinitionFormat(G,{alias:$});this.resolutions[$]=y(W,"root")?this.bindReference(W):this.createParseContext(W).id}}t_??=this.node("union",{branches:["string","number","object","bigint","symbol",{unit:!0},{unit:!1},{unit:void 0},{unit:null}]},{prereduced:!0}),this.nodesByHash[t_.hash]=this.node("intersection",{},{prereduced:!0}),this.intrinsic=I.intrinsic?o(I.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 n8(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(c2(Y),Y,Z);preparseNode(Y,Z,X){let _=typeof Y==="string"?Y:c2(Z,Y);if(D0(Z)&&Z.kind===_)return Z;if(_==="alias"&&!X?.prereduced){let{reference:W}=s2.implementation.normalize(Z,this);if(W.startsWith("$")){let H=this.resolveRoot(W.slice(1));Z=H,_=H.kind}}else if(_==="union"&&W1(Z,"object")){let W=mQ(Z);if(W?.length===1)Z=W[0],_=c2(Z)}if(D0(Z)&&Z.kind===_)return Z;let $=G2[_].normalize?.(Z,this)??Z;if(D0($))return $.kind===_?$:uQ(_,$.kind);return{...X,$:this,kind:_,def:$,prefix:X.alias??_}}bindReference(Y){let Z;if(D0(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)??A(EZ(Y))}maybeResolveRoot(Y){let Z=this.maybeResolve(Y);if(y(Z,"generic"))return;return Z}maybeResolveSubalias(Y){return UZ(this.aliases,Y)??UZ(this.ambient,Y)}get ambient(){return I.ambient}maybeResolve(Y){let Z=this.resolutions[Y];if(Z){if(typeof Z!=="string")return this.bindReference(Z);let _=Z1[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: ${i(_)}`);_.phase="resolving";let G=this.bindReference(this.parseOwnDefinitionFormat(_.def,_));return _.phase="resolved",Z1[G.id]=G,Z1[_.id]=G,this.resolutions[Y]=G}return _0(`Unexpected nodesById entry for ${Z}: ${i(_)}`)}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)A(GG(Y));return this.resolutions[Y]=this.bindReference(X.root)}return this.resolutions[Y]=this.parse(X,{alias:Y})}createParseContext(Y){let Z=Y.id??iY(Y.prefix);return Z1[Z]=Object.assign(Y,{[Y1]:"context",$:this,id:Z,phase:"unresolved"})}traversal(Y){return new x1(Y,this.resolvedConfig)}import(...Y){return new H2(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")?QZ(_,this):a_(this.maybeResolve(X))}for(let X of this.lazyResolutions)X.resolution;if(this._exportedResolutions=_G(this,this._exports),this._json=XG(this._exportedResolutions),Object.assign(this.resolutions,this._exportedResolutions),this.references=Object.values(this.referencesById),!this.resolvedConfig.jitless){let X=ZG(this.references);this.precompilation=X.write(e_,4),YG(this.references,X)}this.resolved=!0}let Z=Y.length?Y:this.exportedNames;return new H2(o(Z,(X,_)=>[_,this._exports[_]]))}resolve(Y){return this.export()[Y]}node=(Y,Z,X={})=>{let _=this.preparseNode(Y,Z,X);if(D0(_))return this.bindReference(_);let G=this.createParseContext(_),$=nY(G),W=this.bindReference($);return Z1[G.id]=W};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);Z1[_.id]=_;let G=this.bindReference(this.parseOwnDefinitionFormat(Y,_));if(G.isCyclic)G=K_(G,_.id);return Z1[_.id]=G,G}finalize(Y){if(a_(Y),!Y.precompilation&&!this.resolvedConfig.jitless)dQ(Y.references);return Y}}class FZ extends X6{parseOwnDefinitionFormat(Y,Z){return nY(Z)}preparseOwnDefinitionFormat(Y,Z){return this.preparseNode(c2(Y),Y,Z)}preparseOwnAliasEntry(Y,Z){return[Y,Z]}normalizeRootScopeValue(Y){return Y}}var a_=(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},XG=(Y)=>o(Y,(Z,X)=>[Z,y(X,"root")||y(X,"generic")?X.json:y(X,"module")?XG(X):_0(`Unexpected resolution ${i(X)}`)]),UZ=(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 A(cQ(_));let $=Z.slice(X+1),W=G[$];if(W===void 0)return UZ(G,$);if(y(W,"root")||y(W,"generic"))return W;if(y(W,"module"))return W.root??A(GG(Z));_0(`Unexpected resolution for alias '${Z}': ${i(W)}`)},_6=(Y,Z)=>new FZ(Y,Z),e2=new FZ({});var _G=(Y,Z)=>{let X={};for(let _ in Z){let G=Z[_];if(y(G,"module")){let $=_G(Y,G),W=o($,(H,Q)=>[`${_}.${H}`,Q]);Object.assign(X,W)}else if(y(G,"root")||y(G,"generic"))X[_]=G;else _0(`Unexpected scope resolution ${i(G)}`)}return X},EZ=(Y)=>`'${Y}' is unresolvable`,cQ=(Y)=>`'${Y}' must reference a module to be accessed using dot syntax`,GG=(Y)=>`Reference to submodule '${Y}' must specify an alias`;e2.export();var{schema:J0,node:J2,defineSchema:kR,generic:K1}=e2;var VZ="^(?:0|[1-9]\\d*)$",lQ=new RegExp(VZ),gR=T0(lQ);var $G=_6({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();I.intrinsic={...$G};var WG=_6({integer:{domain:"number",divisor:1},lengthBoundable:["string",Array],key:["string","symbol"],nonNegativeIntegerString:{domain:"string",pattern:VZ}},{prereducedAliases:!0}).export();Object.assign(I.intrinsic,WG);var oQ=_6({jsonPrimitive:["string","number",{unit:!0},{unit:!1},{unit:null}],jsonObject:{domain:"object",index:{signature:"string",value:"$jsonData"}},jsonData:["$jsonPrimitive","$jsonObject"]},{prereducedAliases:!0}).export(),u={...$G,...WG,...oQ,emptyStructure:J2("structure",{},{prereduced:!0})};I.intrinsic={...u};var JG=(Y)=>typeof Y==="string"&&Y[0]==="d"&&(Y[1]==="'"||Y[1]==='"')&&Y.at(-1)===Y[1],HG=(Y)=>Y.toString()!=="Invalid Date",QG=(Y)=>Y.slice(2,-1),OZ=(Y)=>`'${Y}' could not be parsed by the Date constructor`,zG=(Y,Z)=>iQ(Y,Z),iQ=(Y,Z)=>{let X=new Date(Y);if(HG(X))return X;let _=uX(Y);if(_!==void 0){let G=new Date(_);if(HG(G))return G}return Z?A(Z===!0?OZ(Y):Z):void 0};var DZ=(Y,Z)=>{let X=Y.scanner.shiftUntil(nQ[FG[Z]]);if(Y.scanner.lookahead==="")return Y.error(sQ(X,Z));if(Y.scanner.shift(),Z==="/"){try{new RegExp(X)}catch(_){A(String(_))}Y.root=Y.ctx.$.node("intersection",{domain:"string",pattern:X},{prereduced:!0})}else if(g0(Z,LZ))Y.root=Y.ctx.$.node("unit",{unit:X});else{let _=zG(X,OZ(X));Y.root=Y.ctx.$.node("unit",{meta:X,unit:_})}},LZ={"'":1,'"':1},UG={"/":1,"'":1,'"':1},FG={"d'":"'",'d"':'"',"'":"'",'"':'"',"/":"/"},nQ={"'":(Y)=>Y.lookahead==="'",'"':(Y)=>Y.lookahead==='"',"/":(Y)=>Y.lookahead==="/"},rQ={'"':"double-quote","'":"single-quote","/":"forward slash"},sQ=(Y,Z)=>`${Z}${Y} requires a closing ${rQ[FG[Z]]}`;var EG=(Y)=>`Private type references should not include '#'. Use '${Y}' instead.`,G6="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 VG={">":!0,">=":!0},OG={"<":!0,"<=":!0};var Q2={"<":">",">":"<","<=":">=",">=":"<=","==":"=="},DG=(Y)=>`Unmatched )${Y===""?"":` before ${Y}`}`,W6=(Y)=>`Missing ${Y}`,LG=(Y,Z)=>`Left bounds are only valid when paired with right bounds (try ...${Z}${Y})`,H6=(Y)=>`Left-bounded expressions must specify their limits using < or <= (was ${Y})`,MG=(Y,Z,X,_)=>`An expression may have at most one left bound (parsed ${Y}${Q2[Z]}, ${X}${Q2[_]})`;var AG=(Y,Z,X)=>RG(Y,Z,X,[]),RG=(Y,Z,X,_)=>{let G=X.parseUntilFinalizer();if(_.push(G.root),G.finalizer===">"){if(_.length!==Z.params.length)return X.error(MZ(Y,Z.names,_.map(($)=>$.expression)));return _}if(G.finalizer===",")return RG(Y,Z,X,_);return G.error(W6(">"))},MZ=(Y,Z,X)=>`${Y}<${Z.join(", ")}> requires exactly ${Z.length} args (got ${X.length}${X.length===0?"":`: ${X.join(", ")}`})`;var AZ=(Y)=>{let Z=Y.scanner.shiftUntilNextTerminator();if(Z==="keyof")Y.addPrefix("keyof");else Y.root=aQ(Y,Z)},tQ=(Y,Z,X)=>{if(X.scanner.shiftUntilNonWhitespace(),X.scanner.shift()!=="<")return X.error(MZ(Y,Z.names,[]));let G=AG(Y,Z,X);return Z(...G)},aQ=(Y,Z)=>eQ(Y,Z)??Yz(Y,Z)??Y.error(Z===""?Y.scanner.lookahead==="#"?EG(Y.shiftedByOne().scanner.shiftUntilNextTerminator()):RZ(Y):EZ(Z)),eQ=(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 tQ(Z,X,Y);return A(`Unexpected resolution ${i(X)}`)},Yz=(Y,Z)=>{let X=dX(Z);if(X!==void 0)return Y.ctx.$.node("unit",{unit:X});let _=lX(Z);if(_!==void 0)return Y.ctx.$.node("unit",{unit:_})},RZ=(Y)=>{let Z=Y.previousOperator();return Z?wZ(Z,Y.scanner.unscanned):Zz(Y.scanner.unscanned)},wZ=(Y,Z="")=>`Token '${Y}' requires a right operand${Z?` before '${Z}'`:""}`,Zz=(Y)=>`Expected an expression${Y?` before '${Y}'`:""}`;var NZ=(Y)=>Y.scanner.lookahead===""?Y.error(RZ(Y)):Y.scanner.lookahead==="("?Y.shiftedByOne().reduceGroupOpen():Y.scanner.lookaheadIsIn(UG)?DZ(Y,Y.scanner.shift()):Y.scanner.lookaheadIsIn(V4)?NZ(Y.shiftedByOne()):Y.scanner.lookahead==="d"?Y.scanner.nextLookahead in LZ?DZ(Y,`${Y.scanner.shift()}${Y.scanner.shift()}`):AZ(Y):AZ(Y);class _4 extends CY{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,...V4};static finalizingLookaheads={">":1,",":1,"":1,"=":1,"?":1};static lookaheadIsFinalizing=(Y,Z)=>Y===">"?Z[0]==="="?Z[1]==="=":Z.trimStart()===""||g0(Z.trimStart()[0],_4.terminatingChars):Y==="="?Z[0]!=="=":Y===","||Y==="?"}var NG=(Y,Z)=>{let X=Xz(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 Gz(Y,X)},IG={"<":1,">":1,"=":1},Xz=(Y,Z)=>Y.scanner.lookaheadIs("=")?`${Z}${Y.scanner.shift()}`:Z;var wG=(Y,Z,X,_)=>{if(X.extends(I.intrinsic.number)){if(typeof Z!=="number")return A(IZ(Y,Z,_));return Y==="=="?["min","max"]:Y[0]===">"?["min"]:["max"]}if(X.extends(I.intrinsic.lengthBoundable)){if(typeof Z!=="number")return A(IZ(Y,Z,_));return Y==="=="?["exactLength"]:Y[0]===">"?["minLength"]:["maxLength"]}if(X.extends(I.intrinsic.Date))return Y==="=="?["after","before"]:Y[0]===">"?["after"]:["before"];return A(U_(X.expression))},_z=(Y)=>({rule:JG(Y.limit)?QG(Y.limit):Y.limit,exclusive:Y.comparator.length===1}),Gz=(Y,Z)=>{let X=Y.unsetRoot(),_=Y.scanner.location;Y.parseOperand();let G=Y.unsetRoot(),$=Y.scanner.sliceChars(_,Y.scanner.location);if(Y.root=X,!G.hasKind("unit")||typeof G.unit!=="number"&&!(G.unit instanceof Date))return Y.error(IZ(Z,$,"right"));let W=G.unit,H=Z.length===1,Q=wG(Z,typeof W==="number"?W:$,X,"right");for(let z of Q)Y.constrainRoot(z,Z==="=="?{rule:W}:{rule:W,exclusive:H});if(!Y.branches.leftBound)return;if(!g0(Z,OG))return Y.error(H6(Z));let J=wG(Y.branches.leftBound.comparator,Y.branches.leftBound.limit,X,"left");Y.constrainRoot(J[0],_z(Y.branches.leftBound)),Y.branches.leftBound=null},IZ=(Y,Z,X)=>`Comparator ${X==="left"?Q2[Y]:Y} must be ${X==="left"?"preceded":"followed"} by a corresponding literal (was ${Z})`;var KG=(Y)=>{Y.scanner.shiftUntilNonWhitespace();let Z=Y.scanner.shiftUntilNextTerminator();Y.root=Y.root.brand(Z)};var TG=(Y)=>{let Z=Y.scanner.shiftUntilNextTerminator(),X=cX(Z,{errorOnFail:BG(Z)});if(X===0)Y.error(BG(0));Y.root=Y.root.constrain("divisor",X)},BG=(Y)=>`% operator must be followed by a non-zero integer literal (was ${Y})`;var KZ=(Y)=>{let Z=Y.scanner.shift();return Z===""?Y.finalize(""):Z==="["?Y.scanner.shift()==="]"?Y.setRoot(Y.root.array()):Y.error($z):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):g0(Z,IG)?NG(Y,Z):Z==="%"?TG(Y):Z==="#"?KG(Y):(Z in V4)?KZ(Y):Y.error(J6(Z))},J6=(Y,Z="")=>`'${Y}' is not allowed here${Z&&` (should be ${Z})`}`,$z="Missing expected ']'";var CG=(Y)=>{let Z=Y.unsetRoot();Y.parseOperand();let X=Y.unsetRoot();if(!X.hasKind("unit"))return Y.error(Wz(X.expression));let _=X.unit instanceof Date?()=>new Date(X.unit):X.unit;return[Z,"=",_]},Wz=(Y)=>`Default value '${Y}' must a literal value`;var BZ=(Y,Z)=>{let X=Z.$.maybeResolveRoot(Y);if(X)return X;if(Y.endsWith("[]")){let $=Z.$.maybeResolveRoot(Y.slice(0,-2));if($)return $.array()}let _=new z2(new _4(Y),Z),G=Hz(_);if(_.finalizer===">")A(J6(">"));return G},Hz=(Y)=>{Y.parseOperand();let Z=Y8(Y).root;if(!Z)return _0(`Root was unexpectedly unset after parsing string '${Y.scanner.scanned}'`);if(Y.finalizer==="=")Z=CG(Y);else if(Y.finalizer==="?")Z=[Z,"?"];if(Y.scanner.shiftUntilNonWhitespace(),Y.scanner.lookahead)A(J6(Y.scanner.lookahead));return Z},Y8=(Y)=>{while(Y.finalizer===void 0)Jz(Y);return Y},Jz=(Y)=>Y.hasRoot()?Y.parseOperator():Y.parseOperand();class z2{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 A(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(W6(")"));this.finalizeBranches(),this.finalizer=Y}reduceLeftBound(Y,Z){let X=Q2[Z];if(!g0(X,VG))return this.error(H6(Z));if(this.branches.leftBound)return this.error(MG(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(DG(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 Y8(new z2(this.scanner,this.ctx))}parseOperator(){return KZ(this)}parseOperand(){return NZ(this)}assertRangeUnset(){if(this.branches.leftBound)return this.error(LG(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 Qz="An empty string is not a valid generic parameter name",Q6=(Y,Z,X)=>{Y.shiftUntilNonWhitespace();let _=Y.shiftUntilNextTerminator();if(_===""){if(Y.lookahead===""&&Z.length)return Z;return A(Qz)}return Y.shiftUntilNonWhitespace(),zz(Y,_,Z,X)},qG="extends ",zz=(Y,Z,X,_)=>{if(Y.shiftUntilNonWhitespace(),Y.unscanned.startsWith(qG))Y.jumpForward(qG.length);else{if(Y.lookahead===",")Y.shift();return X.push(Z),Q6(Y,X,_)}let G=Y8(new z2(Y,_));return X.push([Z,G.root]),Q6(Y,X,_)};class TZ extends v1{$;constructor(Y){super((...Z)=>new Z8(Y)(...Z),{bind:Y});this.$=Y}in(Y){return new Z8(this.$,Y===void 0?void 0:this.$.parse(Y))}at(Y,Z){return new Z8(this.$).at(Y,Z)}case(Y,Z){return new Z8(this.$).case(Y,Z)}}class Z8 extends v1{$;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)A(Fz);if(this.branches.length)A(Uz);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)A("default may only be specified as the last key of a switch definition");return this.default(_)}if(typeof _!=="function")return A(`Value for case "${X}" must be a function (was ${y0(_)})`);this.caseEntry(X,_)}return this}default(Y){if(typeof Y==="function")this.case(u.unknown,Y);let Z={branches:this.branches,ordered:!0};if(Y==="never"||Y==="assert")Z.meta={onFail:jG};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:jG},"self");return this.$.finalize(_)}}var jG=(Y)=>Y.throw(),Uz="A key matcher must be specified before the first case i.e. match.at('foo') or match.in<object>().at('bar')",Fz="At most one key matcher may be specified per expression";var z6=(Y,Z)=>{if(U0(Y)){if(Y[1]==="=")return[Z.$.parseOwnDefinitionFormat(Y[0],Z),"=",Y[2]];if(Y[1]==="?")return[Z.$.parseOwnDefinitionFormat(Y[0],Z),"?"]}return U6(Y,Z)},PG="Only required keys may make their values optional, e.g. { [mySymbol]: ['number', '?'] }",SG="Only required keys may specify default values, e.g. { value: 'number = 0' }";var vG=(Y,Z)=>{let X,_={},G=q4(Y);for(let[W,H]of G){let Q=Oz(W);if(Q.kind==="spread"){if(!l1(_))return A(Vz);let L=Z.$.parseOwnDefinitionFormat(H,Z);if(L.equals(u.object))continue;if(!L.hasKind("intersection")||!L.basis?.equals(u.object))return A(Dz(L.expression));X=L.structure;continue}if(Q.kind==="undeclared"){if(H!=="reject"&&H!=="delete"&&H!=="ignore")A(Ez(H));_.undeclared=H;continue}let J=z6(H,Z),z=Q;if(Q.kind==="required"){if(!U0(J))CZ(_,"required",{key:Q.normalized,value:J},Z);else CZ(_,"optional",J[1]==="="?{key:Q.normalized,value:J[0],default:J[2]}:{key:Q.normalized,value:J[0]},Z);continue}if(U0(J)){if(J[1]==="?")A(PG);if(J[1]==="=")A(SG)}if(Q.kind==="optional"){CZ(_,"optional",{key:Q.normalized,value:J},Z);continue}let F=Z.$.parseOwnDefinitionFormat(z.normalized,Z),O=Z6(F,J,Z.$);if(O.index)_.index=Z0(_.index,O.index);if(O.required)_.required=Z0(_.required,O.required)}let $=Z.$.node("structure",_);return Z.$.parseSchema({domain:"object",structure:X?.merge($)??$})},CZ=(Y,Z,X,_)=>{Y[Z]=Z0(Y[Z],_.$.node(Z,X))},Ez=(Y)=>`Value of '+' key must be 'reject', 'delete', or 'ignore' (was ${i(Y)})`,Vz="Spread operator may only be used as the first key in an object",Oz=(Y)=>typeof Y==="symbol"?{kind:"required",normalized:Y}:Y.at(-1)==="?"?Y.at(-2)===x2?{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]===x2&&Y[1]==="["&&Y.at(-1)==="]"?{kind:"required",normalized:Y.slice(1)}:Y==="..."?{kind:"spread"}:Y==="+"?{kind:"undeclared"}:{kind:"required",normalized:Y==="\\..."?"...":Y==="\\+"?"+":Y},Dz=(Y)=>`Spread operand must resolve to an object literal type (was ${Y})`;var fG=(Y,Z)=>Tz(Y)?yG[Y[0]](Y,Z):Kz(Y)?bG[Y[1]](Y,Z):null,Lz=(Y,Z)=>Z.$.parseOwnDefinitionFormat(Y[1],Z).keyof(),qZ=(Y,Z)=>{if(Y[2]===void 0)return A(wZ(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]==="&"?z1(X,_,Z.$):d2(X,_,Z.$);if(G instanceof S)return G.throw();return G},Mz=(Y,Z)=>Z.$.parseOwnDefinitionFormat(Y[0],Z).array(),Az=(Y,Z)=>{if(typeof Y[2]!=="function")return A(hG("=>",Y[2]));return Z.$.parseOwnDefinitionFormat(Y[0],Z).pipe(Y[2])},hG=(Y,Z)=>`${Y===":"?"Narrow":"Morph"} expression requires a function following '${Y}' (was ${typeof Z})`,Rz=(Y,Z)=>{if(typeof Y[2]!=="function")return A(hG(":",Y[2]));return Z.$.parseOwnDefinitionFormat(Y[0],Z).constrain("predicate",Y[2])},wz=(Y,Z)=>Z.$.parseOwnDefinitionFormat(Y[0],Z).configureReferences(Y[2],"shallow"),kG=(Y)=>Y,Nz=kG({"[]":Mz,"?":()=>A(G6)}),Iz=kG({"|":qZ,"&":qZ,":":Rz,"=>":Az,"|>":qZ,"@":wz,"=":()=>A($6)}),bG={...Nz,...Iz},Kz=(Y)=>bG[Y[1]]!==void 0,Bz=(Y)=>Y,yG=Bz({keyof:Lz,instanceof:(Y,Z)=>{if(typeof Y[1]!=="function")return A(xG(S2(Y[1])));let X=Y.slice(1).map((_)=>typeof _==="function"?Z.$.node("proto",{proto:_}):A(xG(S2(_))));return X.length===1?X[0]:Z.$.node("union",{branches:X})},"===":(Y,Z)=>Z.$.units(Y.slice(1))}),Tz=(Y)=>yG[Y[0]]!==void 0,xG=(Y)=>`Expected a constructor following 'instanceof' operator (was ${Y})`;var mG=(Y,Z)=>{let X=[{}],_=0;while(_<Y.length){let G=!1;if(Y[_]==="..."&&_<Y.length-1)G=!0,_++;let $=z6(Y[_],Z),[W,H,Q]=!U0($)?[$]:$;if(_++,G){if(!W.extends(I.intrinsic.Array))return A(jz(W.expression));X=X.flatMap((J)=>W.distribute((z)=>qz(c8(J),z)))}else X=X.map((J)=>{if(H==="?")return uG(J,W);if(H==="=")return Cz(J,W,Q);return jZ(J,W)})}return Z.$.parseSchema(X.map((G)=>l1(G)?{proto:Array,exactLength:0}:{proto:Array,sequence:G}))},jZ=(Y,Z)=>{if(Y.defaultables||Y.optionals)return A(Y.variadic?WZ:Pz);if(Y.variadic)Y.postfix=Z0(Y.postfix,Z);else Y.prefix=Z0(Y.prefix,Z);return Y},uG=(Y,Z)=>{if(Y.variadic)return A(dG);return Y.optionals=Z0(Y.optionals,Z),Y},Cz=(Y,Z,X)=>{if(Y.variadic)return A(dG);if(Y.optionals)return A(Sz);return Y.defaultables=Z0(Y.defaultables,[[Z,X]]),Y},gG=(Y,Z)=>{if(Y.postfix)A(pG);if(Y.variadic){if(!Y.variadic.equals(Z))A(pG)}else Y.variadic=Z.internal;return Y},qz=(Y,Z)=>{let X=Z.select({method:"find",kind:"sequence"});if(!X)return gG(Y,I.intrinsic.unknown);if(X.prefix)for(let _ of X.prefix)jZ(Y,_);if(X.optionals)for(let _ of X.optionals)uG(Y,_);if(X.variadic)gG(Y,X.variadic);if(X.postfix)for(let _ of X.postfix)jZ(Y,_);return Y},jz=(Y)=>`Spread element must be an array (was ${Y})`,pG="A tuple may have at most one variadic element",Pz="A required element may not follow an optional element",dG="An optional element may not follow a variadic element";var Sz="A defaultable element may not follow an optional element without a default";var vz={},U6=(Y,Z)=>{if(typeof Y==="string"){if(Z.args&&Object.keys(Z.args).some((_)=>Y.includes(_)))return BZ(Y,Z);let X=vz[Z.$.name]??={};return X[Y]??=BZ(Y,Z)}return W1(Y,"object")?xz(Y,Z):A(PZ(y0(Y)))},xz=(Y,Z)=>{let X=P2(Y);switch(X){case void 0:if(y(Y,"root"))return Y;return vG(Y,Z);case"Array":return fz(Y,Z);case"RegExp":return Z.$.node("intersection",{domain:"string",pattern:Y},{prereduced:!0});case"Function":{let _=E4(Y)?Y():Y;if(y(_,"root"))return _;return A(PZ("Function"))}default:return A(PZ(X??i(Y)))}},fz=(Y,Z)=>fG(Y,Z)??mG(Y,Z),PZ=(Y)=>`Type definitions must be strings or objects (was ${Y})`;class SZ extends v1{constructor(Y){let Z=Object.assign({errors:J1,hkt:r0,$: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 U2=I;class F6 extends X6{get ambientAttachments(){if(!U2.typeAttachments)return;return this.cacheGetter("ambientAttachments",o(U2.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 $=this.name==="ark"?Y:Y==="root"?this.name:`${this.name}.${Y}`,W=this.resolvedConfig.keywords?.[$];if(W)Z=[Z,"@",W];return[Y,Z]}if(Y.at(-1)!==">")A("'>' 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 $=this.parseGenericParams(G,{alias:_});return J_($,Z,this)}]}parseGenericParams(Y,Z){return Q6(new _4(Y),[],this.createParseContext({...Z,def:Y,prefix:"generic"}))}normalizeRootScopeValue(Y){if(E4(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 _=U6(Y,Z);if(U0(_)){if(_[1]==="=")return A($6);if(_[1]==="?")return A(G6)}return _}unit=(Y)=>this.units([Y]);valueOf=(Y)=>this.units(qX(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 TZ(this);declare=()=>({type:this.type});define(Y){return Y}type=new SZ(this);static scope=(Y,Z={})=>new F6(Y,Z);static module=(Y,Z={})=>this.scope(Y,Z).export()}var vZ=Object.assign(F6.scope,{define:(Y)=>Y}),e=F6;class cG extends r0{description='merge an object\'s properties onto another like `Merge(User, { isAdmin: "true" })`'}var hz=K1(["base",u.object],["props",u.object])((Y)=>Y.base.merge(Y.props),cG),lG=e.module({Key:u.key,Merge:hz});class oG extends r0{}var kz=K1("element")((Y)=>{let Z=Y.element.exclude(u.Array),X=Z.array();return Z.rawOr(X).pipe(F4).distribute((_)=>_.assertHasKind("morph").declareOut(X),J0)},oG),iG=e.module({root:u.Array,readonly:"root",index:u.nonNegativeIntegerString,liftFrom:kz},{name:"Array"});var xZ=J0(["string",P4.FileConstructor]),bz=xZ.rawOr(xZ.array()),nG=J0({meta:"an object representing parsed form data",domain:"object",index:{signature:"string",value:bz}}),rG=e.module({root:["instanceof",FormData],value:xZ,parsed:nG,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 P4.FileConstructor)Z[X]=[G,_];else G.push(_)}else Z[X]=_;return Z},declaredOut:nG})},{name:"FormData"});var sG=e.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 yz={Boolean:1,Number:1,String:1},tG=e.module({...o({...AY,...wY},(Y,Z)=>(Y in yz)?[]:[Y,["instanceof",Z]]),Array:iG,TypedArray:sG,FormData:rG});var gz=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"}),pz=J0({domain:"number",divisor:1}),E6=e.module({root:u.number,integer:pz,epoch:gz,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 N0=(Y,Z,X)=>{let _={domain:"string",pattern:{rule:Y.source,flags:Y.flags,meta:Z}};if(X)_.meta={format:X};return J2("intersection",_)},aG=N0(f2,"a well-formed integer string"),z9=e.module({root:aG,parse:J0({in:aG,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:u.integer})},{name:"string.integer"}),mz=N0(/^[\dA-Fa-f]+$/,"hex characters only"),uz=e.module({root:N0(/^(?:[\d+/A-Za-z]{4})*(?:[\d+/A-Za-z]{2}==|[\d+/A-Za-z]{3}=)?$/,"base64-encoded"),url:N0(/^(?:[\w-]{4})*(?:[\w-]{2}(?:==|%3D%3D)?|[\w-]{3}(?:=|%3D)?)?$/,"base64url-encoded")},{name:"string.base64"}),eG=N0(/^[A-Z].*$/,"capitalized"),dz=e.module({root:J0({in:"string",morphs:(Y)=>Y.charAt(0).toUpperCase()+Y.slice(1),declaredOut:eG}),preformatted:eG},{name:"string.capitalize"}),cz=(Y)=>{let Z=Y.replaceAll(/[ -]+/g,""),X=0,_,G,$=!1;for(let W=Z.length-1;W>=0;W--){if(_=Z.substring(W,W+1),G=Number.parseInt(_,10),$)G*=2,X+=G>=10?G%10+1:G;else X+=G;$=!$}return!!(X%10===0?Z:!1)},lz=/^(?: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}))$/,oz=J0({domain:"string",pattern:{meta:"a credit card number",rule:lz.source},predicate:{meta:"a credit card number",predicate:cz}});var iz=/^([+-]?\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 nz=(Y)=>!Number.isNaN(new Date(Y).valueOf()),Y9=J0({domain:"string",predicate:{meta:"a parsable date",predicate:nz}}).assertHasKind("intersection"),Z9=z9.root.internal.narrow((Y,Z)=>{let X=Number.parseInt(Y),_=E6.epoch(X);if(_ instanceof J1)return Z.errors.merge(_),!1;return!0}).configure({description:"an integer string representing a safe Unix timestamp"},"self").assertHasKind("intersection"),rz=e.module({root:Z9,parse:J0({in:Z9,morphs:(Y)=>new Date(Y),declaredOut:u.Date})},{name:"string.date.epoch"}),X9=N0(iz,"an ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) date").internal.assertHasKind("intersection"),sz=e.module({root:X9,parse:J0({in:X9,morphs:(Y)=>new Date(Y),declaredOut:u.Date})},{name:"string.date.iso"}),tz=e.module({root:Y9,parse:J0({declaredIn:Y9,in:"string",morphs:(Y,Z)=>{let X=new Date(Y);if(Number.isNaN(X.valueOf()))return Z.error("a parsable date");return X},declaredOut:u.Date}),iso:sz,epoch:rz},{name:"string.date"}),az=N0(/^[\w%+.-]+@[\d.A-Za-z-]+\.[A-Za-z]{2,}$/,"an email address","email"),_9="(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])",A4=`(${_9}[.]){3}${_9}`,ez=new RegExp(`^${A4}$`),x0="(?:[0-9a-fA-F]{1,4})",YU=new RegExp(`^((?:${x0}:){7}(?:${x0}|:)|(?:${x0}:){6}(?:${A4}|:${x0}|:)|(?:${x0}:){5}(?::${A4}|(:${x0}){1,2}|:)|(?:${x0}:){4}(?:(:${x0}){0,1}:${A4}|(:${x0}){1,3}|:)|(?:${x0}:){3}(?:(:${x0}){0,2}:${A4}|(:${x0}){1,4}|:)|(?:${x0}:){2}(?:(:${x0}){0,3}:${A4}|(:${x0}){1,5}|:)|(?:${x0}:){1}(?:(:${x0}){0,4}:${A4}|(:${x0}){1,6}|:)|(?::((?::${x0}){0,5}:${A4}|(?::${x0}){1,7}|:)))(%[0-9a-zA-Z.]{1,})?$`),ZU=e.module({root:["v4 | v6","@","an IP address"],v4:N0(ez,"an IPv4 address","ipv4"),v6:N0(YU,"an IPv6 address","ipv6")},{name:"string.ip"}),F2="a JSON string",U9=(Y)=>{if(!(Y instanceof SyntaxError))throw Y;return`must be ${F2} (${Y})`},XU=J0({meta:F2,domain:"string",predicate:{meta:F2,predicate:(Y,Z)=>{try{return JSON.parse(Y),!0}catch(X){return Z.reject({code:"predicate",expected:F2,problem:U9(X)})}}}}),_U=(Y,Z)=>{if(Y.length===0)return Z.error({code:"predicate",expected:F2,actual:"empty"});try{return JSON.parse(Y)}catch(X){return Z.error({code:"predicate",expected:F2,problem:U9(X)})}},GU=e.module({root:XU,parse:J0({meta:"safe JSON string parser",in:"string",morphs:_U,declaredOut:u.jsonObject})},{name:"string.json"}),G9=N0(/^[a-z]*$/,"only lowercase letters"),$U=e.module({root:J0({in:"string",morphs:(Y)=>Y.toLowerCase(),declaredOut:G9}),preformatted:G9},{name:"string.lower"}),F9=["NFC","NFD","NFKC","NFKD"],X8=o(F9,(Y,Z)=>[Z,J0({domain:"string",predicate:(X)=>X.normalize(Z)===X,meta:`${Z}-normalized unicode`})]),V6=o(F9,(Y,Z)=>[Z,J0({in:"string",morphs:(X)=>X.normalize(Z),declaredOut:X8[Z]})]),WU=e.module({root:V6.NFC,preformatted:X8.NFC},{name:"string.normalize.NFC"}),HU=e.module({root:V6.NFD,preformatted:X8.NFD},{name:"string.normalize.NFD"}),JU=e.module({root:V6.NFKC,preformatted:X8.NFKC},{name:"string.normalize.NFKC"}),QU=e.module({root:V6.NFKD,preformatted:X8.NFKD},{name:"string.normalize.NFKD"}),zU=e.module({root:"NFC",NFC:WU,NFD:HU,NFKC:JU,NFKD:QU},{name:"string.normalize"}),$9=N0(m8,"a well-formed numeric string"),UU=e.module({root:$9,parse:J0({in:$9,morphs:(Y)=>Number.parseFloat(Y),declaredOut:u.number})},{name:"string.numeric"}),W9="a regex pattern",FU=J0({domain:"string",predicate:{meta:W9,predicate:(Y,Z)=>{try{return new RegExp(Y),!0}catch(X){return Z.reject({code:"predicate",expected:W9,problem:String(X)})}}},meta:{format:"regex"}}),EU=/^(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-]+)*))?$/,VU=N0(EU,"a semantic version (see https://semver.org/)"),H9=N0(/^\S.*\S$|^\S?$/,"trimmed"),OU=e.module({root:J0({in:"string",morphs:(Y)=>Y.trim(),declaredOut:H9}),preformatted:H9},{name:"string.trim"}),J9=N0(/^[A-Z]*$/,"only uppercase letters"),DU=e.module({root:J0({in:"string",morphs:(Y)=>Y.toUpperCase(),declaredOut:J9}),preformatted:J9},{name:"string.upper"}),LU=(Y)=>{if(URL.canParse)return URL.canParse(Y);try{return new URL(Y),!0}catch{return!1}},Q9=J0({domain:"string",predicate:{meta:"a URL string",predicate:LU},meta:{format:"uri"}}),MU=e.module({root:Q9,parse:J0({declaredIn:Q9,in:"string",morphs:(Y,Z)=>{try{return new URL(Y)}catch{return Z.error("a URL string")}},declaredOut:J0(URL)})},{name:"string.url"}),AU=e.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:N0(/^[\da-f]{8}-[\da-f]{4}-1[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv1"),v2:N0(/^[\da-f]{8}-[\da-f]{4}-2[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv2"),v3:N0(/^[\da-f]{8}-[\da-f]{4}-3[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv3"),v4:N0(/^[\da-f]{8}-[\da-f]{4}-4[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv4"),v5:N0(/^[\da-f]{8}-[\da-f]{4}-5[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv5"),v6:N0(/^[\da-f]{8}-[\da-f]{4}-6[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv6"),v7:N0(/^[\da-f]{8}-[\da-f]{4}-7[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv7"),v8:N0(/^[\da-f]{8}-[\da-f]{4}-8[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv8")},{name:"string.uuid"}),E9=e.module({root:u.string,alpha:N0(/^[A-Za-z]*$/,"only letters"),alphanumeric:N0(/^[\dA-Za-z]*$/,"only letters and digits 0-9"),hex:mz,base64:uz,capitalize:dz,creditCard:oz,date:tz,digits:N0(/^\d*$/,"only digits 0-9"),email:az,integer:z9,ip:ZU,json:GU,lower:$U,normalize:zU,numeric:UU,regex:FU,semver:VU,trim:OU,upper:DU,url:MU,uuid:AU},{name:"string"});var V9=e.module({bigint:u.bigint,boolean:u.boolean,false:u.false,never:u.never,null:u.null,number:u.number,object:u.object,string:u.string,symbol:u.symbol,true:u.true,unknown:u.unknown,undefined:u.undefined}),O9=e.module({root:u.unknown,any:u.unknown},{name:"unknown"}),RU=e.module({root:u.jsonObject,stringify:J2("morph",{in:u.jsonObject,morphs:(Y)=>JSON.stringify(Y),declaredOut:u.string})},{name:"object.json"}),D9=e.module({root:u.object,json:RU},{name:"object"});class L9 extends r0{description='instantiate an object from an index signature and corresponding value type like `Record("string", "number")`'}var wU=K1(["K",u.key],"V")((Y)=>({domain:"object",index:{signature:Y.K,value:Y.V}}),L9);class M9 extends r0{description='pick a set of properties from an object like `Pick(User, "name | age")`'}var NU=K1(["T",u.object],["K",u.key])((Y)=>Y.T.pick(Y.K),M9);class A9 extends r0{description='omit a set of properties from an object like `Omit(User, "age")`'}var IU=K1(["T",u.object],["K",u.key])((Y)=>Y.T.omit(Y.K),A9);class R9 extends r0{description="make all named properties of an object optional like `Partial(User)`"}var KU=K1(["T",u.object])((Y)=>Y.T.partial(),R9);class w9 extends r0{description="make all named properties of an object required like `Required(User)`"}var BU=K1(["T",u.object])((Y)=>Y.T.required(),w9);class N9 extends r0{description='exclude branches of a union like `Exclude("boolean", "true")`'}var TU=K1("T","U")((Y)=>Y.T.exclude(Y.U),N9);class I9 extends r0{description='extract branches of a union like `Extract("0 | false | 1", "number")`'}var CU=K1("T","U")((Y)=>Y.T.extract(Y.U),I9),K9=e.module({Exclude:TU,Extract:CU,Omit:IU,Partial:KU,Pick:NU,Record:wU,Required:BU});var R4=vZ({...V9,...K9,...tG,...lG,string:E9,number:E6,object:D9,unknown:O9},{prereducedAliases:!0,name:"ark"}),p0=R4.export();Object.assign(U2.ambient,p0);U2.typeAttachments={string:p0.string.root,number:p0.number.root,bigint:p0.bigint,boolean:p0.boolean,symbol:p0.symbol,undefined:p0.undefined,null:p0.null,object:p0.object.root,unknown:p0.unknown.root,false:p0.false,true:p0.true,never:p0.never,arrayIndex:p0.Array.index,Key:p0.Key,Record:p0.Record,Array:p0.Array.root,Date:p0.Date};var U1=Object.assign(R4.type,U2.typeAttachments),qU=R4.match,jU=R4.generic,HK=R4.schema,PU=R4.define,SU=R4.declare;function E2(Y){return w6(F1.STORE,Y,void 0)}function V2(Y){return O2(F1.STORE,Y)}function hZ(...Y){return h1(F1.STORE,...Y)}function O6(Y,Z){return x9(F1.STORE,Y,Z)}function B9(Y){return f9(Y,F1.STORE)}var G4={atom_family:"atom family",atom:"atom",continuity:"continuity",key:"key",mutable_atom_family:"atom family [m]",mutable_atom:"atom [m]",readonly_held_selector_family:"selector family [h]",readonly_held_selector:"selector [h]",readonly_pure_selector_family:"selector family",readonly_pure_selector:"selector",state:"state",timeline:"timeline",transaction:"transaction",unknown:"unknown",writable_held_selector_family:"selector family [wh]",writable_held_selector:"selector [wh]",writable_pure_selector_family:"selector family [w]",writable_pure_selector:"selector [w]"};var fZ=(Y)=>(Z,X,_,G,...$)=>{console[Y](`${Z} ${G4[X]} \`${_}\` ${G}`,...$)},vU={error:fZ("error"),info:fZ("info"),warn:fZ("warn")},T9=class{logLevel;filter;logger;constructor(Y,Z,X=vU){this.logLevel=Y,this.filter=Z,this.logger=X}error=(...Y)=>{if(this.logLevel!==null){let Z=this.filter?.(...Y)??!0;if(Z===!0)this.logger.error(...Y);else if(Z)this.logger.error(...Z)}};info=(...Y)=>{if(this.logLevel==="info"){let Z=this.filter?.(...Y)??!0;if(Z===!0)this.logger.info(...Y);else if(Z)this.logger.info(...Z)}};warn=(...Y)=>{if(this.logLevel!=="error"&&this.logLevel!==null){let Z=this.filter?.(...Y)??!0;if(Z===!0)this.logger.warn(...Y);else if(Z)this.logger.warn(...Z)}}};var C9=class{store;deallocateTX;claimTX;constructor(Y=F1.STORE){this.store=Y,this.deallocateTX=j9(Y),this.claimTX=P9(Y),q9(Y,"root")}allocate(Y,Z,X){A6(this.store,Y,Z,X)}deallocate(Y){M6(this.store,this.deallocateTX,kZ())(Y)}claim(Y,Z,X){_8(this.store,Y,Z,X)}};function D6(Y){return bZ(F1.STORE,Y)}function L6(Y){return G8(F1.STORE,Y)}function X1(Y){return JSON.parse(Y)}var $0=(Y)=>JSON.stringify(Y),vK=[Array.prototype,Boolean.prototype,Number.prototype,Object.prototype,String.prototype];var h9=class Y extends Set{mode="record";subject=new G0;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]=_})}READONLY_VIEW=this;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:${$0(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:${$0(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 _ of this.transactionUpdates)this.doStep(_);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 $ of G.split(";"))this.doStep($)}}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||Number.isNaN(G)){if(G===1||Number.isNaN(G)){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 W=!1;while(!W){this.cacheIdx%=this.cacheLimit;let Q=this.cache[this.cacheIdx];if(this.cacheIdx--,!Q)return"OUT_OF_RANGE";this.undo(Q),W=this.cacheIdx===$-1}let H=Z.substring(X+1);return this.doStep(H),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 $=JSON.parse(G);for(let W of $)this.add(W);break}case"tx":{let $=G.split(";");for(let W=$.length-1;W>=0;W--)this.undoStep($[W])}}}undo(Z){let X=Z.indexOf("=");if(Number(Z.substring(0,X))===this.cacheUpdateNumber){this.mode="playback";let _=Z.substring(X+1);return this.undoStep(_),this.mode="record",this.cacheUpdateNumber--,null}return this.cacheUpdateNumber}};function kZ(Y=Math.random){return Y().toString(36).slice(2)}function Y0(Y){while(Y.child!==null)Y=Y.child;return Y}function fU(Y){while(Y.parent!==null)Y=Y.parent;return Y}var hU=/^\[object (?:Async|Generator|AsyncGenerator)?Function\]$/;function H8(Y){let Z=Object.prototype.toString.call(Y);return hU.test(Z)}function mZ(Y,Z){if(H8(Y))return Y(Z);return Y}var uZ=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}},G0=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 G0{state;constructor(Y){super();this.state=Y}next(Y){this.state=Y,super.next(Y)}},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}};function y1(Y){let Z={key:Y.key,type:Y.type};if("family"in Y)Z.family=Y.family;return Z}var b1=class extends Map{deleted=new Set;changed=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)}set(Y,Z){if(this.deleted.delete(Y),this.source.has(Y))this.changed.add(Y);return 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){if(this.source.has(Y))this.deleted.add(Y),this.changed.delete(Y);return super.delete(Y)}clear(){this.deleted=new Set(this.source.keys()),this.changed.clear(),super.clear()}*[Symbol.iterator](){yield*super[Symbol.iterator]();for(let[Y,Z]of this.source)if(!this.deleted.has(Y)&&!this.changed.has(Y))yield[Y,Z]}*entries(){yield*this[Symbol.iterator]()}*keys(){yield*super.keys();for(let Y of this.source.keys())if(!this.deleted.has(Y)&&!this.changed.has(Y))yield Y}*values(){for(let[,Y]of this[Symbol.iterator]())yield Y}forEach(Y){for(let[Z,X]of this[Symbol.iterator]())Y(X,Z,this)}get size(){return super.size+this.source.size-this.changed.size-this.deleted.size}},p9=class extends Set{deleted=new Set;source;constructor(Y){super();this.source=Y}add(Y){if(this.source.has(Y))return this.deleted.delete(Y),this;return super.add(Y)}hasOwn(Y){return super.has(Y)}has(Y){return!this.deleted.has(Y)&&(super.has(Y)||this.source.has(Y))}delete(Y){if(this.source.has(Y))return this.deleted.add(Y),!0;return super.delete(Y)}clear(){this.deleted=new Set(this.source),super.clear()}*[Symbol.iterator](){yield*super[Symbol.iterator]();for(let Y of this.source)if(!this.deleted.has(Y))yield Y}*iterateOwn(){yield*super[Symbol.iterator]()}get size(){return super.size+this.source.size-this.deleted.size}},yU=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)){let Z=this.source.get(Y),X=new p9(Z);return super.set(Y,X),X}}set(Y,Z){return this.deleted.delete(Y),super.set(Y,Z)}has(Y){return!this.deleted.has(Y)&&(super.has(Y)||this.source.has(Y))}delete(Y){return this.deleted.add(Y),super.delete(Y)}},$4=class Y{a;b;cardinality;relations=new Map;contents=new Map;isAType;isBType;isContent;makeContentKey=(Z,X)=>`${Z}:${X}`;warn;getRelatedKeys(Z){return this.relations.get(Z)}addRelation(Z,X){let _=this.relations.get(Z),G=this.relations.get(X);if(_)_.add(X);else _=new Set([X]),this.relations.set(Z,_);if(G)G.add(Z);else G=new Set([Z]),this.relations.set(X,G)}deleteRelation(Z,X){let _=this.relations.get(Z);if(_){if(_.delete(X),_.size===0)this.relations.delete(Z);let G=this.relations.get(X);if(G){if(G.delete(Z),G.size===0)this.relations.delete(X)}}}replaceRelationsUnsafely(Z,X){this.relations.set(Z,new Set(X));for(let _ of X){let G=new Set().add(Z);this.relations.set(_,G)}}replaceRelationsSafely(Z,X){let _=this.relations.get(Z),G=this.isAType?.(Z)?Z:void 0,$=G===void 0?Z:void 0;if(_)for(let W of _){G??=W,$??=W;let H=this.relations.get(W);if(H){if(H.size===1)this.relations.delete(W);else H.delete(Z);this.contents.delete(this.makeContentKey(G,$))}}this.relations.set(Z,new Set(X));for(let W of X){let H=this.relations.get(W);if(H)H.add(Z);else H=new Set().add(Z),this.relations.set(W,H)}}getContentInternal(Z){return this.contents.get(Z)}setContent(Z,X){this.contents.set(Z,X)}deleteContent(Z){this.contents.delete(Z)}constructor(Z,X){if(this.a=Z.between[0],this.b=Z.between[1],this.cardinality=Z.cardinality,this.isAType=X?.isAType??null,this.isBType=X?.isBType??null,this.isContent=X?.isContent??null,X?.makeContentKey)this.makeContentKey=X.makeContentKey;if(!X?.externalStore){let _=X?.source;if(_===void 0)this.relations=new Map(Z.relations?.map(([G,$])=>[G,new Set($)])),this.contents=new Map(Z.contents);if(_)this.relations=new yU(_.relations),this.contents=new b1(_.contents)}if(X?.externalStore){let _=X.externalStore;if(this.has=(G,$)=>_.has(G,$),this.addRelation=(G,$)=>{_.addRelation(G,$)},this.deleteRelation=(G,$)=>{_.deleteRelation(G,$)},this.replaceRelationsSafely=(G,$)=>{_.replaceRelationsSafely(G,$)},this.replaceRelationsUnsafely=(G,$)=>{_.replaceRelationsUnsafely(G,$)},this.getRelatedKeys=(G)=>_.getRelatedKeys(G),_.getContent)this.getContentInternal=(G)=>{return _.getContent(G)},this.setContent=(G,$)=>{_.setContent(G,$)},this.deleteContent=(G)=>{_.deleteContent(G)};for(let[G,$]of Z.relations??[]){let W=this.isAType?.(G)?G:void 0,H=W===void 0?G:void 0;for(let Q of $)W??=Q,H??=Q,this.addRelation(W,H)}for(let[G,$]of Z.contents??[])this.setContent(G,$)}if(X?.warn)this.warn=X.warn}toJSON(){return{between:[this.a,this.b],cardinality:this.cardinality,relations:[...this.relations.entries()].map(([Z,X])=>[Z,[...X]]),contents:[...this.contents.entries()]}}set(...Z){let X,_,G;switch(Z.length){case 1:{let $=Z[0];X=$[this.a],_=$[this.b],G=void 0;break}case 2:{let $=Z[0];if(typeof $==="string")[X,_]=Z;else X=$[this.a],_=$[this.b],G=Z[1];break}default:X=Z[0],_=Z[1],G=Z[2];break}switch(this.cardinality){case"1:1":{let $=this.getRelatedKey(X);if($&&$!==_)this.delete(X,$)}case"1:n":{let $=this.getRelatedKey(_);if($&&$!==X)this.delete($,_)}break;case"n:n":}if(G){let $=this.makeContentKey(X,_);this.setContent($,G)}return this.addRelation(X,_),this}delete(Z,X){X=typeof X==="string"?X:Z[this.b];let _=typeof Z==="string"?Z:Z[this.a];if(_===void 0&&typeof X==="string"){let G=this.getRelatedKeys(X);if(G)for(let $ of G)this.delete($,X)}else if(typeof _==="string"&&X===void 0){let G=this.getRelatedKeys(_);if(G)for(let $ of G)this.delete(_,$)}else if(typeof _==="string"&&typeof X==="string"){this.deleteRelation(_,X);let G=this.makeContentKey(_,X);this.deleteContent(G)}return this}getRelatedKey(Z){let X=this.getRelatedKeys(Z);if(X){if(X.size>1)this.warn?.(`${X.size} related keys were found for key "${Z}": (${[...X].map((G)=>`"${G}"`).join(", ")}). Only one related key was expected.`);let _;for(let G of X){_=G;break}return _}}replaceRelations(Z,X,_){let G=!Array.isArray(X),$=G?Object.keys(X):X;if(_?.reckless)this.replaceRelationsUnsafely(Z,$);else this.replaceRelationsSafely(Z,$);if(G)for(let W of $){let H=this.makeContentKey(Z,W),Q=X[W];this.setContent(H,Q)}return this}getContent(Z,X){let _=this.makeContentKey(Z,X);return this.getContentInternal(_)}getRelationEntries(Z){let X=Z[this.a],_=Z[this.b];if(X!==void 0&&_===void 0){let G=this.getRelatedKeys(X);if(G)return[...G].map(($)=>{return[$,this.getContent(X,$)]})}if(X===void 0&&_!==void 0){let G=this.getRelatedKeys(_);if(G)return[...G].map(($)=>{return[$,this.getContent($,_)]})}return[]}has(Z,X){if(X)return this.getRelatedKeys(Z)?.has(X)??!1;return this.relations.has(Z)}overlay(){let Z={source:this,makeContentKey:this.makeContentKey};if(this.isAType)Z.isAType=this.isAType;if(this.isBType)Z.isBType=this.isBType;if(this.isContent)Z.isContent=this.isContent;if(this.warn)Z.warn=this.warn;return new Y({between:[this.a,this.b],cardinality:this.cardinality},Z)}incorporate(Z){let{relations:X,contents:_}=Z;for(let[G,$]of X)if($ instanceof p9){let{source:W}=$;for(let H of $.iterateOwn())W.add(H)}else this.relations.set(G,$);for(let G of X.deleted)this.relations.delete(G);for(let[G,$]of _)this.contents.set(G,$);for(let G of _.deleted)this.contents.delete(G)}};function L2(Y){return Y.startsWith("\uD83D\uDD0D ")}var gU=(Y)=>{Y.logger.info("\uD83E\uDE82","transaction",Y.transactionMeta.update.token.key,"Aborting transaction"),Y.parent.child=null};function M6(Y,Z,X){return(..._)=>{return P0(Y,Z).run(_,X)}}function pU(Y,Z,X){let{token:_,update:{newValue:G,oldValue:$}}=Z;k1(Y,_,X==="newValue"?G:$)}function mU(Y){let{stack:Z}=Y;if(Z)return`
48
+ `+Z.split(`
50
49
  `)?.slice(1)?.join(`
51
- `);return""}function b7(Z,Y){let X={key:Y,stringKey:Q0(Y),dependsOn:"any"};return Z.molecules.set(Q0(Y),X),Y}function R6(Z,Y,X,G="any"){let _=Y,$=Q0(X),W=[],H=Z0(Z);if(Array.isArray(_))for(let J of _){let z=Q0(J);if(H.molecules.get(z))Z.moleculeGraph.set(z,$,{source:z});else W.push(z)}else{let J=Q0(_);if(H.molecules.get(J))Z.moleculeGraph.set(J,$,{source:J});else W.push(J)}if(W.length===0)H.molecules.set($,{key:X,stringKey:$,dependsOn:G});let Q={type:"molecule_creation",key:X,provenance:_,timestamp:Date.now()};if(G1(H)&&H.transactionMeta.phase==="building")H.transactionMeta.update.subEvents.push(Q);else H.on.moleculeCreation.next(Q);for(let J of W){let z=Z.disposalTraces.buffer.find((U)=>U?.key===J);Z.logger.error("\u274C","key",X,"allocation failed:",`Could not allocate to ${J} in store "${Z.config.name}".`,z?`
50
+ `);return""}function q9(Y,Z){let X={key:Z,stringKey:$0(Z),dependsOn:"any"};return Y.molecules.set($0(Z),X),Z}function A6(Y,Z,X,_="any"){let G=Z,$=$0(X),W=[],H=Y0(Y);if(Array.isArray(G))for(let J of G){let z=$0(J);if(H.molecules.get(z))Y.moleculeGraph.set(z,$,{source:z});else W.push(z)}else{let J=$0(G);if(H.molecules.get(J))Y.moleculeGraph.set(J,$,{source:J});else W.push(J)}if(W.length===0)H.molecules.set($,{key:X,stringKey:$,dependsOn:_});let Q={type:"molecule_creation",key:X,provenance:G,timestamp:Date.now()};if(E1(H)&&H.transactionMeta.phase==="building")H.transactionMeta.update.subEvents.push(Q);else H.on.moleculeCreation.next(Q);for(let J of W){let z=Y.disposalTraces.buffer.find((F)=>F?.key===J);Y.logger.error("\u274C","key",X,"allocation failed:",`Could not allocate to ${J} in store "${Y.config.name}".`,z?`
52
51
  ${J} was most recently disposed
53
- ${z.trace}`:`No previous disposal trace for ${J} was found.`)}return X}function y7(Z){return Q8(Z,{key:"[Internal] deallocate",do:(Y,X)=>{v6(Z0(Z),X)}})}function v6(Z,Y){let X=Q0(Y),G=Z.molecules.get(X);if(!G){let D=Z.disposalTraces.buffer.find((V)=>V?.key===X);Z.logger.error("\u274C","key",Y,"deallocation failed:",`Could not find allocation for ${X} in store "${Z.config.name}".`,D?`
52
+ ${z.trace}`:`No previous disposal trace for ${J} was found.`)}return X}function j9(Y){return G8(Y,{key:"[Internal] deallocate",do:(Z,X)=>{K6(Y0(Y),X)}})}function K6(Y,Z){let X=$0(Z),_=Y.molecules.get(X);if(!_){let O=Y.disposalTraces.buffer.find((L)=>L?.key===X);Y.logger.error("\u274C","key",Z,"deallocation failed:",`Could not find allocation for ${X} in store "${Y.config.name}".`,O?`
54
53
  This state was most recently deallocated
55
- ${D.trace}`:`No previous disposal trace for ${X} was found.`);return}let _=Z.moleculeJoins.getRelatedKeys(X);if(_)for(let D of _){let V=Z.joins.get(D);if(V)V.relations.delete(Y)}Z.moleculeJoins.delete(X);let $=[],W=[],H=Z.moleculeGraph.getRelationEntries({downstreamMoleculeKey:X});if(H)for(let[D,{source:V}]of H)if(V===X){let N=a0(D);v6(Z,N)}else $.push(V);let Q=Z.moleculeData.getRelatedKeys(G.stringKey);if(Q)for(let D of Q){let V=Z.families.get(D),N=A1(Z,V,Y);W.push([V.key,N]),z8(Z,V,Y)}let J={type:"molecule_disposal",key:G.key,values:W,provenance:$,timestamp:Date.now()};Z.molecules.delete(X);let z=G1(Z)&&Z.transactionMeta.phase==="building";if(z)Z.transactionMeta.update.subEvents.push(J);if(Z.moleculeGraph.delete(G.stringKey),Z.moleculeJoins.delete(G.stringKey),Z.moleculeData.delete(G.stringKey),!z)Z.on.moleculeDisposal.next(J);Z.molecules.delete(G.stringKey);let U=aU(new Error);Z.disposalTraces.add({key:X,trace:U})}function g7(Z){return Q8(Z,{key:"[Internal] claim",do:(Y,X,G,_)=>{J8(Z,X,G,_)}})}function J8(Z,Y,X,G){let _=Q0(X),$=Z0(Z),W=$.molecules.get(_);if(!W){let U=Z.disposalTraces.buffer.find((D)=>D?.key===_);return Z.logger.error("\u274C","key",_,"claim failed:",`Could not allocate to ${_} in store "${Z.config.name}".`,U?`
56
- ${_} was most recently disposed
57
- ${U.trace}`:`No previous disposal trace for ${_} was found.`),X}let H=Q0(Y),Q=$.molecules.get(H);if(!Q){let U=Z.disposalTraces.buffer.find((D)=>D?.key===H);return Z.logger.error("\u274C","key",X,"claim failed:",`Could not allocate to ${H} in store "${Z.config.name}".`,U?`
54
+ ${O.trace}`:`No previous disposal trace for ${X} was found.`);return}let G=Y.moleculeJoins.getRelatedKeys(X);if(G)for(let O of G){let L=Y.joins.get(O);if(L)L.relations.delete(Z)}Y.moleculeJoins.delete(X);let $=[],W=[],H=Y.moleculeGraph.getRelationEntries({downstreamMoleculeKey:X});if(H)for(let[O,{source:L}]of H)if(L===X){let w=X1(O);K6(Y,w)}else $.push(L);let Q=Y.moleculeData.getRelatedKeys(_.stringKey);if(Q)for(let O of Q){let L=Y.families.get(O),w=h1(Y,L,Z);W.push([L.key,w]),$8(Y,L,Z)}let J={type:"molecule_disposal",key:_.key,values:W,provenance:$,timestamp:Date.now()};Y.molecules.delete(X);let z=E1(Y)&&Y.transactionMeta.phase==="building";if(z)Y.transactionMeta.update.subEvents.push(J);if(Y.moleculeGraph.delete(_.stringKey),Y.moleculeJoins.delete(_.stringKey),Y.moleculeData.delete(_.stringKey),!z)Y.on.moleculeDisposal.next(J);Y.molecules.delete(_.stringKey);let F=mU(new Error);Y.disposalTraces.add({key:X,trace:F})}function P9(Y){return G8(Y,{key:"[Internal] claim",do:(Z,X,_,G)=>{_8(Y,X,_,G)}})}function _8(Y,Z,X,_){let G=$0(X),$=Y0(Y),W=$.molecules.get(G);if(!W){let F=Y.disposalTraces.buffer.find((O)=>O?.key===G);return Y.logger.error("\u274C","key",G,"claim failed:",`Could not allocate to ${G} in store "${Y.config.name}".`,F?`
55
+ ${G} was most recently disposed
56
+ ${F.trace}`:`No previous disposal trace for ${G} was found.`),X}let H=$0(Z),Q=$.molecules.get(H);if(!Q){let F=Y.disposalTraces.buffer.find((O)=>O?.key===H);return Y.logger.error("\u274C","key",X,"claim failed:",`Could not allocate to ${H} in store "${Y.config.name}".`,F?`
58
57
  ${H} was most recently disposed
59
- ${U.trace}`:`No previous disposal trace for ${H} was found.`),X}let J=Z.moleculeGraph.getRelationEntries({downstreamMoleculeKey:W.stringKey}).filter(([,{source:U}])=>U!==_).map(([U])=>a0(U));if(G)$.moleculeGraph.delete(_);$.moleculeGraph.set({upstreamMoleculeKey:Q.stringKey,downstreamMoleculeKey:W.stringKey},{source:Q.stringKey});let z={type:"molecule_transfer",key:W.key,exclusive:Boolean(G),from:J,to:[Q.key],timestamp:Date.now()};if(G1($)&&$.transactionMeta.phase==="building")$.transactionMeta.update.subEvents.push(z);return X}function tU(Z,Y,X){switch(X){case"newValue":W_(Z,Y);break;case"oldValue":z8(Z,Y.token);break}}function eU(Z,Y,X){switch(X){case"newValue":z8(Z,Y.token);break;case"oldValue":if(W_(Z,Y),Y.subType==="atom")Z.valueMap.set(Y.token.key,Y.value);break}}function W_(Z,Y){let{token:X}=Y;if(Y.subType==="writable"&&Y.value)R1(Z,X,Y.value);else A1(Z,X)}function ZF(Z,Y,X){switch(X){case"newValue":R6(Z,Y.provenance,Y.key);break;case"oldValue":v6(Z,Y.key);break}}function YF(Z,Y,X){switch(X){case"newValue":v6(Z,Y.key);break;case"oldValue":{let G=Y.provenance.map(a0);R6(Z,G,Y.key);for(let[_,$]of Y.values){let W=Z.families.get(_);if(W){A1(Z,W,Y.key);let H=`${_}(${Q0(Y.key)})`;Z.valueMap.set(H,$)}}}break}}function XF(Z,Y,X){switch(X){case"newValue":for(let G of Y.to)J8(Z,G,Y.key,Y.exclusive?"exclusive":void 0);break;case"oldValue":{let G="exclusive";for(let _ of Y.from)J8(Z,_,Y.key,G),G=void 0}break}}function H_(Z,Y,X){let G=X==="newValue"?Y.subEvents:[...Y.subEvents].reverse();for(let _ of G)switch(_.type){case"atom_update":sU(Z,_,X);break;case"state_creation":tU(Z,_,X);break;case"state_disposal":eU(Z,_,X);break;case"molecule_creation":ZF(Z,_,X);break;case"molecule_disposal":YF(Z,_,X);break;case"molecule_transfer":XF(Z,_,X);break;case"transaction_outcome":H_(Z,_,X);break}}function J_(Z,Y){return Z.transactionMeta.actionContinuities.getRelatedKey(Y)}function GF(Z,Y){return Z.transactionMeta.epoch.get(Y)}function _F(Z,Y){let X=J_(Z,Y);if(X===void 0)return;return GF(Z,X)}function $F(Z,Y,X){let G=J_(Z,Y);if(G!==void 0)Z.transactionMeta.epoch.set(G,X)}function WF(Z,Y){let X=Z0(Z),{parent:G}=X;X.transactionMeta.phase="applying",X.transactionMeta.update.output=Y,G.child=null,G.on.transactionApplying.next(X.transactionMeta);let{subEvents:_}=X.transactionMeta.update;if(Z.logger.info("\uD83D\uDEC4","transaction",X.transactionMeta.update.token.key,`applying ${_.length} subEvents:`,_),H_(G,X.transactionMeta.update,"newValue"),b4(G))$F(G,X.transactionMeta.update.token.key,X.transactionMeta.update.epoch),q0(Z,{key:X.transactionMeta.update.token.key,type:"transaction"})?.subject.next(X.transactionMeta.update),Z.logger.info("\uD83D\uDEEC","transaction",X.transactionMeta.update.token.key,"applied");else if(G1(G))G.transactionMeta.update.subEvents.push(X.transactionMeta.update);G.on.transactionApplying.next(null)}function HF(Z){return{store:Z}}var JF=(Z,Y,X,G)=>{let _=Z0(Z),$={parent:_,child:null,on:_.on,loggers:_.loggers,logger:_.logger,config:_.config,atoms:new y1(_.atoms),atomsThatAreDefault:new Set(_.atomsThatAreDefault),families:new y1(_.families),joins:new y1(_.joins),operation:{open:!1},readonlySelectors:new y1(_.readonlySelectors),timelines:new y1(_.timelines),timelineTopics:_.timelineTopics.overlay(),trackers:new Map,transactions:new y1(_.transactions),selectorAtoms:_.selectorAtoms.overlay(),selectorGraph:_.selectorGraph.overlay(),writableSelectors:new y1(_.writableSelectors),valueMap:new y1(_.valueMap),defaults:_.defaults,disposalTraces:Z.disposalTraces.copy(),molecules:new y1(_.molecules),moleculeGraph:_.moleculeGraph.overlay(),moleculeData:_.moleculeData.overlay(),moleculeJoins:_.moleculeJoins.overlay(),miscResources:new y1(_.miscResources)},W=_F(Z,Y.key),H={phase:"building",update:{type:"transaction_outcome",token:Y,id:G,epoch:W===void 0?NaN:W+1,timestamp:Date.now(),subEvents:[],params:X,output:void 0},toolkit:{get:(...J)=>A1(Q,...J),set:(...J)=>{R1(Q,...J)},reset:(...J)=>{H8(Q,...J)},run:(J,z=d5())=>A6(Q,J,z),find:(...J)=>P0(Z,...J),json:(J)=>g4(Q,J),dispose:(...J)=>{z8(Q,...J)},env:()=>HF(Q)}},Q=Object.assign($,{transactionMeta:H});return _.child=Q,Z.logger.info("\uD83D\uDEEB","transaction",Y.key,"building with params:",X),Q};function Q8(Z,Y){let{key:X}=Y,G=Z.transactions.has(X),_={key:X,type:"transaction",run:(W,H)=>{let Q=q1(_),J=JF(Z,Q,W,H);try{let{toolkit:z}=J.transactionMeta,U=Y.do(z,...W);return WF(J,U),U}catch(z){throw rU(J),Z.logger.warn("\uD83D\uDCA5","transaction",X,"caught:",z),z}},install:(W)=>Q8(W,Y),subject:new _0};Z0(Z).transactions.set(X,_);let $=q1(_);if(!G)Z.on.transactionCreation.next($);return $}var p7=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 W4({between:["selectorKey","atomKey"],cardinality:"n:n"});selectorGraph=new W4({between:["upstreamSelectorKey","downstreamSelectorKey"],cardinality:"n:n"},{makeContentKey:(...Z)=>Z.sort().join(":")});trackers=new Map;families=new Map;joins=new Map;transactions=new Map;transactionMeta={epoch:new Map,actionContinuities:new W4({between:["continuity","action"],cardinality:"1:n"})};timelines=new Map;timelineTopics=new W4({between:["timelineKey","topicKey"],cardinality:"1:n"});disposalTraces=new oU(100);molecules=new Map;moleculeJoins=new W4({between:["moleculeKey","joinKey"],cardinality:"n:n"},{makeContentKey:(...Z)=>Z.sort().join(":")});moleculeGraph=new W4({between:["upstreamMoleculeKey","downstreamMoleculeKey"],cardinality:"n:n"},{makeContentKey:(...Z)=>Z.sort().join(":")});moleculeData=new W4({between:["moleculeKey","stateFamilyKey"],cardinality:"n:n"},{makeContentKey:(...Z)=>Z.sort().join(":")});miscResources=new Map;on={atomCreation:new _0,atomDisposal:new _0,selectorCreation:new _0,selectorDisposal:new _0,timelineCreation:new _0,transactionCreation:new _0,transactionApplying:new i7(null),operationClose:new _0,moleculeCreation:new _0,moleculeDisposal:new _0};operation={open:!1};config={name:"IMPLICIT_STORE",lifespan:"ephemeral"};loggers=[new h7("warn",(Z,Y,X)=>!N2(X))];logger={error:(...Z)=>{for(let Y of this.loggers)Y.error(...Z)},info:(...Z)=>{for(let Y of this.loggers)Y.info(...Z)},warn:(...Z)=>{for(let Y of this.loggers)Y.warn(...Z)}};constructor(Z,Y=null){if(this.config={...Y?.config,...Z},Y!==null){if(this.operation={...Y?.operation},b4(Y))this.transactionMeta={epoch:new Map(Y?.transactionMeta.epoch),actionContinuities:new W4(Y?.transactionMeta.actionContinuities.toJSON())};for(let[,G]of Y.families){if(G.internalRoles?.includes("mutable")||G.internalRoles?.includes("join"))continue;G.install(this)}let X=new Set;for(let[,G]of Y.atoms){if(X.has(G.key))continue;if(G.install(this),G.type==="mutable_atom"){let _=g4(Y,G),$=UY(G);X.add(_.key),X.add($.key)}}for(let[,G]of Y.readonlySelectors)G.install(this);for(let[,G]of Y.writableSelectors){if(X.has(G.key))continue;G.install(this)}for(let[,G]of Y.transactions)G.install(this);for(let[,G]of Y.timelines)G.install(this)}}},E1={get STORE(){return globalThis.ATOM_IO_IMPLICIT_STORE??=new p7({name:"IMPLICIT_STORE",lifespan:"ephemeral"}),globalThis.ATOM_IO_IMPLICIT_STORE}};function P0(Z,Y,X){let G=q0(Z,Y),_=M2(Z,Y,X);if(_)return _;return V2(n7,Z,G,X)}function y4(Z,Y,X){let G=Y.key,_="readonly_pure_selector_family",$={key:G,type:"readonly_pure_selector_family"},W=Z.families.get(G);if(W)Z.logger.error("\u2757","readonly_pure_selector_family",G,`Overwriting an existing ${o1[W.type]} "${W.key}" in store "${Z.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);let H=new _0,J={...$,create:(z)=>{let U=Q0(z),D={key:G,subKey:U},V=`${G}(${U})`,N=Z0(Z),R={key:V,get:Y.get(z)};if(Y.catch)R.catch=Y.catch;return JY(N,R,D)},internalRoles:X,subject:H,install:(z)=>y4(z,Y),default:(z)=>{return Y.get(z)({get:(...U)=>A1(Z,...U),find:(...U)=>P0(Z,...U),json:(U)=>g4(Z,U)})}};return Z.families.set(G,J),$}function O2(Z,Y,X){let G={key:Y.key,type:"atom_family"},_=Z.families.get(Y.key);if(_)Z.logger.error("\u2757","atom_family",Y.key,`Overwriting an existing ${o1[_.type]} "${_.key}" in store "${Z.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);let $=new _0,H={...G,create:(Q)=>{let J=Q0(Q),z={key:Y.key,subKey:J},U=`${Y.key}(${J})`,D=Z0(Z),V=Y.default,N={key:U,default:k4(V)?()=>V(Q):V};if(Y.effects)N.effects=Y.effects(Q);if(Y.catch)N.catch=Y.catch;return w4(D,N,z)},default:Y.default,subject:$,install:(Q)=>O2(Q,Y),internalRoles:X};if(Z.families.set(Y.key,H),k4(Y.default)===!1)Z.defaults.set(Y.key,Y.default);return G}function Q_(Z,Y,X){let G=Y.key,_="readonly_held_selector_family",$={key:G,type:"readonly_held_selector_family"},W=Z.families.get(G);if(W)Z.logger.error("\u2757","readonly_held_selector_family",G,`Overwriting an existing ${o1[W.type]} "${W.key}" in store "${Z.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);let H=new _0,J={...$,create:(z)=>{let U=Q0(z),D={key:G,subKey:U},V=`${G}(${U})`,N=Z0(Z);return HY(N,{key:V,const:Y.const(z),get:Y.get(z)},D)},internalRoles:X,subject:H,install:(z)=>Q_(z,Y),default:Y.const};return Z.families.set(G,J),$}function z_(Z,Y,X){let G=Y.key,_="writable_held_selector_family",$={key:G,type:"writable_held_selector_family"},W=Z.families.get(G);if(W)Z.logger.error("\u2757","writable_held_selector_family",G,`Overwriting an existing ${o1[W.type]} "${W.key}" in store "${Z.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);let H=new _0,J={...$,create:(z)=>{let U=Q0(z),D={key:G,subKey:U},V=`${G}(${U})`,N=Z0(Z);return QY(N,{key:V,const:Y.const(z),get:Y.get(z),set:Y.set(z)},D)},internalRoles:X,subject:H,install:(z)=>z_(z,Y),default:Y.const};return Z.families.set(G,J),$}function WY(Z,Y,X){let G=Y.key,_="writable_pure_selector_family",$={key:G,type:"writable_pure_selector_family"},W=Z.families.get(G);if(W)Z.logger.error("\u2757","writable_pure_selector_family",G,`Overwriting an existing ${o1[W.type]} "${W.key}" in store "${Z.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);let H=new _0,J={...$,create:(z)=>{let U=Q0(z),D={key:G,subKey:U},V=`${G}(${U})`,N=Z0(Z),R={key:V,get:Y.get(z),set:Y.set(z)};if(Y.catch)R.catch=Y.catch;return zY(N,R,D)},internalRoles:X,subject:H,install:(z)=>WY(z,Y),default:(z)=>{return Y.get(z)({get:(...U)=>A1(Z,...U),find:(...U)=>P0(Z,...U),json:(U)=>g4(Z,U)})}};return Z.families.set(G,J),$}function c5(Z,Y){let X="set"in Y,G="const"in Y;if(G&&X)return z_(Z,Y,void 0);if(G)return Q_(Z,Y,void 0);if(X)return WY(Z,Y);return y4(Z,Y)}function z8(Z,...Y){let X;if(Y.length===1)X=Y[0];else{let G=Y[0],_=Y[1];X=P0(Z,G,_)}try{q0(Z,X)}catch(G){Z.logger.error("\u274C",X.type,X.key,`could not be disposed because it was not found in the store "${Z.config.name}".`);return}switch(X.type){case"atom":case"mutable_atom":U_(Z,X);break;case"writable_pure_selector":case"readonly_pure_selector":case"writable_held_selector":case"readonly_held_selector":zF(Z,X);break}}function QF(Z,Y,X,G,_){let $=Z0(Z),{type:W,key:H}=G;if(W==="atom"||W==="mutable_atom")$.selectorAtoms.set({selectorKey:X,atomKey:H}),Z.logger.info("\uD83D\uDD0D",Y,X,`discovers root atom "${H}"`);else{let Q=A2(Z,H,_);Z.logger.info("\uD83D\uDD0D",Y,X,`discovers root atoms: [ ${[...Q.values()].map((J)=>`"${J.key}"`).join(", ")} ]`);for(let{key:J}of Q.values())$.selectorAtoms=$.selectorAtoms.set({selectorKey:X,atomKey:J})}_.add(H)}function x6(Z,Y,X,G){return{get:(..._)=>{let $=Z0(Z),{token:W,family:H,subKey:Q}=q6(Z,..._),J;if("counterfeit"in W&&H&&Q)J=t5(Z,W,H,Q);else{let z=q0(Z,W);J=I4(Z,z)}return Z.logger.info("\uD83D\uDD0C",Y,X,`registers dependency ( "${W.key}" =`,J,")"),$.selectorGraph.set({upstreamSelectorKey:W.key,downstreamSelectorKey:X},{source:W.key}),QF(Z,Y,X,W,G),J},set:(..._)=>{let $=Z0(Z);j6(a7,$,..._)},find:(..._)=>P0(Z,..._),json:(_)=>g4(Z,_)}}function HY(Z,Y,X){let G=Z0(Z),_=new _0,$=new Set,{key:W,const:H}=Y,Q="readonly_held_selector";Z.logger.info("\uD83D\uDD28","readonly_held_selector",W,"is being created");let{get:J,find:z,json:U}=x6(G,"readonly_held_selector",W,$),V={...Y,type:"readonly_held_selector",subject:_,getFrom:(R)=>{let b=R.selectorGraph.getRelationEntries({downstreamSelectorKey:W});for(let[x,{source:h}]of b)if(h!==W)R.selectorGraph.delete(x,W);return R.selectorAtoms.delete(W),Y.get({get:J,find:z,json:U},H),N1(R,V,H),Z.logger.info("\u2728","readonly_held_selector",W,"=",H),$.clear(),H},install:(R)=>HY(R,Y,X)};if(X)V.family=X;G.readonlySelectors.set(W,V);let N={key:W,type:"readonly_held_selector"};if(X)N.family=X;return N}function JY(Z,Y,X){let G=Z0(Z),_=new _0,$=new Set,W=Y.key,H="readonly_pure_selector";Z.logger.info("\uD83D\uDD28","readonly_pure_selector",W,"is being created");let{get:Q,find:J,json:z}=x6(G,"readonly_pure_selector",W,$),D={...Y,type:"readonly_pure_selector",subject:_,getFrom:()=>{let N=Z0(Z),R=N.selectorGraph.getRelationEntries({downstreamSelectorKey:W});for(let[h,{source:g}]of R)if(g!==W)N.selectorGraph.delete(h,W);N.selectorAtoms.delete(W);let b=Y.get({get:Q,find:J,json:z}),x=N1(N,D,b);return Z.logger.info("\u2728","readonly_pure_selector",W,"=",x),$.clear(),x},install:(N)=>JY(N,Y,X)};if(X)D.family=X;G.readonlySelectors.set(W,D);let V={key:W,type:"readonly_pure_selector"};if(X)V.family=X;return V}function QY(Z,Y,X){let G=Z0(Z),_=new _0,$=new Set,{key:W,const:H}=Y,Q="writable_held_selector";Z.logger.info("\uD83D\uDD28","writable_held_selector",W,"is being created");let J=x6(G,"writable_held_selector",W,$),{find:z,get:U,json:D}=J,V={find:z,get:U,json:D},b={...Y,type:"writable_held_selector",subject:_,getFrom:(h)=>{let g=h.selectorGraph.getRelationEntries({downstreamSelectorKey:W});for(let[K,{source:B}]of g)if(B!==W)h.selectorGraph.delete(K,W);return h.selectorAtoms.delete(W),Y.get(V,H),N1(h,b,H),Z.logger.info("\u2728","writable_held_selector",W,"=",H),$.clear(),H},setSelf:()=>{Y.set(J,H)},install:(h)=>QY(h,Y,X)};if(X)b.family=X;G.writableSelectors.set(W,b);let x={key:W,type:"writable_held_selector"};if(X)x.family=X;return x}function zY(Z,Y,X){let G=Z0(Z),_=new _0,$=new Set,W=Y.key,H="writable_pure_selector";Z.logger.info("\uD83D\uDD28","writable_pure_selector",W,"is being created");let Q=x6(G,"writable_pure_selector",W,$),{find:J,get:z,json:U}=Q,D={find:J,get:z,json:U},R={...Y,type:"writable_pure_selector",subject:_,getFrom:(x)=>{let h=x.selectorGraph.getRelationEntries({downstreamSelectorKey:W});for(let[B,{source:T}]of h)if(T!==W)x.selectorGraph.delete(B,W);x.selectorAtoms.delete(W);let g=Y.get(D),K=N1(x,R,g);return Z.logger.info("\u2728","writable_pure_selector",W,"=",K),$.clear(),K},setSelf:(x)=>{Y.set(Q,x)},install:(x)=>zY(x,Y,X)};if(X)R.family=X;G.writableSelectors.set(W,R);let b={key:W,type:"writable_pure_selector"};if(X)b.family=X;return b}function m7(Z,Y){let X="set"in Y,G="const"in Y;if(G&&X){let $=QY(Z,Y,void 0);return Z.on.selectorCreation.next($),$}if(G){let $=HY(Z,Y,void 0);return Z.on.selectorCreation.next($),$}if(X){let $=zY(Z,Y,void 0);return Z.on.selectorCreation.next($),$}let _=JY(Z,Y,void 0);return Z.on.selectorCreation.next(_),_}function zF(Z,Y){let X=Z0(Z),{key:G,type:_,family:$}=Y;if(!$)Z.logger.error("\u274C",_,G,"Standalone selectors cannot be disposed.");else{if(X.molecules.get($.subKey))X.moleculeData.delete($.subKey,$.key);let W;switch(Y.type){case"writable_held_selector":X.writableSelectors.delete(G),W={key:$.key,type:"writable_held_selector_family"},q0(Z,W).subject.next({type:"state_disposal",subType:"selector",token:Y,timestamp:Date.now()});break;case"writable_pure_selector":X.writableSelectors.delete(G),W={key:$.key,type:"writable_pure_selector_family"},q0(Z,W).subject.next({type:"state_disposal",subType:"selector",token:Y,timestamp:Date.now()});break;case"readonly_held_selector":X.readonlySelectors.delete(G),W={key:$.key,type:"readonly_held_selector_family"},q0(Z,W).subject.next({type:"state_disposal",subType:"selector",token:Y,timestamp:Date.now()});break;case"readonly_pure_selector":X.readonlySelectors.delete(G),W={key:$.key,type:"readonly_pure_selector_family"},q0(Z,W).subject.next({type:"state_disposal",subType:"selector",token:Y,timestamp:Date.now()});break}if(X.valueMap.delete(G),X.selectorAtoms.delete(G),X.selectorGraph.delete(G),X.moleculeData.delete($.key,$.subKey),Z.logger.info("\uD83D\uDD25",Y.type,G,"deleted"),G1(X)&&X.transactionMeta.phase==="building")X.transactionMeta.update.subEvents.push({type:"state_disposal",subType:"selector",token:Y,timestamp:Date.now()});else Z.on.selectorDisposal.next(Y)}}function N6(Z,Y,X){Z.logger.info("\uD83D\uDD28","atom",Y.key,`creating in store "${Z.config.name}"`);let G=Z0(Z),{key:_}=Y,$=G.atoms.get(_),W="mutable_atom";if($&&$.type===W)return Z.logger.error("\u274C",W,_,"Tried to create atom, but it already exists in the store."),q1($);let H=new _0,Q={...Y,type:W,install:(z)=>{return z.logger.info("\uD83D\uDEE0\uFE0F","atom",_,`installing in store "${z.config.name}"`),N6(z,Y,X)},subject:H};if(X)Q.family=X;G.atoms.set(Q.key,Q);let J=q1(Q);if(Y.effects){let z=0,U=[];for(let D of Y.effects){let V=D({resetSelf:()=>{H8(Z,J)},setSelf:(N)=>{R1(Z,J,N)},onSet:(N)=>R2(Z,J,`effect[${z}]`,N)});if(V)U.push(V);++z}Q.cleanup=()=>{for(let D of U)D()}}if(new P6(J,Z),!X)m7(Z,{key:`${_}:JSON`,get:({get:z})=>z(J).toJSON(),set:({set:z},U)=>{z(J,Y.class.fromJSON(U))}});return Z.on.atomCreation.next(J),J}var UF=class{trackers=new Map;latestSignalAtoms;mutableAtoms;constructor(Z,Y){let X=O2(Y,{key:`*${Z.key}`,default:null},["mutable","updates"]);this.latestSignalAtoms=q0(Y,X),this.mutableAtoms=Z;let G=(_)=>{let{type:$,token:W}=_;if(W.family){let H=a0(W.family.subKey);switch($){case"state_creation":this.trackers.set(H,new P6(W,Y));break;case"state_disposal":{let Q=this.trackers.get(H);if(Q)Q[Symbol.dispose](),this.trackers.delete(H)}}}};this.mutableAtoms.subject.subscribe(`store=${Y.config.name}::tracker-atom-family`,G)}};function l5(Z,Y,X){let G={key:Y.key,type:"mutable_atom_family"},_=Z.families.get(Y.key);if(_)Z.logger.error("\u2757","mutable_atom_family",Y.key,`Overwriting an existing ${o1[_.type]} "${_.key}" in store "${Z.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);let $=new _0,H={...G,create:(Q)=>{let J=Q0(Q),z={key:Y.key,subKey:J},U=`${Y.key}(${J})`,D=Z0(Z),V={key:U,class:Y.class};if(Y.effects)V.effects=Y.effects(Q);return N6(D,V,z)},class:Y.class,subject:$,install:(Q)=>l5(Q,Y),internalRoles:X};return Z.families.set(Y.key,H),WY(Z,{key:`${Y.key}:JSON`,get:(Q)=>({get:J})=>J(G,Q).toJSON(),set:(Q)=>({set:J},z)=>{J(G,Q,Y.class.fromJSON(z))}},["mutable","json"]),new UF(H,Z),G}var __=(Z,Y)=>{let X=Z0(Y),G=`${Z.key}:JSON`;return X.families.get(G)},g4=(Z,Y)=>{if(Y.family){let X=Z0(Z),G={key:`${Y.family.key}:JSON`,type:"writable_pure_selector_family"},_=q0(X,G),$=a0(Y.family.subKey);return P0(Z,_,$)}return{type:"writable_pure_selector",key:`${Y.key}:JSON`}};var UY=(Z)=>{let Y={type:"atom",key:`*${Z.key}`};if(Z.family)Y.family={key:`*${Z.family.key}`,subKey:Z.family.subKey};return Y};function U_(Z,Y){let X=Z0(Z),{key:G,family:_}=Y,$=q0(X,Y);if(!_)Z.logger.error("\u274C","atom",G,"Standalone atoms cannot be disposed.");else{$.cleanup?.();let W=Z.valueMap.get($.key),H=T6(Z,Y),Q=q0(Z,H).subject,J={type:"state_disposal",subType:"atom",token:Y,value:W,timestamp:Date.now()};Q.next(J);let z=G1(X);if(X.atoms.delete(G),X.valueMap.delete(G),X.selectorAtoms.delete(G),X.atomsThatAreDefault.delete(G),X.moleculeData.delete(_.key,_.subKey),Z.timelineTopics.delete(G),Y.type==="mutable_atom"){let U=UY(Y);U_(Z,U),Z.trackers.delete(G)}if(Z.logger.info("\uD83D\uDD25","atom",G,"deleted"),z&&X.transactionMeta.phase==="building"){let U=X.transactionMeta.update.subEvents.at(-1),D=U?.type==="molecule_disposal"&&U.values.some(([N])=>N===$.family?.key),V=$Y($,"tracker:signal");if(!D&&!V)X.transactionMeta.update.subEvents.push(J)}else Z.on.atomDisposal.next(Y)}}function B0(Z){return Z[0].toUpperCase()+Z.slice(1)}var F_=class{toolkit;options;defaultContent;relations;states;core;transact(Z,Y){let X=this.toolkit;this.toolkit=Z,Y(this),this.toolkit=X}store;realm;[Symbol.dispose](){}constructor(Z,Y,X=E1.STORE){this.store=X,this.realm=new k7(X),this.options=Z,this.defaultContent=Y,this.store.miscResources.set(`join:${Z.key}`,this),this.realm.allocate("root",Z.key),this.toolkit={get:(...K)=>A1(X,...K),set:(...K)=>{R1(X,...K)},find:(...K)=>P0(X,...K),json:(K)=>g4(X,K)};let G=Z.between[0],_=Z.between[1],$=l5(X,{key:`${Z.key}/relatedKeys`,class:$4},["join","relations"]);this.core={relatedKeysAtoms:$};let W=({get:K},B)=>K($,B),H=({set:K},B,T)=>{if(!this.store.molecules.has(Q0(B)))this.realm.allocate(Z.key,B);K($,B,(q)=>q.add(T)),K($,T,(q)=>q.add(B))},Q=({set:K},B,T)=>{K($,B,(w)=>{return w.delete(T),w}),K($,T,(w)=>{return w.delete(B),w});let[q,c]=[B,T].sort(),n=`${q}:${c}`;this.store.moleculeJoins.delete(n)},J=(K,B,T)=>{let{find:q,get:c,set:n}=K,w=q($,B),s=c(w);for(let p of s){if(T.includes(p))continue;n($,p,(a)=>{return a.delete(B),a})}n(w,(p)=>{return p.transaction((a)=>{a.clear();for(let I0 of T){let h0=W(K,I0),W1=h0.has(B);if(this.relations.cardinality==="1:n"){let s1=[];for(let C of h0){if(C===B)continue;let m=W(K,C);if(m.delete(I0),m.size===0)s1.push(C)}if(!W1&&h0.size>0)h0.clear();for(let C of s1){let[m,$0]=[I0,C].sort(),L0=`${m}:${$0}`;X.moleculeJoins.delete(L0)}}if(!W1)h0.add(B);a.add(I0)}return!0}),p})},z=(K,B,T)=>{let{set:q}=K;q($,B,(c)=>{return c.transaction((n)=>{for(let w of T)n.add(w);return!0}),c});for(let c of T)q($,c,(n)=>{return n.add(B),n});return!0},U=(K,B,T)=>{let q=W(K,B);return T?q.has(T):q.size>0},D={getRelatedKeys:(K)=>W(this.toolkit,K),addRelation:(K,B)=>{this.store.moleculeJoins.set(`"${K}"`,Z.key),this.store.moleculeJoins.set(`"${B}"`,Z.key),H(this.toolkit,K,B)},deleteRelation:(K,B)=>{Q(this.toolkit,K,B)},replaceRelationsSafely:(K,B)=>{J(this.toolkit,K,B)},replaceRelationsUnsafely:(K,B)=>{z(this.toolkit,K,B)},has:(K,B)=>U(this.toolkit,K,B)},V,N;if(Y){N=O2(X,{key:`${Z.key}/content`,default:Y},["join","content"]);let K=({get:T},q)=>T(N,q),B=({set:T},q,c)=>{T(N,q,c)};V=Object.assign(D,{getContent:(T)=>{return K(this.toolkit,T)},setContent:(T,q)=>{B(this.toolkit,T,q)},deleteContent:(T)=>{}})}else V=D;let R=new W4(Z,{externalStore:V,isAType:Z.isAType,isBType:Z.isBType,makeContentKey:(...K)=>{let[B,T]=K,[q,c]=K.sort(),n=`${q}:${c}`,w=X.molecules.get(Q0(B)),s=X.molecules.get(Q0(T));if(!w)this.realm.allocate(Z.key,B);if(!s)this.realm.allocate(Z.key,T);return this.realm.allocate(B,n,"all"),this.realm.claim(T,n),this.store.moleculeJoins.set(n,Z.key),n}}),b=()=>y4(X,{key:`${Z.key}/singleRelatedKey`,get:(K)=>({get:B})=>{let T=B($,K);for(let q of T)return q;return null}},["join","keys"]),x=()=>{return y4(X,{key:`${Z.key}/multipleRelatedKeys`,get:(K)=>({get:B})=>{let T=__($,X);return B(T,K).members}},["join","keys"])},h=()=>y4(X,{key:`${Z.key}/singleRelatedEntry`,get:(K)=>({get:B})=>{let T=B($,K);for(let q of T){let c=R.isAType?.(K)?K:void 0,n=c===void 0?K:void 0;c??=q,n??=q;let w=R.makeContentKey(c,n),s=B(N,w);return[q,s]}return null}},["join","entries"]),g=()=>y4(X,{key:`${Z.key}/multipleRelatedEntries`,get:(K)=>({get:B})=>{let T=__($,X);return B(T,K).members.map((q)=>{let c=R.isAType?.(K)?K:void 0,n=c===void 0?K:void 0;c??=q,n??=q;let w=R.makeContentKey(c,n),s=B(N,w);return[q,s]})}},["join","entries"]);switch(Z.cardinality){case"1:1":{let K=b(),B=`${G}KeyOf${B0(_)}`,T=`${_}KeyOf${B0(G)}`,q={[B]:K,[T]:K},c;if(Y){let n=h(),w=`${G}EntryOf${B0(_)}`,s=`${_}EntryOf${B0(G)}`,p={[w]:n,[s]:n};c=Object.assign(q,p)}else c=q;this.relations=R,this.states=c;break}case"1:n":{let K=b(),B=x(),T=`${G}KeyOf${B0(_)}`,q=`${_}KeysOf${B0(G)}`,c={[T]:K,[q]:B},n;if(Y){let w=h(),s=g(),p=`${G}EntryOf${B0(_)}`,a=`${_}EntriesOf${B0(G)}`,I0={[p]:w,[a]:s};n=Object.assign(c,I0)}else n=c;this.relations=R,this.states=n;break}case"n:n":{let K=x(),B=`${G}KeysOf${B0(_)}`,T=`${_}KeysOf${B0(G)}`,q={[B]:K,[T]:K},c;if(Y){let n=g(),w=`${G}EntriesOf${B0(_)}`,s=`${_}EntriesOf${B0(G)}`,p={[w]:n,[s]:n};c=Object.assign(q,p)}else c=q;this.relations=R,this.states=c}}}};function u7(Z,Y,X){return Z.joins.set(Y.key,new F_(Y,X,Z)),{key:Y.key,type:"join",a:Y.between[0],b:Y.between[1],cardinality:Y.cardinality}}function FY(Z,Y){let X=Y.joins.get(Z.key);if(X===void 0){let G=E1.STORE.joins.get(Z.key);if(G===void 0)throw new Error(`Join "${Z.key}" not found in store "${Y.config.name}"`);let _=l7(Y);X=new F_(G.options,G.defaultContent,_),Y.joins.set(Z.key,X)}return X}function U8(Z,Y,X){let G=FY(Z,X),_=Z0(X);if(G1(_)){let{toolkit:$}=_.transactionMeta;G.transact($,({relations:W})=>{Y(W)})}else Y(G.relations)}function lU(Z,Y,X){let G=FY(Z,X),_;switch(Z.cardinality){case"1:1":{let $=`${Z.a}KeyOf${B0(Z.b)}`,W=`${Z.b}KeyOf${B0(Z.a)}`;_={get[$](){let Q=G.states[$];return P0(X,Q,Y)},get[W](){let Q=G.states[W];return P0(X,Q,Y)}};let H=`${Z.a}EntryOf${B0(Z.b)}`;if(H in G.states){let Q=`${Z.b}EntryOf${B0(Z.a)}`;Object.assign(_,{get[H](){let J=G.states[H];return P0(X,J,Y)},get[Q](){let J=G.states[Q];return P0(X,J,Y)}})}break}case"1:n":{let $=`${Z.a}KeyOf${B0(Z.b)}`,W=`${Z.b}KeysOf${B0(Z.a)}`;_={get[$](){let Q=G.states[$];return P0(X,Q,Y)},get[W](){let Q=G.states[W];return P0(X,Q,Y)}};let H=`${Z.a}EntryOf${B0(Z.b)}`;if(H in G.states){let Q=`${Z.b}EntriesOf${B0(Z.a)}`;Object.assign(_,{get[H](){let J=G.states[H];return P0(X,J,Y)},get[Q](){let J=G.states[Q];return P0(X,J,Y)}})}break}case"n:n":{let $=`${Z.a}KeysOf${B0(Z.b)}`,W=`${Z.b}KeysOf${B0(Z.a)}`;_={get[$](){let Q=G.states[$];return P0(X,Q,Y)},get[W](){let Q=G.states[W];return P0(X,Q,Y)}};let H=`${Z.a}EntriesOf${B0(Z.b)}`;if(H in G.states){let Q=`${Z.b}EntriesOf${B0(Z.a)}`;Object.assign(_,{get[H](){let J=G.states[H];return P0(X,J,Y)},get[Q](){let J=G.states[Q];return P0(X,J,Y)}})}}}return _}function d7(Z,Y){return FY(Z,Y).core.relatedKeysAtoms}var FF=(Z)=>{return w4(Z,{key:"\uD83D\uDD0D Atom Token Index",default:()=>{let Y=new Map;for(let[X,G]of Z.atoms){if(N2(X))continue;let _=q1(G);if(G.family){let $=Y.get(G.family.key);if(!$||!("familyMembers"in $))$={key:G.family.key,familyMembers:new Map},Y.set(G.family.key,$);$.familyMembers.set(G.family.subKey,_)}else Y.set(X,_)}return Y},effects:[({setSelf:Y})=>{Z.on.atomCreation.subscribe("introspection",(X)=>{if(N2(X.key))return;Y((G)=>{if(X.family){let{key:_,subKey:$}=X.family,W=G.get(_);if(W===void 0||!("familyMembers"in W))W={key:_,familyMembers:new Map},G.set(_,W);W.familyMembers.set($,X)}else G.set(X.key,X);return new Map(G)})}),Z.on.atomDisposal.subscribe("introspection",(X)=>{Y((G)=>{if(X.family){let{key:_,subKey:$}=X.family,W=G.get(_);if(W&&"familyMembers"in W){if(W.familyMembers.delete($),W.familyMembers.size===0)G.delete(_)}}return new Map(G)})})}]},void 0)},EF=(Z)=>{return w4(Z,{key:"\uD83D\uDD0D Selector Token Index",default:()=>{let Y=new Map;for(let X of[Z.readonlySelectors,Z.writableSelectors])for(let[G,_]of X){if(N2(G))continue;let $=q1(_);if(_.family){let W=Y.get(_.family.key);if(!W||!("familyMembers"in W))W={key:_.family.key,familyMembers:new Map},Y.set(_.family.key,W);W.familyMembers.set(_.family.subKey,$)}else Y.set(G,$)}return Y},effects:[({setSelf:Y})=>{Z.on.selectorCreation.subscribe("introspection",(X)=>{if(N2(X.key))return;Y((G)=>{if(X.family){let{key:_,subKey:$}=X.family,W=G.get(_);if(W===void 0||!("familyMembers"in W))W={key:_,familyMembers:new Map},G.set(_,W);W.familyMembers.set($,X)}else G.set(X.key,X);return new Map(G)})}),Z.on.selectorDisposal.subscribe("introspection",(X)=>{Y((G)=>{if(X.family){let{key:_,subKey:$}=X.family,W=G.get(_);if(W&&"familyMembers"in W){if(W.familyMembers.delete($),W.familyMembers.size===0)G.delete(_)}}else G.delete(X.key);return new Map(G)})})}]},void 0)};var EY=class{supported;constructor(Z){this.supported=Z}refine(Z){for(let[Y,X]of Object.entries(this.supported))try{if(X(Z)===!0&&X!==Boolean)return{type:Y,data:Z}}catch(G){try{if(Z instanceof X)return{type:Y,data:Z}}catch(_){}}return null}},L_=new EY({number:(Z)=>typeof Z==="number",string:(Z)=>typeof Z==="string",boolean:(Z)=>typeof Z==="boolean",null:(Z)=>Z===null});function D_(Z){if(!Z)return!1;return Object.getPrototypeOf(Z)===Object.prototype}var O_=new EY({object:D_,array:(Z)=>Array.isArray(Z)}),LF=new EY({...L_.supported,...O_.supported}),f6=(Z)=>{if(Z===void 0)return"undefined";let Y=LF.refine(Z);if(Y)return Y.type;return Object.getPrototypeOf(Z).constructor.name};var $K=class Z{store;auditorCreatedAt=performance.now();statesCreatedAt=new Map;atomIndex;selectorIndex;disposed=!1;unsubscribeFromAtomCreation;unsubscribeFromAtomDisposal;unsubscribeFromSelectorCreation;unsubscribeFromSelectorDisposal;constructor(Y=E1.STORE){this.store=Y,this.atomIndex=FF(this.store),this.selectorIndex=EF(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(Y=Z.DEFAULT_LIST_RESOURCES_PARAM){if(this.disposed)throw new Error("This Auditor has been disposed");let X=u5(this.atomIndex),G=u5(this.selectorIndex),_=[...X.values()].filter((Q)=>("familyMembers"in Q)),$=[...G.values()].filter((Q)=>("familyMembers"in Q)),W=performance.now(),H=[];if(Y.atomFamilies)for(let Q of _){let J=Q.familyMembers.values();for(let z of J){let U=this.statesCreatedAt.get(z.key)??this.auditorCreatedAt,D=W-U;H.push([z,D])}}if(Y.selectorFamilies)for(let Q of $){let J=Q.familyMembers.values();for(let z of J){let U=this.statesCreatedAt.get(z.key)??this.auditorCreatedAt,D=W-U;H.push([z,D])}}return H}[Symbol.dispose](){this.unsubscribeFromAtomCreation(),this.unsubscribeFromAtomDisposal(),this.unsubscribeFromSelectorCreation(),this.unsubscribeFromSelectorDisposal(),this.disposed=!0}},E_=(Z,Y)=>{let X=(G,_)=>{let W=((Q,J)=>{let z=Y(Q,J);if(z)return z;return null})(G,_);if(W?.jobComplete??W?.pathComplete)return W;let H=Array.isArray(_)?_.map((Q,J)=>[J,Q]):D_(_)?Object.entries(_):[];for(let[Q,J]of H){let z=X([...G,Q],J);if(z?.jobComplete)return z}return{}};X([],Z)};function DF(Z,Y){return{summary:`${Z<Y?"+":"-"}${Math.abs(Z-Y)} (${Z} \u2192 ${Y})`}}function OF(Z,Y){return{summary:`${Z.length<Y.length?"+":"-"}${Math.abs(Z.length-Y.length)} ("${Z}" \u2192 "${Y}")`}}function VF(Z,Y){return{summary:`${Z} \u2192 ${Y}`}}function V_(Z,Y,X){let G="",_=[],$=[],W=[];return E_(Z,(H,Q)=>{let J;for(J of H){let z=Y[J];if(z===void 0)$.push([J,JSON.stringify(Q)]);else{let U=X(Q,z);if(U.summary!=="No Change")W.push([J,U])}}}),E_(Y,(H,Q)=>{let J;for(J of H)if(Z[J]===void 0)_.push([J,JSON.stringify(Q)])}),G=`\uFF5E${W.length} \uFF0B${_.length} \uFF0D${$.length}`,{summary:G,added:_,removed:$,changed:W}}function MF(Z,Y,X){return V_(Z,Y,X)}var AF=class{leafRefinery;treeRefinery;leafDiffers;treeDiffers;constructor(Z,Y,X){this.leafRefinery=Z,this.treeRefinery=Y,this.leafDiffers={},this.treeDiffers={};for(let G of Object.keys(Z.supported)){let _=X[G];this.leafDiffers[G]=_}for(let G of Object.keys(Y.supported)){let _=X[G];this.treeDiffers[G]=_}}diff(Z,Y){if(Z===Y)return{summary:"No Change"};let X=this.leafRefinery.refine(Z)??this.treeRefinery.refine(Z),G=this.leafRefinery.refine(Y)??this.treeRefinery.refine(Y);if(X!==null&&G!==null){if(X.type===G.type){if(X.type in this.leafDiffers)return this.leafDiffers[X.type](X.data,G.data);if(X.type in this.treeDiffers)return this.treeDiffers[X.type](X.data,G.data,(W,H)=>this.diff(W,H))}}let _=f6(Z),$=f6(Y);if(_===$)return{summary:`${_} \u2192 ${$}`};return{summary:`Type change: ${_} \u2192 ${$}`}}},WK=new AF(L_,O_,{number:DF,string:OF,boolean:VF,null:()=>({summary:"No Change"}),object:V_,array:MF});var FK=D2({key:"usersInRoomIndex",class:$4}),M_=D2({key:"roomIndex",class:$4}),RF={enteredAtEpoch:0},L8=O6({key:"usersInRooms",between:["room","user"],cardinality:"1:n",isAType:(Z)=>typeof Z==="string",isBType:(Z)=>typeof Z==="string"},RF),EK=V6({key:"usersInMyRoomView",get:(Z)=>({find:Y})=>{let X=f7(L8);return[Y(X,Z)]}});var NK=D6({key:"redactor",default:{occlude:(Z)=>Z}}),wK=D6({key:"unacknowledgedUpdates",default:()=>[]});var LY=class{listeners;globalListeners;handleEvent(...Z){let[Y,...X]=Z;for(let _ of this.globalListeners)_(Y,...X);let G=this.listeners.get(Y);if(G)for(let _ of G)_(...X)}id="no_id_retrieved";emit;constructor(Z){this.emit=Z,this.listeners=new Map,this.globalListeners=new Set}on(Z,Y){let X=this.listeners.get(Z);if(X)X.add(Y);else this.listeners.set(Z,new Set([Y]));return this}onAny(Z){return this.globalListeners.add(Z),this}off(Z,Y){let X=this.listeners.get(Z);if(X)if(Y)X.delete(Y);else this.listeners.delete(Z);return this}offAny(Z){return this.globalListeners.delete(Z),this}},IK=class extends LY{incompleteData="";unprocessedEvents=[];incompleteLog="";unprocessedLogs=[];id="#####";proc;key;logger;handleLog(Z){if(Array.isArray(Z)){let[Y,...X]=Z;switch(Y){case"i":this.logger.info(...X);break;case"w":this.logger.warn(...X);break;case"e":this.logger.error(...X);break}}}constructor(Z,Y,X){super((G,..._)=>{let $=JSON.stringify([G,..._])+"\x03",W=(H)=>{if(H.code==="EPIPE")console.error("EPIPE error during write",this.proc.stdin);this.proc.stdin.removeListener("error",W)};return this.proc.stdin.once("error",W),this.proc.stdin.write($),this});if(this.proc=Z,this.key=Y,this.logger=X??{info:(...G)=>{console.info(this.id,this.key,...G)},warn:(...G)=>{console.warn(this.id,this.key,...G)},error:(...G)=>{console.error(this.id,this.key,...G)}},this.proc.stdout.on("data",(G)=>{let _=G.toString();if(_==="ALIVE"){this.logger.info(_);return}let $=_.split("\x03"),W=$[0];$[0]=this.incompleteData+W;let H=0;for(let Q of $){if(Q==="")continue;try{let J=a0(Q);this.handleEvent(...J),this.incompleteData=""}catch(J){if(J instanceof Error)console.error(["\u274C Malformed data received from child process","",Q,"",J.message].join(`
60
- \u274C `));try{if(H===0){this.incompleteData=Q;let z=a0(W);this.handleEvent(...z),this.incompleteData=""}else this.incompleteData+=Q}catch(z){if(z instanceof Error)console.error(["\u274C Malformed data received from child process","",W,"",z.message].join(`
61
- \u274C `))}}++H}}),this.proc.stderr.on("data",(G)=>{let _=G.toString().split("\x03"),$=_[0];_[0]=this.incompleteData+$;let W=0;for(let H of _){if(H==="")continue;try{let Q=a0(H);this.handleLog(Q),this.incompleteData=""}catch(Q){if(Q instanceof Error)console.error(["\u274C Malformed log received from child process","",H,"",Q.message].join(`
62
- \u274C `));try{if(W===0){this.incompleteData=H;let J=a0($);this.handleLog(J),this.incompleteData=""}else this.incompleteData+=H}catch(J){if(J instanceof Error)console.error(["\u274C Malformed log received from child process...","",$,"",J.message].join(`
63
- \u274C `))}}++W}}),Z.pid)this.id=Z.pid.toString()}},NF=class extends LY{in;out;id="no_id_retrieved";disposalFunctions=[];constructor(Z){super((...Y)=>{return this.out.next(Y),this});this.id=Z,this.in=new _0,this.out=new _0,this.in.subscribe("socket",(Y)=>{this.handleEvent(...Y)})}dispose(){for(let Z of this.disposalFunctions)Z()}},R_=class extends LY{incompleteData="";unprocessedEvents=[];relays;relayServices;proc;id="#####";log(...Z){this.proc.stderr.write(Q0(Z.map((Y)=>Y instanceof $4?`{ ${Y.toJSON().members.join(" | ")} }`:Y))+"\x03")}logger={info:(...Z)=>{this.log("i",...Z)},warn:(...Z)=>{this.log("w",...Z)},error:(...Z)=>{this.log("e",...Z)}};constructor(Z){super((Y,...X)=>{let G=JSON.stringify([Y,...X]);return this.proc.stdout.write(G+"\x03"),this});if(this.proc=Z,this.proc.stdin.resume(),this.relays=new Map,this.relayServices=[],this.proc.stdin.on("data",(Y)=>{let X=Y.toString().split("\x03"),G=X[0];X[0]=this.incompleteData+G;let _=0;for(let $ of X){if($==="")continue;try{let W=a0($);this.logger.info("\uD83C\uDFB0","received",W),this.handleEvent(...W),this.incompleteData=""}catch(W){if(W instanceof Error)this.logger.error(["received malformed data from parent process:","",$,"",W.message].join(`
64
- \u274C `));try{if(_===0){this.incompleteData=$;let H=a0(G);this.logger.info("\uD83C\uDFB0","received",H),this.handleEvent(...H),this.incompleteData=""}else this.incompleteData+=$}catch(H){if(H instanceof Error)this.logger.error(["received malformed data from parent process:","",G,"",H.message].join(`
65
- \u274C `))}}++_}}),this.on("exit",()=>{this.logger.info("\uD83D\uDD25",this.id,'received "exit"'),this.proc.exit(0)}),this.proc.pid)this.id=this.proc.pid?.toString();this.on("user-joins",(Y)=>{this.logger.info("\uD83D\uDC64","user",Y,"joined");let X=`user::${Y}`,G=new NF(X);this.relays.set(Y,G),this.logger.info("\uD83D\uDD17","attaching services:",`[${[...this.relayServices.keys()].join(", ")}]`);for(let _ of this.relayServices){let $=_(G,X);if($)G.disposalFunctions.push($)}this.on(X,(..._)=>{G.in.next(_)}),G.out.subscribe("socket",(_)=>{this.emit(..._)})}),this.on("user-leaves",(Y)=>{let X=this.relays.get(Y);if(this.off(`relay:${Y}`),X)X.dispose(),this.relays.delete(Y)}),this.proc.stdout.write("ALIVE")}receiveRelay(Z){this.logger.info("\uD83D\uDD17","running relay method"),this.relayServices.push(Z)}};var A_=new Map;var BK=M6({key:"joinRoom",do:(Z,Y,X,G)=>{let _={enteredAtEpoch:G};return U8(L8,($)=>{$.set({room:Y,user:X},_)},Z.env().store),_}}),KK=M6({key:"leaveRoom",do:({env:Z},Y,X)=>{U8(L8,(G)=>{G.delete({room:Y,user:X})},Z().store)}}),CK=M6({key:"destroyRoom",do:({set:Z,env:Y},X)=>{U8(L8,(_)=>{_.delete({room:X})},Y().store),Z(M_,(_)=>(_.delete(X),_));let G=A_.get(X);if(G)G.emit("exit"),A_.delete(X)}}),TK=D6({key:"sockets",default:null}),qK=D2({key:"socketsIndex",class:$4}),jK=D2({key:"usersIndex",class:$4}),PK=O6({key:"usersOfSockets",between:["user","socket"],cardinality:"1:1",isAType:(Z)=>Z.startsWith("user::"),isBType:(Z)=>Z.startsWith("socket::")}),SK=V6({key:"userMutualSituationalAwarenessIndexes",get:(Z)=>()=>{return[Z]}});var{file:tW,serve:bE}=globalThis.Bun;import{readFileSync as I_}from"fs";import{createServer as KF}from"http";import{createServer as CF}from"https";import{resolve as OY}from"path";function N_(Z,Y){if(Z instanceof Promise)throw new Error(Y)}function wF(Z,Y){let X={},G=[];for(let _ in Z){let $=Z[_]["~standard"].validate(Y[_]);if(N_($,`Validation must be synchronous, but ${_} returned a Promise.`),$.issues){G.push(...$.issues.map((W)=>({...W,message:W.message,path:[_,...W.path??[]]})));continue}X[_]=$.value}if(G.length)return{issues:G};return{value:X}}function DY(Z){let Y=Z.runtimeEnvStrict??Z.runtimeEnv??process.env;if(Z.emptyStringAsUndefined??!1){for(let[h,g]of Object.entries(Y))if(g==="")delete Y[h]}if(!!Z.skipValidation)return Y;let _=typeof Z.client==="object"?Z.client:{},$=typeof Z.server==="object"?Z.server:{},W=typeof Z.shared==="object"?Z.shared:{},H=Z.isServer??(typeof window==="undefined"||("Deno"in window)),Q=H?{...$,...W,..._}:{..._,...W},J=Z.createFinalSchema?.(Q,H)["~standard"].validate(Y)??wF(Q,Y);N_(J,"Validation must be synchronous");let z=Z.onValidationError??((h)=>{throw console.error("\u274C Invalid environment variables:",h),new Error("Invalid environment variables")}),U=Z.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=(h)=>{if(!Z.clientPrefix)return!0;return!h.startsWith(Z.clientPrefix)&&!(h in W)},V=(h)=>{return H||!D(h)},N=(h)=>{return h==="__esModule"||h==="$$typeof"},R=(Z.extends??[]).reduce((h,g)=>{return Object.assign(h,g)},{}),b=Object.assign(R,J.value);return new Proxy(b,{get(h,g){if(typeof g!=="string")return;if(N(g))return;if(!V(g))return U(g);return Reflect.get(h,g)}})}var IF="__vite_start_time"in globalThis,BF=typeof window!=="undefined",uK="vitest"in globalThis,H4=F1("string"),w_=F1('"true" | "false" | undefined'),g1=DY({isServer:!IF&&!BF,server:{CI:F1("string | undefined").pipe(Boolean),POSTGRES_USER:H4,POSTGRES_PASSWORD:H4,POSTGRES_DATABASE:H4,POSTGRES_HOST:H4,POSTGRES_PORT:H4.pipe((Z)=>Number.parseInt(Z,10)),BACKEND_PORT:H4.pipe((Z)=>Number.parseInt(Z,10)),RUN_WORKERS_FROM_SOURCE:w_.pipe((Z)=>Z==="true"),FRONTEND_PORT:H4.pipe((Z)=>Number.parseInt(Z,10)),FRONTEND_ORIGINS:H4.pipe.try((Z)=>JSON.parse(Z),F1("string[]")),API_KEY_OPENAI:F1("string | undefined"),API_KEY_RESEND:F1("string | undefined")},clientPrefix:"VITE_",client:{VITE_BACKEND_ORIGIN:H4,VITE_DEV_FRONTEND_HOST:F1("string | undefined"),VITE_DEV_HTTPS:w_.pipe((Z)=>Z==="true")},runtimeEnv:import.meta.env,emptyStringAsUndefined:!0});var B_=OY(import.meta.dirname,"../dev"),h6=g1.VITE_DEV_HTTPS?{cert:I_(OY(B_,"./cert.pem"),"utf-8"),key:I_(OY(B_,"./key.pem"),"utf-8")}:void 0;function rK(Z){if(h6)return CF(h6,Z);return KF({},Z)}import PE from"path";var E=Symbol.for("drizzle:entityKind");function M(Z,Y){if(!Z||typeof Z!=="object")return!1;if(Z instanceof Y)return!0;if(!Object.prototype.hasOwnProperty.call(Y,E))throw new Error(`Class "${Y.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(Z).constructor;if(X)while(X){if(E in X&&X[E]===Y[E])return!0;X=Object.getPrototypeOf(X)}return!1}class F0{constructor(Z,Y){this.table=Z,this.config=Y,this.name=Y.name,this.keyAsName=Y.keyAsName,this.notNull=Y.notNull,this.default=Y.default,this.defaultFn=Y.defaultFn,this.onUpdateFn=Y.onUpdateFn,this.hasDefault=Y.hasDefault,this.primary=Y.primaryKey,this.isUnique=Y.isUnique,this.uniqueName=Y.uniqueName,this.uniqueType=Y.uniqueType,this.dataType=Y.dataType,this.columnType=Y.columnType,this.generated=Y.generated,this.generatedIdentity=Y.generatedIdentity}static[E]="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(Z){return Z}mapToDriverValue(Z){return Z}shouldDisableInsert(){return this.config.generated!==void 0&&this.config.generated.type!=="byDefault"}}class VY{static[E]="ColumnBuilder";config;constructor(Z,Y,X){this.config={name:Z,keyAsName:Z==="",notNull:!1,default:void 0,hasDefault:!1,primaryKey:!1,isUnique:!1,uniqueName:void 0,uniqueType:void 0,dataType:Y,columnType:X,generated:void 0}}$type(){return this}notNull(){return this.config.notNull=!0,this}default(Z){return this.config.default=Z,this.config.hasDefault=!0,this}$defaultFn(Z){return this.config.defaultFn=Z,this.config.hasDefault=!0,this}$default=this.$defaultFn;$onUpdateFn(Z){return this.config.onUpdateFn=Z,this.config.hasDefault=!0,this}$onUpdate=this.$onUpdateFn;primaryKey(){return this.config.primaryKey=!0,this.config.notNull=!0,this}setName(Z){if(this.config.name!=="")return;this.config.name=Z}}var p1=Symbol.for("drizzle:Name");class MY{static[E]="PgForeignKeyBuilder";reference;_onUpdate="no action";_onDelete="no action";constructor(Z,Y){if(this.reference=()=>{let{name:X,columns:G,foreignColumns:_}=Z();return{name:X,columns:G,foreignTable:_[0].table,foreignColumns:_}},Y)this._onUpdate=Y.onUpdate,this._onDelete=Y.onDelete}onUpdate(Z){return this._onUpdate=Z===void 0?"no action":Z,this}onDelete(Z){return this._onDelete=Z===void 0?"no action":Z,this}build(Z){return new K_(Z,this)}}class K_{constructor(Z,Y){this.table=Z,this.reference=Y.reference,this.onUpdate=Y._onUpdate,this.onDelete=Y._onDelete}static[E]="PgForeignKey";reference;onUpdate;onDelete;getName(){let{name:Z,columns:Y,foreignColumns:X}=this.reference(),G=Y.map((W)=>W.name),_=X.map((W)=>W.name),$=[this.table[p1],...G,X[0].table[p1],..._];return Z??`${$.join("_")}_fk`}}function k6(Z,...Y){return Z(...Y)}function C_(Z,Y){return`${Z[p1]}_${Y.join("_")}_unique`}function T_(Z,Y,X){for(let G=Y;G<Z.length;G++){let _=Z[G];if(_==="\\"){G++;continue}if(_==='"')return[Z.slice(Y,G).replace(/\\/g,""),G+1];if(X)continue;if(_===","||_==="}")return[Z.slice(Y,G).replace(/\\/g,""),G]}return[Z.slice(Y).replace(/\\/g,""),Z.length]}function q_(Z,Y=0){let X=[],G=Y,_=!1;while(G<Z.length){let $=Z[G];if($===","){if(_||G===Y)X.push("");_=!0,G++;continue}if(_=!1,$==="\\"){G+=2;continue}if($==='"'){let[Q,J]=T_(Z,G+1,!0);X.push(Q),G=J;continue}if($==="}")return[X,G+1];if($==="{"){let[Q,J]=q_(Z,G+1);X.push(Q),G=J;continue}let[W,H]=T_(Z,G,!1);X.push(W),G=H}return[X,G]}function j_(Z){let[Y]=q_(Z,1);return Y}function AY(Z){return`{${Z.map((Y)=>{if(Array.isArray(Y))return AY(Y);if(typeof Y==="string")return`"${Y.replace(/\\/g,"\\\\").replace(/"/g,"\\\"")}"`;return`${Y}`}).join(",")}}`}class k extends VY{foreignKeyConfigs=[];static[E]="PgColumnBuilder";array(Z){return new S_(this.config.name,this,Z)}references(Z,Y={}){return this.foreignKeyConfigs.push({ref:Z,actions:Y}),this}unique(Z,Y){return this.config.isUnique=!0,this.config.uniqueName=Z,this.config.uniqueType=Y?.nulls,this}generatedAlwaysAs(Z){return this.config.generated={as:Z,type:"always",mode:"stored"},this}buildForeignKeys(Z,Y){return this.foreignKeyConfigs.map(({ref:X,actions:G})=>{return k6((_,$)=>{let W=new MY(()=>{let H=_();return{columns:[Z],foreignColumns:[H]}});if($.onUpdate)W.onUpdate($.onUpdate);if($.onDelete)W.onDelete($.onDelete);return W.build(Y)},X,G)})}buildExtraConfigColumn(Z){return new P_(Z,this.config)}}class j extends F0{constructor(Z,Y){if(!Y.uniqueName)Y.uniqueName=C_(Z,[Y.name]);super(Z,Y);this.table=Z}static[E]="PgColumn"}class P_ extends j{static[E]="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(Z){return this.indexConfig.opClass=Z,this}}class D8{static[E]="IndexedColumn";constructor(Z,Y,X,G){this.name=Z,this.keyAsName=Y,this.type=X,this.indexConfig=G}name;keyAsName;type;indexConfig}class S_ extends k{static[E]="PgArrayBuilder";constructor(Z,Y,X){super(Z,"array","PgArray");this.config.baseBuilder=Y,this.config.size=X}build(Z){let Y=this.config.baseBuilder.build(Z);return new RY(Z,this.config,Y)}}class RY extends j{constructor(Z,Y,X,G){super(Z,Y);this.baseColumn=X,this.range=G,this.size=Y.size}size;static[E]="PgArray";getSQLType(){return`${this.baseColumn.getSQLType()}[${typeof this.size==="number"?this.size:""}]`}mapFromDriverValue(Z){if(typeof Z==="string")Z=j_(Z);return Z.map((Y)=>this.baseColumn.mapFromDriverValue(Y))}mapToDriverValue(Z,Y=!1){let X=Z.map((G)=>G===null?null:M(this.baseColumn,RY)?this.baseColumn.mapToDriverValue(G,!0):this.baseColumn.mapToDriverValue(G));if(Y)return X;return AY(X)}}class v_ extends k{static[E]="PgEnumObjectColumnBuilder";constructor(Z,Y){super(Z,"string","PgEnumObjectColumn");this.config.enum=Y}build(Z){return new x_(Z,this.config)}}class x_ extends j{static[E]="PgEnumObjectColumn";enum;enumValues=this.config.enum.enumValues;constructor(Z,Y){super(Z,Y);this.enum=Y.enum}getSQLType(){return this.enum.enumName}}var b6=Symbol.for("drizzle:isPgEnum");function f_(Z){return!!Z&&typeof Z==="function"&&b6 in Z&&Z[b6]===!0}class h_ extends k{static[E]="PgEnumColumnBuilder";constructor(Z,Y){super(Z,"string","PgEnumColumn");this.config.enum=Y}build(Z){return new k_(Z,this.config)}}class k_ extends j{static[E]="PgEnumColumn";enum=this.config.enum;enumValues=this.config.enum.enumValues;constructor(Z,Y){super(Z,Y);this.enum=Y.enum}getSQLType(){return this.enum.enumName}}function O8(Z,Y){return Array.isArray(Y)?TF(Z,[...Y],void 0):qF(Z,Y,void 0)}function TF(Z,Y,X){let G=Object.assign((_)=>new h_(_??"",G),{enumName:Z,enumValues:Y,schema:X,[b6]:!0});return G}function qF(Z,Y,X){let G=Object.assign((_)=>new v_(_??"",G),{enumName:Z,enumValues:Object.values(Y),schema:X,[b6]:!0});return G}class S0{static[E]="Subquery";constructor(Z,Y,X,G=!1,_=[]){this._={brand:"Subquery",sql:Z,selectedFields:Y,alias:X,isWith:G,usedTables:_}}}class V8 extends S0{static[E]="WithSubquery"}var b_="0.44.5";var NY,wY,E0={startActiveSpan(Z,Y){if(!NY)return Y();if(!wY)wY=NY.trace.getTracer("drizzle-orm",b_);return k6((X,G)=>G.startActiveSpan(Z,(_)=>{try{return Y(_)}catch($){throw _.setStatus({code:X.SpanStatusCode.ERROR,message:$ instanceof Error?$.message:"Unknown error"}),$}finally{_.end()}}),NY,wY)}};var M0=Symbol.for("drizzle:ViewBaseConfig");var p4=Symbol.for("drizzle:Schema"),y6=Symbol.for("drizzle:Columns"),y_=Symbol.for("drizzle:ExtraConfigColumns"),IY=Symbol.for("drizzle:OriginalName"),BY=Symbol.for("drizzle:BaseName"),M8=Symbol.for("drizzle:IsAlias"),g_=Symbol.for("drizzle:ExtraConfigBuilder"),jF=Symbol.for("drizzle:IsDrizzleTable");class P{static[E]="Table";static Symbol={Name:p1,Schema:p4,OriginalName:IY,Columns:y6,ExtraConfigColumns:y_,BaseName:BY,IsAlias:M8,ExtraConfigBuilder:g_};[p1];[IY];[p4];[y6];[y_];[BY];[M8]=!1;[jF]=!0;[g_]=void 0;constructor(Z,Y,X){this[p1]=this[IY]=Z,this[p4]=Y,this[BY]=X}}function d0(Z){return Z[p1]}function m4(Z){return`${Z[p4]??"public"}.${Z[p1]}`}function KY(Z){return Z!==null&&Z!==void 0&&typeof Z.getSQL==="function"}function PF(Z){let Y={sql:"",params:[]};for(let X of Z)if(Y.sql+=X.sql,Y.params.push(...X.params),X.typings?.length){if(!Y.typings)Y.typings=[];Y.typings.push(...X.typings)}return Y}class m0{static[E]="StringChunk";value;constructor(Z){this.value=Array.isArray(Z)?Z:[Z]}getSQL(){return new f([this])}}class f{constructor(Z){this.queryChunks=Z;for(let Y of Z)if(M(Y,P)){let X=Y[P.Symbol.Schema];this.usedTables.push(X===void 0?Y[P.Symbol.Name]:X+"."+Y[P.Symbol.Name])}}static[E]="SQL";decoder=m_;shouldInlineParams=!1;usedTables=[];append(Z){return this.queryChunks.push(...Z.queryChunks),this}toQuery(Z){return E0.startActiveSpan("drizzle.buildSQL",(Y)=>{let X=this.buildQueryFromSourceParams(this.queryChunks,Z);return Y?.setAttributes({"drizzle.query.text":X.sql,"drizzle.query.params":JSON.stringify(X.params)}),X})}buildQueryFromSourceParams(Z,Y){let X=Object.assign({},Y,{inlineParams:Y.inlineParams||this.shouldInlineParams,paramStartIndex:Y.paramStartIndex||{value:0}}),{casing:G,escapeName:_,escapeParam:$,prepareTyping:W,inlineParams:H,paramStartIndex:Q}=X;return PF(Z.map((J)=>{if(M(J,m0))return{sql:J.value.join(""),params:[]};if(M(J,g6))return{sql:_(J.value),params:[]};if(J===void 0)return{sql:"",params:[]};if(Array.isArray(J)){let z=[new m0("(")];for(let[U,D]of J.entries())if(z.push(D),U<J.length-1)z.push(new m0(", "));return z.push(new m0(")")),this.buildQueryFromSourceParams(z,X)}if(M(J,f))return this.buildQueryFromSourceParams(J.queryChunks,{...X,inlineParams:H||J.shouldInlineParams});if(M(J,P)){let z=J[P.Symbol.Schema],U=J[P.Symbol.Name];return{sql:z===void 0||J[M8]?_(U):_(z)+"."+_(U),params:[]}}if(M(J,F0)){let z=G.getColumnCasing(J);if(Y.invokeSource==="indexes")return{sql:_(z),params:[]};let U=J.table[P.Symbol.Schema];return{sql:J.table[M8]||U===void 0?_(J.table[P.Symbol.Name])+"."+_(z):_(U)+"."+_(J.table[P.Symbol.Name])+"."+_(z),params:[]}}if(M(J,L1)){let z=J[M0].schema,U=J[M0].name;return{sql:z===void 0||J[M0].isAlias?_(U):_(z)+"."+_(U),params:[]}}if(M(J,w1)){if(M(J.value,B4))return{sql:$(Q.value++,J),params:[J],typings:["none"]};let z=J.value===null?null:J.encoder.mapToDriverValue(J.value);if(M(z,f))return this.buildQueryFromSourceParams([z],X);if(H)return{sql:this.mapInlineParam(z,X),params:[]};let U=["none"];if(W)U=[W(J.encoder)];return{sql:$(Q.value++,z),params:[z],typings:U}}if(M(J,B4))return{sql:$(Q.value++,J),params:[J],typings:["none"]};if(M(J,f.Aliased)&&J.fieldAlias!==void 0)return{sql:_(J.fieldAlias),params:[]};if(M(J,S0)){if(J._.isWith)return{sql:_(J._.alias),params:[]};return this.buildQueryFromSourceParams([new m0("("),J._.sql,new m0(") "),new g6(J._.alias)],X)}if(f_(J)){if(J.schema)return{sql:_(J.schema)+"."+_(J.enumName),params:[]};return{sql:_(J.enumName),params:[]}}if(KY(J)){if(J.shouldOmitSQLParens?.())return this.buildQueryFromSourceParams([J.getSQL()],X);return this.buildQueryFromSourceParams([new m0("("),J.getSQL(),new m0(")")],X)}if(H)return{sql:this.mapInlineParam(J,X),params:[]};return{sql:$(Q.value++,J),params:[J],typings:["none"]}}))}mapInlineParam(Z,{escapeString:Y}){if(Z===null)return"null";if(typeof Z==="number"||typeof Z==="boolean")return Z.toString();if(typeof Z==="string")return Y(Z);if(typeof Z==="object"){let X=Z.toString();if(X==="[object Object]")return Y(JSON.stringify(Z));return Y(X)}throw new Error("Unexpected param value: "+Z)}getSQL(){return this}as(Z){if(Z===void 0)return this;return new f.Aliased(this,Z)}mapWith(Z){return this.decoder=typeof Z==="function"?{mapFromDriverValue:Z}:Z,this}inlineParams(){return this.shouldInlineParams=!0,this}if(Z){return Z?this:void 0}}class g6{constructor(Z){this.value=Z}static[E]="Name";brand;getSQL(){return new f([this])}}function p_(Z){return typeof Z==="object"&&Z!==null&&"mapToDriverValue"in Z&&typeof Z.mapToDriverValue==="function"}var m_={mapFromDriverValue:(Z)=>Z},u_={mapToDriverValue:(Z)=>Z},yC={...m_,...u_};class w1{constructor(Z,Y=u_){this.value=Z,this.encoder=Y}static[E]="Param";brand;getSQL(){return new f([this])}}function L(Z,...Y){let X=[];if(Y.length>0||Z.length>0&&Z[0]!=="")X.push(new m0(Z[0]));for(let[G,_]of Y.entries())X.push(_,new m0(Z[G+1]));return new f(X)}((Z)=>{function Y(){return new f([])}Z.empty=Y;function X(Q){return new f(Q)}Z.fromList=X;function G(Q){return new f([new m0(Q)])}Z.raw=G;function _(Q,J){let z=[];for(let[U,D]of Q.entries()){if(U>0&&J!==void 0)z.push(J);z.push(D)}return new f(z)}Z.join=_;function $(Q){return new g6(Q)}Z.identifier=$;function W(Q){return new B4(Q)}Z.placeholder=W;function H(Q,J){return new w1(Q,J)}Z.param=H})(L||(L={}));((Z)=>{class Y{constructor(X,G){this.sql=X,this.fieldAlias=G}static[E]="SQL.Aliased";isSelectionField=!1;getSQL(){return this.sql}clone(){return new Y(this.sql,this.fieldAlias)}}Z.Aliased=Y})(f||(f={}));class B4{constructor(Z){this.name=Z}static[E]="Placeholder";getSQL(){return new f([this])}}function CY(Z,Y){return Z.map((X)=>{if(M(X,B4)){if(!(X.name in Y))throw new Error(`No value for placeholder "${X.name}" was provided`);return Y[X.name]}if(M(X,w1)&&M(X.value,B4)){if(!(X.value.name in Y))throw new Error(`No value for placeholder "${X.value.name}" was provided`);return X.encoder.mapToDriverValue(Y[X.value.name])}return X})}var SF=Symbol.for("drizzle:IsDrizzleView");class L1{static[E]="View";[M0];[SF]=!0;constructor({name:Z,schema:Y,selectedFields:X,query:G}){this[M0]={name:Z,originalName:Z,schema:Y,selectedFields:X,query:G,isExisting:!G,isAlias:!1}}getSQL(){return new f([this])}}F0.prototype.getSQL=function(){return new f([this])};P.prototype.getSQL=function(){return new f([this])};S0.prototype.getSQL=function(){return new f([this])};class w2{constructor(Z){this.table=Z}static[E]="ColumnAliasProxyHandler";get(Z,Y){if(Y==="table")return this.table;return Z[Y]}}class A8{constructor(Z,Y){this.alias=Z,this.replaceOriginalName=Y}static[E]="TableAliasProxyHandler";get(Z,Y){if(Y===P.Symbol.IsAlias)return!0;if(Y===P.Symbol.Name)return this.alias;if(this.replaceOriginalName&&Y===P.Symbol.OriginalName)return this.alias;if(Y===M0)return{...Z[M0],name:this.alias,isAlias:!0};if(Y===P.Symbol.Columns){let G=Z[P.Symbol.Columns];if(!G)return G;let _={};return Object.keys(G).map(($)=>{_[$]=new Proxy(G[$],new w2(new Proxy(Z,this)))}),_}let X=Z[Y];if(M(X,F0))return new Proxy(X,new w2(new Proxy(Z,this)));return X}}function p6(Z,Y){return new Proxy(Z,new A8(Y,!1))}function n1(Z,Y){return new Proxy(Z,new w2(new Proxy(Z.table,new A8(Y,!1))))}function TY(Z,Y){return new f.Aliased(R8(Z.sql,Y),Z.fieldAlias)}function R8(Z,Y){return L.join(Z.queryChunks.map((X)=>{if(M(X,F0))return n1(X,Y);if(M(X,f))return R8(X,Y);if(M(X,f.Aliased))return TY(X,Y);return X}))}class m6 extends Error{static[E]="DrizzleError";constructor({message:Z,cause:Y}){super(Z);this.name="DrizzleError",this.cause=Y}}class J4 extends Error{constructor(Z,Y,X){super(`Failed query: ${Z}
66
- params: ${Y}`);if(this.query=Z,this.params=Y,this.cause=X,Error.captureStackTrace(this,J4),X)this.cause=X}}class qY extends m6{static[E]="TransactionRollbackError";constructor(){super({message:"Rollback"})}}class d_{static[E]="ConsoleLogWriter";write(Z){console.log(Z)}}class jY{static[E]="DefaultLogger";writer;constructor(Z){this.writer=Z?.writer??new d_}logQuery(Z,Y){let X=Y.map((_)=>{try{return JSON.stringify(_)}catch{return String(_)}}),G=X.length?` -- params: [${X.join(", ")}]`:"";this.writer.write(`Query: ${Z}${G}`)}}class PY{static[E]="NoopLogger";logQuery(){}}class _1{static[E]="QueryPromise";[Symbol.toStringTag]="QueryPromise";catch(Z){return this.then(void 0,Z)}finally(Z){return this.then((Y)=>{return Z?.(),Y},(Y)=>{throw Z?.(),Y})}then(Z,Y){return this.execute().then(Z,Y)}}function c_(Z,Y,X){let G={},_=Z.reduce(($,{path:W,field:H},Q)=>{let J;if(M(H,F0))J=H;else if(M(H,f))J=H.decoder;else J=H.sql.decoder;let z=$;for(let[U,D]of W.entries())if(U<W.length-1){if(!(D in z))z[D]={};z=z[D]}else{let V=Y[Q],N=z[D]=V===null?null:J.mapFromDriverValue(V);if(X&&M(H,F0)&&W.length===2){let R=W[0];if(!(R in G))G[R]=N===null?d0(H.table):!1;else if(typeof G[R]==="string"&&G[R]!==d0(H.table))G[R]=!1}}return $},{});if(X&&Object.keys(G).length>0){for(let[$,W]of Object.entries(G))if(typeof W==="string"&&!X[W])_[$]=null}return _}function j1(Z,Y){return Object.entries(Z).reduce((X,[G,_])=>{if(typeof G!=="string")return X;let $=Y?[...Y,G]:[G];if(M(_,F0)||M(_,f)||M(_,f.Aliased))X.push({path:$,field:_});else if(M(_,P))X.push(...j1(_[P.Symbol.Columns],$));else X.push(...j1(_,$));return X},[])}function N8(Z,Y){let X=Object.keys(Z),G=Object.keys(Y);if(X.length!==G.length)return!1;for(let[_,$]of X.entries())if($!==G[_])return!1;return!0}function u6(Z,Y){let X=Object.entries(Y).filter(([,G])=>G!==void 0).map(([G,_])=>{if(M(_,f)||M(_,F0))return[G,_];else return[G,new w1(_,Z[P.Symbol.Columns][G])]});if(X.length===0)throw new Error("No values to set");return Object.fromEntries(X)}function l_(Z,Y){for(let X of Y)for(let G of Object.getOwnPropertyNames(X.prototype)){if(G==="constructor")continue;Object.defineProperty(Z.prototype,G,Object.getOwnPropertyDescriptor(X.prototype,G)||Object.create(null))}}function i_(Z){return Z[P.Symbol.Columns]}function Q4(Z){return M(Z,S0)?Z._.alias:M(Z,L1)?Z[M0].name:M(Z,f)?void 0:Z[P.Symbol.IsAlias]?Z[P.Symbol.Name]:Z[P.Symbol.BaseName]}function X0(Z,Y){return{name:typeof Z==="string"&&Z.length>0?Z:"",config:typeof Z==="object"?Z:Y}}function o_(Z){if(typeof Z!=="object"||Z===null)return!1;if(Z.constructor.name!=="Object")return!1;if("logger"in Z){let Y=typeof Z.logger;if(Y!=="boolean"&&(Y!=="object"||typeof Z.logger.logQuery!=="function")&&Y!=="undefined")return!1;return!0}if("schema"in Z){let Y=typeof Z.schema;if(Y!=="object"&&Y!=="undefined")return!1;return!0}if("casing"in Z){let Y=typeof Z.casing;if(Y!=="string"&&Y!=="undefined")return!1;return!0}if("mode"in Z){if(Z.mode!=="default"||Z.mode!=="planetscale"||Z.mode!==void 0)return!1;return!0}if("connection"in Z){let Y=typeof Z.connection;if(Y!=="string"&&Y!=="object"&&Y!=="undefined")return!1;return!0}if("client"in Z){let Y=typeof Z.client;if(Y!=="object"&&Y!=="function"&&Y!=="undefined")return!1;return!0}if(Object.keys(Z).length===0)return!0;return!1}class K4 extends k{static[E]="PgIntColumnBaseBuilder";generatedAlwaysAsIdentity(Z){if(Z){let{name:Y,...X}=Z;this.config.generatedIdentity={type:"always",sequenceName:Y,sequenceOptions:X}}else this.config.generatedIdentity={type:"always"};return this.config.hasDefault=!0,this.config.notNull=!0,this}generatedByDefaultAsIdentity(Z){if(Z){let{name:Y,...X}=Z;this.config.generatedIdentity={type:"byDefault",sequenceName:Y,sequenceOptions:X}}else this.config.generatedIdentity={type:"byDefault"};return this.config.hasDefault=!0,this.config.notNull=!0,this}}class n_ extends K4{static[E]="PgBigInt53Builder";constructor(Z){super(Z,"number","PgBigInt53")}build(Z){return new r_(Z,this.config)}}class r_ extends j{static[E]="PgBigInt53";getSQLType(){return"bigint"}mapFromDriverValue(Z){if(typeof Z==="number")return Z;return Number(Z)}}class s_ extends K4{static[E]="PgBigInt64Builder";constructor(Z){super(Z,"bigint","PgBigInt64")}build(Z){return new a_(Z,this.config)}}class a_ extends j{static[E]="PgBigInt64";getSQLType(){return"bigint"}mapFromDriverValue(Z){return BigInt(Z)}}function t_(Z,Y){let{name:X,config:G}=X0(Z,Y);if(G.mode==="number")return new n_(X);return new s_(X)}class e_ extends k{static[E]="PgBigSerial53Builder";constructor(Z){super(Z,"number","PgBigSerial53");this.config.hasDefault=!0,this.config.notNull=!0}build(Z){return new Z$(Z,this.config)}}class Z$ extends j{static[E]="PgBigSerial53";getSQLType(){return"bigserial"}mapFromDriverValue(Z){if(typeof Z==="number")return Z;return Number(Z)}}class Y$ extends k{static[E]="PgBigSerial64Builder";constructor(Z){super(Z,"bigint","PgBigSerial64");this.config.hasDefault=!0}build(Z){return new X$(Z,this.config)}}class X$ extends j{static[E]="PgBigSerial64";getSQLType(){return"bigserial"}mapFromDriverValue(Z){return BigInt(Z)}}function G$(Z,Y){let{name:X,config:G}=X0(Z,Y);if(G.mode==="number")return new e_(X);return new Y$(X)}class _$ extends k{static[E]="PgBooleanBuilder";constructor(Z){super(Z,"boolean","PgBoolean")}build(Z){return new $$(Z,this.config)}}class $$ extends j{static[E]="PgBoolean";getSQLType(){return"boolean"}}function w8(Z){return new _$(Z??"")}class W$ extends k{static[E]="PgCharBuilder";constructor(Z,Y){super(Z,"string","PgChar");this.config.length=Y.length,this.config.enumValues=Y.enum}build(Z){return new H$(Z,this.config)}}class H$ extends j{static[E]="PgChar";length=this.config.length;enumValues=this.config.enumValues;getSQLType(){return this.length===void 0?"char":`char(${this.length})`}}function J$(Z,Y={}){let{name:X,config:G}=X0(Z,Y);return new W$(X,G)}class Q$ extends k{static[E]="PgCidrBuilder";constructor(Z){super(Z,"string","PgCidr")}build(Z){return new z$(Z,this.config)}}class z$ extends j{static[E]="PgCidr";getSQLType(){return"cidr"}}function U$(Z){return new Q$(Z??"")}class F$ extends k{static[E]="PgCustomColumnBuilder";constructor(Z,Y,X){super(Z,"custom","PgCustomColumn");this.config.fieldConfig=Y,this.config.customTypeParams=X}build(Z){return new E$(Z,this.config)}}class E$ extends j{static[E]="PgCustomColumn";sqlName;mapTo;mapFrom;constructor(Z,Y){super(Z,Y);this.sqlName=Y.customTypeParams.dataType(Y.fieldConfig),this.mapTo=Y.customTypeParams.toDriver,this.mapFrom=Y.customTypeParams.fromDriver}getSQLType(){return this.sqlName}mapFromDriverValue(Z){return typeof this.mapFrom==="function"?this.mapFrom(Z):Z}mapToDriverValue(Z){return typeof this.mapTo==="function"?this.mapTo(Z):Z}}function L$(Z){return(Y,X)=>{let{name:G,config:_}=X0(Y,X);return new F$(G,_,Z)}}class z4 extends k{static[E]="PgDateColumnBaseBuilder";defaultNow(){return this.default(L`now()`)}}class D$ extends z4{static[E]="PgDateBuilder";constructor(Z){super(Z,"date","PgDate")}build(Z){return new d6(Z,this.config)}}class d6 extends j{static[E]="PgDate";getSQLType(){return"date"}mapFromDriverValue(Z){return new Date(Z)}mapToDriverValue(Z){return Z.toISOString()}}class O$ extends z4{static[E]="PgDateStringBuilder";constructor(Z){super(Z,"string","PgDateString")}build(Z){return new c6(Z,this.config)}}class c6 extends j{static[E]="PgDateString";getSQLType(){return"date"}}function V$(Z,Y){let{name:X,config:G}=X0(Z,Y);if(G?.mode==="date")return new D$(X);return new O$(X)}class M$ extends k{static[E]="PgDoublePrecisionBuilder";constructor(Z){super(Z,"number","PgDoublePrecision")}build(Z){return new A$(Z,this.config)}}class A$ extends j{static[E]="PgDoublePrecision";getSQLType(){return"double precision"}mapFromDriverValue(Z){if(typeof Z==="string")return Number.parseFloat(Z);return Z}}function R$(Z){return new M$(Z??"")}class N$ extends k{static[E]="PgInetBuilder";constructor(Z){super(Z,"string","PgInet")}build(Z){return new w$(Z,this.config)}}class w$ extends j{static[E]="PgInet";getSQLType(){return"inet"}}function I$(Z){return new N$(Z??"")}class B$ extends K4{static[E]="PgIntegerBuilder";constructor(Z){super(Z,"number","PgInteger")}build(Z){return new K$(Z,this.config)}}class K$ extends j{static[E]="PgInteger";getSQLType(){return"integer"}mapFromDriverValue(Z){if(typeof Z==="string")return Number.parseInt(Z);return Z}}function I8(Z){return new B$(Z??"")}class C$ extends k{static[E]="PgIntervalBuilder";constructor(Z,Y){super(Z,"string","PgInterval");this.config.intervalConfig=Y}build(Z){return new T$(Z,this.config)}}class T$ extends j{static[E]="PgInterval";fields=this.config.intervalConfig.fields;precision=this.config.intervalConfig.precision;getSQLType(){let Z=this.fields?` ${this.fields}`:"",Y=this.precision?`(${this.precision})`:"";return`interval${Z}${Y}`}}function q$(Z,Y={}){let{name:X,config:G}=X0(Z,Y);return new C$(X,G)}class j$ extends k{static[E]="PgJsonBuilder";constructor(Z){super(Z,"json","PgJson")}build(Z){return new l6(Z,this.config)}}class l6 extends j{static[E]="PgJson";constructor(Z,Y){super(Z,Y)}getSQLType(){return"json"}mapToDriverValue(Z){return JSON.stringify(Z)}mapFromDriverValue(Z){if(typeof Z==="string")try{return JSON.parse(Z)}catch{return Z}return Z}}function P$(Z){return new j$(Z??"")}class S$ extends k{static[E]="PgJsonbBuilder";constructor(Z){super(Z,"json","PgJsonb")}build(Z){return new i6(Z,this.config)}}class i6 extends j{static[E]="PgJsonb";constructor(Z,Y){super(Z,Y)}getSQLType(){return"jsonb"}mapToDriverValue(Z){return JSON.stringify(Z)}mapFromDriverValue(Z){if(typeof Z==="string")try{return JSON.parse(Z)}catch{return Z}return Z}}function v$(Z){return new S$(Z??"")}class x$ extends k{static[E]="PgLineBuilder";constructor(Z){super(Z,"array","PgLine")}build(Z){return new f$(Z,this.config)}}class f$ extends j{static[E]="PgLine";getSQLType(){return"line"}mapFromDriverValue(Z){let[Y,X,G]=Z.slice(1,-1).split(",");return[Number.parseFloat(Y),Number.parseFloat(X),Number.parseFloat(G)]}mapToDriverValue(Z){return`{${Z[0]},${Z[1]},${Z[2]}}`}}class h$ extends k{static[E]="PgLineABCBuilder";constructor(Z){super(Z,"json","PgLineABC")}build(Z){return new k$(Z,this.config)}}class k$ extends j{static[E]="PgLineABC";getSQLType(){return"line"}mapFromDriverValue(Z){let[Y,X,G]=Z.slice(1,-1).split(",");return{a:Number.parseFloat(Y),b:Number.parseFloat(X),c:Number.parseFloat(G)}}mapToDriverValue(Z){return`{${Z.a},${Z.b},${Z.c}}`}}function b$(Z,Y){let{name:X,config:G}=X0(Z,Y);if(!G?.mode||G.mode==="tuple")return new x$(X);return new h$(X)}class y$ extends k{static[E]="PgMacaddrBuilder";constructor(Z){super(Z,"string","PgMacaddr")}build(Z){return new g$(Z,this.config)}}class g$ extends j{static[E]="PgMacaddr";getSQLType(){return"macaddr"}}function p$(Z){return new y$(Z??"")}class m$ extends k{static[E]="PgMacaddr8Builder";constructor(Z){super(Z,"string","PgMacaddr8")}build(Z){return new u$(Z,this.config)}}class u$ extends j{static[E]="PgMacaddr8";getSQLType(){return"macaddr8"}}function d$(Z){return new m$(Z??"")}class c$ extends k{static[E]="PgNumericBuilder";constructor(Z,Y,X){super(Z,"string","PgNumeric");this.config.precision=Y,this.config.scale=X}build(Z){return new o6(Z,this.config)}}class o6 extends j{static[E]="PgNumeric";precision;scale;constructor(Z,Y){super(Z,Y);this.precision=Y.precision,this.scale=Y.scale}mapFromDriverValue(Z){if(typeof Z==="string")return Z;return String(Z)}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 l$ extends k{static[E]="PgNumericNumberBuilder";constructor(Z,Y,X){super(Z,"number","PgNumericNumber");this.config.precision=Y,this.config.scale=X}build(Z){return new i$(Z,this.config)}}class i$ extends j{static[E]="PgNumericNumber";precision;scale;constructor(Z,Y){super(Z,Y);this.precision=Y.precision,this.scale=Y.scale}mapFromDriverValue(Z){if(typeof Z==="number")return Z;return Number(Z)}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 o$ extends k{static[E]="PgNumericBigIntBuilder";constructor(Z,Y,X){super(Z,"bigint","PgNumericBigInt");this.config.precision=Y,this.config.scale=X}build(Z){return new n$(Z,this.config)}}class n$ extends j{static[E]="PgNumericBigInt";precision;scale;constructor(Z,Y){super(Z,Y);this.precision=Y.precision,this.scale=Y.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 r$(Z,Y){let{name:X,config:G}=X0(Z,Y),_=G?.mode;return _==="number"?new l$(X,G?.precision,G?.scale):_==="bigint"?new o$(X,G?.precision,G?.scale):new c$(X,G?.precision,G?.scale)}class s$ extends k{static[E]="PgPointTupleBuilder";constructor(Z){super(Z,"array","PgPointTuple")}build(Z){return new a$(Z,this.config)}}class a$ extends j{static[E]="PgPointTuple";getSQLType(){return"point"}mapFromDriverValue(Z){if(typeof Z==="string"){let[Y,X]=Z.slice(1,-1).split(",");return[Number.parseFloat(Y),Number.parseFloat(X)]}return[Z.x,Z.y]}mapToDriverValue(Z){return`(${Z[0]},${Z[1]})`}}class t$ extends k{static[E]="PgPointObjectBuilder";constructor(Z){super(Z,"json","PgPointObject")}build(Z){return new e$(Z,this.config)}}class e$ extends j{static[E]="PgPointObject";getSQLType(){return"point"}mapFromDriverValue(Z){if(typeof Z==="string"){let[Y,X]=Z.slice(1,-1).split(",");return{x:Number.parseFloat(Y),y:Number.parseFloat(X)}}return Z}mapToDriverValue(Z){return`(${Z.x},${Z.y})`}}function Z3(Z,Y){let{name:X,config:G}=X0(Z,Y);if(!G?.mode||G.mode==="tuple")return new s$(X);return new t$(X)}function vF(Z){let Y=[];for(let X=0;X<Z.length;X+=2)Y.push(Number.parseInt(Z.slice(X,X+2),16));return new Uint8Array(Y)}function Y3(Z,Y){let X=new ArrayBuffer(8),G=new DataView(X);for(let _=0;_<8;_++)G.setUint8(_,Z[Y+_]);return G.getFloat64(0,!0)}function SY(Z){let Y=vF(Z),X=0,G=Y[X];X+=1;let _=new DataView(Y.buffer),$=_.getUint32(X,G===1);X+=4;let W;if($&536870912)W=_.getUint32(X,G===1),X+=4;if(($&65535)===1){let H=Y3(Y,X);X+=8;let Q=Y3(Y,X);return X+=8,[H,Q]}throw new Error("Unsupported geometry type")}class X3 extends k{static[E]="PgGeometryBuilder";constructor(Z){super(Z,"array","PgGeometry")}build(Z){return new G3(Z,this.config)}}class G3 extends j{static[E]="PgGeometry";getSQLType(){return"geometry(point)"}mapFromDriverValue(Z){return SY(Z)}mapToDriverValue(Z){return`point(${Z[0]} ${Z[1]})`}}class _3 extends k{static[E]="PgGeometryObjectBuilder";constructor(Z){super(Z,"json","PgGeometryObject")}build(Z){return new $3(Z,this.config)}}class $3 extends j{static[E]="PgGeometryObject";getSQLType(){return"geometry(point)"}mapFromDriverValue(Z){let Y=SY(Z);return{x:Y[0],y:Y[1]}}mapToDriverValue(Z){return`point(${Z.x} ${Z.y})`}}function W3(Z,Y){let{name:X,config:G}=X0(Z,Y);if(!G?.mode||G.mode==="tuple")return new X3(X);return new _3(X)}class H3 extends k{static[E]="PgRealBuilder";constructor(Z,Y){super(Z,"number","PgReal");this.config.length=Y}build(Z){return new J3(Z,this.config)}}class J3 extends j{static[E]="PgReal";constructor(Z,Y){super(Z,Y)}getSQLType(){return"real"}mapFromDriverValue=(Z)=>{if(typeof Z==="string")return Number.parseFloat(Z);return Z}}function Q3(Z){return new H3(Z??"")}class z3 extends k{static[E]="PgSerialBuilder";constructor(Z){super(Z,"number","PgSerial");this.config.hasDefault=!0,this.config.notNull=!0}build(Z){return new U3(Z,this.config)}}class U3 extends j{static[E]="PgSerial";getSQLType(){return"serial"}}function F3(Z){return new z3(Z??"")}class E3 extends K4{static[E]="PgSmallIntBuilder";constructor(Z){super(Z,"number","PgSmallInt")}build(Z){return new L3(Z,this.config)}}class L3 extends j{static[E]="PgSmallInt";getSQLType(){return"smallint"}mapFromDriverValue=(Z)=>{if(typeof Z==="string")return Number(Z);return Z}}function D3(Z){return new E3(Z??"")}class O3 extends k{static[E]="PgSmallSerialBuilder";constructor(Z){super(Z,"number","PgSmallSerial");this.config.hasDefault=!0,this.config.notNull=!0}build(Z){return new V3(Z,this.config)}}class V3 extends j{static[E]="PgSmallSerial";getSQLType(){return"smallserial"}}function M3(Z){return new O3(Z??"")}class A3 extends k{static[E]="PgTextBuilder";constructor(Z,Y){super(Z,"string","PgText");this.config.enumValues=Y.enum}build(Z){return new R3(Z,this.config)}}class R3 extends j{static[E]="PgText";enumValues=this.config.enumValues;getSQLType(){return"text"}}function N3(Z,Y={}){let{name:X,config:G}=X0(Z,Y);return new A3(X,G)}class w3 extends z4{constructor(Z,Y,X){super(Z,"string","PgTime");this.withTimezone=Y,this.precision=X,this.config.withTimezone=Y,this.config.precision=X}static[E]="PgTimeBuilder";build(Z){return new n6(Z,this.config)}}class n6 extends j{static[E]="PgTime";withTimezone;precision;constructor(Z,Y){super(Z,Y);this.withTimezone=Y.withTimezone,this.precision=Y.precision}getSQLType(){return`time${this.precision===void 0?"":`(${this.precision})`}${this.withTimezone?" with time zone":""}`}}function I3(Z,Y={}){let{name:X,config:G}=X0(Z,Y);return new w3(X,G.withTimezone??!1,G.precision)}class B3 extends z4{static[E]="PgTimestampBuilder";constructor(Z,Y,X){super(Z,"date","PgTimestamp");this.config.withTimezone=Y,this.config.precision=X}build(Z){return new r6(Z,this.config)}}class r6 extends j{static[E]="PgTimestamp";withTimezone;precision;constructor(Z,Y){super(Z,Y);this.withTimezone=Y.withTimezone,this.precision=Y.precision}getSQLType(){return`timestamp${this.precision===void 0?"":` (${this.precision})`}${this.withTimezone?" with time zone":""}`}mapFromDriverValue=(Z)=>{return new Date(this.withTimezone?Z:Z+"+0000")};mapToDriverValue=(Z)=>{return Z.toISOString()}}class K3 extends z4{static[E]="PgTimestampStringBuilder";constructor(Z,Y,X){super(Z,"string","PgTimestampString");this.config.withTimezone=Y,this.config.precision=X}build(Z){return new s6(Z,this.config)}}class s6 extends j{static[E]="PgTimestampString";withTimezone;precision;constructor(Z,Y){super(Z,Y);this.withTimezone=Y.withTimezone,this.precision=Y.precision}getSQLType(){return`timestamp${this.precision===void 0?"":`(${this.precision})`}${this.withTimezone?" with time zone":""}`}}function C3(Z,Y={}){let{name:X,config:G}=X0(Z,Y);if(G?.mode==="string")return new K3(X,G.withTimezone??!1,G.precision);return new B3(X,G?.withTimezone??!1,G?.precision)}class T3 extends k{static[E]="PgUUIDBuilder";constructor(Z){super(Z,"string","PgUUID")}defaultRandom(){return this.default(L`gen_random_uuid()`)}build(Z){return new a6(Z,this.config)}}class a6 extends j{static[E]="PgUUID";getSQLType(){return"uuid"}}function P1(Z){return new T3(Z??"")}class q3 extends k{static[E]="PgVarcharBuilder";constructor(Z,Y){super(Z,"string","PgVarchar");this.config.length=Y.length,this.config.enumValues=Y.enum}build(Z){return new j3(Z,this.config)}}class j3 extends j{static[E]="PgVarchar";length=this.config.length;enumValues=this.config.enumValues;getSQLType(){return this.length===void 0?"varchar":`varchar(${this.length})`}}function t0(Z,Y={}){let{name:X,config:G}=X0(Z,Y);return new q3(X,G)}class P3 extends k{static[E]="PgBinaryVectorBuilder";constructor(Z,Y){super(Z,"string","PgBinaryVector");this.config.dimensions=Y.dimensions}build(Z){return new S3(Z,this.config)}}class S3 extends j{static[E]="PgBinaryVector";dimensions=this.config.dimensions;getSQLType(){return`bit(${this.dimensions})`}}function v3(Z,Y){let{name:X,config:G}=X0(Z,Y);return new P3(X,G)}class x3 extends k{static[E]="PgHalfVectorBuilder";constructor(Z,Y){super(Z,"array","PgHalfVector");this.config.dimensions=Y.dimensions}build(Z){return new f3(Z,this.config)}}class f3 extends j{static[E]="PgHalfVector";dimensions=this.config.dimensions;getSQLType(){return`halfvec(${this.dimensions})`}mapToDriverValue(Z){return JSON.stringify(Z)}mapFromDriverValue(Z){return Z.slice(1,-1).split(",").map((Y)=>Number.parseFloat(Y))}}function h3(Z,Y){let{name:X,config:G}=X0(Z,Y);return new x3(X,G)}class k3 extends k{static[E]="PgSparseVectorBuilder";constructor(Z,Y){super(Z,"string","PgSparseVector");this.config.dimensions=Y.dimensions}build(Z){return new b3(Z,this.config)}}class b3 extends j{static[E]="PgSparseVector";dimensions=this.config.dimensions;getSQLType(){return`sparsevec(${this.dimensions})`}}function y3(Z,Y){let{name:X,config:G}=X0(Z,Y);return new k3(X,G)}class g3 extends k{static[E]="PgVectorBuilder";constructor(Z,Y){super(Z,"array","PgVector");this.config.dimensions=Y.dimensions}build(Z){return new p3(Z,this.config)}}class p3 extends j{static[E]="PgVector";dimensions=this.config.dimensions;getSQLType(){return`vector(${this.dimensions})`}mapToDriverValue(Z){return JSON.stringify(Z)}mapFromDriverValue(Z){return Z.slice(1,-1).split(",").map((Y)=>Number.parseFloat(Y))}}function m3(Z,Y){let{name:X,config:G}=X0(Z,Y);return new g3(X,G)}function u3(){return{bigint:t_,bigserial:G$,boolean:w8,char:J$,cidr:U$,customType:L$,date:V$,doublePrecision:R$,inet:I$,integer:I8,interval:q$,json:P$,jsonb:v$,line:b$,macaddr:p$,macaddr8:d$,numeric:r$,point:Z3,geometry:W3,real:Q3,serial:F3,smallint:D3,smallserial:M3,text:N3,time:I3,timestamp:C3,uuid:P1,varchar:t0,bit:v3,halfvec:h3,sparsevec:y3,vector:m3}}var vY=Symbol.for("drizzle:PgInlineForeignKeys"),d3=Symbol.for("drizzle:EnableRLS");class u0 extends P{static[E]="PgTable";static Symbol=Object.assign({},P.Symbol,{InlineForeignKeys:vY,EnableRLS:d3});[vY]=[];[d3]=!1;[P.Symbol.ExtraConfigBuilder]=void 0;[P.Symbol.ExtraConfigColumns]={}}function xF(Z,Y,X,G,_=Z){let $=new u0(Z,G,_),W=typeof Y==="function"?Y(u3()):Y,H=Object.fromEntries(Object.entries(W).map(([z,U])=>{let D=U;D.setName(z);let V=D.build($);return $[vY].push(...D.buildForeignKeys(V,$)),[z,V]})),Q=Object.fromEntries(Object.entries(W).map(([z,U])=>{let D=U;D.setName(z);let V=D.buildExtraConfigColumn($);return[z,V]})),J=Object.assign($,H);if(J[P.Symbol.Columns]=H,J[P.Symbol.ExtraConfigColumns]=Q,X)J[u0.Symbol.ExtraConfigBuilder]=X;return Object.assign(J,{enableRLS:()=>{return J[u0.Symbol.EnableRLS]=!0,J}})}var C4=(Z,Y,X)=>{return xF(Z,Y,X,void 0)};function c3(...Z){if(Z[0].columns)return new B8(Z[0].columns,Z[0].name);return new B8(Z)}class B8{static[E]="PgPrimaryKeyBuilder";columns;name;constructor(Z,Y){this.columns=Z,this.name=Y}build(Z){return new l3(Z,this.columns,this.name)}}class l3{constructor(Z,Y,X){this.table=Z,this.columns=Y,this.name=X}static[E]="PgPrimaryKey";columns;name;getName(){return this.name??`${this.table[u0.Symbol.Name]}_${this.columns.map((Z)=>Z.name).join("_")}_pk`}}function D1(Z,Y){if(p_(Y)&&!KY(Z)&&!M(Z,w1)&&!M(Z,B4)&&!M(Z,F0)&&!M(Z,P)&&!M(Z,L1))return new w1(Z,Y);return Z}var t6=(Z,Y)=>{return L`${Z} = ${D1(Y,Z)}`},i3=(Z,Y)=>{return L`${Z} <> ${D1(Y,Z)}`};function K8(...Z){let Y=Z.filter((X)=>X!==void 0);if(Y.length===0)return;if(Y.length===1)return new f(Y);return new f([new m0("("),L.join(Y,new m0(" and ")),new m0(")")])}function o3(...Z){let Y=Z.filter((X)=>X!==void 0);if(Y.length===0)return;if(Y.length===1)return new f(Y);return new f([new m0("("),L.join(Y,new m0(" or ")),new m0(")")])}function n3(Z){return L`not ${Z}`}var r3=(Z,Y)=>{return L`${Z} > ${D1(Y,Z)}`},s3=(Z,Y)=>{return L`${Z} >= ${D1(Y,Z)}`},a3=(Z,Y)=>{return L`${Z} < ${D1(Y,Z)}`},t3=(Z,Y)=>{return L`${Z} <= ${D1(Y,Z)}`};function e3(Z,Y){if(Array.isArray(Y)){if(Y.length===0)return L`false`;return L`${Z} in ${Y.map((X)=>D1(X,Z))}`}return L`${Z} in ${D1(Y,Z)}`}function ZW(Z,Y){if(Array.isArray(Y)){if(Y.length===0)return L`true`;return L`${Z} not in ${Y.map((X)=>D1(X,Z))}`}return L`${Z} not in ${D1(Y,Z)}`}function YW(Z){return L`${Z} is null`}function XW(Z){return L`${Z} is not null`}function GW(Z){return L`exists ${Z}`}function _W(Z){return L`not exists ${Z}`}function $W(Z,Y,X){return L`${Z} between ${D1(Y,Z)} and ${D1(X,Z)}`}function WW(Z,Y,X){return L`${Z} not between ${D1(Y,Z)} and ${D1(X,Z)}`}function HW(Z,Y){return L`${Z} like ${Y}`}function JW(Z,Y){return L`${Z} not like ${Y}`}function QW(Z,Y){return L`${Z} ilike ${Y}`}function zW(Z,Y){return L`${Z} not ilike ${Y}`}function UW(Z){return L`${Z} asc`}function FW(Z){return L`${Z} desc`}class xY{constructor(Z,Y,X){this.sourceTable=Z,this.referencedTable=Y,this.relationName=X,this.referencedTableName=Y[P.Symbol.Name]}static[E]="Relation";referencedTableName;fieldName}class EW{constructor(Z,Y){this.table=Z,this.config=Y}static[E]="Relations"}class T4 extends xY{constructor(Z,Y,X,G){super(Z,Y,X?.relationName);this.config=X,this.isNullable=G}static[E]="One";withFieldName(Z){let Y=new T4(this.sourceTable,this.referencedTable,this.config,this.isNullable);return Y.fieldName=Z,Y}}class C8 extends xY{constructor(Z,Y,X){super(Z,Y,X?.relationName);this.config=X}static[E]="Many";withFieldName(Z){let Y=new C8(this.sourceTable,this.referencedTable,this.config);return Y.fieldName=Z,Y}}function LW(){return{and:K8,between:$W,eq:t6,exists:GW,gt:r3,gte:s3,ilike:QW,inArray:e3,isNull:YW,isNotNull:XW,like:HW,lt:a3,lte:t3,ne:i3,not:n3,notBetween:WW,notExists:_W,notLike:JW,notIlike:zW,notInArray:ZW,or:o3,sql:L}}function DW(){return{sql:L,asc:UW,desc:FW}}function OW(Z,Y){if(Object.keys(Z).length===1&&"default"in Z&&!M(Z.default,P))Z=Z.default;let X={},G={},_={};for(let[$,W]of Object.entries(Z))if(M(W,P)){let H=m4(W),Q=G[H];X[H]=$,_[$]={tsName:$,dbName:W[P.Symbol.Name],schema:W[P.Symbol.Schema],columns:W[P.Symbol.Columns],relations:Q?.relations??{},primaryKey:Q?.primaryKey??[]};for(let z of Object.values(W[P.Symbol.Columns]))if(z.primary)_[$].primaryKey.push(z);let J=W[P.Symbol.ExtraConfigBuilder]?.(W[P.Symbol.ExtraConfigColumns]);if(J){for(let z of Object.values(J))if(M(z,B8))_[$].primaryKey.push(...z.columns)}}else if(M(W,EW)){let H=m4(W.table),Q=X[H],J=W.config(Y(W.table)),z;for(let[U,D]of Object.entries(J))if(Q){let V=_[Q];if(V.relations[U]=D,z)V.primaryKey.push(...z)}else{if(!(H in G))G[H]={relations:{},primaryKey:z};G[H].relations[U]=D}}return{tables:_,tableNamesMap:X}}function fF(Z){return function Y(X,G){return new T4(Z,X,G,G?.fields.reduce((_,$)=>_&&$.notNull,!0)??!1)}}function hF(Z){return function Y(X,G){return new C8(Z,X,G)}}function VW(Z,Y,X){if(M(X,T4)&&X.config)return{fields:X.config.fields,references:X.config.references};let G=Y[m4(X.referencedTable)];if(!G)throw new Error(`Table "${X.referencedTable[P.Symbol.Name]}" not found in schema`);let _=Z[G];if(!_)throw new Error(`Table "${G}" not found in schema`);let $=X.sourceTable,W=Y[m4($)];if(!W)throw new Error(`Table "${$[P.Symbol.Name]}" not found in schema`);let H=[];for(let Q of Object.values(_.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 "${G}"`):new Error(`There are multiple relations between "${G}" and "${X.sourceTable[P.Symbol.Name]}". Please specify relation name`);if(H[0]&&M(H[0],T4)&&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 "${W}.${X.fieldName}"`)}function MW(Z){return{one:fF(Z),many:hF(Z)}}function e6(Z,Y,X,G,_=($)=>$){let $={};for(let[W,H]of G.entries())if(H.isJson){let Q=Y.relations[H.tsKey],J=X[W],z=typeof J==="string"?JSON.parse(J):J;$[H.tsKey]=M(Q,T4)?z&&e6(Z,Z[H.relationTableTsKey],z,H.selection,_):z.map((U)=>e6(Z,Z[H.relationTableTsKey],U,H.selection,_))}else{let Q=_(X[W]),J=H.field,z;if(M(J,F0))z=J;else if(M(J,f))z=J.decoder;else z=J.sql.decoder;$[H.tsKey]=Q===null?null:z.mapFromDriverValue(Q)}return $}import $E from"os";import WE from"fs";var ZZ=new Map,fY=new Map,hY=Symbol("OriginError"),I2={};class S1 extends Promise{constructor(Z,Y,X,G,_={}){let $,W;super((H,Q)=>{$=H,W=Q});this.tagged=Array.isArray(Z.raw),this.strings=Z,this.args=Y,this.handler=X,this.canceller=G,this.options=_,this.state=null,this.statement=null,this.resolve=(H)=>(this.active=!1,$(H)),this.reject=(H)=>(this.active=!1,W(H)),this.active=!1,this.cancelled=null,this.executed=!1,this.signature="",this[hY]=this.handler.debug?new Error:this.tagged&&kF(this.strings)}get origin(){return(this.handler.debug?this[hY].stack:this.tagged&&fY.has(this.strings)?fY.get(this.strings):fY.set(this.strings,this[hY].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(Z=1,Y){if(this.options.simple=!1,typeof Z==="function")Y=Z,Z=1;if(this.cursorRows=Z,typeof Y==="function")return this.cursorFn=Y,this;let X;return{[Symbol.asyncIterator]:()=>({next:()=>{if(this.executed&&!this.active)return{done:!0};X&&X();let G=new Promise((_,$)=>{this.cursorFn=(W)=>{return _({value:W,done:!1}),new Promise((H)=>X=H)},this.resolve=()=>(this.active=!1,_({done:!0})),this.reject=(W)=>(this.active=!1,$(W))});return this.execute(),G},return(){return X&&X(I2),{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(Z){return this.forEachFn=Z,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 kF(Z){if(ZZ.has(Z))return ZZ.get(Z);let Y=Error.stackTraceLimit;return Error.stackTraceLimit=4,ZZ.set(Z,new Error),Error.stackTraceLimit=Y,ZZ.get(Z)}class B2 extends Error{constructor(Z){super(Z.message);this.name=this.constructor.name,Object.assign(this,Z)}}var f0={connection:AW,postgres:RW,generic:NW,notSupported:wW};function AW(Z,Y,X){let{host:G,port:_}=X||Y,$=Object.assign(new Error("write "+Z+" "+(Y.path||G+":"+_)),{code:Z,errno:Z,address:Y.path||G},Y.path?{}:{port:_});return Error.captureStackTrace($,AW),$}function RW(Z){let Y=new B2(Z);return Error.captureStackTrace(Y,RW),Y}function NW(Z,Y){let X=Object.assign(new Error(Z+": "+Y),{code:Z});return Error.captureStackTrace(X,NW),X}function wW(Z){let Y=Object.assign(new Error(Z+" (B) is not supported"),{code:"MESSAGE_NOT_SUPPORTED",name:Z});return Error.captureStackTrace(Y,wW),Y}var bF={string:{to:25,from:null,serialize:(Z)=>""+Z},number:{to:0,from:[21,23,26,700,701],serialize:(Z)=>""+Z,parse:(Z)=>+Z},json:{to:114,from:[114,3802],serialize:(Z)=>JSON.stringify(Z),parse:(Z)=>JSON.parse(Z)},boolean:{to:16,from:16,serialize:(Z)=>Z===!0?"t":"f",parse:(Z)=>Z==="t"},date:{to:1184,from:[1082,1114,1184],serialize:(Z)=>(Z instanceof Date?Z:new Date(Z)).toISOString(),parse:(Z)=>new Date(Z)},bytea:{to:17,from:17,serialize:(Z)=>"\\x"+Buffer.from(Z).toString("hex"),parse:(Z)=>Buffer.from(Z.slice(2),"hex")}};class GZ{then(){kY()}catch(){kY()}finally(){kY()}}class P8 extends GZ{constructor(Z){super();this.value=WZ(Z)}}class r1 extends GZ{constructor(Z,Y,X){super();this.value=Z,this.type=Y,this.array=X}}class _Z extends GZ{constructor(Z,Y){super();this.first=Z,this.rest=Y}build(Z,Y,X,G){let _=yF.map(([$,W])=>({fn:W,i:Z.search($)})).sort(($,W)=>$.i-W.i).pop();return _.i===-1?mY(this.first,G):_.fn(this.first,this.rest,Y,X,G)}}function $Z(Z,Y,X,G){let _=Z instanceof r1?Z.value:Z;if(_===void 0){if(Z instanceof r1?Z.value=G.transform.undefined:_=Z=G.transform.undefined,_===void 0)throw f0.generic("UNDEFINED_VALUE","Undefined values are not allowed")}return"$"+X.push(Z instanceof r1?(Y.push(Z.value),Z.array?Z.array[Z.type||XZ(Z.value)]||Z.type||CW(Z.value):Z.type):(Y.push(Z),XZ(Z)))}var BW=qW(bF);function gY(Z,Y,X,G,_,$){for(let W=1;W<Z.strings.length;W++)Y+=pY(Y,X,G,_,$)+Z.strings[W],X=Z.args[W];return Y}function pY(Z,Y,X,G,_){return Y instanceof _Z?Y.build(Z,X,G,_):Y instanceof S1?yY(Y,X,G,_):Y instanceof P8?Y.value:Y&&Y[0]instanceof S1?Y.reduce(($,W)=>$+" "+yY(W,X,G,_),""):$Z(Y,X,G,_)}function yY(Z,Y,X,G){return Z.fragment=!0,gY(Z,Z.strings[0],Z.args[0],Y,X,G)}function KW(Z,Y,X,G,_){return Z.map(($)=>"("+G.map((W)=>pY("values",$[W],Y,X,_)).join(",")+")").join(",")}function IW(Z,Y,X,G,_){let $=Array.isArray(Z[0]),W=Y.length?Y.flat():Object.keys($?Z[0]:Z);return KW($?Z:[Z],X,G,W,_)}function YZ(Z,Y,X,G,_){if(typeof Z==="string"&&(Z=[Z].concat(Y)),Array.isArray(Z))return mY(Z,_);let $;return(Y.length?Y.flat():Object.keys(Z)).map((H)=>{return $=Z[H],($ instanceof S1?yY($,X,G,_):$ instanceof P8?$.value:$Z($,X,G,_))+" as "+WZ(_.transform.column.to?_.transform.column.to(H):H)}).join(",")}var yF=Object.entries({values:IW,in:(...Z)=>{let Y=IW(...Z);return Y==="()"?"(null)":Y},select:YZ,as:YZ,returning:YZ,"\\(":YZ,update(Z,Y,X,G,_){return(Y.length?Y.flat():Object.keys(Z)).map(($)=>WZ(_.transform.column.to?_.transform.column.to($):$)+"="+pY("values",Z[$],X,G,_))},insert(Z,Y,X,G,_){let $=Y.length?Y.flat():Object.keys(Array.isArray(Z)?Z[0]:Z);return"("+mY($,_)+")values"+KW(Array.isArray(Z)?Z:[Z],X,G,$,_)}}).map(([Z,Y])=>[new RegExp("((?:^|[\\s(])"+Z+"(?:$|[\\s(]))(?![\\s\\S]*\\1)","i"),Y]);function kY(){throw f0.generic("NOT_TAGGED_CALL","Query not called as a tagged template literal")}var{serializers:gF,parsers:pF}=BW;function CW(Z){if(Array.isArray(Z))return CW(Z[0]);return typeof Z==="string"?1009:0}var TW=function(Z){let Y=qW(Z||{});return{serializers:Object.assign({},gF,Y.serializers),parsers:Object.assign({},pF,Y.parsers)}};function qW(Z){return Object.keys(Z).reduce((Y,X)=>{if(Z[X].from&&[].concat(Z[X].from).forEach((G)=>Y.parsers[G]=Z[X].parse),Z[X].serialize)Y.serializers[Z[X].to]=Z[X].serialize,Z[X].from&&[].concat(Z[X].from).forEach((G)=>Y.serializers[G]=Z[X].serialize);return Y},{parsers:{},serializers:{}})}function mY(Z,{transform:{column:Y}}){return Z.map((X)=>WZ(Y.to?Y.to(X):X)).join(",")}var WZ=function Z(Y){return'"'+Y.replace(/"/g,'""').replace(/\./g,'"."')+'"'},XZ=function Z(Y){return Y instanceof r1?Y.type:Y instanceof Date?1184:Y instanceof Uint8Array?17:Y===!0||Y===!1?16:typeof Y==="bigint"?20:Array.isArray(Y)?Z(Y[0]):0},mF=/\\/g,uF=/"/g;function dF(Z){return Z.replace(mF,"\\\\").replace(uF,"\\\"")}var jW=function Z(Y,X,G,_){if(Array.isArray(Y)===!1)return Y;if(!Y.length)return"{}";let $=Y[0],W=_===1020?";":",";if(Array.isArray($)&&!$.type)return"{"+Y.map((H)=>Z(H,X,G,_)).join(W)+"}";return"{"+Y.map((H)=>{if(H===void 0){if(H=G.transform.undefined,H===void 0)throw f0.generic("UNDEFINED_VALUE","Undefined values are not allowed")}return H===null?"null":'"'+dF(X?X(H.type?H.value:H):""+H)+'"'}).join(W)+"}"},bY={i:0,char:null,str:"",quoted:!1,last:0},PW=function Z(Y,X,G){return bY.i=bY.last=0,SW(bY,Y,X,G)};function SW(Z,Y,X,G){let _=[],$=G===1020?";":",";for(;Z.i<Y.length;Z.i++){if(Z.char=Y[Z.i],Z.quoted)if(Z.char==="\\")Z.str+=Y[++Z.i];else if(Z.char==='"')_.push(X?X(Z.str):Z.str),Z.str="",Z.quoted=Y[Z.i+1]==='"',Z.last=Z.i+2;else Z.str+=Z.char;else if(Z.char==='"')Z.quoted=!0;else if(Z.char==="{")Z.last=++Z.i,_.push(SW(Z,Y,X,G));else if(Z.char==="}"){Z.quoted=!1,Z.last<Z.i&&_.push(X?X(Y.slice(Z.last,Z.i)):Y.slice(Z.last,Z.i)),Z.last=Z.i+1;break}else if(Z.char===$&&Z.p!=="}"&&Z.p!=='"')_.push(X?X(Y.slice(Z.last,Z.i)):Y.slice(Z.last,Z.i)),Z.last=Z.i+1;Z.p=Z.char}return Z.last<Z.i&&_.push(X?X(Y.slice(Z.last,Z.i+1)):Y.slice(Z.last,Z.i+1)),_}var u4=(Z)=>{let Y=Z[0];for(let X=1;X<Z.length;X++)Y+=Z[X]==="_"?Z[++X].toUpperCase():Z[X];return Y},d4=(Z)=>{let Y=Z[0].toUpperCase();for(let X=1;X<Z.length;X++)Y+=Z[X]==="_"?Z[++X].toUpperCase():Z[X];return Y},c4=(Z)=>Z.replace(/_/g,"-"),T8=(Z)=>Z.replace(/([A-Z])/g,"_$1").toLowerCase(),q8=(Z)=>(Z.slice(0,1)+Z.slice(1).replace(/([A-Z])/g,"_$1")).toLowerCase(),j8=(Z)=>Z.replace(/-/g,"_");function uY(Z){return function Y(X,G){return typeof X==="object"&&X!==null&&(G.type===114||G.type===3802)?Array.isArray(X)?X.map((_)=>Y(_,G)):Object.entries(X).reduce((_,[$,W])=>Object.assign(_,{[Z($)]:Y(W,G)}),{}):X}}u4.column={from:u4};u4.value={from:uY(u4)};T8.column={to:T8};var dY={...u4};dY.column.to=T8;d4.column={from:d4};d4.value={from:uY(d4)};q8.column={to:q8};var cY={...d4};cY.column.to=q8;c4.column={from:c4};c4.value={from:uY(c4)};j8.column={to:j8};var lY={...c4};lY.column.to=j8;import vW from"net";import oF from"tls";import S8 from"crypto";import iY from"stream";import{performance as xW}from"perf_hooks";class l4 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=cF;function cF(Z=[]){let Y=Z.slice(),X=0;return{get length(){return Y.length-X},remove:(G)=>{let _=Y.indexOf(G);return _===-1?null:(Y.splice(_,1),G)},push:(G)=>(Y.push(G),G),shift:()=>{let G=Y[X++];if(X===Y.length)X=0,Y=[];else Y[X-1]=void 0;return G}}}var e0=Buffer.allocUnsafe(256),lF="BCcDdEFfHPpQSX".split("").reduce((Z,Y)=>{let X=Y.charCodeAt(0);return Z[Y]=()=>{return e0[0]=X,z0.i=5,z0},Z},{}),z0=Object.assign(iF,lF,{N:String.fromCharCode(0),i:0,inc(Z){return z0.i+=Z,z0},str(Z){let Y=Buffer.byteLength(Z);return HZ(Y),z0.i+=e0.write(Z,z0.i,Y,"utf8"),z0},i16(Z){return HZ(2),e0.writeUInt16BE(Z,z0.i),z0.i+=2,z0},i32(Z,Y){if(Y||Y===0)return e0.writeUInt32BE(Z,Y),z0;return HZ(4),e0.writeUInt32BE(Z,z0.i),z0.i+=4,z0},z(Z){return HZ(Z),e0.fill(0,z0.i,z0.i+Z),z0.i+=Z,z0},raw(Z){return e0=Buffer.concat([e0.subarray(0,z0.i),Z]),z0.i=e0.length,z0},end(Z=1){e0.writeUInt32BE(z0.i-Z,Z);let Y=e0.subarray(0,z0.i);return z0.i=0,e0=Buffer.allocUnsafe(256),Y}}),d=z0;function HZ(Z){if(e0.length-z0.i<Z){let Y=e0,X=Y.length;e0=Buffer.allocUnsafe(X+(X>>1)+Z),Y.copy(e0)}}function iF(){return z0.i=0,z0}var rY=kW,nF=1,q4=d().S().end(),fW=d().H().end(),rF=d().i32(8).i32(80877103).end(8),sF=Buffer.concat([d().E().str(d.N).i32(0).end(),q4]),aF=d().D().str("S").str(d.N).end(),K2=()=>{},tF=new Set(["FetchPreparedStatement","RevalidateCachedQuery","transformAssignedExpr"]),eF={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 kW(Z,Y={},{onopen:X=K2,onend:G=K2,onclose:_=K2}={}){let{ssl:$,max:W,user:H,host:Q,port:J,database:z,parsers:U,transform:D,onnotice:V,onnotify:N,onparameter:R,max_pipeline:b,keep_alive:x,backoff:h,target_session_attrs:g}=Z,K=I1(),B=nF++,T={pid:null,secret:null},q=nY(NZ,Z.idle_timeout),c=nY(NZ,Z.max_lifetime),n=nY($H,Z.connect_timeout),w=null,s,p=new l4,a=Buffer.alloc(0),I0=Z.fetch_types,h0={},W1={},s1=Math.random().toString(36).slice(2),C=1,m=0,$0=0,L0=0,k0=0,t=0,J0=0,v0=0,K0=null,A0=null,i0=!1,D0=null,v1=null,c0=null,U4=null,b0=null,R0=null,x1=null,u1=null,v=null,j2=null,o0={queue:Y.closed,idleTimer:q,connect(F){c0=F,wX()},terminate:S2,execute:P2,cancel:YH,end:NZ,count:0,id:B};return Y.closed&&Y.closed.push(o0),o0;async function ZH(){let F;try{F=Z.socket?await Promise.resolve(Z.socket(Z)):new vW.Socket}catch(O){r4(O);return}return F.on("error",r4),F.on("close",IX),F.on("drain",RX),F}async function YH({pid:F,secret:O},l,W0){try{s=d().i32(16).i32(80877102).i32(F).i32(O).end(16),await NX(),w.once("error",W0),w.once("close",l)}catch(T0){W0(T0)}}function P2(F){if(i0)return g8(F,f0.connection("CONNECTION_DESTROYED",Z));if(F.cancelled)return;try{return F.state=T,v?K.push(F):(v=F,v.active=!0),_H(F),l0(XH(F))&&!F.describeFirst&&!F.cursorFn&&K.length<b&&(!F.options.onexecute||F.options.onexecute(o0))}catch(O){return K.length===0&&l0(q4),d1(O),!0}}function XH(F){if(F.parameters.length>=65534)throw f0.generic("MAX_PARAMETERS_EXCEEDED","Max number of parameters (65534) exceeded");return F.options.simple?d().Q().str(F.statement.string+d.N).end():F.describeFirst?Buffer.concat([VX(F),fW]):F.prepare?F.prepared?y8(F):Buffer.concat([VX(F),y8(F)]):GH(F)}function VX(F){return Buffer.concat([KX(F.statement.string,F.parameters,F.statement.types,F.statement.name),dH("S",F.statement.name)])}function y8(F){return Buffer.concat([uH(F.parameters,F.statement.types,F.statement.name,F.cursorName),F.cursorFn?CX("",F.cursorRows):sF])}function GH(F){return Buffer.concat([KX(F.statement.string,F.parameters,F.statement.types),aF,y8(F)])}function _H(F){let O=[],l=[],W0=gY(F,F.strings[0],F.args[0],O,l,Z);!F.tagged&&F.args.forEach((T0)=>$Z(T0,O,l,Z)),F.prepare=Z.prepare&&("prepare"in F.options?F.options.prepare:!0),F.string=W0,F.signature=F.prepare&&l+W0,F.onlyDescribe&&delete W1[F.signature],F.parameters=F.parameters||O,F.prepared=F.prepare&&F.signature in W1,F.describeFirst=F.onlyDescribe||O.length&&!F.prepared,F.statement=F.prepared?W1[F.signature]:{string:W0,types:l,name:F.prepare?s1+C++:""},typeof Z.debug==="function"&&Z.debug(B,W0,O,l)}function l0(F,O){if(R0=R0?Buffer.concat([R0,F]):Buffer.from(F),O||R0.length>=1024)return MX(O);return A0===null&&(A0=setImmediate(MX)),!0}function MX(F){let O=w.write(R0,F);return A0!==null&&clearImmediate(A0),R0=A0=null,O}function $H(){d1(f0.connection("CONNECT_TIMEOUT",Z,w)),w.destroy()}async function AX(){if(l0(rF),!await new Promise((O)=>w.once("data",(l)=>O(l[0]===83)))&&$==="prefer")return n4();w.removeAllListeners(),w=oF.connect({socket:w,servername:vW.isIP(w.host)?void 0:w.host,...$==="require"||$==="allow"||$==="prefer"?{rejectUnauthorized:!1}:$==="verify-full"?{}:typeof $==="object"?$:{}}),w.on("secureConnect",n4),w.on("error",r4),w.on("close",IX),w.on("drain",RX)}function RX(){!v&&X(o0)}function RZ(F){if(D0){if(D0.push(F),$0-=F.length,$0>0)return}a=D0?Buffer.concat(D0,t-$0):a.length===0?F:Buffer.concat([a,F],a.length+F.length);while(a.length>4){if(t=a.readUInt32BE(1),t>=a.length){$0=t-a.length,D0=[a];break}try{WH(a.subarray(0,t+1))}catch(O){v&&(v.cursorFn||v.describeFirst)&&l0(q4),d1(O)}a=a.subarray(t+1),$0=0,D0=null}}async function NX(){if(i0=!1,h0={},w||(w=await ZH()),!w)return;if(n.start(),Z.socket)return $?AX():n4();if(w.on("connect",$?AX:n4),Z.path)return w.connect(Z.path);w.ssl=$,w.connect(J[L0],Q[L0]),w.host=Q[L0],w.port=J[L0],L0=(L0+1)%J.length}function wX(){setTimeout(NX,m?m+J0-xW.now():0)}function n4(){try{W1={},I0=Z.fetch_types,s1=Math.random().toString(36).slice(2),C=1,c.start(),w.on("data",RZ),x&&w.setKeepAlive&&w.setKeepAlive(!0,1000*x);let F=lH();l0(F)}catch(F){r4(F)}}function r4(F){if(o0.queue===Y.connecting&&Z.host[k0+1])return;d1(F);while(K.length)g8(K.shift(),F)}function d1(F){b0&&(b0.destroy(F),b0=null),v&&g8(v,F),c0&&(g8(c0,F),c0=null)}function g8(F,O){if(F.reserve)return F.reject(O);if(!O||typeof O!=="object")O=new Error(O);"query"in O||"parameters"in O||Object.defineProperties(O,{stack:{value:O.stack+F.origin.replace(/.*\n/,`
67
- `),enumerable:Z.debug},query:{value:F.string,enumerable:Z.debug},parameters:{value:F.parameters,enumerable:Z.debug},args:{value:F.args,enumerable:Z.debug},types:{value:F.statement&&F.statement.types,enumerable:Z.debug}}),F.reject(O)}function NZ(){return U4||(!o0.reserved&&G(o0),!o0.reserved&&!c0&&!v&&K.length===0?(S2(),new Promise((F)=>w&&w.readyState!=="closed"?w.once("close",F):F())):U4=new Promise((F)=>x1=F))}function S2(){if(i0=!0,b0||v||c0||K.length)r4(f0.connection("CONNECTION_DESTROYED",Z));if(clearImmediate(A0),w)w.removeListener("data",RZ),w.removeListener("connect",n4),w.readyState==="open"&&w.end(d().X().end());x1&&(x1(),U4=x1=null)}async function IX(F){if(a=Buffer.alloc(0),$0=0,D0=null,clearImmediate(A0),w.removeListener("data",RZ),w.removeListener("connect",n4),q.cancel(),c.cancel(),n.cancel(),w.removeAllListeners(),w=null,c0)return wX();!F&&(v||K.length)&&r4(f0.connection("CONNECTION_CLOSED",Z,w)),m=xW.now(),F&&Z.shared.retries++,J0=(typeof h==="function"?h(Z.shared.retries):h)*1000,_(o0,f0.connection("CONNECTION_CLOSED",Z,w))}function WH(F,O=F[0]){(O===68?HH:O===100?fH:O===65?qH:O===83?JH:O===90?QH:O===67?zH:O===50?BX:O===49?UH:O===116?FH:O===84?EH:O===82?LH:O===110?RH:O===75?NH:O===69?CH:O===115?jH:O===51?PH:O===71?SH:O===78?kH:O===72?vH:O===99?hH:O===73?bH:O===86?yH:O===118?gH:O===87?xH:pH)(F)}function HH(F){let O=7,l,W0,T0,n0=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(O),O+=4,T0=l===-1?null:v.isRaw===!0?F.subarray(O,O+=l):W0.parser===void 0?F.toString("utf8",O,O+=l):W0.parser.array===!0?W0.parser(F.toString("utf8",O+1,O+=l)):W0.parser(F.toString("utf8",O,O+=l)),v.isRaw?n0[Z1]=v.isRaw===!0?T0:D.value.from?D.value.from(T0,W0):T0:n0[W0.name]=D.value.from?D.value.from(T0,W0):T0;v.forEachFn?v.forEachFn(D.row.from?D.row.from(n0):n0,p):p[v0++]=D.row.from?D.row.from(n0):n0}function JH(F){let[O,l]=F.toString("utf8",5,F.length-1).split(d.N);if(h0[O]=l,Z.parameters[O]!==l)Z.parameters[O]=l,R&&R(O,l)}function QH(F){if(v&&v.options.simple&&v.resolve(v1||p),v=v1=null,p=new l4,n.cancel(),c0){if(g){if(!h0.in_hot_standby||!h0.default_transaction_read_only)return KH();else if(BH(g,h0))return S2()}if(I0)return c0.reserve&&(c0=null),wH();c0&&!c0.reserve&&P2(c0),Z.shared.retries=k0=0,c0=null;return}while(K.length&&(v=K.shift())&&(v.active=!0,v.cancelled))kW(Z).cancel(v.state,v.cancelled.resolve,v.cancelled.reject);if(v)return;o0.reserved?!o0.reserved.release&&F[5]===73?U4?S2():(o0.reserved=null,X(o0)):o0.reserved():U4?S2():X(o0)}function zH(F){v0=0;for(let O=F.length-1;O>0;O--){if(F[O]===32&&F[O+1]<58&&p.count===null)p.count=+F.toString("utf8",O+1,F.length-1);if(F[O-1]>=65){p.command=F.toString("utf8",5,O),p.state=T;break}}if(j2&&(j2(),j2=null),p.command==="BEGIN"&&W!==1&&!o0.reserved)return d1(f0.generic("UNSAFE_TRANSACTION","Only use sql.begin, sql.reserved or max: 1"));if(v.options.simple)return BX();if(v.cursorFn)p.count&&v.cursorFn(p),l0(q4);v.resolve(p)}function UH(){v.parsing=!1}function BX(){!p.statement&&(p.statement=v.statement),p.columns=v.statement.columns}function FH(F){let O=F.readUInt16BE(5);for(let l=0;l<O;++l)!v.statement.types[l]&&(v.statement.types[l]=F.readUInt32BE(7+l*4));v.prepare&&(W1[v.signature]=v.statement),v.describeFirst&&!v.onlyDescribe&&(l0(y8(v)),v.describeFirst=!1)}function EH(F){if(p.command)v1=v1||[p],v1.push(p=new l4),p.count=null,v.statement.columns=null;let O=F.readUInt16BE(5),l=7,W0;v.statement.columns=Array(O);for(let T0=0;T0<O;++T0){W0=l;while(F[l++]!==0);let n0=F.readUInt32BE(l),Z1=F.readUInt16BE(l+4),F4=F.readUInt32BE(l+6);v.statement.columns[T0]={name:D.column.from?D.column.from(F.toString("utf8",W0,l-1)):F.toString("utf8",W0,l-1),parser:U[F4],table:n0,number:Z1,type:F4},l+=18}if(p.statement=v.statement,v.onlyDescribe)return v.resolve(v.statement),l0(q4)}async function LH(F,O=F.readUInt32BE(5)){(O===3?DH:O===5?OH:O===10?VH:O===11?MH:O===12?AH:O!==0?mH:K2)(F,O)}async function DH(){let F=await wZ();l0(d().p().str(F).z(1).end())}async function OH(F){let O="md5"+await hW(Buffer.concat([Buffer.from(await hW(await wZ()+H)),F.subarray(9)]));l0(d().p().str(O).z(1).end())}async function VH(){u1=(await S8.randomBytes(18)).toString("base64"),d().p().str("SCRAM-SHA-256"+d.N);let F=d.i;l0(d.inc(4).str("n,,n=*,r="+u1).i32(d.i-F-4,F).end())}async function MH(F){let O=F.toString("utf8",9).split(",").reduce((Z1,F4)=>(Z1[F4[0]]=F4.slice(2),Z1),{}),l=await S8.pbkdf2Sync(await wZ(),Buffer.from(O.s,"base64"),parseInt(O.i),32,"sha256"),W0=await JZ(l,"Client Key"),T0="n=*,r="+u1+",r="+O.r+",s="+O.s+",i="+O.i+",c=biws,r="+O.r;K0=(await JZ(await JZ(l,"Server Key"),T0)).toString("base64");let n0="c=biws,r="+O.r+",p="+YE(W0,Buffer.from(await JZ(await ZE(W0),T0))).toString("base64");l0(d().p().str(n0).end())}function AH(F){if(F.toString("utf8",9).split(d.N,1)[0].slice(2)===K0)return;d1(f0.generic("SASL_SIGNATURE_MISMATCH","The server did not return the correct signature")),w.destroy()}function wZ(){return Promise.resolve(typeof Z.pass==="function"?Z.pass():Z.pass)}function RH(){if(p.statement=v.statement,p.statement.columns=[],v.onlyDescribe)return v.resolve(v.statement),l0(q4)}function NH(F){T.pid=F.readUInt32BE(5),T.secret=F.readUInt32BE(9)}async function wH(){I0=!1,(await new S1([`
58
+ ${F.trace}`:`No previous disposal trace for ${H} was found.`),X}let J=Y.moleculeGraph.getRelationEntries({downstreamMoleculeKey:W.stringKey}).filter(([,{source:F}])=>F!==G).map(([F])=>X1(F));if(_)$.moleculeGraph.delete(G);$.moleculeGraph.set({upstreamMoleculeKey:Q.stringKey,downstreamMoleculeKey:W.stringKey},{source:Q.stringKey});let z={type:"molecule_transfer",key:W.key,exclusive:Boolean(_),from:J,to:[Q.key],timestamp:Date.now()};if(E1($)&&$.transactionMeta.phase==="building")$.transactionMeta.update.subEvents.push(z);return X}function uU(Y,Z,X){switch(X){case"newValue":m9(Y,Z);break;case"oldValue":$8(Y,Z.token);break}}function dU(Y,Z,X){switch(X){case"newValue":$8(Y,Z.token);break;case"oldValue":if(m9(Y,Z),Z.subType==="atom")Y.valueMap.set(Z.token.key,Z.value);break}}function m9(Y,Z){let{token:X}=Z;if(Z.subType==="writable"&&Z.value)k1(Y,X,Z.value);else h1(Y,X)}function cU(Y,Z,X){switch(X){case"newValue":A6(Y,Z.provenance,Z.key);break;case"oldValue":K6(Y,Z.key);break}}function lU(Y,Z,X){switch(X){case"newValue":K6(Y,Z.key);break;case"oldValue":{let _=Z.provenance.map(X1);A6(Y,_,Z.key);for(let[G,$]of Z.values){let W=Y.families.get(G);if(W){h1(Y,W,Z.key);let H=`${G}(${$0(Z.key)})`;Y.valueMap.set(H,$)}}}break}}function oU(Y,Z,X){switch(X){case"newValue":for(let _ of Z.to)_8(Y,_,Z.key,Z.exclusive?"exclusive":void 0);break;case"oldValue":{let _="exclusive";for(let G of Z.from)_8(Y,G,Z.key,_),_=void 0}break}}function u9(Y,Z,X){let _=X==="newValue"?Z.subEvents:[...Z.subEvents].reverse();for(let G of _)switch(G.type){case"atom_update":pU(Y,G,X);break;case"state_creation":uU(Y,G,X);break;case"state_disposal":dU(Y,G,X);break;case"molecule_creation":cU(Y,G,X);break;case"molecule_disposal":lU(Y,G,X);break;case"molecule_transfer":oU(Y,G,X);break;case"transaction_outcome":u9(Y,G,X);break}}function D2(Y){return"epoch"in Y.transactionMeta}function E1(Y){return"phase"in Y.transactionMeta}function d9(Y,Z){return Y.transactionMeta.actionContinuities.getRelatedKey(Z)}function iU(Y,Z){return Y.transactionMeta.epoch.get(Z)}function nU(Y,Z){let X=d9(Y,Z);if(X===void 0)return;return iU(Y,X)}function rU(Y,Z,X){let _=d9(Y,Z);if(_!==void 0)Y.transactionMeta.epoch.set(_,X)}function sU(Y,Z){let X=Y0(Y),{parent:_}=X;X.transactionMeta.phase="applying",X.transactionMeta.update.output=Z,_.child=null,_.on.transactionApplying.next(X.transactionMeta);let{subEvents:G}=X.transactionMeta.update;if(Y.logger.info("\uD83D\uDEC4","transaction",X.transactionMeta.update.token.key,`applying ${G.length} subEvents:`,G),u9(_,X.transactionMeta.update,"newValue"),D2(_))rU(_,X.transactionMeta.update.token.key,X.transactionMeta.update.epoch),P0(Y,{key:X.transactionMeta.update.token.key,type:"transaction"})?.subject.next(X.transactionMeta.update),Y.logger.info("\uD83D\uDEEC","transaction",X.transactionMeta.update.token.key,"applied");else if(E1(_))_.transactionMeta.update.subEvents.push(X.transactionMeta.update);_.on.transactionApplying.next(null)}function tU(Y){return{store:Y}}var aU=(Y,Z,X,_)=>{let G=Y0(Y),$={parent:G,child:null,on:G.on,loggers:G.loggers,logger:G.logger,config:G.config,atoms:new b1(G.atoms),atomsThatAreDefault:new Set(G.atomsThatAreDefault),families:new b1(G.families),joins:new b1(G.joins),operation:{open:!1},readonlySelectors:new b1(G.readonlySelectors),timelines:new b1(G.timelines),timelineTopics:G.timelineTopics.overlay(),trackers:new Map,transactions:new b1(G.transactions),selectorAtoms:G.selectorAtoms.overlay(),selectorGraph:G.selectorGraph.overlay(),writableSelectors:new b1(G.writableSelectors),valueMap:new b1(G.valueMap),defaults:G.defaults,disposalTraces:Y.disposalTraces.copy(),molecules:new b1(G.molecules),moleculeGraph:G.moleculeGraph.overlay(),moleculeData:G.moleculeData.overlay(),moleculeJoins:G.moleculeJoins.overlay(),miscResources:new b1(G.miscResources)},W=nU(Y,Z.key),H={phase:"building",update:{type:"transaction_outcome",token:Z,id:_,epoch:W===void 0?NaN:W+1,timestamp:Date.now(),subEvents:[],params:X,output:void 0},toolkit:{get:(...J)=>h1(Q,...J),set:(...J)=>{k1(Q,...J)},reset:(...J)=>{R6(Q,...J)},run:(J,z=kZ())=>M6(Q,J,z),find:(...J)=>j0(Y,...J),json:(J)=>k4(Q,J),dispose:(...J)=>{$8(Q,...J)},env:()=>tU(Q)}},Q=Object.assign($,{transactionMeta:H});return G.child=Q,Y.logger.info("\uD83D\uDEEB","transaction",Z.key,"building with params:",X),Q};function G8(Y,Z){let{key:X}=Z,_=Y.transactions.has(X),G={key:X,type:"transaction",run:(W,H)=>{let Q=y1(G),J=aU(Y,Q,W,H);try{let{toolkit:z}=J.transactionMeta,F=Z.do(z,...W);return sU(J,F),F}catch(z){throw gU(J),Y.logger.warn("\uD83D\uDCA5","transaction",X,"caught:",z),z}},install:(W)=>G8(W,Z),subject:new G0};Y0(Y).transactions.set(X,G);let $=y1(G);if(!_)Y.on.transactionCreation.next($);return $}var S9=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 $4({between:["selectorKey","atomKey"],cardinality:"n:n"});selectorGraph=new $4({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 $4({between:["continuity","action"],cardinality:"1:n"})};timelines=new Map;timelineTopics=new $4({between:["timelineKey","topicKey"],cardinality:"1:n"});disposalTraces=new bU(100);molecules=new Map;moleculeJoins=new $4({between:["moleculeKey","joinKey"],cardinality:"n:n"},{makeContentKey:(...Y)=>Y.sort().join(":")});moleculeGraph=new $4({between:["upstreamMoleculeKey","downstreamMoleculeKey"],cardinality:"n:n"},{makeContentKey:(...Y)=>Y.sort().join(":")});moleculeData=new $4({between:["moleculeKey","stateFamilyKey"],cardinality:"n:n"},{makeContentKey:(...Y)=>Y.sort().join(":")});miscResources=new Map;on={atomCreation:new G0,atomDisposal:new G0,selectorCreation:new G0,selectorDisposal:new G0,timelineCreation:new G0,transactionCreation:new G0,transactionApplying:new kU(null),operationClose:new G0,moleculeCreation:new G0,moleculeDisposal:new G0};operation={open:!1};config={name:"IMPLICIT_STORE",lifespan:"ephemeral"};loggers=[new T9("warn",(Y,Z,X)=>!L2(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},D2(Z))this.transactionMeta={epoch:new Map(Z?.transactionMeta.epoch),actionContinuities:new $4(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,_),$=Y5(_);X.add(G.key),X.add($.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)}}},F1={get STORE(){return globalThis.ATOM_IO_IMPLICIT_STORE??=new S9({name:"IMPLICIT_STORE",lifespan:"ephemeral"}),globalThis.ATOM_IO_IMPLICIT_STORE}};var eU=class extends Error{constructor(Y,Z){super(`${G4[Y.type]} ${$0(Y.key)} not found in store "${Z.config.name}".`)}};function P0(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 eU(Z,Y)}function c9(Y,Z,X,_){let G=Y.disposalTraces.buffer.find(($)=>$?.key===$0(_));switch(Y.logger.error("\u274C",Z.type,Z.key,"gets a fallback value because key",_,"is not allocated",G?`This key was previously disposed:
59
+ ${G.trace}`:"(no previous disposal trace found)"),X.type){case"mutable_atom_family":{if(Y.defaults.has(X.key))return Y.defaults.get(X.key);let $=new X.class;return Y.defaults.set(X.key,$),$.READONLY_VIEW}case"atom_family":{if(Y.defaults.has(X.key))return Y.defaults.get(X.key);let $=X.default,W=$(_);return Y.defaults.set(X.key,W),W}case"readonly_pure_selector_family":case"writable_pure_selector_family":case"readonly_held_selector_family":case"writable_held_selector_family":{if(Y.defaults.has(X.key))return Y.defaults.get(X.key);let $=X.default(_);return Y.defaults.set(X.key,$),$}}}function N6(Y,Z){let{type:X,key:_,catch:G}=Z;switch(X){case"readonly_pure_selector":case"writable_pure_selector":{let $;Y.logger.info("\uD83E\uDDEE",X,_,"computing value");try{if($=Z.getFrom(Y),$ instanceof Promise)return $.catch((W)=>{if(Y.logger.error("\uD83D\uDCA5",X,_,"rejected:",W),G){for(let H of G)if(W instanceof H)return W}throw W})}catch(W){if(Y.logger.error("\uD83D\uDCA5",X,_,"rejected:",W),G){for(let H of G)if(W instanceof H)return B1(Y,Z,W)}throw W}return B1(Y,Z,$)}case"atom":{let $;if(H8(Z.default))try{if($=Z.default(),$ instanceof Promise)$=$.catch((W)=>{if(Y.logger.error("\uD83D\uDCA5",X,_,"rejected:",W),G){for(let H of G)if(W instanceof H)return W}throw W})}catch(W){if(Y.logger.error("\uD83D\uDCA5",X,_,"rejected:",W),G){for(let H of G)if(W instanceof H)return $=B1(Y,Z,W),Y.logger.info("\u2728",Z.type,_,"computed default",$),$}throw W}else $=Z.default,Y.logger.info("\u2728",Z.type,_,"using static default",$);return B1(Y,Z,$)}}}function h4(Y,Z,X){if(Y.valueMap.has(Z.key))return FF(Y,Z,X);Y.logger.info("\u2754",Z.type,Z.key,"value not found in cache");let{key:_}=Z;switch(Z.type){case"readonly_held_selector":case"writable_held_selector":return Y.logger.info("\uD83E\uDDEE",Z.type,_,"computing value"),Z.getFrom(Y);case"writable_pure_selector":case"readonly_pure_selector":case"atom":return N6(Y,Z);case"mutable_atom":{let G=new Z.class;return Y.logger.info("\u2728",Z.type,_,"created new instance",G),B1(Y,Z,G)}}}function oZ(Y,Z){return P0(Y,{key:Z.family.key,type:`${Z.type}_family`})}var k9={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"},J8=Symbol("MUST_CREATE"),YF=Symbol("DO_NOT_CREATE");function Q8(Y,Z,X,_){let G=$0(_),$=Z.molecules.get(G);if(!$&&Z.config.lifespan==="immortal"){let{type:H,key:Q}=X;Z.logger.warn("\uD83D\uDCA3","key",G,"was used to mint a counterfeit token for",H,`"${Q}"`);let J=`${Q}(${G})`,z=k9[H];return{counterfeit:!0,key:J,type:z,family:{key:Q,subKey:G}}}let W;if(Y===J8){if(Z.logger.info("\uD83D\uDC6A",X.type,X.key,"adds member",typeof _==="string"?`\`${_}\``:_),W=X.create(_),$)Z.moleculeData.set(G,X.key)}else{let{type:H,key:Q}=X,J=`${Q}(${G})`,z=k9[H];return{key:J,type:z,family:{key:Q,subKey:G}}}return W}function iZ(Y,...Z){let X,_,G,$,W;if(Z.length===1){if(W=Z[0],"family"in W){let Q=oZ(Y,W);if(G=P0(Y,Q),$=X1(W.family.subKey),X=z8(Y,Q,$),"counterfeit"in W)return{token:W,family:G,subKey:$,isNew:!1};if(!X)_=Q8(J8,Y,Q,$),W=_;else W=X}}else if(G=P0(Y,Z[0]),$=Z[1],X=z8(Y,G,$),!X)_=Q8(J8,Y,G,$),W=_;else W=X;let H="counterfeit"in W;if(Boolean(_)&&H===!1&&G){let Q;switch(W.type){case"readonly_pure_selector":case"readonly_held_selector":Q="readable";break;case"atom":case"mutable_atom":case"writable_pure_selector":case"writable_held_selector":Q="writable";break}let J={type:"state_creation",subType:Q,token:W,timestamp:Date.now()};G.subject.next(J);let z=Y0(Y);if(W.family){if(D2(z))switch(W.type){case"atom":case"mutable_atom":Y.on.atomCreation.next(W);break;case"writable_pure_selector":case"readonly_pure_selector":case"writable_held_selector":case"readonly_held_selector":Y.on.selectorCreation.next(W);break}else if(E1(z)&&z.on.transactionApplying.state===null)z.transactionMeta.update.subEvents.push(J)}}return{token:W,family:G,subKey:$,isNew:Boolean(_)}}function h1(Y,...Z){let{token:X,family:_,subKey:G}=iZ(Y,...Z);if("counterfeit"in X&&_&&G)return c9(Y,X,_,G);let $=P0(Y,X);return h4(Y,$)}function z8(Y,Z,X){let _=$0(X),G=`${Z.key}(${_})`,$=Y0(Y),W;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(W)return y1(W);return W}function j0(Y,Z,X){let _=P0(Y,Z),G=z8(Y,Z,X);if(G)return G;return Q8(YF,Y,_,X)}function f4(Y,Z,X){let _=Z.key,G="readonly_pure_selector_family",$={key:_,type:"readonly_pure_selector_family"},W=Y.families.get(_);if(W)Y.logger.error("\u2757","readonly_pure_selector_family",_,`Overwriting an existing ${G4[W.type]} "${W.key}" in store "${Y.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);let H=new G0,J={...$,create:(z)=>{let F=$0(z),O={key:_,subKey:F},L=`${_}(${F})`,w=Y0(Y),R={key:L,get:Z.get(z)};if(Z.catch)R.catch=Z.catch;return sZ(w,R,O)},internalRoles:X,subject:H,install:(z)=>f4(z,Z),default:(z)=>{return Z.get(z)({get:(...F)=>h1(Y,...F),find:(...F)=>j0(Y,...F),json:(F)=>k4(Y,F)})}};return Y.families.set(_,J),$}function O2(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 ${G4[G.type]} "${G.key}" in store "${Y.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);let $=new G0,H={..._,create:(Q)=>{let J=$0(Q),z={key:Z.key,subKey:J},F=`${Z.key}(${J})`,O=Y0(Y),L=Z.default,w={key:F,default:H8(L)?()=>L(Q):L};if(Z.effects)w.effects=Z.effects(Q);if(Z.catch)w.catch=Z.catch;return x4(O,w,z)},default:Z.default,subject:$,install:(Q)=>O2(Q,Z),internalRoles:X};if(Y.families.set(Z.key,H),H8(Z.default)===!1)Y.defaults.set(Z.key,Z.default);return _}function l9(Y,Z,X){let _=Z.key,G="readonly_held_selector_family",$={key:_,type:"readonly_held_selector_family"},W=Y.families.get(_);if(W)Y.logger.error("\u2757","readonly_held_selector_family",_,`Overwriting an existing ${G4[W.type]} "${W.key}" in store "${Y.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);let H=new G0,J={...$,create:(z)=>{let F=$0(z),O={key:_,subKey:F},L=`${_}(${F})`,w=Y0(Y);return rZ(w,{key:L,const:Z.const(z),get:Z.get(z)},O)},internalRoles:X,subject:H,install:(z)=>l9(z,Z),default:Z.const};return Y.families.set(_,J),$}function o9(Y,Z,X){let _=Z.key,G="writable_held_selector_family",$={key:_,type:"writable_held_selector_family"},W=Y.families.get(_);if(W)Y.logger.error("\u2757","writable_held_selector_family",_,`Overwriting an existing ${G4[W.type]} "${W.key}" in store "${Y.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);let H=new G0,J={...$,create:(z)=>{let F=$0(z),O={key:_,subKey:F},L=`${_}(${F})`,w=Y0(Y);return tZ(w,{key:L,const:Z.const(z),get:Z.get(z),set:Z.set(z)},O)},internalRoles:X,subject:H,install:(z)=>o9(z,Z),default:Z.const};return Y.families.set(_,J),$}function nZ(Y,Z,X){let _=Z.key,G="writable_pure_selector_family",$={key:_,type:"writable_pure_selector_family"},W=Y.families.get(_);if(W)Y.logger.error("\u2757","writable_pure_selector_family",_,`Overwriting an existing ${G4[W.type]} "${W.key}" in store "${Y.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);let H=new G0,J={...$,create:(z)=>{let F=$0(z),O={key:_,subKey:F},L=`${_}(${F})`,w=Y0(Y),R={key:L,get:Z.get(z),set:Z.set(z)};if(Z.catch)R.catch=Z.catch;return aZ(w,R,O)},internalRoles:X,subject:H,install:(z)=>nZ(z,Z),default:(z)=>{return Z.get(z)({get:(...F)=>h1(Y,...F),find:(...F)=>j0(Y,...F),json:(F)=>k4(Y,F)})}};return Y.families.set(_,J),$}function bZ(Y,Z){let X="set"in Z,_="const"in Z;if(_&&X)return o9(Y,Z,void 0);if(_)return l9(Y,Z,void 0);if(X)return nZ(Y,Z);return f4(Y,Z)}function $8(Y,...Z){let X;if(Z.length===1)X=Z[0];else{let _=Z[0],G=Z[1];X=j0(Y,_,G)}try{P0(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":Y7(Y,X);break;case"writable_pure_selector":case"readonly_pure_selector":case"writable_held_selector":case"readonly_held_selector":JF(Y,X);break}}function i9(Y,Z){if(Y.operation.open){let X=performance.now();return Y.logger.info("\uD83D\uDEAB",Z.type,Z.key,`deferring setState at T-${X} until setState for "${Y.operation.token.key}" is done`),X}return Y.operation={open:!0,done:new Set,prev:new Map,timestamp:Date.now(),token:Z,subEvents:[]},Y.logger.info("\u2B55",Z.type,Z.key,`operation start in store "${Y.config.name}"${E1(Y)?` ${Y.transactionMeta.phase} "${Y.transactionMeta.update.token.key}"`:""}`),Y}function n9(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)}var r9=(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)},B6=(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 dZ(Y,Z,{oldValue:X,newValue:_},G,$){let W=y1(Z);if(G&&$){Z.subject.next({newValue:_});let F={checkpoint:!0,type:"state_creation",subType:"writable",token:W,timestamp:Date.now(),value:_};Y.operation.subEvents.push(F),$.subject.next(F);let O=Y0(Y);if(W.family){if(D2(O))switch(W.type){case"atom":case"mutable_atom":Y.on.atomCreation.next(W);break;case"writable_pure_selector":case"writable_held_selector":Y.on.selectorCreation.next(W);break}else if(E1(O)&&O.on.transactionApplying.state===null)O.transactionMeta.update.subEvents.push(F)}return}let{key:H,subject:Q,type:J}=Z,z={oldValue:pZ(X)?X.READONLY_VIEW:X,newValue:pZ(_)?_.READONLY_VIEW:_};if(D2(Y)){switch(J){case"mutable_atom":Y.logger.info("\uD83D\uDCE2",J,H,"is now (",_,") subscribers:",Q.subscribers.keys());break;case"atom":case"writable_pure_selector":case"writable_held_selector":Y.logger.info("\uD83D\uDCE2",J,H,"went (",X,"->",_,") subscribers:",Q.subscribers.keys())}Q.next(z)}if(E1(Y)&&(J==="mutable_atom"||J==="atom")){if(Y.on.transactionApplying.state===null){if(pZ(_))return;let{timestamp:F}=Y.operation,O={type:"atom_update",token:W,timestamp:F,update:z};Y.transactionMeta.update.subEvents.push(O),Y.logger.info("\uD83D\uDCC1","atom",H,"stowed (",X,"->",_,")");return}if(X5(Z,"tracker:signal")){let F=H.slice(1),O=Y.atoms.get(F);if(h4(Y,O,"mut").do(z.newValue)===null===!0)Z5(Y,O)}}}var cZ=(Y,Z,X)=>{let _=h4(Y,Z,"mut"),G=mZ(X,_);return Y.logger.info("\u2B50","atom",Z.key,"setting value",G),G=B1(Y,Z,G),B6(Y,Z.key),Z5(Y,Z),{oldValue:_,newValue:G}};function gZ(Y,Z){switch(Z.type){case"mutable_atom":return cZ(Y,Z,new Z.class);case"atom":{let X;if(H8(Z.default))X=N6(Y,Z);else X=Z.default;return cZ(Y,Z,X)}}}function ZF(Y,Z){let X;switch(Z.type){case"atom":case"mutable_atom":X=gZ(Y,Z);break;case"writable_held_selector":{let _=U8(Y,Z.key);for(let $ of _.values()){let W=gZ(Y,$);dZ(Y,Z,W,!1)}let G=Z.getFrom(Y);X={oldValue:G,newValue:G}}break;case"writable_pure_selector":{let _=N6(Y,Z),G=U8(Y,Z.key);for(let W of G.values()){let H=gZ(Y,W);dZ(Y,Z,H,!1)}let $=N6(Y,Z);X={oldValue:_,newValue:$}}break}return X}function k1(Y,...Z){E8(I6,Y,...Z)}var lZ=Symbol("RESET");function R6(Y,...Z){let X=[...Z,lZ];k1(Y,...X)}function XF(Y,Z,X){let _,G,$,{type:W,key:H}=Z;switch(Z.type){case"writable_pure_selector":_=h4(Y,Z,"mut"),G=mZ(X,_),G=B1(Y,Z,G);break;case"writable_held_selector":$=Z.const,mZ(X,$),_=$,G=$}return Y.logger.info("\u2B50",W,H,"setting to",G),B6(Y,H),Z.setSelf(G),{oldValue:_,newValue:G}}var _F=(Y,Z,X)=>{let _;switch(Z.type){case"atom":case"mutable_atom":_=cZ(Y,Z,X);break;case"writable_pure_selector":case"writable_held_selector":_=XF(Y,Z,X);break}return _},I6=Symbol("OWN_OP"),s9=Symbol("JOIN_OP");function E8(Y,Z,...X){let _,G,$,W,H,Q;if(X.length===2){if($=X[0],Q=X[1],"family"in $)if(W=oZ(Z,$),H=X1($.family.subKey),_=z8(Z,W,H),!_)$=G=Q8(J8,Z,W,H);else $=_}else if(W=P0(Z,X[0]),H=X[1],Q=X[2],_=z8(Z,W,H),!_)$=G=Q8(J8,Z,W,H);else $=_;let J=Q===lZ?"reset":"set",z;if(Y===I6){let L=i9(Z,$);if(typeof L==="number"){let w=L,R=Z.on.operationClose.subscribe(`waiting to ${J} "${$.key}" at T-${w}`,function b(){R(),Z.logger.info("\uD83D\uDFE2",$.type,$.key,"resuming deferred",J,`from T-${w}`),E8(Y,Z,$,Q)});return}z=L}else z=Z;if("counterfeit"in $&&"family"in $){let L=$.family.subKey,w=Z.disposalTraces.buffer.find((R)=>R?.key===L);Z.logger.error("\u274C",$.type,$.key,"could not be",J,"because key",L,"is not allocated.",w?`this key was previously disposed:${w.trace}`:"(no previous disposal trace found)");return}let F=P0(z,$),O;if(Q===lZ)O=ZF(z,F);else O=_F(z,F,Q);if(dZ(z,F,O,Boolean(G),W),Y===I6)n9(z)}var t9=(Y,Z)=>Y0(Y).atoms.has(Z),GF=(Y,Z)=>Y0(Y).writableSelectors.has(Z),$F=(Y,Z)=>Y0(Y).readonlySelectors.has(Z),WF=(Y,Z)=>t9(Y,Z)||GF(Y,Z)||$F(Y,Z);function b9(Y,Z){return Y0(Y).selectorGraph.getRelationEntries({downstreamSelectorKey:Z}).filter(([X,{source:_}])=>_!==Z).map(([X,{source:_}])=>_).filter((X)=>WF(Y,X))}function U8(Y,Z,X=new Set){let _=b9(Y,Z),G=new Map;while(_.length>0){let $=_.pop();if(X.has($))continue;if(X.add($),t9(Y,$)){let W=Y.atoms.get($);G.set(W.key,W)}else _.push(...b9(Y,$))}return G}function HF(Y,Z,X,_,G){let $=Y0(Y),{type:W,key:H}=_;if(W==="atom"||W==="mutable_atom")$.selectorAtoms.set({selectorKey:X,atomKey:H}),Y.logger.info("\uD83D\uDD0D",Z,X,`discovers root atom "${H}"`);else{let Q=U8(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())$.selectorAtoms=$.selectorAtoms.set({selectorKey:X,atomKey:J})}G.add(H)}function T6(Y,Z,X,_){return{get:(...G)=>{let $=Y0(Y),{token:W,family:H,subKey:Q}=iZ(Y,...G),J;if("counterfeit"in W&&H&&Q)J=c9(Y,W,H,Q);else{let z=P0(Y,W);J=h4(Y,z)}return Y.logger.info("\uD83D\uDD0C",Z,X,`registers dependency ( "${W.key}" =`,J,")"),$.selectorGraph.set({upstreamSelectorKey:W.key,downstreamSelectorKey:X},{source:W.key}),HF(Y,Z,X,W,_),J},set:(...G)=>{let $=Y0(Y);E8(s9,$,...G)},find:(...G)=>j0(Y,...G),json:(G)=>k4(Y,G)}}function rZ(Y,Z,X){let _=Y0(Y),G=new G0,$=new Set,{key:W,const:H}=Z,Q="readonly_held_selector";Y.logger.info("\uD83D\uDD28","readonly_held_selector",W,"is being created");let{get:J,find:z,json:F}=T6(_,"readonly_held_selector",W,$),L={...Z,type:"readonly_held_selector",subject:G,getFrom:(R)=>{let b=R.selectorGraph.getRelationEntries({downstreamSelectorKey:W});for(let[x,{source:h}]of b)if(h!==W)R.selectorGraph.delete(x,W);return R.selectorAtoms.delete(W),Z.get({get:J,find:z,json:F},H),B1(R,L,H),Y.logger.info("\u2728","readonly_held_selector",W,"=",H),$.clear(),H},install:(R)=>rZ(R,Z,X)};if(X)L.family=X;_.readonlySelectors.set(W,L);let w={key:W,type:"readonly_held_selector"};if(X)w.family=X;return w}function sZ(Y,Z,X){let _=Y0(Y),G=new G0,$=new Set,W=Z.key,H="readonly_pure_selector";Y.logger.info("\uD83D\uDD28","readonly_pure_selector",W,"is being created");let{get:Q,find:J,json:z}=T6(_,"readonly_pure_selector",W,$),O={...Z,type:"readonly_pure_selector",subject:G,getFrom:()=>{let w=Y0(Y),R=w.selectorGraph.getRelationEntries({downstreamSelectorKey:W});for(let[h,{source:g}]of R)if(g!==W)w.selectorGraph.delete(h,W);w.selectorAtoms.delete(W);let b=Z.get({get:Q,find:J,json:z}),x=B1(w,O,b);return Y.logger.info("\u2728","readonly_pure_selector",W,"=",x),$.clear(),x},install:(w)=>sZ(w,Z,X)};if(X)O.family=X;_.readonlySelectors.set(W,O);let L={key:W,type:"readonly_pure_selector"};if(X)L.family=X;return L}function tZ(Y,Z,X){let _=Y0(Y),G=new G0,$=new Set,{key:W,const:H}=Z,Q="writable_held_selector";Y.logger.info("\uD83D\uDD28","writable_held_selector",W,"is being created");let J=T6(_,"writable_held_selector",W,$),{find:z,get:F,json:O}=J,L={find:z,get:F,json:O},b={...Z,type:"writable_held_selector",subject:G,getFrom:(h)=>{let g=h.selectorGraph.getRelationEntries({downstreamSelectorKey:W});for(let[B,{source:K}]of g)if(K!==W)h.selectorGraph.delete(B,W);return h.selectorAtoms.delete(W),Z.get(L,H),B1(h,b,H),Y.logger.info("\u2728","writable_held_selector",W,"=",H),$.clear(),H},setSelf:()=>{Z.set(J,H)},install:(h)=>tZ(h,Z,X)};if(X)b.family=X;_.writableSelectors.set(W,b);let x={key:W,type:"writable_held_selector"};if(X)x.family=X;return x}function aZ(Y,Z,X){let _=Y0(Y),G=new G0,$=new Set,W=Z.key,H="writable_pure_selector";Y.logger.info("\uD83D\uDD28","writable_pure_selector",W,"is being created");let Q=T6(_,"writable_pure_selector",W,$),{find:J,get:z,json:F}=Q,O={find:J,get:z,json:F},R={...Z,type:"writable_pure_selector",subject:G,getFrom:(x)=>{let h=x.selectorGraph.getRelationEntries({downstreamSelectorKey:W});for(let[K,{source:C}]of h)if(C!==W)x.selectorGraph.delete(K,W);x.selectorAtoms.delete(W);let g=Z.get(O),B=B1(x,R,g);return Y.logger.info("\u2728","writable_pure_selector",W,"=",B),$.clear(),B},setSelf:(x)=>{Z.set(Q,x)},install:(x)=>aZ(x,Z,X)};if(X)R.family=X;_.writableSelectors.set(W,R);let b={key:W,type:"writable_pure_selector"};if(X)b.family=X;return b}function v9(Y,Z){let X="set"in Z,_="const"in Z;if(_&&X){let $=tZ(Y,Z,void 0);return Y.on.selectorCreation.next($),$}if(_){let $=rZ(Y,Z,void 0);return Y.on.selectorCreation.next($),$}if(X){let $=aZ(Y,Z,void 0);return Y.on.selectorCreation.next($),$}let G=sZ(Y,Z,void 0);return Y.on.selectorCreation.next(G),G}function JF(Y,Z){let X=Y0(Y),{key:_,type:G,family:$}=Z;if(!$)Y.logger.error("\u274C",G,_,"Standalone selectors cannot be disposed.");else{if(X.molecules.get($.subKey))X.moleculeData.delete($.subKey,$.key);let W;switch(Z.type){case"writable_held_selector":X.writableSelectors.delete(_),W={key:$.key,type:"writable_held_selector_family"},P0(Y,W).subject.next({type:"state_disposal",subType:"selector",token:Z,timestamp:Date.now()});break;case"writable_pure_selector":X.writableSelectors.delete(_),W={key:$.key,type:"writable_pure_selector_family"},P0(Y,W).subject.next({type:"state_disposal",subType:"selector",token:Z,timestamp:Date.now()});break;case"readonly_held_selector":X.readonlySelectors.delete(_),W={key:$.key,type:"readonly_held_selector_family"},P0(Y,W).subject.next({type:"state_disposal",subType:"selector",token:Z,timestamp:Date.now()});break;case"readonly_pure_selector":X.readonlySelectors.delete(_),W={key:$.key,type:"readonly_pure_selector_family"},P0(Y,W).subject.next({type:"state_disposal",subType:"selector",token:Z,timestamp:Date.now()});break}if(X.valueMap.delete(_),X.selectorAtoms.delete(_),X.selectorGraph.delete(_),X.moleculeData.delete($.key,$.subKey),Y.logger.info("\uD83D\uDD25",Z.type,_,"deleted"),E1(X)&&X.transactionMeta.phase==="building")X.transactionMeta.update.subEvents.push({type:"state_disposal",subType:"selector",token:Z,timestamp:Date.now()});else Y.on.selectorDisposal.next(Z)}}var QF=(Y,Z)=>{let X=Y0(Y);if(X.operation.open)return X.operation.prev.get(Z.key);return X.valueMap.get(Z.key)},y9=(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=QF(Y,Z),$=h4(Y,Z);Y.logger.info("\u2728",Z.type,Z.key,"went",G,"->",$),Z.subject.next({newValue:$,oldValue:G})})};function F8(Y,Z,X,_){function G(F){if(Y.operation.open){if($?.type==="atom"&&X5($,"tracker:signal")&&"*"+Y.operation.token.key===Z.key&&"inboundTracker"in _)return;let O=Y.on.operationClose.subscribe(`state subscription ${X}`,()=>{O(),_(F)})}else _(F)}iZ(Y,Z);let $=P0(Y,Z);Y.logger.info("\uD83D\uDC40",$.type,$.key,`Adding subscription "${X}"`);let W=$.type==="writable_pure_selector"||$.type==="readonly_pure_selector",H=new Map,Q=G;if(W){h4(Y,$);for(let[F,O]of U8(Y,$.key))H.set(F,y9(Y,$,O));Q=function F(O){let L=U8(Y,$.key);for(let[w,R]of H)if(L.get(w))L.delete(w);else R(),H.delete(w);for(let[w,R]of L)H.set(w,y9(Y,$,R));G(O)}}let J=$.subject.subscribe(X,Q);return()=>{Y.logger.info("\uD83D\uDE48",$.type,$.key,`Removing subscription "${X}"`),J();for(let F of H.values())F()}}var zF=(Y,Z,X,_)=>{let G=P0(Y,Z);Y.logger.info("\uD83D\uDC40","timeline",Z.key,`Adding subscription "${X}"`);let $=G.subject.subscribe(X,_);return()=>{Y.logger.info("\uD83D\uDE48","timeline",Z.key,`Removing subscription "${X}" from timeline`),$()}};var eZ=class{initializeSignalAtom(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=x4(Z,{key:X,default:null},_,["tracker:signal"]);if(Z.parent?.valueMap.has(X)){let $=Z.parent.valueMap.get(X);Z.valueMap.set(X,$)}return G}unsubscribeFromInnerValue;unsubscribeFromState;captureSignalsFromCore(Y,Z,X){let _=Y.key,G=X.config.name,$=E1(X)?X.transactionMeta.update.token.key:"main",W=`tracker-from-core:${G}:${$}:${_}`,H=(Q)=>{E8(s9,X,Z,Q)};this.unsubscribeFromInnerValue=h1(X,Y).subscribe(W,H),this.unsubscribeFromState=F8(X,Y,W,function Q(J){if(J.newValue!==J.oldValue)this.unsubscribeFromInnerValue(),this.unsubscribeFromInnerValue=J.newValue.subscribe(W,H)}.bind(this))}supplySignalsToCore(Y,Z,X){let _=Y.key,G=X.config.name,$=E1(X)?X.transactionMeta.update.token.key:"main",W=`tracker-to-core:${G}:${$}:${_}`;F8(X,Z,W,Object.assign(function H({newValue:Q,oldValue:J}){let z=X.timelineTopics.getRelatedKey(Z.key);if(z&&X.timelines.get(z)?.timeTraveling){let F=zF(X,{key:z,type:"timeline"},W,function O(L){F(),k1(X,Y,(w)=>{if(L==="redo"&&Q)w.do(Q);else if(L==="undo"&&J)w.undo(J);return w})});return}k1(X,Y,(F)=>(F.do(Q),F))},{inboundTracker:!0}))}mutableAtomToken;latestSignalToken;[Symbol.dispose];constructor(Y,Z){let X=Y0(Z),_=this.initializeSignalAtom(Y,X);this.mutableAtomToken=Y,this.latestSignalToken=_,this.captureSignalsFromCore(Y,_,X),this.supplySignalsToCore(Y,_,X),X.trackers.set(Y.key,this),this[Symbol.dispose]=()=>{this.unsubscribeFromInnerValue(),this.unsubscribeFromState(),X.trackers.delete(Y.key)}}};function w6(Y,Z,X){Y.logger.info("\uD83D\uDD28","atom",Z.key,`creating in store "${Y.config.name}"`);let _=Y0(Y),{key:G}=Z,$=_.atoms.get(G),W="mutable_atom";if($&&$.type===W)return Y.logger.error("\u274C",W,G,"Tried to create atom, but it already exists in the store."),y1($);let H=new G0,Q={...Z,type:W,install:(z)=>{return z.logger.info("\uD83D\uDEE0\uFE0F","atom",G,`installing in store "${z.config.name}"`),w6(z,Z,X)},subject:H};if(X)Q.family=X;_.atoms.set(Q.key,Q);let J=y1(Q);if(Z.effects){let z=0,F=[];for(let O of Z.effects){let L=O({resetSelf:()=>{R6(Y,J)},setSelf:(w)=>{k1(Y,J,w)},onSet:(w)=>F8(Y,J,`effect[${z}]`,w)});if(L)F.push(L);++z}Q.cleanup=()=>{for(let O of F)O()}}if(new eZ(J,Y),!X)v9(Y,{key:`${G}:JSON`,get:({get:z})=>z(J).toJSON(),set:({set:z},F)=>{z(J,Z.class.fromJSON(F))}});return Y.on.atomCreation.next(J),J}var UF=class{trackers=new Map;latestSignalAtoms;mutableAtoms;constructor(Y,Z){let X=O2(Z,{key:`*${Y.key}`,default:null},["mutable","updates"]);this.latestSignalAtoms=P0(Z,X),this.mutableAtoms=Y;let _=(G)=>{let{type:$,token:W}=G;if(W.family){let H=X1(W.family.subKey);switch($){case"state_creation":this.trackers.set(H,new eZ(W,Z));break;case"state_disposal":{let Q=this.trackers.get(H);if(Q)Q[Symbol.dispose](),this.trackers.delete(H)}}}};this.mutableAtoms.subject.subscribe(`store=${Z.config.name}::tracker-atom-family`,_)}};function yZ(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 ${G4[G.type]} "${G.key}" in store "${Y.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);let $=new G0,H={..._,create:(Q)=>{let J=$0(Q),z={key:Z.key,subKey:J},F=`${Z.key}(${J})`,O=Y0(Y),L={key:F,class:Z.class};if(Z.effects)L.effects=Z.effects(Q);return w6(O,L,z)},class:Z.class,subject:$,install:(Q)=>yZ(Q,Z),internalRoles:X};return Y.families.set(Z.key,H),nZ(Y,{key:`${Z.key}:JSON`,get:(Q)=>({get:J})=>J(_,Q).toJSON(),set:(Q)=>({set:J},z)=>{J(_,Q,Z.class.fromJSON(z))}},["mutable","json"]),new UF(H,Y),_}var g9=(Y,Z)=>{let X=Y0(Z),_=`${Y.key}:JSON`;return X.families.get(_)},k4=(Y,Z)=>{if(Z.family){let X=Y0(Y),_={key:`${Z.family.key}:JSON`,type:"writable_pure_selector_family"},G=P0(X,_),$=X1(Z.family.subKey);return j0(Y,G,$)}return{type:"writable_pure_selector",key:`${Z.key}:JSON`}};var Y5=(Y)=>{let Z={type:"atom",key:`*${Y.key}`};if(Y.family)Z.family={key:`*${Y.family.key}`,subKey:Y.family.subKey};return Z};function pZ(Y){return typeof Y==="object"&&Y!==null&&"do"in Y&&"undo"in Y&&"subscribe"in Y&&"READONLY_VIEW"in Y&&"toJSON"in Y}function B1(Y,Z,X){let{key:_,subject:G,type:$}=Z,W=Y.valueMap.get(_);if(W instanceof uZ&&!W.done){let H=W;if(X instanceof Promise)return H.use(X),H;return Y.valueMap.set(_,X),X}if(X instanceof Promise){let H=new uZ(X);return Y.valueMap.set(_,H),H.then(function Q(J){if(Y.valueMap.get(_)===H){switch(i9(Y,Z),B1(Y,Z,J),$){case"atom":Z5(Y,Z);break;case"readonly_pure_selector":case"writable_pure_selector":e9(Y,_);break}n9(Y),G.next({newValue:J,oldValue:H})}}).catch((Q)=>{Y.logger.error("\uD83D\uDCA5",Z.type,_,"rejected:",Q)}),H}return Y.logger.info("\uD83D\uDCDD",Z.type,Z.key,"writing to cache",X),Y.valueMap.set(_,X),X}function FF(Y,Z,X){Y.logger.info("\uD83D\uDCD6",Z.type,Z.key,"reading cached value");let _=Y.valueMap.get(Z.key);if(X==="mut"&&Z.type==="mutable_atom"&&E1(Y)){let G=Z,{parent:$}=Y;if(Y.valueMap.hasOwn(G.key))return _;let W=$.valueMap.get(G.key);Y.logger.info("\uD83D\uDCC3","atom",G.key,"copying");let H=W.toJSON(),Q=G.class.fromJSON(H);Y.valueMap.set(G.key,Q),new eZ(G,$),_=Q}return _}function a9(Y,Z){let X=Y.valueMap.get(Z);if(X instanceof uZ){let _=Y.writableSelectors.get(Z)??Y.readonlySelectors.get(Z);if(_)_.getFrom(Y);return}if(Y.operation.open)Y.operation.prev.set(Z,X);Y.valueMap.delete(Z),Y.logger.info("\uD83D\uDDD1","state",Z,"evicted")}function Z5(Y,Z){let X=Y0(Y),{key:_,type:G}=Z,$=X.selectorAtoms.getRelatedKeys(_);if(X.logger.info("\uD83E\uDDF9",G,_,$?`evicting ${$.size} states downstream:`:"no downstream states",$??"to evict"),$){if(X.operation.open)X.logger.info("\uD83E\uDDF9",G,_,`[ ${[...X.operation.done].join(", ")} ] already done`);for(let W of $){if(r9(X,W))continue;a9(X,W),B6(X,W)}}}function e9(Y,Z){let X=Y0(Y),_=X.selectorGraph.getRelationEntries({upstreamSelectorKey:Z}).filter(([G,{source:$}])=>$===Z);for(let[G]of _){if(r9(X,G))continue;a9(X,G),B6(X,G),e9(Y,G)}}function x4(Y,Z,X,_){let{key:$}=Z;Y.logger.info("\uD83D\uDD28","atom",$,"is being created");let W=Y0(Y),H=W.atoms.get($);if(H&&H.type==="atom")return Y.logger.error("\u274C","atom",$,"Tried to create atom, but it already exists in the store."),y1(H);let Q=new G0,J={...Z,type:"atom",install:(F)=>{return F.logger.info("\uD83D\uDEE0\uFE0F","atom",$,`installing in store "${F.config.name}"`),x4(F,Z,X)},subject:Q};if(X)J.family=X;if(_)J.internalRoles=_;W.atoms.set($,J);let z=y1(J);if(Z.effects){let F=0,O=[];for(let L of Z.effects){let w=L({resetSelf:()=>{R6(Y,z)},setSelf:(R)=>{k1(Y,z,R)},onSet:(R)=>F8(Y,z,`effect[${F}]`,R)});if(w)O.push(w);++F}J.cleanup=()=>{for(let L of O)L()}}return Y.on.atomCreation.next(z),z}function X5(Y,Z){if("internalRoles"in Y===!1)return!1;return Y.internalRoles.includes(Z)}function Y7(Y,Z){let X=Y0(Y),{key:_,family:G}=Z,$=P0(X,Z);if(!G)Y.logger.error("\u274C","atom",_,"Standalone atoms cannot be disposed.");else{$.cleanup?.();let W=Y.valueMap.get($.key),H=oZ(Y,Z),Q=P0(Y,H).subject,J={type:"state_disposal",subType:"atom",token:Z,value:W,timestamp:Date.now()};Q.next(J);let z=E1(X);if(X.atoms.delete(_),X.valueMap.delete(_),X.selectorAtoms.delete(_),X.atomsThatAreDefault.delete(_),X.moleculeData.delete(G.key,G.subKey),Y.timelineTopics.delete(_),Z.type==="mutable_atom"){let F=Y5(Z);Y7(Y,F),Y.trackers.delete(_)}if(Y.logger.info("\uD83D\uDD25","atom",_,"deleted"),z&&X.transactionMeta.phase==="building"){let F=X.transactionMeta.update.subEvents.at(-1),O=F?.type==="molecule_disposal"&&F.values.some(([w])=>w===$.family?.key),L=X5($,"tracker:signal");if(!O&&!L)X.transactionMeta.update.subEvents.push(J)}else Y.on.atomDisposal.next(Z)}}function K0(Y){return Y[0].toUpperCase()+Y.slice(1)}var Z7=class{toolkit;options;defaultContent;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=F1.STORE){this.store=X,this.realm=new C9(X),this.options=Y,this.defaultContent=Z,this.store.miscResources.set(`join:${Y.key}`,this),this.realm.allocate("root",Y.key),this.toolkit={get:(...B)=>h1(X,...B),set:(...B)=>{k1(X,...B)},find:(...B)=>j0(X,...B),json:(B)=>k4(X,B)};let _=Y.between[0],G=Y.between[1],$=yZ(X,{key:`${Y.key}/relatedKeys`,class:h9},["join","relations"]);this.core={relatedKeysAtoms:$};let W=({get:B},K)=>B($,K),H=({set:B},K,C)=>{if(!this.store.molecules.has($0(K)))this.realm.allocate(Y.key,K);B($,K,(q)=>q.add(C)),B($,C,(q)=>q.add(K))},Q=({set:B},K,C)=>{B($,K,(N)=>{return N.delete(C),N}),B($,C,(N)=>{return N.delete(K),N});let[q,c]=[K,C].sort(),n=`${q}:${c}`;this.store.moleculeJoins.delete(n)},J=(B,K,C)=>{let{find:q,get:c,set:n}=B,N=q($,K),s=c(N);for(let p of s){if(C.includes(p))continue;n($,p,(t)=>{return t.delete(K),t})}n(N,(p)=>{return p.transaction((t)=>{t.clear();for(let I0 of C){let h0=W(B,I0),$1=h0.has(K);if(this.relations.cardinality==="1:n"){let r1=[];for(let T of h0){if(T===K)continue;let m=W(B,T);if(m.delete(I0),m.size===0)r1.push(T)}if(!$1&&h0.size>0)h0.clear();for(let T of r1){let[m,W0]=[I0,T].sort(),V0=`${m}:${W0}`;X.moleculeJoins.delete(V0)}}if(!$1)h0.add(K);t.add(I0)}return!0}),p})},z=(B,K,C)=>{let{set:q}=B;q($,K,(c)=>{return c.transaction((n)=>{for(let N of C)n.add(N);return!0}),c});for(let c of C)q($,c,(n)=>{return n.add(K),n});return!0},F=(B,K,C)=>{let q=W(B,K);return C?q.has(C):q.size>0},O={getRelatedKeys:(B)=>W(this.toolkit,B),addRelation:(B,K)=>{this.store.moleculeJoins.set(`"${B}"`,Y.key),this.store.moleculeJoins.set(`"${K}"`,Y.key),H(this.toolkit,B,K)},deleteRelation:(B,K)=>{Q(this.toolkit,B,K)},replaceRelationsSafely:(B,K)=>{J(this.toolkit,B,K)},replaceRelationsUnsafely:(B,K)=>{z(this.toolkit,B,K)},has:(B,K)=>F(this.toolkit,B,K)},L,w;if(Z){w=O2(X,{key:`${Y.key}/content`,default:Z},["join","content"]);let B=({get:C},q)=>C(w,q),K=({set:C},q,c)=>{C(w,q,c)};L=Object.assign(O,{getContent:(C)=>{return B(this.toolkit,C)},setContent:(C,q)=>{K(this.toolkit,C,q)},deleteContent:(C)=>{}})}else L=O;let R=new $4(Y,{externalStore:L,isAType:Y.isAType,isBType:Y.isBType,makeContentKey:(...B)=>{let[K,C]=B,[q,c]=B.sort(),n=`${q}:${c}`,N=X.molecules.get($0(K)),s=X.molecules.get($0(C));if(!N)this.realm.allocate(Y.key,K);if(!s)this.realm.allocate(Y.key,C);return this.realm.allocate(K,n,"all"),this.realm.claim(C,n),this.store.moleculeJoins.set(n,Y.key),n}}),b=()=>f4(X,{key:`${Y.key}/singleRelatedKey`,get:(B)=>({get:K})=>{let C=K($,B);for(let q of C)return q;return null}},["join","keys"]),x=()=>{return f4(X,{key:`${Y.key}/multipleRelatedKeys`,get:(B)=>({get:K})=>{let C=g9($,X);return K(C,B).members}},["join","keys"])},h=()=>f4(X,{key:`${Y.key}/singleRelatedEntry`,get:(B)=>({get:K})=>{let C=K($,B);for(let q of C){let c=R.isAType?.(B)?B:void 0,n=c===void 0?B:void 0;c??=q,n??=q;let N=R.makeContentKey(c,n),s=K(w,N);return[q,s]}return null}},["join","entries"]),g=()=>f4(X,{key:`${Y.key}/multipleRelatedEntries`,get:(B)=>({get:K})=>{let C=g9($,X);return K(C,B).members.map((q)=>{let c=R.isAType?.(B)?B:void 0,n=c===void 0?B:void 0;c??=q,n??=q;let N=R.makeContentKey(c,n),s=K(w,N);return[q,s]})}},["join","entries"]);switch(Y.cardinality){case"1:1":{let B=b(),K=`${_}KeyOf${K0(G)}`,C=`${G}KeyOf${K0(_)}`,q={[K]:B,[C]:B},c;if(Z){let n=h(),N=`${_}EntryOf${K0(G)}`,s=`${G}EntryOf${K0(_)}`,p={[N]:n,[s]:n};c=Object.assign(q,p)}else c=q;this.relations=R,this.states=c;break}case"1:n":{let B=b(),K=x(),C=`${_}KeyOf${K0(G)}`,q=`${G}KeysOf${K0(_)}`,c={[C]:B,[q]:K},n;if(Z){let N=h(),s=g(),p=`${_}EntryOf${K0(G)}`,t=`${G}EntriesOf${K0(_)}`,I0={[p]:N,[t]:s};n=Object.assign(c,I0)}else n=c;this.relations=R,this.states=n;break}case"n:n":{let B=x(),K=`${_}KeysOf${K0(G)}`,C=`${G}KeysOf${K0(_)}`,q={[K]:B,[C]:B},c;if(Z){let n=g(),N=`${_}EntriesOf${K0(G)}`,s=`${G}EntriesOf${K0(_)}`,p={[N]:n,[s]:n};c=Object.assign(q,p)}else c=q;this.relations=R,this.states=c}}}};function x9(Y,Z,X){return Y.joins.set(Z.key,new Z7(Z,X,Y)),{key:Z.key,type:"join",a:Z.between[0],b:Z.between[1],cardinality:Z.cardinality}}function _5(Y,Z){let X=Z.joins.get(Y.key);if(X===void 0){let _=F1.STORE.joins.get(Y.key);if(_===void 0)throw new Error(`Join "${Y.key}" not found in store "${Z.config.name}"`);let G=fU(Z);X=new Z7(_.options,_.defaultContent,G),Z.joins.set(Y.key,X)}return X}function W8(Y,Z,X){let _=_5(Y,X),G=Y0(X);if(E1(G)){let{toolkit:$}=G.transactionMeta;_.transact($,({relations:W})=>{Z(W)})}else Z(_.relations)}function xU(Y,Z,X){let _=_5(Y,X),G;switch(Y.cardinality){case"1:1":{let $=`${Y.a}KeyOf${K0(Y.b)}`,W=`${Y.b}KeyOf${K0(Y.a)}`;G={get[$](){let Q=_.states[$];return j0(X,Q,Z)},get[W](){let Q=_.states[W];return j0(X,Q,Z)}};let H=`${Y.a}EntryOf${K0(Y.b)}`;if(H in _.states){let Q=`${Y.b}EntryOf${K0(Y.a)}`;Object.assign(G,{get[H](){let J=_.states[H];return j0(X,J,Z)},get[Q](){let J=_.states[Q];return j0(X,J,Z)}})}break}case"1:n":{let $=`${Y.a}KeyOf${K0(Y.b)}`,W=`${Y.b}KeysOf${K0(Y.a)}`;G={get[$](){let Q=_.states[$];return j0(X,Q,Z)},get[W](){let Q=_.states[W];return j0(X,Q,Z)}};let H=`${Y.a}EntryOf${K0(Y.b)}`;if(H in _.states){let Q=`${Y.b}EntriesOf${K0(Y.a)}`;Object.assign(G,{get[H](){let J=_.states[H];return j0(X,J,Z)},get[Q](){let J=_.states[Q];return j0(X,J,Z)}})}break}case"n:n":{let $=`${Y.a}KeysOf${K0(Y.b)}`,W=`${Y.b}KeysOf${K0(Y.a)}`;G={get[$](){let Q=_.states[$];return j0(X,Q,Z)},get[W](){let Q=_.states[W];return j0(X,Q,Z)}};let H=`${Y.a}EntriesOf${K0(Y.b)}`;if(H in _.states){let Q=`${Y.b}EntriesOf${K0(Y.a)}`;Object.assign(G,{get[H](){let J=_.states[H];return j0(X,J,Z)},get[Q](){let J=_.states[Q];return j0(X,J,Z)}})}}}return G}function f9(Y,Z){return _5(Y,Z).core.relatedKeysAtoms}var EF=(Y)=>{return x4(Y,{key:"\uD83D\uDD0D Atom Token Index",default:()=>{let Z=new Map;for(let[X,_]of Y.atoms){if(L2(X))continue;let G=y1(_);if(_.family){let $=Z.get(_.family.key);if(!$||!("familyMembers"in $))$={key:_.family.key,familyMembers:new Map},Z.set(_.family.key,$);$.familyMembers.set(_.family.subKey,G)}else Z.set(X,G)}return Z},effects:[({setSelf:Z})=>{Y.on.atomCreation.subscribe("introspection",(X)=>{if(L2(X.key))return;Z((_)=>{if(X.family){let{key:G,subKey:$}=X.family,W=_.get(G);if(W===void 0||!("familyMembers"in W))W={key:G,familyMembers:new Map},_.set(G,W);W.familyMembers.set($,X)}else _.set(X.key,X);return new Map(_)})}),Y.on.atomDisposal.subscribe("introspection",(X)=>{Z((_)=>{if(X.family){let{key:G,subKey:$}=X.family,W=_.get(G);if(W&&"familyMembers"in W){if(W.familyMembers.delete($),W.familyMembers.size===0)_.delete(G)}}return new Map(_)})})}]},void 0)},VF=(Y)=>{return x4(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(L2(_))continue;let $=y1(G);if(G.family){let W=Z.get(G.family.key);if(!W||!("familyMembers"in W))W={key:G.family.key,familyMembers:new Map},Z.set(G.family.key,W);W.familyMembers.set(G.family.subKey,$)}else Z.set(_,$)}return Z},effects:[({setSelf:Z})=>{Y.on.selectorCreation.subscribe("introspection",(X)=>{if(L2(X.key))return;Z((_)=>{if(X.family){let{key:G,subKey:$}=X.family,W=_.get(G);if(W===void 0||!("familyMembers"in W))W={key:G,familyMembers:new Map},_.set(G,W);W.familyMembers.set($,X)}else _.set(X.key,X);return new Map(_)})}),Y.on.selectorDisposal.subscribe("introspection",(X)=>{Z((_)=>{if(X.family){let{key:G,subKey:$}=X.family,W=_.get(G);if(W&&"familyMembers"in W){if(W.familyMembers.delete($),W.familyMembers.size===0)_.delete(G)}}else _.delete(X.key);return new Map(_)})})}]},void 0)};var G5=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}},_7=new G5({number:(Y)=>typeof Y==="number",string:(Y)=>typeof Y==="string",boolean:(Y)=>typeof Y==="boolean",null:(Y)=>Y===null});function G7(Y){if(!Y)return!1;return Object.getPrototypeOf(Y)===Object.prototype}var $7=new G5({object:G7,array:(Y)=>Array.isArray(Y)}),OF=new G5({..._7.supported,...$7.supported}),C6=(Y)=>{if(Y===void 0)return"undefined";let Z=OF.refine(Y);if(Z)return Z.type;return Object.getPrototypeOf(Y).constructor.name};var YB=class Y{store;auditorCreatedAt=performance.now();statesCreatedAt=new Map;atomIndex;selectorIndex;disposed=!1;unsubscribeFromAtomCreation;unsubscribeFromAtomDisposal;unsubscribeFromSelectorCreation;unsubscribeFromSelectorDisposal;constructor(Z=F1.STORE){this.store=Z,this.atomIndex=EF(this.store),this.selectorIndex=VF(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=hZ(this.atomIndex),_=hZ(this.selectorIndex),G=[...X.values()].filter((Q)=>("familyMembers"in Q)),$=[..._.values()].filter((Q)=>("familyMembers"in Q)),W=performance.now(),H=[];if(Z.atomFamilies)for(let Q of G){let J=Q.familyMembers.values();for(let z of J){let F=this.statesCreatedAt.get(z.key)??this.auditorCreatedAt,O=W-F;H.push([z,O])}}if(Z.selectorFamilies)for(let Q of $){let J=Q.familyMembers.values();for(let z of J){let F=this.statesCreatedAt.get(z.key)??this.auditorCreatedAt,O=W-F;H.push([z,O])}}return H}[Symbol.dispose](){this.unsubscribeFromAtomCreation(),this.unsubscribeFromAtomDisposal(),this.unsubscribeFromSelectorCreation(),this.unsubscribeFromSelectorDisposal(),this.disposed=!0}},X7=(Y,Z)=>{let X=(_,G)=>{let W=((Q,J)=>{let z=Z(Q,J);if(z)return z;return null})(_,G);if(W?.jobComplete??W?.pathComplete)return W;let H=Array.isArray(G)?G.map((Q,J)=>[J,Q]):G7(G)?Object.entries(G):[];for(let[Q,J]of H){let z=X([..._,Q],J);if(z?.jobComplete)return z}return{}};X([],Y)};function DF(Y,Z){return{summary:`${Y<Z?"+":"-"}${Math.abs(Y-Z)} (${Y} \u2192 ${Z})`}}function LF(Y,Z){return{summary:`${Y.length<Z.length?"+":"-"}${Math.abs(Y.length-Z.length)} ("${Y}" \u2192 "${Z}")`}}function MF(Y,Z){return{summary:`${Y} \u2192 ${Z}`}}function W7(Y,Z,X){let _="",G=[],$=[],W=[];return X7(Y,(H,Q)=>{let J;for(J of H){let z=Z[J];if(z===void 0)$.push([J,JSON.stringify(Q)]);else{let F=X(Q,z);if(F.summary!=="No Change")W.push([J,F])}}}),X7(Z,(H,Q)=>{let J;for(J of H)if(Y[J]===void 0)G.push([J,JSON.stringify(Q)])}),_=`\uFF5E${W.length} \uFF0B${G.length} \uFF0D${$.length}`,{summary:_,added:G,removed:$,changed:W}}function AF(Y,Z,X){return W7(Y,Z,X)}var RF=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,(W,H)=>this.diff(W,H))}}let G=C6(Y),$=C6(Z);if(G===$)return{summary:`${G} \u2192 ${$}`};return{summary:`Type change: ${G} \u2192 ${$}`}}},ZB=new RF(_7,$7,{number:DF,string:LF,boolean:MF,null:()=>({summary:"No Change"}),object:W7,array:AF});var b4=class Y extends Set{mode="record";subject=new G0;constructor(Z){super(Z);if(Z instanceof Y);}READONLY_VIEW=this;toJSON(){return{members:[...this]}}static fromJSON(Z){return new Y(Z.members)}add(Z){let X=super.add(Z);if(this.mode==="record")this.emit(`add:${$0(Z)}`);return X}clear(){let Z=this.mode==="record"?[...this]:null;if(super.clear(),Z)this.emit(`clear:${$0(Z)}`)}delete(Z){let X=super.delete(Z);if(this.mode==="record")this.emit(`del:${$0(Z)}`);return X}subscribe(Z,X){return this.subject.subscribe(Z,X)}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"del":this.delete(JSON.parse(G));break;case"clear":this.clear()}}do(Z){return this.mode="playback",this.doStep(Z),this.mode="record",null}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 $=JSON.parse(G);for(let W of $)this.add(W)}}}undo(Z){return this.mode="playback",this.undoStep(Z),this.mode="record",null}};var wF=V2({key:"mutex",default:!1}),NF=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)}},zB=class Y{type="continuity";globals=[];actions=[];perspectives=[];key;constructor(Z){this.key=Z}static existing=new NF;static create(Z,X){let _=new Y(Z),{type:G,globals:$,actions:W,perspectives:H}=X(_),Q={type:G,key:Z,globals:$,actions:W,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[X,_]=Z;this.perspectives.push({type:"realtime_perspective",resourceAtoms:X,viewAtoms:_})}break}return this}};var UB=E2({key:"usersInRoomIndex",class:b4}),H7=E2({key:"roomIndex",class:b4}),IF={enteredAtEpoch:0},V8=O6({key:"usersInRooms",between:["room","user"],cardinality:"1:n",isAType:(Y)=>typeof Y==="string",isBType:(Y)=>typeof Y==="string"},IF),FB=D6({key:"usersInMyRoomView",get:(Y)=>({find:Z})=>{let X=B9(V8);return[Z(X,Y)]}});var NB=V2({key:"redactor",default:{occlude:(Y)=>Y}}),IB=V2({key:"unacknowledgedUpdates",default:()=>[]});var $5=class{listeners;globalListeners;handleEvent(...Y){let[Z,...X]=Y;for(let G of this.globalListeners)G(Z,...X);let _=this.listeners.get(Z);if(_)for(let G of _)G(...X)}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}},KB=class extends $5{incompleteData="";unprocessedEvents=[];incompleteLog="";unprocessedLogs=[];id="#####";proc;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}}}constructor(Y,Z,X){super((_,...G)=>{let $=JSON.stringify([_,...G])+"\x03",W=(H)=>{if(H.code==="EPIPE")console.error("EPIPE error during write",this.proc.stdin);this.proc.stdin.removeListener("error",W)};return this.proc.stdin.once("error",W),this.proc.stdin.write($),this});if(this.proc=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.proc.stdout.on("data",(_)=>{let G=_.toString();if(G==="ALIVE"){this.logger.info(G);return}let $=G.split("\x03"),W=$[0];$[0]=this.incompleteData+W;let H=0;for(let Q of $){if(Q==="")continue;try{let J=X1(Q);this.handleEvent(...J),this.incompleteData=""}catch(J){if(J instanceof Error)console.error(["\u274C Malformed data received from child process","",Q,"",J.message].join(`
60
+ \u274C `));try{if(H===0){this.incompleteData=Q;let z=X1(W);this.handleEvent(...z),this.incompleteData=""}else this.incompleteData+=Q}catch(z){if(z instanceof Error)console.error(["\u274C Malformed data received from child process","",W,"",z.message].join(`
61
+ \u274C `))}}++H}}),this.proc.stderr.on("data",(_)=>{let G=_.toString().split("\x03"),$=G[0];G[0]=this.incompleteData+$;let W=0;for(let H of G){if(H==="")continue;try{let Q=X1(H);this.handleLog(Q),this.incompleteData=""}catch(Q){if(Q instanceof Error)console.error(["\u274C Malformed log received from child process","",H,"",Q.message].join(`
62
+ \u274C `));try{if(W===0){this.incompleteData=H;let J=X1($);this.handleLog(J),this.incompleteData=""}else this.incompleteData+=H}catch(J){if(J instanceof Error)console.error(["\u274C Malformed log received from child process...","",$,"",J.message].join(`
63
+ \u274C `))}}++W}}),Y.pid)this.id=Y.pid.toString()}},KF=class extends $5{in;out;id="no_id_retrieved";disposalFunctions=[];constructor(Y){super((...Z)=>{return this.out.next(Z),this});this.id=Y,this.in=new G0,this.out=new G0,this.in.subscribe("socket",(Z)=>{this.handleEvent(...Z)})}dispose(){for(let Y of this.disposalFunctions)Y()}},Q7=class extends $5{incompleteData="";unprocessedEvents=[];relays;relayServices;proc;id="#####";log(...Y){this.proc.stderr.write($0(Y.map((Z)=>Z instanceof b4?`{ ${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(Y){super((Z,...X)=>{let _=JSON.stringify([Z,...X]);return this.proc.stdout.write(_+"\x03"),this});if(this.proc=Y,this.proc.stdin.resume(),this.relays=new Map,this.relayServices=[],this.proc.stdin.on("data",(Z)=>{let X=Z.toString().split("\x03"),_=X[0];X[0]=this.incompleteData+_;let G=0;for(let $ of X){if($==="")continue;try{let W=X1($);this.logger.info("\uD83C\uDFB0","received",W),this.handleEvent(...W),this.incompleteData=""}catch(W){if(W instanceof Error)this.logger.error(["received malformed data from parent process:","",$,"",W.message].join(`
64
+ \u274C `));try{if(G===0){this.incompleteData=$;let H=X1(_);this.logger.info("\uD83C\uDFB0","received",H),this.handleEvent(...H),this.incompleteData=""}else this.incompleteData+=$}catch(H){if(H instanceof Error)this.logger.error(["received malformed data from parent process:","",_,"",H.message].join(`
65
+ \u274C `))}}++G}}),this.on("exit",()=>{this.logger.info("\uD83D\uDD25",this.id,'received "exit"'),this.proc.exit(0)}),this.proc.pid)this.id=this.proc.pid?.toString();this.on("user-joins",(Z)=>{this.logger.info("\uD83D\uDC64","user",Z,"joined");let X=`user::${Z}`,_=new KF(X);this.relays.set(Z,_),this.logger.info("\uD83D\uDD17","attaching services:",`[${[...this.relayServices.keys()].join(", ")}]`);for(let G of this.relayServices){let $=G(_,X);if($)_.disposalFunctions.push($)}this.on(X,(...G)=>{_.in.next(G)}),_.out.subscribe("socket",(G)=>{this.emit(...G)})}),this.on("user-leaves",(Z)=>{let X=this.relays.get(Z);if(this.off(`relay:${Z}`),X)X.dispose(),this.relays.delete(Z)}),this.proc.stdout.write("ALIVE")}receiveRelay(Y){this.logger.info("\uD83D\uDD17","running relay method"),this.relayServices.push(Y)}};var J7=new Map;var BB=L6({key:"joinRoom",do:(Y,Z,X,_)=>{let G={enteredAtEpoch:_};return W8(V8,($)=>{$.set({room:Z,user:X},G)},Y.env().store),G}}),TB=L6({key:"leaveRoom",do:({env:Y},Z,X)=>{W8(V8,(_)=>{_.delete({room:Z,user:X})},Y().store)}}),CB=L6({key:"destroyRoom",do:({set:Y,env:Z},X)=>{W8(V8,(G)=>{G.delete({room:X})},Z().store),Y(H7,(G)=>(G.delete(X),G));let _=J7.get(X);if(_)_.emit("exit"),J7.delete(X)}}),qB=V2({key:"sockets",default:null}),jB=E2({key:"socketsIndex",class:b4}),PB=E2({key:"usersIndex",class:b4}),SB=O6({key:"usersOfSockets",between:["user","socket"],cardinality:"1:1",isAType:(Y)=>Y.startsWith("user::"),isBType:(Y)=>Y.startsWith("socket::")}),vB=D6({key:"userMutualSituationalAwarenessIndexes",get:(Y)=>()=>{return[Y]}});var{file:mW,serve:pE}=globalThis.Bun;import{readFileSync as F7}from"fs";import{createServer as qF}from"http";import{createServer as jF}from"https";import{resolve as H5}from"path";function z7(Y,Z){if(Y instanceof Promise)throw new Error(Z)}function BF(Y,Z){let X={},_=[];for(let G in Y){let $=Y[G]["~standard"].validate(Z[G]);if(z7($,`Validation must be synchronous, but ${G} returned a Promise.`),$.issues){_.push(...$.issues.map((W)=>({...W,message:W.message,path:[G,...W.path??[]]})));continue}X[G]=$.value}if(_.length)return{issues:_};return{value:X}}function W5(Y){let Z=Y.runtimeEnvStrict??Y.runtimeEnv??process.env;if(Y.emptyStringAsUndefined??!1){for(let[h,g]of Object.entries(Z))if(g==="")delete Z[h]}if(!!Y.skipValidation)return Z;let G=typeof Y.client==="object"?Y.client:{},$=typeof Y.server==="object"?Y.server:{},W=typeof Y.shared==="object"?Y.shared:{},H=Y.isServer??(typeof window==="undefined"||("Deno"in window)),Q=H?{...$,...W,...G}:{...G,...W},J=Y.createFinalSchema?.(Q,H)["~standard"].validate(Z)??BF(Q,Z);z7(J,"Validation must be synchronous");let z=Y.onValidationError??((h)=>{throw console.error("\u274C Invalid environment variables:",h),new Error("Invalid environment variables")}),F=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 O=(h)=>{if(!Y.clientPrefix)return!0;return!h.startsWith(Y.clientPrefix)&&!(h in W)},L=(h)=>{return H||!O(h)},w=(h)=>{return h==="__esModule"||h==="$$typeof"},R=(Y.extends??[]).reduce((h,g)=>{return Object.assign(h,g)},{}),b=Object.assign(R,J.value);return new Proxy(b,{get(h,g){if(typeof g!=="string")return;if(w(g))return;if(!L(g))return F(g);return Reflect.get(h,g)}})}var TF="__vite_start_time"in globalThis,CF=typeof window!=="undefined",dB="vitest"in globalThis,W4=U1("string"),U7=U1('"true" | "false" | undefined'),g1=W5({isServer:!TF&&!CF,server:{CI:U1("string | undefined").pipe(Boolean),POSTGRES_USER:W4,POSTGRES_PASSWORD:W4,POSTGRES_DATABASE:W4,POSTGRES_HOST:W4,POSTGRES_PORT:W4.pipe((Y)=>Number.parseInt(Y,10)),BACKEND_PORT:W4.pipe((Y)=>Number.parseInt(Y,10)),RUN_WORKERS_FROM_SOURCE:U7.pipe((Y)=>Y==="true"),FRONTEND_PORT:W4.pipe((Y)=>Number.parseInt(Y,10)),FRONTEND_ORIGINS:W4.pipe.try((Y)=>JSON.parse(Y),U1("string[]")),API_KEY_OPENAI:U1("string | undefined"),API_KEY_RESEND:U1("string | undefined")},clientPrefix:"VITE_",client:{VITE_BACKEND_ORIGIN:W4,VITE_DEV_FRONTEND_HOST:U1("string | undefined"),VITE_DEV_HTTPS:U7.pipe((Y)=>Y==="true")},runtimeEnv:import.meta.env,emptyStringAsUndefined:!0});var E7=H5(import.meta.dirname,"../dev"),q6=g1.VITE_DEV_HTTPS?{cert:F7(H5(E7,"./cert.pem"),"utf-8"),key:F7(H5(E7,"./key.pem"),"utf-8")}:void 0;function sB(Y){if(q6)return jF(q6,Y);return qF({},Y)}import xE from"path";var E=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,E))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(E in X&&X[E]===Z[E])return!0;X=Object.getPrototypeOf(X)}return!1}class F0{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[E]="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 J5{static[E]="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 p1=Symbol.for("drizzle:Name");class Q5{static[E]="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 V7(Y,this)}}class V7{constructor(Y,Z){this.table=Y,this.reference=Z.reference,this.onUpdate=Z._onUpdate,this.onDelete=Z._onDelete}static[E]="PgForeignKey";reference;onUpdate;onDelete;getName(){let{name:Y,columns:Z,foreignColumns:X}=this.reference(),_=Z.map((W)=>W.name),G=X.map((W)=>W.name),$=[this.table[p1],..._,X[0].table[p1],...G];return Y??`${$.join("_")}_fk`}}function j6(Y,...Z){return Y(...Z)}function O7(Y,Z){return`${Y[p1]}_${Z.join("_")}_unique`}function D7(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 L7(Y,Z=0){let X=[],_=Z,G=!1;while(_<Y.length){let $=Y[_];if($===","){if(G||_===Z)X.push("");G=!0,_++;continue}if(G=!1,$==="\\"){_+=2;continue}if($==='"'){let[Q,J]=D7(Y,_+1,!0);X.push(Q),_=J;continue}if($==="}")return[X,_+1];if($==="{"){let[Q,J]=L7(Y,_+1);X.push(Q),_=J;continue}let[W,H]=D7(Y,_,!1);X.push(W),_=H}return[X,_]}function M7(Y){let[Z]=L7(Y,1);return Z}function z5(Y){return`{${Y.map((Z)=>{if(Array.isArray(Z))return z5(Z);if(typeof Z==="string")return`"${Z.replace(/\\/g,"\\\\").replace(/"/g,"\\\"")}"`;return`${Z}`}).join(",")}}`}class k extends J5{foreignKeyConfigs=[];static[E]="PgColumnBuilder";array(Y){return new R7(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 j6((G,$)=>{let W=new Q5(()=>{let H=G();return{columns:[Y],foreignColumns:[H]}});if($.onUpdate)W.onUpdate($.onUpdate);if($.onDelete)W.onDelete($.onDelete);return W.build(Z)},X,_)})}buildExtraConfigColumn(Y){return new A7(Y,this.config)}}class j extends F0{constructor(Y,Z){if(!Z.uniqueName)Z.uniqueName=O7(Y,[Z.name]);super(Y,Z);this.table=Y}static[E]="PgColumn"}class A7 extends j{static[E]="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 O8{static[E]="IndexedColumn";constructor(Y,Z,X,_){this.name=Y,this.keyAsName=Z,this.type=X,this.indexConfig=_}name;keyAsName;type;indexConfig}class R7 extends k{static[E]="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 U5(Y,this.config,Z)}}class U5 extends j{constructor(Y,Z,X,_){super(Y,Z);this.baseColumn=X,this.range=_,this.size=Z.size}size;static[E]="PgArray";getSQLType(){return`${this.baseColumn.getSQLType()}[${typeof this.size==="number"?this.size:""}]`}mapFromDriverValue(Y){if(typeof Y==="string")Y=M7(Y);return Y.map((Z)=>this.baseColumn.mapFromDriverValue(Z))}mapToDriverValue(Y,Z=!1){let X=Y.map((_)=>_===null?null:M(this.baseColumn,U5)?this.baseColumn.mapToDriverValue(_,!0):this.baseColumn.mapToDriverValue(_));if(Z)return X;return z5(X)}}class w7 extends k{static[E]="PgEnumObjectColumnBuilder";constructor(Y,Z){super(Y,"string","PgEnumObjectColumn");this.config.enum=Z}build(Y){return new N7(Y,this.config)}}class N7 extends j{static[E]="PgEnumObjectColumn";enum;enumValues=this.config.enum.enumValues;constructor(Y,Z){super(Y,Z);this.enum=Z.enum}getSQLType(){return this.enum.enumName}}var P6=Symbol.for("drizzle:isPgEnum");function I7(Y){return!!Y&&typeof Y==="function"&&P6 in Y&&Y[P6]===!0}class K7 extends k{static[E]="PgEnumColumnBuilder";constructor(Y,Z){super(Y,"string","PgEnumColumn");this.config.enum=Z}build(Y){return new B7(Y,this.config)}}class B7 extends j{static[E]="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 D8(Y,Z){return Array.isArray(Z)?PF(Y,[...Z],void 0):SF(Y,Z,void 0)}function PF(Y,Z,X){let _=Object.assign((G)=>new K7(G??"",_),{enumName:Y,enumValues:Z,schema:X,[P6]:!0});return _}function SF(Y,Z,X){let _=Object.assign((G)=>new w7(G??"",_),{enumName:Y,enumValues:Object.values(Z),schema:X,[P6]:!0});return _}class S0{static[E]="Subquery";constructor(Y,Z,X,_=!1,G=[]){this._={brand:"Subquery",sql:Y,selectedFields:Z,alias:X,isWith:_,usedTables:G}}}class L8 extends S0{static[E]="WithSubquery"}var T7="0.44.5";var F5,E5,E0={startActiveSpan(Y,Z){if(!F5)return Z();if(!E5)E5=F5.trace.getTracer("drizzle-orm",T7);return j6((X,_)=>_.startActiveSpan(Y,(G)=>{try{return Z(G)}catch($){throw G.setStatus({code:X.SpanStatusCode.ERROR,message:$ instanceof Error?$.message:"Unknown error"}),$}finally{G.end()}}),F5,E5)}};var M0=Symbol.for("drizzle:ViewBaseConfig");var y4=Symbol.for("drizzle:Schema"),S6=Symbol.for("drizzle:Columns"),C7=Symbol.for("drizzle:ExtraConfigColumns"),V5=Symbol.for("drizzle:OriginalName"),O5=Symbol.for("drizzle:BaseName"),M8=Symbol.for("drizzle:IsAlias"),q7=Symbol.for("drizzle:ExtraConfigBuilder"),vF=Symbol.for("drizzle:IsDrizzleTable");class P{static[E]="Table";static Symbol={Name:p1,Schema:y4,OriginalName:V5,Columns:S6,ExtraConfigColumns:C7,BaseName:O5,IsAlias:M8,ExtraConfigBuilder:q7};[p1];[V5];[y4];[S6];[C7];[O5];[M8]=!1;[vF]=!0;[q7]=void 0;constructor(Y,Z,X){this[p1]=this[V5]=Y,this[y4]=Z,this[O5]=X}}function d0(Y){return Y[p1]}function g4(Y){return`${Y[y4]??"public"}.${Y[p1]}`}function D5(Y){return Y!==null&&Y!==void 0&&typeof Y.getSQL==="function"}function xF(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 m0{static[E]="StringChunk";value;constructor(Y){this.value=Array.isArray(Y)?Y:[Y]}getSQL(){return new f([this])}}class f{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[E]="SQL";decoder=P7;shouldInlineParams=!1;usedTables=[];append(Y){return this.queryChunks.push(...Y.queryChunks),this}toQuery(Y){return E0.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:$,prepareTyping:W,inlineParams:H,paramStartIndex:Q}=X;return xF(Y.map((J)=>{if(M(J,m0))return{sql:J.value.join(""),params:[]};if(M(J,v6))return{sql:G(J.value),params:[]};if(J===void 0)return{sql:"",params:[]};if(Array.isArray(J)){let z=[new m0("(")];for(let[F,O]of J.entries())if(z.push(O),F<J.length-1)z.push(new m0(", "));return z.push(new m0(")")),this.buildQueryFromSourceParams(z,X)}if(M(J,f))return this.buildQueryFromSourceParams(J.queryChunks,{...X,inlineParams:H||J.shouldInlineParams});if(M(J,P)){let z=J[P.Symbol.Schema],F=J[P.Symbol.Name];return{sql:z===void 0||J[M8]?G(F):G(z)+"."+G(F),params:[]}}if(M(J,F0)){let z=_.getColumnCasing(J);if(Z.invokeSource==="indexes")return{sql:G(z),params:[]};let F=J.table[P.Symbol.Schema];return{sql:J.table[M8]||F===void 0?G(J.table[P.Symbol.Name])+"."+G(z):G(F)+"."+G(J.table[P.Symbol.Name])+"."+G(z),params:[]}}if(M(J,V1)){let z=J[M0].schema,F=J[M0].name;return{sql:z===void 0||J[M0].isAlias?G(F):G(z)+"."+G(F),params:[]}}if(M(J,A1)){if(M(J.value,w4))return{sql:$(Q.value++,J),params:[J],typings:["none"]};let z=J.value===null?null:J.encoder.mapToDriverValue(J.value);if(M(z,f))return this.buildQueryFromSourceParams([z],X);if(H)return{sql:this.mapInlineParam(z,X),params:[]};let F=["none"];if(W)F=[W(J.encoder)];return{sql:$(Q.value++,z),params:[z],typings:F}}if(M(J,w4))return{sql:$(Q.value++,J),params:[J],typings:["none"]};if(M(J,f.Aliased)&&J.fieldAlias!==void 0)return{sql:G(J.fieldAlias),params:[]};if(M(J,S0)){if(J._.isWith)return{sql:G(J._.alias),params:[]};return this.buildQueryFromSourceParams([new m0("("),J._.sql,new m0(") "),new v6(J._.alias)],X)}if(I7(J)){if(J.schema)return{sql:G(J.schema)+"."+G(J.enumName),params:[]};return{sql:G(J.enumName),params:[]}}if(D5(J)){if(J.shouldOmitSQLParens?.())return this.buildQueryFromSourceParams([J.getSQL()],X);return this.buildQueryFromSourceParams([new m0("("),J.getSQL(),new m0(")")],X)}if(H)return{sql:this.mapInlineParam(J,X),params:[]};return{sql:$(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 f.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 v6{constructor(Y){this.value=Y}static[E]="Name";brand;getSQL(){return new f([this])}}function j7(Y){return typeof Y==="object"&&Y!==null&&"mapToDriverValue"in Y&&typeof Y.mapToDriverValue==="function"}var P7={mapFromDriverValue:(Y)=>Y},S7={mapToDriverValue:(Y)=>Y},gT={...P7,...S7};class A1{constructor(Y,Z=S7){this.value=Y,this.encoder=Z}static[E]="Param";brand;getSQL(){return new f([this])}}function V(Y,...Z){let X=[];if(Z.length>0||Y.length>0&&Y[0]!=="")X.push(new m0(Y[0]));for(let[_,G]of Z.entries())X.push(G,new m0(Y[_+1]));return new f(X)}((Y)=>{function Z(){return new f([])}Y.empty=Z;function X(Q){return new f(Q)}Y.fromList=X;function _(Q){return new f([new m0(Q)])}Y.raw=_;function G(Q,J){let z=[];for(let[F,O]of Q.entries()){if(F>0&&J!==void 0)z.push(J);z.push(O)}return new f(z)}Y.join=G;function $(Q){return new v6(Q)}Y.identifier=$;function W(Q){return new w4(Q)}Y.placeholder=W;function H(Q,J){return new A1(Q,J)}Y.param=H})(V||(V={}));((Y)=>{class Z{constructor(X,_){this.sql=X,this.fieldAlias=_}static[E]="SQL.Aliased";isSelectionField=!1;getSQL(){return this.sql}clone(){return new Z(this.sql,this.fieldAlias)}}Y.Aliased=Z})(f||(f={}));class w4{constructor(Y){this.name=Y}static[E]="Placeholder";getSQL(){return new f([this])}}function L5(Y,Z){return Y.map((X)=>{if(M(X,w4)){if(!(X.name in Z))throw new Error(`No value for placeholder "${X.name}" was provided`);return Z[X.name]}if(M(X,A1)&&M(X.value,w4)){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 fF=Symbol.for("drizzle:IsDrizzleView");class V1{static[E]="View";[M0];[fF]=!0;constructor({name:Y,schema:Z,selectedFields:X,query:_}){this[M0]={name:Y,originalName:Y,schema:Z,selectedFields:X,query:_,isExisting:!_,isAlias:!1}}getSQL(){return new f([this])}}F0.prototype.getSQL=function(){return new f([this])};P.prototype.getSQL=function(){return new f([this])};S0.prototype.getSQL=function(){return new f([this])};class M2{constructor(Y){this.table=Y}static[E]="ColumnAliasProxyHandler";get(Y,Z){if(Z==="table")return this.table;return Y[Z]}}class A8{constructor(Y,Z){this.alias=Y,this.replaceOriginalName=Z}static[E]="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===M0)return{...Y[M0],name:this.alias,isAlias:!0};if(Z===P.Symbol.Columns){let _=Y[P.Symbol.Columns];if(!_)return _;let G={};return Object.keys(_).map(($)=>{G[$]=new Proxy(_[$],new M2(new Proxy(Y,this)))}),G}let X=Y[Z];if(M(X,F0))return new Proxy(X,new M2(new Proxy(Y,this)));return X}}function x6(Y,Z){return new Proxy(Y,new A8(Z,!1))}function i1(Y,Z){return new Proxy(Y,new M2(new Proxy(Y.table,new A8(Z,!1))))}function M5(Y,Z){return new f.Aliased(R8(Y.sql,Z),Y.fieldAlias)}function R8(Y,Z){return V.join(Y.queryChunks.map((X)=>{if(M(X,F0))return i1(X,Z);if(M(X,f))return R8(X,Z);if(M(X,f.Aliased))return M5(X,Z);return X}))}class f6 extends Error{static[E]="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}
66
+ params: ${Z}`);if(this.query=Y,this.params=Z,this.cause=X,Error.captureStackTrace(this,H4),X)this.cause=X}}class A5 extends f6{static[E]="TransactionRollbackError";constructor(){super({message:"Rollback"})}}class v7{static[E]="ConsoleLogWriter";write(Y){console.log(Y)}}class R5{static[E]="DefaultLogger";writer;constructor(Y){this.writer=Y?.writer??new v7}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 w5{static[E]="NoopLogger";logQuery(){}}class _1{static[E]="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 x7(Y,Z,X){let _={},G=Y.reduce(($,{path:W,field:H},Q)=>{let J;if(M(H,F0))J=H;else if(M(H,f))J=H.decoder;else J=H.sql.decoder;let z=$;for(let[F,O]of W.entries())if(F<W.length-1){if(!(O in z))z[O]={};z=z[O]}else{let L=Z[Q],w=z[O]=L===null?null:J.mapFromDriverValue(L);if(X&&M(H,F0)&&W.length===2){let R=W[0];if(!(R in _))_[R]=w===null?d0(H.table):!1;else if(typeof _[R]==="string"&&_[R]!==d0(H.table))_[R]=!1}}return $},{});if(X&&Object.keys(_).length>0){for(let[$,W]of Object.entries(_))if(typeof W==="string"&&!X[W])G[$]=null}return G}function T1(Y,Z){return Object.entries(Y).reduce((X,[_,G])=>{if(typeof _!=="string")return X;let $=Z?[...Z,_]:[_];if(M(G,F0)||M(G,f)||M(G,f.Aliased))X.push({path:$,field:G});else if(M(G,P))X.push(...T1(G[P.Symbol.Columns],$));else X.push(...T1(G,$));return X},[])}function w8(Y,Z){let X=Object.keys(Y),_=Object.keys(Z);if(X.length!==_.length)return!1;for(let[G,$]of X.entries())if($!==_[G])return!1;return!0}function h6(Y,Z){let X=Object.entries(Z).filter(([,_])=>_!==void 0).map(([_,G])=>{if(M(G,f)||M(G,F0))return[_,G];else return[_,new A1(G,Y[P.Symbol.Columns][_])]});if(X.length===0)throw new Error("No values to set");return Object.fromEntries(X)}function f7(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 h7(Y){return Y[P.Symbol.Columns]}function J4(Y){return M(Y,S0)?Y._.alias:M(Y,V1)?Y[M0].name:M(Y,f)?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 k7(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 N4 extends k{static[E]="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 b7 extends N4{static[E]="PgBigInt53Builder";constructor(Y){super(Y,"number","PgBigInt53")}build(Y){return new y7(Y,this.config)}}class y7 extends j{static[E]="PgBigInt53";getSQLType(){return"bigint"}mapFromDriverValue(Y){if(typeof Y==="number")return Y;return Number(Y)}}class g7 extends N4{static[E]="PgBigInt64Builder";constructor(Y){super(Y,"bigint","PgBigInt64")}build(Y){return new p7(Y,this.config)}}class p7 extends j{static[E]="PgBigInt64";getSQLType(){return"bigint"}mapFromDriverValue(Y){return BigInt(Y)}}function m7(Y,Z){let{name:X,config:_}=X0(Y,Z);if(_.mode==="number")return new b7(X);return new g7(X)}class u7 extends k{static[E]="PgBigSerial53Builder";constructor(Y){super(Y,"number","PgBigSerial53");this.config.hasDefault=!0,this.config.notNull=!0}build(Y){return new d7(Y,this.config)}}class d7 extends j{static[E]="PgBigSerial53";getSQLType(){return"bigserial"}mapFromDriverValue(Y){if(typeof Y==="number")return Y;return Number(Y)}}class c7 extends k{static[E]="PgBigSerial64Builder";constructor(Y){super(Y,"bigint","PgBigSerial64");this.config.hasDefault=!0}build(Y){return new l7(Y,this.config)}}class l7 extends j{static[E]="PgBigSerial64";getSQLType(){return"bigserial"}mapFromDriverValue(Y){return BigInt(Y)}}function o7(Y,Z){let{name:X,config:_}=X0(Y,Z);if(_.mode==="number")return new u7(X);return new c7(X)}class i7 extends k{static[E]="PgBooleanBuilder";constructor(Y){super(Y,"boolean","PgBoolean")}build(Y){return new n7(Y,this.config)}}class n7 extends j{static[E]="PgBoolean";getSQLType(){return"boolean"}}function N8(Y){return new i7(Y??"")}class r7 extends k{static[E]="PgCharBuilder";constructor(Y,Z){super(Y,"string","PgChar");this.config.length=Z.length,this.config.enumValues=Z.enum}build(Y){return new s7(Y,this.config)}}class s7 extends j{static[E]="PgChar";length=this.config.length;enumValues=this.config.enumValues;getSQLType(){return this.length===void 0?"char":`char(${this.length})`}}function t7(Y,Z={}){let{name:X,config:_}=X0(Y,Z);return new r7(X,_)}class a7 extends k{static[E]="PgCidrBuilder";constructor(Y){super(Y,"string","PgCidr")}build(Y){return new e7(Y,this.config)}}class e7 extends j{static[E]="PgCidr";getSQLType(){return"cidr"}}function Y$(Y){return new a7(Y??"")}class Z$ extends k{static[E]="PgCustomColumnBuilder";constructor(Y,Z,X){super(Y,"custom","PgCustomColumn");this.config.fieldConfig=Z,this.config.customTypeParams=X}build(Y){return new X$(Y,this.config)}}class X$ extends j{static[E]="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 _$(Y){return(Z,X)=>{let{name:_,config:G}=X0(Z,X);return new Z$(_,G,Y)}}class Q4 extends k{static[E]="PgDateColumnBaseBuilder";defaultNow(){return this.default(V`now()`)}}class G$ extends Q4{static[E]="PgDateBuilder";constructor(Y){super(Y,"date","PgDate")}build(Y){return new k6(Y,this.config)}}class k6 extends j{static[E]="PgDate";getSQLType(){return"date"}mapFromDriverValue(Y){return new Date(Y)}mapToDriverValue(Y){return Y.toISOString()}}class $$ extends Q4{static[E]="PgDateStringBuilder";constructor(Y){super(Y,"string","PgDateString")}build(Y){return new b6(Y,this.config)}}class b6 extends j{static[E]="PgDateString";getSQLType(){return"date"}}function W$(Y,Z){let{name:X,config:_}=X0(Y,Z);if(_?.mode==="date")return new G$(X);return new $$(X)}class H$ extends k{static[E]="PgDoublePrecisionBuilder";constructor(Y){super(Y,"number","PgDoublePrecision")}build(Y){return new J$(Y,this.config)}}class J$ extends j{static[E]="PgDoublePrecision";getSQLType(){return"double precision"}mapFromDriverValue(Y){if(typeof Y==="string")return Number.parseFloat(Y);return Y}}function Q$(Y){return new H$(Y??"")}class z$ extends k{static[E]="PgInetBuilder";constructor(Y){super(Y,"string","PgInet")}build(Y){return new U$(Y,this.config)}}class U$ extends j{static[E]="PgInet";getSQLType(){return"inet"}}function F$(Y){return new z$(Y??"")}class E$ extends N4{static[E]="PgIntegerBuilder";constructor(Y){super(Y,"number","PgInteger")}build(Y){return new V$(Y,this.config)}}class V$ extends j{static[E]="PgInteger";getSQLType(){return"integer"}mapFromDriverValue(Y){if(typeof Y==="string")return Number.parseInt(Y);return Y}}function I8(Y){return new E$(Y??"")}class O$ extends k{static[E]="PgIntervalBuilder";constructor(Y,Z){super(Y,"string","PgInterval");this.config.intervalConfig=Z}build(Y){return new D$(Y,this.config)}}class D$ extends j{static[E]="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 L$(Y,Z={}){let{name:X,config:_}=X0(Y,Z);return new O$(X,_)}class M$ extends k{static[E]="PgJsonBuilder";constructor(Y){super(Y,"json","PgJson")}build(Y){return new y6(Y,this.config)}}class y6 extends j{static[E]="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 A$(Y){return new M$(Y??"")}class R$ extends k{static[E]="PgJsonbBuilder";constructor(Y){super(Y,"json","PgJsonb")}build(Y){return new g6(Y,this.config)}}class g6 extends j{static[E]="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 w$(Y){return new R$(Y??"")}class N$ extends k{static[E]="PgLineBuilder";constructor(Y){super(Y,"array","PgLine")}build(Y){return new I$(Y,this.config)}}class I$ extends j{static[E]="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 K$ extends k{static[E]="PgLineABCBuilder";constructor(Y){super(Y,"json","PgLineABC")}build(Y){return new B$(Y,this.config)}}class B$ extends j{static[E]="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 T$(Y,Z){let{name:X,config:_}=X0(Y,Z);if(!_?.mode||_.mode==="tuple")return new N$(X);return new K$(X)}class C$ extends k{static[E]="PgMacaddrBuilder";constructor(Y){super(Y,"string","PgMacaddr")}build(Y){return new q$(Y,this.config)}}class q$ extends j{static[E]="PgMacaddr";getSQLType(){return"macaddr"}}function j$(Y){return new C$(Y??"")}class P$ extends k{static[E]="PgMacaddr8Builder";constructor(Y){super(Y,"string","PgMacaddr8")}build(Y){return new S$(Y,this.config)}}class S$ extends j{static[E]="PgMacaddr8";getSQLType(){return"macaddr8"}}function v$(Y){return new P$(Y??"")}class x$ extends k{static[E]="PgNumericBuilder";constructor(Y,Z,X){super(Y,"string","PgNumeric");this.config.precision=Z,this.config.scale=X}build(Y){return new p6(Y,this.config)}}class p6 extends j{static[E]="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 f$ extends k{static[E]="PgNumericNumberBuilder";constructor(Y,Z,X){super(Y,"number","PgNumericNumber");this.config.precision=Z,this.config.scale=X}build(Y){return new h$(Y,this.config)}}class h$ extends j{static[E]="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 k$ extends k{static[E]="PgNumericBigIntBuilder";constructor(Y,Z,X){super(Y,"bigint","PgNumericBigInt");this.config.precision=Z,this.config.scale=X}build(Y){return new b$(Y,this.config)}}class b$ extends j{static[E]="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 y$(Y,Z){let{name:X,config:_}=X0(Y,Z),G=_?.mode;return G==="number"?new f$(X,_?.precision,_?.scale):G==="bigint"?new k$(X,_?.precision,_?.scale):new x$(X,_?.precision,_?.scale)}class g$ extends k{static[E]="PgPointTupleBuilder";constructor(Y){super(Y,"array","PgPointTuple")}build(Y){return new p$(Y,this.config)}}class p$ extends j{static[E]="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 m$ extends k{static[E]="PgPointObjectBuilder";constructor(Y){super(Y,"json","PgPointObject")}build(Y){return new u$(Y,this.config)}}class u$ extends j{static[E]="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 d$(Y,Z){let{name:X,config:_}=X0(Y,Z);if(!_?.mode||_.mode==="tuple")return new g$(X);return new m$(X)}function hF(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 c$(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 N5(Y){let Z=hF(Y),X=0,_=Z[X];X+=1;let G=new DataView(Z.buffer),$=G.getUint32(X,_===1);X+=4;let W;if($&536870912)W=G.getUint32(X,_===1),X+=4;if(($&65535)===1){let H=c$(Z,X);X+=8;let Q=c$(Z,X);return X+=8,[H,Q]}throw new Error("Unsupported geometry type")}class l$ extends k{static[E]="PgGeometryBuilder";constructor(Y){super(Y,"array","PgGeometry")}build(Y){return new o$(Y,this.config)}}class o$ extends j{static[E]="PgGeometry";getSQLType(){return"geometry(point)"}mapFromDriverValue(Y){return N5(Y)}mapToDriverValue(Y){return`point(${Y[0]} ${Y[1]})`}}class i$ extends k{static[E]="PgGeometryObjectBuilder";constructor(Y){super(Y,"json","PgGeometryObject")}build(Y){return new n$(Y,this.config)}}class n$ extends j{static[E]="PgGeometryObject";getSQLType(){return"geometry(point)"}mapFromDriverValue(Y){let Z=N5(Y);return{x:Z[0],y:Z[1]}}mapToDriverValue(Y){return`point(${Y.x} ${Y.y})`}}function r$(Y,Z){let{name:X,config:_}=X0(Y,Z);if(!_?.mode||_.mode==="tuple")return new l$(X);return new i$(X)}class s$ extends k{static[E]="PgRealBuilder";constructor(Y,Z){super(Y,"number","PgReal");this.config.length=Z}build(Y){return new t$(Y,this.config)}}class t$ extends j{static[E]="PgReal";constructor(Y,Z){super(Y,Z)}getSQLType(){return"real"}mapFromDriverValue=(Y)=>{if(typeof Y==="string")return Number.parseFloat(Y);return Y}}function a$(Y){return new s$(Y??"")}class e$ extends k{static[E]="PgSerialBuilder";constructor(Y){super(Y,"number","PgSerial");this.config.hasDefault=!0,this.config.notNull=!0}build(Y){return new Y3(Y,this.config)}}class Y3 extends j{static[E]="PgSerial";getSQLType(){return"serial"}}function Z3(Y){return new e$(Y??"")}class X3 extends N4{static[E]="PgSmallIntBuilder";constructor(Y){super(Y,"number","PgSmallInt")}build(Y){return new _3(Y,this.config)}}class _3 extends j{static[E]="PgSmallInt";getSQLType(){return"smallint"}mapFromDriverValue=(Y)=>{if(typeof Y==="string")return Number(Y);return Y}}function G3(Y){return new X3(Y??"")}class $3 extends k{static[E]="PgSmallSerialBuilder";constructor(Y){super(Y,"number","PgSmallSerial");this.config.hasDefault=!0,this.config.notNull=!0}build(Y){return new W3(Y,this.config)}}class W3 extends j{static[E]="PgSmallSerial";getSQLType(){return"smallserial"}}function H3(Y){return new $3(Y??"")}class J3 extends k{static[E]="PgTextBuilder";constructor(Y,Z){super(Y,"string","PgText");this.config.enumValues=Z.enum}build(Y){return new Q3(Y,this.config)}}class Q3 extends j{static[E]="PgText";enumValues=this.config.enumValues;getSQLType(){return"text"}}function z3(Y,Z={}){let{name:X,config:_}=X0(Y,Z);return new J3(X,_)}class U3 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[E]="PgTimeBuilder";build(Y){return new m6(Y,this.config)}}class m6 extends j{static[E]="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 F3(Y,Z={}){let{name:X,config:_}=X0(Y,Z);return new U3(X,_.withTimezone??!1,_.precision)}class E3 extends Q4{static[E]="PgTimestampBuilder";constructor(Y,Z,X){super(Y,"date","PgTimestamp");this.config.withTimezone=Z,this.config.precision=X}build(Y){return new u6(Y,this.config)}}class u6 extends j{static[E]="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 V3 extends Q4{static[E]="PgTimestampStringBuilder";constructor(Y,Z,X){super(Y,"string","PgTimestampString");this.config.withTimezone=Z,this.config.precision=X}build(Y){return new d6(Y,this.config)}}class d6 extends j{static[E]="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 O3(Y,Z={}){let{name:X,config:_}=X0(Y,Z);if(_?.mode==="string")return new V3(X,_.withTimezone??!1,_.precision);return new E3(X,_?.withTimezone??!1,_?.precision)}class D3 extends k{static[E]="PgUUIDBuilder";constructor(Y){super(Y,"string","PgUUID")}defaultRandom(){return this.default(V`gen_random_uuid()`)}build(Y){return new c6(Y,this.config)}}class c6 extends j{static[E]="PgUUID";getSQLType(){return"uuid"}}function C1(Y){return new D3(Y??"")}class L3 extends k{static[E]="PgVarcharBuilder";constructor(Y,Z){super(Y,"string","PgVarchar");this.config.length=Z.length,this.config.enumValues=Z.enum}build(Y){return new M3(Y,this.config)}}class M3 extends j{static[E]="PgVarchar";length=this.config.length;enumValues=this.config.enumValues;getSQLType(){return this.length===void 0?"varchar":`varchar(${this.length})`}}function t0(Y,Z={}){let{name:X,config:_}=X0(Y,Z);return new L3(X,_)}class A3 extends k{static[E]="PgBinaryVectorBuilder";constructor(Y,Z){super(Y,"string","PgBinaryVector");this.config.dimensions=Z.dimensions}build(Y){return new R3(Y,this.config)}}class R3 extends j{static[E]="PgBinaryVector";dimensions=this.config.dimensions;getSQLType(){return`bit(${this.dimensions})`}}function w3(Y,Z){let{name:X,config:_}=X0(Y,Z);return new A3(X,_)}class N3 extends k{static[E]="PgHalfVectorBuilder";constructor(Y,Z){super(Y,"array","PgHalfVector");this.config.dimensions=Z.dimensions}build(Y){return new I3(Y,this.config)}}class I3 extends j{static[E]="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 K3(Y,Z){let{name:X,config:_}=X0(Y,Z);return new N3(X,_)}class B3 extends k{static[E]="PgSparseVectorBuilder";constructor(Y,Z){super(Y,"string","PgSparseVector");this.config.dimensions=Z.dimensions}build(Y){return new T3(Y,this.config)}}class T3 extends j{static[E]="PgSparseVector";dimensions=this.config.dimensions;getSQLType(){return`sparsevec(${this.dimensions})`}}function C3(Y,Z){let{name:X,config:_}=X0(Y,Z);return new B3(X,_)}class q3 extends k{static[E]="PgVectorBuilder";constructor(Y,Z){super(Y,"array","PgVector");this.config.dimensions=Z.dimensions}build(Y){return new j3(Y,this.config)}}class j3 extends j{static[E]="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 P3(Y,Z){let{name:X,config:_}=X0(Y,Z);return new q3(X,_)}function S3(){return{bigint:m7,bigserial:o7,boolean:N8,char:t7,cidr:Y$,customType:_$,date:W$,doublePrecision:Q$,inet:F$,integer:I8,interval:L$,json:A$,jsonb:w$,line:T$,macaddr:j$,macaddr8:v$,numeric:y$,point:d$,geometry:r$,real:a$,serial:Z3,smallint:G3,smallserial:H3,text:z3,time:F3,timestamp:O3,uuid:C1,varchar:t0,bit:w3,halfvec:K3,sparsevec:C3,vector:P3}}var I5=Symbol.for("drizzle:PgInlineForeignKeys"),v3=Symbol.for("drizzle:EnableRLS");class u0 extends P{static[E]="PgTable";static Symbol=Object.assign({},P.Symbol,{InlineForeignKeys:I5,EnableRLS:v3});[I5]=[];[v3]=!1;[P.Symbol.ExtraConfigBuilder]=void 0;[P.Symbol.ExtraConfigColumns]={}}function kF(Y,Z,X,_,G=Y){let $=new u0(Y,_,G),W=typeof Z==="function"?Z(S3()):Z,H=Object.fromEntries(Object.entries(W).map(([z,F])=>{let O=F;O.setName(z);let L=O.build($);return $[I5].push(...O.buildForeignKeys(L,$)),[z,L]})),Q=Object.fromEntries(Object.entries(W).map(([z,F])=>{let O=F;O.setName(z);let L=O.buildExtraConfigColumn($);return[z,L]})),J=Object.assign($,H);if(J[P.Symbol.Columns]=H,J[P.Symbol.ExtraConfigColumns]=Q,X)J[u0.Symbol.ExtraConfigBuilder]=X;return Object.assign(J,{enableRLS:()=>{return J[u0.Symbol.EnableRLS]=!0,J}})}var I4=(Y,Z,X)=>{return kF(Y,Z,X,void 0)};function x3(...Y){if(Y[0].columns)return new K8(Y[0].columns,Y[0].name);return new K8(Y)}class K8{static[E]="PgPrimaryKeyBuilder";columns;name;constructor(Y,Z){this.columns=Y,this.name=Z}build(Y){return new f3(Y,this.columns,this.name)}}class f3{constructor(Y,Z,X){this.table=Y,this.columns=Z,this.name=X}static[E]="PgPrimaryKey";columns;name;getName(){return this.name??`${this.table[u0.Symbol.Name]}_${this.columns.map((Y)=>Y.name).join("_")}_pk`}}function O1(Y,Z){if(j7(Z)&&!D5(Y)&&!M(Y,A1)&&!M(Y,w4)&&!M(Y,F0)&&!M(Y,P)&&!M(Y,V1))return new A1(Y,Z);return Y}var l6=(Y,Z)=>{return V`${Y} = ${O1(Z,Y)}`},h3=(Y,Z)=>{return V`${Y} <> ${O1(Z,Y)}`};function B8(...Y){let Z=Y.filter((X)=>X!==void 0);if(Z.length===0)return;if(Z.length===1)return new f(Z);return new f([new m0("("),V.join(Z,new m0(" and ")),new m0(")")])}function k3(...Y){let Z=Y.filter((X)=>X!==void 0);if(Z.length===0)return;if(Z.length===1)return new f(Z);return new f([new m0("("),V.join(Z,new m0(" or ")),new m0(")")])}function b3(Y){return V`not ${Y}`}var y3=(Y,Z)=>{return V`${Y} > ${O1(Z,Y)}`},g3=(Y,Z)=>{return V`${Y} >= ${O1(Z,Y)}`},p3=(Y,Z)=>{return V`${Y} < ${O1(Z,Y)}`},m3=(Y,Z)=>{return V`${Y} <= ${O1(Z,Y)}`};function u3(Y,Z){if(Array.isArray(Z)){if(Z.length===0)return V`false`;return V`${Y} in ${Z.map((X)=>O1(X,Y))}`}return V`${Y} in ${O1(Z,Y)}`}function d3(Y,Z){if(Array.isArray(Z)){if(Z.length===0)return V`true`;return V`${Y} not in ${Z.map((X)=>O1(X,Y))}`}return V`${Y} not in ${O1(Z,Y)}`}function c3(Y){return V`${Y} is null`}function l3(Y){return V`${Y} is not null`}function o3(Y){return V`exists ${Y}`}function i3(Y){return V`not exists ${Y}`}function n3(Y,Z,X){return V`${Y} between ${O1(Z,Y)} and ${O1(X,Y)}`}function r3(Y,Z,X){return V`${Y} not between ${O1(Z,Y)} and ${O1(X,Y)}`}function s3(Y,Z){return V`${Y} like ${Z}`}function t3(Y,Z){return V`${Y} not like ${Z}`}function a3(Y,Z){return V`${Y} ilike ${Z}`}function e3(Y,Z){return V`${Y} not ilike ${Z}`}function YW(Y){return V`${Y} asc`}function ZW(Y){return V`${Y} desc`}class K5{constructor(Y,Z,X){this.sourceTable=Y,this.referencedTable=Z,this.relationName=X,this.referencedTableName=Z[P.Symbol.Name]}static[E]="Relation";referencedTableName;fieldName}class XW{constructor(Y,Z){this.table=Y,this.config=Z}static[E]="Relations"}class K4 extends K5{constructor(Y,Z,X,_){super(Y,Z,X?.relationName);this.config=X,this.isNullable=_}static[E]="One";withFieldName(Y){let Z=new K4(this.sourceTable,this.referencedTable,this.config,this.isNullable);return Z.fieldName=Y,Z}}class T8 extends K5{constructor(Y,Z,X){super(Y,Z,X?.relationName);this.config=X}static[E]="Many";withFieldName(Y){let Z=new T8(this.sourceTable,this.referencedTable,this.config);return Z.fieldName=Y,Z}}function _W(){return{and:B8,between:n3,eq:l6,exists:o3,gt:y3,gte:g3,ilike:a3,inArray:u3,isNull:c3,isNotNull:l3,like:s3,lt:p3,lte:m3,ne:h3,not:b3,notBetween:r3,notExists:i3,notLike:t3,notIlike:e3,notInArray:d3,or:k3,sql:V}}function GW(){return{sql:V,asc:YW,desc:ZW}}function $W(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(W,P)){let H=g4(W),Q=_[H];X[H]=$,G[$]={tsName:$,dbName:W[P.Symbol.Name],schema:W[P.Symbol.Schema],columns:W[P.Symbol.Columns],relations:Q?.relations??{},primaryKey:Q?.primaryKey??[]};for(let z of Object.values(W[P.Symbol.Columns]))if(z.primary)G[$].primaryKey.push(z);let J=W[P.Symbol.ExtraConfigBuilder]?.(W[P.Symbol.ExtraConfigColumns]);if(J){for(let z of Object.values(J))if(M(z,K8))G[$].primaryKey.push(...z.columns)}}else if(M(W,XW)){let H=g4(W.table),Q=X[H],J=W.config(Z(W.table)),z;for(let[F,O]of Object.entries(J))if(Q){let L=G[Q];if(L.relations[F]=O,z)L.primaryKey.push(...z)}else{if(!(H in _))_[H]={relations:{},primaryKey:z};_[H].relations[F]=O}}return{tables:G,tableNamesMap:X}}function bF(Y){return function Z(X,_){return new K4(Y,X,_,_?.fields.reduce((G,$)=>G&&$.notNull,!0)??!1)}}function yF(Y){return function Z(X,_){return new T8(Y,X,_)}}function WW(Y,Z,X){if(M(X,K4)&&X.config)return{fields:X.config.fields,references:X.config.references};let _=Z[g4(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 $=X.sourceTable,W=Z[g4($)];if(!W)throw new Error(`Table "${$[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],K4)&&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 "${W}.${X.fieldName}"`)}function HW(Y){return{one:bF(Y),many:yF(Y)}}function o6(Y,Z,X,_,G=($)=>$){let $={};for(let[W,H]of _.entries())if(H.isJson){let Q=Z.relations[H.tsKey],J=X[W],z=typeof J==="string"?JSON.parse(J):J;$[H.tsKey]=M(Q,K4)?z&&o6(Y,Y[H.relationTableTsKey],z,H.selection,G):z.map((F)=>o6(Y,Y[H.relationTableTsKey],F,H.selection,G))}else{let Q=G(X[W]),J=H.field,z;if(M(J,F0))z=J;else if(M(J,f))z=J.decoder;else z=J.sql.decoder;$[H.tsKey]=Q===null?null:z.mapFromDriverValue(Q)}return $}import JE from"os";import QE from"fs";var i6=new Map,B5=new Map,T5=Symbol("OriginError"),A2={};class q1 extends Promise{constructor(Y,Z,X,_,G={}){let $,W;super((H,Q)=>{$=H,W=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,$(H)),this.reject=(H)=>(this.active=!1,W(H)),this.active=!1,this.cancelled=null,this.executed=!1,this.signature="",this[T5]=this.handler.debug?new Error:this.tagged&&gF(this.strings)}get origin(){return(this.handler.debug?this[T5].stack:this.tagged&&B5.has(this.strings)?B5.get(this.strings):B5.set(this.strings,this[T5].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,$)=>{this.cursorFn=(W)=>{return G({value:W,done:!1}),new Promise((H)=>X=H)},this.resolve=()=>(this.active=!1,G({done:!0})),this.reject=(W)=>(this.active=!1,$(W))});return this.execute(),_},return(){return X&&X(A2),{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 gF(Y){if(i6.has(Y))return i6.get(Y);let Z=Error.stackTraceLimit;return Error.stackTraceLimit=4,i6.set(Y,new Error),Error.stackTraceLimit=Z,i6.get(Y)}class R2 extends Error{constructor(Y){super(Y.message);this.name=this.constructor.name,Object.assign(this,Y)}}var f0={connection:JW,postgres:QW,generic:zW,notSupported:UW};function JW(Y,Z,X){let{host:_,port:G}=X||Z,$=Object.assign(new Error("write "+Y+" "+(Z.path||_+":"+G)),{code:Y,errno:Y,address:Z.path||_},Z.path?{}:{port:G});return Error.captureStackTrace($,JW),$}function QW(Y){let Z=new R2(Y);return Error.captureStackTrace(Z,QW),Z}function zW(Y,Z){let X=Object.assign(new Error(Y+": "+Z),{code:Y});return Error.captureStackTrace(X,zW),X}function UW(Y){let Z=Object.assign(new Error(Y+" (B) is not supported"),{code:"MESSAGE_NOT_SUPPORTED",name:Y});return Error.captureStackTrace(Z,UW),Z}var pF={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 s6{then(){C5()}catch(){C5()}finally(){C5()}}class P8 extends s6{constructor(Y){super();this.value=e6(Y)}}class n1 extends s6{constructor(Y,Z,X){super();this.value=Y,this.type=Z,this.array=X}}class t6 extends s6{constructor(Y,Z){super();this.first=Y,this.rest=Z}build(Y,Z,X,_){let G=mF.map(([$,W])=>({fn:W,i:Y.search($)})).sort(($,W)=>$.i-W.i).pop();return G.i===-1?v5(this.first,_):G.fn(this.first,this.rest,Z,X,_)}}function a6(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||r6(Y.value)]||Y.type||OW(Y.value):Y.type):(Z.push(Y),r6(Y)))}var EW=LW(pF);function P5(Y,Z,X,_,G,$){for(let W=1;W<Y.strings.length;W++)Z+=S5(Z,X,_,G,$)+Y.strings[W],X=Y.args[W];return Z}function S5(Y,Z,X,_,G){return Z instanceof t6?Z.build(Y,X,_,G):Z instanceof q1?j5(Z,X,_,G):Z instanceof P8?Z.value:Z&&Z[0]instanceof q1?Z.reduce(($,W)=>$+" "+j5(W,X,_,G),""):a6(Z,X,_,G)}function j5(Y,Z,X,_){return Y.fragment=!0,P5(Y,Y.strings[0],Y.args[0],Z,X,_)}function VW(Y,Z,X,_,G){return Y.map(($)=>"("+_.map((W)=>S5("values",$[W],Z,X,G)).join(",")+")").join(",")}function FW(Y,Z,X,_,G){let $=Array.isArray(Y[0]),W=Z.length?Z.flat():Object.keys($?Y[0]:Y);return VW($?Y:[Y],X,_,W,G)}function n6(Y,Z,X,_,G){if(typeof Y==="string"&&(Y=[Y].concat(Z)),Array.isArray(Y))return v5(Y,G);let $;return(Z.length?Z.flat():Object.keys(Y)).map((H)=>{return $=Y[H],($ instanceof q1?j5($,X,_,G):$ instanceof P8?$.value:a6($,X,_,G))+" as "+e6(G.transform.column.to?G.transform.column.to(H):H)}).join(",")}var mF=Object.entries({values:FW,in:(...Y)=>{let Z=FW(...Y);return Z==="()"?"(null)":Z},select:n6,as:n6,returning:n6,"\\(":n6,update(Y,Z,X,_,G){return(Z.length?Z.flat():Object.keys(Y)).map(($)=>e6(G.transform.column.to?G.transform.column.to($):$)+"="+S5("values",Y[$],X,_,G))},insert(Y,Z,X,_,G){let $=Z.length?Z.flat():Object.keys(Array.isArray(Y)?Y[0]:Y);return"("+v5($,G)+")values"+VW(Array.isArray(Y)?Y:[Y],X,_,$,G)}}).map(([Y,Z])=>[new RegExp("((?:^|[\\s(])"+Y+"(?:$|[\\s(]))(?![\\s\\S]*\\1)","i"),Z]);function C5(){throw f0.generic("NOT_TAGGED_CALL","Query not called as a tagged template literal")}var{serializers:uF,parsers:dF}=EW;function OW(Y){if(Array.isArray(Y))return OW(Y[0]);return typeof Y==="string"?1009:0}var DW=function(Y){let Z=LW(Y||{});return{serializers:Object.assign({},uF,Z.serializers),parsers:Object.assign({},dF,Z.parsers)}};function LW(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 v5(Y,{transform:{column:Z}}){return Y.map((X)=>e6(Z.to?Z.to(X):X)).join(",")}var e6=function Y(Z){return'"'+Z.replace(/"/g,'""').replace(/\./g,'"."')+'"'},r6=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},cF=/\\/g,lF=/"/g;function oF(Y){return Y.replace(cF,"\\\\").replace(lF,"\\\"")}var MW=function Y(Z,X,_,G){if(Array.isArray(Z)===!1)return Z;if(!Z.length)return"{}";let $=Z[0],W=G===1020?";":",";if(Array.isArray($)&&!$.type)return"{"+Z.map((H)=>Y(H,X,_,G)).join(W)+"}";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":'"'+oF(X?X(H.type?H.value:H):""+H)+'"'}).join(W)+"}"},q5={i:0,char:null,str:"",quoted:!1,last:0},AW=function Y(Z,X,_){return q5.i=q5.last=0,RW(q5,Z,X,_)};function RW(Y,Z,X,_){let G=[],$=_===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(RW(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===$&&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,"-"),C8=(Y)=>Y.replace(/([A-Z])/g,"_$1").toLowerCase(),q8=(Y)=>(Y.slice(0,1)+Y.slice(1).replace(/([A-Z])/g,"_$1")).toLowerCase(),j8=(Y)=>Y.replace(/-/g,"_");function x5(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($)]:Z(W,_)}),{}):X}}p4.column={from:p4};p4.value={from:x5(p4)};C8.column={to:C8};var f5={...p4};f5.column.to=C8;m4.column={from:m4};m4.value={from:x5(m4)};q8.column={to:q8};var h5={...m4};h5.column.to=q8;u4.column={from:u4};u4.value={from:x5(u4)};j8.column={to:j8};var k5={...u4};k5.column.to=j8;import wW from"net";import sF from"tls";import S8 from"crypto";import b5 from"stream";import{performance as NW}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 R1=iF;function iF(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 a0=Buffer.allocUnsafe(256),nF="BCcDdEFfHPpQSX".split("").reduce((Y,Z)=>{let X=Z.charCodeAt(0);return Y[Z]=()=>{return a0[0]=X,z0.i=5,z0},Y},{}),z0=Object.assign(rF,nF,{N:String.fromCharCode(0),i:0,inc(Y){return z0.i+=Y,z0},str(Y){let Z=Buffer.byteLength(Y);return YY(Z),z0.i+=a0.write(Y,z0.i,Z,"utf8"),z0},i16(Y){return YY(2),a0.writeUInt16BE(Y,z0.i),z0.i+=2,z0},i32(Y,Z){if(Z||Z===0)return a0.writeUInt32BE(Y,Z),z0;return YY(4),a0.writeUInt32BE(Y,z0.i),z0.i+=4,z0},z(Y){return YY(Y),a0.fill(0,z0.i,z0.i+Y),z0.i+=Y,z0},raw(Y){return a0=Buffer.concat([a0.subarray(0,z0.i),Y]),z0.i=a0.length,z0},end(Y=1){a0.writeUInt32BE(z0.i-Y,Y);let Z=a0.subarray(0,z0.i);return z0.i=0,a0=Buffer.allocUnsafe(256),Z}}),d=z0;function YY(Y){if(a0.length-z0.i<Y){let Z=a0,X=Z.length;a0=Buffer.allocUnsafe(X+(X>>1)+Y),Z.copy(a0)}}function rF(){return z0.i=0,z0}var p5=BW,tF=1,B4=d().S().end(),IW=d().H().end(),aF=d().i32(8).i32(80877103).end(8),eF=Buffer.concat([d().E().str(d.N).i32(0).end(),B4]),YE=d().D().str("S").str(d.N).end(),w2=()=>{},ZE=new Set(["FetchPreparedStatement","RevalidateCachedQuery","transformAssignedExpr"]),XE={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 BW(Y,Z={},{onopen:X=w2,onend:_=w2,onclose:G=w2}={}){let{ssl:$,max:W,user:H,host:Q,port:J,database:z,parsers:F,transform:O,onnotice:L,onnotify:w,onparameter:R,max_pipeline:b,keep_alive:x,backoff:h,target_session_attrs:g}=Y,B=R1(),K=tF++,C={pid:null,secret:null},q=g5(VY,Y.idle_timeout),c=g5(VY,Y.max_lifetime),n=g5(nW,Y.connect_timeout),N=null,s,p=new d4,t=Buffer.alloc(0),I0=Y.fetch_types,h0={},$1={},r1=Math.random().toString(36).slice(2),T=1,m=0,W0=0,V0=0,k0=0,a=0,Q0=0,v0=0,B0=null,A0=null,o0=!1,O0=null,j1=null,c0=null,z4=null,b0=null,R0=null,P1=null,u1=null,v=null,B2=null,i0={queue:Z.closed,idleTimer:q,connect(U){c0=U,EX()},terminate:C2,execute:T2,cancel:cW,end:VY,count:0,id:K};return Z.closed&&Z.closed.push(i0),i0;async function dW(){let U;try{U=Y.socket?await Promise.resolve(Y.socket(Y)):new wW.Socket}catch(D){i4(D);return}return U.on("error",i4),U.on("close",VX),U.on("drain",UX),U}async function cW({pid:U,secret:D},l,H0){try{s=d().i32(16).i32(80877102).i32(U).i32(D).end(16),await FX(),N.once("error",H0),N.once("close",l)}catch(C0){H0(C0)}}function T2(U){if(o0)return g8(U,f0.connection("CONNECTION_DESTROYED",Y));if(U.cancelled)return;try{return U.state=C,v?B.push(U):(v=U,v.active=!0),iW(U),l0(lW(U))&&!U.describeFirst&&!U.cursorFn&&B.length<b&&(!U.options.onexecute||U.options.onexecute(i0))}catch(D){return B.length===0&&l0(B4),d1(D),!0}}function lW(U){if(U.parameters.length>=65534)throw f0.generic("MAX_PARAMETERS_EXCEEDED","Max number of parameters (65534) exceeded");return U.options.simple?d().Q().str(U.statement.string+d.N).end():U.describeFirst?Buffer.concat([JX(U),IW]):U.prepare?U.prepared?y8(U):Buffer.concat([JX(U),y8(U)]):oW(U)}function JX(U){return Buffer.concat([DX(U.statement.string,U.parameters,U.statement.types,U.statement.name),vH("S",U.statement.name)])}function y8(U){return Buffer.concat([SH(U.parameters,U.statement.types,U.statement.name,U.cursorName),U.cursorFn?LX("",U.cursorRows):eF])}function oW(U){return Buffer.concat([DX(U.statement.string,U.parameters,U.statement.types),YE,y8(U)])}function iW(U){let D=[],l=[],H0=P5(U,U.strings[0],U.args[0],D,l,Y);!U.tagged&&U.args.forEach((C0)=>a6(C0,D,l,Y)),U.prepare=Y.prepare&&("prepare"in U.options?U.options.prepare:!0),U.string=H0,U.signature=U.prepare&&l+H0,U.onlyDescribe&&delete $1[U.signature],U.parameters=U.parameters||D,U.prepared=U.prepare&&U.signature in $1,U.describeFirst=U.onlyDescribe||D.length&&!U.prepared,U.statement=U.prepared?$1[U.signature]:{string:H0,types:l,name:U.prepare?r1+T++:""},typeof Y.debug==="function"&&Y.debug(K,H0,D,l)}function l0(U,D){if(R0=R0?Buffer.concat([R0,U]):Buffer.from(U),D||R0.length>=1024)return QX(D);return A0===null&&(A0=setImmediate(QX)),!0}function QX(U){let D=N.write(R0,U);return A0!==null&&clearImmediate(A0),R0=A0=null,D}function nW(){d1(f0.connection("CONNECT_TIMEOUT",Y,N)),N.destroy()}async function zX(){if(l0(aF),!await new Promise((D)=>N.once("data",(l)=>D(l[0]===83)))&&$==="prefer")return o4();N.removeAllListeners(),N=sF.connect({socket:N,servername:wW.isIP(N.host)?void 0:N.host,...$==="require"||$==="allow"||$==="prefer"?{rejectUnauthorized:!1}:$==="verify-full"?{}:typeof $==="object"?$:{}}),N.on("secureConnect",o4),N.on("error",i4),N.on("close",VX),N.on("drain",UX)}function UX(){!v&&X(i0)}function EY(U){if(O0){if(O0.push(U),W0-=U.length,W0>0)return}t=O0?Buffer.concat(O0,a-W0):t.length===0?U:Buffer.concat([t,U],t.length+U.length);while(t.length>4){if(a=t.readUInt32BE(1),a>=t.length){W0=a-t.length,O0=[t];break}try{rW(t.subarray(0,a+1))}catch(D){v&&(v.cursorFn||v.describeFirst)&&l0(B4),d1(D)}t=t.subarray(a+1),W0=0,O0=null}}async function FX(){if(o0=!1,h0={},N||(N=await dW()),!N)return;if(n.start(),Y.socket)return $?zX():o4();if(N.on("connect",$?zX:o4),Y.path)return N.connect(Y.path);N.ssl=$,N.connect(J[V0],Q[V0]),N.host=Q[V0],N.port=J[V0],V0=(V0+1)%J.length}function EX(){setTimeout(FX,m?m+Q0-NW.now():0)}function o4(){try{$1={},I0=Y.fetch_types,r1=Math.random().toString(36).slice(2),T=1,c.start(),N.on("data",EY),x&&N.setKeepAlive&&N.setKeepAlive(!0,1000*x);let U=fH();l0(U)}catch(U){i4(U)}}function i4(U){if(i0.queue===Z.connecting&&Y.host[k0+1])return;d1(U);while(B.length)g8(B.shift(),U)}function d1(U){b0&&(b0.destroy(U),b0=null),v&&g8(v,U),c0&&(g8(c0,U),c0=null)}function g8(U,D){if(U.reserve)return U.reject(D);if(!D||typeof D!=="object")D=new Error(D);"query"in D||"parameters"in D||Object.defineProperties(D,{stack:{value:D.stack+U.origin.replace(/.*\n/,`
67
+ `),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(D)}function VY(){return z4||(!i0.reserved&&_(i0),!i0.reserved&&!c0&&!v&&B.length===0?(C2(),new Promise((U)=>N&&N.readyState!=="closed"?N.once("close",U):U())):z4=new Promise((U)=>P1=U))}function C2(){if(o0=!0,b0||v||c0||B.length)i4(f0.connection("CONNECTION_DESTROYED",Y));if(clearImmediate(A0),N)N.removeListener("data",EY),N.removeListener("connect",o4),N.readyState==="open"&&N.end(d().X().end());P1&&(P1(),z4=P1=null)}async function VX(U){if(t=Buffer.alloc(0),W0=0,O0=null,clearImmediate(A0),N.removeListener("data",EY),N.removeListener("connect",o4),q.cancel(),c.cancel(),n.cancel(),N.removeAllListeners(),N=null,c0)return EX();!U&&(v||B.length)&&i4(f0.connection("CONNECTION_CLOSED",Y,N)),m=NW.now(),U&&Y.shared.retries++,Q0=(typeof h==="function"?h(Y.shared.retries):h)*1000,G(i0,f0.connection("CONNECTION_CLOSED",Y,N))}function rW(U,D=U[0]){(D===68?sW:D===100?IH:D===65?LH:D===83?tW:D===90?aW:D===67?eW:D===50?OX:D===49?YH:D===116?ZH:D===84?XH:D===82?_H:D===110?QH:D===75?zH:D===69?OH:D===115?MH:D===51?AH:D===71?RH:D===78?BH:D===72?wH:D===99?KH:D===73?TH:D===86?CH:D===118?qH:D===87?NH:jH)(U)}function sW(U){let D=7,l,H0,C0,n0=v.isRaw?new Array(v.statement.columns.length):{};for(let e0=0;e0<v.statement.columns.length;e0++)H0=v.statement.columns[e0],l=U.readInt32BE(D),D+=4,C0=l===-1?null:v.isRaw===!0?U.subarray(D,D+=l):H0.parser===void 0?U.toString("utf8",D,D+=l):H0.parser.array===!0?H0.parser(U.toString("utf8",D+1,D+=l)):H0.parser(U.toString("utf8",D,D+=l)),v.isRaw?n0[e0]=v.isRaw===!0?C0:O.value.from?O.value.from(C0,H0):C0:n0[H0.name]=O.value.from?O.value.from(C0,H0):C0;v.forEachFn?v.forEachFn(O.row.from?O.row.from(n0):n0,p):p[v0++]=O.row.from?O.row.from(n0):n0}function tW(U){let[D,l]=U.toString("utf8",5,U.length-1).split(d.N);if(h0[D]=l,Y.parameters[D]!==l)Y.parameters[D]=l,R&&R(D,l)}function aW(U){if(v&&v.options.simple&&v.resolve(j1||p),v=j1=null,p=new d4,n.cancel(),c0){if(g){if(!h0.in_hot_standby||!h0.default_transaction_read_only)return VH();else if(EH(g,h0))return C2()}if(I0)return c0.reserve&&(c0=null),UH();c0&&!c0.reserve&&T2(c0),Y.shared.retries=k0=0,c0=null;return}while(B.length&&(v=B.shift())&&(v.active=!0,v.cancelled))BW(Y).cancel(v.state,v.cancelled.resolve,v.cancelled.reject);if(v)return;i0.reserved?!i0.reserved.release&&U[5]===73?z4?C2():(i0.reserved=null,X(i0)):i0.reserved():z4?C2():X(i0)}function eW(U){v0=0;for(let D=U.length-1;D>0;D--){if(U[D]===32&&U[D+1]<58&&p.count===null)p.count=+U.toString("utf8",D+1,U.length-1);if(U[D-1]>=65){p.command=U.toString("utf8",5,D),p.state=C;break}}if(B2&&(B2(),B2=null),p.command==="BEGIN"&&W!==1&&!i0.reserved)return d1(f0.generic("UNSAFE_TRANSACTION","Only use sql.begin, sql.reserved or max: 1"));if(v.options.simple)return OX();if(v.cursorFn)p.count&&v.cursorFn(p),l0(B4);v.resolve(p)}function YH(){v.parsing=!1}function OX(){!p.statement&&(p.statement=v.statement),p.columns=v.statement.columns}function ZH(U){let D=U.readUInt16BE(5);for(let l=0;l<D;++l)!v.statement.types[l]&&(v.statement.types[l]=U.readUInt32BE(7+l*4));v.prepare&&($1[v.signature]=v.statement),v.describeFirst&&!v.onlyDescribe&&(l0(y8(v)),v.describeFirst=!1)}function XH(U){if(p.command)j1=j1||[p],j1.push(p=new d4),p.count=null,v.statement.columns=null;let D=U.readUInt16BE(5),l=7,H0;v.statement.columns=Array(D);for(let C0=0;C0<D;++C0){H0=l;while(U[l++]!==0);let n0=U.readUInt32BE(l),e0=U.readUInt16BE(l+4),U4=U.readUInt32BE(l+6);v.statement.columns[C0]={name:O.column.from?O.column.from(U.toString("utf8",H0,l-1)):U.toString("utf8",H0,l-1),parser:F[U4],table:n0,number:e0,type:U4},l+=18}if(p.statement=v.statement,v.onlyDescribe)return v.resolve(v.statement),l0(B4)}async function _H(U,D=U.readUInt32BE(5)){(D===3?GH:D===5?$H:D===10?WH:D===11?HH:D===12?JH:D!==0?PH:w2)(U,D)}async function GH(){let U=await OY();l0(d().p().str(U).z(1).end())}async function $H(U){let D="md5"+await KW(Buffer.concat([Buffer.from(await KW(await OY()+H)),U.subarray(9)]));l0(d().p().str(D).z(1).end())}async function WH(){u1=(await S8.randomBytes(18)).toString("base64"),d().p().str("SCRAM-SHA-256"+d.N);let U=d.i;l0(d.inc(4).str("n,,n=*,r="+u1).i32(d.i-U-4,U).end())}async function HH(U){let D=U.toString("utf8",9).split(",").reduce((e0,U4)=>(e0[U4[0]]=U4.slice(2),e0),{}),l=await S8.pbkdf2Sync(await OY(),Buffer.from(D.s,"base64"),parseInt(D.i),32,"sha256"),H0=await ZY(l,"Client Key"),C0="n=*,r="+u1+",r="+D.r+",s="+D.s+",i="+D.i+",c=biws,r="+D.r;B0=(await ZY(await ZY(l,"Server Key"),C0)).toString("base64");let n0="c=biws,r="+D.r+",p="+GE(H0,Buffer.from(await ZY(await _E(H0),C0))).toString("base64");l0(d().p().str(n0).end())}function JH(U){if(U.toString("utf8",9).split(d.N,1)[0].slice(2)===B0)return;d1(f0.generic("SASL_SIGNATURE_MISMATCH","The server did not return the correct signature")),N.destroy()}function OY(){return Promise.resolve(typeof Y.pass==="function"?Y.pass():Y.pass)}function QH(){if(p.statement=v.statement,p.statement.columns=[],v.onlyDescribe)return v.resolve(v.statement),l0(B4)}function zH(U){C.pid=U.readUInt32BE(5),C.secret=U.readUInt32BE(9)}async function UH(){I0=!1,(await new q1([`
68
68
  select b.oid, b.typarray
69
69
  from pg_catalog.pg_type a
70
70
  left join pg_catalog.pg_type b on b.oid = a.typelem
71
71
  where a.typcategory = 'A'
72
72
  group by b.oid, b.typarray
73
73
  order by b.oid
74
- `],[],P2)).forEach(({oid:O,typarray:l})=>IH(O,l))}function IH(F,O){if(!!Z.parsers[O]&&!!Z.serializers[O])return;let l=Z.parsers[F];Z.shared.typeArrayMap[F]=O,Z.parsers[O]=(W0)=>PW(W0,l,O),Z.parsers[O].array=!0,Z.serializers[O]=(W0)=>jW(W0,Z.serializers[F],Z,O)}function BH(F,O){return F==="read-write"&&O.default_transaction_read_only==="on"||F==="read-only"&&O.default_transaction_read_only==="off"||F==="primary"&&O.in_hot_standby==="on"||F==="standby"&&O.in_hot_standby==="off"||F==="prefer-standby"&&O.in_hot_standby==="off"&&Z.host[k0]}function KH(){let F=new S1([`
74
+ `],[],T2)).forEach(({oid:D,typarray:l})=>FH(D,l))}function FH(U,D){if(!!Y.parsers[D]&&!!Y.serializers[D])return;let l=Y.parsers[U];Y.shared.typeArrayMap[U]=D,Y.parsers[D]=(H0)=>AW(H0,l,D),Y.parsers[D].array=!0,Y.serializers[D]=(H0)=>MW(H0,Y.serializers[U],Y,D)}function EH(U,D){return U==="read-write"&&D.default_transaction_read_only==="on"||U==="read-only"&&D.default_transaction_read_only==="off"||U==="primary"&&D.in_hot_standby==="on"||U==="standby"&&D.in_hot_standby==="off"||U==="prefer-standby"&&D.in_hot_standby==="off"&&Y.host[k0]}function VH(){let U=new q1([`
75
75
  show transaction_read_only;
76
76
  select pg_catalog.pg_is_in_recovery()
77
- `],[],P2,null,{simple:!0});F.resolve=([[O],[l]])=>{h0.default_transaction_read_only=O.transaction_read_only,h0.in_hot_standby=l.pg_is_in_recovery?"on":"off"},F.execute()}function CH(F){v&&(v.cursorFn||v.describeFirst)&&l0(q4);let O=f0.postgres(oY(F));v&&v.retried?d1(v.retried):v&&v.prepared&&tF.has(O.routine)?TH(v,O):d1(O)}function TH(F,O){delete W1[F.signature],F.retried=O,P2(F)}function qH(F){if(!N)return;let O=9;while(F[O++]!==0);N(F.toString("utf8",9,O-1),F.toString("utf8",O,F.length-1))}async function jH(){try{let F=await Promise.resolve(v.cursorFn(p));v0=0,F===I2?l0(cH(v.portal)):(p=new l4,l0(CX("",v.cursorRows)))}catch(F){l0(q4),v.reject(F)}}function PH(){p.count&&v.cursorFn(p),v.resolve(p)}function SH(){b0=new iY.Writable({autoDestroy:!0,write(F,O,l){w.write(d().d().raw(F).end(),l)},destroy(F,O){O(F),w.write(d().f().str(F+d.N).end()),b0=null},final(F){w.write(d().c().end()),j2=F}}),v.resolve(b0)}function vH(){b0=new iY.Readable({read(){w.resume()}}),v.resolve(b0)}function xH(){b0=new iY.Duplex({autoDestroy:!0,read(){w.resume()},write(F,O,l){w.write(d().d().raw(F).end(),l)},destroy(F,O){O(F),w.write(d().f().str(F+d.N).end()),b0=null},final(F){w.write(d().c().end()),j2=F}}),v.resolve(b0)}function fH(F){b0&&(b0.push(F.subarray(5))||w.pause())}function hH(){b0&&b0.push(null),b0=null}function kH(F){V?V(oY(F)):console.log(oY(F))}function bH(){}function yH(){d1(f0.notSupported("FunctionCallResponse"))}function gH(){d1(f0.notSupported("NegotiateProtocolVersion"))}function pH(F){console.error("Postgres.js : Unknown Message:",F[0])}function mH(F,O){console.error("Postgres.js : Unknown Auth:",O)}function uH(F,O,l="",W0=""){let T0,n0;return d().B().str(W0+d.N).str(l+d.N).i16(0).i16(F.length),F.forEach((Z1,F4)=>{if(Z1===null)return d.i32(4294967295);n0=O[F4],F[F4]=Z1=n0 in Z.serializers?Z.serializers[n0](Z1):""+Z1,T0=d.i,d.inc(4).str(Z1).i32(d.i-T0-4,T0)}),d.i16(0),d.end()}function KX(F,O,l,W0=""){return d().P().str(W0+d.N).str(F+d.N).i16(O.length),O.forEach((T0,n0)=>d.i32(l[n0]||0)),d.end()}function dH(F,O=""){return d().D().str(F).str(O+d.N).end()}function CX(F="",O=0){return Buffer.concat([d().E().str(F+d.N).i32(O).end(),fW])}function cH(F=""){return Buffer.concat([d().C().str("P").str(F+d.N).end(),d().S().end()])}function lH(){return s||d().inc(4).i16(3).z(2).str(Object.entries(Object.assign({user:H,database:z,client_encoding:"UTF8"},Z.connection)).filter(([,F])=>F).map(([F,O])=>F+d.N+O).join(d.N)).z(2).end(0)}}function oY(Z){let Y={},X=5;for(let G=5;G<Z.length-1;G++)if(Z[G]===0)Y[eF[Z[X]]]=Z.toString("utf8",X+1,G),X=G+1;return Y}function hW(Z){return S8.createHash("md5").update(Z).digest("hex")}function JZ(Z,Y){return S8.createHmac("sha256",Z).update(Y).digest()}function ZE(Z){return S8.createHash("sha256").update(Z).digest()}function YE(Z,Y){let X=Math.max(Z.length,Y.length),G=Buffer.allocUnsafe(X);for(let _=0;_<X;_++)G[_]=Z[_]^Y[_];return G}function nY(Z,Y){if(Y=typeof Y==="function"?Y():Y,!Y)return{cancel:K2,start:K2};let X;return{cancel(){X&&(clearTimeout(X),X=null)},start(){X&&clearTimeout(X),X=setTimeout(G,Y*1000,arguments)}};function G(_){Z.apply(null,_),X=null}}var bW=()=>{};function sY(Z,Y){let X=new Map,G="postgresjs_"+Math.random().toString(36).slice(2),_={},$,W,H=!1,Q=U.sql=Z({...Y,transform:{column:{},value:{},row:{}},max:1,fetch_types:!1,idle_timeout:null,max_lifetime:null,connection:{...Y.connection,replication:"database"},onclose:async function(){if(H)return;W=null,_.pid=_.secret=void 0,D(await V(Q,G,Y.publications)),X.forEach((R)=>R.forEach(({onsubscribe:b})=>b()))},no_subscribe:!0}),J=Q.end,z=Q.close;return Q.end=async()=>{return H=!0,W&&await new Promise((R)=>(W.once("close",R),W.end())),J()},Q.close=async()=>{return W&&await new Promise((R)=>(W.once("close",R),W.end())),z()},U;async function U(R,b,x=bW,h=bW){if(R=_E(R),!$)$=V(Q,G,Y.publications);let g={fn:b,onsubscribe:x},K=X.has(R)?X.get(R).add(g):X.set(R,new Set([g])).get(R),B=()=>{K.delete(g),K.size===0&&X.delete(R)};return $.then((T)=>{return D(T),x(),W&&W.on("error",h),{unsubscribe:B,state:_,sql:Q}})}function D(R){W=R.stream,_.pid=R.state.pid,_.secret=R.state.secret}async function V(R,b,x){if(!x)throw new Error("Missing publication names");let h=await R.unsafe(`CREATE_REPLICATION_SLOT ${b} TEMPORARY LOGICAL pgoutput NOEXPORT_SNAPSHOT`),[g]=h,K=await R.unsafe(`START_REPLICATION SLOT ${b} LOGICAL ${g.consistent_point} (proto_version '1', publication_names '${x}')`).writable(),B={lsn:Buffer.concat(g.consistent_point.split("/").map((w)=>Buffer.from(("00000000"+w).slice(-8),"hex")))};return K.on("data",q),K.on("error",T),K.on("close",R.close),{stream:K,state:h.state};function T(w){console.error("Unexpected error during logical streaming - reconnecting",w)}function q(w){if(w[0]===119)GE(w.subarray(25),B,R.options.parsers,c,Y.transform);else if(w[0]===107&&w[17])B.lsn=w.subarray(1,9),n()}function c(w,s){let p=s.relation.schema+"."+s.relation.table;N("*",w,s),N("*:"+p,w,s),s.relation.keys.length&&N("*:"+p+"="+s.relation.keys.map((a)=>w[a.name]),w,s),N(s.command,w,s),N(s.command+":"+p,w,s),s.relation.keys.length&&N(s.command+":"+p+"="+s.relation.keys.map((a)=>w[a.name]),w,s)}function n(){let w=Buffer.alloc(34);w[0]=114,w.fill(B.lsn,1),w.writeBigInt64BE(BigInt(Date.now()-Date.UTC(2000,0,1))*BigInt(1000),25),K.write(w)}}function N(R,b,x){X.has(R)&&X.get(R).forEach(({fn:h})=>h(b,x,R))}}function XE(Z){return new Date(Date.UTC(2000,0,1)+Number(Z/BigInt(1000)))}function GE(Z,Y,X,G,_){let $=(W,[H,Q])=>(W[H.charCodeAt(0)]=Q,W);Object.entries({R:(W)=>{let H=1,Q=Y[W.readUInt32BE(H)]={schema:W.toString("utf8",H+=4,H=W.indexOf(0,H))||"pg_catalog",table:W.toString("utf8",H+1,H=W.indexOf(0,H+1)),columns:Array(W.readUInt16BE(H+=2)),keys:[]};H+=2;let J=0,z;while(H<W.length)z=Q.columns[J++]={key:W[H++],name:_.column.from?_.column.from(W.toString("utf8",H,H=W.indexOf(0,H))):W.toString("utf8",H,H=W.indexOf(0,H)),type:W.readUInt32BE(H+=1),parser:X[W.readUInt32BE(H)],atttypmod:W.readUInt32BE(H+=4)},z.key&&Q.keys.push(z),H+=4},Y:()=>{},O:()=>{},B:(W)=>{Y.date=XE(W.readBigInt64BE(9)),Y.lsn=W.subarray(1,9)},I:(W)=>{let H=1,Q=Y[W.readUInt32BE(H)],{row:J}=QZ(W,Q.columns,H+=7,_);G(J,{command:"insert",relation:Q})},D:(W)=>{let H=1,Q=Y[W.readUInt32BE(H)];H+=4;let J=W[H]===75;G(J||W[H]===79?QZ(W,Q.columns,H+=3,_).row:null,{command:"delete",relation:Q,key:J})},U:(W)=>{let H=1,Q=Y[W.readUInt32BE(H)];H+=4;let J=W[H]===75,z=J||W[H]===79?QZ(W,Q.columns,H+=3,_):null;z&&(H=z.i);let{row:U}=QZ(W,Q.columns,H+3,_);G(U,{command:"update",relation:Q,key:J,old:z&&z.row})},T:()=>{},C:()=>{}}).reduce($,{})[Z[0]](Z)}function QZ(Z,Y,X,G){let _,$,W,H=G.raw?new Array(Y.length):{};for(let Q=0;Q<Y.length;Q++)_=Z[X++],$=Y[Q],W=_===110?null:_===117?void 0:$.parser===void 0?Z.toString("utf8",X+4,X+=4+Z.readUInt32BE(X)):$.parser.array===!0?$.parser(Z.toString("utf8",X+5,X+=4+Z.readUInt32BE(X))):$.parser(Z.toString("utf8",X+4,X+=4+Z.readUInt32BE(X))),G.raw?H[Q]=G.raw===!0?W:G.value.from?G.value.from(W,$):W:H[$.name]=G.value.from?G.value.from(W,$):W;return{i:X,row:G.row.from?G.row.from(H):H}}function _E(Z){let Y=Z.match(/^(\*|insert|update|delete)?:?([^.]+?\.?[^=]+)?=?(.+)?/i)||[];if(!Y)throw new Error("Malformed subscribe pattern: "+Z);let[,X,G,_]=Y;return(X||"*")+(G?":"+(G.indexOf(".")===-1?"public."+G:G):"")+(_?"="+_:"")}import yW from"stream";function aY(Z,Y,X=393216){return new Promise(async(G,_)=>{await Z.begin(async($)=>{let W;!Y&&([{oid:Y}]=await $`select lo_creat(-1) as oid`);let[{fd:H}]=await $`select lo_open(${Y}, ${X}) as fd`,Q={writable:z,readable:J,close:()=>$`select lo_close(${H})`.then(W),tell:()=>$`select lo_tell64(${H})`,read:(U)=>$`select loread(${H}, ${U}) as data`,write:(U)=>$`select lowrite(${H}, ${U})`,truncate:(U)=>$`select lo_truncate64(${H}, ${U})`,seek:(U,D=0)=>$`select lo_lseek64(${H}, ${U}, ${D})`,size:()=>$`
77
+ `],[],T2,null,{simple:!0});U.resolve=([[D],[l]])=>{h0.default_transaction_read_only=D.transaction_read_only,h0.in_hot_standby=l.pg_is_in_recovery?"on":"off"},U.execute()}function OH(U){v&&(v.cursorFn||v.describeFirst)&&l0(B4);let D=f0.postgres(y5(U));v&&v.retried?d1(v.retried):v&&v.prepared&&ZE.has(D.routine)?DH(v,D):d1(D)}function DH(U,D){delete $1[U.signature],U.retried=D,T2(U)}function LH(U){if(!w)return;let D=9;while(U[D++]!==0);w(U.toString("utf8",9,D-1),U.toString("utf8",D,U.length-1))}async function MH(){try{let U=await Promise.resolve(v.cursorFn(p));v0=0,U===A2?l0(xH(v.portal)):(p=new d4,l0(LX("",v.cursorRows)))}catch(U){l0(B4),v.reject(U)}}function AH(){p.count&&v.cursorFn(p),v.resolve(p)}function RH(){b0=new b5.Writable({autoDestroy:!0,write(U,D,l){N.write(d().d().raw(U).end(),l)},destroy(U,D){D(U),N.write(d().f().str(U+d.N).end()),b0=null},final(U){N.write(d().c().end()),B2=U}}),v.resolve(b0)}function wH(){b0=new b5.Readable({read(){N.resume()}}),v.resolve(b0)}function NH(){b0=new b5.Duplex({autoDestroy:!0,read(){N.resume()},write(U,D,l){N.write(d().d().raw(U).end(),l)},destroy(U,D){D(U),N.write(d().f().str(U+d.N).end()),b0=null},final(U){N.write(d().c().end()),B2=U}}),v.resolve(b0)}function IH(U){b0&&(b0.push(U.subarray(5))||N.pause())}function KH(){b0&&b0.push(null),b0=null}function BH(U){L?L(y5(U)):console.log(y5(U))}function TH(){}function CH(){d1(f0.notSupported("FunctionCallResponse"))}function qH(){d1(f0.notSupported("NegotiateProtocolVersion"))}function jH(U){console.error("Postgres.js : Unknown Message:",U[0])}function PH(U,D){console.error("Postgres.js : Unknown Auth:",D)}function SH(U,D,l="",H0=""){let C0,n0;return d().B().str(H0+d.N).str(l+d.N).i16(0).i16(U.length),U.forEach((e0,U4)=>{if(e0===null)return d.i32(4294967295);n0=D[U4],U[U4]=e0=n0 in Y.serializers?Y.serializers[n0](e0):""+e0,C0=d.i,d.inc(4).str(e0).i32(d.i-C0-4,C0)}),d.i16(0),d.end()}function DX(U,D,l,H0=""){return d().P().str(H0+d.N).str(U+d.N).i16(D.length),D.forEach((C0,n0)=>d.i32(l[n0]||0)),d.end()}function vH(U,D=""){return d().D().str(U).str(D+d.N).end()}function LX(U="",D=0){return Buffer.concat([d().E().str(U+d.N).i32(D).end(),IW])}function xH(U=""){return Buffer.concat([d().C().str("P").str(U+d.N).end(),d().S().end()])}function fH(){return s||d().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,D])=>U+d.N+D).join(d.N)).z(2).end(0)}}function y5(Y){let Z={},X=5;for(let _=5;_<Y.length-1;_++)if(Y[_]===0)Z[XE[Y[X]]]=Y.toString("utf8",X+1,_),X=_+1;return Z}function KW(Y){return S8.createHash("md5").update(Y).digest("hex")}function ZY(Y,Z){return S8.createHmac("sha256",Y).update(Z).digest()}function _E(Y){return S8.createHash("sha256").update(Y).digest()}function GE(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 g5(Y,Z){if(Z=typeof Z==="function"?Z():Z,!Z)return{cancel:w2,start:w2};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 TW=()=>{};function m5(Y,Z){let X=new Map,_="postgresjs_"+Math.random().toString(36).slice(2),G={},$,W,H=!1,Q=F.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;W=null,G.pid=G.secret=void 0,O(await L(Q,_,Z.publications)),X.forEach((R)=>R.forEach(({onsubscribe:b})=>b()))},no_subscribe:!0}),J=Q.end,z=Q.close;return Q.end=async()=>{return H=!0,W&&await new Promise((R)=>(W.once("close",R),W.end())),J()},Q.close=async()=>{return W&&await new Promise((R)=>(W.once("close",R),W.end())),z()},F;async function F(R,b,x=TW,h=TW){if(R=HE(R),!$)$=L(Q,_,Z.publications);let g={fn:b,onsubscribe:x},B=X.has(R)?X.get(R).add(g):X.set(R,new Set([g])).get(R),K=()=>{B.delete(g),B.size===0&&X.delete(R)};return $.then((C)=>{return O(C),x(),W&&W.on("error",h),{unsubscribe:K,state:G,sql:Q}})}function O(R){W=R.stream,G.pid=R.state.pid,G.secret=R.state.secret}async function L(R,b,x){if(!x)throw new Error("Missing publication names");let h=await R.unsafe(`CREATE_REPLICATION_SLOT ${b} TEMPORARY LOGICAL pgoutput NOEXPORT_SNAPSHOT`),[g]=h,B=await R.unsafe(`START_REPLICATION SLOT ${b} LOGICAL ${g.consistent_point} (proto_version '1', publication_names '${x}')`).writable(),K={lsn:Buffer.concat(g.consistent_point.split("/").map((N)=>Buffer.from(("00000000"+N).slice(-8),"hex")))};return B.on("data",q),B.on("error",C),B.on("close",R.close),{stream:B,state:h.state};function C(N){console.error("Unexpected error during logical streaming - reconnecting",N)}function q(N){if(N[0]===119)WE(N.subarray(25),K,R.options.parsers,c,Z.transform);else if(N[0]===107&&N[17])K.lsn=N.subarray(1,9),n()}function c(N,s){let p=s.relation.schema+"."+s.relation.table;w("*",N,s),w("*:"+p,N,s),s.relation.keys.length&&w("*:"+p+"="+s.relation.keys.map((t)=>N[t.name]),N,s),w(s.command,N,s),w(s.command+":"+p,N,s),s.relation.keys.length&&w(s.command+":"+p+"="+s.relation.keys.map((t)=>N[t.name]),N,s)}function n(){let N=Buffer.alloc(34);N[0]=114,N.fill(K.lsn,1),N.writeBigInt64BE(BigInt(Date.now()-Date.UTC(2000,0,1))*BigInt(1000),25),B.write(N)}}function w(R,b,x){X.has(R)&&X.get(R).forEach(({fn:h})=>h(b,x,R))}}function $E(Y){return new Date(Date.UTC(2000,0,1)+Number(Y/BigInt(1000)))}function WE(Y,Z,X,_,G){let $=(W,[H,Q])=>(W[H.charCodeAt(0)]=Q,W);Object.entries({R:(W)=>{let H=1,Q=Z[W.readUInt32BE(H)]={schema:W.toString("utf8",H+=4,H=W.indexOf(0,H))||"pg_catalog",table:W.toString("utf8",H+1,H=W.indexOf(0,H+1)),columns:Array(W.readUInt16BE(H+=2)),keys:[]};H+=2;let J=0,z;while(H<W.length)z=Q.columns[J++]={key:W[H++],name:G.column.from?G.column.from(W.toString("utf8",H,H=W.indexOf(0,H))):W.toString("utf8",H,H=W.indexOf(0,H)),type:W.readUInt32BE(H+=1),parser:X[W.readUInt32BE(H)],atttypmod:W.readUInt32BE(H+=4)},z.key&&Q.keys.push(z),H+=4},Y:()=>{},O:()=>{},B:(W)=>{Z.date=$E(W.readBigInt64BE(9)),Z.lsn=W.subarray(1,9)},I:(W)=>{let H=1,Q=Z[W.readUInt32BE(H)],{row:J}=XY(W,Q.columns,H+=7,G);_(J,{command:"insert",relation:Q})},D:(W)=>{let H=1,Q=Z[W.readUInt32BE(H)];H+=4;let J=W[H]===75;_(J||W[H]===79?XY(W,Q.columns,H+=3,G).row:null,{command:"delete",relation:Q,key:J})},U:(W)=>{let H=1,Q=Z[W.readUInt32BE(H)];H+=4;let J=W[H]===75,z=J||W[H]===79?XY(W,Q.columns,H+=3,G):null;z&&(H=z.i);let{row:F}=XY(W,Q.columns,H+3,G);_(F,{command:"update",relation:Q,key:J,old:z&&z.row})},T:()=>{},C:()=>{}}).reduce($,{})[Y[0]](Y)}function XY(Y,Z,X,_){let G,$,W,H=_.raw?new Array(Z.length):{};for(let Q=0;Q<Z.length;Q++)G=Y[X++],$=Z[Q],W=G===110?null:G===117?void 0:$.parser===void 0?Y.toString("utf8",X+4,X+=4+Y.readUInt32BE(X)):$.parser.array===!0?$.parser(Y.toString("utf8",X+5,X+=4+Y.readUInt32BE(X))):$.parser(Y.toString("utf8",X+4,X+=4+Y.readUInt32BE(X))),_.raw?H[Q]=_.raw===!0?W:_.value.from?_.value.from(W,$):W:H[$.name]=_.value.from?_.value.from(W,$):W;return{i:X,row:_.row.from?_.row.from(H):H}}function HE(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 CW from"stream";function u5(Y,Z,X=393216){return new Promise(async(_,G)=>{await Y.begin(async($)=>{let W;!Z&&([{oid:Z}]=await $`select lo_creat(-1) as oid`);let[{fd:H}]=await $`select lo_open(${Z}, ${X}) as fd`,Q={writable:z,readable:J,close:()=>$`select lo_close(${H})`.then(W),tell:()=>$`select lo_tell64(${H})`,read:(F)=>$`select loread(${H}, ${F}) as data`,write:(F)=>$`select lowrite(${H}, ${F})`,truncate:(F)=>$`select lo_truncate64(${H}, ${F})`,seek:(F,O=0)=>$`select lo_lseek64(${H}, ${F}, ${O})`,size:()=>$`
78
78
  select
79
79
  lo_lseek64(${H}, location, 0) as position,
80
80
  seek.size
@@ -84,10 +84,10 @@ params: ${Y}`);if(this.query=Z,this.params=Y,this.cause=X,Error.captureStackTrac
84
84
  tell.location
85
85
  from (select lo_tell64($1) as location) tell
86
86
  ) seek
87
- `};return G(Q),new Promise(async(U)=>W=U);async function J({highWaterMark:U=16384,start:D=0,end:V=1/0}={}){let N=V-D;return D&&await Q.seek(D),new yW.Readable({highWaterMark:U,async read(R){let b=R>N?R-N:R;N-=R;let[{data:x}]=await Q.read(b);if(this.push(x),x.length<R)this.push(null)}})}async function z({highWaterMark:U=16384,start:D=0}={}){return D&&await Q.seek(D),new yW.Writable({highWaterMark:U,write(V,N,R){Q.write(V).then(()=>R(),R)}})}}).catch(_)})}Object.assign(zZ,{PostgresError:B2,toPascal:d4,pascal:cY,toCamel:u4,camel:dY,toKebab:c4,kebab:lY,fromPascal:q8,fromCamel:T8,fromKebab:j8,BigInt:{to:20,from:[20],parse:(Z)=>BigInt(Z),serialize:(Z)=>Z.toString()}});var C2=zZ;function zZ(Z,Y){let X=HE(Z,Y),G=X.no_subscribe||sY(zZ,{...X}),_=!1,$=I1(),W=I1(),H=I1(),Q=I1(),J=I1(),z=I1(),U=I1(),D=I1(),V={connecting:W,reserved:H,closed:Q,ended:J,open:z,busy:U,full:D},N=[...Array(X.max)].map(()=>rY(X,V,{onopen:W1,onend:h0,onclose:s1})),R=b(c);return Object.assign(R,{get parameters(){return X.parameters},largeObject:aY.bind(null,R),subscribe:G,CLOSE:I2,END:I2,PostgresError:B2,options:X,reserve:g,listen:x,begin:K,close:p,end:s}),R;function b(C){return C.debug=X.debug,Object.entries(X.types).reduce((t,[J0,v0])=>{return t[J0]=(K0)=>new r1(K0,v0.to),t},m),Object.assign($0,{types:m,typed:m,unsafe:L0,notify:h,array:q,json:T,file:k0}),$0;function m(t,J0){return new r1(t,J0)}function $0(t,...J0){return t&&Array.isArray(t.raw)?new S1(t,J0,C,w):typeof t==="string"&&!J0.length?new P8(X.transform.column.to?X.transform.column.to(t):t):new _Z(t,J0)}function L0(t,J0=[],v0={}){return arguments.length===2&&!Array.isArray(J0)&&(v0=J0,J0=[]),new S1([t],J0,C,w,{prepare:!1,...v0,simple:"simple"in v0?v0.simple:J0.length===0})}function k0(t,J0=[],v0={}){return arguments.length===2&&!Array.isArray(J0)&&(v0=J0,J0=[]),new S1([],J0,(A0)=>{WE.readFile(t,"utf8",(i0,D0)=>{if(i0)return A0.reject(i0);A0.strings=[D0],C(A0)})},w,{...v0,simple:"simple"in v0?v0.simple:J0.length===0})}}async function x(C,m,$0){let L0={fn:m,onlisten:$0},k0=x.sql||(x.sql=zZ({...X,max:1,idle_timeout:null,max_lifetime:null,fetch_types:!1,onclose(){Object.entries(x.channels).forEach(([A0,{listeners:i0}])=>{delete x.channels[A0],Promise.all(i0.map((D0)=>x(A0,D0.fn,D0.onlisten).catch(()=>{})))})},onnotify(A0,i0){A0 in x.channels&&x.channels[A0].listeners.forEach((D0)=>D0.fn(i0))}})),t=x.channels||(x.channels={});if(C in t){t[C].listeners.push(L0);let A0=await t[C].result;return L0.onlisten&&L0.onlisten(),{state:A0.state,unlisten:K0}}t[C]={result:k0`listen ${k0.unsafe('"'+C.replace(/"/g,'""')+'"')}`,listeners:[L0]};let v0=await t[C].result;return L0.onlisten&&L0.onlisten(),{state:v0.state,unlisten:K0};async function K0(){if(C in t===!1)return;if(t[C].listeners=t[C].listeners.filter((A0)=>A0!==L0),t[C].listeners.length)return;return delete t[C],k0`unlisten ${k0.unsafe('"'+C.replace(/"/g,'""')+'"')}`}}async function h(C,m){return await R`select pg_notify(${C}, ${""+m})`}async function g(){let C=I1(),m=z.length?z.shift():await new Promise((k0,t)=>{let J0={reserve:k0,reject:t};$.push(J0),Q.length&&I0(Q.shift(),J0)});B(m,H),m.reserved=()=>C.length?m.execute(C.shift()):B(m,H),m.reserved.release=!0;let $0=b(L0);return $0.release=()=>{m.reserved=null,W1(m)},$0;function L0(k0){m.queue===D?C.push(k0):m.execute(k0)||B(m,D)}}async function K(C,m){!m&&(m=C,C="");let $0=I1(),L0=0,k0,t=null;try{return await R.unsafe("begin "+C.replace(/[^a-z ]/ig,""),[],{onexecute:v0}).execute(),await Promise.race([J0(k0,m),new Promise((K0,A0)=>k0.onclose=A0)])}catch(K0){throw K0}async function J0(K0,A0,i0){let D0=b(b0);D0.savepoint=U4,D0.prepare=(R0)=>t=R0.replace(/[^a-z0-9$-_. ]/gi);let v1,c0;i0&&await D0`savepoint ${D0(i0)}`;try{if(c0=await new Promise((R0,x1)=>{let u1=A0(D0);Promise.resolve(Array.isArray(u1)?Promise.all(u1):u1).then(R0,x1)}),v1)throw v1}catch(R0){throw await(i0?D0`rollback to ${D0(i0)}`:D0`rollback`),R0 instanceof B2&&R0.code==="25P02"&&v1||R0}if(!i0)t?await D0`prepare transaction '${D0.unsafe(t)}'`:await D0`commit`;return c0;function U4(R0,x1){if(R0&&Array.isArray(R0.raw))return U4((u1)=>u1.apply(u1,arguments));return arguments.length===1&&(x1=R0,R0=null),J0(K0,x1,"s"+L0+++(R0?"_"+R0:""))}function b0(R0){R0.catch((x1)=>v1||(v1=x1)),K0.queue===D?$0.push(R0):K0.execute(R0)||B(K0,D)}}function v0(K0){k0=K0,B(K0,H),K0.reserved=()=>$0.length?K0.execute($0.shift()):B(K0,H)}}function B(C,m){return C.queue.remove(C),m.push(C),C.queue=m,m===z?C.idleTimer.start():C.idleTimer.cancel(),C}function T(C){return new r1(C,3802)}function q(C,m){if(!Array.isArray(C))return q(Array.from(arguments));return new r1(C,m||(C.length?XZ(C)||25:0),X.shared.typeArrayMap)}function c(C){if(_)return C.reject(f0.connection("CONNECTION_ENDED",X,X));if(z.length)return n(z.shift(),C);if(Q.length)return I0(Q.shift(),C);U.length?n(U.shift(),C):$.push(C)}function n(C,m){return C.execute(m)?B(C,U):B(C,D)}function w(C){return new Promise((m,$0)=>{C.state?C.active?rY(X).cancel(C.state,m,$0):C.cancelled={resolve:m,reject:$0}:($.remove(C),C.cancelled=!0,C.reject(f0.generic("57014","canceling statement due to user request")),m())})}async function s({timeout:C=null}={}){if(_)return _;await 1;let m;return _=Promise.race([new Promise(($0)=>C!==null&&(m=setTimeout(a,C*1000,$0))),Promise.all(N.map(($0)=>$0.end()).concat(x.sql?x.sql.end({timeout:0}):[],G.sql?G.sql.end({timeout:0}):[]))]).then(()=>clearTimeout(m))}async function p(){await Promise.all(N.map((C)=>C.end()))}async function a(C){await Promise.all(N.map((m)=>m.terminate()));while($.length)$.shift().reject(f0.connection("CONNECTION_DESTROYED",X));C()}function I0(C,m){return B(C,W),C.connect(m),C}function h0(C){B(C,J)}function W1(C){if($.length===0)return B(C,z);let m=Math.ceil($.length/(W.length+1)),$0=!0;while($0&&$.length&&m-- >0){let L0=$.shift();if(L0.reserve)return L0.reserve(C);$0=C.execute(L0)}$0?B(C,U):B(C,D)}function s1(C,m){B(C,Q),C.reserved=null,C.onclose&&(C.onclose(m),C.onclose=null),X.onclose&&X.onclose(C.id),$.length&&I0(C,$.shift())}}function HE(Z,Y){if(Z&&Z.shared)return Z;let X=process.env,G=(!Z||typeof Z==="string"?Y:Z)||{},{url:_,multihost:$}=FE(Z),W=[..._.searchParams].reduce((D,[V,N])=>(D[V]=N,D),{}),H=G.hostname||G.host||$||_.hostname||X.PGHOST||"localhost",Q=G.port||_.port||X.PGPORT||5432,J=G.user||G.username||_.username||X.PGUSERNAME||X.PGUSER||EE();G.no_prepare&&(G.prepare=!1),W.sslmode&&(W.ssl=W.sslmode,delete W.sslmode),"timeout"in G&&(console.log("The timeout option is deprecated, use idle_timeout instead"),G.idle_timeout=G.timeout),W.sslrootcert==="system"&&(W.ssl="verify-full");let z=["idle_timeout","connect_timeout","max_lifetime","max_pipeline","backoff","keep_alive"],U={max:10,ssl:!1,idle_timeout:null,connect_timeout:30,max_lifetime:zE,max_pipeline:100,backoff:QE,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:G.path||H.indexOf("/")>-1&&H+"/.s.PGSQL."+Q,database:G.database||G.db||(_.pathname||"").slice(1)||X.PGDATABASE||J,user:J,pass:G.pass||G.password||_.password||X.PGPASSWORD||"",...Object.entries(U).reduce((D,[V,N])=>{let R=V in G?G[V]:(V in W)?W[V]==="disable"||W[V]==="false"?!1:W[V]:X["PG"+V.toUpperCase()]||N;return D[V]=typeof R==="string"&&z.includes(V)?+R:R,D},{}),connection:{application_name:X.PGAPPNAME||"postgres.js",...G.connection,...Object.entries(W).reduce((D,[V,N])=>((V in U)||(D[V]=N),D),{})},types:G.types||{},target_session_attrs:JE(G,_,X),onnotice:G.onnotice,onnotify:G.onnotify,onclose:G.onclose,onparameter:G.onparameter,socket:G.socket,transform:UE(G.transform||{undefined:void 0}),parameters:{},shared:{retries:0,typeArrayMap:{}},...TW(G.types)}}function JE(Z,Y,X){let G=Z.target_session_attrs||Y.searchParams.get("target_session_attrs")||X.PGTARGETSESSIONATTRS;if(!G||["read-write","read-only","primary","standby","prefer-standby"].includes(G))return G;throw new Error("target_session_attrs "+G+" is not supported")}function QE(Z){return(0.5+Math.random()/2)*Math.min(3**Z/100,20)}function zE(){return 60*(30+Math.random()*30)}function UE(Z){return{undefined:Z.undefined,column:{from:typeof Z.column==="function"?Z.column:Z.column&&Z.column.from,to:Z.column&&Z.column.to},value:{from:typeof Z.value==="function"?Z.value:Z.value&&Z.value.from,to:Z.value&&Z.value.to},row:{from:typeof Z.row==="function"?Z.row:Z.row&&Z.row.from,to:Z.row&&Z.row.to}}}function FE(Z){if(!Z||typeof Z!=="string")return{url:{searchParams:new Map}};let Y=Z;Y=Y.slice(Y.indexOf("://")+3).split(/[?/]/)[0],Y=decodeURIComponent(Y.slice(Y.indexOf("@")+1));let X=new URL(Z.replace(Y,Y.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:Y.indexOf(",")>-1&&Y}}function EE(){try{return $E.userInfo().username}catch(Z){return process.env.USERNAME||process.env.USER||process.env.LOGNAME}}class j0{static[E]="SelectionProxyHandler";config;constructor(Z){this.config={...Z}}get(Z,Y){if(Y==="_")return{...Z._,selectedFields:new Proxy(Z._.selectedFields,this)};if(Y===M0)return{...Z[M0],selectedFields:new Proxy(Z[M0].selectedFields,this)};if(typeof Y==="symbol")return Z[Y];let G=(M(Z,S0)?Z._.selectedFields:M(Z,L1)?Z[M0].selectedFields:Z)[Y];if(M(G,f.Aliased)){if(this.config.sqlAliasedBehavior==="sql"&&!G.isSelectionField)return G.sql;let _=G.clone();return _.isSelectionField=!0,_}if(M(G,f)){if(this.config.sqlBehavior==="sql")return G;throw new Error(`You tried to reference "${Y}" 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(G,F0)){if(this.config.alias)return new Proxy(G,new w2(new Proxy(G.table,new A8(this.config.alias,this.config.replaceOriginalName??!1))));return G}if(typeof G!=="object"||G===null)return G;return new Proxy(G,new j0(this.config))}}class gW{constructor(Z,Y){this.unique=Z,this.name=Y}static[E]="PgIndexBuilderOn";on(...Z){return new UZ(Z.map((Y)=>{if(M(Y,f))return Y;Y=Y;let X=new D8(Y.name,!!Y.keyAsName,Y.columnType,Y.indexConfig);return Y.indexConfig=JSON.parse(JSON.stringify(Y.defaultConfig)),X}),this.unique,!1,this.name)}onOnly(...Z){return new UZ(Z.map((Y)=>{if(M(Y,f))return Y;Y=Y;let X=new D8(Y.name,!!Y.keyAsName,Y.columnType,Y.indexConfig);return Y.indexConfig=Y.defaultConfig,X}),this.unique,!0,this.name)}using(Z,...Y){return new UZ(Y.map((X)=>{if(M(X,f))return X;X=X;let G=new D8(X.name,!!X.keyAsName,X.columnType,X.indexConfig);return X.indexConfig=JSON.parse(JSON.stringify(X.defaultConfig)),G}),this.unique,!0,this.name,Z)}}class UZ{static[E]="PgIndexBuilder";config;constructor(Z,Y,X,G,_="btree"){this.config={name:G,columns:Z,unique:Y,only:X,method:_}}concurrently(){return this.config.concurrently=!0,this}with(Z){return this.config.with=Z,this}where(Z){return this.config.where=Z,this}build(Z){return new pW(this.config,Z)}}class pW{static[E]="PgIndex";config;constructor(Z,Y){this.config={...Z,table:Y}}}function tY(Z){return new gW(!0,Z)}function LE(Z){return(Z.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).map((X)=>X.toLowerCase()).join("_")}function DE(Z){return(Z.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).reduce((X,G,_)=>{let $=_===0?G.toLowerCase():`${G[0].toUpperCase()}${G.slice(1)}`;return X+$},"")}function OE(Z){return Z}class eY{static[E]="CasingCache";cache={};cachedTables={};convert;constructor(Z){this.convert=Z==="snake_case"?LE:Z==="camelCase"?DE:OE}getColumnCasing(Z){if(!Z.keyAsName)return Z.name;let Y=Z.table[P.Symbol.Schema]??"public",X=Z.table[P.Symbol.OriginalName],G=`${Y}.${X}.${Z.name}`;if(!this.cache[G])this.cacheTable(Z.table);return this.cache[G]}cacheTable(Z){let Y=Z[P.Symbol.Schema]??"public",X=Z[P.Symbol.OriginalName],G=`${Y}.${X}`;if(!this.cachedTables[G]){for(let _ of Object.values(Z[P.Symbol.Columns])){let $=`${G}.${_.name}`;this.cache[$]=this.convert(_.name)}this.cachedTables[G]=!0}}clearCache(){this.cache={},this.cachedTables={}}}class v8 extends L1{static[E]="PgViewBase"}class i4{static[E]="PgDialect";casing;constructor(Z){this.casing=new eY(Z?.casing)}async migrate(Z,Y,X){let G=typeof X==="string"?"__drizzle_migrations":X.migrationsTable??"__drizzle_migrations",_=typeof X==="string"?"drizzle":X.migrationsSchema??"drizzle",$=L`
88
- CREATE TABLE IF NOT EXISTS ${L.identifier(_)}.${L.identifier(G)} (
87
+ `};return _(Q),new Promise(async(F)=>W=F);async function J({highWaterMark:F=16384,start:O=0,end:L=1/0}={}){let w=L-O;return O&&await Q.seek(O),new CW.Readable({highWaterMark:F,async read(R){let b=R>w?R-w:R;w-=R;let[{data:x}]=await Q.read(b);if(this.push(x),x.length<R)this.push(null)}})}async function z({highWaterMark:F=16384,start:O=0}={}){return O&&await Q.seek(O),new CW.Writable({highWaterMark:F,write(L,w,R){Q.write(L).then(()=>R(),R)}})}}).catch(G)})}Object.assign(_Y,{PostgresError:R2,toPascal:m4,pascal:h5,toCamel:p4,camel:f5,toKebab:u4,kebab:k5,fromPascal:q8,fromCamel:C8,fromKebab:j8,BigInt:{to:20,from:[20],parse:(Y)=>BigInt(Y),serialize:(Y)=>Y.toString()}});var N2=_Y;function _Y(Y,Z){let X=zE(Y,Z),_=X.no_subscribe||m5(_Y,{...X}),G=!1,$=R1(),W=R1(),H=R1(),Q=R1(),J=R1(),z=R1(),F=R1(),O=R1(),L={connecting:W,reserved:H,closed:Q,ended:J,open:z,busy:F,full:O},w=[...Array(X.max)].map(()=>p5(X,L,{onopen:$1,onend:h0,onclose:r1})),R=b(c);return Object.assign(R,{get parameters(){return X.parameters},largeObject:u5.bind(null,R),subscribe:_,CLOSE:A2,END:A2,PostgresError:R2,options:X,reserve:g,listen:x,begin:B,close:p,end:s}),R;function b(T){return T.debug=X.debug,Object.entries(X.types).reduce((a,[Q0,v0])=>{return a[Q0]=(B0)=>new n1(B0,v0.to),a},m),Object.assign(W0,{types:m,typed:m,unsafe:V0,notify:h,array:q,json:C,file:k0}),W0;function m(a,Q0){return new n1(a,Q0)}function W0(a,...Q0){return a&&Array.isArray(a.raw)?new q1(a,Q0,T,N):typeof a==="string"&&!Q0.length?new P8(X.transform.column.to?X.transform.column.to(a):a):new t6(a,Q0)}function V0(a,Q0=[],v0={}){return arguments.length===2&&!Array.isArray(Q0)&&(v0=Q0,Q0=[]),new q1([a],Q0,T,N,{prepare:!1,...v0,simple:"simple"in v0?v0.simple:Q0.length===0})}function k0(a,Q0=[],v0={}){return arguments.length===2&&!Array.isArray(Q0)&&(v0=Q0,Q0=[]),new q1([],Q0,(A0)=>{QE.readFile(a,"utf8",(o0,O0)=>{if(o0)return A0.reject(o0);A0.strings=[O0],T(A0)})},N,{...v0,simple:"simple"in v0?v0.simple:Q0.length===0})}}async function x(T,m,W0){let V0={fn:m,onlisten:W0},k0=x.sql||(x.sql=_Y({...X,max:1,idle_timeout:null,max_lifetime:null,fetch_types:!1,onclose(){Object.entries(x.channels).forEach(([A0,{listeners:o0}])=>{delete x.channels[A0],Promise.all(o0.map((O0)=>x(A0,O0.fn,O0.onlisten).catch(()=>{})))})},onnotify(A0,o0){A0 in x.channels&&x.channels[A0].listeners.forEach((O0)=>O0.fn(o0))}})),a=x.channels||(x.channels={});if(T in a){a[T].listeners.push(V0);let A0=await a[T].result;return V0.onlisten&&V0.onlisten(),{state:A0.state,unlisten:B0}}a[T]={result:k0`listen ${k0.unsafe('"'+T.replace(/"/g,'""')+'"')}`,listeners:[V0]};let v0=await a[T].result;return V0.onlisten&&V0.onlisten(),{state:v0.state,unlisten:B0};async function B0(){if(T in a===!1)return;if(a[T].listeners=a[T].listeners.filter((A0)=>A0!==V0),a[T].listeners.length)return;return delete a[T],k0`unlisten ${k0.unsafe('"'+T.replace(/"/g,'""')+'"')}`}}async function h(T,m){return await R`select pg_notify(${T}, ${""+m})`}async function g(){let T=R1(),m=z.length?z.shift():await new Promise((k0,a)=>{let Q0={reserve:k0,reject:a};$.push(Q0),Q.length&&I0(Q.shift(),Q0)});K(m,H),m.reserved=()=>T.length?m.execute(T.shift()):K(m,H),m.reserved.release=!0;let W0=b(V0);return W0.release=()=>{m.reserved=null,$1(m)},W0;function V0(k0){m.queue===O?T.push(k0):m.execute(k0)||K(m,O)}}async function B(T,m){!m&&(m=T,T="");let W0=R1(),V0=0,k0,a=null;try{return await R.unsafe("begin "+T.replace(/[^a-z ]/ig,""),[],{onexecute:v0}).execute(),await Promise.race([Q0(k0,m),new Promise((B0,A0)=>k0.onclose=A0)])}catch(B0){throw B0}async function Q0(B0,A0,o0){let O0=b(b0);O0.savepoint=z4,O0.prepare=(R0)=>a=R0.replace(/[^a-z0-9$-_. ]/gi);let j1,c0;o0&&await O0`savepoint ${O0(o0)}`;try{if(c0=await new Promise((R0,P1)=>{let u1=A0(O0);Promise.resolve(Array.isArray(u1)?Promise.all(u1):u1).then(R0,P1)}),j1)throw j1}catch(R0){throw await(o0?O0`rollback to ${O0(o0)}`:O0`rollback`),R0 instanceof R2&&R0.code==="25P02"&&j1||R0}if(!o0)a?await O0`prepare transaction '${O0.unsafe(a)}'`:await O0`commit`;return c0;function z4(R0,P1){if(R0&&Array.isArray(R0.raw))return z4((u1)=>u1.apply(u1,arguments));return arguments.length===1&&(P1=R0,R0=null),Q0(B0,P1,"s"+V0+++(R0?"_"+R0:""))}function b0(R0){R0.catch((P1)=>j1||(j1=P1)),B0.queue===O?W0.push(R0):B0.execute(R0)||K(B0,O)}}function v0(B0){k0=B0,K(B0,H),B0.reserved=()=>W0.length?B0.execute(W0.shift()):K(B0,H)}}function K(T,m){return T.queue.remove(T),m.push(T),T.queue=m,m===z?T.idleTimer.start():T.idleTimer.cancel(),T}function C(T){return new n1(T,3802)}function q(T,m){if(!Array.isArray(T))return q(Array.from(arguments));return new n1(T,m||(T.length?r6(T)||25:0),X.shared.typeArrayMap)}function c(T){if(G)return T.reject(f0.connection("CONNECTION_ENDED",X,X));if(z.length)return n(z.shift(),T);if(Q.length)return I0(Q.shift(),T);F.length?n(F.shift(),T):$.push(T)}function n(T,m){return T.execute(m)?K(T,F):K(T,O)}function N(T){return new Promise((m,W0)=>{T.state?T.active?p5(X).cancel(T.state,m,W0):T.cancelled={resolve:m,reject:W0}:($.remove(T),T.cancelled=!0,T.reject(f0.generic("57014","canceling statement due to user request")),m())})}async function s({timeout:T=null}={}){if(G)return G;await 1;let m;return G=Promise.race([new Promise((W0)=>T!==null&&(m=setTimeout(t,T*1000,W0))),Promise.all(w.map((W0)=>W0.end()).concat(x.sql?x.sql.end({timeout:0}):[],_.sql?_.sql.end({timeout:0}):[]))]).then(()=>clearTimeout(m))}async function p(){await Promise.all(w.map((T)=>T.end()))}async function t(T){await Promise.all(w.map((m)=>m.terminate()));while($.length)$.shift().reject(f0.connection("CONNECTION_DESTROYED",X));T()}function I0(T,m){return K(T,W),T.connect(m),T}function h0(T){K(T,J)}function $1(T){if($.length===0)return K(T,z);let m=Math.ceil($.length/(W.length+1)),W0=!0;while(W0&&$.length&&m-- >0){let V0=$.shift();if(V0.reserve)return V0.reserve(T);W0=T.execute(V0)}W0?K(T,F):K(T,O)}function r1(T,m){K(T,Q),T.reserved=null,T.onclose&&(T.onclose(m),T.onclose=null),X.onclose&&X.onclose(T.id),$.length&&I0(T,$.shift())}}function zE(Y,Z){if(Y&&Y.shared)return Y;let X=process.env,_=(!Y||typeof Y==="string"?Z:Y)||{},{url:G,multihost:$}=OE(Y),W=[...G.searchParams].reduce((O,[L,w])=>(O[L]=w,O),{}),H=_.hostname||_.host||$||G.hostname||X.PGHOST||"localhost",Q=_.port||G.port||X.PGPORT||5432,J=_.user||_.username||G.username||X.PGUSERNAME||X.PGUSER||DE();_.no_prepare&&(_.prepare=!1),W.sslmode&&(W.ssl=W.sslmode,delete W.sslmode),"timeout"in _&&(console.log("The timeout option is deprecated, use idle_timeout instead"),_.idle_timeout=_.timeout),W.sslrootcert==="system"&&(W.ssl="verify-full");let z=["idle_timeout","connect_timeout","max_lifetime","max_pipeline","backoff","keep_alive"],F={max:10,ssl:!1,idle_timeout:null,connect_timeout:30,max_lifetime:EE,max_pipeline:100,backoff:FE,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((O)=>O.split(":")[0]),port:Array.isArray(Q)?Q:H.split(",").map((O)=>parseInt(O.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(F).reduce((O,[L,w])=>{let R=L in _?_[L]:(L in W)?W[L]==="disable"||W[L]==="false"?!1:W[L]:X["PG"+L.toUpperCase()]||w;return O[L]=typeof R==="string"&&z.includes(L)?+R:R,O},{}),connection:{application_name:X.PGAPPNAME||"postgres.js",..._.connection,...Object.entries(W).reduce((O,[L,w])=>((L in F)||(O[L]=w),O),{})},types:_.types||{},target_session_attrs:UE(_,G,X),onnotice:_.onnotice,onnotify:_.onnotify,onclose:_.onclose,onparameter:_.onparameter,socket:_.socket,transform:VE(_.transform||{undefined:void 0}),parameters:{},shared:{retries:0,typeArrayMap:{}},...DW(_.types)}}function UE(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 FE(Y){return(0.5+Math.random()/2)*Math.min(3**Y/100,20)}function EE(){return 60*(30+Math.random()*30)}function VE(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 OE(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 DE(){try{return JE.userInfo().username}catch(Y){return process.env.USERNAME||process.env.USER||process.env.LOGNAME}}class q0{static[E]="SelectionProxyHandler";config;constructor(Y){this.config={...Y}}get(Y,Z){if(Z==="_")return{...Y._,selectedFields:new Proxy(Y._.selectedFields,this)};if(Z===M0)return{...Y[M0],selectedFields:new Proxy(Y[M0].selectedFields,this)};if(typeof Z==="symbol")return Y[Z];let _=(M(Y,S0)?Y._.selectedFields:M(Y,V1)?Y[M0].selectedFields:Y)[Z];if(M(_,f.Aliased)){if(this.config.sqlAliasedBehavior==="sql"&&!_.isSelectionField)return _.sql;let G=_.clone();return G.isSelectionField=!0,G}if(M(_,f)){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(_,F0)){if(this.config.alias)return new Proxy(_,new M2(new Proxy(_.table,new A8(this.config.alias,this.config.replaceOriginalName??!1))));return _}if(typeof _!=="object"||_===null)return _;return new Proxy(_,new q0(this.config))}}class qW{constructor(Y,Z){this.unique=Y,this.name=Z}static[E]="PgIndexBuilderOn";on(...Y){return new GY(Y.map((Z)=>{if(M(Z,f))return Z;Z=Z;let X=new O8(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 GY(Y.map((Z)=>{if(M(Z,f))return Z;Z=Z;let X=new O8(Z.name,!!Z.keyAsName,Z.columnType,Z.indexConfig);return Z.indexConfig=Z.defaultConfig,X}),this.unique,!0,this.name)}using(Y,...Z){return new GY(Z.map((X)=>{if(M(X,f))return X;X=X;let _=new O8(X.name,!!X.keyAsName,X.columnType,X.indexConfig);return X.indexConfig=JSON.parse(JSON.stringify(X.defaultConfig)),_}),this.unique,!0,this.name,Y)}}class GY{static[E]="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 jW(this.config,Y)}}class jW{static[E]="PgIndex";config;constructor(Y,Z){this.config={...Y,table:Z}}}function d5(Y){return new qW(!0,Y)}function LE(Y){return(Y.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).map((X)=>X.toLowerCase()).join("_")}function ME(Y){return(Y.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).reduce((X,_,G)=>{let $=G===0?_.toLowerCase():`${_[0].toUpperCase()}${_.slice(1)}`;return X+$},"")}function AE(Y){return Y}class c5{static[E]="CasingCache";cache={};cachedTables={};convert;constructor(Y){this.convert=Y==="snake_case"?LE:Y==="camelCase"?ME:AE}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 $=`${_}.${G.name}`;this.cache[$]=this.convert(G.name)}this.cachedTables[_]=!0}}clearCache(){this.cache={},this.cachedTables={}}}class v8 extends V1{static[E]="PgViewBase"}class c4{static[E]="PgDialect";casing;constructor(Y){this.casing=new c5(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",$=V`
88
+ CREATE TABLE IF NOT EXISTS ${V.identifier(G)}.${V.identifier(_)} (
89
89
  id SERIAL PRIMARY KEY,
90
90
  hash text NOT NULL,
91
91
  created_at bigint
92
92
  )
93
- `;await Y.execute(L`CREATE SCHEMA IF NOT EXISTS ${L.identifier(_)}`),await Y.execute($);let H=(await Y.all(L`select id, hash, created_at from ${L.identifier(_)}.${L.identifier(G)} order by created_at desc limit 1`))[0];await Y.transaction(async(Q)=>{for await(let J of Z)if(!H||Number(H.created_at)<J.folderMillis){for(let z of J.sql)await Q.execute(L.raw(z));await Q.execute(L`insert into ${L.identifier(_)}.${L.identifier(G)} ("hash", "created_at") values(${J.hash}, ${J.folderMillis})`)}})}escapeName(Z){return`"${Z}"`}escapeParam(Z){return`$${Z+1}`}escapeString(Z){return`'${Z.replace(/'/g,"''")}'`}buildWithCTE(Z){if(!Z?.length)return;let Y=[L`with `];for(let[X,G]of Z.entries())if(Y.push(L`${L.identifier(G._.alias)} as (${G._.sql})`),X<Z.length-1)Y.push(L`, `);return Y.push(L` `),L.join(Y)}buildDeleteQuery({table:Z,where:Y,returning:X,withList:G}){let _=this.buildWithCTE(G),$=X?L` returning ${this.buildSelection(X,{isSingleTable:!0})}`:void 0,W=Y?L` where ${Y}`:void 0;return L`${_}delete from ${Z}${W}${$}`}buildUpdateSet(Z,Y){let X=Z[P.Symbol.Columns],G=Object.keys(X).filter(($)=>Y[$]!==void 0||X[$]?.onUpdateFn!==void 0),_=G.length;return L.join(G.flatMap(($,W)=>{let H=X[$],Q=Y[$]??L.param(H.onUpdateFn(),H),J=L`${L.identifier(this.casing.getColumnCasing(H))} = ${Q}`;if(W<_-1)return[J,L.raw(", ")];return[J]}))}buildUpdateQuery({table:Z,set:Y,where:X,returning:G,withList:_,from:$,joins:W}){let H=this.buildWithCTE(_),Q=Z[u0.Symbol.Name],J=Z[u0.Symbol.Schema],z=Z[u0.Symbol.OriginalName],U=Q===z?void 0:Q,D=L`${J?L`${L.identifier(J)}.`:void 0}${L.identifier(z)}${U&&L` ${L.identifier(U)}`}`,V=this.buildUpdateSet(Z,Y),N=$&&L.join([L.raw(" from "),this.buildFromTable($)]),R=this.buildJoins(W),b=G?L` returning ${this.buildSelection(G,{isSingleTable:!$})}`:void 0,x=X?L` where ${X}`:void 0;return L`${H}update ${D} set ${V}${N}${R}${x}${b}`}buildSelection(Z,{isSingleTable:Y=!1}={}){let X=Z.length,G=Z.flatMap(({field:_},$)=>{let W=[];if(M(_,f.Aliased)&&_.isSelectionField)W.push(L.identifier(_.fieldAlias));else if(M(_,f.Aliased)||M(_,f)){let H=M(_,f.Aliased)?_.sql:_;if(Y)W.push(new f(H.queryChunks.map((Q)=>{if(M(Q,j))return L.identifier(this.casing.getColumnCasing(Q));return Q})));else W.push(H);if(M(_,f.Aliased))W.push(L` as ${L.identifier(_.fieldAlias)}`)}else if(M(_,F0))if(Y)W.push(L.identifier(this.casing.getColumnCasing(_)));else W.push(_);if($<X-1)W.push(L`, `);return W});return L.join(G)}buildJoins(Z){if(!Z||Z.length===0)return;let Y=[];for(let[X,G]of Z.entries()){if(X===0)Y.push(L` `);let _=G.table,$=G.lateral?L` lateral`:void 0,W=G.on?L` on ${G.on}`:void 0;if(M(_,u0)){let H=_[u0.Symbol.Name],Q=_[u0.Symbol.Schema],J=_[u0.Symbol.OriginalName],z=H===J?void 0:G.alias;Y.push(L`${L.raw(G.joinType)} join${$} ${Q?L`${L.identifier(Q)}.`:void 0}${L.identifier(J)}${z&&L` ${L.identifier(z)}`}${W}`)}else if(M(_,L1)){let H=_[M0].name,Q=_[M0].schema,J=_[M0].originalName,z=H===J?void 0:G.alias;Y.push(L`${L.raw(G.joinType)} join${$} ${Q?L`${L.identifier(Q)}.`:void 0}${L.identifier(J)}${z&&L` ${L.identifier(z)}`}${W}`)}else Y.push(L`${L.raw(G.joinType)} join${$} ${_}${W}`);if(X<Z.length-1)Y.push(L` `)}return L.join(Y)}buildFromTable(Z){if(M(Z,P)&&Z[P.Symbol.IsAlias]){let Y=L`${L.identifier(Z[P.Symbol.OriginalName])}`;if(Z[P.Symbol.Schema])Y=L`${L.identifier(Z[P.Symbol.Schema])}.${Y}`;return L`${Y} ${L.identifier(Z[P.Symbol.Name])}`}return Z}buildSelectQuery({withList:Z,fields:Y,fieldsFlat:X,where:G,having:_,table:$,joins:W,orderBy:H,groupBy:Q,limit:J,offset:z,lockingClause:U,distinct:D,setOperators:V}){let N=X??j1(Y);for(let a of N)if(M(a.field,F0)&&d0(a.field.table)!==(M($,S0)?$._.alias:M($,v8)?$[M0].name:M($,f)?void 0:d0($))&&!((I0)=>W?.some(({alias:h0})=>h0===(I0[P.Symbol.IsAlias]?d0(I0):I0[P.Symbol.BaseName])))(a.field.table)){let I0=d0(a.field.table);throw new Error(`Your "${a.path.join("->")}" field references a column "${I0}"."${a.field.name}", but the table "${I0}" is not part of the query! Did you forget to join it?`)}let R=!W||W.length===0,b=this.buildWithCTE(Z),x;if(D)x=D===!0?L` distinct`:L` distinct on (${L.join(D.on,L`, `)})`;let h=this.buildSelection(N,{isSingleTable:R}),g=this.buildFromTable($),K=this.buildJoins(W),B=G?L` where ${G}`:void 0,T=_?L` having ${_}`:void 0,q;if(H&&H.length>0)q=L` order by ${L.join(H,L`, `)}`;let c;if(Q&&Q.length>0)c=L` group by ${L.join(Q,L`, `)}`;let n=typeof J==="object"||typeof J==="number"&&J>=0?L` limit ${J}`:void 0,w=z?L` offset ${z}`:void 0,s=L.empty();if(U){let a=L` for ${L.raw(U.strength)}`;if(U.config.of)a.append(L` of ${L.join(Array.isArray(U.config.of)?U.config.of:[U.config.of],L`, `)}`);if(U.config.noWait)a.append(L` nowait`);else if(U.config.skipLocked)a.append(L` skip locked`);s.append(a)}let p=L`${b}select${x} ${h} from ${g}${K}${B}${c}${T}${q}${n}${w}${s}`;if(V.length>0)return this.buildSetOperations(p,V);return p}buildSetOperations(Z,Y){let[X,...G]=Y;if(!X)throw new Error("Cannot pass undefined values to any set operator");if(G.length===0)return this.buildSetOperationQuery({leftSelect:Z,setOperator:X});return this.buildSetOperations(this.buildSetOperationQuery({leftSelect:Z,setOperator:X}),G)}buildSetOperationQuery({leftSelect:Z,setOperator:{type:Y,isAll:X,rightSelect:G,limit:_,orderBy:$,offset:W}}){let H=L`(${Z.getSQL()}) `,Q=L`(${G.getSQL()})`,J;if($&&$.length>0){let V=[];for(let N of $)if(M(N,j))V.push(L.identifier(N.name));else if(M(N,f)){for(let R=0;R<N.queryChunks.length;R++){let b=N.queryChunks[R];if(M(b,j))N.queryChunks[R]=L.identifier(b.name)}V.push(L`${N}`)}else V.push(L`${N}`);J=L` order by ${L.join(V,L`, `)} `}let z=typeof _==="object"||typeof _==="number"&&_>=0?L` limit ${_}`:void 0,U=L.raw(`${Y} ${X?"all ":""}`),D=W?L` offset ${W}`:void 0;return L`${H}${U}${Q}${J}${z}${D}`}buildInsertQuery({table:Z,values:Y,onConflict:X,returning:G,withList:_,select:$,overridingSystemValue_:W}){let H=[],Q=Z[P.Symbol.Columns],J=Object.entries(Q).filter(([b,x])=>!x.shouldDisableInsert()),z=J.map(([,b])=>L.identifier(this.casing.getColumnCasing(b)));if($){let b=Y;if(M(b,f))H.push(b);else H.push(b.getSQL())}else{let b=Y;H.push(L.raw("values "));for(let[x,h]of b.entries()){let g=[];for(let[K,B]of J){let T=h[K];if(T===void 0||M(T,w1)&&T.value===void 0)if(B.defaultFn!==void 0){let q=B.defaultFn(),c=M(q,f)?q:L.param(q,B);g.push(c)}else if(!B.default&&B.onUpdateFn!==void 0){let q=B.onUpdateFn(),c=M(q,f)?q:L.param(q,B);g.push(c)}else g.push(L`default`);else g.push(T)}if(H.push(g),x<b.length-1)H.push(L`, `)}}let U=this.buildWithCTE(_),D=L.join(H),V=G?L` returning ${this.buildSelection(G,{isSingleTable:!0})}`:void 0,N=X?L` on conflict ${X}`:void 0,R=W===!0?L`overriding system value `:void 0;return L`${U}insert into ${Z} ${z} ${R}${D}${N}${V}`}buildRefreshMaterializedViewQuery({view:Z,concurrently:Y,withNoData:X}){let G=Y?L` concurrently`:void 0,_=X?L` with no data`:void 0;return L`refresh materialized view${G} ${Z}${_}`}prepareTyping(Z){if(M(Z,i6)||M(Z,l6))return"json";else if(M(Z,o6))return"decimal";else if(M(Z,n6))return"time";else if(M(Z,r6)||M(Z,s6))return"timestamp";else if(M(Z,d6)||M(Z,c6))return"date";else if(M(Z,a6))return"uuid";else return"none"}sqlToQuery(Z,Y){return Z.toQuery({casing:this.casing,escapeName:this.escapeName,escapeParam:this.escapeParam,escapeString:this.escapeString,prepareTyping:this.prepareTyping,invokeSource:Y})}buildRelationalQueryWithoutPK({fullSchema:Z,schema:Y,tableNamesMap:X,table:G,tableConfig:_,queryConfig:$,tableAlias:W,nestedQueryRelation:H,joinOn:Q}){let J=[],z,U,D=[],V,N=[];if($===!0)J=Object.entries(_.columns).map(([x,h])=>({dbKey:h.name,tsKey:x,field:n1(h,W),relationTableTsKey:void 0,isJson:!1,selection:[]}));else{let b=Object.fromEntries(Object.entries(_.columns).map(([T,q])=>[T,n1(q,W)]));if($.where){let T=typeof $.where==="function"?$.where(b,LW()):$.where;V=T&&R8(T,W)}let x=[],h=[];if($.columns){let T=!1;for(let[q,c]of Object.entries($.columns)){if(c===void 0)continue;if(q in _.columns){if(!T&&c===!0)T=!0;h.push(q)}}if(h.length>0)h=T?h.filter((q)=>$.columns?.[q]===!0):Object.keys(_.columns).filter((q)=>!h.includes(q))}else h=Object.keys(_.columns);for(let T of h){let q=_.columns[T];x.push({tsKey:T,value:q})}let g=[];if($.with)g=Object.entries($.with).filter((T)=>!!T[1]).map(([T,q])=>({tsKey:T,queryConfig:q,relation:_.relations[T]}));let K;if($.extras){K=typeof $.extras==="function"?$.extras(b,{sql:L}):$.extras;for(let[T,q]of Object.entries(K))x.push({tsKey:T,value:TY(q,W)})}for(let{tsKey:T,value:q}of x)J.push({dbKey:M(q,f.Aliased)?q.fieldAlias:_.columns[T].name,tsKey:T,field:M(q,F0)?n1(q,W):q,relationTableTsKey:void 0,isJson:!1,selection:[]});let B=typeof $.orderBy==="function"?$.orderBy(b,DW()):$.orderBy??[];if(!Array.isArray(B))B=[B];D=B.map((T)=>{if(M(T,F0))return n1(T,W);return R8(T,W)}),z=$.limit,U=$.offset;for(let{tsKey:T,queryConfig:q,relation:c}of g){let n=VW(Y,X,c),w=m4(c.referencedTable),s=X[w],p=`${W}_${T}`,a=K8(...n.fields.map((W1,s1)=>t6(n1(n.references[s1],p),n1(W1,W)))),I0=this.buildRelationalQueryWithoutPK({fullSchema:Z,schema:Y,tableNamesMap:X,table:Z[s],tableConfig:Y[s],queryConfig:M(c,T4)?q===!0?{limit:1}:{...q,limit:1}:q,tableAlias:p,joinOn:a,nestedQueryRelation:c}),h0=L`${L.identifier(p)}.${L.identifier("data")}`.as(T);N.push({on:L`true`,table:new S0(I0.sql,{},p),alias:p,joinType:"left",lateral:!0}),J.push({dbKey:T,tsKey:T,field:h0,relationTableTsKey:s,isJson:!0,selection:I0.selection})}}if(J.length===0)throw new m6({message:`No fields selected for table "${_.tsName}" ("${W}")`});let R;if(V=K8(Q,V),H){let b=L`json_build_array(${L.join(J.map(({field:g,tsKey:K,isJson:B})=>B?L`${L.identifier(`${W}_${K}`)}.${L.identifier("data")}`:M(g,f.Aliased)?g.sql:g),L`, `)})`;if(M(H,C8))b=L`coalesce(json_agg(${b}${D.length>0?L` order by ${L.join(D,L`, `)}`:void 0}), '[]'::json)`;let x=[{dbKey:"data",tsKey:"data",field:b.as("data"),isJson:!0,relationTableTsKey:_.tsName,selection:J}];if(z!==void 0||U!==void 0||D.length>0)R=this.buildSelectQuery({table:p6(G,W),fields:{},fieldsFlat:[{path:[],field:L.raw("*")}],where:V,limit:z,offset:U,orderBy:D,setOperators:[]}),V=void 0,z=void 0,U=void 0,D=[];else R=p6(G,W);R=this.buildSelectQuery({table:M(R,u0)?R:new S0(R,{},W),fields:{},fieldsFlat:x.map(({field:g})=>({path:[],field:M(g,F0)?n1(g,W):g})),joins:N,where:V,limit:z,offset:U,orderBy:D,setOperators:[]})}else R=this.buildSelectQuery({table:p6(G,W),fields:{},fieldsFlat:J.map(({field:b})=>({path:[],field:M(b,F0)?n1(b,W):b})),joins:N,where:V,limit:z,offset:U,orderBy:D,setOperators:[]});return{tableTsKey:_.tsName,sql:R,selection:J}}}class ZX{static[E]="TypedQueryBuilder";getSelectedFields(){return this._.selectedFields}}class $1{static[E]="PgSelectBuilder";fields;session;dialect;withList=[];distinct;constructor(Z){if(this.fields=Z.fields,this.session=Z.session,this.dialect=Z.dialect,Z.withList)this.withList=Z.withList;this.distinct=Z.distinct}authToken;setToken(Z){return this.authToken=Z,this}from(Z){let Y=!!this.fields,X=Z,G;if(this.fields)G=this.fields;else if(M(X,S0))G=Object.fromEntries(Object.keys(X._.selectedFields).map((_)=>[_,X[_]]));else if(M(X,v8))G=X[M0].selectedFields;else if(M(X,f))G={};else G=i_(X);return new YX({table:X,fields:G,isPartialSelect:Y,session:this.session,dialect:this.dialect,withList:this.withList,distinct:this.distinct}).setToken(this.authToken)}}class mW extends ZX{static[E]="PgSelectQueryBuilder";_;config;joinsNotNullableMap;tableName;isPartialSelect;session;dialect;cacheConfig=void 0;usedTables=new Set;constructor({table:Z,fields:Y,isPartialSelect:X,session:G,dialect:_,withList:$,distinct:W}){super();this.config={withList:$,table:Z,fields:{...Y},distinct:W,setOperators:[]},this.isPartialSelect=X,this.session=G,this.dialect=_,this._={selectedFields:Y,config:this.config},this.tableName=Q4(Z),this.joinsNotNullableMap=typeof this.tableName==="string"?{[this.tableName]:!0}:{};for(let H of m1(Z))this.usedTables.add(H)}getUsedTables(){return[...this.usedTables]}createJoin(Z,Y){return(X,G)=>{let _=this.tableName,$=Q4(X);for(let W of m1(X))this.usedTables.add(W);if(typeof $==="string"&&this.config.joins?.some((W)=>W.alias===$))throw new Error(`Alias "${$}" is already used in this query`);if(!this.isPartialSelect){if(Object.keys(this.joinsNotNullableMap).length===1&&typeof _==="string")this.config.fields={[_]:this.config.fields};if(typeof $==="string"&&!M(X,f)){let W=M(X,S0)?X._.selectedFields:M(X,L1)?X[M0].selectedFields:X[P.Symbol.Columns];this.config.fields[$]=W}}if(typeof G==="function")G=G(new Proxy(this.config.fields,new j0({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));if(!this.config.joins)this.config.joins=[];if(this.config.joins.push({on:G,table:X,joinType:Z,alias:$,lateral:Y}),typeof $==="string")switch(Z){case"left":{this.joinsNotNullableMap[$]=!1;break}case"right":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([W])=>[W,!1])),this.joinsNotNullableMap[$]=!0;break}case"cross":case"inner":{this.joinsNotNullableMap[$]=!0;break}case"full":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([W])=>[W,!1])),this.joinsNotNullableMap[$]=!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(Z,Y){return(X)=>{let G=typeof X==="function"?X(VE()):X;if(!N8(this.getSelectedFields(),G.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:Z,isAll:Y,rightSelect:G}),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(Z){return this.config.setOperators.push(...Z),this}where(Z){if(typeof Z==="function")Z=Z(new Proxy(this.config.fields,new j0({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));return this.config.where=Z,this}having(Z){if(typeof Z==="function")Z=Z(new Proxy(this.config.fields,new j0({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));return this.config.having=Z,this}groupBy(...Z){if(typeof Z[0]==="function"){let Y=Z[0](new Proxy(this.config.fields,new j0({sqlAliasedBehavior:"alias",sqlBehavior:"sql"})));this.config.groupBy=Array.isArray(Y)?Y:[Y]}else this.config.groupBy=Z;return this}orderBy(...Z){if(typeof Z[0]==="function"){let Y=Z[0](new Proxy(this.config.fields,new j0({sqlAliasedBehavior:"alias",sqlBehavior:"sql"}))),X=Array.isArray(Y)?Y:[Y];if(this.config.setOperators.length>0)this.config.setOperators.at(-1).orderBy=X;else this.config.orderBy=X}else{let Y=Z;if(this.config.setOperators.length>0)this.config.setOperators.at(-1).orderBy=Y;else this.config.orderBy=Y}return this}limit(Z){if(this.config.setOperators.length>0)this.config.setOperators.at(-1).limit=Z;else this.config.limit=Z;return this}offset(Z){if(this.config.setOperators.length>0)this.config.setOperators.at(-1).offset=Z;else this.config.offset=Z;return this}for(Z,Y={}){return this.config.lockingClause={strength:Z,config:Y},this}getSQL(){return this.dialect.buildSelectQuery(this.config)}toSQL(){let{typings:Z,...Y}=this.dialect.sqlToQuery(this.getSQL());return Y}as(Z){let Y=[];if(Y.push(...m1(this.config.table)),this.config.joins)for(let X of this.config.joins)Y.push(...m1(X.table));return new Proxy(new S0(this.getSQL(),this.config.fields,Z,!1,[...new Set(Y)]),new j0({alias:Z,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}getSelectedFields(){return new Proxy(this.config.fields,new j0({alias:this.tableName,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}$dynamic(){return this}$withCache(Z){return this.cacheConfig=Z===void 0?{config:{},enable:!0,autoInvalidate:!0}:Z===!1?{enable:!1}:{enable:!0,autoInvalidate:!0,...Z},this}}class YX extends mW{static[E]="PgSelect";_prepare(Z){let{session:Y,config:X,dialect:G,joinsNotNullableMap:_,authToken:$,cacheConfig:W,usedTables:H}=this;if(!Y)throw new Error("Cannot execute a query on a query builder. Please use a database instance instead.");let{fields:Q}=X;return E0.startActiveSpan("drizzle.prepareQuery",()=>{let J=j1(Q),z=Y.prepareQuery(G.sqlToQuery(this.getSQL()),J,Z,!0,void 0,{type:"select",tables:[...H]},W);return z.joinsNotNullableMap=_,z.setToken($)})}prepare(Z){return this._prepare(Z)}authToken;setToken(Z){return this.authToken=Z,this}execute=(Z)=>{return E0.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(Z,this.authToken)})}}l_(YX,[_1]);function T2(Z,Y){return(X,G,..._)=>{let $=[G,..._].map((W)=>({type:Z,isAll:Y,rightSelect:W}));for(let W of $)if(!N8(X.getSelectedFields(),W.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($)}}var VE=()=>({union:ME,unionAll:AE,intersect:RE,intersectAll:NE,except:wE,exceptAll:IE}),ME=T2("union",!1),AE=T2("union",!0),RE=T2("intersect",!1),NE=T2("intersect",!0),wE=T2("except",!1),IE=T2("except",!0);class x8{static[E]="PgQueryBuilder";dialect;dialectConfig;constructor(Z){this.dialect=M(Z,i4)?Z:void 0,this.dialectConfig=M(Z,i4)?void 0:Z}$with=(Z,Y)=>{let X=this;return{as:(_)=>{if(typeof _==="function")_=_(X);return new Proxy(new V8(_.getSQL(),Y??("getSelectedFields"in _?_.getSelectedFields()??{}:{}),Z,!0),new j0({alias:Z,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}};with(...Z){let Y=this;function X($){return new $1({fields:$??void 0,session:void 0,dialect:Y.getDialect(),withList:Z})}function G($){return new $1({fields:$??void 0,session:void 0,dialect:Y.getDialect(),distinct:!0})}function _($,W){return new $1({fields:W??void 0,session:void 0,dialect:Y.getDialect(),distinct:{on:$}})}return{select:X,selectDistinct:G,selectDistinctOn:_}}select(Z){return new $1({fields:Z??void 0,session:void 0,dialect:this.getDialect()})}selectDistinct(Z){return new $1({fields:Z??void 0,session:void 0,dialect:this.getDialect(),distinct:!0})}selectDistinctOn(Z,Y){return new $1({fields:Y??void 0,session:void 0,dialect:this.getDialect(),distinct:{on:Z}})}getDialect(){if(!this.dialect)this.dialect=new i4(this.dialectConfig);return this.dialect}}function m1(Z){if(M(Z,u0))return[Z[p4]?`${Z[p4]}.${Z[P.Symbol.BaseName]}`:Z[P.Symbol.BaseName]];if(M(Z,S0))return Z._.usedTables??[];if(M(Z,f))return Z.usedTables??[];return[]}class FZ extends _1{constructor(Z,Y,X,G){super();this.session=Y,this.dialect=X,this.config={table:Z,withList:G}}static[E]="PgDelete";config;cacheConfig;where(Z){return this.config.where=Z,this}returning(Z=this.config.table[P.Symbol.Columns]){return this.config.returningFields=Z,this.config.returning=j1(Z),this}getSQL(){return this.dialect.buildDeleteQuery(this.config)}toSQL(){let{typings:Z,...Y}=this.dialect.sqlToQuery(this.getSQL());return Y}_prepare(Z){return E0.startActiveSpan("drizzle.prepareQuery",()=>{return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,Z,!0,void 0,{type:"delete",tables:m1(this.config.table)},this.cacheConfig)})}prepare(Z){return this._prepare(Z)}authToken;setToken(Z){return this.authToken=Z,this}execute=(Z)=>{return E0.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(Z,this.authToken)})};getSelectedFields(){return this.config.returningFields?new Proxy(this.config.returningFields,new j0({alias:d0(this.config.table),sqlAliasedBehavior:"alias",sqlBehavior:"error"})):void 0}$dynamic(){return this}}class EZ{constructor(Z,Y,X,G,_){this.table=Z,this.session=Y,this.dialect=X,this.withList=G,this.overridingSystemValue_=_}static[E]="PgInsertBuilder";authToken;setToken(Z){return this.authToken=Z,this}overridingSystemValue(){return this.overridingSystemValue_=!0,this}values(Z){if(Z=Array.isArray(Z)?Z:[Z],Z.length===0)throw new Error("values() must be called with at least one value");let Y=Z.map((X)=>{let G={},_=this.table[P.Symbol.Columns];for(let $ of Object.keys(X)){let W=X[$];G[$]=M(W,f)?W:new w1(W,_[$])}return G});return new XX(this.table,Y,this.session,this.dialect,this.withList,!1,this.overridingSystemValue_).setToken(this.authToken)}select(Z){let Y=typeof Z==="function"?Z(new x8):Z;if(!M(Y,f)&&!N8(this.table[y6],Y._.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 XX(this.table,Y,this.session,this.dialect,this.withList,!0)}}class XX extends _1{constructor(Z,Y,X,G,_,$,W){super();this.session=X,this.dialect=G,this.config={table:Z,values:Y,withList:_,select:$,overridingSystemValue_:W}}static[E]="PgInsert";config;cacheConfig;returning(Z=this.config.table[P.Symbol.Columns]){return this.config.returningFields=Z,this.config.returning=j1(Z),this}onConflictDoNothing(Z={}){if(Z.target===void 0)this.config.onConflict=L`do nothing`;else{let Y="";Y=Array.isArray(Z.target)?Z.target.map((G)=>this.dialect.escapeName(this.dialect.casing.getColumnCasing(G))).join(","):this.dialect.escapeName(this.dialect.casing.getColumnCasing(Z.target));let X=Z.where?L` where ${Z.where}`:void 0;this.config.onConflict=L`(${L.raw(Y)})${X} do nothing`}return this}onConflictDoUpdate(Z){if(Z.where&&(Z.targetWhere||Z.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 Y=Z.where?L` where ${Z.where}`:void 0,X=Z.targetWhere?L` where ${Z.targetWhere}`:void 0,G=Z.setWhere?L` where ${Z.setWhere}`:void 0,_=this.dialect.buildUpdateSet(this.config.table,u6(this.config.table,Z.set)),$="";return $=Array.isArray(Z.target)?Z.target.map((W)=>this.dialect.escapeName(this.dialect.casing.getColumnCasing(W))).join(","):this.dialect.escapeName(this.dialect.casing.getColumnCasing(Z.target)),this.config.onConflict=L`(${L.raw($)})${X} do update set ${_}${Y}${G}`,this}getSQL(){return this.dialect.buildInsertQuery(this.config)}toSQL(){let{typings:Z,...Y}=this.dialect.sqlToQuery(this.getSQL());return Y}_prepare(Z){return E0.startActiveSpan("drizzle.prepareQuery",()=>{return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,Z,!0,void 0,{type:"insert",tables:m1(this.config.table)},this.cacheConfig)})}prepare(Z){return this._prepare(Z)}authToken;setToken(Z){return this.authToken=Z,this}execute=(Z)=>{return E0.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(Z,this.authToken)})};getSelectedFields(){return this.config.returningFields?new Proxy(this.config.returningFields,new j0({alias:d0(this.config.table),sqlAliasedBehavior:"alias",sqlBehavior:"error"})):void 0}$dynamic(){return this}}class GX extends _1{constructor(Z,Y,X){super();this.session=Y,this.dialect=X,this.config={view:Z}}static[E]="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:Z,...Y}=this.dialect.sqlToQuery(this.getSQL());return Y}_prepare(Z){return E0.startActiveSpan("drizzle.prepareQuery",()=>{return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),void 0,Z,!0)})}prepare(Z){return this._prepare(Z)}authToken;setToken(Z){return this.authToken=Z,this}execute=(Z)=>{return E0.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(Z,this.authToken)})}}class LZ{constructor(Z,Y,X,G){this.table=Z,this.session=Y,this.dialect=X,this.withList=G}static[E]="PgUpdateBuilder";authToken;setToken(Z){return this.authToken=Z,this}set(Z){return new uW(this.table,u6(this.table,Z),this.session,this.dialect,this.withList).setToken(this.authToken)}}class uW extends _1{constructor(Z,Y,X,G,_){super();this.session=X,this.dialect=G,this.config={set:Y,table:Z,withList:_,joins:[]},this.tableName=Q4(Z),this.joinsNotNullableMap=typeof this.tableName==="string"?{[this.tableName]:!0}:{}}static[E]="PgUpdate";config;tableName;joinsNotNullableMap;cacheConfig;from(Z){let Y=Z,X=Q4(Y);if(typeof X==="string")this.joinsNotNullableMap[X]=!0;return this.config.from=Y,this}getTableLikeFields(Z){if(M(Z,u0))return Z[P.Symbol.Columns];else if(M(Z,S0))return Z._.selectedFields;return Z[M0].selectedFields}createJoin(Z){return(Y,X)=>{let G=Q4(Y);if(typeof G==="string"&&this.config.joins.some((_)=>_.alias===G))throw new Error(`Alias "${G}" is already used in this query`);if(typeof X==="function"){let _=this.config.from&&!M(this.config.from,f)?this.getTableLikeFields(this.config.from):void 0;X=X(new Proxy(this.config.table[P.Symbol.Columns],new j0({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})),_&&new Proxy(_,new j0({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})))}if(this.config.joins.push({on:X,table:Y,joinType:Z,alias:G}),typeof G==="string")switch(Z){case"left":{this.joinsNotNullableMap[G]=!1;break}case"right":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([_])=>[_,!1])),this.joinsNotNullableMap[G]=!0;break}case"inner":{this.joinsNotNullableMap[G]=!0;break}case"full":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([_])=>[_,!1])),this.joinsNotNullableMap[G]=!1;break}}return this}}leftJoin=this.createJoin("left");rightJoin=this.createJoin("right");innerJoin=this.createJoin("inner");fullJoin=this.createJoin("full");where(Z){return this.config.where=Z,this}returning(Z){if(!Z){if(Z=Object.assign({},this.config.table[P.Symbol.Columns]),this.config.from){let Y=Q4(this.config.from);if(typeof Y==="string"&&this.config.from&&!M(this.config.from,f)){let X=this.getTableLikeFields(this.config.from);Z[Y]=X}for(let X of this.config.joins){let G=Q4(X.table);if(typeof G==="string"&&!M(X.table,f)){let _=this.getTableLikeFields(X.table);Z[G]=_}}}}return this.config.returningFields=Z,this.config.returning=j1(Z),this}getSQL(){return this.dialect.buildUpdateQuery(this.config)}toSQL(){let{typings:Z,...Y}=this.dialect.sqlToQuery(this.getSQL());return Y}_prepare(Z){let Y=this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,Z,!0,void 0,{type:"insert",tables:m1(this.config.table)},this.cacheConfig);return Y.joinsNotNullableMap=this.joinsNotNullableMap,Y}prepare(Z){return this._prepare(Z)}authToken;setToken(Z){return this.authToken=Z,this}execute=(Z)=>{return this._prepare().execute(Z,this.authToken)};getSelectedFields(){return this.config.returningFields?new Proxy(this.config.returningFields,new j0({alias:d0(this.config.table),sqlAliasedBehavior:"alias",sqlBehavior:"error"})):void 0}$dynamic(){return this}}class f8 extends f{constructor(Z){super(f8.buildEmbeddedCount(Z.source,Z.filters).queryChunks);this.params=Z,this.mapWith(Number),this.session=Z.session,this.sql=f8.buildCount(Z.source,Z.filters)}sql;token;static[E]="PgCountBuilder";[Symbol.toStringTag]="PgCountBuilder";session;static buildEmbeddedCount(Z,Y){return L`(select count(*) from ${Z}${L.raw(" where ").if(Y)}${Y})`}static buildCount(Z,Y){return L`select count(*) as count from ${Z}${L.raw(" where ").if(Y)}${Y};`}setToken(Z){return this.token=Z,this}then(Z,Y){return Promise.resolve(this.session.count(this.sql,this.token)).then(Z,Y)}catch(Z){return this.then(void 0,Z)}finally(Z){return this.then((Y)=>{return Z?.(),Y},(Y)=>{throw Z?.(),Y})}}class $X{constructor(Z,Y,X,G,_,$,W){this.fullSchema=Z,this.schema=Y,this.tableNamesMap=X,this.table=G,this.tableConfig=_,this.dialect=$,this.session=W}static[E]="PgRelationalQueryBuilder";findMany(Z){return new _X(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,Z?Z:{},"many")}findFirst(Z){return new _X(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,Z?{...Z,limit:1}:{limit:1},"first")}}class _X extends _1{constructor(Z,Y,X,G,_,$,W,H,Q){super();this.fullSchema=Z,this.schema=Y,this.tableNamesMap=X,this.table=G,this.tableConfig=_,this.dialect=$,this.session=W,this.config=H,this.mode=Q}static[E]="PgRelationalQuery";_prepare(Z){return E0.startActiveSpan("drizzle.prepareQuery",()=>{let{query:Y,builtQuery:X}=this._toSQL();return this.session.prepareQuery(X,void 0,Z,!0,(G,_)=>{let $=G.map((W)=>e6(this.schema,this.tableConfig,W,Y.selection,_));if(this.mode==="first")return $[0];return $})})}prepare(Z){return this._prepare(Z)}_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 Z=this._getQuery(),Y=this.dialect.sqlToQuery(Z.sql);return{query:Z,builtQuery:Y}}toSQL(){return this._toSQL().builtQuery}authToken;setToken(Z){return this.authToken=Z,this}execute(){return E0.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(void 0,this.authToken)})}}class WX extends _1{constructor(Z,Y,X,G){super();this.execute=Z,this.sql=Y,this.query=X,this.mapBatchResult=G}static[E]="PgRaw";getSQL(){return this.sql}getQuery(){return this.query}mapResult(Z,Y){return Y?this.mapBatchResult(Z):Z}_prepare(){return this}isResponseInArrayMode(){return!1}}class h8{constructor(Z,Y,X){if(this.dialect=Z,this.session=Y,this._=X?{schema:X.schema,fullSchema:X.fullSchema,tableNamesMap:X.tableNamesMap,session:Y}:{schema:void 0,fullSchema:{},tableNamesMap:{},session:Y},this.query={},this._.schema)for(let[G,_]of Object.entries(this._.schema))this.query[G]=new $X(X.fullSchema,this._.schema,this._.tableNamesMap,X.fullSchema[G],_,Z,Y);this.$cache={invalidate:async(G)=>{}}}static[E]="PgDatabase";query;$with=(Z,Y)=>{let X=this;return{as:(_)=>{if(typeof _==="function")_=_(new x8(X.dialect));return new Proxy(new V8(_.getSQL(),Y??("getSelectedFields"in _?_.getSelectedFields()??{}:{}),Z,!0),new j0({alias:Z,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}};$count(Z,Y){return new f8({source:Z,filters:Y,session:this.session})}$cache;with(...Z){let Y=this;function X(Q){return new $1({fields:Q??void 0,session:Y.session,dialect:Y.dialect,withList:Z})}function G(Q){return new $1({fields:Q??void 0,session:Y.session,dialect:Y.dialect,withList:Z,distinct:!0})}function _(Q,J){return new $1({fields:J??void 0,session:Y.session,dialect:Y.dialect,withList:Z,distinct:{on:Q}})}function $(Q){return new LZ(Q,Y.session,Y.dialect,Z)}function W(Q){return new EZ(Q,Y.session,Y.dialect,Z)}function H(Q){return new FZ(Q,Y.session,Y.dialect,Z)}return{select:X,selectDistinct:G,selectDistinctOn:_,update:$,insert:W,delete:H}}select(Z){return new $1({fields:Z??void 0,session:this.session,dialect:this.dialect})}selectDistinct(Z){return new $1({fields:Z??void 0,session:this.session,dialect:this.dialect,distinct:!0})}selectDistinctOn(Z,Y){return new $1({fields:Y??void 0,session:this.session,dialect:this.dialect,distinct:{on:Z}})}update(Z){return new LZ(Z,this.session,this.dialect)}insert(Z){return new EZ(Z,this.session,this.dialect)}delete(Z){return new FZ(Z,this.session,this.dialect)}refreshMaterializedView(Z){return new GX(Z,this.session,this.dialect)}authToken;execute(Z){let Y=typeof Z==="string"?L.raw(Z):Z.getSQL(),X=this.dialect.sqlToQuery(Y),G=this.session.prepareQuery(X,void 0,void 0,!1);return new WX(()=>G.execute(void 0,this.authToken),Y,X,(_)=>G.mapResult(_,!0))}transaction(Z,Y){return this.session.transaction(Z,Y)}}class dW{static[E]="Cache"}class k8 extends dW{strategy(){return"all"}static[E]="NoopCache";async get(Z){return}async put(Z,Y,X,G){}async onMutate(Z){}}async function HX(Z,Y){let X=`${Z}-${JSON.stringify(Y)}`,_=new TextEncoder().encode(X),$=await crypto.subtle.digest("SHA-256",_);return[...new Uint8Array($)].map((Q)=>Q.toString(16).padStart(2,"0")).join("")}class JX{constructor(Z,Y,X,G){if(this.query=Z,this.cache=Y,this.queryMetadata=X,this.cacheConfig=G,Y&&Y.strategy()==="all"&&G===void 0)this.cacheConfig={enable:!0,autoInvalidate:!0};if(!this.cacheConfig?.enable)this.cacheConfig=void 0}authToken;getQuery(){return this.query}mapResult(Z,Y){return Z}setToken(Z){return this.authToken=Z,this}static[E]="PgPreparedQuery";joinsNotNullableMap;async queryWithCache(Z,Y,X){if(this.cache===void 0||M(this.cache,k8)||this.queryMetadata===void 0)try{return await X()}catch(G){throw new J4(Z,Y,G)}if(this.cacheConfig&&!this.cacheConfig.enable)try{return await X()}catch(G){throw new J4(Z,Y,G)}if((this.queryMetadata.type==="insert"||this.queryMetadata.type==="update"||this.queryMetadata.type==="delete")&&this.queryMetadata.tables.length>0)try{let[G]=await Promise.all([X(),this.cache.onMutate({tables:this.queryMetadata.tables})]);return G}catch(G){throw new J4(Z,Y,G)}if(!this.cacheConfig)try{return await X()}catch(G){throw new J4(Z,Y,G)}if(this.queryMetadata.type==="select"){let G=await this.cache.get(this.cacheConfig.tag??await HX(Z,Y),this.queryMetadata.tables,this.cacheConfig.tag!==void 0,this.cacheConfig.autoInvalidate);if(G===void 0){let _;try{_=await X()}catch($){throw new J4(Z,Y,$)}return await this.cache.put(this.cacheConfig.tag??await HX(Z,Y),_,this.cacheConfig.autoInvalidate?this.queryMetadata.tables:[],this.cacheConfig.tag!==void 0,this.cacheConfig.config),_}return G}try{return await X()}catch(G){throw new J4(Z,Y,G)}}}class QX{constructor(Z){this.dialect=Z}static[E]="PgSession";execute(Z,Y){return E0.startActiveSpan("drizzle.operation",()=>{return E0.startActiveSpan("drizzle.prepareQuery",()=>{return this.prepareQuery(this.dialect.sqlToQuery(Z),void 0,void 0,!1)}).setToken(Y).execute(void 0,Y)})}all(Z){return this.prepareQuery(this.dialect.sqlToQuery(Z),void 0,void 0,!1).all()}async count(Z,Y){let X=await this.execute(Z,Y);return Number(X[0].count)}}class zX extends h8{constructor(Z,Y,X,G=0){super(Z,Y,X);this.schema=X,this.nestedIndex=G}static[E]="PgTransaction";rollback(){throw new qY}getTransactionConfigSQL(Z){let Y=[];if(Z.isolationLevel)Y.push(`isolation level ${Z.isolationLevel}`);if(Z.accessMode)Y.push(Z.accessMode);if(typeof Z.deferrable==="boolean")Y.push(Z.deferrable?"deferrable":"not deferrable");return L.raw(Y.join(" "))}setTransaction(Z){return this.session.execute(L`set transaction ${this.getTransactionConfigSQL(Z)}`)}}class cW extends JX{constructor(Z,Y,X,G,_,$,W,H,Q,J){super({sql:Y,params:X},_,$,W);this.client=Z,this.queryString=Y,this.params=X,this.logger=G,this.fields=H,this._isResponseInArrayMode=Q,this.customResultMapper=J}static[E]="PostgresJsPreparedQuery";async execute(Z={}){return E0.startActiveSpan("drizzle.execute",async(Y)=>{let X=CY(this.params,Z);Y?.setAttributes({"drizzle.query.text":this.queryString,"drizzle.query.params":JSON.stringify(X)}),this.logger.logQuery(this.queryString,X);let{fields:G,queryString:_,client:$,joinsNotNullableMap:W,customResultMapper:H}=this;if(!G&&!H)return E0.startActiveSpan("drizzle.driver.execute",()=>{return this.queryWithCache(_,X,async()=>{return await $.unsafe(_,X)})});let Q=await E0.startActiveSpan("drizzle.driver.execute",()=>{return Y?.setAttributes({"drizzle.query.text":_,"drizzle.query.params":JSON.stringify(X)}),this.queryWithCache(_,X,async()=>{return await $.unsafe(_,X).values()})});return E0.startActiveSpan("drizzle.mapResponse",()=>{return H?H(Q):Q.map((J)=>c_(G,J,W))})})}all(Z={}){return E0.startActiveSpan("drizzle.execute",async(Y)=>{let X=CY(this.params,Z);return Y?.setAttributes({"drizzle.query.text":this.queryString,"drizzle.query.params":JSON.stringify(X)}),this.logger.logQuery(this.queryString,X),E0.startActiveSpan("drizzle.driver.execute",()=>{return Y?.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 b8 extends QX{constructor(Z,Y,X,G={}){super(Y);this.client=Z,this.schema=X,this.options=G,this.logger=G.logger??new PY,this.cache=G.cache??new k8}static[E]="PostgresJsSession";logger;cache;prepareQuery(Z,Y,X,G,_,$,W){return new cW(this.client,Z.sql,Z.params,this.logger,this.cache,$,W,Y,G,_)}query(Z,Y){return this.logger.logQuery(Z,Y),this.client.unsafe(Z,Y).values()}queryObjects(Z,Y){return this.client.unsafe(Z,Y)}transaction(Z,Y){return this.client.begin(async(X)=>{let G=new b8(X,this.dialect,this.schema,this.options),_=new UX(this.dialect,G,this.schema);if(Y)await _.setTransaction(Y);return Z(_)})}}class UX extends zX{constructor(Z,Y,X,G=0){super(Z,Y,X,G);this.session=Y}static[E]="PostgresJsTransaction";transaction(Z){return this.session.client.savepoint((Y)=>{let X=new b8(Y,this.dialect,this.schema,this.session.options),G=new UX(this.dialect,X,this.schema);return Z(G)})}}class lW extends h8{static[E]="PostgresJsDatabase"}function q2(Z,Y={}){let X=(Q)=>Q;for(let Q of["1184","1082","1083","1114","1182","1185","1115","1231"])Z.options.parsers[Q]=X,Z.options.serializers[Q]=X;Z.options.serializers["114"]=X,Z.options.serializers["3802"]=X;let G=new i4({casing:Y.casing}),_;if(Y.logger===!0)_=new jY;else if(Y.logger!==!1)_=Y.logger;let $;if(Y.schema){let Q=OW(Y.schema,MW);$={fullSchema:Y.schema,schema:Q.tables,tableNamesMap:Q.tableNamesMap}}let W=new b8(Z,G,$,{logger:_,cache:Y.cache}),H=new lW(G,W,$);if(H.$client=Z,H.$cache=Y.cache,H.$cache)H.$cache.invalidate=Y.cache?.onMutate;return H}function DZ(...Z){if(typeof Z[0]==="string"){let Y=C2(Z[0]);return q2(Y,Z[1])}if(o_(Z[0])){let{connection:Y,client:X,...G}=Z[0];if(X)return q2(X,G);if(typeof Y==="object"&&Y.url!==void 0){let{url:$,...W}=Y,H=C2($,W);return q2(H,G)}let _=C2(Y);return q2(_,G)}return q2(Z[0],Z[1])}((Z)=>{function Y(X){return q2({options:{parsers:{},serializers:{}}},X)}Z.mock=Y})(DZ||(DZ={}));var EX={};sH(EX,{users:()=>o4,untrackedUserColumnNames:()=>BE,twoFactorMethod:()=>sW,trackedUserColumnName:()=>KE,trackableUserColumnNames:()=>nW,signInHistory:()=>TE,role:()=>oW,players:()=>FX,passwordResetAttempts:()=>qE,games:()=>VZ,banishedIps:()=>jE,accountActions:()=>CE,accountAction:()=>rW});function j4(){return t0({length:24}).$type()}function iW(Z){return L`lower(${Z})`}var OZ=L`TO_CHAR(NOW() AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.MS"Z"')`,oW=O8("role",["admin","user"]),o4=C4("users",{id:P1().primaryKey().defaultRandom(),username:t0({length:16}).notNull(),emailOffered:t0({length:254}).notNull(),emailVerified:t0({length:254}),password:t0({length:254}),createdAtIso:j4().notNull().default(OZ),createdIp:t0({length:45}).notNull(),isActive:w8().notNull().default(!1),verifiedAtIso:j4(),userRole:oW().default("user")},(Z)=>[tY("usernameUniqueIndex").on(iW(Z.username)),tY("emailVerifiedUniqueIndex").on(iW(Z.emailVerified))]),BE=["id","createdAtIso","createdIp","isActive","verifiedAtIso"],nW=["username","emailOffered","emailVerified","password","userRole"],KE=O8("trackedUserColumnName",nW),rW=O8("accountAction",["cooldown","confirmEmail","signIn","resetPassword"]),CE=C4("accountActions",{userId:P1().references(()=>o4.id).primaryKey(),action:rW().notNull(),code:t0({length:254}).notNull(),wrongCodeCount:I8().notNull().default(0),expiresAtIso:j4().notNull()}),VZ=C4("games",{id:P1().primaryKey().defaultRandom()}),FX=C4("players",{userId:P1().notNull().references(()=>o4.id,{onDelete:"cascade"}),gameId:P1().notNull().references(()=>VZ.id,{onDelete:"cascade"}),score:I8().notNull()},(Z)=>[c3({name:"players_userId_gameId_pk",columns:[Z.userId,Z.gameId]})]),TE=C4("signInHistory",{id:P1().primaryKey().defaultRandom(),userId:P1().references(()=>o4.id,{onDelete:"cascade"}),signInTimeIso:j4().notNull().default(OZ),ipAddress:t0({length:45}).notNull(),userAgent:t0({length:1024}),successful:w8().notNull().default(!1)}),sW=O8("twoFactorMethod",["email","phone"]),qE=C4("passwordResetAttempts",{id:P1().primaryKey().defaultRandom(),userId:P1().notNull().references(()=>o4.id,{onDelete:"cascade"}),requestedIp:t0({length:45}).notNull(),requestedAtIso:j4().notNull().default(OZ),succeededIp:t0({length:45}),succeededAtIso:j4(),verificationMethod:sW().notNull()}),jE=C4("banishedIps",{ip:t0({length:45}).primaryKey(),reason:t0({length:2048}).notNull(),banishedAtIso:j4().notNull().default(OZ),banishedUntilIso:j4()});var __dirname="/home/runner/work/wayforge/wayforge/apps/tempest.games/src/database";class LX{options;sql;drizzle;observers=new Map;async setupTriggersAndNotifications(){await this.sql.file(PE.resolve(__dirname,"notify_update.sql"));let Z=[d0(o4),d0(VZ),d0(FX)];await this.sql`SELECT create_notify_triggers(${this.sql.array(Z)})`,await this.sql.listen("table_update",(Y)=>{let X=Y.split(","),G=X[0],_=X[1],$=`${G}("${_}")`;if(this.observers.has($))this.observers.get($).next($)})}constructor(Z=!1,Y={host:g1.POSTGRES_HOST,port:g1.POSTGRES_PORT,user:g1.POSTGRES_USER,password:g1.POSTGRES_PASSWORD,database:g1.POSTGRES_DATABASE}){this.options=Y,this.sql=C2(Y),this.drizzle=DZ(this.sql,{schema:EX,logger:Z})}observe(Z,Y){if(!this.observers.has(Z))this.observers.set(Z,new _0);this.observers.get(Z).subscribe("SINGLETON",Y)}}var MZ={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 SE(Z){return Number.parseInt(Z,10)}var vE=F1(MZ),xE=vE.keyof().pipe((Z)=>SE(Z)),aW=F1([xE,"string"]);var OX=new R_(process),{logger:O1}=OX;Object.assign(console,O1,{log:O1.info});O1.info("ready");var DX=eW(import.meta.dir,"..","app"),Hf=new LX({logQuery(Z,Y){O1.info("\uD83D\uDCDD query",Z,Y)}});bE({hostname:"0.0.0.0",port:g1.FRONTEND_PORT??3333,...h6??void 0,async fetch(Z){try{let Y=new Date,X=new URL(Z.url);if(O1.info(Z.method,X.pathname),X.pathname==="/")return new Response(Bun.file(eW(DX,"index.html")));if(X.pathname==="/index.html")return Response.redirect("/");let G=hE(DX,X.pathname),_=kE(G);if(!_.startsWith(DX))throw[403,"Access Denied"];if(!await tW(_).exists())return Response.redirect("/");return new Response(tW(_))}catch(Y){let X=aW(Y);if(X instanceof F1.errors===!1){let[G,_]=X,W=`${MZ[G]}. ${_}`;return O1.info(`\u274C ${G}: ${W}`),new Response(W,{status:G})}if(Y instanceof Error)O1.error(Y.message);else{let G=f6(Y);O1.error("frontend server threw",G)}return new Response(MZ[500],{status:500})}}});function AZ(){O1.info("\uD83D\uDEEC frontend server exiting"),process.exit(0)}process.on("SIGINT",()=>{O1.info("\u2757 received SIGINT; exiting gracefully"),AZ()});process.on("SIGTERM",()=>{O1.info("\u2757 received SIGTERM; exiting gracefully"),AZ()});process.on("exit",()=>{O1.info("\u2757 received exit; exiting gracefully"),AZ()});OX.on("timeToStop",()=>{O1.info('\u2757 backend server received signal "timeToStop"; exiting gracefully'),AZ()});var{version:yE}=await Bun.file(fE.resolve(import.meta.dir,"../package.json")).json();O1.info(`\uD83D\uDEEB frontend v${yE} running at http://localhost:${g1.FRONTEND_PORT}/`);OX.emit("alive");
93
+ `;await Z.execute(V`CREATE SCHEMA IF NOT EXISTS ${V.identifier(G)}`),await Z.execute($);let H=(await Z.all(V`select id, hash, created_at from ${V.identifier(G)}.${V.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(V.raw(z));await Q.execute(V`insert into ${V.identifier(G)}.${V.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=[V`with `];for(let[X,_]of Y.entries())if(Z.push(V`${V.identifier(_._.alias)} as (${_._.sql})`),X<Y.length-1)Z.push(V`, `);return Z.push(V` `),V.join(Z)}buildDeleteQuery({table:Y,where:Z,returning:X,withList:_}){let G=this.buildWithCTE(_),$=X?V` returning ${this.buildSelection(X,{isSingleTable:!0})}`:void 0,W=Z?V` where ${Z}`:void 0;return V`${G}delete from ${Y}${W}${$}`}buildUpdateSet(Y,Z){let X=Y[P.Symbol.Columns],_=Object.keys(X).filter(($)=>Z[$]!==void 0||X[$]?.onUpdateFn!==void 0),G=_.length;return V.join(_.flatMap(($,W)=>{let H=X[$],Q=Z[$]??V.param(H.onUpdateFn(),H),J=V`${V.identifier(this.casing.getColumnCasing(H))} = ${Q}`;if(W<G-1)return[J,V.raw(", ")];return[J]}))}buildUpdateQuery({table:Y,set:Z,where:X,returning:_,withList:G,from:$,joins:W}){let H=this.buildWithCTE(G),Q=Y[u0.Symbol.Name],J=Y[u0.Symbol.Schema],z=Y[u0.Symbol.OriginalName],F=Q===z?void 0:Q,O=V`${J?V`${V.identifier(J)}.`:void 0}${V.identifier(z)}${F&&V` ${V.identifier(F)}`}`,L=this.buildUpdateSet(Y,Z),w=$&&V.join([V.raw(" from "),this.buildFromTable($)]),R=this.buildJoins(W),b=_?V` returning ${this.buildSelection(_,{isSingleTable:!$})}`:void 0,x=X?V` where ${X}`:void 0;return V`${H}update ${O} set ${L}${w}${R}${x}${b}`}buildSelection(Y,{isSingleTable:Z=!1}={}){let X=Y.length,_=Y.flatMap(({field:G},$)=>{let W=[];if(M(G,f.Aliased)&&G.isSelectionField)W.push(V.identifier(G.fieldAlias));else if(M(G,f.Aliased)||M(G,f)){let H=M(G,f.Aliased)?G.sql:G;if(Z)W.push(new f(H.queryChunks.map((Q)=>{if(M(Q,j))return V.identifier(this.casing.getColumnCasing(Q));return Q})));else W.push(H);if(M(G,f.Aliased))W.push(V` as ${V.identifier(G.fieldAlias)}`)}else if(M(G,F0))if(Z)W.push(V.identifier(this.casing.getColumnCasing(G)));else W.push(G);if($<X-1)W.push(V`, `);return W});return V.join(_)}buildJoins(Y){if(!Y||Y.length===0)return;let Z=[];for(let[X,_]of Y.entries()){if(X===0)Z.push(V` `);let G=_.table,$=_.lateral?V` lateral`:void 0,W=_.on?V` on ${_.on}`:void 0;if(M(G,u0)){let H=G[u0.Symbol.Name],Q=G[u0.Symbol.Schema],J=G[u0.Symbol.OriginalName],z=H===J?void 0:_.alias;Z.push(V`${V.raw(_.joinType)} join${$} ${Q?V`${V.identifier(Q)}.`:void 0}${V.identifier(J)}${z&&V` ${V.identifier(z)}`}${W}`)}else if(M(G,V1)){let H=G[M0].name,Q=G[M0].schema,J=G[M0].originalName,z=H===J?void 0:_.alias;Z.push(V`${V.raw(_.joinType)} join${$} ${Q?V`${V.identifier(Q)}.`:void 0}${V.identifier(J)}${z&&V` ${V.identifier(z)}`}${W}`)}else Z.push(V`${V.raw(_.joinType)} join${$} ${G}${W}`);if(X<Y.length-1)Z.push(V` `)}return V.join(Z)}buildFromTable(Y){if(M(Y,P)&&Y[P.Symbol.IsAlias]){let Z=V`${V.identifier(Y[P.Symbol.OriginalName])}`;if(Y[P.Symbol.Schema])Z=V`${V.identifier(Y[P.Symbol.Schema])}.${Z}`;return V`${Z} ${V.identifier(Y[P.Symbol.Name])}`}return Y}buildSelectQuery({withList:Y,fields:Z,fieldsFlat:X,where:_,having:G,table:$,joins:W,orderBy:H,groupBy:Q,limit:J,offset:z,lockingClause:F,distinct:O,setOperators:L}){let w=X??T1(Z);for(let t of w)if(M(t.field,F0)&&d0(t.field.table)!==(M($,S0)?$._.alias:M($,v8)?$[M0].name:M($,f)?void 0:d0($))&&!((I0)=>W?.some(({alias:h0})=>h0===(I0[P.Symbol.IsAlias]?d0(I0):I0[P.Symbol.BaseName])))(t.field.table)){let I0=d0(t.field.table);throw new Error(`Your "${t.path.join("->")}" field references a column "${I0}"."${t.field.name}", but the table "${I0}" is not part of the query! Did you forget to join it?`)}let R=!W||W.length===0,b=this.buildWithCTE(Y),x;if(O)x=O===!0?V` distinct`:V` distinct on (${V.join(O.on,V`, `)})`;let h=this.buildSelection(w,{isSingleTable:R}),g=this.buildFromTable($),B=this.buildJoins(W),K=_?V` where ${_}`:void 0,C=G?V` having ${G}`:void 0,q;if(H&&H.length>0)q=V` order by ${V.join(H,V`, `)}`;let c;if(Q&&Q.length>0)c=V` group by ${V.join(Q,V`, `)}`;let n=typeof J==="object"||typeof J==="number"&&J>=0?V` limit ${J}`:void 0,N=z?V` offset ${z}`:void 0,s=V.empty();if(F){let t=V` for ${V.raw(F.strength)}`;if(F.config.of)t.append(V` of ${V.join(Array.isArray(F.config.of)?F.config.of:[F.config.of],V`, `)}`);if(F.config.noWait)t.append(V` nowait`);else if(F.config.skipLocked)t.append(V` skip locked`);s.append(t)}let p=V`${b}select${x} ${h} from ${g}${B}${K}${c}${C}${q}${n}${N}${s}`;if(L.length>0)return this.buildSetOperations(p,L);return p}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:$,offset:W}}){let H=V`(${Y.getSQL()}) `,Q=V`(${_.getSQL()})`,J;if($&&$.length>0){let L=[];for(let w of $)if(M(w,j))L.push(V.identifier(w.name));else if(M(w,f)){for(let R=0;R<w.queryChunks.length;R++){let b=w.queryChunks[R];if(M(b,j))w.queryChunks[R]=V.identifier(b.name)}L.push(V`${w}`)}else L.push(V`${w}`);J=V` order by ${V.join(L,V`, `)} `}let z=typeof G==="object"||typeof G==="number"&&G>=0?V` limit ${G}`:void 0,F=V.raw(`${Z} ${X?"all ":""}`),O=W?V` offset ${W}`:void 0;return V`${H}${F}${Q}${J}${z}${O}`}buildInsertQuery({table:Y,values:Z,onConflict:X,returning:_,withList:G,select:$,overridingSystemValue_:W}){let H=[],Q=Y[P.Symbol.Columns],J=Object.entries(Q).filter(([b,x])=>!x.shouldDisableInsert()),z=J.map(([,b])=>V.identifier(this.casing.getColumnCasing(b)));if($){let b=Z;if(M(b,f))H.push(b);else H.push(b.getSQL())}else{let b=Z;H.push(V.raw("values "));for(let[x,h]of b.entries()){let g=[];for(let[B,K]of J){let C=h[B];if(C===void 0||M(C,A1)&&C.value===void 0)if(K.defaultFn!==void 0){let q=K.defaultFn(),c=M(q,f)?q:V.param(q,K);g.push(c)}else if(!K.default&&K.onUpdateFn!==void 0){let q=K.onUpdateFn(),c=M(q,f)?q:V.param(q,K);g.push(c)}else g.push(V`default`);else g.push(C)}if(H.push(g),x<b.length-1)H.push(V`, `)}}let F=this.buildWithCTE(G),O=V.join(H),L=_?V` returning ${this.buildSelection(_,{isSingleTable:!0})}`:void 0,w=X?V` on conflict ${X}`:void 0,R=W===!0?V`overriding system value `:void 0;return V`${F}insert into ${Y} ${z} ${R}${O}${w}${L}`}buildRefreshMaterializedViewQuery({view:Y,concurrently:Z,withNoData:X}){let _=Z?V` concurrently`:void 0,G=X?V` with no data`:void 0;return V`refresh materialized view${_} ${Y}${G}`}prepareTyping(Y){if(M(Y,g6)||M(Y,y6))return"json";else if(M(Y,p6))return"decimal";else if(M(Y,m6))return"time";else if(M(Y,u6)||M(Y,d6))return"timestamp";else if(M(Y,k6)||M(Y,b6))return"date";else if(M(Y,c6))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:$,tableAlias:W,nestedQueryRelation:H,joinOn:Q}){let J=[],z,F,O=[],L,w=[];if($===!0)J=Object.entries(G.columns).map(([x,h])=>({dbKey:h.name,tsKey:x,field:i1(h,W),relationTableTsKey:void 0,isJson:!1,selection:[]}));else{let b=Object.fromEntries(Object.entries(G.columns).map(([C,q])=>[C,i1(q,W)]));if($.where){let C=typeof $.where==="function"?$.where(b,_W()):$.where;L=C&&R8(C,W)}let x=[],h=[];if($.columns){let C=!1;for(let[q,c]of Object.entries($.columns)){if(c===void 0)continue;if(q in G.columns){if(!C&&c===!0)C=!0;h.push(q)}}if(h.length>0)h=C?h.filter((q)=>$.columns?.[q]===!0):Object.keys(G.columns).filter((q)=>!h.includes(q))}else h=Object.keys(G.columns);for(let C of h){let q=G.columns[C];x.push({tsKey:C,value:q})}let g=[];if($.with)g=Object.entries($.with).filter((C)=>!!C[1]).map(([C,q])=>({tsKey:C,queryConfig:q,relation:G.relations[C]}));let B;if($.extras){B=typeof $.extras==="function"?$.extras(b,{sql:V}):$.extras;for(let[C,q]of Object.entries(B))x.push({tsKey:C,value:M5(q,W)})}for(let{tsKey:C,value:q}of x)J.push({dbKey:M(q,f.Aliased)?q.fieldAlias:G.columns[C].name,tsKey:C,field:M(q,F0)?i1(q,W):q,relationTableTsKey:void 0,isJson:!1,selection:[]});let K=typeof $.orderBy==="function"?$.orderBy(b,GW()):$.orderBy??[];if(!Array.isArray(K))K=[K];O=K.map((C)=>{if(M(C,F0))return i1(C,W);return R8(C,W)}),z=$.limit,F=$.offset;for(let{tsKey:C,queryConfig:q,relation:c}of g){let n=WW(Z,X,c),N=g4(c.referencedTable),s=X[N],p=`${W}_${C}`,t=B8(...n.fields.map(($1,r1)=>l6(i1(n.references[r1],p),i1($1,W)))),I0=this.buildRelationalQueryWithoutPK({fullSchema:Y,schema:Z,tableNamesMap:X,table:Y[s],tableConfig:Z[s],queryConfig:M(c,K4)?q===!0?{limit:1}:{...q,limit:1}:q,tableAlias:p,joinOn:t,nestedQueryRelation:c}),h0=V`${V.identifier(p)}.${V.identifier("data")}`.as(C);w.push({on:V`true`,table:new S0(I0.sql,{},p),alias:p,joinType:"left",lateral:!0}),J.push({dbKey:C,tsKey:C,field:h0,relationTableTsKey:s,isJson:!0,selection:I0.selection})}}if(J.length===0)throw new f6({message:`No fields selected for table "${G.tsName}" ("${W}")`});let R;if(L=B8(Q,L),H){let b=V`json_build_array(${V.join(J.map(({field:g,tsKey:B,isJson:K})=>K?V`${V.identifier(`${W}_${B}`)}.${V.identifier("data")}`:M(g,f.Aliased)?g.sql:g),V`, `)})`;if(M(H,T8))b=V`coalesce(json_agg(${b}${O.length>0?V` order by ${V.join(O,V`, `)}`:void 0}), '[]'::json)`;let x=[{dbKey:"data",tsKey:"data",field:b.as("data"),isJson:!0,relationTableTsKey:G.tsName,selection:J}];if(z!==void 0||F!==void 0||O.length>0)R=this.buildSelectQuery({table:x6(_,W),fields:{},fieldsFlat:[{path:[],field:V.raw("*")}],where:L,limit:z,offset:F,orderBy:O,setOperators:[]}),L=void 0,z=void 0,F=void 0,O=[];else R=x6(_,W);R=this.buildSelectQuery({table:M(R,u0)?R:new S0(R,{},W),fields:{},fieldsFlat:x.map(({field:g})=>({path:[],field:M(g,F0)?i1(g,W):g})),joins:w,where:L,limit:z,offset:F,orderBy:O,setOperators:[]})}else R=this.buildSelectQuery({table:x6(_,W),fields:{},fieldsFlat:J.map(({field:b})=>({path:[],field:M(b,F0)?i1(b,W):b})),joins:w,where:L,limit:z,offset:F,orderBy:O,setOperators:[]});return{tableTsKey:G.tsName,sql:R,selection:J}}}class l5{static[E]="TypedQueryBuilder";getSelectedFields(){return this._.selectedFields}}class G1{static[E]="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,S0))_=Object.fromEntries(Object.keys(X._.selectedFields).map((G)=>[G,X[G]]));else if(M(X,v8))_=X[M0].selectedFields;else if(M(X,f))_={};else _=h7(X);return new o5({table:X,fields:_,isPartialSelect:Z,session:this.session,dialect:this.dialect,withList:this.withList,distinct:this.distinct}).setToken(this.authToken)}}class PW extends l5{static[E]="PgSelectQueryBuilder";_;config;joinsNotNullableMap;tableName;isPartialSelect;session;dialect;cacheConfig=void 0;usedTables=new Set;constructor({table:Y,fields:Z,isPartialSelect:X,session:_,dialect:G,withList:$,distinct:W}){super();this.config={withList:$,table:Y,fields:{...Z},distinct:W,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 m1(Y))this.usedTables.add(H)}getUsedTables(){return[...this.usedTables]}createJoin(Y,Z){return(X,_)=>{let G=this.tableName,$=J4(X);for(let W of m1(X))this.usedTables.add(W);if(typeof $==="string"&&this.config.joins?.some((W)=>W.alias===$))throw new Error(`Alias "${$}" 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 $==="string"&&!M(X,f)){let W=M(X,S0)?X._.selectedFields:M(X,V1)?X[M0].selectedFields:X[P.Symbol.Columns];this.config.fields[$]=W}}if(typeof _==="function")_=_(new Proxy(this.config.fields,new q0({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));if(!this.config.joins)this.config.joins=[];if(this.config.joins.push({on:_,table:X,joinType:Y,alias:$,lateral:Z}),typeof $==="string")switch(Y){case"left":{this.joinsNotNullableMap[$]=!1;break}case"right":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([W])=>[W,!1])),this.joinsNotNullableMap[$]=!0;break}case"cross":case"inner":{this.joinsNotNullableMap[$]=!0;break}case"full":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([W])=>[W,!1])),this.joinsNotNullableMap[$]=!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(RE()):X;if(!w8(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 q0({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));return this.config.where=Y,this}having(Y){if(typeof Y==="function")Y=Y(new Proxy(this.config.fields,new q0({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 q0({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 q0({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(...m1(this.config.table)),this.config.joins)for(let X of this.config.joins)Z.push(...m1(X.table));return new Proxy(new S0(this.getSQL(),this.config.fields,Y,!1,[...new Set(Z)]),new q0({alias:Y,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}getSelectedFields(){return new Proxy(this.config.fields,new q0({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 o5 extends PW{static[E]="PgSelect";_prepare(Y){let{session:Z,config:X,dialect:_,joinsNotNullableMap:G,authToken:$,cacheConfig:W,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 E0.startActiveSpan("drizzle.prepareQuery",()=>{let J=T1(Q),z=Z.prepareQuery(_.sqlToQuery(this.getSQL()),J,Y,!0,void 0,{type:"select",tables:[...H]},W);return z.joinsNotNullableMap=G,z.setToken($)})}prepare(Y){return this._prepare(Y)}authToken;setToken(Y){return this.authToken=Y,this}execute=(Y)=>{return E0.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(Y,this.authToken)})}}f7(o5,[_1]);function I2(Y,Z){return(X,_,...G)=>{let $=[_,...G].map((W)=>({type:Y,isAll:Z,rightSelect:W}));for(let W of $)if(!w8(X.getSelectedFields(),W.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($)}}var RE=()=>({union:wE,unionAll:NE,intersect:IE,intersectAll:KE,except:BE,exceptAll:TE}),wE=I2("union",!1),NE=I2("union",!0),IE=I2("intersect",!1),KE=I2("intersect",!0),BE=I2("except",!1),TE=I2("except",!0);class x8{static[E]="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 L8(G.getSQL(),Z??("getSelectedFields"in G?G.getSelectedFields()??{}:{}),Y,!0),new q0({alias:Y,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}};with(...Y){let Z=this;function X($){return new G1({fields:$??void 0,session:void 0,dialect:Z.getDialect(),withList:Y})}function _($){return new G1({fields:$??void 0,session:void 0,dialect:Z.getDialect(),distinct:!0})}function G($,W){return new G1({fields:W??void 0,session:void 0,dialect:Z.getDialect(),distinct:{on:$}})}return{select:X,selectDistinct:_,selectDistinctOn:G}}select(Y){return new G1({fields:Y??void 0,session:void 0,dialect:this.getDialect()})}selectDistinct(Y){return new G1({fields:Y??void 0,session:void 0,dialect:this.getDialect(),distinct:!0})}selectDistinctOn(Y,Z){return new G1({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 m1(Y){if(M(Y,u0))return[Y[y4]?`${Y[y4]}.${Y[P.Symbol.BaseName]}`:Y[P.Symbol.BaseName]];if(M(Y,S0))return Y._.usedTables??[];if(M(Y,f))return Y.usedTables??[];return[]}class $Y extends _1{constructor(Y,Z,X,_){super();this.session=Z,this.dialect=X,this.config={table:Y,withList:_}}static[E]="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=T1(Y),this}getSQL(){return this.dialect.buildDeleteQuery(this.config)}toSQL(){let{typings:Y,...Z}=this.dialect.sqlToQuery(this.getSQL());return Z}_prepare(Y){return E0.startActiveSpan("drizzle.prepareQuery",()=>{return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,Y,!0,void 0,{type:"delete",tables:m1(this.config.table)},this.cacheConfig)})}prepare(Y){return this._prepare(Y)}authToken;setToken(Y){return this.authToken=Y,this}execute=(Y)=>{return E0.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(Y,this.authToken)})};getSelectedFields(){return this.config.returningFields?new Proxy(this.config.returningFields,new q0({alias:d0(this.config.table),sqlAliasedBehavior:"alias",sqlBehavior:"error"})):void 0}$dynamic(){return this}}class WY{constructor(Y,Z,X,_,G){this.table=Y,this.session=Z,this.dialect=X,this.withList=_,this.overridingSystemValue_=G}static[E]="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 $ of Object.keys(X)){let W=X[$];_[$]=M(W,f)?W:new A1(W,G[$])}return _});return new i5(this.table,Z,this.session,this.dialect,this.withList,!1,this.overridingSystemValue_).setToken(this.authToken)}select(Y){let Z=typeof Y==="function"?Y(new x8):Y;if(!M(Z,f)&&!w8(this.table[S6],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 i5(this.table,Z,this.session,this.dialect,this.withList,!0)}}class i5 extends _1{constructor(Y,Z,X,_,G,$,W){super();this.session=X,this.dialect=_,this.config={table:Y,values:Z,withList:G,select:$,overridingSystemValue_:W}}static[E]="PgInsert";config;cacheConfig;returning(Y=this.config.table[P.Symbol.Columns]){return this.config.returningFields=Y,this.config.returning=T1(Y),this}onConflictDoNothing(Y={}){if(Y.target===void 0)this.config.onConflict=V`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?V` where ${Y.where}`:void 0;this.config.onConflict=V`(${V.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?V` where ${Y.where}`:void 0,X=Y.targetWhere?V` where ${Y.targetWhere}`:void 0,_=Y.setWhere?V` where ${Y.setWhere}`:void 0,G=this.dialect.buildUpdateSet(this.config.table,h6(this.config.table,Y.set)),$="";return $=Array.isArray(Y.target)?Y.target.map((W)=>this.dialect.escapeName(this.dialect.casing.getColumnCasing(W))).join(","):this.dialect.escapeName(this.dialect.casing.getColumnCasing(Y.target)),this.config.onConflict=V`(${V.raw($)})${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 E0.startActiveSpan("drizzle.prepareQuery",()=>{return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,Y,!0,void 0,{type:"insert",tables:m1(this.config.table)},this.cacheConfig)})}prepare(Y){return this._prepare(Y)}authToken;setToken(Y){return this.authToken=Y,this}execute=(Y)=>{return E0.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(Y,this.authToken)})};getSelectedFields(){return this.config.returningFields?new Proxy(this.config.returningFields,new q0({alias:d0(this.config.table),sqlAliasedBehavior:"alias",sqlBehavior:"error"})):void 0}$dynamic(){return this}}class n5 extends _1{constructor(Y,Z,X){super();this.session=Z,this.dialect=X,this.config={view:Y}}static[E]="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 E0.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 E0.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(Y,this.authToken)})}}class HY{constructor(Y,Z,X,_){this.table=Y,this.session=Z,this.dialect=X,this.withList=_}static[E]="PgUpdateBuilder";authToken;setToken(Y){return this.authToken=Y,this}set(Y){return new SW(this.table,h6(this.table,Y),this.session,this.dialect,this.withList).setToken(this.authToken)}}class SW 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[E]="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,u0))return Y[P.Symbol.Columns];else if(M(Y,S0))return Y._.selectedFields;return Y[M0].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,f)?this.getTableLikeFields(this.config.from):void 0;X=X(new Proxy(this.config.table[P.Symbol.Columns],new q0({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})),G&&new Proxy(G,new q0({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,f)){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,f)){let G=this.getTableLikeFields(X.table);Y[_]=G}}}}return this.config.returningFields=Y,this.config.returning=T1(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:m1(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 q0({alias:d0(this.config.table),sqlAliasedBehavior:"alias",sqlBehavior:"error"})):void 0}$dynamic(){return this}}class f8 extends f{constructor(Y){super(f8.buildEmbeddedCount(Y.source,Y.filters).queryChunks);this.params=Y,this.mapWith(Number),this.session=Y.session,this.sql=f8.buildCount(Y.source,Y.filters)}sql;token;static[E]="PgCountBuilder";[Symbol.toStringTag]="PgCountBuilder";session;static buildEmbeddedCount(Y,Z){return V`(select count(*) from ${Y}${V.raw(" where ").if(Z)}${Z})`}static buildCount(Y,Z){return V`select count(*) as count from ${Y}${V.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 s5{constructor(Y,Z,X,_,G,$,W){this.fullSchema=Y,this.schema=Z,this.tableNamesMap=X,this.table=_,this.tableConfig=G,this.dialect=$,this.session=W}static[E]="PgRelationalQueryBuilder";findMany(Y){return new r5(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,Y?Y:{},"many")}findFirst(Y){return new r5(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,Y?{...Y,limit:1}:{limit:1},"first")}}class r5 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=$,this.session=W,this.config=H,this.mode=Q}static[E]="PgRelationalQuery";_prepare(Y){return E0.startActiveSpan("drizzle.prepareQuery",()=>{let{query:Z,builtQuery:X}=this._toSQL();return this.session.prepareQuery(X,void 0,Y,!0,(_,G)=>{let $=_.map((W)=>o6(this.schema,this.tableConfig,W,Z.selection,G));if(this.mode==="first")return $[0];return $})})}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 E0.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(void 0,this.authToken)})}}class t5 extends _1{constructor(Y,Z,X,_){super();this.execute=Y,this.sql=Z,this.query=X,this.mapBatchResult=_}static[E]="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 h8{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 s5(X.fullSchema,this._.schema,this._.tableNamesMap,X.fullSchema[_],G,Y,Z);this.$cache={invalidate:async(_)=>{}}}static[E]="PgDatabase";query;$with=(Y,Z)=>{let X=this;return{as:(G)=>{if(typeof G==="function")G=G(new x8(X.dialect));return new Proxy(new L8(G.getSQL(),Z??("getSelectedFields"in G?G.getSelectedFields()??{}:{}),Y,!0),new q0({alias:Y,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}};$count(Y,Z){return new f8({source:Y,filters:Z,session:this.session})}$cache;with(...Y){let Z=this;function X(Q){return new G1({fields:Q??void 0,session:Z.session,dialect:Z.dialect,withList:Y})}function _(Q){return new G1({fields:Q??void 0,session:Z.session,dialect:Z.dialect,withList:Y,distinct:!0})}function G(Q,J){return new G1({fields:J??void 0,session:Z.session,dialect:Z.dialect,withList:Y,distinct:{on:Q}})}function $(Q){return new HY(Q,Z.session,Z.dialect,Y)}function W(Q){return new WY(Q,Z.session,Z.dialect,Y)}function H(Q){return new $Y(Q,Z.session,Z.dialect,Y)}return{select:X,selectDistinct:_,selectDistinctOn:G,update:$,insert:W,delete:H}}select(Y){return new G1({fields:Y??void 0,session:this.session,dialect:this.dialect})}selectDistinct(Y){return new G1({fields:Y??void 0,session:this.session,dialect:this.dialect,distinct:!0})}selectDistinctOn(Y,Z){return new G1({fields:Z??void 0,session:this.session,dialect:this.dialect,distinct:{on:Y}})}update(Y){return new HY(Y,this.session,this.dialect)}insert(Y){return new WY(Y,this.session,this.dialect)}delete(Y){return new $Y(Y,this.session,this.dialect)}refreshMaterializedView(Y){return new n5(Y,this.session,this.dialect)}authToken;execute(Y){let Z=typeof Y==="string"?V.raw(Y):Y.getSQL(),X=this.dialect.sqlToQuery(Z),_=this.session.prepareQuery(X,void 0,void 0,!1);return new t5(()=>_.execute(void 0,this.authToken),Z,X,(G)=>_.mapResult(G,!0))}transaction(Y,Z){return this.session.transaction(Y,Z)}}class vW{static[E]="Cache"}class k8 extends vW{strategy(){return"all"}static[E]="NoopCache";async get(Y){return}async put(Y,Z,X,_){}async onMutate(Y){}}async function a5(Y,Z){let X=`${Y}-${JSON.stringify(Z)}`,G=new TextEncoder().encode(X),$=await crypto.subtle.digest("SHA-256",G);return[...new Uint8Array($)].map((Q)=>Q.toString(16).padStart(2,"0")).join("")}class e5{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[E]="PgPreparedQuery";joinsNotNullableMap;async queryWithCache(Y,Z,X){if(this.cache===void 0||M(this.cache,k8)||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 a5(Y,Z),this.queryMetadata.tables,this.cacheConfig.tag!==void 0,this.cacheConfig.autoInvalidate);if(_===void 0){let G;try{G=await X()}catch($){throw new H4(Y,Z,$)}return await this.cache.put(this.cacheConfig.tag??await a5(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 YX{constructor(Y){this.dialect=Y}static[E]="PgSession";execute(Y,Z){return E0.startActiveSpan("drizzle.operation",()=>{return E0.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 ZX extends h8{constructor(Y,Z,X,_=0){super(Y,Z,X);this.schema=X,this.nestedIndex=_}static[E]="PgTransaction";rollback(){throw new A5}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 V.raw(Z.join(" "))}setTransaction(Y){return this.session.execute(V`set transaction ${this.getTransactionConfigSQL(Y)}`)}}class xW extends e5{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[E]="PostgresJsPreparedQuery";async execute(Y={}){return E0.startActiveSpan("drizzle.execute",async(Z)=>{let X=L5(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:$,joinsNotNullableMap:W,customResultMapper:H}=this;if(!_&&!H)return E0.startActiveSpan("drizzle.driver.execute",()=>{return this.queryWithCache(G,X,async()=>{return await $.unsafe(G,X)})});let Q=await E0.startActiveSpan("drizzle.driver.execute",()=>{return Z?.setAttributes({"drizzle.query.text":G,"drizzle.query.params":JSON.stringify(X)}),this.queryWithCache(G,X,async()=>{return await $.unsafe(G,X).values()})});return E0.startActiveSpan("drizzle.mapResponse",()=>{return H?H(Q):Q.map((J)=>x7(_,J,W))})})}all(Y={}){return E0.startActiveSpan("drizzle.execute",async(Z)=>{let X=L5(this.params,Y);return Z?.setAttributes({"drizzle.query.text":this.queryString,"drizzle.query.params":JSON.stringify(X)}),this.logger.logQuery(this.queryString,X),E0.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 b8 extends YX{constructor(Y,Z,X,_={}){super(Z);this.client=Y,this.schema=X,this.options=_,this.logger=_.logger??new w5,this.cache=_.cache??new k8}static[E]="PostgresJsSession";logger;cache;prepareQuery(Y,Z,X,_,G,$,W){return new xW(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 b8(X,this.dialect,this.schema,this.options),G=new XX(this.dialect,_,this.schema);if(Z)await G.setTransaction(Z);return Y(G)})}}class XX extends ZX{constructor(Y,Z,X,_=0){super(Y,Z,X,_);this.session=Z}static[E]="PostgresJsTransaction";transaction(Y){return this.session.client.savepoint((Z)=>{let X=new b8(Z,this.dialect,this.schema,this.session.options),_=new XX(this.dialect,X,this.schema);return Y(_)})}}class fW extends h8{static[E]="PostgresJsDatabase"}function K2(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 R5;else if(Z.logger!==!1)G=Z.logger;let $;if(Z.schema){let Q=$W(Z.schema,HW);$={fullSchema:Z.schema,schema:Q.tables,tableNamesMap:Q.tableNamesMap}}let W=new b8(Y,_,$,{logger:G,cache:Z.cache}),H=new fW(_,W,$);if(H.$client=Y,H.$cache=Z.cache,H.$cache)H.$cache.invalidate=Z.cache?.onMutate;return H}function JY(...Y){if(typeof Y[0]==="string"){let Z=N2(Y[0]);return K2(Z,Y[1])}if(k7(Y[0])){let{connection:Z,client:X,..._}=Y[0];if(X)return K2(X,_);if(typeof Z==="object"&&Z.url!==void 0){let{url:$,...W}=Z,H=N2($,W);return K2(H,_)}let G=N2(Z);return K2(G,_)}return K2(Y[0],Y[1])}((Y)=>{function Z(X){return K2({options:{parsers:{},serializers:{}}},X)}Y.mock=Z})(JY||(JY={}));var GX={};gH(GX,{users:()=>l4,untrackedUserColumnNames:()=>CE,twoFactorMethod:()=>gW,trackedUserColumnName:()=>qE,trackableUserColumnNames:()=>bW,signInHistory:()=>PE,role:()=>kW,players:()=>_X,passwordResetAttempts:()=>SE,games:()=>zY,banishedIps:()=>vE,accountActions:()=>jE,accountAction:()=>yW});function T4(){return t0({length:24}).$type()}function hW(Y){return V`lower(${Y})`}var QY=V`TO_CHAR(NOW() AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.MS"Z"')`,kW=D8("role",["admin","user"]),l4=I4("users",{id:C1().primaryKey().defaultRandom(),username:t0({length:16}).notNull(),emailOffered:t0({length:254}).notNull(),emailVerified:t0({length:254}),password:t0({length:254}),createdAtIso:T4().notNull().default(QY),createdIp:t0({length:45}).notNull(),isActive:N8().notNull().default(!1),verifiedAtIso:T4(),userRole:kW().default("user")},(Y)=>[d5("usernameUniqueIndex").on(hW(Y.username)),d5("emailVerifiedUniqueIndex").on(hW(Y.emailVerified))]),CE=["id","createdAtIso","createdIp","isActive","verifiedAtIso"],bW=["username","emailOffered","emailVerified","password","userRole"],qE=D8("trackedUserColumnName",bW),yW=D8("accountAction",["cooldown","confirmEmail","signIn","resetPassword"]),jE=I4("accountActions",{userId:C1().references(()=>l4.id).primaryKey(),action:yW().notNull(),code:t0({length:254}).notNull(),wrongCodeCount:I8().notNull().default(0),expiresAtIso:T4().notNull()}),zY=I4("games",{id:C1().primaryKey().defaultRandom()}),_X=I4("players",{userId:C1().notNull().references(()=>l4.id,{onDelete:"cascade"}),gameId:C1().notNull().references(()=>zY.id,{onDelete:"cascade"}),score:I8().notNull()},(Y)=>[x3({name:"players_userId_gameId_pk",columns:[Y.userId,Y.gameId]})]),PE=I4("signInHistory",{id:C1().primaryKey().defaultRandom(),userId:C1().references(()=>l4.id,{onDelete:"cascade"}),signInTimeIso:T4().notNull().default(QY),ipAddress:t0({length:45}).notNull(),userAgent:t0({length:1024}),successful:N8().notNull().default(!1)}),gW=D8("twoFactorMethod",["email","phone"]),SE=I4("passwordResetAttempts",{id:C1().primaryKey().defaultRandom(),userId:C1().notNull().references(()=>l4.id,{onDelete:"cascade"}),requestedIp:t0({length:45}).notNull(),requestedAtIso:T4().notNull().default(QY),succeededIp:t0({length:45}),succeededAtIso:T4(),verificationMethod:gW().notNull()}),vE=I4("banishedIps",{ip:t0({length:45}).primaryKey(),reason:t0({length:2048}).notNull(),banishedAtIso:T4().notNull().default(QY),banishedUntilIso:T4()});var __dirname="/home/runner/work/wayforge/wayforge/apps/tempest.games/src/database";class $X{options;sql;drizzle;observers=new Map;async setupTriggersAndNotifications(){await this.sql.file(xE.resolve(__dirname,"notify_update.sql"));let Y=[d0(l4),d0(zY),d0(_X)];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],$=`${_}("${G}")`;if(this.observers.has($))this.observers.get($).next($)})}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=N2(Z),this.drizzle=JY(this.sql,{schema:GX,logger:Y})}observe(Y,Z){if(!this.observers.has(Y))this.observers.set(Y,new G0);this.observers.get(Y).subscribe("SINGLETON",Z)}}var UY={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 fE(Y){return Number.parseInt(Y,10)}var hE=U1(UY),kE=hE.keyof().pipe((Y)=>fE(Y)),pW=U1([kE,"string"]);var HX=new Q7(process),{logger:D1}=HX;Object.assign(console,D1,{log:D1.info});D1.info("ready");var WX=uW(import.meta.dir,"..","app"),Jf=new $X({logQuery(Y,Z){D1.info("\uD83D\uDCDD query",Y,Z)}});pE({hostname:"0.0.0.0",port:g1.FRONTEND_PORT??3333,...q6??void 0,async fetch(Y){try{let Z=new Date,X=new URL(Y.url);if(D1.info(Y.method,X.pathname),X.pathname==="/")return new Response(Bun.file(uW(WX,"index.html")));if(X.pathname==="/index.html")return Response.redirect("/");let _=yE(WX,X.pathname),G=gE(_);if(!G.startsWith(WX))throw[403,"Access Denied"];if(!await mW(G).exists())return Response.redirect("/");return new Response(mW(G))}catch(Z){let X=pW(Z);if(X instanceof U1.errors===!1){let[_,G]=X,W=`${UY[_]}. ${G}`;return D1.info(`\u274C ${_}: ${W}`),new Response(W,{status:_})}if(Z instanceof Error)D1.error(Z.message);else{let _=C6(Z);D1.error("frontend server threw",_)}return new Response(UY[500],{status:500})}}});function FY(){D1.info("\uD83D\uDEEC frontend server exiting"),process.exit(0)}process.on("SIGINT",()=>{D1.info("\u2757 received SIGINT; exiting gracefully"),FY()});process.on("SIGTERM",()=>{D1.info("\u2757 received SIGTERM; exiting gracefully"),FY()});process.on("exit",()=>{D1.info("\u2757 received exit; exiting gracefully"),FY()});HX.on("timeToStop",()=>{D1.info('\u2757 backend server received signal "timeToStop"; exiting gracefully'),FY()});var{version:mE}=await Bun.file(bE.resolve(import.meta.dir,"../package.json")).json();D1.info(`\uD83D\uDEEB frontend v${mE} running at http://localhost:${g1.FRONTEND_PORT}/`);HX.emit("alive");