tempest.games 0.2.9 → 0.2.11
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +12 -0
- package/app/assets/index-BG6T8CzE.js +109 -0
- package/app/assets/index-ki_mruCb.css +1 -0
- package/app/index.html +2 -2
- package/bin/backend.bun.js +249 -244
- package/bin/backend.worker.tribunal.bun.js +86 -85
- package/bin/frontend.bun.js +31 -30
- package/bin/setup-db.bun.js +402 -222
- package/package.json +18 -18
- package/app/assets/index-B2F2ZwG-.css +0 -1
- package/app/assets/index-D-81-7hL.js +0 -109
package/bin/frontend.bun.js
CHANGED
|
@@ -1,63 +1,63 @@
|
|
|
1
1
|
#!/usr/bin/env bun
|
|
2
2
|
// @bun
|
|
3
|
-
var
|
|
3
|
+
var uG=Object.create;var{getPrototypeOf:cG,defineProperty:n1,getOwnPropertyNames:dG}=Object;var lG=Object.prototype.hasOwnProperty;var HO=(T,_,F)=>{F=T!=null?uG(cG(T)):{};let W=_||!T||!T.__esModule?n1(F,"default",{value:T,enumerable:!0}):F;for(let J of dG(T))if(!lG.call(W,J))n1(W,J,{get:()=>T[J],enumerable:!0});return W};var OO=(T,_)=>()=>(_||T((_={exports:{}}).exports,_),_.exports);var tG=(T,_)=>{for(var F in _)n1(T,F,{get:_[F],enumerable:!0,configurable:!0,set:(W)=>_[F]=()=>W})};var UO=(T,_)=>()=>(T&&(_=T(T=0)),_);var MO=import.meta.require;import $O,{join as ZO,normalize as XO,resolve as r5}from"path";var J0=(T)=>Array.isArray(T)?T:[T],h8=(T,_)=>{let F=[[],[]];for(let W of T)if(_(W))F[0].push(W);else F[1].push(W);return F},NW=Array,c_=(T,_)=>T.includes(_),p8=(T,_=0)=>[...new Array(T)].map((F,W)=>W+_),s=(T,_,F)=>{if(T===void 0)return _===void 0?[]:Array.isArray(_)?_:[_];if(F?.prepend)if(Array.isArray(_))T.unshift(..._);else T.unshift(_);else if(Array.isArray(_))T.push(..._);else T.push(_);return T},d_=(T,_)=>{if(_===void 0||_===null)return T??[];if(T===void 0||T===null)return J0(_);return T.concat(_)},g8=(...T)=>T.reduce(d_,[]),h_=(T,_,F)=>{if(T===void 0)return Array.isArray(_)?_:[_];let W=F?.isEqual??((J,Y)=>J===Y);for(let J of J0(_))if(!T.some((Y)=>W(Y,J)))T.push(J);return T},m8=(T,_)=>T.reduce((F,W)=>{let J=W[_];return F[J]=s(F[J],W),F},{}),l_=(T,_,F)=>T.length===_.length&&T.every(F?.isEqual?(W,J)=>F.isEqual(W,_[J]):(W,J)=>W===_[J]);var T_=(T,_)=>PT(T)===_,PT=(T)=>{let _=typeof T;return _==="object"?T===null?"null":"object":_==="function"?"object":_},__={boolean:"boolean",null:"null",undefined:"undefined",bigint:"a bigint",number:"a number",object:"an object",string:"a string",symbol:"a symbol"},o8={...__,function:"a function"};class u8 extends Error{}var e=(T)=>D0(T,u8),D0=(T,_=Error)=>{throw new _(T)};class EF extends Error{name="ParseError"}var E=(T)=>D0(T,EF),B_=(T)=>` ${T}`;var c=(T,_)=>{let F={},W=Array.isArray(T),J=!1;for(let[Y,$]of Object.entries(T).entries()){let Z=W?_(Y,$[1]):_(...$,Y);J||=typeof Z[0]==="number";let G=Array.isArray(Z[0])||Z.length===0?Z:[Z];for(let[X,O]of G)if(typeof X==="object")F[X.group]=s(F[X.group],O);else F[X]=O}return J?Object.values(F):F};var r1=Object.entries;var qT=(T,_)=>(T in _),g0=(T,_)=>(_ in T);class s1{constructor(T){Object.assign(this,T)}}var c8=class{};class zF extends c8{}var iG=(T,_)=>{let F={},W={},J;for(J in T)if(J in _)F[J]=T[J];else W[J]=T[J];return[F,W]};var d8=(T,_)=>iG(T,_)[1],p_=(T)=>Object.keys(T).length===0,S0=(T)=>[...Object.entries(T),...Object.getOwnPropertySymbols(T).map((_)=>[_,T[_]])],l8=(T,_)=>Object.defineProperties(T,Object.getOwnPropertyDescriptors(_)),t8=(T)=>{let _=Object.keys(T).sort(),F={};for(let W=0;W<_.length;W++)F[_[W]]=T[_[W]];return F};var O_=B_("represents an uninitialized value"),i8=(T)=>Object.values(T).filter((_)=>{if(typeof _==="number")return!0;return typeof T[_]!=="number"});var a1={Array,Boolean,Date,Error,Function,Map,Number,Promise,RegExp,Set,String,WeakMap,WeakSet},e1=globalThis.File??Blob,T2={ArrayBuffer,Blob,File:e1,FormData,Headers,Request,Response,URL},nG={Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array},I0={...a1,...T2,...nG,String,Number,Boolean},VF=(T)=>{let _=Object.getPrototypeOf(T);while(_?.constructor&&(!qT(_.constructor.name,I0)||!(T instanceof I0[_.constructor.name])))_=Object.getPrototypeOf(_);let F=_?.constructor?.name;if(F===void 0||F==="Object")return;return F},KF=(T)=>typeof T==="object"&&T!==null?VF(T)??"object":PT(T);var XT=Array.isArray,rG={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"},sG={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"},aG={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"},n8={...rG,...sG,...aG},LF=(T)=>{let _=Object(T).name??null;return _&&qT(_,I0)&&I0[_]===T?_:null};var _2=(T,_)=>{let F=T.prototype;while(F!==null){if(F===_.prototype)return!0;F=Object.getPrototypeOf(F)}return!1};var r8=(T)=>s8(T,new Map),s8=(T,_)=>{if(typeof T!=="object"||T===null)return T;if(_?.has(T))return _.get(T);let F=LF(T.constructor);if(F==="Date")return new Date(T.getTime());if(F&&F!=="Array")return T;let W=Array.isArray(T)?T.slice():Object.create(Object.getPrototypeOf(T)),J=Object.getOwnPropertyDescriptors(T);if(_){_.set(T,W);for(let Y in J){let $=J[Y];if("get"in $||"set"in $)continue;$.value=s8($.value,_)}}return Object.defineProperties(W,J),W};var eG=(T)=>{let _=O_;return()=>_===O_?_=T():_},Y0=(T)=>typeof T==="function"&&T.length===0;var a8=class extends Function{constructor(...T){let _=T.slice(0,-1),F=T.at(-1);try{super(..._,F)}catch(W){return e(`Encountered an unexpected error while compiling your definition:
|
|
4
4
|
Message: ${W}
|
|
5
5
|
Source: (${T.slice(0,-1)}) => {
|
|
6
6
|
${T.at(-1)}
|
|
7
|
-
}`)}}};class k_{constructor(T,...[_]){return Object.assign(Object.setPrototypeOf(T.bind(_?.bind??this),this.constructor.prototype),_?.attach)}}var
|
|
8
|
-
`)[2]?.trim()||"").match(/\(?(.+?)(?::\d+:\d+)?\)?$/)?.[1]||"unknown").replace(/^file:\/\//,"")}catch{return"unknown"}},
|
|
7
|
+
}`)}}};class k_{constructor(T,...[_]){return Object.assign(Object.setPrototypeOf(T.bind(_?.bind??this),this.constructor.prototype),_?.attach)}}var e8=eG(()=>{try{return new Function("return false")()}catch{return!0}});var vO=B_("brand");var TJ=B_("arkInferred");var hO=B_("args");class uT{constructor(){}}var T9=()=>{try{return((new Error().stack?.split(`
|
|
8
|
+
`)[2]?.trim()||"").match(/\(?(.+?)(?::\d+:\d+)?\)?$/)?.[1]||"unknown").replace(/^file:\/\//,"")}catch{return"unknown"}},_9=globalThis.process?.env??{},_J={fileName:T9,env:_9};var FJ=(T)=>T[0].toUpperCase()+T.slice(1);var F2=(T)=>new RegExp(F9(T),typeof T==="string"?"":T.flags);var F9=(T)=>{return`^(?:${typeof T==="string"?T:T.source})$`};var t_={negativeLookahead:(T)=>`(?!${T})`,nonCapturingGroup:(T)=>`(?:${T})`},DF="\\",$0={" ":1,"\n":1,"\t":1};var W9=/^-0\.?0*$/.source,JJ=/[1-9]\d*/.source,J9=/\.\d+/.source,Y9=/\.\d*[1-9]/.source,YJ=(T)=>F2(t_.negativeLookahead(W9)+t_.nonCapturingGroup("-?"+t_.nonCapturingGroup(t_.nonCapturingGroup("0|"+JJ)+t_.nonCapturingGroup(T.decimalPattern)+"?")+(T.allowDecimalOnly?"|"+T.decimalPattern:"")+"?")),WJ=YJ({decimalPattern:Y9,allowDecimalOnly:!1}),$9=WJ.test.bind(WJ),CW=YJ({decimalPattern:J9,allowDecimalOnly:!0}),dO=CW.test.bind(CW),Z9=/^-?\d*\.?\d*$/,X9=(T)=>T.length!==0&&Z9.test(T),SF=F2(t_.negativeLookahead("^-0$")+"-?"+t_.nonCapturingGroup(t_.nonCapturingGroup("0|"+JJ))),G9=SF.test.bind(SF),W2=/^-?\d+$/,A9=W2.test.bind(W2),$J={number:"a number",bigint:"a bigint",integer:"an integer"},ZJ=(T,_)=>`'${T}' was parsed as ${$J[_]} but could not be narrowed to a literal value. Avoid unnecessary leading or trailing zeros and other abnormal notation`,H9=(T,_)=>_==="number"?$9(T):G9(T),O9=(T,_)=>_==="number"?Number(T):Number.parseInt(T),U9=(T,_)=>_==="number"?X9(T):A9(T),XJ=(T,_)=>J2(T,"number",_),GJ=(T,_)=>J2(T,"number",{..._,strict:!0}),AJ=(T,_)=>J2(T,"integer",_),J2=(T,_,F)=>{let W=O9(T,_);if(!Number.isNaN(W)){if(U9(T,_)){if(F?.strict)return H9(T,_)?W:E(ZJ(T,_));return W}}return F?.errorOnFail?E(F?.errorOnFail===!0?`Failed to parse ${$J[_]} from '${T}'`:F?.errorOnFail):void 0},HJ=(T)=>{if(T[T.length-1]!=="n")return;let _=T.slice(0,-1),F;try{F=BigInt(_)}catch{return}if(SF.test(_))return F;if(W2.test(_))return E(ZJ(T,"bigint"))};var M9="0.46.0",w9={version:M9,filename:_J.fileName(),FileConstructor:e1},N0=w9,OJ=new Map,Y2=Object.create(null),IF=(T)=>{let _=OJ.get(T);if(_)return _;let F=Q9(T);if(Y2[F])F=`${F}${Y2[F]++}`;else Y2[F]=1;return N0[F]=T,OJ.set(T,F),F},Z0=(T)=>/^[$A-Z_a-z][\w$]*$/.test(T),Q9=(T)=>{switch(typeof T){case"object":{if(T===null)break;let _=VF(T)??"object";return _[0].toLowerCase()+_.slice(1)}case"function":return Z0(T.name)?T.name:"fn";case"symbol":return T.description&&Z0(T.description)?T.description:"symbol"}return e(`Unexpected attempt to register serializable value of type ${PT(T)}`)};var NF=(T)=>typeof T==="string"?JSON.stringify(T):typeof T==="bigint"?`${T}n`:`${T}`;var UJ=(T,_={})=>CF(T,{onUndefined:"$ark.undefined",onBigInt:(F)=>`$ark.bigint-${F}`,..._},[]);var d=(T,_)=>{switch(PT(T)){case"object":let F=T,W=F.constructor.name;return W==="Object"||W==="Array"?_?.quoteKeys===!1?BW(F,_?.indent??0,""):JSON.stringify(CF(F,m0,[]),null,_?.indent):BW(F,_?.indent??0,"");case"symbol":return m0.onSymbol(T);default:return NF(T)}},BW=(T,_,F)=>{if(typeof T==="function")return m0.onFunction(T);if(typeof T!=="object"||T===null)return NF(T);let W=F+" ".repeat(_);if(Array.isArray(T)){if(T.length===0)return"[]";let Y=T.map(($)=>BW($,_,W)).join(`,
|
|
9
9
|
`+W);return _?`[
|
|
10
10
|
${W}${Y}
|
|
11
|
-
${F}]`:`[${Y}]`}let J=T.constructor.name;if(J==="Object"){let Y=
|
|
11
|
+
${F}]`:`[${Y}]`}let J=T.constructor.name;if(J==="Object"){let Y=S0(T).map(([$,Z])=>{let G=typeof $==="symbol"?m0.onSymbol($):Z0($)?$:JSON.stringify($),X=BW(Z,_,W);return`${W}${G}: ${X}`});if(Y.length===0)return"{}";return _?`{
|
|
12
12
|
${Y.join(`,
|
|
13
13
|
`)}
|
|
14
|
-
${F}}`:`{${Y.join(", ")}}`}if(T instanceof Date)return
|
|
14
|
+
${F}}`:`{${Y.join(", ")}}`}if(T instanceof Date)return C0(T);if("expression"in T&&typeof T.expression==="string")return T.expression;return J},m0={onCycle:()=>"(cycle)",onSymbol:(T)=>`Symbol(${IF(T)})`,onFunction:(T)=>`Function(${IF(T)})`},CF=(T,_,F)=>{switch(PT(T)){case"object":{let W=T;if("toJSON"in W&&typeof W.toJSON==="function")return W.toJSON();if(typeof W==="function")return m0.onFunction(W);if(F.includes(W))return"(cycle)";let J=[...F,W];if(Array.isArray(W))return W.map(($)=>CF($,_,J));if(W instanceof Date)return W.toDateString();let Y={};for(let $ in W)Y[$]=CF(W[$],_,J);for(let $ of Object.getOwnPropertySymbols(W))Y[_.onSymbol?.($)??$.toString()]=CF(W[$],_,J);return Y}case"symbol":return m0.onSymbol(T);case"bigint":return _.onBigInt?.(T)??`${T}n`;case"undefined":return _.onUndefined??"undefined";case"string":return T.replaceAll("\\","\\\\");default:return T}},C0=(T)=>{let _=T.getFullYear(),F=T.getMonth(),W=T.getDate(),J=T.getHours(),Y=T.getMinutes(),$=T.getSeconds(),Z=T.getMilliseconds();if(F===0&&W===1&&J===0&&Y===0&&$===0&&Z===0)return`${_}`;let G=`${R9[F]} ${W}, ${_}`;if(J===0&&Y===0&&$===0&&Z===0)return G;let X=T.toLocaleTimeString(),O=X.endsWith(" AM")||X.endsWith(" PM")?X.slice(-3):"";if(O)X=X.slice(0,-O.length);if(Z)X+=`.${z9(Z,3)}`;else if(E9.test(X))X=X.slice(0,-3);return`${X+O}, ${G}`},R9=["January","February","March","April","May","June","July","August","September","October","November","December"],E9=/:\d\d:00$/,z9=(T,_)=>String(T).padStart(_,"0");var MJ=(T,_,...[F])=>{let W=F?.stringifySymbol??d,J=T;switch(typeof _){case"string":J=Z0(_)?T===""?_:`${T}.${_}`:`${T}[${JSON.stringify(_)}]`;break;case"number":J=`${T}[${_}]`;break;case"symbol":J=`${T}[${W(_)}]`;break;default:if(F?.stringifyNonKey)J=`${T}[${F.stringifyNonKey(_)}]`;else E(`${d(_)} must be a PropertyKey or stringifyNonKey must be passed to options`)}return J},i_=(T,..._)=>T.reduce((F,W)=>MJ(F,W,..._),"");class BF extends NW{cache={};constructor(...T){super();this.push(...T)}toJSON(){if(this.cache.json)return this.cache.json;this.cache.json=[];for(let T=0;T<this.length;T++)this.cache.json.push(typeof this[T]==="symbol"?d(this[T]):this[T]);return this.cache.json}stringify(){if(this.cache.stringify)return this.cache.stringify;return this.cache.stringify=i_(this)}stringifyAncestors(){if(this.cache.stringifyAncestors)return this.cache.stringifyAncestors;let T="",_=[T];for(let F of this)T=MJ(T,F),_.push(T);return this.cache.stringifyAncestors=_}}class $2{chars;i;def;constructor(T){this.def=T,this.chars=[...T],this.i=0}shift(){return this.chars[this.i++]??""}get lookahead(){return this.chars[this.i]??""}get nextLookahead(){return this.chars[this.i+1]??""}get length(){return this.chars.length}shiftUntil(T){let _="";while(this.lookahead){if(T(this,_))if(_[_.length-1]===DF)_=_.slice(0,-1);else break;_+=this.shift()}return _}shiftUntilLookahead(T){return typeof T==="string"?this.shiftUntil((_)=>_.lookahead===T):this.shiftUntil((_)=>(_.lookahead in T))}shiftUntilNonWhitespace(){return this.shiftUntil(()=>!(this.lookahead in $0))}jumpToIndex(T){this.i=T<0?this.length+T:T}jumpForward(T){this.i+=T}get location(){return this.i}get unscanned(){return this.chars.slice(this.i,this.length).join("")}get scanned(){return this.chars.slice(0,this.i).join("")}sliceChars(T,_){return this.chars.slice(T,_).join("")}lookaheadIs(T){return this.lookahead===T}lookaheadIsIn(T){return this.lookahead in T}}var QU=B_("implementedTraits");var Z2="$ark",V9=2;while(Z2 in globalThis)Z2=`$ark${V9++}`;var wJ=Z2;globalThis[wJ]=N0;var z=N0,K9=(T)=>`${wJ}.${T}`,KT=(T)=>K9(IF(T));class kW extends zF{argNames;body="";constructor(...T){super();this.argNames=T;for(let _ of T){if(_ in this)throw new Error(`Arg name '${_}' would overwrite an existing property on FunctionBody`);this[_]=_}}indentation=0;indent(){return this.indentation+=4,this}dedent(){return this.indentation-=4,this}prop(T,_=!1){return X2(T,_)}index(T,_=!1){return QJ(`${T}`,_)}line(T){return this.body+=`${" ".repeat(this.indentation)}${T}
|
|
15
15
|
`,this}const(T,_){return this.line(`const ${T} = ${_}`),this}let(T,_){return this.line(`let ${T} = ${_}`)}set(T,_){return this.line(`${T} = ${_}`)}if(T,_){return this.block(`if (${T})`,_)}elseIf(T,_){return this.block(`else if (${T})`,_)}else(T){return this.block("else",T)}for(T,_,F=0){return this.block(`for (let i = ${F}; ${T}; i++)`,_)}forIn(T,_){return this.block(`for (const k in ${T})`,_)}block(T,_,F=""){return this.line(`${T} {`),this.indent(),_(this),this.dedent(),this.line(`}${F}`)}return(T=""){return this.line(`return ${T}`)}write(T="anonymous",_=0){return`${T}(${this.argNames.join(", ")}) { ${_?this.body.split(`
|
|
16
16
|
`).map((F)=>" ".repeat(_)+`${F}`).join(`
|
|
17
|
-
`):this.body} }`}compile(){return new
|
|
18
|
-
`)}_add(T){let _=this.byPath[T.propString];if(_){if(_.hasCode("union")&&_.errors.length===0)return;let F=T.hasCode("union")&&T.errors.length===0?T:new
|
|
19
|
-
`+T.map((_)=>` \u2022 ${
|
|
20
|
-
`));Object.defineProperty(this,"arkErrors",{value:T,enumerable:!1})}}var
|
|
17
|
+
`):this.body} }`}compile(){return new a8(...this.argNames,this.body)}}var n_=(T)=>T_(T,"object")||typeof T==="symbol"?KT(T):NF(T),X2=(T,_=!1)=>{if(typeof T==="string"&&Z0(T))return`${_?"?":""}.${T}`;return QJ(L9(T),_)},L9=(T)=>typeof T==="symbol"?KT(T):JSON.stringify(T),QJ=(T,_=!1)=>`${_?"?.":""}[${T}]`;class kF extends kW{traversalKind;optimistic;constructor(T){super("data","ctx");this.traversalKind=T.kind,this.optimistic=T.optimistic===!0}invoke(T,_){let F=_?.arg??this.data,W=typeof T==="string"?!0:this.requiresContextFor(T),J=typeof T==="string"?T:T.id;if(W)return`${this.referenceToId(J,_)}(${F}, ${this.ctx})`;return`${this.referenceToId(J,_)}(${F})`}referenceToId(T,_){let F=_?.kind??this.traversalKind,W=`this.${T}${F}`;return _?.bind?`${W}.bind(${_?.bind})`:W}requiresContextFor(T){return this.traversalKind==="Apply"||T.allowsRequiresContext}initializeErrorCount(){return this.const("errorCount","ctx.currentErrorCount")}returnIfFail(){return this.if("ctx.currentErrorCount > errorCount",()=>this.return())}returnIfFailFast(){return this.if("ctx.failFast && ctx.currentErrorCount > errorCount",()=>this.return())}traverseKey(T,_,F){let W=this.requiresContextFor(F);if(W)this.line(`${this.ctx}.path.push(${T})`);if(this.check(F,{arg:_}),W)this.line(`${this.ctx}.path.pop()`);return this}check(T,_){return this.traversalKind==="Allows"?this.if(`!${this.invoke(T,_)}`,()=>this.return(!1)):this.line(this.invoke(T,_))}}var fW=(T)=>c(T,(_,F)=>[_,XT(F)?[...F]:F]),tT=B_("arkKind"),P=(T,_)=>T?.[tT]===_,OT=(T)=>P(T,"root")||P(T,"constraint");var RJ=["unit","proto","domain"],o0=["required","optional","index","sequence"],G2=["pattern","divisor","exactLength","max","min","maxLength","minLength","before","after"],PW=[...G2,...o0,"structure","predicate"],u0=["alias","union","morph","unit","intersection","proto","domain"],D9=[...u0,...PW],qW=c(PW,(T,_)=>[_,1]),EJ=c([...o0,"undeclared"],(T,_)=>[_,1]),zJ=c(D9,(T,_)=>[_,T]),c0=(T)=>typeof T==="string"&&(T in zJ);var d0=(T)=>zJ[T],jW=(T)=>u0.slice(d0(T)+1),eU=[...jW("union"),"alias"],TM=[...jW("morph"),"alias"],E_=(T)=>{if(typeof T==="string"||typeof T==="boolean"||T===null)return T;if(typeof T==="number"){if(Number.isNaN(T))return"NaN";if(T===Number.POSITIVE_INFINITY)return"Infinity";if(T===Number.NEGATIVE_INFINITY)return"-Infinity";return T}return n_(T)},X0=(T)=>{let _="{ ";for(let[F,W]of Object.entries(T))_+=`${F}: ${n_(W)}, `;return _+" }"},l=(T)=>{let _=T;if(_.hasAssociatedError)_.defaults.expected??=(F)=>("description"in F)?F.description:_.defaults.description(F),_.defaults.actual??=(F)=>d(F),_.defaults.problem??=(F)=>`must be ${F.expected}${F.actual?` (was ${F.actual})`:""}`,_.defaults.message??=(F)=>{if(F.path.length===0)return F.problem;let W=`${F.propString} ${F.problem}`;if(W[0]==="[")return`value at ${W}`;return W};return _};class VJ extends Error{name="ToJsonSchemaError";code;context;constructor(T,_){super(d(_,{quoteKeys:!1,indent:4}));this.code=T,this.context=_}hasCode(T){return this.code===T}}var S9={dialect:"https://json-schema.org/draft/2020-12/schema",useRefs:!1,fallback:{arrayObject:(T)=>RT.throw("arrayObject",T),arrayPostfix:(T)=>RT.throw("arrayPostfix",T),defaultValue:(T)=>RT.throw("defaultValue",T),domain:(T)=>RT.throw("domain",T),morph:(T)=>RT.throw("morph",T),patternIntersection:(T)=>RT.throw("patternIntersection",T),predicate:(T)=>RT.throw("predicate",T),proto:(T)=>RT.throw("proto",T),symbolKey:(T)=>RT.throw("symbolKey",T),unit:(T)=>RT.throw("unit",T),date:(T)=>RT.throw("date",T)}},RT={Error:VJ,throw:(...T)=>{throw new RT.Error(...T)},throwInternalOperandError:(T,_)=>e(`Unexpected JSON Schema input for ${T}: ${d(_)}`),defaultConfig:S9};z.config??={};var fF=(T,_)=>{if(!_)return T;let F={...T},W;for(W in _){let J={...T.keywords};if(W==="keywords"){for(let Y in _[W]){let $=_.keywords[Y];if($===void 0)continue;J[Y]=typeof $==="string"?{description:$}:$}F.keywords=J}else if(W==="toJsonSchema")F[W]=A2(T.toJsonSchema,_.toJsonSchema);else if(c0(W))F[W]={...T[W],..._[W]};else F[W]=_[W]}return F},A2=(T,_)=>{if(!T)return _??{};if(!_)return T;let F={...T},W;for(W in _)if(W==="fallback")F.fallback=I9(T.fallback,_.fallback);else F[W]=_[W];return F},I9=(T,_)=>{T=KJ(T),_=KJ(_);let F={},W;for(W in RT.defaultConfig.fallback)F[W]=_[W]??_.default??T[W]??T.default??RT.defaultConfig.fallback[W];return F},KJ=(T)=>typeof T==="function"?{default:T}:T??{};class G0 extends zF{[tT]="error";path;data;nodeConfig;input;ctx;constructor({prefixPath:T,relativePath:_,...F},W){super();this.input=F,this.ctx=W,l8(this,F);let J=W.data;if(F.code==="union")F.errors=F.errors.flatMap(($)=>{let Z=$.hasCode("union")?$.errors:[$];if(!T&&!_)return Z;return Z.map((G)=>G.transform((X)=>({...X,path:g8(T,X.path,_)})))});this.nodeConfig=W.config[this.code];let Y=[...F.path??W.path];if(_)Y.push(..._);if(T)Y.unshift(...T);this.path=new BF(...Y),this.data="data"in F?F.data:J}transform(T){return new G0(T({data:this.data,path:this.path,...this.input}),this.ctx)}hasCode(T){return this.code===T}get propString(){return i_(this.path)}get expected(){if(this.input.expected)return this.input.expected;let T=this.meta?.expected??this.nodeConfig.expected;return typeof T==="function"?T(this.input):T}get actual(){if(this.input.actual)return this.input.actual;let T=this.meta?.actual??this.nodeConfig.actual;return typeof T==="function"?T(this.data):T}get problem(){if(this.input.problem)return this.input.problem;let T=this.meta?.problem??this.nodeConfig.problem;return typeof T==="function"?T(this):T}get message(){if(this.input.message)return this.input.message;let T=this.meta?.message??this.nodeConfig.message;return typeof T==="function"?T(this):T}get flat(){return this.hasCode("intersection")?[...this.errors]:[this]}toJSON(){return{data:this.data,path:this.path,...this.input,expected:this.expected,actual:this.actual,problem:this.problem,message:this.message}}toString(){return this.message}throw(){throw this}}class F_ extends NW{[tT]="errors";ctx;constructor(T){super();this.ctx=T}byPath=Object.create(null);get flatByPath(){return c(this.byPath,(T,_)=>[T,_.flat])}get flatProblemsByPath(){return c(this.byPath,(T,_)=>[T,_.flat.map((F)=>F.problem)])}byAncestorPath=Object.create(null);count=0;mutable=this;throw(){throw this.toTraversalError()}toTraversalError(){return new H2(this)}add(T){if(this.includes(T))return;this._add(T)}transform(T){let _=new F_(this.ctx);for(let F of this)_.add(T(F));return _}merge(T){for(let _ of T){if(this.includes(_))continue;this._add(new G0({..._,path:[...this.ctx.path,..._.path]},this.ctx))}}affectsPath(T){if(this.length===0)return!1;return T.stringifyAncestors().some((_)=>(_ in this.byPath))||T.stringify()in this.byAncestorPath}get summary(){return this.toString()}get issues(){return this}toJSON(){return[...this.map((T)=>T.toJSON())]}toString(){return this.join(`
|
|
18
|
+
`)}_add(T){let _=this.byPath[T.propString];if(_){if(_.hasCode("union")&&_.errors.length===0)return;let F=T.hasCode("union")&&T.errors.length===0?T:new G0({code:"intersection",errors:_.hasCode("intersection")?[..._.errors,T]:[_,T]},this.ctx),W=this.indexOf(_);this.mutable[W===-1?this.length:W]=F,this.byPath[T.propString]=F,this.addAncestorPaths(T)}else this.byPath[T.propString]=T,this.addAncestorPaths(T),this.mutable.push(T);this.count++}addAncestorPaths(T){for(let _ of T.path.stringifyAncestors())this.byAncestorPath[_]=s(this.byAncestorPath[_],T)}}class H2 extends Error{name="TraversalError";constructor(T){if(T.length===1)super(T.summary);else super(`
|
|
19
|
+
`+T.map((_)=>` \u2022 ${N9(_)}`).join(`
|
|
20
|
+
`));Object.defineProperty(this,"arkErrors",{value:T,enumerable:!1})}}var N9=(T)=>T.toString().split(`
|
|
21
21
|
`).join(`
|
|
22
|
-
`);class f_{path=[];errors=new F_(this);root;config;queuedMorphs=[];branches=[];seen={};constructor(T,_){this.root=T,this.config=_}get data(){let T=this.root;for(let _ of this.path)T=T?.[_];return T}get propString(){return t_(this.path)}reject(T){return this.error(T),!1}mustBe(T){return this.error(T),!1}error(T){let _=typeof T==="object"?T.code?T:{...T,code:"predicate"}:{code:"predicate",expected:T};return this.errorFromContext(_)}hasError(){return this.currentErrorCount!==0}get currentBranch(){return this.branches.at(-1)}queueMorphs(T){let _={path:new IF(...this.path),morphs:T};if(this.currentBranch)this.currentBranch.queuedMorphs.push(_);else this.queuedMorphs.push(_)}finalize(T){if(this.queuedMorphs.length){if(typeof this.root==="object"&&this.root!==null&&this.config.clone)this.root=this.config.clone(this.root);this.applyQueuedMorphs()}if(this.hasError())return T?T(this.errors):this.errors;return this.root}get currentErrorCount(){return this.currentBranch?this.currentBranch.error?1:0:this.errors.count}get failFast(){return this.branches.length!==0}pushBranch(){this.branches.push({error:void 0,queuedMorphs:[]})}popBranch(){return this.branches.pop()}get external(){return this}errorFromNodeContext(T){return this.errorFromContext(T)}errorFromContext(T){let _=new Z0(T,this);if(this.currentBranch)this.currentBranch.error=_;else this.errors.add(_);return _}applyQueuedMorphs(){while(this.queuedMorphs.length){let T=this.queuedMorphs;this.queuedMorphs=[];for(let{path:_,morphs:F}of T){if(this.errors.affectsPath(_))continue;this.applyMorphsAtPath(_,F)}}}applyMorphsAtPath(T,_){let F=T.at(-1),W;if(F!==void 0){W=this.root;for(let J=0;J<T.length-1;J++)W=W[T[J]]}this.path=[...T];for(let J of _){let Y=UT(J),$=J(W===void 0?this.root:W[F],this);if($ instanceof Z0){this.errors.add($);break}if($ instanceof F_){if(!Y)this.errors.merge($);break}if(W===void 0)this.root=$;else W[F]=$;this.applyQueuedMorphs()}}}var W_=(T,_,F)=>{if(!F)return _();F.path.push(T);let W=_();return F.path.pop(),W};class kF extends k_{attachments;$;onFail;includesTransform;includesContextualPredicate;isCyclic;allowsRequiresContext;rootApplyStrategy;contextFreeMorph;rootApply;referencesById;shallowReferences;flatRefs;flatMorphs;allows;get shallowMorphs(){return[]}constructor(T,_){super((W,J,Y=this.onFail)=>{if(J)return this.traverseApply(W,J),J.hasError()?J.errors:J.data;return this.rootApply(W,Y)},{attach:T});this.attachments=T,this.$=_,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((W,J)=>I9(W,J.shallowReferences),[this]);let F=this.isStructural();this.flatRefs=[],this.flatMorphs=[];for(let W=0;W<this.children.length;W++){if(this.includesTransform||=this.children[W].includesTransform,this.includesContextualPredicate||=this.children[W].includesContextualPredicate,this.isCyclic||=this.children[W].isCyclic,!F){let J=this.children[W].flatRefs;for(let Y=0;Y<J.length;Y++){let $=J[Y];if(!this.flatRefs.some((Z)=>RJ(Z,$))){this.flatRefs.push($);for(let Z of $.node.branches)if(Z.hasKind("morph")||Z.hasKind("intersection")&&Z.structure?.structuralMorph!==void 0)this.flatMorphs.push({path:$.path,propString:$.propString,node:Z})}}}Object.assign(this.referencesById,this.children[W].referencesById)}this.flatRefs.sort((W,J)=>W.path.length>J.path.length?1:W.path.length<J.path.length?-1:W.propString>J.propString?1:W.propString<J.propString?-1:W.node.expression<J.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((W)=>W.length===1||W.name==="$arkStructuralMorph")?this.hasKind("union")?this.branches.some((W)=>W.shallowMorphs.length>1)?"contextual":"branchedOptimistic":this.shallowMorphs.length>1?"contextual":"optimistic":"contextual":"contextual",this.rootApply=this.createRootApply(),this.allows=this.allowsRequiresContext?(W)=>this.traverseAllows(W,new f_(W,this.$.resolvedConfig)):(W)=>this.traverseAllows(W)}createRootApply(){switch(this.rootApplyStrategy){case"allows":return(_,F)=>{if(this.allows(_))return _;let W=new f_(_,this.$.resolvedConfig);return this.traverseApply(_,W),W.finalize(F)};case"contextual":return(_,F)=>{let W=new f_(_,this.$.resolvedConfig);return this.traverseApply(_,W),W.finalize(F)};case"optimistic":this.contextFreeMorph=this.shallowMorphs[0];let T=this.$.resolvedConfig.clone;return(_,F)=>{if(this.allows(_))return this.contextFreeMorph(T&&(typeof _==="object"&&_!==null||typeof _==="function")?T(_):_);let W=new f_(_,this.$.resolvedConfig);return this.traverseApply(_,W),W.finalize(F)};case"branchedOptimistic":return this.createBranchedOptimisticRootApply();default:return this.rootApplyStrategy,e(`Unexpected rootApplyStrategy ${this.rootApplyStrategy}`)}}compiledMeta=S9(this.metaJson);cacheGetter(T,_){return Object.defineProperty(this,T,{value:_}),_}get description(){return this.cacheGetter("description",this.meta?.description??this.$.resolvedConfig[this.kind].description(this))}get references(){return Object.values(this.referencesById)}precedence=o0(this.kind);precompilation;assert=(T,_)=>this(T,_,(F)=>F.throw());traverse(T,_){return this(T,_,null)}get in(){return this.cacheGetter("in",this.getIo("in"))}get out(){return this.cacheGetter("out",this.getIo("out"))}getIo(T){if(!this.includesTransform)return this;let _={};for(let[F,W]of this.innerEntries){let J=this.impl.keys[F];if(J.reduceIo)J.reduceIo(T,_,W);else if(J.child){let Y=W;_[F]=ZT(Y)?Y.map(($)=>$[T]):Y[T]}else _[F]=W}return this.$.node(this.kind,_)}toJSON(){return this.json}toString(){return`Type<${this.expression}>`}equals(T){let _=UT(T)?T:this.$.parseDefinition(T);return this.innerHash===_.innerHash}ifEquals(T){return this.equals(T)?this:void 0}hasKind(T){return this.kind===T}assertHasKind(T){if(this.kind!==T)V0(`${this.kind} node was not of asserted kind ${T}`);return this}hasKindIn(...T){return T.includes(this.kind)}assertHasKindIn(...T){if(!u_(T,this.kind))V0(`${this.kind} node was not one of asserted kinds ${T}`);return this}isBasis(){return u_(OJ,this.kind)}isConstraint(){return u_(CW,this.kind)}isStructural(){return u_(p0,this.kind)}isRefinement(){return u_($2,this.kind)}isRoot(){return u_(g0,this.kind)}isUnknown(){return this.hasKind("intersection")&&this.children.length===0}isNever(){return this.hasKind("union")&&this.children.length===0}hasUnit(T){return this.hasKind("unit")&&this.allows(T)}hasOpenIntersection(){return this.impl.intersectionIsOpen}get nestableExpression(){return this.expression}select(T){let _=BF.normalize(T);return this._select(_)}_select(T){let _=BF.applyBoundary[T.boundary??"references"](this);if(T.kind)_=_.filter((F)=>F.kind===T.kind);if(T.where)_=_.filter(T.where);return BF.applyMethod[T.method??"filter"](_,this,T)}transform(T,_){return this._transform(T,this._createTransformContext(_))}_createTransformContext(T){return{root:this,selected:void 0,seen:{},path:[],parseOptions:{prereduced:T?.prereduced??!1},undeclaredKeyHandling:void 0,...T}}_transform(T,_){let F=_.bindScope??this.$;if(_.seen[this.id])return this.$.lazilyResolve(_.seen[this.id]);if(_.shouldTransform?.(this,_)===!1)return this;let W;if(_.seen[this.id]=()=>W,this.hasKind("structure")&&this.undeclared!==_.undeclaredKeyHandling)_={..._,undeclaredKeyHandling:this.undeclared};let J=c(this.inner,(X,U)=>{if(!this.impl.keys[X].child)return[X,U];let M=U;if(!ZT(M)){let V=M._transform(T,_);return V?[X,V]:[]}if(M.length===0)return[X,U];let Q=M.flatMap((V)=>{return V._transform(T,_)??[]});return Q.length?[X,Q]:[]});delete _.seen[this.id];let Y=Object.assign(J,{meta:this.meta}),$=_.selected&&!_.selected.includes(this)?Y:T(this.kind,Y,_);if($===null)return null;if(UT($))return W=$;let Z=Object.keys($);if((Z.length===0||Z.length===1&&Z[0]==="meta")&&!h_(this.inner))return null;if((this.kind==="required"||this.kind==="optional"||this.kind==="index")&&!("value"in $))return _.undeclaredKeyHandling?{...$,value:R.intrinsic.unknown}:null;if(this.kind==="morph")$.in??=R.intrinsic.unknown;return W=F.node(this.kind,$,_.parseOptions)}configureReferences(T,_="references"){let F=BF.normalize(_),W=typeof T==="string"?(Z,G)=>({...G,meta:{...G.meta,description:T}}):typeof T==="function"?(Z,G)=>({...G,meta:T(G.meta)}):(Z,G)=>({...G,meta:{...G.meta,...T}});if(F.boundary==="self")return this.$.node(this.kind,W(this.kind,{...this.inner,meta:this.meta}));let J=this._select(F),Y=J&&F0(J),$=F.boundary==="child"?(Z,G)=>G.root.children.includes(Z):F.boundary==="shallow"?(Z)=>Z.kind!=="structure":()=>!0;return this.$.finalize(this.transform(W,{shouldTransform:$,selected:Y}))}}var BF={applyBoundary:{self:(T)=>[T],child:(T)=>[...T.children],shallow:(T)=>[...T.shallowReferences],references:(T)=>[...T.references]},applyMethod:{filter:(T)=>T,assertFilter:(T,_,F)=>{if(T.length===0)V0(EJ(_,F));return T},find:(T)=>T[0],assertFind:(T,_,F)=>{if(T.length===0)V0(EJ(_,F));return T[0]}},normalize:(T)=>typeof T==="function"?{boundary:"references",method:"filter",where:T}:typeof T==="string"?qT(T,BF.applyBoundary)?{method:"filter",boundary:T}:{boundary:"references",method:"filter",kind:T}:{boundary:"references",method:"filter",...T}},EJ=(T,_)=>`${T} had no references matching ${d(_)}.`,D9=(T)=>t_(T,{stringifyNonKey:(_)=>_.expression}),L9=/"(\$ark\.[^"]+)"/g,S9=(T)=>JSON.stringify(T).replaceAll(L9,"$1"),q_=(T,_)=>({path:T,node:_,propString:D9(T)}),RJ=(T,_)=>T.propString===_.propString&&T.node.equals(_.node),G2=(T,_)=>x_(T,_,{isEqual:RJ}),I9=(T,_)=>x_(T,_,{isEqual:(F,W)=>F.equals(W)});class I extends Array{static init(T,_,F,W){return new I({kind:T,l:_,r:F,path:W?.path??[],optional:W?.optional??!1})}add(T,_,F,W){return this.push({kind:T,l:_,r:F,path:W?.path??[],optional:W?.optional??!1}),this}get summary(){return this.describeReasons()}describeReasons(){if(this.length===1){let{path:T,l:_,r:F}=this[0],W=t_(T);return A2(`Intersection${W&&` at ${W}`} of ${KJ(_,F)}`)}return`The following intersections result in unsatisfiable types:
|
|
23
|
-
\u2022 ${this.map(({path:T,l:_,r:F})=>`${T}: ${
|
|
24
|
-
\u2022 `)}`}throw(){return z(this.describeReasons())}invert(){let T=this.map((_)=>({..._,l:_.r,r:_.l}));if(!(T instanceof I))return new I(...T);return T}withPrefixKey(T,_){return this.map((F)=>({...F,path:[T,...F.path],optional:F.optional||_==="optional"}))}toNeverIfDisjoint(){return R.intrinsic.never}}var KJ=(T,_)=>`${H2(T)} and ${H2(_)}`,H2=(T)=>UT(T)?T.expression:ZT(T)?T.map(H2).join(" | ")||"never":String(T),A2=(T)=>`${T} results in an unsatisfiable type`;var u0={},J_=(T,_,F)=>OT(T,_,{$:F,invert:!1,pipe:!1}),fF=(T,_,F)=>OT(T,_,{$:F,invert:!1,pipe:!0}),OT=(T,_,F)=>{let W=F.pipe?"|>":"&",J=`${T.hash}${W}${_.hash}`;if(u0[J]!==void 0)return u0[J];if(!F.pipe){let Z=`${_.hash}${W}${T.hash}`;if(u0[Z]!==void 0){let G=u0[Z],X=G instanceof I?G.invert():G;return u0[J]=X,X}}let Y=!F.pipe||!T.includesTransform&&!_.includesTransform;if(Y&&T.equals(_))return T;let $=Y?U2(T,_,F):T.hasKindIn(...g0)?N9(T,_,F):U2(T,_,F);if(UT($)){if(T.equals($))$=T;else if(_.equals($))$=_}return u0[J]=$,$},U2=(T,_,F)=>{let W=T.precedence<_.precedence?T.kind:_.kind,J=T.impl.intersections[_.kind]??_.impl.intersections[T.kind];if(J===void 0)return null;else if(W===T.kind)return J(T,_,F);else{let Y=J(_,T,{...F,invert:!F.invert});if(Y instanceof I)Y=Y.invert();return Y}},N9=(T,_,F)=>T.includesTransform||_.includesTransform?F.invert?VJ(_,T,F):VJ(T,_,F):U2(T,_,F),VJ=(T,_,F)=>T.distribute((W)=>C9(W,_,F),(W)=>{let J=W.filter(UT);if(J.length===0)return I.init("union",T.branches,_.branches);if(J.length<T.branches.length||!T.branches.every((Z,G)=>Z.in.equals(J[G].in)))return F.$.parseSchema(J);let Y;if(J.length===1){let Z=J[0];if(!Y)return Z;return F.$.node("morph",{...Z.inner,in:Z.in.configure(Y,"self")})}let $={branches:J};if(Y)$.meta=Y;return F.$.parseSchema($)}),C9=(T,_,F)=>{if(T.hasKind("morph")){let J=[...T.morphs];if(T.lastMorphIfNode){let Y=OT(T.lastMorphIfNode,_,F);if(Y instanceof I)return Y;J[J.length-1]=Y}else J.push(_);return F.$.node("morph",{morphs:J,in:T.inner.in})}if(_.hasKind("morph")){let J=OT(T,_.in,F);if(J instanceof I)return J;return F.$.node("morph",{morphs:[_],in:J})}return F.$.node("morph",{morphs:[_],in:T})};class R_ extends kF{constructor(T,_){super(T,_);Object.defineProperty(this,tT,{value:"constraint",enumerable:!1})}impliedSiblings;intersect(T){return J_(this,T,this.$)}}class n_ extends R_{traverseApply=(T,_)=>{if(!this.traverseAllows(T,_))_.errorFromNodeContext(this.errorContext)};compile(T){if(T.traversalKind==="Allows")T.return(this.compiledCondition);else T.if(this.compiledNegation,()=>T.line(`${T.ctx}.errorFromNodeContext(${this.compiledErrorContext})`))}get errorContext(){return{code:this.kind,description:this.description,meta:this.meta,...this.inner}}get compiledErrorContext(){return $0(this.errorContext)}}var cT=(T)=>(_,F)=>{if(ZT(_)){if(_.length===0)return;let J=_.map((Y)=>F.$.node(T,Y));if(T==="predicate")return J;return J.sort((Y,$)=>Y.hash<$.hash?-1:1)}let W=F.$.node(T,_);return W.hasOpenIntersection()?[W]:W},c0=(T)=>{let _=T.r.shift();if(!_){let W=T.l.length===0&&T.kind==="structure"?R.intrinsic.unknown.internal:T.ctx.$.node(T.kind,Object.assign(T.baseInner,B9(T.l)),{prereduced:!0});for(let J of T.roots){if(W instanceof I)return W;W=OT(J,W,T.ctx)}return W}let F=!1;for(let W=0;W<T.l.length;W++){let J=OT(T.l[W],_,T.ctx);if(J===null)continue;if(J instanceof I)return J;if(!F){if(J.isRoot())return T.roots.push(J),T.l.splice(W),c0(T);T.l[W]=J,F=!0}else if(!T.l.includes(J))return e(`Unexpectedly encountered multiple distinct intersection results for refinement ${J}`)}if(!F)T.l.push(_);if(T.kind==="intersection"){if(_.impliedSiblings)for(let W of _.impliedSiblings)x_(T.r,W)}return c0(T)},d0=(T)=>{return Object.entries(T).flatMap(([F,W])=>(F in BW)?W:[]).sort((F,W)=>F.precedence<W.precedence?-1:F.precedence>W.precedence?1:F.kind==="predicate"&&W.kind==="predicate"?0:F.hash<W.hash?-1:1)},B9=(T)=>{let _={};for(let F of T)if(F.hasOpenIntersection())_[F.kind]=s(_[F.kind],F);else{if(_[F.kind])return e(`Unexpected intersection of closed refinements of kind ${F.kind}`);_[F.kind]=F}return _},DJ=(...T)=>z(LJ(...T)),LJ=(T,_,F)=>{let W=F.hasKind("morph")?"a morph":F.isUnknown()?"unknown":F.exclude(_).defaultShortDescription;return`${a8(T)} operand must be ${_.description} (was ${W})`};var SJ=(T,_,F)=>new X0(T,_,F,F,null);class fW extends k_{}class X0 extends k_{[tT]="generic";paramDefs;bodyDef;$;arg$;baseInstantiation;hkt;description;constructor(T,_,F,W,J){super((...Y)=>{let $=c(this.names,(Z,G)=>{let X=this.arg$.parse(Y[Z]);if(!X.extends(this.constraints[Z]))z(k9(G,this.constraints[Z].expression,X.expression));return[G,X]});if(this.defIsLazy()){let Z=this.bodyDef($);return this.$.parse(Z)}return this.$.parse(_,{args:$})});this.paramDefs=T,this.bodyDef=_,this.$=F,this.arg$=W,this.hkt=J,this.description=J?new J().description??`a generic type for ${J.constructor.name}`:"a generic type",this.baseInstantiation=this(...this.constraints)}defIsLazy(){return this.bodyDef instanceof fW}cacheGetter(T,_){return Object.defineProperty(this,T,{value:_}),_}get json(){return this.cacheGetter("json",{params:this.params.map((T)=>T[1].isUnknown()?T[0]:[T[0],T[1].json]),body:GJ(this.bodyDef)})}get params(){return this.cacheGetter("params",this.paramDefs.map((T)=>typeof T==="string"?[T,R.intrinsic.unknown]:[T[0],this.$.parse(T[1])]))}get names(){return this.cacheGetter("names",this.params.map((T)=>T[0]))}get constraints(){return this.cacheGetter("constraints",this.params.map((T)=>T[1]))}get internal(){return this}get referencesById(){return this.baseInstantiation.internal.referencesById}get references(){return this.baseInstantiation.internal.references}}var k9=(T,_,F)=>`${T} must be assignable to ${_} (was ${F})`;var f9=l({kind:"predicate",hasAssociatedError:!0,collapsibleKey:"predicate",keys:{predicate:{}},normalize:(T)=>typeof T==="function"?{predicate:T}:T,defaults:{description:(T)=>`valid according to ${T.predicate.name||"an anonymous predicate"}`},intersectionIsOpen:!0,intersections:{predicate:()=>null}});class IJ extends R_{serializedPredicate=VT(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=$0(this.errorContext);traverseApply=(T,_)=>{if(!this.predicate(T,_.external)&&!_.hasError())_.errorFromNodeContext(this.errorContext)};compile(T){if(T.traversalKind==="Allows"){T.return(this.compiledCondition);return}T.if(`${this.compiledNegation} && !ctx.hasError()`,()=>T.line(`ctx.errorFromNodeContext(${this.compiledErrorContext})`))}reduceJsonSchema(T,_){return _.fallback.predicate({code:"predicate",base:T,predicate:this.predicate})}}var O2={implementation:f9,Node:IJ};var q9=l({kind:"divisor",collapsibleKey:"rule",keys:{rule:{parse:(T)=>Number.isInteger(T)?T:z(P9(T))}},normalize:(T)=>typeof T==="number"?{rule:T}:T,hasAssociatedError:!0,defaults:{description:(T)=>T.rule===1?"an integer":T.rule===2?"even":`a multiple of ${T.rule}`},intersections:{divisor:(T,_,F)=>F.$.node("divisor",{rule:Math.abs(T.rule*_.rule/j9(T.rule,_.rule))})},obviatesBasisDescription:!0});class NJ extends n_{traverseAllows=(T)=>T%this.rule===0;compiledCondition=`data % ${this.rule} === 0`;compiledNegation=`data % ${this.rule} !== 0`;impliedBasis=R.intrinsic.number.internal;expression=`% ${this.rule}`;reduceJsonSchema(T){if(T.type="integer",this.rule===1)return T;return T.multipleOf=this.rule,T}}var M2={implementation:q9,Node:NJ};var P9=(T)=>`divisor must be an integer (was ${T})`,j9=(T,_)=>{let F,W=T,J=_;while(J!==0)F=J,J=W%J,W=F;return W};class O_ extends n_{boundOperandKind=x9[this.kind];compiledActual=this.boundOperandKind==="value"?"data":this.boundOperandKind==="length"?"data.length":"data.valueOf()";comparator=h9(this.kind,this.exclusive);numericLimit=this.rule.valueOf();expression=`${this.comparator} ${this.rule}`;compiledCondition=`${this.compiledActual} ${this.comparator} ${this.numericLimit}`;compiledNegation=`${this.compiledActual} ${y9[this.comparator]} ${this.numericLimit}`;stringLimit=this.boundOperandKind==="date"?p9(this.numericLimit):`${this.numericLimit}`;limitKind=this.comparator["0"]==="<"?"upper":"lower";isStricterThan(T){return(this.limitKind==="upper"?this.numericLimit<T.numericLimit:this.numericLimit>T.numericLimit)||this.numericLimit===T.numericLimit&&this.exclusive===!0&&!T.exclusive}overlapsRange(T){if(this.isStricterThan(T))return!1;if(this.numericLimit===T.numericLimit&&(this.exclusive||T.exclusive))return!1;return!0}overlapIsUnit(T){return this.numericLimit===T.numericLimit&&!this.exclusive&&!T.exclusive}}var y9={"<":">=","<=":">",">":"<=",">=":"<"},v9={min:"max",minLength:"maxLength",after:"before"},qW={parse:(T)=>T||void 0},PW=(T)=>(_)=>{if(typeof _==="number")return{rule:_};let{exclusive:F,...W}=_;return F?{...W,rule:T==="minLength"?W.rule+1:W.rule-1}:W},jW=(T)=>(_)=>{if(typeof _==="number"||typeof _==="string"||_ instanceof Date)return{rule:_};let{exclusive:F,...W}=_;if(!F)return W;let J=typeof W.rule==="number"?W.rule:typeof W.rule==="string"?new Date(W.rule).valueOf():W.rule.valueOf();return F?{...W,rule:T==="after"?J+1:J-1}:W},yW=(T)=>typeof T==="string"||typeof T==="number"?new Date(T):T,b9=(T,_)=>`${T} bound must be a positive integer (was ${_})`,l0=(T)=>(_)=>{if(!Number.isInteger(_)||_<0)z(b9(T,_));return _},x9={min:"value",max:"value",minLength:"length",maxLength:"length",after:"date",before:"date"},h9=(T,_)=>`${qT(T,v9)?">":"<"}${_?"":"="}`,p9=(T)=>typeof T==="string"?T:new Date(T).toLocaleString(),CJ=(T)=>`Bounded expression ${T} must be exactly one of number, string, Array, or Date`;var g9=l({kind:"after",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:yW,serialize:(T)=>T.toISOString()}},normalize:jW("after"),defaults:{description:(T)=>`${T.collapsibleLimitString} or later`,actual:I0},intersections:{after:(T,_)=>T.isStricterThan(_)?T:_}});class BJ extends O_{impliedBasis=R.intrinsic.Date.internal;collapsibleLimitString=I0(this.rule);traverseAllows=(T)=>T>=this.rule;reduceJsonSchema(T,_){return _.fallback.date({code:"date",base:T,after:this.rule})}}var w2={implementation:g9,Node:BJ};var m9=l({kind:"before",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:yW,serialize:(T)=>T.toISOString()}},normalize:jW("before"),defaults:{description:(T)=>`${T.collapsibleLimitString} or earlier`,actual:I0},intersections:{before:(T,_)=>T.isStricterThan(_)?T:_,after:(T,_,F)=>T.overlapsRange(_)?T.overlapIsUnit(_)?F.$.node("unit",{unit:T.rule}):null:I.init("range",T,_)}});class kJ extends O_{collapsibleLimitString=I0(this.rule);traverseAllows=(T)=>T<=this.rule;impliedBasis=R.intrinsic.Date.internal;reduceJsonSchema(T,_){return _.fallback.date({code:"date",base:T,before:this.rule})}}var Q2={implementation:m9,Node:kJ};var o9=l({kind:"exactLength",collapsibleKey:"rule",keys:{rule:{parse:l0("exactLength")}},normalize:(T)=>typeof T==="number"?{rule:T}:T,hasAssociatedError:!0,defaults:{description:(T)=>`exactly length ${T.rule}`,actual:(T)=>`${T.length}`},intersections:{exactLength:(T,_,F)=>I.init("unit",F.$.node("unit",{unit:T.rule}),F.$.node("unit",{unit:_.rule}),{path:["length"]}),minLength:(T,_)=>T.rule>=_.rule?T:I.init("range",T,_),maxLength:(T,_)=>T.rule<=_.rule?T:I.init("range",T,_)}});class fJ extends n_{traverseAllows=(T)=>T.length===this.rule;compiledCondition=`data.length === ${this.rule}`;compiledNegation=`data.length !== ${this.rule}`;impliedBasis=R.intrinsic.lengthBoundable.internal;expression=`== ${this.rule}`;reduceJsonSchema(T){switch(T.type){case"string":return T.minLength=this.rule,T.maxLength=this.rule,T;case"array":return T.minItems=this.rule,T.maxItems=this.rule,T;default:return zT.throwInternalOperandError("exactLength",T)}}}var z2={implementation:o9,Node:fJ};var u9=l({kind:"max",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{},exclusive:qW},normalize:(T)=>typeof T==="number"?{rule:T}:T,defaults:{description:(T)=>{if(T.rule===0)return T.exclusive?"negative":"non-positive";return`${T.exclusive?"less than":"at most"} ${T.rule}`}},intersections:{max:(T,_)=>T.isStricterThan(_)?T:_,min:(T,_,F)=>T.overlapsRange(_)?T.overlapIsUnit(_)?F.$.node("unit",{unit:T.rule}):null:I.init("range",T,_)},obviatesBasisDescription:!0});class qJ extends O_{impliedBasis=R.intrinsic.number.internal;traverseAllows=this.exclusive?(T)=>T<this.rule:(T)=>T<=this.rule;reduceJsonSchema(T){if(this.exclusive)T.exclusiveMaximum=this.rule;else T.maximum=this.rule;return T}}var E2={implementation:u9,Node:qJ};var c9=l({kind:"maxLength",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:l0("maxLength")}},reduce:(T,_)=>T.rule===0?_.node("exactLength",T):void 0,normalize:PW("maxLength"),defaults:{description:(T)=>`at most length ${T.rule}`,actual:(T)=>`${T.length}`},intersections:{maxLength:(T,_)=>T.isStricterThan(_)?T:_,minLength:(T,_,F)=>T.overlapsRange(_)?T.overlapIsUnit(_)?F.$.node("exactLength",{rule:T.rule}):null:I.init("range",T,_)}});class PJ extends O_{impliedBasis=R.intrinsic.lengthBoundable.internal;traverseAllows=(T)=>T.length<=this.rule;reduceJsonSchema(T){switch(T.type){case"string":return T.maxLength=this.rule,T;case"array":return T.maxItems=this.rule,T;default:return zT.throwInternalOperandError("maxLength",T)}}}var R2={implementation:c9,Node:PJ};var d9=l({kind:"min",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{},exclusive:qW},normalize:(T)=>typeof T==="number"?{rule:T}:T,defaults:{description:(T)=>{if(T.rule===0)return T.exclusive?"positive":"non-negative";return`${T.exclusive?"more than":"at least"} ${T.rule}`}},intersections:{min:(T,_)=>T.isStricterThan(_)?T:_},obviatesBasisDescription:!0});class jJ extends O_{impliedBasis=R.intrinsic.number.internal;traverseAllows=this.exclusive?(T)=>T>this.rule:(T)=>T>=this.rule;reduceJsonSchema(T){if(this.exclusive)T.exclusiveMinimum=this.rule;else T.minimum=this.rule;return T}}var K2={implementation:d9,Node:jJ};var l9=l({kind:"minLength",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:l0("minLength")}},reduce:(T)=>T.rule===0?R.intrinsic.unknown:void 0,normalize:PW("minLength"),defaults:{description:(T)=>T.rule===1?"non-empty":`at least length ${T.rule}`,actual:(T)=>T.length===0?"":`${T.length}`},intersections:{minLength:(T,_)=>T.isStricterThan(_)?T:_}});class yJ extends O_{impliedBasis=R.intrinsic.lengthBoundable.internal;traverseAllows=(T)=>T.length>=this.rule;reduceJsonSchema(T){switch(T.type){case"string":return T.minLength=this.rule,T;case"array":return T.minItems=this.rule,T;default:return zT.throwInternalOperandError("minLength",T)}}}var V2={implementation:l9,Node:yJ};var vJ={min:K2.implementation,max:E2.implementation,minLength:V2.implementation,maxLength:R2.implementation,exactLength:z2.implementation,after:w2.implementation,before:Q2.implementation},bJ={min:K2.Node,max:E2.Node,minLength:V2.Node,maxLength:R2.Node,exactLength:z2.Node,after:w2.Node,before:Q2.Node};var t9=l({kind:"pattern",collapsibleKey:"rule",keys:{rule:{},flags:{}},normalize:(T)=>typeof T==="string"?{rule:T}:T instanceof RegExp?T.flags?{rule:T.source,flags:T.flags}:{rule:T.source}:T,obviatesBasisDescription:!0,obviatesBasisExpression:!0,hasAssociatedError:!0,intersectionIsOpen:!0,defaults:{description:(T)=>`matched by ${T.rule}`},intersections:{pattern:()=>null}});class xJ extends n_{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=R.intrinsic.string.internal;reduceJsonSchema(T,_){if(T.pattern)return _.fallback.patternIntersection({code:"patternIntersection",base:T,pattern:this.rule});return T.pattern=this.rule,T}}var D2={implementation:t9,Node:xJ};var qF=(T,_)=>{let F=i9(T);if(_&&!_.includes(F))return z(`Root of kind ${F} should be one of ${_}`);return F},i9=(T)=>{if(q(T,"root"))return T.kind;if(typeof T==="string")return T[0]==="$"?"alias":(T in __)?"domain":"proto";if(typeof T==="function")return"proto";if(typeof T!=="object"||T===null)return z(hJ(T));if("morphs"in T)return"morph";if("branches"in T||ZT(T))return"union";if("unit"in T)return"unit";if("reference"in T)return"alias";let _=Object.keys(T);if(_.length===0||_.some((F)=>(F in BW)))return"intersection";if("proto"in T)return"proto";if("domain"in T)return"domain";return z(hJ(T))},hJ=(T)=>`${d(T)} is not a valid type schema`,pJ={},n9=(T)=>ZT(T)?T.map((_)=>_.collapsibleJson):T.collapsibleJson,iT={};R.nodesByRegisteredId=iT;var L2=(T)=>{return pJ[T]??=0,`${T}${++pJ[T]}`},S2=(T)=>{let _=t0[T.kind],F=_.applyConfig?.(T.def,T.$.resolvedConfig)??T.def,W={},{meta:J,...Y}=F,$=J===void 0?{}:typeof J==="string"?{description:J}:J,Z=t1(Y).sort(([X],[U])=>m0(X)?m0(U)?o0(X)-o0(U):1:m0(U)?-1:X<U?-1:1).filter(([X,U])=>{if(X.startsWith("meta.")){let M=X.slice(5);return $[M]=U,!1}return!0});for(let X of Z){let U=X[0],M=_.keys[U];if(!M)return z(`Key ${U} is not valid on ${T.kind} schema`);let Q=M.parse?M.parse(X[1],T):X[1];if(Q!==U_&&(Q!==void 0||M.preserveUndefined))W[U]=Q}if(_.reduce&&!T.prereduced){let X=_.reduce(W,T.$);if(X){if(X instanceof I)return X.throw();return r9(X,$)}}return I2({id:T.id,kind:T.kind,inner:W,meta:$,$:T.$})},I2=({id:T,kind:_,inner:F,meta:W,$:J,ignoreCache:Y})=>{let $=t0[_],Z=t1(F),G=[],X={};for(let[P,j]of Z){let y=$.keys[P],u=y.serialize??(y.child?n9:E_);if(X[P]=u(j),y.child===!0){let h=j;if(ZT(h))G.push(...h);else G.push(h)}else if(typeof y.child==="function")G.push(...y.child(j))}if($.finalizeInnerJson)X=$.finalizeInnerJson(X);let U={...X},M={};if(!h_(W))M=c(W,(P,j)=>[P,P==="examples"?j:E_(j)]),U.meta=vW(M,"description",!0);X=vW(X,$.collapsibleKey,!1);let Q=JSON.stringify({kind:_,...X});U=vW(U,$.collapsibleKey,!1);let V=vW(U,$.collapsibleKey,!0),C=JSON.stringify({kind:_,...U});if(J.nodesByHash[C]&&!Y)return J.nodesByHash[C];let K={id:T,kind:_,impl:$,inner:F,innerEntries:Z,innerJson:X,innerHash:Q,meta:W,metaJson:M,json:U,hash:C,collapsibleJson:V,children:G};if(_!=="intersection"){for(let P in F)if(P!=="in"&&P!=="out")K[P]=F[P]}let v=new mJ[_](K,J);return J.nodesByHash[C]=v},gJ=(T,_)=>{if(T.id===_)return T;if(UT(iT[_]))e(`Unexpected attempt to overwrite node id ${_}`);return I2({id:_,kind:T.kind,inner:T.inner,meta:T.meta,$:T.$,ignoreCache:!0})},r9=(T,_,F)=>{if(F&&UT(iT[F]))e(`Unexpected attempt to overwrite node id ${F}`);return I2({id:F??L2(_.alias??T.kind),kind:T.kind,inner:T.inner,meta:_,$:T.$})},vW=(T,_,F)=>{let W=Object.keys(T);if(W.length===1&&W[0]===_){let J=T[_];if(F)return J;if(T_(J,"object")&&(Object.keys(J).length===1||Array.isArray(J)))return J}return T};var PF=(T,_,F)=>{if(T.key!==_.key)return null;let W=T.key,J=OT(T.value,_.value,F),Y=T.required||_.required?"required":"optional";if(J instanceof I)if(Y==="optional")J=R.intrinsic.never.internal;else return J.withPrefixKey(T.key,T.required&&_.required?"required":"optional");if(Y==="required")return F.$.node("required",{key:W,value:J});let $=T.hasDefault()?_.hasDefault()?T.default===_.default?T.default:z(N2(T.default,_.default)):T.default:_.hasDefault()?_.default:U_;return F.$.node("optional",{key:W,value:J,default:$})};class jF extends R_{required=this.kind==="required";optional=this.kind==="optional";impliedBasis=R.intrinsic.object.internal;serializedKey=i_(this.key);compiledKey=typeof this.key==="string"?this.key:this.serializedKey;flatRefs=s(this.value.flatRefs.map((T)=>q_([this.key,...T.path],T.node)),q_([this.key],this.value));_transform(T,_){_.path.push(this.key);let F=super._transform(T,_);return _.path.pop(),F}hasDefault(){return"default"in this.inner}traverseAllows=(T,_)=>{if(this.key in T)return W_(this.key,()=>this.value.traverseAllows(T[this.key],_),_);return this.optional};traverseApply=(T,_)=>{if(this.key in T)W_(this.key,()=>this.value.traverseApply(T[this.key],_),_);else if(this.hasKind("required"))_.errorFromNodeContext(this.errorContext)};compile(T){if(T.if(`${this.serializedKey} in data`,()=>T.traverseKey(this.serializedKey,`data${T.prop(this.key)}`,this.value)),this.hasKind("required"))T.else(()=>T.traversalKind==="Apply"?T.line(`ctx.errorFromNodeContext(${this.compiledErrorContext})`):T.return(!1));if(T.traversalKind==="Allows")T.return(!0)}}var N2=(T,_)=>`Invalid intersection of default values ${d(T)} & ${d(_)}`;var s9=l({kind:"optional",hasAssociatedError:!1,intersectionIsOpen:!0,keys:{key:{},value:{child:!0,parse:(T,_)=>_.$.parseSchema(T)},default:{preserveUndefined:!0}},normalize:(T)=>T,reduce:(T,_)=>{if(_.resolvedConfig.exactOptionalPropertyTypes===!1){if(!T.value.allows(void 0))return _.node("optional",{...T,value:T.value.or(b.undefined)},{prereduced:!0})}},defaults:{description:(T)=>`${T.compiledKey}?: ${T.value.description}`},intersections:{optional:PF}});class oJ extends jF{constructor(...T){super(...T);if("default"in this.inner)vF(this.value,this.inner.default,this.key)}get outProp(){if(!this.hasDefault())return this;let{default:T,..._}=this.inner;return this.cacheGetter("outProp",this.$.node("required",_,{prereduced:!0}))}expression=this.hasDefault()?`${this.compiledKey}: ${this.value.expression} = ${d(this.inner.default)}`:`${this.compiledKey}?: ${this.value.expression}`;defaultValueMorph=e9(this);defaultValueMorphRef=this.defaultValueMorph&&VT(this.defaultValueMorph)}var yF={implementation:s9,Node:oJ},a9={},e9=(T)=>{if(!T.hasDefault())return;let _=`{${T.compiledKey}: ${T.value.id} = ${E_(T.default)}}`;return a9[_]??=C2(T.key,T.value,T.default)},C2=(T,_,F)=>{if(typeof F==="function")return _.includesTransform?(J,Y)=>{return W_(T,()=>_(J[T]=F(),Y),Y),J}:(J)=>{return J[T]=F(),J};let W=_.includesTransform?_.assert(F):F;return T_(W,"object")?(J,Y)=>{return W_(T,()=>_(J[T]=F,Y),Y),J}:(J)=>{return J[T]=W,J}},vF=(T,_,F)=>{let W=W0(_);if(T_(_,"object")&&!W)z(TH(F));let J=T.in(W?_():_);if(J instanceof F_){if(F===null)z(`Default ${J.summary}`);let Y=J.transform(($)=>$.transform((Z)=>({...Z,prefixPath:[F]})));z(`Default for ${Y.summary}`)}return _},TH=(T)=>{return`Non-primitive default ${T===null?"":typeof T==="number"?`for value at [${T}] `:`for ${i_(T)} `}must be specified as a function like () => ({my: 'object'})`};class K_ extends kF{constructor(T,_){super(T,_);Object.defineProperty(this,tT,{value:"root",enumerable:!1})}get internal(){return this}get "~standard"(){return{vendor:"arktype",version:1,validate:(T)=>{let _=this(T);if(_ instanceof F_)return _;return{value:_}}}}as(){return this}brand(T){if(T==="")return z(_H);return this}readonly(){return this}branches=this.hasKind("union")?this.inner.branches:[this];distribute(T,_){let F=this.branches.map(T);return _?.(F)??F}get shortDescription(){return this.meta.description??this.defaultShortDescription}toJsonSchema(T={}){let _=Z2(this.$.resolvedConfig.toJsonSchema,T);_.useRefs||=this.isCyclic;let F=typeof _.dialect==="string"?{$schema:_.dialect}:{};if(Object.assign(F,this.toJsonSchemaRecurse(_)),_.useRefs)F.$defs=c(this.references,(W,J)=>J.isRoot()&&!J.alwaysExpandJsonSchema?[J.id,J.toResolvedJsonSchema(_)]:[]);return F}toJsonSchemaRecurse(T){if(T.useRefs&&!this.alwaysExpandJsonSchema)return{$ref:`#/$defs/${this.id}`};return this.toResolvedJsonSchema(T)}get alwaysExpandJsonSchema(){return this.isBasis()||this.kind==="alias"||this.hasKind("union")&&this.isBoolean}toResolvedJsonSchema(T){let _=this.innerToJsonSchema(T);return Object.assign(_,this.metaJson)}intersect(T){let _=this.$.parseDefinition(T),F=this.rawIntersect(_);if(F instanceof I)return F;return this.$.finalize(F)}rawIntersect(T){return J_(this,T,this.$)}toNeverIfDisjoint(){return this}and(T){let _=this.intersect(T);return _ instanceof I?_.throw():_}rawAnd(T){let _=this.rawIntersect(T);return _ instanceof I?_.throw():_}or(T){let _=this.$.parseDefinition(T);return this.$.finalize(this.rawOr(_))}rawOr(T){let _=[...this.branches,...T.branches];return this.$.node("union",_)}map(T){return this.$.schema(this.applyStructuralOperation("map",[T]))}pick(...T){return this.$.schema(this.applyStructuralOperation("pick",T))}omit(...T){return this.$.schema(this.applyStructuralOperation("omit",T))}required(){return this.$.schema(this.applyStructuralOperation("required",[]))}partial(){return this.$.schema(this.applyStructuralOperation("partial",[]))}_keyof;keyof(){if(this._keyof)return this._keyof;let T=this.applyStructuralOperation("keyof",[]).reduce((_,F)=>_.intersect(F).toNeverIfDisjoint(),R.intrinsic.unknown.internal);if(T.branches.length===0)z(A2(`keyof ${this.expression}`));return this._keyof=this.$.finalize(T)}get props(){if(this.branches.length!==1)return z(FH(this.expression));return[...this.applyStructuralOperation("props",[])[0]]}merge(T){let _=this.$.parseDefinition(T);return this.$.schema(_.distribute((F)=>this.applyStructuralOperation("merge",[uJ(F)??z(cJ("merge",F.expression))])))}applyStructuralOperation(T,_){return this.distribute((F)=>{if(F.equals(R.intrinsic.object)&&T!=="merge")return F;let W=uJ(F);if(!W)z(cJ(T,F.expression));if(T==="keyof")return W.keyof();if(T==="get")return W.get(..._);if(T==="props")return W.props;let J=T==="required"?"require":T==="partial"?"optionalize":T;return this.$.node("intersection",{...F.inner,structure:W[J](..._)})})}get(...T){if(T[0]===void 0)return this;return this.$.schema(this.applyStructuralOperation("get",T))}extract(T){let _=this.$.parseDefinition(T);return this.$.schema(this.branches.filter((F)=>F.extends(_)))}exclude(T){let _=this.$.parseDefinition(T);return this.$.schema(this.branches.filter((F)=>!F.extends(_)))}array(){return this.$.schema(this.isUnknown()?{proto:Array}:{proto:Array,sequence:this},{prereduced:!0})}overlaps(T){return!(this.intersect(T)instanceof I)}extends(T){let _=this.intersect(T);return!(_ instanceof I)&&this.equals(_)}ifExtends(T){return this.extends(T)?this:void 0}subsumes(T){return this.$.parseDefinition(T).extends(this)}configure(T,_="shallow"){return this.configureReferences(T,_)}describe(T,_="shallow"){return this.configure({description:T},_)}optional(){return[this,"?"]}default(T){return vF(this,T,null),[this,"=",T]}from(T){return this.assert(T)}_pipe(...T){let _=T.reduce((F,W)=>F.rawPipeOnce(W),this);return this.$.finalize(_)}tryPipe(...T){let _=T.reduce((F,W)=>F.rawPipeOnce(q(W,"root")?W:(J,Y)=>{try{return W(J,Y)}catch($){return Y.error({code:"predicate",predicate:W,actual:`aborted due to error:
|
|
22
|
+
`);class f_{path=[];errors=new F_(this);root;config;queuedMorphs=[];branches=[];seen={};constructor(T,_){this.root=T,this.config=_}get data(){let T=this.root;for(let _ of this.path)T=T?.[_];return T}get propString(){return i_(this.path)}reject(T){return this.error(T),!1}mustBe(T){return this.error(T),!1}error(T){let _=typeof T==="object"?T.code?T:{...T,code:"predicate"}:{code:"predicate",expected:T};return this.errorFromContext(_)}hasError(){return this.currentErrorCount!==0}get currentBranch(){return this.branches.at(-1)}queueMorphs(T){let _={path:new BF(...this.path),morphs:T};if(this.currentBranch)this.currentBranch.queuedMorphs.push(_);else this.queuedMorphs.push(_)}finalize(T){if(this.queuedMorphs.length){if(typeof this.root==="object"&&this.root!==null&&this.config.clone)this.root=this.config.clone(this.root);this.applyQueuedMorphs()}if(this.hasError())return T?T(this.errors):this.errors;return this.root}get currentErrorCount(){return this.currentBranch?this.currentBranch.error?1:0:this.errors.count}get failFast(){return this.branches.length!==0}pushBranch(){this.branches.push({error:void 0,queuedMorphs:[]})}popBranch(){return this.branches.pop()}get external(){return this}errorFromNodeContext(T){return this.errorFromContext(T)}errorFromContext(T){let _=new G0(T,this);if(this.currentBranch)this.currentBranch.error=_;else this.errors.add(_);return _}applyQueuedMorphs(){while(this.queuedMorphs.length){let T=this.queuedMorphs;this.queuedMorphs=[];for(let{path:_,morphs:F}of T){if(this.errors.affectsPath(_))continue;this.applyMorphsAtPath(_,F)}}}applyMorphsAtPath(T,_){let F=T.at(-1),W;if(F!==void 0){W=this.root;for(let J=0;J<T.length-1;J++)W=W[T[J]]}this.path=[...T];for(let J of _){let Y=OT(J),$=J(W===void 0?this.root:W[F],this);if($ instanceof G0){this.errors.add($);break}if($ instanceof F_){if(!Y)this.errors.merge($);break}if(W===void 0)this.root=$;else W[F]=$;this.applyQueuedMorphs()}}}var W_=(T,_,F)=>{if(!F)return _();F.path.push(T);let W=_();return F.path.pop(),W};class qF extends k_{attachments;$;onFail;includesTransform;includesContextualPredicate;isCyclic;allowsRequiresContext;rootApplyStrategy;contextFreeMorph;rootApply;referencesById;shallowReferences;flatRefs;flatMorphs;allows;get shallowMorphs(){return[]}constructor(T,_){super((W,J,Y=this.onFail)=>{if(J)return this.traverseApply(W,J),J.hasError()?J.errors:J.data;return this.rootApply(W,Y)},{attach:T});this.attachments=T,this.$=_,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((W,J)=>f9(W,J.shallowReferences),[this]);let F=this.isStructural();this.flatRefs=[],this.flatMorphs=[];for(let W=0;W<this.children.length;W++){if(this.includesTransform||=this.children[W].includesTransform,this.includesContextualPredicate||=this.children[W].includesContextualPredicate,this.isCyclic||=this.children[W].isCyclic,!F){let J=this.children[W].flatRefs;for(let Y=0;Y<J.length;Y++){let $=J[Y];if(!this.flatRefs.some((Z)=>DJ(Z,$))){this.flatRefs.push($);for(let Z of $.node.branches)if(Z.hasKind("morph")||Z.hasKind("intersection")&&Z.structure?.structuralMorph!==void 0)this.flatMorphs.push({path:$.path,propString:$.propString,node:Z})}}}Object.assign(this.referencesById,this.children[W].referencesById)}this.flatRefs.sort((W,J)=>W.path.length>J.path.length?1:W.path.length<J.path.length?-1:W.propString>J.propString?1:W.propString<J.propString?-1:W.node.expression<J.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((W)=>W.length===1||W.name==="$arkStructuralMorph")?this.hasKind("union")?this.branches.some((W)=>W.shallowMorphs.length>1)?"contextual":"branchedOptimistic":this.shallowMorphs.length>1?"contextual":"optimistic":"contextual":"contextual",this.rootApply=this.createRootApply(),this.allows=this.allowsRequiresContext?(W)=>this.traverseAllows(W,new f_(W,this.$.resolvedConfig)):(W)=>this.traverseAllows(W)}createRootApply(){switch(this.rootApplyStrategy){case"allows":return(_,F)=>{if(this.allows(_))return _;let W=new f_(_,this.$.resolvedConfig);return this.traverseApply(_,W),W.finalize(F)};case"contextual":return(_,F)=>{let W=new f_(_,this.$.resolvedConfig);return this.traverseApply(_,W),W.finalize(F)};case"optimistic":this.contextFreeMorph=this.shallowMorphs[0];let T=this.$.resolvedConfig.clone;return(_,F)=>{if(this.allows(_))return this.contextFreeMorph(T&&(typeof _==="object"&&_!==null||typeof _==="function")?T(_):_);let W=new f_(_,this.$.resolvedConfig);return this.traverseApply(_,W),W.finalize(F)};case"branchedOptimistic":return this.createBranchedOptimisticRootApply();default:return this.rootApplyStrategy,e(`Unexpected rootApplyStrategy ${this.rootApplyStrategy}`)}}compiledMeta=k9(this.metaJson);cacheGetter(T,_){return Object.defineProperty(this,T,{value:_}),_}get description(){return this.cacheGetter("description",this.meta?.description??this.$.resolvedConfig[this.kind].description(this))}get references(){return Object.values(this.referencesById)}precedence=d0(this.kind);precompilation;assert=(T,_)=>this(T,_,(F)=>F.throw());traverse(T,_){return this(T,_,null)}get in(){return this.cacheGetter("in",this.getIo("in"))}get out(){return this.cacheGetter("out",this.getIo("out"))}getIo(T){if(!this.includesTransform)return this;let _={};for(let[F,W]of this.innerEntries){let J=this.impl.keys[F];if(J.reduceIo)J.reduceIo(T,_,W);else if(J.child){let Y=W;_[F]=XT(Y)?Y.map(($)=>$[T]):Y[T]}else _[F]=W}return this.$.node(this.kind,_)}toJSON(){return this.json}toString(){return`Type<${this.expression}>`}equals(T){let _=OT(T)?T:this.$.parseDefinition(T);return this.innerHash===_.innerHash}ifEquals(T){return this.equals(T)?this:void 0}hasKind(T){return this.kind===T}assertHasKind(T){if(this.kind!==T)D0(`${this.kind} node was not of asserted kind ${T}`);return this}hasKindIn(...T){return T.includes(this.kind)}assertHasKindIn(...T){if(!c_(T,this.kind))D0(`${this.kind} node was not one of asserted kinds ${T}`);return this}isBasis(){return c_(RJ,this.kind)}isConstraint(){return c_(PW,this.kind)}isStructural(){return c_(o0,this.kind)}isRefinement(){return c_(G2,this.kind)}isRoot(){return c_(u0,this.kind)}isUnknown(){return this.hasKind("intersection")&&this.children.length===0}isNever(){return this.hasKind("union")&&this.children.length===0}hasUnit(T){return this.hasKind("unit")&&this.allows(T)}hasOpenIntersection(){return this.impl.intersectionIsOpen}get nestableExpression(){return this.expression}select(T){let _=PF.normalize(T);return this._select(_)}_select(T){let _=PF.applyBoundary[T.boundary??"references"](this);if(T.kind)_=_.filter((F)=>F.kind===T.kind);if(T.where)_=_.filter(T.where);return PF.applyMethod[T.method??"filter"](_,this,T)}transform(T,_){return this._transform(T,this._createTransformContext(_))}_createTransformContext(T){return{root:this,selected:void 0,seen:{},path:[],parseOptions:{prereduced:T?.prereduced??!1},undeclaredKeyHandling:void 0,...T}}_transform(T,_){let F=_.bindScope??this.$;if(_.seen[this.id])return this.$.lazilyResolve(_.seen[this.id]);if(_.shouldTransform?.(this,_)===!1)return this;let W;if(_.seen[this.id]=()=>W,this.hasKind("structure")&&this.undeclared!==_.undeclaredKeyHandling)_={..._,undeclaredKeyHandling:this.undeclared};let J=c(this.inner,(X,O)=>{if(!this.impl.keys[X].child)return[X,O];let M=O;if(!XT(M)){let K=M._transform(T,_);return K?[X,K]:[]}if(M.length===0)return[X,O];let Q=M.flatMap((K)=>{return K._transform(T,_)??[]});return Q.length?[X,Q]:[]});delete _.seen[this.id];let Y=Object.assign(J,{meta:this.meta}),$=_.selected&&!_.selected.includes(this)?Y:T(this.kind,Y,_);if($===null)return null;if(OT($))return W=$;let Z=Object.keys($);if((Z.length===0||Z.length===1&&Z[0]==="meta")&&!p_(this.inner))return null;if((this.kind==="required"||this.kind==="optional"||this.kind==="index")&&!("value"in $))return _.undeclaredKeyHandling?{...$,value:z.intrinsic.unknown}:null;if(this.kind==="morph")$.in??=z.intrinsic.unknown;return W=F.node(this.kind,$,_.parseOptions)}configureReferences(T,_="references"){let F=PF.normalize(_),W=typeof T==="string"?(Z,G)=>({...G,meta:{...G.meta,description:T}}):typeof T==="function"?(Z,G)=>({...G,meta:T(G.meta)}):(Z,G)=>({...G,meta:{...G.meta,...T}});if(F.boundary==="self")return this.$.node(this.kind,W(this.kind,{...this.inner,meta:this.meta}));let J=this._select(F),Y=J&&J0(J),$=F.boundary==="child"?(Z,G)=>G.root.children.includes(Z):F.boundary==="shallow"?(Z)=>Z.kind!=="structure":()=>!0;return this.$.finalize(this.transform(W,{shouldTransform:$,selected:Y}))}}var PF={applyBoundary:{self:(T)=>[T],child:(T)=>[...T.children],shallow:(T)=>[...T.shallowReferences],references:(T)=>[...T.references]},applyMethod:{filter:(T)=>T,assertFilter:(T,_,F)=>{if(T.length===0)D0(LJ(_,F));return T},find:(T)=>T[0],assertFind:(T,_,F)=>{if(T.length===0)D0(LJ(_,F));return T[0]}},normalize:(T)=>typeof T==="function"?{boundary:"references",method:"filter",where:T}:typeof T==="string"?qT(T,PF.applyBoundary)?{method:"filter",boundary:T}:{boundary:"references",method:"filter",kind:T}:{boundary:"references",method:"filter",...T}},LJ=(T,_)=>`${T} had no references matching ${d(_)}.`,C9=(T)=>i_(T,{stringifyNonKey:(_)=>_.expression}),B9=/"(\$ark\.[^"]+)"/g,k9=(T)=>JSON.stringify(T).replaceAll(B9,"$1"),P_=(T,_)=>({path:T,node:_,propString:C9(T)}),DJ=(T,_)=>T.propString===_.propString&&T.node.equals(_.node),O2=(T,_)=>h_(T,_,{isEqual:DJ}),f9=(T,_)=>h_(T,_,{isEqual:(F,W)=>F.equals(W)});class N extends Array{static init(T,_,F,W){return new N({kind:T,l:_,r:F,path:W?.path??[],optional:W?.optional??!1})}add(T,_,F,W){return this.push({kind:T,l:_,r:F,path:W?.path??[],optional:W?.optional??!1}),this}get summary(){return this.describeReasons()}describeReasons(){if(this.length===1){let{path:T,l:_,r:F}=this[0],W=i_(T);return M2(`Intersection${W&&` at ${W}`} of ${SJ(_,F)}`)}return`The following intersections result in unsatisfiable types:
|
|
23
|
+
\u2022 ${this.map(({path:T,l:_,r:F})=>`${T}: ${SJ(_,F)}`).join(`
|
|
24
|
+
\u2022 `)}`}throw(){return E(this.describeReasons())}invert(){let T=this.map((_)=>({..._,l:_.r,r:_.l}));if(!(T instanceof N))return new N(...T);return T}withPrefixKey(T,_){return this.map((F)=>({...F,path:[T,...F.path],optional:F.optional||_==="optional"}))}toNeverIfDisjoint(){return z.intrinsic.never}}var SJ=(T,_)=>`${U2(T)} and ${U2(_)}`,U2=(T)=>OT(T)?T.expression:XT(T)?T.map(U2).join(" | ")||"never":String(T),M2=(T)=>`${T} results in an unsatisfiable type`;var l0={},J_=(T,_,F)=>UT(T,_,{$:F,invert:!1,pipe:!1}),jF=(T,_,F)=>UT(T,_,{$:F,invert:!1,pipe:!0}),UT=(T,_,F)=>{let W=F.pipe?"|>":"&",J=`${T.hash}${W}${_.hash}`;if(l0[J]!==void 0)return l0[J];if(!F.pipe){let Z=`${_.hash}${W}${T.hash}`;if(l0[Z]!==void 0){let G=l0[Z],X=G instanceof N?G.invert():G;return l0[J]=X,X}}let Y=!F.pipe||!T.includesTransform&&!_.includesTransform;if(Y&&T.equals(_))return T;let $=Y?w2(T,_,F):T.hasKindIn(...u0)?P9(T,_,F):w2(T,_,F);if(OT($)){if(T.equals($))$=T;else if(_.equals($))$=_}return l0[J]=$,$},w2=(T,_,F)=>{let W=T.precedence<_.precedence?T.kind:_.kind,J=T.impl.intersections[_.kind]??_.impl.intersections[T.kind];if(J===void 0)return null;else if(W===T.kind)return J(T,_,F);else{let Y=J(_,T,{...F,invert:!F.invert});if(Y instanceof N)Y=Y.invert();return Y}},P9=(T,_,F)=>T.includesTransform||_.includesTransform?F.invert?IJ(_,T,F):IJ(T,_,F):w2(T,_,F),IJ=(T,_,F)=>T.distribute((W)=>q9(W,_,F),(W)=>{let J=W.filter(OT);if(J.length===0)return N.init("union",T.branches,_.branches);if(J.length<T.branches.length||!T.branches.every((Z,G)=>Z.in.equals(J[G].in)))return F.$.parseSchema(J);let Y;if(J.length===1){let Z=J[0];if(!Y)return Z;return F.$.node("morph",{...Z.inner,in:Z.in.configure(Y,"self")})}let $={branches:J};if(Y)$.meta=Y;return F.$.parseSchema($)}),q9=(T,_,F)=>{if(T.hasKind("morph")){let J=[...T.morphs];if(T.lastMorphIfNode){let Y=UT(T.lastMorphIfNode,_,F);if(Y instanceof N)return Y;J[J.length-1]=Y}else J.push(_);return F.$.node("morph",{morphs:J,in:T.inner.in})}if(_.hasKind("morph")){let J=UT(T,_.in,F);if(J instanceof N)return J;return F.$.node("morph",{morphs:[_],in:J})}return F.$.node("morph",{morphs:[_],in:T})};class z_ extends qF{constructor(T,_){super(T,_);Object.defineProperty(this,tT,{value:"constraint",enumerable:!1})}impliedSiblings;intersect(T){return J_(this,T,this.$)}}class r_ extends z_{traverseApply=(T,_)=>{if(!this.traverseAllows(T,_))_.errorFromNodeContext(this.errorContext)};compile(T){if(T.traversalKind==="Allows")T.return(this.compiledCondition);else T.if(this.compiledNegation,()=>T.line(`${T.ctx}.errorFromNodeContext(${this.compiledErrorContext})`))}get errorContext(){return{code:this.kind,description:this.description,meta:this.meta,...this.inner}}get compiledErrorContext(){return X0(this.errorContext)}}var cT=(T)=>(_,F)=>{if(XT(_)){if(_.length===0)return;let J=_.map((Y)=>F.$.node(T,Y));if(T==="predicate")return J;return J.sort((Y,$)=>Y.hash<$.hash?-1:1)}let W=F.$.node(T,_);return W.hasOpenIntersection()?[W]:W},t0=(T)=>{let _=T.r.shift();if(!_){let W=T.l.length===0&&T.kind==="structure"?z.intrinsic.unknown.internal:T.ctx.$.node(T.kind,Object.assign(T.baseInner,j9(T.l)),{prereduced:!0});for(let J of T.roots){if(W instanceof N)return W;W=UT(J,W,T.ctx)}return W}let F=!1;for(let W=0;W<T.l.length;W++){let J=UT(T.l[W],_,T.ctx);if(J===null)continue;if(J instanceof N)return J;if(!F){if(J.isRoot())return T.roots.push(J),T.l.splice(W),t0(T);T.l[W]=J,F=!0}else if(!T.l.includes(J))return e(`Unexpectedly encountered multiple distinct intersection results for refinement ${J}`)}if(!F)T.l.push(_);if(T.kind==="intersection"){if(_.impliedSiblings)for(let W of _.impliedSiblings)h_(T.r,W)}return t0(T)},i0=(T)=>{return Object.entries(T).flatMap(([F,W])=>(F in qW)?W:[]).sort((F,W)=>F.precedence<W.precedence?-1:F.precedence>W.precedence?1:F.kind==="predicate"&&W.kind==="predicate"?0:F.hash<W.hash?-1:1)},j9=(T)=>{let _={};for(let F of T)if(F.hasOpenIntersection())_[F.kind]=s(_[F.kind],F);else{if(_[F.kind])return e(`Unexpected intersection of closed refinements of kind ${F.kind}`);_[F.kind]=F}return _},NJ=(...T)=>E(CJ(...T)),CJ=(T,_,F)=>{let W=F.hasKind("morph")?"a morph":F.isUnknown()?"unknown":F.exclude(_).defaultShortDescription;return`${FJ(T)} operand must be ${_.description} (was ${W})`};var BJ=(T,_,F)=>new A0(T,_,F,F,null);class yW extends k_{}class A0 extends k_{[tT]="generic";paramDefs;bodyDef;$;arg$;baseInstantiation;hkt;description;constructor(T,_,F,W,J){super((...Y)=>{let $=c(this.names,(Z,G)=>{let X=this.arg$.parse(Y[Z]);if(!X.extends(this.constraints[Z]))E(y9(G,this.constraints[Z].expression,X.expression));return[G,X]});if(this.defIsLazy()){let Z=this.bodyDef($);return this.$.parse(Z)}return this.$.parse(_,{args:$})});this.paramDefs=T,this.bodyDef=_,this.$=F,this.arg$=W,this.hkt=J,this.description=J?new J().description??`a generic type for ${J.constructor.name}`:"a generic type",this.baseInstantiation=this(...this.constraints)}defIsLazy(){return this.bodyDef instanceof yW}cacheGetter(T,_){return Object.defineProperty(this,T,{value:_}),_}get json(){return this.cacheGetter("json",{params:this.params.map((T)=>T[1].isUnknown()?T[0]:[T[0],T[1].json]),body:UJ(this.bodyDef)})}get params(){return this.cacheGetter("params",this.paramDefs.map((T)=>typeof T==="string"?[T,z.intrinsic.unknown]:[T[0],this.$.parse(T[1])]))}get names(){return this.cacheGetter("names",this.params.map((T)=>T[0]))}get constraints(){return this.cacheGetter("constraints",this.params.map((T)=>T[1]))}get internal(){return this}get referencesById(){return this.baseInstantiation.internal.referencesById}get references(){return this.baseInstantiation.internal.references}}var y9=(T,_,F)=>`${T} must be assignable to ${_} (was ${F})`;var v9=l({kind:"predicate",hasAssociatedError:!0,collapsibleKey:"predicate",keys:{predicate:{}},normalize:(T)=>typeof T==="function"?{predicate:T}:T,defaults:{description:(T)=>`valid according to ${T.predicate.name||"an anonymous predicate"}`},intersectionIsOpen:!0,intersections:{predicate:()=>null}});class kJ extends z_{serializedPredicate=KT(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=X0(this.errorContext);traverseApply=(T,_)=>{if(!this.predicate(T,_.external)&&!_.hasError())_.errorFromNodeContext(this.errorContext)};compile(T){if(T.traversalKind==="Allows"){T.return(this.compiledCondition);return}T.if(`${this.compiledNegation} && !ctx.hasError()`,()=>T.line(`ctx.errorFromNodeContext(${this.compiledErrorContext})`))}reduceJsonSchema(T,_){return _.fallback.predicate({code:"predicate",base:T,predicate:this.predicate})}}var Q2={implementation:v9,Node:kJ};var x9=l({kind:"divisor",collapsibleKey:"rule",keys:{rule:{parse:(T)=>Number.isInteger(T)?T:E(b9(T))}},normalize:(T)=>typeof T==="number"?{rule:T}:T,hasAssociatedError:!0,defaults:{description:(T)=>T.rule===1?"an integer":T.rule===2?"even":`a multiple of ${T.rule}`},intersections:{divisor:(T,_,F)=>F.$.node("divisor",{rule:Math.abs(T.rule*_.rule/h9(T.rule,_.rule))})},obviatesBasisDescription:!0});class fJ extends r_{traverseAllows=(T)=>T%this.rule===0;compiledCondition=`data % ${this.rule} === 0`;compiledNegation=`data % ${this.rule} !== 0`;impliedBasis=z.intrinsic.number.internal;expression=`% ${this.rule}`;reduceJsonSchema(T){if(T.type="integer",this.rule===1)return T;return T.multipleOf=this.rule,T}}var R2={implementation:x9,Node:fJ};var b9=(T)=>`divisor must be an integer (was ${T})`,h9=(T,_)=>{let F,W=T,J=_;while(J!==0)F=J,J=W%J,W=F;return W};class U_ extends r_{boundOperandKind=o9[this.kind];compiledActual=this.boundOperandKind==="value"?"data":this.boundOperandKind==="length"?"data.length":"data.valueOf()";comparator=u9(this.kind,this.exclusive);numericLimit=this.rule.valueOf();expression=`${this.comparator} ${this.rule}`;compiledCondition=`${this.compiledActual} ${this.comparator} ${this.numericLimit}`;compiledNegation=`${this.compiledActual} ${p9[this.comparator]} ${this.numericLimit}`;stringLimit=this.boundOperandKind==="date"?c9(this.numericLimit):`${this.numericLimit}`;limitKind=this.comparator["0"]==="<"?"upper":"lower";isStricterThan(T){return(this.limitKind==="upper"?this.numericLimit<T.numericLimit:this.numericLimit>T.numericLimit)||this.numericLimit===T.numericLimit&&this.exclusive===!0&&!T.exclusive}overlapsRange(T){if(this.isStricterThan(T))return!1;if(this.numericLimit===T.numericLimit&&(this.exclusive||T.exclusive))return!1;return!0}overlapIsUnit(T){return this.numericLimit===T.numericLimit&&!this.exclusive&&!T.exclusive}}var p9={"<":">=","<=":">",">":"<=",">=":"<"},g9={min:"max",minLength:"maxLength",after:"before"},vW={parse:(T)=>T||void 0},xW=(T)=>(_)=>{if(typeof _==="number")return{rule:_};let{exclusive:F,...W}=_;return F?{...W,rule:T==="minLength"?W.rule+1:W.rule-1}:W},bW=(T)=>(_)=>{if(typeof _==="number"||typeof _==="string"||_ instanceof Date)return{rule:_};let{exclusive:F,...W}=_;if(!F)return W;let J=typeof W.rule==="number"?W.rule:typeof W.rule==="string"?new Date(W.rule).valueOf():W.rule.valueOf();return F?{...W,rule:T==="after"?J+1:J-1}:W},hW=(T)=>typeof T==="string"||typeof T==="number"?new Date(T):T,m9=(T,_)=>`${T} bound must be a positive integer (was ${_})`,n0=(T)=>(_)=>{if(!Number.isInteger(_)||_<0)E(m9(T,_));return _},o9={min:"value",max:"value",minLength:"length",maxLength:"length",after:"date",before:"date"},u9=(T,_)=>`${qT(T,g9)?">":"<"}${_?"":"="}`,c9=(T)=>typeof T==="string"?T:new Date(T).toLocaleString(),PJ=(T)=>`Bounded expression ${T} must be exactly one of number, string, Array, or Date`;var d9=l({kind:"after",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:hW,serialize:(T)=>T.toISOString()}},normalize:bW("after"),defaults:{description:(T)=>`${T.collapsibleLimitString} or later`,actual:C0},intersections:{after:(T,_)=>T.isStricterThan(_)?T:_}});class qJ extends U_{impliedBasis=z.intrinsic.Date.internal;collapsibleLimitString=C0(this.rule);traverseAllows=(T)=>T>=this.rule;reduceJsonSchema(T,_){return _.fallback.date({code:"date",base:T,after:this.rule})}}var E2={implementation:d9,Node:qJ};var l9=l({kind:"before",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:hW,serialize:(T)=>T.toISOString()}},normalize:bW("before"),defaults:{description:(T)=>`${T.collapsibleLimitString} or earlier`,actual:C0},intersections:{before:(T,_)=>T.isStricterThan(_)?T:_,after:(T,_,F)=>T.overlapsRange(_)?T.overlapIsUnit(_)?F.$.node("unit",{unit:T.rule}):null:N.init("range",T,_)}});class jJ extends U_{collapsibleLimitString=C0(this.rule);traverseAllows=(T)=>T<=this.rule;impliedBasis=z.intrinsic.Date.internal;reduceJsonSchema(T,_){return _.fallback.date({code:"date",base:T,before:this.rule})}}var z2={implementation:l9,Node:jJ};var t9=l({kind:"exactLength",collapsibleKey:"rule",keys:{rule:{parse:n0("exactLength")}},normalize:(T)=>typeof T==="number"?{rule:T}:T,hasAssociatedError:!0,defaults:{description:(T)=>`exactly length ${T.rule}`,actual:(T)=>`${T.length}`},intersections:{exactLength:(T,_,F)=>N.init("unit",F.$.node("unit",{unit:T.rule}),F.$.node("unit",{unit:_.rule}),{path:["length"]}),minLength:(T,_)=>T.rule>=_.rule?T:N.init("range",T,_),maxLength:(T,_)=>T.rule<=_.rule?T:N.init("range",T,_)}});class yJ extends r_{traverseAllows=(T)=>T.length===this.rule;compiledCondition=`data.length === ${this.rule}`;compiledNegation=`data.length !== ${this.rule}`;impliedBasis=z.intrinsic.lengthBoundable.internal;expression=`== ${this.rule}`;reduceJsonSchema(T){switch(T.type){case"string":return T.minLength=this.rule,T.maxLength=this.rule,T;case"array":return T.minItems=this.rule,T.maxItems=this.rule,T;default:return RT.throwInternalOperandError("exactLength",T)}}}var V2={implementation:t9,Node:yJ};var i9=l({kind:"max",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{},exclusive:vW},normalize:(T)=>typeof T==="number"?{rule:T}:T,defaults:{description:(T)=>{if(T.rule===0)return T.exclusive?"negative":"non-positive";return`${T.exclusive?"less than":"at most"} ${T.rule}`}},intersections:{max:(T,_)=>T.isStricterThan(_)?T:_,min:(T,_,F)=>T.overlapsRange(_)?T.overlapIsUnit(_)?F.$.node("unit",{unit:T.rule}):null:N.init("range",T,_)},obviatesBasisDescription:!0});class vJ extends U_{impliedBasis=z.intrinsic.number.internal;traverseAllows=this.exclusive?(T)=>T<this.rule:(T)=>T<=this.rule;reduceJsonSchema(T){if(this.exclusive)T.exclusiveMaximum=this.rule;else T.maximum=this.rule;return T}}var K2={implementation:i9,Node:vJ};var n9=l({kind:"maxLength",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:n0("maxLength")}},reduce:(T,_)=>T.rule===0?_.node("exactLength",T):void 0,normalize:xW("maxLength"),defaults:{description:(T)=>`at most length ${T.rule}`,actual:(T)=>`${T.length}`},intersections:{maxLength:(T,_)=>T.isStricterThan(_)?T:_,minLength:(T,_,F)=>T.overlapsRange(_)?T.overlapIsUnit(_)?F.$.node("exactLength",{rule:T.rule}):null:N.init("range",T,_)}});class xJ extends U_{impliedBasis=z.intrinsic.lengthBoundable.internal;traverseAllows=(T)=>T.length<=this.rule;reduceJsonSchema(T){switch(T.type){case"string":return T.maxLength=this.rule,T;case"array":return T.maxItems=this.rule,T;default:return RT.throwInternalOperandError("maxLength",T)}}}var L2={implementation:n9,Node:xJ};var r9=l({kind:"min",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{},exclusive:vW},normalize:(T)=>typeof T==="number"?{rule:T}:T,defaults:{description:(T)=>{if(T.rule===0)return T.exclusive?"positive":"non-negative";return`${T.exclusive?"more than":"at least"} ${T.rule}`}},intersections:{min:(T,_)=>T.isStricterThan(_)?T:_},obviatesBasisDescription:!0});class bJ extends U_{impliedBasis=z.intrinsic.number.internal;traverseAllows=this.exclusive?(T)=>T>this.rule:(T)=>T>=this.rule;reduceJsonSchema(T){if(this.exclusive)T.exclusiveMinimum=this.rule;else T.minimum=this.rule;return T}}var D2={implementation:r9,Node:bJ};var s9=l({kind:"minLength",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:n0("minLength")}},reduce:(T)=>T.rule===0?z.intrinsic.unknown:void 0,normalize:xW("minLength"),defaults:{description:(T)=>T.rule===1?"non-empty":`at least length ${T.rule}`,actual:(T)=>T.length===0?"":`${T.length}`},intersections:{minLength:(T,_)=>T.isStricterThan(_)?T:_}});class hJ extends U_{impliedBasis=z.intrinsic.lengthBoundable.internal;traverseAllows=(T)=>T.length>=this.rule;reduceJsonSchema(T){switch(T.type){case"string":return T.minLength=this.rule,T;case"array":return T.minItems=this.rule,T;default:return RT.throwInternalOperandError("minLength",T)}}}var S2={implementation:s9,Node:hJ};var pJ={min:D2.implementation,max:K2.implementation,minLength:S2.implementation,maxLength:L2.implementation,exactLength:V2.implementation,after:E2.implementation,before:z2.implementation},gJ={min:D2.Node,max:K2.Node,minLength:S2.Node,maxLength:L2.Node,exactLength:V2.Node,after:E2.Node,before:z2.Node};var a9=l({kind:"pattern",collapsibleKey:"rule",keys:{rule:{},flags:{}},normalize:(T)=>typeof T==="string"?{rule:T}:T instanceof RegExp?T.flags?{rule:T.source,flags:T.flags}:{rule:T.source}:T,obviatesBasisDescription:!0,obviatesBasisExpression:!0,hasAssociatedError:!0,intersectionIsOpen:!0,defaults:{description:(T)=>`matched by ${T.rule}`},intersections:{pattern:()=>null}});class mJ extends r_{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=z.intrinsic.string.internal;reduceJsonSchema(T,_){if(T.pattern)return _.fallback.patternIntersection({code:"patternIntersection",base:T,pattern:this.rule});return T.pattern=this.rule,T}}var I2={implementation:a9,Node:mJ};var yF=(T,_)=>{let F=e9(T);if(_&&!_.includes(F))return E(`Root of kind ${F} should be one of ${_}`);return F},e9=(T)=>{if(P(T,"root"))return T.kind;if(typeof T==="string")return T[0]==="$"?"alias":(T in __)?"domain":"proto";if(typeof T==="function")return"proto";if(typeof T!=="object"||T===null)return E(oJ(T));if("morphs"in T)return"morph";if("branches"in T||XT(T))return"union";if("unit"in T)return"unit";if("reference"in T)return"alias";let _=Object.keys(T);if(_.length===0||_.some((F)=>(F in qW)))return"intersection";if("proto"in T)return"proto";if("domain"in T)return"domain";return E(oJ(T))},oJ=(T)=>`${d(T)} is not a valid type schema`,uJ={},TA=(T)=>XT(T)?T.map((_)=>_.collapsibleJson):T.collapsibleJson,iT={};z.nodesByRegisteredId=iT;var N2=(T)=>{return uJ[T]??=0,`${T}${++uJ[T]}`},C2=(T)=>{let _=r0[T.kind],F=_.applyConfig?.(T.def,T.$.resolvedConfig)??T.def,W={},{meta:J,...Y}=F,$=J===void 0?{}:typeof J==="string"?{description:J}:J,Z=r1(Y).sort(([X],[O])=>c0(X)?c0(O)?d0(X)-d0(O):1:c0(O)?-1:X<O?-1:1).filter(([X,O])=>{if(X.startsWith("meta.")){let M=X.slice(5);return $[M]=O,!1}return!0});for(let X of Z){let O=X[0],M=_.keys[O];if(!M)return E(`Key ${O} is not valid on ${T.kind} schema`);let Q=M.parse?M.parse(X[1],T):X[1];if(Q!==O_&&(Q!==void 0||M.preserveUndefined))W[O]=Q}if(_.reduce&&!T.prereduced){let X=_.reduce(W,T.$);if(X){if(X instanceof N)return X.throw();return _A(X,$)}}return B2({id:T.id,kind:T.kind,inner:W,meta:$,$:T.$})},B2=({id:T,kind:_,inner:F,meta:W,$:J,ignoreCache:Y})=>{let $=r0[_],Z=r1(F),G=[],X={};for(let[q,j]of Z){let y=$.keys[q],u=y.serialize??(y.child?TA:E_);if(X[q]=u(j),y.child===!0){let h=j;if(XT(h))G.push(...h);else G.push(h)}else if(typeof y.child==="function")G.push(...y.child(j))}if($.finalizeInnerJson)X=$.finalizeInnerJson(X);let O={...X},M={};if(!p_(W))M=c(W,(q,j)=>[q,q==="examples"?j:E_(j)]),O.meta=pW(M,"description",!0);X=pW(X,$.collapsibleKey,!1);let Q=JSON.stringify({kind:_,...X});O=pW(O,$.collapsibleKey,!1);let K=pW(O,$.collapsibleKey,!0),B=JSON.stringify({kind:_,...O});if(J.nodesByHash[B]&&!Y)return J.nodesByHash[B];let V={id:T,kind:_,impl:$,inner:F,innerEntries:Z,innerJson:X,innerHash:Q,meta:W,metaJson:M,json:O,hash:B,collapsibleJson:K,children:G};if(_!=="intersection"){for(let q in F)if(q!=="in"&&q!=="out")V[q]=F[q]}let v=new dJ[_](V,J);return J.nodesByHash[B]=v},cJ=(T,_)=>{if(T.id===_)return T;if(OT(iT[_]))e(`Unexpected attempt to overwrite node id ${_}`);return B2({id:_,kind:T.kind,inner:T.inner,meta:T.meta,$:T.$,ignoreCache:!0})},_A=(T,_,F)=>{if(F&&OT(iT[F]))e(`Unexpected attempt to overwrite node id ${F}`);return B2({id:F??N2(_.alias??T.kind),kind:T.kind,inner:T.inner,meta:_,$:T.$})},pW=(T,_,F)=>{let W=Object.keys(T);if(W.length===1&&W[0]===_){let J=T[_];if(F)return J;if(T_(J,"object")&&(Object.keys(J).length===1||Array.isArray(J)))return J}return T};var vF=(T,_,F)=>{if(T.key!==_.key)return null;let W=T.key,J=UT(T.value,_.value,F),Y=T.required||_.required?"required":"optional";if(J instanceof N)if(Y==="optional")J=z.intrinsic.never.internal;else return J.withPrefixKey(T.key,T.required&&_.required?"required":"optional");if(Y==="required")return F.$.node("required",{key:W,value:J});let $=T.hasDefault()?_.hasDefault()?T.default===_.default?T.default:E(k2(T.default,_.default)):T.default:_.hasDefault()?_.default:O_;return F.$.node("optional",{key:W,value:J,default:$})};class xF extends z_{required=this.kind==="required";optional=this.kind==="optional";impliedBasis=z.intrinsic.object.internal;serializedKey=n_(this.key);compiledKey=typeof this.key==="string"?this.key:this.serializedKey;flatRefs=s(this.value.flatRefs.map((T)=>P_([this.key,...T.path],T.node)),P_([this.key],this.value));_transform(T,_){_.path.push(this.key);let F=super._transform(T,_);return _.path.pop(),F}hasDefault(){return"default"in this.inner}traverseAllows=(T,_)=>{if(this.key in T)return W_(this.key,()=>this.value.traverseAllows(T[this.key],_),_);return this.optional};traverseApply=(T,_)=>{if(this.key in T)W_(this.key,()=>this.value.traverseApply(T[this.key],_),_);else if(this.hasKind("required"))_.errorFromNodeContext(this.errorContext)};compile(T){if(T.if(`${this.serializedKey} in data`,()=>T.traverseKey(this.serializedKey,`data${T.prop(this.key)}`,this.value)),this.hasKind("required"))T.else(()=>T.traversalKind==="Apply"?T.line(`ctx.errorFromNodeContext(${this.compiledErrorContext})`):T.return(!1));if(T.traversalKind==="Allows")T.return(!0)}}var k2=(T,_)=>`Invalid intersection of default values ${d(T)} & ${d(_)}`;var FA=l({kind:"optional",hasAssociatedError:!1,intersectionIsOpen:!0,keys:{key:{},value:{child:!0,parse:(T,_)=>_.$.parseSchema(T)},default:{preserveUndefined:!0}},normalize:(T)=>T,reduce:(T,_)=>{if(_.resolvedConfig.exactOptionalPropertyTypes===!1){if(!T.value.allows(void 0))return _.node("optional",{...T,value:T.value.or(x.undefined)},{prereduced:!0})}},defaults:{description:(T)=>`${T.compiledKey}?: ${T.value.description}`},intersections:{optional:vF}});class lJ extends xF{constructor(...T){super(...T);if("default"in this.inner)hF(this.value,this.inner.default,this.key)}get outProp(){if(!this.hasDefault())return this;let{default:T,..._}=this.inner;return this.cacheGetter("outProp",this.$.node("required",_,{prereduced:!0}))}expression=this.hasDefault()?`${this.compiledKey}: ${this.value.expression} = ${d(this.inner.default)}`:`${this.compiledKey}?: ${this.value.expression}`;defaultValueMorph=JA(this);defaultValueMorphRef=this.defaultValueMorph&&KT(this.defaultValueMorph)}var bF={implementation:FA,Node:lJ},WA={},JA=(T)=>{if(!T.hasDefault())return;let _=`{${T.compiledKey}: ${T.value.id} = ${E_(T.default)}}`;return WA[_]??=f2(T.key,T.value,T.default)},f2=(T,_,F)=>{if(typeof F==="function")return _.includesTransform?(J,Y)=>{return W_(T,()=>_(J[T]=F(),Y),Y),J}:(J)=>{return J[T]=F(),J};let W=_.includesTransform?_.assert(F):F;return T_(W,"object")?(J,Y)=>{return W_(T,()=>_(J[T]=F,Y),Y),J}:(J)=>{return J[T]=W,J}},hF=(T,_,F)=>{let W=Y0(_);if(T_(_,"object")&&!W)E(YA(F));let J=T.in(W?_():_);if(J instanceof F_){if(F===null)E(`Default ${J.summary}`);let Y=J.transform(($)=>$.transform((Z)=>({...Z,prefixPath:[F]})));E(`Default for ${Y.summary}`)}return _},YA=(T)=>{return`Non-primitive default ${T===null?"":typeof T==="number"?`for value at [${T}] `:`for ${n_(T)} `}must be specified as a function like () => ({my: 'object'})`};class V_ extends qF{constructor(T,_){super(T,_);Object.defineProperty(this,tT,{value:"root",enumerable:!1})}get internal(){return this}get "~standard"(){return{vendor:"arktype",version:1,validate:(T)=>{let _=this(T);if(_ instanceof F_)return _;return{value:_}}}}as(){return this}brand(T){if(T==="")return E($A);return this}readonly(){return this}branches=this.hasKind("union")?this.inner.branches:[this];distribute(T,_){let F=this.branches.map(T);return _?.(F)??F}get shortDescription(){return this.meta.description??this.defaultShortDescription}toJsonSchema(T={}){let _=A2(this.$.resolvedConfig.toJsonSchema,T);_.useRefs||=this.isCyclic;let F=typeof _.dialect==="string"?{$schema:_.dialect}:{};if(Object.assign(F,this.toJsonSchemaRecurse(_)),_.useRefs)F.$defs=c(this.references,(W,J)=>J.isRoot()&&!J.alwaysExpandJsonSchema?[J.id,J.toResolvedJsonSchema(_)]:[]);return F}toJsonSchemaRecurse(T){if(T.useRefs&&!this.alwaysExpandJsonSchema)return{$ref:`#/$defs/${this.id}`};return this.toResolvedJsonSchema(T)}get alwaysExpandJsonSchema(){return this.isBasis()||this.kind==="alias"||this.hasKind("union")&&this.isBoolean}toResolvedJsonSchema(T){let _=this.innerToJsonSchema(T);return Object.assign(_,this.metaJson)}intersect(T){let _=this.$.parseDefinition(T),F=this.rawIntersect(_);if(F instanceof N)return F;return this.$.finalize(F)}rawIntersect(T){return J_(this,T,this.$)}toNeverIfDisjoint(){return this}and(T){let _=this.intersect(T);return _ instanceof N?_.throw():_}rawAnd(T){let _=this.rawIntersect(T);return _ instanceof N?_.throw():_}or(T){let _=this.$.parseDefinition(T);return this.$.finalize(this.rawOr(_))}rawOr(T){let _=[...this.branches,...T.branches];return this.$.node("union",_)}map(T){return this.$.schema(this.applyStructuralOperation("map",[T]))}pick(...T){return this.$.schema(this.applyStructuralOperation("pick",T))}omit(...T){return this.$.schema(this.applyStructuralOperation("omit",T))}required(){return this.$.schema(this.applyStructuralOperation("required",[]))}partial(){return this.$.schema(this.applyStructuralOperation("partial",[]))}_keyof;keyof(){if(this._keyof)return this._keyof;let T=this.applyStructuralOperation("keyof",[]).reduce((_,F)=>_.intersect(F).toNeverIfDisjoint(),z.intrinsic.unknown.internal);if(T.branches.length===0)E(M2(`keyof ${this.expression}`));return this._keyof=this.$.finalize(T)}get props(){if(this.branches.length!==1)return E(ZA(this.expression));return[...this.applyStructuralOperation("props",[])[0]]}merge(T){let _=this.$.parseDefinition(T);return this.$.schema(_.distribute((F)=>this.applyStructuralOperation("merge",[tJ(F)??E(iJ("merge",F.expression))])))}applyStructuralOperation(T,_){return this.distribute((F)=>{if(F.equals(z.intrinsic.object)&&T!=="merge")return F;let W=tJ(F);if(!W)E(iJ(T,F.expression));if(T==="keyof")return W.keyof();if(T==="get")return W.get(..._);if(T==="props")return W.props;let J=T==="required"?"require":T==="partial"?"optionalize":T;return this.$.node("intersection",{...F.inner,structure:W[J](..._)})})}get(...T){if(T[0]===void 0)return this;return this.$.schema(this.applyStructuralOperation("get",T))}extract(T){let _=this.$.parseDefinition(T);return this.$.schema(this.branches.filter((F)=>F.extends(_)))}exclude(T){let _=this.$.parseDefinition(T);return this.$.schema(this.branches.filter((F)=>!F.extends(_)))}array(){return this.$.schema(this.isUnknown()?{proto:Array}:{proto:Array,sequence:this},{prereduced:!0})}overlaps(T){return!(this.intersect(T)instanceof N)}extends(T){let _=this.intersect(T);return!(_ instanceof N)&&this.equals(_)}ifExtends(T){return this.extends(T)?this:void 0}subsumes(T){return this.$.parseDefinition(T).extends(this)}configure(T,_="shallow"){return this.configureReferences(T,_)}describe(T,_="shallow"){return this.configure({description:T},_)}optional(){return[this,"?"]}default(T){return hF(this,T,null),[this,"=",T]}from(T){return this.assert(T)}_pipe(...T){let _=T.reduce((F,W)=>F.rawPipeOnce(W),this);return this.$.finalize(_)}tryPipe(...T){let _=T.reduce((F,W)=>F.rawPipeOnce(P(W,"root")?W:(J,Y)=>{try{return W(J,Y)}catch($){return Y.error({code:"predicate",predicate:W,actual:`aborted due to error:
|
|
25
25
|
${$}
|
|
26
|
-
`})}}),this);return this.$.finalize(_)}pipe=Object.assign(this._pipe.bind(this),{try:this.tryPipe.bind(this)});to(T){return this.$.finalize(this.toNode(this.$.parseDefinition(T)))}toNode(T){let _=
|
|
27
|
-
${T}`,
|
|
26
|
+
`})}}),this);return this.$.finalize(_)}pipe=Object.assign(this._pipe.bind(this),{try:this.tryPipe.bind(this)});to(T){return this.$.finalize(this.toNode(this.$.parseDefinition(T)))}toNode(T){let _=jF(this,T,this.$);if(_ instanceof N)return _.throw();return _}rawPipeOnce(T){if(P(T,"root"))return this.toNode(T);return this.distribute((_)=>_.hasKind("morph")?this.$.node("morph",{in:_.inner.in,morphs:[..._.morphs,T]}):this.$.node("morph",{in:_,morphs:[T]}),this.$.parseSchema)}narrow(T){return this.constrainOut("predicate",T)}constrain(T,_){return this._constrain("root",T,_)}constrainIn(T,_){return this._constrain("in",T,_)}constrainOut(T,_){return this._constrain("out",T,_)}_constrain(T,_,F){let W=this.$.node(_,F);if(W.isRoot())return W.isUnknown()?this:e(`Unexpected constraint node ${W}`);let J=T==="root"?this:this[T];if(J.hasKind("morph")||W.impliedBasis&&!J.extends(W.impliedBasis))return NJ(_,W.impliedBasis,this);let Y=this.$.node("intersection",{[W.kind]:W}),$=T==="out"?jF(this,Y,this.$):J_(this,Y,this.$);if($ instanceof N)$.throw();return this.$.finalize($)}onUndeclaredKey(T){let _=typeof T==="string"?T:T.rule,F=typeof T==="string"?!1:T.deep;return this.$.finalize(this.transform((W,J)=>W==="structure"?_==="ignore"?d8(J,{undeclared:1}):{...J,undeclared:_}:J,F?void 0:{shouldTransform:(W)=>!c_(o0,W.kind)}))}hasEqualMorphs(T){if(!this.includesTransform&&!T.includesTransform)return!0;if(!l_(this.shallowMorphs,T.shallowMorphs))return!1;if(!l_(this.flatMorphs,T.flatMorphs,{isEqual:(_,F)=>_.propString===F.propString&&(_.node.hasKind("morph")&&F.node.hasKind("morph")?_.node.hasEqualMorphs(F.node):_.node.hasKind("intersection")&&F.node.hasKind("intersection")?_.node.structure?.structuralMorphRef===F.node.structure?.structuralMorphRef:!1)}))return!1;return!0}onDeepUndeclaredKey(T){return this.onUndeclaredKey({rule:T,deep:!0})}filter(T){return this.constrainIn("predicate",T)}divisibleBy(T){return this.constrain("divisor",T)}matching(T){return this.constrain("pattern",T)}atLeast(T){return this.constrain("min",T)}atMost(T){return this.constrain("max",T)}moreThan(T){return this.constrain("min",s0(T))}lessThan(T){return this.constrain("max",s0(T))}atLeastLength(T){return this.constrain("minLength",T)}atMostLength(T){return this.constrain("maxLength",T)}moreThanLength(T){return this.constrain("minLength",s0(T))}lessThanLength(T){return this.constrain("maxLength",s0(T))}exactlyLength(T){return this.constrain("exactLength",T)}atOrAfter(T){return this.constrain("after",T)}atOrBefore(T){return this.constrain("before",T)}laterThan(T){return this.constrain("after",s0(T))}earlierThan(T){return this.constrain("before",s0(T))}}var $A="Expected a non-empty brand name after #",s0=(T)=>typeof T==="object"&&!(T instanceof Date)?{...T,exclusive:!0}:{rule:T,exclusive:!0},pF=(T,_)=>P(_,"root")?P(T,"root")?T.extends(_):_.allows(T):P(T,"root")?T.hasUnit(_):_===T,tJ=(T)=>{if(T.hasKind("morph"))return null;if(T.hasKind("intersection"))return T.inner.structure??(T.basis?.domain==="object"?T.$.bindReference(z.intrinsic.emptyStructure):null);if(T.isBasis()&&T.domain==="object")return T.$.bindReference(z.intrinsic.emptyStructure);return null},ZA=(T)=>`Props cannot be extracted from a union. Use .distribute to extract props from each branch instead. Received:
|
|
27
|
+
${T}`,iJ=(T,_)=>`${T} operand must be an object (was ${_})`;var g_=(T,_)=>c(jW(T),(F,W)=>[W,_]);var XA=(T)=>typeof T==="string"?{reference:T}:T,nJ=(T)=>T instanceof N?z.intrinsic.never.internal:T,GA=l({kind:"alias",hasAssociatedError:!1,collapsibleKey:"reference",keys:{reference:{serialize:(T)=>T.startsWith("$")?T:`$ark.${T}`},resolve:{}},normalize:XA,defaults:{description:(T)=>T.reference},intersections:{alias:(T,_,F)=>F.$.lazilyResolve(()=>nJ(UT(T.resolution,_.resolution,F)),`${T.reference}${F.pipe?"=>":"&"}${_.reference}`),...g_("alias",(T,_,F)=>{if(_.isUnknown())return T;if(_.isNever())return _;if(_.isBasis()&&!_.overlaps(z.intrinsic.object))return N.init("assignability",z.intrinsic.object,_);return F.$.lazilyResolve(()=>nJ(UT(T.resolution,_,F)),`${T.reference}${F.pipe?"=>":"&"}${_.id}`)})}});class rJ extends V_{expression=this.reference;structure=void 0;get resolution(){let T=this._resolve();return iT[this.id]=T}_resolve(){if(this.resolve)return this.resolve();if(this.reference[0]==="$")return this.$.resolveRoot(this.reference.slice(1));let T=this.reference,_=iT[T],F=[];while(P(_,"context")){if(F.includes(_.id))return E(AA(_.id,F));F.push(_.id),_=iT[_.id]}if(!P(_,"root"))return e(`Unexpected resolution for reference ${this.reference}
|
|
28
28
|
Seen: [${F.join("->")}]
|
|
29
|
-
Resolution: ${d(_)}`);return _}get resolutionId(){if(this.reference.includes("&")||this.reference.includes("=>"))return this.resolution.id;if(this.reference[0]!=="$")return this.reference;let T=this.reference.slice(1),_=this.$.resolutions[T];if(typeof _==="string")return _;if(
|
|
29
|
+
Resolution: ${d(_)}`);return _}get resolutionId(){if(this.reference.includes("&")||this.reference.includes("=>"))return this.resolution.id;if(this.reference[0]!=="$")return this.reference;let T=this.reference.slice(1),_=this.$.resolutions[T];if(typeof _==="string")return _;if(P(_,"root"))return _.id;return e(`Unexpected resolution for reference ${this.reference}: ${d(_)}`)}get defaultShortDescription(){return __.object}innerToJsonSchema(T){return this.resolution.toJsonSchemaRecurse(T)}traverseAllows=(T,_)=>{let F=_.seen[this.reference];if(F?.includes(T))return!0;return _.seen[this.reference]=s(F,T),this.resolution.traverseAllows(T,_)};traverseApply=(T,_)=>{let F=_.seen[this.reference];if(F?.includes(T))return;_.seen[this.reference]=s(F,T),this.resolution.traverseApply(T,_)};compile(T){let _=this.resolutionId;T.if(`ctx.seen.${_} && ctx.seen.${_}.includes(data)`,()=>T.return(!0)),T.if(`!ctx.seen.${_}`,()=>T.line(`ctx.seen.${_} = []`)),T.line(`ctx.seen.${_}.push(data)`),T.return(T.invoke(_))}}var AA=(T,_)=>`Alias '${T}' has a shallow resolution cycle: ${[..._,T].join("->")}`,gF={implementation:GA,Node:rJ};class B0 extends V_{traverseApply=(T,_)=>{if(!this.traverseAllows(T,_))_.errorFromNodeContext(this.errorContext)};get errorContext(){return{code:this.kind,description:this.description,meta:this.meta,...this.inner}}get compiledErrorContext(){return X0(this.errorContext)}compile(T){if(T.traversalKind==="Allows")T.return(this.compiledCondition);else T.if(this.compiledNegation,()=>T.line(`${T.ctx}.errorFromNodeContext(${this.compiledErrorContext})`))}}var HA=l({kind:"domain",hasAssociatedError:!0,collapsibleKey:"domain",keys:{domain:{},numberAllowsNaN:{}},normalize:(T)=>typeof T==="string"?{domain:T}:g0(T,"numberAllowsNaN")&&T.domain!=="number"?E(gW.writeBadAllowNanMessage(T.domain)):T,applyConfig:(T,_)=>T.numberAllowsNaN===void 0&&T.domain==="number"&&_.numberAllowsNaN?{...T,numberAllowsNaN:!0}:T,defaults:{description:(T)=>__[T.domain],actual:(T)=>Number.isNaN(T)?"NaN":__[PT(T)]},intersections:{domain:(T,_)=>T.domain==="number"&&_.domain==="number"?T.numberAllowsNaN?_:T:N.init("domain",T,_)}});class sJ extends B0{requiresNaNCheck=this.domain==="number"&&!this.numberAllowsNaN;traverseAllows=this.requiresNaNCheck?(T)=>typeof T==="number"&&!Number.isNaN(T):(T)=>PT(T)===this.domain;compiledCondition=this.domain==="object"?'((typeof data === "object" && data !== null) || typeof data === "function")':`typeof data === "${this.domain}"${this.requiresNaNCheck?" && !Number.isNaN(data)":""}`;compiledNegation=this.domain==="object"?'((typeof data !== "object" || data === null) && typeof data !== "function")':`typeof data !== "${this.domain}"${this.requiresNaNCheck?" || Number.isNaN(data)":""}`;expression=this.numberAllowsNaN?"number | NaN":this.domain;get nestableExpression(){return this.numberAllowsNaN?`(${this.expression})`:this.expression}get defaultShortDescription(){return __[this.domain]}innerToJsonSchema(T){if(this.domain==="bigint"||this.domain==="symbol")return T.fallback.domain({code:"domain",base:{},domain:this.domain});return{type:this.domain}}}var gW={implementation:HA,Node:sJ,writeBadAllowNanMessage:(T)=>`numberAllowsNaN may only be specified with domain "number" (was ${T})`};var OA=l({kind:"intersection",hasAssociatedError:!0,normalize:(T)=>{if(OT(T))return T;let{structure:_,...F}=T,W=!!_,J=_??{},Y=c(F,($,Z)=>{if(qT($,EJ)){if(W)E(`Flattened structure key ${$} cannot be specified alongside a root 'structure' key.`);return J[$]=Z,[]}return[$,Z]});if(P(J,"constraint")||!p_(J))Y.structure=J;return Y},finalizeInnerJson:({structure:T,..._})=>T_(T,"object")?{...T,..._}:_,keys:{domain:{child:!0,parse:(T,_)=>_.$.node("domain",T)},proto:{child:!0,parse:(T,_)=>_.$.node("proto",T)},structure:{child:!0,parse:(T,_)=>_.$.node("structure",T),serialize:(T)=>{if(!T.sequence?.minLength)return T.collapsibleJson;let{sequence:_,...F}=T.collapsibleJson,{minVariadicLength:W,...J}=_,Y=J.variadic&&Object.keys(J).length===1?J.variadic:J;return{...F,sequence:Y}}},divisor:{child:!0,parse:cT("divisor")},max:{child:!0,parse:cT("max")},min:{child:!0,parse:cT("min")},maxLength:{child:!0,parse:cT("maxLength")},minLength:{child:!0,parse:cT("minLength")},exactLength:{child:!0,parse:cT("exactLength")},before:{child:!0,parse:cT("before")},after:{child:!0,parse:cT("after")},pattern:{child:!0,parse:cT("pattern")},predicate:{child:!0,parse:cT("predicate")}},reduce:(T,_)=>aJ({},T,{$:_,invert:!1,pipe:!1}),defaults:{description:(T)=>{if(T.children.length===0)return"unknown";if(T.structure)return T.structure.description;let _=[];if(T.basis&&!T.refinements.some((F)=>F.impl.obviatesBasisDescription))_.push(T.basis.description);if(T.refinements.length){let F=T.refinements.toSorted((W,J)=>W.kind==="min"&&J.kind==="max"?-1:0).map((W)=>W.description);_.push(...F)}if(T.inner.predicate)_.push(...T.inner.predicate.map((F)=>F.description));return _.join(" and ")},expected:(T)=>` \u25E6 ${T.errors.map((_)=>_.expected).join(`
|
|
30
30
|
\u25E6 `)}`,problem:(T)=>`(${T.actual}) must be...
|
|
31
|
-
${T.expected}`},intersections:{intersection:(T,_,F)=>
|
|
31
|
+
${T.expected}`},intersections:{intersection:(T,_,F)=>aJ(T.inner,_.inner,F),...g_("intersection",(T,_,F)=>{if(T.children.length===0)return _;let{domain:W,proto:J,...Y}=T.inner,$=J??W,Z=$?UT($,_,F):_;return Z instanceof N?Z:T?.basis?.equals(Z)?T:T.$.node("intersection",{...Y,[Z.kind]:Z},{prereduced:!0})})}});class eJ extends V_{basis=this.inner.domain??this.inner.proto??null;refinements=this.children.filter((T)=>T.isRefinement());structure=this.inner.structure;expression=UA(this);get shallowMorphs(){return this.inner.structure?.structuralMorph?[this.inner.structure.structuralMorph]:[]}get defaultShortDescription(){return this.basis?.defaultShortDescription??"present"}innerToJsonSchema(T){return this.children.reduce((_,F)=>F.isBasis()?F.toJsonSchemaRecurse(T):F.reduceJsonSchema(_,T),{})}traverseAllows=(T,_)=>this.children.every((F)=>F.traverseAllows(T,_));traverseApply=(T,_)=>{let F=_.currentErrorCount;if(this.basis){if(this.basis.traverseApply(T,_),_.currentErrorCount>F)return}if(this.refinements.length){for(let W=0;W<this.refinements.length-1;W++)if(this.refinements[W].traverseApply(T,_),_.failFast&&_.currentErrorCount>F)return;if(this.refinements.at(-1).traverseApply(T,_),_.currentErrorCount>F)return}if(this.structure){if(this.structure.traverseApply(T,_),_.currentErrorCount>F)return}if(this.inner.predicate){for(let W=0;W<this.inner.predicate.length-1;W++)if(this.inner.predicate[W].traverseApply(T,_),_.failFast&&_.currentErrorCount>F)return;this.inner.predicate.at(-1).traverseApply(T,_)}};compile(T){if(T.traversalKind==="Allows"){for(let _ of this.children)T.check(_);T.return(!0);return}if(T.initializeErrorCount(),this.basis){if(T.check(this.basis),this.children.length>1)T.returnIfFail()}if(this.refinements.length){for(let _=0;_<this.refinements.length-1;_++)T.check(this.refinements[_]),T.returnIfFailFast();if(T.check(this.refinements.at(-1)),this.structure||this.inner.predicate)T.returnIfFail()}if(this.structure){if(T.check(this.structure),this.inner.predicate)T.returnIfFail()}if(this.inner.predicate){for(let _=0;_<this.inner.predicate.length-1;_++)T.check(this.inner.predicate[_]),T.returnIfFail();T.check(this.inner.predicate.at(-1))}}}var P2={implementation:OA,Node:eJ},UA=(T)=>{let _=T.structure?.expression||`${T.basis&&!T.refinements.some((F)=>F.impl.obviatesBasisExpression)?T.basis.nestableExpression+" ":""}${T.refinements.map((F)=>F.expression).join(" & ")}`||"unknown";if(_==="Array == 0")_="[]";return _},aJ=(T,_,F)=>{let W={},J=T.proto??T.domain,Y=_.proto??_.domain,$=J?Y?UT(J,Y,F):J:Y;if($ instanceof N)return $;if($)W[$.kind]=$;return t0({kind:"intersection",baseInner:W,l:i0(T),r:i0(_),roots:[],ctx:F})};var MA=l({kind:"morph",hasAssociatedError:!1,keys:{in:{child:!0,parse:(T,_)=>_.$.parseSchema(T)},morphs:{parse:J0,serialize:(T)=>T.map((_)=>P(_,"root")?_.json:KT(_))},declaredIn:{child:!1,serialize:(T)=>T.json},declaredOut:{child:!1,serialize:(T)=>T.json}},normalize:(T)=>T,defaults:{description:(T)=>`a morph from ${T.in.description} to ${T.out?.description??"unknown"}`},intersections:{morph:(T,_,F)=>{if(!T.hasEqualMorphs(_))return E(wA(T.expression,_.expression));let W=UT(T.in,_.in,F);if(W instanceof N)return W;let J={morphs:T.morphs};if(T.declaredIn||_.declaredIn){let Y=UT(T.in,_.in,F);if(Y instanceof N)return Y.throw();else J.declaredIn=Y}if(T.declaredOut||_.declaredOut){let Y=UT(T.out,_.out,F);if(Y instanceof N)return Y.throw();else J.declaredOut=Y}return W.distribute((Y)=>F.$.node("morph",{...J,in:Y}),F.$.parseSchema)},...g_("morph",(T,_,F)=>{let W=T.inner.in?UT(T.inner.in,_,F):_;return W instanceof N?W:W.equals(T.inner.in)?T:F.$.node("morph",{...T.inner,in:W})})}});class T6 extends V_{serializedMorphs=this.morphs.map(KT);compiledMorphs=`[${this.serializedMorphs}]`;lastMorph=this.inner.morphs.at(-1);lastMorphIfNode=P(this.lastMorph,"root")?this.lastMorph:void 0;introspectableIn=this.inner.in;introspectableOut=this.lastMorphIfNode?Object.assign(this.referencesById,this.lastMorphIfNode.referencesById)&&this.lastMorphIfNode.out:void 0;get shallowMorphs(){return Array.isArray(this.inner.in?.shallowMorphs)?[...this.inner.in.shallowMorphs,...this.morphs]:this.morphs}get in(){return this.declaredIn??this.inner.in?.in??z.intrinsic.unknown.internal}get out(){return this.declaredOut??this.introspectableOut??z.intrinsic.unknown.internal}declareIn(T){return this.$.node("morph",{...this.inner,declaredIn:T})}declareOut(T){return this.$.node("morph",{...this.inner,declaredOut:T})}expression=`(In: ${this.in.expression}) => ${this.lastMorphIfNode?"To":"Out"}<${this.out.expression}>`;get defaultShortDescription(){return this.in.meta.description??this.in.defaultShortDescription}innerToJsonSchema(T){return T.fallback.morph({code:"morph",base:this.in.toJsonSchemaRecurse(T),out:this.introspectableOut?.toJsonSchemaRecurse(T)??null})}compile(T){if(T.traversalKind==="Allows"){if(!this.introspectableIn)return;T.return(T.invoke(this.introspectableIn));return}if(this.introspectableIn)T.line(T.invoke(this.introspectableIn));T.line(`ctx.queueMorphs(${this.compiledMorphs})`)}traverseAllows=(T,_)=>!this.introspectableIn||this.introspectableIn.traverseAllows(T,_);traverseApply=(T,_)=>{if(this.introspectableIn)this.introspectableIn.traverseApply(T,_);_.queueMorphs(this.morphs)};hasEqualMorphs(T){return l_(this.morphs,T.morphs,{isEqual:(_,F)=>_===F||P(_,"root")&&P(F,"root")&&_.equals(F)})}}var q2={implementation:MA,Node:T6},wA=(T,_)=>`The intersection of distinct morphs at a single path is indeterminate:
|
|
32
32
|
Left: ${T}
|
|
33
|
-
Right: ${_}`;var
|
|
33
|
+
Right: ${_}`;var QA=l({kind:"proto",hasAssociatedError:!0,collapsibleKey:"proto",keys:{proto:{serialize:(T)=>LF(T)??E_(T)},dateAllowsInvalid:{}},normalize:(T)=>{let _=typeof T==="string"?{proto:I0[T]}:typeof T==="function"?OT(T)?T:{proto:T}:typeof T.proto==="string"?{...T,proto:I0[T.proto]}:T;if(typeof _.proto!=="function")E(mF.writeInvalidSchemaMessage(_.proto));if(g0(_,"dateAllowsInvalid")&&_.proto!==Date)E(mF.writeBadInvalidDateMessage(_.proto));return _},applyConfig:(T,_)=>{if(T.dateAllowsInvalid===void 0&&T.proto===Date&&_.dateAllowsInvalid)return{...T,dateAllowsInvalid:!0};return T},defaults:{description:(T)=>T.builtinName?n8[T.builtinName]:`an instance of ${T.proto.name}`,actual:(T)=>T instanceof Date&&T.toString()==="Invalid Date"?"an invalid Date":KF(T)},intersections:{proto:(T,_)=>T.proto===Date&&_.proto===Date?T.dateAllowsInvalid?_:T:_2(T.proto,_.proto)?T:_2(_.proto,T.proto)?_:N.init("proto",T,_),domain:(T,_)=>_.domain==="object"?T:N.init("domain",z.intrinsic.object.internal,_)}});class _6 extends B0{builtinName=LF(this.proto);serializedConstructor=this.json.proto;requiresInvalidDateCheck=this.proto===Date&&!this.dateAllowsInvalid;traverseAllows=this.requiresInvalidDateCheck?(T)=>T instanceof Date&&T.toString()!=="Invalid Date":(T)=>T instanceof this.proto;compiledCondition=`data instanceof ${this.serializedConstructor}${this.requiresInvalidDateCheck?' && data.toString() !== "Invalid Date"':""}`;compiledNegation=`!(${this.compiledCondition})`;innerToJsonSchema(T){switch(this.builtinName){case"Array":return{type:"array"};case"Date":return T.fallback.date?.({code:"date",base:{}})??T.fallback.proto({code:"proto",base:{},proto:this.proto});default:return T.fallback.proto({code:"proto",base:{},proto:this.proto})}}expression=this.dateAllowsInvalid?"Date | InvalidDate":this.proto.name;get nestableExpression(){return this.dateAllowsInvalid?`(${this.expression})`:this.expression}domain="object";get defaultShortDescription(){return this.description}}var mF={implementation:QA,Node:_6,writeBadInvalidDateMessage:(T)=>`dateAllowsInvalid may only be specified with constructor Date (was ${T.name})`,writeInvalidSchemaMessage:(T)=>`instanceOf operand must be a function (was ${PT(T)})`};var RA=l({kind:"union",hasAssociatedError:!0,collapsibleKey:"branches",keys:{ordered:{},branches:{child:!0,parse:(T,_)=>{let F=[];for(let W of T){let J=P(W,"root")?W.branches:_.$.parseSchema(W).branches;for(let Y of J)if(Y.hasKind("morph")){let $=F.findIndex((Z)=>Z.hasKind("morph")&&Z.hasEqualMorphs(Y));if($===-1)F.push(Y);else{let Z=F[$];F[$]=_.$.node("morph",{...Z.inner,in:Z.in.rawOr(Y.in)})}}else F.push(Y)}if(!_.def.ordered)F.sort((W,J)=>W.hash<J.hash?-1:1);return F}}},normalize:(T)=>XT(T)?{branches:T}:T,reduce:(T,_)=>{let F=CA(T);if(F.length===1)return F[0];if(F.length===T.branches.length)return;return _.node("union",{...T,branches:F},{prereduced:!0})},defaults:{description:(T)=>T.distribute((_)=>_.description,a0),expected:(T)=>{let _=m8(T.errors,"propString"),F=Object.entries(_).map(([W,J])=>{let Y=[];for(let G of J)h_(Y,G.expected);let $=a0(Y),Z=J.every((G)=>G.actual===J[0].actual)?J[0].actual:d(J[0].data);return`${W&&`${W} `}must be ${$}${Z&&` (was ${Z})`}`});return a0(F)},problem:(T)=>T.expected,message:(T)=>T.problem},intersections:{union:(T,_,F)=>{if(T.isNever!==_.isNever)return N.init("presence",T,_);let W;if(T.ordered){if(_.ordered)E(kA(T.expression,_.expression));if(W=j2(_.branches,T.branches,F),W instanceof N)W.invert()}else W=j2(T.branches,_.branches,F);if(W instanceof N)return W;return F.$.parseSchema(T.ordered||_.ordered?{branches:W,ordered:!0}:{branches:W})},...g_("union",(T,_,F)=>{let W=j2(T.branches,[_],F);if(W instanceof N)return W;if(W.length===1)return W[0];return F.$.parseSchema(T.ordered?{branches:W,ordered:!0}:{branches:W})})}});class J6 extends V_{isBoolean=this.branches.length===2&&this.branches[0].hasUnit(!1)&&this.branches[1].hasUnit(!0);get branchGroups(){let T=[],_=-1;for(let F of this.branches){if(F.hasKind("unit")&&F.domain==="boolean"){if(_===-1)_=T.length,T.push(F);else T[_]=z.intrinsic.boolean;continue}T.push(F)}return T}unitBranches=this.branches.filter((T)=>T.in.hasKind("unit"));discriminant=this.discriminate();discriminantJson=this.discriminant?SA(this.discriminant):null;expression=this.distribute((T)=>T.nestableExpression,NA);createBranchedOptimisticRootApply(){return(T,_)=>{let F=this.traverseOptimistic(T);if(F!==O_)return F;let W=new f_(T,this.$.resolvedConfig);return this.traverseApply(T,W),W.finalize(_)}}get shallowMorphs(){return this.branches.reduce((T,_)=>h_(T,_.shallowMorphs),[])}get defaultShortDescription(){return this.distribute((T)=>T.defaultShortDescription,a0)}innerToJsonSchema(T){if(this.branchGroups.length===1&&this.branchGroups[0].equals(z.intrinsic.boolean))return{type:"boolean"};let _=this.branchGroups.map((F)=>F.toJsonSchemaRecurse(T));if(_.every((F)=>Object.keys(F).length===1&&g0(F,"const")))return{enum:_.map((F)=>F.const)};return{anyOf:_}}traverseAllows=(T,_)=>this.branches.some((F)=>F.traverseAllows(T,_));traverseApply=(T,_)=>{let F=[];for(let W=0;W<this.branches.length;W++){if(_.pushBranch(),this.branches[W].traverseApply(T,_),!_.hasError()){if(this.branches[W].includesTransform)return _.queuedMorphs.push(..._.popBranch().queuedMorphs);return _.popBranch()}F.push(_.popBranch().error)}_.errorFromNodeContext({code:"union",errors:F,meta:this.meta})};traverseOptimistic=(T)=>{for(let _=0;_<this.branches.length;_++){let F=this.branches[_];if(F.traverseAllows(T)){if(F.contextFreeMorph)return F.contextFreeMorph(T);return T}}return O_};compile(T){if(!this.discriminant||this.unitBranches.length===this.branches.length&&this.branches.length===2)return this.compileIndiscriminable(T);let _=this.discriminant.optionallyChainedPropString;if(this.discriminant.kind==="domain")_=`typeof ${_} === "object" ? ${_} === null ? "null" : "object" : typeof ${_} === "function" ? "object" : typeof ${_}`;let F=this.discriminant.cases,W=Object.keys(F),{optimistic:J}=T;if(T.optimistic=!1,T.block(`switch(${_})`,()=>{for(let X in F){let O=F[X],M=X==="default"?X:`case ${X}`;T.line(`${M}: return ${O===!0?J?T.data:O:J?`${T.invoke(O)} ? ${O.contextFreeMorph?`${KT(O.contextFreeMorph)}(${T.data})`:T.data} : "${O_}"`:T.invoke(O)}`)}return T}),T.traversalKind==="Allows"){T.return(J?`"${O_}"`:!1);return}let Y=a0(this.discriminant.kind==="domain"?W.map((X)=>{let O=X.slice(1,-1);return O==="function"?__.object:__[O]}):W),$=this.discriminant.path.map((X)=>typeof X==="symbol"?KT(X):JSON.stringify(X)),Z=JSON.stringify(Y),G=this.discriminant.kind==="domain"?`${LA}[${_}]`:`${DA}(${_})`;T.line(`ctx.errorFromNodeContext({
|
|
34
34
|
code: "predicate",
|
|
35
35
|
expected: ${Z},
|
|
36
36
|
actual: ${G},
|
|
37
37
|
relativePath: [${$}],
|
|
38
38
|
meta: ${this.compiledMeta}
|
|
39
|
-
})`)}compileIndiscriminable(T){if(T.traversalKind==="Apply"){T.const("errors","[]");for(let _ of this.branches)T.line("ctx.pushBranch()").line(T.invoke(_)).if("!ctx.hasError()",()=>T.return(_.includesTransform?"ctx.queuedMorphs.push(...ctx.popBranch().queuedMorphs)":"ctx.popBranch()")).line("errors.push(ctx.popBranch().error)");T.line(`ctx.errorFromNodeContext({ code: "union", errors, meta: ${this.compiledMeta} })`)}else{let{optimistic:_}=T;T.optimistic=!1;for(let F of this.branches)T.if(`${T.invoke(F)}`,()=>T.return(_?F.contextFreeMorph?`${
|
|
39
|
+
})`)}compileIndiscriminable(T){if(T.traversalKind==="Apply"){T.const("errors","[]");for(let _ of this.branches)T.line("ctx.pushBranch()").line(T.invoke(_)).if("!ctx.hasError()",()=>T.return(_.includesTransform?"ctx.queuedMorphs.push(...ctx.popBranch().queuedMorphs)":"ctx.popBranch()")).line("errors.push(ctx.popBranch().error)");T.line(`ctx.errorFromNodeContext({ code: "union", errors, meta: ${this.compiledMeta} })`)}else{let{optimistic:_}=T;T.optimistic=!1;for(let F of this.branches)T.if(`${T.invoke(F)}`,()=>T.return(_?F.contextFreeMorph?`${KT(F.contextFreeMorph)}(${T.data})`:T.data:!0));T.return(_?`"${O_}"`:!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 J=c(this.unitBranches,(Y,$)=>[`${$.in.serializedValue}`,$.hasKind("morph")?$:!0]);return{kind:"unit",path:[],optionallyChainedPropString:"data",cases:J}}let T=[];for(let J=0;J<this.branches.length-1;J++){let Y=this.branches[J];for(let $=J+1;$<this.branches.length;$++){let Z=this.branches[$],G=J_(Y.in,Z.in,Y.$);if(!(G instanceof N))continue;for(let X of G){if(!X.kind||X.optional)continue;let O,M;if(X.kind==="domain"){let{l:K,r:B}=X;O=`"${typeof K==="string"?K:K.domain}"`,M=`"${typeof B==="string"?B:B.domain}"`}else if(X.kind==="unit")O=X.l.serializedValue,M=X.r.serializedValue;else continue;let Q=T.find((K)=>l_(K.path,X.path)&&K.kind===X.kind);if(!Q)T.push({kind:X.kind,cases:{[O]:{branchIndices:[J],condition:X.l},[M]:{branchIndices:[$],condition:X.r}},path:X.path});else{if(Q.cases[O])Q.cases[O].branchIndices=h_(Q.cases[O].branchIndices,J);else Q.cases[O]??={branchIndices:[J],condition:X.l};if(Q.cases[M])Q.cases[M].branchIndices=h_(Q.cases[M].branchIndices,$);else Q.cases[M]??={branchIndices:[$],condition:X.r}}}}}let _=this.ordered?VA(T,this.branches):T;if(!_.length)return null;let F=EA(_,this),W={};for(let J in F.best.cases){let Y=zA(F,J);if(Y===null){W[J]=!0;continue}if(Y.length===this.branches.length)return null;if(this.ordered)Y.sort((G,X)=>G.originalIndex-X.originalIndex);let $=Y.map((G)=>G.branch),Z=$.length===1?$[0]:this.$.node("union",this.ordered?{branches:$,ordered:!0}:$);Object.assign(this.referencesById,Z.referencesById),W[J]=Z}if(F.defaultEntries.length){let J=F.defaultEntries.map((Y)=>Y.branch);W.default=this.$.node("union",this.ordered?{branches:J,ordered:!0}:J,{prereduced:!0}),Object.assign(this.referencesById,W.default.referencesById)}return Object.assign(F.location,{cases:W})}}var EA=(T,_)=>{let F=T.sort((Y,$)=>Object.keys($.cases).length-Object.keys(Y.cases).length)[0],W={kind:F.kind,path:F.path,optionallyChainedPropString:Y6(F.path)},J=_.branches.map((Y,$)=>({originalIndex:$,branch:Y}));return{best:F,location:W,defaultEntries:J,node:_}},zA=(T,_)=>{let F=T.best.cases[_],W=KA(F.condition,T.location.path,T.node.$),J=[],Y=[];for(let $=0;$<T.defaultEntries.length;$++){let Z=T.defaultEntries[$];if(F.branchIndices.includes(Z.originalIndex)){let G=F6(T.node.branches[Z.originalIndex],T.location);if(G===null)J=null;else J?.push({originalIndex:Z.originalIndex,branch:G})}else if(Z.branch.hasKind("alias")&&W.hasKind("domain")&&W.domain==="object")J?.push(Z);else{if(Z.branch.in.overlaps(W)){let G=F6(Z.branch,T.location);J?.push({originalIndex:Z.originalIndex,branch:G})}Y.push(Z)}}return T.defaultEntries=Y,J},VA=(T,_)=>{return T.filter((W)=>{let J=Object.values(W.cases).map((Y)=>Y.branchIndices);for(let Y=0;Y<J.length-1;Y++){let $=J[Y];for(let Z=Y+1;Z<J.length;Z++){let G=J[Z];for(let X of $)for(let O of G)if(X>O){if(_[X].overlaps(_[O]))return!1}}}return!0})},KA=(T,_,F)=>{let W=T==="undefined"?F.node("unit",{unit:void 0}):T==="null"?F.node("unit",{unit:null}):T==="boolean"?F.units([!0,!1]):T;for(let J=_.length-1;J>=0;J--){let Y=_[J];W=F.node("intersection",typeof Y==="number"?{proto:"Array",sequence:[...p8(Y).map(($)=>({})),W]}:{domain:"object",required:[{key:Y,value:W}]})}return W},Y6=(T)=>T.reduce((_,F)=>_+X2(F,!0),"data"),LA=KT(o8),DA=KT(d),y2={implementation:RA,Node:J6},SA=(T)=>({kind:T.kind,path:T.path.map((_)=>typeof _==="string"?_:n_(_)),cases:c(T.cases,(_,F)=>[_,F===!0?F:F.hasKind("union")&&F.discriminantJson?F.discriminantJson:F.json])}),IA={delimiter:" | ",finalDelimiter:" | "},NA=(T)=>a0(T,IA),a0=(T,_)=>{let F=_?.delimiter??", ",W=_?.finalDelimiter??" or ";if(T.length===0)return"never";if(T.length===1)return T[0];if(T.length===2&&T[0]==="false"&&T[1]==="true"||T[0]==="true"&&T[1]==="false")return"boolean";let J={},Y=T.filter((Z)=>J[Z]?!1:J[Z]=!0),$=Y.pop();return`${Y.join(F)}${Y.length?W:""}${$}`},j2=(T,_,F)=>{let W=_.map(()=>[]);for(let Y=0;Y<T.length;Y++){let $={};for(let Z=0;Z<_.length;Z++){if(W[Z]===null)continue;if(T[Y].equals(_[Z])){W[Z]=null,$={};break}let G=UT(T[Y],_[Z],F);if(G instanceof N)continue;if(G.equals(T[Y])){W[Z].push(T[Y]),$={};break}if(G.equals(_[Z]))W[Z]=null;else $[Z]=G}for(let Z in $)W[Z][Y]=$[Z]}let J=W.flatMap((Y,$)=>Y?.flatMap((Z)=>Z.branches)??_[$]);return J.length===0?N.init("union",T,_):J},CA=({branches:T,ordered:_})=>{if(T.length<2)return T;let F=T.map(()=>!0);for(let W=0;W<T.length;W++)for(let J=W+1;J<T.length&&F[W]&&F[J];J++){if(T[W].equals(T[J])){F[J]=!1;continue}let Y=J_(T[W].in,T[J].in,T[0].$);if(Y instanceof N)continue;if(!_)BA(T[W],T[J]);if(Y.equals(T[W].in))F[W]=!!_;else if(Y.equals(T[J].in))F[J]=!1}return T.filter((W,J)=>F[J])},BA=(T,_)=>{if(!T.includesTransform&&!_.includesTransform)return;if(!l_(T.shallowMorphs,_.shallowMorphs))E(W6(T.expression,_.expression));if(!l_(T.flatMorphs,_.flatMorphs,{isEqual:(F,W)=>F.propString===W.propString&&(F.node.hasKind("morph")&&W.node.hasKind("morph")?F.node.hasEqualMorphs(W.node):F.node.hasKind("intersection")&&W.node.hasKind("intersection")?F.node.structure?.structuralMorphRef===W.node.structure?.structuralMorphRef:!1)}))E(W6(T.expression,_.expression))},F6=(T,_)=>T.transform((F,W)=>{if(F==="domain"||F==="unit")return null;return W},{shouldTransform:(F,W)=>{let J=Y6(W.path);if(!_.optionallyChainedPropString.startsWith(J))return!1;if(F.hasKind("domain")&&F.domain==="object")return!0;if((F.hasKind("domain")||_.kind==="unit")&&J===_.optionallyChainedPropString)return!0;return F.children.length!==0&&F.kind!=="index"}}),W6=(T,_)=>`An unordered union of a type including a morph and a type with overlapping input is indeterminate:
|
|
40
40
|
Left: ${T}
|
|
41
|
-
Right: ${_}`,
|
|
41
|
+
Right: ${_}`,kA=(T,_)=>`The intersection of two ordered unions is indeterminate:
|
|
42
42
|
Left: ${T}
|
|
43
|
-
Right: ${_}`;var IH=l({kind:"unit",hasAssociatedError:!0,keys:{unit:{preserveUndefined:!0,serialize:(T)=>T instanceof Date?T.toISOString():E_(T)}},normalize:(T)=>T,defaults:{description:(T)=>d(T.unit),problem:({expected:T,actual:_})=>`${T===_?`must be reference equal to ${T} (serialized to the same value)`:`must be ${T} (was ${_})`}`},intersections:{unit:(T,_)=>I.init("unit",T,_),...p_("unit",(T,_)=>{if(_.allows(T.unit))return T;let F=_.hasKind("intersection")?_.basis:_;if(F){let W=F.hasKind("domain")?F:R.intrinsic.object;if(T.domain!==W.domain){let J=T.domain==="undefined"||T.domain==="null"||T.domain==="boolean"?T.domain:R.intrinsic[T.domain];return I.init("domain",J,W)}}return I.init("assignability",T,_.hasKind("intersection")?_.children.find((W)=>!W.allows(T.unit)):_)})}});class W6 extends N0{compiledValue=this.json.unit;serializedValue=typeof this.unit==="string"||this.unit instanceof Date?JSON.stringify(this.compiledValue):`${this.compiledValue}`;compiledCondition=F6(this.unit,this.serializedValue);compiledNegation=F6(this.unit,this.serializedValue,"negated");expression=d(this.unit);domain=fT(this.unit);get defaultShortDescription(){return this.domain==="object"?__.object:this.description}innerToJsonSchema(T){return this.unit===null?{type:"null"}:R.intrinsic.jsonPrimitive.allows(this.unit)?{const:this.unit}:T.fallback.unit({code:"unit",base:{},unit:this.unit})}traverseAllows=this.unit instanceof Date?(T)=>T instanceof Date&&T.toISOString()===this.compiledValue:Number.isNaN(this.unit)?(T)=>Number.isNaN(T):(T)=>T===this.unit}var P2={implementation:IH,Node:W6},F6=(T,_,F)=>{if(T instanceof Date){let W=`data instanceof Date && data.toISOString() === ${_}`;return F?`!(${W})`:W}if(Number.isNaN(T))return`${F?"!":""}Number.isNaN(data)`;return`data ${F?"!":"="}== ${_}`};var NH=l({kind:"index",hasAssociatedError:!1,intersectionIsOpen:!0,keys:{signature:{child:!0,parse:(T,_)=>{let F=_.$.parseSchema(T);if(!F.extends(R.intrinsic.key))return z(BH(F.expression));let W=F.branches.filter((J)=>J.hasKind("unit"));if(W.length)return z(CH(W.map((J)=>d(J.unit))));return F}},value:{child:!0,parse:(T,_)=>_.$.parseSchema(T)}},normalize:(T)=>T,defaults:{description:(T)=>`[${T.signature.expression}]: ${T.value.description}`},intersections:{index:(T,_,F)=>{if(T.signature.equals(_.signature)){let W=OT(T.value,_.value,F),J=W instanceof I?R.intrinsic.never.internal:W;return F.$.node("index",{signature:T.signature,value:J})}if(T.signature.extends(_.signature)&&T.value.subsumes(_.value))return _;if(_.signature.extends(T.signature)&&_.value.subsumes(T.value))return T;return null}}});class J6 extends R_{impliedBasis=R.intrinsic.object.internal;expression=`[${this.signature.expression}]: ${this.value.expression}`;flatRefs=s(this.value.flatRefs.map((T)=>q_([this.signature,...T.path],T.node)),q_([this.signature],this.value));traverseAllows=(T,_)=>D0(T).every((F)=>{if(this.signature.traverseAllows(F[0],_))return W_(F[0],()=>this.value.traverseAllows(F[1],_),_);return!0});traverseApply=(T,_)=>{for(let F of D0(T))if(this.signature.traverseAllows(F[0],_))W_(F[0],()=>this.value.traverseApply(F[1],_),_)};_transform(T,_){_.path.push(this.signature);let F=super._transform(T,_);return _.path.pop(),F}compile(){}}var j2={implementation:NH,Node:J6},CH=(T)=>`Index keys ${T.join(", ")} should be specified as named props.`,BH=(T)=>`Indexed key definition '${T}' must be a string or symbol`;var kH=l({kind:"required",hasAssociatedError:!0,intersectionIsOpen:!0,keys:{key:{},value:{child:!0,parse:(T,_)=>_.$.parseSchema(T)}},normalize:(T)=>T,defaults:{description:(T)=>`${T.compiledKey}: ${T.value.description}`,expected:(T)=>T.missingValueDescription,actual:()=>"missing"},intersections:{required:PF,optional:PF}});class Y6 extends jF{expression=`${this.compiledKey}: ${this.value.expression}`;errorContext=Object.freeze({code:"required",missingValueDescription:this.value.defaultShortDescription,relativePath:[this.key],meta:this.meta});compiledErrorContext=$0(this.errorContext)}var y2={implementation:kH,Node:Y6};var fH=l({kind:"sequence",hasAssociatedError:!1,collapsibleKey:"variadic",keys:{prefix:{child:!0,parse:(T,_)=>{if(T.length===0)return;return T.map((F)=>_.$.parseSchema(F))}},optionals:{child:!0,parse:(T,_)=>{if(T.length===0)return;return T.map((F)=>_.$.parseSchema(F))}},defaultables:{child:(T)=>T.map((_)=>_[0]),parse:(T,_)=>{if(T.length===0)return;return T.map((F)=>{let W=_.$.parseSchema(F[0]);return vF(W,F[1],null),[W,F[1]]})},serialize:(T)=>T.map((_)=>[_[0].collapsibleJson,E_(_[1])])},variadic:{child:!0,parse:(T,_)=>_.$.parseSchema(T,_)},minVariadicLength:{parse:(T)=>T===0?void 0:T},postfix:{child:!0,parse:(T,_)=>{if(T.length===0)return;return T.map((F)=>_.$.parseSchema(F))}}},normalize:(T)=>{if(typeof T==="string")return{variadic:T};if("variadic"in T||"prefix"in T||"defaultables"in T||"optionals"in T||"postfix"in T||"minVariadicLength"in T){if(T.postfix?.length){if(!T.variadic)return z(yH);if(T.optionals?.length||T.defaultables?.length)return z(b2)}if(T.minVariadicLength&&!T.variadic)return z("minVariadicLength may not be specified without a variadic element");return T}return{variadic:T}},reduce:(T,_)=>{let F=T.minVariadicLength??0,W=T.prefix?.slice()??[],J=T.defaultables?.slice()??[],Y=T.optionals?.slice()??[],$=T.postfix?.slice()??[];if(T.variadic){while(Y.at(-1)?.equals(T.variadic))Y.pop();if(Y.length===0&&J.length===0)while(W.at(-1)?.equals(T.variadic))W.pop(),F++;while($[0]?.equals(T.variadic))$.shift(),F++}else if(Y.length===0&&J.length===0)W.push(...$.splice(0));if(F!==T.minVariadicLength||T.prefix&&T.prefix.length!==W.length)return _.node("sequence",{...T,prefix:W,defaultables:J,optionals:Y,postfix:$,minVariadicLength:F},{prereduced:!0})},defaults:{description:(T)=>{if(T.isVariadicOnly)return`${T.variadic.nestableExpression}[]`;return`[${T.tuple.map((F)=>F.kind==="defaultables"?`${F.node.nestableExpression} = ${d(F.default)}`:F.kind==="optionals"?`${F.node.nestableExpression}?`:F.kind==="variadic"?`...${F.node.nestableExpression}[]`:F.node.expression).join(", ")}]`}},intersections:{sequence:(T,_,F)=>{let W=pF({l:T.tuple,r:_.tuple,disjoint:new I,result:[],fixedVariants:[],ctx:F}),J=W.disjoint.length===0?[W,...W.fixedVariants]:W.fixedVariants;return J.length===0?W.disjoint:J.length===1?F.$.node("sequence",$6(J[0].result)):F.$.node("union",J.map((Y)=>({proto:Array,sequence:$6(Y.result)})))}}});class Z6 extends R_{impliedBasis=R.intrinsic.Array.internal;tuple=jH(this.inner);prefixLength=this.prefix?.length??0;defaultablesLength=this.defaultables?.length??0;optionalsLength=this.optionals?.length??0;postfixLength=this.postfix?.length??0;defaultablesAndOptionals=[];prevariadic=this.tuple.filter((T)=>{if(T.kind==="defaultables"||T.kind==="optionals")return this.defaultablesAndOptionals.push(T.node),!0;return T.kind==="prefix"});variadicOrPostfix=c_(this.variadic&&[this.variadic],this.postfix);flatRefs=this.addFlatRefs();addFlatRefs(){return G2(this.flatRefs,this.prevariadic.flatMap((T,_)=>s(T.node.flatRefs.map((F)=>q_([`${_}`,...F.path],F.node)),q_([`${_}`],T.node)))),G2(this.flatRefs,this.variadicOrPostfix.flatMap((T)=>s(T.flatRefs.map((_)=>q_([R.intrinsic.nonNegativeIntegerString.internal,..._.path],_.node)),q_([R.intrinsic.nonNegativeIntegerString.internal],T)))),this.flatRefs}isVariadicOnly=this.prevariadic.length+this.postfixLength===0;minVariadicLength=this.inner.minVariadicLength??0;minLength=this.prefixLength+this.minVariadicLength+this.postfixLength;minLengthNode=this.minLength===0?null:this.$.node("minLength",this.minLength);maxLength=this.variadic?null:this.tuple.length;maxLengthNode=this.maxLength===null?null:this.$.node("maxLength",this.maxLength);impliedSiblings=this.minLengthNode?this.maxLengthNode?[this.minLengthNode,this.maxLengthNode]:[this.minLengthNode]:this.maxLengthNode?[this.maxLengthNode]:[];defaultValueMorphs=PH(this);defaultValueMorphsReference=this.defaultValueMorphs.length?VT(this.defaultValueMorphs):void 0;elementAtIndex(T,_){if(_<this.prevariadic.length)return this.tuple[_];let F=T.length-this.postfixLength;if(_>=F)return{kind:"postfix",node:this.postfix[_-F]};return{kind:"variadic",node:this.variadic??e(`Unexpected attempt to access index ${_} on ${this}`)}}traverseAllows=(T,_)=>{for(let F=0;F<T.length;F++)if(!this.elementAtIndex(T,F).node.traverseAllows(T[F],_))return!1;return!0};traverseApply=(T,_)=>{let F=0;for(;F<T.length;F++)W_(F,()=>this.elementAtIndex(T,F).node.traverseApply(T[F],_),_)};get element(){return this.cacheGetter("element",this.$.node("union",this.children))}compile(T){if(this.prefix)for(let[_,F]of this.prefix.entries())T.traverseKey(`${_}`,`data[${_}]`,F);for(let[_,F]of this.defaultablesAndOptionals.entries()){let W=`${_+this.prefixLength}`;T.if(`${W} >= ${T.data}.length`,()=>T.traversalKind==="Allows"?T.return(!0):T.return()),T.traverseKey(W,`data[${W}]`,F)}if(this.variadic){if(this.postfix)T.const("firstPostfixIndex",`${T.data}.length${this.postfix?`- ${this.postfix.length}`:""}`);if(T.for(`i < ${this.postfix?"firstPostfixIndex":"data.length"}`,()=>T.traverseKey("i","data[i]",this.variadic),this.prevariadic.length),this.postfix)for(let[_,F]of this.postfix.entries()){let W=`firstPostfixIndex + ${_}`;T.traverseKey(W,`data[${W}]`,F)}}if(T.traversalKind==="Allows")T.return(!0)}_transform(T,_){_.path.push(R.intrinsic.nonNegativeIntegerString.internal);let F=super._transform(T,_);return _.path.pop(),F}expression=this.description;reduceJsonSchema(T,_){if(this.prevariadic.length)T.prefixItems=this.prevariadic.map((F)=>{let W=F.node.toJsonSchemaRecurse(_);if(F.kind==="defaultables"){let J=typeof F.default==="function"?F.default():F.default;W.default=R.intrinsic.jsonData.allows(J)?J:_.fallback.defaultValue({code:"defaultValue",base:W,value:J})}return W});if(this.minLength)T.minItems=this.minLength;if(this.variadic){let F=Object.assign(T,{items:this.variadic.toJsonSchemaRecurse(_)});if(this.maxLength)F.maxItems=this.maxLength;if(this.postfix){let W=this.postfix.map((J)=>J.toJsonSchemaRecurse(_));T=_.fallback.arrayPostfix({code:"arrayPostfix",base:F,elements:W})}}else T.items=!1,delete T.maxItems;return T}}var qH={},PH=(T)=>{if(!T.defaultables)return[];let _=[],F="[",W=T.prefixLength+T.defaultablesLength-1;for(let J=T.prefixLength;J<=W;J++){let[Y,$]=T.defaultables[J-T.prefixLength];_.push(C2(J,Y,$)),F+=`${J}: ${Y.id} = ${E_($)}, `}return F+="]",qH[F]??=_},v2={implementation:fH,Node:Z6},jH=(T)=>{let _=[];if(T.prefix)for(let F of T.prefix)_.push({kind:"prefix",node:F});if(T.defaultables)for(let[F,W]of T.defaultables)_.push({kind:"defaultables",node:F,default:W});if(T.optionals)for(let F of T.optionals)_.push({kind:"optionals",node:F});if(T.variadic)_.push({kind:"variadic",node:T.variadic});if(T.postfix)for(let F of T.postfix)_.push({kind:"postfix",node:F});return _},$6=(T)=>T.reduce((_,F)=>{if(F.kind==="variadic")_.variadic=F.node;else if(F.kind==="defaultables")_.defaultables=s(_.defaultables,[[F.node,F.default]]);else _[F.kind]=s(_[F.kind],F.node);return _},{}),b2="A postfix required element cannot follow an optional or defaultable element",yH="A postfix element requires a variadic element",pF=(T)=>{let[_,...F]=T.l,[W,...J]=T.r;if(!_||!W)return T;let Y=F.at(-1)?.kind==="postfix",$=J.at(-1)?.kind==="postfix",Z=_.kind==="prefix"||W.kind==="prefix"?"prefix":_.kind==="postfix"||W.kind==="postfix"?"postfix":_.kind==="variadic"&&W.kind==="variadic"?"variadic":Y||$?"prefix":_.kind==="defaultables"||W.kind==="defaultables"?"defaultables":"optionals";if(_.kind==="prefix"&&W.kind==="variadic"&&$){let M=pF({...T,fixedVariants:[],r:J.map((Q)=>({...Q,kind:"prefix"}))});if(M.disjoint.length===0)T.fixedVariants.push(M)}else if(W.kind==="prefix"&&_.kind==="variadic"&&Y){let M=pF({...T,fixedVariants:[],l:F.map((Q)=>({...Q,kind:"prefix"}))});if(M.disjoint.length===0)T.fixedVariants.push(M)}let G=OT(_.node,W.node,T.ctx);if(G instanceof I)if(Z==="prefix"||Z==="postfix")T.disjoint.push(...G.withPrefixKey(Z==="prefix"?T.result.length:`-${F.length+1}`,"required")),T.result=[...T.result,{kind:Z,node:R.intrinsic.never.internal}];else if(Z==="optionals"||Z==="defaultables")return T;else return pF({...T,fixedVariants:[],l:F.map((M)=>({...M,kind:"prefix"})),r:F.map((M)=>({...M,kind:"prefix"}))});else if(Z==="defaultables"){if(_.kind==="defaultables"&&W.kind==="defaultables"&&_.default!==W.default)z(N2(_.default,W.default));T.result=[...T.result,{kind:Z,node:G,default:_.kind==="defaultables"?_.default:W.kind==="defaultables"?W.default:e(`Unexpected defaultable intersection from ${_.kind} and ${W.kind} elements.`)}]}else T.result=[...T.result,{kind:Z,node:G}];let X=T.l.length,U=T.r.length;if(_.kind!=="variadic"||X>=U&&(W.kind==="variadic"||U===1))T.l=F;if(W.kind!=="variadic"||U>=X&&(_.kind==="variadic"||X===1))T.r=J;return pF(T)};var H6=(T)=>(_)=>{if(_.props.length||_.index){let F=_.index?.map((J)=>J[T])??[];for(let J of _.props)F.push(J[T]);if(_.undeclared)F.push(`+ (undeclared): ${_.undeclared}`);let W=`{ ${F.join(", ")} }`;return _.sequence?`${W} & ${_.sequence.description}`:W}return _.sequence?.description??"{}"},vH=H6("description"),bH=H6("expression"),X6=(T,_,F)=>{let W=T.required?"required":"optional";if(!_.signature.allows(T.key))return null;let J=J_(T.value,_.value,F);if(J instanceof I)return W==="optional"?F.node("optional",{key:T.key,value:R.intrinsic.never.internal}):J.withPrefixKey(T.key,T.kind);return null},xH=l({kind:"structure",hasAssociatedError:!1,normalize:(T)=>T,applyConfig:(T,_)=>{if(!T.undeclared&&_.onUndeclaredKey!=="ignore")return{...T,undeclared:_.onUndeclaredKey};return T},keys:{required:{child:!0,parse:cT("required"),reduceIo:(T,_,F)=>{_.required=s(_.required,F.map((W)=>W[T]));return}},optional:{child:!0,parse:cT("optional"),reduceIo:(T,_,F)=>{if(T==="in"){_.optional=F.map((W)=>W.in);return}for(let W of F)_[W.outProp.kind]=s(_[W.outProp.kind],W.outProp.out)}},index:{child:!0,parse:cT("index")},sequence:{child:!0,parse:cT("sequence")},undeclared:{parse:(T)=>T==="ignore"?void 0:T,reduceIo:(T,_,F)=>{if(F!=="delete")return;if(T==="in")delete _.undeclared;else _.undeclared="reject"}}},defaults:{description:vH},intersections:{structure:(T,_,F)=>{let W={...T.inner},J={..._.inner},Y=new I;if(T.undeclared){let G=T.keyof();for(let X of _.requiredKeys)if(!G.allows(X))Y.add("presence",R.intrinsic.never.internal,_.propsByKey[X].value,{path:[X]});if(J.optional)J.optional=J.optional.filter((X)=>G.allows(X.key));if(J.index)J.index=J.index.flatMap((X)=>{if(X.signature.extends(G))return X;let U=J_(G,X.signature,F.$);if(U instanceof I)return[];let M=xW(U,X.value,F.$);if(M.required)J.required=c_(J.required,M.required);if(M.optional)J.optional=c_(J.optional,M.optional);return M.index??[]})}if(_.undeclared){let G=_.keyof();for(let X of T.requiredKeys)if(!G.allows(X))Y.add("presence",T.propsByKey[X].value,R.intrinsic.never.internal,{path:[X]});if(W.optional)W.optional=W.optional.filter((X)=>G.allows(X.key));if(W.index)W.index=W.index.flatMap((X)=>{if(X.signature.extends(G))return X;let U=J_(G,X.signature,F.$);if(U instanceof I)return[];let M=xW(U,X.value,F.$);if(M.required)W.required=c_(W.required,M.required);if(M.optional)W.optional=c_(W.optional,M.optional);return M.index??[]})}let $={};if(T.undeclared||_.undeclared)$.undeclared=T.undeclared==="reject"||_.undeclared==="reject"?"reject":"delete";let Z=c0({kind:"structure",baseInner:$,l:d0(W),r:d0(J),roots:[],ctx:F});if(Z instanceof I)Y.push(...Z);if(Y.length)return Y;return Z}},reduce:(T,_)=>{if(T.index){if(!(T.required||T.optional))return;let F=!1,W=T.required??[],J=T.optional??[],Y=[...J];for(let $ of T.index){for(let Z of W){let G=X6(Z,$,_);if(G instanceof I)return G}for(let[Z,G]of J.entries()){let X=X6(G,$,_);if(X instanceof I)return X;if(X===null)continue;Y[Z]=X,F=!0}}if(F)return _.node("structure",{...T,optional:Y},{prereduced:!0})}}});class A6 extends R_{impliedBasis=R.intrinsic.object.internal;impliedSiblings=this.children.flatMap((T)=>T.impliedSiblings??[]);props=c_(this.required,this.optional);propsByKey=c(this.props,(T,_)=>[_.key,_]);propsByKeyReference=VT(this.propsByKey);expression=bH(this);requiredKeys=this.required?.map((T)=>T.key)??[];optionalKeys=this.optional?.map((T)=>T.key)??[];literalKeys=[...this.requiredKeys,...this.optionalKeys];_keyof;keyof(){if(this._keyof)return this._keyof;let T=this.$.units(this.literalKeys).branches;if(this.index)for(let{signature:_}of this.index)T=T.concat(_.branches);return this._keyof=this.$.node("union",T)}map(T){return this.$.node("structure",this.props.flatMap(T).reduce((_,F)=>{let W=this.propsByKey[F.key];if(UT(F)){if(F.kind!=="required"&&F.kind!=="optional")return z(`Map result must have kind "required" or "optional" (was ${F.kind})`);return _[F.kind]=s(_[F.kind],F),_}let J=F.kind??W?.kind??"required",Y=c(F,($,Z)=>($ in yF.implementation.keys)?[$,Z]:[]);return _[J]=s(_[J],this.$.node(J,Y)),_},{}))}assertHasKeys(T){let _=T.filter((F)=>!bF(F,this.keyof()));if(_.length)return z(G6(this.expression,_))}get(T,..._){let F,W=!1,J=mH(T);if((typeof J==="string"||typeof J==="symbol")&&this.propsByKey[J])F=this.propsByKey[J].value,W=this.propsByKey[J].required;if(this.index){for(let $ of this.index)if(bF(J,$.signature))F=F?.and($.value)??$.value}if(this.sequence&&bF(J,R.intrinsic.nonNegativeIntegerString))if(q(J,"root")){if(this.sequence.variadic)F=F?.and(this.sequence.element)??this.sequence.element}else{let $=Number.parseInt(J);if($<this.sequence.prevariadic.length){let Z=this.sequence.prevariadic[$].node;F=F?.and(Z)??Z,W||=$<this.sequence.prefixLength}else if(this.sequence.variadic){let Z=this.$.node("union",this.sequence.variadicOrPostfix);F=F?.and(Z)??Z}}if(!F){if(this.sequence?.variadic&&q(J,"root")&&J.extends(R.intrinsic.number))return z(oH(J.expression,this.sequence.expression));return z(G6(this.expression,[J]))}let Y=F.get(..._);return W?Y:Y.or(R.intrinsic.undefined)}pick(...T){return this.assertHasKeys(T),this.$.node("structure",this.filterKeys("pick",T))}omit(...T){return this.assertHasKeys(T),this.$.node("structure",this.filterKeys("omit",T))}optionalize(){let{required:T,..._}=this.inner;return this.$.node("structure",{..._,optional:this.props.map((F)=>F.hasKind("required")?this.$.node("optional",F.inner):F)})}require(){let{optional:T,..._}=this.inner;return this.$.node("structure",{..._,required:this.props.map((F)=>F.hasKind("optional")?{key:F.key,value:F.value}:F)})}merge(T){let _=this.filterKeys("omit",[T.keyof()]);if(T.required)_.required=s(_.required,T.required);if(T.optional)_.optional=s(_.optional,T.optional);if(T.index)_.index=s(_.index,T.index);if(T.sequence)_.sequence=T.sequence;if(T.undeclared)_.undeclared=T.undeclared;else delete _.undeclared;return this.$.node("structure",_)}filterKeys(T,_){let F=NW(this.inner),W=(J)=>{let Y=_.some(($)=>bF(J,$));return T==="pick"?Y:!Y};if(F.required)F.required=F.required.filter((J)=>W(J.key));if(F.optional)F.optional=F.optional.filter((J)=>W(J.key));if(F.index)F.index=F.index.filter((J)=>W(J.signature));return F}traverseAllows=(T,_)=>this._traverse("Allows",T,_);traverseApply=(T,_)=>this._traverse("Apply",T,_);_traverse=(T,_,F)=>{let W=F?.currentErrorCount??0;for(let J=0;J<this.props.length;J++)if(T==="Allows"){if(!this.props[J].traverseAllows(_,F))return!1}else if(this.props[J].traverseApply(_,F),F.failFast&&F.currentErrorCount>W)return!1;if(this.sequence){if(T==="Allows"){if(!this.sequence.traverseAllows(_,F))return!1}else if(this.sequence.traverseApply(_,F),F.failFast&&F.currentErrorCount>W)return!1}if(this.index||this.undeclared==="reject"){let J=Object.keys(_);J.push(...Object.getOwnPropertySymbols(_));for(let Y=0;Y<J.length;Y++){let $=J[Y];if(this.index){for(let Z of this.index)if(Z.signature.traverseAllows($,F)){if(T==="Allows"){if(!W_($,()=>Z.value.traverseAllows(_[$],F),F))return!1}else if(W_($,()=>Z.value.traverseApply(_[$],F),F),F.failFast&&F.currentErrorCount>W)return!1}}if(this.undeclared==="reject"&&!this.declaresKey($)){if(T==="Allows")return!1;if(F.errorFromNodeContext({code:"predicate",expected:"removed",actual:"",relativePath:[$],meta:this.meta}),F.failFast)return!1}}}if(this.structuralMorph&&F&&!F.hasError())F.queueMorphs([this.structuralMorph]);return!0};get defaultable(){return this.cacheGetter("defaultable",this.optional?.filter((T)=>T.hasDefault())??[])}declaresKey=(T)=>(T in this.propsByKey)||this.index?.some((_)=>_.signature.allows(T))||this.sequence!==void 0&&R.intrinsic.nonNegativeIntegerString.allows(T);_compileDeclaresKey(T){let _=[];if(this.props.length)_.push(`k in ${this.propsByKeyReference}`);if(this.index)for(let F of this.index)_.push(T.invoke(F.signature,{kind:"Allows",arg:"k"}));if(this.sequence)_.push("$ark.intrinsic.nonNegativeIntegerString.allows(k)");return _.join(" || ")||"false"}get structuralMorph(){return this.cacheGetter("structuralMorph",pH(this))}structuralMorphRef=this.structuralMorph&&VT(this.structuralMorph);compile(T){if(T.traversalKind==="Apply")T.initializeErrorCount();for(let _ of this.props)if(T.check(_),T.traversalKind==="Apply")T.returnIfFailFast();if(this.sequence){if(T.check(this.sequence),T.traversalKind==="Apply")T.returnIfFailFast()}if(this.index||this.undeclared==="reject")T.const("keys","Object.keys(data)"),T.line("keys.push(...Object.getOwnPropertySymbols(data))"),T.for("i < keys.length",()=>this.compileExhaustiveEntry(T));if(T.traversalKind==="Allows")return T.return(!0);if(this.structuralMorphRef)T.if("ctx && !ctx.hasError()",()=>{return T.line("ctx.queueMorphs(["),gH(T,this),T.line("])")})}compileExhaustiveEntry(T){if(T.const("k","keys[i]"),this.index)for(let _ of this.index)T.if(`${T.invoke(_.signature,{arg:"k",kind:"Allows"})}`,()=>T.traverseKey("k","data[k]",_.value));if(this.undeclared==="reject")T.if(`!(${this._compileDeclaresKey(T)})`,()=>{if(T.traversalKind==="Allows")return T.return(!1);return T.line(`ctx.errorFromNodeContext({ code: "predicate", expected: "removed", actual: "", relativePath: [k], meta: ${this.compiledMeta} })`).if("ctx.failFast",()=>T.return())});return T}reduceJsonSchema(T,_){switch(T.type){case"object":return this.reduceObjectJsonSchema(T,_);case"array":let F=this.sequence?.reduceJsonSchema(T,_)??T;if(this.props.length||this.index)return _.fallback.arrayObject({code:"arrayObject",base:F,object:this.reduceObjectJsonSchema({type:"object"},_)});return F;default:return zT.throwInternalOperandError("structure",T)}}reduceObjectJsonSchema(T,_){if(this.props.length){T.properties={};for(let F of this.props){let W=F.value.toJsonSchemaRecurse(_);if(typeof F.key==="symbol"){_.fallback.symbolKey({code:"symbolKey",base:T,key:F.key,value:W,optional:F.optional});continue}if(F.hasDefault()){let J=typeof F.default==="function"?F.default():F.default;W.default=R.intrinsic.jsonData.allows(J)?J:_.fallback.defaultValue({code:"defaultValue",base:W,value:J})}T.properties[F.key]=W}if(this.requiredKeys.length&&T.properties)T.required=this.requiredKeys.filter((F)=>typeof F==="string"&&(F in T.properties))}if(this.index)for(let F of this.index){let W=F.value.toJsonSchemaRecurse(_);if(F.signature.equals(R.intrinsic.string)){T.additionalProperties=W;continue}for(let J of F.signature.branches){if(!J.extends(R.intrinsic.string)){T=_.fallback.symbolKey({code:"symbolKey",base:T,key:null,value:W,optional:!1});continue}let Y={type:"string"};if(J.hasKind("morph"))Y=_.fallback.morph({code:"morph",base:J.in.toJsonSchemaRecurse(_),out:J.out.toJsonSchemaRecurse(_)});if(!J.hasKind("intersection"))return e(`Unexpected index branch kind ${J.kind}.`);let{pattern:$}=J.inner;if($){let Z=Object.assign(Y,{pattern:$[0].rule});for(let G=1;G<$.length;G++)Y=_.fallback.patternIntersection({code:"patternIntersection",base:Z,pattern:$[G].rule});T.patternProperties??={},T.patternProperties[Z.pattern]=W}}}if(this.undeclared&&!T.additionalProperties)T.additionalProperties=!1;return T}}var x2={},hH=(T)=>{let _="";for(let F=0;F<T.defaultable.length;F++)_+=T.defaultable[F].defaultValueMorphRef;if(T.sequence?.defaultValueMorphsReference)_+=T.sequence?.defaultValueMorphsReference;if(T.undeclared==="delete"){if(_+="delete !(",T.required)for(let F of T.required)_+=F.compiledKey+" | ";if(T.optional)for(let F of T.optional)_+=F.compiledKey+" | ";if(T.index)for(let F of T.index)_+=F.signature.id+" | ";if(T.sequence)if(T.sequence.maxLength===null)_+=b.nonNegativeIntegerString.id;else for(let F=0;F<T.sequence.tuple.length;F++)_+=F+" | ";_+=")"}return _},pH=(T)=>{let _=hH(T);if(!_)return;if(x2[_])return x2[_];let F=(W,J)=>{for(let Y=0;Y<T.defaultable.length;Y++)if(!(T.defaultable[Y].key in W))T.defaultable[Y].defaultValueMorph(W,J);if(T.sequence?.defaultables)for(let Y=W.length-T.sequence.prefixLength;Y<T.sequence.defaultables.length;Y++)T.sequence.defaultValueMorphs[Y](W,J);if(T.undeclared==="delete"){for(let Y in W)if(!T.declaresKey(Y))delete W[Y]}return W};return x2[_]=F},gH=(T,_)=>{let W=`(data${_.defaultable.some((J)=>J.defaultValueMorph.length===2)||_.sequence?.defaultValueMorphs.some((J)=>J.length===2)?", ctx":""})`;return T.block(`${W} => `,(J)=>{for(let Y=0;Y<_.defaultable.length;Y++){let{serializedKey:$,defaultValueMorphRef:Z}=_.defaultable[Y];J.if(`!(${$} in data)`,(G)=>G.line(`${Z}${W}`))}if(_.sequence?.defaultables)J.for(`i < ${_.sequence.defaultables.length}`,(Y)=>Y.set("data[i]",5),`data.length - ${_.sequence.prefixLength}`);if(_.undeclared==="delete")J.forIn("data",(Y)=>Y.if(`!(${_._compileDeclaresKey(Y)})`,($)=>$.line("delete data[k]")));return J.return("data")})},h2={implementation:xH,Node:A6},mH=(T)=>{if(q(T,"root")&&T.hasKind("unit"))T=T.unit;if(typeof T==="number")T=`${T}`;return T},oH=(T,_)=>`${T} is not allowed as an array index on ${_}. Use the 'nonNegativeIntegerString' keyword instead.`,xW=(T,_,F)=>{let[W,J]=y8(T.branches,($)=>$.hasKind("unit"));if(!W.length)return{index:F.node("index",{signature:T,value:_})};let Y={};for(let $ of W){let Z=F.node("required",{key:$.unit,value:_});Y[Z.kind]=s(Y[Z.kind],Z)}if(J.length)Y.index=F.node("index",{signature:J,value:_});return Y},uH=(T)=>q(T,"root")?T.expression:d(T),G6=(T,_)=>`Key${_.length===1?"":"s"} ${_.map(uH).join(", ")} ${_.length===1?"does":"do"} not exist on ${T}`;var t0={...vJ,alias:xF.implementation,domain:bW.implementation,unit:P2.implementation,proto:hF.implementation,union:q2.implementation,morph:k2.implementation,intersection:B2.implementation,divisor:M2.implementation,pattern:D2.implementation,predicate:O2.implementation,required:y2.implementation,optional:yF.implementation,index:j2.implementation,sequence:v2.implementation,structure:h2.implementation};R.defaultConfig=u8(Object.assign(c(t0,(T,_)=>[T,_.defaults]),{jitless:n8(),clone:l8,onUndeclaredKey:"ignore",exactOptionalPropertyTypes:!0,numberAllowsNaN:!1,dateAllowsInvalid:!1,onFail:null,keywords:{},toJsonSchema:zT.defaultConfig}));R.resolvedConfig=CF(R.defaultConfig,R.config);var mJ={...bJ,alias:xF.Node,domain:bW.Node,unit:P2.Node,proto:hF.Node,union:q2.Node,morph:k2.Node,intersection:B2.Node,divisor:M2.Node,pattern:D2.Node,predicate:O2.Node,required:y2.Node,optional:yF.Node,index:j2.Node,sequence:v2.Node,structure:h2.Node};class r0 extends i1{get[tT](){return"module"}}var p2=(T,_)=>new r0(c(T,(F,W)=>[F,q(W,"module")?p2(W,_):_.bindReference(W)]));var cH=(T)=>ZT(T)?T:("branches"in T)&&ZT(T.branches)?T.branches:void 0,dH=(T,_)=>z(`Node of kind ${_} is not valid as a ${T} definition`),U6=(T)=>`#${T} duplicates public alias ${T}`,g2={};R.ambient??={};var O6,w6="function $",lH=(T)=>Q6(T,z6(T)),Q6=(T,_)=>{let F=_.write(w6,4),W=_.compile()();for(let J of T){if(J.precompilation)continue;if(J.traverseAllows=W[`${J.id}Allows`].bind(W),J.isRoot()&&!J.allowsRequiresContext)J.allows=J.traverseAllows;if(J.traverseApply=W[`${J.id}Apply`].bind(W),W[`${J.id}Optimistic`])J.traverseOptimistic=W[`${J.id}Optimistic`].bind(W);J.precompilation=F}},z6=(T)=>new IW().return(T.reduce((_,F)=>{let W=new NF({kind:"Allows"}).indent();F.compile(W);let J=W.write(`${F.id}Allows`),Y=new NF({kind:"Apply"}).indent();F.compile(Y);let $=Y.write(`${F.id}Apply`),Z=`${_}${J},
|
|
43
|
+
Right: ${_}`;var fA=l({kind:"unit",hasAssociatedError:!0,keys:{unit:{preserveUndefined:!0,serialize:(T)=>T instanceof Date?T.toISOString():E_(T)}},normalize:(T)=>T,defaults:{description:(T)=>d(T.unit),problem:({expected:T,actual:_})=>`${T===_?`must be reference equal to ${T} (serialized to the same value)`:`must be ${T} (was ${_})`}`},intersections:{unit:(T,_)=>N.init("unit",T,_),...g_("unit",(T,_)=>{if(_.allows(T.unit))return T;let F=_.hasKind("intersection")?_.basis:_;if(F){let W=F.hasKind("domain")?F:z.intrinsic.object;if(T.domain!==W.domain){let J=T.domain==="undefined"||T.domain==="null"||T.domain==="boolean"?T.domain:z.intrinsic[T.domain];return N.init("domain",J,W)}}return N.init("assignability",T,_.hasKind("intersection")?_.children.find((W)=>!W.allows(T.unit)):_)})}});class Z6 extends B0{compiledValue=this.json.unit;serializedValue=typeof this.unit==="string"||this.unit instanceof Date?JSON.stringify(this.compiledValue):`${this.compiledValue}`;compiledCondition=$6(this.unit,this.serializedValue);compiledNegation=$6(this.unit,this.serializedValue,"negated");expression=d(this.unit);domain=PT(this.unit);get defaultShortDescription(){return this.domain==="object"?__.object:this.description}innerToJsonSchema(T){return this.unit===null?{type:"null"}:z.intrinsic.jsonPrimitive.allows(this.unit)?{const:this.unit}:T.fallback.unit({code:"unit",base:{},unit:this.unit})}traverseAllows=this.unit instanceof Date?(T)=>T instanceof Date&&T.toISOString()===this.compiledValue:Number.isNaN(this.unit)?(T)=>Number.isNaN(T):(T)=>T===this.unit}var v2={implementation:fA,Node:Z6},$6=(T,_,F)=>{if(T instanceof Date){let W=`data instanceof Date && data.toISOString() === ${_}`;return F?`!(${W})`:W}if(Number.isNaN(T))return`${F?"!":""}Number.isNaN(data)`;return`data ${F?"!":"="}== ${_}`};var PA=l({kind:"index",hasAssociatedError:!1,intersectionIsOpen:!0,keys:{signature:{child:!0,parse:(T,_)=>{let F=_.$.parseSchema(T);if(!F.extends(z.intrinsic.key))return E(jA(F.expression));let W=F.branches.filter((J)=>J.hasKind("unit"));if(W.length)return E(qA(W.map((J)=>d(J.unit))));return F}},value:{child:!0,parse:(T,_)=>_.$.parseSchema(T)}},normalize:(T)=>T,defaults:{description:(T)=>`[${T.signature.expression}]: ${T.value.description}`},intersections:{index:(T,_,F)=>{if(T.signature.equals(_.signature)){let W=UT(T.value,_.value,F),J=W instanceof N?z.intrinsic.never.internal:W;return F.$.node("index",{signature:T.signature,value:J})}if(T.signature.extends(_.signature)&&T.value.subsumes(_.value))return _;if(_.signature.extends(T.signature)&&_.value.subsumes(T.value))return T;return null}}});class X6 extends z_{impliedBasis=z.intrinsic.object.internal;expression=`[${this.signature.expression}]: ${this.value.expression}`;flatRefs=s(this.value.flatRefs.map((T)=>P_([this.signature,...T.path],T.node)),P_([this.signature],this.value));traverseAllows=(T,_)=>S0(T).every((F)=>{if(this.signature.traverseAllows(F[0],_))return W_(F[0],()=>this.value.traverseAllows(F[1],_),_);return!0});traverseApply=(T,_)=>{for(let F of S0(T))if(this.signature.traverseAllows(F[0],_))W_(F[0],()=>this.value.traverseApply(F[1],_),_)};_transform(T,_){_.path.push(this.signature);let F=super._transform(T,_);return _.path.pop(),F}compile(){}}var x2={implementation:PA,Node:X6},qA=(T)=>`Index keys ${T.join(", ")} should be specified as named props.`,jA=(T)=>`Indexed key definition '${T}' must be a string or symbol`;var yA=l({kind:"required",hasAssociatedError:!0,intersectionIsOpen:!0,keys:{key:{},value:{child:!0,parse:(T,_)=>_.$.parseSchema(T)}},normalize:(T)=>T,defaults:{description:(T)=>`${T.compiledKey}: ${T.value.description}`,expected:(T)=>T.missingValueDescription,actual:()=>"missing"},intersections:{required:vF,optional:vF}});class G6 extends xF{expression=`${this.compiledKey}: ${this.value.expression}`;errorContext=Object.freeze({code:"required",missingValueDescription:this.value.defaultShortDescription,relativePath:[this.key],meta:this.meta});compiledErrorContext=X0(this.errorContext)}var b2={implementation:yA,Node:G6};var vA=l({kind:"sequence",hasAssociatedError:!1,collapsibleKey:"variadic",keys:{prefix:{child:!0,parse:(T,_)=>{if(T.length===0)return;return T.map((F)=>_.$.parseSchema(F))}},optionals:{child:!0,parse:(T,_)=>{if(T.length===0)return;return T.map((F)=>_.$.parseSchema(F))}},defaultables:{child:(T)=>T.map((_)=>_[0]),parse:(T,_)=>{if(T.length===0)return;return T.map((F)=>{let W=_.$.parseSchema(F[0]);return hF(W,F[1],null),[W,F[1]]})},serialize:(T)=>T.map((_)=>[_[0].collapsibleJson,E_(_[1])])},variadic:{child:!0,parse:(T,_)=>_.$.parseSchema(T,_)},minVariadicLength:{parse:(T)=>T===0?void 0:T},postfix:{child:!0,parse:(T,_)=>{if(T.length===0)return;return T.map((F)=>_.$.parseSchema(F))}}},normalize:(T)=>{if(typeof T==="string")return{variadic:T};if("variadic"in T||"prefix"in T||"defaultables"in T||"optionals"in T||"postfix"in T||"minVariadicLength"in T){if(T.postfix?.length){if(!T.variadic)return E(pA);if(T.optionals?.length||T.defaultables?.length)return E(p2)}if(T.minVariadicLength&&!T.variadic)return E("minVariadicLength may not be specified without a variadic element");return T}return{variadic:T}},reduce:(T,_)=>{let F=T.minVariadicLength??0,W=T.prefix?.slice()??[],J=T.defaultables?.slice()??[],Y=T.optionals?.slice()??[],$=T.postfix?.slice()??[];if(T.variadic){while(Y.at(-1)?.equals(T.variadic))Y.pop();if(Y.length===0&&J.length===0)while(W.at(-1)?.equals(T.variadic))W.pop(),F++;while($[0]?.equals(T.variadic))$.shift(),F++}else if(Y.length===0&&J.length===0)W.push(...$.splice(0));if(F!==T.minVariadicLength||T.prefix&&T.prefix.length!==W.length)return _.node("sequence",{...T,prefix:W,defaultables:J,optionals:Y,postfix:$,minVariadicLength:F},{prereduced:!0})},defaults:{description:(T)=>{if(T.isVariadicOnly)return`${T.variadic.nestableExpression}[]`;return`[${T.tuple.map((F)=>F.kind==="defaultables"?`${F.node.nestableExpression} = ${d(F.default)}`:F.kind==="optionals"?`${F.node.nestableExpression}?`:F.kind==="variadic"?`...${F.node.nestableExpression}[]`:F.node.expression).join(", ")}]`}},intersections:{sequence:(T,_,F)=>{let W=oF({l:T.tuple,r:_.tuple,disjoint:new N,result:[],fixedVariants:[],ctx:F}),J=W.disjoint.length===0?[W,...W.fixedVariants]:W.fixedVariants;return J.length===0?W.disjoint:J.length===1?F.$.node("sequence",A6(J[0].result)):F.$.node("union",J.map((Y)=>({proto:Array,sequence:A6(Y.result)})))}}});class H6 extends z_{impliedBasis=z.intrinsic.Array.internal;tuple=hA(this.inner);prefixLength=this.prefix?.length??0;defaultablesLength=this.defaultables?.length??0;optionalsLength=this.optionals?.length??0;postfixLength=this.postfix?.length??0;defaultablesAndOptionals=[];prevariadic=this.tuple.filter((T)=>{if(T.kind==="defaultables"||T.kind==="optionals")return this.defaultablesAndOptionals.push(T.node),!0;return T.kind==="prefix"});variadicOrPostfix=d_(this.variadic&&[this.variadic],this.postfix);flatRefs=this.addFlatRefs();addFlatRefs(){return O2(this.flatRefs,this.prevariadic.flatMap((T,_)=>s(T.node.flatRefs.map((F)=>P_([`${_}`,...F.path],F.node)),P_([`${_}`],T.node)))),O2(this.flatRefs,this.variadicOrPostfix.flatMap((T)=>s(T.flatRefs.map((_)=>P_([z.intrinsic.nonNegativeIntegerString.internal,..._.path],_.node)),P_([z.intrinsic.nonNegativeIntegerString.internal],T)))),this.flatRefs}isVariadicOnly=this.prevariadic.length+this.postfixLength===0;minVariadicLength=this.inner.minVariadicLength??0;minLength=this.prefixLength+this.minVariadicLength+this.postfixLength;minLengthNode=this.minLength===0?null:this.$.node("minLength",this.minLength);maxLength=this.variadic?null:this.tuple.length;maxLengthNode=this.maxLength===null?null:this.$.node("maxLength",this.maxLength);impliedSiblings=this.minLengthNode?this.maxLengthNode?[this.minLengthNode,this.maxLengthNode]:[this.minLengthNode]:this.maxLengthNode?[this.maxLengthNode]:[];defaultValueMorphs=bA(this);defaultValueMorphsReference=this.defaultValueMorphs.length?KT(this.defaultValueMorphs):void 0;elementAtIndex(T,_){if(_<this.prevariadic.length)return this.tuple[_];let F=T.length-this.postfixLength;if(_>=F)return{kind:"postfix",node:this.postfix[_-F]};return{kind:"variadic",node:this.variadic??e(`Unexpected attempt to access index ${_} on ${this}`)}}traverseAllows=(T,_)=>{for(let F=0;F<T.length;F++)if(!this.elementAtIndex(T,F).node.traverseAllows(T[F],_))return!1;return!0};traverseApply=(T,_)=>{let F=0;for(;F<T.length;F++)W_(F,()=>this.elementAtIndex(T,F).node.traverseApply(T[F],_),_)};get element(){return this.cacheGetter("element",this.$.node("union",this.children))}compile(T){if(this.prefix)for(let[_,F]of this.prefix.entries())T.traverseKey(`${_}`,`data[${_}]`,F);for(let[_,F]of this.defaultablesAndOptionals.entries()){let W=`${_+this.prefixLength}`;T.if(`${W} >= ${T.data}.length`,()=>T.traversalKind==="Allows"?T.return(!0):T.return()),T.traverseKey(W,`data[${W}]`,F)}if(this.variadic){if(this.postfix)T.const("firstPostfixIndex",`${T.data}.length${this.postfix?`- ${this.postfix.length}`:""}`);if(T.for(`i < ${this.postfix?"firstPostfixIndex":"data.length"}`,()=>T.traverseKey("i","data[i]",this.variadic),this.prevariadic.length),this.postfix)for(let[_,F]of this.postfix.entries()){let W=`firstPostfixIndex + ${_}`;T.traverseKey(W,`data[${W}]`,F)}}if(T.traversalKind==="Allows")T.return(!0)}_transform(T,_){_.path.push(z.intrinsic.nonNegativeIntegerString.internal);let F=super._transform(T,_);return _.path.pop(),F}expression=this.description;reduceJsonSchema(T,_){if(this.prevariadic.length)T.prefixItems=this.prevariadic.map((F)=>{let W=F.node.toJsonSchemaRecurse(_);if(F.kind==="defaultables"){let J=typeof F.default==="function"?F.default():F.default;W.default=z.intrinsic.jsonData.allows(J)?J:_.fallback.defaultValue({code:"defaultValue",base:W,value:J})}return W});if(this.minLength)T.minItems=this.minLength;if(this.variadic){let F=Object.assign(T,{items:this.variadic.toJsonSchemaRecurse(_)});if(this.maxLength)F.maxItems=this.maxLength;if(this.postfix){let W=this.postfix.map((J)=>J.toJsonSchemaRecurse(_));T=_.fallback.arrayPostfix({code:"arrayPostfix",base:F,elements:W})}}else T.items=!1,delete T.maxItems;return T}}var xA={},bA=(T)=>{if(!T.defaultables)return[];let _=[],F="[",W=T.prefixLength+T.defaultablesLength-1;for(let J=T.prefixLength;J<=W;J++){let[Y,$]=T.defaultables[J-T.prefixLength];_.push(f2(J,Y,$)),F+=`${J}: ${Y.id} = ${E_($)}, `}return F+="]",xA[F]??=_},h2={implementation:vA,Node:H6},hA=(T)=>{let _=[];if(T.prefix)for(let F of T.prefix)_.push({kind:"prefix",node:F});if(T.defaultables)for(let[F,W]of T.defaultables)_.push({kind:"defaultables",node:F,default:W});if(T.optionals)for(let F of T.optionals)_.push({kind:"optionals",node:F});if(T.variadic)_.push({kind:"variadic",node:T.variadic});if(T.postfix)for(let F of T.postfix)_.push({kind:"postfix",node:F});return _},A6=(T)=>T.reduce((_,F)=>{if(F.kind==="variadic")_.variadic=F.node;else if(F.kind==="defaultables")_.defaultables=s(_.defaultables,[[F.node,F.default]]);else _[F.kind]=s(_[F.kind],F.node);return _},{}),p2="A postfix required element cannot follow an optional or defaultable element",pA="A postfix element requires a variadic element",oF=(T)=>{let[_,...F]=T.l,[W,...J]=T.r;if(!_||!W)return T;let Y=F.at(-1)?.kind==="postfix",$=J.at(-1)?.kind==="postfix",Z=_.kind==="prefix"||W.kind==="prefix"?"prefix":_.kind==="postfix"||W.kind==="postfix"?"postfix":_.kind==="variadic"&&W.kind==="variadic"?"variadic":Y||$?"prefix":_.kind==="defaultables"||W.kind==="defaultables"?"defaultables":"optionals";if(_.kind==="prefix"&&W.kind==="variadic"&&$){let M=oF({...T,fixedVariants:[],r:J.map((Q)=>({...Q,kind:"prefix"}))});if(M.disjoint.length===0)T.fixedVariants.push(M)}else if(W.kind==="prefix"&&_.kind==="variadic"&&Y){let M=oF({...T,fixedVariants:[],l:F.map((Q)=>({...Q,kind:"prefix"}))});if(M.disjoint.length===0)T.fixedVariants.push(M)}let G=UT(_.node,W.node,T.ctx);if(G instanceof N)if(Z==="prefix"||Z==="postfix")T.disjoint.push(...G.withPrefixKey(Z==="prefix"?T.result.length:`-${F.length+1}`,"required")),T.result=[...T.result,{kind:Z,node:z.intrinsic.never.internal}];else if(Z==="optionals"||Z==="defaultables")return T;else return oF({...T,fixedVariants:[],l:F.map((M)=>({...M,kind:"prefix"})),r:F.map((M)=>({...M,kind:"prefix"}))});else if(Z==="defaultables"){if(_.kind==="defaultables"&&W.kind==="defaultables"&&_.default!==W.default)E(k2(_.default,W.default));T.result=[...T.result,{kind:Z,node:G,default:_.kind==="defaultables"?_.default:W.kind==="defaultables"?W.default:e(`Unexpected defaultable intersection from ${_.kind} and ${W.kind} elements.`)}]}else T.result=[...T.result,{kind:Z,node:G}];let X=T.l.length,O=T.r.length;if(_.kind!=="variadic"||X>=O&&(W.kind==="variadic"||O===1))T.l=F;if(W.kind!=="variadic"||O>=X&&(_.kind==="variadic"||X===1))T.r=J;return oF(T)};var M6=(T)=>(_)=>{if(_.props.length||_.index){let F=_.index?.map((J)=>J[T])??[];for(let J of _.props)F.push(J[T]);if(_.undeclared)F.push(`+ (undeclared): ${_.undeclared}`);let W=`{ ${F.join(", ")} }`;return _.sequence?`${W} & ${_.sequence.description}`:W}return _.sequence?.description??"{}"},gA=M6("description"),mA=M6("expression"),O6=(T,_,F)=>{let W=T.required?"required":"optional";if(!_.signature.allows(T.key))return null;let J=J_(T.value,_.value,F);if(J instanceof N)return W==="optional"?F.node("optional",{key:T.key,value:z.intrinsic.never.internal}):J.withPrefixKey(T.key,T.kind);return null},oA=l({kind:"structure",hasAssociatedError:!1,normalize:(T)=>T,applyConfig:(T,_)=>{if(!T.undeclared&&_.onUndeclaredKey!=="ignore")return{...T,undeclared:_.onUndeclaredKey};return T},keys:{required:{child:!0,parse:cT("required"),reduceIo:(T,_,F)=>{_.required=s(_.required,F.map((W)=>W[T]));return}},optional:{child:!0,parse:cT("optional"),reduceIo:(T,_,F)=>{if(T==="in"){_.optional=F.map((W)=>W.in);return}for(let W of F)_[W.outProp.kind]=s(_[W.outProp.kind],W.outProp.out)}},index:{child:!0,parse:cT("index")},sequence:{child:!0,parse:cT("sequence")},undeclared:{parse:(T)=>T==="ignore"?void 0:T,reduceIo:(T,_,F)=>{if(F!=="delete")return;if(T==="in")delete _.undeclared;else _.undeclared="reject"}}},defaults:{description:gA},intersections:{structure:(T,_,F)=>{let W={...T.inner},J={..._.inner},Y=new N;if(T.undeclared){let G=T.keyof();for(let X of _.requiredKeys)if(!G.allows(X))Y.add("presence",z.intrinsic.never.internal,_.propsByKey[X].value,{path:[X]});if(J.optional)J.optional=J.optional.filter((X)=>G.allows(X.key));if(J.index)J.index=J.index.flatMap((X)=>{if(X.signature.extends(G))return X;let O=J_(G,X.signature,F.$);if(O instanceof N)return[];let M=mW(O,X.value,F.$);if(M.required)J.required=d_(J.required,M.required);if(M.optional)J.optional=d_(J.optional,M.optional);return M.index??[]})}if(_.undeclared){let G=_.keyof();for(let X of T.requiredKeys)if(!G.allows(X))Y.add("presence",T.propsByKey[X].value,z.intrinsic.never.internal,{path:[X]});if(W.optional)W.optional=W.optional.filter((X)=>G.allows(X.key));if(W.index)W.index=W.index.flatMap((X)=>{if(X.signature.extends(G))return X;let O=J_(G,X.signature,F.$);if(O instanceof N)return[];let M=mW(O,X.value,F.$);if(M.required)W.required=d_(W.required,M.required);if(M.optional)W.optional=d_(W.optional,M.optional);return M.index??[]})}let $={};if(T.undeclared||_.undeclared)$.undeclared=T.undeclared==="reject"||_.undeclared==="reject"?"reject":"delete";let Z=t0({kind:"structure",baseInner:$,l:i0(W),r:i0(J),roots:[],ctx:F});if(Z instanceof N)Y.push(...Z);if(Y.length)return Y;return Z}},reduce:(T,_)=>{if(T.index){if(!(T.required||T.optional))return;let F=!1,W=T.required??[],J=T.optional??[],Y=[...J];for(let $ of T.index){for(let Z of W){let G=O6(Z,$,_);if(G instanceof N)return G}for(let[Z,G]of J.entries()){let X=O6(G,$,_);if(X instanceof N)return X;if(X===null)continue;Y[Z]=X,F=!0}}if(F)return _.node("structure",{...T,optional:Y},{prereduced:!0})}}});class w6 extends z_{impliedBasis=z.intrinsic.object.internal;impliedSiblings=this.children.flatMap((T)=>T.impliedSiblings??[]);props=d_(this.required,this.optional);propsByKey=c(this.props,(T,_)=>[_.key,_]);propsByKeyReference=KT(this.propsByKey);expression=mA(this);requiredKeys=this.required?.map((T)=>T.key)??[];optionalKeys=this.optional?.map((T)=>T.key)??[];literalKeys=[...this.requiredKeys,...this.optionalKeys];_keyof;keyof(){if(this._keyof)return this._keyof;let T=this.$.units(this.literalKeys).branches;if(this.index)for(let{signature:_}of this.index)T=T.concat(_.branches);return this._keyof=this.$.node("union",T)}map(T){return this.$.node("structure",this.props.flatMap(T).reduce((_,F)=>{let W=this.propsByKey[F.key];if(OT(F)){if(F.kind!=="required"&&F.kind!=="optional")return E(`Map result must have kind "required" or "optional" (was ${F.kind})`);return _[F.kind]=s(_[F.kind],F),_}let J=F.kind??W?.kind??"required",Y=c(F,($,Z)=>($ in bF.implementation.keys)?[$,Z]:[]);return _[J]=s(_[J],this.$.node(J,Y)),_},{}))}assertHasKeys(T){let _=T.filter((F)=>!pF(F,this.keyof()));if(_.length)return E(U6(this.expression,_))}get(T,..._){let F,W=!1,J=lA(T);if((typeof J==="string"||typeof J==="symbol")&&this.propsByKey[J])F=this.propsByKey[J].value,W=this.propsByKey[J].required;if(this.index){for(let $ of this.index)if(pF(J,$.signature))F=F?.and($.value)??$.value}if(this.sequence&&pF(J,z.intrinsic.nonNegativeIntegerString))if(P(J,"root")){if(this.sequence.variadic)F=F?.and(this.sequence.element)??this.sequence.element}else{let $=Number.parseInt(J);if($<this.sequence.prevariadic.length){let Z=this.sequence.prevariadic[$].node;F=F?.and(Z)??Z,W||=$<this.sequence.prefixLength}else if(this.sequence.variadic){let Z=this.$.node("union",this.sequence.variadicOrPostfix);F=F?.and(Z)??Z}}if(!F){if(this.sequence?.variadic&&P(J,"root")&&J.extends(z.intrinsic.number))return E(tA(J.expression,this.sequence.expression));return E(U6(this.expression,[J]))}let Y=F.get(..._);return W?Y:Y.or(z.intrinsic.undefined)}pick(...T){return this.assertHasKeys(T),this.$.node("structure",this.filterKeys("pick",T))}omit(...T){return this.assertHasKeys(T),this.$.node("structure",this.filterKeys("omit",T))}optionalize(){let{required:T,..._}=this.inner;return this.$.node("structure",{..._,optional:this.props.map((F)=>F.hasKind("required")?this.$.node("optional",F.inner):F)})}require(){let{optional:T,..._}=this.inner;return this.$.node("structure",{..._,required:this.props.map((F)=>F.hasKind("optional")?{key:F.key,value:F.value}:F)})}merge(T){let _=this.filterKeys("omit",[T.keyof()]);if(T.required)_.required=s(_.required,T.required);if(T.optional)_.optional=s(_.optional,T.optional);if(T.index)_.index=s(_.index,T.index);if(T.sequence)_.sequence=T.sequence;if(T.undeclared)_.undeclared=T.undeclared;else delete _.undeclared;return this.$.node("structure",_)}filterKeys(T,_){let F=fW(this.inner),W=(J)=>{let Y=_.some(($)=>pF(J,$));return T==="pick"?Y:!Y};if(F.required)F.required=F.required.filter((J)=>W(J.key));if(F.optional)F.optional=F.optional.filter((J)=>W(J.key));if(F.index)F.index=F.index.filter((J)=>W(J.signature));return F}traverseAllows=(T,_)=>this._traverse("Allows",T,_);traverseApply=(T,_)=>this._traverse("Apply",T,_);_traverse=(T,_,F)=>{let W=F?.currentErrorCount??0;for(let J=0;J<this.props.length;J++)if(T==="Allows"){if(!this.props[J].traverseAllows(_,F))return!1}else if(this.props[J].traverseApply(_,F),F.failFast&&F.currentErrorCount>W)return!1;if(this.sequence){if(T==="Allows"){if(!this.sequence.traverseAllows(_,F))return!1}else if(this.sequence.traverseApply(_,F),F.failFast&&F.currentErrorCount>W)return!1}if(this.index||this.undeclared==="reject"){let J=Object.keys(_);J.push(...Object.getOwnPropertySymbols(_));for(let Y=0;Y<J.length;Y++){let $=J[Y];if(this.index){for(let Z of this.index)if(Z.signature.traverseAllows($,F)){if(T==="Allows"){if(!W_($,()=>Z.value.traverseAllows(_[$],F),F))return!1}else if(W_($,()=>Z.value.traverseApply(_[$],F),F),F.failFast&&F.currentErrorCount>W)return!1}}if(this.undeclared==="reject"&&!this.declaresKey($)){if(T==="Allows")return!1;if(F.errorFromNodeContext({code:"predicate",expected:"removed",actual:"",relativePath:[$],meta:this.meta}),F.failFast)return!1}}}if(this.structuralMorph&&F&&!F.hasError())F.queueMorphs([this.structuralMorph]);return!0};get defaultable(){return this.cacheGetter("defaultable",this.optional?.filter((T)=>T.hasDefault())??[])}declaresKey=(T)=>(T in this.propsByKey)||this.index?.some((_)=>_.signature.allows(T))||this.sequence!==void 0&&z.intrinsic.nonNegativeIntegerString.allows(T);_compileDeclaresKey(T){let _=[];if(this.props.length)_.push(`k in ${this.propsByKeyReference}`);if(this.index)for(let F of this.index)_.push(T.invoke(F.signature,{kind:"Allows",arg:"k"}));if(this.sequence)_.push("$ark.intrinsic.nonNegativeIntegerString.allows(k)");return _.join(" || ")||"false"}get structuralMorph(){return this.cacheGetter("structuralMorph",cA(this))}structuralMorphRef=this.structuralMorph&&KT(this.structuralMorph);compile(T){if(T.traversalKind==="Apply")T.initializeErrorCount();for(let _ of this.props)if(T.check(_),T.traversalKind==="Apply")T.returnIfFailFast();if(this.sequence){if(T.check(this.sequence),T.traversalKind==="Apply")T.returnIfFailFast()}if(this.index||this.undeclared==="reject")T.const("keys","Object.keys(data)"),T.line("keys.push(...Object.getOwnPropertySymbols(data))"),T.for("i < keys.length",()=>this.compileExhaustiveEntry(T));if(T.traversalKind==="Allows")return T.return(!0);if(this.structuralMorphRef)T.if("ctx && !ctx.hasError()",()=>{return T.line("ctx.queueMorphs(["),dA(T,this),T.line("])")})}compileExhaustiveEntry(T){if(T.const("k","keys[i]"),this.index)for(let _ of this.index)T.if(`${T.invoke(_.signature,{arg:"k",kind:"Allows"})}`,()=>T.traverseKey("k","data[k]",_.value));if(this.undeclared==="reject")T.if(`!(${this._compileDeclaresKey(T)})`,()=>{if(T.traversalKind==="Allows")return T.return(!1);return T.line(`ctx.errorFromNodeContext({ code: "predicate", expected: "removed", actual: "", relativePath: [k], meta: ${this.compiledMeta} })`).if("ctx.failFast",()=>T.return())});return T}reduceJsonSchema(T,_){switch(T.type){case"object":return this.reduceObjectJsonSchema(T,_);case"array":let F=this.sequence?.reduceJsonSchema(T,_)??T;if(this.props.length||this.index)return _.fallback.arrayObject({code:"arrayObject",base:F,object:this.reduceObjectJsonSchema({type:"object"},_)});return F;default:return RT.throwInternalOperandError("structure",T)}}reduceObjectJsonSchema(T,_){if(this.props.length){T.properties={};for(let F of this.props){let W=F.value.toJsonSchemaRecurse(_);if(typeof F.key==="symbol"){_.fallback.symbolKey({code:"symbolKey",base:T,key:F.key,value:W,optional:F.optional});continue}if(F.hasDefault()){let J=typeof F.default==="function"?F.default():F.default;W.default=z.intrinsic.jsonData.allows(J)?J:_.fallback.defaultValue({code:"defaultValue",base:W,value:J})}T.properties[F.key]=W}if(this.requiredKeys.length&&T.properties)T.required=this.requiredKeys.filter((F)=>typeof F==="string"&&(F in T.properties))}if(this.index)for(let F of this.index){let W=F.value.toJsonSchemaRecurse(_);if(F.signature.equals(z.intrinsic.string)){T.additionalProperties=W;continue}for(let J of F.signature.branches){if(!J.extends(z.intrinsic.string)){T=_.fallback.symbolKey({code:"symbolKey",base:T,key:null,value:W,optional:!1});continue}let Y={type:"string"};if(J.hasKind("morph"))Y=_.fallback.morph({code:"morph",base:J.in.toJsonSchemaRecurse(_),out:J.out.toJsonSchemaRecurse(_)});if(!J.hasKind("intersection"))return e(`Unexpected index branch kind ${J.kind}.`);let{pattern:$}=J.inner;if($){let Z=Object.assign(Y,{pattern:$[0].rule});for(let G=1;G<$.length;G++)Y=_.fallback.patternIntersection({code:"patternIntersection",base:Z,pattern:$[G].rule});T.patternProperties??={},T.patternProperties[Z.pattern]=W}}}if(this.undeclared&&!T.additionalProperties)T.additionalProperties=!1;return T}}var g2={},uA=(T)=>{let _="";for(let F=0;F<T.defaultable.length;F++)_+=T.defaultable[F].defaultValueMorphRef;if(T.sequence?.defaultValueMorphsReference)_+=T.sequence?.defaultValueMorphsReference;if(T.undeclared==="delete"){if(_+="delete !(",T.required)for(let F of T.required)_+=F.compiledKey+" | ";if(T.optional)for(let F of T.optional)_+=F.compiledKey+" | ";if(T.index)for(let F of T.index)_+=F.signature.id+" | ";if(T.sequence)if(T.sequence.maxLength===null)_+=x.nonNegativeIntegerString.id;else for(let F=0;F<T.sequence.tuple.length;F++)_+=F+" | ";_+=")"}return _},cA=(T)=>{let _=uA(T);if(!_)return;if(g2[_])return g2[_];let F=(W,J)=>{for(let Y=0;Y<T.defaultable.length;Y++)if(!(T.defaultable[Y].key in W))T.defaultable[Y].defaultValueMorph(W,J);if(T.sequence?.defaultables)for(let Y=W.length-T.sequence.prefixLength;Y<T.sequence.defaultables.length;Y++)T.sequence.defaultValueMorphs[Y](W,J);if(T.undeclared==="delete"){for(let Y in W)if(!T.declaresKey(Y))delete W[Y]}return W};return g2[_]=F},dA=(T,_)=>{let W=`(data${_.defaultable.some((J)=>J.defaultValueMorph.length===2)||_.sequence?.defaultValueMorphs.some((J)=>J.length===2)?", ctx":""})`;return T.block(`${W} => `,(J)=>{for(let Y=0;Y<_.defaultable.length;Y++){let{serializedKey:$,defaultValueMorphRef:Z}=_.defaultable[Y];J.if(`!(${$} in data)`,(G)=>G.line(`${Z}${W}`))}if(_.sequence?.defaultables)J.for(`i < ${_.sequence.defaultables.length}`,(Y)=>Y.set("data[i]",5),`data.length - ${_.sequence.prefixLength}`);if(_.undeclared==="delete")J.forIn("data",(Y)=>Y.if(`!(${_._compileDeclaresKey(Y)})`,($)=>$.line("delete data[k]")));return J.return("data")})},m2={implementation:oA,Node:w6},lA=(T)=>{if(P(T,"root")&&T.hasKind("unit"))T=T.unit;if(typeof T==="number")T=`${T}`;return T},tA=(T,_)=>`${T} is not allowed as an array index on ${_}. Use the 'nonNegativeIntegerString' keyword instead.`,mW=(T,_,F)=>{let[W,J]=h8(T.branches,($)=>$.hasKind("unit"));if(!W.length)return{index:F.node("index",{signature:T,value:_})};let Y={};for(let $ of W){let Z=F.node("required",{key:$.unit,value:_});Y[Z.kind]=s(Y[Z.kind],Z)}if(J.length)Y.index=F.node("index",{signature:J,value:_});return Y},iA=(T)=>P(T,"root")?T.expression:d(T),U6=(T,_)=>`Key${_.length===1?"":"s"} ${_.map(iA).join(", ")} ${_.length===1?"does":"do"} not exist on ${T}`;var r0={...pJ,alias:gF.implementation,domain:gW.implementation,unit:v2.implementation,proto:mF.implementation,union:y2.implementation,morph:q2.implementation,intersection:P2.implementation,divisor:R2.implementation,pattern:I2.implementation,predicate:Q2.implementation,required:b2.implementation,optional:bF.implementation,index:x2.implementation,sequence:h2.implementation,structure:m2.implementation};z.defaultConfig=t8(Object.assign(c(r0,(T,_)=>[T,_.defaults]),{jitless:e8(),clone:r8,onUndeclaredKey:"ignore",exactOptionalPropertyTypes:!0,numberAllowsNaN:!1,dateAllowsInvalid:!1,onFail:null,keywords:{},toJsonSchema:RT.defaultConfig}));z.resolvedConfig=fF(z.defaultConfig,z.config);var dJ={...gJ,alias:gF.Node,domain:gW.Node,unit:v2.Node,proto:mF.Node,union:y2.Node,morph:q2.Node,intersection:P2.Node,divisor:R2.Node,pattern:I2.Node,predicate:Q2.Node,required:b2.Node,optional:bF.Node,index:x2.Node,sequence:h2.Node,structure:m2.Node};class e0 extends s1{get[tT](){return"module"}}var o2=(T,_)=>new e0(c(T,(F,W)=>[F,P(W,"module")?o2(W,_):_.bindReference(W)]));var nA=(T)=>XT(T)?T:("branches"in T)&&XT(T.branches)?T.branches:void 0,rA=(T,_)=>E(`Node of kind ${_} is not valid as a ${T} definition`),Q6=(T)=>`#${T} duplicates public alias ${T}`,u2={};z.ambient??={};var R6,z6="function $",sA=(T)=>V6(T,K6(T)),V6=(T,_)=>{let F=_.write(z6,4),W=_.compile()();for(let J of T){if(J.precompilation)continue;if(J.traverseAllows=W[`${J.id}Allows`].bind(W),J.isRoot()&&!J.allowsRequiresContext)J.allows=J.traverseAllows;if(J.traverseApply=W[`${J.id}Apply`].bind(W),W[`${J.id}Optimistic`])J.traverseOptimistic=W[`${J.id}Optimistic`].bind(W);J.precompilation=F}},K6=(T)=>new kW().return(T.reduce((_,F)=>{let W=new kF({kind:"Allows"}).indent();F.compile(W);let J=W.write(`${F.id}Allows`),Y=new kF({kind:"Apply"}).indent();F.compile(Y);let $=Y.write(`${F.id}Apply`),Z=`${_}${J},
|
|
44
44
|
${$},
|
|
45
|
-
`;if(!F.hasKind("union"))return Z;let G=new
|
|
45
|
+
`;if(!F.hasKind("union"))return Z;let G=new kF({kind:"Allows",optimistic:!0}).indent();F.compile(G);let X=G.write(`${F.id}Optimistic`);return`${Z}${X},
|
|
46
46
|
`},`{
|
|
47
|
-
`)+"}");class hW{config;resolvedConfig;name;get[tT](){return"scope"}referencesById={};references=[];resolutions={};exportedNames=[];aliases={};resolved=!1;nodesByHash={};intrinsic;constructor(T,_){if(this.config=CF(R.config,_),this.resolvedConfig=CF(R.resolvedConfig,_),this.name=this.resolvedConfig.name??`anonymousScope${Object.keys(g2).length}`,this.name in g2)z(`A Scope already named ${this.name} already exists`);g2[this.name]=this;let F=Object.entries(T).map((W)=>this.preparseOwnAliasEntry(...W));for(let[W,J]of F){let Y=W;if(W[0]==="#"){if(Y=W.slice(1),Y in this.aliases)z(U6(Y));this.aliases[Y]=J}else{if(Y in this.aliases)z(U6(W));this.aliases[Y]=J,this.exportedNames.push(Y)}if(!q(J,"module")&&!q(J,"generic")&&!W0(J)){let $=this.preparseOwnDefinitionFormat(J,{alias:Y});this.resolutions[Y]=q($,"root")?this.bindReference($):this.createParseContext($).id}}O6??=this.node("union",{branches:["string","number","object","bigint","symbol",{unit:!0},{unit:!1},{unit:void 0},{unit:null}]},{prereduced:!0}),this.nodesByHash[O6.hash]=this.node("intersection",{},{prereduced:!0}),this.intrinsic=R.intrinsic?c(R.intrinsic,(W,J)=>W.startsWith("json")?[]:[W,this.bindReference(J)]):{}}cacheGetter(T,_){return Object.defineProperty(this,T,{value:_}),_}get internal(){return this}_json;get json(){if(!this._json)this.export();return this._json}defineSchema(T){return T}generic=(...T)=>{let _=this;return(F,W)=>new X0(T,W?new fW(F):F,_,_,W??null)};units=(T,_)=>{let F=[];for(let J of T)if(!F.includes(J))F.push(J);let W=F.map((J)=>this.node("unit",{unit:J},_));return this.node("union",W,{..._,prereduced:!0})};lazyResolutions=[];lazilyResolve(T,_){let F=this.node("alias",{reference:_??"synthetic",resolve:T},{prereduced:!0});if(!this.resolved)this.lazyResolutions.push(F);return F}schema=(T,_)=>this.finalize(this.parseSchema(T,_));parseSchema=(T,_)=>this.node(qF(T),T,_);preparseNode(T,_,F){let W=typeof T==="string"?T:qF(_,T);if(UT(_)&&_.kind===W)return _;if(W==="alias"&&!F?.prereduced){let{reference:$}=xF.implementation.normalize(_,this);if($.startsWith("$")){let Z=this.resolveRoot($.slice(1));_=Z,W=Z.kind}}else if(W==="union"&&T_(_,"object")){let $=cH(_);if($?.length===1)_=$[0],W=qF(_)}if(UT(_)&&_.kind===W)return _;let Y=t0[W].normalize?.(_,this)??_;if(UT(Y))return Y.kind===W?Y:dH(W,Y.kind);return{...F,$:this,kind:W,def:Y,prefix:F.alias??W}}bindReference(T){let _;if(UT(T))_=T.$===this?T:new T.constructor(T.attachments,this);else _=T.$===this?T:new X0(T.params,T.bodyDef,T.$,this,T.hkt);if(!this.resolved)Object.assign(this.referencesById,_.referencesById);return _}resolveRoot(T){return this.maybeResolveRoot(T)??z(u2(T))}maybeResolveRoot(T){let _=this.maybeResolve(T);if(q(_,"generic"))return;return _}maybeResolveSubalias(T){return m2(this.aliases,T)??m2(this.ambient,T)}get ambient(){return R.ambient}maybeResolve(T){let _=this.resolutions[T];if(_){if(typeof _!=="string")return this.bindReference(_);let W=iT[_];if(q(W,"root"))return this.resolutions[T]=W;if(q(W,"context")){if(W.phase==="resolving")return this.node("alias",{reference:`$${T}`},{prereduced:!0});if(W.phase==="resolved")return e(`Unexpected resolved context for was uncached by its scope: ${d(W)}`);W.phase="resolving";let J=this.bindReference(this.parseOwnDefinitionFormat(W.def,W));return W.phase="resolved",iT[J.id]=J,iT[W.id]=J,this.resolutions[T]=J}return e(`Unexpected nodesById entry for ${_}: ${d(W)}`)}let F=this.aliases[T]??this.ambient?.[T];if(!F)return this.maybeResolveSubalias(T);if(F=this.normalizeRootScopeValue(F),q(F,"generic"))return this.resolutions[T]=this.bindReference(F);if(q(F,"module")){if(!F.root)z(K6(T));return this.resolutions[T]=this.bindReference(F.root)}return this.resolutions[T]=this.parse(F,{alias:T})}createParseContext(T){let _=T.id??L2(T.prefix);return iT[_]=Object.assign(T,{[tT]:"context",$:this,id:_,phase:"unresolved"})}traversal(T){return new f_(T,this.resolvedConfig)}import(...T){return new r0(c(this.export(...T),(_,F)=>[`#${_}`,F]))}precompilation;_exportedResolutions;_exports;export(...T){if(!this._exports){this._exports={};for(let F of this.exportedNames){let W=this.aliases[F];this._exports[F]=q(W,"module")?p2(W,this):M6(this.maybeResolve(F))}for(let F of this.lazyResolutions)F.resolution;if(this._exportedResolutions=R6(this,this._exports),this._json=E6(this._exportedResolutions),Object.assign(this.resolutions,this._exportedResolutions),this.references=Object.values(this.referencesById),!this.resolvedConfig.jitless){let F=z6(this.references);this.precompilation=F.write(w6,4),Q6(this.references,F)}this.resolved=!0}let _=T.length?T:this.exportedNames;return new r0(c(_,(F,W)=>[W,this._exports[W]]))}resolve(T){return this.export()[T]}node=(T,_,F={})=>{let W=this.preparseNode(T,_,F);if(UT(W))return this.bindReference(W);let J=this.createParseContext(W),Y=S2(J),$=this.bindReference(Y);return iT[J.id]=$};parse=(T,_={})=>this.finalize(this.parseDefinition(T,_));parseDefinition(T,_={}){if(q(T,"root"))return this.bindReference(T);let F=this.preparseOwnDefinitionFormat(T,_);if(q(F,"root"))return this.bindReference(F);let W=this.createParseContext(F);iT[W.id]=W;let J=this.bindReference(this.parseOwnDefinitionFormat(T,W));if(J.isCyclic)J=gJ(J,W.id);return iT[W.id]=J,J}finalize(T){if(M6(T),!T.precompilation&&!this.resolvedConfig.jitless)lH(T.references);return T}}class o2 extends hW{parseOwnDefinitionFormat(T,_){return S2(_)}preparseOwnDefinitionFormat(T,_){return this.preparseNode(qF(T),T,_)}preparseOwnAliasEntry(T,_){return[T,_]}normalizeRootScopeValue(T){return T}}var M6=(T)=>{let _=T.references.filter((F)=>F.hasKind("alias"));for(let F of _){Object.assign(F.referencesById,F.resolution.referencesById);for(let W of T.references)if(F.id in W.referencesById)Object.assign(W.referencesById,F.referencesById)}return T},E6=(T)=>c(T,(_,F)=>[_,q(F,"root")||q(F,"generic")?F.json:q(F,"module")?E6(F):e(`Unexpected resolution ${d(F)}`)]),m2=(T,_)=>{let F=_.indexOf(".");if(F===-1)return;let W=_.slice(0,F),J=T[W];if(J===void 0)return;if(!q(J,"module"))return z(tH(W));let Y=_.slice(F+1),$=J[Y];if($===void 0)return m2(J,Y);if(q($,"root")||q($,"generic"))return $;if(q($,"module"))return $.root??z(K6(_));e(`Unexpected resolution for alias '${_}': ${d($)}`)},pW=(T,_)=>new o2(T,_),gF=new o2({});var R6=(T,_)=>{let F={};for(let W in _){let J=_[W];if(q(J,"module")){let Y=R6(T,J),$=c(Y,(Z,G)=>[`${W}.${Z}`,G]);Object.assign(F,$)}else if(q(J,"root")||q(J,"generic"))F[W]=J;else e(`Unexpected scope resolution ${d(J)}`)}return F},u2=(T)=>`'${T}' is unresolvable`,tH=(T)=>`'${T}' must reference a module to be accessed using dot syntax`,K6=(T)=>`Reference to submodule '${T}' must specify an alias`;gF.export();var{schema:WT,node:s0,defineSchema:TR,generic:V_}=gF;var c2="^(?:0|[1-9]\\d*)$",iH=new RegExp(c2),WR=VT(iH);var V6=pW({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();R.intrinsic={...V6};var D6=pW({integer:{domain:"number",divisor:1},lengthBoundable:["string",Array],key:["string","symbol"],nonNegativeIntegerString:{domain:"string",pattern:c2}},{prereducedAliases:!0}).export();Object.assign(R.intrinsic,D6);var nH=pW({jsonPrimitive:["string","number",{unit:!0},{unit:!1},{unit:null}],jsonObject:{domain:"object",index:{signature:"string",value:"$jsonData"}},jsonData:["$jsonPrimitive","$jsonObject"]},{prereducedAliases:!0}).export(),b={...V6,...D6,...nH,emptyStructure:s0("structure",{},{prereduced:!0})};R.intrinsic={...b};var S6=(T)=>typeof T==="string"&&T[0]==="d"&&(T[1]==="'"||T[1]==='"')&&T.at(-1)===T[1],L6=(T)=>T.toString()!=="Invalid Date",I6=(T)=>T.slice(2,-1),d2=(T)=>`'${T}' could not be parsed by the Date constructor`,N6=(T,_)=>rH(T,_),rH=(T,_)=>{let F=new Date(T);if(L6(F))return F;let W=JJ(T);if(W!==void 0){let J=new Date(W);if(L6(J))return J}return _?z(_===!0?d2(T):_):void 0};var l2=(T,_)=>{let F=T.scanner.shiftUntil(sH[B6[_]]);if(T.scanner.lookahead==="")return T.error(eH(F,_));if(T.scanner.shift(),_==="/"){try{new RegExp(F)}catch(W){z(String(W))}T.root=T.ctx.$.node("intersection",{domain:"string",pattern:F},{prereduced:!0})}else if(qT(_,t2))T.root=T.ctx.$.node("unit",{unit:F});else{let W=N6(F,d2(F));T.root=T.ctx.$.node("unit",{meta:F,unit:W})}},t2={"'":1,'"':1},C6={"/":1,"'":1,'"':1},B6={"d'":"'",'d"':'"',"'":"'",'"':'"',"/":"/"},sH={"'":(T)=>T.lookahead==="'",'"':(T)=>T.lookahead==='"',"/":(T)=>T.lookahead==="/"},aH={'"':"double-quote","'":"single-quote","/":"forward slash"},eH=(T,_)=>`${_}${T} requires a closing ${aH[B6[_]]}`;var k6=(T)=>`Private type references should not include '#'. Use '${T}' instead.`,gW="Optional definitions like 'string?' are only valid as properties in an object or tuple",mW="Defaultable definitions like 'number = 0' are only valid as properties in an object or tuple";var f6={">":!0,">=":!0},q6={"<":!0,"<=":!0};var a0={"<":">",">":"<","<=":">=",">=":"<=","==":"=="},P6=(T)=>`Unmatched )${T===""?"":` before ${T}`}`,oW=(T)=>`Missing ${T}`,j6=(T,_)=>`Left bounds are only valid when paired with right bounds (try ...${_}${T})`,uW=(T)=>`Left-bounded expressions must specify their limits using < or <= (was ${T})`,y6=(T,_,F,W)=>`An expression may have at most one left bound (parsed ${T}${a0[_]}, ${F}${a0[W]})`;var v6=(T,_,F)=>b6(T,_,F,[]),b6=(T,_,F,W)=>{let J=F.parseUntilFinalizer();if(W.push(J.root),J.finalizer===">"){if(W.length!==_.params.length)return F.error(i2(T,_.names,W.map((Y)=>Y.expression)));return W}if(J.finalizer===",")return b6(T,_,F,W);return J.error(oW(">"))},i2=(T,_,F)=>`${T}<${_.join(", ")}> requires exactly ${_.length} args (got ${F.length}${F.length===0?"":`: ${F.join(", ")}`})`;var n2=(T)=>{let _=T.scanner.shiftUntilNextTerminator();if(_==="keyof")T.addPrefix("keyof");else T.root=_A(T,_)},TA=(T,_,F)=>{if(F.scanner.shiftUntilNonWhitespace(),F.scanner.shift()!=="<")return F.error(i2(T,_.names,[]));let J=v6(T,_,F);return _(...J)},_A=(T,_)=>FA(T,_)??WA(T,_)??T.error(_===""?T.scanner.lookahead==="#"?k6(T.shiftedByOne().scanner.shiftUntilNextTerminator()):r2(T):u2(_)),FA=(T,_)=>{if(T.ctx.args?.[_]){let W=T.ctx.args[_];if(typeof W!=="string")return W;return T.ctx.$.node("alias",{reference:W},{prereduced:!0})}let F=T.ctx.$.maybeResolve(_);if(q(F,"root"))return F;if(F===void 0)return;if(q(F,"generic"))return TA(_,F,T);return z(`Unexpected resolution ${d(F)}`)},WA=(T,_)=>{let F=YJ(_);if(F!==void 0)return T.ctx.$.node("unit",{unit:F});let W=ZJ(_);if(W!==void 0)return T.ctx.$.node("unit",{unit:W})},r2=(T)=>{let _=T.previousOperator();return _?s2(_,T.scanner.unscanned):JA(T.scanner.unscanned)},s2=(T,_="")=>`Token '${T}' requires a right operand${_?` before '${_}'`:""}`,JA=(T)=>`Expected an expression${T?` before '${T}'`:""}`;var a2=(T)=>T.scanner.lookahead===""?T.error(r2(T)):T.scanner.lookahead==="("?T.shiftedByOne().reduceGroupOpen():T.scanner.lookaheadIsIn(C6)?l2(T,T.scanner.shift()):T.scanner.lookaheadIsIn(J0)?a2(T.shiftedByOne()):T.scanner.lookahead==="d"?T.scanner.nextLookahead in t2?l2(T,`${T.scanner.shift()}${T.scanner.shift()}`):n2(T):n2(T);class r_ extends W2{shiftUntilNextTerminator(){return this.shiftUntilNonWhitespace(),this.shiftUntil(()=>(this.lookahead in r_.terminatingChars))}static terminatingChars={"<":1,">":1,"=":1,"|":1,"&":1,")":1,"[":1,"%":1,",":1,":":1,"?":1,"#":1,...J0};static finalizingLookaheads={">":1,",":1,"":1,"=":1,"?":1};static lookaheadIsFinalizing=(T,_)=>T===">"?_[0]==="="?_[1]==="=":_.trimStart()===""||qT(_.trimStart()[0],r_.terminatingChars):T==="="?_[0]!=="=":T===","||T==="?"}var h6=(T,_)=>{let F=YA(T,_);if(T.root.hasKind("unit")){if(typeof T.root.unit==="number"){T.reduceLeftBound(T.root.unit,F),T.unsetRoot();return}if(T.root.unit instanceof Date){let W=`d'${T.root.description??T.root.unit.toISOString()}'`;T.unsetRoot(),T.reduceLeftBound(W,F);return}}return ZA(T,F)},p6={"<":1,">":1,"=":1},YA=(T,_)=>T.scanner.lookaheadIs("=")?`${_}${T.scanner.shift()}`:_;var x6=(T,_,F,W)=>{if(F.extends(R.intrinsic.number)){if(typeof _!=="number")return z(e2(T,_,W));return T==="=="?["min","max"]:T[0]===">"?["min"]:["max"]}if(F.extends(R.intrinsic.lengthBoundable)){if(typeof _!=="number")return z(e2(T,_,W));return T==="=="?["exactLength"]:T[0]===">"?["minLength"]:["maxLength"]}if(F.extends(R.intrinsic.Date))return T==="=="?["after","before"]:T[0]===">"?["after"]:["before"];return z(CJ(F.expression))},$A=(T)=>({rule:S6(T.limit)?I6(T.limit):T.limit,exclusive:T.comparator.length===1}),ZA=(T,_)=>{let F=T.unsetRoot(),W=T.scanner.location;T.parseOperand();let J=T.unsetRoot(),Y=T.scanner.sliceChars(W,T.scanner.location);if(T.root=F,!J.hasKind("unit")||typeof J.unit!=="number"&&!(J.unit instanceof Date))return T.error(e2(_,Y,"right"));let $=J.unit,Z=_.length===1,G=x6(_,typeof $==="number"?$:Y,F,"right");for(let U of G)T.constrainRoot(U,_==="=="?{rule:$}:{rule:$,exclusive:Z});if(!T.branches.leftBound)return;if(!qT(_,q6))return T.error(uW(_));let X=x6(T.branches.leftBound.comparator,T.branches.leftBound.limit,F,"left");T.constrainRoot(X[0],$A(T.branches.leftBound)),T.branches.leftBound=null},e2=(T,_,F)=>`Comparator ${F==="left"?a0[T]:T} must be ${F==="left"?"preceded":"followed"} by a corresponding literal (was ${_})`;var g6=(T)=>{T.scanner.shiftUntilNonWhitespace();let _=T.scanner.shiftUntilNextTerminator();T.root=T.root.brand(_)};var o6=(T)=>{let _=T.scanner.shiftUntilNextTerminator(),F=$J(_,{errorOnFail:m6(_)});if(F===0)T.error(m6(0));T.root=T.root.constrain("divisor",F)},m6=(T)=>`% operator must be followed by a non-zero integer literal (was ${T})`;var T4=(T)=>{let _=T.scanner.shift();return _===""?T.finalize(""):_==="["?T.scanner.shift()==="]"?T.setRoot(T.root.array()):T.error(XA):_==="|"?T.scanner.lookahead===">"?T.shiftedByOne().pushRootToBranch("|>"):T.pushRootToBranch(_):_==="&"?T.pushRootToBranch(_):_===")"?T.finalizeGroup():r_.lookaheadIsFinalizing(_,T.scanner.unscanned)?T.finalize(_):qT(_,p6)?h6(T,_):_==="%"?o6(T):_==="#"?g6(T):(_ in J0)?T4(T):T.error(cW(_))},cW=(T,_="")=>`'${T}' is not allowed here${_&&` (should be ${_})`}`,XA="Missing expected ']'";var u6=(T)=>{let _=T.unsetRoot();T.parseOperand();let F=T.unsetRoot();if(!F.hasKind("unit"))return T.error(GA(F.expression));let W=F.unit instanceof Date?()=>new Date(F.unit):F.unit;return[_,"=",W]},GA=(T)=>`Default value '${T}' must a literal value`;var _4=(T,_)=>{let F=_.$.maybeResolveRoot(T);if(F)return F;if(T.endsWith("[]")){let Y=_.$.maybeResolveRoot(T.slice(0,-2));if(Y)return Y.array()}let W=new e0(new r_(T),_),J=HA(W);if(W.finalizer===">")z(cW(">"));return J},HA=(T)=>{T.parseOperand();let _=mF(T).root;if(!_)return e(`Root was unexpectedly unset after parsing string '${T.scanner.scanned}'`);if(T.finalizer==="=")_=u6(T);else if(T.finalizer==="?")_=[_,"?"];if(T.scanner.shiftUntilNonWhitespace(),T.scanner.lookahead)z(cW(T.scanner.lookahead));return _},mF=(T)=>{while(T.finalizer===void 0)AA(T);return T},AA=(T)=>T.hasRoot()?T.parseOperator():T.parseOperand();class e0{root;branches={prefixes:[],leftBound:null,intersection:null,union:null,pipe:null};finalizer;groups=[];scanner;ctx;constructor(T,_){this.scanner=T,this.ctx=_}error(T){return z(T)}hasRoot(){return this.root!==void 0}setRoot(T){this.root=T}unsetRoot(){let T=this.root;return this.root=void 0,T}constrainRoot(...T){this.root=this.root.constrain(T[0],T[1])}finalize(T){if(this.groups.length)return this.error(oW(")"));this.finalizeBranches(),this.finalizer=T}reduceLeftBound(T,_){let F=a0[_];if(!qT(F,f6))return this.error(uW(_));if(this.branches.leftBound)return this.error(y6(this.branches.leftBound.limit,this.branches.leftBound.comparator,T,F));this.branches.leftBound={comparator:F,limit:T}}finalizeBranches(){if(this.assertRangeUnset(),this.branches.pipe){this.pushRootToBranch("|>"),this.root=this.branches.pipe;return}if(this.branches.union){this.pushRootToBranch("|"),this.root=this.branches.union;return}if(this.branches.intersection){this.pushRootToBranch("&"),this.root=this.branches.intersection;return}this.applyPrefixes()}finalizeGroup(){this.finalizeBranches();let T=this.groups.pop();if(!T)return this.error(P6(this.scanner.unscanned));this.branches=T}addPrefix(T){this.branches.prefixes.push(T)}applyPrefixes(){while(this.branches.prefixes.length){let T=this.branches.prefixes.pop();this.root=T==="keyof"?this.root.keyof():e(`Unexpected prefix '${T}'`)}}pushRootToBranch(T){this.assertRangeUnset(),this.applyPrefixes();let _=this.root;if(this.root=void 0,this.branches.intersection=this.branches.intersection?.rawAnd(_)??_,T==="&")return;if(this.branches.union=this.branches.union?.rawOr(this.branches.intersection)??this.branches.intersection,this.branches.intersection=null,T==="|")return;this.branches.pipe=this.branches.pipe?.rawPipeOnce(this.branches.union)??this.branches.union,this.branches.union=null}parseUntilFinalizer(){return mF(new e0(this.scanner,this.ctx))}parseOperator(){return T4(this)}parseOperand(){return a2(this)}assertRangeUnset(){if(this.branches.leftBound)return this.error(j6(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 UA="An empty string is not a valid generic parameter name",dW=(T,_,F)=>{T.shiftUntilNonWhitespace();let W=T.shiftUntilNextTerminator();if(W===""){if(T.lookahead===""&&_.length)return _;return z(UA)}return T.shiftUntilNonWhitespace(),OA(T,W,_,F)},c6="extends ",OA=(T,_,F,W)=>{if(T.shiftUntilNonWhitespace(),T.unscanned.startsWith(c6))T.jumpForward(c6.length);else{if(T.lookahead===",")T.shift();return F.push(_),dW(T,F,W)}let J=mF(new e0(T,W));return F.push([_,J.root]),dW(T,F,W)};class F4 extends k_{$;constructor(T){super((..._)=>new oF(T)(..._),{bind:T});this.$=T}in(T){return new oF(this.$,T===void 0?void 0:this.$.parse(T))}at(T,_){return new oF(this.$).at(T,_)}case(T,_){return new oF(this.$).case(T,_)}}class oF extends k_{$;in;key;branches=[];constructor(T,_){super((F)=>this.caseEntries(Object.entries(F).map(([W,J])=>W==="default"?[W,J]:[this.$.parse(W),J])));this.$=T,this.in=_}at(T,_){if(this.key)z(wA);if(this.branches.length)z(MA);return this.key=T,_?this.match(_):this}case(T,_){return this.caseEntry(this.$.parse(T),_)}caseEntry(T,_){let W=(this.key?this.$.parse({[this.key]:T}):T).pipe(_);return this.branches.push(W),this}match(T){return this(T)}strings(T){return this.caseEntries(Object.entries(T).map(([_,F])=>_==="default"?[_,F]:[this.$.node("unit",{unit:_}),F]))}caseEntries(T){for(let _=0;_<T.length;_++){let[F,W]=T[_];if(F==="default"){if(_!==T.length-1)z("default may only be specified as the last key of a switch definition");return this.default(W)}if(typeof W!=="function")return z(`Value for case "${F}" must be a function (was ${fT(W)})`);this.caseEntry(F,W)}return this}default(T){if(typeof T==="function")this.case(b.unknown,T);let _={branches:this.branches,ordered:!0};if(T==="never"||T==="assert")_.meta={onFail:d6};let F=this.$.node("union",_);if(!this.in)return this.$.finalize(F);let W=this.in.pipe(F);if(T==="never"||T==="assert")W=W.configureReferences({onFail:d6},"self");return this.$.finalize(W)}}var d6=(T)=>T.throw(),MA="A key matcher must be specified before the first case i.e. match.at('foo') or match.in<object>().at('bar')",wA="At most one key matcher may be specified per expression";var lW=(T,_)=>{if(ZT(T)){if(T[1]==="=")return[_.$.parseOwnDefinitionFormat(T[0],_),"=",T[2]];if(T[1]==="?")return[_.$.parseOwnDefinitionFormat(T[0],_),"?"]}return tW(T,_)},l6="Only required keys may make their values optional, e.g. { [mySymbol]: ['number', '?'] }",t6="Only required keys may specify default values, e.g. { value: 'number = 0' }";var i6=(T,_)=>{let F,W={},J=D0(T);for(let[$,Z]of J){let G=EA($);if(G.kind==="spread"){if(!h_(W))return z(zA);let V=_.$.parseOwnDefinitionFormat(Z,_);if(V.equals(b.object))continue;if(!V.hasKind("intersection")||!V.basis?.equals(b.object))return z(RA(V.expression));F=V.structure;continue}if(G.kind==="undeclared"){if(Z!=="reject"&&Z!=="delete"&&Z!=="ignore")z(QA(Z));W.undeclared=Z;continue}let X=lW(Z,_),U=G;if(G.kind==="required"){if(!ZT(X))W4(W,"required",{key:G.normalized,value:X},_);else W4(W,"optional",X[1]==="="?{key:G.normalized,value:X[0],default:X[2]}:{key:G.normalized,value:X[0]},_);continue}if(ZT(X)){if(X[1]==="?")z(l6);if(X[1]==="=")z(t6)}if(G.kind==="optional"){W4(W,"optional",{key:G.normalized,value:X},_);continue}let M=_.$.parseOwnDefinitionFormat(U.normalized,_),Q=xW(M,X,_.$);if(Q.index)W.index=s(W.index,Q.index);if(Q.required)W.required=s(W.required,Q.required)}let Y=_.$.node("structure",W);return _.$.parseSchema({domain:"object",structure:F?.merge(Y)??Y})},W4=(T,_,F,W)=>{T[_]=s(T[_],W.$.node(_,F))},QA=(T)=>`Value of '+' key must be 'reject', 'delete', or 'ignore' (was ${d(T)})`,zA="Spread operator may only be used as the first key in an object",EA=(T)=>typeof T==="symbol"?{kind:"required",normalized:T}:T.at(-1)==="?"?T.at(-2)===KF?{kind:"required",normalized:`${T.slice(0,-2)}?`}:{kind:"optional",normalized:T.slice(0,-1)}:T[0]==="["&&T.at(-1)==="]"?{kind:"index",normalized:T.slice(1,-1)}:T[0]===KF&&T[1]==="["&&T.at(-1)==="]"?{kind:"required",normalized:T.slice(1)}:T==="..."?{kind:"spread"}:T==="+"?{kind:"undeclared"}:{kind:"required",normalized:T==="\\..."?"...":T==="\\+"?"+":T},RA=(T)=>`Spread operand must resolve to an object literal type (was ${T})`;var r6=(T,_)=>kA(T)?TY[T[0]](T,_):CA(T)?e6[T[1]](T,_):null,KA=(T,_)=>_.$.parseOwnDefinitionFormat(T[1],_).keyof(),J4=(T,_)=>{if(T[2]===void 0)return z(s2(T[1],""));let F=_.$.parseOwnDefinitionFormat(T[0],_),W=_.$.parseOwnDefinitionFormat(T[2],_);if(T[1]==="|")return _.$.node("union",{branches:[F,W]});let J=T[1]==="&"?J_(F,W,_.$):fF(F,W,_.$);if(J instanceof I)return J.throw();return J},VA=(T,_)=>_.$.parseOwnDefinitionFormat(T[0],_).array(),DA=(T,_)=>{if(typeof T[2]!=="function")return z(s6("=>",T[2]));return _.$.parseOwnDefinitionFormat(T[0],_).pipe(T[2])},s6=(T,_)=>`${T===":"?"Narrow":"Morph"} expression requires a function following '${T}' (was ${typeof _})`,LA=(T,_)=>{if(typeof T[2]!=="function")return z(s6(":",T[2]));return _.$.parseOwnDefinitionFormat(T[0],_).constrain("predicate",T[2])},SA=(T,_)=>_.$.parseOwnDefinitionFormat(T[0],_).configureReferences(T[2],"shallow"),a6=(T)=>T,IA=a6({"[]":VA,"?":()=>z(gW)}),NA=a6({"|":J4,"&":J4,":":LA,"=>":DA,"|>":J4,"@":SA,"=":()=>z(mW)}),e6={...IA,...NA},CA=(T)=>e6[T[1]]!==void 0,BA=(T)=>T,TY=BA({keyof:KA,instanceof:(T,_)=>{if(typeof T[1]!=="function")return z(n6(EF(T[1])));let F=T.slice(1).map((W)=>typeof W==="function"?_.$.node("proto",{proto:W}):z(n6(EF(W))));return F.length===1?F[0]:_.$.node("union",{branches:F})},"===":(T,_)=>_.$.units(T.slice(1))}),kA=(T)=>TY[T[0]]!==void 0,n6=(T)=>`Expected a constructor following 'instanceof' operator (was ${T})`;var WY=(T,_)=>{let F=[{}],W=0;while(W<T.length){let J=!1;if(T[W]==="..."&&W<T.length-1)J=!0,W++;let Y=lW(T[W],_),[$,Z,G]=!ZT(Y)?[Y]:Y;if(W++,J){if(!$.extends(R.intrinsic.Array))return z(PA($.expression));F=F.flatMap((X)=>$.distribute((U)=>qA(NW(X),U)))}else F=F.map((X)=>{if(Z==="?")return JY(X,$);if(Z==="=")return fA(X,$,G);return Y4(X,$)})}return _.$.parseSchema(F.map((J)=>h_(J)?{proto:Array,exactLength:0}:{proto:Array,sequence:J}))},Y4=(T,_)=>{if(T.defaultables||T.optionals)return z(T.variadic?b2:jA);if(T.variadic)T.postfix=s(T.postfix,_);else T.prefix=s(T.prefix,_);return T},JY=(T,_)=>{if(T.variadic)return z(YY);return T.optionals=s(T.optionals,_),T},fA=(T,_,F)=>{if(T.variadic)return z(YY);if(T.optionals)return z(yA);return T.defaultables=s(T.defaultables,[[_,F]]),T},_Y=(T,_)=>{if(T.postfix)z(FY);if(T.variadic){if(!T.variadic.equals(_))z(FY)}else T.variadic=_.internal;return T},qA=(T,_)=>{let F=_.select({method:"find",kind:"sequence"});if(!F)return _Y(T,R.intrinsic.unknown);if(F.prefix)for(let W of F.prefix)Y4(T,W);if(F.optionals)for(let W of F.optionals)JY(T,W);if(F.variadic)_Y(T,F.variadic);if(F.postfix)for(let W of F.postfix)Y4(T,W);return T},PA=(T)=>`Spread element must be an array (was ${T})`,FY="A tuple may have at most one variadic element",jA="A required element may not follow an optional element",YY="An optional element may not follow a variadic element";var yA="A defaultable element may not follow an optional element without a default";var vA={},tW=(T,_)=>{if(typeof T==="string"){if(_.args&&Object.keys(_.args).some((W)=>T.includes(W)))return _4(T,_);let F=vA[_.$.name]??={};return F[T]??=_4(T,_)}return T_(T,"object")?bA(T,_):z($4(fT(T)))},bA=(T,_)=>{let F=zF(T);switch(F){case void 0:if(q(T,"root"))return T;return i6(T,_);case"Array":return xA(T,_);case"RegExp":return _.$.node("intersection",{domain:"string",pattern:T},{prereduced:!0});case"Function":{let W=W0(T)?T():T;if(q(W,"root"))return W;return z($4("Function"))}default:return z($4(F??d(T)))}},xA=(T,_)=>r6(T,_)??WY(T,_),$4=(T)=>`Type definitions must be strings or objects (was ${T})`;class Z4 extends k_{constructor(T){let _=Object.assign({errors:F_,hkt:uT,$:T,raw:T.parse,module:T.constructor.module,scope:T.constructor.scope,define:T.define,match:T.match,generic:T.generic,schema:T.schema,keywords:T.ambient,unit:T.unit,enumerated:T.enumerated,instanceOf:T.instanceOf,valueOf:T.valueOf,or:T.or,and:T.and,merge:T.merge,pipe:T.pipe},T.ambientAttachments);super((...F)=>{if(F.length===1)return T.parse(F[0]);if(F.length===2&&typeof F[0]==="string"&&F[0][0]==="<"&&F[0].at(-1)===">"){let W=F[0].slice(1,-1),J=T.parseGenericParams(W,{});return new X0(J,F[1],T,T,null)}return T.parse(F)},{bind:T,attach:_})}}var TF=R;class iW extends hW{get ambientAttachments(){if(!TF.typeAttachments)return;return this.cacheGetter("ambientAttachments",c(TF.typeAttachments,(T,_)=>[T,this.bindReference(_)]))}preparseOwnAliasEntry(T,_){let F=T.indexOf("<");if(F===-1){if(q(_,"module")||q(_,"generic"))return[T,_];let Y=this.name==="ark"?T:T==="root"?this.name:`${this.name}.${T}`,$=this.resolvedConfig.keywords?.[Y];if($)_=[_,"@",$];return[T,_]}if(T.at(-1)!==">")z("'>' must be the last character of a generic declaration in a scope");let W=T.slice(0,F),J=T.slice(F+1,-1);return[W,()=>{let Y=this.parseGenericParams(J,{alias:W});return SJ(Y,_,this)}]}parseGenericParams(T,_){return dW(new r_(T),[],this.createParseContext({..._,def:T,prefix:"generic"}))}normalizeRootScopeValue(T){if(W0(T)&&!q(T,"generic"))return T();return T}preparseOwnDefinitionFormat(T,_){return{..._,def:T,prefix:_.alias??"type"}}parseOwnDefinitionFormat(T,_){if(!(_.alias&&(_.alias in this.aliases))&&!_.args)_.args={this:_.id};let W=tW(T,_);if(ZT(W)){if(W[1]==="=")return z(mW);if(W[1]==="?")return z(gW)}return W}unit=(T)=>this.units([T]);valueOf=(T)=>this.units(c8(T));enumerated=(...T)=>this.units(T);instanceOf=(T)=>this.node("proto",{proto:T},{prereduced:!0});or=(...T)=>this.schema(T.map((_)=>this.parse(_)));and=(...T)=>T.reduce((_,F)=>_.and(this.parse(F)),this.intrinsic.unknown);merge=(...T)=>T.reduce((_,F)=>_.merge(this.parse(F)),this.intrinsic.object);pipe=(...T)=>this.intrinsic.unknown.pipe(...T);match=new F4(this);declare=()=>({type:this.type});define(T){return T}type=new Z4(this);static scope=(T,_={})=>new iW(T,_);static module=(T,_={})=>this.scope(T,_).export()}var X4=Object.assign(iW.scope,{define:(T)=>T}),n=iW;class $Y extends uT{description='merge an object\'s properties onto another like `Merge(User, { isAdmin: "true" })`'}var hA=V_(["base",b.object],["props",b.object])((T)=>T.base.merge(T.props),$Y),ZY=n.module({Key:b.key,Merge:hA});class XY extends uT{}var pA=V_("element")((T)=>{let _=T.element.exclude(b.Array),F=_.array();return _.rawOr(F).pipe(F0).distribute((W)=>W.assertHasKind("morph").declareOut(F),WT)},XY),GY=n.module({root:b.Array,readonly:"root",index:b.nonNegativeIntegerString,liftFrom:pA},{name:"Array"});var G4=WT(["string",S0.FileConstructor]),gA=G4.rawOr(G4.array()),HY=WT({meta:"an object representing parsed form data",domain:"object",index:{signature:"string",value:gA}}),AY=n.module({root:["instanceof",FormData],value:G4,parsed:HY,parse:WT({in:FormData,morphs:(T)=>{let _={};for(let[F,W]of T)if(F in _){let J=_[F];if(typeof J==="string"||J instanceof S0.FileConstructor)_[F]=[J,W];else J.push(W)}else _[F]=W;return _},declaredOut:HY})},{name:"FormData"});var UY=n.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 mA={Boolean:1,Number:1,String:1},OY=n.module({...c({...n1,...s1},(T,_)=>(T in mA)?[]:[T,["instanceof",_]]),Array:GY,TypedArray:UY,FormData:AY});var oA=WT({domain:{domain:"number",meta:"a number representing a Unix timestamp"},divisor:{rule:1,meta:"an integer representing a Unix timestamp"},min:{rule:-8640000000000000,meta:"a Unix timestamp after -8640000000000000"},max:{rule:8640000000000000,meta:"a Unix timestamp before 8640000000000000"},meta:"an integer representing a safe Unix timestamp"}),uA=WT({domain:"number",divisor:1}),nW=n.module({root:b.number,integer:uA,epoch:oA,safe:WT({domain:{domain:"number",numberAllowsNaN:!1},min:Number.MIN_SAFE_INTEGER,max:Number.MAX_SAFE_INTEGER}),NaN:["===",Number.NaN],Infinity:["===",Number.POSITIVE_INFINITY],NegativeInfinity:["===",Number.NEGATIVE_INFINITY]},{name:"number"});var ET=(T,_,F)=>{let W={domain:"string",pattern:{rule:T.source,flags:T.flags,meta:_}};if(F)W.meta={format:F};return s0("intersection",W)},MY=ET(VF,"a well-formed integer string"),NY=n.module({root:MY,parse:WT({in:MY,morphs:(T,_)=>{let F=Number.parseInt(T);return Number.isSafeInteger(F)?F:_.error("an integer in the range Number.MIN_SAFE_INTEGER to Number.MAX_SAFE_INTEGER")},declaredOut:b.integer})},{name:"string.integer"}),cA=ET(/^[\dA-Fa-f]+$/,"hex characters only"),dA=n.module({root:ET(/^(?:[\d+/A-Za-z]{4})*(?:[\d+/A-Za-z]{2}==|[\d+/A-Za-z]{3}=)?$/,"base64-encoded"),url:ET(/^(?:[\w-]{4})*(?:[\w-]{2}(?:==|%3D%3D)?|[\w-]{3}(?:=|%3D)?)?$/,"base64url-encoded")},{name:"string.base64"}),wY=ET(/^[A-Z].*$/,"capitalized"),lA=n.module({root:WT({in:"string",morphs:(T)=>T.charAt(0).toUpperCase()+T.slice(1),declaredOut:wY}),preformatted:wY},{name:"string.capitalize"}),tA=(T)=>{let _=T.replaceAll(/[ -]+/g,""),F=0,W,J,Y=!1;for(let $=_.length-1;$>=0;$--){if(W=_.substring($,$+1),J=Number.parseInt(W,10),Y)J*=2,F+=J>=10?J%10+1:J;else F+=J;Y=!Y}return!!(F%10===0?_:!1)},iA=/^(?: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}))$/,nA=WT({domain:"string",pattern:{meta:"a credit card number",rule:iA.source},predicate:{meta:"a credit card number",predicate:tA}});var rA=/^([+-]?\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 sA=(T)=>!Number.isNaN(new Date(T).valueOf()),QY=WT({domain:"string",predicate:{meta:"a parsable date",predicate:sA}}).assertHasKind("intersection"),zY=NY.root.internal.narrow((T,_)=>{let F=Number.parseInt(T),W=nW.epoch(F);if(W instanceof F_)return _.errors.merge(W),!1;return!0}).configure({description:"an integer string representing a safe Unix timestamp"},"self").assertHasKind("intersection"),aA=n.module({root:zY,parse:WT({in:zY,morphs:(T)=>new Date(T),declaredOut:b.Date})},{name:"string.date.epoch"}),EY=ET(rA,"an ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) date").internal.assertHasKind("intersection"),eA=n.module({root:EY,parse:WT({in:EY,morphs:(T)=>new Date(T),declaredOut:b.Date})},{name:"string.date.iso"}),T7=n.module({root:QY,parse:WT({declaredIn:QY,in:"string",morphs:(T,_)=>{let F=new Date(T);if(Number.isNaN(F.valueOf()))return _.error("a parsable date");return F},declaredOut:b.Date}),iso:eA,epoch:aA},{name:"string.date"}),_7=ET(/^[\w%+.-]+@[\d.A-Za-z-]+\.[A-Za-z]{2,}$/,"an email address","email"),RY="(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])",G0=`(${RY}[.]){3}${RY}`,F7=new RegExp(`^${G0}$`),NT="(?:[0-9a-fA-F]{1,4})",W7=new RegExp(`^((?:${NT}:){7}(?:${NT}|:)|(?:${NT}:){6}(?:${G0}|:${NT}|:)|(?:${NT}:){5}(?::${G0}|(:${NT}){1,2}|:)|(?:${NT}:){4}(?:(:${NT}){0,1}:${G0}|(:${NT}){1,3}|:)|(?:${NT}:){3}(?:(:${NT}){0,2}:${G0}|(:${NT}){1,4}|:)|(?:${NT}:){2}(?:(:${NT}){0,3}:${G0}|(:${NT}){1,5}|:)|(?:${NT}:){1}(?:(:${NT}){0,4}:${G0}|(:${NT}){1,6}|:)|(?::((?::${NT}){0,5}:${G0}|(?::${NT}){1,7}|:)))(%[0-9a-zA-Z.]{1,})?$`),J7=n.module({root:["v4 | v6","@","an IP address"],v4:ET(F7,"an IPv4 address","ipv4"),v6:ET(W7,"an IPv6 address","ipv6")},{name:"string.ip"}),_F="a JSON string",CY=(T)=>{if(!(T instanceof SyntaxError))throw T;return`must be ${_F} (${T})`},Y7=WT({meta:_F,domain:"string",predicate:{meta:_F,predicate:(T,_)=>{try{return JSON.parse(T),!0}catch(F){return _.reject({code:"predicate",expected:_F,problem:CY(F)})}}}}),$7=(T,_)=>{if(T.length===0)return _.error({code:"predicate",expected:_F,actual:"empty"});try{return JSON.parse(T)}catch(F){return _.error({code:"predicate",expected:_F,problem:CY(F)})}},Z7=n.module({root:Y7,parse:WT({meta:"safe JSON string parser",in:"string",morphs:$7,declaredOut:b.jsonObject})},{name:"string.json"}),KY=ET(/^[a-z]*$/,"only lowercase letters"),X7=n.module({root:WT({in:"string",morphs:(T)=>T.toLowerCase(),declaredOut:KY}),preformatted:KY},{name:"string.lower"}),BY=["NFC","NFD","NFKC","NFKD"],uF=c(BY,(T,_)=>[_,WT({domain:"string",predicate:(F)=>F.normalize(_)===F,meta:`${_}-normalized unicode`})]),rW=c(BY,(T,_)=>[_,WT({in:"string",morphs:(F)=>F.normalize(_),declaredOut:uF[_]})]),G7=n.module({root:rW.NFC,preformatted:uF.NFC},{name:"string.normalize.NFC"}),H7=n.module({root:rW.NFD,preformatted:uF.NFD},{name:"string.normalize.NFD"}),A7=n.module({root:rW.NFKC,preformatted:uF.NFKC},{name:"string.normalize.NFKC"}),U7=n.module({root:rW.NFKD,preformatted:uF.NFKD},{name:"string.normalize.NFKD"}),O7=n.module({root:"NFC",NFC:G7,NFD:H7,NFKC:A7,NFKD:U7},{name:"string.normalize"}),VY=ET(LW,"a well-formed numeric string"),M7=n.module({root:VY,parse:WT({in:VY,morphs:(T)=>Number.parseFloat(T),declaredOut:b.number})},{name:"string.numeric"}),DY="a regex pattern",w7=WT({domain:"string",predicate:{meta:DY,predicate:(T,_)=>{try{return new RegExp(T),!0}catch(F){return _.reject({code:"predicate",expected:DY,problem:String(F)})}}},meta:{format:"regex"}}),Q7=/^(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-]+)*))?$/,z7=ET(Q7,"a semantic version (see https://semver.org/)"),LY=ET(/^\S.*\S$|^\S?$/,"trimmed"),E7=n.module({root:WT({in:"string",morphs:(T)=>T.trim(),declaredOut:LY}),preformatted:LY},{name:"string.trim"}),SY=ET(/^[A-Z]*$/,"only uppercase letters"),R7=n.module({root:WT({in:"string",morphs:(T)=>T.toUpperCase(),declaredOut:SY}),preformatted:SY},{name:"string.upper"}),K7=(T)=>{if(URL.canParse)return URL.canParse(T);try{return new URL(T),!0}catch{return!1}},IY=WT({domain:"string",predicate:{meta:"a URL string",predicate:K7},meta:{format:"uri"}}),V7=n.module({root:IY,parse:WT({declaredIn:IY,in:"string",morphs:(T,_)=>{try{return new URL(T)}catch{return _.error("a URL string")}},declaredOut:WT(URL)})},{name:"string.url"}),D7=n.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:ET(/^[\da-f]{8}-[\da-f]{4}-1[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv1"),v2:ET(/^[\da-f]{8}-[\da-f]{4}-2[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv2"),v3:ET(/^[\da-f]{8}-[\da-f]{4}-3[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv3"),v4:ET(/^[\da-f]{8}-[\da-f]{4}-4[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv4"),v5:ET(/^[\da-f]{8}-[\da-f]{4}-5[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv5"),v6:ET(/^[\da-f]{8}-[\da-f]{4}-6[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv6"),v7:ET(/^[\da-f]{8}-[\da-f]{4}-7[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv7"),v8:ET(/^[\da-f]{8}-[\da-f]{4}-8[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv8")},{name:"string.uuid"}),kY=n.module({root:b.string,alpha:ET(/^[A-Za-z]*$/,"only letters"),alphanumeric:ET(/^[\dA-Za-z]*$/,"only letters and digits 0-9"),hex:cA,base64:dA,capitalize:lA,creditCard:nA,date:T7,digits:ET(/^\d*$/,"only digits 0-9"),email:_7,integer:NY,ip:J7,json:Z7,lower:X7,normalize:O7,numeric:M7,regex:w7,semver:z7,trim:E7,upper:R7,url:V7,uuid:D7},{name:"string"});var fY=n.module({bigint:b.bigint,boolean:b.boolean,false:b.false,never:b.never,null:b.null,number:b.number,object:b.object,string:b.string,symbol:b.symbol,true:b.true,unknown:b.unknown,undefined:b.undefined}),qY=n.module({root:b.unknown,any:b.unknown},{name:"unknown"}),L7=n.module({root:b.jsonObject,stringify:s0("morph",{in:b.jsonObject,morphs:(T)=>JSON.stringify(T),declaredOut:b.string})},{name:"object.json"}),PY=n.module({root:b.object,json:L7},{name:"object"});class jY extends uT{description='instantiate an object from an index signature and corresponding value type like `Record("string", "number")`'}var S7=V_(["K",b.key],"V")((T)=>({domain:"object",index:{signature:T.K,value:T.V}}),jY);class yY extends uT{description='pick a set of properties from an object like `Pick(User, "name | age")`'}var I7=V_(["T",b.object],["K",b.key])((T)=>T.T.pick(T.K),yY);class vY extends uT{description='omit a set of properties from an object like `Omit(User, "age")`'}var N7=V_(["T",b.object],["K",b.key])((T)=>T.T.omit(T.K),vY);class bY extends uT{description="make all named properties of an object optional like `Partial(User)`"}var C7=V_(["T",b.object])((T)=>T.T.partial(),bY);class xY extends uT{description="make all named properties of an object required like `Required(User)`"}var B7=V_(["T",b.object])((T)=>T.T.required(),xY);class hY extends uT{description='exclude branches of a union like `Exclude("boolean", "true")`'}var k7=V_("T","U")((T)=>T.T.exclude(T.U),hY);class pY extends uT{description='extract branches of a union like `Extract("0 | false | 1", "number")`'}var f7=V_("T","U")((T)=>T.T.extract(T.U),pY),gY=n.module({Exclude:k7,Extract:f7,Omit:N7,Partial:C7,Pick:I7,Record:S7,Required:B7});var H0=X4({...fY,...gY,...OY,...ZY,string:kY,number:nW,object:PY,unknown:qY},{prereducedAliases:!0,name:"ark"}),PT=H0.export();Object.assign(TF.ambient,PT);TF.typeAttachments={string:PT.string.root,number:PT.number.root,bigint:PT.bigint,boolean:PT.boolean,symbol:PT.symbol,undefined:PT.undefined,null:PT.null,object:PT.object.root,unknown:PT.unknown.root,false:PT.false,true:PT.true,never:PT.never,arrayIndex:PT.Array.index,Key:PT.Key,Record:PT.Record,Array:PT.Array.root,Date:PT.Date};var Y_=Object.assign(H0.type,TF.typeAttachments),q7=H0.match,P7=H0.generic,ID=H0.schema,j7=H0.define,y7=H0.declare;class cF extends Promise{fate;resolve;reject;done=!1;constructor(T){let _,F;super((W,J)=>{_=W,F=J});this.resolve=_,this.reject=F,this.use(T instanceof Promise?T:new Promise(T))}pass(T,_){if(T===this.fate)this.resolve(_),this.done=!0}fail(T,_){if(T===this.fate)this.reject(_),this.done=!0}use(T){if(T instanceof Promise){let _=T;this.fate=_,_.then((F)=>{this.pass(_,F)},(F)=>{this.fail(_,F)})}else this.resolve(T),this.fate=void 0}}var uD=(T,_,F=oY.STORE)=>{return mY(F,{key:`${T.key}:JSON`,get:({get:W})=>_.toJson(W(T)),set:({set:W},J)=>{W(T,_.fromJson(J))}})};function lD(T,_,F){return H4(T,{key:`${_.key}:JSON`,get:(J)=>({get:Y})=>{let $=Y(_,J);return F.toJson($)},set:(J)=>({set:Y},$)=>{Y(_,J,F.fromJson($))}},["mutable","json"])}var dF=(T)=>JSON.parse(T),nT=(T)=>JSON.stringify(T),iD=[Array.prototype,Boolean.prototype,Number.prototype,Object.prototype,String.prototype];function m(T){while(T.child!==null)T=T.child;return T}class sW{_buffer;_index=0;constructor(T){let _;if(typeof T==="number")_=T;else _=T.length;this._buffer=Array.from({length:_})}get buffer(){return this._buffer}get index(){return this._index}add(T){this._buffer[this._index]=T,this._index=(this._index+1)%this._buffer.length}copy(){let T=new sW([...this._buffer]);return T._index=this._index,T}}var v7={atom_family:"atom",molecule_family:"molecule",mutable_atom_family:"mutable_atom",readonly_held_selector_family:"readonly_held_selector",readonly_pure_selector_family:"readonly_pure_selector",writable_held_selector_family:"writable_held_selector",writable_pure_selector_family:"writable_pure_selector"};function uY(T,_){let F=nT(_),W=`${T.key}(${F})`,J=v7[T.type],Y={key:W,type:J};return Object.assign(Y,{family:{key:T.key,subKey:F}}),Object.assign(Y,{counterfeit:!0}),Y}function lF(T){let _={key:T.key,type:T.type};if("family"in T)_.family=T.family;return _}var A4=(T)=>(_,F,W,J,...Y)=>{console[T](`${_} ${F} "${W}" ${J}`,...Y)},b7={error:A4("error"),info:A4("info"),warn:A4("warn")};class U4{logLevel;filter;logger;constructor(T,_,F=b7){this.logLevel=T,this.filter=_,this.logger=F}error=(...T)=>{let _=this.filter?.(...T)??!0;if(this.logLevel!==null){if(_===!0)this.logger.error(...T);else if(_!==!1)this.logger.error(..._)}};info=(...T)=>{let _=this.filter?.(...T)??!0;if(this.logLevel==="info"){if(_===!0)this.logger.info(...T);else if(_!==!1)this.logger.info(..._)}};warn=(...T)=>{let _=this.filter?.(...T)??!0;if(this.logLevel!=="error"&&this.logLevel!==null){if(_===!0)this.logger.warn(...T);else if(_!==!1)this.logger.warn(..._)}}}class g_{a;b;cardinality;relations=new Map;contents=new Map;isAType;isBType;isContent;makeContentKey=(T,_)=>`${T}:${_}`;warn;getRelatedKeys(T){return this.relations.get(T)}addRelation(T,_){let F=this.relations.get(T),W=this.relations.get(_);if(F)F.add(_);else F=new Set([_]),this.relations.set(T,F);if(W)W.add(T);else W=new Set([T]),this.relations.set(_,W)}deleteRelation(T,_){let F=this.relations.get(T);if(F){if(F.delete(_),F.size===0)this.relations.delete(T);let W=this.relations.get(_);if(W){if(W.delete(T),W.size===0)this.relations.delete(_)}}}replaceRelationsUnsafely(T,_){this.relations.set(T,new Set(_));for(let F of _){let W=new Set().add(T);this.relations.set(F,W)}}replaceRelationsSafely(T,_){let F=this.relations.get(T),W=this.isAType?.(T)?T:void 0,J=W===void 0?T:void 0;if(F)for(let Y of F){W??=Y,J??=Y;let $=this.relations.get(Y);if($){if($.size===1)this.relations.delete(Y);else $.delete(T);this.contents.delete(this.makeContentKey(W,J))}}this.relations.set(T,new Set(_));for(let Y of _){let $=this.relations.get(Y);if($)$.add(T);else $=new Set().add(T),this.relations.set(Y,$)}}getContentInternal(T){return this.contents.get(T)}setContent(T,_){this.contents.set(T,_)}deleteContent(T){this.contents.delete(T)}constructor(T,_){if(this.a=T.between[0],this.b=T.between[1],this.cardinality=T.cardinality,!_?.externalStore)this.relations=new Map(T.relations?.map(([F,W])=>[F,new Set(W)])),this.contents=new Map(T.contents);if(this.isAType=_?.isAType??null,this.isBType=_?.isBType??null,this.isContent=_?.isContent??null,_?.makeContentKey)this.makeContentKey=_.makeContentKey;if(_?.externalStore){let F=_.externalStore;if(this.has=(W,J)=>F.has(W,J),this.addRelation=(W,J)=>{F.addRelation(W,J)},this.deleteRelation=(W,J)=>{F.deleteRelation(W,J)},this.replaceRelationsSafely=(W,J)=>{F.replaceRelationsSafely(W,J)},this.replaceRelationsUnsafely=(W,J)=>{F.replaceRelationsUnsafely(W,J)},this.getRelatedKeys=(W)=>F.getRelatedKeys(W),F.getContent)this.getContentInternal=(W)=>{return F.getContent(W)},this.setContent=(W,J)=>{F.setContent(W,J)},this.deleteContent=(W)=>{F.deleteContent(W)};for(let[W,J]of T.relations??[]){let Y=this.isAType?.(W)?W:void 0,$=Y===void 0?W:void 0;for(let Z of J)Y??=Z,$??=Z,this.addRelation(Y,$)}for(let[W,J]of T.contents??[])this.setContent(W,J)}if(_?.warn)this.warn=_.warn}toJSON(){return{between:[this.a,this.b],cardinality:this.cardinality,relations:[...this.relations.entries()].map(([T,_])=>[T,[..._]]),contents:[...this.contents.entries()]}}set(...T){let _,F,W;switch(T.length){case 1:{let J=T[0];_=J[this.a],F=J[this.b],W=void 0;break}case 2:{let J=T[0];if(typeof J==="string")[_,F]=T;else _=J[this.a],F=J[this.b],W=T[1];break}default:{_=T[0],F=T[1],W=T[2];break}}switch(this.cardinality){case"1:1":{let J=this.getRelatedKey(_);if(J&&J!==F)this.delete(_,J)}case"1:n":{let J=this.getRelatedKey(F);if(J&&J!==_)this.delete(J,F)}break;case"n:n":}if(W){let J=this.makeContentKey(_,F);this.setContent(J,W)}return this.addRelation(_,F),this}delete(T,_){_=typeof _==="string"?_:T[this.b];let F=typeof T==="string"?T:T[this.a];if(F===void 0&&typeof _==="string"){let W=this.getRelatedKeys(_);if(W)for(let J of W)this.delete(J,_)}if(typeof F==="string"&&_===void 0){let W=this.getRelatedKeys(F);if(W)for(let J of W)this.delete(F,J)}if(typeof F==="string"&&typeof _==="string"){this.deleteRelation(F,_);let W=this.makeContentKey(F,_);this.deleteContent(W)}return this}getRelatedKey(T){let _=this.getRelatedKeys(T);if(_){if(_.size>1)this.warn?.(`${_.size} related keys were found for key "${T}": (${[..._].map((W)=>`"${W}"`).join(", ")}). Only one related key was expected.`);let F;for(let W of _){F=W;break}return F}}replaceRelations(T,_,F){let W=!Array.isArray(_),J=W?Object.keys(_):_;if(F?.reckless)this.replaceRelationsUnsafely(T,J);else this.replaceRelationsSafely(T,J);if(W)for(let Y of J){let $=this.makeContentKey(T,Y),Z=_[Y];this.setContent($,Z)}return this}getContent(T,_){let F=this.makeContentKey(T,_);return this.getContentInternal(F)}getRelationEntries(T){let _=T[this.a],F=T[this.b];if(_!==void 0&&F===void 0){let W=this.getRelatedKeys(_);if(W)return[...W].map((J)=>{return[J,this.getContent(_,J)]})}if(_===void 0&&F!==void 0){let W=this.getRelatedKeys(F);if(W)return[...W].map((J)=>{return[J,this.getContent(J,F)]})}return[]}has(T,_){if(_)return this.getRelatedKeys(T)?.has(_)??!1;return this.relations.has(T)}}class FT{Subscriber;subscribers=new Map;subscribe(T,_){return this.subscribers.set(T,_),()=>{this.unsubscribe(T)}}unsubscribe(T){this.subscribers.delete(T)}next(T){let _=this.subscribers.values();for(let F of _)F(T)}}class O4 extends FT{state;constructor(T){super();this.state=T}next(T){this.state=T,super.next(T)}}function A0(T){return"epoch"in T.transactionMeta}function M_(T){return"phase"in T.transactionMeta}function cY(T){return T[0].toUpperCase()+T.slice(1)}function aW(T){return T.type.split("_").map(cY).join(" ")}class tF extends Error{constructor(T,_){super(`${aW(T)} ${nT(T.key)} not found in store "${_.config.name}".`)}}var FF=(T)=>(_)=>T instanceof Function?T(_):T;var U0=(T,_)=>{if(T.valueMap.has(_.key))return T.logger.info("\uD83D\uDCD6",_.type,_.key,"reading cached value"),dY(_,T);switch(_.type){case"readonly_held_selector":case"readonly_pure_selector":case"writable_held_selector":case"writable_pure_selector":return T.logger.info("\uD83E\uDDEE",_.type,_.key,"computing value"),_.get();case"atom":case"mutable_atom":{let F=_.default,W;if(F instanceof Function)W=F();else W=F;return T.logger.info("\uD83D\uDC81","atom",_.key,"could not find cached value; using default",W),W}}};var lY=(T,_)=>{if(T.operation.open){let F=performance.now();return T.logger.info("\u2757",_.type,_.key,`deferring setState at T-${F} until setState for "${T.operation.token.key}" is done`),F}T.operation={open:!0,done:new Set,prev:new Map,time:Date.now(),token:_},T.logger.info("\u2B55",_.type,_.key,`operation start in store "${T.config.name}"${!M_(T)?"":` ${T.transactionMeta.phase} "${T.transactionMeta.update.key}"`}`)},tY=(T)=>{if(T.operation.open)T.logger.info("\uD83D\uDD34",T.operation.token.type,T.operation.token.key,`operation done in store "${T.config.name}"`);T.operation={open:!1},T.on.operationClose.next(T.operation)},iY=(T,_)=>{if(!T.operation.open)return T.logger.error("\uD83D\uDC1E","unknown",_,"isDone called outside of an operation. This is probably a bug in AtomIO."),!0;return T.operation.done.has(_)},O0=(T,_)=>{if(!T.operation.open){T.logger.error("\uD83D\uDC1E","unknown",_,"markDone called outside of an operation. This is probably a bug in AtomIO.");return}T.operation.done.add(_)};var nY=(T,_,F)=>{switch(_.type){case"mutable_atom":T.logger.info("\uD83D\uDCE2",_.type,_.key,"is now (",F.newValue,") subscribers:",_.subject.subscribers);break;case"atom":case"writable_pure_selector":case"readonly_pure_selector":case"writable_held_selector":case"readonly_held_selector":T.logger.info("\uD83D\uDCE2",_.type,_.key,"went (",F.oldValue,"->",F.newValue,") subscribers:",_.subject.subscribers)}_.subject.next(F)};var M4=(T,_)=>{let F=m(T),W=F.selectorAtoms.getRelatedKeys(_.key);if(F.logger.info("\uD83E\uDDF9",_.type,_.key,W?`evicting ${W.size} states downstream:`:"no downstream states",W??"to evict"),W){if(F.operation.open)F.logger.info("\uD83E\uDDF9",_.type,_.key,`[ ${[...F.operation.done].join(", ")} ] already done`);for(let J of W){if(iY(F,J))continue;rY(J,F),O0(F,J)}}};var sY=(T,_,F)=>{let W=U0(T,_),J=W;if(_.type==="mutable_atom"&&M_(T)){let{parent:$}=T;J=iF(T,_,$)}if(J=FF(F)(J),T.logger.info("\uD83D\uDCDD","atom",_.key,"set to",J),J=rT(T,_.key,J,_.subject),eY(T,_.key))T$(T,_.key);O0(T,_.key),M4(T,_);let Y={oldValue:W,newValue:J};if(!M_(T)){nY(T,_,Y);return}if(T.on.transactionApplying.state===null){let{key:$}=_;if(aY(Y.newValue))return;let Z={type:"atom_update",key:$,...Y};if(_.family)Z.family=_.family;T.transactionMeta.update.updates.push(Z),T.logger.info("\uD83D\uDCC1","atom",$,"stowed (",Y.oldValue,"->",Y.newValue,")")}else if(_.key.startsWith("*")){let $=_.key.slice(1),Z=T.atoms.get($),G=T.valueMap.get($);if(Z.type==="mutable_atom"&&M_(T)){let{parent:U}=T;G=iF(T,Z,U)}if(G.do(Y.newValue)===null)M4(T,Z)}};var eW=(T,_,F)=>{switch(_.type){case"atom":case"mutable_atom":sY(T,_,F);break;case"writable_pure_selector":case"writable_held_selector":_.set(F);break}};var T1=(T,_)=>m(T).atoms.has(_),x7=(T,_)=>m(T).writableSelectors.has(_),h7=(T,_)=>m(T).readonlySelectors.has(_),_$=(T,_)=>T1(T,_)||x7(T,_)||h7(T,_);var _1=(T,_)=>{return m(T).selectorGraph.getRelationEntries({downstreamSelectorKey:_}).filter(([W,{source:J}])=>J!==_).map(([W,{source:J}])=>J).filter((W)=>_$(T,W))};var w4=(T,_,F)=>{let W=[],J=_1(T,_);while(J.length>0){let Y=J.shift();if(F.has(Y))continue;if(F.add(Y),!T1(T,Y))J.push(..._1(T,Y));else if(!W.includes(Y))W.push(Y)}return W},F$=(T,_)=>{let F=T.key,W=_1(_,F),J=new Set;return W.flatMap((Y)=>T1(_,Y)?Y:w4(_,Y,J))};var W$=(T,_,F,W,J)=>{let Y=m(T),{type:$,key:Z}=W;if($==="atom"||$==="mutable_atom")Y.selectorAtoms.set({selectorKey:F,atomKey:Z}),T.logger.info("\uD83D\uDD0D",_,F,`discovers root atom "${Z}"`);else{let G=w4(T,Z,J);T.logger.info("\uD83D\uDD0D",_,F,`discovers root atoms: [ ${G.map((X)=>`"${X}"`).join(", ")} ]`);for(let X of G)Y.selectorAtoms=Y.selectorAtoms.set({selectorKey:F,atomKey:X})}J.add(Z)};var M0=(T,_,F,W)=>({get:(...J)=>{let Y=m(T),$;if(J.length===2){let[U,M]=J;$=w_(T,U,M)}else[$]=J;let Z=$_(T,$),G=U0(T,Z),X=$.key;return T.logger.info("\uD83D\uDD0C",_,F,`registers dependency ( "${X}" =`,G,")"),Y.selectorGraph.set({upstreamSelectorKey:X,downstreamSelectorKey:F},{source:$.key}),W$(T,_,F,$,W),G},set:(...J)=>{let Y,$;if(J.length===2)Y=J[0],$=J[1];else{let X=J[0],U=J[1];$=J[2],Y=w_(T,X,U)}let Z=m(T),G=$_(Z,Y);eW(Z,G,$)},find:(...J)=>w_(T,...J),json:(J)=>WF(T,J)});var Q4=(T,_,F)=>{let W=m(T),J=new FT,Y=new Set,{key:$,const:Z}=_,G="readonly_held_selector",{get:X,find:U,json:M}=M0(W,"readonly_held_selector",$,Y),V={..._,type:"readonly_held_selector",subject:J,install:(K)=>Q4(K,_,F),get:()=>{return _.get({get:X,find:U,json:M},Z),rT(m(T),$,Z,J),Y.clear(),Z},...F&&{family:F}};W.readonlySelectors.set($,V),T.logger.info("\u2728","readonly_held_selector",$,"=",Z);let C={key:$,type:"readonly_held_selector"};if(F)C.family=F;return C};var z4=(T,_,F)=>{let W=m(T),J=new FT,Y=new Set,$=_.key,Z="readonly_pure_selector",{get:G,find:X,json:U}=M0(W,"readonly_pure_selector",$,Y),M=()=>{let K=_.get({get:G,find:X,json:U});return rT(m(T),$,K,J),Y.clear(),K},Q={..._,type:"readonly_pure_selector",subject:J,install:(K)=>z4(K,_,F),get:M,...F&&{family:F}};W.readonlySelectors.set($,Q);let V=M();T.logger.info("\u2728","readonly_pure_selector",$,"=",V);let C={key:$,type:"readonly_pure_selector"};if(F)C.family=F;return C};var E4=(T,_,F)=>{let W=m(T),J=new FT,Y=new Set,{key:$,const:Z}=_,G="writable_held_selector",X=M0(W,"writable_held_selector",$,Y),{find:U,get:M,json:Q}=X,V={find:U,get:M,json:Q},C=(y=_.get,u=m(T))=>{return y(V,Z),rT(u,$,Z,J),Y.clear(),Z},v={..._,type:"writable_held_selector",subject:J,install:(y)=>E4(y,_,F),get:C,set:(y)=>{let u=m(T),h=C(_.get,u),p=FF(y)(h);if(T.logger.info("\uD83D\uDCDD","writable_held_selector",$,"set (",h,"->",p,")"),rT(u,$,p,J),O0(u,$),A0(u))J.next({newValue:p,oldValue:h});_.set(X,p)},...F&&{family:F}};W.writableSelectors.set($,v);let P=C();T.logger.info("\u2728","writable_held_selector",$,"=",P);let j={key:$,type:"writable_held_selector"};if(F)j.family=F;return j};var nF=(T,_,F)=>{let W=m(T),J=new FT,Y=new Set,$=_.key,Z="writable_pure_selector",G=M0(W,"writable_pure_selector",$,Y),{find:X,get:U,json:M}=G,Q={find:X,get:U,json:M},V=(j=_.get,y=m(T))=>{let u=j(Q);return rT(y,$,u,J),Y.clear(),u},K={..._,type:"writable_pure_selector",subject:J,install:(j)=>nF(j,_,F),get:V,set:(j)=>{let y=m(T),u=V(_.get,y),h=FF(j)(u);if(T.logger.info("\uD83D\uDCDD","writable_pure_selector",$,"set (",u,"->",h,")"),rT(y,_.key,h,J),O0(y,_.key),A0(y))J.next({newValue:h,oldValue:u});_.set(G,h)},...F&&{family:F}};W.writableSelectors.set($,K);let v=V();T.logger.info("\u2728",K.type,K.key,"=",v);let P={key:$,type:"writable_pure_selector"};if(F)P.family=F;return P};function mY(T,_){let F="set"in _,W="const"in _;if(W&&F){let Y=E4(T,_,void 0);return T.on.selectorCreation.next(Y),Y}if(W){let Y=Q4(T,_,void 0);return T.on.selectorCreation.next(Y),Y}if(F){let Y=nF(T,_,void 0);return T.on.selectorCreation.next(Y),Y}let J=z4(T,_,void 0);return T.on.selectorCreation.next(J),J}function H4(T,_,F){let W=_.key,J="writable_pure_selector_family",Y={key:W,type:"writable_pure_selector_family"},$=T.families.get(W);if($)T.logger.error("\u2757","writable_pure_selector_family",W,`Overwriting an existing ${aW($)} "${$.key}" in store "${T.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);let Z=new FT,X=Object.assign((U)=>{let M=nT(U),Q={key:W,subKey:M},V=`${W}(${M})`,C=m(T),K=nF(C,{key:V,get:_.get(U),set:_.set(U)},Q);return Z.next({type:"state_creation",token:K}),K},Y,{internalRoles:F,subject:Z,install:(U)=>H4(U,_),default:(U)=>{return _.get(U)({get:(...Q)=>rF(T,...Q),find:(...Q)=>w_(T,...Q),json:(Q)=>WF(T,Q)})}});return T.families.set(W,X),Y}function J$(T,_,F){let W=T.families.get(_.key);if(W===void 0)throw new tF(_,T);let J=W(F),Y=m(T);if(J.family){if(A0(Y))switch(J.type){case"atom":case"mutable_atom":T.on.atomCreation.next(J);break;case"writable_pure_selector":case"readonly_pure_selector":case"writable_held_selector":case"readonly_held_selector":T.on.selectorCreation.next(J);break}else if(M_(Y)&&Y.on.transactionApplying.state===null)Y.transactionMeta.update.updates.push({type:"state_creation",token:J})}return J}function Y$(T,_,F){let W=nT(F),J=`${_.key}(${W})`,Y=m(T),$;switch(_.type){case"atom_family":case"mutable_atom_family":$=Y.atoms.get(J);break;case"writable_held_selector_family":case"writable_pure_selector_family":$=Y.writableSelectors.get(J);break;case"readonly_held_selector_family":case"readonly_pure_selector_family":$=Y.readonlySelectors.get(J);break}if($)return lF($);return $}function w_(T,_,F){let W=Y$(T,_,F);if(W)return W;let J=nT(F),Y=T.molecules.get(J);if(!Y&&T.config.lifespan==="immortal"){let $=uY(_,F);return T.logger.error("\u274C",$.type,$.key,`was not found in store "${T.config.name}"; returned a counterfeit token.`),$}if(W=J$(T,_,F),Y)m(T).moleculeData.set(J,_.key);return W}function $$(T,_){if(_.family){let F=T.families.get(_.family.key);if(F)return F}}function w0(T,..._){let F,W,J,Y;if(_.length===2){if(F=_[0],Y=_[1],W=$$(T,F)??null,W)J=F.family?dF(F.family.subKey):null,F=w_(T,W,J)}else W=_[0],J=_[1],Y=_[2],F=w_(T,W,J);if("counterfeit"in F&&"family"in F){let G=F.family.subKey,X=T.disposalTraces.buffer.find((U)=>U?.key===G);T.logger.error("\u274C",F.type,F.key,`could not be set because it was not found in the store "${T.config.name}".`,X?`This state was previously disposed:
|
|
48
|
-
${X.trace}`:"No previous disposal trace was found.");return}let $=
|
|
49
|
-
${$.trace}`:"No previous disposal trace was found."),W.type){case"atom_family":case"mutable_atom_family":return T.defaults.get(W.key);case"readonly_pure_selector_family":case"writable_pure_selector_family":case"readonly_held_selector_family":case"writable_held_selector_family":{if(T.defaults.has(W.key))return T.defaults.get(F.family.key);let Z=$_(T,W).default(Y);return T.defaults.set(W.key,Z),Z}}}return U0(T,$_(T,F))}class Z${parent=null;child=null;valueMap=new Map;defaults=new Map;atoms=new Map;writableSelectors=new Map;readonlySelectors=new Map;atomsThatAreDefault=new Set;selectorAtoms=new g_({between:["selectorKey","atomKey"],cardinality:"n:n"});selectorGraph=new g_({between:["upstreamSelectorKey","downstreamSelectorKey"],cardinality:"n:n"},{makeContentKey:(...T)=>T.sort().join(":")});trackers=new Map;families=new Map;joins=new Map;transactions=new Map;transactionMeta={epoch:new Map,actionContinuities:new g_({between:["continuity","action"],cardinality:"1:n"})};timelines=new Map;timelineTopics=new g_({between:["timelineKey","topicKey"],cardinality:"1:n"});disposalTraces=new sW(100);molecules=new Map;moleculeJoins=new g_({between:["moleculeKey","joinKey"],cardinality:"n:n"},{makeContentKey:(...T)=>T.sort().join(":")});moleculeGraph=new g_({between:["upstreamMoleculeKey","downstreamMoleculeKey"],cardinality:"n:n"},{makeContentKey:(...T)=>T.sort().join(":")});moleculeData=new g_({between:["moleculeKey","stateFamilyKey"],cardinality:"n:n"},{makeContentKey:(...T)=>T.sort().join(":")});miscResources=new Map;on={atomCreation:new FT,atomDisposal:new FT,selectorCreation:new FT,selectorDisposal:new FT,timelineCreation:new FT,transactionCreation:new FT,transactionApplying:new O4(null),operationClose:new FT,moleculeCreation:new FT,moleculeDisposal:new FT};operation={open:!1};config={name:"IMPLICIT_STORE",lifespan:"ephemeral"};loggers=[new U4("warn",(T,_,F)=>!G$(F))];logger={error:(...T)=>{for(let _ of this.loggers)_.error(...T)},info:(...T)=>{for(let _ of this.loggers)_.info(...T)},warn:(...T)=>{for(let _ of this.loggers)_.warn(...T)}};constructor(T,_=null){if(this.config={..._?.config,...T},_!==null){if(this.valueMap=new Map(_?.valueMap),this.operation={..._?.operation},A0(_))this.transactionMeta={epoch:new Map(_?.transactionMeta.epoch),actionContinuities:new g_(_?.transactionMeta.actionContinuities.toJSON())};for(let[,W]of _.families){if(W.internalRoles?.includes("mutable")||W.internalRoles?.includes("join"))continue;W.install(this)}let F=new Set;for(let[,W]of _.atoms){if(F.has(W.key))continue;if(W.install(this),W.type==="mutable_atom"){let J=WF(_,W),Y=X$(W);F.add(J.key),F.add(Y.key)}}for(let[,W]of _.readonlySelectors)W.install(this);for(let[,W]of _.writableSelectors){if(F.has(W.key))continue;W.install(this)}for(let[,W]of _.transactions)W.install(this);for(let[,W]of _.timelines)W.install(this)}}}var oY={get STORE(){return globalThis.ATOM_IO_IMPLICIT_STORE??=new Z$({name:"IMPLICIT_STORE",lifespan:"ephemeral"}),globalThis.ATOM_IO_IMPLICIT_STORE}};function $_(T,_){let F,W=T;while(W!==null){switch(_.type){case"atom":case"mutable_atom":F=W.atoms.get(_.key);break;case"writable_pure_selector":case"writable_held_selector":F=W.writableSelectors.get(_.key);break;case"readonly_pure_selector":case"readonly_held_selector":F=W.readonlySelectors.get(_.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":F=W.families.get(_.key);break;case"timeline":F=W.timelines.get(_.key);break;case"transaction":F=W.transactions.get(_.key);break}if(F)return F;W=W.child}throw new tF(_,T)}var H$=(T,_)=>{let F=m(T);if(F.operation.open)return F.operation.prev.get(_.key);return F.valueMap.get(_.key)};var R4=(T,_)=>{let F=m(T);return F$(_,T).map((J)=>{let Y=F.atoms.get(J);if(Y===void 0)throw new Error(`Atom "${J}", a dependency of selector "${_.key}", not found in store "${T.config.name}".`);return Y.subject.subscribe(`${_.type}:${_.key}`,($)=>{T.logger.info("\uD83D\uDCE2",_.type,_.key,"root",J,"went",$.oldValue,"->",$.newValue);let Z=H$(F,_),G=U0(F,_);T.logger.info("\u2728",_.type,_.key,"went",Z,"->",G),_.subject.next({newValue:G,oldValue:Z})})})};function sF(T,_,F,W){function J(M){if(T.operation.open){let Q=T.on.operationClose.subscribe(`state subscription ${F}`,()=>{Q(),W(M)})}else W(M)}let Y=$_(T,_);T.logger.info("\uD83D\uDC40",Y.type,Y.key,`Adding subscription "${F}"`);let $=Y.type==="writable_pure_selector"||Y.type==="readonly_pure_selector",Z=null,G=J;if($)Z=R4(T,Y),G=(M)=>{if(Z)Z.length=0,Z.push(...R4(T,Y));J(M)};let X=Y.subject.subscribe(F,G);return()=>{if(T.logger.info("\uD83D\uDE48",Y.type,Y.key,`Removing subscription "${F}"`),X(),Z)for(let M of Z)M()}}var A$=(T,_,F,W)=>{let J=$_(T,_);T.logger.info("\uD83D\uDC40","timeline",_.key,`Adding subscription "${F}"`);let Y=J.subject.subscribe(F,W);return()=>{T.logger.info("\uD83D\uDE48","timeline",_.key,`Removing subscription "${F}" from timeline`),Y()}};class K4{initializeState(T,_){let F=`*${T.key}`;_.atoms.delete(F),_.valueMap.delete(F);let W=T.family?{key:`*${T.family.key}`,subKey:T.family.subKey}:void 0,J=V4(_,{key:F,default:null},W);if(_.parent?.valueMap.has(F)){let Y=_.parent.valueMap.get(F);_.valueMap.set(F,Y)}return J}unsubscribeFromInnerValue;unsubscribeFromState;observeCore(T,_,F){let W=`tracker:${F.config.name}:${M_(F)?F.transactionMeta.update.key:"main"}:${T.key}`,J=rF(F,T);this.unsubscribeFromInnerValue=J.subscribe(W,(Y)=>{w0(F,_,Y)}),this.unsubscribeFromState=sF(F,T,W,(Y)=>{if(Y.newValue!==Y.oldValue)this.unsubscribeFromInnerValue(),this.unsubscribeFromInnerValue=Y.newValue.subscribe(W,($)=>{w0(F,_,$)})})}updateCore(T,_,F){let W=`tracker:${F.config.name}:${M_(F)?F.transactionMeta.update.key:"main"}:${T.key}`;sF(F,_,W,({newValue:J,oldValue:Y})=>{let $=F.timelineTopics.getRelatedKey(_.key);if($){if(F.timelines.get($)?.timeTraveling){let X=A$(F,{key:$,type:"timeline"},W,(U)=>{X(),w0(F,T,(M)=>{if(U==="redo"&&J)M.do(J);else if(U==="undo"&&Y)M.undo(Y);return M})});return}}let Z=F.on.operationClose.subscribe(W,()=>{Z();let G=rF(F,T),X=J===null?-1:G.getUpdateNumber(J),U=X-G.cacheUpdateNumber;if(J&&U===1)w0(F,T,(M)=>(M.do(J),M));else F.logger.info("\u274C","mutable_atom",T.key,`could not be updated. Expected update number ${G.cacheUpdateNumber+1}, but got ${X}`)})})}mutableState;latestUpdateState;[Symbol.dispose];constructor(T,_){this.mutableState=T;let F=m(_);this.latestUpdateState=this.initializeState(T,F),this.observeCore(T,this.latestUpdateState,F),this.updateCore(T,this.latestUpdateState,F),F.trackers.set(T.key,this),this[Symbol.dispose]=()=>{this.unsubscribeFromInnerValue(),this.unsubscribeFromState(),F.trackers.delete(T.key)}}}var WF=(T,_)=>{if(_.family){let W=m(T),Y={key:`${_.family.key}:JSON`,type:"writable_pure_selector_family"},$=$_(W,Y),Z=JSON.parse(_.family.subKey);return w_(T,$,Z)}return{type:"writable_pure_selector",key:`${_.key}:JSON`}};var X$=(T)=>{let F={type:"atom",key:`*${T.key}`};if(T.family)F.family={key:`*${T.family.key}`,subKey:T.family.subKey};return F};function aY(T){return typeof T==="object"&&T!==null&&"do"in T&&"undo"in T&&"subscribe"in T}function iF(T,_,F){let W=F.valueMap.get(_.key),J=T.valueMap.get(_.key);if(W!==J)return J;if(W===void 0)return _.default();F.logger.info("\uD83D\uDCC3","atom",_.key,"copying");let Y=_.toJson(W),$=_.fromJson(Y);return T.valueMap.set(_.key,$),new K4(_,F),$}function rT(T,_,F,W){let J=T.valueMap.get(_);if(J instanceof cF)J.use(F);if(F instanceof Promise){let Y=new cF(F);return T.valueMap.set(_,Y),Y.then(($)=>{rT(T,_,$,W),W.next({newValue:$,oldValue:Y})}).catch(($)=>{T.logger.error("\uD83D\uDCA5","state",_,"rejected:",$)}),Y}return T.valueMap.set(_,F),F}var dY=(T,_)=>{let F=_.valueMap.get(T.key);if(T.type==="mutable_atom"&&M_(_)){let{parent:W}=_;F=iF(_,T,W)}return F},rY=(T,_)=>{let F=_.valueMap.get(T);if(F instanceof cF){let W=F,J=_.writableSelectors.get(T)??_.readonlySelectors.get(T);if(J)W.use(J.get());return}if(_.operation.open)_.operation.prev.set(T,F);_.valueMap.delete(T),_.logger.info("\uD83D\uDDD1","state",T,"evicted")};var eY=(T,_)=>{return m(T).atomsThatAreDefault.has(_)},U$=(T,_)=>{let F=m(T);F.atomsThatAreDefault=new Set(F.atomsThatAreDefault).add(_)},T$=(T,_)=>{let F=m(T);F.atomsThatAreDefault=new Set(m(T).atomsThatAreDefault),F.atomsThatAreDefault.delete(_)};function V4(T,_,F){let{key:J,default:Y}=_;T.logger.info("\uD83D\uDD28","atom",J,`creating in store "${T.config.name}"`);let $=m(T),Z=$.atoms.get(J);if(Z&&Z.type==="atom")return T.logger.error("\u274C","atom",J,"Tried to create atom, but it already exists in the store."),lF(Z);let G=new FT,X={..._,type:"atom",install:(Q)=>{return Q.logger.info("\uD83D\uDEE0\uFE0F","atom",J,`installing in store "${Q.config.name}"`),V4(Q,_,F)},subject:G};if(F)X.family=F;let U=Y;if(Y instanceof Function)U=Y();$.atoms.set(J,X),U$(T,J),rT($,J,U,G);let M=lF(X);if(_.effects){let Q=0,V=[];for(let C of _.effects){let K=C({setSelf:(v)=>{w0(T,M,v)},onSet:(v)=>sF(T,M,`effect[${Q}]`,v)});if(K)V.push(K);++Q}X.cleanup=()=>{for(let C of V)C()}}return M}class JF extends Set{mode="record";subject=new FT;cacheLimit=0;cache=[];cacheIdx=-1;cacheUpdateNumber=-1;constructor(T,_=0){super(T);if(T instanceof JF)this.parent=T,this.cacheUpdateNumber=T.cacheUpdateNumber;if(_)this.cacheLimit=_,this.cache=new Array(_),this.subscribe("auto cache",(F)=>{this.cacheIdx++,this.cacheIdx%=this.cacheLimit,this.cache[this.cacheIdx]=F})}toJSON(){return{members:[...this],cache:this.cache,cacheLimit:this.cacheLimit,cacheIdx:this.cacheIdx,cacheUpdateNumber:this.cacheUpdateNumber}}static fromJSON(T){let _=new JF(T.members,T.cacheLimit);return _.cache=T.cache,_.cacheIdx=T.cacheIdx,_.cacheUpdateNumber=T.cacheUpdateNumber,_}add(T){let _=super.add(T);if(this.mode==="record")this.cacheUpdateNumber++,this.emit(`add:${nT(T)}`);return _}clear(){let T=this.mode==="record"?[...this]:null;if(super.clear(),T)this.cacheUpdateNumber++,this.emit(`clear:${JSON.stringify(T)}`)}delete(T){let _=super.delete(T);if(this.mode==="record")this.cacheUpdateNumber++,this.emit(`del:${nT(T)}`);return _}parent=null;child=null;transactionUpdates=null;transaction(T){this.mode="transaction",this.transactionUpdates=[],this.child=new JF(this);let _=this.child._subscribe("transaction",(F)=>{this.transactionUpdates?.push(F)});try{if(T(this.child)){for(let W of this.transactionUpdates)this.doStep(W);this.cacheUpdateNumber++,this.emit(`tx:${this.transactionUpdates.join(";")}`)}}catch(F){throw console.warn("Did not apply transaction to SetRTX; this error was thrown:",F),F}finally{_(),this.child=null,this.transactionUpdates=null,this.mode="record"}}_subscribe(T,_){return this.subject.subscribe(T,_)}subscribe(T,_){return this.subject.subscribe(T,(F)=>{_(`${this.cacheUpdateNumber}=${F}`)})}emit(T){this.subject.next(T)}doStep(T){let _=T.indexOf(":"),F=T.substring(0,_),W=T.substring(_+1);switch(F){case"add":this.add(JSON.parse(W));break;case"clear":this.clear();break;case"del":this.delete(JSON.parse(W));break;case"tx":for(let J of W.split(";"))this.doStep(J)}}getUpdateNumber(T){let _=T.indexOf("=");return Number(T.substring(0,_))}do(T){let _=T.indexOf("="),F=Number(T.substring(0,_)),W=F-this.cacheUpdateNumber;if(W>0){if(W===1){this.mode="playback";let Y=T.substring(_+1);return this.doStep(Y),this.mode="record",this.cacheUpdateNumber=F,null}return this.cacheUpdateNumber+1}if(Math.abs(W)<this.cacheLimit){let Y=this.cacheIdx+W;if(this.cache[Y]===T)return null;this.mode="playback";let Z=!1;while(!Z){this.cacheIdx%=this.cacheLimit;let X=this.cache[this.cacheIdx];if(this.cacheIdx--,!X)return"OUT_OF_RANGE";this.undo(X),Z=this.cacheIdx===Y-1}let G=T.substring(_+1);return this.doStep(G),this.mode="record",this.cacheUpdateNumber=F,null}return"OUT_OF_RANGE"}undoStep(T){let _=T.indexOf(":"),F=T.substring(0,_),W=T.substring(_+1);switch(F){case"add":this.delete(JSON.parse(W));break;case"del":this.add(JSON.parse(W));break;case"clear":{let J=JSON.parse(W);for(let Y of J)this.add(Y);break}case"tx":{let J=W.split(";");for(let Y=J.length-1;Y>=0;Y--)this.undoStep(J[Y])}}}undo(T){let _=T.indexOf("=");if(Number(T.substring(0,_))===this.cacheUpdateNumber){this.mode="playback";let W=T.substring(_+1);return this.undoStep(W),this.mode="record",this.cacheUpdateNumber--,null}return this.cacheUpdateNumber}}function G$(T){return T.startsWith("\uD83D\uDD0D ")}class F1{supported;constructor(T){this.supported=T}refine(T){for(let[_,F]of Object.entries(this.supported))try{if(F(T)===!0&&F!==Boolean)return{type:_,data:T}}catch(W){try{if(T instanceof F)return{type:_,data:T}}catch(J){}}return null}}var p7=new F1({number:(T)=>typeof T==="number",string:(T)=>typeof T==="string",boolean:(T)=>typeof T==="boolean",null:(T)=>T===null});function g7(T){if(!T)return!1;return Object.getPrototypeOf(T)===Object.prototype}var m7=new F1({object:g7,array:(T)=>Array.isArray(T)}),o7=new F1({...p7.supported,...m7.supported}),O$=(T)=>{if(T===void 0)return"undefined";let _=o7.refine(T);if(_)return _.type;return Object.getPrototypeOf(T).constructor.name};class W1{listeners;globalListeners;handleEvent(T,..._){for(let W of this.globalListeners)W(T,..._);let F=this.listeners.get(T);if(F)for(let W of F)W(..._)}id="no_id_retrieved";emit;constructor(T){this.emit=T,this.listeners=new Map,this.globalListeners=new Set}on(T,_){let F=this.listeners.get(T);if(F)F.add(_);else this.listeners.set(T,new Set([_]));return this}onAny(T){return this.globalListeners.add(T),this}off(T,_){let F=this.listeners.get(T);if(F)if(_)F.delete(_);else this.listeners.delete(T);return this}offAny(T){return this.globalListeners.delete(T),this}}class M$ extends W1{in;out;id="no_id_retrieved";disposalFunctions=[];constructor(T){super((..._)=>{return this.out.next(_),this});this.id=T,this.in=new FT,this.out=new FT,this.in.subscribe("socket",(_)=>{this.handleEvent(..._)})}dispose(){for(let T of this.disposalFunctions)T()}}class D4 extends W1{incompleteData="";unprocessedEvents=[];relays;relayServices;process;id="#####";log(...T){this.process.stderr.write(nT(T.map((_)=>_ instanceof JF?`{ ${_.toJSON().members.join(" | ")} }`:_))+"\x03")}logger={info:(...T)=>{this.log("i",...T)},warn:(...T)=>{this.log("w",...T)},error:(...T)=>{this.log("e",...T)}};constructor(){super((T,..._)=>{let F=JSON.stringify([T,..._]);return this.process.stdout.write(F+"\x03"),this});if(this.process=process,this.process.stdin.resume(),this.relays=new Map,this.relayServices=[],this.process.stdin.on("data",(T)=>{let _=T.toString();this.unprocessedEvents.push(..._.split("\x03"));let F=this.unprocessedEvents.shift();this.incompleteData+=F??"";try{let W=dF(this.incompleteData);this.logger.info("\uD83C\uDFB0","received",W),this.handleEvent(...W);while(this.unprocessedEvents.length>0){let J=this.unprocessedEvents.shift();if(J){if(this.unprocessedEvents.length===0)this.incompleteData=J;let Y=dF(J);this.handleEvent(...Y)}}this.incompleteData=""}catch(W){if(W instanceof Error)this.logger.error("\u2757",W.message,W.cause,W.stack)}}),this.on("exit",()=>{this.logger.info("\uD83D\uDD25",this.id,'received "exit"'),process.exit(0)}),process.on("exit",(T)=>{this.logger.info("\uD83D\uDD25",this.id,`exited with code ${T}`)}),process.on("end",()=>{this.logger.info("\uD83D\uDD25",this.id,"ended"),process.exit(0)}),process.on("SIGTERM",()=>{this.logger.error("\uD83D\uDD25",this.id,"terminated"),process.exit(0)}),process.on("SIGINT",()=>{this.logger.error("\uD83D\uDD25",this.id,"interrupted"),process.exit(0)}),process.pid)this.id=process.pid?.toString();this.on("user-joins",(T)=>{this.logger.info("\uD83D\uDC64","user",T,"joined");let _=new M$(`user:${T}`);this.relays.set(T,_),this.logger.info("\uD83D\uDD17","attaching services:",`[${[...this.relayServices.keys()].join(", ")}]`);for(let F of this.relayServices){let W=F(_);if(W)_.disposalFunctions.push(W)}this.on(`user:${T}`,(...F)=>{_.in.next(F)}),_.out.subscribe("socket",(F)=>{this.emit(...F)})}),this.on("user-leaves",(T)=>{let _=this.relays.get(T);if(this.off(`relay:${T}`),_)_.dispose(),this.relays.delete(T)}),process.stdout.write("ALIVE")}relay(T){this.logger.info("\uD83D\uDD17","running relay method"),this.relayServices.push(T)}}var{file:c5,serve:JU}=globalThis.Bun;import{readFileSync as z$}from"fs";import{createServer as l7}from"http";import{createServer as t7}from"https";import{resolve as S4}from"path";function w$(T,_){if(T instanceof Promise)throw new Error(_)}function u7(T,_){let F={},W=[];for(let J in T){let Y=T[J]["~standard"].validate(_[J]);if(w$(Y,`Validation must be synchronous, but ${J} returned a Promise.`),Y.issues){W.push(...Y.issues.map(($)=>({...$,path:[J,...$.path??[]]})));continue}F[J]=Y.value}if(W.length)return{issues:W};return{value:F}}function L4(T){let _=T.runtimeEnvStrict??T.runtimeEnv??process.env;if(T.emptyStringAsUndefined??!1){for(let[j,y]of Object.entries(_))if(y==="")delete _[j]}if(!!T.skipValidation)return _;let J=typeof T.client==="object"?T.client:{},Y=typeof T.server==="object"?T.server:{},$=typeof T.shared==="object"?T.shared:{},Z=T.isServer??(typeof window==="undefined"||("Deno"in window)),G=Z?{...Y,...$,...J}:{...J,...$},X=T.createFinalSchema?.(G,Z)["~standard"].validate(_)??u7(G,_);w$(X,"Validation must be synchronous");let U=T.onValidationError??((j)=>{throw console.error("\u274C Invalid environment variables:",j),new Error("Invalid environment variables")}),M=T.onInvalidAccess??(()=>{throw new Error("\u274C Attempted to access a server-side environment variable on the client")});if(X.issues)return U(X.issues);let Q=(j)=>{if(!T.clientPrefix)return!0;return!j.startsWith(T.clientPrefix)&&!(j in $)},V=(j)=>{return Z||!Q(j)},C=(j)=>{return j==="__esModule"||j==="$$typeof"},K=(T.extends??[]).reduce((j,y)=>{return Object.assign(j,y)},{}),v=Object.assign(K,X.value);return new Proxy(v,{get(j,y){if(typeof y!=="string")return;if(C(y))return;if(!V(y))return M(y);return Reflect.get(j,y)}})}var c7="__vite_start_time"in globalThis,d7=typeof window!=="undefined",LN="vitest"in globalThis,s_=Y_("string"),Q$=Y_('"true" | "false" | undefined'),P_=L4({isServer:!c7&&!d7,server:{CI:Y_("string | undefined").pipe(Boolean),POSTGRES_USER:s_,POSTGRES_PASSWORD:s_,POSTGRES_DATABASE:s_,POSTGRES_HOST:s_,POSTGRES_PORT:s_.pipe((T)=>Number.parseInt(T,10)),BACKEND_PORT:s_.pipe((T)=>Number.parseInt(T,10)),RUN_WORKERS_FROM_SOURCE:Q$.pipe((T)=>T==="true"),FRONTEND_PORT:s_.pipe((T)=>Number.parseInt(T,10)),FRONTEND_ORIGINS:s_.pipe.try((T)=>JSON.parse(T),Y_("string[]")),API_KEY_OPENAI:Y_("string | undefined"),API_KEY_RESEND:Y_("string | undefined")},clientPrefix:"VITE_",client:{VITE_BACKEND_ORIGIN:s_,VITE_DEV_FRONTEND_HOST:Y_("string | undefined"),VITE_DEV_HTTPS:Q$.pipe((T)=>T==="true")},runtimeEnv:import.meta.env,emptyStringAsUndefined:!0});var E$=S4(import.meta.dirname,"../dev"),J1=P_.VITE_DEV_HTTPS?{cert:z$(S4(E$,"./cert.pem"),"utf-8"),key:z$(S4(E$,"./key.pem"),"utf-8")}:void 0;function fN(T){if(J1)return t7(J1,T);return l7({},T)}import s3 from"path";var A=Symbol.for("drizzle:entityKind"),PN=Symbol.for("drizzle:hasOwnEntityKind");function E(T,_){if(!T||typeof T!=="object")return!1;if(T instanceof _)return!0;if(!Object.prototype.hasOwnProperty.call(_,A))throw new Error(`Class "${_.name??"<unknown>"}" doesn't look like a Drizzle entity. If this is incorrect and the class is provided by Drizzle, please report this as a bug.`);let F=Object.getPrototypeOf(T).constructor;if(F)while(F){if(A in F&&F[A]===_[A])return!0;F=Object.getPrototypeOf(F)}return!1}class XT{constructor(T,_){this.table=T,this.config=_,this.name=_.name,this.keyAsName=_.keyAsName,this.notNull=_.notNull,this.default=_.default,this.defaultFn=_.defaultFn,this.onUpdateFn=_.onUpdateFn,this.hasDefault=_.hasDefault,this.primary=_.primaryKey,this.isUnique=_.isUnique,this.uniqueName=_.uniqueName,this.uniqueType=_.uniqueType,this.dataType=_.dataType,this.columnType=_.columnType,this.generated=_.generated,this.generatedIdentity=_.generatedIdentity}static[A]="Column";name;keyAsName;primary;notNull;default;defaultFn;onUpdateFn;hasDefault;isUnique;uniqueName;uniqueType;dataType;columnType;enumValues=void 0;generated=void 0;generatedIdentity=void 0;config;mapFromDriverValue(T){return T}mapToDriverValue(T){return T}shouldDisableInsert(){return this.config.generated!==void 0&&this.config.generated.type!=="byDefault"}}class I4{static[A]="ColumnBuilder";config;constructor(T,_,F){this.config={name:T,keyAsName:T==="",notNull:!1,default:void 0,hasDefault:!1,primaryKey:!1,isUnique:!1,uniqueName:void 0,uniqueType:void 0,dataType:_,columnType:F,generated:void 0}}$type(){return this}notNull(){return this.config.notNull=!0,this}default(T){return this.config.default=T,this.config.hasDefault=!0,this}$defaultFn(T){return this.config.defaultFn=T,this.config.hasDefault=!0,this}$default=this.$defaultFn;$onUpdateFn(T){return this.config.onUpdateFn=T,this.config.hasDefault=!0,this}$onUpdate=this.$onUpdateFn;primaryKey(){return this.config.primaryKey=!0,this.config.notNull=!0,this}setName(T){if(this.config.name!=="")return;this.config.name=T}}var j_=Symbol.for("drizzle:Name");class N4{static[A]="PgForeignKeyBuilder";reference;_onUpdate="no action";_onDelete="no action";constructor(T,_){if(this.reference=()=>{let{name:F,columns:W,foreignColumns:J}=T();return{name:F,columns:W,foreignTable:J[0].table,foreignColumns:J}},_)this._onUpdate=_.onUpdate,this._onDelete=_.onDelete}onUpdate(T){return this._onUpdate=T===void 0?"no action":T,this}onDelete(T){return this._onDelete=T===void 0?"no action":T,this}build(T){return new R$(T,this)}}class R${constructor(T,_){this.table=T,this.reference=_.reference,this.onUpdate=_._onUpdate,this.onDelete=_._onDelete}static[A]="PgForeignKey";reference;onUpdate;onDelete;getName(){let{name:T,columns:_,foreignColumns:F}=this.reference(),W=_.map(($)=>$.name),J=F.map(($)=>$.name),Y=[this.table[j_],...W,F[0].table[j_],...J];return T??`${Y.join("_")}_fk`}}function Y1(T,..._){return T(..._)}function K$(T,_){return`${T[j_]}_${_.join("_")}_unique`}function V$(T,_,F){for(let W=_;W<T.length;W++){let J=T[W];if(J==="\\"){W++;continue}if(J==='"')return[T.slice(_,W).replace(/\\/g,""),W+1];if(F)continue;if(J===","||J==="}")return[T.slice(_,W).replace(/\\/g,""),W]}return[T.slice(_).replace(/\\/g,""),T.length]}function D$(T,_=0){let F=[],W=_,J=!1;while(W<T.length){let Y=T[W];if(Y===","){if(J||W===_)F.push("");J=!0,W++;continue}if(J=!1,Y==="\\"){W+=2;continue}if(Y==='"'){let[G,X]=V$(T,W+1,!0);F.push(G),W=X;continue}if(Y==="}")return[F,W+1];if(Y==="{"){let[G,X]=D$(T,W+1);F.push(G),W=X;continue}let[$,Z]=V$(T,W,!1);F.push($),W=Z}return[F,W]}function L$(T){let[_]=D$(T,1);return _}function C4(T){return`{${T.map((_)=>{if(Array.isArray(_))return C4(_);if(typeof _==="string")return`"${_.replace(/\\/g,"\\\\").replace(/"/g,"\\\"")}"`;return`${_}`}).join(",")}}`}class f extends I4{foreignKeyConfigs=[];static[A]="PgColumnBuilder";array(T){return new I$(this.config.name,this,T)}references(T,_={}){return this.foreignKeyConfigs.push({ref:T,actions:_}),this}unique(T,_){return this.config.isUnique=!0,this.config.uniqueName=T,this.config.uniqueType=_?.nulls,this}generatedAlwaysAs(T){return this.config.generated={as:T,type:"always",mode:"stored"},this}buildForeignKeys(T,_){return this.foreignKeyConfigs.map(({ref:F,actions:W})=>{return Y1((J,Y)=>{let $=new N4(()=>{let Z=J();return{columns:[T],foreignColumns:[Z]}});if(Y.onUpdate)$.onUpdate(Y.onUpdate);if(Y.onDelete)$.onDelete(Y.onDelete);return $.build(_)},F,W)})}buildExtraConfigColumn(T){return new S$(T,this.config)}}class S extends XT{constructor(T,_){if(!_.uniqueName)_.uniqueName=K$(T,[_.name]);super(T,_);this.table=T}static[A]="PgColumn"}class S$ extends S{static[A]="ExtraConfigColumn";getSQLType(){return this.getSQLType()}indexConfig={order:this.config.order??"asc",nulls:this.config.nulls??"last",opClass:this.config.opClass};defaultConfig={order:"asc",nulls:"last",opClass:void 0};asc(){return this.indexConfig.order="asc",this}desc(){return this.indexConfig.order="desc",this}nullsFirst(){return this.indexConfig.nulls="first",this}nullsLast(){return this.indexConfig.nulls="last",this}op(T){return this.indexConfig.opClass=T,this}}class aF{static[A]="IndexedColumn";constructor(T,_,F,W){this.name=T,this.keyAsName=_,this.type=F,this.indexConfig=W}name;keyAsName;type;indexConfig}class I$ extends f{static[A]="PgArrayBuilder";constructor(T,_,F){super(T,"array","PgArray");this.config.baseBuilder=_,this.config.size=F}build(T){let _=this.config.baseBuilder.build(T);return new B4(T,this.config,_)}}class B4 extends S{constructor(T,_,F,W){super(T,_);this.baseColumn=F,this.range=W,this.size=_.size}size;static[A]="PgArray";getSQLType(){return`${this.baseColumn.getSQLType()}[${typeof this.size==="number"?this.size:""}]`}mapFromDriverValue(T){if(typeof T==="string")T=L$(T);return T.map((_)=>this.baseColumn.mapFromDriverValue(_))}mapToDriverValue(T,_=!1){let F=T.map((W)=>W===null?null:E(this.baseColumn,B4)?this.baseColumn.mapToDriverValue(W,!0):this.baseColumn.mapToDriverValue(W));if(_)return F;return C4(F)}}class N$ extends f{static[A]="PgEnumObjectColumnBuilder";constructor(T,_){super(T,"string","PgEnumObjectColumn");this.config.enum=_}build(T){return new C$(T,this.config)}}class C$ extends S{static[A]="PgEnumObjectColumn";enum;enumValues=this.config.enum.enumValues;constructor(T,_){super(T,_);this.enum=_.enum}getSQLType(){return this.enum.enumName}}var $1=Symbol.for("drizzle:isPgEnum");function B$(T){return!!T&&typeof T==="function"&&$1 in T&&T[$1]===!0}class k$ extends f{static[A]="PgEnumColumnBuilder";constructor(T,_){super(T,"string","PgEnumColumn");this.config.enum=_}build(T){return new f$(T,this.config)}}class f$ extends S{static[A]="PgEnumColumn";enum=this.config.enum;enumValues=this.config.enum.enumValues;constructor(T,_){super(T,_);this.enum=_.enum}getSQLType(){return this.enum.enumName}}function eF(T,_){return Array.isArray(_)?i7(T,[..._],void 0):n7(T,_,void 0)}function i7(T,_,F){let W=Object.assign((J)=>new k$(J??"",W),{enumName:T,enumValues:_,schema:F,[$1]:!0});return W}function n7(T,_,F){let W=Object.assign((J)=>new N$(J??"",W),{enumName:T,enumValues:Object.values(_),schema:F,[$1]:!0});return W}class jT{static[A]="Subquery";constructor(T,_,F,W=!1){this._={brand:"Subquery",sql:T,selectedFields:_,alias:F,isWith:W}}}class TW extends jT{static[A]="WithSubquery"}var q$="0.43.1";var k4,f4,GT={startActiveSpan(T,_){if(!k4)return _();if(!f4)f4=k4.trace.getTracer("drizzle-orm",q$);return Y1((F,W)=>W.startActiveSpan(T,(J)=>{try{return _(J)}catch(Y){throw J.setStatus({code:F.SpanStatusCode.ERROR,message:Y instanceof Error?Y.message:"Unknown error"}),Y}finally{J.end()}}),k4,f4)}};var MT=Symbol.for("drizzle:ViewBaseConfig");var Z1=Symbol.for("drizzle:Schema"),X1=Symbol.for("drizzle:Columns"),P$=Symbol.for("drizzle:ExtraConfigColumns"),q4=Symbol.for("drizzle:OriginalName"),P4=Symbol.for("drizzle:BaseName"),_W=Symbol.for("drizzle:IsAlias"),j$=Symbol.for("drizzle:ExtraConfigBuilder"),r7=Symbol.for("drizzle:IsDrizzleTable");class B{static[A]="Table";static Symbol={Name:j_,Schema:Z1,OriginalName:q4,Columns:X1,ExtraConfigColumns:P$,BaseName:P4,IsAlias:_W,ExtraConfigBuilder:j$};[j_];[q4];[Z1];[X1];[P$];[P4];[_W]=!1;[r7]=!0;[j$]=void 0;constructor(T,_,F){this[j_]=this[q4]=T,this[Z1]=_,this[P4]=F}}function vT(T){return T[j_]}function C0(T){return`${T[Z1]??"public"}.${T[j_]}`}function j4(T){return T!==null&&T!==void 0&&typeof T.getSQL==="function"}function s7(T){let _={sql:"",params:[]};for(let F of T)if(_.sql+=F.sql,_.params.push(...F.params),F.typings?.length){if(!_.typings)_.typings=[];_.typings.push(...F.typings)}return _}class yT{static[A]="StringChunk";value;constructor(T){this.value=Array.isArray(T)?T:[T]}getSQL(){return new k([this])}}class k{constructor(T){this.queryChunks=T}static[A]="SQL";decoder=v$;shouldInlineParams=!1;append(T){return this.queryChunks.push(...T.queryChunks),this}toQuery(T){return GT.startActiveSpan("drizzle.buildSQL",(_)=>{let F=this.buildQueryFromSourceParams(this.queryChunks,T);return _?.setAttributes({"drizzle.query.text":F.sql,"drizzle.query.params":JSON.stringify(F.params)}),F})}buildQueryFromSourceParams(T,_){let F=Object.assign({},_,{inlineParams:_.inlineParams||this.shouldInlineParams,paramStartIndex:_.paramStartIndex||{value:0}}),{casing:W,escapeName:J,escapeParam:Y,prepareTyping:$,inlineParams:Z,paramStartIndex:G}=F;return s7(T.map((X)=>{if(E(X,yT))return{sql:X.value.join(""),params:[]};if(E(X,G1))return{sql:J(X.value),params:[]};if(X===void 0)return{sql:"",params:[]};if(Array.isArray(X)){let U=[new yT("(")];for(let[M,Q]of X.entries())if(U.push(Q),M<X.length-1)U.push(new yT(", "));return U.push(new yT(")")),this.buildQueryFromSourceParams(U,F)}if(E(X,k))return this.buildQueryFromSourceParams(X.queryChunks,{...F,inlineParams:Z||X.shouldInlineParams});if(E(X,B)){let U=X[B.Symbol.Schema],M=X[B.Symbol.Name];return{sql:U===void 0||X[_W]?J(M):J(U)+"."+J(M),params:[]}}if(E(X,XT)){let U=W.getColumnCasing(X);if(_.invokeSource==="indexes")return{sql:J(U),params:[]};let M=X.table[B.Symbol.Schema];return{sql:X.table[_W]||M===void 0?J(X.table[B.Symbol.Name])+"."+J(U):J(M)+"."+J(X.table[B.Symbol.Name])+"."+J(U),params:[]}}if(E(X,Z_)){let U=X[MT].schema,M=X[MT].name;return{sql:U===void 0||X[MT].isAlias?J(M):J(U)+"."+J(M),params:[]}}if(E(X,Q_)){if(E(X.value,Q0))return{sql:Y(G.value++,X),params:[X],typings:["none"]};let U=X.value===null?null:X.encoder.mapToDriverValue(X.value);if(E(U,k))return this.buildQueryFromSourceParams([U],F);if(Z)return{sql:this.mapInlineParam(U,F),params:[]};let M=["none"];if($)M=[$(X.encoder)];return{sql:Y(G.value++,U),params:[U],typings:M}}if(E(X,Q0))return{sql:Y(G.value++,X),params:[X],typings:["none"]};if(E(X,k.Aliased)&&X.fieldAlias!==void 0)return{sql:J(X.fieldAlias),params:[]};if(E(X,jT)){if(X._.isWith)return{sql:J(X._.alias),params:[]};return this.buildQueryFromSourceParams([new yT("("),X._.sql,new yT(") "),new G1(X._.alias)],F)}if(B$(X)){if(X.schema)return{sql:J(X.schema)+"."+J(X.enumName),params:[]};return{sql:J(X.enumName),params:[]}}if(j4(X)){if(X.shouldOmitSQLParens?.())return this.buildQueryFromSourceParams([X.getSQL()],F);return this.buildQueryFromSourceParams([new yT("("),X.getSQL(),new yT(")")],F)}if(Z)return{sql:this.mapInlineParam(X,F),params:[]};return{sql:Y(G.value++,X),params:[X],typings:["none"]}}))}mapInlineParam(T,{escapeString:_}){if(T===null)return"null";if(typeof T==="number"||typeof T==="boolean")return T.toString();if(typeof T==="string")return _(T);if(typeof T==="object"){let F=T.toString();if(F==="[object Object]")return _(JSON.stringify(T));return _(F)}throw new Error("Unexpected param value: "+T)}getSQL(){return this}as(T){if(T===void 0)return this;return new k.Aliased(this,T)}mapWith(T){return this.decoder=typeof T==="function"?{mapFromDriverValue:T}:T,this}inlineParams(){return this.shouldInlineParams=!0,this}if(T){return T?this:void 0}}class G1{constructor(T){this.value=T}static[A]="Name";brand;getSQL(){return new k([this])}}function y$(T){return typeof T==="object"&&T!==null&&"mapToDriverValue"in T&&typeof T.mapToDriverValue==="function"}var v$={mapFromDriverValue:(T)=>T},b$={mapToDriverValue:(T)=>T},KC={...v$,...b$};class Q_{constructor(T,_=b$){this.value=T,this.encoder=_}static[A]="Param";brand;getSQL(){return new k([this])}}function O(T,..._){let F=[];if(_.length>0||T.length>0&&T[0]!=="")F.push(new yT(T[0]));for(let[W,J]of _.entries())F.push(J,new yT(T[W+1]));return new k(F)}((T)=>{function _(){return new k([])}T.empty=_;function F(G){return new k(G)}T.fromList=F;function W(G){return new k([new yT(G)])}T.raw=W;function J(G,X){let U=[];for(let[M,Q]of G.entries()){if(M>0&&X!==void 0)U.push(X);U.push(Q)}return new k(U)}T.join=J;function Y(G){return new G1(G)}T.identifier=Y;function $(G){return new Q0(G)}T.placeholder=$;function Z(G,X){return new Q_(G,X)}T.param=Z})(O||(O={}));((T)=>{class _{constructor(F,W){this.sql=F,this.fieldAlias=W}static[A]="SQL.Aliased";isSelectionField=!1;getSQL(){return this.sql}clone(){return new _(this.sql,this.fieldAlias)}}T.Aliased=_})(k||(k={}));class Q0{constructor(T){this.name=T}static[A]="Placeholder";getSQL(){return new k([this])}}function y4(T,_){return T.map((F)=>{if(E(F,Q0)){if(!(F.name in _))throw new Error(`No value for placeholder "${F.name}" was provided`);return _[F.name]}if(E(F,Q_)&&E(F.value,Q0)){if(!(F.value.name in _))throw new Error(`No value for placeholder "${F.value.name}" was provided`);return F.encoder.mapToDriverValue(_[F.value.name])}return F})}var a7=Symbol.for("drizzle:IsDrizzleView");class Z_{static[A]="View";[MT];[a7]=!0;constructor({name:T,schema:_,selectedFields:F,query:W}){this[MT]={name:T,originalName:T,schema:_,selectedFields:F,query:W,isExisting:!W,isAlias:!1}}getSQL(){return new k([this])}}XT.prototype.getSQL=function(){return new k([this])};B.prototype.getSQL=function(){return new k([this])};jT.prototype.getSQL=function(){return new k([this])};class YF{constructor(T){this.table=T}static[A]="ColumnAliasProxyHandler";get(T,_){if(_==="table")return this.table;return T[_]}}class FW{constructor(T,_){this.alias=T,this.replaceOriginalName=_}static[A]="TableAliasProxyHandler";get(T,_){if(_===B.Symbol.IsAlias)return!0;if(_===B.Symbol.Name)return this.alias;if(this.replaceOriginalName&&_===B.Symbol.OriginalName)return this.alias;if(_===MT)return{...T[MT],name:this.alias,isAlias:!0};if(_===B.Symbol.Columns){let W=T[B.Symbol.Columns];if(!W)return W;let J={};return Object.keys(W).map((Y)=>{J[Y]=new Proxy(W[Y],new YF(new Proxy(T,this)))}),J}let F=T[_];if(E(F,XT))return new Proxy(F,new YF(new Proxy(T,this)));return F}}function H1(T,_){return new Proxy(T,new FW(_,!1))}function m_(T,_){return new Proxy(T,new YF(new Proxy(T.table,new FW(_,!1))))}function v4(T,_){return new k.Aliased(WW(T.sql,_),T.fieldAlias)}function WW(T,_){return O.join(T.queryChunks.map((F)=>{if(E(F,XT))return m_(F,_);if(E(F,k))return WW(F,_);if(E(F,k.Aliased))return v4(F,_);return F}))}class A1 extends Error{static[A]="DrizzleError";constructor({message:T,cause:_}){super(T);this.name="DrizzleError",this.cause=_}}class b4 extends A1{static[A]="TransactionRollbackError";constructor(){super({message:"Rollback"})}}class x${static[A]="ConsoleLogWriter";write(T){console.log(T)}}class x4{static[A]="DefaultLogger";writer;constructor(T){this.writer=T?.writer??new x$}logQuery(T,_){let F=_.map((J)=>{try{return JSON.stringify(J)}catch{return String(J)}}),W=F.length?` -- params: [${F.join(", ")}]`:"";this.writer.write(`Query: ${T}${W}`)}}class h4{static[A]="NoopLogger";logQuery(){}}class sT{static[A]="QueryPromise";[Symbol.toStringTag]="QueryPromise";catch(T){return this.then(void 0,T)}finally(T){return this.then((_)=>{return T?.(),_},(_)=>{throw T?.(),_})}then(T,_){return this.execute().then(T,_)}}function h$(T,_,F){let W={},J=T.reduce((Y,{path:$,field:Z},G)=>{let X;if(E(Z,XT))X=Z;else if(E(Z,k))X=Z.decoder;else X=Z.sql.decoder;let U=Y;for(let[M,Q]of $.entries())if(M<$.length-1){if(!(Q in U))U[Q]={};U=U[Q]}else{let V=_[G],C=U[Q]=V===null?null:X.mapFromDriverValue(V);if(F&&E(Z,XT)&&$.length===2){let K=$[0];if(!(K in W))W[K]=C===null?vT(Z.table):!1;else if(typeof W[K]==="string"&&W[K]!==vT(Z.table))W[K]=!1}}return Y},{});if(F&&Object.keys(W).length>0){for(let[Y,$]of Object.entries(W))if(typeof $==="string"&&!F[$])J[Y]=null}return J}function D_(T,_){return Object.entries(T).reduce((F,[W,J])=>{if(typeof W!=="string")return F;let Y=_?[..._,W]:[W];if(E(J,XT)||E(J,k)||E(J,k.Aliased))F.push({path:Y,field:J});else if(E(J,B))F.push(...D_(J[B.Symbol.Columns],Y));else F.push(...D_(J,Y));return F},[])}function JW(T,_){let F=Object.keys(T),W=Object.keys(_);if(F.length!==W.length)return!1;for(let[J,Y]of F.entries())if(Y!==W[J])return!1;return!0}function U1(T,_){let F=Object.entries(_).filter(([,W])=>W!==void 0).map(([W,J])=>{if(E(J,k)||E(J,XT))return[W,J];else return[W,new Q_(J,T[B.Symbol.Columns][W])]});if(F.length===0)throw new Error("No values to set");return Object.fromEntries(F)}function p$(T,_){for(let F of _)for(let W of Object.getOwnPropertyNames(F.prototype)){if(W==="constructor")continue;Object.defineProperty(T.prototype,W,Object.getOwnPropertyDescriptor(F.prototype,W)||Object.create(null))}}function g$(T){return T[B.Symbol.Columns]}function a_(T){return E(T,jT)?T._.alias:E(T,Z_)?T[MT].name:E(T,k)?void 0:T[B.Symbol.IsAlias]?T[B.Symbol.Name]:T[B.Symbol.BaseName]}function a(T,_){return{name:typeof T==="string"&&T.length>0?T:"",config:typeof T==="object"?T:_}}function m$(T){if(typeof T!=="object"||T===null)return!1;if(T.constructor.name!=="Object")return!1;if("logger"in T){let _=typeof T.logger;if(_!=="boolean"&&(_!=="object"||typeof T.logger.logQuery!=="function")&&_!=="undefined")return!1;return!0}if("schema"in T){let _=typeof T.schema;if(_!=="object"&&_!=="undefined")return!1;return!0}if("casing"in T){let _=typeof T.casing;if(_!=="string"&&_!=="undefined")return!1;return!0}if("mode"in T){if(T.mode!=="default"||T.mode!=="planetscale"||T.mode!==void 0)return!1;return!0}if("connection"in T){let _=typeof T.connection;if(_!=="string"&&_!=="object"&&_!=="undefined")return!1;return!0}if("client"in T){let _=typeof T.client;if(_!=="object"&&_!=="function"&&_!=="undefined")return!1;return!0}if(Object.keys(T).length===0)return!0;return!1}class z0 extends f{static[A]="PgIntColumnBaseBuilder";generatedAlwaysAsIdentity(T){if(T){let{name:_,...F}=T;this.config.generatedIdentity={type:"always",sequenceName:_,sequenceOptions:F}}else this.config.generatedIdentity={type:"always"};return this.config.hasDefault=!0,this.config.notNull=!0,this}generatedByDefaultAsIdentity(T){if(T){let{name:_,...F}=T;this.config.generatedIdentity={type:"byDefault",sequenceName:_,sequenceOptions:F}}else this.config.generatedIdentity={type:"byDefault"};return this.config.hasDefault=!0,this.config.notNull=!0,this}}class o$ extends z0{static[A]="PgBigInt53Builder";constructor(T){super(T,"number","PgBigInt53")}build(T){return new u$(T,this.config)}}class u$ extends S{static[A]="PgBigInt53";getSQLType(){return"bigint"}mapFromDriverValue(T){if(typeof T==="number")return T;return Number(T)}}class c$ extends z0{static[A]="PgBigInt64Builder";constructor(T){super(T,"bigint","PgBigInt64")}build(T){return new d$(T,this.config)}}class d$ extends S{static[A]="PgBigInt64";getSQLType(){return"bigint"}mapFromDriverValue(T){return BigInt(T)}}function l$(T,_){let{name:F,config:W}=a(T,_);if(W.mode==="number")return new o$(F);return new c$(F)}class t$ extends f{static[A]="PgBigSerial53Builder";constructor(T){super(T,"number","PgBigSerial53");this.config.hasDefault=!0,this.config.notNull=!0}build(T){return new i$(T,this.config)}}class i$ extends S{static[A]="PgBigSerial53";getSQLType(){return"bigserial"}mapFromDriverValue(T){if(typeof T==="number")return T;return Number(T)}}class n$ extends f{static[A]="PgBigSerial64Builder";constructor(T){super(T,"bigint","PgBigSerial64");this.config.hasDefault=!0}build(T){return new r$(T,this.config)}}class r$ extends S{static[A]="PgBigSerial64";getSQLType(){return"bigserial"}mapFromDriverValue(T){return BigInt(T)}}function s$(T,_){let{name:F,config:W}=a(T,_);if(W.mode==="number")return new t$(F);return new n$(F)}class a$ extends f{static[A]="PgBooleanBuilder";constructor(T){super(T,"boolean","PgBoolean")}build(T){return new e$(T,this.config)}}class e$ extends S{static[A]="PgBoolean";getSQLType(){return"boolean"}}function YW(T){return new a$(T??"")}class TZ extends f{static[A]="PgCharBuilder";constructor(T,_){super(T,"string","PgChar");this.config.length=_.length,this.config.enumValues=_.enum}build(T){return new _Z(T,this.config)}}class _Z extends S{static[A]="PgChar";length=this.config.length;enumValues=this.config.enumValues;getSQLType(){return this.length===void 0?"char":`char(${this.length})`}}function FZ(T,_={}){let{name:F,config:W}=a(T,_);return new TZ(F,W)}class WZ extends f{static[A]="PgCidrBuilder";constructor(T){super(T,"string","PgCidr")}build(T){return new JZ(T,this.config)}}class JZ extends S{static[A]="PgCidr";getSQLType(){return"cidr"}}function YZ(T){return new WZ(T??"")}class $Z extends f{static[A]="PgCustomColumnBuilder";constructor(T,_,F){super(T,"custom","PgCustomColumn");this.config.fieldConfig=_,this.config.customTypeParams=F}build(T){return new ZZ(T,this.config)}}class ZZ extends S{static[A]="PgCustomColumn";sqlName;mapTo;mapFrom;constructor(T,_){super(T,_);this.sqlName=_.customTypeParams.dataType(_.fieldConfig),this.mapTo=_.customTypeParams.toDriver,this.mapFrom=_.customTypeParams.fromDriver}getSQLType(){return this.sqlName}mapFromDriverValue(T){return typeof this.mapFrom==="function"?this.mapFrom(T):T}mapToDriverValue(T){return typeof this.mapTo==="function"?this.mapTo(T):T}}function XZ(T){return(_,F)=>{let{name:W,config:J}=a(_,F);return new $Z(W,J,T)}}class e_ extends f{static[A]="PgDateColumnBaseBuilder";defaultNow(){return this.default(O`now()`)}}class GZ extends e_{static[A]="PgDateBuilder";constructor(T){super(T,"date","PgDate")}build(T){return new O1(T,this.config)}}class O1 extends S{static[A]="PgDate";getSQLType(){return"date"}mapFromDriverValue(T){return new Date(T)}mapToDriverValue(T){return T.toISOString()}}class HZ extends e_{static[A]="PgDateStringBuilder";constructor(T){super(T,"string","PgDateString")}build(T){return new M1(T,this.config)}}class M1 extends S{static[A]="PgDateString";getSQLType(){return"date"}}function AZ(T,_){let{name:F,config:W}=a(T,_);if(W?.mode==="date")return new GZ(F);return new HZ(F)}class UZ extends f{static[A]="PgDoublePrecisionBuilder";constructor(T){super(T,"number","PgDoublePrecision")}build(T){return new OZ(T,this.config)}}class OZ extends S{static[A]="PgDoublePrecision";getSQLType(){return"double precision"}mapFromDriverValue(T){if(typeof T==="string")return Number.parseFloat(T);return T}}function MZ(T){return new UZ(T??"")}class wZ extends f{static[A]="PgInetBuilder";constructor(T){super(T,"string","PgInet")}build(T){return new QZ(T,this.config)}}class QZ extends S{static[A]="PgInet";getSQLType(){return"inet"}}function zZ(T){return new wZ(T??"")}class EZ extends z0{static[A]="PgIntegerBuilder";constructor(T){super(T,"number","PgInteger")}build(T){return new RZ(T,this.config)}}class RZ extends S{static[A]="PgInteger";getSQLType(){return"integer"}mapFromDriverValue(T){if(typeof T==="string")return Number.parseInt(T);return T}}function $W(T){return new EZ(T??"")}class KZ extends f{static[A]="PgIntervalBuilder";constructor(T,_){super(T,"string","PgInterval");this.config.intervalConfig=_}build(T){return new VZ(T,this.config)}}class VZ extends S{static[A]="PgInterval";fields=this.config.intervalConfig.fields;precision=this.config.intervalConfig.precision;getSQLType(){let T=this.fields?` ${this.fields}`:"",_=this.precision?`(${this.precision})`:"";return`interval${T}${_}`}}function DZ(T,_={}){let{name:F,config:W}=a(T,_);return new KZ(F,W)}class LZ extends f{static[A]="PgJsonBuilder";constructor(T){super(T,"json","PgJson")}build(T){return new w1(T,this.config)}}class w1 extends S{static[A]="PgJson";constructor(T,_){super(T,_)}getSQLType(){return"json"}mapToDriverValue(T){return JSON.stringify(T)}mapFromDriverValue(T){if(typeof T==="string")try{return JSON.parse(T)}catch{return T}return T}}function SZ(T){return new LZ(T??"")}class IZ extends f{static[A]="PgJsonbBuilder";constructor(T){super(T,"json","PgJsonb")}build(T){return new Q1(T,this.config)}}class Q1 extends S{static[A]="PgJsonb";constructor(T,_){super(T,_)}getSQLType(){return"jsonb"}mapToDriverValue(T){return JSON.stringify(T)}mapFromDriverValue(T){if(typeof T==="string")try{return JSON.parse(T)}catch{return T}return T}}function NZ(T){return new IZ(T??"")}class CZ extends f{static[A]="PgLineBuilder";constructor(T){super(T,"array","PgLine")}build(T){return new BZ(T,this.config)}}class BZ extends S{static[A]="PgLine";getSQLType(){return"line"}mapFromDriverValue(T){let[_,F,W]=T.slice(1,-1).split(",");return[Number.parseFloat(_),Number.parseFloat(F),Number.parseFloat(W)]}mapToDriverValue(T){return`{${T[0]},${T[1]},${T[2]}}`}}class kZ extends f{static[A]="PgLineABCBuilder";constructor(T){super(T,"json","PgLineABC")}build(T){return new fZ(T,this.config)}}class fZ extends S{static[A]="PgLineABC";getSQLType(){return"line"}mapFromDriverValue(T){let[_,F,W]=T.slice(1,-1).split(",");return{a:Number.parseFloat(_),b:Number.parseFloat(F),c:Number.parseFloat(W)}}mapToDriverValue(T){return`{${T.a},${T.b},${T.c}}`}}function qZ(T,_){let{name:F,config:W}=a(T,_);if(!W?.mode||W.mode==="tuple")return new CZ(F);return new kZ(F)}class PZ extends f{static[A]="PgMacaddrBuilder";constructor(T){super(T,"string","PgMacaddr")}build(T){return new jZ(T,this.config)}}class jZ extends S{static[A]="PgMacaddr";getSQLType(){return"macaddr"}}function yZ(T){return new PZ(T??"")}class vZ extends f{static[A]="PgMacaddr8Builder";constructor(T){super(T,"string","PgMacaddr8")}build(T){return new bZ(T,this.config)}}class bZ extends S{static[A]="PgMacaddr8";getSQLType(){return"macaddr8"}}function xZ(T){return new vZ(T??"")}class hZ extends f{static[A]="PgNumericBuilder";constructor(T,_,F){super(T,"string","PgNumeric");this.config.precision=_,this.config.scale=F}build(T){return new z1(T,this.config)}}class z1 extends S{static[A]="PgNumeric";precision;scale;constructor(T,_){super(T,_);this.precision=_.precision,this.scale=_.scale}mapFromDriverValue(T){if(typeof T==="string")return T;return String(T)}getSQLType(){if(this.precision!==void 0&&this.scale!==void 0)return`numeric(${this.precision}, ${this.scale})`;else if(this.precision===void 0)return"numeric";else return`numeric(${this.precision})`}}class pZ extends f{static[A]="PgNumericNumberBuilder";constructor(T,_,F){super(T,"number","PgNumericNumber");this.config.precision=_,this.config.scale=F}build(T){return new gZ(T,this.config)}}class gZ extends S{static[A]="PgNumericNumber";precision;scale;constructor(T,_){super(T,_);this.precision=_.precision,this.scale=_.scale}mapFromDriverValue(T){if(typeof T==="number")return T;return Number(T)}mapToDriverValue=String;getSQLType(){if(this.precision!==void 0&&this.scale!==void 0)return`numeric(${this.precision}, ${this.scale})`;else if(this.precision===void 0)return"numeric";else return`numeric(${this.precision})`}}class mZ extends f{static[A]="PgNumericBigIntBuilder";constructor(T,_,F){super(T,"bigint","PgNumericBigInt");this.config.precision=_,this.config.scale=F}build(T){return new oZ(T,this.config)}}class oZ extends S{static[A]="PgNumericBigInt";precision;scale;constructor(T,_){super(T,_);this.precision=_.precision,this.scale=_.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 uZ(T,_){let{name:F,config:W}=a(T,_),J=W?.mode;return J==="number"?new pZ(F,W?.precision,W?.scale):J==="bigint"?new mZ(F,W?.precision,W?.scale):new hZ(F,W?.precision,W?.scale)}class cZ extends f{static[A]="PgPointTupleBuilder";constructor(T){super(T,"array","PgPointTuple")}build(T){return new dZ(T,this.config)}}class dZ extends S{static[A]="PgPointTuple";getSQLType(){return"point"}mapFromDriverValue(T){if(typeof T==="string"){let[_,F]=T.slice(1,-1).split(",");return[Number.parseFloat(_),Number.parseFloat(F)]}return[T.x,T.y]}mapToDriverValue(T){return`(${T[0]},${T[1]})`}}class lZ extends f{static[A]="PgPointObjectBuilder";constructor(T){super(T,"json","PgPointObject")}build(T){return new tZ(T,this.config)}}class tZ extends S{static[A]="PgPointObject";getSQLType(){return"point"}mapFromDriverValue(T){if(typeof T==="string"){let[_,F]=T.slice(1,-1).split(",");return{x:Number.parseFloat(_),y:Number.parseFloat(F)}}return T}mapToDriverValue(T){return`(${T.x},${T.y})`}}function iZ(T,_){let{name:F,config:W}=a(T,_);if(!W?.mode||W.mode==="tuple")return new cZ(F);return new lZ(F)}function e7(T){let _=[];for(let F=0;F<T.length;F+=2)_.push(Number.parseInt(T.slice(F,F+2),16));return new Uint8Array(_)}function nZ(T,_){let F=new ArrayBuffer(8),W=new DataView(F);for(let J=0;J<8;J++)W.setUint8(J,T[_+J]);return W.getFloat64(0,!0)}function p4(T){let _=e7(T),F=0,W=_[F];F+=1;let J=new DataView(_.buffer),Y=J.getUint32(F,W===1);F+=4;let $;if(Y&536870912)$=J.getUint32(F,W===1),F+=4;if((Y&65535)===1){let Z=nZ(_,F);F+=8;let G=nZ(_,F);return F+=8,[Z,G]}throw new Error("Unsupported geometry type")}class rZ extends f{static[A]="PgGeometryBuilder";constructor(T){super(T,"array","PgGeometry")}build(T){return new sZ(T,this.config)}}class sZ extends S{static[A]="PgGeometry";getSQLType(){return"geometry(point)"}mapFromDriverValue(T){return p4(T)}mapToDriverValue(T){return`point(${T[0]} ${T[1]})`}}class aZ extends f{static[A]="PgGeometryObjectBuilder";constructor(T){super(T,"json","PgGeometryObject")}build(T){return new eZ(T,this.config)}}class eZ extends S{static[A]="PgGeometryObject";getSQLType(){return"geometry(point)"}mapFromDriverValue(T){let _=p4(T);return{x:_[0],y:_[1]}}mapToDriverValue(T){return`point(${T.x} ${T.y})`}}function TX(T,_){let{name:F,config:W}=a(T,_);if(!W?.mode||W.mode==="tuple")return new rZ(F);return new aZ(F)}class _X extends f{static[A]="PgRealBuilder";constructor(T,_){super(T,"number","PgReal");this.config.length=_}build(T){return new FX(T,this.config)}}class FX extends S{static[A]="PgReal";constructor(T,_){super(T,_)}getSQLType(){return"real"}mapFromDriverValue=(T)=>{if(typeof T==="string")return Number.parseFloat(T);return T}}function WX(T){return new _X(T??"")}class JX extends f{static[A]="PgSerialBuilder";constructor(T){super(T,"number","PgSerial");this.config.hasDefault=!0,this.config.notNull=!0}build(T){return new YX(T,this.config)}}class YX extends S{static[A]="PgSerial";getSQLType(){return"serial"}}function $X(T){return new JX(T??"")}class ZX extends z0{static[A]="PgSmallIntBuilder";constructor(T){super(T,"number","PgSmallInt")}build(T){return new XX(T,this.config)}}class XX extends S{static[A]="PgSmallInt";getSQLType(){return"smallint"}mapFromDriverValue=(T)=>{if(typeof T==="string")return Number(T);return T}}function GX(T){return new ZX(T??"")}class HX extends f{static[A]="PgSmallSerialBuilder";constructor(T){super(T,"number","PgSmallSerial");this.config.hasDefault=!0,this.config.notNull=!0}build(T){return new AX(T,this.config)}}class AX extends S{static[A]="PgSmallSerial";getSQLType(){return"smallserial"}}function UX(T){return new HX(T??"")}class OX extends f{static[A]="PgTextBuilder";constructor(T,_){super(T,"string","PgText");this.config.enumValues=_.enum}build(T){return new MX(T,this.config)}}class MX extends S{static[A]="PgText";enumValues=this.config.enumValues;getSQLType(){return"text"}}function wX(T,_={}){let{name:F,config:W}=a(T,_);return new OX(F,W)}class QX extends e_{constructor(T,_,F){super(T,"string","PgTime");this.withTimezone=_,this.precision=F,this.config.withTimezone=_,this.config.precision=F}static[A]="PgTimeBuilder";build(T){return new E1(T,this.config)}}class E1 extends S{static[A]="PgTime";withTimezone;precision;constructor(T,_){super(T,_);this.withTimezone=_.withTimezone,this.precision=_.precision}getSQLType(){return`time${this.precision===void 0?"":`(${this.precision})`}${this.withTimezone?" with time zone":""}`}}function zX(T,_={}){let{name:F,config:W}=a(T,_);return new QX(F,W.withTimezone??!1,W.precision)}class EX extends e_{static[A]="PgTimestampBuilder";constructor(T,_,F){super(T,"date","PgTimestamp");this.config.withTimezone=_,this.config.precision=F}build(T){return new R1(T,this.config)}}class R1 extends S{static[A]="PgTimestamp";withTimezone;precision;constructor(T,_){super(T,_);this.withTimezone=_.withTimezone,this.precision=_.precision}getSQLType(){return`timestamp${this.precision===void 0?"":` (${this.precision})`}${this.withTimezone?" with time zone":""}`}mapFromDriverValue=(T)=>{return new Date(this.withTimezone?T:T+"+0000")};mapToDriverValue=(T)=>{return T.toISOString()}}class RX extends e_{static[A]="PgTimestampStringBuilder";constructor(T,_,F){super(T,"string","PgTimestampString");this.config.withTimezone=_,this.config.precision=F}build(T){return new K1(T,this.config)}}class K1 extends S{static[A]="PgTimestampString";withTimezone;precision;constructor(T,_){super(T,_);this.withTimezone=_.withTimezone,this.precision=_.precision}getSQLType(){return`timestamp${this.precision===void 0?"":`(${this.precision})`}${this.withTimezone?" with time zone":""}`}}function y_(T,_={}){let{name:F,config:W}=a(T,_);if(W?.mode==="string")return new RX(F,W.withTimezone??!1,W.precision);return new EX(F,W?.withTimezone??!1,W?.precision)}class KX extends f{static[A]="PgUUIDBuilder";constructor(T){super(T,"string","PgUUID")}defaultRandom(){return this.default(O`gen_random_uuid()`)}build(T){return new V1(T,this.config)}}class V1 extends S{static[A]="PgUUID";getSQLType(){return"uuid"}}function L_(T){return new KX(T??"")}class VX extends f{static[A]="PgVarcharBuilder";constructor(T,_){super(T,"string","PgVarchar");this.config.length=_.length,this.config.enumValues=_.enum}build(T){return new DX(T,this.config)}}class DX extends S{static[A]="PgVarchar";length=this.config.length;enumValues=this.config.enumValues;getSQLType(){return this.length===void 0?"varchar":`varchar(${this.length})`}}function aT(T,_={}){let{name:F,config:W}=a(T,_);return new VX(F,W)}class LX extends f{static[A]="PgBinaryVectorBuilder";constructor(T,_){super(T,"string","PgBinaryVector");this.config.dimensions=_.dimensions}build(T){return new SX(T,this.config)}}class SX extends S{static[A]="PgBinaryVector";dimensions=this.config.dimensions;getSQLType(){return`bit(${this.dimensions})`}}function IX(T,_){let{name:F,config:W}=a(T,_);return new LX(F,W)}class NX extends f{static[A]="PgHalfVectorBuilder";constructor(T,_){super(T,"array","PgHalfVector");this.config.dimensions=_.dimensions}build(T){return new CX(T,this.config)}}class CX extends S{static[A]="PgHalfVector";dimensions=this.config.dimensions;getSQLType(){return`halfvec(${this.dimensions})`}mapToDriverValue(T){return JSON.stringify(T)}mapFromDriverValue(T){return T.slice(1,-1).split(",").map((_)=>Number.parseFloat(_))}}function BX(T,_){let{name:F,config:W}=a(T,_);return new NX(F,W)}class kX extends f{static[A]="PgSparseVectorBuilder";constructor(T,_){super(T,"string","PgSparseVector");this.config.dimensions=_.dimensions}build(T){return new fX(T,this.config)}}class fX extends S{static[A]="PgSparseVector";dimensions=this.config.dimensions;getSQLType(){return`sparsevec(${this.dimensions})`}}function qX(T,_){let{name:F,config:W}=a(T,_);return new kX(F,W)}class PX extends f{static[A]="PgVectorBuilder";constructor(T,_){super(T,"array","PgVector");this.config.dimensions=_.dimensions}build(T){return new jX(T,this.config)}}class jX extends S{static[A]="PgVector";dimensions=this.config.dimensions;getSQLType(){return`vector(${this.dimensions})`}mapToDriverValue(T){return JSON.stringify(T)}mapFromDriverValue(T){return T.slice(1,-1).split(",").map((_)=>Number.parseFloat(_))}}function yX(T,_){let{name:F,config:W}=a(T,_);return new PX(F,W)}function vX(){return{bigint:l$,bigserial:s$,boolean:YW,char:FZ,cidr:YZ,customType:XZ,date:AZ,doublePrecision:MZ,inet:zZ,integer:$W,interval:DZ,json:SZ,jsonb:NZ,line:qZ,macaddr:yZ,macaddr8:xZ,numeric:uZ,point:iZ,geometry:TX,real:WX,serial:$X,smallint:GX,smallserial:UX,text:wX,time:zX,timestamp:y_,uuid:L_,varchar:aT,bit:IX,halfvec:BX,sparsevec:qX,vector:yX}}var g4=Symbol.for("drizzle:PgInlineForeignKeys"),bX=Symbol.for("drizzle:EnableRLS");class hT extends B{static[A]="PgTable";static Symbol=Object.assign({},B.Symbol,{InlineForeignKeys:g4,EnableRLS:bX});[g4]=[];[bX]=!1;[B.Symbol.ExtraConfigBuilder]=void 0;[B.Symbol.ExtraConfigColumns]={}}function T3(T,_,F,W,J=T){let Y=new hT(T,W,J),$=typeof _==="function"?_(vX()):_,Z=Object.fromEntries(Object.entries($).map(([U,M])=>{let Q=M;Q.setName(U);let V=Q.build(Y);return Y[g4].push(...Q.buildForeignKeys(V,Y)),[U,V]})),G=Object.fromEntries(Object.entries($).map(([U,M])=>{let Q=M;Q.setName(U);let V=Q.buildExtraConfigColumn(Y);return[U,V]})),X=Object.assign(Y,Z);if(X[B.Symbol.Columns]=Z,X[B.Symbol.ExtraConfigColumns]=G,F)X[hT.Symbol.ExtraConfigBuilder]=F;return Object.assign(X,{enableRLS:()=>{return X[hT.Symbol.EnableRLS]=!0,X}})}var E0=(T,_,F)=>{return T3(T,_,F,void 0)};function xX(...T){if(T[0].columns)return new ZW(T[0].columns,T[0].name);return new ZW(T)}class ZW{static[A]="PgPrimaryKeyBuilder";columns;name;constructor(T,_){this.columns=T,this.name=_}build(T){return new hX(T,this.columns,this.name)}}class hX{constructor(T,_,F){this.table=T,this.columns=_,this.name=F}static[A]="PgPrimaryKey";columns;name;getName(){return this.name??`${this.table[hT.Symbol.Name]}_${this.columns.map((T)=>T.name).join("_")}_pk`}}function X_(T,_){if(y$(_)&&!j4(T)&&!E(T,Q_)&&!E(T,Q0)&&!E(T,XT)&&!E(T,B)&&!E(T,Z_))return new Q_(T,_);return T}var D1=(T,_)=>{return O`${T} = ${X_(_,T)}`},pX=(T,_)=>{return O`${T} <> ${X_(_,T)}`};function XW(...T){let _=T.filter((F)=>F!==void 0);if(_.length===0)return;if(_.length===1)return new k(_);return new k([new yT("("),O.join(_,new yT(" and ")),new yT(")")])}function gX(...T){let _=T.filter((F)=>F!==void 0);if(_.length===0)return;if(_.length===1)return new k(_);return new k([new yT("("),O.join(_,new yT(" or ")),new yT(")")])}function mX(T){return O`not ${T}`}var oX=(T,_)=>{return O`${T} > ${X_(_,T)}`},uX=(T,_)=>{return O`${T} >= ${X_(_,T)}`},cX=(T,_)=>{return O`${T} < ${X_(_,T)}`},dX=(T,_)=>{return O`${T} <= ${X_(_,T)}`};function lX(T,_){if(Array.isArray(_)){if(_.length===0)return O`false`;return O`${T} in ${_.map((F)=>X_(F,T))}`}return O`${T} in ${X_(_,T)}`}function tX(T,_){if(Array.isArray(_)){if(_.length===0)return O`true`;return O`${T} not in ${_.map((F)=>X_(F,T))}`}return O`${T} not in ${X_(_,T)}`}function iX(T){return O`${T} is null`}function nX(T){return O`${T} is not null`}function rX(T){return O`exists ${T}`}function sX(T){return O`not exists ${T}`}function aX(T,_,F){return O`${T} between ${X_(_,T)} and ${X_(F,T)}`}function eX(T,_,F){return O`${T} not between ${X_(_,T)} and ${X_(F,T)}`}function T5(T,_){return O`${T} like ${_}`}function _5(T,_){return O`${T} not like ${_}`}function F5(T,_){return O`${T} ilike ${_}`}function W5(T,_){return O`${T} not ilike ${_}`}function J5(T){return O`${T} asc`}function Y5(T){return O`${T} desc`}class m4{constructor(T,_,F){this.sourceTable=T,this.referencedTable=_,this.relationName=F,this.referencedTableName=_[B.Symbol.Name]}static[A]="Relation";referencedTableName;fieldName}class $5{constructor(T,_){this.table=T,this.config=_}static[A]="Relations"}class R0 extends m4{constructor(T,_,F,W){super(T,_,F?.relationName);this.config=F,this.isNullable=W}static[A]="One";withFieldName(T){let _=new R0(this.sourceTable,this.referencedTable,this.config,this.isNullable);return _.fieldName=T,_}}class GW extends m4{constructor(T,_,F){super(T,_,F?.relationName);this.config=F}static[A]="Many";withFieldName(T){let _=new GW(this.sourceTable,this.referencedTable,this.config);return _.fieldName=T,_}}function Z5(){return{and:XW,between:aX,eq:D1,exists:rX,gt:oX,gte:uX,ilike:F5,inArray:lX,isNull:iX,isNotNull:nX,like:T5,lt:cX,lte:dX,ne:pX,not:mX,notBetween:eX,notExists:sX,notLike:_5,notIlike:W5,notInArray:tX,or:gX,sql:O}}function X5(){return{sql:O,asc:J5,desc:Y5}}function G5(T,_){if(Object.keys(T).length===1&&"default"in T&&!E(T.default,B))T=T.default;let F={},W={},J={};for(let[Y,$]of Object.entries(T))if(E($,B)){let Z=C0($),G=W[Z];F[Z]=Y,J[Y]={tsName:Y,dbName:$[B.Symbol.Name],schema:$[B.Symbol.Schema],columns:$[B.Symbol.Columns],relations:G?.relations??{},primaryKey:G?.primaryKey??[]};for(let U of Object.values($[B.Symbol.Columns]))if(U.primary)J[Y].primaryKey.push(U);let X=$[B.Symbol.ExtraConfigBuilder]?.($[B.Symbol.ExtraConfigColumns]);if(X){for(let U of Object.values(X))if(E(U,ZW))J[Y].primaryKey.push(...U.columns)}}else if(E($,$5)){let Z=C0($.table),G=F[Z],X=$.config(_($.table)),U;for(let[M,Q]of Object.entries(X))if(G){let V=J[G];if(V.relations[M]=Q,U)V.primaryKey.push(...U)}else{if(!(Z in W))W[Z]={relations:{},primaryKey:U};W[Z].relations[M]=Q}}return{tables:J,tableNamesMap:F}}function _3(T){return function _(F,W){return new R0(T,F,W,W?.fields.reduce((J,Y)=>J&&Y.notNull,!0)??!1)}}function F3(T){return function _(F,W){return new GW(T,F,W)}}function H5(T,_,F){if(E(F,R0)&&F.config)return{fields:F.config.fields,references:F.config.references};let W=_[C0(F.referencedTable)];if(!W)throw new Error(`Table "${F.referencedTable[B.Symbol.Name]}" not found in schema`);let J=T[W];if(!J)throw new Error(`Table "${W}" not found in schema`);let Y=F.sourceTable,$=_[C0(Y)];if(!$)throw new Error(`Table "${Y[B.Symbol.Name]}" not found in schema`);let Z=[];for(let G of Object.values(J.relations))if(F.relationName&&F!==G&&G.relationName===F.relationName||!F.relationName&&G.referencedTable===F.sourceTable)Z.push(G);if(Z.length>1)throw F.relationName?new Error(`There are multiple relations with name "${F.relationName}" in table "${W}"`):new Error(`There are multiple relations between "${W}" and "${F.sourceTable[B.Symbol.Name]}". Please specify relation name`);if(Z[0]&&E(Z[0],R0)&&Z[0].config)return{fields:Z[0].config.references,references:Z[0].config.fields};throw new Error(`There is not enough information to infer relation "${$}.${F.fieldName}"`)}function A5(T){return{one:_3(T),many:F3(T)}}function L1(T,_,F,W,J=(Y)=>Y){let Y={};for(let[$,Z]of W.entries())if(Z.isJson){let G=_.relations[Z.tsKey],X=F[$],U=typeof X==="string"?JSON.parse(X):X;Y[Z.tsKey]=E(G,R0)?U&&L1(T,T[Z.relationTableTsKey],U,Z.selection,J):U.map((M)=>L1(T,T[Z.relationTableTsKey],M,Z.selection,J))}else{let G=J(F[$]),X=Z.field,U;if(E(X,XT))U=X;else if(E(X,k))U=X.decoder;else U=X.sql.decoder;Y[Z.tsKey]=G===null?null:U.mapFromDriverValue(G)}return Y}import N3 from"os";import C3 from"fs";var S1=new Map,o4=new Map,u4=Symbol("OriginError"),$F={};class S_ extends Promise{constructor(T,_,F,W,J={}){let Y,$;super((Z,G)=>{Y=Z,$=G});this.tagged=Array.isArray(T.raw),this.strings=T,this.args=_,this.handler=F,this.canceller=W,this.options=J,this.state=null,this.statement=null,this.resolve=(Z)=>(this.active=!1,Y(Z)),this.reject=(Z)=>(this.active=!1,$(Z)),this.active=!1,this.cancelled=null,this.executed=!1,this.signature="",this[u4]=this.handler.debug?new Error:this.tagged&&W3(this.strings)}get origin(){return(this.handler.debug?this[u4].stack:this.tagged&&o4.has(this.strings)?o4.get(this.strings):o4.set(this.strings,this[u4].stack).get(this.strings))||""}static get[Symbol.species](){return Promise}cancel(){return this.canceller&&(this.canceller(this),this.canceller=null)}simple(){return this.options.simple=!0,this.options.prepare=!1,this}async readable(){return this.simple(),this.streaming=!0,this}async writable(){return this.simple(),this.streaming=!0,this}cursor(T=1,_){if(this.options.simple=!1,typeof T==="function")_=T,T=1;if(this.cursorRows=T,typeof _==="function")return this.cursorFn=_,this;let F;return{[Symbol.asyncIterator]:()=>({next:()=>{if(this.executed&&!this.active)return{done:!0};F&&F();let W=new Promise((J,Y)=>{this.cursorFn=($)=>{return J({value:$,done:!1}),new Promise((Z)=>F=Z)},this.resolve=()=>(this.active=!1,J({done:!0})),this.reject=($)=>(this.active=!1,Y($))});return this.execute(),W},return(){return F&&F($F),{done:!0}}})}}describe(){return this.options.simple=!1,this.onlyDescribe=this.options.prepare=!0,this}stream(){throw new Error(".stream has been renamed to .forEach")}forEach(T){return this.forEachFn=T,this.handle(),this}raw(){return this.isRaw=!0,this}values(){return this.isRaw="values",this}async handle(){!this.executed&&(this.executed=!0)&&await 1&&this.handler(this)}execute(){return this.handle(),this}then(){return this.handle(),super.then.apply(this,arguments)}catch(){return this.handle(),super.catch.apply(this,arguments)}finally(){return this.handle(),super.finally.apply(this,arguments)}}function W3(T){if(S1.has(T))return S1.get(T);let _=Error.stackTraceLimit;return Error.stackTraceLimit=4,S1.set(T,new Error),Error.stackTraceLimit=_,S1.get(T)}class ZF extends Error{constructor(T){super(T.message);this.name=this.constructor.name,Object.assign(this,T)}}var CT={connection:U5,postgres:O5,generic:M5,notSupported:w5};function U5(T,_,F){let{host:W,port:J}=F||_,Y=Object.assign(new Error("write "+T+" "+(_.path||W+":"+J)),{code:T,errno:T,address:_.path||W},_.path?{}:{port:J});return Error.captureStackTrace(Y,U5),Y}function O5(T){let _=new ZF(T);return Error.captureStackTrace(_,O5),_}function M5(T,_){let F=Object.assign(new Error(T+": "+_),{code:T});return Error.captureStackTrace(F,M5),F}function w5(T){let _=Object.assign(new Error(T+" (B) is not supported"),{code:"MESSAGE_NOT_SUPPORTED",name:T});return Error.captureStackTrace(_,w5),_}var J3={string:{to:25,from:null,serialize:(T)=>""+T},number:{to:0,from:[21,23,26,700,701],serialize:(T)=>""+T,parse:(T)=>+T},json:{to:114,from:[114,3802],serialize:(T)=>JSON.stringify(T),parse:(T)=>JSON.parse(T)},boolean:{to:16,from:16,serialize:(T)=>T===!0?"t":"f",parse:(T)=>T==="t"},date:{to:1184,from:[1082,1114,1184],serialize:(T)=>(T instanceof Date?T:new Date(T)).toISOString(),parse:(T)=>new Date(T)},bytea:{to:17,from:17,serialize:(T)=>"\\x"+Buffer.from(T).toString("hex"),parse:(T)=>Buffer.from(T.slice(2),"hex")}};class C1{then(){c4()}catch(){c4()}finally(){c4()}}class OW extends C1{constructor(T){super();this.value=f1(T)}}class o_ extends C1{constructor(T,_,F){super();this.value=T,this.type=_,this.array=F}}class B1 extends C1{constructor(T,_){super();this.first=T,this.rest=_}build(T,_,F,W){let J=Y3.map(([Y,$])=>({fn:$,i:T.search(Y)})).sort((Y,$)=>Y.i-$.i).pop();return J.i===-1?n4(this.first,W):J.fn(this.first,this.rest,_,F,W)}}function k1(T,_,F,W){let J=T instanceof o_?T.value:T;if(J===void 0){if(T instanceof o_?T.value=W.transform.undefined:J=T=W.transform.undefined,J===void 0)throw CT.generic("UNDEFINED_VALUE","Undefined values are not allowed")}return"$"+F.push(T instanceof o_?(_.push(T.value),T.array?T.array[T.type||N1(T.value)]||T.type||R5(T.value):T.type):(_.push(T),N1(T)))}var z5=V5(J3);function t4(T,_,F,W,J,Y){for(let $=1;$<T.strings.length;$++)_+=i4(_,F,W,J,Y)+T.strings[$],F=T.args[$];return _}function i4(T,_,F,W,J){return _ instanceof B1?_.build(T,F,W,J):_ instanceof S_?l4(_,F,W,J):_ instanceof OW?_.value:_&&_[0]instanceof S_?_.reduce((Y,$)=>Y+" "+l4($,F,W,J),""):k1(_,F,W,J)}function l4(T,_,F,W){return T.fragment=!0,t4(T,T.strings[0],T.args[0],_,F,W)}function E5(T,_,F,W,J){return T.map((Y)=>"("+W.map(($)=>i4("values",Y[$],_,F,J)).join(",")+")").join(",")}function Q5(T,_,F,W,J){let Y=Array.isArray(T[0]),$=_.length?_.flat():Object.keys(Y?T[0]:T);return E5(Y?T:[T],F,W,$,J)}function I1(T,_,F,W,J){if(typeof T==="string"&&(T=[T].concat(_)),Array.isArray(T))return n4(T,J);let Y;return(_.length?_.flat():Object.keys(T)).map((Z)=>{return Y=T[Z],(Y instanceof S_?l4(Y,F,W,J):Y instanceof OW?Y.value:k1(Y,F,W,J))+" as "+f1(J.transform.column.to?J.transform.column.to(Z):Z)}).join(",")}var Y3=Object.entries({values:Q5,in:(...T)=>{let _=Q5(...T);return _==="()"?"(null)":_},select:I1,as:I1,returning:I1,"\\(":I1,update(T,_,F,W,J){return(_.length?_.flat():Object.keys(T)).map((Y)=>f1(J.transform.column.to?J.transform.column.to(Y):Y)+"="+i4("values",T[Y],F,W,J))},insert(T,_,F,W,J){let Y=_.length?_.flat():Object.keys(Array.isArray(T)?T[0]:T);return"("+n4(Y,J)+")values"+E5(Array.isArray(T)?T:[T],F,W,Y,J)}}).map(([T,_])=>[new RegExp("((?:^|[\\s(])"+T+"(?:$|[\\s(]))(?![\\s\\S]*\\1)","i"),_]);function c4(){throw CT.generic("NOT_TAGGED_CALL","Query not called as a tagged template literal")}var{serializers:$3,parsers:Z3}=z5;function R5(T){if(Array.isArray(T))return R5(T[0]);return typeof T==="string"?1009:0}var K5=function(T){let _=V5(T||{});return{serializers:Object.assign({},$3,_.serializers),parsers:Object.assign({},Z3,_.parsers)}};function V5(T){return Object.keys(T).reduce((_,F)=>{if(T[F].from&&[].concat(T[F].from).forEach((W)=>_.parsers[W]=T[F].parse),T[F].serialize)_.serializers[T[F].to]=T[F].serialize,T[F].from&&[].concat(T[F].from).forEach((W)=>_.serializers[W]=T[F].serialize);return _},{parsers:{},serializers:{}})}function n4(T,{transform:{column:_}}){return T.map((F)=>f1(_.to?_.to(F):F)).join(",")}var f1=function T(_){return'"'+_.replace(/"/g,'""').replace(/\./g,'"."')+'"'},N1=function T(_){return _ instanceof o_?_.type:_ instanceof Date?1184:_ instanceof Uint8Array?17:_===!0||_===!1?16:typeof _==="bigint"?20:Array.isArray(_)?T(_[0]):0},X3=/\\/g,G3=/"/g;function H3(T){return T.replace(X3,"\\\\").replace(G3,"\\\"")}var D5=function T(_,F,W,J){if(Array.isArray(_)===!1)return _;if(!_.length)return"{}";let Y=_[0],$=J===1020?";":",";if(Array.isArray(Y)&&!Y.type)return"{"+_.map((Z)=>T(Z,F,W,J)).join($)+"}";return"{"+_.map((Z)=>{if(Z===void 0){if(Z=W.transform.undefined,Z===void 0)throw CT.generic("UNDEFINED_VALUE","Undefined values are not allowed")}return Z===null?"null":'"'+H3(F?F(Z.type?Z.value:Z):""+Z)+'"'}).join($)+"}"},d4={i:0,char:null,str:"",quoted:!1,last:0},L5=function T(_,F,W){return d4.i=d4.last=0,S5(d4,_,F,W)};function S5(T,_,F,W){let J=[],Y=W===1020?";":",";for(;T.i<_.length;T.i++){if(T.char=_[T.i],T.quoted)if(T.char==="\\")T.str+=_[++T.i];else if(T.char==='"')J.push(F?F(T.str):T.str),T.str="",T.quoted=_[T.i+1]==='"',T.last=T.i+2;else T.str+=T.char;else if(T.char==='"')T.quoted=!0;else if(T.char==="{")T.last=++T.i,J.push(S5(T,_,F,W));else if(T.char==="}"){T.quoted=!1,T.last<T.i&&J.push(F?F(_.slice(T.last,T.i)):_.slice(T.last,T.i)),T.last=T.i+1;break}else if(T.char===Y&&T.p!=="}"&&T.p!=='"')J.push(F?F(_.slice(T.last,T.i)):_.slice(T.last,T.i)),T.last=T.i+1;T.p=T.char}return T.last<T.i&&J.push(F?F(_.slice(T.last,T.i+1)):_.slice(T.last,T.i+1)),J}var B0=(T)=>{let _=T[0];for(let F=1;F<T.length;F++)_+=T[F]==="_"?T[++F].toUpperCase():T[F];return _},k0=(T)=>{let _=T[0].toUpperCase();for(let F=1;F<T.length;F++)_+=T[F]==="_"?T[++F].toUpperCase():T[F];return _},f0=(T)=>T.replace(/_/g,"-"),HW=(T)=>T.replace(/([A-Z])/g,"_$1").toLowerCase(),AW=(T)=>(T.slice(0,1)+T.slice(1).replace(/([A-Z])/g,"_$1")).toLowerCase(),UW=(T)=>T.replace(/-/g,"_");function r4(T){return function _(F,W){return typeof F==="object"&&F!==null&&(W.type===114||W.type===3802)?Array.isArray(F)?F.map((J)=>_(J,W)):Object.entries(F).reduce((J,[Y,$])=>Object.assign(J,{[T(Y)]:_($,W)}),{}):F}}B0.column={from:B0};B0.value={from:r4(B0)};HW.column={to:HW};var s4={...B0};s4.column.to=HW;k0.column={from:k0};k0.value={from:r4(k0)};AW.column={to:AW};var a4={...k0};a4.column.to=AW;f0.column={from:f0};f0.value={from:r4(f0)};UW.column={to:UW};var e4={...f0};e4.column.to=UW;import I5 from"net";import M3 from"tls";import MW from"crypto";import T8 from"stream";import{performance as N5}from"perf_hooks";class q0 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 z_=A3;function A3(T=[]){let _=T.slice(),F=0;return{get length(){return _.length-F},remove:(W)=>{let J=_.indexOf(W);return J===-1?null:(_.splice(J,1),W)},push:(W)=>(_.push(W),W),shift:()=>{let W=_[F++];if(F===_.length)F=0,_=[];else _[F-1]=void 0;return W}}}var dT=Buffer.allocUnsafe(256),U3="BCcDdEFfHPpQSX".split("").reduce((T,_)=>{let F=_.charCodeAt(0);return T[_]=()=>{return dT[0]=F,YT.i=5,YT},T},{}),YT=Object.assign(O3,U3,{N:String.fromCharCode(0),i:0,inc(T){return YT.i+=T,YT},str(T){let _=Buffer.byteLength(T);return q1(_),YT.i+=dT.write(T,YT.i,_,"utf8"),YT},i16(T){return q1(2),dT.writeUInt16BE(T,YT.i),YT.i+=2,YT},i32(T,_){if(_||_===0)return dT.writeUInt32BE(T,_),YT;return q1(4),dT.writeUInt32BE(T,YT.i),YT.i+=4,YT},z(T){return q1(T),dT.fill(0,YT.i,YT.i+T),YT.i+=T,YT},raw(T){return dT=Buffer.concat([dT.subarray(0,YT.i),T]),YT.i=dT.length,YT},end(T=1){dT.writeUInt32BE(YT.i-T,T);let _=dT.subarray(0,YT.i);return YT.i=0,dT=Buffer.allocUnsafe(256),_}}),x=YT;function q1(T){if(dT.length-YT.i<T){let _=dT,F=_.length;dT=Buffer.allocUnsafe(F+(F>>1)+T),_.copy(dT)}}function O3(){return YT.i=0,YT}var W8=k5,w3=1,K0=x().S().end(),C5=x().H().end(),Q3=x().i32(8).i32(80877103).end(8),z3=Buffer.concat([x().E().str(x.N).i32(0).end(),K0]),E3=x().D().str("S").str(x.N).end(),XF=()=>{},R3=new Set(["FetchPreparedStatement","RevalidateCachedQuery","transformAssignedExpr"]),K3={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 k5(T,_={},{onopen:F=XF,onend:W=XF,onclose:J=XF}={}){let{ssl:Y,max:$,user:Z,host:G,port:X,database:U,parsers:M,transform:Q,onnotice:V,onnotify:C,onparameter:K,max_pipeline:v,keep_alive:P,backoff:j,target_session_attrs:y}=T,u=z_(),h=w3++,p={pid:null,secret:null},t=F8(c1,T.idle_timeout),ST=F8(c1,T.max_lifetime),H_=F8(s5,T.connect_timeout),L=null,$T,i=new q0,TT=Buffer.alloc(0),bT=T.fetch_types,A_={},I_={},y0=Math.random().toString(36).slice(2),D=1,o=0,JT=0,RT=0,BT=0,r=0,HT=0,IT=0,KT=null,wT=null,pT=!1,AT=null,N_=null,gT=null,T0=null,kT=null,QT=null,C_=null,v_=null,N=null,UF=null,mT={queue:_.closed,idleTimer:t,connect(H){gT=H||!0,k8()},terminate:MF,execute:OF,cancel:t5,end:c1,count:0,id:h};return _.closed&&_.closed.push(mT),mT;async function l5(){let H;try{H=T.socket?await Promise.resolve(T.socket(T)):new I5.Socket}catch(w){b0(w);return}return H.on("error",b0),H.on("close",f8),H.on("drain",C8),H}async function t5({pid:H,secret:w},g,_T){try{$T=x().i32(16).i32(80877102).i32(H).i32(w).end(16),await B8(),L.once("error",_T),L.once("close",g)}catch(DT){_T(DT)}}function OF(H){if(pT)return VW(H,CT.connection("CONNECTION_DESTROYED",T));if(H.cancelled)return;try{return H.state=p,N?u.push(H):(N=H,N.active=!0),r5(H),xT(i5(H))&&!H.describeFirst&&!H.cursorFn&&u.length<v&&(!H.options.onexecute||H.options.onexecute(mT))}catch(w){return u.length===0&&xT(K0),b_(w),!0}}function i5(H){if(H.parameters.length>=65534)throw CT.generic("MAX_PARAMETERS_EXCEEDED","Max number of parameters (65534) exceeded");return H.options.simple?x().Q().str(H.statement.string+x.N).end():H.describeFirst?Buffer.concat([S8(H),C5]):H.prepare?H.prepared?KW(H):Buffer.concat([S8(H),KW(H)]):n5(H)}function S8(H){return Buffer.concat([P8(H.statement.string,H.parameters,H.statement.types,H.statement.name),vG("S",H.statement.name)])}function KW(H){return Buffer.concat([yG(H.parameters,H.statement.types,H.statement.name,H.cursorName),H.cursorFn?j8("",H.cursorRows):z3])}function n5(H){return Buffer.concat([P8(H.statement.string,H.parameters,H.statement.types),E3,KW(H)])}function r5(H){let w=[],g=[],_T=t4(H,H.strings[0],H.args[0],w,g,T);!H.tagged&&H.args.forEach((DT)=>k1(DT,w,g,T)),H.prepare=T.prepare&&("prepare"in H.options?H.options.prepare:!0),H.string=_T,H.signature=H.prepare&&g+_T,H.onlyDescribe&&delete I_[H.signature],H.parameters=H.parameters||w,H.prepared=H.prepare&&H.signature in I_,H.describeFirst=H.onlyDescribe||w.length&&!H.prepared,H.statement=H.prepared?I_[H.signature]:{string:_T,types:g,name:H.prepare?y0+D++:""},typeof T.debug==="function"&&T.debug(h,_T,w,g)}function xT(H,w){if(QT=QT?Buffer.concat([QT,H]):Buffer.from(H),w||QT.length>=1024)return I8(w);return wT===null&&(wT=setImmediate(I8)),!0}function I8(H){let w=L.write(QT,H);return wT!==null&&clearImmediate(wT),QT=wT=null,w}function s5(){b_(CT.connection("CONNECT_TIMEOUT",T,L)),L.destroy()}async function N8(){if(xT(Q3),!await new Promise((w)=>L.once("data",(g)=>w(g[0]===83)))&&Y==="prefer")return v0();L.removeAllListeners(),L=M3.connect({socket:L,servername:I5.isIP(L.host)?void 0:L.host,...Y==="require"||Y==="allow"||Y==="prefer"?{rejectUnauthorized:!1}:Y==="verify-full"?{}:typeof Y==="object"?Y:{}}),L.on("secureConnect",v0),L.on("error",b0),L.on("close",f8),L.on("drain",C8)}function C8(){!N&&F(mT)}function u1(H){if(AT){if(AT.push(H),JT-=H.length,JT>=0)return}TT=AT?Buffer.concat(AT,r-JT):TT.length===0?H:Buffer.concat([TT,H],TT.length+H.length);while(TT.length>4){if(r=TT.readUInt32BE(1),r>=TT.length){JT=r-TT.length,AT=[TT];break}try{a5(TT.subarray(0,r+1))}catch(w){N&&(N.cursorFn||N.describeFirst)&&xT(K0),b_(w)}TT=TT.subarray(r+1),JT=0,AT=null}}async function B8(){if(pT=!1,A_={},L||(L=await l5()),!L)return;if(H_.start(),T.socket)return Y?N8():v0();if(L.on("connect",Y?N8:v0),T.path)return L.connect(T.path);L.ssl=Y,L.connect(X[RT],G[RT]),L.host=G[RT],L.port=X[RT],RT=(RT+1)%X.length}function k8(){setTimeout(B8,o?o+HT-N5.now():0)}function v0(){try{I_={},bT=T.fetch_types,y0=Math.random().toString(36).slice(2),D=1,ST.start(),L.on("data",u1),P&&L.setKeepAlive&&L.setKeepAlive(!0,1000*P);let H=xG();xT(H)}catch(H){b0(H)}}function b0(H){if(mT.queue===_.connecting&&T.host[BT+1])return;b_(H);while(u.length)VW(u.shift(),H)}function b_(H){kT&&(kT.destroy(H),kT=null),N&&VW(N,H),gT&&(VW(gT,H),gT=null)}function VW(H,w){"query"in w||"parameters"in w||Object.defineProperties(w,{stack:{value:w.stack+H.origin.replace(/.*\n/,`
|
|
50
|
-
`),enumerable:T.debug},query:{value:
|
|
47
|
+
`)+"}");class oW{config;resolvedConfig;name;get[tT](){return"scope"}referencesById={};references=[];resolutions={};exportedNames=[];aliases={};resolved=!1;nodesByHash={};intrinsic;constructor(T,_){if(this.config=fF(z.config,_),this.resolvedConfig=fF(z.resolvedConfig,_),this.name=this.resolvedConfig.name??`anonymousScope${Object.keys(u2).length}`,this.name in u2)E(`A Scope already named ${this.name} already exists`);u2[this.name]=this;let F=Object.entries(T).map((W)=>this.preparseOwnAliasEntry(...W));for(let[W,J]of F){let Y=W;if(W[0]==="#"){if(Y=W.slice(1),Y in this.aliases)E(Q6(Y));this.aliases[Y]=J}else{if(Y in this.aliases)E(Q6(W));this.aliases[Y]=J,this.exportedNames.push(Y)}if(!P(J,"module")&&!P(J,"generic")&&!Y0(J)){let $=this.preparseOwnDefinitionFormat(J,{alias:Y});this.resolutions[Y]=P($,"root")?this.bindReference($):this.createParseContext($).id}}R6??=this.node("union",{branches:["string","number","object","bigint","symbol",{unit:!0},{unit:!1},{unit:void 0},{unit:null}]},{prereduced:!0}),this.nodesByHash[R6.hash]=this.node("intersection",{},{prereduced:!0}),this.intrinsic=z.intrinsic?c(z.intrinsic,(W,J)=>W.startsWith("json")?[]:[W,this.bindReference(J)]):{}}cacheGetter(T,_){return Object.defineProperty(this,T,{value:_}),_}get internal(){return this}_json;get json(){if(!this._json)this.export();return this._json}defineSchema(T){return T}generic=(...T)=>{let _=this;return(F,W)=>new A0(T,W?new yW(F):F,_,_,W??null)};units=(T,_)=>{let F=[];for(let J of T)if(!F.includes(J))F.push(J);let W=F.map((J)=>this.node("unit",{unit:J},_));return this.node("union",W,{..._,prereduced:!0})};lazyResolutions=[];lazilyResolve(T,_){let F=this.node("alias",{reference:_??"synthetic",resolve:T},{prereduced:!0});if(!this.resolved)this.lazyResolutions.push(F);return F}schema=(T,_)=>this.finalize(this.parseSchema(T,_));parseSchema=(T,_)=>this.node(yF(T),T,_);preparseNode(T,_,F){let W=typeof T==="string"?T:yF(_,T);if(OT(_)&&_.kind===W)return _;if(W==="alias"&&!F?.prereduced){let{reference:$}=gF.implementation.normalize(_,this);if($.startsWith("$")){let Z=this.resolveRoot($.slice(1));_=Z,W=Z.kind}}else if(W==="union"&&T_(_,"object")){let $=nA(_);if($?.length===1)_=$[0],W=yF(_)}if(OT(_)&&_.kind===W)return _;let Y=r0[W].normalize?.(_,this)??_;if(OT(Y))return Y.kind===W?Y:rA(W,Y.kind);return{...F,$:this,kind:W,def:Y,prefix:F.alias??W}}bindReference(T){let _;if(OT(T))_=T.$===this?T:new T.constructor(T.attachments,this);else _=T.$===this?T:new A0(T.params,T.bodyDef,T.$,this,T.hkt);if(!this.resolved)Object.assign(this.referencesById,_.referencesById);return _}resolveRoot(T){return this.maybeResolveRoot(T)??E(l2(T))}maybeResolveRoot(T){let _=this.maybeResolve(T);if(P(_,"generic"))return;return _}maybeResolveSubalias(T){return c2(this.aliases,T)??c2(this.ambient,T)}get ambient(){return z.ambient}maybeResolve(T){let _=this.resolutions[T];if(_){if(typeof _!=="string")return this.bindReference(_);let W=iT[_];if(P(W,"root"))return this.resolutions[T]=W;if(P(W,"context")){if(W.phase==="resolving")return this.node("alias",{reference:`$${T}`},{prereduced:!0});if(W.phase==="resolved")return e(`Unexpected resolved context for was uncached by its scope: ${d(W)}`);W.phase="resolving";let J=this.bindReference(this.parseOwnDefinitionFormat(W.def,W));return W.phase="resolved",iT[J.id]=J,iT[W.id]=J,this.resolutions[T]=J}return e(`Unexpected nodesById entry for ${_}: ${d(W)}`)}let F=this.aliases[T]??this.ambient?.[T];if(!F)return this.maybeResolveSubalias(T);if(F=this.normalizeRootScopeValue(F),P(F,"generic"))return this.resolutions[T]=this.bindReference(F);if(P(F,"module")){if(!F.root)E(S6(T));return this.resolutions[T]=this.bindReference(F.root)}return this.resolutions[T]=this.parse(F,{alias:T})}createParseContext(T){let _=T.id??N2(T.prefix);return iT[_]=Object.assign(T,{[tT]:"context",$:this,id:_,phase:"unresolved"})}traversal(T){return new f_(T,this.resolvedConfig)}import(...T){return new e0(c(this.export(...T),(_,F)=>[`#${_}`,F]))}precompilation;_exportedResolutions;_exports;export(...T){if(!this._exports){this._exports={};for(let F of this.exportedNames){let W=this.aliases[F];this._exports[F]=P(W,"module")?o2(W,this):E6(this.maybeResolve(F))}for(let F of this.lazyResolutions)F.resolution;if(this._exportedResolutions=D6(this,this._exports),this._json=L6(this._exportedResolutions),Object.assign(this.resolutions,this._exportedResolutions),this.references=Object.values(this.referencesById),!this.resolvedConfig.jitless){let F=K6(this.references);this.precompilation=F.write(z6,4),V6(this.references,F)}this.resolved=!0}let _=T.length?T:this.exportedNames;return new e0(c(_,(F,W)=>[W,this._exports[W]]))}resolve(T){return this.export()[T]}node=(T,_,F={})=>{let W=this.preparseNode(T,_,F);if(OT(W))return this.bindReference(W);let J=this.createParseContext(W),Y=C2(J),$=this.bindReference(Y);return iT[J.id]=$};parse=(T,_={})=>this.finalize(this.parseDefinition(T,_));parseDefinition(T,_={}){if(P(T,"root"))return this.bindReference(T);let F=this.preparseOwnDefinitionFormat(T,_);if(P(F,"root"))return this.bindReference(F);let W=this.createParseContext(F);iT[W.id]=W;let J=this.bindReference(this.parseOwnDefinitionFormat(T,W));if(J.isCyclic)J=cJ(J,W.id);return iT[W.id]=J,J}finalize(T){if(E6(T),!T.precompilation&&!this.resolvedConfig.jitless)sA(T.references);return T}}class d2 extends oW{parseOwnDefinitionFormat(T,_){return C2(_)}preparseOwnDefinitionFormat(T,_){return this.preparseNode(yF(T),T,_)}preparseOwnAliasEntry(T,_){return[T,_]}normalizeRootScopeValue(T){return T}}var E6=(T)=>{let _=T.references.filter((F)=>F.hasKind("alias"));for(let F of _){Object.assign(F.referencesById,F.resolution.referencesById);for(let W of T.references)if(F.id in W.referencesById)Object.assign(W.referencesById,F.referencesById)}return T},L6=(T)=>c(T,(_,F)=>[_,P(F,"root")||P(F,"generic")?F.json:P(F,"module")?L6(F):e(`Unexpected resolution ${d(F)}`)]),c2=(T,_)=>{let F=_.indexOf(".");if(F===-1)return;let W=_.slice(0,F),J=T[W];if(J===void 0)return;if(!P(J,"module"))return E(aA(W));let Y=_.slice(F+1),$=J[Y];if($===void 0)return c2(J,Y);if(P($,"root")||P($,"generic"))return $;if(P($,"module"))return $.root??E(S6(_));e(`Unexpected resolution for alias '${_}': ${d($)}`)},uW=(T,_)=>new d2(T,_),uF=new d2({});var D6=(T,_)=>{let F={};for(let W in _){let J=_[W];if(P(J,"module")){let Y=D6(T,J),$=c(Y,(Z,G)=>[`${W}.${Z}`,G]);Object.assign(F,$)}else if(P(J,"root")||P(J,"generic"))F[W]=J;else e(`Unexpected scope resolution ${d(J)}`)}return F},l2=(T)=>`'${T}' is unresolvable`,aA=(T)=>`'${T}' must reference a module to be accessed using dot syntax`,S6=(T)=>`Reference to submodule '${T}' must specify an alias`;uF.export();var{schema:WT,node:TF,defineSchema:Yz,generic:K_}=uF;var t2="^(?:0|[1-9]\\d*)$",eA=new RegExp(t2),Xz=KT(eA);var I6=uW({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();z.intrinsic={...I6};var N6=uW({integer:{domain:"number",divisor:1},lengthBoundable:["string",Array],key:["string","symbol"],nonNegativeIntegerString:{domain:"string",pattern:t2}},{prereducedAliases:!0}).export();Object.assign(z.intrinsic,N6);var TH=uW({jsonPrimitive:["string","number",{unit:!0},{unit:!1},{unit:null}],jsonObject:{domain:"object",index:{signature:"string",value:"$jsonData"}},jsonData:["$jsonPrimitive","$jsonObject"]},{prereducedAliases:!0}).export(),x={...I6,...N6,...TH,emptyStructure:TF("structure",{},{prereduced:!0})};z.intrinsic={...x};var B6=(T)=>typeof T==="string"&&T[0]==="d"&&(T[1]==="'"||T[1]==='"')&&T.at(-1)===T[1],C6=(T)=>T.toString()!=="Invalid Date",k6=(T)=>T.slice(2,-1),i2=(T)=>`'${T}' could not be parsed by the Date constructor`,f6=(T,_)=>_H(T,_),_H=(T,_)=>{let F=new Date(T);if(C6(F))return F;let W=XJ(T);if(W!==void 0){let J=new Date(W);if(C6(J))return J}return _?E(_===!0?i2(T):_):void 0};var n2=(T,_)=>{let F=T.scanner.shiftUntil(FH[q6[_]]);if(T.scanner.lookahead==="")return T.error(JH(F,_));if(T.scanner.shift(),_==="/"){try{new RegExp(F)}catch(W){E(String(W))}T.root=T.ctx.$.node("intersection",{domain:"string",pattern:F},{prereduced:!0})}else if(qT(_,r2))T.root=T.ctx.$.node("unit",{unit:F});else{let W=f6(F,i2(F));T.root=T.ctx.$.node("unit",{meta:F,unit:W})}},r2={"'":1,'"':1},P6={"/":1,"'":1,'"':1},q6={"d'":"'",'d"':'"',"'":"'",'"':'"',"/":"/"},FH={"'":(T)=>T.lookahead==="'",'"':(T)=>T.lookahead==='"',"/":(T)=>T.lookahead==="/"},WH={'"':"double-quote","'":"single-quote","/":"forward slash"},JH=(T,_)=>`${_}${T} requires a closing ${WH[q6[_]]}`;var j6=(T)=>`Private type references should not include '#'. Use '${T}' instead.`,cW="Optional definitions like 'string?' are only valid as properties in an object or tuple",dW="Defaultable definitions like 'number = 0' are only valid as properties in an object or tuple";var y6={">":!0,">=":!0},v6={"<":!0,"<=":!0};var _F={"<":">",">":"<","<=":">=",">=":"<=","==":"=="},x6=(T)=>`Unmatched )${T===""?"":` before ${T}`}`,lW=(T)=>`Missing ${T}`,b6=(T,_)=>`Left bounds are only valid when paired with right bounds (try ...${_}${T})`,tW=(T)=>`Left-bounded expressions must specify their limits using < or <= (was ${T})`,h6=(T,_,F,W)=>`An expression may have at most one left bound (parsed ${T}${_F[_]}, ${F}${_F[W]})`;var p6=(T,_,F)=>g6(T,_,F,[]),g6=(T,_,F,W)=>{let J=F.parseUntilFinalizer();if(W.push(J.root),J.finalizer===">"){if(W.length!==_.params.length)return F.error(s2(T,_.names,W.map((Y)=>Y.expression)));return W}if(J.finalizer===",")return g6(T,_,F,W);return J.error(lW(">"))},s2=(T,_,F)=>`${T}<${_.join(", ")}> requires exactly ${_.length} args (got ${F.length}${F.length===0?"":`: ${F.join(", ")}`})`;var a2=(T)=>{let _=T.scanner.shiftUntilNextTerminator();if(_==="keyof")T.addPrefix("keyof");else T.root=$H(T,_)},YH=(T,_,F)=>{if(F.scanner.shiftUntilNonWhitespace(),F.scanner.shift()!=="<")return F.error(s2(T,_.names,[]));let J=p6(T,_,F);return _(...J)},$H=(T,_)=>ZH(T,_)??XH(T,_)??T.error(_===""?T.scanner.lookahead==="#"?j6(T.shiftedByOne().scanner.shiftUntilNextTerminator()):e2(T):l2(_)),ZH=(T,_)=>{if(T.ctx.args?.[_]){let W=T.ctx.args[_];if(typeof W!=="string")return W;return T.ctx.$.node("alias",{reference:W},{prereduced:!0})}let F=T.ctx.$.maybeResolve(_);if(P(F,"root"))return F;if(F===void 0)return;if(P(F,"generic"))return YH(_,F,T);return E(`Unexpected resolution ${d(F)}`)},XH=(T,_)=>{let F=GJ(_);if(F!==void 0)return T.ctx.$.node("unit",{unit:F});let W=HJ(_);if(W!==void 0)return T.ctx.$.node("unit",{unit:W})},e2=(T)=>{let _=T.previousOperator();return _?T4(_,T.scanner.unscanned):GH(T.scanner.unscanned)},T4=(T,_="")=>`Token '${T}' requires a right operand${_?` before '${_}'`:""}`,GH=(T)=>`Expected an expression${T?` before '${T}'`:""}`;var _4=(T)=>T.scanner.lookahead===""?T.error(e2(T)):T.scanner.lookahead==="("?T.shiftedByOne().reduceGroupOpen():T.scanner.lookaheadIsIn(P6)?n2(T,T.scanner.shift()):T.scanner.lookaheadIsIn($0)?_4(T.shiftedByOne()):T.scanner.lookahead==="d"?T.scanner.nextLookahead in r2?n2(T,`${T.scanner.shift()}${T.scanner.shift()}`):a2(T):a2(T);class s_ extends $2{shiftUntilNextTerminator(){return this.shiftUntilNonWhitespace(),this.shiftUntil(()=>(this.lookahead in s_.terminatingChars))}static terminatingChars={"<":1,">":1,"=":1,"|":1,"&":1,")":1,"[":1,"%":1,",":1,":":1,"?":1,"#":1,...$0};static finalizingLookaheads={">":1,",":1,"":1,"=":1,"?":1};static lookaheadIsFinalizing=(T,_)=>T===">"?_[0]==="="?_[1]==="=":_.trimStart()===""||qT(_.trimStart()[0],s_.terminatingChars):T==="="?_[0]!=="=":T===","||T==="?"}var o6=(T,_)=>{let F=AH(T,_);if(T.root.hasKind("unit")){if(typeof T.root.unit==="number"){T.reduceLeftBound(T.root.unit,F),T.unsetRoot();return}if(T.root.unit instanceof Date){let W=`d'${T.root.description??T.root.unit.toISOString()}'`;T.unsetRoot(),T.reduceLeftBound(W,F);return}}return OH(T,F)},u6={"<":1,">":1,"=":1},AH=(T,_)=>T.scanner.lookaheadIs("=")?`${_}${T.scanner.shift()}`:_;var m6=(T,_,F,W)=>{if(F.extends(z.intrinsic.number)){if(typeof _!=="number")return E(F4(T,_,W));return T==="=="?["min","max"]:T[0]===">"?["min"]:["max"]}if(F.extends(z.intrinsic.lengthBoundable)){if(typeof _!=="number")return E(F4(T,_,W));return T==="=="?["exactLength"]:T[0]===">"?["minLength"]:["maxLength"]}if(F.extends(z.intrinsic.Date))return T==="=="?["after","before"]:T[0]===">"?["after"]:["before"];return E(PJ(F.expression))},HH=(T)=>({rule:B6(T.limit)?k6(T.limit):T.limit,exclusive:T.comparator.length===1}),OH=(T,_)=>{let F=T.unsetRoot(),W=T.scanner.location;T.parseOperand();let J=T.unsetRoot(),Y=T.scanner.sliceChars(W,T.scanner.location);if(T.root=F,!J.hasKind("unit")||typeof J.unit!=="number"&&!(J.unit instanceof Date))return T.error(F4(_,Y,"right"));let $=J.unit,Z=_.length===1,G=m6(_,typeof $==="number"?$:Y,F,"right");for(let O of G)T.constrainRoot(O,_==="=="?{rule:$}:{rule:$,exclusive:Z});if(!T.branches.leftBound)return;if(!qT(_,v6))return T.error(tW(_));let X=m6(T.branches.leftBound.comparator,T.branches.leftBound.limit,F,"left");T.constrainRoot(X[0],HH(T.branches.leftBound)),T.branches.leftBound=null},F4=(T,_,F)=>`Comparator ${F==="left"?_F[T]:T} must be ${F==="left"?"preceded":"followed"} by a corresponding literal (was ${_})`;var c6=(T)=>{T.scanner.shiftUntilNonWhitespace();let _=T.scanner.shiftUntilNextTerminator();T.root=T.root.brand(_)};var l6=(T)=>{let _=T.scanner.shiftUntilNextTerminator(),F=AJ(_,{errorOnFail:d6(_)});if(F===0)T.error(d6(0));T.root=T.root.constrain("divisor",F)},d6=(T)=>`% operator must be followed by a non-zero integer literal (was ${T})`;var W4=(T)=>{let _=T.scanner.shift();return _===""?T.finalize(""):_==="["?T.scanner.shift()==="]"?T.setRoot(T.root.array()):T.error(UH):_==="|"?T.scanner.lookahead===">"?T.shiftedByOne().pushRootToBranch("|>"):T.pushRootToBranch(_):_==="&"?T.pushRootToBranch(_):_===")"?T.finalizeGroup():s_.lookaheadIsFinalizing(_,T.scanner.unscanned)?T.finalize(_):qT(_,u6)?o6(T,_):_==="%"?l6(T):_==="#"?c6(T):(_ in $0)?W4(T):T.error(iW(_))},iW=(T,_="")=>`'${T}' is not allowed here${_&&` (should be ${_})`}`,UH="Missing expected ']'";var t6=(T)=>{let _=T.unsetRoot();T.parseOperand();let F=T.unsetRoot();if(!F.hasKind("unit"))return T.error(MH(F.expression));let W=F.unit instanceof Date?()=>new Date(F.unit):F.unit;return[_,"=",W]},MH=(T)=>`Default value '${T}' must a literal value`;var J4=(T,_)=>{let F=_.$.maybeResolveRoot(T);if(F)return F;if(T.endsWith("[]")){let Y=_.$.maybeResolveRoot(T.slice(0,-2));if(Y)return Y.array()}let W=new FF(new s_(T),_),J=wH(W);if(W.finalizer===">")E(iW(">"));return J},wH=(T)=>{T.parseOperand();let _=cF(T).root;if(!_)return e(`Root was unexpectedly unset after parsing string '${T.scanner.scanned}'`);if(T.finalizer==="=")_=t6(T);else if(T.finalizer==="?")_=[_,"?"];if(T.scanner.shiftUntilNonWhitespace(),T.scanner.lookahead)E(iW(T.scanner.lookahead));return _},cF=(T)=>{while(T.finalizer===void 0)QH(T);return T},QH=(T)=>T.hasRoot()?T.parseOperator():T.parseOperand();class FF{root;branches={prefixes:[],leftBound:null,intersection:null,union:null,pipe:null};finalizer;groups=[];scanner;ctx;constructor(T,_){this.scanner=T,this.ctx=_}error(T){return E(T)}hasRoot(){return this.root!==void 0}setRoot(T){this.root=T}unsetRoot(){let T=this.root;return this.root=void 0,T}constrainRoot(...T){this.root=this.root.constrain(T[0],T[1])}finalize(T){if(this.groups.length)return this.error(lW(")"));this.finalizeBranches(),this.finalizer=T}reduceLeftBound(T,_){let F=_F[_];if(!qT(F,y6))return this.error(tW(_));if(this.branches.leftBound)return this.error(h6(this.branches.leftBound.limit,this.branches.leftBound.comparator,T,F));this.branches.leftBound={comparator:F,limit:T}}finalizeBranches(){if(this.assertRangeUnset(),this.branches.pipe){this.pushRootToBranch("|>"),this.root=this.branches.pipe;return}if(this.branches.union){this.pushRootToBranch("|"),this.root=this.branches.union;return}if(this.branches.intersection){this.pushRootToBranch("&"),this.root=this.branches.intersection;return}this.applyPrefixes()}finalizeGroup(){this.finalizeBranches();let T=this.groups.pop();if(!T)return this.error(x6(this.scanner.unscanned));this.branches=T}addPrefix(T){this.branches.prefixes.push(T)}applyPrefixes(){while(this.branches.prefixes.length){let T=this.branches.prefixes.pop();this.root=T==="keyof"?this.root.keyof():e(`Unexpected prefix '${T}'`)}}pushRootToBranch(T){this.assertRangeUnset(),this.applyPrefixes();let _=this.root;if(this.root=void 0,this.branches.intersection=this.branches.intersection?.rawAnd(_)??_,T==="&")return;if(this.branches.union=this.branches.union?.rawOr(this.branches.intersection)??this.branches.intersection,this.branches.intersection=null,T==="|")return;this.branches.pipe=this.branches.pipe?.rawPipeOnce(this.branches.union)??this.branches.union,this.branches.union=null}parseUntilFinalizer(){return cF(new FF(this.scanner,this.ctx))}parseOperator(){return W4(this)}parseOperand(){return _4(this)}assertRangeUnset(){if(this.branches.leftBound)return this.error(b6(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 RH="An empty string is not a valid generic parameter name",nW=(T,_,F)=>{T.shiftUntilNonWhitespace();let W=T.shiftUntilNextTerminator();if(W===""){if(T.lookahead===""&&_.length)return _;return E(RH)}return T.shiftUntilNonWhitespace(),EH(T,W,_,F)},i6="extends ",EH=(T,_,F,W)=>{if(T.shiftUntilNonWhitespace(),T.unscanned.startsWith(i6))T.jumpForward(i6.length);else{if(T.lookahead===",")T.shift();return F.push(_),nW(T,F,W)}let J=cF(new FF(T,W));return F.push([_,J.root]),nW(T,F,W)};class Y4 extends k_{$;constructor(T){super((..._)=>new dF(T)(..._),{bind:T});this.$=T}in(T){return new dF(this.$,T===void 0?void 0:this.$.parse(T))}at(T,_){return new dF(this.$).at(T,_)}case(T,_){return new dF(this.$).case(T,_)}}class dF extends k_{$;in;key;branches=[];constructor(T,_){super((F)=>this.caseEntries(Object.entries(F).map(([W,J])=>W==="default"?[W,J]:[this.$.parse(W),J])));this.$=T,this.in=_}at(T,_){if(this.key)E(VH);if(this.branches.length)E(zH);return this.key=T,_?this.match(_):this}case(T,_){return this.caseEntry(this.$.parse(T),_)}caseEntry(T,_){let W=(this.key?this.$.parse({[this.key]:T}):T).pipe(_);return this.branches.push(W),this}match(T){return this(T)}strings(T){return this.caseEntries(Object.entries(T).map(([_,F])=>_==="default"?[_,F]:[this.$.node("unit",{unit:_}),F]))}caseEntries(T){for(let _=0;_<T.length;_++){let[F,W]=T[_];if(F==="default"){if(_!==T.length-1)E("default may only be specified as the last key of a switch definition");return this.default(W)}if(typeof W!=="function")return E(`Value for case "${F}" must be a function (was ${PT(W)})`);this.caseEntry(F,W)}return this}default(T){if(typeof T==="function")this.case(x.unknown,T);let _={branches:this.branches,ordered:!0};if(T==="never"||T==="assert")_.meta={onFail:n6};let F=this.$.node("union",_);if(!this.in)return this.$.finalize(F);let W=this.in.pipe(F);if(T==="never"||T==="assert")W=W.configureReferences({onFail:n6},"self");return this.$.finalize(W)}}var n6=(T)=>T.throw(),zH="A key matcher must be specified before the first case i.e. match.at('foo') or match.in<object>().at('bar')",VH="At most one key matcher may be specified per expression";var rW=(T,_)=>{if(XT(T)){if(T[1]==="=")return[_.$.parseOwnDefinitionFormat(T[0],_),"=",T[2]];if(T[1]==="?")return[_.$.parseOwnDefinitionFormat(T[0],_),"?"]}return sW(T,_)},r6="Only required keys may make their values optional, e.g. { [mySymbol]: ['number', '?'] }",s6="Only required keys may specify default values, e.g. { value: 'number = 0' }";var a6=(T,_)=>{let F,W={},J=S0(T);for(let[$,Z]of J){let G=DH($);if(G.kind==="spread"){if(!p_(W))return E(LH);let K=_.$.parseOwnDefinitionFormat(Z,_);if(K.equals(x.object))continue;if(!K.hasKind("intersection")||!K.basis?.equals(x.object))return E(SH(K.expression));F=K.structure;continue}if(G.kind==="undeclared"){if(Z!=="reject"&&Z!=="delete"&&Z!=="ignore")E(KH(Z));W.undeclared=Z;continue}let X=rW(Z,_),O=G;if(G.kind==="required"){if(!XT(X))$4(W,"required",{key:G.normalized,value:X},_);else $4(W,"optional",X[1]==="="?{key:G.normalized,value:X[0],default:X[2]}:{key:G.normalized,value:X[0]},_);continue}if(XT(X)){if(X[1]==="?")E(r6);if(X[1]==="=")E(s6)}if(G.kind==="optional"){$4(W,"optional",{key:G.normalized,value:X},_);continue}let M=_.$.parseOwnDefinitionFormat(O.normalized,_),Q=mW(M,X,_.$);if(Q.index)W.index=s(W.index,Q.index);if(Q.required)W.required=s(W.required,Q.required)}let Y=_.$.node("structure",W);return _.$.parseSchema({domain:"object",structure:F?.merge(Y)??Y})},$4=(T,_,F,W)=>{T[_]=s(T[_],W.$.node(_,F))},KH=(T)=>`Value of '+' key must be 'reject', 'delete', or 'ignore' (was ${d(T)})`,LH="Spread operator may only be used as the first key in an object",DH=(T)=>typeof T==="symbol"?{kind:"required",normalized:T}:T.at(-1)==="?"?T.at(-2)===DF?{kind:"required",normalized:`${T.slice(0,-2)}?`}:{kind:"optional",normalized:T.slice(0,-1)}:T[0]==="["&&T.at(-1)==="]"?{kind:"index",normalized:T.slice(1,-1)}:T[0]===DF&&T[1]==="["&&T.at(-1)==="]"?{kind:"required",normalized:T.slice(1)}:T==="..."?{kind:"spread"}:T==="+"?{kind:"undeclared"}:{kind:"required",normalized:T==="\\..."?"...":T==="\\+"?"+":T},SH=(T)=>`Spread operand must resolve to an object literal type (was ${T})`;var TY=(T,_)=>yH(T)?JY[T[0]](T,_):qH(T)?WY[T[1]](T,_):null,IH=(T,_)=>_.$.parseOwnDefinitionFormat(T[1],_).keyof(),Z4=(T,_)=>{if(T[2]===void 0)return E(T4(T[1],""));let F=_.$.parseOwnDefinitionFormat(T[0],_),W=_.$.parseOwnDefinitionFormat(T[2],_);if(T[1]==="|")return _.$.node("union",{branches:[F,W]});let J=T[1]==="&"?J_(F,W,_.$):jF(F,W,_.$);if(J instanceof N)return J.throw();return J},NH=(T,_)=>_.$.parseOwnDefinitionFormat(T[0],_).array(),CH=(T,_)=>{if(typeof T[2]!=="function")return E(_Y("=>",T[2]));return _.$.parseOwnDefinitionFormat(T[0],_).pipe(T[2])},_Y=(T,_)=>`${T===":"?"Narrow":"Morph"} expression requires a function following '${T}' (was ${typeof _})`,BH=(T,_)=>{if(typeof T[2]!=="function")return E(_Y(":",T[2]));return _.$.parseOwnDefinitionFormat(T[0],_).constrain("predicate",T[2])},kH=(T,_)=>_.$.parseOwnDefinitionFormat(T[0],_).configureReferences(T[2],"shallow"),FY=(T)=>T,fH=FY({"[]":NH,"?":()=>E(cW)}),PH=FY({"|":Z4,"&":Z4,":":BH,"=>":CH,"|>":Z4,"@":kH,"=":()=>E(dW)}),WY={...fH,...PH},qH=(T)=>WY[T[1]]!==void 0,jH=(T)=>T,JY=jH({keyof:IH,instanceof:(T,_)=>{if(typeof T[1]!=="function")return E(e6(KF(T[1])));let F=T.slice(1).map((W)=>typeof W==="function"?_.$.node("proto",{proto:W}):E(e6(KF(W))));return F.length===1?F[0]:_.$.node("union",{branches:F})},"===":(T,_)=>_.$.units(T.slice(1))}),yH=(T)=>JY[T[0]]!==void 0,e6=(T)=>`Expected a constructor following 'instanceof' operator (was ${T})`;var ZY=(T,_)=>{let F=[{}],W=0;while(W<T.length){let J=!1;if(T[W]==="..."&&W<T.length-1)J=!0,W++;let Y=rW(T[W],_),[$,Z,G]=!XT(Y)?[Y]:Y;if(W++,J){if(!$.extends(z.intrinsic.Array))return E(bH($.expression));F=F.flatMap((X)=>$.distribute((O)=>xH(fW(X),O)))}else F=F.map((X)=>{if(Z==="?")return XY(X,$);if(Z==="=")return vH(X,$,G);return X4(X,$)})}return _.$.parseSchema(F.map((J)=>p_(J)?{proto:Array,exactLength:0}:{proto:Array,sequence:J}))},X4=(T,_)=>{if(T.defaultables||T.optionals)return E(T.variadic?p2:hH);if(T.variadic)T.postfix=s(T.postfix,_);else T.prefix=s(T.prefix,_);return T},XY=(T,_)=>{if(T.variadic)return E(GY);return T.optionals=s(T.optionals,_),T},vH=(T,_,F)=>{if(T.variadic)return E(GY);if(T.optionals)return E(pH);return T.defaultables=s(T.defaultables,[[_,F]]),T},YY=(T,_)=>{if(T.postfix)E($Y);if(T.variadic){if(!T.variadic.equals(_))E($Y)}else T.variadic=_.internal;return T},xH=(T,_)=>{let F=_.select({method:"find",kind:"sequence"});if(!F)return YY(T,z.intrinsic.unknown);if(F.prefix)for(let W of F.prefix)X4(T,W);if(F.optionals)for(let W of F.optionals)XY(T,W);if(F.variadic)YY(T,F.variadic);if(F.postfix)for(let W of F.postfix)X4(T,W);return T},bH=(T)=>`Spread element must be an array (was ${T})`,$Y="A tuple may have at most one variadic element",hH="A required element may not follow an optional element",GY="An optional element may not follow a variadic element";var pH="A defaultable element may not follow an optional element without a default";var gH={},sW=(T,_)=>{if(typeof T==="string"){if(_.args&&Object.keys(_.args).some((W)=>T.includes(W)))return J4(T,_);let F=gH[_.$.name]??={};return F[T]??=J4(T,_)}return T_(T,"object")?mH(T,_):E(G4(PT(T)))},mH=(T,_)=>{let F=VF(T);switch(F){case void 0:if(P(T,"root"))return T;return a6(T,_);case"Array":return oH(T,_);case"RegExp":return _.$.node("intersection",{domain:"string",pattern:T},{prereduced:!0});case"Function":{let W=Y0(T)?T():T;if(P(W,"root"))return W;return E(G4("Function"))}default:return E(G4(F??d(T)))}},oH=(T,_)=>TY(T,_)??ZY(T,_),G4=(T)=>`Type definitions must be strings or objects (was ${T})`;class A4 extends k_{constructor(T){let _=Object.assign({errors:F_,hkt:uT,$:T,raw:T.parse,module:T.constructor.module,scope:T.constructor.scope,define:T.define,match:T.match,generic:T.generic,schema:T.schema,keywords:T.ambient,unit:T.unit,enumerated:T.enumerated,instanceOf:T.instanceOf,valueOf:T.valueOf,or:T.or,and:T.and,merge:T.merge,pipe:T.pipe},T.ambientAttachments);super((...F)=>{if(F.length===1)return T.parse(F[0]);if(F.length===2&&typeof F[0]==="string"&&F[0][0]==="<"&&F[0].at(-1)===">"){let W=F[0].slice(1,-1),J=T.parseGenericParams(W,{});return new A0(J,F[1],T,T,null)}return T.parse(F)},{bind:T,attach:_})}}var WF=z;class aW extends oW{get ambientAttachments(){if(!WF.typeAttachments)return;return this.cacheGetter("ambientAttachments",c(WF.typeAttachments,(T,_)=>[T,this.bindReference(_)]))}preparseOwnAliasEntry(T,_){let F=T.indexOf("<");if(F===-1){if(P(_,"module")||P(_,"generic"))return[T,_];let Y=this.name==="ark"?T:T==="root"?this.name:`${this.name}.${T}`,$=this.resolvedConfig.keywords?.[Y];if($)_=[_,"@",$];return[T,_]}if(T.at(-1)!==">")E("'>' must be the last character of a generic declaration in a scope");let W=T.slice(0,F),J=T.slice(F+1,-1);return[W,()=>{let Y=this.parseGenericParams(J,{alias:W});return BJ(Y,_,this)}]}parseGenericParams(T,_){return nW(new s_(T),[],this.createParseContext({..._,def:T,prefix:"generic"}))}normalizeRootScopeValue(T){if(Y0(T)&&!P(T,"generic"))return T();return T}preparseOwnDefinitionFormat(T,_){return{..._,def:T,prefix:_.alias??"type"}}parseOwnDefinitionFormat(T,_){if(!(_.alias&&(_.alias in this.aliases))&&!_.args)_.args={this:_.id};let W=sW(T,_);if(XT(W)){if(W[1]==="=")return E(dW);if(W[1]==="?")return E(cW)}return W}unit=(T)=>this.units([T]);valueOf=(T)=>this.units(i8(T));enumerated=(...T)=>this.units(T);instanceOf=(T)=>this.node("proto",{proto:T},{prereduced:!0});or=(...T)=>this.schema(T.map((_)=>this.parse(_)));and=(...T)=>T.reduce((_,F)=>_.and(this.parse(F)),this.intrinsic.unknown);merge=(...T)=>T.reduce((_,F)=>_.merge(this.parse(F)),this.intrinsic.object);pipe=(...T)=>this.intrinsic.unknown.pipe(...T);match=new Y4(this);declare=()=>({type:this.type});define(T){return T}type=new A4(this);static scope=(T,_={})=>new aW(T,_);static module=(T,_={})=>this.scope(T,_).export()}var H4=Object.assign(aW.scope,{define:(T)=>T}),r=aW;class AY extends uT{description='merge an object\'s properties onto another like `Merge(User, { isAdmin: "true" })`'}var uH=K_(["base",x.object],["props",x.object])((T)=>T.base.merge(T.props),AY),HY=r.module({Key:x.key,Merge:uH});class OY extends uT{}var cH=K_("element")((T)=>{let _=T.element.exclude(x.Array),F=_.array();return _.rawOr(F).pipe(J0).distribute((W)=>W.assertHasKind("morph").declareOut(F),WT)},OY),UY=r.module({root:x.Array,readonly:"root",index:x.nonNegativeIntegerString,liftFrom:cH},{name:"Array"});var O4=WT(["string",N0.FileConstructor]),dH=O4.rawOr(O4.array()),MY=WT({meta:"an object representing parsed form data",domain:"object",index:{signature:"string",value:dH}}),wY=r.module({root:["instanceof",FormData],value:O4,parsed:MY,parse:WT({in:FormData,morphs:(T)=>{let _={};for(let[F,W]of T)if(F in _){let J=_[F];if(typeof J==="string"||J instanceof N0.FileConstructor)_[F]=[J,W];else J.push(W)}else _[F]=W;return _},declaredOut:MY})},{name:"FormData"});var QY=r.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 lH={Boolean:1,Number:1,String:1},RY=r.module({...c({...a1,...T2},(T,_)=>(T in lH)?[]:[T,["instanceof",_]]),Array:UY,TypedArray:QY,FormData:wY});var tH=WT({domain:{domain:"number",meta:"a number representing a Unix timestamp"},divisor:{rule:1,meta:"an integer representing a Unix timestamp"},min:{rule:-8640000000000000,meta:"a Unix timestamp after -8640000000000000"},max:{rule:8640000000000000,meta:"a Unix timestamp before 8640000000000000"},meta:"an integer representing a safe Unix timestamp"}),iH=WT({domain:"number",divisor:1}),eW=r.module({root:x.number,integer:iH,epoch:tH,safe:WT({domain:{domain:"number",numberAllowsNaN:!1},min:Number.MIN_SAFE_INTEGER,max:Number.MAX_SAFE_INTEGER}),NaN:["===",Number.NaN],Infinity:["===",Number.POSITIVE_INFINITY],NegativeInfinity:["===",Number.NEGATIVE_INFINITY]},{name:"number"});var ET=(T,_,F)=>{let W={domain:"string",pattern:{rule:T.source,flags:T.flags,meta:_}};if(F)W.meta={format:F};return TF("intersection",W)},EY=ET(SF,"a well-formed integer string"),fY=r.module({root:EY,parse:WT({in:EY,morphs:(T,_)=>{let F=Number.parseInt(T);return Number.isSafeInteger(F)?F:_.error("an integer in the range Number.MIN_SAFE_INTEGER to Number.MAX_SAFE_INTEGER")},declaredOut:x.integer})},{name:"string.integer"}),nH=ET(/^[\dA-Fa-f]+$/,"hex characters only"),rH=r.module({root:ET(/^(?:[\d+/A-Za-z]{4})*(?:[\d+/A-Za-z]{2}==|[\d+/A-Za-z]{3}=)?$/,"base64-encoded"),url:ET(/^(?:[\w-]{4})*(?:[\w-]{2}(?:==|%3D%3D)?|[\w-]{3}(?:=|%3D)?)?$/,"base64url-encoded")},{name:"string.base64"}),zY=ET(/^[A-Z].*$/,"capitalized"),sH=r.module({root:WT({in:"string",morphs:(T)=>T.charAt(0).toUpperCase()+T.slice(1),declaredOut:zY}),preformatted:zY},{name:"string.capitalize"}),aH=(T)=>{let _=T.replaceAll(/[ -]+/g,""),F=0,W,J,Y=!1;for(let $=_.length-1;$>=0;$--){if(W=_.substring($,$+1),J=Number.parseInt(W,10),Y)J*=2,F+=J>=10?J%10+1:J;else F+=J;Y=!Y}return!!(F%10===0?_:!1)},eH=/^(?: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}))$/,T7=WT({domain:"string",pattern:{meta:"a credit card number",rule:eH.source},predicate:{meta:"a credit card number",predicate:aH}});var _7=/^([+-]?\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 F7=(T)=>!Number.isNaN(new Date(T).valueOf()),VY=WT({domain:"string",predicate:{meta:"a parsable date",predicate:F7}}).assertHasKind("intersection"),KY=fY.root.internal.narrow((T,_)=>{let F=Number.parseInt(T),W=eW.epoch(F);if(W instanceof F_)return _.errors.merge(W),!1;return!0}).configure({description:"an integer string representing a safe Unix timestamp"},"self").assertHasKind("intersection"),W7=r.module({root:KY,parse:WT({in:KY,morphs:(T)=>new Date(T),declaredOut:x.Date})},{name:"string.date.epoch"}),LY=ET(_7,"an ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) date").internal.assertHasKind("intersection"),J7=r.module({root:LY,parse:WT({in:LY,morphs:(T)=>new Date(T),declaredOut:x.Date})},{name:"string.date.iso"}),Y7=r.module({root:VY,parse:WT({declaredIn:VY,in:"string",morphs:(T,_)=>{let F=new Date(T);if(Number.isNaN(F.valueOf()))return _.error("a parsable date");return F},declaredOut:x.Date}),iso:J7,epoch:W7},{name:"string.date"}),$7=ET(/^[\w%+.-]+@[\d.A-Za-z-]+\.[A-Za-z]{2,}$/,"an email address","email"),DY="(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])",H0=`(${DY}[.]){3}${DY}`,Z7=new RegExp(`^${H0}$`),CT="(?:[0-9a-fA-F]{1,4})",X7=new RegExp(`^((?:${CT}:){7}(?:${CT}|:)|(?:${CT}:){6}(?:${H0}|:${CT}|:)|(?:${CT}:){5}(?::${H0}|(:${CT}){1,2}|:)|(?:${CT}:){4}(?:(:${CT}){0,1}:${H0}|(:${CT}){1,3}|:)|(?:${CT}:){3}(?:(:${CT}){0,2}:${H0}|(:${CT}){1,4}|:)|(?:${CT}:){2}(?:(:${CT}){0,3}:${H0}|(:${CT}){1,5}|:)|(?:${CT}:){1}(?:(:${CT}){0,4}:${H0}|(:${CT}){1,6}|:)|(?::((?::${CT}){0,5}:${H0}|(?::${CT}){1,7}|:)))(%[0-9a-zA-Z.]{1,})?$`),G7=r.module({root:["v4 | v6","@","an IP address"],v4:ET(Z7,"an IPv4 address","ipv4"),v6:ET(X7,"an IPv6 address","ipv6")},{name:"string.ip"}),JF="a JSON string",PY=(T)=>{if(!(T instanceof SyntaxError))throw T;return`must be ${JF} (${T})`},A7=WT({meta:JF,domain:"string",predicate:{meta:JF,predicate:(T,_)=>{try{return JSON.parse(T),!0}catch(F){return _.reject({code:"predicate",expected:JF,problem:PY(F)})}}}}),H7=(T,_)=>{if(T.length===0)return _.error({code:"predicate",expected:JF,actual:"empty"});try{return JSON.parse(T)}catch(F){return _.error({code:"predicate",expected:JF,problem:PY(F)})}},O7=r.module({root:A7,parse:WT({meta:"safe JSON string parser",in:"string",morphs:H7,declaredOut:x.jsonObject})},{name:"string.json"}),SY=ET(/^[a-z]*$/,"only lowercase letters"),U7=r.module({root:WT({in:"string",morphs:(T)=>T.toLowerCase(),declaredOut:SY}),preformatted:SY},{name:"string.lower"}),qY=["NFC","NFD","NFKC","NFKD"],lF=c(qY,(T,_)=>[_,WT({domain:"string",predicate:(F)=>F.normalize(_)===F,meta:`${_}-normalized unicode`})]),T1=c(qY,(T,_)=>[_,WT({in:"string",morphs:(F)=>F.normalize(_),declaredOut:lF[_]})]),M7=r.module({root:T1.NFC,preformatted:lF.NFC},{name:"string.normalize.NFC"}),w7=r.module({root:T1.NFD,preformatted:lF.NFD},{name:"string.normalize.NFD"}),Q7=r.module({root:T1.NFKC,preformatted:lF.NFKC},{name:"string.normalize.NFKC"}),R7=r.module({root:T1.NFKD,preformatted:lF.NFKD},{name:"string.normalize.NFKD"}),E7=r.module({root:"NFC",NFC:M7,NFD:w7,NFKC:Q7,NFKD:R7},{name:"string.normalize"}),IY=ET(CW,"a well-formed numeric string"),z7=r.module({root:IY,parse:WT({in:IY,morphs:(T)=>Number.parseFloat(T),declaredOut:x.number})},{name:"string.numeric"}),NY="a regex pattern",V7=WT({domain:"string",predicate:{meta:NY,predicate:(T,_)=>{try{return new RegExp(T),!0}catch(F){return _.reject({code:"predicate",expected:NY,problem:String(F)})}}},meta:{format:"regex"}}),K7=/^(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-]+)*))?$/,L7=ET(K7,"a semantic version (see https://semver.org/)"),CY=ET(/^\S.*\S$|^\S?$/,"trimmed"),D7=r.module({root:WT({in:"string",morphs:(T)=>T.trim(),declaredOut:CY}),preformatted:CY},{name:"string.trim"}),BY=ET(/^[A-Z]*$/,"only uppercase letters"),S7=r.module({root:WT({in:"string",morphs:(T)=>T.toUpperCase(),declaredOut:BY}),preformatted:BY},{name:"string.upper"}),I7=(T)=>{if(URL.canParse)return URL.canParse(T);try{return new URL(T),!0}catch{return!1}},kY=WT({domain:"string",predicate:{meta:"a URL string",predicate:I7},meta:{format:"uri"}}),N7=r.module({root:kY,parse:WT({declaredIn:kY,in:"string",morphs:(T,_)=>{try{return new URL(T)}catch{return _.error("a URL string")}},declaredOut:WT(URL)})},{name:"string.url"}),C7=r.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:ET(/^[\da-f]{8}-[\da-f]{4}-1[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv1"),v2:ET(/^[\da-f]{8}-[\da-f]{4}-2[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv2"),v3:ET(/^[\da-f]{8}-[\da-f]{4}-3[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv3"),v4:ET(/^[\da-f]{8}-[\da-f]{4}-4[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv4"),v5:ET(/^[\da-f]{8}-[\da-f]{4}-5[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv5"),v6:ET(/^[\da-f]{8}-[\da-f]{4}-6[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv6"),v7:ET(/^[\da-f]{8}-[\da-f]{4}-7[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv7"),v8:ET(/^[\da-f]{8}-[\da-f]{4}-8[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv8")},{name:"string.uuid"}),jY=r.module({root:x.string,alpha:ET(/^[A-Za-z]*$/,"only letters"),alphanumeric:ET(/^[\dA-Za-z]*$/,"only letters and digits 0-9"),hex:nH,base64:rH,capitalize:sH,creditCard:T7,date:Y7,digits:ET(/^\d*$/,"only digits 0-9"),email:$7,integer:fY,ip:G7,json:O7,lower:U7,normalize:E7,numeric:z7,regex:V7,semver:L7,trim:D7,upper:S7,url:N7,uuid:C7},{name:"string"});var yY=r.module({bigint:x.bigint,boolean:x.boolean,false:x.false,never:x.never,null:x.null,number:x.number,object:x.object,string:x.string,symbol:x.symbol,true:x.true,unknown:x.unknown,undefined:x.undefined}),vY=r.module({root:x.unknown,any:x.unknown},{name:"unknown"}),B7=r.module({root:x.jsonObject,stringify:TF("morph",{in:x.jsonObject,morphs:(T)=>JSON.stringify(T),declaredOut:x.string})},{name:"object.json"}),xY=r.module({root:x.object,json:B7},{name:"object"});class bY extends uT{description='instantiate an object from an index signature and corresponding value type like `Record("string", "number")`'}var k7=K_(["K",x.key],"V")((T)=>({domain:"object",index:{signature:T.K,value:T.V}}),bY);class hY extends uT{description='pick a set of properties from an object like `Pick(User, "name | age")`'}var f7=K_(["T",x.object],["K",x.key])((T)=>T.T.pick(T.K),hY);class pY extends uT{description='omit a set of properties from an object like `Omit(User, "age")`'}var P7=K_(["T",x.object],["K",x.key])((T)=>T.T.omit(T.K),pY);class gY extends uT{description="make all named properties of an object optional like `Partial(User)`"}var q7=K_(["T",x.object])((T)=>T.T.partial(),gY);class mY extends uT{description="make all named properties of an object required like `Required(User)`"}var j7=K_(["T",x.object])((T)=>T.T.required(),mY);class oY extends uT{description='exclude branches of a union like `Exclude("boolean", "true")`'}var y7=K_("T","U")((T)=>T.T.exclude(T.U),oY);class uY extends uT{description='extract branches of a union like `Extract("0 | false | 1", "number")`'}var v7=K_("T","U")((T)=>T.T.extract(T.U),uY),cY=r.module({Exclude:y7,Extract:v7,Omit:P7,Partial:q7,Pick:f7,Record:k7,Required:j7});var O0=H4({...yY,...cY,...RY,...HY,string:jY,number:eW,object:xY,unknown:vY},{prereducedAliases:!0,name:"ark"}),jT=O0.export();Object.assign(WF.ambient,jT);WF.typeAttachments={string:jT.string.root,number:jT.number.root,bigint:jT.bigint,boolean:jT.boolean,symbol:jT.symbol,undefined:jT.undefined,null:jT.null,object:jT.object.root,unknown:jT.unknown.root,false:jT.false,true:jT.true,never:jT.never,arrayIndex:jT.Array.index,Key:jT.Key,Record:jT.Record,Array:jT.Array.root,Date:jT.Date};var Y_=Object.assign(O0.type,WF.typeAttachments),x7=O0.match,b7=O0.generic,fL=O0.schema,h7=O0.define,p7=O0.declare;class tF extends Promise{fate;resolve;reject;done=!1;constructor(T){let _,F;super((W,J)=>{_=W,F=J});this.resolve=_,this.reject=F,this.use(T instanceof Promise?T:new Promise(T))}pass(T,_){if(T===this.fate)this.resolve(_),this.done=!0}fail(T,_){if(T===this.fate)this.reject(_),this.done=!0}use(T){if(T instanceof Promise){let _=T;this.fate=_,_.then((F)=>{this.pass(_,F)},(F)=>{this.fail(_,F)})}else this.resolve(T),this.fate=void 0}}var iL=(T,_,F=lY.STORE)=>{return dY(F,{key:`${T.key}:JSON`,get:({get:W})=>_.toJson(W(T)),set:({set:W},J)=>{W(T,_.fromJson(J))}})};function sL(T,_,F){return U4(T,{key:`${_.key}:JSON`,get:(J)=>({get:Y})=>{let $=Y(_,J);return F.toJson($)},set:(J)=>({set:Y},$)=>{Y(_,J,F.fromJson($))}},["mutable","json"])}var iF=(T)=>JSON.parse(T),nT=(T)=>JSON.stringify(T),eL=[Array.prototype,Boolean.prototype,Number.prototype,Object.prototype,String.prototype];function m(T){while(T.child!==null)T=T.child;return T}class _1{_buffer;_index=0;constructor(T){let _;if(typeof T==="number")_=T;else _=T.length;this._buffer=Array.from({length:_})}get buffer(){return this._buffer}get index(){return this._index}add(T){this._buffer[this._index]=T,this._index=(this._index+1)%this._buffer.length}copy(){let T=new _1([...this._buffer]);return T._index=this._index,T}}var g7={atom_family:"atom",molecule_family:"molecule",mutable_atom_family:"mutable_atom",readonly_held_selector_family:"readonly_held_selector",readonly_pure_selector_family:"readonly_pure_selector",writable_held_selector_family:"writable_held_selector",writable_pure_selector_family:"writable_pure_selector"};function tY(T,_){let F=nT(_),W=`${T.key}(${F})`,J=g7[T.type],Y={key:W,type:J};return Object.assign(Y,{family:{key:T.key,subKey:F}}),Object.assign(Y,{counterfeit:!0}),Y}function nF(T){let _={key:T.key,type:T.type};if("family"in T)_.family=T.family;return _}var M4=(T)=>(_,F,W,J,...Y)=>{console[T](`${_} ${F} "${W}" ${J}`,...Y)},m7={error:M4("error"),info:M4("info"),warn:M4("warn")};class w4{logLevel;filter;logger;constructor(T,_,F=m7){this.logLevel=T,this.filter=_,this.logger=F}error=(...T)=>{let _=this.filter?.(...T)??!0;if(this.logLevel!==null){if(_===!0)this.logger.error(...T);else if(_!==!1)this.logger.error(..._)}};info=(...T)=>{let _=this.filter?.(...T)??!0;if(this.logLevel==="info"){if(_===!0)this.logger.info(...T);else if(_!==!1)this.logger.info(..._)}};warn=(...T)=>{let _=this.filter?.(...T)??!0;if(this.logLevel!=="error"&&this.logLevel!==null){if(_===!0)this.logger.warn(...T);else if(_!==!1)this.logger.warn(..._)}}}class m_{a;b;cardinality;relations=new Map;contents=new Map;isAType;isBType;isContent;makeContentKey=(T,_)=>`${T}:${_}`;warn;getRelatedKeys(T){return this.relations.get(T)}addRelation(T,_){let F=this.relations.get(T),W=this.relations.get(_);if(F)F.add(_);else F=new Set([_]),this.relations.set(T,F);if(W)W.add(T);else W=new Set([T]),this.relations.set(_,W)}deleteRelation(T,_){let F=this.relations.get(T);if(F){if(F.delete(_),F.size===0)this.relations.delete(T);let W=this.relations.get(_);if(W){if(W.delete(T),W.size===0)this.relations.delete(_)}}}replaceRelationsUnsafely(T,_){this.relations.set(T,new Set(_));for(let F of _){let W=new Set().add(T);this.relations.set(F,W)}}replaceRelationsSafely(T,_){let F=this.relations.get(T),W=this.isAType?.(T)?T:void 0,J=W===void 0?T:void 0;if(F)for(let Y of F){W??=Y,J??=Y;let $=this.relations.get(Y);if($){if($.size===1)this.relations.delete(Y);else $.delete(T);this.contents.delete(this.makeContentKey(W,J))}}this.relations.set(T,new Set(_));for(let Y of _){let $=this.relations.get(Y);if($)$.add(T);else $=new Set().add(T),this.relations.set(Y,$)}}getContentInternal(T){return this.contents.get(T)}setContent(T,_){this.contents.set(T,_)}deleteContent(T){this.contents.delete(T)}constructor(T,_){if(this.a=T.between[0],this.b=T.between[1],this.cardinality=T.cardinality,!_?.externalStore)this.relations=new Map(T.relations?.map(([F,W])=>[F,new Set(W)])),this.contents=new Map(T.contents);if(this.isAType=_?.isAType??null,this.isBType=_?.isBType??null,this.isContent=_?.isContent??null,_?.makeContentKey)this.makeContentKey=_.makeContentKey;if(_?.externalStore){let F=_.externalStore;if(this.has=(W,J)=>F.has(W,J),this.addRelation=(W,J)=>{F.addRelation(W,J)},this.deleteRelation=(W,J)=>{F.deleteRelation(W,J)},this.replaceRelationsSafely=(W,J)=>{F.replaceRelationsSafely(W,J)},this.replaceRelationsUnsafely=(W,J)=>{F.replaceRelationsUnsafely(W,J)},this.getRelatedKeys=(W)=>F.getRelatedKeys(W),F.getContent)this.getContentInternal=(W)=>{return F.getContent(W)},this.setContent=(W,J)=>{F.setContent(W,J)},this.deleteContent=(W)=>{F.deleteContent(W)};for(let[W,J]of T.relations??[]){let Y=this.isAType?.(W)?W:void 0,$=Y===void 0?W:void 0;for(let Z of J)Y??=Z,$??=Z,this.addRelation(Y,$)}for(let[W,J]of T.contents??[])this.setContent(W,J)}if(_?.warn)this.warn=_.warn}toJSON(){return{between:[this.a,this.b],cardinality:this.cardinality,relations:[...this.relations.entries()].map(([T,_])=>[T,[..._]]),contents:[...this.contents.entries()]}}set(...T){let _,F,W;switch(T.length){case 1:{let J=T[0];_=J[this.a],F=J[this.b],W=void 0;break}case 2:{let J=T[0];if(typeof J==="string")[_,F]=T;else _=J[this.a],F=J[this.b],W=T[1];break}default:{_=T[0],F=T[1],W=T[2];break}}switch(this.cardinality){case"1:1":{let J=this.getRelatedKey(_);if(J&&J!==F)this.delete(_,J)}case"1:n":{let J=this.getRelatedKey(F);if(J&&J!==_)this.delete(J,F)}break;case"n:n":}if(W){let J=this.makeContentKey(_,F);this.setContent(J,W)}return this.addRelation(_,F),this}delete(T,_){_=typeof _==="string"?_:T[this.b];let F=typeof T==="string"?T:T[this.a];if(F===void 0&&typeof _==="string"){let W=this.getRelatedKeys(_);if(W)for(let J of W)this.delete(J,_)}if(typeof F==="string"&&_===void 0){let W=this.getRelatedKeys(F);if(W)for(let J of W)this.delete(F,J)}if(typeof F==="string"&&typeof _==="string"){this.deleteRelation(F,_);let W=this.makeContentKey(F,_);this.deleteContent(W)}return this}getRelatedKey(T){let _=this.getRelatedKeys(T);if(_){if(_.size>1)this.warn?.(`${_.size} related keys were found for key "${T}": (${[..._].map((W)=>`"${W}"`).join(", ")}). Only one related key was expected.`);let F;for(let W of _){F=W;break}return F}}replaceRelations(T,_,F){let W=!Array.isArray(_),J=W?Object.keys(_):_;if(F?.reckless)this.replaceRelationsUnsafely(T,J);else this.replaceRelationsSafely(T,J);if(W)for(let Y of J){let $=this.makeContentKey(T,Y),Z=_[Y];this.setContent($,Z)}return this}getContent(T,_){let F=this.makeContentKey(T,_);return this.getContentInternal(F)}getRelationEntries(T){let _=T[this.a],F=T[this.b];if(_!==void 0&&F===void 0){let W=this.getRelatedKeys(_);if(W)return[...W].map((J)=>{return[J,this.getContent(_,J)]})}if(_===void 0&&F!==void 0){let W=this.getRelatedKeys(F);if(W)return[...W].map((J)=>{return[J,this.getContent(J,F)]})}return[]}has(T,_){if(_)return this.getRelatedKeys(T)?.has(_)??!1;return this.relations.has(T)}}class FT{Subscriber;subscribers=new Map;subscribe(T,_){return this.subscribers.set(T,_),()=>{this.unsubscribe(T)}}unsubscribe(T){this.subscribers.delete(T)}next(T){let _=this.subscribers.values();for(let F of _)F(T)}}class Q4 extends FT{state;constructor(T){super();this.state=T}next(T){this.state=T,super.next(T)}}function U0(T){return"epoch"in T.transactionMeta}function M_(T){return"phase"in T.transactionMeta}function iY(T){return T[0].toUpperCase()+T.slice(1)}function F1(T){return T.type.split("_").map(iY).join(" ")}class rF extends Error{constructor(T,_){super(`${F1(T)} ${nT(T.key)} not found in store "${_.config.name}".`)}}var YF=(T)=>(_)=>T instanceof Function?T(_):T;var M0=(T,_)=>{if(T.valueMap.has(_.key))return T.logger.info("\uD83D\uDCD6",_.type,_.key,"reading cached value"),nY(_,T);switch(_.type){case"readonly_held_selector":case"readonly_pure_selector":case"writable_held_selector":case"writable_pure_selector":return T.logger.info("\uD83E\uDDEE",_.type,_.key,"computing value"),_.get();case"atom":case"mutable_atom":{let F=_.default,W;if(F instanceof Function)W=F();else W=F;return T.logger.info("\uD83D\uDC81","atom",_.key,"could not find cached value; using default",W),W}}};var rY=(T,_)=>{if(T.operation.open){let F=performance.now();return T.logger.info("\u2757",_.type,_.key,`deferring setState at T-${F} until setState for "${T.operation.token.key}" is done`),F}T.operation={open:!0,done:new Set,prev:new Map,time:Date.now(),token:_},T.logger.info("\u2B55",_.type,_.key,`operation start in store "${T.config.name}"${!M_(T)?"":` ${T.transactionMeta.phase} "${T.transactionMeta.update.key}"`}`)},sY=(T)=>{if(T.operation.open)T.logger.info("\uD83D\uDD34",T.operation.token.type,T.operation.token.key,`operation done in store "${T.config.name}"`);T.operation={open:!1},T.on.operationClose.next(T.operation)},aY=(T,_)=>{if(!T.operation.open)return T.logger.error("\uD83D\uDC1E","unknown",_,"isDone called outside of an operation. This is probably a bug in AtomIO."),!0;return T.operation.done.has(_)},w0=(T,_)=>{if(!T.operation.open){T.logger.error("\uD83D\uDC1E","unknown",_,"markDone called outside of an operation. This is probably a bug in AtomIO.");return}T.operation.done.add(_)};var eY=(T,_,F)=>{switch(_.type){case"mutable_atom":T.logger.info("\uD83D\uDCE2",_.type,_.key,"is now (",F.newValue,") subscribers:",_.subject.subscribers);break;case"atom":case"writable_pure_selector":case"readonly_pure_selector":case"writable_held_selector":case"readonly_held_selector":T.logger.info("\uD83D\uDCE2",_.type,_.key,"went (",F.oldValue,"->",F.newValue,") subscribers:",_.subject.subscribers)}_.subject.next(F)};var R4=(T,_)=>{let F=m(T),W=F.selectorAtoms.getRelatedKeys(_.key);if(F.logger.info("\uD83E\uDDF9",_.type,_.key,W?`evicting ${W.size} states downstream:`:"no downstream states",W??"to evict"),W){if(F.operation.open)F.logger.info("\uD83E\uDDF9",_.type,_.key,`[ ${[...F.operation.done].join(", ")} ] already done`);for(let J of W){if(aY(F,J))continue;T$(J,F),w0(F,J)}}};var _$=(T,_,F)=>{let W=M0(T,_),J=W;if(_.type==="mutable_atom"&&M_(T)){let{parent:$}=T;J=sF(T,_,$)}if(J=YF(F)(J),T.logger.info("\uD83D\uDCDD","atom",_.key,"set to",J),J=rT(T,_.key,J,_.subject),W$(T,_.key))J$(T,_.key);w0(T,_.key),R4(T,_);let Y={oldValue:W,newValue:J};if(!M_(T)){eY(T,_,Y);return}if(T.on.transactionApplying.state===null){let{key:$}=_;if(F$(Y.newValue))return;let Z={type:"atom_update",key:$,...Y};if(_.family)Z.family=_.family;T.transactionMeta.update.updates.push(Z),T.logger.info("\uD83D\uDCC1","atom",$,"stowed (",Y.oldValue,"->",Y.newValue,")")}else if(_.key.startsWith("*")){let $=_.key.slice(1),Z=T.atoms.get($),G=T.valueMap.get($);if(Z.type==="mutable_atom"&&M_(T)){let{parent:O}=T;G=sF(T,Z,O)}if(G.do(Y.newValue)===null)R4(T,Z)}};var W1=(T,_,F)=>{switch(_.type){case"atom":case"mutable_atom":_$(T,_,F);break;case"writable_pure_selector":case"writable_held_selector":_.set(F);break}};var J1=(T,_)=>m(T).atoms.has(_),o7=(T,_)=>m(T).writableSelectors.has(_),u7=(T,_)=>m(T).readonlySelectors.has(_),Y$=(T,_)=>J1(T,_)||o7(T,_)||u7(T,_);var Y1=(T,_)=>{return m(T).selectorGraph.getRelationEntries({downstreamSelectorKey:_}).filter(([W,{source:J}])=>J!==_).map(([W,{source:J}])=>J).filter((W)=>Y$(T,W))};var E4=(T,_,F)=>{let W=[],J=Y1(T,_);while(J.length>0){let Y=J.shift();if(F.has(Y))continue;if(F.add(Y),!J1(T,Y))J.push(...Y1(T,Y));else if(!W.includes(Y))W.push(Y)}return W},$$=(T,_)=>{let F=T.key,W=Y1(_,F),J=new Set;return W.flatMap((Y)=>J1(_,Y)?Y:E4(_,Y,J))};var Z$=(T,_,F,W,J)=>{let Y=m(T),{type:$,key:Z}=W;if($==="atom"||$==="mutable_atom")Y.selectorAtoms.set({selectorKey:F,atomKey:Z}),T.logger.info("\uD83D\uDD0D",_,F,`discovers root atom "${Z}"`);else{let G=E4(T,Z,J);T.logger.info("\uD83D\uDD0D",_,F,`discovers root atoms: [ ${G.map((X)=>`"${X}"`).join(", ")} ]`);for(let X of G)Y.selectorAtoms=Y.selectorAtoms.set({selectorKey:F,atomKey:X})}J.add(Z)};var Q0=(T,_,F,W)=>({get:(...J)=>{let Y=m(T),$;if(J.length===2){let[O,M]=J;$=w_(T,O,M)}else[$]=J;let Z=$_(T,$),G=M0(T,Z),X=$.key;return T.logger.info("\uD83D\uDD0C",_,F,`registers dependency ( "${X}" =`,G,")"),Y.selectorGraph.set({upstreamSelectorKey:X,downstreamSelectorKey:F},{source:$.key}),Z$(T,_,F,$,W),G},set:(...J)=>{let Y,$;if(J.length===2)Y=J[0],$=J[1];else{let X=J[0],O=J[1];$=J[2],Y=w_(T,X,O)}let Z=m(T),G=$_(Z,Y);W1(Z,G,$)},find:(...J)=>w_(T,...J),json:(J)=>$F(T,J)});var z4=(T,_,F)=>{let W=m(T),J=new FT,Y=new Set,{key:$,const:Z}=_,G="readonly_held_selector",{get:X,find:O,json:M}=Q0(W,"readonly_held_selector",$,Y),K={..._,type:"readonly_held_selector",subject:J,install:(V)=>z4(V,_,F),get:()=>{return _.get({get:X,find:O,json:M},Z),rT(m(T),$,Z,J),Y.clear(),Z},...F&&{family:F}};W.readonlySelectors.set($,K),T.logger.info("\u2728","readonly_held_selector",$,"=",Z);let B={key:$,type:"readonly_held_selector"};if(F)B.family=F;return B};var V4=(T,_,F)=>{let W=m(T),J=new FT,Y=new Set,$=_.key,Z="readonly_pure_selector",{get:G,find:X,json:O}=Q0(W,"readonly_pure_selector",$,Y),M=()=>{let V=_.get({get:G,find:X,json:O});return rT(m(T),$,V,J),Y.clear(),V},Q={..._,type:"readonly_pure_selector",subject:J,install:(V)=>V4(V,_,F),get:M,...F&&{family:F}};W.readonlySelectors.set($,Q);let K=M();T.logger.info("\u2728","readonly_pure_selector",$,"=",K);let B={key:$,type:"readonly_pure_selector"};if(F)B.family=F;return B};var K4=(T,_,F)=>{let W=m(T),J=new FT,Y=new Set,{key:$,const:Z}=_,G="writable_held_selector",X=Q0(W,"writable_held_selector",$,Y),{find:O,get:M,json:Q}=X,K={find:O,get:M,json:Q},B=(y=_.get,u=m(T))=>{return y(K,Z),rT(u,$,Z,J),Y.clear(),Z},v={..._,type:"writable_held_selector",subject:J,install:(y)=>K4(y,_,F),get:B,set:(y)=>{let u=m(T),h=B(_.get,u),p=YF(y)(h);if(T.logger.info("\uD83D\uDCDD","writable_held_selector",$,"set (",h,"->",p,")"),rT(u,$,p,J),w0(u,$),U0(u))J.next({newValue:p,oldValue:h});_.set(X,p)},...F&&{family:F}};W.writableSelectors.set($,v);let q=B();T.logger.info("\u2728","writable_held_selector",$,"=",q);let j={key:$,type:"writable_held_selector"};if(F)j.family=F;return j};var aF=(T,_,F)=>{let W=m(T),J=new FT,Y=new Set,$=_.key,Z="writable_pure_selector",G=Q0(W,"writable_pure_selector",$,Y),{find:X,get:O,json:M}=G,Q={find:X,get:O,json:M},K=(j=_.get,y=m(T))=>{let u=j(Q);return rT(y,$,u,J),Y.clear(),u},V={..._,type:"writable_pure_selector",subject:J,install:(j)=>aF(j,_,F),get:K,set:(j)=>{let y=m(T),u=K(_.get,y),h=YF(j)(u);if(T.logger.info("\uD83D\uDCDD","writable_pure_selector",$,"set (",u,"->",h,")"),rT(y,_.key,h,J),w0(y,_.key),U0(y))J.next({newValue:h,oldValue:u});_.set(G,h)},...F&&{family:F}};W.writableSelectors.set($,V);let v=K();T.logger.info("\u2728",V.type,V.key,"=",v);let q={key:$,type:"writable_pure_selector"};if(F)q.family=F;return q};function dY(T,_){let F="set"in _,W="const"in _;if(W&&F){let Y=K4(T,_,void 0);return T.on.selectorCreation.next(Y),Y}if(W){let Y=z4(T,_,void 0);return T.on.selectorCreation.next(Y),Y}if(F){let Y=aF(T,_,void 0);return T.on.selectorCreation.next(Y),Y}let J=V4(T,_,void 0);return T.on.selectorCreation.next(J),J}function U4(T,_,F){let W=_.key,J="writable_pure_selector_family",Y={key:W,type:"writable_pure_selector_family"},$=T.families.get(W);if($)T.logger.error("\u2757","writable_pure_selector_family",W,`Overwriting an existing ${F1($)} "${$.key}" in store "${T.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);let Z=new FT,X=Object.assign((O)=>{let M=nT(O),Q={key:W,subKey:M},K=`${W}(${M})`,B=m(T),V=aF(B,{key:K,get:_.get(O),set:_.set(O)},Q);return Z.next({type:"state_creation",token:V}),V},Y,{internalRoles:F,subject:Z,install:(O)=>U4(O,_),default:(O)=>{return _.get(O)({get:(...Q)=>eF(T,...Q),find:(...Q)=>w_(T,...Q),json:(Q)=>$F(T,Q)})}});return T.families.set(W,X),Y}function X$(T,_,F){let W=T.families.get(_.key);if(W===void 0)throw new rF(_,T);let J=W(F),Y=m(T);if(J.family){if(U0(Y))switch(J.type){case"atom":case"mutable_atom":T.on.atomCreation.next(J);break;case"writable_pure_selector":case"readonly_pure_selector":case"writable_held_selector":case"readonly_held_selector":T.on.selectorCreation.next(J);break}else if(M_(Y)&&Y.on.transactionApplying.state===null)Y.transactionMeta.update.updates.push({type:"state_creation",token:J})}return J}function G$(T,_,F){let W=nT(F),J=`${_.key}(${W})`,Y=m(T),$;switch(_.type){case"atom_family":case"mutable_atom_family":$=Y.atoms.get(J);break;case"writable_held_selector_family":case"writable_pure_selector_family":$=Y.writableSelectors.get(J);break;case"readonly_held_selector_family":case"readonly_pure_selector_family":$=Y.readonlySelectors.get(J);break}if($)return nF($);return $}function w_(T,_,F){let W=G$(T,_,F);if(W)return W;let J=nT(F),Y=T.molecules.get(J);if(!Y&&T.config.lifespan==="immortal"){let $=tY(_,F);return T.logger.error("\u274C",$.type,$.key,`was not found in store "${T.config.name}"; returned a counterfeit token.`),$}if(W=X$(T,_,F),Y)m(T).moleculeData.set(J,_.key);return W}function A$(T,_){if(_.family){let F=T.families.get(_.family.key);if(F)return F}}function R0(T,..._){let F,W,J,Y;if(_.length===2){if(F=_[0],Y=_[1],W=A$(T,F)??null,W)J=F.family?iF(F.family.subKey):null,F=w_(T,W,J)}else W=_[0],J=_[1],Y=_[2],F=w_(T,W,J);if("counterfeit"in F&&"family"in F){let G=F.family.subKey,X=T.disposalTraces.buffer.find((O)=>O?.key===G);T.logger.error("\u274C",F.type,F.key,`could not be set because it was not found in the store "${T.config.name}".`,X?`This state was previously disposed:
|
|
48
|
+
${X.trace}`:"No previous disposal trace was found.");return}let $=rY(T,F);if($){let G=T.on.operationClose.subscribe(`waiting to set "${F.key}" at T-${$}`,()=>{G(),T.logger.info("\uD83D\uDFE2",F.type,F.key,`resuming deferred setState from T-${$}`),R0(T,F,Y)});return}let Z=$_(T,F);W1(T,Z,Y),sY(T)}function eF(T,..._){let F,W,J;if(_.length===1)F=_[0];else W=_[0],J=_[1],F=w_(T,W,J);if("counterfeit"in F&&"family"in F){W=T.families.get(F.family.key);let Y=F.family.subKey,$=T.disposalTraces.buffer.find((Z)=>Z?.key===Y);switch(T.logger.error("\u274C",F.type,F.key,`could not be retrieved because it was not found in the store "${T.config.name}".`,$?`This state was previously disposed:
|
|
49
|
+
${$.trace}`:"No previous disposal trace was found."),W.type){case"atom_family":case"mutable_atom_family":return T.defaults.get(W.key);case"readonly_pure_selector_family":case"writable_pure_selector_family":case"readonly_held_selector_family":case"writable_held_selector_family":{if(T.defaults.has(W.key))return T.defaults.get(F.family.key);let Z=$_(T,W).default(Y);return T.defaults.set(W.key,Z),Z}}}return M0(T,$_(T,F))}class H${parent=null;child=null;valueMap=new Map;defaults=new Map;atoms=new Map;writableSelectors=new Map;readonlySelectors=new Map;atomsThatAreDefault=new Set;selectorAtoms=new m_({between:["selectorKey","atomKey"],cardinality:"n:n"});selectorGraph=new m_({between:["upstreamSelectorKey","downstreamSelectorKey"],cardinality:"n:n"},{makeContentKey:(...T)=>T.sort().join(":")});trackers=new Map;families=new Map;joins=new Map;transactions=new Map;transactionMeta={epoch:new Map,actionContinuities:new m_({between:["continuity","action"],cardinality:"1:n"})};timelines=new Map;timelineTopics=new m_({between:["timelineKey","topicKey"],cardinality:"1:n"});disposalTraces=new _1(100);molecules=new Map;moleculeJoins=new m_({between:["moleculeKey","joinKey"],cardinality:"n:n"},{makeContentKey:(...T)=>T.sort().join(":")});moleculeGraph=new m_({between:["upstreamMoleculeKey","downstreamMoleculeKey"],cardinality:"n:n"},{makeContentKey:(...T)=>T.sort().join(":")});moleculeData=new m_({between:["moleculeKey","stateFamilyKey"],cardinality:"n:n"},{makeContentKey:(...T)=>T.sort().join(":")});miscResources=new Map;on={atomCreation:new FT,atomDisposal:new FT,selectorCreation:new FT,selectorDisposal:new FT,timelineCreation:new FT,transactionCreation:new FT,transactionApplying:new Q4(null),operationClose:new FT,moleculeCreation:new FT,moleculeDisposal:new FT};operation={open:!1};config={name:"IMPLICIT_STORE",lifespan:"ephemeral"};loggers=[new w4("warn",(T,_,F)=>!U$(F))];logger={error:(...T)=>{for(let _ of this.loggers)_.error(...T)},info:(...T)=>{for(let _ of this.loggers)_.info(...T)},warn:(...T)=>{for(let _ of this.loggers)_.warn(...T)}};constructor(T,_=null){if(this.config={..._?.config,...T},_!==null){if(this.valueMap=new Map(_?.valueMap),this.operation={..._?.operation},U0(_))this.transactionMeta={epoch:new Map(_?.transactionMeta.epoch),actionContinuities:new m_(_?.transactionMeta.actionContinuities.toJSON())};for(let[,W]of _.families){if(W.internalRoles?.includes("mutable")||W.internalRoles?.includes("join"))continue;W.install(this)}let F=new Set;for(let[,W]of _.atoms){if(F.has(W.key))continue;if(W.install(this),W.type==="mutable_atom"){let J=$F(_,W),Y=O$(W);F.add(J.key),F.add(Y.key)}}for(let[,W]of _.readonlySelectors)W.install(this);for(let[,W]of _.writableSelectors){if(F.has(W.key))continue;W.install(this)}for(let[,W]of _.transactions)W.install(this);for(let[,W]of _.timelines)W.install(this)}}}var lY={get STORE(){return globalThis.ATOM_IO_IMPLICIT_STORE??=new H$({name:"IMPLICIT_STORE",lifespan:"ephemeral"}),globalThis.ATOM_IO_IMPLICIT_STORE}};function $_(T,_){let F,W=T;while(W!==null){switch(_.type){case"atom":case"mutable_atom":F=W.atoms.get(_.key);break;case"writable_pure_selector":case"writable_held_selector":F=W.writableSelectors.get(_.key);break;case"readonly_pure_selector":case"readonly_held_selector":F=W.readonlySelectors.get(_.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":F=W.families.get(_.key);break;case"timeline":F=W.timelines.get(_.key);break;case"transaction":F=W.transactions.get(_.key);break}if(F)return F;W=W.child}throw new rF(_,T)}var M$=(T,_)=>{let F=m(T);if(F.operation.open)return F.operation.prev.get(_.key);return F.valueMap.get(_.key)};var L4=(T,_)=>{let F=m(T);return $$(_,T).map((J)=>{let Y=F.atoms.get(J);if(Y===void 0)throw new Error(`Atom "${J}", a dependency of selector "${_.key}", not found in store "${T.config.name}".`);return Y.subject.subscribe(`${_.type}:${_.key}`,($)=>{T.logger.info("\uD83D\uDCE2",_.type,_.key,"root",J,"went",$.oldValue,"->",$.newValue);let Z=M$(F,_),G=M0(F,_);T.logger.info("\u2728",_.type,_.key,"went",Z,"->",G),_.subject.next({newValue:G,oldValue:Z})})})};function TW(T,_,F,W){function J(M){if(T.operation.open){let Q=T.on.operationClose.subscribe(`state subscription ${F}`,()=>{Q(),W(M)})}else W(M)}let Y=$_(T,_);T.logger.info("\uD83D\uDC40",Y.type,Y.key,`Adding subscription "${F}"`);let $=Y.type==="writable_pure_selector"||Y.type==="readonly_pure_selector",Z=null,G=J;if($)Z=L4(T,Y),G=(M)=>{if(Z)Z.length=0,Z.push(...L4(T,Y));J(M)};let X=Y.subject.subscribe(F,G);return()=>{if(T.logger.info("\uD83D\uDE48",Y.type,Y.key,`Removing subscription "${F}"`),X(),Z)for(let M of Z)M()}}var w$=(T,_,F,W)=>{let J=$_(T,_);T.logger.info("\uD83D\uDC40","timeline",_.key,`Adding subscription "${F}"`);let Y=J.subject.subscribe(F,W);return()=>{T.logger.info("\uD83D\uDE48","timeline",_.key,`Removing subscription "${F}" from timeline`),Y()}};class D4{initializeState(T,_){let F=`*${T.key}`;_.atoms.delete(F),_.valueMap.delete(F);let W=T.family?{key:`*${T.family.key}`,subKey:T.family.subKey}:void 0,J=S4(_,{key:F,default:null},W);if(_.parent?.valueMap.has(F)){let Y=_.parent.valueMap.get(F);_.valueMap.set(F,Y)}return J}unsubscribeFromInnerValue;unsubscribeFromState;observeCore(T,_,F){let W=`tracker:${F.config.name}:${M_(F)?F.transactionMeta.update.key:"main"}:${T.key}`,J=eF(F,T);this.unsubscribeFromInnerValue=J.subscribe(W,(Y)=>{R0(F,_,Y)}),this.unsubscribeFromState=TW(F,T,W,(Y)=>{if(Y.newValue!==Y.oldValue)this.unsubscribeFromInnerValue(),this.unsubscribeFromInnerValue=Y.newValue.subscribe(W,($)=>{R0(F,_,$)})})}updateCore(T,_,F){let W=`tracker:${F.config.name}:${M_(F)?F.transactionMeta.update.key:"main"}:${T.key}`;TW(F,_,W,({newValue:J,oldValue:Y})=>{let $=F.timelineTopics.getRelatedKey(_.key);if($){if(F.timelines.get($)?.timeTraveling){let X=w$(F,{key:$,type:"timeline"},W,(O)=>{X(),R0(F,T,(M)=>{if(O==="redo"&&J)M.do(J);else if(O==="undo"&&Y)M.undo(Y);return M})});return}}let Z=F.on.operationClose.subscribe(W,()=>{Z();let G=eF(F,T),X=J===null?-1:G.getUpdateNumber(J),O=X-G.cacheUpdateNumber;if(J&&O===1)R0(F,T,(M)=>(M.do(J),M));else F.logger.info("\u274C","mutable_atom",T.key,`could not be updated. Expected update number ${G.cacheUpdateNumber+1}, but got ${X}`)})})}mutableState;latestUpdateState;[Symbol.dispose];constructor(T,_){this.mutableState=T;let F=m(_);this.latestUpdateState=this.initializeState(T,F),this.observeCore(T,this.latestUpdateState,F),this.updateCore(T,this.latestUpdateState,F),F.trackers.set(T.key,this),this[Symbol.dispose]=()=>{this.unsubscribeFromInnerValue(),this.unsubscribeFromState(),F.trackers.delete(T.key)}}}var $F=(T,_)=>{if(_.family){let W=m(T),Y={key:`${_.family.key}:JSON`,type:"writable_pure_selector_family"},$=$_(W,Y),Z=JSON.parse(_.family.subKey);return w_(T,$,Z)}return{type:"writable_pure_selector",key:`${_.key}:JSON`}};var O$=(T)=>{let F={type:"atom",key:`*${T.key}`};if(T.family)F.family={key:`*${T.family.key}`,subKey:T.family.subKey};return F};function F$(T){return typeof T==="object"&&T!==null&&"do"in T&&"undo"in T&&"subscribe"in T}function sF(T,_,F){let W=F.valueMap.get(_.key),J=T.valueMap.get(_.key);if(W!==J)return J;if(W===void 0)return _.default();F.logger.info("\uD83D\uDCC3","atom",_.key,"copying");let Y=_.toJson(W),$=_.fromJson(Y);return T.valueMap.set(_.key,$),new D4(_,F),$}function rT(T,_,F,W){let J=T.valueMap.get(_);if(J instanceof tF)J.use(F);if(F instanceof Promise){let Y=new tF(F);return T.valueMap.set(_,Y),Y.then(($)=>{rT(T,_,$,W),W.next({newValue:$,oldValue:Y})}).catch(($)=>{T.logger.error("\uD83D\uDCA5","state",_,"rejected:",$)}),Y}return T.valueMap.set(_,F),F}var nY=(T,_)=>{let F=_.valueMap.get(T.key);if(T.type==="mutable_atom"&&M_(_)){let{parent:W}=_;F=sF(_,T,W)}return F},T$=(T,_)=>{let F=_.valueMap.get(T);if(F instanceof tF){let W=F,J=_.writableSelectors.get(T)??_.readonlySelectors.get(T);if(J)W.use(J.get());return}if(_.operation.open)_.operation.prev.set(T,F);_.valueMap.delete(T),_.logger.info("\uD83D\uDDD1","state",T,"evicted")};var W$=(T,_)=>{return m(T).atomsThatAreDefault.has(_)},Q$=(T,_)=>{let F=m(T);F.atomsThatAreDefault=new Set(F.atomsThatAreDefault).add(_)},J$=(T,_)=>{let F=m(T);F.atomsThatAreDefault=new Set(m(T).atomsThatAreDefault),F.atomsThatAreDefault.delete(_)};function S4(T,_,F){let{key:J,default:Y}=_;T.logger.info("\uD83D\uDD28","atom",J,`creating in store "${T.config.name}"`);let $=m(T),Z=$.atoms.get(J);if(Z&&Z.type==="atom")return T.logger.error("\u274C","atom",J,"Tried to create atom, but it already exists in the store."),nF(Z);let G=new FT,X={..._,type:"atom",install:(Q)=>{return Q.logger.info("\uD83D\uDEE0\uFE0F","atom",J,`installing in store "${Q.config.name}"`),S4(Q,_,F)},subject:G};if(F)X.family=F;let O=Y;if(Y instanceof Function)O=Y();$.atoms.set(J,X),Q$(T,J),rT($,J,O,G);let M=nF(X);if(_.effects){let Q=0,K=[];for(let B of _.effects){let V=B({setSelf:(v)=>{R0(T,M,v)},onSet:(v)=>TW(T,M,`effect[${Q}]`,v)});if(V)K.push(V);++Q}X.cleanup=()=>{for(let B of K)B()}}return M}class ZF extends Set{mode="record";subject=new FT;cacheLimit=0;cache=[];cacheIdx=-1;cacheUpdateNumber=-1;constructor(T,_=0){super(T);if(T instanceof ZF)this.parent=T,this.cacheUpdateNumber=T.cacheUpdateNumber;if(_)this.cacheLimit=_,this.cache=new Array(_),this.subscribe("auto cache",(F)=>{this.cacheIdx++,this.cacheIdx%=this.cacheLimit,this.cache[this.cacheIdx]=F})}toJSON(){return{members:[...this],cache:this.cache,cacheLimit:this.cacheLimit,cacheIdx:this.cacheIdx,cacheUpdateNumber:this.cacheUpdateNumber}}static fromJSON(T){let _=new ZF(T.members,T.cacheLimit);return _.cache=T.cache,_.cacheIdx=T.cacheIdx,_.cacheUpdateNumber=T.cacheUpdateNumber,_}add(T){let _=super.add(T);if(this.mode==="record")this.cacheUpdateNumber++,this.emit(`add:${nT(T)}`);return _}clear(){let T=this.mode==="record"?[...this]:null;if(super.clear(),T)this.cacheUpdateNumber++,this.emit(`clear:${JSON.stringify(T)}`)}delete(T){let _=super.delete(T);if(this.mode==="record")this.cacheUpdateNumber++,this.emit(`del:${nT(T)}`);return _}parent=null;child=null;transactionUpdates=null;transaction(T){this.mode="transaction",this.transactionUpdates=[],this.child=new ZF(this);let _=this.child._subscribe("transaction",(F)=>{this.transactionUpdates?.push(F)});try{if(T(this.child)){for(let W of this.transactionUpdates)this.doStep(W);this.cacheUpdateNumber++,this.emit(`tx:${this.transactionUpdates.join(";")}`)}}catch(F){throw console.warn("Did not apply transaction to SetRTX; this error was thrown:",F),F}finally{_(),this.child=null,this.transactionUpdates=null,this.mode="record"}}_subscribe(T,_){return this.subject.subscribe(T,_)}subscribe(T,_){return this.subject.subscribe(T,(F)=>{_(`${this.cacheUpdateNumber}=${F}`)})}emit(T){this.subject.next(T)}doStep(T){let _=T.indexOf(":"),F=T.substring(0,_),W=T.substring(_+1);switch(F){case"add":this.add(JSON.parse(W));break;case"clear":this.clear();break;case"del":this.delete(JSON.parse(W));break;case"tx":for(let J of W.split(";"))this.doStep(J)}}getUpdateNumber(T){let _=T.indexOf("=");return Number(T.substring(0,_))}do(T){let _=T.indexOf("="),F=Number(T.substring(0,_)),W=F-this.cacheUpdateNumber;if(W>0){if(W===1){this.mode="playback";let Y=T.substring(_+1);return this.doStep(Y),this.mode="record",this.cacheUpdateNumber=F,null}return this.cacheUpdateNumber+1}if(Math.abs(W)<this.cacheLimit){let Y=this.cacheIdx+W;if(this.cache[Y]===T)return null;this.mode="playback";let Z=!1;while(!Z){this.cacheIdx%=this.cacheLimit;let X=this.cache[this.cacheIdx];if(this.cacheIdx--,!X)return"OUT_OF_RANGE";this.undo(X),Z=this.cacheIdx===Y-1}let G=T.substring(_+1);return this.doStep(G),this.mode="record",this.cacheUpdateNumber=F,null}return"OUT_OF_RANGE"}undoStep(T){let _=T.indexOf(":"),F=T.substring(0,_),W=T.substring(_+1);switch(F){case"add":this.delete(JSON.parse(W));break;case"del":this.add(JSON.parse(W));break;case"clear":{let J=JSON.parse(W);for(let Y of J)this.add(Y);break}case"tx":{let J=W.split(";");for(let Y=J.length-1;Y>=0;Y--)this.undoStep(J[Y])}}}undo(T){let _=T.indexOf("=");if(Number(T.substring(0,_))===this.cacheUpdateNumber){this.mode="playback";let W=T.substring(_+1);return this.undoStep(W),this.mode="record",this.cacheUpdateNumber--,null}return this.cacheUpdateNumber}}function U$(T){return T.startsWith("\uD83D\uDD0D ")}class $1{supported;constructor(T){this.supported=T}refine(T){for(let[_,F]of Object.entries(this.supported))try{if(F(T)===!0&&F!==Boolean)return{type:_,data:T}}catch(W){try{if(T instanceof F)return{type:_,data:T}}catch(J){}}return null}}var c7=new $1({number:(T)=>typeof T==="number",string:(T)=>typeof T==="string",boolean:(T)=>typeof T==="boolean",null:(T)=>T===null});function d7(T){if(!T)return!1;return Object.getPrototypeOf(T)===Object.prototype}var l7=new $1({object:d7,array:(T)=>Array.isArray(T)}),t7=new $1({...c7.supported,...l7.supported}),R$=(T)=>{if(T===void 0)return"undefined";let _=t7.refine(T);if(_)return _.type;return Object.getPrototypeOf(T).constructor.name};class Z1{listeners;globalListeners;handleEvent(T,..._){for(let W of this.globalListeners)W(T,..._);let F=this.listeners.get(T);if(F)for(let W of F)W(..._)}id="no_id_retrieved";emit;constructor(T){this.emit=T,this.listeners=new Map,this.globalListeners=new Set}on(T,_){let F=this.listeners.get(T);if(F)F.add(_);else this.listeners.set(T,new Set([_]));return this}onAny(T){return this.globalListeners.add(T),this}off(T,_){let F=this.listeners.get(T);if(F)if(_)F.delete(_);else this.listeners.delete(T);return this}offAny(T){return this.globalListeners.delete(T),this}}class E$ extends Z1{in;out;id="no_id_retrieved";disposalFunctions=[];constructor(T){super((..._)=>{return this.out.next(_),this});this.id=T,this.in=new FT,this.out=new FT,this.in.subscribe("socket",(_)=>{this.handleEvent(..._)})}dispose(){for(let T of this.disposalFunctions)T()}}class I4 extends Z1{incompleteData="";unprocessedEvents=[];relays;relayServices;process;id="#####";log(...T){this.process.stderr.write(nT(T.map((_)=>_ instanceof ZF?`{ ${_.toJSON().members.join(" | ")} }`:_))+"\x03")}logger={info:(...T)=>{this.log("i",...T)},warn:(...T)=>{this.log("w",...T)},error:(...T)=>{this.log("e",...T)}};constructor(){super((T,..._)=>{let F=JSON.stringify([T,..._]);return this.process.stdout.write(F+"\x03"),this});if(this.process=process,this.process.stdin.resume(),this.relays=new Map,this.relayServices=[],this.process.stdin.on("data",(T)=>{let _=T.toString();this.unprocessedEvents.push(..._.split("\x03"));let F=this.unprocessedEvents.shift();this.incompleteData+=F??"";try{let W=iF(this.incompleteData);this.logger.info("\uD83C\uDFB0","received",W),this.handleEvent(...W);while(this.unprocessedEvents.length>0){let J=this.unprocessedEvents.shift();if(J){if(this.unprocessedEvents.length===0)this.incompleteData=J;let Y=iF(J);this.handleEvent(...Y)}}this.incompleteData=""}catch(W){if(W instanceof Error)this.logger.error("\u2757",W.message,W.cause,W.stack)}}),this.on("exit",()=>{this.logger.info("\uD83D\uDD25",this.id,'received "exit"'),process.exit(0)}),process.on("exit",(T)=>{this.logger.info("\uD83D\uDD25",this.id,`exited with code ${T}`)}),process.on("end",()=>{this.logger.info("\uD83D\uDD25",this.id,"ended"),process.exit(0)}),process.on("SIGTERM",()=>{this.logger.error("\uD83D\uDD25",this.id,"terminated"),process.exit(0)}),process.on("SIGINT",()=>{this.logger.error("\uD83D\uDD25",this.id,"interrupted"),process.exit(0)}),process.pid)this.id=process.pid?.toString();this.on("user-joins",(T)=>{this.logger.info("\uD83D\uDC64","user",T,"joined");let _=new E$(`user:${T}`);this.relays.set(T,_),this.logger.info("\uD83D\uDD17","attaching services:",`[${[...this.relayServices.keys()].join(", ")}]`);for(let F of this.relayServices){let W=F(_);if(W)_.disposalFunctions.push(W)}this.on(`user:${T}`,(...F)=>{_.in.next(F)}),_.out.subscribe("socket",(F)=>{this.emit(...F)})}),this.on("user-leaves",(T)=>{let _=this.relays.get(T);if(this.off(`relay:${T}`),_)_.dispose(),this.relays.delete(T)}),process.stdout.write("ALIVE")}relay(T){this.logger.info("\uD83D\uDD17","running relay method"),this.relayServices.push(T)}}var{file:n5,serve:GO}=globalThis.Bun;import{readFileSync as K$}from"fs";import{createServer as s7}from"http";import{createServer as a7}from"https";import{resolve as C4}from"path";function z$(T,_){if(T instanceof Promise)throw new Error(_)}function i7(T,_){let F={},W=[];for(let J in T){let Y=T[J]["~standard"].validate(_[J]);if(z$(Y,`Validation must be synchronous, but ${J} returned a Promise.`),Y.issues){W.push(...Y.issues.map(($)=>({...$,message:$.message,path:[J,...$.path??[]]})));continue}F[J]=Y.value}if(W.length)return{issues:W};return{value:F}}function N4(T){let _=T.runtimeEnvStrict??T.runtimeEnv??process.env;if(T.emptyStringAsUndefined??!1){for(let[j,y]of Object.entries(_))if(y==="")delete _[j]}if(!!T.skipValidation)return _;let J=typeof T.client==="object"?T.client:{},Y=typeof T.server==="object"?T.server:{},$=typeof T.shared==="object"?T.shared:{},Z=T.isServer??(typeof window==="undefined"||("Deno"in window)),G=Z?{...Y,...$,...J}:{...J,...$},X=T.createFinalSchema?.(G,Z)["~standard"].validate(_)??i7(G,_);z$(X,"Validation must be synchronous");let O=T.onValidationError??((j)=>{throw console.error("\u274C Invalid environment variables:",j),new Error("Invalid environment variables")}),M=T.onInvalidAccess??(()=>{throw new Error("\u274C Attempted to access a server-side environment variable on the client")});if(X.issues)return O(X.issues);let Q=(j)=>{if(!T.clientPrefix)return!0;return!j.startsWith(T.clientPrefix)&&!(j in $)},K=(j)=>{return Z||!Q(j)},B=(j)=>{return j==="__esModule"||j==="$$typeof"},V=(T.extends??[]).reduce((j,y)=>{return Object.assign(j,y)},{}),v=Object.assign(V,X.value);return new Proxy(v,{get(j,y){if(typeof y!=="string")return;if(B(y))return;if(!K(y))return M(y);return Reflect.get(j,y)}})}var n7="__vite_start_time"in globalThis,r7=typeof window!=="undefined",BN="vitest"in globalThis,a_=Y_("string"),V$=Y_('"true" | "false" | undefined'),q_=N4({isServer:!n7&&!r7,server:{CI:Y_("string | undefined").pipe(Boolean),POSTGRES_USER:a_,POSTGRES_PASSWORD:a_,POSTGRES_DATABASE:a_,POSTGRES_HOST:a_,POSTGRES_PORT:a_.pipe((T)=>Number.parseInt(T,10)),BACKEND_PORT:a_.pipe((T)=>Number.parseInt(T,10)),RUN_WORKERS_FROM_SOURCE:V$.pipe((T)=>T==="true"),FRONTEND_PORT:a_.pipe((T)=>Number.parseInt(T,10)),FRONTEND_ORIGINS:a_.pipe.try((T)=>JSON.parse(T),Y_("string[]")),API_KEY_OPENAI:Y_("string | undefined"),API_KEY_RESEND:Y_("string | undefined")},clientPrefix:"VITE_",client:{VITE_BACKEND_ORIGIN:a_,VITE_DEV_FRONTEND_HOST:Y_("string | undefined"),VITE_DEV_HTTPS:V$.pipe((T)=>T==="true")},runtimeEnv:import.meta.env,emptyStringAsUndefined:!0});var L$=C4(import.meta.dirname,"../dev"),X1=q_.VITE_DEV_HTTPS?{cert:K$(C4(L$,"./cert.pem"),"utf-8"),key:K$(C4(L$,"./key.pem"),"utf-8")}:void 0;function vN(T){if(X1)return a7(X1,T);return s7({},T)}import FO from"path";var H=Symbol.for("drizzle:entityKind"),bN=Symbol.for("drizzle:hasOwnEntityKind");function R(T,_){if(!T||typeof T!=="object")return!1;if(T instanceof _)return!0;if(!Object.prototype.hasOwnProperty.call(_,H))throw new Error(`Class "${_.name??"<unknown>"}" doesn't look like a Drizzle entity. If this is incorrect and the class is provided by Drizzle, please report this as a bug.`);let F=Object.getPrototypeOf(T).constructor;if(F)while(F){if(H in F&&F[H]===_[H])return!0;F=Object.getPrototypeOf(F)}return!1}class GT{constructor(T,_){this.table=T,this.config=_,this.name=_.name,this.keyAsName=_.keyAsName,this.notNull=_.notNull,this.default=_.default,this.defaultFn=_.defaultFn,this.onUpdateFn=_.onUpdateFn,this.hasDefault=_.hasDefault,this.primary=_.primaryKey,this.isUnique=_.isUnique,this.uniqueName=_.uniqueName,this.uniqueType=_.uniqueType,this.dataType=_.dataType,this.columnType=_.columnType,this.generated=_.generated,this.generatedIdentity=_.generatedIdentity}static[H]="Column";name;keyAsName;primary;notNull;default;defaultFn;onUpdateFn;hasDefault;isUnique;uniqueName;uniqueType;dataType;columnType;enumValues=void 0;generated=void 0;generatedIdentity=void 0;config;mapFromDriverValue(T){return T}mapToDriverValue(T){return T}shouldDisableInsert(){return this.config.generated!==void 0&&this.config.generated.type!=="byDefault"}}class B4{static[H]="ColumnBuilder";config;constructor(T,_,F){this.config={name:T,keyAsName:T==="",notNull:!1,default:void 0,hasDefault:!1,primaryKey:!1,isUnique:!1,uniqueName:void 0,uniqueType:void 0,dataType:_,columnType:F,generated:void 0}}$type(){return this}notNull(){return this.config.notNull=!0,this}default(T){return this.config.default=T,this.config.hasDefault=!0,this}$defaultFn(T){return this.config.defaultFn=T,this.config.hasDefault=!0,this}$default=this.$defaultFn;$onUpdateFn(T){return this.config.onUpdateFn=T,this.config.hasDefault=!0,this}$onUpdate=this.$onUpdateFn;primaryKey(){return this.config.primaryKey=!0,this.config.notNull=!0,this}setName(T){if(this.config.name!=="")return;this.config.name=T}}var j_=Symbol.for("drizzle:Name");class k4{static[H]="PgForeignKeyBuilder";reference;_onUpdate="no action";_onDelete="no action";constructor(T,_){if(this.reference=()=>{let{name:F,columns:W,foreignColumns:J}=T();return{name:F,columns:W,foreignTable:J[0].table,foreignColumns:J}},_)this._onUpdate=_.onUpdate,this._onDelete=_.onDelete}onUpdate(T){return this._onUpdate=T===void 0?"no action":T,this}onDelete(T){return this._onDelete=T===void 0?"no action":T,this}build(T){return new D$(T,this)}}class D${constructor(T,_){this.table=T,this.reference=_.reference,this.onUpdate=_._onUpdate,this.onDelete=_._onDelete}static[H]="PgForeignKey";reference;onUpdate;onDelete;getName(){let{name:T,columns:_,foreignColumns:F}=this.reference(),W=_.map(($)=>$.name),J=F.map(($)=>$.name),Y=[this.table[j_],...W,F[0].table[j_],...J];return T??`${Y.join("_")}_fk`}}function G1(T,..._){return T(..._)}function S$(T,_){return`${T[j_]}_${_.join("_")}_unique`}function I$(T,_,F){for(let W=_;W<T.length;W++){let J=T[W];if(J==="\\"){W++;continue}if(J==='"')return[T.slice(_,W).replace(/\\/g,""),W+1];if(F)continue;if(J===","||J==="}")return[T.slice(_,W).replace(/\\/g,""),W]}return[T.slice(_).replace(/\\/g,""),T.length]}function N$(T,_=0){let F=[],W=_,J=!1;while(W<T.length){let Y=T[W];if(Y===","){if(J||W===_)F.push("");J=!0,W++;continue}if(J=!1,Y==="\\"){W+=2;continue}if(Y==='"'){let[G,X]=I$(T,W+1,!0);F.push(G),W=X;continue}if(Y==="}")return[F,W+1];if(Y==="{"){let[G,X]=N$(T,W+1);F.push(G),W=X;continue}let[$,Z]=I$(T,W,!1);F.push($),W=Z}return[F,W]}function C$(T){let[_]=N$(T,1);return _}function f4(T){return`{${T.map((_)=>{if(Array.isArray(_))return f4(_);if(typeof _==="string")return`"${_.replace(/\\/g,"\\\\").replace(/"/g,"\\\"")}"`;return`${_}`}).join(",")}}`}class f extends B4{foreignKeyConfigs=[];static[H]="PgColumnBuilder";array(T){return new k$(this.config.name,this,T)}references(T,_={}){return this.foreignKeyConfigs.push({ref:T,actions:_}),this}unique(T,_){return this.config.isUnique=!0,this.config.uniqueName=T,this.config.uniqueType=_?.nulls,this}generatedAlwaysAs(T){return this.config.generated={as:T,type:"always",mode:"stored"},this}buildForeignKeys(T,_){return this.foreignKeyConfigs.map(({ref:F,actions:W})=>{return G1((J,Y)=>{let $=new k4(()=>{let Z=J();return{columns:[T],foreignColumns:[Z]}});if(Y.onUpdate)$.onUpdate(Y.onUpdate);if(Y.onDelete)$.onDelete(Y.onDelete);return $.build(_)},F,W)})}buildExtraConfigColumn(T){return new B$(T,this.config)}}class S extends GT{constructor(T,_){if(!_.uniqueName)_.uniqueName=S$(T,[_.name]);super(T,_);this.table=T}static[H]="PgColumn"}class B$ extends S{static[H]="ExtraConfigColumn";getSQLType(){return this.getSQLType()}indexConfig={order:this.config.order??"asc",nulls:this.config.nulls??"last",opClass:this.config.opClass};defaultConfig={order:"asc",nulls:"last",opClass:void 0};asc(){return this.indexConfig.order="asc",this}desc(){return this.indexConfig.order="desc",this}nullsFirst(){return this.indexConfig.nulls="first",this}nullsLast(){return this.indexConfig.nulls="last",this}op(T){return this.indexConfig.opClass=T,this}}class _W{static[H]="IndexedColumn";constructor(T,_,F,W){this.name=T,this.keyAsName=_,this.type=F,this.indexConfig=W}name;keyAsName;type;indexConfig}class k$ extends f{static[H]="PgArrayBuilder";constructor(T,_,F){super(T,"array","PgArray");this.config.baseBuilder=_,this.config.size=F}build(T){let _=this.config.baseBuilder.build(T);return new P4(T,this.config,_)}}class P4 extends S{constructor(T,_,F,W){super(T,_);this.baseColumn=F,this.range=W,this.size=_.size}size;static[H]="PgArray";getSQLType(){return`${this.baseColumn.getSQLType()}[${typeof this.size==="number"?this.size:""}]`}mapFromDriverValue(T){if(typeof T==="string")T=C$(T);return T.map((_)=>this.baseColumn.mapFromDriverValue(_))}mapToDriverValue(T,_=!1){let F=T.map((W)=>W===null?null:R(this.baseColumn,P4)?this.baseColumn.mapToDriverValue(W,!0):this.baseColumn.mapToDriverValue(W));if(_)return F;return f4(F)}}class f$ extends f{static[H]="PgEnumObjectColumnBuilder";constructor(T,_){super(T,"string","PgEnumObjectColumn");this.config.enum=_}build(T){return new P$(T,this.config)}}class P$ extends S{static[H]="PgEnumObjectColumn";enum;enumValues=this.config.enum.enumValues;constructor(T,_){super(T,_);this.enum=_.enum}getSQLType(){return this.enum.enumName}}var A1=Symbol.for("drizzle:isPgEnum");function q$(T){return!!T&&typeof T==="function"&&A1 in T&&T[A1]===!0}class j$ extends f{static[H]="PgEnumColumnBuilder";constructor(T,_){super(T,"string","PgEnumColumn");this.config.enum=_}build(T){return new y$(T,this.config)}}class y$ extends S{static[H]="PgEnumColumn";enum=this.config.enum;enumValues=this.config.enum.enumValues;constructor(T,_){super(T,_);this.enum=_.enum}getSQLType(){return this.enum.enumName}}function FW(T,_){return Array.isArray(_)?e7(T,[..._],void 0):T3(T,_,void 0)}function e7(T,_,F){let W=Object.assign((J)=>new j$(J??"",W),{enumName:T,enumValues:_,schema:F,[A1]:!0});return W}function T3(T,_,F){let W=Object.assign((J)=>new f$(J??"",W),{enumName:T,enumValues:Object.values(_),schema:F,[A1]:!0});return W}class IT{static[H]="Subquery";constructor(T,_,F,W=!1,J=[]){this._={brand:"Subquery",sql:T,selectedFields:_,alias:F,isWith:W,usedTables:J}}}class WW extends IT{static[H]="WithSubquery"}var v$="0.44.0";var q4,j4,AT={startActiveSpan(T,_){if(!q4)return _();if(!j4)j4=q4.trace.getTracer("drizzle-orm",v$);return G1((F,W)=>W.startActiveSpan(T,(J)=>{try{return _(J)}catch(Y){throw J.setStatus({code:F.SpanStatusCode.ERROR,message:Y instanceof Error?Y.message:"Unknown error"}),Y}finally{J.end()}}),q4,j4)}};var MT=Symbol.for("drizzle:ViewBaseConfig");var k0=Symbol.for("drizzle:Schema"),H1=Symbol.for("drizzle:Columns"),x$=Symbol.for("drizzle:ExtraConfigColumns"),y4=Symbol.for("drizzle:OriginalName"),v4=Symbol.for("drizzle:BaseName"),JW=Symbol.for("drizzle:IsAlias"),b$=Symbol.for("drizzle:ExtraConfigBuilder"),_3=Symbol.for("drizzle:IsDrizzleTable");class I{static[H]="Table";static Symbol={Name:j_,Schema:k0,OriginalName:y4,Columns:H1,ExtraConfigColumns:x$,BaseName:v4,IsAlias:JW,ExtraConfigBuilder:b$};[j_];[y4];[k0];[H1];[x$];[v4];[JW]=!1;[_3]=!0;[b$]=void 0;constructor(T,_,F){this[j_]=this[y4]=T,this[k0]=_,this[v4]=F}}function xT(T){return T[j_]}function f0(T){return`${T[k0]??"public"}.${T[j_]}`}function x4(T){return T!==null&&T!==void 0&&typeof T.getSQL==="function"}function F3(T){let _={sql:"",params:[]};for(let F of T)if(_.sql+=F.sql,_.params.push(...F.params),F.typings?.length){if(!_.typings)_.typings=[];_.typings.push(...F.typings)}return _}class yT{static[H]="StringChunk";value;constructor(T){this.value=Array.isArray(T)?T:[T]}getSQL(){return new k([this])}}class k{constructor(T){this.queryChunks=T;for(let _ of T)if(R(_,I)){let F=_[I.Symbol.Schema];this.usedTables.push(F===void 0?_[I.Symbol.Name]:F+"."+_[I.Symbol.Name])}}static[H]="SQL";decoder=p$;shouldInlineParams=!1;usedTables=[];append(T){return this.queryChunks.push(...T.queryChunks),this}toQuery(T){return AT.startActiveSpan("drizzle.buildSQL",(_)=>{let F=this.buildQueryFromSourceParams(this.queryChunks,T);return _?.setAttributes({"drizzle.query.text":F.sql,"drizzle.query.params":JSON.stringify(F.params)}),F})}buildQueryFromSourceParams(T,_){let F=Object.assign({},_,{inlineParams:_.inlineParams||this.shouldInlineParams,paramStartIndex:_.paramStartIndex||{value:0}}),{casing:W,escapeName:J,escapeParam:Y,prepareTyping:$,inlineParams:Z,paramStartIndex:G}=F;return F3(T.map((X)=>{if(R(X,yT))return{sql:X.value.join(""),params:[]};if(R(X,O1))return{sql:J(X.value),params:[]};if(X===void 0)return{sql:"",params:[]};if(Array.isArray(X)){let O=[new yT("(")];for(let[M,Q]of X.entries())if(O.push(Q),M<X.length-1)O.push(new yT(", "));return O.push(new yT(")")),this.buildQueryFromSourceParams(O,F)}if(R(X,k))return this.buildQueryFromSourceParams(X.queryChunks,{...F,inlineParams:Z||X.shouldInlineParams});if(R(X,I)){let O=X[I.Symbol.Schema],M=X[I.Symbol.Name];return{sql:O===void 0||X[JW]?J(M):J(O)+"."+J(M),params:[]}}if(R(X,GT)){let O=W.getColumnCasing(X);if(_.invokeSource==="indexes")return{sql:J(O),params:[]};let M=X.table[I.Symbol.Schema];return{sql:X.table[JW]||M===void 0?J(X.table[I.Symbol.Name])+"."+J(O):J(M)+"."+J(X.table[I.Symbol.Name])+"."+J(O),params:[]}}if(R(X,Z_)){let O=X[MT].schema,M=X[MT].name;return{sql:O===void 0||X[MT].isAlias?J(M):J(O)+"."+J(M),params:[]}}if(R(X,Q_)){if(R(X.value,E0))return{sql:Y(G.value++,X),params:[X],typings:["none"]};let O=X.value===null?null:X.encoder.mapToDriverValue(X.value);if(R(O,k))return this.buildQueryFromSourceParams([O],F);if(Z)return{sql:this.mapInlineParam(O,F),params:[]};let M=["none"];if($)M=[$(X.encoder)];return{sql:Y(G.value++,O),params:[O],typings:M}}if(R(X,E0))return{sql:Y(G.value++,X),params:[X],typings:["none"]};if(R(X,k.Aliased)&&X.fieldAlias!==void 0)return{sql:J(X.fieldAlias),params:[]};if(R(X,IT)){if(X._.isWith)return{sql:J(X._.alias),params:[]};return this.buildQueryFromSourceParams([new yT("("),X._.sql,new yT(") "),new O1(X._.alias)],F)}if(q$(X)){if(X.schema)return{sql:J(X.schema)+"."+J(X.enumName),params:[]};return{sql:J(X.enumName),params:[]}}if(x4(X)){if(X.shouldOmitSQLParens?.())return this.buildQueryFromSourceParams([X.getSQL()],F);return this.buildQueryFromSourceParams([new yT("("),X.getSQL(),new yT(")")],F)}if(Z)return{sql:this.mapInlineParam(X,F),params:[]};return{sql:Y(G.value++,X),params:[X],typings:["none"]}}))}mapInlineParam(T,{escapeString:_}){if(T===null)return"null";if(typeof T==="number"||typeof T==="boolean")return T.toString();if(typeof T==="string")return _(T);if(typeof T==="object"){let F=T.toString();if(F==="[object Object]")return _(JSON.stringify(T));return _(F)}throw new Error("Unexpected param value: "+T)}getSQL(){return this}as(T){if(T===void 0)return this;return new k.Aliased(this,T)}mapWith(T){return this.decoder=typeof T==="function"?{mapFromDriverValue:T}:T,this}inlineParams(){return this.shouldInlineParams=!0,this}if(T){return T?this:void 0}}class O1{constructor(T){this.value=T}static[H]="Name";brand;getSQL(){return new k([this])}}function h$(T){return typeof T==="object"&&T!==null&&"mapToDriverValue"in T&&typeof T.mapToDriverValue==="function"}var p$={mapFromDriverValue:(T)=>T},g$={mapToDriverValue:(T)=>T},IC={...p$,...g$};class Q_{constructor(T,_=g$){this.value=T,this.encoder=_}static[H]="Param";brand;getSQL(){return new k([this])}}function U(T,..._){let F=[];if(_.length>0||T.length>0&&T[0]!=="")F.push(new yT(T[0]));for(let[W,J]of _.entries())F.push(J,new yT(T[W+1]));return new k(F)}((T)=>{function _(){return new k([])}T.empty=_;function F(G){return new k(G)}T.fromList=F;function W(G){return new k([new yT(G)])}T.raw=W;function J(G,X){let O=[];for(let[M,Q]of G.entries()){if(M>0&&X!==void 0)O.push(X);O.push(Q)}return new k(O)}T.join=J;function Y(G){return new O1(G)}T.identifier=Y;function $(G){return new E0(G)}T.placeholder=$;function Z(G,X){return new Q_(G,X)}T.param=Z})(U||(U={}));((T)=>{class _{constructor(F,W){this.sql=F,this.fieldAlias=W}static[H]="SQL.Aliased";isSelectionField=!1;getSQL(){return this.sql}clone(){return new _(this.sql,this.fieldAlias)}}T.Aliased=_})(k||(k={}));class E0{constructor(T){this.name=T}static[H]="Placeholder";getSQL(){return new k([this])}}function b4(T,_){return T.map((F)=>{if(R(F,E0)){if(!(F.name in _))throw new Error(`No value for placeholder "${F.name}" was provided`);return _[F.name]}if(R(F,Q_)&&R(F.value,E0)){if(!(F.value.name in _))throw new Error(`No value for placeholder "${F.value.name}" was provided`);return F.encoder.mapToDriverValue(_[F.value.name])}return F})}var W3=Symbol.for("drizzle:IsDrizzleView");class Z_{static[H]="View";[MT];[W3]=!0;constructor({name:T,schema:_,selectedFields:F,query:W}){this[MT]={name:T,originalName:T,schema:_,selectedFields:F,query:W,isExisting:!W,isAlias:!1}}getSQL(){return new k([this])}}GT.prototype.getSQL=function(){return new k([this])};I.prototype.getSQL=function(){return new k([this])};IT.prototype.getSQL=function(){return new k([this])};class XF{constructor(T){this.table=T}static[H]="ColumnAliasProxyHandler";get(T,_){if(_==="table")return this.table;return T[_]}}class YW{constructor(T,_){this.alias=T,this.replaceOriginalName=_}static[H]="TableAliasProxyHandler";get(T,_){if(_===I.Symbol.IsAlias)return!0;if(_===I.Symbol.Name)return this.alias;if(this.replaceOriginalName&&_===I.Symbol.OriginalName)return this.alias;if(_===MT)return{...T[MT],name:this.alias,isAlias:!0};if(_===I.Symbol.Columns){let W=T[I.Symbol.Columns];if(!W)return W;let J={};return Object.keys(W).map((Y)=>{J[Y]=new Proxy(W[Y],new XF(new Proxy(T,this)))}),J}let F=T[_];if(R(F,GT))return new Proxy(F,new XF(new Proxy(T,this)));return F}}function U1(T,_){return new Proxy(T,new YW(_,!1))}function o_(T,_){return new Proxy(T,new XF(new Proxy(T.table,new YW(_,!1))))}function h4(T,_){return new k.Aliased($W(T.sql,_),T.fieldAlias)}function $W(T,_){return U.join(T.queryChunks.map((F)=>{if(R(F,GT))return o_(F,_);if(R(F,k))return $W(F,_);if(R(F,k.Aliased))return h4(F,_);return F}))}class M1 extends Error{static[H]="DrizzleError";constructor({message:T,cause:_}){super(T);this.name="DrizzleError",this.cause=_}}class p4 extends M1{static[H]="TransactionRollbackError";constructor(){super({message:"Rollback"})}}class m${static[H]="ConsoleLogWriter";write(T){console.log(T)}}class g4{static[H]="DefaultLogger";writer;constructor(T){this.writer=T?.writer??new m$}logQuery(T,_){let F=_.map((J)=>{try{return JSON.stringify(J)}catch{return String(J)}}),W=F.length?` -- params: [${F.join(", ")}]`:"";this.writer.write(`Query: ${T}${W}`)}}class m4{static[H]="NoopLogger";logQuery(){}}class sT{static[H]="QueryPromise";[Symbol.toStringTag]="QueryPromise";catch(T){return this.then(void 0,T)}finally(T){return this.then((_)=>{return T?.(),_},(_)=>{throw T?.(),_})}then(T,_){return this.execute().then(T,_)}}function o$(T,_,F){let W={},J=T.reduce((Y,{path:$,field:Z},G)=>{let X;if(R(Z,GT))X=Z;else if(R(Z,k))X=Z.decoder;else X=Z.sql.decoder;let O=Y;for(let[M,Q]of $.entries())if(M<$.length-1){if(!(Q in O))O[Q]={};O=O[Q]}else{let K=_[G],B=O[Q]=K===null?null:X.mapFromDriverValue(K);if(F&&R(Z,GT)&&$.length===2){let V=$[0];if(!(V in W))W[V]=B===null?xT(Z.table):!1;else if(typeof W[V]==="string"&&W[V]!==xT(Z.table))W[V]=!1}}return Y},{});if(F&&Object.keys(W).length>0){for(let[Y,$]of Object.entries(W))if(typeof $==="string"&&!F[$])J[Y]=null}return J}function L_(T,_){return Object.entries(T).reduce((F,[W,J])=>{if(typeof W!=="string")return F;let Y=_?[..._,W]:[W];if(R(J,GT)||R(J,k)||R(J,k.Aliased))F.push({path:Y,field:J});else if(R(J,I))F.push(...L_(J[I.Symbol.Columns],Y));else F.push(...L_(J,Y));return F},[])}function ZW(T,_){let F=Object.keys(T),W=Object.keys(_);if(F.length!==W.length)return!1;for(let[J,Y]of F.entries())if(Y!==W[J])return!1;return!0}function w1(T,_){let F=Object.entries(_).filter(([,W])=>W!==void 0).map(([W,J])=>{if(R(J,k)||R(J,GT))return[W,J];else return[W,new Q_(J,T[I.Symbol.Columns][W])]});if(F.length===0)throw new Error("No values to set");return Object.fromEntries(F)}function u$(T,_){for(let F of _)for(let W of Object.getOwnPropertyNames(F.prototype)){if(W==="constructor")continue;Object.defineProperty(T.prototype,W,Object.getOwnPropertyDescriptor(F.prototype,W)||Object.create(null))}}function c$(T){return T[I.Symbol.Columns]}function e_(T){return R(T,IT)?T._.alias:R(T,Z_)?T[MT].name:R(T,k)?void 0:T[I.Symbol.IsAlias]?T[I.Symbol.Name]:T[I.Symbol.BaseName]}function a(T,_){return{name:typeof T==="string"&&T.length>0?T:"",config:typeof T==="object"?T:_}}function d$(T){if(typeof T!=="object"||T===null)return!1;if(T.constructor.name!=="Object")return!1;if("logger"in T){let _=typeof T.logger;if(_!=="boolean"&&(_!=="object"||typeof T.logger.logQuery!=="function")&&_!=="undefined")return!1;return!0}if("schema"in T){let _=typeof T.schema;if(_!=="object"&&_!=="undefined")return!1;return!0}if("casing"in T){let _=typeof T.casing;if(_!=="string"&&_!=="undefined")return!1;return!0}if("mode"in T){if(T.mode!=="default"||T.mode!=="planetscale"||T.mode!==void 0)return!1;return!0}if("connection"in T){let _=typeof T.connection;if(_!=="string"&&_!=="object"&&_!=="undefined")return!1;return!0}if("client"in T){let _=typeof T.client;if(_!=="object"&&_!=="function"&&_!=="undefined")return!1;return!0}if(Object.keys(T).length===0)return!0;return!1}class z0 extends f{static[H]="PgIntColumnBaseBuilder";generatedAlwaysAsIdentity(T){if(T){let{name:_,...F}=T;this.config.generatedIdentity={type:"always",sequenceName:_,sequenceOptions:F}}else this.config.generatedIdentity={type:"always"};return this.config.hasDefault=!0,this.config.notNull=!0,this}generatedByDefaultAsIdentity(T){if(T){let{name:_,...F}=T;this.config.generatedIdentity={type:"byDefault",sequenceName:_,sequenceOptions:F}}else this.config.generatedIdentity={type:"byDefault"};return this.config.hasDefault=!0,this.config.notNull=!0,this}}class l$ extends z0{static[H]="PgBigInt53Builder";constructor(T){super(T,"number","PgBigInt53")}build(T){return new t$(T,this.config)}}class t$ extends S{static[H]="PgBigInt53";getSQLType(){return"bigint"}mapFromDriverValue(T){if(typeof T==="number")return T;return Number(T)}}class i$ extends z0{static[H]="PgBigInt64Builder";constructor(T){super(T,"bigint","PgBigInt64")}build(T){return new n$(T,this.config)}}class n$ extends S{static[H]="PgBigInt64";getSQLType(){return"bigint"}mapFromDriverValue(T){return BigInt(T)}}function r$(T,_){let{name:F,config:W}=a(T,_);if(W.mode==="number")return new l$(F);return new i$(F)}class s$ extends f{static[H]="PgBigSerial53Builder";constructor(T){super(T,"number","PgBigSerial53");this.config.hasDefault=!0,this.config.notNull=!0}build(T){return new a$(T,this.config)}}class a$ extends S{static[H]="PgBigSerial53";getSQLType(){return"bigserial"}mapFromDriverValue(T){if(typeof T==="number")return T;return Number(T)}}class e$ extends f{static[H]="PgBigSerial64Builder";constructor(T){super(T,"bigint","PgBigSerial64");this.config.hasDefault=!0}build(T){return new TZ(T,this.config)}}class TZ extends S{static[H]="PgBigSerial64";getSQLType(){return"bigserial"}mapFromDriverValue(T){return BigInt(T)}}function _Z(T,_){let{name:F,config:W}=a(T,_);if(W.mode==="number")return new s$(F);return new e$(F)}class FZ extends f{static[H]="PgBooleanBuilder";constructor(T){super(T,"boolean","PgBoolean")}build(T){return new WZ(T,this.config)}}class WZ extends S{static[H]="PgBoolean";getSQLType(){return"boolean"}}function XW(T){return new FZ(T??"")}class JZ extends f{static[H]="PgCharBuilder";constructor(T,_){super(T,"string","PgChar");this.config.length=_.length,this.config.enumValues=_.enum}build(T){return new YZ(T,this.config)}}class YZ extends S{static[H]="PgChar";length=this.config.length;enumValues=this.config.enumValues;getSQLType(){return this.length===void 0?"char":`char(${this.length})`}}function $Z(T,_={}){let{name:F,config:W}=a(T,_);return new JZ(F,W)}class ZZ extends f{static[H]="PgCidrBuilder";constructor(T){super(T,"string","PgCidr")}build(T){return new XZ(T,this.config)}}class XZ extends S{static[H]="PgCidr";getSQLType(){return"cidr"}}function GZ(T){return new ZZ(T??"")}class AZ extends f{static[H]="PgCustomColumnBuilder";constructor(T,_,F){super(T,"custom","PgCustomColumn");this.config.fieldConfig=_,this.config.customTypeParams=F}build(T){return new HZ(T,this.config)}}class HZ extends S{static[H]="PgCustomColumn";sqlName;mapTo;mapFrom;constructor(T,_){super(T,_);this.sqlName=_.customTypeParams.dataType(_.fieldConfig),this.mapTo=_.customTypeParams.toDriver,this.mapFrom=_.customTypeParams.fromDriver}getSQLType(){return this.sqlName}mapFromDriverValue(T){return typeof this.mapFrom==="function"?this.mapFrom(T):T}mapToDriverValue(T){return typeof this.mapTo==="function"?this.mapTo(T):T}}function OZ(T){return(_,F)=>{let{name:W,config:J}=a(_,F);return new AZ(W,J,T)}}class T0 extends f{static[H]="PgDateColumnBaseBuilder";defaultNow(){return this.default(U`now()`)}}class UZ extends T0{static[H]="PgDateBuilder";constructor(T){super(T,"date","PgDate")}build(T){return new Q1(T,this.config)}}class Q1 extends S{static[H]="PgDate";getSQLType(){return"date"}mapFromDriverValue(T){return new Date(T)}mapToDriverValue(T){return T.toISOString()}}class MZ extends T0{static[H]="PgDateStringBuilder";constructor(T){super(T,"string","PgDateString")}build(T){return new R1(T,this.config)}}class R1 extends S{static[H]="PgDateString";getSQLType(){return"date"}}function wZ(T,_){let{name:F,config:W}=a(T,_);if(W?.mode==="date")return new UZ(F);return new MZ(F)}class QZ extends f{static[H]="PgDoublePrecisionBuilder";constructor(T){super(T,"number","PgDoublePrecision")}build(T){return new RZ(T,this.config)}}class RZ extends S{static[H]="PgDoublePrecision";getSQLType(){return"double precision"}mapFromDriverValue(T){if(typeof T==="string")return Number.parseFloat(T);return T}}function EZ(T){return new QZ(T??"")}class zZ extends f{static[H]="PgInetBuilder";constructor(T){super(T,"string","PgInet")}build(T){return new VZ(T,this.config)}}class VZ extends S{static[H]="PgInet";getSQLType(){return"inet"}}function KZ(T){return new zZ(T??"")}class LZ extends z0{static[H]="PgIntegerBuilder";constructor(T){super(T,"number","PgInteger")}build(T){return new DZ(T,this.config)}}class DZ extends S{static[H]="PgInteger";getSQLType(){return"integer"}mapFromDriverValue(T){if(typeof T==="string")return Number.parseInt(T);return T}}function GW(T){return new LZ(T??"")}class SZ extends f{static[H]="PgIntervalBuilder";constructor(T,_){super(T,"string","PgInterval");this.config.intervalConfig=_}build(T){return new IZ(T,this.config)}}class IZ extends S{static[H]="PgInterval";fields=this.config.intervalConfig.fields;precision=this.config.intervalConfig.precision;getSQLType(){let T=this.fields?` ${this.fields}`:"",_=this.precision?`(${this.precision})`:"";return`interval${T}${_}`}}function NZ(T,_={}){let{name:F,config:W}=a(T,_);return new SZ(F,W)}class CZ extends f{static[H]="PgJsonBuilder";constructor(T){super(T,"json","PgJson")}build(T){return new E1(T,this.config)}}class E1 extends S{static[H]="PgJson";constructor(T,_){super(T,_)}getSQLType(){return"json"}mapToDriverValue(T){return JSON.stringify(T)}mapFromDriverValue(T){if(typeof T==="string")try{return JSON.parse(T)}catch{return T}return T}}function BZ(T){return new CZ(T??"")}class kZ extends f{static[H]="PgJsonbBuilder";constructor(T){super(T,"json","PgJsonb")}build(T){return new z1(T,this.config)}}class z1 extends S{static[H]="PgJsonb";constructor(T,_){super(T,_)}getSQLType(){return"jsonb"}mapToDriverValue(T){return JSON.stringify(T)}mapFromDriverValue(T){if(typeof T==="string")try{return JSON.parse(T)}catch{return T}return T}}function fZ(T){return new kZ(T??"")}class PZ extends f{static[H]="PgLineBuilder";constructor(T){super(T,"array","PgLine")}build(T){return new qZ(T,this.config)}}class qZ extends S{static[H]="PgLine";getSQLType(){return"line"}mapFromDriverValue(T){let[_,F,W]=T.slice(1,-1).split(",");return[Number.parseFloat(_),Number.parseFloat(F),Number.parseFloat(W)]}mapToDriverValue(T){return`{${T[0]},${T[1]},${T[2]}}`}}class jZ extends f{static[H]="PgLineABCBuilder";constructor(T){super(T,"json","PgLineABC")}build(T){return new yZ(T,this.config)}}class yZ extends S{static[H]="PgLineABC";getSQLType(){return"line"}mapFromDriverValue(T){let[_,F,W]=T.slice(1,-1).split(",");return{a:Number.parseFloat(_),b:Number.parseFloat(F),c:Number.parseFloat(W)}}mapToDriverValue(T){return`{${T.a},${T.b},${T.c}}`}}function vZ(T,_){let{name:F,config:W}=a(T,_);if(!W?.mode||W.mode==="tuple")return new PZ(F);return new jZ(F)}class xZ extends f{static[H]="PgMacaddrBuilder";constructor(T){super(T,"string","PgMacaddr")}build(T){return new bZ(T,this.config)}}class bZ extends S{static[H]="PgMacaddr";getSQLType(){return"macaddr"}}function hZ(T){return new xZ(T??"")}class pZ extends f{static[H]="PgMacaddr8Builder";constructor(T){super(T,"string","PgMacaddr8")}build(T){return new gZ(T,this.config)}}class gZ extends S{static[H]="PgMacaddr8";getSQLType(){return"macaddr8"}}function mZ(T){return new pZ(T??"")}class oZ extends f{static[H]="PgNumericBuilder";constructor(T,_,F){super(T,"string","PgNumeric");this.config.precision=_,this.config.scale=F}build(T){return new V1(T,this.config)}}class V1 extends S{static[H]="PgNumeric";precision;scale;constructor(T,_){super(T,_);this.precision=_.precision,this.scale=_.scale}mapFromDriverValue(T){if(typeof T==="string")return T;return String(T)}getSQLType(){if(this.precision!==void 0&&this.scale!==void 0)return`numeric(${this.precision}, ${this.scale})`;else if(this.precision===void 0)return"numeric";else return`numeric(${this.precision})`}}class uZ extends f{static[H]="PgNumericNumberBuilder";constructor(T,_,F){super(T,"number","PgNumericNumber");this.config.precision=_,this.config.scale=F}build(T){return new cZ(T,this.config)}}class cZ extends S{static[H]="PgNumericNumber";precision;scale;constructor(T,_){super(T,_);this.precision=_.precision,this.scale=_.scale}mapFromDriverValue(T){if(typeof T==="number")return T;return Number(T)}mapToDriverValue=String;getSQLType(){if(this.precision!==void 0&&this.scale!==void 0)return`numeric(${this.precision}, ${this.scale})`;else if(this.precision===void 0)return"numeric";else return`numeric(${this.precision})`}}class dZ extends f{static[H]="PgNumericBigIntBuilder";constructor(T,_,F){super(T,"bigint","PgNumericBigInt");this.config.precision=_,this.config.scale=F}build(T){return new lZ(T,this.config)}}class lZ extends S{static[H]="PgNumericBigInt";precision;scale;constructor(T,_){super(T,_);this.precision=_.precision,this.scale=_.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 tZ(T,_){let{name:F,config:W}=a(T,_),J=W?.mode;return J==="number"?new uZ(F,W?.precision,W?.scale):J==="bigint"?new dZ(F,W?.precision,W?.scale):new oZ(F,W?.precision,W?.scale)}class iZ extends f{static[H]="PgPointTupleBuilder";constructor(T){super(T,"array","PgPointTuple")}build(T){return new nZ(T,this.config)}}class nZ extends S{static[H]="PgPointTuple";getSQLType(){return"point"}mapFromDriverValue(T){if(typeof T==="string"){let[_,F]=T.slice(1,-1).split(",");return[Number.parseFloat(_),Number.parseFloat(F)]}return[T.x,T.y]}mapToDriverValue(T){return`(${T[0]},${T[1]})`}}class rZ extends f{static[H]="PgPointObjectBuilder";constructor(T){super(T,"json","PgPointObject")}build(T){return new sZ(T,this.config)}}class sZ extends S{static[H]="PgPointObject";getSQLType(){return"point"}mapFromDriverValue(T){if(typeof T==="string"){let[_,F]=T.slice(1,-1).split(",");return{x:Number.parseFloat(_),y:Number.parseFloat(F)}}return T}mapToDriverValue(T){return`(${T.x},${T.y})`}}function aZ(T,_){let{name:F,config:W}=a(T,_);if(!W?.mode||W.mode==="tuple")return new iZ(F);return new rZ(F)}function J3(T){let _=[];for(let F=0;F<T.length;F+=2)_.push(Number.parseInt(T.slice(F,F+2),16));return new Uint8Array(_)}function eZ(T,_){let F=new ArrayBuffer(8),W=new DataView(F);for(let J=0;J<8;J++)W.setUint8(J,T[_+J]);return W.getFloat64(0,!0)}function o4(T){let _=J3(T),F=0,W=_[F];F+=1;let J=new DataView(_.buffer),Y=J.getUint32(F,W===1);F+=4;let $;if(Y&536870912)$=J.getUint32(F,W===1),F+=4;if((Y&65535)===1){let Z=eZ(_,F);F+=8;let G=eZ(_,F);return F+=8,[Z,G]}throw new Error("Unsupported geometry type")}class TX extends f{static[H]="PgGeometryBuilder";constructor(T){super(T,"array","PgGeometry")}build(T){return new _X(T,this.config)}}class _X extends S{static[H]="PgGeometry";getSQLType(){return"geometry(point)"}mapFromDriverValue(T){return o4(T)}mapToDriverValue(T){return`point(${T[0]} ${T[1]})`}}class FX extends f{static[H]="PgGeometryObjectBuilder";constructor(T){super(T,"json","PgGeometryObject")}build(T){return new WX(T,this.config)}}class WX extends S{static[H]="PgGeometryObject";getSQLType(){return"geometry(point)"}mapFromDriverValue(T){let _=o4(T);return{x:_[0],y:_[1]}}mapToDriverValue(T){return`point(${T.x} ${T.y})`}}function JX(T,_){let{name:F,config:W}=a(T,_);if(!W?.mode||W.mode==="tuple")return new TX(F);return new FX(F)}class YX extends f{static[H]="PgRealBuilder";constructor(T,_){super(T,"number","PgReal");this.config.length=_}build(T){return new $X(T,this.config)}}class $X extends S{static[H]="PgReal";constructor(T,_){super(T,_)}getSQLType(){return"real"}mapFromDriverValue=(T)=>{if(typeof T==="string")return Number.parseFloat(T);return T}}function ZX(T){return new YX(T??"")}class XX extends f{static[H]="PgSerialBuilder";constructor(T){super(T,"number","PgSerial");this.config.hasDefault=!0,this.config.notNull=!0}build(T){return new GX(T,this.config)}}class GX extends S{static[H]="PgSerial";getSQLType(){return"serial"}}function AX(T){return new XX(T??"")}class HX extends z0{static[H]="PgSmallIntBuilder";constructor(T){super(T,"number","PgSmallInt")}build(T){return new OX(T,this.config)}}class OX extends S{static[H]="PgSmallInt";getSQLType(){return"smallint"}mapFromDriverValue=(T)=>{if(typeof T==="string")return Number(T);return T}}function UX(T){return new HX(T??"")}class MX extends f{static[H]="PgSmallSerialBuilder";constructor(T){super(T,"number","PgSmallSerial");this.config.hasDefault=!0,this.config.notNull=!0}build(T){return new wX(T,this.config)}}class wX extends S{static[H]="PgSmallSerial";getSQLType(){return"smallserial"}}function QX(T){return new MX(T??"")}class RX extends f{static[H]="PgTextBuilder";constructor(T,_){super(T,"string","PgText");this.config.enumValues=_.enum}build(T){return new EX(T,this.config)}}class EX extends S{static[H]="PgText";enumValues=this.config.enumValues;getSQLType(){return"text"}}function zX(T,_={}){let{name:F,config:W}=a(T,_);return new RX(F,W)}class VX extends T0{constructor(T,_,F){super(T,"string","PgTime");this.withTimezone=_,this.precision=F,this.config.withTimezone=_,this.config.precision=F}static[H]="PgTimeBuilder";build(T){return new K1(T,this.config)}}class K1 extends S{static[H]="PgTime";withTimezone;precision;constructor(T,_){super(T,_);this.withTimezone=_.withTimezone,this.precision=_.precision}getSQLType(){return`time${this.precision===void 0?"":`(${this.precision})`}${this.withTimezone?" with time zone":""}`}}function KX(T,_={}){let{name:F,config:W}=a(T,_);return new VX(F,W.withTimezone??!1,W.precision)}class LX extends T0{static[H]="PgTimestampBuilder";constructor(T,_,F){super(T,"date","PgTimestamp");this.config.withTimezone=_,this.config.precision=F}build(T){return new L1(T,this.config)}}class L1 extends S{static[H]="PgTimestamp";withTimezone;precision;constructor(T,_){super(T,_);this.withTimezone=_.withTimezone,this.precision=_.precision}getSQLType(){return`timestamp${this.precision===void 0?"":` (${this.precision})`}${this.withTimezone?" with time zone":""}`}mapFromDriverValue=(T)=>{return new Date(this.withTimezone?T:T+"+0000")};mapToDriverValue=(T)=>{return T.toISOString()}}class DX extends T0{static[H]="PgTimestampStringBuilder";constructor(T,_,F){super(T,"string","PgTimestampString");this.config.withTimezone=_,this.config.precision=F}build(T){return new D1(T,this.config)}}class D1 extends S{static[H]="PgTimestampString";withTimezone;precision;constructor(T,_){super(T,_);this.withTimezone=_.withTimezone,this.precision=_.precision}getSQLType(){return`timestamp${this.precision===void 0?"":`(${this.precision})`}${this.withTimezone?" with time zone":""}`}}function y_(T,_={}){let{name:F,config:W}=a(T,_);if(W?.mode==="string")return new DX(F,W.withTimezone??!1,W.precision);return new LX(F,W?.withTimezone??!1,W?.precision)}class SX extends f{static[H]="PgUUIDBuilder";constructor(T){super(T,"string","PgUUID")}defaultRandom(){return this.default(U`gen_random_uuid()`)}build(T){return new S1(T,this.config)}}class S1 extends S{static[H]="PgUUID";getSQLType(){return"uuid"}}function D_(T){return new SX(T??"")}class IX extends f{static[H]="PgVarcharBuilder";constructor(T,_){super(T,"string","PgVarchar");this.config.length=_.length,this.config.enumValues=_.enum}build(T){return new NX(T,this.config)}}class NX extends S{static[H]="PgVarchar";length=this.config.length;enumValues=this.config.enumValues;getSQLType(){return this.length===void 0?"varchar":`varchar(${this.length})`}}function aT(T,_={}){let{name:F,config:W}=a(T,_);return new IX(F,W)}class CX extends f{static[H]="PgBinaryVectorBuilder";constructor(T,_){super(T,"string","PgBinaryVector");this.config.dimensions=_.dimensions}build(T){return new BX(T,this.config)}}class BX extends S{static[H]="PgBinaryVector";dimensions=this.config.dimensions;getSQLType(){return`bit(${this.dimensions})`}}function kX(T,_){let{name:F,config:W}=a(T,_);return new CX(F,W)}class fX extends f{static[H]="PgHalfVectorBuilder";constructor(T,_){super(T,"array","PgHalfVector");this.config.dimensions=_.dimensions}build(T){return new PX(T,this.config)}}class PX extends S{static[H]="PgHalfVector";dimensions=this.config.dimensions;getSQLType(){return`halfvec(${this.dimensions})`}mapToDriverValue(T){return JSON.stringify(T)}mapFromDriverValue(T){return T.slice(1,-1).split(",").map((_)=>Number.parseFloat(_))}}function qX(T,_){let{name:F,config:W}=a(T,_);return new fX(F,W)}class jX extends f{static[H]="PgSparseVectorBuilder";constructor(T,_){super(T,"string","PgSparseVector");this.config.dimensions=_.dimensions}build(T){return new yX(T,this.config)}}class yX extends S{static[H]="PgSparseVector";dimensions=this.config.dimensions;getSQLType(){return`sparsevec(${this.dimensions})`}}function vX(T,_){let{name:F,config:W}=a(T,_);return new jX(F,W)}class xX extends f{static[H]="PgVectorBuilder";constructor(T,_){super(T,"array","PgVector");this.config.dimensions=_.dimensions}build(T){return new bX(T,this.config)}}class bX extends S{static[H]="PgVector";dimensions=this.config.dimensions;getSQLType(){return`vector(${this.dimensions})`}mapToDriverValue(T){return JSON.stringify(T)}mapFromDriverValue(T){return T.slice(1,-1).split(",").map((_)=>Number.parseFloat(_))}}function hX(T,_){let{name:F,config:W}=a(T,_);return new xX(F,W)}function pX(){return{bigint:r$,bigserial:_Z,boolean:XW,char:$Z,cidr:GZ,customType:OZ,date:wZ,doublePrecision:EZ,inet:KZ,integer:GW,interval:NZ,json:BZ,jsonb:fZ,line:vZ,macaddr:hZ,macaddr8:mZ,numeric:tZ,point:aZ,geometry:JX,real:ZX,serial:AX,smallint:UX,smallserial:QX,text:zX,time:KX,timestamp:y_,uuid:D_,varchar:aT,bit:kX,halfvec:qX,sparsevec:vX,vector:hX}}var u4=Symbol.for("drizzle:PgInlineForeignKeys"),gX=Symbol.for("drizzle:EnableRLS");class vT extends I{static[H]="PgTable";static Symbol=Object.assign({},I.Symbol,{InlineForeignKeys:u4,EnableRLS:gX});[u4]=[];[gX]=!1;[I.Symbol.ExtraConfigBuilder]=void 0;[I.Symbol.ExtraConfigColumns]={}}function Y3(T,_,F,W,J=T){let Y=new vT(T,W,J),$=typeof _==="function"?_(pX()):_,Z=Object.fromEntries(Object.entries($).map(([O,M])=>{let Q=M;Q.setName(O);let K=Q.build(Y);return Y[u4].push(...Q.buildForeignKeys(K,Y)),[O,K]})),G=Object.fromEntries(Object.entries($).map(([O,M])=>{let Q=M;Q.setName(O);let K=Q.buildExtraConfigColumn(Y);return[O,K]})),X=Object.assign(Y,Z);if(X[I.Symbol.Columns]=Z,X[I.Symbol.ExtraConfigColumns]=G,F)X[vT.Symbol.ExtraConfigBuilder]=F;return Object.assign(X,{enableRLS:()=>{return X[vT.Symbol.EnableRLS]=!0,X}})}var V0=(T,_,F)=>{return Y3(T,_,F,void 0)};function mX(...T){if(T[0].columns)return new AW(T[0].columns,T[0].name);return new AW(T)}class AW{static[H]="PgPrimaryKeyBuilder";columns;name;constructor(T,_){this.columns=T,this.name=_}build(T){return new oX(T,this.columns,this.name)}}class oX{constructor(T,_,F){this.table=T,this.columns=_,this.name=F}static[H]="PgPrimaryKey";columns;name;getName(){return this.name??`${this.table[vT.Symbol.Name]}_${this.columns.map((T)=>T.name).join("_")}_pk`}}function X_(T,_){if(h$(_)&&!x4(T)&&!R(T,Q_)&&!R(T,E0)&&!R(T,GT)&&!R(T,I)&&!R(T,Z_))return new Q_(T,_);return T}var I1=(T,_)=>{return U`${T} = ${X_(_,T)}`},uX=(T,_)=>{return U`${T} <> ${X_(_,T)}`};function HW(...T){let _=T.filter((F)=>F!==void 0);if(_.length===0)return;if(_.length===1)return new k(_);return new k([new yT("("),U.join(_,new yT(" and ")),new yT(")")])}function cX(...T){let _=T.filter((F)=>F!==void 0);if(_.length===0)return;if(_.length===1)return new k(_);return new k([new yT("("),U.join(_,new yT(" or ")),new yT(")")])}function dX(T){return U`not ${T}`}var lX=(T,_)=>{return U`${T} > ${X_(_,T)}`},tX=(T,_)=>{return U`${T} >= ${X_(_,T)}`},iX=(T,_)=>{return U`${T} < ${X_(_,T)}`},nX=(T,_)=>{return U`${T} <= ${X_(_,T)}`};function rX(T,_){if(Array.isArray(_)){if(_.length===0)return U`false`;return U`${T} in ${_.map((F)=>X_(F,T))}`}return U`${T} in ${X_(_,T)}`}function sX(T,_){if(Array.isArray(_)){if(_.length===0)return U`true`;return U`${T} not in ${_.map((F)=>X_(F,T))}`}return U`${T} not in ${X_(_,T)}`}function aX(T){return U`${T} is null`}function eX(T){return U`${T} is not null`}function T5(T){return U`exists ${T}`}function _5(T){return U`not exists ${T}`}function F5(T,_,F){return U`${T} between ${X_(_,T)} and ${X_(F,T)}`}function W5(T,_,F){return U`${T} not between ${X_(_,T)} and ${X_(F,T)}`}function J5(T,_){return U`${T} like ${_}`}function Y5(T,_){return U`${T} not like ${_}`}function $5(T,_){return U`${T} ilike ${_}`}function Z5(T,_){return U`${T} not ilike ${_}`}function X5(T){return U`${T} asc`}function G5(T){return U`${T} desc`}class c4{constructor(T,_,F){this.sourceTable=T,this.referencedTable=_,this.relationName=F,this.referencedTableName=_[I.Symbol.Name]}static[H]="Relation";referencedTableName;fieldName}class A5{constructor(T,_){this.table=T,this.config=_}static[H]="Relations"}class K0 extends c4{constructor(T,_,F,W){super(T,_,F?.relationName);this.config=F,this.isNullable=W}static[H]="One";withFieldName(T){let _=new K0(this.sourceTable,this.referencedTable,this.config,this.isNullable);return _.fieldName=T,_}}class OW extends c4{constructor(T,_,F){super(T,_,F?.relationName);this.config=F}static[H]="Many";withFieldName(T){let _=new OW(this.sourceTable,this.referencedTable,this.config);return _.fieldName=T,_}}function H5(){return{and:HW,between:F5,eq:I1,exists:T5,gt:lX,gte:tX,ilike:$5,inArray:rX,isNull:aX,isNotNull:eX,like:J5,lt:iX,lte:nX,ne:uX,not:dX,notBetween:W5,notExists:_5,notLike:Y5,notIlike:Z5,notInArray:sX,or:cX,sql:U}}function O5(){return{sql:U,asc:X5,desc:G5}}function U5(T,_){if(Object.keys(T).length===1&&"default"in T&&!R(T.default,I))T=T.default;let F={},W={},J={};for(let[Y,$]of Object.entries(T))if(R($,I)){let Z=f0($),G=W[Z];F[Z]=Y,J[Y]={tsName:Y,dbName:$[I.Symbol.Name],schema:$[I.Symbol.Schema],columns:$[I.Symbol.Columns],relations:G?.relations??{},primaryKey:G?.primaryKey??[]};for(let O of Object.values($[I.Symbol.Columns]))if(O.primary)J[Y].primaryKey.push(O);let X=$[I.Symbol.ExtraConfigBuilder]?.($[I.Symbol.ExtraConfigColumns]);if(X){for(let O of Object.values(X))if(R(O,AW))J[Y].primaryKey.push(...O.columns)}}else if(R($,A5)){let Z=f0($.table),G=F[Z],X=$.config(_($.table)),O;for(let[M,Q]of Object.entries(X))if(G){let K=J[G];if(K.relations[M]=Q,O)K.primaryKey.push(...O)}else{if(!(Z in W))W[Z]={relations:{},primaryKey:O};W[Z].relations[M]=Q}}return{tables:J,tableNamesMap:F}}function $3(T){return function _(F,W){return new K0(T,F,W,W?.fields.reduce((J,Y)=>J&&Y.notNull,!0)??!1)}}function Z3(T){return function _(F,W){return new OW(T,F,W)}}function M5(T,_,F){if(R(F,K0)&&F.config)return{fields:F.config.fields,references:F.config.references};let W=_[f0(F.referencedTable)];if(!W)throw new Error(`Table "${F.referencedTable[I.Symbol.Name]}" not found in schema`);let J=T[W];if(!J)throw new Error(`Table "${W}" not found in schema`);let Y=F.sourceTable,$=_[f0(Y)];if(!$)throw new Error(`Table "${Y[I.Symbol.Name]}" not found in schema`);let Z=[];for(let G of Object.values(J.relations))if(F.relationName&&F!==G&&G.relationName===F.relationName||!F.relationName&&G.referencedTable===F.sourceTable)Z.push(G);if(Z.length>1)throw F.relationName?new Error(`There are multiple relations with name "${F.relationName}" in table "${W}"`):new Error(`There are multiple relations between "${W}" and "${F.sourceTable[I.Symbol.Name]}". Please specify relation name`);if(Z[0]&&R(Z[0],K0)&&Z[0].config)return{fields:Z[0].config.references,references:Z[0].config.fields};throw new Error(`There is not enough information to infer relation "${$}.${F.fieldName}"`)}function w5(T){return{one:$3(T),many:Z3(T)}}function N1(T,_,F,W,J=(Y)=>Y){let Y={};for(let[$,Z]of W.entries())if(Z.isJson){let G=_.relations[Z.tsKey],X=F[$],O=typeof X==="string"?JSON.parse(X):X;Y[Z.tsKey]=R(G,K0)?O&&N1(T,T[Z.relationTableTsKey],O,Z.selection,J):O.map((M)=>N1(T,T[Z.relationTableTsKey],M,Z.selection,J))}else{let G=J(F[$]),X=Z.field,O;if(R(X,GT))O=X;else if(R(X,k))O=X.decoder;else O=X.sql.decoder;Y[Z.tsKey]=G===null?null:O.mapFromDriverValue(G)}return Y}import P3 from"os";import q3 from"fs";var C1=new Map,d4=new Map,l4=Symbol("OriginError"),GF={};class S_ extends Promise{constructor(T,_,F,W,J={}){let Y,$;super((Z,G)=>{Y=Z,$=G});this.tagged=Array.isArray(T.raw),this.strings=T,this.args=_,this.handler=F,this.canceller=W,this.options=J,this.state=null,this.statement=null,this.resolve=(Z)=>(this.active=!1,Y(Z)),this.reject=(Z)=>(this.active=!1,$(Z)),this.active=!1,this.cancelled=null,this.executed=!1,this.signature="",this[l4]=this.handler.debug?new Error:this.tagged&&X3(this.strings)}get origin(){return(this.handler.debug?this[l4].stack:this.tagged&&d4.has(this.strings)?d4.get(this.strings):d4.set(this.strings,this[l4].stack).get(this.strings))||""}static get[Symbol.species](){return Promise}cancel(){return this.canceller&&(this.canceller(this),this.canceller=null)}simple(){return this.options.simple=!0,this.options.prepare=!1,this}async readable(){return this.simple(),this.streaming=!0,this}async writable(){return this.simple(),this.streaming=!0,this}cursor(T=1,_){if(this.options.simple=!1,typeof T==="function")_=T,T=1;if(this.cursorRows=T,typeof _==="function")return this.cursorFn=_,this;let F;return{[Symbol.asyncIterator]:()=>({next:()=>{if(this.executed&&!this.active)return{done:!0};F&&F();let W=new Promise((J,Y)=>{this.cursorFn=($)=>{return J({value:$,done:!1}),new Promise((Z)=>F=Z)},this.resolve=()=>(this.active=!1,J({done:!0})),this.reject=($)=>(this.active=!1,Y($))});return this.execute(),W},return(){return F&&F(GF),{done:!0}}})}}describe(){return this.options.simple=!1,this.onlyDescribe=this.options.prepare=!0,this}stream(){throw new Error(".stream has been renamed to .forEach")}forEach(T){return this.forEachFn=T,this.handle(),this}raw(){return this.isRaw=!0,this}values(){return this.isRaw="values",this}async handle(){!this.executed&&(this.executed=!0)&&await 1&&this.handler(this)}execute(){return this.handle(),this}then(){return this.handle(),super.then.apply(this,arguments)}catch(){return this.handle(),super.catch.apply(this,arguments)}finally(){return this.handle(),super.finally.apply(this,arguments)}}function X3(T){if(C1.has(T))return C1.get(T);let _=Error.stackTraceLimit;return Error.stackTraceLimit=4,C1.set(T,new Error),Error.stackTraceLimit=_,C1.get(T)}class AF extends Error{constructor(T){super(T.message);this.name=this.constructor.name,Object.assign(this,T)}}var BT={connection:Q5,postgres:R5,generic:E5,notSupported:z5};function Q5(T,_,F){let{host:W,port:J}=F||_,Y=Object.assign(new Error("write "+T+" "+(_.path||W+":"+J)),{code:T,errno:T,address:_.path||W},_.path?{}:{port:J});return Error.captureStackTrace(Y,Q5),Y}function R5(T){let _=new AF(T);return Error.captureStackTrace(_,R5),_}function E5(T,_){let F=Object.assign(new Error(T+": "+_),{code:T});return Error.captureStackTrace(F,E5),F}function z5(T){let _=Object.assign(new Error(T+" (B) is not supported"),{code:"MESSAGE_NOT_SUPPORTED",name:T});return Error.captureStackTrace(_,z5),_}var G3={string:{to:25,from:null,serialize:(T)=>""+T},number:{to:0,from:[21,23,26,700,701],serialize:(T)=>""+T,parse:(T)=>+T},json:{to:114,from:[114,3802],serialize:(T)=>JSON.stringify(T),parse:(T)=>JSON.parse(T)},boolean:{to:16,from:16,serialize:(T)=>T===!0?"t":"f",parse:(T)=>T==="t"},date:{to:1184,from:[1082,1114,1184],serialize:(T)=>(T instanceof Date?T:new Date(T)).toISOString(),parse:(T)=>new Date(T)},bytea:{to:17,from:17,serialize:(T)=>"\\x"+Buffer.from(T).toString("hex"),parse:(T)=>Buffer.from(T.slice(2),"hex")}};class f1{then(){t4()}catch(){t4()}finally(){t4()}}class QW extends f1{constructor(T){super();this.value=j1(T)}}class u_ extends f1{constructor(T,_,F){super();this.value=T,this.type=_,this.array=F}}class P1 extends f1{constructor(T,_){super();this.first=T,this.rest=_}build(T,_,F,W){let J=A3.map(([Y,$])=>({fn:$,i:T.search(Y)})).sort((Y,$)=>Y.i-$.i).pop();return J.i===-1?a4(this.first,W):J.fn(this.first,this.rest,_,F,W)}}function q1(T,_,F,W){let J=T instanceof u_?T.value:T;if(J===void 0){if(T instanceof u_?T.value=W.transform.undefined:J=T=W.transform.undefined,J===void 0)throw BT.generic("UNDEFINED_VALUE","Undefined values are not allowed")}return"$"+F.push(T instanceof u_?(_.push(T.value),T.array?T.array[T.type||k1(T.value)]||T.type||D5(T.value):T.type):(_.push(T),k1(T)))}var K5=I5(G3);function r4(T,_,F,W,J,Y){for(let $=1;$<T.strings.length;$++)_+=s4(_,F,W,J,Y)+T.strings[$],F=T.args[$];return _}function s4(T,_,F,W,J){return _ instanceof P1?_.build(T,F,W,J):_ instanceof S_?n4(_,F,W,J):_ instanceof QW?_.value:_&&_[0]instanceof S_?_.reduce((Y,$)=>Y+" "+n4($,F,W,J),""):q1(_,F,W,J)}function n4(T,_,F,W){return T.fragment=!0,r4(T,T.strings[0],T.args[0],_,F,W)}function L5(T,_,F,W,J){return T.map((Y)=>"("+W.map(($)=>s4("values",Y[$],_,F,J)).join(",")+")").join(",")}function V5(T,_,F,W,J){let Y=Array.isArray(T[0]),$=_.length?_.flat():Object.keys(Y?T[0]:T);return L5(Y?T:[T],F,W,$,J)}function B1(T,_,F,W,J){if(typeof T==="string"&&(T=[T].concat(_)),Array.isArray(T))return a4(T,J);let Y;return(_.length?_.flat():Object.keys(T)).map((Z)=>{return Y=T[Z],(Y instanceof S_?n4(Y,F,W,J):Y instanceof QW?Y.value:q1(Y,F,W,J))+" as "+j1(J.transform.column.to?J.transform.column.to(Z):Z)}).join(",")}var A3=Object.entries({values:V5,in:(...T)=>{let _=V5(...T);return _==="()"?"(null)":_},select:B1,as:B1,returning:B1,"\\(":B1,update(T,_,F,W,J){return(_.length?_.flat():Object.keys(T)).map((Y)=>j1(J.transform.column.to?J.transform.column.to(Y):Y)+"="+s4("values",T[Y],F,W,J))},insert(T,_,F,W,J){let Y=_.length?_.flat():Object.keys(Array.isArray(T)?T[0]:T);return"("+a4(Y,J)+")values"+L5(Array.isArray(T)?T:[T],F,W,Y,J)}}).map(([T,_])=>[new RegExp("((?:^|[\\s(])"+T+"(?:$|[\\s(]))(?![\\s\\S]*\\1)","i"),_]);function t4(){throw BT.generic("NOT_TAGGED_CALL","Query not called as a tagged template literal")}var{serializers:H3,parsers:O3}=K5;function D5(T){if(Array.isArray(T))return D5(T[0]);return typeof T==="string"?1009:0}var S5=function(T){let _=I5(T||{});return{serializers:Object.assign({},H3,_.serializers),parsers:Object.assign({},O3,_.parsers)}};function I5(T){return Object.keys(T).reduce((_,F)=>{if(T[F].from&&[].concat(T[F].from).forEach((W)=>_.parsers[W]=T[F].parse),T[F].serialize)_.serializers[T[F].to]=T[F].serialize,T[F].from&&[].concat(T[F].from).forEach((W)=>_.serializers[W]=T[F].serialize);return _},{parsers:{},serializers:{}})}function a4(T,{transform:{column:_}}){return T.map((F)=>j1(_.to?_.to(F):F)).join(",")}var j1=function T(_){return'"'+_.replace(/"/g,'""').replace(/\./g,'"."')+'"'},k1=function T(_){return _ instanceof u_?_.type:_ instanceof Date?1184:_ instanceof Uint8Array?17:_===!0||_===!1?16:typeof _==="bigint"?20:Array.isArray(_)?T(_[0]):0},U3=/\\/g,M3=/"/g;function w3(T){return T.replace(U3,"\\\\").replace(M3,"\\\"")}var N5=function T(_,F,W,J){if(Array.isArray(_)===!1)return _;if(!_.length)return"{}";let Y=_[0],$=J===1020?";":",";if(Array.isArray(Y)&&!Y.type)return"{"+_.map((Z)=>T(Z,F,W,J)).join($)+"}";return"{"+_.map((Z)=>{if(Z===void 0){if(Z=W.transform.undefined,Z===void 0)throw BT.generic("UNDEFINED_VALUE","Undefined values are not allowed")}return Z===null?"null":'"'+w3(F?F(Z.type?Z.value:Z):""+Z)+'"'}).join($)+"}"},i4={i:0,char:null,str:"",quoted:!1,last:0},C5=function T(_,F,W){return i4.i=i4.last=0,B5(i4,_,F,W)};function B5(T,_,F,W){let J=[],Y=W===1020?";":",";for(;T.i<_.length;T.i++){if(T.char=_[T.i],T.quoted)if(T.char==="\\")T.str+=_[++T.i];else if(T.char==='"')J.push(F?F(T.str):T.str),T.str="",T.quoted=_[T.i+1]==='"',T.last=T.i+2;else T.str+=T.char;else if(T.char==='"')T.quoted=!0;else if(T.char==="{")T.last=++T.i,J.push(B5(T,_,F,W));else if(T.char==="}"){T.quoted=!1,T.last<T.i&&J.push(F?F(_.slice(T.last,T.i)):_.slice(T.last,T.i)),T.last=T.i+1;break}else if(T.char===Y&&T.p!=="}"&&T.p!=='"')J.push(F?F(_.slice(T.last,T.i)):_.slice(T.last,T.i)),T.last=T.i+1;T.p=T.char}return T.last<T.i&&J.push(F?F(_.slice(T.last,T.i+1)):_.slice(T.last,T.i+1)),J}var P0=(T)=>{let _=T[0];for(let F=1;F<T.length;F++)_+=T[F]==="_"?T[++F].toUpperCase():T[F];return _},q0=(T)=>{let _=T[0].toUpperCase();for(let F=1;F<T.length;F++)_+=T[F]==="_"?T[++F].toUpperCase():T[F];return _},j0=(T)=>T.replace(/_/g,"-"),UW=(T)=>T.replace(/([A-Z])/g,"_$1").toLowerCase(),MW=(T)=>(T.slice(0,1)+T.slice(1).replace(/([A-Z])/g,"_$1")).toLowerCase(),wW=(T)=>T.replace(/-/g,"_");function e4(T){return function _(F,W){return typeof F==="object"&&F!==null&&(W.type===114||W.type===3802)?Array.isArray(F)?F.map((J)=>_(J,W)):Object.entries(F).reduce((J,[Y,$])=>Object.assign(J,{[T(Y)]:_($,W)}),{}):F}}P0.column={from:P0};P0.value={from:e4(P0)};UW.column={to:UW};var T8={...P0};T8.column.to=UW;q0.column={from:q0};q0.value={from:e4(q0)};MW.column={to:MW};var _8={...q0};_8.column.to=MW;j0.column={from:j0};j0.value={from:e4(j0)};wW.column={to:wW};var F8={...j0};F8.column.to=wW;import k5 from"net";import z3 from"tls";import RW from"crypto";import W8 from"stream";import{performance as f5}from"perf_hooks";class y0 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 R_=Q3;function Q3(T=[]){let _=T.slice(),F=0;return{get length(){return _.length-F},remove:(W)=>{let J=_.indexOf(W);return J===-1?null:(_.splice(J,1),W)},push:(W)=>(_.push(W),W),shift:()=>{let W=_[F++];if(F===_.length)F=0,_=[];else _[F-1]=void 0;return W}}}var dT=Buffer.allocUnsafe(256),R3="BCcDdEFfHPpQSX".split("").reduce((T,_)=>{let F=_.charCodeAt(0);return T[_]=()=>{return dT[0]=F,$T.i=5,$T},T},{}),$T=Object.assign(E3,R3,{N:String.fromCharCode(0),i:0,inc(T){return $T.i+=T,$T},str(T){let _=Buffer.byteLength(T);return y1(_),$T.i+=dT.write(T,$T.i,_,"utf8"),$T},i16(T){return y1(2),dT.writeUInt16BE(T,$T.i),$T.i+=2,$T},i32(T,_){if(_||_===0)return dT.writeUInt32BE(T,_),$T;return y1(4),dT.writeUInt32BE(T,$T.i),$T.i+=4,$T},z(T){return y1(T),dT.fill(0,$T.i,$T.i+T),$T.i+=T,$T},raw(T){return dT=Buffer.concat([dT.subarray(0,$T.i),T]),$T.i=dT.length,$T},end(T=1){dT.writeUInt32BE($T.i-T,T);let _=dT.subarray(0,$T.i);return $T.i=0,dT=Buffer.allocUnsafe(256),_}}),b=$T;function y1(T){if(dT.length-$T.i<T){let _=dT,F=_.length;dT=Buffer.allocUnsafe(F+(F>>1)+T),_.copy(dT)}}function E3(){return $T.i=0,$T}var $8=j5,V3=1,L0=b().S().end(),P5=b().H().end(),K3=b().i32(8).i32(80877103).end(8),L3=Buffer.concat([b().E().str(b.N).i32(0).end(),L0]),D3=b().D().str("S").str(b.N).end(),HF=()=>{},S3=new Set(["FetchPreparedStatement","RevalidateCachedQuery","transformAssignedExpr"]),I3={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 j5(T,_={},{onopen:F=HF,onend:W=HF,onclose:J=HF}={}){let{ssl:Y,max:$,user:Z,host:G,port:X,database:O,parsers:M,transform:Q,onnotice:K,onnotify:B,onparameter:V,max_pipeline:v,keep_alive:q,backoff:j,target_session_attrs:y}=T,u=R_(),h=V3++,p={pid:null,secret:null},t=Y8(t1,T.idle_timeout),ST=Y8(t1,T.max_lifetime),A_=Y8(FG,T.connect_timeout),D=null,ZT,i=new y0,TT=Buffer.alloc(0),bT=T.fetch_types,H_={},I_={},b0=Math.random().toString(36).slice(2),L=1,o=0,JT=0,zT=0,kT=0,n=0,YT=0,NT=0,VT=null,wT=null,gT=!1,HT=null,N_=null,hT=null,F0=null,fT=null,QT=null,C_=null,x_=null,C=null,wF=null,mT={queue:_.closed,idleTimer:t,connect(A){hT=A,j8()},terminate:RF,execute:QF,cancel:a5,end:t1,count:0,id:h};return _.closed&&_.closed.push(mT),mT;async function s5(){let A;try{A=T.socket?await Promise.resolve(T.socket(T)):new k5.Socket}catch(w){p0(w);return}return A.on("error",p0),A.on("close",y8),A.on("drain",P8),A}async function a5({pid:A,secret:w},g,_T){try{ZT=b().i32(16).i32(80877102).i32(A).i32(w).end(16),await q8(),D.once("error",_T),D.once("close",g)}catch(LT){_T(LT)}}function QF(A){if(gT)return IW(A,BT.connection("CONNECTION_DESTROYED",T));if(A.cancelled)return;try{return A.state=p,C?u.push(A):(C=A,C.active=!0),_G(A),pT(e5(A))&&!A.describeFirst&&!A.cursorFn&&u.length<v&&(!A.options.onexecute||A.options.onexecute(mT))}catch(w){return u.length===0&&pT(L0),b_(w),!0}}function e5(A){if(A.parameters.length>=65534)throw BT.generic("MAX_PARAMETERS_EXCEEDED","Max number of parameters (65534) exceeded");return A.options.simple?b().Q().str(A.statement.string+b.N).end():A.describeFirst?Buffer.concat([B8(A),P5]):A.prepare?A.prepared?SW(A):Buffer.concat([B8(A),SW(A)]):TG(A)}function B8(A){return Buffer.concat([x8(A.statement.string,A.parameters,A.statement.types,A.statement.name),gG("S",A.statement.name)])}function SW(A){return Buffer.concat([pG(A.parameters,A.statement.types,A.statement.name,A.cursorName),A.cursorFn?b8("",A.cursorRows):L3])}function TG(A){return Buffer.concat([x8(A.statement.string,A.parameters,A.statement.types),D3,SW(A)])}function _G(A){let w=[],g=[],_T=r4(A,A.strings[0],A.args[0],w,g,T);!A.tagged&&A.args.forEach((LT)=>q1(LT,w,g,T)),A.prepare=T.prepare&&("prepare"in A.options?A.options.prepare:!0),A.string=_T,A.signature=A.prepare&&g+_T,A.onlyDescribe&&delete I_[A.signature],A.parameters=A.parameters||w,A.prepared=A.prepare&&A.signature in I_,A.describeFirst=A.onlyDescribe||w.length&&!A.prepared,A.statement=A.prepared?I_[A.signature]:{string:_T,types:g,name:A.prepare?b0+L++:""},typeof T.debug==="function"&&T.debug(h,_T,w,g)}function pT(A,w){if(QT=QT?Buffer.concat([QT,A]):Buffer.from(A),w||QT.length>=1024)return k8(w);return wT===null&&(wT=setImmediate(k8)),!0}function k8(A){let w=D.write(QT,A);return wT!==null&&clearImmediate(wT),QT=wT=null,w}function FG(){b_(BT.connection("CONNECT_TIMEOUT",T,D)),D.destroy()}async function f8(){if(pT(K3),!await new Promise((w)=>D.once("data",(g)=>w(g[0]===83)))&&Y==="prefer")return h0();D.removeAllListeners(),D=z3.connect({socket:D,servername:k5.isIP(D.host)?void 0:D.host,...Y==="require"||Y==="allow"||Y==="prefer"?{rejectUnauthorized:!1}:Y==="verify-full"?{}:typeof Y==="object"?Y:{}}),D.on("secureConnect",h0),D.on("error",p0),D.on("close",y8),D.on("drain",P8)}function P8(){!C&&F(mT)}function l1(A){if(HT){if(HT.push(A),JT-=A.length,JT>0)return}TT=HT?Buffer.concat(HT,n-JT):TT.length===0?A:Buffer.concat([TT,A],TT.length+A.length);while(TT.length>4){if(n=TT.readUInt32BE(1),n>=TT.length){JT=n-TT.length,HT=[TT];break}try{WG(TT.subarray(0,n+1))}catch(w){C&&(C.cursorFn||C.describeFirst)&&pT(L0),b_(w)}TT=TT.subarray(n+1),JT=0,HT=null}}async function q8(){if(gT=!1,H_={},D||(D=await s5()),!D)return;if(A_.start(),T.socket)return Y?f8():h0();if(D.on("connect",Y?f8:h0),T.path)return D.connect(T.path);D.ssl=Y,D.connect(X[zT],G[zT]),D.host=G[zT],D.port=X[zT],zT=(zT+1)%X.length}function j8(){setTimeout(q8,o?o+YT-f5.now():0)}function h0(){try{I_={},bT=T.fetch_types,b0=Math.random().toString(36).slice(2),L=1,ST.start(),D.on("data",l1),q&&D.setKeepAlive&&D.setKeepAlive(!0,1000*q);let A=oG();pT(A)}catch(A){p0(A)}}function p0(A){if(mT.queue===_.connecting&&T.host[kT+1])return;b_(A);while(u.length)IW(u.shift(),A)}function b_(A){fT&&(fT.destroy(A),fT=null),C&&IW(C,A),hT&&(IW(hT,A),hT=null)}function IW(A,w){if(A.reserve)return A.reject(w);if(!w||typeof w!=="object")w=new Error(w);"query"in w||"parameters"in w||Object.defineProperties(w,{stack:{value:w.stack+A.origin.replace(/.*\n/,`
|
|
50
|
+
`),enumerable:T.debug},query:{value:A.string,enumerable:T.debug},parameters:{value:A.parameters,enumerable:T.debug},args:{value:A.args,enumerable:T.debug},types:{value:A.statement&&A.statement.types,enumerable:T.debug}}),A.reject(w)}function t1(){return F0||(!mT.reserved&&W(mT),!mT.reserved&&!hT&&!C&&u.length===0?(RF(),new Promise((A)=>D&&D.readyState!=="closed"?D.once("close",A):A())):F0=new Promise((A)=>C_=A))}function RF(){if(gT=!0,fT||C||hT||u.length)p0(BT.connection("CONNECTION_DESTROYED",T));if(clearImmediate(wT),D)D.removeListener("data",l1),D.removeListener("connect",h0),D.readyState==="open"&&D.end(b().X().end());C_&&(C_(),F0=C_=null)}async function y8(A){if(TT=Buffer.alloc(0),JT=0,HT=null,clearImmediate(wT),D.removeListener("data",l1),D.removeListener("connect",h0),t.cancel(),ST.cancel(),A_.cancel(),D.removeAllListeners(),D=null,hT)return j8();!A&&(C||u.length)&&p0(BT.connection("CONNECTION_CLOSED",T,D)),o=f5.now(),A&&T.shared.retries++,YT=(typeof j==="function"?j(T.shared.retries):j)*1000,J(mT,BT.connection("CONNECTION_CLOSED",T,D))}function WG(A,w=A[0]){(w===68?JG:w===100?PG:w===65?IG:w===83?YG:w===90?$G:w===67?ZG:w===50?v8:w===49?XG:w===116?GG:w===84?AG:w===82?HG:w===110?RG:w===75?EG:w===69?DG:w===115?NG:w===51?CG:w===71?BG:w===78?jG:w===72?kG:w===99?qG:w===73?yG:w===86?vG:w===118?xG:w===87?fG:bG)(A)}function JG(A){let w=7,g,_T,LT,oT=C.isRaw?new Array(C.statement.columns.length):{};for(let lT=0;lT<C.statement.columns.length;lT++)_T=C.statement.columns[lT],g=A.readInt32BE(w),w+=4,LT=g===-1?null:C.isRaw===!0?A.subarray(w,w+=g):_T.parser===void 0?A.toString("utf8",w,w+=g):_T.parser.array===!0?_T.parser(A.toString("utf8",w+1,w+=g)):_T.parser(A.toString("utf8",w,w+=g)),C.isRaw?oT[lT]=C.isRaw===!0?LT:Q.value.from?Q.value.from(LT,_T):LT:oT[_T.name]=Q.value.from?Q.value.from(LT,_T):LT;C.forEachFn?C.forEachFn(Q.row.from?Q.row.from(oT):oT,i):i[NT++]=Q.row.from?Q.row.from(oT):oT}function YG(A){let[w,g]=A.toString("utf8",5,A.length-1).split(b.N);if(H_[w]=g,T.parameters[w]!==g)T.parameters[w]=g,V&&V(w,g)}function $G(A){if(C&&C.options.simple&&C.resolve(N_||i),C=N_=null,i=new y0,A_.cancel(),hT){if(y){if(!H_.in_hot_standby||!H_.default_transaction_read_only)return LG();else if(KG(y,H_))return RF()}if(bT)return hT.reserve&&(hT=null),zG();hT&&!hT.reserve&&QF(hT),T.shared.retries=kT=0,hT=null;return}while(u.length&&(C=u.shift())&&(C.active=!0,C.cancelled))j5(T).cancel(C.state,C.cancelled.resolve,C.cancelled.reject);if(C)return;mT.reserved?!mT.reserved.release&&A[5]===73?F0?RF():(mT.reserved=null,F(mT)):mT.reserved():F0?RF():F(mT)}function ZG(A){NT=0;for(let w=A.length-1;w>0;w--){if(A[w]===32&&A[w+1]<58&&i.count===null)i.count=+A.toString("utf8",w+1,A.length-1);if(A[w-1]>=65){i.command=A.toString("utf8",5,w),i.state=p;break}}if(wF&&(wF(),wF=null),i.command==="BEGIN"&&$!==1&&!mT.reserved)return b_(BT.generic("UNSAFE_TRANSACTION","Only use sql.begin, sql.reserved or max: 1"));if(C.options.simple)return v8();if(C.cursorFn)i.count&&C.cursorFn(i),pT(L0);C.resolve(i)}function XG(){C.parsing=!1}function v8(){!i.statement&&(i.statement=C.statement),i.columns=C.statement.columns}function GG(A){let w=A.readUInt16BE(5);for(let g=0;g<w;++g)!C.statement.types[g]&&(C.statement.types[g]=A.readUInt32BE(7+g*4));C.prepare&&(I_[C.signature]=C.statement),C.describeFirst&&!C.onlyDescribe&&(pT(SW(C)),C.describeFirst=!1)}function AG(A){if(i.command)N_=N_||[i],N_.push(i=new y0),i.count=null,C.statement.columns=null;let w=A.readUInt16BE(5),g=7,_T;C.statement.columns=Array(w);for(let LT=0;LT<w;++LT){_T=g;while(A[g++]!==0);let oT=A.readUInt32BE(g),lT=A.readUInt16BE(g+4),W0=A.readUInt32BE(g+6);C.statement.columns[LT]={name:Q.column.from?Q.column.from(A.toString("utf8",_T,g-1)):A.toString("utf8",_T,g-1),parser:M[W0],table:oT,number:lT,type:W0},g+=18}if(i.statement=C.statement,C.onlyDescribe)return C.resolve(C.statement),pT(L0)}async function HG(A,w=A.readUInt32BE(5)){(w===3?OG:w===5?UG:w===10?MG:w===11?wG:w===12?QG:w!==0?hG:HF)(A,w)}async function OG(){let A=await i1();pT(b().p().str(A).z(1).end())}async function UG(A){let w="md5"+await q5(Buffer.concat([Buffer.from(await q5(await i1()+Z)),A.subarray(9)]));pT(b().p().str(w).z(1).end())}async function MG(){x_=(await RW.randomBytes(18)).toString("base64"),b().p().str("SCRAM-SHA-256"+b.N);let A=b.i;pT(b.inc(4).str("n,,n=*,r="+x_).i32(b.i-A-4,A).end())}async function wG(A){let w=A.toString("utf8",9).split(",").reduce((lT,W0)=>(lT[W0[0]]=W0.slice(2),lT),{}),g=await RW.pbkdf2Sync(await i1(),Buffer.from(w.s,"base64"),parseInt(w.i),32,"sha256"),_T=await v1(g,"Client Key"),LT="n=*,r="+x_+",r="+w.r+",s="+w.s+",i="+w.i+",c=biws,r="+w.r;VT=(await v1(await v1(g,"Server Key"),LT)).toString("base64");let oT="c=biws,r="+w.r+",p="+C3(_T,Buffer.from(await v1(await N3(_T),LT))).toString("base64");pT(b().p().str(oT).end())}function QG(A){if(A.toString("utf8",9).split(b.N,1)[0].slice(2)===VT)return;b_(BT.generic("SASL_SIGNATURE_MISMATCH","The server did not return the correct signature")),D.destroy()}function i1(){return Promise.resolve(typeof T.pass==="function"?T.pass():T.pass)}function RG(){if(i.statement=C.statement,i.statement.columns=[],C.onlyDescribe)return C.resolve(C.statement),pT(L0)}function EG(A){p.pid=A.readUInt32BE(5),p.secret=A.readUInt32BE(9)}async function zG(){bT=!1,(await new S_([`
|
|
51
51
|
select b.oid, b.typarray
|
|
52
52
|
from pg_catalog.pg_type a
|
|
53
53
|
left join pg_catalog.pg_type b on b.oid = a.typelem
|
|
54
54
|
where a.typcategory = 'A'
|
|
55
55
|
group by b.oid, b.typarray
|
|
56
56
|
order by b.oid
|
|
57
|
-
`],[],
|
|
57
|
+
`],[],QF)).forEach(({oid:w,typarray:g})=>VG(w,g))}function VG(A,w){if(!!T.parsers[w]&&!!T.serializers[w])return;let g=T.parsers[A];T.shared.typeArrayMap[A]=w,T.parsers[w]=(_T)=>C5(_T,g,w),T.parsers[w].array=!0,T.serializers[w]=(_T)=>N5(_T,T.serializers[A],T,w)}function KG(A,w){return A==="read-write"&&w.default_transaction_read_only==="on"||A==="read-only"&&w.default_transaction_read_only==="off"||A==="primary"&&w.in_hot_standby==="on"||A==="standby"&&w.in_hot_standby==="off"||A==="prefer-standby"&&w.in_hot_standby==="off"&&T.host[kT]}function LG(){let A=new S_([`
|
|
58
58
|
show transaction_read_only;
|
|
59
59
|
select pg_catalog.pg_is_in_recovery()
|
|
60
|
-
`],[],
|
|
60
|
+
`],[],QF,null,{simple:!0});A.resolve=([[w],[g]])=>{H_.default_transaction_read_only=w.transaction_read_only,H_.in_hot_standby=g.pg_is_in_recovery?"on":"off"},A.execute()}function DG(A){C&&(C.cursorFn||C.describeFirst)&&pT(L0);let w=BT.postgres(J8(A));C&&C.retried?b_(C.retried):C&&C.prepared&&S3.has(w.routine)?SG(C,w):b_(w)}function SG(A,w){delete I_[A.signature],A.retried=w,QF(A)}function IG(A){if(!B)return;let w=9;while(A[w++]!==0);B(A.toString("utf8",9,w-1),A.toString("utf8",w,A.length-1))}async function NG(){try{let A=await Promise.resolve(C.cursorFn(i));NT=0,A===GF?pT(mG(C.portal)):(i=new y0,pT(b8("",C.cursorRows)))}catch(A){pT(L0),C.reject(A)}}function CG(){i.count&&C.cursorFn(i),C.resolve(i)}function BG(){fT=new W8.Writable({autoDestroy:!0,write(A,w,g){D.write(b().d().raw(A).end(),g)},destroy(A,w){w(A),D.write(b().f().str(A+b.N).end()),fT=null},final(A){D.write(b().c().end()),wF=A}}),C.resolve(fT)}function kG(){fT=new W8.Readable({read(){D.resume()}}),C.resolve(fT)}function fG(){fT=new W8.Duplex({autoDestroy:!0,read(){D.resume()},write(A,w,g){D.write(b().d().raw(A).end(),g)},destroy(A,w){w(A),D.write(b().f().str(A+b.N).end()),fT=null},final(A){D.write(b().c().end()),wF=A}}),C.resolve(fT)}function PG(A){fT&&(fT.push(A.subarray(5))||D.pause())}function qG(){fT&&fT.push(null),fT=null}function jG(A){K?K(J8(A)):console.log(J8(A))}function yG(){}function vG(){b_(BT.notSupported("FunctionCallResponse"))}function xG(){b_(BT.notSupported("NegotiateProtocolVersion"))}function bG(A){console.error("Postgres.js : Unknown Message:",A[0])}function hG(A,w){console.error("Postgres.js : Unknown Auth:",w)}function pG(A,w,g="",_T=""){let LT,oT;return b().B().str(_T+b.N).str(g+b.N).i16(0).i16(A.length),A.forEach((lT,W0)=>{if(lT===null)return b.i32(4294967295);oT=w[W0],A[W0]=lT=oT in T.serializers?T.serializers[oT](lT):""+lT,LT=b.i,b.inc(4).str(lT).i32(b.i-LT-4,LT)}),b.i16(0),b.end()}function x8(A,w,g,_T=""){return b().P().str(_T+b.N).str(A+b.N).i16(w.length),w.forEach((LT,oT)=>b.i32(g[oT]||0)),b.end()}function gG(A,w=""){return b().D().str(A).str(w+b.N).end()}function b8(A="",w=0){return Buffer.concat([b().E().str(A+b.N).i32(w).end(),P5])}function mG(A=""){return Buffer.concat([b().C().str("P").str(A+b.N).end(),b().S().end()])}function oG(){return ZT||b().inc(4).i16(3).z(2).str(Object.entries(Object.assign({user:Z,database:O,client_encoding:"UTF8"},T.connection)).filter(([,A])=>A).map(([A,w])=>A+b.N+w).join(b.N)).z(2).end(0)}}function J8(T){let _={},F=5;for(let W=5;W<T.length-1;W++)if(T[W]===0)_[I3[T[F]]]=T.toString("utf8",F+1,W),F=W+1;return _}function q5(T){return RW.createHash("md5").update(T).digest("hex")}function v1(T,_){return RW.createHmac("sha256",T).update(_).digest()}function N3(T){return RW.createHash("sha256").update(T).digest()}function C3(T,_){let F=Math.max(T.length,_.length),W=Buffer.allocUnsafe(F);for(let J=0;J<F;J++)W[J]=T[J]^_[J];return W}function Y8(T,_){if(_=typeof _==="function"?_():_,!_)return{cancel:HF,start:HF};let F;return{cancel(){F&&(clearTimeout(F),F=null)},start(){F&&clearTimeout(F),F=setTimeout(W,_*1000,arguments)}};function W(J){T.apply(null,J),F=null}}var y5=()=>{};function Z8(T,_){let F=new Map,W="postgresjs_"+Math.random().toString(36).slice(2),J={},Y,$,Z=!1,G=M.sql=T({..._,transform:{column:{},value:{},row:{}},max:1,fetch_types:!1,idle_timeout:null,max_lifetime:null,connection:{..._.connection,replication:"database"},onclose:async function(){if(Z)return;$=null,J.pid=J.secret=void 0,Q(await K(G,W,_.publications)),F.forEach((V)=>V.forEach(({onsubscribe:v})=>v()))},no_subscribe:!0}),X=G.end,O=G.close;return G.end=async()=>{return Z=!0,$&&await new Promise((V)=>($.once("close",V),$.end())),X()},G.close=async()=>{return $&&await new Promise((V)=>($.once("close",V),$.end())),O()},M;async function M(V,v,q=y5,j=y5){if(V=f3(V),!Y)Y=K(G,W,_.publications);let y={fn:v,onsubscribe:q},u=F.has(V)?F.get(V).add(y):F.set(V,new Set([y])).get(V),h=()=>{u.delete(y),u.size===0&&F.delete(V)};return Y.then((p)=>{return Q(p),q(),$&&$.on("error",j),{unsubscribe:h,state:J,sql:G}})}function Q(V){$=V.stream,J.pid=V.state.pid,J.secret=V.state.secret}async function K(V,v,q){if(!q)throw new Error("Missing publication names");let j=await V.unsafe(`CREATE_REPLICATION_SLOT ${v} TEMPORARY LOGICAL pgoutput NOEXPORT_SNAPSHOT`),[y]=j,u=await V.unsafe(`START_REPLICATION SLOT ${v} LOGICAL ${y.consistent_point} (proto_version '1', publication_names '${q}')`).writable(),h={lsn:Buffer.concat(y.consistent_point.split("/").map((D)=>Buffer.from(("00000000"+D).slice(-8),"hex")))};return u.on("data",t),u.on("error",p),u.on("close",V.close),{stream:u,state:j.state};function p(D){console.error("Unexpected error during logical streaming - reconnecting",D)}function t(D){if(D[0]===119)k3(D.subarray(25),h,V.options.parsers,ST,_.transform);else if(D[0]===107&&D[17])h.lsn=D.subarray(1,9),A_()}function ST(D,ZT){let i=ZT.relation.schema+"."+ZT.relation.table;B("*",D,ZT),B("*:"+i,D,ZT),ZT.relation.keys.length&&B("*:"+i+"="+ZT.relation.keys.map((TT)=>D[TT.name]),D,ZT),B(ZT.command,D,ZT),B(ZT.command+":"+i,D,ZT),ZT.relation.keys.length&&B(ZT.command+":"+i+"="+ZT.relation.keys.map((TT)=>D[TT.name]),D,ZT)}function A_(){let D=Buffer.alloc(34);D[0]=114,D.fill(h.lsn,1),D.writeBigInt64BE(BigInt(Date.now()-Date.UTC(2000,0,1))*BigInt(1000),25),u.write(D)}}function B(V,v,q){F.has(V)&&F.get(V).forEach(({fn:j})=>j(v,q,V))}}function B3(T){return new Date(Date.UTC(2000,0,1)+Number(T/BigInt(1000)))}function k3(T,_,F,W,J){let Y=($,[Z,G])=>($[Z.charCodeAt(0)]=G,$);Object.entries({R:($)=>{let Z=1,G=_[$.readUInt32BE(Z)]={schema:$.toString("utf8",Z+=4,Z=$.indexOf(0,Z))||"pg_catalog",table:$.toString("utf8",Z+1,Z=$.indexOf(0,Z+1)),columns:Array($.readUInt16BE(Z+=2)),keys:[]};Z+=2;let X=0,O;while(Z<$.length)O=G.columns[X++]={key:$[Z++],name:J.column.from?J.column.from($.toString("utf8",Z,Z=$.indexOf(0,Z))):$.toString("utf8",Z,Z=$.indexOf(0,Z)),type:$.readUInt32BE(Z+=1),parser:F[$.readUInt32BE(Z)],atttypmod:$.readUInt32BE(Z+=4)},O.key&&G.keys.push(O),Z+=4},Y:()=>{},O:()=>{},B:($)=>{_.date=B3($.readBigInt64BE(9)),_.lsn=$.subarray(1,9)},I:($)=>{let Z=1,G=_[$.readUInt32BE(Z)],{row:X}=x1($,G.columns,Z+=7,J);W(X,{command:"insert",relation:G})},D:($)=>{let Z=1,G=_[$.readUInt32BE(Z)];Z+=4;let X=$[Z]===75;W(X||$[Z]===79?x1($,G.columns,Z+=3,J).row:null,{command:"delete",relation:G,key:X})},U:($)=>{let Z=1,G=_[$.readUInt32BE(Z)];Z+=4;let X=$[Z]===75,O=X||$[Z]===79?x1($,G.columns,Z+=3,J):null;O&&(Z=O.i);let{row:M}=x1($,G.columns,Z+3,J);W(M,{command:"update",relation:G,key:X,old:O&&O.row})},T:()=>{},C:()=>{}}).reduce(Y,{})[T[0]](T)}function x1(T,_,F,W){let J,Y,$,Z=W.raw?new Array(_.length):{};for(let G=0;G<_.length;G++)J=T[F++],Y=_[G],$=J===110?null:J===117?void 0:Y.parser===void 0?T.toString("utf8",F+4,F+=4+T.readUInt32BE(F)):Y.parser.array===!0?Y.parser(T.toString("utf8",F+5,F+=4+T.readUInt32BE(F))):Y.parser(T.toString("utf8",F+4,F+=4+T.readUInt32BE(F))),W.raw?Z[G]=W.raw===!0?$:W.value.from?W.value.from($,Y):$:Z[Y.name]=W.value.from?W.value.from($,Y):$;return{i:F,row:W.row.from?W.row.from(Z):Z}}function f3(T){let _=T.match(/^(\*|insert|update|delete)?:?([^.]+?\.?[^=]+)?=?(.+)?/i)||[];if(!_)throw new Error("Malformed subscribe pattern: "+T);let[,F,W,J]=_;return(F||"*")+(W?":"+(W.indexOf(".")===-1?"public."+W:W):"")+(J?"="+J:"")}import v5 from"stream";function X8(T,_,F=393216){return new Promise(async(W,J)=>{await T.begin(async(Y)=>{let $;!_&&([{oid:_}]=await Y`select lo_creat(-1) as oid`);let[{fd:Z}]=await Y`select lo_open(${_}, ${F}) as fd`,G={writable:O,readable:X,close:()=>Y`select lo_close(${Z})`.then($),tell:()=>Y`select lo_tell64(${Z})`,read:(M)=>Y`select loread(${Z}, ${M}) as data`,write:(M)=>Y`select lowrite(${Z}, ${M})`,truncate:(M)=>Y`select lo_truncate64(${Z}, ${M})`,seek:(M,Q=0)=>Y`select lo_lseek64(${Z}, ${M}, ${Q})`,size:()=>Y`
|
|
61
61
|
select
|
|
62
62
|
lo_lseek64(${Z}, location, 0) as position,
|
|
63
63
|
seek.size
|
|
@@ -67,10 +67,11 @@ ${$.trace}`:"No previous disposal trace was found."),W.type){case"atom_family":c
|
|
|
67
67
|
tell.location
|
|
68
68
|
from (select lo_tell64($1) as location) tell
|
|
69
69
|
) seek
|
|
70
|
-
`};return W(G),new Promise(async(M)=>$=M);async function X({highWaterMark:M=16384,start:Q=0,end:V=1/0}={}){let C=V-Q;return Q&&await G.seek(Q),new q5.Readable({highWaterMark:M,async read(K){let v=K>C?K-C:K;C-=K;let[{data:P}]=await G.read(v);if(this.push(P),P.length<K)this.push(null)}})}async function U({highWaterMark:M=16384,start:Q=0}={}){return Q&&await G.seek(Q),new q5.Writable({highWaterMark:M,write(V,C,K){G.write(V).then(()=>K(),K)}})}}).catch(J)})}Object.assign(y1,{PostgresError:ZF,toPascal:k0,pascal:a4,toCamel:B0,camel:s4,toKebab:f0,kebab:e4,fromPascal:AW,fromCamel:HW,fromKebab:UW,BigInt:{to:20,from:[20],parse:(T)=>BigInt(T),serialize:(T)=>T.toString()}});var GF=y1;function y1(T,_){let F=B3(T,_),W=F.no_subscribe||J8(y1,{...F}),J=!1,Y=z_(),$=z_(),Z=z_(),G=z_(),X=z_(),U=z_(),M=z_(),Q=z_(),V={connecting:$,reserved:Z,closed:G,ended:X,open:U,busy:M,full:Q},C=[...Array(F.max)].map(()=>W8(F,V,{onopen:I_,onend:A_,onclose:y0})),K=v(ST);return Object.assign(K,{get parameters(){return F.parameters},largeObject:Y8.bind(null,K),subscribe:W,CLOSE:$F,END:$F,PostgresError:ZF,options:F,reserve:y,listen:P,begin:u,close:i,end:$T}),K;function v(D){return D.debug=F.debug,Object.entries(F.types).reduce((r,[HT,IT])=>{return r[HT]=(KT)=>new o_(KT,IT.to),r},o),Object.assign(JT,{types:o,typed:o,unsafe:RT,notify:j,array:t,json:p,file:BT}),JT;function o(r,HT){return new o_(r,HT)}function JT(r,...HT){return r&&Array.isArray(r.raw)?new S_(r,HT,D,L):typeof r==="string"&&!HT.length?new OW(F.transform.column.to?F.transform.column.to(r):r):new B1(r,HT)}function RT(r,HT=[],IT={}){return arguments.length===2&&!Array.isArray(HT)&&(IT=HT,HT=[]),new S_([r],HT,D,L,{prepare:!1,...IT,simple:"simple"in IT?IT.simple:HT.length===0})}function BT(r,HT=[],IT={}){return arguments.length===2&&!Array.isArray(HT)&&(IT=HT,HT=[]),new S_([],HT,(wT)=>{C3.readFile(r,"utf8",(pT,AT)=>{if(pT)return wT.reject(pT);wT.strings=[AT],D(wT)})},L,{...IT,simple:"simple"in IT?IT.simple:HT.length===0})}}async function P(D,o,JT){let RT={fn:o,onlisten:JT},BT=P.sql||(P.sql=y1({...F,max:1,idle_timeout:null,max_lifetime:null,fetch_types:!1,onclose(){Object.entries(P.channels).forEach(([wT,{listeners:pT}])=>{delete P.channels[wT],Promise.all(pT.map((AT)=>P(wT,AT.fn,AT.onlisten).catch(()=>{})))})},onnotify(wT,pT){wT in P.channels&&P.channels[wT].listeners.forEach((AT)=>AT.fn(pT))}})),r=P.channels||(P.channels={});if(D in r){r[D].listeners.push(RT);let wT=await r[D].result;return RT.onlisten&&RT.onlisten(),{state:wT.state,unlisten:KT}}r[D]={result:BT`listen ${BT.unsafe('"'+D.replace(/"/g,'""')+'"')}`,listeners:[RT]};let IT=await r[D].result;return RT.onlisten&&RT.onlisten(),{state:IT.state,unlisten:KT};async function KT(){if(D in r===!1)return;if(r[D].listeners=r[D].listeners.filter((wT)=>wT!==RT),r[D].listeners.length)return;return delete r[D],BT`unlisten ${BT.unsafe('"'+D.replace(/"/g,'""')+'"')}`}}async function j(D,o){return await K`select pg_notify(${D}, ${""+o})`}async function y(){let D=z_(),o=U.length?U.shift():await new Promise((BT)=>{Y.push({reserve:BT}),G.length&&bT(G.shift())});h(o,Z),o.reserved=()=>D.length?o.execute(D.shift()):h(o,Z),o.reserved.release=!0;let JT=v(RT);return JT.release=()=>{o.reserved=null,I_(o)},JT;function RT(BT){o.queue===Q?D.push(BT):o.execute(BT)||h(o,Q)}}async function u(D,o){!o&&(o=D,D="");let JT=z_(),RT=0,BT,r=null;try{return await K.unsafe("begin "+D.replace(/[^a-z ]/ig,""),[],{onexecute:IT}).execute(),await Promise.race([HT(BT,o),new Promise((KT,wT)=>BT.onclose=wT)])}catch(KT){throw KT}async function HT(KT,wT,pT){let AT=v(kT);AT.savepoint=T0,AT.prepare=(QT)=>r=QT.replace(/[^a-z0-9$-_. ]/gi);let N_,gT;pT&&await AT`savepoint ${AT(pT)}`;try{if(gT=await new Promise((QT,C_)=>{let v_=wT(AT);Promise.resolve(Array.isArray(v_)?Promise.all(v_):v_).then(QT,C_)}),N_)throw N_}catch(QT){throw await(pT?AT`rollback to ${AT(pT)}`:AT`rollback`),QT instanceof ZF&&QT.code==="25P02"&&N_||QT}if(!pT)r?await AT`prepare transaction '${AT.unsafe(r)}'`:await AT`commit`;return gT;function T0(QT,C_){if(QT&&Array.isArray(QT.raw))return T0((v_)=>v_.apply(v_,arguments));return arguments.length===1&&(C_=QT,QT=null),HT(KT,C_,"s"+RT+++(QT?"_"+QT:""))}function kT(QT){QT.catch((C_)=>N_||(N_=C_)),KT.queue===Q?JT.push(QT):KT.execute(QT)||h(KT,Q)}}function IT(KT){BT=KT,h(KT,Z),KT.reserved=()=>JT.length?KT.execute(JT.shift()):h(KT,Z)}}function h(D,o){return D.queue.remove(D),o.push(D),D.queue=o,o===U?D.idleTimer.start():D.idleTimer.cancel(),D}function p(D){return new o_(D,3802)}function t(D,o){if(!Array.isArray(D))return t(Array.from(arguments));return new o_(D,o||(D.length?N1(D)||25:0),F.shared.typeArrayMap)}function ST(D){if(J)return D.reject(CT.connection("CONNECTION_ENDED",F,F));if(U.length)return H_(U.shift(),D);if(G.length)return bT(G.shift(),D);M.length?H_(M.shift(),D):Y.push(D)}function H_(D,o){return D.execute(o)?h(D,M):h(D,Q)}function L(D){return new Promise((o,JT)=>{D.state?D.active?W8(F).cancel(D.state,o,JT):D.cancelled={resolve:o,reject:JT}:(Y.remove(D),D.cancelled=!0,D.reject(CT.generic("57014","canceling statement due to user request")),o())})}async function $T({timeout:D=null}={}){if(J)return J;await 1;let o;return J=Promise.race([new Promise((JT)=>D!==null&&(o=setTimeout(TT,D*1000,JT))),Promise.all(C.map((JT)=>JT.end()).concat(P.sql?P.sql.end({timeout:0}):[],W.sql?W.sql.end({timeout:0}):[]))]).then(()=>clearTimeout(o))}async function i(){await Promise.all(C.map((D)=>D.end()))}async function TT(D){await Promise.all(C.map((o)=>o.terminate()));while(Y.length)Y.shift().reject(CT.connection("CONNECTION_DESTROYED",F));D()}function bT(D,o){return h(D,$),D.connect(o),D}function A_(D){h(D,X)}function I_(D){if(Y.length===0)return h(D,U);let o=Math.ceil(Y.length/($.length+1)),JT=!0;while(JT&&Y.length&&o-- >0){let RT=Y.shift();if(RT.reserve)return RT.reserve(D);JT=D.execute(RT)}JT?h(D,M):h(D,Q)}function y0(D,o){h(D,G),D.reserved=null,D.onclose&&(D.onclose(o),D.onclose=null),F.onclose&&F.onclose(D.id),Y.length&&bT(D,Y.shift())}}function B3(T,_){if(T&&T.shared)return T;let F=process.env,W=(!T||typeof T==="string"?_:T)||{},{url:J,multihost:Y}=j3(T),$=[...J.searchParams].reduce((Q,[V,C])=>(Q[V]=C,Q),{}),Z=W.hostname||W.host||Y||J.hostname||F.PGHOST||"localhost",G=W.port||J.port||F.PGPORT||5432,X=W.user||W.username||J.username||F.PGUSERNAME||F.PGUSER||y3();W.no_prepare&&(W.prepare=!1),$.sslmode&&($.ssl=$.sslmode,delete $.sslmode),"timeout"in W&&(console.log("The timeout option is deprecated, use idle_timeout instead"),W.idle_timeout=W.timeout),$.sslrootcert==="system"&&($.ssl="verify-full");let U=["idle_timeout","connect_timeout","max_lifetime","max_pipeline","backoff","keep_alive"],M={max:10,ssl:!1,idle_timeout:null,connect_timeout:30,max_lifetime:q3,max_pipeline:100,backoff:f3,keep_alive:60,prepare:!0,debug:!1,fetch_types:!0,publications:"alltables",target_session_attrs:null};return{host:Array.isArray(Z)?Z:Z.split(",").map((Q)=>Q.split(":")[0]),port:Array.isArray(G)?G:Z.split(",").map((Q)=>parseInt(Q.split(":")[1]||G)),path:W.path||Z.indexOf("/")>-1&&Z+"/.s.PGSQL."+G,database:W.database||W.db||(J.pathname||"").slice(1)||F.PGDATABASE||X,user:X,pass:W.pass||W.password||J.password||F.PGPASSWORD||"",...Object.entries(M).reduce((Q,[V,C])=>{let K=V in W?W[V]:(V in $)?$[V]==="disable"||$[V]==="false"?!1:$[V]:F["PG"+V.toUpperCase()]||C;return Q[V]=typeof K==="string"&&U.includes(V)?+K:K,Q},{}),connection:{application_name:"postgres.js",...W.connection,...Object.entries($).reduce((Q,[V,C])=>((V in M)||(Q[V]=C),Q),{})},types:W.types||{},target_session_attrs:k3(W,J,F),onnotice:W.onnotice,onnotify:W.onnotify,onclose:W.onclose,onparameter:W.onparameter,socket:W.socket,transform:P3(W.transform||{undefined:void 0}),parameters:{},shared:{retries:0,typeArrayMap:{}},...K5(W.types)}}function k3(T,_,F){let W=T.target_session_attrs||_.searchParams.get("target_session_attrs")||F.PGTARGETSESSIONATTRS;if(!W||["read-write","read-only","primary","standby","prefer-standby"].includes(W))return W;throw new Error("target_session_attrs "+W+" is not supported")}function f3(T){return(0.5+Math.random()/2)*Math.min(3**T/100,20)}function q3(){return 60*(30+Math.random()*30)}function P3(T){return{undefined:T.undefined,column:{from:typeof T.column==="function"?T.column:T.column&&T.column.from,to:T.column&&T.column.to},value:{from:typeof T.value==="function"?T.value:T.value&&T.value.from,to:T.value&&T.value.to},row:{from:typeof T.row==="function"?T.row:T.row&&T.row.from,to:T.row&&T.row.to}}}function j3(T){if(!T||typeof T!=="string")return{url:{searchParams:new Map}};let _=T;_=_.slice(_.indexOf("://")+3).split(/[?/]/)[0],_=decodeURIComponent(_.slice(_.indexOf("@")+1));let F=new URL(T.replace(_,_.split(",")[0]));return{url:{username:decodeURIComponent(F.username),password:decodeURIComponent(F.password),host:F.host,hostname:F.hostname,port:F.port,pathname:F.pathname,searchParams:F.searchParams},multihost:_.indexOf(",")>-1&&_}}function y3(){try{return N3.userInfo().username}catch(T){return process.env.USERNAME||process.env.USER||process.env.LOGNAME}}class LT{static[A]="SelectionProxyHandler";config;constructor(T){this.config={...T}}get(T,_){if(_==="_")return{...T._,selectedFields:new Proxy(T._.selectedFields,this)};if(_===MT)return{...T[MT],selectedFields:new Proxy(T[MT].selectedFields,this)};if(typeof _==="symbol")return T[_];let W=(E(T,jT)?T._.selectedFields:E(T,Z_)?T[MT].selectedFields:T)[_];if(E(W,k.Aliased)){if(this.config.sqlAliasedBehavior==="sql"&&!W.isSelectionField)return W.sql;let J=W.clone();return J.isSelectionField=!0,J}if(E(W,k)){if(this.config.sqlBehavior==="sql")return W;throw new Error(`You tried to reference "${_}" field from a subquery, which is a raw SQL field, but it doesn't have an alias declared. Please add an alias to the field using ".as('alias')" method.`)}if(E(W,XT)){if(this.config.alias)return new Proxy(W,new YF(new Proxy(W.table,new FW(this.config.alias,this.config.replaceOriginalName??!1))));return W}if(typeof W!=="object"||W===null)return W;return new Proxy(W,new LT(this.config))}}class v1 extends sT{constructor(T,_,F,W){super();this.session=_,this.dialect=F,this.config={table:T,withList:W}}static[A]="PgDelete";config;where(T){return this.config.where=T,this}returning(T=this.config.table[B.Symbol.Columns]){return this.config.returningFields=T,this.config.returning=D_(T),this}getSQL(){return this.dialect.buildDeleteQuery(this.config)}toSQL(){let{typings:T,..._}=this.dialect.sqlToQuery(this.getSQL());return _}_prepare(T){return GT.startActiveSpan("drizzle.prepareQuery",()=>{return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,T,!0)})}prepare(T){return this._prepare(T)}authToken;setToken(T){return this.authToken=T,this}execute=(T)=>{return GT.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(T,this.authToken)})};getSelectedFields(){return this.config.returningFields?new Proxy(this.config.returningFields,new LT({alias:vT(this.config.table),sqlAliasedBehavior:"alias",sqlBehavior:"error"})):void 0}$dynamic(){return this}}function v3(T){return(T.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).map((F)=>F.toLowerCase()).join("_")}function b3(T){return(T.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).reduce((F,W,J)=>{let Y=J===0?W.toLowerCase():`${W[0].toUpperCase()}${W.slice(1)}`;return F+Y},"")}function x3(T){return T}class $8{static[A]="CasingCache";cache={};cachedTables={};convert;constructor(T){this.convert=T==="snake_case"?v3:T==="camelCase"?b3:x3}getColumnCasing(T){if(!T.keyAsName)return T.name;let _=T.table[B.Symbol.Schema]??"public",F=T.table[B.Symbol.OriginalName],W=`${_}.${F}.${T.name}`;if(!this.cache[W])this.cacheTable(T.table);return this.cache[W]}cacheTable(T){let _=T[B.Symbol.Schema]??"public",F=T[B.Symbol.OriginalName],W=`${_}.${F}`;if(!this.cachedTables[W]){for(let J of Object.values(T[B.Symbol.Columns])){let Y=`${W}.${J.name}`;this.cache[Y]=this.convert(J.name)}this.cachedTables[W]=!0}}clearCache(){this.cache={},this.cachedTables={}}}class wW extends Z_{static[A]="PgViewBase"}class P0{static[A]="PgDialect";casing;constructor(T){this.casing=new $8(T?.casing)}async migrate(T,_,F){let W=typeof F==="string"?"__drizzle_migrations":F.migrationsTable??"__drizzle_migrations",J=typeof F==="string"?"drizzle":F.migrationsSchema??"drizzle",Y=O`
|
|
71
|
-
CREATE TABLE IF NOT EXISTS ${
|
|
70
|
+
`};return W(G),new Promise(async(M)=>$=M);async function X({highWaterMark:M=16384,start:Q=0,end:K=1/0}={}){let B=K-Q;return Q&&await G.seek(Q),new v5.Readable({highWaterMark:M,async read(V){let v=V>B?V-B:V;B-=V;let[{data:q}]=await G.read(v);if(this.push(q),q.length<V)this.push(null)}})}async function O({highWaterMark:M=16384,start:Q=0}={}){return Q&&await G.seek(Q),new v5.Writable({highWaterMark:M,write(K,B,V){G.write(K).then(()=>V(),V)}})}}).catch(J)})}Object.assign(b1,{PostgresError:AF,toPascal:q0,pascal:_8,toCamel:P0,camel:T8,toKebab:j0,kebab:F8,fromPascal:MW,fromCamel:UW,fromKebab:wW,BigInt:{to:20,from:[20],parse:(T)=>BigInt(T),serialize:(T)=>T.toString()}});var OF=b1;function b1(T,_){let F=j3(T,_),W=F.no_subscribe||Z8(b1,{...F}),J=!1,Y=R_(),$=R_(),Z=R_(),G=R_(),X=R_(),O=R_(),M=R_(),Q=R_(),K={connecting:$,reserved:Z,closed:G,ended:X,open:O,busy:M,full:Q},B=[...Array(F.max)].map(()=>$8(F,K,{onopen:I_,onend:H_,onclose:b0})),V=v(ST);return Object.assign(V,{get parameters(){return F.parameters},largeObject:X8.bind(null,V),subscribe:W,CLOSE:GF,END:GF,PostgresError:AF,options:F,reserve:y,listen:q,begin:u,close:i,end:ZT}),V;function v(L){return L.debug=F.debug,Object.entries(F.types).reduce((n,[YT,NT])=>{return n[YT]=(VT)=>new u_(VT,NT.to),n},o),Object.assign(JT,{types:o,typed:o,unsafe:zT,notify:j,array:t,json:p,file:kT}),JT;function o(n,YT){return new u_(n,YT)}function JT(n,...YT){return n&&Array.isArray(n.raw)?new S_(n,YT,L,D):typeof n==="string"&&!YT.length?new QW(F.transform.column.to?F.transform.column.to(n):n):new P1(n,YT)}function zT(n,YT=[],NT={}){return arguments.length===2&&!Array.isArray(YT)&&(NT=YT,YT=[]),new S_([n],YT,L,D,{prepare:!1,...NT,simple:"simple"in NT?NT.simple:YT.length===0})}function kT(n,YT=[],NT={}){return arguments.length===2&&!Array.isArray(YT)&&(NT=YT,YT=[]),new S_([],YT,(wT)=>{q3.readFile(n,"utf8",(gT,HT)=>{if(gT)return wT.reject(gT);wT.strings=[HT],L(wT)})},D,{...NT,simple:"simple"in NT?NT.simple:YT.length===0})}}async function q(L,o,JT){let zT={fn:o,onlisten:JT},kT=q.sql||(q.sql=b1({...F,max:1,idle_timeout:null,max_lifetime:null,fetch_types:!1,onclose(){Object.entries(q.channels).forEach(([wT,{listeners:gT}])=>{delete q.channels[wT],Promise.all(gT.map((HT)=>q(wT,HT.fn,HT.onlisten).catch(()=>{})))})},onnotify(wT,gT){wT in q.channels&&q.channels[wT].listeners.forEach((HT)=>HT.fn(gT))}})),n=q.channels||(q.channels={});if(L in n){n[L].listeners.push(zT);let wT=await n[L].result;return zT.onlisten&&zT.onlisten(),{state:wT.state,unlisten:VT}}n[L]={result:kT`listen ${kT.unsafe('"'+L.replace(/"/g,'""')+'"')}`,listeners:[zT]};let NT=await n[L].result;return zT.onlisten&&zT.onlisten(),{state:NT.state,unlisten:VT};async function VT(){if(L in n===!1)return;if(n[L].listeners=n[L].listeners.filter((wT)=>wT!==zT),n[L].listeners.length)return;return delete n[L],kT`unlisten ${kT.unsafe('"'+L.replace(/"/g,'""')+'"')}`}}async function j(L,o){return await V`select pg_notify(${L}, ${""+o})`}async function y(){let L=R_(),o=O.length?O.shift():await new Promise((kT,n)=>{let YT={reserve:kT,reject:n};Y.push(YT),G.length&&bT(G.shift(),YT)});h(o,Z),o.reserved=()=>L.length?o.execute(L.shift()):h(o,Z),o.reserved.release=!0;let JT=v(zT);return JT.release=()=>{o.reserved=null,I_(o)},JT;function zT(kT){o.queue===Q?L.push(kT):o.execute(kT)||h(o,Q)}}async function u(L,o){!o&&(o=L,L="");let JT=R_(),zT=0,kT,n=null;try{return await V.unsafe("begin "+L.replace(/[^a-z ]/ig,""),[],{onexecute:NT}).execute(),await Promise.race([YT(kT,o),new Promise((VT,wT)=>kT.onclose=wT)])}catch(VT){throw VT}async function YT(VT,wT,gT){let HT=v(fT);HT.savepoint=F0,HT.prepare=(QT)=>n=QT.replace(/[^a-z0-9$-_. ]/gi);let N_,hT;gT&&await HT`savepoint ${HT(gT)}`;try{if(hT=await new Promise((QT,C_)=>{let x_=wT(HT);Promise.resolve(Array.isArray(x_)?Promise.all(x_):x_).then(QT,C_)}),N_)throw N_}catch(QT){throw await(gT?HT`rollback to ${HT(gT)}`:HT`rollback`),QT instanceof AF&&QT.code==="25P02"&&N_||QT}if(!gT)n?await HT`prepare transaction '${HT.unsafe(n)}'`:await HT`commit`;return hT;function F0(QT,C_){if(QT&&Array.isArray(QT.raw))return F0((x_)=>x_.apply(x_,arguments));return arguments.length===1&&(C_=QT,QT=null),YT(VT,C_,"s"+zT+++(QT?"_"+QT:""))}function fT(QT){QT.catch((C_)=>N_||(N_=C_)),VT.queue===Q?JT.push(QT):VT.execute(QT)||h(VT,Q)}}function NT(VT){kT=VT,h(VT,Z),VT.reserved=()=>JT.length?VT.execute(JT.shift()):h(VT,Z)}}function h(L,o){return L.queue.remove(L),o.push(L),L.queue=o,o===O?L.idleTimer.start():L.idleTimer.cancel(),L}function p(L){return new u_(L,3802)}function t(L,o){if(!Array.isArray(L))return t(Array.from(arguments));return new u_(L,o||(L.length?k1(L)||25:0),F.shared.typeArrayMap)}function ST(L){if(J)return L.reject(BT.connection("CONNECTION_ENDED",F,F));if(O.length)return A_(O.shift(),L);if(G.length)return bT(G.shift(),L);M.length?A_(M.shift(),L):Y.push(L)}function A_(L,o){return L.execute(o)?h(L,M):h(L,Q)}function D(L){return new Promise((o,JT)=>{L.state?L.active?$8(F).cancel(L.state,o,JT):L.cancelled={resolve:o,reject:JT}:(Y.remove(L),L.cancelled=!0,L.reject(BT.generic("57014","canceling statement due to user request")),o())})}async function ZT({timeout:L=null}={}){if(J)return J;await 1;let o;return J=Promise.race([new Promise((JT)=>L!==null&&(o=setTimeout(TT,L*1000,JT))),Promise.all(B.map((JT)=>JT.end()).concat(q.sql?q.sql.end({timeout:0}):[],W.sql?W.sql.end({timeout:0}):[]))]).then(()=>clearTimeout(o))}async function i(){await Promise.all(B.map((L)=>L.end()))}async function TT(L){await Promise.all(B.map((o)=>o.terminate()));while(Y.length)Y.shift().reject(BT.connection("CONNECTION_DESTROYED",F));L()}function bT(L,o){return h(L,$),L.connect(o),L}function H_(L){h(L,X)}function I_(L){if(Y.length===0)return h(L,O);let o=Math.ceil(Y.length/($.length+1)),JT=!0;while(JT&&Y.length&&o-- >0){let zT=Y.shift();if(zT.reserve)return zT.reserve(L);JT=L.execute(zT)}JT?h(L,M):h(L,Q)}function b0(L,o){h(L,G),L.reserved=null,L.onclose&&(L.onclose(o),L.onclose=null),F.onclose&&F.onclose(L.id),Y.length&&bT(L,Y.shift())}}function j3(T,_){if(T&&T.shared)return T;let F=process.env,W=(!T||typeof T==="string"?_:T)||{},{url:J,multihost:Y}=h3(T),$=[...J.searchParams].reduce((Q,[K,B])=>(Q[K]=B,Q),{}),Z=W.hostname||W.host||Y||J.hostname||F.PGHOST||"localhost",G=W.port||J.port||F.PGPORT||5432,X=W.user||W.username||J.username||F.PGUSERNAME||F.PGUSER||p3();W.no_prepare&&(W.prepare=!1),$.sslmode&&($.ssl=$.sslmode,delete $.sslmode),"timeout"in W&&(console.log("The timeout option is deprecated, use idle_timeout instead"),W.idle_timeout=W.timeout),$.sslrootcert==="system"&&($.ssl="verify-full");let O=["idle_timeout","connect_timeout","max_lifetime","max_pipeline","backoff","keep_alive"],M={max:10,ssl:!1,idle_timeout:null,connect_timeout:30,max_lifetime:x3,max_pipeline:100,backoff:v3,keep_alive:60,prepare:!0,debug:!1,fetch_types:!0,publications:"alltables",target_session_attrs:null};return{host:Array.isArray(Z)?Z:Z.split(",").map((Q)=>Q.split(":")[0]),port:Array.isArray(G)?G:Z.split(",").map((Q)=>parseInt(Q.split(":")[1]||G)),path:W.path||Z.indexOf("/")>-1&&Z+"/.s.PGSQL."+G,database:W.database||W.db||(J.pathname||"").slice(1)||F.PGDATABASE||X,user:X,pass:W.pass||W.password||J.password||F.PGPASSWORD||"",...Object.entries(M).reduce((Q,[K,B])=>{let V=K in W?W[K]:(K in $)?$[K]==="disable"||$[K]==="false"?!1:$[K]:F["PG"+K.toUpperCase()]||B;return Q[K]=typeof V==="string"&&O.includes(K)?+V:V,Q},{}),connection:{application_name:F.PGAPPNAME||"postgres.js",...W.connection,...Object.entries($).reduce((Q,[K,B])=>((K in M)||(Q[K]=B),Q),{})},types:W.types||{},target_session_attrs:y3(W,J,F),onnotice:W.onnotice,onnotify:W.onnotify,onclose:W.onclose,onparameter:W.onparameter,socket:W.socket,transform:b3(W.transform||{undefined:void 0}),parameters:{},shared:{retries:0,typeArrayMap:{}},...S5(W.types)}}function y3(T,_,F){let W=T.target_session_attrs||_.searchParams.get("target_session_attrs")||F.PGTARGETSESSIONATTRS;if(!W||["read-write","read-only","primary","standby","prefer-standby"].includes(W))return W;throw new Error("target_session_attrs "+W+" is not supported")}function v3(T){return(0.5+Math.random()/2)*Math.min(3**T/100,20)}function x3(){return 60*(30+Math.random()*30)}function b3(T){return{undefined:T.undefined,column:{from:typeof T.column==="function"?T.column:T.column&&T.column.from,to:T.column&&T.column.to},value:{from:typeof T.value==="function"?T.value:T.value&&T.value.from,to:T.value&&T.value.to},row:{from:typeof T.row==="function"?T.row:T.row&&T.row.from,to:T.row&&T.row.to}}}function h3(T){if(!T||typeof T!=="string")return{url:{searchParams:new Map}};let _=T;_=_.slice(_.indexOf("://")+3).split(/[?/]/)[0],_=decodeURIComponent(_.slice(_.indexOf("@")+1));let F=new URL(T.replace(_,_.split(",")[0]));return{url:{username:decodeURIComponent(F.username),password:decodeURIComponent(F.password),host:F.host,hostname:F.hostname,port:F.port,pathname:F.pathname,searchParams:F.searchParams},multihost:_.indexOf(",")>-1&&_}}function p3(){try{return P3.userInfo().username}catch(T){return process.env.USERNAME||process.env.USER||process.env.LOGNAME}}class DT{static[H]="SelectionProxyHandler";config;constructor(T){this.config={...T}}get(T,_){if(_==="_")return{...T._,selectedFields:new Proxy(T._.selectedFields,this)};if(_===MT)return{...T[MT],selectedFields:new Proxy(T[MT].selectedFields,this)};if(typeof _==="symbol")return T[_];let W=(R(T,IT)?T._.selectedFields:R(T,Z_)?T[MT].selectedFields:T)[_];if(R(W,k.Aliased)){if(this.config.sqlAliasedBehavior==="sql"&&!W.isSelectionField)return W.sql;let J=W.clone();return J.isSelectionField=!0,J}if(R(W,k)){if(this.config.sqlBehavior==="sql")return W;throw new Error(`You tried to reference "${_}" 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(R(W,GT)){if(this.config.alias)return new Proxy(W,new XF(new Proxy(W.table,new YW(this.config.alias,this.config.replaceOriginalName??!1))));return W}if(typeof W!=="object"||W===null)return W;return new Proxy(W,new DT(this.config))}}class x5{constructor(T,_){this.unique=T,this.name=_}static[H]="PgIndexBuilderOn";on(...T){return new h1(T.map((_)=>{if(R(_,k))return _;_=_;let F=new _W(_.name,!!_.keyAsName,_.columnType,_.indexConfig);return _.indexConfig=JSON.parse(JSON.stringify(_.defaultConfig)),F}),this.unique,!1,this.name)}onOnly(...T){return new h1(T.map((_)=>{if(R(_,k))return _;_=_;let F=new _W(_.name,!!_.keyAsName,_.columnType,_.indexConfig);return _.indexConfig=_.defaultConfig,F}),this.unique,!0,this.name)}using(T,..._){return new h1(_.map((F)=>{if(R(F,k))return F;F=F;let W=new _W(F.name,!!F.keyAsName,F.columnType,F.indexConfig);return F.indexConfig=JSON.parse(JSON.stringify(F.defaultConfig)),W}),this.unique,!0,this.name,T)}}class h1{static[H]="PgIndexBuilder";config;constructor(T,_,F,W,J="btree"){this.config={name:W,columns:T,unique:_,only:F,method:J}}concurrently(){return this.config.concurrently=!0,this}with(T){return this.config.with=T,this}where(T){return this.config.where=T,this}build(T){return new b5(this.config,T)}}class b5{static[H]="PgIndex";config;constructor(T,_){this.config={...T,table:_}}}function G8(T){return new x5(!0,T)}function g3(T){return(T.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).map((F)=>F.toLowerCase()).join("_")}function m3(T){return(T.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).reduce((F,W,J)=>{let Y=J===0?W.toLowerCase():`${W[0].toUpperCase()}${W.slice(1)}`;return F+Y},"")}function o3(T){return T}class A8{static[H]="CasingCache";cache={};cachedTables={};convert;constructor(T){this.convert=T==="snake_case"?g3:T==="camelCase"?m3:o3}getColumnCasing(T){if(!T.keyAsName)return T.name;let _=T.table[I.Symbol.Schema]??"public",F=T.table[I.Symbol.OriginalName],W=`${_}.${F}.${T.name}`;if(!this.cache[W])this.cacheTable(T.table);return this.cache[W]}cacheTable(T){let _=T[I.Symbol.Schema]??"public",F=T[I.Symbol.OriginalName],W=`${_}.${F}`;if(!this.cachedTables[W]){for(let J of Object.values(T[I.Symbol.Columns])){let Y=`${W}.${J.name}`;this.cache[Y]=this.convert(J.name)}this.cachedTables[W]=!0}}clearCache(){this.cache={},this.cachedTables={}}}class EW extends Z_{static[H]="PgViewBase"}class v0{static[H]="PgDialect";casing;constructor(T){this.casing=new A8(T?.casing)}async migrate(T,_,F){let W=typeof F==="string"?"__drizzle_migrations":F.migrationsTable??"__drizzle_migrations",J=typeof F==="string"?"drizzle":F.migrationsSchema??"drizzle",Y=U`
|
|
71
|
+
CREATE TABLE IF NOT EXISTS ${U.identifier(J)}.${U.identifier(W)} (
|
|
72
72
|
id SERIAL PRIMARY KEY,
|
|
73
73
|
hash text NOT NULL,
|
|
74
74
|
created_at bigint
|
|
75
75
|
)
|
|
76
|
-
`;await _.execute(O`CREATE SCHEMA IF NOT EXISTS ${O.identifier(J)}`),await _.execute(Y);let Z=(await _.all(O`select id, hash, created_at from ${O.identifier(J)}.${O.identifier(W)} order by created_at desc limit 1`))[0];await _.transaction(async(G)=>{for await(let X of T)if(!Z||Number(Z.created_at)<X.folderMillis){for(let U of X.sql)await G.execute(O.raw(U));await G.execute(O`insert into ${O.identifier(J)}.${O.identifier(W)} ("hash", "created_at") values(${X.hash}, ${X.folderMillis})`)}})}escapeName(T){return`"${T}"`}escapeParam(T){return`$${T+1}`}escapeString(T){return`'${T.replace(/'/g,"''")}'`}buildWithCTE(T){if(!T?.length)return;let _=[O`with `];for(let[F,W]of T.entries())if(_.push(O`${O.identifier(W._.alias)} as (${W._.sql})`),F<T.length-1)_.push(O`, `);return _.push(O` `),O.join(_)}buildDeleteQuery({table:T,where:_,returning:F,withList:W}){let J=this.buildWithCTE(W),Y=F?O` returning ${this.buildSelection(F,{isSingleTable:!0})}`:void 0,$=_?O` where ${_}`:void 0;return O`${J}delete from ${T}${$}${Y}`}buildUpdateSet(T,_){let F=T[B.Symbol.Columns],W=Object.keys(F).filter((Y)=>_[Y]!==void 0||F[Y]?.onUpdateFn!==void 0),J=W.length;return O.join(W.flatMap((Y,$)=>{let Z=F[Y],G=_[Y]??O.param(Z.onUpdateFn(),Z),X=O`${O.identifier(this.casing.getColumnCasing(Z))} = ${G}`;if($<J-1)return[X,O.raw(", ")];return[X]}))}buildUpdateQuery({table:T,set:_,where:F,returning:W,withList:J,from:Y,joins:$}){let Z=this.buildWithCTE(J),G=T[hT.Symbol.Name],X=T[hT.Symbol.Schema],U=T[hT.Symbol.OriginalName],M=G===U?void 0:G,Q=O`${X?O`${O.identifier(X)}.`:void 0}${O.identifier(U)}${M&&O` ${O.identifier(M)}`}`,V=this.buildUpdateSet(T,_),C=Y&&O.join([O.raw(" from "),this.buildFromTable(Y)]),K=this.buildJoins($),v=W?O` returning ${this.buildSelection(W,{isSingleTable:!Y})}`:void 0,P=F?O` where ${F}`:void 0;return O`${Z}update ${Q} set ${V}${C}${K}${P}${v}`}buildSelection(T,{isSingleTable:_=!1}={}){let F=T.length,W=T.flatMap(({field:J},Y)=>{let $=[];if(E(J,k.Aliased)&&J.isSelectionField)$.push(O.identifier(J.fieldAlias));else if(E(J,k.Aliased)||E(J,k)){let Z=E(J,k.Aliased)?J.sql:J;if(_)$.push(new k(Z.queryChunks.map((G)=>{if(E(G,S))return O.identifier(this.casing.getColumnCasing(G));return G})));else $.push(Z);if(E(J,k.Aliased))$.push(O` as ${O.identifier(J.fieldAlias)}`)}else if(E(J,XT))if(_)$.push(O.identifier(this.casing.getColumnCasing(J)));else $.push(J);if(Y<F-1)$.push(O`, `);return $});return O.join(W)}buildJoins(T){if(!T||T.length===0)return;let _=[];for(let[F,W]of T.entries()){if(F===0)_.push(O` `);let J=W.table,Y=W.lateral?O` lateral`:void 0,$=W.on?O` on ${W.on}`:void 0;if(E(J,hT)){let Z=J[hT.Symbol.Name],G=J[hT.Symbol.Schema],X=J[hT.Symbol.OriginalName],U=Z===X?void 0:W.alias;_.push(O`${O.raw(W.joinType)} join${Y} ${G?O`${O.identifier(G)}.`:void 0}${O.identifier(X)}${U&&O` ${O.identifier(U)}`}${$}`)}else if(E(J,Z_)){let Z=J[MT].name,G=J[MT].schema,X=J[MT].originalName,U=Z===X?void 0:W.alias;_.push(O`${O.raw(W.joinType)} join${Y} ${G?O`${O.identifier(G)}.`:void 0}${O.identifier(X)}${U&&O` ${O.identifier(U)}`}${$}`)}else _.push(O`${O.raw(W.joinType)} join${Y} ${J}${$}`);if(F<T.length-1)_.push(O` `)}return O.join(_)}buildFromTable(T){if(E(T,B)&&T[B.Symbol.IsAlias]){let _=O`${O.identifier(T[B.Symbol.OriginalName])}`;if(T[B.Symbol.Schema])_=O`${O.identifier(T[B.Symbol.Schema])}.${_}`;return O`${_} ${O.identifier(T[B.Symbol.Name])}`}return T}buildSelectQuery({withList:T,fields:_,fieldsFlat:F,where:W,having:J,table:Y,joins:$,orderBy:Z,groupBy:G,limit:X,offset:U,lockingClause:M,distinct:Q,setOperators:V}){let C=F??D_(_);for(let TT of C)if(E(TT.field,XT)&&vT(TT.field.table)!==(E(Y,jT)?Y._.alias:E(Y,wW)?Y[MT].name:E(Y,k)?void 0:vT(Y))&&!((bT)=>$?.some(({alias:A_})=>A_===(bT[B.Symbol.IsAlias]?vT(bT):bT[B.Symbol.BaseName])))(TT.field.table)){let bT=vT(TT.field.table);throw new Error(`Your "${TT.path.join("->")}" field references a column "${bT}"."${TT.field.name}", but the table "${bT}" is not part of the query! Did you forget to join it?`)}let K=!$||$.length===0,v=this.buildWithCTE(T),P;if(Q)P=Q===!0?O` distinct`:O` distinct on (${O.join(Q.on,O`, `)})`;let j=this.buildSelection(C,{isSingleTable:K}),y=this.buildFromTable(Y),u=this.buildJoins($),h=W?O` where ${W}`:void 0,p=J?O` having ${J}`:void 0,t;if(Z&&Z.length>0)t=O` order by ${O.join(Z,O`, `)}`;let ST;if(G&&G.length>0)ST=O` group by ${O.join(G,O`, `)}`;let H_=typeof X==="object"||typeof X==="number"&&X>=0?O` limit ${X}`:void 0,L=U?O` offset ${U}`:void 0,$T=O.empty();if(M){let TT=O` for ${O.raw(M.strength)}`;if(M.config.of)TT.append(O` of ${O.join(Array.isArray(M.config.of)?M.config.of:[M.config.of],O`, `)}`);if(M.config.noWait)TT.append(O` nowait`);else if(M.config.skipLocked)TT.append(O` skip locked`);$T.append(TT)}let i=O`${v}select${P} ${j} from ${y}${u}${h}${ST}${p}${t}${H_}${L}${$T}`;if(V.length>0)return this.buildSetOperations(i,V);return i}buildSetOperations(T,_){let[F,...W]=_;if(!F)throw new Error("Cannot pass undefined values to any set operator");if(W.length===0)return this.buildSetOperationQuery({leftSelect:T,setOperator:F});return this.buildSetOperations(this.buildSetOperationQuery({leftSelect:T,setOperator:F}),W)}buildSetOperationQuery({leftSelect:T,setOperator:{type:_,isAll:F,rightSelect:W,limit:J,orderBy:Y,offset:$}}){let Z=O`(${T.getSQL()}) `,G=O`(${W.getSQL()})`,X;if(Y&&Y.length>0){let V=[];for(let C of Y)if(E(C,S))V.push(O.identifier(C.name));else if(E(C,k)){for(let K=0;K<C.queryChunks.length;K++){let v=C.queryChunks[K];if(E(v,S))C.queryChunks[K]=O.identifier(v.name)}V.push(O`${C}`)}else V.push(O`${C}`);X=O` order by ${O.join(V,O`, `)} `}let U=typeof J==="object"||typeof J==="number"&&J>=0?O` limit ${J}`:void 0,M=O.raw(`${_} ${F?"all ":""}`),Q=$?O` offset ${$}`:void 0;return O`${Z}${M}${G}${X}${U}${Q}`}buildInsertQuery({table:T,values:_,onConflict:F,returning:W,withList:J,select:Y,overridingSystemValue_:$}){let Z=[],G=T[B.Symbol.Columns],X=Object.entries(G).filter(([v,P])=>!P.shouldDisableInsert()),U=X.map(([,v])=>O.identifier(this.casing.getColumnCasing(v)));if(Y){let v=_;if(E(v,k))Z.push(v);else Z.push(v.getSQL())}else{let v=_;Z.push(O.raw("values "));for(let[P,j]of v.entries()){let y=[];for(let[u,h]of X){let p=j[u];if(p===void 0||E(p,Q_)&&p.value===void 0)if(h.defaultFn!==void 0){let t=h.defaultFn(),ST=E(t,k)?t:O.param(t,h);y.push(ST)}else if(!h.default&&h.onUpdateFn!==void 0){let t=h.onUpdateFn(),ST=E(t,k)?t:O.param(t,h);y.push(ST)}else y.push(O`default`);else y.push(p)}if(Z.push(y),P<v.length-1)Z.push(O`, `)}}let M=this.buildWithCTE(J),Q=O.join(Z),V=W?O` returning ${this.buildSelection(W,{isSingleTable:!0})}`:void 0,C=F?O` on conflict ${F}`:void 0,K=$===!0?O`overriding system value `:void 0;return O`${M}insert into ${T} ${U} ${K}${Q}${C}${V}`}buildRefreshMaterializedViewQuery({view:T,concurrently:_,withNoData:F}){let W=_?O` concurrently`:void 0,J=F?O` with no data`:void 0;return O`refresh materialized view${W} ${T}${J}`}prepareTyping(T){if(E(T,Q1)||E(T,w1))return"json";else if(E(T,z1))return"decimal";else if(E(T,E1))return"time";else if(E(T,R1)||E(T,K1))return"timestamp";else if(E(T,O1)||E(T,M1))return"date";else if(E(T,V1))return"uuid";else return"none"}sqlToQuery(T,_){return T.toQuery({casing:this.casing,escapeName:this.escapeName,escapeParam:this.escapeParam,escapeString:this.escapeString,prepareTyping:this.prepareTyping,invokeSource:_})}buildRelationalQueryWithoutPK({fullSchema:T,schema:_,tableNamesMap:F,table:W,tableConfig:J,queryConfig:Y,tableAlias:$,nestedQueryRelation:Z,joinOn:G}){let X=[],U,M,Q=[],V,C=[];if(Y===!0)X=Object.entries(J.columns).map(([P,j])=>({dbKey:j.name,tsKey:P,field:m_(j,$),relationTableTsKey:void 0,isJson:!1,selection:[]}));else{let v=Object.fromEntries(Object.entries(J.columns).map(([p,t])=>[p,m_(t,$)]));if(Y.where){let p=typeof Y.where==="function"?Y.where(v,Z5()):Y.where;V=p&&WW(p,$)}let P=[],j=[];if(Y.columns){let p=!1;for(let[t,ST]of Object.entries(Y.columns)){if(ST===void 0)continue;if(t in J.columns){if(!p&&ST===!0)p=!0;j.push(t)}}if(j.length>0)j=p?j.filter((t)=>Y.columns?.[t]===!0):Object.keys(J.columns).filter((t)=>!j.includes(t))}else j=Object.keys(J.columns);for(let p of j){let t=J.columns[p];P.push({tsKey:p,value:t})}let y=[];if(Y.with)y=Object.entries(Y.with).filter((p)=>!!p[1]).map(([p,t])=>({tsKey:p,queryConfig:t,relation:J.relations[p]}));let u;if(Y.extras){u=typeof Y.extras==="function"?Y.extras(v,{sql:O}):Y.extras;for(let[p,t]of Object.entries(u))P.push({tsKey:p,value:v4(t,$)})}for(let{tsKey:p,value:t}of P)X.push({dbKey:E(t,k.Aliased)?t.fieldAlias:J.columns[p].name,tsKey:p,field:E(t,XT)?m_(t,$):t,relationTableTsKey:void 0,isJson:!1,selection:[]});let h=typeof Y.orderBy==="function"?Y.orderBy(v,X5()):Y.orderBy??[];if(!Array.isArray(h))h=[h];Q=h.map((p)=>{if(E(p,XT))return m_(p,$);return WW(p,$)}),U=Y.limit,M=Y.offset;for(let{tsKey:p,queryConfig:t,relation:ST}of y){let H_=H5(_,F,ST),L=C0(ST.referencedTable),$T=F[L],i=`${$}_${p}`,TT=XW(...H_.fields.map((I_,y0)=>D1(m_(H_.references[y0],i),m_(I_,$)))),bT=this.buildRelationalQueryWithoutPK({fullSchema:T,schema:_,tableNamesMap:F,table:T[$T],tableConfig:_[$T],queryConfig:E(ST,R0)?t===!0?{limit:1}:{...t,limit:1}:t,tableAlias:i,joinOn:TT,nestedQueryRelation:ST}),A_=O`${O.identifier(i)}.${O.identifier("data")}`.as(p);C.push({on:O`true`,table:new jT(bT.sql,{},i),alias:i,joinType:"left",lateral:!0}),X.push({dbKey:p,tsKey:p,field:A_,relationTableTsKey:$T,isJson:!0,selection:bT.selection})}}if(X.length===0)throw new A1({message:`No fields selected for table "${J.tsName}" ("${$}")`});let K;if(V=XW(G,V),Z){let v=O`json_build_array(${O.join(X.map(({field:y,tsKey:u,isJson:h})=>h?O`${O.identifier(`${$}_${u}`)}.${O.identifier("data")}`:E(y,k.Aliased)?y.sql:y),O`, `)})`;if(E(Z,GW))v=O`coalesce(json_agg(${v}${Q.length>0?O` order by ${O.join(Q,O`, `)}`:void 0}), '[]'::json)`;let P=[{dbKey:"data",tsKey:"data",field:v.as("data"),isJson:!0,relationTableTsKey:J.tsName,selection:X}];if(U!==void 0||M!==void 0||Q.length>0)K=this.buildSelectQuery({table:H1(W,$),fields:{},fieldsFlat:[{path:[],field:O.raw("*")}],where:V,limit:U,offset:M,orderBy:Q,setOperators:[]}),V=void 0,U=void 0,M=void 0,Q=[];else K=H1(W,$);K=this.buildSelectQuery({table:E(K,hT)?K:new jT(K,{},$),fields:{},fieldsFlat:P.map(({field:y})=>({path:[],field:E(y,XT)?m_(y,$):y})),joins:C,where:V,limit:U,offset:M,orderBy:Q,setOperators:[]})}else K=this.buildSelectQuery({table:H1(W,$),fields:{},fieldsFlat:X.map(({field:v})=>({path:[],field:E(v,XT)?m_(v,$):v})),joins:C,where:V,limit:U,offset:M,orderBy:Q,setOperators:[]});return{tableTsKey:J.tsName,sql:K,selection:X}}}class Z8{static[A]="TypedQueryBuilder";getSelectedFields(){return this._.selectedFields}}class eT{static[A]="PgSelectBuilder";fields;session;dialect;withList=[];distinct;constructor(T){if(this.fields=T.fields,this.session=T.session,this.dialect=T.dialect,T.withList)this.withList=T.withList;this.distinct=T.distinct}authToken;setToken(T){return this.authToken=T,this}from(T){let _=!!this.fields,F=T,W;if(this.fields)W=this.fields;else if(E(F,jT))W=Object.fromEntries(Object.keys(F._.selectedFields).map((J)=>[J,F[J]]));else if(E(F,wW))W=F[MT].selectedFields;else if(E(F,k))W={};else W=g$(F);return new X8({table:F,fields:W,isPartialSelect:_,session:this.session,dialect:this.dialect,withList:this.withList,distinct:this.distinct}).setToken(this.authToken)}}class P5 extends Z8{static[A]="PgSelectQueryBuilder";_;config;joinsNotNullableMap;tableName;isPartialSelect;session;dialect;constructor({table:T,fields:_,isPartialSelect:F,session:W,dialect:J,withList:Y,distinct:$}){super();this.config={withList:Y,table:T,fields:{..._},distinct:$,setOperators:[]},this.isPartialSelect=F,this.session=W,this.dialect=J,this._={selectedFields:_},this.tableName=a_(T),this.joinsNotNullableMap=typeof this.tableName==="string"?{[this.tableName]:!0}:{}}createJoin(T,_){return(F,W)=>{let J=this.tableName,Y=a_(F);if(typeof Y==="string"&&this.config.joins?.some(($)=>$.alias===Y))throw new Error(`Alias "${Y}" is already used in this query`);if(!this.isPartialSelect){if(Object.keys(this.joinsNotNullableMap).length===1&&typeof J==="string")this.config.fields={[J]:this.config.fields};if(typeof Y==="string"&&!E(F,k)){let $=E(F,jT)?F._.selectedFields:E(F,Z_)?F[MT].selectedFields:F[B.Symbol.Columns];this.config.fields[Y]=$}}if(typeof W==="function")W=W(new Proxy(this.config.fields,new LT({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));if(!this.config.joins)this.config.joins=[];if(this.config.joins.push({on:W,table:F,joinType:T,alias:Y,lateral:_}),typeof Y==="string")switch(T){case"left":{this.joinsNotNullableMap[Y]=!1;break}case"right":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([$])=>[$,!1])),this.joinsNotNullableMap[Y]=!0;break}case"cross":case"inner":{this.joinsNotNullableMap[Y]=!0;break}case"full":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([$])=>[$,!1])),this.joinsNotNullableMap[Y]=!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(T,_){return(F)=>{let W=typeof F==="function"?F(h3()):F;if(!JW(this.getSelectedFields(),W.getSelectedFields()))throw new Error("Set operator error (union / intersect / except): selected fields are not the same or are in a different order");return this.config.setOperators.push({type:T,isAll:_,rightSelect:W}),this}}union=this.createSetOperator("union",!1);unionAll=this.createSetOperator("union",!0);intersect=this.createSetOperator("intersect",!1);intersectAll=this.createSetOperator("intersect",!0);except=this.createSetOperator("except",!1);exceptAll=this.createSetOperator("except",!0);addSetOperators(T){return this.config.setOperators.push(...T),this}where(T){if(typeof T==="function")T=T(new Proxy(this.config.fields,new LT({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));return this.config.where=T,this}having(T){if(typeof T==="function")T=T(new Proxy(this.config.fields,new LT({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));return this.config.having=T,this}groupBy(...T){if(typeof T[0]==="function"){let _=T[0](new Proxy(this.config.fields,new LT({sqlAliasedBehavior:"alias",sqlBehavior:"sql"})));this.config.groupBy=Array.isArray(_)?_:[_]}else this.config.groupBy=T;return this}orderBy(...T){if(typeof T[0]==="function"){let _=T[0](new Proxy(this.config.fields,new LT({sqlAliasedBehavior:"alias",sqlBehavior:"sql"}))),F=Array.isArray(_)?_:[_];if(this.config.setOperators.length>0)this.config.setOperators.at(-1).orderBy=F;else this.config.orderBy=F}else{let _=T;if(this.config.setOperators.length>0)this.config.setOperators.at(-1).orderBy=_;else this.config.orderBy=_}return this}limit(T){if(this.config.setOperators.length>0)this.config.setOperators.at(-1).limit=T;else this.config.limit=T;return this}offset(T){if(this.config.setOperators.length>0)this.config.setOperators.at(-1).offset=T;else this.config.offset=T;return this}for(T,_={}){return this.config.lockingClause={strength:T,config:_},this}getSQL(){return this.dialect.buildSelectQuery(this.config)}toSQL(){let{typings:T,..._}=this.dialect.sqlToQuery(this.getSQL());return _}as(T){return new Proxy(new jT(this.getSQL(),this.config.fields,T),new LT({alias:T,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}getSelectedFields(){return new Proxy(this.config.fields,new LT({alias:this.tableName,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}$dynamic(){return this}}class X8 extends P5{static[A]="PgSelect";_prepare(T){let{session:_,config:F,dialect:W,joinsNotNullableMap:J,authToken:Y}=this;if(!_)throw new Error("Cannot execute a query on a query builder. Please use a database instance instead.");return GT.startActiveSpan("drizzle.prepareQuery",()=>{let $=D_(F.fields),Z=_.prepareQuery(W.sqlToQuery(this.getSQL()),$,T,!0);return Z.joinsNotNullableMap=J,Z.setToken(Y)})}prepare(T){return this._prepare(T)}authToken;setToken(T){return this.authToken=T,this}execute=(T)=>{return GT.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(T,this.authToken)})}}p$(X8,[sT]);function HF(T,_){return(F,W,...J)=>{let Y=[W,...J].map(($)=>({type:T,isAll:_,rightSelect:$}));for(let $ of Y)if(!JW(F.getSelectedFields(),$.rightSelect.getSelectedFields()))throw new Error("Set operator error (union / intersect / except): selected fields are not the same or are in a different order");return F.addSetOperators(Y)}}var h3=()=>({union:p3,unionAll:g3,intersect:m3,intersectAll:o3,except:u3,exceptAll:c3}),p3=HF("union",!1),g3=HF("union",!0),m3=HF("intersect",!1),o3=HF("intersect",!0),u3=HF("except",!1),c3=HF("except",!0);class QW{static[A]="PgQueryBuilder";dialect;dialectConfig;constructor(T){this.dialect=E(T,P0)?T:void 0,this.dialectConfig=E(T,P0)?void 0:T}$with=(T,_)=>{let F=this;return{as:(J)=>{if(typeof J==="function")J=J(F);return new Proxy(new TW(J.getSQL(),_??("getSelectedFields"in J?J.getSelectedFields()??{}:{}),T,!0),new LT({alias:T,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}};with(...T){let _=this;function F(Y){return new eT({fields:Y??void 0,session:void 0,dialect:_.getDialect(),withList:T})}function W(Y){return new eT({fields:Y??void 0,session:void 0,dialect:_.getDialect(),distinct:!0})}function J(Y,$){return new eT({fields:$??void 0,session:void 0,dialect:_.getDialect(),distinct:{on:Y}})}return{select:F,selectDistinct:W,selectDistinctOn:J}}select(T){return new eT({fields:T??void 0,session:void 0,dialect:this.getDialect()})}selectDistinct(T){return new eT({fields:T??void 0,session:void 0,dialect:this.getDialect(),distinct:!0})}selectDistinctOn(T,_){return new eT({fields:_??void 0,session:void 0,dialect:this.getDialect(),distinct:{on:T}})}getDialect(){if(!this.dialect)this.dialect=new P0(this.dialectConfig);return this.dialect}}class b1{constructor(T,_,F,W,J){this.table=T,this.session=_,this.dialect=F,this.withList=W,this.overridingSystemValue_=J}static[A]="PgInsertBuilder";authToken;setToken(T){return this.authToken=T,this}overridingSystemValue(){return this.overridingSystemValue_=!0,this}values(T){if(T=Array.isArray(T)?T:[T],T.length===0)throw new Error("values() must be called with at least one value");let _=T.map((F)=>{let W={},J=this.table[B.Symbol.Columns];for(let Y of Object.keys(F)){let $=F[Y];W[Y]=E($,k)?$:new Q_($,J[Y])}return W});return new G8(this.table,_,this.session,this.dialect,this.withList,!1,this.overridingSystemValue_).setToken(this.authToken)}select(T){let _=typeof T==="function"?T(new QW):T;if(!E(_,k)&&!JW(this.table[X1],_._.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 G8(this.table,_,this.session,this.dialect,this.withList,!0)}}class G8 extends sT{constructor(T,_,F,W,J,Y,$){super();this.session=F,this.dialect=W,this.config={table:T,values:_,withList:J,select:Y,overridingSystemValue_:$}}static[A]="PgInsert";config;returning(T=this.config.table[B.Symbol.Columns]){return this.config.returningFields=T,this.config.returning=D_(T),this}onConflictDoNothing(T={}){if(T.target===void 0)this.config.onConflict=O`do nothing`;else{let _="";_=Array.isArray(T.target)?T.target.map((W)=>this.dialect.escapeName(this.dialect.casing.getColumnCasing(W))).join(","):this.dialect.escapeName(this.dialect.casing.getColumnCasing(T.target));let F=T.where?O` where ${T.where}`:void 0;this.config.onConflict=O`(${O.raw(_)})${F} do nothing`}return this}onConflictDoUpdate(T){if(T.where&&(T.targetWhere||T.setWhere))throw new Error('You cannot use both "where" and "targetWhere"/"setWhere" at the same time - "where" is deprecated, use "targetWhere" or "setWhere" instead.');let _=T.where?O` where ${T.where}`:void 0,F=T.targetWhere?O` where ${T.targetWhere}`:void 0,W=T.setWhere?O` where ${T.setWhere}`:void 0,J=this.dialect.buildUpdateSet(this.config.table,U1(this.config.table,T.set)),Y="";return Y=Array.isArray(T.target)?T.target.map(($)=>this.dialect.escapeName(this.dialect.casing.getColumnCasing($))).join(","):this.dialect.escapeName(this.dialect.casing.getColumnCasing(T.target)),this.config.onConflict=O`(${O.raw(Y)})${F} do update set ${J}${_}${W}`,this}getSQL(){return this.dialect.buildInsertQuery(this.config)}toSQL(){let{typings:T,..._}=this.dialect.sqlToQuery(this.getSQL());return _}_prepare(T){return GT.startActiveSpan("drizzle.prepareQuery",()=>{return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,T,!0)})}prepare(T){return this._prepare(T)}authToken;setToken(T){return this.authToken=T,this}execute=(T)=>{return GT.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(T,this.authToken)})};getSelectedFields(){return this.config.returningFields?new Proxy(this.config.returningFields,new LT({alias:vT(this.config.table),sqlAliasedBehavior:"alias",sqlBehavior:"error"})):void 0}$dynamic(){return this}}class H8 extends sT{constructor(T,_,F){super();this.session=_,this.dialect=F,this.config={view:T}}static[A]="PgRefreshMaterializedView";config;concurrently(){if(this.config.withNoData!==void 0)throw new Error("Cannot use concurrently and withNoData together");return this.config.concurrently=!0,this}withNoData(){if(this.config.concurrently!==void 0)throw new Error("Cannot use concurrently and withNoData together");return this.config.withNoData=!0,this}getSQL(){return this.dialect.buildRefreshMaterializedViewQuery(this.config)}toSQL(){let{typings:T,..._}=this.dialect.sqlToQuery(this.getSQL());return _}_prepare(T){return GT.startActiveSpan("drizzle.prepareQuery",()=>{return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),void 0,T,!0)})}prepare(T){return this._prepare(T)}authToken;setToken(T){return this.authToken=T,this}execute=(T)=>{return GT.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(T,this.authToken)})}}class x1{constructor(T,_,F,W){this.table=T,this.session=_,this.dialect=F,this.withList=W}static[A]="PgUpdateBuilder";authToken;setToken(T){return this.authToken=T,this}set(T){return new j5(this.table,U1(this.table,T),this.session,this.dialect,this.withList).setToken(this.authToken)}}class j5 extends sT{constructor(T,_,F,W,J){super();this.session=F,this.dialect=W,this.config={set:_,table:T,withList:J,joins:[]},this.tableName=a_(T),this.joinsNotNullableMap=typeof this.tableName==="string"?{[this.tableName]:!0}:{}}static[A]="PgUpdate";config;tableName;joinsNotNullableMap;from(T){let _=T,F=a_(_);if(typeof F==="string")this.joinsNotNullableMap[F]=!0;return this.config.from=_,this}getTableLikeFields(T){if(E(T,hT))return T[B.Symbol.Columns];else if(E(T,jT))return T._.selectedFields;return T[MT].selectedFields}createJoin(T){return(_,F)=>{let W=a_(_);if(typeof W==="string"&&this.config.joins.some((J)=>J.alias===W))throw new Error(`Alias "${W}" is already used in this query`);if(typeof F==="function"){let J=this.config.from&&!E(this.config.from,k)?this.getTableLikeFields(this.config.from):void 0;F=F(new Proxy(this.config.table[B.Symbol.Columns],new LT({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})),J&&new Proxy(J,new LT({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})))}if(this.config.joins.push({on:F,table:_,joinType:T,alias:W}),typeof W==="string")switch(T){case"left":{this.joinsNotNullableMap[W]=!1;break}case"right":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([J])=>[J,!1])),this.joinsNotNullableMap[W]=!0;break}case"inner":{this.joinsNotNullableMap[W]=!0;break}case"full":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([J])=>[J,!1])),this.joinsNotNullableMap[W]=!1;break}}return this}}leftJoin=this.createJoin("left");rightJoin=this.createJoin("right");innerJoin=this.createJoin("inner");fullJoin=this.createJoin("full");where(T){return this.config.where=T,this}returning(T){if(!T){if(T=Object.assign({},this.config.table[B.Symbol.Columns]),this.config.from){let _=a_(this.config.from);if(typeof _==="string"&&this.config.from&&!E(this.config.from,k)){let F=this.getTableLikeFields(this.config.from);T[_]=F}for(let F of this.config.joins){let W=a_(F.table);if(typeof W==="string"&&!E(F.table,k)){let J=this.getTableLikeFields(F.table);T[W]=J}}}}return this.config.returningFields=T,this.config.returning=D_(T),this}getSQL(){return this.dialect.buildUpdateQuery(this.config)}toSQL(){let{typings:T,..._}=this.dialect.sqlToQuery(this.getSQL());return _}_prepare(T){let _=this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,T,!0);return _.joinsNotNullableMap=this.joinsNotNullableMap,_}prepare(T){return this._prepare(T)}authToken;setToken(T){return this.authToken=T,this}execute=(T)=>{return this._prepare().execute(T,this.authToken)};getSelectedFields(){return this.config.returningFields?new Proxy(this.config.returningFields,new LT({alias:vT(this.config.table),sqlAliasedBehavior:"alias",sqlBehavior:"error"})):void 0}$dynamic(){return this}}class zW extends k{constructor(T){super(zW.buildEmbeddedCount(T.source,T.filters).queryChunks);this.params=T,this.mapWith(Number),this.session=T.session,this.sql=zW.buildCount(T.source,T.filters)}sql;token;static[A]="PgCountBuilder";[Symbol.toStringTag]="PgCountBuilder";session;static buildEmbeddedCount(T,_){return O`(select count(*) from ${T}${O.raw(" where ").if(_)}${_})`}static buildCount(T,_){return O`select count(*) as count from ${T}${O.raw(" where ").if(_)}${_};`}setToken(T){return this.token=T,this}then(T,_){return Promise.resolve(this.session.count(this.sql,this.token)).then(T,_)}catch(T){return this.then(void 0,T)}finally(T){return this.then((_)=>{return T?.(),_},(_)=>{throw T?.(),_})}}class U8{constructor(T,_,F,W,J,Y,$){this.fullSchema=T,this.schema=_,this.tableNamesMap=F,this.table=W,this.tableConfig=J,this.dialect=Y,this.session=$}static[A]="PgRelationalQueryBuilder";findMany(T){return new A8(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,T?T:{},"many")}findFirst(T){return new A8(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,T?{...T,limit:1}:{limit:1},"first")}}class A8 extends sT{constructor(T,_,F,W,J,Y,$,Z,G){super();this.fullSchema=T,this.schema=_,this.tableNamesMap=F,this.table=W,this.tableConfig=J,this.dialect=Y,this.session=$,this.config=Z,this.mode=G}static[A]="PgRelationalQuery";_prepare(T){return GT.startActiveSpan("drizzle.prepareQuery",()=>{let{query:_,builtQuery:F}=this._toSQL();return this.session.prepareQuery(F,void 0,T,!0,(W,J)=>{let Y=W.map(($)=>L1(this.schema,this.tableConfig,$,_.selection,J));if(this.mode==="first")return Y[0];return Y})})}prepare(T){return this._prepare(T)}_getQuery(){return this.dialect.buildRelationalQueryWithoutPK({fullSchema:this.fullSchema,schema:this.schema,tableNamesMap:this.tableNamesMap,table:this.table,tableConfig:this.tableConfig,queryConfig:this.config,tableAlias:this.tableConfig.tsName})}getSQL(){return this._getQuery().sql}_toSQL(){let T=this._getQuery(),_=this.dialect.sqlToQuery(T.sql);return{query:T,builtQuery:_}}toSQL(){return this._toSQL().builtQuery}authToken;setToken(T){return this.authToken=T,this}execute(){return GT.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(void 0,this.authToken)})}}class O8 extends sT{constructor(T,_,F,W){super();this.execute=T,this.sql=_,this.query=F,this.mapBatchResult=W}static[A]="PgRaw";getSQL(){return this.sql}getQuery(){return this.query}mapResult(T,_){return _?this.mapBatchResult(T):T}_prepare(){return this}isResponseInArrayMode(){return!1}}class EW{constructor(T,_,F){if(this.dialect=T,this.session=_,this._=F?{schema:F.schema,fullSchema:F.fullSchema,tableNamesMap:F.tableNamesMap,session:_}:{schema:void 0,fullSchema:{},tableNamesMap:{},session:_},this.query={},this._.schema)for(let[W,J]of Object.entries(this._.schema))this.query[W]=new U8(F.fullSchema,this._.schema,this._.tableNamesMap,F.fullSchema[W],J,T,_)}static[A]="PgDatabase";query;$with=(T,_)=>{let F=this;return{as:(J)=>{if(typeof J==="function")J=J(new QW(F.dialect));return new Proxy(new TW(J.getSQL(),_??("getSelectedFields"in J?J.getSelectedFields()??{}:{}),T,!0),new LT({alias:T,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}};$count(T,_){return new zW({source:T,filters:_,session:this.session})}with(...T){let _=this;function F(G){return new eT({fields:G??void 0,session:_.session,dialect:_.dialect,withList:T})}function W(G){return new eT({fields:G??void 0,session:_.session,dialect:_.dialect,withList:T,distinct:!0})}function J(G,X){return new eT({fields:X??void 0,session:_.session,dialect:_.dialect,withList:T,distinct:{on:G}})}function Y(G){return new x1(G,_.session,_.dialect,T)}function $(G){return new b1(G,_.session,_.dialect,T)}function Z(G){return new v1(G,_.session,_.dialect,T)}return{select:F,selectDistinct:W,selectDistinctOn:J,update:Y,insert:$,delete:Z}}select(T){return new eT({fields:T??void 0,session:this.session,dialect:this.dialect})}selectDistinct(T){return new eT({fields:T??void 0,session:this.session,dialect:this.dialect,distinct:!0})}selectDistinctOn(T,_){return new eT({fields:_??void 0,session:this.session,dialect:this.dialect,distinct:{on:T}})}update(T){return new x1(T,this.session,this.dialect)}insert(T){return new b1(T,this.session,this.dialect)}delete(T){return new v1(T,this.session,this.dialect)}refreshMaterializedView(T){return new H8(T,this.session,this.dialect)}authToken;execute(T){let _=typeof T==="string"?O.raw(T):T.getSQL(),F=this.dialect.sqlToQuery(_),W=this.session.prepareQuery(F,void 0,void 0,!1);return new O8(()=>W.execute(void 0,this.authToken),_,F,(J)=>W.mapResult(J,!0))}transaction(T,_){return this.session.transaction(T,_)}}class y5{constructor(T,_){this.unique=T,this.name=_}static[A]="PgIndexBuilderOn";on(...T){return new h1(T.map((_)=>{if(E(_,k))return _;_=_;let F=new aF(_.name,!!_.keyAsName,_.columnType,_.indexConfig);return _.indexConfig=JSON.parse(JSON.stringify(_.defaultConfig)),F}),this.unique,!1,this.name)}onOnly(...T){return new h1(T.map((_)=>{if(E(_,k))return _;_=_;let F=new aF(_.name,!!_.keyAsName,_.columnType,_.indexConfig);return _.indexConfig=_.defaultConfig,F}),this.unique,!0,this.name)}using(T,..._){return new h1(_.map((F)=>{if(E(F,k))return F;F=F;let W=new aF(F.name,!!F.keyAsName,F.columnType,F.indexConfig);return F.indexConfig=JSON.parse(JSON.stringify(F.defaultConfig)),W}),this.unique,!0,this.name,T)}}class h1{static[A]="PgIndexBuilder";config;constructor(T,_,F,W,J="btree"){this.config={name:W,columns:T,unique:_,only:F,method:J}}concurrently(){return this.config.concurrently=!0,this}with(T){return this.config.with=T,this}where(T){return this.config.where=T,this}build(T){return new v5(this.config,T)}}class v5{static[A]="PgIndex";config;constructor(T,_){this.config={...T,table:_}}}function M8(T){return new y5(!0,T)}class w8{constructor(T){this.query=T}authToken;getQuery(){return this.query}mapResult(T,_){return T}setToken(T){return this.authToken=T,this}static[A]="PgPreparedQuery";joinsNotNullableMap}class Q8{constructor(T){this.dialect=T}static[A]="PgSession";execute(T,_){return GT.startActiveSpan("drizzle.operation",()=>{return GT.startActiveSpan("drizzle.prepareQuery",()=>{return this.prepareQuery(this.dialect.sqlToQuery(T),void 0,void 0,!1)}).setToken(_).execute(void 0,_)})}all(T){return this.prepareQuery(this.dialect.sqlToQuery(T),void 0,void 0,!1).all()}async count(T,_){let F=await this.execute(T,_);return Number(F[0].count)}}class z8 extends EW{constructor(T,_,F,W=0){super(T,_,F);this.schema=F,this.nestedIndex=W}static[A]="PgTransaction";rollback(){throw new b4}getTransactionConfigSQL(T){let _=[];if(T.isolationLevel)_.push(`isolation level ${T.isolationLevel}`);if(T.accessMode)_.push(T.accessMode);if(typeof T.deferrable==="boolean")_.push(T.deferrable?"deferrable":"not deferrable");return O.raw(_.join(" "))}setTransaction(T){return this.session.execute(O`set transaction ${this.getTransactionConfigSQL(T)}`)}}class b5 extends w8{constructor(T,_,F,W,J,Y,$){super({sql:_,params:F});this.client=T,this.queryString=_,this.params=F,this.logger=W,this.fields=J,this._isResponseInArrayMode=Y,this.customResultMapper=$}static[A]="PostgresJsPreparedQuery";async execute(T={}){return GT.startActiveSpan("drizzle.execute",async(_)=>{let F=y4(this.params,T);_?.setAttributes({"drizzle.query.text":this.queryString,"drizzle.query.params":JSON.stringify(F)}),this.logger.logQuery(this.queryString,F);let{fields:W,queryString:J,client:Y,joinsNotNullableMap:$,customResultMapper:Z}=this;if(!W&&!Z)return GT.startActiveSpan("drizzle.driver.execute",()=>{return Y.unsafe(J,F)});let G=await GT.startActiveSpan("drizzle.driver.execute",()=>{return _?.setAttributes({"drizzle.query.text":J,"drizzle.query.params":JSON.stringify(F)}),Y.unsafe(J,F).values()});return GT.startActiveSpan("drizzle.mapResponse",()=>{return Z?Z(G):G.map((X)=>h$(W,X,$))})})}all(T={}){return GT.startActiveSpan("drizzle.execute",async(_)=>{let F=y4(this.params,T);return _?.setAttributes({"drizzle.query.text":this.queryString,"drizzle.query.params":JSON.stringify(F)}),this.logger.logQuery(this.queryString,F),GT.startActiveSpan("drizzle.driver.execute",()=>{return _?.setAttributes({"drizzle.query.text":this.queryString,"drizzle.query.params":JSON.stringify(F)}),this.client.unsafe(this.queryString,F)})})}isResponseInArrayMode(){return this._isResponseInArrayMode}}class RW extends Q8{constructor(T,_,F,W={}){super(_);this.client=T,this.schema=F,this.options=W,this.logger=W.logger??new h4}static[A]="PostgresJsSession";logger;prepareQuery(T,_,F,W,J){return new b5(this.client,T.sql,T.params,this.logger,_,W,J)}query(T,_){return this.logger.logQuery(T,_),this.client.unsafe(T,_).values()}queryObjects(T,_){return this.client.unsafe(T,_)}transaction(T,_){return this.client.begin(async(F)=>{let W=new RW(F,this.dialect,this.schema,this.options),J=new E8(this.dialect,W,this.schema);if(_)await J.setTransaction(_);return T(J)})}}class E8 extends z8{constructor(T,_,F,W=0){super(T,_,F,W);this.session=_}static[A]="PostgresJsTransaction";transaction(T){return this.session.client.savepoint((_)=>{let F=new RW(_,this.dialect,this.schema,this.session.options),W=new E8(this.dialect,F,this.schema);return T(W)})}}class x5 extends EW{static[A]="PostgresJsDatabase"}function AF(T,_={}){let F=(G)=>G;for(let G of["1184","1082","1083","1114","1182","1185","1115","1231"])T.options.parsers[G]=F,T.options.serializers[G]=F;T.options.serializers["114"]=F,T.options.serializers["3802"]=F;let W=new P0({casing:_.casing}),J;if(_.logger===!0)J=new x4;else if(_.logger!==!1)J=_.logger;let Y;if(_.schema){let G=G5(_.schema,A5);Y={fullSchema:_.schema,schema:G.tables,tableNamesMap:G.tableNamesMap}}let $=new RW(T,W,Y,{logger:J}),Z=new x5(W,$,Y);return Z.$client=T,Z}function p1(...T){if(typeof T[0]==="string"){let _=GF(T[0]);return AF(_,T[1])}if(m$(T[0])){let{connection:_,client:F,...W}=T[0];if(F)return AF(F,W);if(typeof _==="object"&&_.url!==void 0){let{url:Y,...$}=_,Z=GF(Y,$);return AF(Z,W)}let J=GF(_);return AF(J,W)}return AF(T[0],T[1])}((T)=>{function _(F){return AF({options:{parsers:{},serializers:{}}},F)}T.mock=_})(p1||(p1={}));var K8={};oG(K8,{users:()=>j0,untrackedUserColumnNames:()=>d3,twoFactorMethod:()=>o5,trackedUserColumnName:()=>l3,trackableUserColumnNames:()=>g5,signInHistory:()=>i3,role:()=>p5,players:()=>R8,passwordResetAttempts:()=>n3,games:()=>g1,banishedIps:()=>r3,accountActions:()=>t3,accountAction:()=>m5});function h5(T){return O`lower(${T})`}var p5=eF("role",["admin","user"]),j0=E0("users",{id:L_().primaryKey().defaultRandom(),username:aT({length:16}).notNull(),emailOffered:aT({length:254}).notNull(),emailVerified:aT({length:254}),password:aT({length:254}),createdAt:y_({withTimezone:!0}).notNull().defaultNow(),createdIp:aT({length:45}).notNull(),isActive:YW().notNull().default(!1),verifiedAt:y_({withTimezone:!0}),userRole:p5().default("user")},(T)=>[M8("usernameUniqueIndex").on(h5(T.username)),M8("emailVerifiedUniqueIndex").on(h5(T.emailVerified))]),d3=["id","createdAt","createdIp","isActive","verifiedAt"],g5=["username","emailOffered","emailVerified","password","userRole"],l3=eF("trackedUserColumnName",g5),m5=eF("accountAction",["cooldown","confirmEmail","signIn","resetPassword"]),t3=E0("accountActions",{userId:L_().references(()=>j0.id).primaryKey(),action:m5().notNull(),code:aT({length:254}).notNull(),wrongCodeCount:$W().notNull().default(0),expiresAt:y_({withTimezone:!0}).notNull()}),g1=E0("games",{id:L_().primaryKey().defaultRandom()}),R8=E0("players",{userId:L_().notNull().references(()=>j0.id,{onDelete:"cascade"}),gameId:L_().notNull().references(()=>g1.id,{onDelete:"cascade"}),score:$W().notNull()},(T)=>[xX({name:"players_userId_gameId_pk",columns:[T.userId,T.gameId]})]),i3=E0("signInHistory",{id:L_().primaryKey().defaultRandom(),userId:L_().references(()=>j0.id,{onDelete:"cascade"}),signInTime:y_({withTimezone:!0}).notNull().defaultNow(),ipAddress:aT({length:45}).notNull(),userAgent:aT({length:1024}),successful:YW().notNull().default(!1)}),o5=eF("twoFactorMethod",["email","phone"]),n3=E0("passwordResetAttempts",{id:L_().primaryKey().defaultRandom(),userId:L_().notNull().references(()=>j0.id,{onDelete:"cascade"}),requestedIp:aT({length:45}).notNull(),requestedAt:y_({withTimezone:!0}).notNull().defaultNow(),succeededIp:aT({length:45}),succeededAt:y_({withTimezone:!0}),verificationMethod:o5().notNull()}),r3=E0("banishedIps",{ip:aT({length:45}).primaryKey(),reason:aT({length:2048}).notNull(),banishedAt:y_({withTimezone:!0}).notNull().defaultNow(),banishedUntil:y_({withTimezone:!0})});var __dirname="/home/runner/work/wayforge/wayforge/apps/tempest.games/src/database";class V8{options;sql;drizzle;observers=new Map;async setupTriggersAndNotifications(){await this.sql.file(s3.resolve(__dirname,"notify_update.sql"));let T=[vT(j0),vT(g1),vT(R8)];await this.sql`SELECT create_notify_triggers(${this.sql.array(T)})`,await this.sql.listen("table_update",(_)=>{let F=_.split(","),W=F[0],J=F[1],Y=`${W}("${J}")`;if(this.observers.has(Y))this.observers.get(Y).next(Y)})}constructor(T=!1,_={host:P_.POSTGRES_HOST,port:P_.POSTGRES_PORT,user:P_.POSTGRES_USER,password:P_.POSTGRES_PASSWORD,database:P_.POSTGRES_DATABASE}){this.options=_,this.sql=GF(_),this.drizzle=p1(this.sql,{schema:K8,logger:T})}observe(T,_){if(!this.observers.has(T))this.observers.set(T,new FT);this.observers.get(T).subscribe("SINGLETON",_)}}var m1={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 a3(T){return Number.parseInt(T,10)}var e3=Y_(m1),TU=e3.keyof().pipe((T)=>a3(T)),u5=Y_([TU,"string"]);var L8=new D4,{logger:G_}=L8;Object.assign(console,G_,{log:G_.info});G_.info("ready");var D8=d5(import.meta.dir,"..","app"),fy=new V8({logQuery(T,_){G_.info("\uD83D\uDCDD query",T,_)}});JU({hostname:"0.0.0.0",port:P_.FRONTEND_PORT??3333,...J1??void 0,async fetch(T){try{let _=new Date,F=new URL(T.url);if(G_.info(T.method,F.pathname),F.pathname==="/")return new Response(Bun.file(d5(D8,"index.html")));if(F.pathname==="/index.html")return Response.redirect("/");let W=FU(D8,F.pathname),J=WU(W);if(!J.startsWith(D8))throw[403,"Access Denied"];if(!await c5(J).exists())return Response.redirect("/");return new Response(c5(J))}catch(_){let F=u5(_);if(F instanceof Y_.errors===!1){let[W,J]=F,$=`${m1[W]}. ${J}`;return G_.info(`\u274C ${W}: ${$}`),new Response($,{status:W})}if(_ instanceof Error)G_.error(_.message);else{let W=O$(_);G_.error("frontend server threw",W)}return new Response(m1[500],{status:500})}}});function o1(){G_.info("\uD83D\uDEEC frontend server exiting"),process.exit(0)}process.on("SIGINT",()=>{G_.info("\u2757 received SIGINT; exiting gracefully"),o1()});process.on("SIGTERM",()=>{G_.info("\u2757 received SIGTERM; exiting gracefully"),o1()});process.on("exit",()=>{G_.info("\u2757 received exit; exiting gracefully"),o1()});L8.on("timeToStop",()=>{G_.info('\u2757 backend server received signal "timeToStop"; exiting gracefully'),o1()});var{version:YU}=await Bun.file(_U.resolve(import.meta.dir,"../package.json")).json();G_.info(`\uD83D\uDEEB frontend v${YU} running at http://localhost:${P_.FRONTEND_PORT}/`);L8.emit("alive");
|
|
76
|
+
`;await _.execute(U`CREATE SCHEMA IF NOT EXISTS ${U.identifier(J)}`),await _.execute(Y);let Z=(await _.all(U`select id, hash, created_at from ${U.identifier(J)}.${U.identifier(W)} order by created_at desc limit 1`))[0];await _.transaction(async(G)=>{for await(let X of T)if(!Z||Number(Z.created_at)<X.folderMillis){for(let O of X.sql)await G.execute(U.raw(O));await G.execute(U`insert into ${U.identifier(J)}.${U.identifier(W)} ("hash", "created_at") values(${X.hash}, ${X.folderMillis})`)}})}escapeName(T){return`"${T}"`}escapeParam(T){return`$${T+1}`}escapeString(T){return`'${T.replace(/'/g,"''")}'`}buildWithCTE(T){if(!T?.length)return;let _=[U`with `];for(let[F,W]of T.entries())if(_.push(U`${U.identifier(W._.alias)} as (${W._.sql})`),F<T.length-1)_.push(U`, `);return _.push(U` `),U.join(_)}buildDeleteQuery({table:T,where:_,returning:F,withList:W}){let J=this.buildWithCTE(W),Y=F?U` returning ${this.buildSelection(F,{isSingleTable:!0})}`:void 0,$=_?U` where ${_}`:void 0;return U`${J}delete from ${T}${$}${Y}`}buildUpdateSet(T,_){let F=T[I.Symbol.Columns],W=Object.keys(F).filter((Y)=>_[Y]!==void 0||F[Y]?.onUpdateFn!==void 0),J=W.length;return U.join(W.flatMap((Y,$)=>{let Z=F[Y],G=_[Y]??U.param(Z.onUpdateFn(),Z),X=U`${U.identifier(this.casing.getColumnCasing(Z))} = ${G}`;if($<J-1)return[X,U.raw(", ")];return[X]}))}buildUpdateQuery({table:T,set:_,where:F,returning:W,withList:J,from:Y,joins:$}){let Z=this.buildWithCTE(J),G=T[vT.Symbol.Name],X=T[vT.Symbol.Schema],O=T[vT.Symbol.OriginalName],M=G===O?void 0:G,Q=U`${X?U`${U.identifier(X)}.`:void 0}${U.identifier(O)}${M&&U` ${U.identifier(M)}`}`,K=this.buildUpdateSet(T,_),B=Y&&U.join([U.raw(" from "),this.buildFromTable(Y)]),V=this.buildJoins($),v=W?U` returning ${this.buildSelection(W,{isSingleTable:!Y})}`:void 0,q=F?U` where ${F}`:void 0;return U`${Z}update ${Q} set ${K}${B}${V}${q}${v}`}buildSelection(T,{isSingleTable:_=!1}={}){let F=T.length,W=T.flatMap(({field:J},Y)=>{let $=[];if(R(J,k.Aliased)&&J.isSelectionField)$.push(U.identifier(J.fieldAlias));else if(R(J,k.Aliased)||R(J,k)){let Z=R(J,k.Aliased)?J.sql:J;if(_)$.push(new k(Z.queryChunks.map((G)=>{if(R(G,S))return U.identifier(this.casing.getColumnCasing(G));return G})));else $.push(Z);if(R(J,k.Aliased))$.push(U` as ${U.identifier(J.fieldAlias)}`)}else if(R(J,GT))if(_)$.push(U.identifier(this.casing.getColumnCasing(J)));else $.push(J);if(Y<F-1)$.push(U`, `);return $});return U.join(W)}buildJoins(T){if(!T||T.length===0)return;let _=[];for(let[F,W]of T.entries()){if(F===0)_.push(U` `);let J=W.table,Y=W.lateral?U` lateral`:void 0,$=W.on?U` on ${W.on}`:void 0;if(R(J,vT)){let Z=J[vT.Symbol.Name],G=J[vT.Symbol.Schema],X=J[vT.Symbol.OriginalName],O=Z===X?void 0:W.alias;_.push(U`${U.raw(W.joinType)} join${Y} ${G?U`${U.identifier(G)}.`:void 0}${U.identifier(X)}${O&&U` ${U.identifier(O)}`}${$}`)}else if(R(J,Z_)){let Z=J[MT].name,G=J[MT].schema,X=J[MT].originalName,O=Z===X?void 0:W.alias;_.push(U`${U.raw(W.joinType)} join${Y} ${G?U`${U.identifier(G)}.`:void 0}${U.identifier(X)}${O&&U` ${U.identifier(O)}`}${$}`)}else _.push(U`${U.raw(W.joinType)} join${Y} ${J}${$}`);if(F<T.length-1)_.push(U` `)}return U.join(_)}buildFromTable(T){if(R(T,I)&&T[I.Symbol.IsAlias]){let _=U`${U.identifier(T[I.Symbol.OriginalName])}`;if(T[I.Symbol.Schema])_=U`${U.identifier(T[I.Symbol.Schema])}.${_}`;return U`${_} ${U.identifier(T[I.Symbol.Name])}`}return T}buildSelectQuery({withList:T,fields:_,fieldsFlat:F,where:W,having:J,table:Y,joins:$,orderBy:Z,groupBy:G,limit:X,offset:O,lockingClause:M,distinct:Q,setOperators:K}){let B=F??L_(_);for(let TT of B)if(R(TT.field,GT)&&xT(TT.field.table)!==(R(Y,IT)?Y._.alias:R(Y,EW)?Y[MT].name:R(Y,k)?void 0:xT(Y))&&!((bT)=>$?.some(({alias:H_})=>H_===(bT[I.Symbol.IsAlias]?xT(bT):bT[I.Symbol.BaseName])))(TT.field.table)){let bT=xT(TT.field.table);throw new Error(`Your "${TT.path.join("->")}" field references a column "${bT}"."${TT.field.name}", but the table "${bT}" is not part of the query! Did you forget to join it?`)}let V=!$||$.length===0,v=this.buildWithCTE(T),q;if(Q)q=Q===!0?U` distinct`:U` distinct on (${U.join(Q.on,U`, `)})`;let j=this.buildSelection(B,{isSingleTable:V}),y=this.buildFromTable(Y),u=this.buildJoins($),h=W?U` where ${W}`:void 0,p=J?U` having ${J}`:void 0,t;if(Z&&Z.length>0)t=U` order by ${U.join(Z,U`, `)}`;let ST;if(G&&G.length>0)ST=U` group by ${U.join(G,U`, `)}`;let A_=typeof X==="object"||typeof X==="number"&&X>=0?U` limit ${X}`:void 0,D=O?U` offset ${O}`:void 0,ZT=U.empty();if(M){let TT=U` for ${U.raw(M.strength)}`;if(M.config.of)TT.append(U` of ${U.join(Array.isArray(M.config.of)?M.config.of:[M.config.of],U`, `)}`);if(M.config.noWait)TT.append(U` nowait`);else if(M.config.skipLocked)TT.append(U` skip locked`);ZT.append(TT)}let i=U`${v}select${q} ${j} from ${y}${u}${h}${ST}${p}${t}${A_}${D}${ZT}`;if(K.length>0)return this.buildSetOperations(i,K);return i}buildSetOperations(T,_){let[F,...W]=_;if(!F)throw new Error("Cannot pass undefined values to any set operator");if(W.length===0)return this.buildSetOperationQuery({leftSelect:T,setOperator:F});return this.buildSetOperations(this.buildSetOperationQuery({leftSelect:T,setOperator:F}),W)}buildSetOperationQuery({leftSelect:T,setOperator:{type:_,isAll:F,rightSelect:W,limit:J,orderBy:Y,offset:$}}){let Z=U`(${T.getSQL()}) `,G=U`(${W.getSQL()})`,X;if(Y&&Y.length>0){let K=[];for(let B of Y)if(R(B,S))K.push(U.identifier(B.name));else if(R(B,k)){for(let V=0;V<B.queryChunks.length;V++){let v=B.queryChunks[V];if(R(v,S))B.queryChunks[V]=U.identifier(v.name)}K.push(U`${B}`)}else K.push(U`${B}`);X=U` order by ${U.join(K,U`, `)} `}let O=typeof J==="object"||typeof J==="number"&&J>=0?U` limit ${J}`:void 0,M=U.raw(`${_} ${F?"all ":""}`),Q=$?U` offset ${$}`:void 0;return U`${Z}${M}${G}${X}${O}${Q}`}buildInsertQuery({table:T,values:_,onConflict:F,returning:W,withList:J,select:Y,overridingSystemValue_:$}){let Z=[],G=T[I.Symbol.Columns],X=Object.entries(G).filter(([v,q])=>!q.shouldDisableInsert()),O=X.map(([,v])=>U.identifier(this.casing.getColumnCasing(v)));if(Y){let v=_;if(R(v,k))Z.push(v);else Z.push(v.getSQL())}else{let v=_;Z.push(U.raw("values "));for(let[q,j]of v.entries()){let y=[];for(let[u,h]of X){let p=j[u];if(p===void 0||R(p,Q_)&&p.value===void 0)if(h.defaultFn!==void 0){let t=h.defaultFn(),ST=R(t,k)?t:U.param(t,h);y.push(ST)}else if(!h.default&&h.onUpdateFn!==void 0){let t=h.onUpdateFn(),ST=R(t,k)?t:U.param(t,h);y.push(ST)}else y.push(U`default`);else y.push(p)}if(Z.push(y),q<v.length-1)Z.push(U`, `)}}let M=this.buildWithCTE(J),Q=U.join(Z),K=W?U` returning ${this.buildSelection(W,{isSingleTable:!0})}`:void 0,B=F?U` on conflict ${F}`:void 0,V=$===!0?U`overriding system value `:void 0;return U`${M}insert into ${T} ${O} ${V}${Q}${B}${K}`}buildRefreshMaterializedViewQuery({view:T,concurrently:_,withNoData:F}){let W=_?U` concurrently`:void 0,J=F?U` with no data`:void 0;return U`refresh materialized view${W} ${T}${J}`}prepareTyping(T){if(R(T,z1)||R(T,E1))return"json";else if(R(T,V1))return"decimal";else if(R(T,K1))return"time";else if(R(T,L1)||R(T,D1))return"timestamp";else if(R(T,Q1)||R(T,R1))return"date";else if(R(T,S1))return"uuid";else return"none"}sqlToQuery(T,_){return T.toQuery({casing:this.casing,escapeName:this.escapeName,escapeParam:this.escapeParam,escapeString:this.escapeString,prepareTyping:this.prepareTyping,invokeSource:_})}buildRelationalQueryWithoutPK({fullSchema:T,schema:_,tableNamesMap:F,table:W,tableConfig:J,queryConfig:Y,tableAlias:$,nestedQueryRelation:Z,joinOn:G}){let X=[],O,M,Q=[],K,B=[];if(Y===!0)X=Object.entries(J.columns).map(([q,j])=>({dbKey:j.name,tsKey:q,field:o_(j,$),relationTableTsKey:void 0,isJson:!1,selection:[]}));else{let v=Object.fromEntries(Object.entries(J.columns).map(([p,t])=>[p,o_(t,$)]));if(Y.where){let p=typeof Y.where==="function"?Y.where(v,H5()):Y.where;K=p&&$W(p,$)}let q=[],j=[];if(Y.columns){let p=!1;for(let[t,ST]of Object.entries(Y.columns)){if(ST===void 0)continue;if(t in J.columns){if(!p&&ST===!0)p=!0;j.push(t)}}if(j.length>0)j=p?j.filter((t)=>Y.columns?.[t]===!0):Object.keys(J.columns).filter((t)=>!j.includes(t))}else j=Object.keys(J.columns);for(let p of j){let t=J.columns[p];q.push({tsKey:p,value:t})}let y=[];if(Y.with)y=Object.entries(Y.with).filter((p)=>!!p[1]).map(([p,t])=>({tsKey:p,queryConfig:t,relation:J.relations[p]}));let u;if(Y.extras){u=typeof Y.extras==="function"?Y.extras(v,{sql:U}):Y.extras;for(let[p,t]of Object.entries(u))q.push({tsKey:p,value:h4(t,$)})}for(let{tsKey:p,value:t}of q)X.push({dbKey:R(t,k.Aliased)?t.fieldAlias:J.columns[p].name,tsKey:p,field:R(t,GT)?o_(t,$):t,relationTableTsKey:void 0,isJson:!1,selection:[]});let h=typeof Y.orderBy==="function"?Y.orderBy(v,O5()):Y.orderBy??[];if(!Array.isArray(h))h=[h];Q=h.map((p)=>{if(R(p,GT))return o_(p,$);return $W(p,$)}),O=Y.limit,M=Y.offset;for(let{tsKey:p,queryConfig:t,relation:ST}of y){let A_=M5(_,F,ST),D=f0(ST.referencedTable),ZT=F[D],i=`${$}_${p}`,TT=HW(...A_.fields.map((I_,b0)=>I1(o_(A_.references[b0],i),o_(I_,$)))),bT=this.buildRelationalQueryWithoutPK({fullSchema:T,schema:_,tableNamesMap:F,table:T[ZT],tableConfig:_[ZT],queryConfig:R(ST,K0)?t===!0?{limit:1}:{...t,limit:1}:t,tableAlias:i,joinOn:TT,nestedQueryRelation:ST}),H_=U`${U.identifier(i)}.${U.identifier("data")}`.as(p);B.push({on:U`true`,table:new IT(bT.sql,{},i),alias:i,joinType:"left",lateral:!0}),X.push({dbKey:p,tsKey:p,field:H_,relationTableTsKey:ZT,isJson:!0,selection:bT.selection})}}if(X.length===0)throw new M1({message:`No fields selected for table "${J.tsName}" ("${$}")`});let V;if(K=HW(G,K),Z){let v=U`json_build_array(${U.join(X.map(({field:y,tsKey:u,isJson:h})=>h?U`${U.identifier(`${$}_${u}`)}.${U.identifier("data")}`:R(y,k.Aliased)?y.sql:y),U`, `)})`;if(R(Z,OW))v=U`coalesce(json_agg(${v}${Q.length>0?U` order by ${U.join(Q,U`, `)}`:void 0}), '[]'::json)`;let q=[{dbKey:"data",tsKey:"data",field:v.as("data"),isJson:!0,relationTableTsKey:J.tsName,selection:X}];if(O!==void 0||M!==void 0||Q.length>0)V=this.buildSelectQuery({table:U1(W,$),fields:{},fieldsFlat:[{path:[],field:U.raw("*")}],where:K,limit:O,offset:M,orderBy:Q,setOperators:[]}),K=void 0,O=void 0,M=void 0,Q=[];else V=U1(W,$);V=this.buildSelectQuery({table:R(V,vT)?V:new IT(V,{},$),fields:{},fieldsFlat:q.map(({field:y})=>({path:[],field:R(y,GT)?o_(y,$):y})),joins:B,where:K,limit:O,offset:M,orderBy:Q,setOperators:[]})}else V=this.buildSelectQuery({table:U1(W,$),fields:{},fieldsFlat:X.map(({field:v})=>({path:[],field:R(v,GT)?o_(v,$):v})),joins:B,where:K,limit:O,offset:M,orderBy:Q,setOperators:[]});return{tableTsKey:J.tsName,sql:V,selection:X}}}class H8{static[H]="TypedQueryBuilder";getSelectedFields(){return this._.selectedFields}}class eT{static[H]="PgSelectBuilder";fields;session;dialect;withList=[];distinct;constructor(T){if(this.fields=T.fields,this.session=T.session,this.dialect=T.dialect,T.withList)this.withList=T.withList;this.distinct=T.distinct}authToken;setToken(T){return this.authToken=T,this}from(T){let _=!!this.fields,F=T,W;if(this.fields)W=this.fields;else if(R(F,IT))W=Object.fromEntries(Object.keys(F._.selectedFields).map((J)=>[J,F[J]]));else if(R(F,EW))W=F[MT].selectedFields;else if(R(F,k))W={};else W=c$(F);return new O8({table:F,fields:W,isPartialSelect:_,session:this.session,dialect:this.dialect,withList:this.withList,distinct:this.distinct}).setToken(this.authToken)}}class h5 extends H8{static[H]="PgSelectQueryBuilder";_;config;joinsNotNullableMap;tableName;isPartialSelect;session;dialect;cacheConfig=void 0;usedTables=new Set;constructor({table:T,fields:_,isPartialSelect:F,session:W,dialect:J,withList:Y,distinct:$}){super();this.config={withList:Y,table:T,fields:{..._},distinct:$,setOperators:[]},this.isPartialSelect=F,this.session=W,this.dialect=J,this._={selectedFields:_,config:this.config},this.tableName=e_(T),this.joinsNotNullableMap=typeof this.tableName==="string"?{[this.tableName]:!0}:{};for(let Z of v_(T))this.usedTables.add(Z)}getUsedTables(){return[...this.usedTables]}createJoin(T,_){return(F,W)=>{let J=this.tableName,Y=e_(F);for(let $ of v_(F))this.usedTables.add($);if(typeof Y==="string"&&this.config.joins?.some(($)=>$.alias===Y))throw new Error(`Alias "${Y}" is already used in this query`);if(!this.isPartialSelect){if(Object.keys(this.joinsNotNullableMap).length===1&&typeof J==="string")this.config.fields={[J]:this.config.fields};if(typeof Y==="string"&&!R(F,k)){let $=R(F,IT)?F._.selectedFields:R(F,Z_)?F[MT].selectedFields:F[I.Symbol.Columns];this.config.fields[Y]=$}}if(typeof W==="function")W=W(new Proxy(this.config.fields,new DT({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));if(!this.config.joins)this.config.joins=[];if(this.config.joins.push({on:W,table:F,joinType:T,alias:Y,lateral:_}),typeof Y==="string")switch(T){case"left":{this.joinsNotNullableMap[Y]=!1;break}case"right":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([$])=>[$,!1])),this.joinsNotNullableMap[Y]=!0;break}case"cross":case"inner":{this.joinsNotNullableMap[Y]=!0;break}case"full":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([$])=>[$,!1])),this.joinsNotNullableMap[Y]=!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(T,_){return(F)=>{let W=typeof F==="function"?F(u3()):F;if(!ZW(this.getSelectedFields(),W.getSelectedFields()))throw new Error("Set operator error (union / intersect / except): selected fields are not the same or are in a different order");return this.config.setOperators.push({type:T,isAll:_,rightSelect:W}),this}}union=this.createSetOperator("union",!1);unionAll=this.createSetOperator("union",!0);intersect=this.createSetOperator("intersect",!1);intersectAll=this.createSetOperator("intersect",!0);except=this.createSetOperator("except",!1);exceptAll=this.createSetOperator("except",!0);addSetOperators(T){return this.config.setOperators.push(...T),this}where(T){if(typeof T==="function")T=T(new Proxy(this.config.fields,new DT({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));return this.config.where=T,this}having(T){if(typeof T==="function")T=T(new Proxy(this.config.fields,new DT({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));return this.config.having=T,this}groupBy(...T){if(typeof T[0]==="function"){let _=T[0](new Proxy(this.config.fields,new DT({sqlAliasedBehavior:"alias",sqlBehavior:"sql"})));this.config.groupBy=Array.isArray(_)?_:[_]}else this.config.groupBy=T;return this}orderBy(...T){if(typeof T[0]==="function"){let _=T[0](new Proxy(this.config.fields,new DT({sqlAliasedBehavior:"alias",sqlBehavior:"sql"}))),F=Array.isArray(_)?_:[_];if(this.config.setOperators.length>0)this.config.setOperators.at(-1).orderBy=F;else this.config.orderBy=F}else{let _=T;if(this.config.setOperators.length>0)this.config.setOperators.at(-1).orderBy=_;else this.config.orderBy=_}return this}limit(T){if(this.config.setOperators.length>0)this.config.setOperators.at(-1).limit=T;else this.config.limit=T;return this}offset(T){if(this.config.setOperators.length>0)this.config.setOperators.at(-1).offset=T;else this.config.offset=T;return this}for(T,_={}){return this.config.lockingClause={strength:T,config:_},this}getSQL(){return this.dialect.buildSelectQuery(this.config)}toSQL(){let{typings:T,..._}=this.dialect.sqlToQuery(this.getSQL());return _}as(T){let _=[];if(_.push(...v_(this.config.table)),this.config.joins)for(let F of this.config.joins)_.push(...v_(F.table));return new Proxy(new IT(this.getSQL(),this.config.fields,T,!1,[...new Set(_)]),new DT({alias:T,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}getSelectedFields(){return new Proxy(this.config.fields,new DT({alias:this.tableName,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}$dynamic(){return this}$withCache(T){return this.cacheConfig=T===void 0?{config:{},enable:!0,autoInvalidate:!0}:T===!1?{enable:!1}:{enable:!0,autoInvalidate:!0,...T},this}}class O8 extends h5{static[H]="PgSelect";_prepare(T){let{session:_,config:F,dialect:W,joinsNotNullableMap:J,authToken:Y,cacheConfig:$,usedTables:Z}=this;if(!_)throw new Error("Cannot execute a query on a query builder. Please use a database instance instead.");let{fields:G}=F;return AT.startActiveSpan("drizzle.prepareQuery",()=>{let X=L_(G),O=_.prepareQuery(W.sqlToQuery(this.getSQL()),X,T,!0,void 0,{type:"select",tables:[...Z]},$);return O.joinsNotNullableMap=J,O.setToken(Y)})}prepare(T){return this._prepare(T)}authToken;setToken(T){return this.authToken=T,this}execute=(T)=>{return AT.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(T,this.authToken)})}}u$(O8,[sT]);function UF(T,_){return(F,W,...J)=>{let Y=[W,...J].map(($)=>({type:T,isAll:_,rightSelect:$}));for(let $ of Y)if(!ZW(F.getSelectedFields(),$.rightSelect.getSelectedFields()))throw new Error("Set operator error (union / intersect / except): selected fields are not the same or are in a different order");return F.addSetOperators(Y)}}var u3=()=>({union:c3,unionAll:d3,intersect:l3,intersectAll:t3,except:i3,exceptAll:n3}),c3=UF("union",!1),d3=UF("union",!0),l3=UF("intersect",!1),t3=UF("intersect",!0),i3=UF("except",!1),n3=UF("except",!0);class zW{static[H]="PgQueryBuilder";dialect;dialectConfig;constructor(T){this.dialect=R(T,v0)?T:void 0,this.dialectConfig=R(T,v0)?void 0:T}$with=(T,_)=>{let F=this;return{as:(J)=>{if(typeof J==="function")J=J(F);return new Proxy(new WW(J.getSQL(),_??("getSelectedFields"in J?J.getSelectedFields()??{}:{}),T,!0),new DT({alias:T,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}};with(...T){let _=this;function F(Y){return new eT({fields:Y??void 0,session:void 0,dialect:_.getDialect(),withList:T})}function W(Y){return new eT({fields:Y??void 0,session:void 0,dialect:_.getDialect(),distinct:!0})}function J(Y,$){return new eT({fields:$??void 0,session:void 0,dialect:_.getDialect(),distinct:{on:Y}})}return{select:F,selectDistinct:W,selectDistinctOn:J}}select(T){return new eT({fields:T??void 0,session:void 0,dialect:this.getDialect()})}selectDistinct(T){return new eT({fields:T??void 0,session:void 0,dialect:this.getDialect(),distinct:!0})}selectDistinctOn(T,_){return new eT({fields:_??void 0,session:void 0,dialect:this.getDialect(),distinct:{on:T}})}getDialect(){if(!this.dialect)this.dialect=new v0(this.dialectConfig);return this.dialect}}function v_(T){if(R(T,vT))return[T[k0]?`${T[k0]}.${T[I.Symbol.BaseName]}`:T[I.Symbol.BaseName]];if(R(T,IT))return T._.usedTables??[];if(R(T,k))return T.usedTables??[];return[]}class p1 extends sT{constructor(T,_,F,W){super();this.session=_,this.dialect=F,this.config={table:T,withList:W}}static[H]="PgDelete";config;cacheConfig;where(T){return this.config.where=T,this}returning(T=this.config.table[I.Symbol.Columns]){return this.config.returningFields=T,this.config.returning=L_(T),this}getSQL(){return this.dialect.buildDeleteQuery(this.config)}toSQL(){let{typings:T,..._}=this.dialect.sqlToQuery(this.getSQL());return _}_prepare(T){return AT.startActiveSpan("drizzle.prepareQuery",()=>{return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,T,!0,void 0,{type:"delete",tables:v_(this.config.table)},this.cacheConfig)})}prepare(T){return this._prepare(T)}authToken;setToken(T){return this.authToken=T,this}execute=(T)=>{return AT.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(T,this.authToken)})};getSelectedFields(){return this.config.returningFields?new Proxy(this.config.returningFields,new DT({alias:xT(this.config.table),sqlAliasedBehavior:"alias",sqlBehavior:"error"})):void 0}$dynamic(){return this}}class g1{constructor(T,_,F,W,J){this.table=T,this.session=_,this.dialect=F,this.withList=W,this.overridingSystemValue_=J}static[H]="PgInsertBuilder";authToken;setToken(T){return this.authToken=T,this}overridingSystemValue(){return this.overridingSystemValue_=!0,this}values(T){if(T=Array.isArray(T)?T:[T],T.length===0)throw new Error("values() must be called with at least one value");let _=T.map((F)=>{let W={},J=this.table[I.Symbol.Columns];for(let Y of Object.keys(F)){let $=F[Y];W[Y]=R($,k)?$:new Q_($,J[Y])}return W});return new U8(this.table,_,this.session,this.dialect,this.withList,!1,this.overridingSystemValue_).setToken(this.authToken)}select(T){let _=typeof T==="function"?T(new zW):T;if(!R(_,k)&&!ZW(this.table[H1],_._.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 U8(this.table,_,this.session,this.dialect,this.withList,!0)}}class U8 extends sT{constructor(T,_,F,W,J,Y,$){super();this.session=F,this.dialect=W,this.config={table:T,values:_,withList:J,select:Y,overridingSystemValue_:$}}static[H]="PgInsert";config;cacheConfig;returning(T=this.config.table[I.Symbol.Columns]){return this.config.returningFields=T,this.config.returning=L_(T),this}onConflictDoNothing(T={}){if(T.target===void 0)this.config.onConflict=U`do nothing`;else{let _="";_=Array.isArray(T.target)?T.target.map((W)=>this.dialect.escapeName(this.dialect.casing.getColumnCasing(W))).join(","):this.dialect.escapeName(this.dialect.casing.getColumnCasing(T.target));let F=T.where?U` where ${T.where}`:void 0;this.config.onConflict=U`(${U.raw(_)})${F} do nothing`}return this}onConflictDoUpdate(T){if(T.where&&(T.targetWhere||T.setWhere))throw new Error('You cannot use both "where" and "targetWhere"/"setWhere" at the same time - "where" is deprecated, use "targetWhere" or "setWhere" instead.');let _=T.where?U` where ${T.where}`:void 0,F=T.targetWhere?U` where ${T.targetWhere}`:void 0,W=T.setWhere?U` where ${T.setWhere}`:void 0,J=this.dialect.buildUpdateSet(this.config.table,w1(this.config.table,T.set)),Y="";return Y=Array.isArray(T.target)?T.target.map(($)=>this.dialect.escapeName(this.dialect.casing.getColumnCasing($))).join(","):this.dialect.escapeName(this.dialect.casing.getColumnCasing(T.target)),this.config.onConflict=U`(${U.raw(Y)})${F} do update set ${J}${_}${W}`,this}getSQL(){return this.dialect.buildInsertQuery(this.config)}toSQL(){let{typings:T,..._}=this.dialect.sqlToQuery(this.getSQL());return _}_prepare(T){return AT.startActiveSpan("drizzle.prepareQuery",()=>{return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,T,!0,void 0,{type:"insert",tables:v_(this.config.table)},this.cacheConfig)})}prepare(T){return this._prepare(T)}authToken;setToken(T){return this.authToken=T,this}execute=(T)=>{return AT.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(T,this.authToken)})};getSelectedFields(){return this.config.returningFields?new Proxy(this.config.returningFields,new DT({alias:xT(this.config.table),sqlAliasedBehavior:"alias",sqlBehavior:"error"})):void 0}$dynamic(){return this}}class M8 extends sT{constructor(T,_,F){super();this.session=_,this.dialect=F,this.config={view:T}}static[H]="PgRefreshMaterializedView";config;concurrently(){if(this.config.withNoData!==void 0)throw new Error("Cannot use concurrently and withNoData together");return this.config.concurrently=!0,this}withNoData(){if(this.config.concurrently!==void 0)throw new Error("Cannot use concurrently and withNoData together");return this.config.withNoData=!0,this}getSQL(){return this.dialect.buildRefreshMaterializedViewQuery(this.config)}toSQL(){let{typings:T,..._}=this.dialect.sqlToQuery(this.getSQL());return _}_prepare(T){return AT.startActiveSpan("drizzle.prepareQuery",()=>{return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),void 0,T,!0)})}prepare(T){return this._prepare(T)}authToken;setToken(T){return this.authToken=T,this}execute=(T)=>{return AT.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(T,this.authToken)})}}class m1{constructor(T,_,F,W){this.table=T,this.session=_,this.dialect=F,this.withList=W}static[H]="PgUpdateBuilder";authToken;setToken(T){return this.authToken=T,this}set(T){return new p5(this.table,w1(this.table,T),this.session,this.dialect,this.withList).setToken(this.authToken)}}class p5 extends sT{constructor(T,_,F,W,J){super();this.session=F,this.dialect=W,this.config={set:_,table:T,withList:J,joins:[]},this.tableName=e_(T),this.joinsNotNullableMap=typeof this.tableName==="string"?{[this.tableName]:!0}:{}}static[H]="PgUpdate";config;tableName;joinsNotNullableMap;cacheConfig;from(T){let _=T,F=e_(_);if(typeof F==="string")this.joinsNotNullableMap[F]=!0;return this.config.from=_,this}getTableLikeFields(T){if(R(T,vT))return T[I.Symbol.Columns];else if(R(T,IT))return T._.selectedFields;return T[MT].selectedFields}createJoin(T){return(_,F)=>{let W=e_(_);if(typeof W==="string"&&this.config.joins.some((J)=>J.alias===W))throw new Error(`Alias "${W}" is already used in this query`);if(typeof F==="function"){let J=this.config.from&&!R(this.config.from,k)?this.getTableLikeFields(this.config.from):void 0;F=F(new Proxy(this.config.table[I.Symbol.Columns],new DT({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})),J&&new Proxy(J,new DT({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})))}if(this.config.joins.push({on:F,table:_,joinType:T,alias:W}),typeof W==="string")switch(T){case"left":{this.joinsNotNullableMap[W]=!1;break}case"right":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([J])=>[J,!1])),this.joinsNotNullableMap[W]=!0;break}case"inner":{this.joinsNotNullableMap[W]=!0;break}case"full":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([J])=>[J,!1])),this.joinsNotNullableMap[W]=!1;break}}return this}}leftJoin=this.createJoin("left");rightJoin=this.createJoin("right");innerJoin=this.createJoin("inner");fullJoin=this.createJoin("full");where(T){return this.config.where=T,this}returning(T){if(!T){if(T=Object.assign({},this.config.table[I.Symbol.Columns]),this.config.from){let _=e_(this.config.from);if(typeof _==="string"&&this.config.from&&!R(this.config.from,k)){let F=this.getTableLikeFields(this.config.from);T[_]=F}for(let F of this.config.joins){let W=e_(F.table);if(typeof W==="string"&&!R(F.table,k)){let J=this.getTableLikeFields(F.table);T[W]=J}}}}return this.config.returningFields=T,this.config.returning=L_(T),this}getSQL(){return this.dialect.buildUpdateQuery(this.config)}toSQL(){let{typings:T,..._}=this.dialect.sqlToQuery(this.getSQL());return _}_prepare(T){let _=this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,T,!0,void 0,{type:"insert",tables:v_(this.config.table)},this.cacheConfig);return _.joinsNotNullableMap=this.joinsNotNullableMap,_}prepare(T){return this._prepare(T)}authToken;setToken(T){return this.authToken=T,this}execute=(T)=>{return this._prepare().execute(T,this.authToken)};getSelectedFields(){return this.config.returningFields?new Proxy(this.config.returningFields,new DT({alias:xT(this.config.table),sqlAliasedBehavior:"alias",sqlBehavior:"error"})):void 0}$dynamic(){return this}}class VW extends k{constructor(T){super(VW.buildEmbeddedCount(T.source,T.filters).queryChunks);this.params=T,this.mapWith(Number),this.session=T.session,this.sql=VW.buildCount(T.source,T.filters)}sql;token;static[H]="PgCountBuilder";[Symbol.toStringTag]="PgCountBuilder";session;static buildEmbeddedCount(T,_){return U`(select count(*) from ${T}${U.raw(" where ").if(_)}${_})`}static buildCount(T,_){return U`select count(*) as count from ${T}${U.raw(" where ").if(_)}${_};`}setToken(T){return this.token=T,this}then(T,_){return Promise.resolve(this.session.count(this.sql,this.token)).then(T,_)}catch(T){return this.then(void 0,T)}finally(T){return this.then((_)=>{return T?.(),_},(_)=>{throw T?.(),_})}}class Q8{constructor(T,_,F,W,J,Y,$){this.fullSchema=T,this.schema=_,this.tableNamesMap=F,this.table=W,this.tableConfig=J,this.dialect=Y,this.session=$}static[H]="PgRelationalQueryBuilder";findMany(T){return new w8(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,T?T:{},"many")}findFirst(T){return new w8(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,T?{...T,limit:1}:{limit:1},"first")}}class w8 extends sT{constructor(T,_,F,W,J,Y,$,Z,G){super();this.fullSchema=T,this.schema=_,this.tableNamesMap=F,this.table=W,this.tableConfig=J,this.dialect=Y,this.session=$,this.config=Z,this.mode=G}static[H]="PgRelationalQuery";_prepare(T){return AT.startActiveSpan("drizzle.prepareQuery",()=>{let{query:_,builtQuery:F}=this._toSQL();return this.session.prepareQuery(F,void 0,T,!0,(W,J)=>{let Y=W.map(($)=>N1(this.schema,this.tableConfig,$,_.selection,J));if(this.mode==="first")return Y[0];return Y})})}prepare(T){return this._prepare(T)}_getQuery(){return this.dialect.buildRelationalQueryWithoutPK({fullSchema:this.fullSchema,schema:this.schema,tableNamesMap:this.tableNamesMap,table:this.table,tableConfig:this.tableConfig,queryConfig:this.config,tableAlias:this.tableConfig.tsName})}getSQL(){return this._getQuery().sql}_toSQL(){let T=this._getQuery(),_=this.dialect.sqlToQuery(T.sql);return{query:T,builtQuery:_}}toSQL(){return this._toSQL().builtQuery}authToken;setToken(T){return this.authToken=T,this}execute(){return AT.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(void 0,this.authToken)})}}class R8 extends sT{constructor(T,_,F,W){super();this.execute=T,this.sql=_,this.query=F,this.mapBatchResult=W}static[H]="PgRaw";getSQL(){return this.sql}getQuery(){return this.query}mapResult(T,_){return _?this.mapBatchResult(T):T}_prepare(){return this}isResponseInArrayMode(){return!1}}class KW{constructor(T,_,F){if(this.dialect=T,this.session=_,this._=F?{schema:F.schema,fullSchema:F.fullSchema,tableNamesMap:F.tableNamesMap,session:_}:{schema:void 0,fullSchema:{},tableNamesMap:{},session:_},this.query={},this._.schema)for(let[W,J]of Object.entries(this._.schema))this.query[W]=new Q8(F.fullSchema,this._.schema,this._.tableNamesMap,F.fullSchema[W],J,T,_);this.$cache={invalidate:async(W)=>{}}}static[H]="PgDatabase";query;$with=(T,_)=>{let F=this;return{as:(J)=>{if(typeof J==="function")J=J(new zW(F.dialect));return new Proxy(new WW(J.getSQL(),_??("getSelectedFields"in J?J.getSelectedFields()??{}:{}),T,!0),new DT({alias:T,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}};$count(T,_){return new VW({source:T,filters:_,session:this.session})}$cache;with(...T){let _=this;function F(G){return new eT({fields:G??void 0,session:_.session,dialect:_.dialect,withList:T})}function W(G){return new eT({fields:G??void 0,session:_.session,dialect:_.dialect,withList:T,distinct:!0})}function J(G,X){return new eT({fields:X??void 0,session:_.session,dialect:_.dialect,withList:T,distinct:{on:G}})}function Y(G){return new m1(G,_.session,_.dialect,T)}function $(G){return new g1(G,_.session,_.dialect,T)}function Z(G){return new p1(G,_.session,_.dialect,T)}return{select:F,selectDistinct:W,selectDistinctOn:J,update:Y,insert:$,delete:Z}}select(T){return new eT({fields:T??void 0,session:this.session,dialect:this.dialect})}selectDistinct(T){return new eT({fields:T??void 0,session:this.session,dialect:this.dialect,distinct:!0})}selectDistinctOn(T,_){return new eT({fields:_??void 0,session:this.session,dialect:this.dialect,distinct:{on:T}})}update(T){return new m1(T,this.session,this.dialect)}insert(T){return new g1(T,this.session,this.dialect)}delete(T){return new p1(T,this.session,this.dialect)}refreshMaterializedView(T){return new M8(T,this.session,this.dialect)}authToken;execute(T){let _=typeof T==="string"?U.raw(T):T.getSQL(),F=this.dialect.sqlToQuery(_),W=this.session.prepareQuery(F,void 0,void 0,!1);return new R8(()=>W.execute(void 0,this.authToken),_,F,(J)=>W.mapResult(J,!0))}transaction(T,_){return this.session.transaction(T,_)}}class g5{static[H]="Cache"}class LW extends g5{strategy(){return"all"}static[H]="NoopCache";async get(T){return}async put(T,_,F,W){}async onMutate(T){}}async function E8(T,_){let F=`${T}-${JSON.stringify(_)}`,J=new TextEncoder().encode(F),Y=await crypto.subtle.digest("SHA-256",J);return[...new Uint8Array(Y)].map((G)=>G.toString(16).padStart(2,"0")).join("")}class _0 extends Error{constructor(T,_,F){super(`Failed query: ${T}
|
|
77
|
+
params: ${_}`);if(this.query=T,this.params=_,this.cause=F,Error.captureStackTrace(this,_0),F)this.cause=F}}class z8{constructor(T,_,F,W){if(this.query=T,this.cache=_,this.queryMetadata=F,this.cacheConfig=W,_&&_.strategy()==="all"&&W===void 0)this.cacheConfig={enable:!0,autoInvalidate:!0};if(!this.cacheConfig?.enable)this.cacheConfig=void 0}authToken;getQuery(){return this.query}mapResult(T,_){return T}setToken(T){return this.authToken=T,this}static[H]="PgPreparedQuery";joinsNotNullableMap;async queryWithCache(T,_,F){if(this.cache===void 0||R(this.cache,LW)||this.queryMetadata===void 0)try{return await F()}catch(W){throw new _0(T,_,W)}if(this.cacheConfig&&!this.cacheConfig.enable)try{return await F()}catch(W){throw new _0(T,_,W)}if((this.queryMetadata.type==="insert"||this.queryMetadata.type==="update"||this.queryMetadata.type==="delete")&&this.queryMetadata.tables.length>0)try{let[W]=await Promise.all([F(),this.cache.onMutate({tables:this.queryMetadata.tables})]);return W}catch(W){throw new _0(T,_,W)}if(!this.cacheConfig)try{return await F()}catch(W){throw new _0(T,_,W)}if(this.queryMetadata.type==="select"){let W=await this.cache.get(this.cacheConfig.tag??await E8(T,_),this.queryMetadata.tables,this.cacheConfig.tag!==void 0,this.cacheConfig.autoInvalidate);if(W===void 0){let J;try{J=await F()}catch(Y){throw new _0(T,_,Y)}return await this.cache.put(this.cacheConfig.tag??await E8(T,_),J,this.cacheConfig.autoInvalidate?this.queryMetadata.tables:[],this.cacheConfig.tag!==void 0,this.cacheConfig.config),J}return W}try{return await F()}catch(W){throw new _0(T,_,W)}}}class V8{constructor(T){this.dialect=T}static[H]="PgSession";execute(T,_){return AT.startActiveSpan("drizzle.operation",()=>{return AT.startActiveSpan("drizzle.prepareQuery",()=>{return this.prepareQuery(this.dialect.sqlToQuery(T),void 0,void 0,!1)}).setToken(_).execute(void 0,_)})}all(T){return this.prepareQuery(this.dialect.sqlToQuery(T),void 0,void 0,!1).all()}async count(T,_){let F=await this.execute(T,_);return Number(F[0].count)}}class K8 extends KW{constructor(T,_,F,W=0){super(T,_,F);this.schema=F,this.nestedIndex=W}static[H]="PgTransaction";rollback(){throw new p4}getTransactionConfigSQL(T){let _=[];if(T.isolationLevel)_.push(`isolation level ${T.isolationLevel}`);if(T.accessMode)_.push(T.accessMode);if(typeof T.deferrable==="boolean")_.push(T.deferrable?"deferrable":"not deferrable");return U.raw(_.join(" "))}setTransaction(T){return this.session.execute(U`set transaction ${this.getTransactionConfigSQL(T)}`)}}class m5 extends z8{constructor(T,_,F,W,J,Y,$,Z,G,X){super({sql:_,params:F},J,Y,$);this.client=T,this.queryString=_,this.params=F,this.logger=W,this.fields=Z,this._isResponseInArrayMode=G,this.customResultMapper=X}static[H]="PostgresJsPreparedQuery";async execute(T={}){return AT.startActiveSpan("drizzle.execute",async(_)=>{let F=b4(this.params,T);_?.setAttributes({"drizzle.query.text":this.queryString,"drizzle.query.params":JSON.stringify(F)}),this.logger.logQuery(this.queryString,F);let{fields:W,queryString:J,client:Y,joinsNotNullableMap:$,customResultMapper:Z}=this;if(!W&&!Z)return AT.startActiveSpan("drizzle.driver.execute",()=>{return this.queryWithCache(J,F,async()=>{return await Y.unsafe(J,F)})});let G=await AT.startActiveSpan("drizzle.driver.execute",()=>{return _?.setAttributes({"drizzle.query.text":J,"drizzle.query.params":JSON.stringify(F)}),this.queryWithCache(J,F,async()=>{return await Y.unsafe(J,F).values()})});return AT.startActiveSpan("drizzle.mapResponse",()=>{return Z?Z(G):G.map((X)=>o$(W,X,$))})})}all(T={}){return AT.startActiveSpan("drizzle.execute",async(_)=>{let F=b4(this.params,T);return _?.setAttributes({"drizzle.query.text":this.queryString,"drizzle.query.params":JSON.stringify(F)}),this.logger.logQuery(this.queryString,F),AT.startActiveSpan("drizzle.driver.execute",()=>{return _?.setAttributes({"drizzle.query.text":this.queryString,"drizzle.query.params":JSON.stringify(F)}),this.queryWithCache(this.queryString,F,async()=>{return this.client.unsafe(this.queryString,F)})})})}isResponseInArrayMode(){return this._isResponseInArrayMode}}class DW extends V8{constructor(T,_,F,W={}){super(_);this.client=T,this.schema=F,this.options=W,this.logger=W.logger??new m4,this.cache=W.cache??new LW}static[H]="PostgresJsSession";logger;cache;prepareQuery(T,_,F,W,J,Y,$){return new m5(this.client,T.sql,T.params,this.logger,this.cache,Y,$,_,W,J)}query(T,_){return this.logger.logQuery(T,_),this.client.unsafe(T,_).values()}queryObjects(T,_){return this.client.unsafe(T,_)}transaction(T,_){return this.client.begin(async(F)=>{let W=new DW(F,this.dialect,this.schema,this.options),J=new L8(this.dialect,W,this.schema);if(_)await J.setTransaction(_);return T(J)})}}class L8 extends K8{constructor(T,_,F,W=0){super(T,_,F,W);this.session=_}static[H]="PostgresJsTransaction";transaction(T){return this.session.client.savepoint((_)=>{let F=new DW(_,this.dialect,this.schema,this.session.options),W=new L8(this.dialect,F,this.schema);return T(W)})}}class o5 extends KW{static[H]="PostgresJsDatabase"}function MF(T,_={}){let F=(G)=>G;for(let G of["1184","1082","1083","1114","1182","1185","1115","1231"])T.options.parsers[G]=F,T.options.serializers[G]=F;T.options.serializers["114"]=F,T.options.serializers["3802"]=F;let W=new v0({casing:_.casing}),J;if(_.logger===!0)J=new g4;else if(_.logger!==!1)J=_.logger;let Y;if(_.schema){let G=U5(_.schema,w5);Y={fullSchema:_.schema,schema:G.tables,tableNamesMap:G.tableNamesMap}}let $=new DW(T,W,Y,{logger:J,cache:_.cache}),Z=new o5(W,$,Y);if(Z.$client=T,Z.$cache=_.cache,Z.$cache)Z.$cache.invalidate=_.cache?.onMutate;return Z}function o1(...T){if(typeof T[0]==="string"){let _=OF(T[0]);return MF(_,T[1])}if(d$(T[0])){let{connection:_,client:F,...W}=T[0];if(F)return MF(F,W);if(typeof _==="object"&&_.url!==void 0){let{url:Y,...$}=_,Z=OF(Y,$);return MF(Z,W)}let J=OF(_);return MF(J,W)}return MF(T[0],T[1])}((T)=>{function _(F){return MF({options:{parsers:{},serializers:{}}},F)}T.mock=_})(o1||(o1={}));var S8={};tG(S8,{users:()=>x0,untrackedUserColumnNames:()=>r3,twoFactorMethod:()=>t5,trackedUserColumnName:()=>s3,trackableUserColumnNames:()=>d5,signInHistory:()=>e3,role:()=>c5,players:()=>D8,passwordResetAttempts:()=>TO,games:()=>u1,banishedIps:()=>_O,accountActions:()=>a3,accountAction:()=>l5});function u5(T){return U`lower(${T})`}var c5=FW("role",["admin","user"]),x0=V0("users",{id:D_().primaryKey().defaultRandom(),username:aT({length:16}).notNull(),emailOffered:aT({length:254}).notNull(),emailVerified:aT({length:254}),password:aT({length:254}),createdAt:y_({withTimezone:!0}).notNull().defaultNow(),createdIp:aT({length:45}).notNull(),isActive:XW().notNull().default(!1),verifiedAt:y_({withTimezone:!0}),userRole:c5().default("user")},(T)=>[G8("usernameUniqueIndex").on(u5(T.username)),G8("emailVerifiedUniqueIndex").on(u5(T.emailVerified))]),r3=["id","createdAt","createdIp","isActive","verifiedAt"],d5=["username","emailOffered","emailVerified","password","userRole"],s3=FW("trackedUserColumnName",d5),l5=FW("accountAction",["cooldown","confirmEmail","signIn","resetPassword"]),a3=V0("accountActions",{userId:D_().references(()=>x0.id).primaryKey(),action:l5().notNull(),code:aT({length:254}).notNull(),wrongCodeCount:GW().notNull().default(0),expiresAt:y_({withTimezone:!0}).notNull()}),u1=V0("games",{id:D_().primaryKey().defaultRandom()}),D8=V0("players",{userId:D_().notNull().references(()=>x0.id,{onDelete:"cascade"}),gameId:D_().notNull().references(()=>u1.id,{onDelete:"cascade"}),score:GW().notNull()},(T)=>[mX({name:"players_userId_gameId_pk",columns:[T.userId,T.gameId]})]),e3=V0("signInHistory",{id:D_().primaryKey().defaultRandom(),userId:D_().references(()=>x0.id,{onDelete:"cascade"}),signInTime:y_({withTimezone:!0}).notNull().defaultNow(),ipAddress:aT({length:45}).notNull(),userAgent:aT({length:1024}),successful:XW().notNull().default(!1)}),t5=FW("twoFactorMethod",["email","phone"]),TO=V0("passwordResetAttempts",{id:D_().primaryKey().defaultRandom(),userId:D_().notNull().references(()=>x0.id,{onDelete:"cascade"}),requestedIp:aT({length:45}).notNull(),requestedAt:y_({withTimezone:!0}).notNull().defaultNow(),succeededIp:aT({length:45}),succeededAt:y_({withTimezone:!0}),verificationMethod:t5().notNull()}),_O=V0("banishedIps",{ip:aT({length:45}).primaryKey(),reason:aT({length:2048}).notNull(),banishedAt:y_({withTimezone:!0}).notNull().defaultNow(),banishedUntil:y_({withTimezone:!0})});var __dirname="/home/runner/work/wayforge/wayforge/apps/tempest.games/src/database";class I8{options;sql;drizzle;observers=new Map;async setupTriggersAndNotifications(){await this.sql.file(FO.resolve(__dirname,"notify_update.sql"));let T=[xT(x0),xT(u1),xT(D8)];await this.sql`SELECT create_notify_triggers(${this.sql.array(T)})`,await this.sql.listen("table_update",(_)=>{let F=_.split(","),W=F[0],J=F[1],Y=`${W}("${J}")`;if(this.observers.has(Y))this.observers.get(Y).next(Y)})}constructor(T=!1,_={host:q_.POSTGRES_HOST,port:q_.POSTGRES_PORT,user:q_.POSTGRES_USER,password:q_.POSTGRES_PASSWORD,database:q_.POSTGRES_DATABASE}){this.options=_,this.sql=OF(_),this.drizzle=o1(this.sql,{schema:S8,logger:T})}observe(T,_){if(!this.observers.has(T))this.observers.set(T,new FT);this.observers.get(T).subscribe("SINGLETON",_)}}var c1={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 WO(T){return Number.parseInt(T,10)}var JO=Y_(c1),YO=JO.keyof().pipe((T)=>WO(T)),i5=Y_([YO,"string"]);var C8=new I4,{logger:G_}=C8;Object.assign(console,G_,{log:G_.info});G_.info("ready");var N8=r5(import.meta.dir,"..","app"),sy=new I8({logQuery(T,_){G_.info("\uD83D\uDCDD query",T,_)}});GO({hostname:"0.0.0.0",port:q_.FRONTEND_PORT??3333,...X1??void 0,async fetch(T){try{let _=new Date,F=new URL(T.url);if(G_.info(T.method,F.pathname),F.pathname==="/")return new Response(Bun.file(r5(N8,"index.html")));if(F.pathname==="/index.html")return Response.redirect("/");let W=ZO(N8,F.pathname),J=XO(W);if(!J.startsWith(N8))throw[403,"Access Denied"];if(!await n5(J).exists())return Response.redirect("/");return new Response(n5(J))}catch(_){let F=i5(_);if(F instanceof Y_.errors===!1){let[W,J]=F,$=`${c1[W]}. ${J}`;return G_.info(`\u274C ${W}: ${$}`),new Response($,{status:W})}if(_ instanceof Error)G_.error(_.message);else{let W=R$(_);G_.error("frontend server threw",W)}return new Response(c1[500],{status:500})}}});function d1(){G_.info("\uD83D\uDEEC frontend server exiting"),process.exit(0)}process.on("SIGINT",()=>{G_.info("\u2757 received SIGINT; exiting gracefully"),d1()});process.on("SIGTERM",()=>{G_.info("\u2757 received SIGTERM; exiting gracefully"),d1()});process.on("exit",()=>{G_.info("\u2757 received exit; exiting gracefully"),d1()});C8.on("timeToStop",()=>{G_.info('\u2757 backend server received signal "timeToStop"; exiting gracefully'),d1()});var{version:AO}=await Bun.file($O.resolve(import.meta.dir,"../package.json")).json();G_.info(`\uD83D\uDEEB frontend v${AO} running at http://localhost:${q_.FRONTEND_PORT}/`);C8.emit("alive");
|